Make sure that undefined symbols added to the linker command line via the -u option...
[external/binutils.git] / bfd / elflink.c
1 /* ELF linking support for BFD.
2    Copyright (C) 1995-2017 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       bh = &h->root;
123     }
124   else
125     bh = NULL;
126
127   bed = get_elf_backend_data (abfd);
128   if (!_bfd_generic_link_add_one_symbol (info, abfd, name, BSF_GLOBAL,
129                                          sec, 0, NULL, FALSE, bed->collect,
130                                          &bh))
131     return NULL;
132   h = (struct elf_link_hash_entry *) bh;
133   BFD_ASSERT (h != NULL);
134   h->def_regular = 1;
135   h->non_elf = 0;
136   h->root.linker_def = 1;
137   h->type = STT_OBJECT;
138   if (ELF_ST_VISIBILITY (h->other) != STV_INTERNAL)
139     h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_HIDDEN;
140
141   (*bed->elf_backend_hide_symbol) (info, h, TRUE);
142   return h;
143 }
144
145 bfd_boolean
146 _bfd_elf_create_got_section (bfd *abfd, struct bfd_link_info *info)
147 {
148   flagword flags;
149   asection *s;
150   struct elf_link_hash_entry *h;
151   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
152   struct elf_link_hash_table *htab = elf_hash_table (info);
153
154   /* This function may be called more than once.  */
155   if (htab->sgot != NULL)
156     return TRUE;
157
158   flags = bed->dynamic_sec_flags;
159
160   s = bfd_make_section_anyway_with_flags (abfd,
161                                           (bed->rela_plts_and_copies_p
162                                            ? ".rela.got" : ".rel.got"),
163                                           (bed->dynamic_sec_flags
164                                            | SEC_READONLY));
165   if (s == NULL
166       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
167     return FALSE;
168   htab->srelgot = s;
169
170   s = bfd_make_section_anyway_with_flags (abfd, ".got", flags);
171   if (s == NULL
172       || !bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
173     return FALSE;
174   htab->sgot = s;
175
176   if (bed->want_got_plt)
177     {
178       s = bfd_make_section_anyway_with_flags (abfd, ".got.plt", flags);
179       if (s == NULL
180           || !bfd_set_section_alignment (abfd, s,
181                                          bed->s->log_file_align))
182         return FALSE;
183       htab->sgotplt = s;
184     }
185
186   /* The first bit of the global offset table is the header.  */
187   s->size += bed->got_header_size;
188
189   if (bed->want_got_sym)
190     {
191       /* Define the symbol _GLOBAL_OFFSET_TABLE_ at the start of the .got
192          (or .got.plt) section.  We don't do this in the linker script
193          because we don't want to define the symbol if we are not creating
194          a global offset table.  */
195       h = _bfd_elf_define_linkage_sym (abfd, info, s,
196                                        "_GLOBAL_OFFSET_TABLE_");
197       elf_hash_table (info)->hgot = h;
198       if (h == NULL)
199         return FALSE;
200     }
201
202   return TRUE;
203 }
204 \f
205 /* Create a strtab to hold the dynamic symbol names.  */
206 static bfd_boolean
207 _bfd_elf_link_create_dynstrtab (bfd *abfd, struct bfd_link_info *info)
208 {
209   struct elf_link_hash_table *hash_table;
210
211   hash_table = elf_hash_table (info);
212   if (hash_table->dynobj == NULL)
213     {
214       /* We may not set dynobj, an input file holding linker created
215          dynamic sections to abfd, which may be a dynamic object with
216          its own dynamic sections.  We need to find a normal input file
217          to hold linker created sections if possible.  */
218       if ((abfd->flags & (DYNAMIC | BFD_PLUGIN)) != 0)
219         {
220           bfd *ibfd;
221           asection *s;
222           for (ibfd = info->input_bfds; ibfd; ibfd = ibfd->link.next)
223             if ((ibfd->flags
224                  & (DYNAMIC | BFD_LINKER_CREATED | BFD_PLUGIN)) == 0
225                 && bfd_get_flavour (ibfd) == bfd_target_elf_flavour
226                 && !((s = ibfd->sections) != NULL
227                      && s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS))
228               {
229                 abfd = ibfd;
230                 break;
231               }
232         }
233       hash_table->dynobj = abfd;
234     }
235
236   if (hash_table->dynstr == NULL)
237     {
238       hash_table->dynstr = _bfd_elf_strtab_init ();
239       if (hash_table->dynstr == NULL)
240         return FALSE;
241     }
242   return TRUE;
243 }
244
245 /* Create some sections which will be filled in with dynamic linking
246    information.  ABFD is an input file which requires dynamic sections
247    to be created.  The dynamic sections take up virtual memory space
248    when the final executable is run, so we need to create them before
249    addresses are assigned to the output sections.  We work out the
250    actual contents and size of these sections later.  */
251
252 bfd_boolean
253 _bfd_elf_link_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
254 {
255   flagword flags;
256   asection *s;
257   const struct elf_backend_data *bed;
258   struct elf_link_hash_entry *h;
259
260   if (! is_elf_hash_table (info->hash))
261     return FALSE;
262
263   if (elf_hash_table (info)->dynamic_sections_created)
264     return TRUE;
265
266   if (!_bfd_elf_link_create_dynstrtab (abfd, info))
267     return FALSE;
268
269   abfd = elf_hash_table (info)->dynobj;
270   bed = get_elf_backend_data (abfd);
271
272   flags = bed->dynamic_sec_flags;
273
274   /* A dynamically linked executable has a .interp section, but a
275      shared library does not.  */
276   if (bfd_link_executable (info) && !info->nointerp)
277     {
278       s = bfd_make_section_anyway_with_flags (abfd, ".interp",
279                                               flags | SEC_READONLY);
280       if (s == NULL)
281         return FALSE;
282     }
283
284   /* Create sections to hold version informations.  These are removed
285      if they are not needed.  */
286   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version_d",
287                                           flags | SEC_READONLY);
288   if (s == NULL
289       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
290     return FALSE;
291
292   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version",
293                                           flags | SEC_READONLY);
294   if (s == NULL
295       || ! bfd_set_section_alignment (abfd, s, 1))
296     return FALSE;
297
298   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version_r",
299                                           flags | SEC_READONLY);
300   if (s == NULL
301       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
302     return FALSE;
303
304   s = bfd_make_section_anyway_with_flags (abfd, ".dynsym",
305                                           flags | SEC_READONLY);
306   if (s == NULL
307       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
308     return FALSE;
309   elf_hash_table (info)->dynsym = s;
310
311   s = bfd_make_section_anyway_with_flags (abfd, ".dynstr",
312                                           flags | SEC_READONLY);
313   if (s == NULL)
314     return FALSE;
315
316   s = bfd_make_section_anyway_with_flags (abfd, ".dynamic", flags);
317   if (s == NULL
318       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
319     return FALSE;
320
321   /* The special symbol _DYNAMIC is always set to the start of the
322      .dynamic section.  We could set _DYNAMIC in a linker script, but we
323      only want to define it if we are, in fact, creating a .dynamic
324      section.  We don't want to define it if there is no .dynamic
325      section, since on some ELF platforms the start up code examines it
326      to decide how to initialize the process.  */
327   h = _bfd_elf_define_linkage_sym (abfd, info, s, "_DYNAMIC");
328   elf_hash_table (info)->hdynamic = h;
329   if (h == NULL)
330     return FALSE;
331
332   if (info->emit_hash)
333     {
334       s = bfd_make_section_anyway_with_flags (abfd, ".hash",
335                                               flags | SEC_READONLY);
336       if (s == NULL
337           || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
338         return FALSE;
339       elf_section_data (s)->this_hdr.sh_entsize = bed->s->sizeof_hash_entry;
340     }
341
342   if (info->emit_gnu_hash)
343     {
344       s = bfd_make_section_anyway_with_flags (abfd, ".gnu.hash",
345                                               flags | SEC_READONLY);
346       if (s == NULL
347           || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
348         return FALSE;
349       /* For 64-bit ELF, .gnu.hash is a non-uniform entity size section:
350          4 32-bit words followed by variable count of 64-bit words, then
351          variable count of 32-bit words.  */
352       if (bed->s->arch_size == 64)
353         elf_section_data (s)->this_hdr.sh_entsize = 0;
354       else
355         elf_section_data (s)->this_hdr.sh_entsize = 4;
356     }
357
358   /* Let the backend create the rest of the sections.  This lets the
359      backend set the right flags.  The backend will normally create
360      the .got and .plt sections.  */
361   if (bed->elf_backend_create_dynamic_sections == NULL
362       || ! (*bed->elf_backend_create_dynamic_sections) (abfd, info))
363     return FALSE;
364
365   elf_hash_table (info)->dynamic_sections_created = TRUE;
366
367   return TRUE;
368 }
369
370 /* Create dynamic sections when linking against a dynamic object.  */
371
372 bfd_boolean
373 _bfd_elf_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
374 {
375   flagword flags, pltflags;
376   struct elf_link_hash_entry *h;
377   asection *s;
378   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
379   struct elf_link_hash_table *htab = elf_hash_table (info);
380
381   /* We need to create .plt, .rel[a].plt, .got, .got.plt, .dynbss, and
382      .rel[a].bss sections.  */
383   flags = bed->dynamic_sec_flags;
384
385   pltflags = flags;
386   if (bed->plt_not_loaded)
387     /* We do not clear SEC_ALLOC here because we still want the OS to
388        allocate space for the section; it's just that there's nothing
389        to read in from the object file.  */
390     pltflags &= ~ (SEC_CODE | SEC_LOAD | SEC_HAS_CONTENTS);
391   else
392     pltflags |= SEC_ALLOC | SEC_CODE | SEC_LOAD;
393   if (bed->plt_readonly)
394     pltflags |= SEC_READONLY;
395
396   s = bfd_make_section_anyway_with_flags (abfd, ".plt", pltflags);
397   if (s == NULL
398       || ! bfd_set_section_alignment (abfd, s, bed->plt_alignment))
399     return FALSE;
400   htab->splt = s;
401
402   /* Define the symbol _PROCEDURE_LINKAGE_TABLE_ at the start of the
403      .plt section.  */
404   if (bed->want_plt_sym)
405     {
406       h = _bfd_elf_define_linkage_sym (abfd, info, s,
407                                        "_PROCEDURE_LINKAGE_TABLE_");
408       elf_hash_table (info)->hplt = h;
409       if (h == NULL)
410         return FALSE;
411     }
412
413   s = bfd_make_section_anyway_with_flags (abfd,
414                                           (bed->rela_plts_and_copies_p
415                                            ? ".rela.plt" : ".rel.plt"),
416                                           flags | SEC_READONLY);
417   if (s == NULL
418       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
419     return FALSE;
420   htab->srelplt = s;
421
422   if (! _bfd_elf_create_got_section (abfd, info))
423     return FALSE;
424
425   if (bed->want_dynbss)
426     {
427       /* The .dynbss section is a place to put symbols which are defined
428          by dynamic objects, are referenced by regular objects, and are
429          not functions.  We must allocate space for them in the process
430          image and use a R_*_COPY reloc to tell the dynamic linker to
431          initialize them at run time.  The linker script puts the .dynbss
432          section into the .bss section of the final image.  */
433       s = bfd_make_section_anyway_with_flags (abfd, ".dynbss",
434                                               SEC_ALLOC | SEC_LINKER_CREATED);
435       if (s == NULL)
436         return FALSE;
437       htab->sdynbss = s;
438
439       if (bed->want_dynrelro)
440         {
441           /* Similarly, but for symbols that were originally in read-only
442              sections.  This section doesn't really need to have contents,
443              but make it like other .data.rel.ro sections.  */
444           s = bfd_make_section_anyway_with_flags (abfd, ".data.rel.ro",
445                                                   flags);
446           if (s == NULL)
447             return FALSE;
448           htab->sdynrelro = s;
449         }
450
451       /* The .rel[a].bss section holds copy relocs.  This section is not
452          normally needed.  We need to create it here, though, so that the
453          linker will map it to an output section.  We can't just create it
454          only if we need it, because we will not know whether we need it
455          until we have seen all the input files, and the first time the
456          main linker code calls BFD after examining all the input files
457          (size_dynamic_sections) the input sections have already been
458          mapped to the output sections.  If the section turns out not to
459          be needed, we can discard it later.  We will never need this
460          section when generating a shared object, since they do not use
461          copy relocs.  */
462       if (bfd_link_executable (info))
463         {
464           s = bfd_make_section_anyway_with_flags (abfd,
465                                                   (bed->rela_plts_and_copies_p
466                                                    ? ".rela.bss" : ".rel.bss"),
467                                                   flags | SEC_READONLY);
468           if (s == NULL
469               || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
470             return FALSE;
471           htab->srelbss = s;
472
473           if (bed->want_dynrelro)
474             {
475               s = (bfd_make_section_anyway_with_flags
476                    (abfd, (bed->rela_plts_and_copies_p
477                            ? ".rela.data.rel.ro" : ".rel.data.rel.ro"),
478                     flags | SEC_READONLY));
479               if (s == NULL
480                   || ! bfd_set_section_alignment (abfd, s,
481                                                   bed->s->log_file_align))
482                 return FALSE;
483               htab->sreldynrelro = s;
484             }
485         }
486     }
487
488   return TRUE;
489 }
490 \f
491 /* Record a new dynamic symbol.  We record the dynamic symbols as we
492    read the input files, since we need to have a list of all of them
493    before we can determine the final sizes of the output sections.
494    Note that we may actually call this function even though we are not
495    going to output any dynamic symbols; in some cases we know that a
496    symbol should be in the dynamic symbol table, but only if there is
497    one.  */
498
499 bfd_boolean
500 bfd_elf_link_record_dynamic_symbol (struct bfd_link_info *info,
501                                     struct elf_link_hash_entry *h)
502 {
503   if (h->dynindx == -1)
504     {
505       struct elf_strtab_hash *dynstr;
506       char *p;
507       const char *name;
508       size_t indx;
509
510       /* XXX: The ABI draft says the linker must turn hidden and
511          internal symbols into STB_LOCAL symbols when producing the
512          DSO. However, if ld.so honors st_other in the dynamic table,
513          this would not be necessary.  */
514       switch (ELF_ST_VISIBILITY (h->other))
515         {
516         case STV_INTERNAL:
517         case STV_HIDDEN:
518           if (h->root.type != bfd_link_hash_undefined
519               && h->root.type != bfd_link_hash_undefweak)
520             {
521               h->forced_local = 1;
522               if (!elf_hash_table (info)->is_relocatable_executable)
523                 return TRUE;
524             }
525
526         default:
527           break;
528         }
529
530       h->dynindx = elf_hash_table (info)->dynsymcount;
531       ++elf_hash_table (info)->dynsymcount;
532
533       dynstr = elf_hash_table (info)->dynstr;
534       if (dynstr == NULL)
535         {
536           /* Create a strtab to hold the dynamic symbol names.  */
537           elf_hash_table (info)->dynstr = dynstr = _bfd_elf_strtab_init ();
538           if (dynstr == NULL)
539             return FALSE;
540         }
541
542       /* We don't put any version information in the dynamic string
543          table.  */
544       name = h->root.root.string;
545       p = strchr (name, ELF_VER_CHR);
546       if (p != NULL)
547         /* We know that the p points into writable memory.  In fact,
548            there are only a few symbols that have read-only names, being
549            those like _GLOBAL_OFFSET_TABLE_ that are created specially
550            by the backends.  Most symbols will have names pointing into
551            an ELF string table read from a file, or to objalloc memory.  */
552         *p = 0;
553
554       indx = _bfd_elf_strtab_add (dynstr, name, p != NULL);
555
556       if (p != NULL)
557         *p = ELF_VER_CHR;
558
559       if (indx == (size_t) -1)
560         return FALSE;
561       h->dynstr_index = indx;
562     }
563
564   return TRUE;
565 }
566 \f
567 /* Mark a symbol dynamic.  */
568
569 static void
570 bfd_elf_link_mark_dynamic_symbol (struct bfd_link_info *info,
571                                   struct elf_link_hash_entry *h,
572                                   Elf_Internal_Sym *sym)
573 {
574   struct bfd_elf_dynamic_list *d = info->dynamic_list;
575
576   /* It may be called more than once on the same H.  */
577   if(h->dynamic || bfd_link_relocatable (info))
578     return;
579
580   if ((info->dynamic_data
581        && (h->type == STT_OBJECT
582            || h->type == STT_COMMON
583            || (sym != NULL
584                && (ELF_ST_TYPE (sym->st_info) == STT_OBJECT
585                    || ELF_ST_TYPE (sym->st_info) == STT_COMMON))))
586       || (d != NULL
587           && h->non_elf
588           && (*d->match) (&d->head, NULL, h->root.root.string)))
589     h->dynamic = 1;
590 }
591
592 /* Record an assignment to a symbol made by a linker script.  We need
593    this in case some dynamic object refers to this symbol.  */
594
595 bfd_boolean
596 bfd_elf_record_link_assignment (bfd *output_bfd,
597                                 struct bfd_link_info *info,
598                                 const char *name,
599                                 bfd_boolean provide,
600                                 bfd_boolean hidden)
601 {
602   struct elf_link_hash_entry *h, *hv;
603   struct elf_link_hash_table *htab;
604   const struct elf_backend_data *bed;
605
606   if (!is_elf_hash_table (info->hash))
607     return TRUE;
608
609   htab = elf_hash_table (info);
610   h = elf_link_hash_lookup (htab, name, !provide, TRUE, FALSE);
611   if (h == NULL)
612     return provide;
613
614   if (h->root.type == bfd_link_hash_warning)
615     h = (struct elf_link_hash_entry *) h->root.u.i.link;
616
617   if (h->versioned == unknown)
618     {
619       /* Set versioned if symbol version is unknown.  */
620       char *version = strrchr (name, ELF_VER_CHR);
621       if (version)
622         {
623           if (version > name && version[-1] != ELF_VER_CHR)
624             h->versioned = versioned_hidden;
625           else
626             h->versioned = versioned;
627         }
628     }
629
630   /* Symbols defined in a linker script but not referenced anywhere
631      else will have non_elf set.  */
632   if (h->non_elf)
633     {
634       bfd_elf_link_mark_dynamic_symbol (info, h, NULL);
635       h->non_elf = 0;
636     }
637
638   switch (h->root.type)
639     {
640     case bfd_link_hash_defined:
641     case bfd_link_hash_defweak:
642     case bfd_link_hash_common:
643       break;
644     case bfd_link_hash_undefweak:
645     case bfd_link_hash_undefined:
646       /* Since we're defining the symbol, don't let it seem to have not
647          been defined.  record_dynamic_symbol and size_dynamic_sections
648          may depend on this.  */
649       h->root.type = bfd_link_hash_new;
650       if (h->root.u.undef.next != NULL || htab->root.undefs_tail == &h->root)
651         bfd_link_repair_undef_list (&htab->root);
652       break;
653     case bfd_link_hash_new:
654       break;
655     case bfd_link_hash_indirect:
656       /* We had a versioned symbol in a dynamic library.  We make the
657          the versioned symbol point to this one.  */
658       bed = get_elf_backend_data (output_bfd);
659       hv = h;
660       while (hv->root.type == bfd_link_hash_indirect
661              || hv->root.type == bfd_link_hash_warning)
662         hv = (struct elf_link_hash_entry *) hv->root.u.i.link;
663       /* We don't need to update h->root.u since linker will set them
664          later.  */
665       h->root.type = bfd_link_hash_undefined;
666       hv->root.type = bfd_link_hash_indirect;
667       hv->root.u.i.link = (struct bfd_link_hash_entry *) h;
668       (*bed->elf_backend_copy_indirect_symbol) (info, h, hv);
669       break;
670     default:
671       BFD_FAIL ();
672       return FALSE;
673     }
674
675   /* If this symbol is being provided by the linker script, and it is
676      currently defined by a dynamic object, but not by a regular
677      object, then mark it as undefined so that the generic linker will
678      force the correct value.  */
679   if (provide
680       && h->def_dynamic
681       && !h->def_regular)
682     h->root.type = bfd_link_hash_undefined;
683
684   /* If this symbol is not being provided by the linker script, and it is
685      currently defined by a dynamic object, but not by a regular object,
686      then clear out any version information because the symbol will not be
687      associated with the dynamic object any more.  */
688   if (!provide
689       && h->def_dynamic
690       && !h->def_regular)
691     h->verinfo.verdef = NULL;
692
693   /* Make sure this symbol is not garbage collected.  */
694   h->mark = 1;
695
696   h->def_regular = 1;
697
698   if (hidden)
699     {
700       bed = get_elf_backend_data (output_bfd);
701       if (ELF_ST_VISIBILITY (h->other) != STV_INTERNAL)
702         h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_HIDDEN;
703       (*bed->elf_backend_hide_symbol) (info, h, TRUE);
704     }
705
706   /* STV_HIDDEN and STV_INTERNAL symbols must be STB_LOCAL in shared objects
707      and executables.  */
708   if (!bfd_link_relocatable (info)
709       && h->dynindx != -1
710       && (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
711           || ELF_ST_VISIBILITY (h->other) == STV_INTERNAL))
712     h->forced_local = 1;
713
714   if ((h->def_dynamic
715        || h->ref_dynamic
716        || bfd_link_dll (info)
717        || elf_hash_table (info)->is_relocatable_executable)
718       && h->dynindx == -1)
719     {
720       if (! bfd_elf_link_record_dynamic_symbol (info, h))
721         return FALSE;
722
723       /* If this is a weak defined symbol, and we know a corresponding
724          real symbol from the same dynamic object, make sure the real
725          symbol is also made into a dynamic symbol.  */
726       if (h->u.weakdef != NULL
727           && h->u.weakdef->dynindx == -1)
728         {
729           if (! bfd_elf_link_record_dynamic_symbol (info, h->u.weakdef))
730             return FALSE;
731         }
732     }
733
734   return TRUE;
735 }
736
737 /* Record a new local dynamic symbol.  Returns 0 on failure, 1 on
738    success, and 2 on a failure caused by attempting to record a symbol
739    in a discarded section, eg. a discarded link-once section symbol.  */
740
741 int
742 bfd_elf_link_record_local_dynamic_symbol (struct bfd_link_info *info,
743                                           bfd *input_bfd,
744                                           long input_indx)
745 {
746   bfd_size_type amt;
747   struct elf_link_local_dynamic_entry *entry;
748   struct elf_link_hash_table *eht;
749   struct elf_strtab_hash *dynstr;
750   size_t dynstr_index;
751   char *name;
752   Elf_External_Sym_Shndx eshndx;
753   char esym[sizeof (Elf64_External_Sym)];
754
755   if (! is_elf_hash_table (info->hash))
756     return 0;
757
758   /* See if the entry exists already.  */
759   for (entry = elf_hash_table (info)->dynlocal; entry ; entry = entry->next)
760     if (entry->input_bfd == input_bfd && entry->input_indx == input_indx)
761       return 1;
762
763   amt = sizeof (*entry);
764   entry = (struct elf_link_local_dynamic_entry *) bfd_alloc (input_bfd, amt);
765   if (entry == NULL)
766     return 0;
767
768   /* Go find the symbol, so that we can find it's name.  */
769   if (!bfd_elf_get_elf_syms (input_bfd, &elf_tdata (input_bfd)->symtab_hdr,
770                              1, input_indx, &entry->isym, esym, &eshndx))
771     {
772       bfd_release (input_bfd, entry);
773       return 0;
774     }
775
776   if (entry->isym.st_shndx != SHN_UNDEF
777       && entry->isym.st_shndx < SHN_LORESERVE)
778     {
779       asection *s;
780
781       s = bfd_section_from_elf_index (input_bfd, entry->isym.st_shndx);
782       if (s == NULL || bfd_is_abs_section (s->output_section))
783         {
784           /* We can still bfd_release here as nothing has done another
785              bfd_alloc.  We can't do this later in this function.  */
786           bfd_release (input_bfd, entry);
787           return 2;
788         }
789     }
790
791   name = (bfd_elf_string_from_elf_section
792           (input_bfd, elf_tdata (input_bfd)->symtab_hdr.sh_link,
793            entry->isym.st_name));
794
795   dynstr = elf_hash_table (info)->dynstr;
796   if (dynstr == NULL)
797     {
798       /* Create a strtab to hold the dynamic symbol names.  */
799       elf_hash_table (info)->dynstr = dynstr = _bfd_elf_strtab_init ();
800       if (dynstr == NULL)
801         return 0;
802     }
803
804   dynstr_index = _bfd_elf_strtab_add (dynstr, name, FALSE);
805   if (dynstr_index == (size_t) -1)
806     return 0;
807   entry->isym.st_name = dynstr_index;
808
809   eht = elf_hash_table (info);
810
811   entry->next = eht->dynlocal;
812   eht->dynlocal = entry;
813   entry->input_bfd = input_bfd;
814   entry->input_indx = input_indx;
815   eht->dynsymcount++;
816
817   /* Whatever binding the symbol had before, it's now local.  */
818   entry->isym.st_info
819     = ELF_ST_INFO (STB_LOCAL, ELF_ST_TYPE (entry->isym.st_info));
820
821   /* The dynindx will be set at the end of size_dynamic_sections.  */
822
823   return 1;
824 }
825
826 /* Return the dynindex of a local dynamic symbol.  */
827
828 long
829 _bfd_elf_link_lookup_local_dynindx (struct bfd_link_info *info,
830                                     bfd *input_bfd,
831                                     long input_indx)
832 {
833   struct elf_link_local_dynamic_entry *e;
834
835   for (e = elf_hash_table (info)->dynlocal; e ; e = e->next)
836     if (e->input_bfd == input_bfd && e->input_indx == input_indx)
837       return e->dynindx;
838   return -1;
839 }
840
841 /* This function is used to renumber the dynamic symbols, if some of
842    them are removed because they are marked as local.  This is called
843    via elf_link_hash_traverse.  */
844
845 static bfd_boolean
846 elf_link_renumber_hash_table_dynsyms (struct elf_link_hash_entry *h,
847                                       void *data)
848 {
849   size_t *count = (size_t *) data;
850
851   if (h->forced_local)
852     return TRUE;
853
854   if (h->dynindx != -1)
855     h->dynindx = ++(*count);
856
857   return TRUE;
858 }
859
860
861 /* Like elf_link_renumber_hash_table_dynsyms, but just number symbols with
862    STB_LOCAL binding.  */
863
864 static bfd_boolean
865 elf_link_renumber_local_hash_table_dynsyms (struct elf_link_hash_entry *h,
866                                             void *data)
867 {
868   size_t *count = (size_t *) data;
869
870   if (!h->forced_local)
871     return TRUE;
872
873   if (h->dynindx != -1)
874     h->dynindx = ++(*count);
875
876   return TRUE;
877 }
878
879 /* Return true if the dynamic symbol for a given section should be
880    omitted when creating a shared library.  */
881 bfd_boolean
882 _bfd_elf_link_omit_section_dynsym (bfd *output_bfd ATTRIBUTE_UNUSED,
883                                    struct bfd_link_info *info,
884                                    asection *p)
885 {
886   struct elf_link_hash_table *htab;
887   asection *ip;
888
889   switch (elf_section_data (p)->this_hdr.sh_type)
890     {
891     case SHT_PROGBITS:
892     case SHT_NOBITS:
893       /* If sh_type is yet undecided, assume it could be
894          SHT_PROGBITS/SHT_NOBITS.  */
895     case SHT_NULL:
896       htab = elf_hash_table (info);
897       if (p == htab->tls_sec)
898         return FALSE;
899
900       if (htab->text_index_section != NULL)
901         return p != htab->text_index_section && p != htab->data_index_section;
902
903       return (htab->dynobj != NULL
904               && (ip = bfd_get_linker_section (htab->dynobj, p->name)) != NULL
905               && ip->output_section == p);
906
907       /* There shouldn't be section relative relocations
908          against any other section.  */
909     default:
910       return TRUE;
911     }
912 }
913
914 /* Assign dynsym indices.  In a shared library we generate a section
915    symbol for each output section, which come first.  Next come symbols
916    which have been forced to local binding.  Then all of the back-end
917    allocated local dynamic syms, followed by the rest of the global
918    symbols.  */
919
920 static unsigned long
921 _bfd_elf_link_renumber_dynsyms (bfd *output_bfd,
922                                 struct bfd_link_info *info,
923                                 unsigned long *section_sym_count)
924 {
925   unsigned long dynsymcount = 0;
926
927   if (bfd_link_pic (info)
928       || elf_hash_table (info)->is_relocatable_executable)
929     {
930       const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
931       asection *p;
932       for (p = output_bfd->sections; p ; p = p->next)
933         if ((p->flags & SEC_EXCLUDE) == 0
934             && (p->flags & SEC_ALLOC) != 0
935             && !(*bed->elf_backend_omit_section_dynsym) (output_bfd, info, p))
936           elf_section_data (p)->dynindx = ++dynsymcount;
937         else
938           elf_section_data (p)->dynindx = 0;
939     }
940   *section_sym_count = dynsymcount;
941
942   elf_link_hash_traverse (elf_hash_table (info),
943                           elf_link_renumber_local_hash_table_dynsyms,
944                           &dynsymcount);
945
946   if (elf_hash_table (info)->dynlocal)
947     {
948       struct elf_link_local_dynamic_entry *p;
949       for (p = elf_hash_table (info)->dynlocal; p ; p = p->next)
950         p->dynindx = ++dynsymcount;
951     }
952   elf_hash_table (info)->local_dynsymcount = dynsymcount;
953
954   elf_link_hash_traverse (elf_hash_table (info),
955                           elf_link_renumber_hash_table_dynsyms,
956                           &dynsymcount);
957
958   /* There is an unused NULL entry at the head of the table which we
959      must account for in our count even if the table is empty since it
960      is intended for the mandatory DT_SYMTAB tag (.dynsym section) in
961      .dynamic section.  */
962   dynsymcount++;
963
964   elf_hash_table (info)->dynsymcount = dynsymcount;
965   return dynsymcount;
966 }
967
968 /* Merge st_other field.  */
969
970 static void
971 elf_merge_st_other (bfd *abfd, struct elf_link_hash_entry *h,
972                     const Elf_Internal_Sym *isym, asection *sec,
973                     bfd_boolean definition, bfd_boolean dynamic)
974 {
975   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
976
977   /* If st_other has a processor-specific meaning, specific
978      code might be needed here.  */
979   if (bed->elf_backend_merge_symbol_attribute)
980     (*bed->elf_backend_merge_symbol_attribute) (h, isym, definition,
981                                                 dynamic);
982
983   if (!dynamic)
984     {
985       unsigned symvis = ELF_ST_VISIBILITY (isym->st_other);
986       unsigned hvis = ELF_ST_VISIBILITY (h->other);
987
988       /* Keep the most constraining visibility.  Leave the remainder
989          of the st_other field to elf_backend_merge_symbol_attribute.  */
990       if (symvis - 1 < hvis - 1)
991         h->other = symvis | (h->other & ~ELF_ST_VISIBILITY (-1));
992     }
993   else if (definition
994            && ELF_ST_VISIBILITY (isym->st_other) != STV_DEFAULT
995            && (sec->flags & SEC_READONLY) == 0)
996     h->protected_def = 1;
997 }
998
999 /* This function is called when we want to merge a new symbol with an
1000    existing symbol.  It handles the various cases which arise when we
1001    find a definition in a dynamic object, or when there is already a
1002    definition in a dynamic object.  The new symbol is described by
1003    NAME, SYM, PSEC, and PVALUE.  We set SYM_HASH to the hash table
1004    entry.  We set POLDBFD to the old symbol's BFD.  We set POLD_WEAK
1005    if the old symbol was weak.  We set POLD_ALIGNMENT to the alignment
1006    of an old common symbol.  We set OVERRIDE if the old symbol is
1007    overriding a new definition.  We set TYPE_CHANGE_OK if it is OK for
1008    the type to change.  We set SIZE_CHANGE_OK if it is OK for the size
1009    to change.  By OK to change, we mean that we shouldn't warn if the
1010    type or size does change.  */
1011
1012 static bfd_boolean
1013 _bfd_elf_merge_symbol (bfd *abfd,
1014                        struct bfd_link_info *info,
1015                        const char *name,
1016                        Elf_Internal_Sym *sym,
1017                        asection **psec,
1018                        bfd_vma *pvalue,
1019                        struct elf_link_hash_entry **sym_hash,
1020                        bfd **poldbfd,
1021                        bfd_boolean *pold_weak,
1022                        unsigned int *pold_alignment,
1023                        bfd_boolean *skip,
1024                        bfd_boolean *override,
1025                        bfd_boolean *type_change_ok,
1026                        bfd_boolean *size_change_ok,
1027                        bfd_boolean *matched)
1028 {
1029   asection *sec, *oldsec;
1030   struct elf_link_hash_entry *h;
1031   struct elf_link_hash_entry *hi;
1032   struct elf_link_hash_entry *flip;
1033   int bind;
1034   bfd *oldbfd;
1035   bfd_boolean newdyn, olddyn, olddef, newdef, newdyncommon, olddyncommon;
1036   bfd_boolean newweak, oldweak, newfunc, oldfunc;
1037   const struct elf_backend_data *bed;
1038   char *new_version;
1039
1040   *skip = FALSE;
1041   *override = FALSE;
1042
1043   sec = *psec;
1044   bind = ELF_ST_BIND (sym->st_info);
1045
1046   if (! bfd_is_und_section (sec))
1047     h = elf_link_hash_lookup (elf_hash_table (info), name, TRUE, FALSE, FALSE);
1048   else
1049     h = ((struct elf_link_hash_entry *)
1050          bfd_wrapped_link_hash_lookup (abfd, info, name, TRUE, FALSE, FALSE));
1051   if (h == NULL)
1052     return FALSE;
1053   *sym_hash = h;
1054
1055   bed = get_elf_backend_data (abfd);
1056
1057   /* NEW_VERSION is the symbol version of the new symbol.  */
1058   if (h->versioned != unversioned)
1059     {
1060       /* Symbol version is unknown or versioned.  */
1061       new_version = strrchr (name, ELF_VER_CHR);
1062       if (new_version)
1063         {
1064           if (h->versioned == unknown)
1065             {
1066               if (new_version > name && new_version[-1] != ELF_VER_CHR)
1067                 h->versioned = versioned_hidden;
1068               else
1069                 h->versioned = versioned;
1070             }
1071           new_version += 1;
1072           if (new_version[0] == '\0')
1073             new_version = NULL;
1074         }
1075       else
1076         h->versioned = unversioned;
1077     }
1078   else
1079     new_version = NULL;
1080
1081   /* For merging, we only care about real symbols.  But we need to make
1082      sure that indirect symbol dynamic flags are updated.  */
1083   hi = h;
1084   while (h->root.type == bfd_link_hash_indirect
1085          || h->root.type == bfd_link_hash_warning)
1086     h = (struct elf_link_hash_entry *) h->root.u.i.link;
1087
1088   if (!*matched)
1089     {
1090       if (hi == h || h->root.type == bfd_link_hash_new)
1091         *matched = TRUE;
1092       else
1093         {
1094           /* OLD_HIDDEN is true if the existing symbol is only visible
1095              to the symbol with the same symbol version.  NEW_HIDDEN is
1096              true if the new symbol is only visible to the symbol with
1097              the same symbol version.  */
1098           bfd_boolean old_hidden = h->versioned == versioned_hidden;
1099           bfd_boolean new_hidden = hi->versioned == versioned_hidden;
1100           if (!old_hidden && !new_hidden)
1101             /* The new symbol matches the existing symbol if both
1102                aren't hidden.  */
1103             *matched = TRUE;
1104           else
1105             {
1106               /* OLD_VERSION is the symbol version of the existing
1107                  symbol. */
1108               char *old_version;
1109
1110               if (h->versioned >= versioned)
1111                 old_version = strrchr (h->root.root.string,
1112                                        ELF_VER_CHR) + 1;
1113               else
1114                  old_version = NULL;
1115
1116               /* The new symbol matches the existing symbol if they
1117                  have the same symbol version.  */
1118               *matched = (old_version == new_version
1119                           || (old_version != NULL
1120                               && new_version != NULL
1121                               && strcmp (old_version, new_version) == 0));
1122             }
1123         }
1124     }
1125
1126   /* OLDBFD and OLDSEC are a BFD and an ASECTION associated with the
1127      existing symbol.  */
1128
1129   oldbfd = NULL;
1130   oldsec = NULL;
1131   switch (h->root.type)
1132     {
1133     default:
1134       break;
1135
1136     case bfd_link_hash_undefined:
1137     case bfd_link_hash_undefweak:
1138       oldbfd = h->root.u.undef.abfd;
1139       break;
1140
1141     case bfd_link_hash_defined:
1142     case bfd_link_hash_defweak:
1143       oldbfd = h->root.u.def.section->owner;
1144       oldsec = h->root.u.def.section;
1145       break;
1146
1147     case bfd_link_hash_common:
1148       oldbfd = h->root.u.c.p->section->owner;
1149       oldsec = h->root.u.c.p->section;
1150       if (pold_alignment)
1151         *pold_alignment = h->root.u.c.p->alignment_power;
1152       break;
1153     }
1154   if (poldbfd && *poldbfd == NULL)
1155     *poldbfd = oldbfd;
1156
1157   /* Differentiate strong and weak symbols.  */
1158   newweak = bind == STB_WEAK;
1159   oldweak = (h->root.type == bfd_link_hash_defweak
1160              || h->root.type == bfd_link_hash_undefweak);
1161   if (pold_weak)
1162     *pold_weak = oldweak;
1163
1164   /* This code is for coping with dynamic objects, and is only useful
1165      if we are doing an ELF link.  */
1166   if (!(*bed->relocs_compatible) (abfd->xvec, info->output_bfd->xvec))
1167     return TRUE;
1168
1169   /* We have to check it for every instance since the first few may be
1170      references and not all compilers emit symbol type for undefined
1171      symbols.  */
1172   bfd_elf_link_mark_dynamic_symbol (info, h, sym);
1173
1174   /* NEWDYN and OLDDYN indicate whether the new or old symbol,
1175      respectively, is from a dynamic object.  */
1176
1177   newdyn = (abfd->flags & DYNAMIC) != 0;
1178
1179   /* ref_dynamic_nonweak and dynamic_def flags track actual undefined
1180      syms and defined syms in dynamic libraries respectively.
1181      ref_dynamic on the other hand can be set for a symbol defined in
1182      a dynamic library, and def_dynamic may not be set;  When the
1183      definition in a dynamic lib is overridden by a definition in the
1184      executable use of the symbol in the dynamic lib becomes a
1185      reference to the executable symbol.  */
1186   if (newdyn)
1187     {
1188       if (bfd_is_und_section (sec))
1189         {
1190           if (bind != STB_WEAK)
1191             {
1192               h->ref_dynamic_nonweak = 1;
1193               hi->ref_dynamic_nonweak = 1;
1194             }
1195         }
1196       else
1197         {
1198           /* Update the existing symbol only if they match. */
1199           if (*matched)
1200             h->dynamic_def = 1;
1201           hi->dynamic_def = 1;
1202         }
1203     }
1204
1205   /* If we just created the symbol, mark it as being an ELF symbol.
1206      Other than that, there is nothing to do--there is no merge issue
1207      with a newly defined symbol--so we just return.  */
1208
1209   if (h->root.type == bfd_link_hash_new)
1210     {
1211       h->non_elf = 0;
1212       return TRUE;
1213     }
1214
1215   /* In cases involving weak versioned symbols, we may wind up trying
1216      to merge a symbol with itself.  Catch that here, to avoid the
1217      confusion that results if we try to override a symbol with
1218      itself.  The additional tests catch cases like
1219      _GLOBAL_OFFSET_TABLE_, which are regular symbols defined in a
1220      dynamic object, which we do want to handle here.  */
1221   if (abfd == oldbfd
1222       && (newweak || oldweak)
1223       && ((abfd->flags & DYNAMIC) == 0
1224           || !h->def_regular))
1225     return TRUE;
1226
1227   olddyn = FALSE;
1228   if (oldbfd != NULL)
1229     olddyn = (oldbfd->flags & DYNAMIC) != 0;
1230   else if (oldsec != NULL)
1231     {
1232       /* This handles the special SHN_MIPS_{TEXT,DATA} section
1233          indices used by MIPS ELF.  */
1234       olddyn = (oldsec->symbol->flags & BSF_DYNAMIC) != 0;
1235     }
1236
1237   /* Handle a case where plugin_notice won't be called and thus won't
1238      set the non_ir_ref flags on the first pass over symbols.  */
1239   if (oldbfd != NULL
1240       && (oldbfd->flags & BFD_PLUGIN) != (abfd->flags & BFD_PLUGIN)
1241       && newdyn != olddyn)
1242     {
1243       h->root.non_ir_ref_dynamic = TRUE;
1244       hi->root.non_ir_ref_dynamic = TRUE;
1245     }
1246
1247   /* NEWDEF and OLDDEF indicate whether the new or old symbol,
1248      respectively, appear to be a definition rather than reference.  */
1249
1250   newdef = !bfd_is_und_section (sec) && !bfd_is_com_section (sec);
1251
1252   olddef = (h->root.type != bfd_link_hash_undefined
1253             && h->root.type != bfd_link_hash_undefweak
1254             && h->root.type != bfd_link_hash_common);
1255
1256   /* NEWFUNC and OLDFUNC indicate whether the new or old symbol,
1257      respectively, appear to be a function.  */
1258
1259   newfunc = (ELF_ST_TYPE (sym->st_info) != STT_NOTYPE
1260              && bed->is_function_type (ELF_ST_TYPE (sym->st_info)));
1261
1262   oldfunc = (h->type != STT_NOTYPE
1263              && bed->is_function_type (h->type));
1264
1265   if (!(newfunc && oldfunc)
1266       && ELF_ST_TYPE (sym->st_info) != h->type
1267       && ELF_ST_TYPE (sym->st_info) != STT_NOTYPE
1268       && h->type != STT_NOTYPE
1269       && (newdef || bfd_is_com_section (sec))
1270       && (olddef || h->root.type == bfd_link_hash_common))
1271     {
1272       /* If creating a default indirect symbol ("foo" or "foo@") from
1273          a dynamic versioned definition ("foo@@") skip doing so if
1274          there is an existing regular definition with a different
1275          type.  We don't want, for example, a "time" variable in the
1276          executable overriding a "time" function in a shared library.  */
1277       if (newdyn
1278           && !olddyn)
1279         {
1280           *skip = TRUE;
1281           return TRUE;
1282         }
1283
1284       /* When adding a symbol from a regular object file after we have
1285          created indirect symbols, undo the indirection and any
1286          dynamic state.  */
1287       if (hi != h
1288           && !newdyn
1289           && olddyn)
1290         {
1291           h = hi;
1292           (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1293           h->forced_local = 0;
1294           h->ref_dynamic = 0;
1295           h->def_dynamic = 0;
1296           h->dynamic_def = 0;
1297           if (h->root.u.undef.next || info->hash->undefs_tail == &h->root)
1298             {
1299               h->root.type = bfd_link_hash_undefined;
1300               h->root.u.undef.abfd = abfd;
1301             }
1302           else
1303             {
1304               h->root.type = bfd_link_hash_new;
1305               h->root.u.undef.abfd = NULL;
1306             }
1307           return TRUE;
1308         }
1309     }
1310
1311   /* Check TLS symbols.  We don't check undefined symbols introduced
1312      by "ld -u" which have no type (and oldbfd NULL), and we don't
1313      check symbols from plugins because they also have no type.  */
1314   if (oldbfd != NULL
1315       && (oldbfd->flags & BFD_PLUGIN) == 0
1316       && (abfd->flags & BFD_PLUGIN) == 0
1317       && ELF_ST_TYPE (sym->st_info) != h->type
1318       && (ELF_ST_TYPE (sym->st_info) == STT_TLS || h->type == STT_TLS))
1319     {
1320       bfd *ntbfd, *tbfd;
1321       bfd_boolean ntdef, tdef;
1322       asection *ntsec, *tsec;
1323
1324       if (h->type == STT_TLS)
1325         {
1326           ntbfd = abfd;
1327           ntsec = sec;
1328           ntdef = newdef;
1329           tbfd = oldbfd;
1330           tsec = oldsec;
1331           tdef = olddef;
1332         }
1333       else
1334         {
1335           ntbfd = oldbfd;
1336           ntsec = oldsec;
1337           ntdef = olddef;
1338           tbfd = abfd;
1339           tsec = sec;
1340           tdef = newdef;
1341         }
1342
1343       if (tdef && ntdef)
1344         _bfd_error_handler
1345           /* xgettext:c-format */
1346           (_("%s: TLS definition in %B section %A "
1347              "mismatches non-TLS definition in %B section %A"),
1348            h->root.root.string, tbfd, tsec, ntbfd, ntsec);
1349       else if (!tdef && !ntdef)
1350         _bfd_error_handler
1351           /* xgettext:c-format */
1352           (_("%s: TLS reference in %B "
1353              "mismatches non-TLS reference in %B"),
1354            h->root.root.string, tbfd, ntbfd);
1355       else if (tdef)
1356         _bfd_error_handler
1357           /* xgettext:c-format */
1358           (_("%s: TLS definition in %B section %A "
1359              "mismatches non-TLS reference in %B"),
1360            h->root.root.string, tbfd, tsec, ntbfd);
1361       else
1362         _bfd_error_handler
1363           /* xgettext:c-format */
1364           (_("%s: TLS reference in %B "
1365              "mismatches non-TLS definition in %B section %A"),
1366            h->root.root.string, tbfd, ntbfd, ntsec);
1367
1368       bfd_set_error (bfd_error_bad_value);
1369       return FALSE;
1370     }
1371
1372   /* If the old symbol has non-default visibility, we ignore the new
1373      definition from a dynamic object.  */
1374   if (newdyn
1375       && ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
1376       && !bfd_is_und_section (sec))
1377     {
1378       *skip = TRUE;
1379       /* Make sure this symbol is dynamic.  */
1380       h->ref_dynamic = 1;
1381       hi->ref_dynamic = 1;
1382       /* A protected symbol has external availability. Make sure it is
1383          recorded as dynamic.
1384
1385          FIXME: Should we check type and size for protected symbol?  */
1386       if (ELF_ST_VISIBILITY (h->other) == STV_PROTECTED)
1387         return bfd_elf_link_record_dynamic_symbol (info, h);
1388       else
1389         return TRUE;
1390     }
1391   else if (!newdyn
1392            && ELF_ST_VISIBILITY (sym->st_other) != STV_DEFAULT
1393            && h->def_dynamic)
1394     {
1395       /* If the new symbol with non-default visibility comes from a
1396          relocatable file and the old definition comes from a dynamic
1397          object, we remove the old definition.  */
1398       if (hi->root.type == bfd_link_hash_indirect)
1399         {
1400           /* Handle the case where the old dynamic definition is
1401              default versioned.  We need to copy the symbol info from
1402              the symbol with default version to the normal one if it
1403              was referenced before.  */
1404           if (h->ref_regular)
1405             {
1406               hi->root.type = h->root.type;
1407               h->root.type = bfd_link_hash_indirect;
1408               (*bed->elf_backend_copy_indirect_symbol) (info, hi, h);
1409
1410               h->root.u.i.link = (struct bfd_link_hash_entry *) hi;
1411               if (ELF_ST_VISIBILITY (sym->st_other) != STV_PROTECTED)
1412                 {
1413                   /* If the new symbol is hidden or internal, completely undo
1414                      any dynamic link state.  */
1415                   (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1416                   h->forced_local = 0;
1417                   h->ref_dynamic = 0;
1418                 }
1419               else
1420                 h->ref_dynamic = 1;
1421
1422               h->def_dynamic = 0;
1423               /* FIXME: Should we check type and size for protected symbol?  */
1424               h->size = 0;
1425               h->type = 0;
1426
1427               h = hi;
1428             }
1429           else
1430             h = hi;
1431         }
1432
1433       /* If the old symbol was undefined before, then it will still be
1434          on the undefs list.  If the new symbol is undefined or
1435          common, we can't make it bfd_link_hash_new here, because new
1436          undefined or common symbols will be added to the undefs list
1437          by _bfd_generic_link_add_one_symbol.  Symbols may not be
1438          added twice to the undefs list.  Also, if the new symbol is
1439          undefweak then we don't want to lose the strong undef.  */
1440       if (h->root.u.undef.next || info->hash->undefs_tail == &h->root)
1441         {
1442           h->root.type = bfd_link_hash_undefined;
1443           h->root.u.undef.abfd = abfd;
1444         }
1445       else
1446         {
1447           h->root.type = bfd_link_hash_new;
1448           h->root.u.undef.abfd = NULL;
1449         }
1450
1451       if (ELF_ST_VISIBILITY (sym->st_other) != STV_PROTECTED)
1452         {
1453           /* If the new symbol is hidden or internal, completely undo
1454              any dynamic link state.  */
1455           (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1456           h->forced_local = 0;
1457           h->ref_dynamic = 0;
1458         }
1459       else
1460         h->ref_dynamic = 1;
1461       h->def_dynamic = 0;
1462       /* FIXME: Should we check type and size for protected symbol?  */
1463       h->size = 0;
1464       h->type = 0;
1465       return TRUE;
1466     }
1467
1468   /* If a new weak symbol definition comes from a regular file and the
1469      old symbol comes from a dynamic library, we treat the new one as
1470      strong.  Similarly, an old weak symbol definition from a regular
1471      file is treated as strong when the new symbol comes from a dynamic
1472      library.  Further, an old weak symbol from a dynamic library is
1473      treated as strong if the new symbol is from a dynamic library.
1474      This reflects the way glibc's ld.so works.
1475
1476      Do this before setting *type_change_ok or *size_change_ok so that
1477      we warn properly when dynamic library symbols are overridden.  */
1478
1479   if (newdef && !newdyn && olddyn)
1480     newweak = FALSE;
1481   if (olddef && newdyn)
1482     oldweak = FALSE;
1483
1484   /* Allow changes between different types of function symbol.  */
1485   if (newfunc && oldfunc)
1486     *type_change_ok = TRUE;
1487
1488   /* It's OK to change the type if either the existing symbol or the
1489      new symbol is weak.  A type change is also OK if the old symbol
1490      is undefined and the new symbol is defined.  */
1491
1492   if (oldweak
1493       || newweak
1494       || (newdef
1495           && h->root.type == bfd_link_hash_undefined))
1496     *type_change_ok = TRUE;
1497
1498   /* It's OK to change the size if either the existing symbol or the
1499      new symbol is weak, or if the old symbol is undefined.  */
1500
1501   if (*type_change_ok
1502       || h->root.type == bfd_link_hash_undefined)
1503     *size_change_ok = TRUE;
1504
1505   /* NEWDYNCOMMON and OLDDYNCOMMON indicate whether the new or old
1506      symbol, respectively, appears to be a common symbol in a dynamic
1507      object.  If a symbol appears in an uninitialized section, and is
1508      not weak, and is not a function, then it may be a common symbol
1509      which was resolved when the dynamic object was created.  We want
1510      to treat such symbols specially, because they raise special
1511      considerations when setting the symbol size: if the symbol
1512      appears as a common symbol in a regular object, and the size in
1513      the regular object is larger, we must make sure that we use the
1514      larger size.  This problematic case can always be avoided in C,
1515      but it must be handled correctly when using Fortran shared
1516      libraries.
1517
1518      Note that if NEWDYNCOMMON is set, NEWDEF will be set, and
1519      likewise for OLDDYNCOMMON and OLDDEF.
1520
1521      Note that this test is just a heuristic, and that it is quite
1522      possible to have an uninitialized symbol in a shared object which
1523      is really a definition, rather than a common symbol.  This could
1524      lead to some minor confusion when the symbol really is a common
1525      symbol in some regular object.  However, I think it will be
1526      harmless.  */
1527
1528   if (newdyn
1529       && newdef
1530       && !newweak
1531       && (sec->flags & SEC_ALLOC) != 0
1532       && (sec->flags & SEC_LOAD) == 0
1533       && sym->st_size > 0
1534       && !newfunc)
1535     newdyncommon = TRUE;
1536   else
1537     newdyncommon = FALSE;
1538
1539   if (olddyn
1540       && olddef
1541       && h->root.type == bfd_link_hash_defined
1542       && h->def_dynamic
1543       && (h->root.u.def.section->flags & SEC_ALLOC) != 0
1544       && (h->root.u.def.section->flags & SEC_LOAD) == 0
1545       && h->size > 0
1546       && !oldfunc)
1547     olddyncommon = TRUE;
1548   else
1549     olddyncommon = FALSE;
1550
1551   /* We now know everything about the old and new symbols.  We ask the
1552      backend to check if we can merge them.  */
1553   if (bed->merge_symbol != NULL)
1554     {
1555       if (!bed->merge_symbol (h, sym, psec, newdef, olddef, oldbfd, oldsec))
1556         return FALSE;
1557       sec = *psec;
1558     }
1559
1560   /* If both the old and the new symbols look like common symbols in a
1561      dynamic object, set the size of the symbol to the larger of the
1562      two.  */
1563
1564   if (olddyncommon
1565       && newdyncommon
1566       && sym->st_size != h->size)
1567     {
1568       /* Since we think we have two common symbols, issue a multiple
1569          common warning if desired.  Note that we only warn if the
1570          size is different.  If the size is the same, we simply let
1571          the old symbol override the new one as normally happens with
1572          symbols defined in dynamic objects.  */
1573
1574       (*info->callbacks->multiple_common) (info, &h->root, abfd,
1575                                            bfd_link_hash_common, sym->st_size);
1576       if (sym->st_size > h->size)
1577         h->size = sym->st_size;
1578
1579       *size_change_ok = TRUE;
1580     }
1581
1582   /* If we are looking at a dynamic object, and we have found a
1583      definition, we need to see if the symbol was already defined by
1584      some other object.  If so, we want to use the existing
1585      definition, and we do not want to report a multiple symbol
1586      definition error; we do this by clobbering *PSEC to be
1587      bfd_und_section_ptr.
1588
1589      We treat a common symbol as a definition if the symbol in the
1590      shared library is a function, since common symbols always
1591      represent variables; this can cause confusion in principle, but
1592      any such confusion would seem to indicate an erroneous program or
1593      shared library.  We also permit a common symbol in a regular
1594      object to override a weak symbol in a shared object.  */
1595
1596   if (newdyn
1597       && newdef
1598       && (olddef
1599           || (h->root.type == bfd_link_hash_common
1600               && (newweak || newfunc))))
1601     {
1602       *override = TRUE;
1603       newdef = FALSE;
1604       newdyncommon = FALSE;
1605
1606       *psec = sec = bfd_und_section_ptr;
1607       *size_change_ok = TRUE;
1608
1609       /* If we get here when the old symbol is a common symbol, then
1610          we are explicitly letting it override a weak symbol or
1611          function in a dynamic object, and we don't want to warn about
1612          a type change.  If the old symbol is a defined symbol, a type
1613          change warning may still be appropriate.  */
1614
1615       if (h->root.type == bfd_link_hash_common)
1616         *type_change_ok = TRUE;
1617     }
1618
1619   /* Handle the special case of an old common symbol merging with a
1620      new symbol which looks like a common symbol in a shared object.
1621      We change *PSEC and *PVALUE to make the new symbol look like a
1622      common symbol, and let _bfd_generic_link_add_one_symbol do the
1623      right thing.  */
1624
1625   if (newdyncommon
1626       && h->root.type == bfd_link_hash_common)
1627     {
1628       *override = TRUE;
1629       newdef = FALSE;
1630       newdyncommon = FALSE;
1631       *pvalue = sym->st_size;
1632       *psec = sec = bed->common_section (oldsec);
1633       *size_change_ok = TRUE;
1634     }
1635
1636   /* Skip weak definitions of symbols that are already defined.  */
1637   if (newdef && olddef && newweak)
1638     {
1639       /* Don't skip new non-IR weak syms.  */
1640       if (!(oldbfd != NULL
1641             && (oldbfd->flags & BFD_PLUGIN) != 0
1642             && (abfd->flags & BFD_PLUGIN) == 0))
1643         {
1644           newdef = FALSE;
1645           *skip = TRUE;
1646         }
1647
1648       /* Merge st_other.  If the symbol already has a dynamic index,
1649          but visibility says it should not be visible, turn it into a
1650          local symbol.  */
1651       elf_merge_st_other (abfd, h, sym, sec, newdef, newdyn);
1652       if (h->dynindx != -1)
1653         switch (ELF_ST_VISIBILITY (h->other))
1654           {
1655           case STV_INTERNAL:
1656           case STV_HIDDEN:
1657             (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1658             break;
1659           }
1660     }
1661
1662   /* If the old symbol is from a dynamic object, and the new symbol is
1663      a definition which is not from a dynamic object, then the new
1664      symbol overrides the old symbol.  Symbols from regular files
1665      always take precedence over symbols from dynamic objects, even if
1666      they are defined after the dynamic object in the link.
1667
1668      As above, we again permit a common symbol in a regular object to
1669      override a definition in a shared object if the shared object
1670      symbol is a function or is weak.  */
1671
1672   flip = NULL;
1673   if (!newdyn
1674       && (newdef
1675           || (bfd_is_com_section (sec)
1676               && (oldweak || oldfunc)))
1677       && olddyn
1678       && olddef
1679       && h->def_dynamic)
1680     {
1681       /* Change the hash table entry to undefined, and let
1682          _bfd_generic_link_add_one_symbol do the right thing with the
1683          new definition.  */
1684
1685       h->root.type = bfd_link_hash_undefined;
1686       h->root.u.undef.abfd = h->root.u.def.section->owner;
1687       *size_change_ok = TRUE;
1688
1689       olddef = FALSE;
1690       olddyncommon = FALSE;
1691
1692       /* We again permit a type change when a common symbol may be
1693          overriding a function.  */
1694
1695       if (bfd_is_com_section (sec))
1696         {
1697           if (oldfunc)
1698             {
1699               /* If a common symbol overrides a function, make sure
1700                  that it isn't defined dynamically nor has type
1701                  function.  */
1702               h->def_dynamic = 0;
1703               h->type = STT_NOTYPE;
1704             }
1705           *type_change_ok = TRUE;
1706         }
1707
1708       if (hi->root.type == bfd_link_hash_indirect)
1709         flip = hi;
1710       else
1711         /* This union may have been set to be non-NULL when this symbol
1712            was seen in a dynamic object.  We must force the union to be
1713            NULL, so that it is correct for a regular symbol.  */
1714         h->verinfo.vertree = NULL;
1715     }
1716
1717   /* Handle the special case of a new common symbol merging with an
1718      old symbol that looks like it might be a common symbol defined in
1719      a shared object.  Note that we have already handled the case in
1720      which a new common symbol should simply override the definition
1721      in the shared library.  */
1722
1723   if (! newdyn
1724       && bfd_is_com_section (sec)
1725       && olddyncommon)
1726     {
1727       /* It would be best if we could set the hash table entry to a
1728          common symbol, but we don't know what to use for the section
1729          or the alignment.  */
1730       (*info->callbacks->multiple_common) (info, &h->root, abfd,
1731                                            bfd_link_hash_common, sym->st_size);
1732
1733       /* If the presumed common symbol in the dynamic object is
1734          larger, pretend that the new symbol has its size.  */
1735
1736       if (h->size > *pvalue)
1737         *pvalue = h->size;
1738
1739       /* We need to remember the alignment required by the symbol
1740          in the dynamic object.  */
1741       BFD_ASSERT (pold_alignment);
1742       *pold_alignment = h->root.u.def.section->alignment_power;
1743
1744       olddef = FALSE;
1745       olddyncommon = FALSE;
1746
1747       h->root.type = bfd_link_hash_undefined;
1748       h->root.u.undef.abfd = h->root.u.def.section->owner;
1749
1750       *size_change_ok = TRUE;
1751       *type_change_ok = TRUE;
1752
1753       if (hi->root.type == bfd_link_hash_indirect)
1754         flip = hi;
1755       else
1756         h->verinfo.vertree = NULL;
1757     }
1758
1759   if (flip != NULL)
1760     {
1761       /* Handle the case where we had a versioned symbol in a dynamic
1762          library and now find a definition in a normal object.  In this
1763          case, we make the versioned symbol point to the normal one.  */
1764       flip->root.type = h->root.type;
1765       flip->root.u.undef.abfd = h->root.u.undef.abfd;
1766       h->root.type = bfd_link_hash_indirect;
1767       h->root.u.i.link = (struct bfd_link_hash_entry *) flip;
1768       (*bed->elf_backend_copy_indirect_symbol) (info, flip, h);
1769       if (h->def_dynamic)
1770         {
1771           h->def_dynamic = 0;
1772           flip->ref_dynamic = 1;
1773         }
1774     }
1775
1776   return TRUE;
1777 }
1778
1779 /* This function is called to create an indirect symbol from the
1780    default for the symbol with the default version if needed. The
1781    symbol is described by H, NAME, SYM, SEC, and VALUE.  We
1782    set DYNSYM if the new indirect symbol is dynamic.  */
1783
1784 static bfd_boolean
1785 _bfd_elf_add_default_symbol (bfd *abfd,
1786                              struct bfd_link_info *info,
1787                              struct elf_link_hash_entry *h,
1788                              const char *name,
1789                              Elf_Internal_Sym *sym,
1790                              asection *sec,
1791                              bfd_vma value,
1792                              bfd **poldbfd,
1793                              bfd_boolean *dynsym)
1794 {
1795   bfd_boolean type_change_ok;
1796   bfd_boolean size_change_ok;
1797   bfd_boolean skip;
1798   char *shortname;
1799   struct elf_link_hash_entry *hi;
1800   struct bfd_link_hash_entry *bh;
1801   const struct elf_backend_data *bed;
1802   bfd_boolean collect;
1803   bfd_boolean dynamic;
1804   bfd_boolean override;
1805   char *p;
1806   size_t len, shortlen;
1807   asection *tmp_sec;
1808   bfd_boolean matched;
1809
1810   if (h->versioned == unversioned || h->versioned == versioned_hidden)
1811     return TRUE;
1812
1813   /* If this symbol has a version, and it is the default version, we
1814      create an indirect symbol from the default name to the fully
1815      decorated name.  This will cause external references which do not
1816      specify a version to be bound to this version of the symbol.  */
1817   p = strchr (name, ELF_VER_CHR);
1818   if (h->versioned == unknown)
1819     {
1820       if (p == NULL)
1821         {
1822           h->versioned = unversioned;
1823           return TRUE;
1824         }
1825       else
1826         {
1827           if (p[1] != ELF_VER_CHR)
1828             {
1829               h->versioned = versioned_hidden;
1830               return TRUE;
1831             }
1832           else
1833             h->versioned = versioned;
1834         }
1835     }
1836   else
1837     {
1838       /* PR ld/19073: We may see an unversioned definition after the
1839          default version.  */
1840       if (p == NULL)
1841         return TRUE;
1842     }
1843
1844   bed = get_elf_backend_data (abfd);
1845   collect = bed->collect;
1846   dynamic = (abfd->flags & DYNAMIC) != 0;
1847
1848   shortlen = p - name;
1849   shortname = (char *) bfd_hash_allocate (&info->hash->table, shortlen + 1);
1850   if (shortname == NULL)
1851     return FALSE;
1852   memcpy (shortname, name, shortlen);
1853   shortname[shortlen] = '\0';
1854
1855   /* We are going to create a new symbol.  Merge it with any existing
1856      symbol with this name.  For the purposes of the merge, act as
1857      though we were defining the symbol we just defined, although we
1858      actually going to define an indirect symbol.  */
1859   type_change_ok = FALSE;
1860   size_change_ok = FALSE;
1861   matched = TRUE;
1862   tmp_sec = sec;
1863   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &tmp_sec, &value,
1864                               &hi, poldbfd, NULL, NULL, &skip, &override,
1865                               &type_change_ok, &size_change_ok, &matched))
1866     return FALSE;
1867
1868   if (skip)
1869     goto nondefault;
1870
1871   if (hi->def_regular)
1872     {
1873       /* If the undecorated symbol will have a version added by a
1874          script different to H, then don't indirect to/from the
1875          undecorated symbol.  This isn't ideal because we may not yet
1876          have seen symbol versions, if given by a script on the
1877          command line rather than via --version-script.  */
1878       if (hi->verinfo.vertree == NULL && info->version_info != NULL)
1879         {
1880           bfd_boolean hide;
1881
1882           hi->verinfo.vertree
1883             = bfd_find_version_for_sym (info->version_info,
1884                                         hi->root.root.string, &hide);
1885           if (hi->verinfo.vertree != NULL && hide)
1886             {
1887               (*bed->elf_backend_hide_symbol) (info, hi, TRUE);
1888               goto nondefault;
1889             }
1890         }
1891       if (hi->verinfo.vertree != NULL
1892           && strcmp (p + 1 + (p[1] == '@'), hi->verinfo.vertree->name) != 0)
1893         goto nondefault;
1894     }
1895
1896   if (! override)
1897     {
1898       /* Add the default symbol if not performing a relocatable link.  */
1899       if (! bfd_link_relocatable (info))
1900         {
1901           bh = &hi->root;
1902           if (! (_bfd_generic_link_add_one_symbol
1903                  (info, abfd, shortname, BSF_INDIRECT,
1904                   bfd_ind_section_ptr,
1905                   0, name, FALSE, collect, &bh)))
1906             return FALSE;
1907           hi = (struct elf_link_hash_entry *) bh;
1908         }
1909     }
1910   else
1911     {
1912       /* In this case the symbol named SHORTNAME is overriding the
1913          indirect symbol we want to add.  We were planning on making
1914          SHORTNAME an indirect symbol referring to NAME.  SHORTNAME
1915          is the name without a version.  NAME is the fully versioned
1916          name, and it is the default version.
1917
1918          Overriding means that we already saw a definition for the
1919          symbol SHORTNAME in a regular object, and it is overriding
1920          the symbol defined in the dynamic object.
1921
1922          When this happens, we actually want to change NAME, the
1923          symbol we just added, to refer to SHORTNAME.  This will cause
1924          references to NAME in the shared object to become references
1925          to SHORTNAME in the regular object.  This is what we expect
1926          when we override a function in a shared object: that the
1927          references in the shared object will be mapped to the
1928          definition in the regular object.  */
1929
1930       while (hi->root.type == bfd_link_hash_indirect
1931              || hi->root.type == bfd_link_hash_warning)
1932         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1933
1934       h->root.type = bfd_link_hash_indirect;
1935       h->root.u.i.link = (struct bfd_link_hash_entry *) hi;
1936       if (h->def_dynamic)
1937         {
1938           h->def_dynamic = 0;
1939           hi->ref_dynamic = 1;
1940           if (hi->ref_regular
1941               || hi->def_regular)
1942             {
1943               if (! bfd_elf_link_record_dynamic_symbol (info, hi))
1944                 return FALSE;
1945             }
1946         }
1947
1948       /* Now set HI to H, so that the following code will set the
1949          other fields correctly.  */
1950       hi = h;
1951     }
1952
1953   /* Check if HI is a warning symbol.  */
1954   if (hi->root.type == bfd_link_hash_warning)
1955     hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1956
1957   /* If there is a duplicate definition somewhere, then HI may not
1958      point to an indirect symbol.  We will have reported an error to
1959      the user in that case.  */
1960
1961   if (hi->root.type == bfd_link_hash_indirect)
1962     {
1963       struct elf_link_hash_entry *ht;
1964
1965       ht = (struct elf_link_hash_entry *) hi->root.u.i.link;
1966       (*bed->elf_backend_copy_indirect_symbol) (info, ht, hi);
1967
1968       /* A reference to the SHORTNAME symbol from a dynamic library
1969          will be satisfied by the versioned symbol at runtime.  In
1970          effect, we have a reference to the versioned symbol.  */
1971       ht->ref_dynamic_nonweak |= hi->ref_dynamic_nonweak;
1972       hi->dynamic_def |= ht->dynamic_def;
1973
1974       /* See if the new flags lead us to realize that the symbol must
1975          be dynamic.  */
1976       if (! *dynsym)
1977         {
1978           if (! dynamic)
1979             {
1980               if (! bfd_link_executable (info)
1981                   || hi->def_dynamic
1982                   || hi->ref_dynamic)
1983                 *dynsym = TRUE;
1984             }
1985           else
1986             {
1987               if (hi->ref_regular)
1988                 *dynsym = TRUE;
1989             }
1990         }
1991     }
1992
1993   /* We also need to define an indirection from the nondefault version
1994      of the symbol.  */
1995
1996 nondefault:
1997   len = strlen (name);
1998   shortname = (char *) bfd_hash_allocate (&info->hash->table, len);
1999   if (shortname == NULL)
2000     return FALSE;
2001   memcpy (shortname, name, shortlen);
2002   memcpy (shortname + shortlen, p + 1, len - shortlen);
2003
2004   /* Once again, merge with any existing symbol.  */
2005   type_change_ok = FALSE;
2006   size_change_ok = FALSE;
2007   tmp_sec = sec;
2008   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &tmp_sec, &value,
2009                               &hi, poldbfd, NULL, NULL, &skip, &override,
2010                               &type_change_ok, &size_change_ok, &matched))
2011     return FALSE;
2012
2013   if (skip)
2014     return TRUE;
2015
2016   if (override)
2017     {
2018       /* Here SHORTNAME is a versioned name, so we don't expect to see
2019          the type of override we do in the case above unless it is
2020          overridden by a versioned definition.  */
2021       if (hi->root.type != bfd_link_hash_defined
2022           && hi->root.type != bfd_link_hash_defweak)
2023         _bfd_error_handler
2024           /* xgettext:c-format */
2025           (_("%B: unexpected redefinition of indirect versioned symbol `%s'"),
2026            abfd, shortname);
2027     }
2028   else
2029     {
2030       bh = &hi->root;
2031       if (! (_bfd_generic_link_add_one_symbol
2032              (info, abfd, shortname, BSF_INDIRECT,
2033               bfd_ind_section_ptr, 0, name, FALSE, collect, &bh)))
2034         return FALSE;
2035       hi = (struct elf_link_hash_entry *) bh;
2036
2037       /* If there is a duplicate definition somewhere, then HI may not
2038          point to an indirect symbol.  We will have reported an error
2039          to the user in that case.  */
2040
2041       if (hi->root.type == bfd_link_hash_indirect)
2042         {
2043           (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
2044           h->ref_dynamic_nonweak |= hi->ref_dynamic_nonweak;
2045           hi->dynamic_def |= h->dynamic_def;
2046
2047           /* See if the new flags lead us to realize that the symbol
2048              must be dynamic.  */
2049           if (! *dynsym)
2050             {
2051               if (! dynamic)
2052                 {
2053                   if (! bfd_link_executable (info)
2054                       || hi->ref_dynamic)
2055                     *dynsym = TRUE;
2056                 }
2057               else
2058                 {
2059                   if (hi->ref_regular)
2060                     *dynsym = TRUE;
2061                 }
2062             }
2063         }
2064     }
2065
2066   return TRUE;
2067 }
2068 \f
2069 /* This routine is used to export all defined symbols into the dynamic
2070    symbol table.  It is called via elf_link_hash_traverse.  */
2071
2072 static bfd_boolean
2073 _bfd_elf_export_symbol (struct elf_link_hash_entry *h, void *data)
2074 {
2075   struct elf_info_failed *eif = (struct elf_info_failed *) data;
2076
2077   /* Ignore indirect symbols.  These are added by the versioning code.  */
2078   if (h->root.type == bfd_link_hash_indirect)
2079     return TRUE;
2080
2081   /* Ignore this if we won't export it.  */
2082   if (!eif->info->export_dynamic && !h->dynamic)
2083     return TRUE;
2084
2085   if (h->dynindx == -1
2086       && (h->def_regular || h->ref_regular)
2087       && ! bfd_hide_sym_by_version (eif->info->version_info,
2088                                     h->root.root.string))
2089     {
2090       if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
2091         {
2092           eif->failed = TRUE;
2093           return FALSE;
2094         }
2095     }
2096
2097   return TRUE;
2098 }
2099 \f
2100 /* Look through the symbols which are defined in other shared
2101    libraries and referenced here.  Update the list of version
2102    dependencies.  This will be put into the .gnu.version_r section.
2103    This function is called via elf_link_hash_traverse.  */
2104
2105 static bfd_boolean
2106 _bfd_elf_link_find_version_dependencies (struct elf_link_hash_entry *h,
2107                                          void *data)
2108 {
2109   struct elf_find_verdep_info *rinfo = (struct elf_find_verdep_info *) data;
2110   Elf_Internal_Verneed *t;
2111   Elf_Internal_Vernaux *a;
2112   bfd_size_type amt;
2113
2114   /* We only care about symbols defined in shared objects with version
2115      information.  */
2116   if (!h->def_dynamic
2117       || h->def_regular
2118       || h->dynindx == -1
2119       || h->verinfo.verdef == NULL
2120       || (elf_dyn_lib_class (h->verinfo.verdef->vd_bfd)
2121           & (DYN_AS_NEEDED | DYN_DT_NEEDED | DYN_NO_NEEDED)))
2122     return TRUE;
2123
2124   /* See if we already know about this version.  */
2125   for (t = elf_tdata (rinfo->info->output_bfd)->verref;
2126        t != NULL;
2127        t = t->vn_nextref)
2128     {
2129       if (t->vn_bfd != h->verinfo.verdef->vd_bfd)
2130         continue;
2131
2132       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
2133         if (a->vna_nodename == h->verinfo.verdef->vd_nodename)
2134           return TRUE;
2135
2136       break;
2137     }
2138
2139   /* This is a new version.  Add it to tree we are building.  */
2140
2141   if (t == NULL)
2142     {
2143       amt = sizeof *t;
2144       t = (Elf_Internal_Verneed *) bfd_zalloc (rinfo->info->output_bfd, amt);
2145       if (t == NULL)
2146         {
2147           rinfo->failed = TRUE;
2148           return FALSE;
2149         }
2150
2151       t->vn_bfd = h->verinfo.verdef->vd_bfd;
2152       t->vn_nextref = elf_tdata (rinfo->info->output_bfd)->verref;
2153       elf_tdata (rinfo->info->output_bfd)->verref = t;
2154     }
2155
2156   amt = sizeof *a;
2157   a = (Elf_Internal_Vernaux *) bfd_zalloc (rinfo->info->output_bfd, amt);
2158   if (a == NULL)
2159     {
2160       rinfo->failed = TRUE;
2161       return FALSE;
2162     }
2163
2164   /* Note that we are copying a string pointer here, and testing it
2165      above.  If bfd_elf_string_from_elf_section is ever changed to
2166      discard the string data when low in memory, this will have to be
2167      fixed.  */
2168   a->vna_nodename = h->verinfo.verdef->vd_nodename;
2169
2170   a->vna_flags = h->verinfo.verdef->vd_flags;
2171   a->vna_nextptr = t->vn_auxptr;
2172
2173   h->verinfo.verdef->vd_exp_refno = rinfo->vers;
2174   ++rinfo->vers;
2175
2176   a->vna_other = h->verinfo.verdef->vd_exp_refno + 1;
2177
2178   t->vn_auxptr = a;
2179
2180   return TRUE;
2181 }
2182
2183 /* Figure out appropriate versions for all the symbols.  We may not
2184    have the version number script until we have read all of the input
2185    files, so until that point we don't know which symbols should be
2186    local.  This function is called via elf_link_hash_traverse.  */
2187
2188 static bfd_boolean
2189 _bfd_elf_link_assign_sym_version (struct elf_link_hash_entry *h, void *data)
2190 {
2191   struct elf_info_failed *sinfo;
2192   struct bfd_link_info *info;
2193   const struct elf_backend_data *bed;
2194   struct elf_info_failed eif;
2195   char *p;
2196
2197   sinfo = (struct elf_info_failed *) data;
2198   info = sinfo->info;
2199
2200   /* Fix the symbol flags.  */
2201   eif.failed = FALSE;
2202   eif.info = info;
2203   if (! _bfd_elf_fix_symbol_flags (h, &eif))
2204     {
2205       if (eif.failed)
2206         sinfo->failed = TRUE;
2207       return FALSE;
2208     }
2209
2210   /* We only need version numbers for symbols defined in regular
2211      objects.  */
2212   if (!h->def_regular)
2213     return TRUE;
2214
2215   bed = get_elf_backend_data (info->output_bfd);
2216   p = strchr (h->root.root.string, ELF_VER_CHR);
2217   if (p != NULL && h->verinfo.vertree == NULL)
2218     {
2219       struct bfd_elf_version_tree *t;
2220
2221       ++p;
2222       if (*p == ELF_VER_CHR)
2223         ++p;
2224
2225       /* If there is no version string, we can just return out.  */
2226       if (*p == '\0')
2227         return TRUE;
2228
2229       /* Look for the version.  If we find it, it is no longer weak.  */
2230       for (t = sinfo->info->version_info; t != NULL; t = t->next)
2231         {
2232           if (strcmp (t->name, p) == 0)
2233             {
2234               size_t len;
2235               char *alc;
2236               struct bfd_elf_version_expr *d;
2237
2238               len = p - h->root.root.string;
2239               alc = (char *) bfd_malloc (len);
2240               if (alc == NULL)
2241                 {
2242                   sinfo->failed = TRUE;
2243                   return FALSE;
2244                 }
2245               memcpy (alc, h->root.root.string, len - 1);
2246               alc[len - 1] = '\0';
2247               if (alc[len - 2] == ELF_VER_CHR)
2248                 alc[len - 2] = '\0';
2249
2250               h->verinfo.vertree = t;
2251               t->used = TRUE;
2252               d = NULL;
2253
2254               if (t->globals.list != NULL)
2255                 d = (*t->match) (&t->globals, NULL, alc);
2256
2257               /* See if there is anything to force this symbol to
2258                  local scope.  */
2259               if (d == NULL && t->locals.list != NULL)
2260                 {
2261                   d = (*t->match) (&t->locals, NULL, alc);
2262                   if (d != NULL
2263                       && h->dynindx != -1
2264                       && ! info->export_dynamic)
2265                     (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2266                 }
2267
2268               free (alc);
2269               break;
2270             }
2271         }
2272
2273       /* If we are building an application, we need to create a
2274          version node for this version.  */
2275       if (t == NULL && bfd_link_executable (info))
2276         {
2277           struct bfd_elf_version_tree **pp;
2278           int version_index;
2279
2280           /* If we aren't going to export this symbol, we don't need
2281              to worry about it.  */
2282           if (h->dynindx == -1)
2283             return TRUE;
2284
2285           t = (struct bfd_elf_version_tree *) bfd_zalloc (info->output_bfd,
2286                                                           sizeof *t);
2287           if (t == NULL)
2288             {
2289               sinfo->failed = TRUE;
2290               return FALSE;
2291             }
2292
2293           t->name = p;
2294           t->name_indx = (unsigned int) -1;
2295           t->used = TRUE;
2296
2297           version_index = 1;
2298           /* Don't count anonymous version tag.  */
2299           if (sinfo->info->version_info != NULL
2300               && sinfo->info->version_info->vernum == 0)
2301             version_index = 0;
2302           for (pp = &sinfo->info->version_info;
2303                *pp != NULL;
2304                pp = &(*pp)->next)
2305             ++version_index;
2306           t->vernum = version_index;
2307
2308           *pp = t;
2309
2310           h->verinfo.vertree = t;
2311         }
2312       else if (t == NULL)
2313         {
2314           /* We could not find the version for a symbol when
2315              generating a shared archive.  Return an error.  */
2316           _bfd_error_handler
2317             /* xgettext:c-format */
2318             (_("%B: version node not found for symbol %s"),
2319              info->output_bfd, h->root.root.string);
2320           bfd_set_error (bfd_error_bad_value);
2321           sinfo->failed = TRUE;
2322           return FALSE;
2323         }
2324     }
2325
2326   /* If we don't have a version for this symbol, see if we can find
2327      something.  */
2328   if (h->verinfo.vertree == NULL && sinfo->info->version_info != NULL)
2329     {
2330       bfd_boolean hide;
2331
2332       h->verinfo.vertree
2333         = bfd_find_version_for_sym (sinfo->info->version_info,
2334                                     h->root.root.string, &hide);
2335       if (h->verinfo.vertree != NULL && hide)
2336         (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2337     }
2338
2339   return TRUE;
2340 }
2341 \f
2342 /* Read and swap the relocs from the section indicated by SHDR.  This
2343    may be either a REL or a RELA section.  The relocations are
2344    translated into RELA relocations and stored in INTERNAL_RELOCS,
2345    which should have already been allocated to contain enough space.
2346    The EXTERNAL_RELOCS are a buffer where the external form of the
2347    relocations should be stored.
2348
2349    Returns FALSE if something goes wrong.  */
2350
2351 static bfd_boolean
2352 elf_link_read_relocs_from_section (bfd *abfd,
2353                                    asection *sec,
2354                                    Elf_Internal_Shdr *shdr,
2355                                    void *external_relocs,
2356                                    Elf_Internal_Rela *internal_relocs)
2357 {
2358   const struct elf_backend_data *bed;
2359   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
2360   const bfd_byte *erela;
2361   const bfd_byte *erelaend;
2362   Elf_Internal_Rela *irela;
2363   Elf_Internal_Shdr *symtab_hdr;
2364   size_t nsyms;
2365
2366   /* Position ourselves at the start of the section.  */
2367   if (bfd_seek (abfd, shdr->sh_offset, SEEK_SET) != 0)
2368     return FALSE;
2369
2370   /* Read the relocations.  */
2371   if (bfd_bread (external_relocs, shdr->sh_size, abfd) != shdr->sh_size)
2372     return FALSE;
2373
2374   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
2375   nsyms = NUM_SHDR_ENTRIES (symtab_hdr);
2376
2377   bed = get_elf_backend_data (abfd);
2378
2379   /* Convert the external relocations to the internal format.  */
2380   if (shdr->sh_entsize == bed->s->sizeof_rel)
2381     swap_in = bed->s->swap_reloc_in;
2382   else if (shdr->sh_entsize == bed->s->sizeof_rela)
2383     swap_in = bed->s->swap_reloca_in;
2384   else
2385     {
2386       bfd_set_error (bfd_error_wrong_format);
2387       return FALSE;
2388     }
2389
2390   erela = (const bfd_byte *) external_relocs;
2391   erelaend = erela + shdr->sh_size;
2392   irela = internal_relocs;
2393   while (erela < erelaend)
2394     {
2395       bfd_vma r_symndx;
2396
2397       (*swap_in) (abfd, erela, irela);
2398       r_symndx = ELF32_R_SYM (irela->r_info);
2399       if (bed->s->arch_size == 64)
2400         r_symndx >>= 24;
2401       if (nsyms > 0)
2402         {
2403           if ((size_t) r_symndx >= nsyms)
2404             {
2405               _bfd_error_handler
2406                 /* xgettext:c-format */
2407                 (_("%B: bad reloc symbol index (%#Lx >= %#lx)"
2408                    " for offset %#Lx in section `%A'"),
2409                  abfd, r_symndx, (unsigned long) nsyms,
2410                  irela->r_offset, sec);
2411               bfd_set_error (bfd_error_bad_value);
2412               return FALSE;
2413             }
2414         }
2415       else if (r_symndx != STN_UNDEF)
2416         {
2417           _bfd_error_handler
2418             /* xgettext:c-format */
2419             (_("%B: non-zero symbol index (%#Lx)"
2420                " for offset %#Lx in section `%A'"
2421                " when the object file has no symbol table"),
2422              abfd, r_symndx,
2423              irela->r_offset, sec);
2424           bfd_set_error (bfd_error_bad_value);
2425           return FALSE;
2426         }
2427       irela += bed->s->int_rels_per_ext_rel;
2428       erela += shdr->sh_entsize;
2429     }
2430
2431   return TRUE;
2432 }
2433
2434 /* Read and swap the relocs for a section O.  They may have been
2435    cached.  If the EXTERNAL_RELOCS and INTERNAL_RELOCS arguments are
2436    not NULL, they are used as buffers to read into.  They are known to
2437    be large enough.  If the INTERNAL_RELOCS relocs argument is NULL,
2438    the return value is allocated using either malloc or bfd_alloc,
2439    according to the KEEP_MEMORY argument.  If O has two relocation
2440    sections (both REL and RELA relocations), then the REL_HDR
2441    relocations will appear first in INTERNAL_RELOCS, followed by the
2442    RELA_HDR relocations.  */
2443
2444 Elf_Internal_Rela *
2445 _bfd_elf_link_read_relocs (bfd *abfd,
2446                            asection *o,
2447                            void *external_relocs,
2448                            Elf_Internal_Rela *internal_relocs,
2449                            bfd_boolean keep_memory)
2450 {
2451   void *alloc1 = NULL;
2452   Elf_Internal_Rela *alloc2 = NULL;
2453   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
2454   struct bfd_elf_section_data *esdo = elf_section_data (o);
2455   Elf_Internal_Rela *internal_rela_relocs;
2456
2457   if (esdo->relocs != NULL)
2458     return esdo->relocs;
2459
2460   if (o->reloc_count == 0)
2461     return NULL;
2462
2463   if (internal_relocs == NULL)
2464     {
2465       bfd_size_type size;
2466
2467       size = (bfd_size_type) o->reloc_count * sizeof (Elf_Internal_Rela);
2468       if (keep_memory)
2469         internal_relocs = alloc2 = (Elf_Internal_Rela *) bfd_alloc (abfd, size);
2470       else
2471         internal_relocs = alloc2 = (Elf_Internal_Rela *) bfd_malloc (size);
2472       if (internal_relocs == NULL)
2473         goto error_return;
2474     }
2475
2476   if (external_relocs == NULL)
2477     {
2478       bfd_size_type size = 0;
2479
2480       if (esdo->rel.hdr)
2481         size += esdo->rel.hdr->sh_size;
2482       if (esdo->rela.hdr)
2483         size += esdo->rela.hdr->sh_size;
2484
2485       alloc1 = bfd_malloc (size);
2486       if (alloc1 == NULL)
2487         goto error_return;
2488       external_relocs = alloc1;
2489     }
2490
2491   internal_rela_relocs = internal_relocs;
2492   if (esdo->rel.hdr)
2493     {
2494       if (!elf_link_read_relocs_from_section (abfd, o, esdo->rel.hdr,
2495                                               external_relocs,
2496                                               internal_relocs))
2497         goto error_return;
2498       external_relocs = (((bfd_byte *) external_relocs)
2499                          + esdo->rel.hdr->sh_size);
2500       internal_rela_relocs += (NUM_SHDR_ENTRIES (esdo->rel.hdr)
2501                                * bed->s->int_rels_per_ext_rel);
2502     }
2503
2504   if (esdo->rela.hdr
2505       && (!elf_link_read_relocs_from_section (abfd, o, esdo->rela.hdr,
2506                                               external_relocs,
2507                                               internal_rela_relocs)))
2508     goto error_return;
2509
2510   /* Cache the results for next time, if we can.  */
2511   if (keep_memory)
2512     esdo->relocs = internal_relocs;
2513
2514   if (alloc1 != NULL)
2515     free (alloc1);
2516
2517   /* Don't free alloc2, since if it was allocated we are passing it
2518      back (under the name of internal_relocs).  */
2519
2520   return internal_relocs;
2521
2522  error_return:
2523   if (alloc1 != NULL)
2524     free (alloc1);
2525   if (alloc2 != NULL)
2526     {
2527       if (keep_memory)
2528         bfd_release (abfd, alloc2);
2529       else
2530         free (alloc2);
2531     }
2532   return NULL;
2533 }
2534
2535 /* Compute the size of, and allocate space for, REL_HDR which is the
2536    section header for a section containing relocations for O.  */
2537
2538 static bfd_boolean
2539 _bfd_elf_link_size_reloc_section (bfd *abfd,
2540                                   struct bfd_elf_section_reloc_data *reldata)
2541 {
2542   Elf_Internal_Shdr *rel_hdr = reldata->hdr;
2543
2544   /* That allows us to calculate the size of the section.  */
2545   rel_hdr->sh_size = rel_hdr->sh_entsize * reldata->count;
2546
2547   /* The contents field must last into write_object_contents, so we
2548      allocate it with bfd_alloc rather than malloc.  Also since we
2549      cannot be sure that the contents will actually be filled in,
2550      we zero the allocated space.  */
2551   rel_hdr->contents = (unsigned char *) bfd_zalloc (abfd, rel_hdr->sh_size);
2552   if (rel_hdr->contents == NULL && rel_hdr->sh_size != 0)
2553     return FALSE;
2554
2555   if (reldata->hashes == NULL && reldata->count)
2556     {
2557       struct elf_link_hash_entry **p;
2558
2559       p = ((struct elf_link_hash_entry **)
2560            bfd_zmalloc (reldata->count * sizeof (*p)));
2561       if (p == NULL)
2562         return FALSE;
2563
2564       reldata->hashes = p;
2565     }
2566
2567   return TRUE;
2568 }
2569
2570 /* Copy the relocations indicated by the INTERNAL_RELOCS (which
2571    originated from the section given by INPUT_REL_HDR) to the
2572    OUTPUT_BFD.  */
2573
2574 bfd_boolean
2575 _bfd_elf_link_output_relocs (bfd *output_bfd,
2576                              asection *input_section,
2577                              Elf_Internal_Shdr *input_rel_hdr,
2578                              Elf_Internal_Rela *internal_relocs,
2579                              struct elf_link_hash_entry **rel_hash
2580                                ATTRIBUTE_UNUSED)
2581 {
2582   Elf_Internal_Rela *irela;
2583   Elf_Internal_Rela *irelaend;
2584   bfd_byte *erel;
2585   struct bfd_elf_section_reloc_data *output_reldata;
2586   asection *output_section;
2587   const struct elf_backend_data *bed;
2588   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
2589   struct bfd_elf_section_data *esdo;
2590
2591   output_section = input_section->output_section;
2592
2593   bed = get_elf_backend_data (output_bfd);
2594   esdo = elf_section_data (output_section);
2595   if (esdo->rel.hdr && esdo->rel.hdr->sh_entsize == input_rel_hdr->sh_entsize)
2596     {
2597       output_reldata = &esdo->rel;
2598       swap_out = bed->s->swap_reloc_out;
2599     }
2600   else if (esdo->rela.hdr
2601            && esdo->rela.hdr->sh_entsize == input_rel_hdr->sh_entsize)
2602     {
2603       output_reldata = &esdo->rela;
2604       swap_out = bed->s->swap_reloca_out;
2605     }
2606   else
2607     {
2608       _bfd_error_handler
2609         /* xgettext:c-format */
2610         (_("%B: relocation size mismatch in %B section %A"),
2611          output_bfd, input_section->owner, input_section);
2612       bfd_set_error (bfd_error_wrong_format);
2613       return FALSE;
2614     }
2615
2616   erel = output_reldata->hdr->contents;
2617   erel += output_reldata->count * input_rel_hdr->sh_entsize;
2618   irela = internal_relocs;
2619   irelaend = irela + (NUM_SHDR_ENTRIES (input_rel_hdr)
2620                       * bed->s->int_rels_per_ext_rel);
2621   while (irela < irelaend)
2622     {
2623       (*swap_out) (output_bfd, irela, erel);
2624       irela += bed->s->int_rels_per_ext_rel;
2625       erel += input_rel_hdr->sh_entsize;
2626     }
2627
2628   /* Bump the counter, so that we know where to add the next set of
2629      relocations.  */
2630   output_reldata->count += NUM_SHDR_ENTRIES (input_rel_hdr);
2631
2632   return TRUE;
2633 }
2634 \f
2635 /* Make weak undefined symbols in PIE dynamic.  */
2636
2637 bfd_boolean
2638 _bfd_elf_link_hash_fixup_symbol (struct bfd_link_info *info,
2639                                  struct elf_link_hash_entry *h)
2640 {
2641   if (bfd_link_pie (info)
2642       && h->dynindx == -1
2643       && h->root.type == bfd_link_hash_undefweak)
2644     return bfd_elf_link_record_dynamic_symbol (info, h);
2645
2646   return TRUE;
2647 }
2648
2649 /* Fix up the flags for a symbol.  This handles various cases which
2650    can only be fixed after all the input files are seen.  This is
2651    currently called by both adjust_dynamic_symbol and
2652    assign_sym_version, which is unnecessary but perhaps more robust in
2653    the face of future changes.  */
2654
2655 static bfd_boolean
2656 _bfd_elf_fix_symbol_flags (struct elf_link_hash_entry *h,
2657                            struct elf_info_failed *eif)
2658 {
2659   const struct elf_backend_data *bed;
2660
2661   /* If this symbol was mentioned in a non-ELF file, try to set
2662      DEF_REGULAR and REF_REGULAR correctly.  This is the only way to
2663      permit a non-ELF file to correctly refer to a symbol defined in
2664      an ELF dynamic object.  */
2665   if (h->non_elf)
2666     {
2667       while (h->root.type == bfd_link_hash_indirect)
2668         h = (struct elf_link_hash_entry *) h->root.u.i.link;
2669
2670       if (h->root.type != bfd_link_hash_defined
2671           && h->root.type != bfd_link_hash_defweak)
2672         {
2673           h->ref_regular = 1;
2674           h->ref_regular_nonweak = 1;
2675         }
2676       else
2677         {
2678           if (h->root.u.def.section->owner != NULL
2679               && (bfd_get_flavour (h->root.u.def.section->owner)
2680                   == bfd_target_elf_flavour))
2681             {
2682               h->ref_regular = 1;
2683               h->ref_regular_nonweak = 1;
2684             }
2685           else
2686             h->def_regular = 1;
2687         }
2688
2689       if (h->dynindx == -1
2690           && (h->def_dynamic
2691               || h->ref_dynamic))
2692         {
2693           if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
2694             {
2695               eif->failed = TRUE;
2696               return FALSE;
2697             }
2698         }
2699     }
2700   else
2701     {
2702       /* Unfortunately, NON_ELF is only correct if the symbol
2703          was first seen in a non-ELF file.  Fortunately, if the symbol
2704          was first seen in an ELF file, we're probably OK unless the
2705          symbol was defined in a non-ELF file.  Catch that case here.
2706          FIXME: We're still in trouble if the symbol was first seen in
2707          a dynamic object, and then later in a non-ELF regular object.  */
2708       if ((h->root.type == bfd_link_hash_defined
2709            || h->root.type == bfd_link_hash_defweak)
2710           && !h->def_regular
2711           && (h->root.u.def.section->owner != NULL
2712               ? (bfd_get_flavour (h->root.u.def.section->owner)
2713                  != bfd_target_elf_flavour)
2714               : (bfd_is_abs_section (h->root.u.def.section)
2715                  && !h->def_dynamic)))
2716         h->def_regular = 1;
2717     }
2718
2719   /* Backend specific symbol fixup.  */
2720   bed = get_elf_backend_data (elf_hash_table (eif->info)->dynobj);
2721   if (bed->elf_backend_fixup_symbol
2722       && !(*bed->elf_backend_fixup_symbol) (eif->info, h))
2723     return FALSE;
2724
2725   /* If this is a final link, and the symbol was defined as a common
2726      symbol in a regular object file, and there was no definition in
2727      any dynamic object, then the linker will have allocated space for
2728      the symbol in a common section but the DEF_REGULAR
2729      flag will not have been set.  */
2730   if (h->root.type == bfd_link_hash_defined
2731       && !h->def_regular
2732       && h->ref_regular
2733       && !h->def_dynamic
2734       && (h->root.u.def.section->owner->flags & (DYNAMIC | BFD_PLUGIN)) == 0)
2735     h->def_regular = 1;
2736
2737   /* If a weak undefined symbol has non-default visibility, we also
2738      hide it from the dynamic linker.  */
2739   if (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
2740       && h->root.type == bfd_link_hash_undefweak)
2741     (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2742
2743   /* A hidden versioned symbol in executable should be forced local if
2744      it is is locally defined, not referenced by shared library and not
2745      exported.  */
2746   else if (bfd_link_executable (eif->info)
2747            && h->versioned == versioned_hidden
2748            && !eif->info->export_dynamic
2749            && !h->dynamic
2750            && !h->ref_dynamic
2751            && h->def_regular)
2752     (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2753
2754   /* If -Bsymbolic was used (which means to bind references to global
2755      symbols to the definition within the shared object), and this
2756      symbol was defined in a regular object, then it actually doesn't
2757      need a PLT entry.  Likewise, if the symbol has non-default
2758      visibility.  If the symbol has hidden or internal visibility, we
2759      will force it local.  */
2760   else if (h->needs_plt
2761            && bfd_link_pic (eif->info)
2762            && is_elf_hash_table (eif->info->hash)
2763            && (SYMBOLIC_BIND (eif->info, h)
2764                || ELF_ST_VISIBILITY (h->other) != STV_DEFAULT)
2765            && h->def_regular)
2766     {
2767       bfd_boolean force_local;
2768
2769       force_local = (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL
2770                      || ELF_ST_VISIBILITY (h->other) == STV_HIDDEN);
2771       (*bed->elf_backend_hide_symbol) (eif->info, h, force_local);
2772     }
2773
2774   /* If this is a weak defined symbol in a dynamic object, and we know
2775      the real definition in the dynamic object, copy interesting flags
2776      over to the real definition.  */
2777   if (h->u.weakdef != NULL)
2778     {
2779       /* If the real definition is defined by a regular object file,
2780          don't do anything special.  See the longer description in
2781          _bfd_elf_adjust_dynamic_symbol, below.  */
2782       if (h->u.weakdef->def_regular)
2783         h->u.weakdef = NULL;
2784       else
2785         {
2786           struct elf_link_hash_entry *weakdef = h->u.weakdef;
2787
2788           while (h->root.type == bfd_link_hash_indirect)
2789             h = (struct elf_link_hash_entry *) h->root.u.i.link;
2790
2791           BFD_ASSERT (h->root.type == bfd_link_hash_defined
2792                       || h->root.type == bfd_link_hash_defweak);
2793           BFD_ASSERT (weakdef->def_dynamic);
2794           BFD_ASSERT (weakdef->root.type == bfd_link_hash_defined
2795                       || weakdef->root.type == bfd_link_hash_defweak);
2796           (*bed->elf_backend_copy_indirect_symbol) (eif->info, weakdef, h);
2797         }
2798     }
2799
2800   return TRUE;
2801 }
2802
2803 /* Make the backend pick a good value for a dynamic symbol.  This is
2804    called via elf_link_hash_traverse, and also calls itself
2805    recursively.  */
2806
2807 static bfd_boolean
2808 _bfd_elf_adjust_dynamic_symbol (struct elf_link_hash_entry *h, void *data)
2809 {
2810   struct elf_info_failed *eif = (struct elf_info_failed *) data;
2811   struct elf_link_hash_table *htab;
2812   const struct elf_backend_data *bed;
2813
2814   if (! is_elf_hash_table (eif->info->hash))
2815     return FALSE;
2816
2817   /* Ignore indirect symbols.  These are added by the versioning code.  */
2818   if (h->root.type == bfd_link_hash_indirect)
2819     return TRUE;
2820
2821   /* Fix the symbol flags.  */
2822   if (! _bfd_elf_fix_symbol_flags (h, eif))
2823     return FALSE;
2824
2825   htab = elf_hash_table (eif->info);
2826   bed = get_elf_backend_data (htab->dynobj);
2827
2828   if (h->root.type == bfd_link_hash_undefweak)
2829     {
2830       if (eif->info->dynamic_undefined_weak == 0)
2831         (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2832       else if (eif->info->dynamic_undefined_weak > 0
2833                && h->ref_regular
2834                && ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
2835                && !bfd_hide_sym_by_version (eif->info->version_info,
2836                                             h->root.root.string))
2837         {
2838           if (!bfd_elf_link_record_dynamic_symbol (eif->info, h))
2839             {
2840               eif->failed = TRUE;
2841               return FALSE;
2842             }
2843         }
2844     }
2845
2846   /* If this symbol does not require a PLT entry, and it is not
2847      defined by a dynamic object, or is not referenced by a regular
2848      object, ignore it.  We do have to handle a weak defined symbol,
2849      even if no regular object refers to it, if we decided to add it
2850      to the dynamic symbol table.  FIXME: Do we normally need to worry
2851      about symbols which are defined by one dynamic object and
2852      referenced by another one?  */
2853   if (!h->needs_plt
2854       && h->type != STT_GNU_IFUNC
2855       && (h->def_regular
2856           || !h->def_dynamic
2857           || (!h->ref_regular
2858               && (h->u.weakdef == NULL || h->u.weakdef->dynindx == -1))))
2859     {
2860       h->plt = elf_hash_table (eif->info)->init_plt_offset;
2861       return TRUE;
2862     }
2863
2864   /* If we've already adjusted this symbol, don't do it again.  This
2865      can happen via a recursive call.  */
2866   if (h->dynamic_adjusted)
2867     return TRUE;
2868
2869   /* Don't look at this symbol again.  Note that we must set this
2870      after checking the above conditions, because we may look at a
2871      symbol once, decide not to do anything, and then get called
2872      recursively later after REF_REGULAR is set below.  */
2873   h->dynamic_adjusted = 1;
2874
2875   /* If this is a weak definition, and we know a real definition, and
2876      the real symbol is not itself defined by a regular object file,
2877      then get a good value for the real definition.  We handle the
2878      real symbol first, for the convenience of the backend routine.
2879
2880      Note that there is a confusing case here.  If the real definition
2881      is defined by a regular object file, we don't get the real symbol
2882      from the dynamic object, but we do get the weak symbol.  If the
2883      processor backend uses a COPY reloc, then if some routine in the
2884      dynamic object changes the real symbol, we will not see that
2885      change in the corresponding weak symbol.  This is the way other
2886      ELF linkers work as well, and seems to be a result of the shared
2887      library model.
2888
2889      I will clarify this issue.  Most SVR4 shared libraries define the
2890      variable _timezone and define timezone as a weak synonym.  The
2891      tzset call changes _timezone.  If you write
2892        extern int timezone;
2893        int _timezone = 5;
2894        int main () { tzset (); printf ("%d %d\n", timezone, _timezone); }
2895      you might expect that, since timezone is a synonym for _timezone,
2896      the same number will print both times.  However, if the processor
2897      backend uses a COPY reloc, then actually timezone will be copied
2898      into your process image, and, since you define _timezone
2899      yourself, _timezone will not.  Thus timezone and _timezone will
2900      wind up at different memory locations.  The tzset call will set
2901      _timezone, leaving timezone unchanged.  */
2902
2903   if (h->u.weakdef != NULL)
2904     {
2905       /* If we get to this point, there is an implicit reference to
2906          H->U.WEAKDEF by a regular object file via the weak symbol H.  */
2907       h->u.weakdef->ref_regular = 1;
2908
2909       /* Ensure that the backend adjust_dynamic_symbol function sees
2910          H->U.WEAKDEF before H by recursively calling ourselves.  */
2911       if (! _bfd_elf_adjust_dynamic_symbol (h->u.weakdef, eif))
2912         return FALSE;
2913     }
2914
2915   /* If a symbol has no type and no size and does not require a PLT
2916      entry, then we are probably about to do the wrong thing here: we
2917      are probably going to create a COPY reloc for an empty object.
2918      This case can arise when a shared object is built with assembly
2919      code, and the assembly code fails to set the symbol type.  */
2920   if (h->size == 0
2921       && h->type == STT_NOTYPE
2922       && !h->needs_plt)
2923     _bfd_error_handler
2924       (_("warning: type and size of dynamic symbol `%s' are not defined"),
2925        h->root.root.string);
2926
2927   if (! (*bed->elf_backend_adjust_dynamic_symbol) (eif->info, h))
2928     {
2929       eif->failed = TRUE;
2930       return FALSE;
2931     }
2932
2933   return TRUE;
2934 }
2935
2936 /* Adjust the dynamic symbol, H, for copy in the dynamic bss section,
2937    DYNBSS.  */
2938
2939 bfd_boolean
2940 _bfd_elf_adjust_dynamic_copy (struct bfd_link_info *info,
2941                               struct elf_link_hash_entry *h,
2942                               asection *dynbss)
2943 {
2944   unsigned int power_of_two;
2945   bfd_vma mask;
2946   asection *sec = h->root.u.def.section;
2947
2948   /* The section alignment of the definition is the maximum alignment
2949      requirement of symbols defined in the section.  Since we don't
2950      know the symbol alignment requirement, we start with the
2951      maximum alignment and check low bits of the symbol address
2952      for the minimum alignment.  */
2953   power_of_two = bfd_get_section_alignment (sec->owner, sec);
2954   mask = ((bfd_vma) 1 << power_of_two) - 1;
2955   while ((h->root.u.def.value & mask) != 0)
2956     {
2957        mask >>= 1;
2958        --power_of_two;
2959     }
2960
2961   if (power_of_two > bfd_get_section_alignment (dynbss->owner,
2962                                                 dynbss))
2963     {
2964       /* Adjust the section alignment if needed.  */
2965       if (! bfd_set_section_alignment (dynbss->owner, dynbss,
2966                                        power_of_two))
2967         return FALSE;
2968     }
2969
2970   /* We make sure that the symbol will be aligned properly.  */
2971   dynbss->size = BFD_ALIGN (dynbss->size, mask + 1);
2972
2973   /* Define the symbol as being at this point in DYNBSS.  */
2974   h->root.u.def.section = dynbss;
2975   h->root.u.def.value = dynbss->size;
2976
2977   /* Increment the size of DYNBSS to make room for the symbol.  */
2978   dynbss->size += h->size;
2979
2980   /* No error if extern_protected_data is true.  */
2981   if (h->protected_def
2982       && (!info->extern_protected_data
2983           || (info->extern_protected_data < 0
2984               && !get_elf_backend_data (dynbss->owner)->extern_protected_data)))
2985     info->callbacks->einfo
2986       (_("%P: copy reloc against protected `%T' is dangerous\n"),
2987        h->root.root.string);
2988
2989   return TRUE;
2990 }
2991
2992 /* Adjust all external symbols pointing into SEC_MERGE sections
2993    to reflect the object merging within the sections.  */
2994
2995 static bfd_boolean
2996 _bfd_elf_link_sec_merge_syms (struct elf_link_hash_entry *h, void *data)
2997 {
2998   asection *sec;
2999
3000   if ((h->root.type == bfd_link_hash_defined
3001        || h->root.type == bfd_link_hash_defweak)
3002       && ((sec = h->root.u.def.section)->flags & SEC_MERGE)
3003       && sec->sec_info_type == SEC_INFO_TYPE_MERGE)
3004     {
3005       bfd *output_bfd = (bfd *) data;
3006
3007       h->root.u.def.value =
3008         _bfd_merged_section_offset (output_bfd,
3009                                     &h->root.u.def.section,
3010                                     elf_section_data (sec)->sec_info,
3011                                     h->root.u.def.value);
3012     }
3013
3014   return TRUE;
3015 }
3016
3017 /* Returns false if the symbol referred to by H should be considered
3018    to resolve local to the current module, and true if it should be
3019    considered to bind dynamically.  */
3020
3021 bfd_boolean
3022 _bfd_elf_dynamic_symbol_p (struct elf_link_hash_entry *h,
3023                            struct bfd_link_info *info,
3024                            bfd_boolean not_local_protected)
3025 {
3026   bfd_boolean binding_stays_local_p;
3027   const struct elf_backend_data *bed;
3028   struct elf_link_hash_table *hash_table;
3029
3030   if (h == NULL)
3031     return FALSE;
3032
3033   while (h->root.type == bfd_link_hash_indirect
3034          || h->root.type == bfd_link_hash_warning)
3035     h = (struct elf_link_hash_entry *) h->root.u.i.link;
3036
3037   /* If it was forced local, then clearly it's not dynamic.  */
3038   if (h->dynindx == -1)
3039     return FALSE;
3040   if (h->forced_local)
3041     return FALSE;
3042
3043   /* Identify the cases where name binding rules say that a
3044      visible symbol resolves locally.  */
3045   binding_stays_local_p = (bfd_link_executable (info)
3046                            || SYMBOLIC_BIND (info, h));
3047
3048   switch (ELF_ST_VISIBILITY (h->other))
3049     {
3050     case STV_INTERNAL:
3051     case STV_HIDDEN:
3052       return FALSE;
3053
3054     case STV_PROTECTED:
3055       hash_table = elf_hash_table (info);
3056       if (!is_elf_hash_table (hash_table))
3057         return FALSE;
3058
3059       bed = get_elf_backend_data (hash_table->dynobj);
3060
3061       /* Proper resolution for function pointer equality may require
3062          that these symbols perhaps be resolved dynamically, even though
3063          we should be resolving them to the current module.  */
3064       if (!not_local_protected || !bed->is_function_type (h->type))
3065         binding_stays_local_p = TRUE;
3066       break;
3067
3068     default:
3069       break;
3070     }
3071
3072   /* If it isn't defined locally, then clearly it's dynamic.  */
3073   if (!h->def_regular && !ELF_COMMON_DEF_P (h))
3074     return TRUE;
3075
3076   /* Otherwise, the symbol is dynamic if binding rules don't tell
3077      us that it remains local.  */
3078   return !binding_stays_local_p;
3079 }
3080
3081 /* Return true if the symbol referred to by H should be considered
3082    to resolve local to the current module, and false otherwise.  Differs
3083    from (the inverse of) _bfd_elf_dynamic_symbol_p in the treatment of
3084    undefined symbols.  The two functions are virtually identical except
3085    for the place where dynindx == -1 is tested.  If that test is true,
3086    _bfd_elf_dynamic_symbol_p will say the symbol is local, while
3087    _bfd_elf_symbol_refs_local_p will say the symbol is local only for
3088    defined symbols.
3089    It might seem that _bfd_elf_dynamic_symbol_p could be rewritten as
3090    !_bfd_elf_symbol_refs_local_p, except that targets differ in their
3091    treatment of undefined weak symbols.  For those that do not make
3092    undefined weak symbols dynamic, both functions may return false.  */
3093
3094 bfd_boolean
3095 _bfd_elf_symbol_refs_local_p (struct elf_link_hash_entry *h,
3096                               struct bfd_link_info *info,
3097                               bfd_boolean local_protected)
3098 {
3099   const struct elf_backend_data *bed;
3100   struct elf_link_hash_table *hash_table;
3101
3102   /* If it's a local sym, of course we resolve locally.  */
3103   if (h == NULL)
3104     return TRUE;
3105
3106   /* STV_HIDDEN or STV_INTERNAL ones must be local.  */
3107   if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
3108       || ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
3109     return TRUE;
3110
3111   /* Forced local symbols resolve locally.  */
3112   if (h->forced_local)
3113     return TRUE;
3114
3115   /* Common symbols that become definitions don't get the DEF_REGULAR
3116      flag set, so test it first, and don't bail out.  */
3117   if (ELF_COMMON_DEF_P (h))
3118     /* Do nothing.  */;
3119   /* If we don't have a definition in a regular file, then we can't
3120      resolve locally.  The sym is either undefined or dynamic.  */
3121   else if (!h->def_regular)
3122     return FALSE;
3123
3124   /* Non-dynamic symbols resolve locally.  */
3125   if (h->dynindx == -1)
3126     return TRUE;
3127
3128   /* At this point, we know the symbol is defined and dynamic.  In an
3129      executable it must resolve locally, likewise when building symbolic
3130      shared libraries.  */
3131   if (bfd_link_executable (info) || SYMBOLIC_BIND (info, h))
3132     return TRUE;
3133
3134   /* Now deal with defined dynamic symbols in shared libraries.  Ones
3135      with default visibility might not resolve locally.  */
3136   if (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT)
3137     return FALSE;
3138
3139   hash_table = elf_hash_table (info);
3140   if (!is_elf_hash_table (hash_table))
3141     return TRUE;
3142
3143   bed = get_elf_backend_data (hash_table->dynobj);
3144
3145   /* If extern_protected_data is false, STV_PROTECTED non-function
3146      symbols are local.  */
3147   if ((!info->extern_protected_data
3148        || (info->extern_protected_data < 0
3149            && !bed->extern_protected_data))
3150       && !bed->is_function_type (h->type))
3151     return TRUE;
3152
3153   /* Function pointer equality tests may require that STV_PROTECTED
3154      symbols be treated as dynamic symbols.  If the address of a
3155      function not defined in an executable is set to that function's
3156      plt entry in the executable, then the address of the function in
3157      a shared library must also be the plt entry in the executable.  */
3158   return local_protected;
3159 }
3160
3161 /* Caches some TLS segment info, and ensures that the TLS segment vma is
3162    aligned.  Returns the first TLS output section.  */
3163
3164 struct bfd_section *
3165 _bfd_elf_tls_setup (bfd *obfd, struct bfd_link_info *info)
3166 {
3167   struct bfd_section *sec, *tls;
3168   unsigned int align = 0;
3169
3170   for (sec = obfd->sections; sec != NULL; sec = sec->next)
3171     if ((sec->flags & SEC_THREAD_LOCAL) != 0)
3172       break;
3173   tls = sec;
3174
3175   for (; sec != NULL && (sec->flags & SEC_THREAD_LOCAL) != 0; sec = sec->next)
3176     if (sec->alignment_power > align)
3177       align = sec->alignment_power;
3178
3179   elf_hash_table (info)->tls_sec = tls;
3180
3181   /* Ensure the alignment of the first section is the largest alignment,
3182      so that the tls segment starts aligned.  */
3183   if (tls != NULL)
3184     tls->alignment_power = align;
3185
3186   return tls;
3187 }
3188
3189 /* Return TRUE iff this is a non-common, definition of a non-function symbol.  */
3190 static bfd_boolean
3191 is_global_data_symbol_definition (bfd *abfd ATTRIBUTE_UNUSED,
3192                                   Elf_Internal_Sym *sym)
3193 {
3194   const struct elf_backend_data *bed;
3195
3196   /* Local symbols do not count, but target specific ones might.  */
3197   if (ELF_ST_BIND (sym->st_info) != STB_GLOBAL
3198       && ELF_ST_BIND (sym->st_info) < STB_LOOS)
3199     return FALSE;
3200
3201   bed = get_elf_backend_data (abfd);
3202   /* Function symbols do not count.  */
3203   if (bed->is_function_type (ELF_ST_TYPE (sym->st_info)))
3204     return FALSE;
3205
3206   /* If the section is undefined, then so is the symbol.  */
3207   if (sym->st_shndx == SHN_UNDEF)
3208     return FALSE;
3209
3210   /* If the symbol is defined in the common section, then
3211      it is a common definition and so does not count.  */
3212   if (bed->common_definition (sym))
3213     return FALSE;
3214
3215   /* If the symbol is in a target specific section then we
3216      must rely upon the backend to tell us what it is.  */
3217   if (sym->st_shndx >= SHN_LORESERVE && sym->st_shndx < SHN_ABS)
3218     /* FIXME - this function is not coded yet:
3219
3220        return _bfd_is_global_symbol_definition (abfd, sym);
3221
3222        Instead for now assume that the definition is not global,
3223        Even if this is wrong, at least the linker will behave
3224        in the same way that it used to do.  */
3225     return FALSE;
3226
3227   return TRUE;
3228 }
3229
3230 /* Search the symbol table of the archive element of the archive ABFD
3231    whose archive map contains a mention of SYMDEF, and determine if
3232    the symbol is defined in this element.  */
3233 static bfd_boolean
3234 elf_link_is_defined_archive_symbol (bfd * abfd, carsym * symdef)
3235 {
3236   Elf_Internal_Shdr * hdr;
3237   size_t symcount;
3238   size_t extsymcount;
3239   size_t extsymoff;
3240   Elf_Internal_Sym *isymbuf;
3241   Elf_Internal_Sym *isym;
3242   Elf_Internal_Sym *isymend;
3243   bfd_boolean result;
3244
3245   abfd = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
3246   if (abfd == NULL)
3247     return FALSE;
3248
3249   if (! bfd_check_format (abfd, bfd_object))
3250     return FALSE;
3251
3252   /* Select the appropriate symbol table.  If we don't know if the
3253      object file is an IR object, give linker LTO plugin a chance to
3254      get the correct symbol table.  */
3255   if (abfd->plugin_format == bfd_plugin_yes
3256 #if BFD_SUPPORTS_PLUGINS
3257       || (abfd->plugin_format == bfd_plugin_unknown
3258           && bfd_link_plugin_object_p (abfd))
3259 #endif
3260       )
3261     {
3262       /* Use the IR symbol table if the object has been claimed by
3263          plugin.  */
3264       abfd = abfd->plugin_dummy_bfd;
3265       hdr = &elf_tdata (abfd)->symtab_hdr;
3266     }
3267   else if ((abfd->flags & DYNAMIC) == 0 || elf_dynsymtab (abfd) == 0)
3268     hdr = &elf_tdata (abfd)->symtab_hdr;
3269   else
3270     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
3271
3272   symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
3273
3274   /* The sh_info field of the symtab header tells us where the
3275      external symbols start.  We don't care about the local symbols.  */
3276   if (elf_bad_symtab (abfd))
3277     {
3278       extsymcount = symcount;
3279       extsymoff = 0;
3280     }
3281   else
3282     {
3283       extsymcount = symcount - hdr->sh_info;
3284       extsymoff = hdr->sh_info;
3285     }
3286
3287   if (extsymcount == 0)
3288     return FALSE;
3289
3290   /* Read in the symbol table.  */
3291   isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
3292                                   NULL, NULL, NULL);
3293   if (isymbuf == NULL)
3294     return FALSE;
3295
3296   /* Scan the symbol table looking for SYMDEF.  */
3297   result = FALSE;
3298   for (isym = isymbuf, isymend = isymbuf + extsymcount; isym < isymend; isym++)
3299     {
3300       const char *name;
3301
3302       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
3303                                               isym->st_name);
3304       if (name == NULL)
3305         break;
3306
3307       if (strcmp (name, symdef->name) == 0)
3308         {
3309           result = is_global_data_symbol_definition (abfd, isym);
3310           break;
3311         }
3312     }
3313
3314   free (isymbuf);
3315
3316   return result;
3317 }
3318 \f
3319 /* Add an entry to the .dynamic table.  */
3320
3321 bfd_boolean
3322 _bfd_elf_add_dynamic_entry (struct bfd_link_info *info,
3323                             bfd_vma tag,
3324                             bfd_vma val)
3325 {
3326   struct elf_link_hash_table *hash_table;
3327   const struct elf_backend_data *bed;
3328   asection *s;
3329   bfd_size_type newsize;
3330   bfd_byte *newcontents;
3331   Elf_Internal_Dyn dyn;
3332
3333   hash_table = elf_hash_table (info);
3334   if (! is_elf_hash_table (hash_table))
3335     return FALSE;
3336
3337   bed = get_elf_backend_data (hash_table->dynobj);
3338   s = bfd_get_linker_section (hash_table->dynobj, ".dynamic");
3339   BFD_ASSERT (s != NULL);
3340
3341   newsize = s->size + bed->s->sizeof_dyn;
3342   newcontents = (bfd_byte *) bfd_realloc (s->contents, newsize);
3343   if (newcontents == NULL)
3344     return FALSE;
3345
3346   dyn.d_tag = tag;
3347   dyn.d_un.d_val = val;
3348   bed->s->swap_dyn_out (hash_table->dynobj, &dyn, newcontents + s->size);
3349
3350   s->size = newsize;
3351   s->contents = newcontents;
3352
3353   return TRUE;
3354 }
3355
3356 /* Add a DT_NEEDED entry for this dynamic object if DO_IT is true,
3357    otherwise just check whether one already exists.  Returns -1 on error,
3358    1 if a DT_NEEDED tag already exists, and 0 on success.  */
3359
3360 static int
3361 elf_add_dt_needed_tag (bfd *abfd,
3362                        struct bfd_link_info *info,
3363                        const char *soname,
3364                        bfd_boolean do_it)
3365 {
3366   struct elf_link_hash_table *hash_table;
3367   size_t strindex;
3368
3369   if (!_bfd_elf_link_create_dynstrtab (abfd, info))
3370     return -1;
3371
3372   hash_table = elf_hash_table (info);
3373   strindex = _bfd_elf_strtab_add (hash_table->dynstr, soname, FALSE);
3374   if (strindex == (size_t) -1)
3375     return -1;
3376
3377   if (_bfd_elf_strtab_refcount (hash_table->dynstr, strindex) != 1)
3378     {
3379       asection *sdyn;
3380       const struct elf_backend_data *bed;
3381       bfd_byte *extdyn;
3382
3383       bed = get_elf_backend_data (hash_table->dynobj);
3384       sdyn = bfd_get_linker_section (hash_table->dynobj, ".dynamic");
3385       if (sdyn != NULL)
3386         for (extdyn = sdyn->contents;
3387              extdyn < sdyn->contents + sdyn->size;
3388              extdyn += bed->s->sizeof_dyn)
3389           {
3390             Elf_Internal_Dyn dyn;
3391
3392             bed->s->swap_dyn_in (hash_table->dynobj, extdyn, &dyn);
3393             if (dyn.d_tag == DT_NEEDED
3394                 && dyn.d_un.d_val == strindex)
3395               {
3396                 _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3397                 return 1;
3398               }
3399           }
3400     }
3401
3402   if (do_it)
3403     {
3404       if (!_bfd_elf_link_create_dynamic_sections (hash_table->dynobj, info))
3405         return -1;
3406
3407       if (!_bfd_elf_add_dynamic_entry (info, DT_NEEDED, strindex))
3408         return -1;
3409     }
3410   else
3411     /* We were just checking for existence of the tag.  */
3412     _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3413
3414   return 0;
3415 }
3416
3417 /* Return true if SONAME is on the needed list between NEEDED and STOP
3418    (or the end of list if STOP is NULL), and needed by a library that
3419    will be loaded.  */
3420
3421 static bfd_boolean
3422 on_needed_list (const char *soname,
3423                 struct bfd_link_needed_list *needed,
3424                 struct bfd_link_needed_list *stop)
3425 {
3426   struct bfd_link_needed_list *look;
3427   for (look = needed; look != stop; look = look->next)
3428     if (strcmp (soname, look->name) == 0
3429         && ((elf_dyn_lib_class (look->by) & DYN_AS_NEEDED) == 0
3430             /* If needed by a library that itself is not directly
3431                needed, recursively check whether that library is
3432                indirectly needed.  Since we add DT_NEEDED entries to
3433                the end of the list, library dependencies appear after
3434                the library.  Therefore search prior to the current
3435                LOOK, preventing possible infinite recursion.  */
3436             || on_needed_list (elf_dt_name (look->by), needed, look)))
3437       return TRUE;
3438
3439   return FALSE;
3440 }
3441
3442 /* Sort symbol by value, section, and size.  */
3443 static int
3444 elf_sort_symbol (const void *arg1, const void *arg2)
3445 {
3446   const struct elf_link_hash_entry *h1;
3447   const struct elf_link_hash_entry *h2;
3448   bfd_signed_vma vdiff;
3449
3450   h1 = *(const struct elf_link_hash_entry **) arg1;
3451   h2 = *(const struct elf_link_hash_entry **) arg2;
3452   vdiff = h1->root.u.def.value - h2->root.u.def.value;
3453   if (vdiff != 0)
3454     return vdiff > 0 ? 1 : -1;
3455   else
3456     {
3457       int sdiff = h1->root.u.def.section->id - h2->root.u.def.section->id;
3458       if (sdiff != 0)
3459         return sdiff > 0 ? 1 : -1;
3460     }
3461   vdiff = h1->size - h2->size;
3462   return vdiff == 0 ? 0 : vdiff > 0 ? 1 : -1;
3463 }
3464
3465 /* This function is used to adjust offsets into .dynstr for
3466    dynamic symbols.  This is called via elf_link_hash_traverse.  */
3467
3468 static bfd_boolean
3469 elf_adjust_dynstr_offsets (struct elf_link_hash_entry *h, void *data)
3470 {
3471   struct elf_strtab_hash *dynstr = (struct elf_strtab_hash *) data;
3472
3473   if (h->dynindx != -1)
3474     h->dynstr_index = _bfd_elf_strtab_offset (dynstr, h->dynstr_index);
3475   return TRUE;
3476 }
3477
3478 /* Assign string offsets in .dynstr, update all structures referencing
3479    them.  */
3480
3481 static bfd_boolean
3482 elf_finalize_dynstr (bfd *output_bfd, struct bfd_link_info *info)
3483 {
3484   struct elf_link_hash_table *hash_table = elf_hash_table (info);
3485   struct elf_link_local_dynamic_entry *entry;
3486   struct elf_strtab_hash *dynstr = hash_table->dynstr;
3487   bfd *dynobj = hash_table->dynobj;
3488   asection *sdyn;
3489   bfd_size_type size;
3490   const struct elf_backend_data *bed;
3491   bfd_byte *extdyn;
3492
3493   _bfd_elf_strtab_finalize (dynstr);
3494   size = _bfd_elf_strtab_size (dynstr);
3495
3496   bed = get_elf_backend_data (dynobj);
3497   sdyn = bfd_get_linker_section (dynobj, ".dynamic");
3498   BFD_ASSERT (sdyn != NULL);
3499
3500   /* Update all .dynamic entries referencing .dynstr strings.  */
3501   for (extdyn = sdyn->contents;
3502        extdyn < sdyn->contents + sdyn->size;
3503        extdyn += bed->s->sizeof_dyn)
3504     {
3505       Elf_Internal_Dyn dyn;
3506
3507       bed->s->swap_dyn_in (dynobj, extdyn, &dyn);
3508       switch (dyn.d_tag)
3509         {
3510         case DT_STRSZ:
3511           dyn.d_un.d_val = size;
3512           break;
3513         case DT_NEEDED:
3514         case DT_SONAME:
3515         case DT_RPATH:
3516         case DT_RUNPATH:
3517         case DT_FILTER:
3518         case DT_AUXILIARY:
3519         case DT_AUDIT:
3520         case DT_DEPAUDIT:
3521           dyn.d_un.d_val = _bfd_elf_strtab_offset (dynstr, dyn.d_un.d_val);
3522           break;
3523         default:
3524           continue;
3525         }
3526       bed->s->swap_dyn_out (dynobj, &dyn, extdyn);
3527     }
3528
3529   /* Now update local dynamic symbols.  */
3530   for (entry = hash_table->dynlocal; entry ; entry = entry->next)
3531     entry->isym.st_name = _bfd_elf_strtab_offset (dynstr,
3532                                                   entry->isym.st_name);
3533
3534   /* And the rest of dynamic symbols.  */
3535   elf_link_hash_traverse (hash_table, elf_adjust_dynstr_offsets, dynstr);
3536
3537   /* Adjust version definitions.  */
3538   if (elf_tdata (output_bfd)->cverdefs)
3539     {
3540       asection *s;
3541       bfd_byte *p;
3542       size_t i;
3543       Elf_Internal_Verdef def;
3544       Elf_Internal_Verdaux defaux;
3545
3546       s = bfd_get_linker_section (dynobj, ".gnu.version_d");
3547       p = s->contents;
3548       do
3549         {
3550           _bfd_elf_swap_verdef_in (output_bfd, (Elf_External_Verdef *) p,
3551                                    &def);
3552           p += sizeof (Elf_External_Verdef);
3553           if (def.vd_aux != sizeof (Elf_External_Verdef))
3554             continue;
3555           for (i = 0; i < def.vd_cnt; ++i)
3556             {
3557               _bfd_elf_swap_verdaux_in (output_bfd,
3558                                         (Elf_External_Verdaux *) p, &defaux);
3559               defaux.vda_name = _bfd_elf_strtab_offset (dynstr,
3560                                                         defaux.vda_name);
3561               _bfd_elf_swap_verdaux_out (output_bfd,
3562                                          &defaux, (Elf_External_Verdaux *) p);
3563               p += sizeof (Elf_External_Verdaux);
3564             }
3565         }
3566       while (def.vd_next);
3567     }
3568
3569   /* Adjust version references.  */
3570   if (elf_tdata (output_bfd)->verref)
3571     {
3572       asection *s;
3573       bfd_byte *p;
3574       size_t i;
3575       Elf_Internal_Verneed need;
3576       Elf_Internal_Vernaux needaux;
3577
3578       s = bfd_get_linker_section (dynobj, ".gnu.version_r");
3579       p = s->contents;
3580       do
3581         {
3582           _bfd_elf_swap_verneed_in (output_bfd, (Elf_External_Verneed *) p,
3583                                     &need);
3584           need.vn_file = _bfd_elf_strtab_offset (dynstr, need.vn_file);
3585           _bfd_elf_swap_verneed_out (output_bfd, &need,
3586                                      (Elf_External_Verneed *) p);
3587           p += sizeof (Elf_External_Verneed);
3588           for (i = 0; i < need.vn_cnt; ++i)
3589             {
3590               _bfd_elf_swap_vernaux_in (output_bfd,
3591                                         (Elf_External_Vernaux *) p, &needaux);
3592               needaux.vna_name = _bfd_elf_strtab_offset (dynstr,
3593                                                          needaux.vna_name);
3594               _bfd_elf_swap_vernaux_out (output_bfd,
3595                                          &needaux,
3596                                          (Elf_External_Vernaux *) p);
3597               p += sizeof (Elf_External_Vernaux);
3598             }
3599         }
3600       while (need.vn_next);
3601     }
3602
3603   return TRUE;
3604 }
3605 \f
3606 /* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3607    The default is to only match when the INPUT and OUTPUT are exactly
3608    the same target.  */
3609
3610 bfd_boolean
3611 _bfd_elf_default_relocs_compatible (const bfd_target *input,
3612                                     const bfd_target *output)
3613 {
3614   return input == output;
3615 }
3616
3617 /* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3618    This version is used when different targets for the same architecture
3619    are virtually identical.  */
3620
3621 bfd_boolean
3622 _bfd_elf_relocs_compatible (const bfd_target *input,
3623                             const bfd_target *output)
3624 {
3625   const struct elf_backend_data *obed, *ibed;
3626
3627   if (input == output)
3628     return TRUE;
3629
3630   ibed = xvec_get_elf_backend_data (input);
3631   obed = xvec_get_elf_backend_data (output);
3632
3633   if (ibed->arch != obed->arch)
3634     return FALSE;
3635
3636   /* If both backends are using this function, deem them compatible.  */
3637   return ibed->relocs_compatible == obed->relocs_compatible;
3638 }
3639
3640 /* Make a special call to the linker "notice" function to tell it that
3641    we are about to handle an as-needed lib, or have finished
3642    processing the lib.  */
3643
3644 bfd_boolean
3645 _bfd_elf_notice_as_needed (bfd *ibfd,
3646                            struct bfd_link_info *info,
3647                            enum notice_asneeded_action act)
3648 {
3649   return (*info->callbacks->notice) (info, NULL, NULL, ibfd, NULL, act, 0);
3650 }
3651
3652 /* Check relocations an ELF object file.  */
3653
3654 bfd_boolean
3655 _bfd_elf_link_check_relocs (bfd *abfd, struct bfd_link_info *info)
3656 {
3657   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
3658   struct elf_link_hash_table *htab = elf_hash_table (info);
3659
3660   /* If this object is the same format as the output object, and it is
3661      not a shared library, then let the backend look through the
3662      relocs.
3663
3664      This is required to build global offset table entries and to
3665      arrange for dynamic relocs.  It is not required for the
3666      particular common case of linking non PIC code, even when linking
3667      against shared libraries, but unfortunately there is no way of
3668      knowing whether an object file has been compiled PIC or not.
3669      Looking through the relocs is not particularly time consuming.
3670      The problem is that we must either (1) keep the relocs in memory,
3671      which causes the linker to require additional runtime memory or
3672      (2) read the relocs twice from the input file, which wastes time.
3673      This would be a good case for using mmap.
3674
3675      I have no idea how to handle linking PIC code into a file of a
3676      different format.  It probably can't be done.  */
3677   if ((abfd->flags & DYNAMIC) == 0
3678       && is_elf_hash_table (htab)
3679       && bed->check_relocs != NULL
3680       && elf_object_id (abfd) == elf_hash_table_id (htab)
3681       && (*bed->relocs_compatible) (abfd->xvec, info->output_bfd->xvec))
3682     {
3683       asection *o;
3684
3685       for (o = abfd->sections; o != NULL; o = o->next)
3686         {
3687           Elf_Internal_Rela *internal_relocs;
3688           bfd_boolean ok;
3689
3690           /* Don't check relocations in excluded sections.  */
3691           if ((o->flags & SEC_RELOC) == 0
3692               || (o->flags & SEC_EXCLUDE) != 0
3693               || o->reloc_count == 0
3694               || ((info->strip == strip_all || info->strip == strip_debugger)
3695                   && (o->flags & SEC_DEBUGGING) != 0)
3696               || bfd_is_abs_section (o->output_section))
3697             continue;
3698
3699           internal_relocs = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
3700                                                        info->keep_memory);
3701           if (internal_relocs == NULL)
3702             return FALSE;
3703
3704           ok = (*bed->check_relocs) (abfd, info, o, internal_relocs);
3705
3706           if (elf_section_data (o)->relocs != internal_relocs)
3707             free (internal_relocs);
3708
3709           if (! ok)
3710             return FALSE;
3711         }
3712     }
3713
3714   return TRUE;
3715 }
3716
3717 /* Add symbols from an ELF object file to the linker hash table.  */
3718
3719 static bfd_boolean
3720 elf_link_add_object_symbols (bfd *abfd, struct bfd_link_info *info)
3721 {
3722   Elf_Internal_Ehdr *ehdr;
3723   Elf_Internal_Shdr *hdr;
3724   size_t symcount;
3725   size_t extsymcount;
3726   size_t extsymoff;
3727   struct elf_link_hash_entry **sym_hash;
3728   bfd_boolean dynamic;
3729   Elf_External_Versym *extversym = NULL;
3730   Elf_External_Versym *ever;
3731   struct elf_link_hash_entry *weaks;
3732   struct elf_link_hash_entry **nondeflt_vers = NULL;
3733   size_t nondeflt_vers_cnt = 0;
3734   Elf_Internal_Sym *isymbuf = NULL;
3735   Elf_Internal_Sym *isym;
3736   Elf_Internal_Sym *isymend;
3737   const struct elf_backend_data *bed;
3738   bfd_boolean add_needed;
3739   struct elf_link_hash_table *htab;
3740   bfd_size_type amt;
3741   void *alloc_mark = NULL;
3742   struct bfd_hash_entry **old_table = NULL;
3743   unsigned int old_size = 0;
3744   unsigned int old_count = 0;
3745   void *old_tab = NULL;
3746   void *old_ent;
3747   struct bfd_link_hash_entry *old_undefs = NULL;
3748   struct bfd_link_hash_entry *old_undefs_tail = NULL;
3749   void *old_strtab = NULL;
3750   size_t tabsize = 0;
3751   asection *s;
3752   bfd_boolean just_syms;
3753
3754   htab = elf_hash_table (info);
3755   bed = get_elf_backend_data (abfd);
3756
3757   if ((abfd->flags & DYNAMIC) == 0)
3758     dynamic = FALSE;
3759   else
3760     {
3761       dynamic = TRUE;
3762
3763       /* You can't use -r against a dynamic object.  Also, there's no
3764          hope of using a dynamic object which does not exactly match
3765          the format of the output file.  */
3766       if (bfd_link_relocatable (info)
3767           || !is_elf_hash_table (htab)
3768           || info->output_bfd->xvec != abfd->xvec)
3769         {
3770           if (bfd_link_relocatable (info))
3771             bfd_set_error (bfd_error_invalid_operation);
3772           else
3773             bfd_set_error (bfd_error_wrong_format);
3774           goto error_return;
3775         }
3776     }
3777
3778   ehdr = elf_elfheader (abfd);
3779   if (info->warn_alternate_em
3780       && bed->elf_machine_code != ehdr->e_machine
3781       && ((bed->elf_machine_alt1 != 0
3782            && ehdr->e_machine == bed->elf_machine_alt1)
3783           || (bed->elf_machine_alt2 != 0
3784               && ehdr->e_machine == bed->elf_machine_alt2)))
3785     info->callbacks->einfo
3786       /* xgettext:c-format */
3787       (_("%P: alternate ELF machine code found (%d) in %B, expecting %d\n"),
3788        ehdr->e_machine, abfd, bed->elf_machine_code);
3789
3790   /* As a GNU extension, any input sections which are named
3791      .gnu.warning.SYMBOL are treated as warning symbols for the given
3792      symbol.  This differs from .gnu.warning sections, which generate
3793      warnings when they are included in an output file.  */
3794   /* PR 12761: Also generate this warning when building shared libraries.  */
3795   for (s = abfd->sections; s != NULL; s = s->next)
3796     {
3797       const char *name;
3798
3799       name = bfd_get_section_name (abfd, s);
3800       if (CONST_STRNEQ (name, ".gnu.warning."))
3801         {
3802           char *msg;
3803           bfd_size_type sz;
3804
3805           name += sizeof ".gnu.warning." - 1;
3806
3807           /* If this is a shared object, then look up the symbol
3808              in the hash table.  If it is there, and it is already
3809              been defined, then we will not be using the entry
3810              from this shared object, so we don't need to warn.
3811              FIXME: If we see the definition in a regular object
3812              later on, we will warn, but we shouldn't.  The only
3813              fix is to keep track of what warnings we are supposed
3814              to emit, and then handle them all at the end of the
3815              link.  */
3816           if (dynamic)
3817             {
3818               struct elf_link_hash_entry *h;
3819
3820               h = elf_link_hash_lookup (htab, name, FALSE, FALSE, TRUE);
3821
3822               /* FIXME: What about bfd_link_hash_common?  */
3823               if (h != NULL
3824                   && (h->root.type == bfd_link_hash_defined
3825                       || h->root.type == bfd_link_hash_defweak))
3826                 continue;
3827             }
3828
3829           sz = s->size;
3830           msg = (char *) bfd_alloc (abfd, sz + 1);
3831           if (msg == NULL)
3832             goto error_return;
3833
3834           if (! bfd_get_section_contents (abfd, s, msg, 0, sz))
3835             goto error_return;
3836
3837           msg[sz] = '\0';
3838
3839           if (! (_bfd_generic_link_add_one_symbol
3840                  (info, abfd, name, BSF_WARNING, s, 0, msg,
3841                   FALSE, bed->collect, NULL)))
3842             goto error_return;
3843
3844           if (bfd_link_executable (info))
3845             {
3846               /* Clobber the section size so that the warning does
3847                  not get copied into the output file.  */
3848               s->size = 0;
3849
3850               /* Also set SEC_EXCLUDE, so that symbols defined in
3851                  the warning section don't get copied to the output.  */
3852               s->flags |= SEC_EXCLUDE;
3853             }
3854         }
3855     }
3856
3857   just_syms = ((s = abfd->sections) != NULL
3858                && s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS);
3859
3860   add_needed = TRUE;
3861   if (! dynamic)
3862     {
3863       /* If we are creating a shared library, create all the dynamic
3864          sections immediately.  We need to attach them to something,
3865          so we attach them to this BFD, provided it is the right
3866          format and is not from ld --just-symbols.  Always create the
3867          dynamic sections for -E/--dynamic-list.  FIXME: If there
3868          are no input BFD's of the same format as the output, we can't
3869          make a shared library.  */
3870       if (!just_syms
3871           && (bfd_link_pic (info)
3872               || (!bfd_link_relocatable (info)
3873                   && info->nointerp
3874                   && (info->export_dynamic || info->dynamic)))
3875           && is_elf_hash_table (htab)
3876           && info->output_bfd->xvec == abfd->xvec
3877           && !htab->dynamic_sections_created)
3878         {
3879           if (! _bfd_elf_link_create_dynamic_sections (abfd, info))
3880             goto error_return;
3881         }
3882     }
3883   else if (!is_elf_hash_table (htab))
3884     goto error_return;
3885   else
3886     {
3887       const char *soname = NULL;
3888       char *audit = NULL;
3889       struct bfd_link_needed_list *rpath = NULL, *runpath = NULL;
3890       const Elf_Internal_Phdr *phdr;
3891       int ret;
3892
3893       /* ld --just-symbols and dynamic objects don't mix very well.
3894          ld shouldn't allow it.  */
3895       if (just_syms)
3896         abort ();
3897
3898       /* If this dynamic lib was specified on the command line with
3899          --as-needed in effect, then we don't want to add a DT_NEEDED
3900          tag unless the lib is actually used.  Similary for libs brought
3901          in by another lib's DT_NEEDED.  When --no-add-needed is used
3902          on a dynamic lib, we don't want to add a DT_NEEDED entry for
3903          any dynamic library in DT_NEEDED tags in the dynamic lib at
3904          all.  */
3905       add_needed = (elf_dyn_lib_class (abfd)
3906                     & (DYN_AS_NEEDED | DYN_DT_NEEDED
3907                        | DYN_NO_NEEDED)) == 0;
3908
3909       s = bfd_get_section_by_name (abfd, ".dynamic");
3910       if (s != NULL)
3911         {
3912           bfd_byte *dynbuf;
3913           bfd_byte *extdyn;
3914           unsigned int elfsec;
3915           unsigned long shlink;
3916
3917           if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
3918             {
3919 error_free_dyn:
3920               free (dynbuf);
3921               goto error_return;
3922             }
3923
3924           elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
3925           if (elfsec == SHN_BAD)
3926             goto error_free_dyn;
3927           shlink = elf_elfsections (abfd)[elfsec]->sh_link;
3928
3929           for (extdyn = dynbuf;
3930                extdyn < dynbuf + s->size;
3931                extdyn += bed->s->sizeof_dyn)
3932             {
3933               Elf_Internal_Dyn dyn;
3934
3935               bed->s->swap_dyn_in (abfd, extdyn, &dyn);
3936               if (dyn.d_tag == DT_SONAME)
3937                 {
3938                   unsigned int tagv = dyn.d_un.d_val;
3939                   soname = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3940                   if (soname == NULL)
3941                     goto error_free_dyn;
3942                 }
3943               if (dyn.d_tag == DT_NEEDED)
3944                 {
3945                   struct bfd_link_needed_list *n, **pn;
3946                   char *fnm, *anm;
3947                   unsigned int tagv = dyn.d_un.d_val;
3948
3949                   amt = sizeof (struct bfd_link_needed_list);
3950                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3951                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3952                   if (n == NULL || fnm == NULL)
3953                     goto error_free_dyn;
3954                   amt = strlen (fnm) + 1;
3955                   anm = (char *) bfd_alloc (abfd, amt);
3956                   if (anm == NULL)
3957                     goto error_free_dyn;
3958                   memcpy (anm, fnm, amt);
3959                   n->name = anm;
3960                   n->by = abfd;
3961                   n->next = NULL;
3962                   for (pn = &htab->needed; *pn != NULL; pn = &(*pn)->next)
3963                     ;
3964                   *pn = n;
3965                 }
3966               if (dyn.d_tag == DT_RUNPATH)
3967                 {
3968                   struct bfd_link_needed_list *n, **pn;
3969                   char *fnm, *anm;
3970                   unsigned int tagv = dyn.d_un.d_val;
3971
3972                   amt = sizeof (struct bfd_link_needed_list);
3973                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3974                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3975                   if (n == NULL || fnm == NULL)
3976                     goto error_free_dyn;
3977                   amt = strlen (fnm) + 1;
3978                   anm = (char *) bfd_alloc (abfd, amt);
3979                   if (anm == NULL)
3980                     goto error_free_dyn;
3981                   memcpy (anm, fnm, amt);
3982                   n->name = anm;
3983                   n->by = abfd;
3984                   n->next = NULL;
3985                   for (pn = & runpath;
3986                        *pn != NULL;
3987                        pn = &(*pn)->next)
3988                     ;
3989                   *pn = n;
3990                 }
3991               /* Ignore DT_RPATH if we have seen DT_RUNPATH.  */
3992               if (!runpath && dyn.d_tag == DT_RPATH)
3993                 {
3994                   struct bfd_link_needed_list *n, **pn;
3995                   char *fnm, *anm;
3996                   unsigned int tagv = dyn.d_un.d_val;
3997
3998                   amt = sizeof (struct bfd_link_needed_list);
3999                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
4000                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
4001                   if (n == NULL || fnm == NULL)
4002                     goto error_free_dyn;
4003                   amt = strlen (fnm) + 1;
4004                   anm = (char *) bfd_alloc (abfd, amt);
4005                   if (anm == NULL)
4006                     goto error_free_dyn;
4007                   memcpy (anm, fnm, amt);
4008                   n->name = anm;
4009                   n->by = abfd;
4010                   n->next = NULL;
4011                   for (pn = & rpath;
4012                        *pn != NULL;
4013                        pn = &(*pn)->next)
4014                     ;
4015                   *pn = n;
4016                 }
4017               if (dyn.d_tag == DT_AUDIT)
4018                 {
4019                   unsigned int tagv = dyn.d_un.d_val;
4020                   audit = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
4021                 }
4022             }
4023
4024           free (dynbuf);
4025         }
4026
4027       /* DT_RUNPATH overrides DT_RPATH.  Do _NOT_ bfd_release, as that
4028          frees all more recently bfd_alloc'd blocks as well.  */
4029       if (runpath)
4030         rpath = runpath;
4031
4032       if (rpath)
4033         {
4034           struct bfd_link_needed_list **pn;
4035           for (pn = &htab->runpath; *pn != NULL; pn = &(*pn)->next)
4036             ;
4037           *pn = rpath;
4038         }
4039
4040       /* If we have a PT_GNU_RELRO program header, mark as read-only
4041          all sections contained fully therein.  This makes relro
4042          shared library sections appear as they will at run-time.  */
4043       phdr = elf_tdata (abfd)->phdr + elf_elfheader (abfd)->e_phnum;
4044       while (--phdr >= elf_tdata (abfd)->phdr)
4045         if (phdr->p_type == PT_GNU_RELRO)
4046           {
4047             for (s = abfd->sections; s != NULL; s = s->next)
4048               if ((s->flags & SEC_ALLOC) != 0
4049                   && s->vma >= phdr->p_vaddr
4050                   && s->vma + s->size <= phdr->p_vaddr + phdr->p_memsz)
4051                 s->flags |= SEC_READONLY;
4052             break;
4053           }
4054
4055       /* We do not want to include any of the sections in a dynamic
4056          object in the output file.  We hack by simply clobbering the
4057          list of sections in the BFD.  This could be handled more
4058          cleanly by, say, a new section flag; the existing
4059          SEC_NEVER_LOAD flag is not the one we want, because that one
4060          still implies that the section takes up space in the output
4061          file.  */
4062       bfd_section_list_clear (abfd);
4063
4064       /* Find the name to use in a DT_NEEDED entry that refers to this
4065          object.  If the object has a DT_SONAME entry, we use it.
4066          Otherwise, if the generic linker stuck something in
4067          elf_dt_name, we use that.  Otherwise, we just use the file
4068          name.  */
4069       if (soname == NULL || *soname == '\0')
4070         {
4071           soname = elf_dt_name (abfd);
4072           if (soname == NULL || *soname == '\0')
4073             soname = bfd_get_filename (abfd);
4074         }
4075
4076       /* Save the SONAME because sometimes the linker emulation code
4077          will need to know it.  */
4078       elf_dt_name (abfd) = soname;
4079
4080       ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
4081       if (ret < 0)
4082         goto error_return;
4083
4084       /* If we have already included this dynamic object in the
4085          link, just ignore it.  There is no reason to include a
4086          particular dynamic object more than once.  */
4087       if (ret > 0)
4088         return TRUE;
4089
4090       /* Save the DT_AUDIT entry for the linker emulation code. */
4091       elf_dt_audit (abfd) = audit;
4092     }
4093
4094   /* If this is a dynamic object, we always link against the .dynsym
4095      symbol table, not the .symtab symbol table.  The dynamic linker
4096      will only see the .dynsym symbol table, so there is no reason to
4097      look at .symtab for a dynamic object.  */
4098
4099   if (! dynamic || elf_dynsymtab (abfd) == 0)
4100     hdr = &elf_tdata (abfd)->symtab_hdr;
4101   else
4102     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
4103
4104   symcount = hdr->sh_size / bed->s->sizeof_sym;
4105
4106   /* The sh_info field of the symtab header tells us where the
4107      external symbols start.  We don't care about the local symbols at
4108      this point.  */
4109   if (elf_bad_symtab (abfd))
4110     {
4111       extsymcount = symcount;
4112       extsymoff = 0;
4113     }
4114   else
4115     {
4116       extsymcount = symcount - hdr->sh_info;
4117       extsymoff = hdr->sh_info;
4118     }
4119
4120   sym_hash = elf_sym_hashes (abfd);
4121   if (extsymcount != 0)
4122     {
4123       isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
4124                                       NULL, NULL, NULL);
4125       if (isymbuf == NULL)
4126         goto error_return;
4127
4128       if (sym_hash == NULL)
4129         {
4130           /* We store a pointer to the hash table entry for each
4131              external symbol.  */
4132           amt = extsymcount;
4133           amt *= sizeof (struct elf_link_hash_entry *);
4134           sym_hash = (struct elf_link_hash_entry **) bfd_zalloc (abfd, amt);
4135           if (sym_hash == NULL)
4136             goto error_free_sym;
4137           elf_sym_hashes (abfd) = sym_hash;
4138         }
4139     }
4140
4141   if (dynamic)
4142     {
4143       /* Read in any version definitions.  */
4144       if (!_bfd_elf_slurp_version_tables (abfd,
4145                                           info->default_imported_symver))
4146         goto error_free_sym;
4147
4148       /* Read in the symbol versions, but don't bother to convert them
4149          to internal format.  */
4150       if (elf_dynversym (abfd) != 0)
4151         {
4152           Elf_Internal_Shdr *versymhdr;
4153
4154           versymhdr = &elf_tdata (abfd)->dynversym_hdr;
4155           extversym = (Elf_External_Versym *) bfd_malloc (versymhdr->sh_size);
4156           if (extversym == NULL)
4157             goto error_free_sym;
4158           amt = versymhdr->sh_size;
4159           if (bfd_seek (abfd, versymhdr->sh_offset, SEEK_SET) != 0
4160               || bfd_bread (extversym, amt, abfd) != amt)
4161             goto error_free_vers;
4162         }
4163     }
4164
4165   /* If we are loading an as-needed shared lib, save the symbol table
4166      state before we start adding symbols.  If the lib turns out
4167      to be unneeded, restore the state.  */
4168   if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
4169     {
4170       unsigned int i;
4171       size_t entsize;
4172
4173       for (entsize = 0, i = 0; i < htab->root.table.size; i++)
4174         {
4175           struct bfd_hash_entry *p;
4176           struct elf_link_hash_entry *h;
4177
4178           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4179             {
4180               h = (struct elf_link_hash_entry *) p;
4181               entsize += htab->root.table.entsize;
4182               if (h->root.type == bfd_link_hash_warning)
4183                 entsize += htab->root.table.entsize;
4184             }
4185         }
4186
4187       tabsize = htab->root.table.size * sizeof (struct bfd_hash_entry *);
4188       old_tab = bfd_malloc (tabsize + entsize);
4189       if (old_tab == NULL)
4190         goto error_free_vers;
4191
4192       /* Remember the current objalloc pointer, so that all mem for
4193          symbols added can later be reclaimed.  */
4194       alloc_mark = bfd_hash_allocate (&htab->root.table, 1);
4195       if (alloc_mark == NULL)
4196         goto error_free_vers;
4197
4198       /* Make a special call to the linker "notice" function to
4199          tell it that we are about to handle an as-needed lib.  */
4200       if (!(*bed->notice_as_needed) (abfd, info, notice_as_needed))
4201         goto error_free_vers;
4202
4203       /* Clone the symbol table.  Remember some pointers into the
4204          symbol table, and dynamic symbol count.  */
4205       old_ent = (char *) old_tab + tabsize;
4206       memcpy (old_tab, htab->root.table.table, tabsize);
4207       old_undefs = htab->root.undefs;
4208       old_undefs_tail = htab->root.undefs_tail;
4209       old_table = htab->root.table.table;
4210       old_size = htab->root.table.size;
4211       old_count = htab->root.table.count;
4212       old_strtab = _bfd_elf_strtab_save (htab->dynstr);
4213       if (old_strtab == NULL)
4214         goto error_free_vers;
4215
4216       for (i = 0; i < htab->root.table.size; i++)
4217         {
4218           struct bfd_hash_entry *p;
4219           struct elf_link_hash_entry *h;
4220
4221           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4222             {
4223               memcpy (old_ent, p, htab->root.table.entsize);
4224               old_ent = (char *) old_ent + htab->root.table.entsize;
4225               h = (struct elf_link_hash_entry *) p;
4226               if (h->root.type == bfd_link_hash_warning)
4227                 {
4228                   memcpy (old_ent, h->root.u.i.link, htab->root.table.entsize);
4229                   old_ent = (char *) old_ent + htab->root.table.entsize;
4230                 }
4231             }
4232         }
4233     }
4234
4235   weaks = NULL;
4236   ever = extversym != NULL ? extversym + extsymoff : NULL;
4237   for (isym = isymbuf, isymend = isymbuf + extsymcount;
4238        isym < isymend;
4239        isym++, sym_hash++, ever = (ever != NULL ? ever + 1 : NULL))
4240     {
4241       int bind;
4242       bfd_vma value;
4243       asection *sec, *new_sec;
4244       flagword flags;
4245       const char *name;
4246       struct elf_link_hash_entry *h;
4247       struct elf_link_hash_entry *hi;
4248       bfd_boolean definition;
4249       bfd_boolean size_change_ok;
4250       bfd_boolean type_change_ok;
4251       bfd_boolean new_weakdef;
4252       bfd_boolean new_weak;
4253       bfd_boolean old_weak;
4254       bfd_boolean override;
4255       bfd_boolean common;
4256       bfd_boolean discarded;
4257       unsigned int old_alignment;
4258       bfd *old_bfd;
4259       bfd_boolean matched;
4260
4261       override = FALSE;
4262
4263       flags = BSF_NO_FLAGS;
4264       sec = NULL;
4265       value = isym->st_value;
4266       common = bed->common_definition (isym);
4267       if (common && info->inhibit_common_definition)
4268         {
4269           /* Treat common symbol as undefined for --no-define-common.  */
4270           isym->st_shndx = SHN_UNDEF;
4271           common = FALSE;
4272         }
4273       discarded = FALSE;
4274
4275       bind = ELF_ST_BIND (isym->st_info);
4276       switch (bind)
4277         {
4278         case STB_LOCAL:
4279           /* This should be impossible, since ELF requires that all
4280              global symbols follow all local symbols, and that sh_info
4281              point to the first global symbol.  Unfortunately, Irix 5
4282              screws this up.  */
4283           continue;
4284
4285         case STB_GLOBAL:
4286           if (isym->st_shndx != SHN_UNDEF && !common)
4287             flags = BSF_GLOBAL;
4288           break;
4289
4290         case STB_WEAK:
4291           flags = BSF_WEAK;
4292           break;
4293
4294         case STB_GNU_UNIQUE:
4295           flags = BSF_GNU_UNIQUE;
4296           break;
4297
4298         default:
4299           /* Leave it up to the processor backend.  */
4300           break;
4301         }
4302
4303       if (isym->st_shndx == SHN_UNDEF)
4304         sec = bfd_und_section_ptr;
4305       else if (isym->st_shndx == SHN_ABS)
4306         sec = bfd_abs_section_ptr;
4307       else if (isym->st_shndx == SHN_COMMON)
4308         {
4309           sec = bfd_com_section_ptr;
4310           /* What ELF calls the size we call the value.  What ELF
4311              calls the value we call the alignment.  */
4312           value = isym->st_size;
4313         }
4314       else
4315         {
4316           sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
4317           if (sec == NULL)
4318             sec = bfd_abs_section_ptr;
4319           else if (discarded_section (sec))
4320             {
4321               /* Symbols from discarded section are undefined.  We keep
4322                  its visibility.  */
4323               sec = bfd_und_section_ptr;
4324               discarded = TRUE;
4325               isym->st_shndx = SHN_UNDEF;
4326             }
4327           else if ((abfd->flags & (EXEC_P | DYNAMIC)) != 0)
4328             value -= sec->vma;
4329         }
4330
4331       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
4332                                               isym->st_name);
4333       if (name == NULL)
4334         goto error_free_vers;
4335
4336       if (isym->st_shndx == SHN_COMMON
4337           && (abfd->flags & BFD_PLUGIN) != 0)
4338         {
4339           asection *xc = bfd_get_section_by_name (abfd, "COMMON");
4340
4341           if (xc == NULL)
4342             {
4343               flagword sflags = (SEC_ALLOC | SEC_IS_COMMON | SEC_KEEP
4344                                  | SEC_EXCLUDE);
4345               xc = bfd_make_section_with_flags (abfd, "COMMON", sflags);
4346               if (xc == NULL)
4347                 goto error_free_vers;
4348             }
4349           sec = xc;
4350         }
4351       else if (isym->st_shndx == SHN_COMMON
4352                && ELF_ST_TYPE (isym->st_info) == STT_TLS
4353                && !bfd_link_relocatable (info))
4354         {
4355           asection *tcomm = bfd_get_section_by_name (abfd, ".tcommon");
4356
4357           if (tcomm == NULL)
4358             {
4359               flagword sflags = (SEC_ALLOC | SEC_THREAD_LOCAL | SEC_IS_COMMON
4360                                  | SEC_LINKER_CREATED);
4361               tcomm = bfd_make_section_with_flags (abfd, ".tcommon", sflags);
4362               if (tcomm == NULL)
4363                 goto error_free_vers;
4364             }
4365           sec = tcomm;
4366         }
4367       else if (bed->elf_add_symbol_hook)
4368         {
4369           if (! (*bed->elf_add_symbol_hook) (abfd, info, isym, &name, &flags,
4370                                              &sec, &value))
4371             goto error_free_vers;
4372
4373           /* The hook function sets the name to NULL if this symbol
4374              should be skipped for some reason.  */
4375           if (name == NULL)
4376             continue;
4377         }
4378
4379       /* Sanity check that all possibilities were handled.  */
4380       if (sec == NULL)
4381         {
4382           bfd_set_error (bfd_error_bad_value);
4383           goto error_free_vers;
4384         }
4385
4386       /* Silently discard TLS symbols from --just-syms.  There's
4387          no way to combine a static TLS block with a new TLS block
4388          for this executable.  */
4389       if (ELF_ST_TYPE (isym->st_info) == STT_TLS
4390           && sec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
4391         continue;
4392
4393       if (bfd_is_und_section (sec)
4394           || bfd_is_com_section (sec))
4395         definition = FALSE;
4396       else
4397         definition = TRUE;
4398
4399       size_change_ok = FALSE;
4400       type_change_ok = bed->type_change_ok;
4401       old_weak = FALSE;
4402       matched = FALSE;
4403       old_alignment = 0;
4404       old_bfd = NULL;
4405       new_sec = sec;
4406
4407       if (is_elf_hash_table (htab))
4408         {
4409           Elf_Internal_Versym iver;
4410           unsigned int vernum = 0;
4411           bfd_boolean skip;
4412
4413           if (ever == NULL)
4414             {
4415               if (info->default_imported_symver)
4416                 /* Use the default symbol version created earlier.  */
4417                 iver.vs_vers = elf_tdata (abfd)->cverdefs;
4418               else
4419                 iver.vs_vers = 0;
4420             }
4421           else
4422             _bfd_elf_swap_versym_in (abfd, ever, &iver);
4423
4424           vernum = iver.vs_vers & VERSYM_VERSION;
4425
4426           /* If this is a hidden symbol, or if it is not version
4427              1, we append the version name to the symbol name.
4428              However, we do not modify a non-hidden absolute symbol
4429              if it is not a function, because it might be the version
4430              symbol itself.  FIXME: What if it isn't?  */
4431           if ((iver.vs_vers & VERSYM_HIDDEN) != 0
4432               || (vernum > 1
4433                   && (!bfd_is_abs_section (sec)
4434                       || bed->is_function_type (ELF_ST_TYPE (isym->st_info)))))
4435             {
4436               const char *verstr;
4437               size_t namelen, verlen, newlen;
4438               char *newname, *p;
4439
4440               if (isym->st_shndx != SHN_UNDEF)
4441                 {
4442                   if (vernum > elf_tdata (abfd)->cverdefs)
4443                     verstr = NULL;
4444                   else if (vernum > 1)
4445                     verstr =
4446                       elf_tdata (abfd)->verdef[vernum - 1].vd_nodename;
4447                   else
4448                     verstr = "";
4449
4450                   if (verstr == NULL)
4451                     {
4452                       _bfd_error_handler
4453                         /* xgettext:c-format */
4454                         (_("%B: %s: invalid version %u (max %d)"),
4455                          abfd, name, vernum,
4456                          elf_tdata (abfd)->cverdefs);
4457                       bfd_set_error (bfd_error_bad_value);
4458                       goto error_free_vers;
4459                     }
4460                 }
4461               else
4462                 {
4463                   /* We cannot simply test for the number of
4464                      entries in the VERNEED section since the
4465                      numbers for the needed versions do not start
4466                      at 0.  */
4467                   Elf_Internal_Verneed *t;
4468
4469                   verstr = NULL;
4470                   for (t = elf_tdata (abfd)->verref;
4471                        t != NULL;
4472                        t = t->vn_nextref)
4473                     {
4474                       Elf_Internal_Vernaux *a;
4475
4476                       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
4477                         {
4478                           if (a->vna_other == vernum)
4479                             {
4480                               verstr = a->vna_nodename;
4481                               break;
4482                             }
4483                         }
4484                       if (a != NULL)
4485                         break;
4486                     }
4487                   if (verstr == NULL)
4488                     {
4489                       _bfd_error_handler
4490                         /* xgettext:c-format */
4491                         (_("%B: %s: invalid needed version %d"),
4492                          abfd, name, vernum);
4493                       bfd_set_error (bfd_error_bad_value);
4494                       goto error_free_vers;
4495                     }
4496                 }
4497
4498               namelen = strlen (name);
4499               verlen = strlen (verstr);
4500               newlen = namelen + verlen + 2;
4501               if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4502                   && isym->st_shndx != SHN_UNDEF)
4503                 ++newlen;
4504
4505               newname = (char *) bfd_hash_allocate (&htab->root.table, newlen);
4506               if (newname == NULL)
4507                 goto error_free_vers;
4508               memcpy (newname, name, namelen);
4509               p = newname + namelen;
4510               *p++ = ELF_VER_CHR;
4511               /* If this is a defined non-hidden version symbol,
4512                  we add another @ to the name.  This indicates the
4513                  default version of the symbol.  */
4514               if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4515                   && isym->st_shndx != SHN_UNDEF)
4516                 *p++ = ELF_VER_CHR;
4517               memcpy (p, verstr, verlen + 1);
4518
4519               name = newname;
4520             }
4521
4522           /* If this symbol has default visibility and the user has
4523              requested we not re-export it, then mark it as hidden.  */
4524           if (!bfd_is_und_section (sec)
4525               && !dynamic
4526               && abfd->no_export
4527               && ELF_ST_VISIBILITY (isym->st_other) != STV_INTERNAL)
4528             isym->st_other = (STV_HIDDEN
4529                               | (isym->st_other & ~ELF_ST_VISIBILITY (-1)));
4530
4531           if (!_bfd_elf_merge_symbol (abfd, info, name, isym, &sec, &value,
4532                                       sym_hash, &old_bfd, &old_weak,
4533                                       &old_alignment, &skip, &override,
4534                                       &type_change_ok, &size_change_ok,
4535                                       &matched))
4536             goto error_free_vers;
4537
4538           if (skip)
4539             continue;
4540
4541           /* Override a definition only if the new symbol matches the
4542              existing one.  */
4543           if (override && matched)
4544             definition = FALSE;
4545
4546           h = *sym_hash;
4547           while (h->root.type == bfd_link_hash_indirect
4548                  || h->root.type == bfd_link_hash_warning)
4549             h = (struct elf_link_hash_entry *) h->root.u.i.link;
4550
4551           if (elf_tdata (abfd)->verdef != NULL
4552               && vernum > 1
4553               && definition)
4554             h->verinfo.verdef = &elf_tdata (abfd)->verdef[vernum - 1];
4555         }
4556
4557       if (! (_bfd_generic_link_add_one_symbol
4558              (info, abfd, name, flags, sec, value, NULL, FALSE, bed->collect,
4559               (struct bfd_link_hash_entry **) sym_hash)))
4560         goto error_free_vers;
4561
4562       if ((flags & BSF_GNU_UNIQUE)
4563           && (abfd->flags & DYNAMIC) == 0
4564           && bfd_get_flavour (info->output_bfd) == bfd_target_elf_flavour)
4565         elf_tdata (info->output_bfd)->has_gnu_symbols |= elf_gnu_symbol_unique;
4566
4567       h = *sym_hash;
4568       /* We need to make sure that indirect symbol dynamic flags are
4569          updated.  */
4570       hi = h;
4571       while (h->root.type == bfd_link_hash_indirect
4572              || h->root.type == bfd_link_hash_warning)
4573         h = (struct elf_link_hash_entry *) h->root.u.i.link;
4574
4575       /* Setting the index to -3 tells elf_link_output_extsym that
4576          this symbol is defined in a discarded section.  */
4577       if (discarded)
4578         h->indx = -3;
4579
4580       *sym_hash = h;
4581
4582       new_weak = (flags & BSF_WEAK) != 0;
4583       new_weakdef = FALSE;
4584       if (dynamic
4585           && definition
4586           && new_weak
4587           && !bed->is_function_type (ELF_ST_TYPE (isym->st_info))
4588           && is_elf_hash_table (htab)
4589           && h->u.weakdef == NULL)
4590         {
4591           /* Keep a list of all weak defined non function symbols from
4592              a dynamic object, using the weakdef field.  Later in this
4593              function we will set the weakdef field to the correct
4594              value.  We only put non-function symbols from dynamic
4595              objects on this list, because that happens to be the only
4596              time we need to know the normal symbol corresponding to a
4597              weak symbol, and the information is time consuming to
4598              figure out.  If the weakdef field is not already NULL,
4599              then this symbol was already defined by some previous
4600              dynamic object, and we will be using that previous
4601              definition anyhow.  */
4602
4603           h->u.weakdef = weaks;
4604           weaks = h;
4605           new_weakdef = TRUE;
4606         }
4607
4608       /* Set the alignment of a common symbol.  */
4609       if ((common || bfd_is_com_section (sec))
4610           && h->root.type == bfd_link_hash_common)
4611         {
4612           unsigned int align;
4613
4614           if (common)
4615             align = bfd_log2 (isym->st_value);
4616           else
4617             {
4618               /* The new symbol is a common symbol in a shared object.
4619                  We need to get the alignment from the section.  */
4620               align = new_sec->alignment_power;
4621             }
4622           if (align > old_alignment)
4623             h->root.u.c.p->alignment_power = align;
4624           else
4625             h->root.u.c.p->alignment_power = old_alignment;
4626         }
4627
4628       if (is_elf_hash_table (htab))
4629         {
4630           /* Set a flag in the hash table entry indicating the type of
4631              reference or definition we just found.  A dynamic symbol
4632              is one which is referenced or defined by both a regular
4633              object and a shared object.  */
4634           bfd_boolean dynsym = FALSE;
4635
4636           /* Plugin symbols aren't normal.  Don't set def_regular or
4637              ref_regular for them, or make them dynamic.  */
4638           if ((abfd->flags & BFD_PLUGIN) != 0)
4639             ;
4640           else if (! dynamic)
4641             {
4642               if (! definition)
4643                 {
4644                   h->ref_regular = 1;
4645                   if (bind != STB_WEAK)
4646                     h->ref_regular_nonweak = 1;
4647                 }
4648               else
4649                 {
4650                   h->def_regular = 1;
4651                   if (h->def_dynamic)
4652                     {
4653                       h->def_dynamic = 0;
4654                       h->ref_dynamic = 1;
4655                     }
4656                 }
4657
4658               /* If the indirect symbol has been forced local, don't
4659                  make the real symbol dynamic.  */
4660               if ((h == hi || !hi->forced_local)
4661                   && (bfd_link_dll (info)
4662                       || h->def_dynamic
4663                       || h->ref_dynamic))
4664                 dynsym = TRUE;
4665             }
4666           else
4667             {
4668               if (! definition)
4669                 {
4670                   h->ref_dynamic = 1;
4671                   hi->ref_dynamic = 1;
4672                 }
4673               else
4674                 {
4675                   h->def_dynamic = 1;
4676                   hi->def_dynamic = 1;
4677                 }
4678
4679               /* If the indirect symbol has been forced local, don't
4680                  make the real symbol dynamic.  */
4681               if ((h == hi || !hi->forced_local)
4682                   && (h->def_regular
4683                       || h->ref_regular
4684                       || (h->u.weakdef != NULL
4685                           && ! new_weakdef
4686                           && h->u.weakdef->dynindx != -1)))
4687                 dynsym = TRUE;
4688             }
4689
4690           /* Check to see if we need to add an indirect symbol for
4691              the default name.  */
4692           if (definition
4693               || (!override && h->root.type == bfd_link_hash_common))
4694             if (!_bfd_elf_add_default_symbol (abfd, info, h, name, isym,
4695                                               sec, value, &old_bfd, &dynsym))
4696               goto error_free_vers;
4697
4698           /* Check the alignment when a common symbol is involved. This
4699              can change when a common symbol is overridden by a normal
4700              definition or a common symbol is ignored due to the old
4701              normal definition. We need to make sure the maximum
4702              alignment is maintained.  */
4703           if ((old_alignment || common)
4704               && h->root.type != bfd_link_hash_common)
4705             {
4706               unsigned int common_align;
4707               unsigned int normal_align;
4708               unsigned int symbol_align;
4709               bfd *normal_bfd;
4710               bfd *common_bfd;
4711
4712               BFD_ASSERT (h->root.type == bfd_link_hash_defined
4713                           || h->root.type == bfd_link_hash_defweak);
4714
4715               symbol_align = ffs (h->root.u.def.value) - 1;
4716               if (h->root.u.def.section->owner != NULL
4717                   && (h->root.u.def.section->owner->flags
4718                        & (DYNAMIC | BFD_PLUGIN)) == 0)
4719                 {
4720                   normal_align = h->root.u.def.section->alignment_power;
4721                   if (normal_align > symbol_align)
4722                     normal_align = symbol_align;
4723                 }
4724               else
4725                 normal_align = symbol_align;
4726
4727               if (old_alignment)
4728                 {
4729                   common_align = old_alignment;
4730                   common_bfd = old_bfd;
4731                   normal_bfd = abfd;
4732                 }
4733               else
4734                 {
4735                   common_align = bfd_log2 (isym->st_value);
4736                   common_bfd = abfd;
4737                   normal_bfd = old_bfd;
4738                 }
4739
4740               if (normal_align < common_align)
4741                 {
4742                   /* PR binutils/2735 */
4743                   if (normal_bfd == NULL)
4744                     _bfd_error_handler
4745                       /* xgettext:c-format */
4746                       (_("Warning: alignment %u of common symbol `%s' in %B is"
4747                          " greater than the alignment (%u) of its section %A"),
4748                        1 << common_align, name, common_bfd,
4749                        1 << normal_align, h->root.u.def.section);
4750                   else
4751                     _bfd_error_handler
4752                       /* xgettext:c-format */
4753                       (_("Warning: alignment %u of symbol `%s' in %B"
4754                          " is smaller than %u in %B"),
4755                        1 << normal_align, name, normal_bfd,
4756                        1 << common_align, common_bfd);
4757                 }
4758             }
4759
4760           /* Remember the symbol size if it isn't undefined.  */
4761           if (isym->st_size != 0
4762               && isym->st_shndx != SHN_UNDEF
4763               && (definition || h->size == 0))
4764             {
4765               if (h->size != 0
4766                   && h->size != isym->st_size
4767                   && ! size_change_ok)
4768                 _bfd_error_handler
4769                   /* xgettext:c-format */
4770                   (_("Warning: size of symbol `%s' changed"
4771                      " from %Lu in %B to %Lu in %B"),
4772                    name, h->size, old_bfd, isym->st_size, abfd);
4773
4774               h->size = isym->st_size;
4775             }
4776
4777           /* If this is a common symbol, then we always want H->SIZE
4778              to be the size of the common symbol.  The code just above
4779              won't fix the size if a common symbol becomes larger.  We
4780              don't warn about a size change here, because that is
4781              covered by --warn-common.  Allow changes between different
4782              function types.  */
4783           if (h->root.type == bfd_link_hash_common)
4784             h->size = h->root.u.c.size;
4785
4786           if (ELF_ST_TYPE (isym->st_info) != STT_NOTYPE
4787               && ((definition && !new_weak)
4788                   || (old_weak && h->root.type == bfd_link_hash_common)
4789                   || h->type == STT_NOTYPE))
4790             {
4791               unsigned int type = ELF_ST_TYPE (isym->st_info);
4792
4793               /* Turn an IFUNC symbol from a DSO into a normal FUNC
4794                  symbol.  */
4795               if (type == STT_GNU_IFUNC
4796                   && (abfd->flags & DYNAMIC) != 0)
4797                 type = STT_FUNC;
4798
4799               if (h->type != type)
4800                 {
4801                   if (h->type != STT_NOTYPE && ! type_change_ok)
4802                     /* xgettext:c-format */
4803                     _bfd_error_handler
4804                       (_("Warning: type of symbol `%s' changed"
4805                          " from %d to %d in %B"),
4806                        name, h->type, type, abfd);
4807
4808                   h->type = type;
4809                 }
4810             }
4811
4812           /* Merge st_other field.  */
4813           elf_merge_st_other (abfd, h, isym, sec, definition, dynamic);
4814
4815           /* We don't want to make debug symbol dynamic.  */
4816           if (definition
4817               && (sec->flags & SEC_DEBUGGING)
4818               && !bfd_link_relocatable (info))
4819             dynsym = FALSE;
4820
4821           /* Nor should we make plugin symbols dynamic.  */
4822           if ((abfd->flags & BFD_PLUGIN) != 0)
4823             dynsym = FALSE;
4824
4825           if (definition)
4826             {
4827               h->target_internal = isym->st_target_internal;
4828               h->unique_global = (flags & BSF_GNU_UNIQUE) != 0;
4829             }
4830
4831           if (definition && !dynamic)
4832             {
4833               char *p = strchr (name, ELF_VER_CHR);
4834               if (p != NULL && p[1] != ELF_VER_CHR)
4835                 {
4836                   /* Queue non-default versions so that .symver x, x@FOO
4837                      aliases can be checked.  */
4838                   if (!nondeflt_vers)
4839                     {
4840                       amt = ((isymend - isym + 1)
4841                              * sizeof (struct elf_link_hash_entry *));
4842                       nondeflt_vers
4843                         = (struct elf_link_hash_entry **) bfd_malloc (amt);
4844                       if (!nondeflt_vers)
4845                         goto error_free_vers;
4846                     }
4847                   nondeflt_vers[nondeflt_vers_cnt++] = h;
4848                 }
4849             }
4850
4851           if (dynsym && h->dynindx == -1)
4852             {
4853               if (! bfd_elf_link_record_dynamic_symbol (info, h))
4854                 goto error_free_vers;
4855               if (h->u.weakdef != NULL
4856                   && ! new_weakdef
4857                   && h->u.weakdef->dynindx == -1)
4858                 {
4859                   if (!bfd_elf_link_record_dynamic_symbol (info, h->u.weakdef))
4860                     goto error_free_vers;
4861                 }
4862             }
4863           else if (h->dynindx != -1)
4864             /* If the symbol already has a dynamic index, but
4865                visibility says it should not be visible, turn it into
4866                a local symbol.  */
4867             switch (ELF_ST_VISIBILITY (h->other))
4868               {
4869               case STV_INTERNAL:
4870               case STV_HIDDEN:
4871                 (*bed->elf_backend_hide_symbol) (info, h, TRUE);
4872                 dynsym = FALSE;
4873                 break;
4874               }
4875
4876           /* Don't add DT_NEEDED for references from the dummy bfd nor
4877              for unmatched symbol.  */
4878           if (!add_needed
4879               && matched
4880               && definition
4881               && ((dynsym
4882                    && h->ref_regular_nonweak
4883                    && (old_bfd == NULL
4884                        || (old_bfd->flags & BFD_PLUGIN) == 0))
4885                   || (h->ref_dynamic_nonweak
4886                       && (elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0
4887                       && !on_needed_list (elf_dt_name (abfd),
4888                                           htab->needed, NULL))))
4889             {
4890               int ret;
4891               const char *soname = elf_dt_name (abfd);
4892
4893               info->callbacks->minfo ("%!", soname, old_bfd,
4894                                       h->root.root.string);
4895
4896               /* A symbol from a library loaded via DT_NEEDED of some
4897                  other library is referenced by a regular object.
4898                  Add a DT_NEEDED entry for it.  Issue an error if
4899                  --no-add-needed is used and the reference was not
4900                  a weak one.  */
4901               if (old_bfd != NULL
4902                   && (elf_dyn_lib_class (abfd) & DYN_NO_NEEDED) != 0)
4903                 {
4904                   _bfd_error_handler
4905                     /* xgettext:c-format */
4906                     (_("%B: undefined reference to symbol '%s'"),
4907                      old_bfd, name);
4908                   bfd_set_error (bfd_error_missing_dso);
4909                   goto error_free_vers;
4910                 }
4911
4912               elf_dyn_lib_class (abfd) = (enum dynamic_lib_link_class)
4913                 (elf_dyn_lib_class (abfd) & ~DYN_AS_NEEDED);
4914
4915               add_needed = TRUE;
4916               ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
4917               if (ret < 0)
4918                 goto error_free_vers;
4919
4920               BFD_ASSERT (ret == 0);
4921             }
4922         }
4923     }
4924
4925   if (extversym != NULL)
4926     {
4927       free (extversym);
4928       extversym = NULL;
4929     }
4930
4931   if (isymbuf != NULL)
4932     {
4933       free (isymbuf);
4934       isymbuf = NULL;
4935     }
4936
4937   if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
4938     {
4939       unsigned int i;
4940
4941       /* Restore the symbol table.  */
4942       old_ent = (char *) old_tab + tabsize;
4943       memset (elf_sym_hashes (abfd), 0,
4944               extsymcount * sizeof (struct elf_link_hash_entry *));
4945       htab->root.table.table = old_table;
4946       htab->root.table.size = old_size;
4947       htab->root.table.count = old_count;
4948       memcpy (htab->root.table.table, old_tab, tabsize);
4949       htab->root.undefs = old_undefs;
4950       htab->root.undefs_tail = old_undefs_tail;
4951       _bfd_elf_strtab_restore (htab->dynstr, old_strtab);
4952       free (old_strtab);
4953       old_strtab = NULL;
4954       for (i = 0; i < htab->root.table.size; i++)
4955         {
4956           struct bfd_hash_entry *p;
4957           struct elf_link_hash_entry *h;
4958           bfd_size_type size;
4959           unsigned int alignment_power;
4960           unsigned int non_ir_ref_dynamic;
4961
4962           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4963             {
4964               h = (struct elf_link_hash_entry *) p;
4965               if (h->root.type == bfd_link_hash_warning)
4966                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
4967
4968               /* Preserve the maximum alignment and size for common
4969                  symbols even if this dynamic lib isn't on DT_NEEDED
4970                  since it can still be loaded at run time by another
4971                  dynamic lib.  */
4972               if (h->root.type == bfd_link_hash_common)
4973                 {
4974                   size = h->root.u.c.size;
4975                   alignment_power = h->root.u.c.p->alignment_power;
4976                 }
4977               else
4978                 {
4979                   size = 0;
4980                   alignment_power = 0;
4981                 }
4982               /* Preserve non_ir_ref_dynamic so that this symbol
4983                  will be exported when the dynamic lib becomes needed
4984                  in the second pass.  */
4985               non_ir_ref_dynamic = h->root.non_ir_ref_dynamic;
4986               memcpy (p, old_ent, htab->root.table.entsize);
4987               old_ent = (char *) old_ent + htab->root.table.entsize;
4988               h = (struct elf_link_hash_entry *) p;
4989               if (h->root.type == bfd_link_hash_warning)
4990                 {
4991                   memcpy (h->root.u.i.link, old_ent, htab->root.table.entsize);
4992                   old_ent = (char *) old_ent + htab->root.table.entsize;
4993                   h = (struct elf_link_hash_entry *) h->root.u.i.link;
4994                 }
4995               if (h->root.type == bfd_link_hash_common)
4996                 {
4997                   if (size > h->root.u.c.size)
4998                     h->root.u.c.size = size;
4999                   if (alignment_power > h->root.u.c.p->alignment_power)
5000                     h->root.u.c.p->alignment_power = alignment_power;
5001                 }
5002               h->root.non_ir_ref_dynamic = non_ir_ref_dynamic;
5003             }
5004         }
5005
5006       /* Make a special call to the linker "notice" function to
5007          tell it that symbols added for crefs may need to be removed.  */
5008       if (!(*bed->notice_as_needed) (abfd, info, notice_not_needed))
5009         goto error_free_vers;
5010
5011       free (old_tab);
5012       objalloc_free_block ((struct objalloc *) htab->root.table.memory,
5013                            alloc_mark);
5014       if (nondeflt_vers != NULL)
5015         free (nondeflt_vers);
5016       return TRUE;
5017     }
5018
5019   if (old_tab != NULL)
5020     {
5021       if (!(*bed->notice_as_needed) (abfd, info, notice_needed))
5022         goto error_free_vers;
5023       free (old_tab);
5024       old_tab = NULL;
5025     }
5026
5027   /* Now that all the symbols from this input file are created, if
5028      not performing a relocatable link, handle .symver foo, foo@BAR
5029      such that any relocs against foo become foo@BAR.  */
5030   if (!bfd_link_relocatable (info) && nondeflt_vers != NULL)
5031     {
5032       size_t cnt, symidx;
5033
5034       for (cnt = 0; cnt < nondeflt_vers_cnt; ++cnt)
5035         {
5036           struct elf_link_hash_entry *h = nondeflt_vers[cnt], *hi;
5037           char *shortname, *p;
5038
5039           p = strchr (h->root.root.string, ELF_VER_CHR);
5040           if (p == NULL
5041               || (h->root.type != bfd_link_hash_defined
5042                   && h->root.type != bfd_link_hash_defweak))
5043             continue;
5044
5045           amt = p - h->root.root.string;
5046           shortname = (char *) bfd_malloc (amt + 1);
5047           if (!shortname)
5048             goto error_free_vers;
5049           memcpy (shortname, h->root.root.string, amt);
5050           shortname[amt] = '\0';
5051
5052           hi = (struct elf_link_hash_entry *)
5053                bfd_link_hash_lookup (&htab->root, shortname,
5054                                      FALSE, FALSE, FALSE);
5055           if (hi != NULL
5056               && hi->root.type == h->root.type
5057               && hi->root.u.def.value == h->root.u.def.value
5058               && hi->root.u.def.section == h->root.u.def.section)
5059             {
5060               (*bed->elf_backend_hide_symbol) (info, hi, TRUE);
5061               hi->root.type = bfd_link_hash_indirect;
5062               hi->root.u.i.link = (struct bfd_link_hash_entry *) h;
5063               (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
5064               sym_hash = elf_sym_hashes (abfd);
5065               if (sym_hash)
5066                 for (symidx = 0; symidx < extsymcount; ++symidx)
5067                   if (sym_hash[symidx] == hi)
5068                     {
5069                       sym_hash[symidx] = h;
5070                       break;
5071                     }
5072             }
5073           free (shortname);
5074         }
5075       free (nondeflt_vers);
5076       nondeflt_vers = NULL;
5077     }
5078
5079   /* Now set the weakdefs field correctly for all the weak defined
5080      symbols we found.  The only way to do this is to search all the
5081      symbols.  Since we only need the information for non functions in
5082      dynamic objects, that's the only time we actually put anything on
5083      the list WEAKS.  We need this information so that if a regular
5084      object refers to a symbol defined weakly in a dynamic object, the
5085      real symbol in the dynamic object is also put in the dynamic
5086      symbols; we also must arrange for both symbols to point to the
5087      same memory location.  We could handle the general case of symbol
5088      aliasing, but a general symbol alias can only be generated in
5089      assembler code, handling it correctly would be very time
5090      consuming, and other ELF linkers don't handle general aliasing
5091      either.  */
5092   if (weaks != NULL)
5093     {
5094       struct elf_link_hash_entry **hpp;
5095       struct elf_link_hash_entry **hppend;
5096       struct elf_link_hash_entry **sorted_sym_hash;
5097       struct elf_link_hash_entry *h;
5098       size_t sym_count;
5099
5100       /* Since we have to search the whole symbol list for each weak
5101          defined symbol, search time for N weak defined symbols will be
5102          O(N^2). Binary search will cut it down to O(NlogN).  */
5103       amt = extsymcount;
5104       amt *= sizeof (struct elf_link_hash_entry *);
5105       sorted_sym_hash = (struct elf_link_hash_entry **) bfd_malloc (amt);
5106       if (sorted_sym_hash == NULL)
5107         goto error_return;
5108       sym_hash = sorted_sym_hash;
5109       hpp = elf_sym_hashes (abfd);
5110       hppend = hpp + extsymcount;
5111       sym_count = 0;
5112       for (; hpp < hppend; hpp++)
5113         {
5114           h = *hpp;
5115           if (h != NULL
5116               && h->root.type == bfd_link_hash_defined
5117               && !bed->is_function_type (h->type))
5118             {
5119               *sym_hash = h;
5120               sym_hash++;
5121               sym_count++;
5122             }
5123         }
5124
5125       qsort (sorted_sym_hash, sym_count,
5126              sizeof (struct elf_link_hash_entry *),
5127              elf_sort_symbol);
5128
5129       while (weaks != NULL)
5130         {
5131           struct elf_link_hash_entry *hlook;
5132           asection *slook;
5133           bfd_vma vlook;
5134           size_t i, j, idx = 0;
5135
5136           hlook = weaks;
5137           weaks = hlook->u.weakdef;
5138           hlook->u.weakdef = NULL;
5139
5140           BFD_ASSERT (hlook->root.type == bfd_link_hash_defined
5141                       || hlook->root.type == bfd_link_hash_defweak
5142                       || hlook->root.type == bfd_link_hash_common
5143                       || hlook->root.type == bfd_link_hash_indirect);
5144           slook = hlook->root.u.def.section;
5145           vlook = hlook->root.u.def.value;
5146
5147           i = 0;
5148           j = sym_count;
5149           while (i != j)
5150             {
5151               bfd_signed_vma vdiff;
5152               idx = (i + j) / 2;
5153               h = sorted_sym_hash[idx];
5154               vdiff = vlook - h->root.u.def.value;
5155               if (vdiff < 0)
5156                 j = idx;
5157               else if (vdiff > 0)
5158                 i = idx + 1;
5159               else
5160                 {
5161                   int sdiff = slook->id - h->root.u.def.section->id;
5162                   if (sdiff < 0)
5163                     j = idx;
5164                   else if (sdiff > 0)
5165                     i = idx + 1;
5166                   else
5167                     break;
5168                 }
5169             }
5170
5171           /* We didn't find a value/section match.  */
5172           if (i == j)
5173             continue;
5174
5175           /* With multiple aliases, or when the weak symbol is already
5176              strongly defined, we have multiple matching symbols and
5177              the binary search above may land on any of them.  Step
5178              one past the matching symbol(s).  */
5179           while (++idx != j)
5180             {
5181               h = sorted_sym_hash[idx];
5182               if (h->root.u.def.section != slook
5183                   || h->root.u.def.value != vlook)
5184                 break;
5185             }
5186
5187           /* Now look back over the aliases.  Since we sorted by size
5188              as well as value and section, we'll choose the one with
5189              the largest size.  */
5190           while (idx-- != i)
5191             {
5192               h = sorted_sym_hash[idx];
5193
5194               /* Stop if value or section doesn't match.  */
5195               if (h->root.u.def.section != slook
5196                   || h->root.u.def.value != vlook)
5197                 break;
5198               else if (h != hlook)
5199                 {
5200                   hlook->u.weakdef = h;
5201
5202                   /* If the weak definition is in the list of dynamic
5203                      symbols, make sure the real definition is put
5204                      there as well.  */
5205                   if (hlook->dynindx != -1 && h->dynindx == -1)
5206                     {
5207                       if (! bfd_elf_link_record_dynamic_symbol (info, h))
5208                         {
5209                         err_free_sym_hash:
5210                           free (sorted_sym_hash);
5211                           goto error_return;
5212                         }
5213                     }
5214
5215                   /* If the real definition is in the list of dynamic
5216                      symbols, make sure the weak definition is put
5217                      there as well.  If we don't do this, then the
5218                      dynamic loader might not merge the entries for the
5219                      real definition and the weak definition.  */
5220                   if (h->dynindx != -1 && hlook->dynindx == -1)
5221                     {
5222                       if (! bfd_elf_link_record_dynamic_symbol (info, hlook))
5223                         goto err_free_sym_hash;
5224                     }
5225                   break;
5226                 }
5227             }
5228         }
5229
5230       free (sorted_sym_hash);
5231     }
5232
5233   if (bed->check_directives
5234       && !(*bed->check_directives) (abfd, info))
5235     return FALSE;
5236
5237   /* If this is a non-traditional link, try to optimize the handling
5238      of the .stab/.stabstr sections.  */
5239   if (! dynamic
5240       && ! info->traditional_format
5241       && is_elf_hash_table (htab)
5242       && (info->strip != strip_all && info->strip != strip_debugger))
5243     {
5244       asection *stabstr;
5245
5246       stabstr = bfd_get_section_by_name (abfd, ".stabstr");
5247       if (stabstr != NULL)
5248         {
5249           bfd_size_type string_offset = 0;
5250           asection *stab;
5251
5252           for (stab = abfd->sections; stab; stab = stab->next)
5253             if (CONST_STRNEQ (stab->name, ".stab")
5254                 && (!stab->name[5] ||
5255                     (stab->name[5] == '.' && ISDIGIT (stab->name[6])))
5256                 && (stab->flags & SEC_MERGE) == 0
5257                 && !bfd_is_abs_section (stab->output_section))
5258               {
5259                 struct bfd_elf_section_data *secdata;
5260
5261                 secdata = elf_section_data (stab);
5262                 if (! _bfd_link_section_stabs (abfd, &htab->stab_info, stab,
5263                                                stabstr, &secdata->sec_info,
5264                                                &string_offset))
5265                   goto error_return;
5266                 if (secdata->sec_info)
5267                   stab->sec_info_type = SEC_INFO_TYPE_STABS;
5268             }
5269         }
5270     }
5271
5272   if (is_elf_hash_table (htab) && add_needed)
5273     {
5274       /* Add this bfd to the loaded list.  */
5275       struct elf_link_loaded_list *n;
5276
5277       n = (struct elf_link_loaded_list *) bfd_alloc (abfd, sizeof (*n));
5278       if (n == NULL)
5279         goto error_return;
5280       n->abfd = abfd;
5281       n->next = htab->loaded;
5282       htab->loaded = n;
5283     }
5284
5285   return TRUE;
5286
5287  error_free_vers:
5288   if (old_tab != NULL)
5289     free (old_tab);
5290   if (old_strtab != NULL)
5291     free (old_strtab);
5292   if (nondeflt_vers != NULL)
5293     free (nondeflt_vers);
5294   if (extversym != NULL)
5295     free (extversym);
5296  error_free_sym:
5297   if (isymbuf != NULL)
5298     free (isymbuf);
5299  error_return:
5300   return FALSE;
5301 }
5302
5303 /* Return the linker hash table entry of a symbol that might be
5304    satisfied by an archive symbol.  Return -1 on error.  */
5305
5306 struct elf_link_hash_entry *
5307 _bfd_elf_archive_symbol_lookup (bfd *abfd,
5308                                 struct bfd_link_info *info,
5309                                 const char *name)
5310 {
5311   struct elf_link_hash_entry *h;
5312   char *p, *copy;
5313   size_t len, first;
5314
5315   h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, TRUE);
5316   if (h != NULL)
5317     return h;
5318
5319   /* If this is a default version (the name contains @@), look up the
5320      symbol again with only one `@' as well as without the version.
5321      The effect is that references to the symbol with and without the
5322      version will be matched by the default symbol in the archive.  */
5323
5324   p = strchr (name, ELF_VER_CHR);
5325   if (p == NULL || p[1] != ELF_VER_CHR)
5326     return h;
5327
5328   /* First check with only one `@'.  */
5329   len = strlen (name);
5330   copy = (char *) bfd_alloc (abfd, len);
5331   if (copy == NULL)
5332     return (struct elf_link_hash_entry *) 0 - 1;
5333
5334   first = p - name + 1;
5335   memcpy (copy, name, first);
5336   memcpy (copy + first, name + first + 1, len - first);
5337
5338   h = elf_link_hash_lookup (elf_hash_table (info), copy, FALSE, FALSE, TRUE);
5339   if (h == NULL)
5340     {
5341       /* We also need to check references to the symbol without the
5342          version.  */
5343       copy[first - 1] = '\0';
5344       h = elf_link_hash_lookup (elf_hash_table (info), copy,
5345                                 FALSE, FALSE, TRUE);
5346     }
5347
5348   bfd_release (abfd, copy);
5349   return h;
5350 }
5351
5352 /* Add symbols from an ELF archive file to the linker hash table.  We
5353    don't use _bfd_generic_link_add_archive_symbols because we need to
5354    handle versioned symbols.
5355
5356    Fortunately, ELF archive handling is simpler than that done by
5357    _bfd_generic_link_add_archive_symbols, which has to allow for a.out
5358    oddities.  In ELF, if we find a symbol in the archive map, and the
5359    symbol is currently undefined, we know that we must pull in that
5360    object file.
5361
5362    Unfortunately, we do have to make multiple passes over the symbol
5363    table until nothing further is resolved.  */
5364
5365 static bfd_boolean
5366 elf_link_add_archive_symbols (bfd *abfd, struct bfd_link_info *info)
5367 {
5368   symindex c;
5369   unsigned char *included = NULL;
5370   carsym *symdefs;
5371   bfd_boolean loop;
5372   bfd_size_type amt;
5373   const struct elf_backend_data *bed;
5374   struct elf_link_hash_entry * (*archive_symbol_lookup)
5375     (bfd *, struct bfd_link_info *, const char *);
5376
5377   if (! bfd_has_map (abfd))
5378     {
5379       /* An empty archive is a special case.  */
5380       if (bfd_openr_next_archived_file (abfd, NULL) == NULL)
5381         return TRUE;
5382       bfd_set_error (bfd_error_no_armap);
5383       return FALSE;
5384     }
5385
5386   /* Keep track of all symbols we know to be already defined, and all
5387      files we know to be already included.  This is to speed up the
5388      second and subsequent passes.  */
5389   c = bfd_ardata (abfd)->symdef_count;
5390   if (c == 0)
5391     return TRUE;
5392   amt = c;
5393   amt *= sizeof (*included);
5394   included = (unsigned char *) bfd_zmalloc (amt);
5395   if (included == NULL)
5396     return FALSE;
5397
5398   symdefs = bfd_ardata (abfd)->symdefs;
5399   bed = get_elf_backend_data (abfd);
5400   archive_symbol_lookup = bed->elf_backend_archive_symbol_lookup;
5401
5402   do
5403     {
5404       file_ptr last;
5405       symindex i;
5406       carsym *symdef;
5407       carsym *symdefend;
5408
5409       loop = FALSE;
5410       last = -1;
5411
5412       symdef = symdefs;
5413       symdefend = symdef + c;
5414       for (i = 0; symdef < symdefend; symdef++, i++)
5415         {
5416           struct elf_link_hash_entry *h;
5417           bfd *element;
5418           struct bfd_link_hash_entry *undefs_tail;
5419           symindex mark;
5420
5421           if (included[i])
5422             continue;
5423           if (symdef->file_offset == last)
5424             {
5425               included[i] = TRUE;
5426               continue;
5427             }
5428
5429           h = archive_symbol_lookup (abfd, info, symdef->name);
5430           if (h == (struct elf_link_hash_entry *) 0 - 1)
5431             goto error_return;
5432
5433           if (h == NULL)
5434             continue;
5435
5436           if (h->root.type == bfd_link_hash_common)
5437             {
5438               /* We currently have a common symbol.  The archive map contains
5439                  a reference to this symbol, so we may want to include it.  We
5440                  only want to include it however, if this archive element
5441                  contains a definition of the symbol, not just another common
5442                  declaration of it.
5443
5444                  Unfortunately some archivers (including GNU ar) will put
5445                  declarations of common symbols into their archive maps, as
5446                  well as real definitions, so we cannot just go by the archive
5447                  map alone.  Instead we must read in the element's symbol
5448                  table and check that to see what kind of symbol definition
5449                  this is.  */
5450               if (! elf_link_is_defined_archive_symbol (abfd, symdef))
5451                 continue;
5452             }
5453           else if (h->root.type != bfd_link_hash_undefined)
5454             {
5455               if (h->root.type != bfd_link_hash_undefweak)
5456                 /* Symbol must be defined.  Don't check it again.  */
5457                 included[i] = TRUE;
5458               continue;
5459             }
5460
5461           /* We need to include this archive member.  */
5462           element = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
5463           if (element == NULL)
5464             goto error_return;
5465
5466           if (! bfd_check_format (element, bfd_object))
5467             goto error_return;
5468
5469           undefs_tail = info->hash->undefs_tail;
5470
5471           if (!(*info->callbacks
5472                 ->add_archive_element) (info, element, symdef->name, &element))
5473             continue;
5474           if (!bfd_link_add_symbols (element, info))
5475             goto error_return;
5476
5477           /* If there are any new undefined symbols, we need to make
5478              another pass through the archive in order to see whether
5479              they can be defined.  FIXME: This isn't perfect, because
5480              common symbols wind up on undefs_tail and because an
5481              undefined symbol which is defined later on in this pass
5482              does not require another pass.  This isn't a bug, but it
5483              does make the code less efficient than it could be.  */
5484           if (undefs_tail != info->hash->undefs_tail)
5485             loop = TRUE;
5486
5487           /* Look backward to mark all symbols from this object file
5488              which we have already seen in this pass.  */
5489           mark = i;
5490           do
5491             {
5492               included[mark] = TRUE;
5493               if (mark == 0)
5494                 break;
5495               --mark;
5496             }
5497           while (symdefs[mark].file_offset == symdef->file_offset);
5498
5499           /* We mark subsequent symbols from this object file as we go
5500              on through the loop.  */
5501           last = symdef->file_offset;
5502         }
5503     }
5504   while (loop);
5505
5506   free (included);
5507
5508   return TRUE;
5509
5510  error_return:
5511   if (included != NULL)
5512     free (included);
5513   return FALSE;
5514 }
5515
5516 /* Given an ELF BFD, add symbols to the global hash table as
5517    appropriate.  */
5518
5519 bfd_boolean
5520 bfd_elf_link_add_symbols (bfd *abfd, struct bfd_link_info *info)
5521 {
5522   switch (bfd_get_format (abfd))
5523     {
5524     case bfd_object:
5525       return elf_link_add_object_symbols (abfd, info);
5526     case bfd_archive:
5527       return elf_link_add_archive_symbols (abfd, info);
5528     default:
5529       bfd_set_error (bfd_error_wrong_format);
5530       return FALSE;
5531     }
5532 }
5533 \f
5534 struct hash_codes_info
5535 {
5536   unsigned long *hashcodes;
5537   bfd_boolean error;
5538 };
5539
5540 /* This function will be called though elf_link_hash_traverse to store
5541    all hash value of the exported symbols in an array.  */
5542
5543 static bfd_boolean
5544 elf_collect_hash_codes (struct elf_link_hash_entry *h, void *data)
5545 {
5546   struct hash_codes_info *inf = (struct hash_codes_info *) data;
5547   const char *name;
5548   unsigned long ha;
5549   char *alc = NULL;
5550
5551   /* Ignore indirect symbols.  These are added by the versioning code.  */
5552   if (h->dynindx == -1)
5553     return TRUE;
5554
5555   name = h->root.root.string;
5556   if (h->versioned >= versioned)
5557     {
5558       char *p = strchr (name, ELF_VER_CHR);
5559       if (p != NULL)
5560         {
5561           alc = (char *) bfd_malloc (p - name + 1);
5562           if (alc == NULL)
5563             {
5564               inf->error = TRUE;
5565               return FALSE;
5566             }
5567           memcpy (alc, name, p - name);
5568           alc[p - name] = '\0';
5569           name = alc;
5570         }
5571     }
5572
5573   /* Compute the hash value.  */
5574   ha = bfd_elf_hash (name);
5575
5576   /* Store the found hash value in the array given as the argument.  */
5577   *(inf->hashcodes)++ = ha;
5578
5579   /* And store it in the struct so that we can put it in the hash table
5580      later.  */
5581   h->u.elf_hash_value = ha;
5582
5583   if (alc != NULL)
5584     free (alc);
5585
5586   return TRUE;
5587 }
5588
5589 struct collect_gnu_hash_codes
5590 {
5591   bfd *output_bfd;
5592   const struct elf_backend_data *bed;
5593   unsigned long int nsyms;
5594   unsigned long int maskbits;
5595   unsigned long int *hashcodes;
5596   unsigned long int *hashval;
5597   unsigned long int *indx;
5598   unsigned long int *counts;
5599   bfd_vma *bitmask;
5600   bfd_byte *contents;
5601   long int min_dynindx;
5602   unsigned long int bucketcount;
5603   unsigned long int symindx;
5604   long int local_indx;
5605   long int shift1, shift2;
5606   unsigned long int mask;
5607   bfd_boolean error;
5608 };
5609
5610 /* This function will be called though elf_link_hash_traverse to store
5611    all hash value of the exported symbols in an array.  */
5612
5613 static bfd_boolean
5614 elf_collect_gnu_hash_codes (struct elf_link_hash_entry *h, void *data)
5615 {
5616   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5617   const char *name;
5618   unsigned long ha;
5619   char *alc = NULL;
5620
5621   /* Ignore indirect symbols.  These are added by the versioning code.  */
5622   if (h->dynindx == -1)
5623     return TRUE;
5624
5625   /* Ignore also local symbols and undefined symbols.  */
5626   if (! (*s->bed->elf_hash_symbol) (h))
5627     return TRUE;
5628
5629   name = h->root.root.string;
5630   if (h->versioned >= versioned)
5631     {
5632       char *p = strchr (name, ELF_VER_CHR);
5633       if (p != NULL)
5634         {
5635           alc = (char *) bfd_malloc (p - name + 1);
5636           if (alc == NULL)
5637             {
5638               s->error = TRUE;
5639               return FALSE;
5640             }
5641           memcpy (alc, name, p - name);
5642           alc[p - name] = '\0';
5643           name = alc;
5644         }
5645     }
5646
5647   /* Compute the hash value.  */
5648   ha = bfd_elf_gnu_hash (name);
5649
5650   /* Store the found hash value in the array for compute_bucket_count,
5651      and also for .dynsym reordering purposes.  */
5652   s->hashcodes[s->nsyms] = ha;
5653   s->hashval[h->dynindx] = ha;
5654   ++s->nsyms;
5655   if (s->min_dynindx < 0 || s->min_dynindx > h->dynindx)
5656     s->min_dynindx = h->dynindx;
5657
5658   if (alc != NULL)
5659     free (alc);
5660
5661   return TRUE;
5662 }
5663
5664 /* This function will be called though elf_link_hash_traverse to do
5665    final dynaminc symbol renumbering.  */
5666
5667 static bfd_boolean
5668 elf_renumber_gnu_hash_syms (struct elf_link_hash_entry *h, void *data)
5669 {
5670   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5671   unsigned long int bucket;
5672   unsigned long int val;
5673
5674   /* Ignore indirect symbols.  */
5675   if (h->dynindx == -1)
5676     return TRUE;
5677
5678   /* Ignore also local symbols and undefined symbols.  */
5679   if (! (*s->bed->elf_hash_symbol) (h))
5680     {
5681       if (h->dynindx >= s->min_dynindx)
5682         h->dynindx = s->local_indx++;
5683       return TRUE;
5684     }
5685
5686   bucket = s->hashval[h->dynindx] % s->bucketcount;
5687   val = (s->hashval[h->dynindx] >> s->shift1)
5688         & ((s->maskbits >> s->shift1) - 1);
5689   s->bitmask[val] |= ((bfd_vma) 1) << (s->hashval[h->dynindx] & s->mask);
5690   s->bitmask[val]
5691     |= ((bfd_vma) 1) << ((s->hashval[h->dynindx] >> s->shift2) & s->mask);
5692   val = s->hashval[h->dynindx] & ~(unsigned long int) 1;
5693   if (s->counts[bucket] == 1)
5694     /* Last element terminates the chain.  */
5695     val |= 1;
5696   bfd_put_32 (s->output_bfd, val,
5697               s->contents + (s->indx[bucket] - s->symindx) * 4);
5698   --s->counts[bucket];
5699   h->dynindx = s->indx[bucket]++;
5700   return TRUE;
5701 }
5702
5703 /* Return TRUE if symbol should be hashed in the `.gnu.hash' section.  */
5704
5705 bfd_boolean
5706 _bfd_elf_hash_symbol (struct elf_link_hash_entry *h)
5707 {
5708   return !(h->forced_local
5709            || h->root.type == bfd_link_hash_undefined
5710            || h->root.type == bfd_link_hash_undefweak
5711            || ((h->root.type == bfd_link_hash_defined
5712                 || h->root.type == bfd_link_hash_defweak)
5713                && h->root.u.def.section->output_section == NULL));
5714 }
5715
5716 /* Array used to determine the number of hash table buckets to use
5717    based on the number of symbols there are.  If there are fewer than
5718    3 symbols we use 1 bucket, fewer than 17 symbols we use 3 buckets,
5719    fewer than 37 we use 17 buckets, and so forth.  We never use more
5720    than 32771 buckets.  */
5721
5722 static const size_t elf_buckets[] =
5723 {
5724   1, 3, 17, 37, 67, 97, 131, 197, 263, 521, 1031, 2053, 4099, 8209,
5725   16411, 32771, 0
5726 };
5727
5728 /* Compute bucket count for hashing table.  We do not use a static set
5729    of possible tables sizes anymore.  Instead we determine for all
5730    possible reasonable sizes of the table the outcome (i.e., the
5731    number of collisions etc) and choose the best solution.  The
5732    weighting functions are not too simple to allow the table to grow
5733    without bounds.  Instead one of the weighting factors is the size.
5734    Therefore the result is always a good payoff between few collisions
5735    (= short chain lengths) and table size.  */
5736 static size_t
5737 compute_bucket_count (struct bfd_link_info *info ATTRIBUTE_UNUSED,
5738                       unsigned long int *hashcodes ATTRIBUTE_UNUSED,
5739                       unsigned long int nsyms,
5740                       int gnu_hash)
5741 {
5742   size_t best_size = 0;
5743   unsigned long int i;
5744
5745   /* We have a problem here.  The following code to optimize the table
5746      size requires an integer type with more the 32 bits.  If
5747      BFD_HOST_U_64_BIT is set we know about such a type.  */
5748 #ifdef BFD_HOST_U_64_BIT
5749   if (info->optimize)
5750     {
5751       size_t minsize;
5752       size_t maxsize;
5753       BFD_HOST_U_64_BIT best_chlen = ~((BFD_HOST_U_64_BIT) 0);
5754       bfd *dynobj = elf_hash_table (info)->dynobj;
5755       size_t dynsymcount = elf_hash_table (info)->dynsymcount;
5756       const struct elf_backend_data *bed = get_elf_backend_data (dynobj);
5757       unsigned long int *counts;
5758       bfd_size_type amt;
5759       unsigned int no_improvement_count = 0;
5760
5761       /* Possible optimization parameters: if we have NSYMS symbols we say
5762          that the hashing table must at least have NSYMS/4 and at most
5763          2*NSYMS buckets.  */
5764       minsize = nsyms / 4;
5765       if (minsize == 0)
5766         minsize = 1;
5767       best_size = maxsize = nsyms * 2;
5768       if (gnu_hash)
5769         {
5770           if (minsize < 2)
5771             minsize = 2;
5772           if ((best_size & 31) == 0)
5773             ++best_size;
5774         }
5775
5776       /* Create array where we count the collisions in.  We must use bfd_malloc
5777          since the size could be large.  */
5778       amt = maxsize;
5779       amt *= sizeof (unsigned long int);
5780       counts = (unsigned long int *) bfd_malloc (amt);
5781       if (counts == NULL)
5782         return 0;
5783
5784       /* Compute the "optimal" size for the hash table.  The criteria is a
5785          minimal chain length.  The minor criteria is (of course) the size
5786          of the table.  */
5787       for (i = minsize; i < maxsize; ++i)
5788         {
5789           /* Walk through the array of hashcodes and count the collisions.  */
5790           BFD_HOST_U_64_BIT max;
5791           unsigned long int j;
5792           unsigned long int fact;
5793
5794           if (gnu_hash && (i & 31) == 0)
5795             continue;
5796
5797           memset (counts, '\0', i * sizeof (unsigned long int));
5798
5799           /* Determine how often each hash bucket is used.  */
5800           for (j = 0; j < nsyms; ++j)
5801             ++counts[hashcodes[j] % i];
5802
5803           /* For the weight function we need some information about the
5804              pagesize on the target.  This is information need not be 100%
5805              accurate.  Since this information is not available (so far) we
5806              define it here to a reasonable default value.  If it is crucial
5807              to have a better value some day simply define this value.  */
5808 # ifndef BFD_TARGET_PAGESIZE
5809 #  define BFD_TARGET_PAGESIZE   (4096)
5810 # endif
5811
5812           /* We in any case need 2 + DYNSYMCOUNT entries for the size values
5813              and the chains.  */
5814           max = (2 + dynsymcount) * bed->s->sizeof_hash_entry;
5815
5816 # if 1
5817           /* Variant 1: optimize for short chains.  We add the squares
5818              of all the chain lengths (which favors many small chain
5819              over a few long chains).  */
5820           for (j = 0; j < i; ++j)
5821             max += counts[j] * counts[j];
5822
5823           /* This adds penalties for the overall size of the table.  */
5824           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5825           max *= fact * fact;
5826 # else
5827           /* Variant 2: Optimize a lot more for small table.  Here we
5828              also add squares of the size but we also add penalties for
5829              empty slots (the +1 term).  */
5830           for (j = 0; j < i; ++j)
5831             max += (1 + counts[j]) * (1 + counts[j]);
5832
5833           /* The overall size of the table is considered, but not as
5834              strong as in variant 1, where it is squared.  */
5835           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5836           max *= fact;
5837 # endif
5838
5839           /* Compare with current best results.  */
5840           if (max < best_chlen)
5841             {
5842               best_chlen = max;
5843               best_size = i;
5844               no_improvement_count = 0;
5845             }
5846           /* PR 11843: Avoid futile long searches for the best bucket size
5847              when there are a large number of symbols.  */
5848           else if (++no_improvement_count == 100)
5849             break;
5850         }
5851
5852       free (counts);
5853     }
5854   else
5855 #endif /* defined (BFD_HOST_U_64_BIT) */
5856     {
5857       /* This is the fallback solution if no 64bit type is available or if we
5858          are not supposed to spend much time on optimizations.  We select the
5859          bucket count using a fixed set of numbers.  */
5860       for (i = 0; elf_buckets[i] != 0; i++)
5861         {
5862           best_size = elf_buckets[i];
5863           if (nsyms < elf_buckets[i + 1])
5864             break;
5865         }
5866       if (gnu_hash && best_size < 2)
5867         best_size = 2;
5868     }
5869
5870   return best_size;
5871 }
5872
5873 /* Size any SHT_GROUP section for ld -r.  */
5874
5875 bfd_boolean
5876 _bfd_elf_size_group_sections (struct bfd_link_info *info)
5877 {
5878   bfd *ibfd;
5879   asection *s;
5880
5881   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
5882     if (bfd_get_flavour (ibfd) == bfd_target_elf_flavour
5883         && (s = ibfd->sections) != NULL
5884         && s->sec_info_type != SEC_INFO_TYPE_JUST_SYMS
5885         && !_bfd_elf_fixup_group_sections (ibfd, bfd_abs_section_ptr))
5886       return FALSE;
5887   return TRUE;
5888 }
5889
5890 /* Set a default stack segment size.  The value in INFO wins.  If it
5891    is unset, LEGACY_SYMBOL's value is used, and if that symbol is
5892    undefined it is initialized.  */
5893
5894 bfd_boolean
5895 bfd_elf_stack_segment_size (bfd *output_bfd,
5896                             struct bfd_link_info *info,
5897                             const char *legacy_symbol,
5898                             bfd_vma default_size)
5899 {
5900   struct elf_link_hash_entry *h = NULL;
5901
5902   /* Look for legacy symbol.  */
5903   if (legacy_symbol)
5904     h = elf_link_hash_lookup (elf_hash_table (info), legacy_symbol,
5905                               FALSE, FALSE, FALSE);
5906   if (h && (h->root.type == bfd_link_hash_defined
5907             || h->root.type == bfd_link_hash_defweak)
5908       && h->def_regular
5909       && (h->type == STT_NOTYPE || h->type == STT_OBJECT))
5910     {
5911       /* The symbol has no type if specified on the command line.  */
5912       h->type = STT_OBJECT;
5913       if (info->stacksize)
5914         /* xgettext:c-format */
5915         _bfd_error_handler (_("%B: stack size specified and %s set"),
5916                             output_bfd, legacy_symbol);
5917       else if (h->root.u.def.section != bfd_abs_section_ptr)
5918         /* xgettext:c-format */
5919         _bfd_error_handler (_("%B: %s not absolute"),
5920                             output_bfd, legacy_symbol);
5921       else
5922         info->stacksize = h->root.u.def.value;
5923     }
5924
5925   if (!info->stacksize)
5926     /* If the user didn't set a size, or explicitly inhibit the
5927        size, set it now.  */
5928     info->stacksize = default_size;
5929
5930   /* Provide the legacy symbol, if it is referenced.  */
5931   if (h && (h->root.type == bfd_link_hash_undefined
5932             || h->root.type == bfd_link_hash_undefweak))
5933     {
5934       struct bfd_link_hash_entry *bh = NULL;
5935
5936       if (!(_bfd_generic_link_add_one_symbol
5937             (info, output_bfd, legacy_symbol,
5938              BSF_GLOBAL, bfd_abs_section_ptr,
5939              info->stacksize >= 0 ? info->stacksize : 0,
5940              NULL, FALSE, get_elf_backend_data (output_bfd)->collect, &bh)))
5941         return FALSE;
5942
5943       h = (struct elf_link_hash_entry *) bh;
5944       h->def_regular = 1;
5945       h->type = STT_OBJECT;
5946     }
5947
5948   return TRUE;
5949 }
5950
5951 /* Sweep symbols in swept sections.  Called via elf_link_hash_traverse.  */
5952
5953 struct elf_gc_sweep_symbol_info
5954 {
5955   struct bfd_link_info *info;
5956   void (*hide_symbol) (struct bfd_link_info *, struct elf_link_hash_entry *,
5957                        bfd_boolean);
5958 };
5959
5960 static bfd_boolean
5961 elf_gc_sweep_symbol (struct elf_link_hash_entry *h, void *data)
5962 {
5963   if (!h->mark
5964       && (((h->root.type == bfd_link_hash_defined
5965             || h->root.type == bfd_link_hash_defweak)
5966            && !((h->def_regular || ELF_COMMON_DEF_P (h))
5967                 && h->root.u.def.section->gc_mark))
5968           || h->root.type == bfd_link_hash_undefined
5969           || h->root.type == bfd_link_hash_undefweak))
5970     {
5971       struct elf_gc_sweep_symbol_info *inf;
5972
5973       inf = (struct elf_gc_sweep_symbol_info *) data;
5974       (*inf->hide_symbol) (inf->info, h, TRUE);
5975       h->def_regular = 0;
5976       h->ref_regular = 0;
5977       h->ref_regular_nonweak = 0;
5978     }
5979
5980   return TRUE;
5981 }
5982
5983 /* Set up the sizes and contents of the ELF dynamic sections.  This is
5984    called by the ELF linker emulation before_allocation routine.  We
5985    must set the sizes of the sections before the linker sets the
5986    addresses of the various sections.  */
5987
5988 bfd_boolean
5989 bfd_elf_size_dynamic_sections (bfd *output_bfd,
5990                                const char *soname,
5991                                const char *rpath,
5992                                const char *filter_shlib,
5993                                const char *audit,
5994                                const char *depaudit,
5995                                const char * const *auxiliary_filters,
5996                                struct bfd_link_info *info,
5997                                asection **sinterpptr)
5998 {
5999   bfd *dynobj;
6000   const struct elf_backend_data *bed;
6001
6002   *sinterpptr = NULL;
6003
6004   if (!is_elf_hash_table (info->hash))
6005     return TRUE;
6006
6007   dynobj = elf_hash_table (info)->dynobj;
6008
6009   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6010     {
6011       struct bfd_elf_version_tree *verdefs;
6012       struct elf_info_failed asvinfo;
6013       struct bfd_elf_version_tree *t;
6014       struct bfd_elf_version_expr *d;
6015       asection *s;
6016       size_t soname_indx;
6017
6018       /* If we are supposed to export all symbols into the dynamic symbol
6019          table (this is not the normal case), then do so.  */
6020       if (info->export_dynamic
6021           || (bfd_link_executable (info) && info->dynamic))
6022         {
6023           struct elf_info_failed eif;
6024
6025           eif.info = info;
6026           eif.failed = FALSE;
6027           elf_link_hash_traverse (elf_hash_table (info),
6028                                   _bfd_elf_export_symbol,
6029                                   &eif);
6030           if (eif.failed)
6031             return FALSE;
6032         }
6033
6034       if (soname != NULL)
6035         {
6036           soname_indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6037                                              soname, TRUE);
6038           if (soname_indx == (size_t) -1
6039               || !_bfd_elf_add_dynamic_entry (info, DT_SONAME, soname_indx))
6040             return FALSE;
6041         }
6042       else
6043         soname_indx = (size_t) -1;
6044
6045       /* Make all global versions with definition.  */
6046       for (t = info->version_info; t != NULL; t = t->next)
6047         for (d = t->globals.list; d != NULL; d = d->next)
6048           if (!d->symver && d->literal)
6049             {
6050               const char *verstr, *name;
6051               size_t namelen, verlen, newlen;
6052               char *newname, *p, leading_char;
6053               struct elf_link_hash_entry *newh;
6054
6055               leading_char = bfd_get_symbol_leading_char (output_bfd);
6056               name = d->pattern;
6057               namelen = strlen (name) + (leading_char != '\0');
6058               verstr = t->name;
6059               verlen = strlen (verstr);
6060               newlen = namelen + verlen + 3;
6061
6062               newname = (char *) bfd_malloc (newlen);
6063               if (newname == NULL)
6064                 return FALSE;
6065               newname[0] = leading_char;
6066               memcpy (newname + (leading_char != '\0'), name, namelen);
6067
6068               /* Check the hidden versioned definition.  */
6069               p = newname + namelen;
6070               *p++ = ELF_VER_CHR;
6071               memcpy (p, verstr, verlen + 1);
6072               newh = elf_link_hash_lookup (elf_hash_table (info),
6073                                            newname, FALSE, FALSE,
6074                                            FALSE);
6075               if (newh == NULL
6076                   || (newh->root.type != bfd_link_hash_defined
6077                       && newh->root.type != bfd_link_hash_defweak))
6078                 {
6079                   /* Check the default versioned definition.  */
6080                   *p++ = ELF_VER_CHR;
6081                   memcpy (p, verstr, verlen + 1);
6082                   newh = elf_link_hash_lookup (elf_hash_table (info),
6083                                                newname, FALSE, FALSE,
6084                                                FALSE);
6085                 }
6086               free (newname);
6087
6088               /* Mark this version if there is a definition and it is
6089                  not defined in a shared object.  */
6090               if (newh != NULL
6091                   && !newh->def_dynamic
6092                   && (newh->root.type == bfd_link_hash_defined
6093                       || newh->root.type == bfd_link_hash_defweak))
6094                 d->symver = 1;
6095             }
6096
6097       /* Attach all the symbols to their version information.  */
6098       asvinfo.info = info;
6099       asvinfo.failed = FALSE;
6100
6101       elf_link_hash_traverse (elf_hash_table (info),
6102                               _bfd_elf_link_assign_sym_version,
6103                               &asvinfo);
6104       if (asvinfo.failed)
6105         return FALSE;
6106
6107       if (!info->allow_undefined_version)
6108         {
6109           /* Check if all global versions have a definition.  */
6110           bfd_boolean all_defined = TRUE;
6111           for (t = info->version_info; t != NULL; t = t->next)
6112             for (d = t->globals.list; d != NULL; d = d->next)
6113               if (d->literal && !d->symver && !d->script)
6114                 {
6115                   _bfd_error_handler
6116                     (_("%s: undefined version: %s"),
6117                      d->pattern, t->name);
6118                   all_defined = FALSE;
6119                 }
6120
6121           if (!all_defined)
6122             {
6123               bfd_set_error (bfd_error_bad_value);
6124               return FALSE;
6125             }
6126         }
6127
6128       /* Set up the version definition section.  */
6129       s = bfd_get_linker_section (dynobj, ".gnu.version_d");
6130       BFD_ASSERT (s != NULL);
6131
6132       /* We may have created additional version definitions if we are
6133          just linking a regular application.  */
6134       verdefs = info->version_info;
6135
6136       /* Skip anonymous version tag.  */
6137       if (verdefs != NULL && verdefs->vernum == 0)
6138         verdefs = verdefs->next;
6139
6140       if (verdefs == NULL && !info->create_default_symver)
6141         s->flags |= SEC_EXCLUDE;
6142       else
6143         {
6144           unsigned int cdefs;
6145           bfd_size_type size;
6146           bfd_byte *p;
6147           Elf_Internal_Verdef def;
6148           Elf_Internal_Verdaux defaux;
6149           struct bfd_link_hash_entry *bh;
6150           struct elf_link_hash_entry *h;
6151           const char *name;
6152
6153           cdefs = 0;
6154           size = 0;
6155
6156           /* Make space for the base version.  */
6157           size += sizeof (Elf_External_Verdef);
6158           size += sizeof (Elf_External_Verdaux);
6159           ++cdefs;
6160
6161           /* Make space for the default version.  */
6162           if (info->create_default_symver)
6163             {
6164               size += sizeof (Elf_External_Verdef);
6165               ++cdefs;
6166             }
6167
6168           for (t = verdefs; t != NULL; t = t->next)
6169             {
6170               struct bfd_elf_version_deps *n;
6171
6172               /* Don't emit base version twice.  */
6173               if (t->vernum == 0)
6174                 continue;
6175
6176               size += sizeof (Elf_External_Verdef);
6177               size += sizeof (Elf_External_Verdaux);
6178               ++cdefs;
6179
6180               for (n = t->deps; n != NULL; n = n->next)
6181                 size += sizeof (Elf_External_Verdaux);
6182             }
6183
6184           s->size = size;
6185           s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6186           if (s->contents == NULL && s->size != 0)
6187             return FALSE;
6188
6189           /* Fill in the version definition section.  */
6190
6191           p = s->contents;
6192
6193           def.vd_version = VER_DEF_CURRENT;
6194           def.vd_flags = VER_FLG_BASE;
6195           def.vd_ndx = 1;
6196           def.vd_cnt = 1;
6197           if (info->create_default_symver)
6198             {
6199               def.vd_aux = 2 * sizeof (Elf_External_Verdef);
6200               def.vd_next = sizeof (Elf_External_Verdef);
6201             }
6202           else
6203             {
6204               def.vd_aux = sizeof (Elf_External_Verdef);
6205               def.vd_next = (sizeof (Elf_External_Verdef)
6206                              + sizeof (Elf_External_Verdaux));
6207             }
6208
6209           if (soname_indx != (size_t) -1)
6210             {
6211               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6212                                       soname_indx);
6213               def.vd_hash = bfd_elf_hash (soname);
6214               defaux.vda_name = soname_indx;
6215               name = soname;
6216             }
6217           else
6218             {
6219               size_t indx;
6220
6221               name = lbasename (output_bfd->filename);
6222               def.vd_hash = bfd_elf_hash (name);
6223               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6224                                           name, FALSE);
6225               if (indx == (size_t) -1)
6226                 return FALSE;
6227               defaux.vda_name = indx;
6228             }
6229           defaux.vda_next = 0;
6230
6231           _bfd_elf_swap_verdef_out (output_bfd, &def,
6232                                     (Elf_External_Verdef *) p);
6233           p += sizeof (Elf_External_Verdef);
6234           if (info->create_default_symver)
6235             {
6236               /* Add a symbol representing this version.  */
6237               bh = NULL;
6238               if (! (_bfd_generic_link_add_one_symbol
6239                      (info, dynobj, name, BSF_GLOBAL, bfd_abs_section_ptr,
6240                       0, NULL, FALSE,
6241                       get_elf_backend_data (dynobj)->collect, &bh)))
6242                 return FALSE;
6243               h = (struct elf_link_hash_entry *) bh;
6244               h->non_elf = 0;
6245               h->def_regular = 1;
6246               h->type = STT_OBJECT;
6247               h->verinfo.vertree = NULL;
6248
6249               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6250                 return FALSE;
6251
6252               /* Create a duplicate of the base version with the same
6253                  aux block, but different flags.  */
6254               def.vd_flags = 0;
6255               def.vd_ndx = 2;
6256               def.vd_aux = sizeof (Elf_External_Verdef);
6257               if (verdefs)
6258                 def.vd_next = (sizeof (Elf_External_Verdef)
6259                                + sizeof (Elf_External_Verdaux));
6260               else
6261                 def.vd_next = 0;
6262               _bfd_elf_swap_verdef_out (output_bfd, &def,
6263                                         (Elf_External_Verdef *) p);
6264               p += sizeof (Elf_External_Verdef);
6265             }
6266           _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6267                                      (Elf_External_Verdaux *) p);
6268           p += sizeof (Elf_External_Verdaux);
6269
6270           for (t = verdefs; t != NULL; t = t->next)
6271             {
6272               unsigned int cdeps;
6273               struct bfd_elf_version_deps *n;
6274
6275               /* Don't emit the base version twice.  */
6276               if (t->vernum == 0)
6277                 continue;
6278
6279               cdeps = 0;
6280               for (n = t->deps; n != NULL; n = n->next)
6281                 ++cdeps;
6282
6283               /* Add a symbol representing this version.  */
6284               bh = NULL;
6285               if (! (_bfd_generic_link_add_one_symbol
6286                      (info, dynobj, t->name, BSF_GLOBAL, bfd_abs_section_ptr,
6287                       0, NULL, FALSE,
6288                       get_elf_backend_data (dynobj)->collect, &bh)))
6289                 return FALSE;
6290               h = (struct elf_link_hash_entry *) bh;
6291               h->non_elf = 0;
6292               h->def_regular = 1;
6293               h->type = STT_OBJECT;
6294               h->verinfo.vertree = t;
6295
6296               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6297                 return FALSE;
6298
6299               def.vd_version = VER_DEF_CURRENT;
6300               def.vd_flags = 0;
6301               if (t->globals.list == NULL
6302                   && t->locals.list == NULL
6303                   && ! t->used)
6304                 def.vd_flags |= VER_FLG_WEAK;
6305               def.vd_ndx = t->vernum + (info->create_default_symver ? 2 : 1);
6306               def.vd_cnt = cdeps + 1;
6307               def.vd_hash = bfd_elf_hash (t->name);
6308               def.vd_aux = sizeof (Elf_External_Verdef);
6309               def.vd_next = 0;
6310
6311               /* If a basever node is next, it *must* be the last node in
6312                  the chain, otherwise Verdef construction breaks.  */
6313               if (t->next != NULL && t->next->vernum == 0)
6314                 BFD_ASSERT (t->next->next == NULL);
6315
6316               if (t->next != NULL && t->next->vernum != 0)
6317                 def.vd_next = (sizeof (Elf_External_Verdef)
6318                                + (cdeps + 1) * sizeof (Elf_External_Verdaux));
6319
6320               _bfd_elf_swap_verdef_out (output_bfd, &def,
6321                                         (Elf_External_Verdef *) p);
6322               p += sizeof (Elf_External_Verdef);
6323
6324               defaux.vda_name = h->dynstr_index;
6325               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6326                                       h->dynstr_index);
6327               defaux.vda_next = 0;
6328               if (t->deps != NULL)
6329                 defaux.vda_next = sizeof (Elf_External_Verdaux);
6330               t->name_indx = defaux.vda_name;
6331
6332               _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6333                                          (Elf_External_Verdaux *) p);
6334               p += sizeof (Elf_External_Verdaux);
6335
6336               for (n = t->deps; n != NULL; n = n->next)
6337                 {
6338                   if (n->version_needed == NULL)
6339                     {
6340                       /* This can happen if there was an error in the
6341                          version script.  */
6342                       defaux.vda_name = 0;
6343                     }
6344                   else
6345                     {
6346                       defaux.vda_name = n->version_needed->name_indx;
6347                       _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6348                                               defaux.vda_name);
6349                     }
6350                   if (n->next == NULL)
6351                     defaux.vda_next = 0;
6352                   else
6353                     defaux.vda_next = sizeof (Elf_External_Verdaux);
6354
6355                   _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6356                                              (Elf_External_Verdaux *) p);
6357                   p += sizeof (Elf_External_Verdaux);
6358                 }
6359             }
6360
6361           elf_tdata (output_bfd)->cverdefs = cdefs;
6362         }
6363     }
6364
6365   bed = get_elf_backend_data (output_bfd);
6366
6367   if (info->gc_sections && bed->can_gc_sections)
6368     {
6369       struct elf_gc_sweep_symbol_info sweep_info;
6370
6371       /* Remove the symbols that were in the swept sections from the
6372          dynamic symbol table.  */
6373       sweep_info.info = info;
6374       sweep_info.hide_symbol = bed->elf_backend_hide_symbol;
6375       elf_link_hash_traverse (elf_hash_table (info), elf_gc_sweep_symbol,
6376                               &sweep_info);
6377     }
6378
6379   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6380     {
6381       asection *s;
6382       struct elf_find_verdep_info sinfo;
6383
6384       /* Work out the size of the version reference section.  */
6385
6386       s = bfd_get_linker_section (dynobj, ".gnu.version_r");
6387       BFD_ASSERT (s != NULL);
6388
6389       sinfo.info = info;
6390       sinfo.vers = elf_tdata (output_bfd)->cverdefs;
6391       if (sinfo.vers == 0)
6392         sinfo.vers = 1;
6393       sinfo.failed = FALSE;
6394
6395       elf_link_hash_traverse (elf_hash_table (info),
6396                               _bfd_elf_link_find_version_dependencies,
6397                               &sinfo);
6398       if (sinfo.failed)
6399         return FALSE;
6400
6401       if (elf_tdata (output_bfd)->verref == NULL)
6402         s->flags |= SEC_EXCLUDE;
6403       else
6404         {
6405           Elf_Internal_Verneed *vn;
6406           unsigned int size;
6407           unsigned int crefs;
6408           bfd_byte *p;
6409
6410           /* Build the version dependency section.  */
6411           size = 0;
6412           crefs = 0;
6413           for (vn = elf_tdata (output_bfd)->verref;
6414                vn != NULL;
6415                vn = vn->vn_nextref)
6416             {
6417               Elf_Internal_Vernaux *a;
6418
6419               size += sizeof (Elf_External_Verneed);
6420               ++crefs;
6421               for (a = vn->vn_auxptr; a != NULL; a = a->vna_nextptr)
6422                 size += sizeof (Elf_External_Vernaux);
6423             }
6424
6425           s->size = size;
6426           s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6427           if (s->contents == NULL)
6428             return FALSE;
6429
6430           p = s->contents;
6431           for (vn = elf_tdata (output_bfd)->verref;
6432                vn != NULL;
6433                vn = vn->vn_nextref)
6434             {
6435               unsigned int caux;
6436               Elf_Internal_Vernaux *a;
6437               size_t indx;
6438
6439               caux = 0;
6440               for (a = vn->vn_auxptr; a != NULL; a = a->vna_nextptr)
6441                 ++caux;
6442
6443               vn->vn_version = VER_NEED_CURRENT;
6444               vn->vn_cnt = caux;
6445               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6446                                           elf_dt_name (vn->vn_bfd) != NULL
6447                                           ? elf_dt_name (vn->vn_bfd)
6448                                           : lbasename (vn->vn_bfd->filename),
6449                                           FALSE);
6450               if (indx == (size_t) -1)
6451                 return FALSE;
6452               vn->vn_file = indx;
6453               vn->vn_aux = sizeof (Elf_External_Verneed);
6454               if (vn->vn_nextref == NULL)
6455                 vn->vn_next = 0;
6456               else
6457                 vn->vn_next = (sizeof (Elf_External_Verneed)
6458                                + caux * sizeof (Elf_External_Vernaux));
6459
6460               _bfd_elf_swap_verneed_out (output_bfd, vn,
6461                                          (Elf_External_Verneed *) p);
6462               p += sizeof (Elf_External_Verneed);
6463
6464               for (a = vn->vn_auxptr; a != NULL; a = a->vna_nextptr)
6465                 {
6466                   a->vna_hash = bfd_elf_hash (a->vna_nodename);
6467                   indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6468                                               a->vna_nodename, FALSE);
6469                   if (indx == (size_t) -1)
6470                     return FALSE;
6471                   a->vna_name = indx;
6472                   if (a->vna_nextptr == NULL)
6473                     a->vna_next = 0;
6474                   else
6475                     a->vna_next = sizeof (Elf_External_Vernaux);
6476
6477                   _bfd_elf_swap_vernaux_out (output_bfd, a,
6478                                              (Elf_External_Vernaux *) p);
6479                   p += sizeof (Elf_External_Vernaux);
6480                 }
6481             }
6482
6483           elf_tdata (output_bfd)->cverrefs = crefs;
6484         }
6485     }
6486
6487   /* Any syms created from now on start with -1 in
6488      got.refcount/offset and plt.refcount/offset.  */
6489   elf_hash_table (info)->init_got_refcount
6490     = elf_hash_table (info)->init_got_offset;
6491   elf_hash_table (info)->init_plt_refcount
6492     = elf_hash_table (info)->init_plt_offset;
6493
6494   if (bfd_link_relocatable (info)
6495       && !_bfd_elf_size_group_sections (info))
6496     return FALSE;
6497
6498   /* The backend may have to create some sections regardless of whether
6499      we're dynamic or not.  */
6500   if (bed->elf_backend_always_size_sections
6501       && ! (*bed->elf_backend_always_size_sections) (output_bfd, info))
6502     return FALSE;
6503
6504   /* Determine any GNU_STACK segment requirements, after the backend
6505      has had a chance to set a default segment size.  */
6506   if (info->execstack)
6507     elf_stack_flags (output_bfd) = PF_R | PF_W | PF_X;
6508   else if (info->noexecstack)
6509     elf_stack_flags (output_bfd) = PF_R | PF_W;
6510   else
6511     {
6512       bfd *inputobj;
6513       asection *notesec = NULL;
6514       int exec = 0;
6515
6516       for (inputobj = info->input_bfds;
6517            inputobj;
6518            inputobj = inputobj->link.next)
6519         {
6520           asection *s;
6521
6522           if (inputobj->flags
6523               & (DYNAMIC | EXEC_P | BFD_PLUGIN | BFD_LINKER_CREATED))
6524             continue;
6525           s = inputobj->sections;
6526           if (s == NULL || s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
6527             continue;
6528
6529           s = bfd_get_section_by_name (inputobj, ".note.GNU-stack");
6530           if (s)
6531             {
6532               if (s->flags & SEC_CODE)
6533                 exec = PF_X;
6534               notesec = s;
6535             }
6536           else if (bed->default_execstack)
6537             exec = PF_X;
6538         }
6539       if (notesec || info->stacksize > 0)
6540         elf_stack_flags (output_bfd) = PF_R | PF_W | exec;
6541       if (notesec && exec && bfd_link_relocatable (info)
6542           && notesec->output_section != bfd_abs_section_ptr)
6543         notesec->output_section->flags |= SEC_CODE;
6544     }
6545
6546   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6547     {
6548       struct elf_info_failed eif;
6549       struct elf_link_hash_entry *h;
6550       asection *dynstr;
6551       asection *s;
6552
6553       *sinterpptr = bfd_get_linker_section (dynobj, ".interp");
6554       BFD_ASSERT (*sinterpptr != NULL || !bfd_link_executable (info) || info->nointerp);
6555
6556       if (info->symbolic)
6557         {
6558           if (!_bfd_elf_add_dynamic_entry (info, DT_SYMBOLIC, 0))
6559             return FALSE;
6560           info->flags |= DF_SYMBOLIC;
6561         }
6562
6563       if (rpath != NULL)
6564         {
6565           size_t indx;
6566           bfd_vma tag;
6567
6568           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, rpath,
6569                                       TRUE);
6570           if (indx == (size_t) -1)
6571             return FALSE;
6572
6573           tag = info->new_dtags ? DT_RUNPATH : DT_RPATH;
6574           if (!_bfd_elf_add_dynamic_entry (info, tag, indx))
6575             return FALSE;
6576         }
6577
6578       if (filter_shlib != NULL)
6579         {
6580           size_t indx;
6581
6582           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6583                                       filter_shlib, TRUE);
6584           if (indx == (size_t) -1
6585               || !_bfd_elf_add_dynamic_entry (info, DT_FILTER, indx))
6586             return FALSE;
6587         }
6588
6589       if (auxiliary_filters != NULL)
6590         {
6591           const char * const *p;
6592
6593           for (p = auxiliary_filters; *p != NULL; p++)
6594             {
6595               size_t indx;
6596
6597               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6598                                           *p, TRUE);
6599               if (indx == (size_t) -1
6600                   || !_bfd_elf_add_dynamic_entry (info, DT_AUXILIARY, indx))
6601                 return FALSE;
6602             }
6603         }
6604
6605       if (audit != NULL)
6606         {
6607           size_t indx;
6608
6609           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, audit,
6610                                       TRUE);
6611           if (indx == (size_t) -1
6612               || !_bfd_elf_add_dynamic_entry (info, DT_AUDIT, indx))
6613             return FALSE;
6614         }
6615
6616       if (depaudit != NULL)
6617         {
6618           size_t indx;
6619
6620           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, depaudit,
6621                                       TRUE);
6622           if (indx == (size_t) -1
6623               || !_bfd_elf_add_dynamic_entry (info, DT_DEPAUDIT, indx))
6624             return FALSE;
6625         }
6626
6627       eif.info = info;
6628       eif.failed = FALSE;
6629
6630       /* Find all symbols which were defined in a dynamic object and make
6631          the backend pick a reasonable value for them.  */
6632       elf_link_hash_traverse (elf_hash_table (info),
6633                               _bfd_elf_adjust_dynamic_symbol,
6634                               &eif);
6635       if (eif.failed)
6636         return FALSE;
6637
6638       /* Add some entries to the .dynamic section.  We fill in some of the
6639          values later, in bfd_elf_final_link, but we must add the entries
6640          now so that we know the final size of the .dynamic section.  */
6641
6642       /* If there are initialization and/or finalization functions to
6643          call then add the corresponding DT_INIT/DT_FINI entries.  */
6644       h = (info->init_function
6645            ? elf_link_hash_lookup (elf_hash_table (info),
6646                                    info->init_function, FALSE,
6647                                    FALSE, FALSE)
6648            : NULL);
6649       if (h != NULL
6650           && (h->ref_regular
6651               || h->def_regular))
6652         {
6653           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT, 0))
6654             return FALSE;
6655         }
6656       h = (info->fini_function
6657            ? elf_link_hash_lookup (elf_hash_table (info),
6658                                    info->fini_function, FALSE,
6659                                    FALSE, FALSE)
6660            : NULL);
6661       if (h != NULL
6662           && (h->ref_regular
6663               || h->def_regular))
6664         {
6665           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI, 0))
6666             return FALSE;
6667         }
6668
6669       s = bfd_get_section_by_name (output_bfd, ".preinit_array");
6670       if (s != NULL && s->linker_has_input)
6671         {
6672           /* DT_PREINIT_ARRAY is not allowed in shared library.  */
6673           if (! bfd_link_executable (info))
6674             {
6675               bfd *sub;
6676               asection *o;
6677
6678               for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
6679                 if (bfd_get_flavour (sub) == bfd_target_elf_flavour
6680                     && (o = sub->sections) != NULL
6681                     && o->sec_info_type != SEC_INFO_TYPE_JUST_SYMS)
6682                   for (o = sub->sections; o != NULL; o = o->next)
6683                     if (elf_section_data (o)->this_hdr.sh_type
6684                         == SHT_PREINIT_ARRAY)
6685                       {
6686                         _bfd_error_handler
6687                           (_("%B: .preinit_array section is not allowed in DSO"),
6688                            sub);
6689                         break;
6690                       }
6691
6692               bfd_set_error (bfd_error_nonrepresentable_section);
6693               return FALSE;
6694             }
6695
6696           if (!_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAY, 0)
6697               || !_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAYSZ, 0))
6698             return FALSE;
6699         }
6700       s = bfd_get_section_by_name (output_bfd, ".init_array");
6701       if (s != NULL && s->linker_has_input)
6702         {
6703           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAY, 0)
6704               || !_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAYSZ, 0))
6705             return FALSE;
6706         }
6707       s = bfd_get_section_by_name (output_bfd, ".fini_array");
6708       if (s != NULL && s->linker_has_input)
6709         {
6710           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAY, 0)
6711               || !_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAYSZ, 0))
6712             return FALSE;
6713         }
6714
6715       dynstr = bfd_get_linker_section (dynobj, ".dynstr");
6716       /* If .dynstr is excluded from the link, we don't want any of
6717          these tags.  Strictly, we should be checking each section
6718          individually;  This quick check covers for the case where
6719          someone does a /DISCARD/ : { *(*) }.  */
6720       if (dynstr != NULL && dynstr->output_section != bfd_abs_section_ptr)
6721         {
6722           bfd_size_type strsize;
6723
6724           strsize = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
6725           if ((info->emit_hash
6726                && !_bfd_elf_add_dynamic_entry (info, DT_HASH, 0))
6727               || (info->emit_gnu_hash
6728                   && !_bfd_elf_add_dynamic_entry (info, DT_GNU_HASH, 0))
6729               || !_bfd_elf_add_dynamic_entry (info, DT_STRTAB, 0)
6730               || !_bfd_elf_add_dynamic_entry (info, DT_SYMTAB, 0)
6731               || !_bfd_elf_add_dynamic_entry (info, DT_STRSZ, strsize)
6732               || !_bfd_elf_add_dynamic_entry (info, DT_SYMENT,
6733                                               bed->s->sizeof_sym))
6734             return FALSE;
6735         }
6736     }
6737
6738   if (! _bfd_elf_maybe_strip_eh_frame_hdr (info))
6739     return FALSE;
6740
6741   /* The backend must work out the sizes of all the other dynamic
6742      sections.  */
6743   if (dynobj != NULL
6744       && bed->elf_backend_size_dynamic_sections != NULL
6745       && ! (*bed->elf_backend_size_dynamic_sections) (output_bfd, info))
6746     return FALSE;
6747
6748   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6749     {
6750       unsigned long section_sym_count;
6751
6752       if (elf_tdata (output_bfd)->cverdefs)
6753         {
6754           unsigned int crefs = elf_tdata (output_bfd)->cverdefs;
6755
6756           if (!_bfd_elf_add_dynamic_entry (info, DT_VERDEF, 0)
6757               || !_bfd_elf_add_dynamic_entry (info, DT_VERDEFNUM, crefs))
6758             return FALSE;
6759         }
6760
6761       if ((info->new_dtags && info->flags) || (info->flags & DF_STATIC_TLS))
6762         {
6763           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS, info->flags))
6764             return FALSE;
6765         }
6766       else if (info->flags & DF_BIND_NOW)
6767         {
6768           if (!_bfd_elf_add_dynamic_entry (info, DT_BIND_NOW, 0))
6769             return FALSE;
6770         }
6771
6772       if (info->flags_1)
6773         {
6774           if (bfd_link_executable (info))
6775             info->flags_1 &= ~ (DF_1_INITFIRST
6776                                 | DF_1_NODELETE
6777                                 | DF_1_NOOPEN);
6778           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS_1, info->flags_1))
6779             return FALSE;
6780         }
6781
6782       if (elf_tdata (output_bfd)->cverrefs)
6783         {
6784           unsigned int crefs = elf_tdata (output_bfd)->cverrefs;
6785
6786           if (!_bfd_elf_add_dynamic_entry (info, DT_VERNEED, 0)
6787               || !_bfd_elf_add_dynamic_entry (info, DT_VERNEEDNUM, crefs))
6788             return FALSE;
6789         }
6790
6791       if ((elf_tdata (output_bfd)->cverrefs == 0
6792            && elf_tdata (output_bfd)->cverdefs == 0)
6793           || _bfd_elf_link_renumber_dynsyms (output_bfd, info,
6794                                              &section_sym_count) <= 1)
6795         {
6796           asection *s;
6797
6798           s = bfd_get_linker_section (dynobj, ".gnu.version");
6799           s->flags |= SEC_EXCLUDE;
6800         }
6801     }
6802   return TRUE;
6803 }
6804
6805 /* Find the first non-excluded output section.  We'll use its
6806    section symbol for some emitted relocs.  */
6807 void
6808 _bfd_elf_init_1_index_section (bfd *output_bfd, struct bfd_link_info *info)
6809 {
6810   asection *s;
6811
6812   for (s = output_bfd->sections; s != NULL; s = s->next)
6813     if ((s->flags & (SEC_EXCLUDE | SEC_ALLOC)) == SEC_ALLOC
6814         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6815       {
6816         elf_hash_table (info)->text_index_section = s;
6817         break;
6818       }
6819 }
6820
6821 /* Find two non-excluded output sections, one for code, one for data.
6822    We'll use their section symbols for some emitted relocs.  */
6823 void
6824 _bfd_elf_init_2_index_sections (bfd *output_bfd, struct bfd_link_info *info)
6825 {
6826   asection *s;
6827
6828   /* Data first, since setting text_index_section changes
6829      _bfd_elf_link_omit_section_dynsym.  */
6830   for (s = output_bfd->sections; s != NULL; s = s->next)
6831     if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY)) == SEC_ALLOC)
6832         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6833       {
6834         elf_hash_table (info)->data_index_section = s;
6835         break;
6836       }
6837
6838   for (s = output_bfd->sections; s != NULL; s = s->next)
6839     if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY))
6840          == (SEC_ALLOC | SEC_READONLY))
6841         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6842       {
6843         elf_hash_table (info)->text_index_section = s;
6844         break;
6845       }
6846
6847   if (elf_hash_table (info)->text_index_section == NULL)
6848     elf_hash_table (info)->text_index_section
6849       = elf_hash_table (info)->data_index_section;
6850 }
6851
6852 bfd_boolean
6853 bfd_elf_size_dynsym_hash_dynstr (bfd *output_bfd, struct bfd_link_info *info)
6854 {
6855   const struct elf_backend_data *bed;
6856   unsigned long section_sym_count;
6857   bfd_size_type dynsymcount = 0;
6858
6859   if (!is_elf_hash_table (info->hash))
6860     return TRUE;
6861
6862   bed = get_elf_backend_data (output_bfd);
6863   (*bed->elf_backend_init_index_section) (output_bfd, info);
6864
6865   /* Assign dynsym indices.  In a shared library we generate a section
6866      symbol for each output section, which come first.  Next come all
6867      of the back-end allocated local dynamic syms, followed by the rest
6868      of the global symbols.
6869
6870      This is usually not needed for static binaries, however backends
6871      can request to always do it, e.g. the MIPS backend uses dynamic
6872      symbol counts to lay out GOT, which will be produced in the
6873      presence of GOT relocations even in static binaries (holding fixed
6874      data in that case, to satisfy those relocations).  */
6875
6876   if (elf_hash_table (info)->dynamic_sections_created
6877       || bed->always_renumber_dynsyms)
6878     dynsymcount = _bfd_elf_link_renumber_dynsyms (output_bfd, info,
6879                                                   &section_sym_count);
6880
6881   if (elf_hash_table (info)->dynamic_sections_created)
6882     {
6883       bfd *dynobj;
6884       asection *s;
6885       unsigned int dtagcount;
6886
6887       dynobj = elf_hash_table (info)->dynobj;
6888
6889       /* Work out the size of the symbol version section.  */
6890       s = bfd_get_linker_section (dynobj, ".gnu.version");
6891       BFD_ASSERT (s != NULL);
6892       if ((s->flags & SEC_EXCLUDE) == 0)
6893         {
6894           s->size = dynsymcount * sizeof (Elf_External_Versym);
6895           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6896           if (s->contents == NULL)
6897             return FALSE;
6898
6899           if (!_bfd_elf_add_dynamic_entry (info, DT_VERSYM, 0))
6900             return FALSE;
6901         }
6902
6903       /* Set the size of the .dynsym and .hash sections.  We counted
6904          the number of dynamic symbols in elf_link_add_object_symbols.
6905          We will build the contents of .dynsym and .hash when we build
6906          the final symbol table, because until then we do not know the
6907          correct value to give the symbols.  We built the .dynstr
6908          section as we went along in elf_link_add_object_symbols.  */
6909       s = elf_hash_table (info)->dynsym;
6910       BFD_ASSERT (s != NULL);
6911       s->size = dynsymcount * bed->s->sizeof_sym;
6912
6913       s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6914       if (s->contents == NULL)
6915         return FALSE;
6916
6917       /* The first entry in .dynsym is a dummy symbol.  Clear all the
6918          section syms, in case we don't output them all.  */
6919       ++section_sym_count;
6920       memset (s->contents, 0, section_sym_count * bed->s->sizeof_sym);
6921
6922       elf_hash_table (info)->bucketcount = 0;
6923
6924       /* Compute the size of the hashing table.  As a side effect this
6925          computes the hash values for all the names we export.  */
6926       if (info->emit_hash)
6927         {
6928           unsigned long int *hashcodes;
6929           struct hash_codes_info hashinf;
6930           bfd_size_type amt;
6931           unsigned long int nsyms;
6932           size_t bucketcount;
6933           size_t hash_entry_size;
6934
6935           /* Compute the hash values for all exported symbols.  At the same
6936              time store the values in an array so that we could use them for
6937              optimizations.  */
6938           amt = dynsymcount * sizeof (unsigned long int);
6939           hashcodes = (unsigned long int *) bfd_malloc (amt);
6940           if (hashcodes == NULL)
6941             return FALSE;
6942           hashinf.hashcodes = hashcodes;
6943           hashinf.error = FALSE;
6944
6945           /* Put all hash values in HASHCODES.  */
6946           elf_link_hash_traverse (elf_hash_table (info),
6947                                   elf_collect_hash_codes, &hashinf);
6948           if (hashinf.error)
6949             {
6950               free (hashcodes);
6951               return FALSE;
6952             }
6953
6954           nsyms = hashinf.hashcodes - hashcodes;
6955           bucketcount
6956             = compute_bucket_count (info, hashcodes, nsyms, 0);
6957           free (hashcodes);
6958
6959           if (bucketcount == 0 && nsyms > 0)
6960             return FALSE;
6961
6962           elf_hash_table (info)->bucketcount = bucketcount;
6963
6964           s = bfd_get_linker_section (dynobj, ".hash");
6965           BFD_ASSERT (s != NULL);
6966           hash_entry_size = elf_section_data (s)->this_hdr.sh_entsize;
6967           s->size = ((2 + bucketcount + dynsymcount) * hash_entry_size);
6968           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6969           if (s->contents == NULL)
6970             return FALSE;
6971
6972           bfd_put (8 * hash_entry_size, output_bfd, bucketcount, s->contents);
6973           bfd_put (8 * hash_entry_size, output_bfd, dynsymcount,
6974                    s->contents + hash_entry_size);
6975         }
6976
6977       if (info->emit_gnu_hash)
6978         {
6979           size_t i, cnt;
6980           unsigned char *contents;
6981           struct collect_gnu_hash_codes cinfo;
6982           bfd_size_type amt;
6983           size_t bucketcount;
6984
6985           memset (&cinfo, 0, sizeof (cinfo));
6986
6987           /* Compute the hash values for all exported symbols.  At the same
6988              time store the values in an array so that we could use them for
6989              optimizations.  */
6990           amt = dynsymcount * 2 * sizeof (unsigned long int);
6991           cinfo.hashcodes = (long unsigned int *) bfd_malloc (amt);
6992           if (cinfo.hashcodes == NULL)
6993             return FALSE;
6994
6995           cinfo.hashval = cinfo.hashcodes + dynsymcount;
6996           cinfo.min_dynindx = -1;
6997           cinfo.output_bfd = output_bfd;
6998           cinfo.bed = bed;
6999
7000           /* Put all hash values in HASHCODES.  */
7001           elf_link_hash_traverse (elf_hash_table (info),
7002                                   elf_collect_gnu_hash_codes, &cinfo);
7003           if (cinfo.error)
7004             {
7005               free (cinfo.hashcodes);
7006               return FALSE;
7007             }
7008
7009           bucketcount
7010             = compute_bucket_count (info, cinfo.hashcodes, cinfo.nsyms, 1);
7011
7012           if (bucketcount == 0)
7013             {
7014               free (cinfo.hashcodes);
7015               return FALSE;
7016             }
7017
7018           s = bfd_get_linker_section (dynobj, ".gnu.hash");
7019           BFD_ASSERT (s != NULL);
7020
7021           if (cinfo.nsyms == 0)
7022             {
7023               /* Empty .gnu.hash section is special.  */
7024               BFD_ASSERT (cinfo.min_dynindx == -1);
7025               free (cinfo.hashcodes);
7026               s->size = 5 * 4 + bed->s->arch_size / 8;
7027               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
7028               if (contents == NULL)
7029                 return FALSE;
7030               s->contents = contents;
7031               /* 1 empty bucket.  */
7032               bfd_put_32 (output_bfd, 1, contents);
7033               /* SYMIDX above the special symbol 0.  */
7034               bfd_put_32 (output_bfd, 1, contents + 4);
7035               /* Just one word for bitmask.  */
7036               bfd_put_32 (output_bfd, 1, contents + 8);
7037               /* Only hash fn bloom filter.  */
7038               bfd_put_32 (output_bfd, 0, contents + 12);
7039               /* No hashes are valid - empty bitmask.  */
7040               bfd_put (bed->s->arch_size, output_bfd, 0, contents + 16);
7041               /* No hashes in the only bucket.  */
7042               bfd_put_32 (output_bfd, 0,
7043                           contents + 16 + bed->s->arch_size / 8);
7044             }
7045           else
7046             {
7047               unsigned long int maskwords, maskbitslog2, x;
7048               BFD_ASSERT (cinfo.min_dynindx != -1);
7049
7050               x = cinfo.nsyms;
7051               maskbitslog2 = 1;
7052               while ((x >>= 1) != 0)
7053                 ++maskbitslog2;
7054               if (maskbitslog2 < 3)
7055                 maskbitslog2 = 5;
7056               else if ((1 << (maskbitslog2 - 2)) & cinfo.nsyms)
7057                 maskbitslog2 = maskbitslog2 + 3;
7058               else
7059                 maskbitslog2 = maskbitslog2 + 2;
7060               if (bed->s->arch_size == 64)
7061                 {
7062                   if (maskbitslog2 == 5)
7063                     maskbitslog2 = 6;
7064                   cinfo.shift1 = 6;
7065                 }
7066               else
7067                 cinfo.shift1 = 5;
7068               cinfo.mask = (1 << cinfo.shift1) - 1;
7069               cinfo.shift2 = maskbitslog2;
7070               cinfo.maskbits = 1 << maskbitslog2;
7071               maskwords = 1 << (maskbitslog2 - cinfo.shift1);
7072               amt = bucketcount * sizeof (unsigned long int) * 2;
7073               amt += maskwords * sizeof (bfd_vma);
7074               cinfo.bitmask = (bfd_vma *) bfd_malloc (amt);
7075               if (cinfo.bitmask == NULL)
7076                 {
7077                   free (cinfo.hashcodes);
7078                   return FALSE;
7079                 }
7080
7081               cinfo.counts = (long unsigned int *) (cinfo.bitmask + maskwords);
7082               cinfo.indx = cinfo.counts + bucketcount;
7083               cinfo.symindx = dynsymcount - cinfo.nsyms;
7084               memset (cinfo.bitmask, 0, maskwords * sizeof (bfd_vma));
7085
7086               /* Determine how often each hash bucket is used.  */
7087               memset (cinfo.counts, 0, bucketcount * sizeof (cinfo.counts[0]));
7088               for (i = 0; i < cinfo.nsyms; ++i)
7089                 ++cinfo.counts[cinfo.hashcodes[i] % bucketcount];
7090
7091               for (i = 0, cnt = cinfo.symindx; i < bucketcount; ++i)
7092                 if (cinfo.counts[i] != 0)
7093                   {
7094                     cinfo.indx[i] = cnt;
7095                     cnt += cinfo.counts[i];
7096                   }
7097               BFD_ASSERT (cnt == dynsymcount);
7098               cinfo.bucketcount = bucketcount;
7099               cinfo.local_indx = cinfo.min_dynindx;
7100
7101               s->size = (4 + bucketcount + cinfo.nsyms) * 4;
7102               s->size += cinfo.maskbits / 8;
7103               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
7104               if (contents == NULL)
7105                 {
7106                   free (cinfo.bitmask);
7107                   free (cinfo.hashcodes);
7108                   return FALSE;
7109                 }
7110
7111               s->contents = contents;
7112               bfd_put_32 (output_bfd, bucketcount, contents);
7113               bfd_put_32 (output_bfd, cinfo.symindx, contents + 4);
7114               bfd_put_32 (output_bfd, maskwords, contents + 8);
7115               bfd_put_32 (output_bfd, cinfo.shift2, contents + 12);
7116               contents += 16 + cinfo.maskbits / 8;
7117
7118               for (i = 0; i < bucketcount; ++i)
7119                 {
7120                   if (cinfo.counts[i] == 0)
7121                     bfd_put_32 (output_bfd, 0, contents);
7122                   else
7123                     bfd_put_32 (output_bfd, cinfo.indx[i], contents);
7124                   contents += 4;
7125                 }
7126
7127               cinfo.contents = contents;
7128
7129               /* Renumber dynamic symbols, populate .gnu.hash section.  */
7130               elf_link_hash_traverse (elf_hash_table (info),
7131                                       elf_renumber_gnu_hash_syms, &cinfo);
7132
7133               contents = s->contents + 16;
7134               for (i = 0; i < maskwords; ++i)
7135                 {
7136                   bfd_put (bed->s->arch_size, output_bfd, cinfo.bitmask[i],
7137                            contents);
7138                   contents += bed->s->arch_size / 8;
7139                 }
7140
7141               free (cinfo.bitmask);
7142               free (cinfo.hashcodes);
7143             }
7144         }
7145
7146       s = bfd_get_linker_section (dynobj, ".dynstr");
7147       BFD_ASSERT (s != NULL);
7148
7149       elf_finalize_dynstr (output_bfd, info);
7150
7151       s->size = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
7152
7153       for (dtagcount = 0; dtagcount <= info->spare_dynamic_tags; ++dtagcount)
7154         if (!_bfd_elf_add_dynamic_entry (info, DT_NULL, 0))
7155           return FALSE;
7156     }
7157
7158   return TRUE;
7159 }
7160 \f
7161 /* Make sure sec_info_type is cleared if sec_info is cleared too.  */
7162
7163 static void
7164 merge_sections_remove_hook (bfd *abfd ATTRIBUTE_UNUSED,
7165                             asection *sec)
7166 {
7167   BFD_ASSERT (sec->sec_info_type == SEC_INFO_TYPE_MERGE);
7168   sec->sec_info_type = SEC_INFO_TYPE_NONE;
7169 }
7170
7171 /* Finish SHF_MERGE section merging.  */
7172
7173 bfd_boolean
7174 _bfd_elf_merge_sections (bfd *obfd, struct bfd_link_info *info)
7175 {
7176   bfd *ibfd;
7177   asection *sec;
7178
7179   if (!is_elf_hash_table (info->hash))
7180     return FALSE;
7181
7182   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
7183     if ((ibfd->flags & DYNAMIC) == 0
7184         && bfd_get_flavour (ibfd) == bfd_target_elf_flavour
7185         && (elf_elfheader (ibfd)->e_ident[EI_CLASS]
7186             == get_elf_backend_data (obfd)->s->elfclass))
7187       for (sec = ibfd->sections; sec != NULL; sec = sec->next)
7188         if ((sec->flags & SEC_MERGE) != 0
7189             && !bfd_is_abs_section (sec->output_section))
7190           {
7191             struct bfd_elf_section_data *secdata;
7192
7193             secdata = elf_section_data (sec);
7194             if (! _bfd_add_merge_section (obfd,
7195                                           &elf_hash_table (info)->merge_info,
7196                                           sec, &secdata->sec_info))
7197               return FALSE;
7198             else if (secdata->sec_info)
7199               sec->sec_info_type = SEC_INFO_TYPE_MERGE;
7200           }
7201
7202   if (elf_hash_table (info)->merge_info != NULL)
7203     _bfd_merge_sections (obfd, info, elf_hash_table (info)->merge_info,
7204                          merge_sections_remove_hook);
7205   return TRUE;
7206 }
7207
7208 /* Create an entry in an ELF linker hash table.  */
7209
7210 struct bfd_hash_entry *
7211 _bfd_elf_link_hash_newfunc (struct bfd_hash_entry *entry,
7212                             struct bfd_hash_table *table,
7213                             const char *string)
7214 {
7215   /* Allocate the structure if it has not already been allocated by a
7216      subclass.  */
7217   if (entry == NULL)
7218     {
7219       entry = (struct bfd_hash_entry *)
7220         bfd_hash_allocate (table, sizeof (struct elf_link_hash_entry));
7221       if (entry == NULL)
7222         return entry;
7223     }
7224
7225   /* Call the allocation method of the superclass.  */
7226   entry = _bfd_link_hash_newfunc (entry, table, string);
7227   if (entry != NULL)
7228     {
7229       struct elf_link_hash_entry *ret = (struct elf_link_hash_entry *) entry;
7230       struct elf_link_hash_table *htab = (struct elf_link_hash_table *) table;
7231
7232       /* Set local fields.  */
7233       ret->indx = -1;
7234       ret->dynindx = -1;
7235       ret->got = htab->init_got_refcount;
7236       ret->plt = htab->init_plt_refcount;
7237       memset (&ret->size, 0, (sizeof (struct elf_link_hash_entry)
7238                               - offsetof (struct elf_link_hash_entry, size)));
7239       /* Assume that we have been called by a non-ELF symbol reader.
7240          This flag is then reset by the code which reads an ELF input
7241          file.  This ensures that a symbol created by a non-ELF symbol
7242          reader will have the flag set correctly.  */
7243       ret->non_elf = 1;
7244     }
7245
7246   return entry;
7247 }
7248
7249 /* Copy data from an indirect symbol to its direct symbol, hiding the
7250    old indirect symbol.  Also used for copying flags to a weakdef.  */
7251
7252 void
7253 _bfd_elf_link_hash_copy_indirect (struct bfd_link_info *info,
7254                                   struct elf_link_hash_entry *dir,
7255                                   struct elf_link_hash_entry *ind)
7256 {
7257   struct elf_link_hash_table *htab;
7258
7259   /* Copy down any references that we may have already seen to the
7260      symbol which just became indirect.  */
7261
7262   if (dir->versioned != versioned_hidden)
7263     dir->ref_dynamic |= ind->ref_dynamic;
7264   dir->ref_regular |= ind->ref_regular;
7265   dir->ref_regular_nonweak |= ind->ref_regular_nonweak;
7266   dir->non_got_ref |= ind->non_got_ref;
7267   dir->needs_plt |= ind->needs_plt;
7268   dir->pointer_equality_needed |= ind->pointer_equality_needed;
7269
7270   if (ind->root.type != bfd_link_hash_indirect)
7271     return;
7272
7273   /* Copy over the global and procedure linkage table refcount entries.
7274      These may have been already set up by a check_relocs routine.  */
7275   htab = elf_hash_table (info);
7276   if (ind->got.refcount > htab->init_got_refcount.refcount)
7277     {
7278       if (dir->got.refcount < 0)
7279         dir->got.refcount = 0;
7280       dir->got.refcount += ind->got.refcount;
7281       ind->got.refcount = htab->init_got_refcount.refcount;
7282     }
7283
7284   if (ind->plt.refcount > htab->init_plt_refcount.refcount)
7285     {
7286       if (dir->plt.refcount < 0)
7287         dir->plt.refcount = 0;
7288       dir->plt.refcount += ind->plt.refcount;
7289       ind->plt.refcount = htab->init_plt_refcount.refcount;
7290     }
7291
7292   if (ind->dynindx != -1)
7293     {
7294       if (dir->dynindx != -1)
7295         _bfd_elf_strtab_delref (htab->dynstr, dir->dynstr_index);
7296       dir->dynindx = ind->dynindx;
7297       dir->dynstr_index = ind->dynstr_index;
7298       ind->dynindx = -1;
7299       ind->dynstr_index = 0;
7300     }
7301 }
7302
7303 void
7304 _bfd_elf_link_hash_hide_symbol (struct bfd_link_info *info,
7305                                 struct elf_link_hash_entry *h,
7306                                 bfd_boolean force_local)
7307 {
7308   /* STT_GNU_IFUNC symbol must go through PLT.  */
7309   if (h->type != STT_GNU_IFUNC)
7310     {
7311       h->plt = elf_hash_table (info)->init_plt_offset;
7312       h->needs_plt = 0;
7313     }
7314   if (force_local)
7315     {
7316       h->forced_local = 1;
7317       if (h->dynindx != -1)
7318         {
7319           _bfd_elf_strtab_delref (elf_hash_table (info)->dynstr,
7320                                   h->dynstr_index);
7321           h->dynindx = -1;
7322           h->dynstr_index = 0;
7323         }
7324     }
7325 }
7326
7327 /* Initialize an ELF linker hash table.  *TABLE has been zeroed by our
7328    caller.  */
7329
7330 bfd_boolean
7331 _bfd_elf_link_hash_table_init
7332   (struct elf_link_hash_table *table,
7333    bfd *abfd,
7334    struct bfd_hash_entry *(*newfunc) (struct bfd_hash_entry *,
7335                                       struct bfd_hash_table *,
7336                                       const char *),
7337    unsigned int entsize,
7338    enum elf_target_id target_id)
7339 {
7340   bfd_boolean ret;
7341   int can_refcount = get_elf_backend_data (abfd)->can_refcount;
7342
7343   table->init_got_refcount.refcount = can_refcount - 1;
7344   table->init_plt_refcount.refcount = can_refcount - 1;
7345   table->init_got_offset.offset = -(bfd_vma) 1;
7346   table->init_plt_offset.offset = -(bfd_vma) 1;
7347   /* The first dynamic symbol is a dummy.  */
7348   table->dynsymcount = 1;
7349
7350   ret = _bfd_link_hash_table_init (&table->root, abfd, newfunc, entsize);
7351
7352   table->root.type = bfd_link_elf_hash_table;
7353   table->hash_table_id = target_id;
7354
7355   return ret;
7356 }
7357
7358 /* Create an ELF linker hash table.  */
7359
7360 struct bfd_link_hash_table *
7361 _bfd_elf_link_hash_table_create (bfd *abfd)
7362 {
7363   struct elf_link_hash_table *ret;
7364   bfd_size_type amt = sizeof (struct elf_link_hash_table);
7365
7366   ret = (struct elf_link_hash_table *) bfd_zmalloc (amt);
7367   if (ret == NULL)
7368     return NULL;
7369
7370   if (! _bfd_elf_link_hash_table_init (ret, abfd, _bfd_elf_link_hash_newfunc,
7371                                        sizeof (struct elf_link_hash_entry),
7372                                        GENERIC_ELF_DATA))
7373     {
7374       free (ret);
7375       return NULL;
7376     }
7377   ret->root.hash_table_free = _bfd_elf_link_hash_table_free;
7378
7379   return &ret->root;
7380 }
7381
7382 /* Destroy an ELF linker hash table.  */
7383
7384 void
7385 _bfd_elf_link_hash_table_free (bfd *obfd)
7386 {
7387   struct elf_link_hash_table *htab;
7388
7389   htab = (struct elf_link_hash_table *) obfd->link.hash;
7390   if (htab->dynstr != NULL)
7391     _bfd_elf_strtab_free (htab->dynstr);
7392   _bfd_merge_sections_free (htab->merge_info);
7393   _bfd_generic_link_hash_table_free (obfd);
7394 }
7395
7396 /* This is a hook for the ELF emulation code in the generic linker to
7397    tell the backend linker what file name to use for the DT_NEEDED
7398    entry for a dynamic object.  */
7399
7400 void
7401 bfd_elf_set_dt_needed_name (bfd *abfd, const char *name)
7402 {
7403   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7404       && bfd_get_format (abfd) == bfd_object)
7405     elf_dt_name (abfd) = name;
7406 }
7407
7408 int
7409 bfd_elf_get_dyn_lib_class (bfd *abfd)
7410 {
7411   int lib_class;
7412   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7413       && bfd_get_format (abfd) == bfd_object)
7414     lib_class = elf_dyn_lib_class (abfd);
7415   else
7416     lib_class = 0;
7417   return lib_class;
7418 }
7419
7420 void
7421 bfd_elf_set_dyn_lib_class (bfd *abfd, enum dynamic_lib_link_class lib_class)
7422 {
7423   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7424       && bfd_get_format (abfd) == bfd_object)
7425     elf_dyn_lib_class (abfd) = lib_class;
7426 }
7427
7428 /* Get the list of DT_NEEDED entries for a link.  This is a hook for
7429    the linker ELF emulation code.  */
7430
7431 struct bfd_link_needed_list *
7432 bfd_elf_get_needed_list (bfd *abfd ATTRIBUTE_UNUSED,
7433                          struct bfd_link_info *info)
7434 {
7435   if (! is_elf_hash_table (info->hash))
7436     return NULL;
7437   return elf_hash_table (info)->needed;
7438 }
7439
7440 /* Get the list of DT_RPATH/DT_RUNPATH entries for a link.  This is a
7441    hook for the linker ELF emulation code.  */
7442
7443 struct bfd_link_needed_list *
7444 bfd_elf_get_runpath_list (bfd *abfd ATTRIBUTE_UNUSED,
7445                           struct bfd_link_info *info)
7446 {
7447   if (! is_elf_hash_table (info->hash))
7448     return NULL;
7449   return elf_hash_table (info)->runpath;
7450 }
7451
7452 /* Get the name actually used for a dynamic object for a link.  This
7453    is the SONAME entry if there is one.  Otherwise, it is the string
7454    passed to bfd_elf_set_dt_needed_name, or it is the filename.  */
7455
7456 const char *
7457 bfd_elf_get_dt_soname (bfd *abfd)
7458 {
7459   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7460       && bfd_get_format (abfd) == bfd_object)
7461     return elf_dt_name (abfd);
7462   return NULL;
7463 }
7464
7465 /* Get the list of DT_NEEDED entries from a BFD.  This is a hook for
7466    the ELF linker emulation code.  */
7467
7468 bfd_boolean
7469 bfd_elf_get_bfd_needed_list (bfd *abfd,
7470                              struct bfd_link_needed_list **pneeded)
7471 {
7472   asection *s;
7473   bfd_byte *dynbuf = NULL;
7474   unsigned int elfsec;
7475   unsigned long shlink;
7476   bfd_byte *extdyn, *extdynend;
7477   size_t extdynsize;
7478   void (*swap_dyn_in) (bfd *, const void *, Elf_Internal_Dyn *);
7479
7480   *pneeded = NULL;
7481
7482   if (bfd_get_flavour (abfd) != bfd_target_elf_flavour
7483       || bfd_get_format (abfd) != bfd_object)
7484     return TRUE;
7485
7486   s = bfd_get_section_by_name (abfd, ".dynamic");
7487   if (s == NULL || s->size == 0)
7488     return TRUE;
7489
7490   if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
7491     goto error_return;
7492
7493   elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
7494   if (elfsec == SHN_BAD)
7495     goto error_return;
7496
7497   shlink = elf_elfsections (abfd)[elfsec]->sh_link;
7498
7499   extdynsize = get_elf_backend_data (abfd)->s->sizeof_dyn;
7500   swap_dyn_in = get_elf_backend_data (abfd)->s->swap_dyn_in;
7501
7502   extdyn = dynbuf;
7503   extdynend = extdyn + s->size;
7504   for (; extdyn < extdynend; extdyn += extdynsize)
7505     {
7506       Elf_Internal_Dyn dyn;
7507
7508       (*swap_dyn_in) (abfd, extdyn, &dyn);
7509
7510       if (dyn.d_tag == DT_NULL)
7511         break;
7512
7513       if (dyn.d_tag == DT_NEEDED)
7514         {
7515           const char *string;
7516           struct bfd_link_needed_list *l;
7517           unsigned int tagv = dyn.d_un.d_val;
7518           bfd_size_type amt;
7519
7520           string = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
7521           if (string == NULL)
7522             goto error_return;
7523
7524           amt = sizeof *l;
7525           l = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
7526           if (l == NULL)
7527             goto error_return;
7528
7529           l->by = abfd;
7530           l->name = string;
7531           l->next = *pneeded;
7532           *pneeded = l;
7533         }
7534     }
7535
7536   free (dynbuf);
7537
7538   return TRUE;
7539
7540  error_return:
7541   if (dynbuf != NULL)
7542     free (dynbuf);
7543   return FALSE;
7544 }
7545
7546 struct elf_symbuf_symbol
7547 {
7548   unsigned long st_name;        /* Symbol name, index in string tbl */
7549   unsigned char st_info;        /* Type and binding attributes */
7550   unsigned char st_other;       /* Visibilty, and target specific */
7551 };
7552
7553 struct elf_symbuf_head
7554 {
7555   struct elf_symbuf_symbol *ssym;
7556   size_t count;
7557   unsigned int st_shndx;
7558 };
7559
7560 struct elf_symbol
7561 {
7562   union
7563     {
7564       Elf_Internal_Sym *isym;
7565       struct elf_symbuf_symbol *ssym;
7566     } u;
7567   const char *name;
7568 };
7569
7570 /* Sort references to symbols by ascending section number.  */
7571
7572 static int
7573 elf_sort_elf_symbol (const void *arg1, const void *arg2)
7574 {
7575   const Elf_Internal_Sym *s1 = *(const Elf_Internal_Sym **) arg1;
7576   const Elf_Internal_Sym *s2 = *(const Elf_Internal_Sym **) arg2;
7577
7578   return s1->st_shndx - s2->st_shndx;
7579 }
7580
7581 static int
7582 elf_sym_name_compare (const void *arg1, const void *arg2)
7583 {
7584   const struct elf_symbol *s1 = (const struct elf_symbol *) arg1;
7585   const struct elf_symbol *s2 = (const struct elf_symbol *) arg2;
7586   return strcmp (s1->name, s2->name);
7587 }
7588
7589 static struct elf_symbuf_head *
7590 elf_create_symbuf (size_t symcount, Elf_Internal_Sym *isymbuf)
7591 {
7592   Elf_Internal_Sym **ind, **indbufend, **indbuf;
7593   struct elf_symbuf_symbol *ssym;
7594   struct elf_symbuf_head *ssymbuf, *ssymhead;
7595   size_t i, shndx_count, total_size;
7596
7597   indbuf = (Elf_Internal_Sym **) bfd_malloc2 (symcount, sizeof (*indbuf));
7598   if (indbuf == NULL)
7599     return NULL;
7600
7601   for (ind = indbuf, i = 0; i < symcount; i++)
7602     if (isymbuf[i].st_shndx != SHN_UNDEF)
7603       *ind++ = &isymbuf[i];
7604   indbufend = ind;
7605
7606   qsort (indbuf, indbufend - indbuf, sizeof (Elf_Internal_Sym *),
7607          elf_sort_elf_symbol);
7608
7609   shndx_count = 0;
7610   if (indbufend > indbuf)
7611     for (ind = indbuf, shndx_count++; ind < indbufend - 1; ind++)
7612       if (ind[0]->st_shndx != ind[1]->st_shndx)
7613         shndx_count++;
7614
7615   total_size = ((shndx_count + 1) * sizeof (*ssymbuf)
7616                 + (indbufend - indbuf) * sizeof (*ssym));
7617   ssymbuf = (struct elf_symbuf_head *) bfd_malloc (total_size);
7618   if (ssymbuf == NULL)
7619     {
7620       free (indbuf);
7621       return NULL;
7622     }
7623
7624   ssym = (struct elf_symbuf_symbol *) (ssymbuf + shndx_count + 1);
7625   ssymbuf->ssym = NULL;
7626   ssymbuf->count = shndx_count;
7627   ssymbuf->st_shndx = 0;
7628   for (ssymhead = ssymbuf, ind = indbuf; ind < indbufend; ssym++, ind++)
7629     {
7630       if (ind == indbuf || ssymhead->st_shndx != (*ind)->st_shndx)
7631         {
7632           ssymhead++;
7633           ssymhead->ssym = ssym;
7634           ssymhead->count = 0;
7635           ssymhead->st_shndx = (*ind)->st_shndx;
7636         }
7637       ssym->st_name = (*ind)->st_name;
7638       ssym->st_info = (*ind)->st_info;
7639       ssym->st_other = (*ind)->st_other;
7640       ssymhead->count++;
7641     }
7642   BFD_ASSERT ((size_t) (ssymhead - ssymbuf) == shndx_count
7643               && (((bfd_hostptr_t) ssym - (bfd_hostptr_t) ssymbuf)
7644                   == total_size));
7645
7646   free (indbuf);
7647   return ssymbuf;
7648 }
7649
7650 /* Check if 2 sections define the same set of local and global
7651    symbols.  */
7652
7653 static bfd_boolean
7654 bfd_elf_match_symbols_in_sections (asection *sec1, asection *sec2,
7655                                    struct bfd_link_info *info)
7656 {
7657   bfd *bfd1, *bfd2;
7658   const struct elf_backend_data *bed1, *bed2;
7659   Elf_Internal_Shdr *hdr1, *hdr2;
7660   size_t symcount1, symcount2;
7661   Elf_Internal_Sym *isymbuf1, *isymbuf2;
7662   struct elf_symbuf_head *ssymbuf1, *ssymbuf2;
7663   Elf_Internal_Sym *isym, *isymend;
7664   struct elf_symbol *symtable1 = NULL, *symtable2 = NULL;
7665   size_t count1, count2, i;
7666   unsigned int shndx1, shndx2;
7667   bfd_boolean result;
7668
7669   bfd1 = sec1->owner;
7670   bfd2 = sec2->owner;
7671
7672   /* Both sections have to be in ELF.  */
7673   if (bfd_get_flavour (bfd1) != bfd_target_elf_flavour
7674       || bfd_get_flavour (bfd2) != bfd_target_elf_flavour)
7675     return FALSE;
7676
7677   if (elf_section_type (sec1) != elf_section_type (sec2))
7678     return FALSE;
7679
7680   shndx1 = _bfd_elf_section_from_bfd_section (bfd1, sec1);
7681   shndx2 = _bfd_elf_section_from_bfd_section (bfd2, sec2);
7682   if (shndx1 == SHN_BAD || shndx2 == SHN_BAD)
7683     return FALSE;
7684
7685   bed1 = get_elf_backend_data (bfd1);
7686   bed2 = get_elf_backend_data (bfd2);
7687   hdr1 = &elf_tdata (bfd1)->symtab_hdr;
7688   symcount1 = hdr1->sh_size / bed1->s->sizeof_sym;
7689   hdr2 = &elf_tdata (bfd2)->symtab_hdr;
7690   symcount2 = hdr2->sh_size / bed2->s->sizeof_sym;
7691
7692   if (symcount1 == 0 || symcount2 == 0)
7693     return FALSE;
7694
7695   result = FALSE;
7696   isymbuf1 = NULL;
7697   isymbuf2 = NULL;
7698   ssymbuf1 = (struct elf_symbuf_head *) elf_tdata (bfd1)->symbuf;
7699   ssymbuf2 = (struct elf_symbuf_head *) elf_tdata (bfd2)->symbuf;
7700
7701   if (ssymbuf1 == NULL)
7702     {
7703       isymbuf1 = bfd_elf_get_elf_syms (bfd1, hdr1, symcount1, 0,
7704                                        NULL, NULL, NULL);
7705       if (isymbuf1 == NULL)
7706         goto done;
7707
7708       if (!info->reduce_memory_overheads)
7709         elf_tdata (bfd1)->symbuf = ssymbuf1
7710           = elf_create_symbuf (symcount1, isymbuf1);
7711     }
7712
7713   if (ssymbuf1 == NULL || ssymbuf2 == NULL)
7714     {
7715       isymbuf2 = bfd_elf_get_elf_syms (bfd2, hdr2, symcount2, 0,
7716                                        NULL, NULL, NULL);
7717       if (isymbuf2 == NULL)
7718         goto done;
7719
7720       if (ssymbuf1 != NULL && !info->reduce_memory_overheads)
7721         elf_tdata (bfd2)->symbuf = ssymbuf2
7722           = elf_create_symbuf (symcount2, isymbuf2);
7723     }
7724
7725   if (ssymbuf1 != NULL && ssymbuf2 != NULL)
7726     {
7727       /* Optimized faster version.  */
7728       size_t lo, hi, mid;
7729       struct elf_symbol *symp;
7730       struct elf_symbuf_symbol *ssym, *ssymend;
7731
7732       lo = 0;
7733       hi = ssymbuf1->count;
7734       ssymbuf1++;
7735       count1 = 0;
7736       while (lo < hi)
7737         {
7738           mid = (lo + hi) / 2;
7739           if (shndx1 < ssymbuf1[mid].st_shndx)
7740             hi = mid;
7741           else if (shndx1 > ssymbuf1[mid].st_shndx)
7742             lo = mid + 1;
7743           else
7744             {
7745               count1 = ssymbuf1[mid].count;
7746               ssymbuf1 += mid;
7747               break;
7748             }
7749         }
7750
7751       lo = 0;
7752       hi = ssymbuf2->count;
7753       ssymbuf2++;
7754       count2 = 0;
7755       while (lo < hi)
7756         {
7757           mid = (lo + hi) / 2;
7758           if (shndx2 < ssymbuf2[mid].st_shndx)
7759             hi = mid;
7760           else if (shndx2 > ssymbuf2[mid].st_shndx)
7761             lo = mid + 1;
7762           else
7763             {
7764               count2 = ssymbuf2[mid].count;
7765               ssymbuf2 += mid;
7766               break;
7767             }
7768         }
7769
7770       if (count1 == 0 || count2 == 0 || count1 != count2)
7771         goto done;
7772
7773       symtable1
7774         = (struct elf_symbol *) bfd_malloc (count1 * sizeof (*symtable1));
7775       symtable2
7776         = (struct elf_symbol *) bfd_malloc (count2 * sizeof (*symtable2));
7777       if (symtable1 == NULL || symtable2 == NULL)
7778         goto done;
7779
7780       symp = symtable1;
7781       for (ssym = ssymbuf1->ssym, ssymend = ssym + count1;
7782            ssym < ssymend; ssym++, symp++)
7783         {
7784           symp->u.ssym = ssym;
7785           symp->name = bfd_elf_string_from_elf_section (bfd1,
7786                                                         hdr1->sh_link,
7787                                                         ssym->st_name);
7788         }
7789
7790       symp = symtable2;
7791       for (ssym = ssymbuf2->ssym, ssymend = ssym + count2;
7792            ssym < ssymend; ssym++, symp++)
7793         {
7794           symp->u.ssym = ssym;
7795           symp->name = bfd_elf_string_from_elf_section (bfd2,
7796                                                         hdr2->sh_link,
7797                                                         ssym->st_name);
7798         }
7799
7800       /* Sort symbol by name.  */
7801       qsort (symtable1, count1, sizeof (struct elf_symbol),
7802              elf_sym_name_compare);
7803       qsort (symtable2, count1, sizeof (struct elf_symbol),
7804              elf_sym_name_compare);
7805
7806       for (i = 0; i < count1; i++)
7807         /* Two symbols must have the same binding, type and name.  */
7808         if (symtable1 [i].u.ssym->st_info != symtable2 [i].u.ssym->st_info
7809             || symtable1 [i].u.ssym->st_other != symtable2 [i].u.ssym->st_other
7810             || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
7811           goto done;
7812
7813       result = TRUE;
7814       goto done;
7815     }
7816
7817   symtable1 = (struct elf_symbol *)
7818       bfd_malloc (symcount1 * sizeof (struct elf_symbol));
7819   symtable2 = (struct elf_symbol *)
7820       bfd_malloc (symcount2 * sizeof (struct elf_symbol));
7821   if (symtable1 == NULL || symtable2 == NULL)
7822     goto done;
7823
7824   /* Count definitions in the section.  */
7825   count1 = 0;
7826   for (isym = isymbuf1, isymend = isym + symcount1; isym < isymend; isym++)
7827     if (isym->st_shndx == shndx1)
7828       symtable1[count1++].u.isym = isym;
7829
7830   count2 = 0;
7831   for (isym = isymbuf2, isymend = isym + symcount2; isym < isymend; isym++)
7832     if (isym->st_shndx == shndx2)
7833       symtable2[count2++].u.isym = isym;
7834
7835   if (count1 == 0 || count2 == 0 || count1 != count2)
7836     goto done;
7837
7838   for (i = 0; i < count1; i++)
7839     symtable1[i].name
7840       = bfd_elf_string_from_elf_section (bfd1, hdr1->sh_link,
7841                                          symtable1[i].u.isym->st_name);
7842
7843   for (i = 0; i < count2; i++)
7844     symtable2[i].name
7845       = bfd_elf_string_from_elf_section (bfd2, hdr2->sh_link,
7846                                          symtable2[i].u.isym->st_name);
7847
7848   /* Sort symbol by name.  */
7849   qsort (symtable1, count1, sizeof (struct elf_symbol),
7850          elf_sym_name_compare);
7851   qsort (symtable2, count1, sizeof (struct elf_symbol),
7852          elf_sym_name_compare);
7853
7854   for (i = 0; i < count1; i++)
7855     /* Two symbols must have the same binding, type and name.  */
7856     if (symtable1 [i].u.isym->st_info != symtable2 [i].u.isym->st_info
7857         || symtable1 [i].u.isym->st_other != symtable2 [i].u.isym->st_other
7858         || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
7859       goto done;
7860
7861   result = TRUE;
7862
7863 done:
7864   if (symtable1)
7865     free (symtable1);
7866   if (symtable2)
7867     free (symtable2);
7868   if (isymbuf1)
7869     free (isymbuf1);
7870   if (isymbuf2)
7871     free (isymbuf2);
7872
7873   return result;
7874 }
7875
7876 /* Return TRUE if 2 section types are compatible.  */
7877
7878 bfd_boolean
7879 _bfd_elf_match_sections_by_type (bfd *abfd, const asection *asec,
7880                                  bfd *bbfd, const asection *bsec)
7881 {
7882   if (asec == NULL
7883       || bsec == NULL
7884       || abfd->xvec->flavour != bfd_target_elf_flavour
7885       || bbfd->xvec->flavour != bfd_target_elf_flavour)
7886     return TRUE;
7887
7888   return elf_section_type (asec) == elf_section_type (bsec);
7889 }
7890 \f
7891 /* Final phase of ELF linker.  */
7892
7893 /* A structure we use to avoid passing large numbers of arguments.  */
7894
7895 struct elf_final_link_info
7896 {
7897   /* General link information.  */
7898   struct bfd_link_info *info;
7899   /* Output BFD.  */
7900   bfd *output_bfd;
7901   /* Symbol string table.  */
7902   struct elf_strtab_hash *symstrtab;
7903   /* .hash section.  */
7904   asection *hash_sec;
7905   /* symbol version section (.gnu.version).  */
7906   asection *symver_sec;
7907   /* Buffer large enough to hold contents of any section.  */
7908   bfd_byte *contents;
7909   /* Buffer large enough to hold external relocs of any section.  */
7910   void *external_relocs;
7911   /* Buffer large enough to hold internal relocs of any section.  */
7912   Elf_Internal_Rela *internal_relocs;
7913   /* Buffer large enough to hold external local symbols of any input
7914      BFD.  */
7915   bfd_byte *external_syms;
7916   /* And a buffer for symbol section indices.  */
7917   Elf_External_Sym_Shndx *locsym_shndx;
7918   /* Buffer large enough to hold internal local symbols of any input
7919      BFD.  */
7920   Elf_Internal_Sym *internal_syms;
7921   /* Array large enough to hold a symbol index for each local symbol
7922      of any input BFD.  */
7923   long *indices;
7924   /* Array large enough to hold a section pointer for each local
7925      symbol of any input BFD.  */
7926   asection **sections;
7927   /* Buffer for SHT_SYMTAB_SHNDX section.  */
7928   Elf_External_Sym_Shndx *symshndxbuf;
7929   /* Number of STT_FILE syms seen.  */
7930   size_t filesym_count;
7931 };
7932
7933 /* This struct is used to pass information to elf_link_output_extsym.  */
7934
7935 struct elf_outext_info
7936 {
7937   bfd_boolean failed;
7938   bfd_boolean localsyms;
7939   bfd_boolean file_sym_done;
7940   struct elf_final_link_info *flinfo;
7941 };
7942
7943
7944 /* Support for evaluating a complex relocation.
7945
7946    Complex relocations are generalized, self-describing relocations.  The
7947    implementation of them consists of two parts: complex symbols, and the
7948    relocations themselves.
7949
7950    The relocations are use a reserved elf-wide relocation type code (R_RELC
7951    external / BFD_RELOC_RELC internal) and an encoding of relocation field
7952    information (start bit, end bit, word width, etc) into the addend.  This
7953    information is extracted from CGEN-generated operand tables within gas.
7954
7955    Complex symbols are mangled symbols (BSF_RELC external / STT_RELC
7956    internal) representing prefix-notation expressions, including but not
7957    limited to those sorts of expressions normally encoded as addends in the
7958    addend field.  The symbol mangling format is:
7959
7960    <node> := <literal>
7961           |  <unary-operator> ':' <node>
7962           |  <binary-operator> ':' <node> ':' <node>
7963           ;
7964
7965    <literal> := 's' <digits=N> ':' <N character symbol name>
7966              |  'S' <digits=N> ':' <N character section name>
7967              |  '#' <hexdigits>
7968              ;
7969
7970    <binary-operator> := as in C
7971    <unary-operator> := as in C, plus "0-" for unambiguous negation.  */
7972
7973 static void
7974 set_symbol_value (bfd *bfd_with_globals,
7975                   Elf_Internal_Sym *isymbuf,
7976                   size_t locsymcount,
7977                   size_t symidx,
7978                   bfd_vma val)
7979 {
7980   struct elf_link_hash_entry **sym_hashes;
7981   struct elf_link_hash_entry *h;
7982   size_t extsymoff = locsymcount;
7983
7984   if (symidx < locsymcount)
7985     {
7986       Elf_Internal_Sym *sym;
7987
7988       sym = isymbuf + symidx;
7989       if (ELF_ST_BIND (sym->st_info) == STB_LOCAL)
7990         {
7991           /* It is a local symbol: move it to the
7992              "absolute" section and give it a value.  */
7993           sym->st_shndx = SHN_ABS;
7994           sym->st_value = val;
7995           return;
7996         }
7997       BFD_ASSERT (elf_bad_symtab (bfd_with_globals));
7998       extsymoff = 0;
7999     }
8000
8001   /* It is a global symbol: set its link type
8002      to "defined" and give it a value.  */
8003
8004   sym_hashes = elf_sym_hashes (bfd_with_globals);
8005   h = sym_hashes [symidx - extsymoff];
8006   while (h->root.type == bfd_link_hash_indirect
8007          || h->root.type == bfd_link_hash_warning)
8008     h = (struct elf_link_hash_entry *) h->root.u.i.link;
8009   h->root.type = bfd_link_hash_defined;
8010   h->root.u.def.value = val;
8011   h->root.u.def.section = bfd_abs_section_ptr;
8012 }
8013
8014 static bfd_boolean
8015 resolve_symbol (const char *name,
8016                 bfd *input_bfd,
8017                 struct elf_final_link_info *flinfo,
8018                 bfd_vma *result,
8019                 Elf_Internal_Sym *isymbuf,
8020                 size_t locsymcount)
8021 {
8022   Elf_Internal_Sym *sym;
8023   struct bfd_link_hash_entry *global_entry;
8024   const char *candidate = NULL;
8025   Elf_Internal_Shdr *symtab_hdr;
8026   size_t i;
8027
8028   symtab_hdr = & elf_tdata (input_bfd)->symtab_hdr;
8029
8030   for (i = 0; i < locsymcount; ++ i)
8031     {
8032       sym = isymbuf + i;
8033
8034       if (ELF_ST_BIND (sym->st_info) != STB_LOCAL)
8035         continue;
8036
8037       candidate = bfd_elf_string_from_elf_section (input_bfd,
8038                                                    symtab_hdr->sh_link,
8039                                                    sym->st_name);
8040 #ifdef DEBUG
8041       printf ("Comparing string: '%s' vs. '%s' = 0x%lx\n",
8042               name, candidate, (unsigned long) sym->st_value);
8043 #endif
8044       if (candidate && strcmp (candidate, name) == 0)
8045         {
8046           asection *sec = flinfo->sections [i];
8047
8048           *result = _bfd_elf_rel_local_sym (input_bfd, sym, &sec, 0);
8049           *result += sec->output_offset + sec->output_section->vma;
8050 #ifdef DEBUG
8051           printf ("Found symbol with value %8.8lx\n",
8052                   (unsigned long) *result);
8053 #endif
8054           return TRUE;
8055         }
8056     }
8057
8058   /* Hmm, haven't found it yet. perhaps it is a global.  */
8059   global_entry = bfd_link_hash_lookup (flinfo->info->hash, name,
8060                                        FALSE, FALSE, TRUE);
8061   if (!global_entry)
8062     return FALSE;
8063
8064   if (global_entry->type == bfd_link_hash_defined
8065       || global_entry->type == bfd_link_hash_defweak)
8066     {
8067       *result = (global_entry->u.def.value
8068                  + global_entry->u.def.section->output_section->vma
8069                  + global_entry->u.def.section->output_offset);
8070 #ifdef DEBUG
8071       printf ("Found GLOBAL symbol '%s' with value %8.8lx\n",
8072               global_entry->root.string, (unsigned long) *result);
8073 #endif
8074       return TRUE;
8075     }
8076
8077   return FALSE;
8078 }
8079
8080 /* Looks up NAME in SECTIONS.  If found sets RESULT to NAME's address (in
8081    bytes) and returns TRUE, otherwise returns FALSE.  Accepts pseudo-section
8082    names like "foo.end" which is the end address of section "foo".  */
8083    
8084 static bfd_boolean
8085 resolve_section (const char *name,
8086                  asection *sections,
8087                  bfd_vma *result,
8088                  bfd * abfd)
8089 {
8090   asection *curr;
8091   unsigned int len;
8092
8093   for (curr = sections; curr; curr = curr->next)
8094     if (strcmp (curr->name, name) == 0)
8095       {
8096         *result = curr->vma;
8097         return TRUE;
8098       }
8099
8100   /* Hmm. still haven't found it. try pseudo-section names.  */
8101   /* FIXME: This could be coded more efficiently...  */
8102   for (curr = sections; curr; curr = curr->next)
8103     {
8104       len = strlen (curr->name);
8105       if (len > strlen (name))
8106         continue;
8107
8108       if (strncmp (curr->name, name, len) == 0)
8109         {
8110           if (strncmp (".end", name + len, 4) == 0)
8111             {
8112               *result = curr->vma + curr->size / bfd_octets_per_byte (abfd);
8113               return TRUE;
8114             }
8115
8116           /* Insert more pseudo-section names here, if you like.  */
8117         }
8118     }
8119
8120   return FALSE;
8121 }
8122
8123 static void
8124 undefined_reference (const char *reftype, const char *name)
8125 {
8126   /* xgettext:c-format */
8127   _bfd_error_handler (_("undefined %s reference in complex symbol: %s"),
8128                       reftype, name);
8129 }
8130
8131 static bfd_boolean
8132 eval_symbol (bfd_vma *result,
8133              const char **symp,
8134              bfd *input_bfd,
8135              struct elf_final_link_info *flinfo,
8136              bfd_vma dot,
8137              Elf_Internal_Sym *isymbuf,
8138              size_t locsymcount,
8139              int signed_p)
8140 {
8141   size_t len;
8142   size_t symlen;
8143   bfd_vma a;
8144   bfd_vma b;
8145   char symbuf[4096];
8146   const char *sym = *symp;
8147   const char *symend;
8148   bfd_boolean symbol_is_section = FALSE;
8149
8150   len = strlen (sym);
8151   symend = sym + len;
8152
8153   if (len < 1 || len > sizeof (symbuf))
8154     {
8155       bfd_set_error (bfd_error_invalid_operation);
8156       return FALSE;
8157     }
8158
8159   switch (* sym)
8160     {
8161     case '.':
8162       *result = dot;
8163       *symp = sym + 1;
8164       return TRUE;
8165
8166     case '#':
8167       ++sym;
8168       *result = strtoul (sym, (char **) symp, 16);
8169       return TRUE;
8170
8171     case 'S':
8172       symbol_is_section = TRUE;
8173       /* Fall through.  */
8174     case 's':
8175       ++sym;
8176       symlen = strtol (sym, (char **) symp, 10);
8177       sym = *symp + 1; /* Skip the trailing ':'.  */
8178
8179       if (symend < sym || symlen + 1 > sizeof (symbuf))
8180         {
8181           bfd_set_error (bfd_error_invalid_operation);
8182           return FALSE;
8183         }
8184
8185       memcpy (symbuf, sym, symlen);
8186       symbuf[symlen] = '\0';
8187       *symp = sym + symlen;
8188
8189       /* Is it always possible, with complex symbols, that gas "mis-guessed"
8190          the symbol as a section, or vice-versa. so we're pretty liberal in our
8191          interpretation here; section means "try section first", not "must be a
8192          section", and likewise with symbol.  */
8193
8194       if (symbol_is_section)
8195         {
8196           if (!resolve_section (symbuf, flinfo->output_bfd->sections, result, input_bfd)
8197               && !resolve_symbol (symbuf, input_bfd, flinfo, result,
8198                                   isymbuf, locsymcount))
8199             {
8200               undefined_reference ("section", symbuf);
8201               return FALSE;
8202             }
8203         }
8204       else
8205         {
8206           if (!resolve_symbol (symbuf, input_bfd, flinfo, result,
8207                                isymbuf, locsymcount)
8208               && !resolve_section (symbuf, flinfo->output_bfd->sections,
8209                                    result, input_bfd))
8210             {
8211               undefined_reference ("symbol", symbuf);
8212               return FALSE;
8213             }
8214         }
8215
8216       return TRUE;
8217
8218       /* All that remains are operators.  */
8219
8220 #define UNARY_OP(op)                                            \
8221   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
8222     {                                                           \
8223       sym += strlen (#op);                                      \
8224       if (*sym == ':')                                          \
8225         ++sym;                                                  \
8226       *symp = sym;                                              \
8227       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
8228                         isymbuf, locsymcount, signed_p))        \
8229         return FALSE;                                           \
8230       if (signed_p)                                             \
8231         *result = op ((bfd_signed_vma) a);                      \
8232       else                                                      \
8233         *result = op a;                                         \
8234       return TRUE;                                              \
8235     }
8236
8237 #define BINARY_OP(op)                                           \
8238   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
8239     {                                                           \
8240       sym += strlen (#op);                                      \
8241       if (*sym == ':')                                          \
8242         ++sym;                                                  \
8243       *symp = sym;                                              \
8244       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
8245                         isymbuf, locsymcount, signed_p))        \
8246         return FALSE;                                           \
8247       ++*symp;                                                  \
8248       if (!eval_symbol (&b, symp, input_bfd, flinfo, dot,       \
8249                         isymbuf, locsymcount, signed_p))        \
8250         return FALSE;                                           \
8251       if (signed_p)                                             \
8252         *result = ((bfd_signed_vma) a) op ((bfd_signed_vma) b); \
8253       else                                                      \
8254         *result = a op b;                                       \
8255       return TRUE;                                              \
8256     }
8257
8258     default:
8259       UNARY_OP  (0-);
8260       BINARY_OP (<<);
8261       BINARY_OP (>>);
8262       BINARY_OP (==);
8263       BINARY_OP (!=);
8264       BINARY_OP (<=);
8265       BINARY_OP (>=);
8266       BINARY_OP (&&);
8267       BINARY_OP (||);
8268       UNARY_OP  (~);
8269       UNARY_OP  (!);
8270       BINARY_OP (*);
8271       BINARY_OP (/);
8272       BINARY_OP (%);
8273       BINARY_OP (^);
8274       BINARY_OP (|);
8275       BINARY_OP (&);
8276       BINARY_OP (+);
8277       BINARY_OP (-);
8278       BINARY_OP (<);
8279       BINARY_OP (>);
8280 #undef UNARY_OP
8281 #undef BINARY_OP
8282       _bfd_error_handler (_("unknown operator '%c' in complex symbol"), * sym);
8283       bfd_set_error (bfd_error_invalid_operation);
8284       return FALSE;
8285     }
8286 }
8287
8288 static void
8289 put_value (bfd_vma size,
8290            unsigned long chunksz,
8291            bfd *input_bfd,
8292            bfd_vma x,
8293            bfd_byte *location)
8294 {
8295   location += (size - chunksz);
8296
8297   for (; size; size -= chunksz, location -= chunksz)
8298     {
8299       switch (chunksz)
8300         {
8301         case 1:
8302           bfd_put_8 (input_bfd, x, location);
8303           x >>= 8;
8304           break;
8305         case 2:
8306           bfd_put_16 (input_bfd, x, location);
8307           x >>= 16;
8308           break;
8309         case 4:
8310           bfd_put_32 (input_bfd, x, location);
8311           /* Computed this way because x >>= 32 is undefined if x is a 32-bit value.  */
8312           x >>= 16;
8313           x >>= 16;
8314           break;
8315 #ifdef BFD64
8316         case 8:
8317           bfd_put_64 (input_bfd, x, location);
8318           /* Computed this way because x >>= 64 is undefined if x is a 64-bit value.  */
8319           x >>= 32;
8320           x >>= 32;
8321           break;
8322 #endif
8323         default:
8324           abort ();
8325           break;
8326         }
8327     }
8328 }
8329
8330 static bfd_vma
8331 get_value (bfd_vma size,
8332            unsigned long chunksz,
8333            bfd *input_bfd,
8334            bfd_byte *location)
8335 {
8336   int shift;
8337   bfd_vma x = 0;
8338
8339   /* Sanity checks.  */
8340   BFD_ASSERT (chunksz <= sizeof (x)
8341               && size >= chunksz
8342               && chunksz != 0
8343               && (size % chunksz) == 0
8344               && input_bfd != NULL
8345               && location != NULL);
8346
8347   if (chunksz == sizeof (x))
8348     {
8349       BFD_ASSERT (size == chunksz);
8350
8351       /* Make sure that we do not perform an undefined shift operation.
8352          We know that size == chunksz so there will only be one iteration
8353          of the loop below.  */
8354       shift = 0;
8355     }
8356   else
8357     shift = 8 * chunksz;
8358
8359   for (; size; size -= chunksz, location += chunksz)
8360     {
8361       switch (chunksz)
8362         {
8363         case 1:
8364           x = (x << shift) | bfd_get_8 (input_bfd, location);
8365           break;
8366         case 2:
8367           x = (x << shift) | bfd_get_16 (input_bfd, location);
8368           break;
8369         case 4:
8370           x = (x << shift) | bfd_get_32 (input_bfd, location);
8371           break;
8372 #ifdef BFD64
8373         case 8:
8374           x = (x << shift) | bfd_get_64 (input_bfd, location);
8375           break;
8376 #endif
8377         default:
8378           abort ();
8379         }
8380     }
8381   return x;
8382 }
8383
8384 static void
8385 decode_complex_addend (unsigned long *start,   /* in bits */
8386                        unsigned long *oplen,   /* in bits */
8387                        unsigned long *len,     /* in bits */
8388                        unsigned long *wordsz,  /* in bytes */
8389                        unsigned long *chunksz, /* in bytes */
8390                        unsigned long *lsb0_p,
8391                        unsigned long *signed_p,
8392                        unsigned long *trunc_p,
8393                        unsigned long encoded)
8394 {
8395   * start     =  encoded        & 0x3F;
8396   * len       = (encoded >>  6) & 0x3F;
8397   * oplen     = (encoded >> 12) & 0x3F;
8398   * wordsz    = (encoded >> 18) & 0xF;
8399   * chunksz   = (encoded >> 22) & 0xF;
8400   * lsb0_p    = (encoded >> 27) & 1;
8401   * signed_p  = (encoded >> 28) & 1;
8402   * trunc_p   = (encoded >> 29) & 1;
8403 }
8404
8405 bfd_reloc_status_type
8406 bfd_elf_perform_complex_relocation (bfd *input_bfd,
8407                                     asection *input_section ATTRIBUTE_UNUSED,
8408                                     bfd_byte *contents,
8409                                     Elf_Internal_Rela *rel,
8410                                     bfd_vma relocation)
8411 {
8412   bfd_vma shift, x, mask;
8413   unsigned long start, oplen, len, wordsz, chunksz, lsb0_p, signed_p, trunc_p;
8414   bfd_reloc_status_type r;
8415
8416   /*  Perform this reloc, since it is complex.
8417       (this is not to say that it necessarily refers to a complex
8418       symbol; merely that it is a self-describing CGEN based reloc.
8419       i.e. the addend has the complete reloc information (bit start, end,
8420       word size, etc) encoded within it.).  */
8421
8422   decode_complex_addend (&start, &oplen, &len, &wordsz,
8423                          &chunksz, &lsb0_p, &signed_p,
8424                          &trunc_p, rel->r_addend);
8425
8426   mask = (((1L << (len - 1)) - 1) << 1) | 1;
8427
8428   if (lsb0_p)
8429     shift = (start + 1) - len;
8430   else
8431     shift = (8 * wordsz) - (start + len);
8432
8433   x = get_value (wordsz, chunksz, input_bfd,
8434                  contents + rel->r_offset * bfd_octets_per_byte (input_bfd));
8435
8436 #ifdef DEBUG
8437   printf ("Doing complex reloc: "
8438           "lsb0? %ld, signed? %ld, trunc? %ld, wordsz %ld, "
8439           "chunksz %ld, start %ld, len %ld, oplen %ld\n"
8440           "    dest: %8.8lx, mask: %8.8lx, reloc: %8.8lx\n",
8441           lsb0_p, signed_p, trunc_p, wordsz, chunksz, start, len,
8442           oplen, (unsigned long) x, (unsigned long) mask,
8443           (unsigned long) relocation);
8444 #endif
8445
8446   r = bfd_reloc_ok;
8447   if (! trunc_p)
8448     /* Now do an overflow check.  */
8449     r = bfd_check_overflow ((signed_p
8450                              ? complain_overflow_signed
8451                              : complain_overflow_unsigned),
8452                             len, 0, (8 * wordsz),
8453                             relocation);
8454
8455   /* Do the deed.  */
8456   x = (x & ~(mask << shift)) | ((relocation & mask) << shift);
8457
8458 #ifdef DEBUG
8459   printf ("           relocation: %8.8lx\n"
8460           "         shifted mask: %8.8lx\n"
8461           " shifted/masked reloc: %8.8lx\n"
8462           "               result: %8.8lx\n",
8463           (unsigned long) relocation, (unsigned long) (mask << shift),
8464           (unsigned long) ((relocation & mask) << shift), (unsigned long) x);
8465 #endif
8466   put_value (wordsz, chunksz, input_bfd, x,
8467              contents + rel->r_offset * bfd_octets_per_byte (input_bfd));
8468   return r;
8469 }
8470
8471 /* Functions to read r_offset from external (target order) reloc
8472    entry.  Faster than bfd_getl32 et al, because we let the compiler
8473    know the value is aligned.  */
8474
8475 static bfd_vma
8476 ext32l_r_offset (const void *p)
8477 {
8478   union aligned32
8479   {
8480     uint32_t v;
8481     unsigned char c[4];
8482   };
8483   const union aligned32 *a
8484     = (const union aligned32 *) &((const Elf32_External_Rel *) p)->r_offset;
8485
8486   uint32_t aval = (  (uint32_t) a->c[0]
8487                    | (uint32_t) a->c[1] << 8
8488                    | (uint32_t) a->c[2] << 16
8489                    | (uint32_t) a->c[3] << 24);
8490   return aval;
8491 }
8492
8493 static bfd_vma
8494 ext32b_r_offset (const void *p)
8495 {
8496   union aligned32
8497   {
8498     uint32_t v;
8499     unsigned char c[4];
8500   };
8501   const union aligned32 *a
8502     = (const union aligned32 *) &((const Elf32_External_Rel *) p)->r_offset;
8503
8504   uint32_t aval = (  (uint32_t) a->c[0] << 24
8505                    | (uint32_t) a->c[1] << 16
8506                    | (uint32_t) a->c[2] << 8
8507                    | (uint32_t) a->c[3]);
8508   return aval;
8509 }
8510
8511 #ifdef BFD_HOST_64_BIT
8512 static bfd_vma
8513 ext64l_r_offset (const void *p)
8514 {
8515   union aligned64
8516   {
8517     uint64_t v;
8518     unsigned char c[8];
8519   };
8520   const union aligned64 *a
8521     = (const union aligned64 *) &((const Elf64_External_Rel *) p)->r_offset;
8522
8523   uint64_t aval = (  (uint64_t) a->c[0]
8524                    | (uint64_t) a->c[1] << 8
8525                    | (uint64_t) a->c[2] << 16
8526                    | (uint64_t) a->c[3] << 24
8527                    | (uint64_t) a->c[4] << 32
8528                    | (uint64_t) a->c[5] << 40
8529                    | (uint64_t) a->c[6] << 48
8530                    | (uint64_t) a->c[7] << 56);
8531   return aval;
8532 }
8533
8534 static bfd_vma
8535 ext64b_r_offset (const void *p)
8536 {
8537   union aligned64
8538   {
8539     uint64_t v;
8540     unsigned char c[8];
8541   };
8542   const union aligned64 *a
8543     = (const union aligned64 *) &((const Elf64_External_Rel *) p)->r_offset;
8544
8545   uint64_t aval = (  (uint64_t) a->c[0] << 56
8546                    | (uint64_t) a->c[1] << 48
8547                    | (uint64_t) a->c[2] << 40
8548                    | (uint64_t) a->c[3] << 32
8549                    | (uint64_t) a->c[4] << 24
8550                    | (uint64_t) a->c[5] << 16
8551                    | (uint64_t) a->c[6] << 8
8552                    | (uint64_t) a->c[7]);
8553   return aval;
8554 }
8555 #endif
8556
8557 /* When performing a relocatable link, the input relocations are
8558    preserved.  But, if they reference global symbols, the indices
8559    referenced must be updated.  Update all the relocations found in
8560    RELDATA.  */
8561
8562 static bfd_boolean
8563 elf_link_adjust_relocs (bfd *abfd,
8564                         asection *sec,
8565                         struct bfd_elf_section_reloc_data *reldata,
8566                         bfd_boolean sort,
8567                         struct bfd_link_info *info)
8568 {
8569   unsigned int i;
8570   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8571   bfd_byte *erela;
8572   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
8573   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
8574   bfd_vma r_type_mask;
8575   int r_sym_shift;
8576   unsigned int count = reldata->count;
8577   struct elf_link_hash_entry **rel_hash = reldata->hashes;
8578
8579   if (reldata->hdr->sh_entsize == bed->s->sizeof_rel)
8580     {
8581       swap_in = bed->s->swap_reloc_in;
8582       swap_out = bed->s->swap_reloc_out;
8583     }
8584   else if (reldata->hdr->sh_entsize == bed->s->sizeof_rela)
8585     {
8586       swap_in = bed->s->swap_reloca_in;
8587       swap_out = bed->s->swap_reloca_out;
8588     }
8589   else
8590     abort ();
8591
8592   if (bed->s->int_rels_per_ext_rel > MAX_INT_RELS_PER_EXT_REL)
8593     abort ();
8594
8595   if (bed->s->arch_size == 32)
8596     {
8597       r_type_mask = 0xff;
8598       r_sym_shift = 8;
8599     }
8600   else
8601     {
8602       r_type_mask = 0xffffffff;
8603       r_sym_shift = 32;
8604     }
8605
8606   erela = reldata->hdr->contents;
8607   for (i = 0; i < count; i++, rel_hash++, erela += reldata->hdr->sh_entsize)
8608     {
8609       Elf_Internal_Rela irela[MAX_INT_RELS_PER_EXT_REL];
8610       unsigned int j;
8611
8612       if (*rel_hash == NULL)
8613         continue;
8614
8615       if ((*rel_hash)->indx == -2
8616           && info->gc_sections
8617           && ! info->gc_keep_exported)
8618         {
8619           /* PR 21524: Let the user know if a symbol was removed by garbage collection.  */
8620           _bfd_error_handler (_("%B:%A: error: relocation references symbol %s which was removed by garbage collection."),
8621                               abfd, sec,
8622                               (*rel_hash)->root.root.string);
8623           _bfd_error_handler (_("%B:%A: error: try relinking with --gc-keep-exported enabled."),
8624                               abfd, sec);
8625           bfd_set_error (bfd_error_invalid_operation);
8626           return FALSE;
8627         }
8628       BFD_ASSERT ((*rel_hash)->indx >= 0);
8629
8630       (*swap_in) (abfd, erela, irela);
8631       for (j = 0; j < bed->s->int_rels_per_ext_rel; j++)
8632         irela[j].r_info = ((bfd_vma) (*rel_hash)->indx << r_sym_shift
8633                            | (irela[j].r_info & r_type_mask));
8634       (*swap_out) (abfd, irela, erela);
8635     }
8636
8637   if (bed->elf_backend_update_relocs)
8638     (*bed->elf_backend_update_relocs) (sec, reldata);
8639
8640   if (sort && count != 0)
8641     {
8642       bfd_vma (*ext_r_off) (const void *);
8643       bfd_vma r_off;
8644       size_t elt_size;
8645       bfd_byte *base, *end, *p, *loc;
8646       bfd_byte *buf = NULL;
8647
8648       if (bed->s->arch_size == 32)
8649         {
8650           if (abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)
8651             ext_r_off = ext32l_r_offset;
8652           else if (abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
8653             ext_r_off = ext32b_r_offset;
8654           else
8655             abort ();
8656         }
8657       else
8658         {
8659 #ifdef BFD_HOST_64_BIT
8660           if (abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)
8661             ext_r_off = ext64l_r_offset;
8662           else if (abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
8663             ext_r_off = ext64b_r_offset;
8664           else
8665 #endif
8666             abort ();
8667         }
8668
8669       /*  Must use a stable sort here.  A modified insertion sort,
8670           since the relocs are mostly sorted already.  */
8671       elt_size = reldata->hdr->sh_entsize;
8672       base = reldata->hdr->contents;
8673       end = base + count * elt_size;
8674       if (elt_size > sizeof (Elf64_External_Rela))
8675         abort ();
8676
8677       /* Ensure the first element is lowest.  This acts as a sentinel,
8678          speeding the main loop below.  */
8679       r_off = (*ext_r_off) (base);
8680       for (p = loc = base; (p += elt_size) < end; )
8681         {
8682           bfd_vma r_off2 = (*ext_r_off) (p);
8683           if (r_off > r_off2)
8684             {
8685               r_off = r_off2;
8686               loc = p;
8687             }
8688         }
8689       if (loc != base)
8690         {
8691           /* Don't just swap *base and *loc as that changes the order
8692              of the original base[0] and base[1] if they happen to
8693              have the same r_offset.  */
8694           bfd_byte onebuf[sizeof (Elf64_External_Rela)];
8695           memcpy (onebuf, loc, elt_size);
8696           memmove (base + elt_size, base, loc - base);
8697           memcpy (base, onebuf, elt_size);
8698         }
8699
8700       for (p = base + elt_size; (p += elt_size) < end; )
8701         {
8702           /* base to p is sorted, *p is next to insert.  */
8703           r_off = (*ext_r_off) (p);
8704           /* Search the sorted region for location to insert.  */
8705           loc = p - elt_size;
8706           while (r_off < (*ext_r_off) (loc))
8707             loc -= elt_size;
8708           loc += elt_size;
8709           if (loc != p)
8710             {
8711               /* Chances are there is a run of relocs to insert here,
8712                  from one of more input files.  Files are not always
8713                  linked in order due to the way elf_link_input_bfd is
8714                  called.  See pr17666.  */
8715               size_t sortlen = p - loc;
8716               bfd_vma r_off2 = (*ext_r_off) (loc);
8717               size_t runlen = elt_size;
8718               size_t buf_size = 96 * 1024;
8719               while (p + runlen < end
8720                      && (sortlen <= buf_size
8721                          || runlen + elt_size <= buf_size)
8722                      && r_off2 > (*ext_r_off) (p + runlen))
8723                 runlen += elt_size;
8724               if (buf == NULL)
8725                 {
8726                   buf = bfd_malloc (buf_size);
8727                   if (buf == NULL)
8728                     return FALSE;
8729                 }
8730               if (runlen < sortlen)
8731                 {
8732                   memcpy (buf, p, runlen);
8733                   memmove (loc + runlen, loc, sortlen);
8734                   memcpy (loc, buf, runlen);
8735                 }
8736               else
8737                 {
8738                   memcpy (buf, loc, sortlen);
8739                   memmove (loc, p, runlen);
8740                   memcpy (loc + runlen, buf, sortlen);
8741                 }
8742               p += runlen - elt_size;
8743             }
8744         }
8745       /* Hashes are no longer valid.  */
8746       free (reldata->hashes);
8747       reldata->hashes = NULL;
8748       free (buf);
8749     }
8750   return TRUE;
8751 }
8752
8753 struct elf_link_sort_rela
8754 {
8755   union {
8756     bfd_vma offset;
8757     bfd_vma sym_mask;
8758   } u;
8759   enum elf_reloc_type_class type;
8760   /* We use this as an array of size int_rels_per_ext_rel.  */
8761   Elf_Internal_Rela rela[1];
8762 };
8763
8764 static int
8765 elf_link_sort_cmp1 (const void *A, const void *B)
8766 {
8767   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
8768   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
8769   int relativea, relativeb;
8770
8771   relativea = a->type == reloc_class_relative;
8772   relativeb = b->type == reloc_class_relative;
8773
8774   if (relativea < relativeb)
8775     return 1;
8776   if (relativea > relativeb)
8777     return -1;
8778   if ((a->rela->r_info & a->u.sym_mask) < (b->rela->r_info & b->u.sym_mask))
8779     return -1;
8780   if ((a->rela->r_info & a->u.sym_mask) > (b->rela->r_info & b->u.sym_mask))
8781     return 1;
8782   if (a->rela->r_offset < b->rela->r_offset)
8783     return -1;
8784   if (a->rela->r_offset > b->rela->r_offset)
8785     return 1;
8786   return 0;
8787 }
8788
8789 static int
8790 elf_link_sort_cmp2 (const void *A, const void *B)
8791 {
8792   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
8793   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
8794
8795   if (a->type < b->type)
8796     return -1;
8797   if (a->type > b->type)
8798     return 1;
8799   if (a->u.offset < b->u.offset)
8800     return -1;
8801   if (a->u.offset > b->u.offset)
8802     return 1;
8803   if (a->rela->r_offset < b->rela->r_offset)
8804     return -1;
8805   if (a->rela->r_offset > b->rela->r_offset)
8806     return 1;
8807   return 0;
8808 }
8809
8810 static size_t
8811 elf_link_sort_relocs (bfd *abfd, struct bfd_link_info *info, asection **psec)
8812 {
8813   asection *dynamic_relocs;
8814   asection *rela_dyn;
8815   asection *rel_dyn;
8816   bfd_size_type count, size;
8817   size_t i, ret, sort_elt, ext_size;
8818   bfd_byte *sort, *s_non_relative, *p;
8819   struct elf_link_sort_rela *sq;
8820   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8821   int i2e = bed->s->int_rels_per_ext_rel;
8822   unsigned int opb = bfd_octets_per_byte (abfd);
8823   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
8824   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
8825   struct bfd_link_order *lo;
8826   bfd_vma r_sym_mask;
8827   bfd_boolean use_rela;
8828
8829   /* Find a dynamic reloc section.  */
8830   rela_dyn = bfd_get_section_by_name (abfd, ".rela.dyn");
8831   rel_dyn  = bfd_get_section_by_name (abfd, ".rel.dyn");
8832   if (rela_dyn != NULL && rela_dyn->size > 0
8833       && rel_dyn != NULL && rel_dyn->size > 0)
8834     {
8835       bfd_boolean use_rela_initialised = FALSE;
8836
8837       /* This is just here to stop gcc from complaining.
8838          Its initialization checking code is not perfect.  */
8839       use_rela = TRUE;
8840
8841       /* Both sections are present.  Examine the sizes
8842          of the indirect sections to help us choose.  */
8843       for (lo = rela_dyn->map_head.link_order; lo != NULL; lo = lo->next)
8844         if (lo->type == bfd_indirect_link_order)
8845           {
8846             asection *o = lo->u.indirect.section;
8847
8848             if ((o->size % bed->s->sizeof_rela) == 0)
8849               {
8850                 if ((o->size % bed->s->sizeof_rel) == 0)
8851                   /* Section size is divisible by both rel and rela sizes.
8852                      It is of no help to us.  */
8853                   ;
8854                 else
8855                   {
8856                     /* Section size is only divisible by rela.  */
8857                     if (use_rela_initialised && !use_rela)
8858                       {
8859                         _bfd_error_handler (_("%B: Unable to sort relocs - "
8860                                               "they are in more than one size"),
8861                                             abfd);
8862                         bfd_set_error (bfd_error_invalid_operation);
8863                         return 0;
8864                       }
8865                     else
8866                       {
8867                         use_rela = TRUE;
8868                         use_rela_initialised = TRUE;
8869                       }
8870                   }
8871               }
8872             else if ((o->size % bed->s->sizeof_rel) == 0)
8873               {
8874                 /* Section size is only divisible by rel.  */
8875                 if (use_rela_initialised && use_rela)
8876                   {
8877                     _bfd_error_handler (_("%B: Unable to sort relocs - "
8878                                           "they are in more than one size"),
8879                                         abfd);
8880                     bfd_set_error (bfd_error_invalid_operation);
8881                     return 0;
8882                   }
8883                 else
8884                   {
8885                     use_rela = FALSE;
8886                     use_rela_initialised = TRUE;
8887                   }
8888               }
8889             else
8890               {
8891                 /* The section size is not divisible by either -
8892                    something is wrong.  */
8893                 _bfd_error_handler (_("%B: Unable to sort relocs - "
8894                                       "they are of an unknown size"), abfd);
8895                 bfd_set_error (bfd_error_invalid_operation);
8896                 return 0;
8897               }
8898           }
8899
8900       for (lo = rel_dyn->map_head.link_order; lo != NULL; lo = lo->next)
8901         if (lo->type == bfd_indirect_link_order)
8902           {
8903             asection *o = lo->u.indirect.section;
8904
8905             if ((o->size % bed->s->sizeof_rela) == 0)
8906               {
8907                 if ((o->size % bed->s->sizeof_rel) == 0)
8908                   /* Section size is divisible by both rel and rela sizes.
8909                      It is of no help to us.  */
8910                   ;
8911                 else
8912                   {
8913                     /* Section size is only divisible by rela.  */
8914                     if (use_rela_initialised && !use_rela)
8915                       {
8916                         _bfd_error_handler (_("%B: Unable to sort relocs - "
8917                                               "they are in more than one size"),
8918                                             abfd);
8919                         bfd_set_error (bfd_error_invalid_operation);
8920                         return 0;
8921                       }
8922                     else
8923                       {
8924                         use_rela = TRUE;
8925                         use_rela_initialised = TRUE;
8926                       }
8927                   }
8928               }
8929             else if ((o->size % bed->s->sizeof_rel) == 0)
8930               {
8931                 /* Section size is only divisible by rel.  */
8932                 if (use_rela_initialised && use_rela)
8933                   {
8934                     _bfd_error_handler (_("%B: Unable to sort relocs - "
8935                                           "they are in more than one size"),
8936                                         abfd);
8937                     bfd_set_error (bfd_error_invalid_operation);
8938                     return 0;
8939                   }
8940                 else
8941                   {
8942                     use_rela = FALSE;
8943                     use_rela_initialised = TRUE;
8944                   }
8945               }
8946             else
8947               {
8948                 /* The section size is not divisible by either -
8949                    something is wrong.  */
8950                 _bfd_error_handler (_("%B: Unable to sort relocs - "
8951                                       "they are of an unknown size"), abfd);
8952                 bfd_set_error (bfd_error_invalid_operation);
8953                 return 0;
8954               }
8955           }
8956
8957       if (! use_rela_initialised)
8958         /* Make a guess.  */
8959         use_rela = TRUE;
8960     }
8961   else if (rela_dyn != NULL && rela_dyn->size > 0)
8962     use_rela = TRUE;
8963   else if (rel_dyn != NULL && rel_dyn->size > 0)
8964     use_rela = FALSE;
8965   else
8966     return 0;
8967
8968   if (use_rela)
8969     {
8970       dynamic_relocs = rela_dyn;
8971       ext_size = bed->s->sizeof_rela;
8972       swap_in = bed->s->swap_reloca_in;
8973       swap_out = bed->s->swap_reloca_out;
8974     }
8975   else
8976     {
8977       dynamic_relocs = rel_dyn;
8978       ext_size = bed->s->sizeof_rel;
8979       swap_in = bed->s->swap_reloc_in;
8980       swap_out = bed->s->swap_reloc_out;
8981     }
8982
8983   size = 0;
8984   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
8985     if (lo->type == bfd_indirect_link_order)
8986       size += lo->u.indirect.section->size;
8987
8988   if (size != dynamic_relocs->size)
8989     return 0;
8990
8991   sort_elt = (sizeof (struct elf_link_sort_rela)
8992               + (i2e - 1) * sizeof (Elf_Internal_Rela));
8993
8994   count = dynamic_relocs->size / ext_size;
8995   if (count == 0)
8996     return 0;
8997   sort = (bfd_byte *) bfd_zmalloc (sort_elt * count);
8998
8999   if (sort == NULL)
9000     {
9001       (*info->callbacks->warning)
9002         (info, _("Not enough memory to sort relocations"), 0, abfd, 0, 0);
9003       return 0;
9004     }
9005
9006   if (bed->s->arch_size == 32)
9007     r_sym_mask = ~(bfd_vma) 0xff;
9008   else
9009     r_sym_mask = ~(bfd_vma) 0xffffffff;
9010
9011   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
9012     if (lo->type == bfd_indirect_link_order)
9013       {
9014         bfd_byte *erel, *erelend;
9015         asection *o = lo->u.indirect.section;
9016
9017         if (o->contents == NULL && o->size != 0)
9018           {
9019             /* This is a reloc section that is being handled as a normal
9020                section.  See bfd_section_from_shdr.  We can't combine
9021                relocs in this case.  */
9022             free (sort);
9023             return 0;
9024           }
9025         erel = o->contents;
9026         erelend = o->contents + o->size;
9027         p = sort + o->output_offset * opb / ext_size * sort_elt;
9028
9029         while (erel < erelend)
9030           {
9031             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
9032
9033             (*swap_in) (abfd, erel, s->rela);
9034             s->type = (*bed->elf_backend_reloc_type_class) (info, o, s->rela);
9035             s->u.sym_mask = r_sym_mask;
9036             p += sort_elt;
9037             erel += ext_size;
9038           }
9039       }
9040
9041   qsort (sort, count, sort_elt, elf_link_sort_cmp1);
9042
9043   for (i = 0, p = sort; i < count; i++, p += sort_elt)
9044     {
9045       struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
9046       if (s->type != reloc_class_relative)
9047         break;
9048     }
9049   ret = i;
9050   s_non_relative = p;
9051
9052   sq = (struct elf_link_sort_rela *) s_non_relative;
9053   for (; i < count; i++, p += sort_elt)
9054     {
9055       struct elf_link_sort_rela *sp = (struct elf_link_sort_rela *) p;
9056       if (((sp->rela->r_info ^ sq->rela->r_info) & r_sym_mask) != 0)
9057         sq = sp;
9058       sp->u.offset = sq->rela->r_offset;
9059     }
9060
9061   qsort (s_non_relative, count - ret, sort_elt, elf_link_sort_cmp2);
9062
9063   struct elf_link_hash_table *htab = elf_hash_table (info);
9064   if (htab->srelplt && htab->srelplt->output_section == dynamic_relocs)
9065     {
9066       /* We have plt relocs in .rela.dyn.  */
9067       sq = (struct elf_link_sort_rela *) sort;
9068       for (i = 0; i < count; i++)
9069         if (sq[count - i - 1].type != reloc_class_plt)
9070           break;
9071       if (i != 0 && htab->srelplt->size == i * ext_size)
9072         {
9073           struct bfd_link_order **plo;
9074           /* Put srelplt link_order last.  This is so the output_offset
9075              set in the next loop is correct for DT_JMPREL.  */
9076           for (plo = &dynamic_relocs->map_head.link_order; *plo != NULL; )
9077             if ((*plo)->type == bfd_indirect_link_order
9078                 && (*plo)->u.indirect.section == htab->srelplt)
9079               {
9080                 lo = *plo;
9081                 *plo = lo->next;
9082               }
9083             else
9084               plo = &(*plo)->next;
9085           *plo = lo;
9086           lo->next = NULL;
9087           dynamic_relocs->map_tail.link_order = lo;
9088         }
9089     }
9090
9091   p = sort;
9092   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
9093     if (lo->type == bfd_indirect_link_order)
9094       {
9095         bfd_byte *erel, *erelend;
9096         asection *o = lo->u.indirect.section;
9097
9098         erel = o->contents;
9099         erelend = o->contents + o->size;
9100         o->output_offset = (p - sort) / sort_elt * ext_size / opb;
9101         while (erel < erelend)
9102           {
9103             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
9104             (*swap_out) (abfd, s->rela, erel);
9105             p += sort_elt;
9106             erel += ext_size;
9107           }
9108       }
9109
9110   free (sort);
9111   *psec = dynamic_relocs;
9112   return ret;
9113 }
9114
9115 /* Add a symbol to the output symbol string table.  */
9116
9117 static int
9118 elf_link_output_symstrtab (struct elf_final_link_info *flinfo,
9119                            const char *name,
9120                            Elf_Internal_Sym *elfsym,
9121                            asection *input_sec,
9122                            struct elf_link_hash_entry *h)
9123 {
9124   int (*output_symbol_hook)
9125     (struct bfd_link_info *, const char *, Elf_Internal_Sym *, asection *,
9126      struct elf_link_hash_entry *);
9127   struct elf_link_hash_table *hash_table;
9128   const struct elf_backend_data *bed;
9129   bfd_size_type strtabsize;
9130
9131   BFD_ASSERT (elf_onesymtab (flinfo->output_bfd));
9132
9133   bed = get_elf_backend_data (flinfo->output_bfd);
9134   output_symbol_hook = bed->elf_backend_link_output_symbol_hook;
9135   if (output_symbol_hook != NULL)
9136     {
9137       int ret = (*output_symbol_hook) (flinfo->info, name, elfsym, input_sec, h);
9138       if (ret != 1)
9139         return ret;
9140     }
9141
9142   if (name == NULL
9143       || *name == '\0'
9144       || (input_sec->flags & SEC_EXCLUDE))
9145     elfsym->st_name = (unsigned long) -1;
9146   else
9147     {
9148       /* Call _bfd_elf_strtab_offset after _bfd_elf_strtab_finalize
9149          to get the final offset for st_name.  */
9150       elfsym->st_name
9151         = (unsigned long) _bfd_elf_strtab_add (flinfo->symstrtab,
9152                                                name, FALSE);
9153       if (elfsym->st_name == (unsigned long) -1)
9154         return 0;
9155     }
9156
9157   hash_table = elf_hash_table (flinfo->info);
9158   strtabsize = hash_table->strtabsize;
9159   if (strtabsize <= hash_table->strtabcount)
9160     {
9161       strtabsize += strtabsize;
9162       hash_table->strtabsize = strtabsize;
9163       strtabsize *= sizeof (*hash_table->strtab);
9164       hash_table->strtab
9165         = (struct elf_sym_strtab *) bfd_realloc (hash_table->strtab,
9166                                                  strtabsize);
9167       if (hash_table->strtab == NULL)
9168         return 0;
9169     }
9170   hash_table->strtab[hash_table->strtabcount].sym = *elfsym;
9171   hash_table->strtab[hash_table->strtabcount].dest_index
9172     = hash_table->strtabcount;
9173   hash_table->strtab[hash_table->strtabcount].destshndx_index
9174     = flinfo->symshndxbuf ? bfd_get_symcount (flinfo->output_bfd) : 0;
9175
9176   bfd_get_symcount (flinfo->output_bfd) += 1;
9177   hash_table->strtabcount += 1;
9178
9179   return 1;
9180 }
9181
9182 /* Swap symbols out to the symbol table and flush the output symbols to
9183    the file.  */
9184
9185 static bfd_boolean
9186 elf_link_swap_symbols_out (struct elf_final_link_info *flinfo)
9187 {
9188   struct elf_link_hash_table *hash_table = elf_hash_table (flinfo->info);
9189   bfd_size_type amt;
9190   size_t i;
9191   const struct elf_backend_data *bed;
9192   bfd_byte *symbuf;
9193   Elf_Internal_Shdr *hdr;
9194   file_ptr pos;
9195   bfd_boolean ret;
9196
9197   if (!hash_table->strtabcount)
9198     return TRUE;
9199
9200   BFD_ASSERT (elf_onesymtab (flinfo->output_bfd));
9201
9202   bed = get_elf_backend_data (flinfo->output_bfd);
9203
9204   amt = bed->s->sizeof_sym * hash_table->strtabcount;
9205   symbuf = (bfd_byte *) bfd_malloc (amt);
9206   if (symbuf == NULL)
9207     return FALSE;
9208
9209   if (flinfo->symshndxbuf)
9210     {
9211       amt = sizeof (Elf_External_Sym_Shndx);
9212       amt *= bfd_get_symcount (flinfo->output_bfd);
9213       flinfo->symshndxbuf = (Elf_External_Sym_Shndx *) bfd_zmalloc (amt);
9214       if (flinfo->symshndxbuf == NULL)
9215         {
9216           free (symbuf);
9217           return FALSE;
9218         }
9219     }
9220
9221   for (i = 0; i < hash_table->strtabcount; i++)
9222     {
9223       struct elf_sym_strtab *elfsym = &hash_table->strtab[i];
9224       if (elfsym->sym.st_name == (unsigned long) -1)
9225         elfsym->sym.st_name = 0;
9226       else
9227         elfsym->sym.st_name
9228           = (unsigned long) _bfd_elf_strtab_offset (flinfo->symstrtab,
9229                                                     elfsym->sym.st_name);
9230       bed->s->swap_symbol_out (flinfo->output_bfd, &elfsym->sym,
9231                                ((bfd_byte *) symbuf
9232                                 + (elfsym->dest_index
9233                                    * bed->s->sizeof_sym)),
9234                                (flinfo->symshndxbuf
9235                                 + elfsym->destshndx_index));
9236     }
9237
9238   hdr = &elf_tdata (flinfo->output_bfd)->symtab_hdr;
9239   pos = hdr->sh_offset + hdr->sh_size;
9240   amt = hash_table->strtabcount * bed->s->sizeof_sym;
9241   if (bfd_seek (flinfo->output_bfd, pos, SEEK_SET) == 0
9242       && bfd_bwrite (symbuf, amt, flinfo->output_bfd) == amt)
9243     {
9244       hdr->sh_size += amt;
9245       ret = TRUE;
9246     }
9247   else
9248     ret = FALSE;
9249
9250   free (symbuf);
9251
9252   free (hash_table->strtab);
9253   hash_table->strtab = NULL;
9254
9255   return ret;
9256 }
9257
9258 /* Return TRUE if the dynamic symbol SYM in ABFD is supported.  */
9259
9260 static bfd_boolean
9261 check_dynsym (bfd *abfd, Elf_Internal_Sym *sym)
9262 {
9263   if (sym->st_shndx >= (SHN_LORESERVE & 0xffff)
9264       && sym->st_shndx < SHN_LORESERVE)
9265     {
9266       /* The gABI doesn't support dynamic symbols in output sections
9267          beyond 64k.  */
9268       _bfd_error_handler
9269         /* xgettext:c-format */
9270         (_("%B: Too many sections: %d (>= %d)"),
9271          abfd, bfd_count_sections (abfd), SHN_LORESERVE & 0xffff);
9272       bfd_set_error (bfd_error_nonrepresentable_section);
9273       return FALSE;
9274     }
9275   return TRUE;
9276 }
9277
9278 /* For DSOs loaded in via a DT_NEEDED entry, emulate ld.so in
9279    allowing an unsatisfied unversioned symbol in the DSO to match a
9280    versioned symbol that would normally require an explicit version.
9281    We also handle the case that a DSO references a hidden symbol
9282    which may be satisfied by a versioned symbol in another DSO.  */
9283
9284 static bfd_boolean
9285 elf_link_check_versioned_symbol (struct bfd_link_info *info,
9286                                  const struct elf_backend_data *bed,
9287                                  struct elf_link_hash_entry *h)
9288 {
9289   bfd *abfd;
9290   struct elf_link_loaded_list *loaded;
9291
9292   if (!is_elf_hash_table (info->hash))
9293     return FALSE;
9294
9295   /* Check indirect symbol.  */
9296   while (h->root.type == bfd_link_hash_indirect)
9297     h = (struct elf_link_hash_entry *) h->root.u.i.link;
9298
9299   switch (h->root.type)
9300     {
9301     default:
9302       abfd = NULL;
9303       break;
9304
9305     case bfd_link_hash_undefined:
9306     case bfd_link_hash_undefweak:
9307       abfd = h->root.u.undef.abfd;
9308       if (abfd == NULL
9309           || (abfd->flags & DYNAMIC) == 0
9310           || (elf_dyn_lib_class (abfd) & DYN_DT_NEEDED) == 0)
9311         return FALSE;
9312       break;
9313
9314     case bfd_link_hash_defined:
9315     case bfd_link_hash_defweak:
9316       abfd = h->root.u.def.section->owner;
9317       break;
9318
9319     case bfd_link_hash_common:
9320       abfd = h->root.u.c.p->section->owner;
9321       break;
9322     }
9323   BFD_ASSERT (abfd != NULL);
9324
9325   for (loaded = elf_hash_table (info)->loaded;
9326        loaded != NULL;
9327        loaded = loaded->next)
9328     {
9329       bfd *input;
9330       Elf_Internal_Shdr *hdr;
9331       size_t symcount;
9332       size_t extsymcount;
9333       size_t extsymoff;
9334       Elf_Internal_Shdr *versymhdr;
9335       Elf_Internal_Sym *isym;
9336       Elf_Internal_Sym *isymend;
9337       Elf_Internal_Sym *isymbuf;
9338       Elf_External_Versym *ever;
9339       Elf_External_Versym *extversym;
9340
9341       input = loaded->abfd;
9342
9343       /* We check each DSO for a possible hidden versioned definition.  */
9344       if (input == abfd
9345           || (input->flags & DYNAMIC) == 0
9346           || elf_dynversym (input) == 0)
9347         continue;
9348
9349       hdr = &elf_tdata (input)->dynsymtab_hdr;
9350
9351       symcount = hdr->sh_size / bed->s->sizeof_sym;
9352       if (elf_bad_symtab (input))
9353         {
9354           extsymcount = symcount;
9355           extsymoff = 0;
9356         }
9357       else
9358         {
9359           extsymcount = symcount - hdr->sh_info;
9360           extsymoff = hdr->sh_info;
9361         }
9362
9363       if (extsymcount == 0)
9364         continue;
9365
9366       isymbuf = bfd_elf_get_elf_syms (input, hdr, extsymcount, extsymoff,
9367                                       NULL, NULL, NULL);
9368       if (isymbuf == NULL)
9369         return FALSE;
9370
9371       /* Read in any version definitions.  */
9372       versymhdr = &elf_tdata (input)->dynversym_hdr;
9373       extversym = (Elf_External_Versym *) bfd_malloc (versymhdr->sh_size);
9374       if (extversym == NULL)
9375         goto error_ret;
9376
9377       if (bfd_seek (input, versymhdr->sh_offset, SEEK_SET) != 0
9378           || (bfd_bread (extversym, versymhdr->sh_size, input)
9379               != versymhdr->sh_size))
9380         {
9381           free (extversym);
9382         error_ret:
9383           free (isymbuf);
9384           return FALSE;
9385         }
9386
9387       ever = extversym + extsymoff;
9388       isymend = isymbuf + extsymcount;
9389       for (isym = isymbuf; isym < isymend; isym++, ever++)
9390         {
9391           const char *name;
9392           Elf_Internal_Versym iver;
9393           unsigned short version_index;
9394
9395           if (ELF_ST_BIND (isym->st_info) == STB_LOCAL
9396               || isym->st_shndx == SHN_UNDEF)
9397             continue;
9398
9399           name = bfd_elf_string_from_elf_section (input,
9400                                                   hdr->sh_link,
9401                                                   isym->st_name);
9402           if (strcmp (name, h->root.root.string) != 0)
9403             continue;
9404
9405           _bfd_elf_swap_versym_in (input, ever, &iver);
9406
9407           if ((iver.vs_vers & VERSYM_HIDDEN) == 0
9408               && !(h->def_regular
9409                    && h->forced_local))
9410             {
9411               /* If we have a non-hidden versioned sym, then it should
9412                  have provided a definition for the undefined sym unless
9413                  it is defined in a non-shared object and forced local.
9414                */
9415               abort ();
9416             }
9417
9418           version_index = iver.vs_vers & VERSYM_VERSION;
9419           if (version_index == 1 || version_index == 2)
9420             {
9421               /* This is the base or first version.  We can use it.  */
9422               free (extversym);
9423               free (isymbuf);
9424               return TRUE;
9425             }
9426         }
9427
9428       free (extversym);
9429       free (isymbuf);
9430     }
9431
9432   return FALSE;
9433 }
9434
9435 /* Convert ELF common symbol TYPE.  */
9436
9437 static int
9438 elf_link_convert_common_type (struct bfd_link_info *info, int type)
9439 {
9440   /* Commom symbol can only appear in relocatable link.  */
9441   if (!bfd_link_relocatable (info))
9442     abort ();
9443   switch (info->elf_stt_common)
9444     {
9445     case unchanged:
9446       break;
9447     case elf_stt_common:
9448       type = STT_COMMON;
9449       break;
9450     case no_elf_stt_common:
9451       type = STT_OBJECT;
9452       break;
9453     }
9454   return type;
9455 }
9456
9457 /* Add an external symbol to the symbol table.  This is called from
9458    the hash table traversal routine.  When generating a shared object,
9459    we go through the symbol table twice.  The first time we output
9460    anything that might have been forced to local scope in a version
9461    script.  The second time we output the symbols that are still
9462    global symbols.  */
9463
9464 static bfd_boolean
9465 elf_link_output_extsym (struct bfd_hash_entry *bh, void *data)
9466 {
9467   struct elf_link_hash_entry *h = (struct elf_link_hash_entry *) bh;
9468   struct elf_outext_info *eoinfo = (struct elf_outext_info *) data;
9469   struct elf_final_link_info *flinfo = eoinfo->flinfo;
9470   bfd_boolean strip;
9471   Elf_Internal_Sym sym;
9472   asection *input_sec;
9473   const struct elf_backend_data *bed;
9474   long indx;
9475   int ret;
9476   unsigned int type;
9477
9478   if (h->root.type == bfd_link_hash_warning)
9479     {
9480       h = (struct elf_link_hash_entry *) h->root.u.i.link;
9481       if (h->root.type == bfd_link_hash_new)
9482         return TRUE;
9483     }
9484
9485   /* Decide whether to output this symbol in this pass.  */
9486   if (eoinfo->localsyms)
9487     {
9488       if (!h->forced_local)
9489         return TRUE;
9490     }
9491   else
9492     {
9493       if (h->forced_local)
9494         return TRUE;
9495     }
9496
9497   bed = get_elf_backend_data (flinfo->output_bfd);
9498
9499   if (h->root.type == bfd_link_hash_undefined)
9500     {
9501       /* If we have an undefined symbol reference here then it must have
9502          come from a shared library that is being linked in.  (Undefined
9503          references in regular files have already been handled unless
9504          they are in unreferenced sections which are removed by garbage
9505          collection).  */
9506       bfd_boolean ignore_undef = FALSE;
9507
9508       /* Some symbols may be special in that the fact that they're
9509          undefined can be safely ignored - let backend determine that.  */
9510       if (bed->elf_backend_ignore_undef_symbol)
9511         ignore_undef = bed->elf_backend_ignore_undef_symbol (h);
9512
9513       /* If we are reporting errors for this situation then do so now.  */
9514       if (!ignore_undef
9515           && h->ref_dynamic
9516           && (!h->ref_regular || flinfo->info->gc_sections)
9517           && !elf_link_check_versioned_symbol (flinfo->info, bed, h)
9518           && flinfo->info->unresolved_syms_in_shared_libs != RM_IGNORE)
9519         (*flinfo->info->callbacks->undefined_symbol)
9520           (flinfo->info, h->root.root.string,
9521            h->ref_regular ? NULL : h->root.u.undef.abfd,
9522            NULL, 0,
9523            flinfo->info->unresolved_syms_in_shared_libs == RM_GENERATE_ERROR);
9524
9525       /* Strip a global symbol defined in a discarded section.  */
9526       if (h->indx == -3)
9527         return TRUE;
9528     }
9529
9530   /* We should also warn if a forced local symbol is referenced from
9531      shared libraries.  */
9532   if (bfd_link_executable (flinfo->info)
9533       && h->forced_local
9534       && h->ref_dynamic
9535       && h->def_regular
9536       && !h->dynamic_def
9537       && h->ref_dynamic_nonweak
9538       && !elf_link_check_versioned_symbol (flinfo->info, bed, h))
9539     {
9540       bfd *def_bfd;
9541       const char *msg;
9542       struct elf_link_hash_entry *hi = h;
9543
9544       /* Check indirect symbol.  */
9545       while (hi->root.type == bfd_link_hash_indirect)
9546         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
9547
9548       if (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
9549         /* xgettext:c-format */
9550         msg = _("%B: internal symbol `%s' in %B is referenced by DSO");
9551       else if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN)
9552         /* xgettext:c-format */
9553         msg = _("%B: hidden symbol `%s' in %B is referenced by DSO");
9554       else
9555         /* xgettext:c-format */
9556         msg = _("%B: local symbol `%s' in %B is referenced by DSO");
9557       def_bfd = flinfo->output_bfd;
9558       if (hi->root.u.def.section != bfd_abs_section_ptr)
9559         def_bfd = hi->root.u.def.section->owner;
9560       _bfd_error_handler (msg, flinfo->output_bfd,
9561                           h->root.root.string, def_bfd);
9562       bfd_set_error (bfd_error_bad_value);
9563       eoinfo->failed = TRUE;
9564       return FALSE;
9565     }
9566
9567   /* We don't want to output symbols that have never been mentioned by
9568      a regular file, or that we have been told to strip.  However, if
9569      h->indx is set to -2, the symbol is used by a reloc and we must
9570      output it.  */
9571   strip = FALSE;
9572   if (h->indx == -2)
9573     ;
9574   else if ((h->def_dynamic
9575             || h->ref_dynamic
9576             || h->root.type == bfd_link_hash_new)
9577            && !h->def_regular
9578            && !h->ref_regular)
9579     strip = TRUE;
9580   else if (flinfo->info->strip == strip_all)
9581     strip = TRUE;
9582   else if (flinfo->info->strip == strip_some
9583            && bfd_hash_lookup (flinfo->info->keep_hash,
9584                                h->root.root.string, FALSE, FALSE) == NULL)
9585     strip = TRUE;
9586   else if ((h->root.type == bfd_link_hash_defined
9587             || h->root.type == bfd_link_hash_defweak)
9588            && ((flinfo->info->strip_discarded
9589                 && discarded_section (h->root.u.def.section))
9590                || ((h->root.u.def.section->flags & SEC_LINKER_CREATED) == 0
9591                    && h->root.u.def.section->owner != NULL
9592                    && (h->root.u.def.section->owner->flags & BFD_PLUGIN) != 0)))
9593     strip = TRUE;
9594   else if ((h->root.type == bfd_link_hash_undefined
9595             || h->root.type == bfd_link_hash_undefweak)
9596            && h->root.u.undef.abfd != NULL
9597            && (h->root.u.undef.abfd->flags & BFD_PLUGIN) != 0)
9598     strip = TRUE;
9599
9600   type = h->type;
9601
9602   /* If we're stripping it, and it's not a dynamic symbol, there's
9603      nothing else to do.   However, if it is a forced local symbol or
9604      an ifunc symbol we need to give the backend finish_dynamic_symbol
9605      function a chance to make it dynamic.  */
9606   if (strip
9607       && h->dynindx == -1
9608       && type != STT_GNU_IFUNC
9609       && !h->forced_local)
9610     return TRUE;
9611
9612   sym.st_value = 0;
9613   sym.st_size = h->size;
9614   sym.st_other = h->other;
9615   switch (h->root.type)
9616     {
9617     default:
9618     case bfd_link_hash_new:
9619     case bfd_link_hash_warning:
9620       abort ();
9621       return FALSE;
9622
9623     case bfd_link_hash_undefined:
9624     case bfd_link_hash_undefweak:
9625       input_sec = bfd_und_section_ptr;
9626       sym.st_shndx = SHN_UNDEF;
9627       break;
9628
9629     case bfd_link_hash_defined:
9630     case bfd_link_hash_defweak:
9631       {
9632         input_sec = h->root.u.def.section;
9633         if (input_sec->output_section != NULL)
9634           {
9635             sym.st_shndx =
9636               _bfd_elf_section_from_bfd_section (flinfo->output_bfd,
9637                                                  input_sec->output_section);
9638             if (sym.st_shndx == SHN_BAD)
9639               {
9640                 _bfd_error_handler
9641                   /* xgettext:c-format */
9642                   (_("%B: could not find output section %A for input section %A"),
9643                    flinfo->output_bfd, input_sec->output_section, input_sec);
9644                 bfd_set_error (bfd_error_nonrepresentable_section);
9645                 eoinfo->failed = TRUE;
9646                 return FALSE;
9647               }
9648
9649             /* ELF symbols in relocatable files are section relative,
9650                but in nonrelocatable files they are virtual
9651                addresses.  */
9652             sym.st_value = h->root.u.def.value + input_sec->output_offset;
9653             if (!bfd_link_relocatable (flinfo->info))
9654               {
9655                 sym.st_value += input_sec->output_section->vma;
9656                 if (h->type == STT_TLS)
9657                   {
9658                     asection *tls_sec = elf_hash_table (flinfo->info)->tls_sec;
9659                     if (tls_sec != NULL)
9660                       sym.st_value -= tls_sec->vma;
9661                   }
9662               }
9663           }
9664         else
9665           {
9666             BFD_ASSERT (input_sec->owner == NULL
9667                         || (input_sec->owner->flags & DYNAMIC) != 0);
9668             sym.st_shndx = SHN_UNDEF;
9669             input_sec = bfd_und_section_ptr;
9670           }
9671       }
9672       break;
9673
9674     case bfd_link_hash_common:
9675       input_sec = h->root.u.c.p->section;
9676       sym.st_shndx = bed->common_section_index (input_sec);
9677       sym.st_value = 1 << h->root.u.c.p->alignment_power;
9678       break;
9679
9680     case bfd_link_hash_indirect:
9681       /* These symbols are created by symbol versioning.  They point
9682          to the decorated version of the name.  For example, if the
9683          symbol foo@@GNU_1.2 is the default, which should be used when
9684          foo is used with no version, then we add an indirect symbol
9685          foo which points to foo@@GNU_1.2.  We ignore these symbols,
9686          since the indirected symbol is already in the hash table.  */
9687       return TRUE;
9688     }
9689
9690   if (type == STT_COMMON || type == STT_OBJECT)
9691     switch (h->root.type)
9692       {
9693       case bfd_link_hash_common:
9694         type = elf_link_convert_common_type (flinfo->info, type);
9695         break;
9696       case bfd_link_hash_defined:
9697       case bfd_link_hash_defweak:
9698         if (bed->common_definition (&sym))
9699           type = elf_link_convert_common_type (flinfo->info, type);
9700         else
9701           type = STT_OBJECT;
9702         break;
9703       case bfd_link_hash_undefined:
9704       case bfd_link_hash_undefweak:
9705         break;
9706       default:
9707         abort ();
9708       }
9709
9710   if (h->forced_local)
9711     {
9712       sym.st_info = ELF_ST_INFO (STB_LOCAL, type);
9713       /* Turn off visibility on local symbol.  */
9714       sym.st_other &= ~ELF_ST_VISIBILITY (-1);
9715     }
9716   /* Set STB_GNU_UNIQUE only if symbol is defined in regular object.  */
9717   else if (h->unique_global && h->def_regular)
9718     sym.st_info = ELF_ST_INFO (STB_GNU_UNIQUE, type);
9719   else if (h->root.type == bfd_link_hash_undefweak
9720            || h->root.type == bfd_link_hash_defweak)
9721     sym.st_info = ELF_ST_INFO (STB_WEAK, type);
9722   else
9723     sym.st_info = ELF_ST_INFO (STB_GLOBAL, type);
9724   sym.st_target_internal = h->target_internal;
9725
9726   /* Give the processor backend a chance to tweak the symbol value,
9727      and also to finish up anything that needs to be done for this
9728      symbol.  FIXME: Not calling elf_backend_finish_dynamic_symbol for
9729      forced local syms when non-shared is due to a historical quirk.
9730      STT_GNU_IFUNC symbol must go through PLT.  */
9731   if ((h->type == STT_GNU_IFUNC
9732        && h->def_regular
9733        && !bfd_link_relocatable (flinfo->info))
9734       || ((h->dynindx != -1
9735            || h->forced_local)
9736           && ((bfd_link_pic (flinfo->info)
9737                && (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
9738                    || h->root.type != bfd_link_hash_undefweak))
9739               || !h->forced_local)
9740           && elf_hash_table (flinfo->info)->dynamic_sections_created))
9741     {
9742       if (! ((*bed->elf_backend_finish_dynamic_symbol)
9743              (flinfo->output_bfd, flinfo->info, h, &sym)))
9744         {
9745           eoinfo->failed = TRUE;
9746           return FALSE;
9747         }
9748     }
9749
9750   /* If we are marking the symbol as undefined, and there are no
9751      non-weak references to this symbol from a regular object, then
9752      mark the symbol as weak undefined; if there are non-weak
9753      references, mark the symbol as strong.  We can't do this earlier,
9754      because it might not be marked as undefined until the
9755      finish_dynamic_symbol routine gets through with it.  */
9756   if (sym.st_shndx == SHN_UNDEF
9757       && h->ref_regular
9758       && (ELF_ST_BIND (sym.st_info) == STB_GLOBAL
9759           || ELF_ST_BIND (sym.st_info) == STB_WEAK))
9760     {
9761       int bindtype;
9762       type = ELF_ST_TYPE (sym.st_info);
9763
9764       /* Turn an undefined IFUNC symbol into a normal FUNC symbol. */
9765       if (type == STT_GNU_IFUNC)
9766         type = STT_FUNC;
9767
9768       if (h->ref_regular_nonweak)
9769         bindtype = STB_GLOBAL;
9770       else
9771         bindtype = STB_WEAK;
9772       sym.st_info = ELF_ST_INFO (bindtype, type);
9773     }
9774
9775   /* If this is a symbol defined in a dynamic library, don't use the
9776      symbol size from the dynamic library.  Relinking an executable
9777      against a new library may introduce gratuitous changes in the
9778      executable's symbols if we keep the size.  */
9779   if (sym.st_shndx == SHN_UNDEF
9780       && !h->def_regular
9781       && h->def_dynamic)
9782     sym.st_size = 0;
9783
9784   /* If a non-weak symbol with non-default visibility is not defined
9785      locally, it is a fatal error.  */
9786   if (!bfd_link_relocatable (flinfo->info)
9787       && ELF_ST_VISIBILITY (sym.st_other) != STV_DEFAULT
9788       && ELF_ST_BIND (sym.st_info) != STB_WEAK
9789       && h->root.type == bfd_link_hash_undefined
9790       && !h->def_regular)
9791     {
9792       const char *msg;
9793
9794       if (ELF_ST_VISIBILITY (sym.st_other) == STV_PROTECTED)
9795         /* xgettext:c-format */
9796         msg = _("%B: protected symbol `%s' isn't defined");
9797       else if (ELF_ST_VISIBILITY (sym.st_other) == STV_INTERNAL)
9798         /* xgettext:c-format */
9799         msg = _("%B: internal symbol `%s' isn't defined");
9800       else
9801         /* xgettext:c-format */
9802         msg = _("%B: hidden symbol `%s' isn't defined");
9803       _bfd_error_handler (msg, flinfo->output_bfd, h->root.root.string);
9804       bfd_set_error (bfd_error_bad_value);
9805       eoinfo->failed = TRUE;
9806       return FALSE;
9807     }
9808
9809   /* If this symbol should be put in the .dynsym section, then put it
9810      there now.  We already know the symbol index.  We also fill in
9811      the entry in the .hash section.  */
9812   if (elf_hash_table (flinfo->info)->dynsym != NULL
9813       && h->dynindx != -1
9814       && elf_hash_table (flinfo->info)->dynamic_sections_created)
9815     {
9816       bfd_byte *esym;
9817
9818       /* Since there is no version information in the dynamic string,
9819          if there is no version info in symbol version section, we will
9820          have a run-time problem if not linking executable, referenced
9821          by shared library, or not bound locally.  */
9822       if (h->verinfo.verdef == NULL
9823           && (!bfd_link_executable (flinfo->info)
9824               || h->ref_dynamic
9825               || !h->def_regular))
9826         {
9827           char *p = strrchr (h->root.root.string, ELF_VER_CHR);
9828
9829           if (p && p [1] != '\0')
9830             {
9831               _bfd_error_handler
9832                 /* xgettext:c-format */
9833                 (_("%B: No symbol version section for versioned symbol `%s'"),
9834                  flinfo->output_bfd, h->root.root.string);
9835               eoinfo->failed = TRUE;
9836               return FALSE;
9837             }
9838         }
9839
9840       sym.st_name = h->dynstr_index;
9841       esym = (elf_hash_table (flinfo->info)->dynsym->contents
9842               + h->dynindx * bed->s->sizeof_sym);
9843       if (!check_dynsym (flinfo->output_bfd, &sym))
9844         {
9845           eoinfo->failed = TRUE;
9846           return FALSE;
9847         }
9848       bed->s->swap_symbol_out (flinfo->output_bfd, &sym, esym, 0);
9849
9850       if (flinfo->hash_sec != NULL)
9851         {
9852           size_t hash_entry_size;
9853           bfd_byte *bucketpos;
9854           bfd_vma chain;
9855           size_t bucketcount;
9856           size_t bucket;
9857
9858           bucketcount = elf_hash_table (flinfo->info)->bucketcount;
9859           bucket = h->u.elf_hash_value % bucketcount;
9860
9861           hash_entry_size
9862             = elf_section_data (flinfo->hash_sec)->this_hdr.sh_entsize;
9863           bucketpos = ((bfd_byte *) flinfo->hash_sec->contents
9864                        + (bucket + 2) * hash_entry_size);
9865           chain = bfd_get (8 * hash_entry_size, flinfo->output_bfd, bucketpos);
9866           bfd_put (8 * hash_entry_size, flinfo->output_bfd, h->dynindx,
9867                    bucketpos);
9868           bfd_put (8 * hash_entry_size, flinfo->output_bfd, chain,
9869                    ((bfd_byte *) flinfo->hash_sec->contents
9870                     + (bucketcount + 2 + h->dynindx) * hash_entry_size));
9871         }
9872
9873       if (flinfo->symver_sec != NULL && flinfo->symver_sec->contents != NULL)
9874         {
9875           Elf_Internal_Versym iversym;
9876           Elf_External_Versym *eversym;
9877
9878           if (!h->def_regular)
9879             {
9880               if (h->verinfo.verdef == NULL
9881                   || (elf_dyn_lib_class (h->verinfo.verdef->vd_bfd)
9882                       & (DYN_AS_NEEDED | DYN_DT_NEEDED | DYN_NO_NEEDED)))
9883                 iversym.vs_vers = 0;
9884               else
9885                 iversym.vs_vers = h->verinfo.verdef->vd_exp_refno + 1;
9886             }
9887           else
9888             {
9889               if (h->verinfo.vertree == NULL)
9890                 iversym.vs_vers = 1;
9891               else
9892                 iversym.vs_vers = h->verinfo.vertree->vernum + 1;
9893               if (flinfo->info->create_default_symver)
9894                 iversym.vs_vers++;
9895             }
9896
9897           /* Turn on VERSYM_HIDDEN only if the hidden versioned symbol is
9898              defined locally.  */
9899           if (h->versioned == versioned_hidden && h->def_regular)
9900             iversym.vs_vers |= VERSYM_HIDDEN;
9901
9902           eversym = (Elf_External_Versym *) flinfo->symver_sec->contents;
9903           eversym += h->dynindx;
9904           _bfd_elf_swap_versym_out (flinfo->output_bfd, &iversym, eversym);
9905         }
9906     }
9907
9908   /* If the symbol is undefined, and we didn't output it to .dynsym,
9909      strip it from .symtab too.  Obviously we can't do this for
9910      relocatable output or when needed for --emit-relocs.  */
9911   else if (input_sec == bfd_und_section_ptr
9912            && h->indx != -2
9913            /* PR 22319 Do not strip global undefined symbols marked as being needed.  */
9914            && (h->mark != 1 || ELF_ST_BIND (sym.st_info) != STB_GLOBAL)
9915            && !bfd_link_relocatable (flinfo->info))
9916     return TRUE;
9917
9918   /* Also strip others that we couldn't earlier due to dynamic symbol
9919      processing.  */
9920   if (strip)
9921     return TRUE;
9922   if ((input_sec->flags & SEC_EXCLUDE) != 0)
9923     return TRUE;
9924
9925   /* Output a FILE symbol so that following locals are not associated
9926      with the wrong input file.  We need one for forced local symbols
9927      if we've seen more than one FILE symbol or when we have exactly
9928      one FILE symbol but global symbols are present in a file other
9929      than the one with the FILE symbol.  We also need one if linker
9930      defined symbols are present.  In practice these conditions are
9931      always met, so just emit the FILE symbol unconditionally.  */
9932   if (eoinfo->localsyms
9933       && !eoinfo->file_sym_done
9934       && eoinfo->flinfo->filesym_count != 0)
9935     {
9936       Elf_Internal_Sym fsym;
9937
9938       memset (&fsym, 0, sizeof (fsym));
9939       fsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
9940       fsym.st_shndx = SHN_ABS;
9941       if (!elf_link_output_symstrtab (eoinfo->flinfo, NULL, &fsym,
9942                                       bfd_und_section_ptr, NULL))
9943         return FALSE;
9944
9945       eoinfo->file_sym_done = TRUE;
9946     }
9947
9948   indx = bfd_get_symcount (flinfo->output_bfd);
9949   ret = elf_link_output_symstrtab (flinfo, h->root.root.string, &sym,
9950                                    input_sec, h);
9951   if (ret == 0)
9952     {
9953       eoinfo->failed = TRUE;
9954       return FALSE;
9955     }
9956   else if (ret == 1)
9957     h->indx = indx;
9958   else if (h->indx == -2)
9959     abort();
9960
9961   return TRUE;
9962 }
9963
9964 /* Return TRUE if special handling is done for relocs in SEC against
9965    symbols defined in discarded sections.  */
9966
9967 static bfd_boolean
9968 elf_section_ignore_discarded_relocs (asection *sec)
9969 {
9970   const struct elf_backend_data *bed;
9971
9972   switch (sec->sec_info_type)
9973     {
9974     case SEC_INFO_TYPE_STABS:
9975     case SEC_INFO_TYPE_EH_FRAME:
9976     case SEC_INFO_TYPE_EH_FRAME_ENTRY:
9977       return TRUE;
9978     default:
9979       break;
9980     }
9981
9982   bed = get_elf_backend_data (sec->owner);
9983   if (bed->elf_backend_ignore_discarded_relocs != NULL
9984       && (*bed->elf_backend_ignore_discarded_relocs) (sec))
9985     return TRUE;
9986
9987   return FALSE;
9988 }
9989
9990 /* Return a mask saying how ld should treat relocations in SEC against
9991    symbols defined in discarded sections.  If this function returns
9992    COMPLAIN set, ld will issue a warning message.  If this function
9993    returns PRETEND set, and the discarded section was link-once and the
9994    same size as the kept link-once section, ld will pretend that the
9995    symbol was actually defined in the kept section.  Otherwise ld will
9996    zero the reloc (at least that is the intent, but some cooperation by
9997    the target dependent code is needed, particularly for REL targets).  */
9998
9999 unsigned int
10000 _bfd_elf_default_action_discarded (asection *sec)
10001 {
10002   if (sec->flags & SEC_DEBUGGING)
10003     return PRETEND;
10004
10005   if (strcmp (".eh_frame", sec->name) == 0)
10006     return 0;
10007
10008   if (strcmp (".gcc_except_table", sec->name) == 0)
10009     return 0;
10010
10011   return COMPLAIN | PRETEND;
10012 }
10013
10014 /* Find a match between a section and a member of a section group.  */
10015
10016 static asection *
10017 match_group_member (asection *sec, asection *group,
10018                     struct bfd_link_info *info)
10019 {
10020   asection *first = elf_next_in_group (group);
10021   asection *s = first;
10022
10023   while (s != NULL)
10024     {
10025       if (bfd_elf_match_symbols_in_sections (s, sec, info))
10026         return s;
10027
10028       s = elf_next_in_group (s);
10029       if (s == first)
10030         break;
10031     }
10032
10033   return NULL;
10034 }
10035
10036 /* Check if the kept section of a discarded section SEC can be used
10037    to replace it.  Return the replacement if it is OK.  Otherwise return
10038    NULL.  */
10039
10040 asection *
10041 _bfd_elf_check_kept_section (asection *sec, struct bfd_link_info *info)
10042 {
10043   asection *kept;
10044
10045   kept = sec->kept_section;
10046   if (kept != NULL)
10047     {
10048       if ((kept->flags & SEC_GROUP) != 0)
10049         kept = match_group_member (sec, kept, info);
10050       if (kept != NULL
10051           && ((sec->rawsize != 0 ? sec->rawsize : sec->size)
10052               != (kept->rawsize != 0 ? kept->rawsize : kept->size)))
10053         kept = NULL;
10054       sec->kept_section = kept;
10055     }
10056   return kept;
10057 }
10058
10059 /* Link an input file into the linker output file.  This function
10060    handles all the sections and relocations of the input file at once.
10061    This is so that we only have to read the local symbols once, and
10062    don't have to keep them in memory.  */
10063
10064 static bfd_boolean
10065 elf_link_input_bfd (struct elf_final_link_info *flinfo, bfd *input_bfd)
10066 {
10067   int (*relocate_section)
10068     (bfd *, struct bfd_link_info *, bfd *, asection *, bfd_byte *,
10069      Elf_Internal_Rela *, Elf_Internal_Sym *, asection **);
10070   bfd *output_bfd;
10071   Elf_Internal_Shdr *symtab_hdr;
10072   size_t locsymcount;
10073   size_t extsymoff;
10074   Elf_Internal_Sym *isymbuf;
10075   Elf_Internal_Sym *isym;
10076   Elf_Internal_Sym *isymend;
10077   long *pindex;
10078   asection **ppsection;
10079   asection *o;
10080   const struct elf_backend_data *bed;
10081   struct elf_link_hash_entry **sym_hashes;
10082   bfd_size_type address_size;
10083   bfd_vma r_type_mask;
10084   int r_sym_shift;
10085   bfd_boolean have_file_sym = FALSE;
10086
10087   output_bfd = flinfo->output_bfd;
10088   bed = get_elf_backend_data (output_bfd);
10089   relocate_section = bed->elf_backend_relocate_section;
10090
10091   /* If this is a dynamic object, we don't want to do anything here:
10092      we don't want the local symbols, and we don't want the section
10093      contents.  */
10094   if ((input_bfd->flags & DYNAMIC) != 0)
10095     return TRUE;
10096
10097   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
10098   if (elf_bad_symtab (input_bfd))
10099     {
10100       locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
10101       extsymoff = 0;
10102     }
10103   else
10104     {
10105       locsymcount = symtab_hdr->sh_info;
10106       extsymoff = symtab_hdr->sh_info;
10107     }
10108
10109   /* Read the local symbols.  */
10110   isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
10111   if (isymbuf == NULL && locsymcount != 0)
10112     {
10113       isymbuf = bfd_elf_get_elf_syms (input_bfd, symtab_hdr, locsymcount, 0,
10114                                       flinfo->internal_syms,
10115                                       flinfo->external_syms,
10116                                       flinfo->locsym_shndx);
10117       if (isymbuf == NULL)
10118         return FALSE;
10119     }
10120
10121   /* Find local symbol sections and adjust values of symbols in
10122      SEC_MERGE sections.  Write out those local symbols we know are
10123      going into the output file.  */
10124   isymend = isymbuf + locsymcount;
10125   for (isym = isymbuf, pindex = flinfo->indices, ppsection = flinfo->sections;
10126        isym < isymend;
10127        isym++, pindex++, ppsection++)
10128     {
10129       asection *isec;
10130       const char *name;
10131       Elf_Internal_Sym osym;
10132       long indx;
10133       int ret;
10134
10135       *pindex = -1;
10136
10137       if (elf_bad_symtab (input_bfd))
10138         {
10139           if (ELF_ST_BIND (isym->st_info) != STB_LOCAL)
10140             {
10141               *ppsection = NULL;
10142               continue;
10143             }
10144         }
10145
10146       if (isym->st_shndx == SHN_UNDEF)
10147         isec = bfd_und_section_ptr;
10148       else if (isym->st_shndx == SHN_ABS)
10149         isec = bfd_abs_section_ptr;
10150       else if (isym->st_shndx == SHN_COMMON)
10151         isec = bfd_com_section_ptr;
10152       else
10153         {
10154           isec = bfd_section_from_elf_index (input_bfd, isym->st_shndx);
10155           if (isec == NULL)
10156             {
10157               /* Don't attempt to output symbols with st_shnx in the
10158                  reserved range other than SHN_ABS and SHN_COMMON.  */
10159               *ppsection = NULL;
10160               continue;
10161             }
10162           else if (isec->sec_info_type == SEC_INFO_TYPE_MERGE
10163                    && ELF_ST_TYPE (isym->st_info) != STT_SECTION)
10164             isym->st_value =
10165               _bfd_merged_section_offset (output_bfd, &isec,
10166                                           elf_section_data (isec)->sec_info,
10167                                           isym->st_value);
10168         }
10169
10170       *ppsection = isec;
10171
10172       /* Don't output the first, undefined, symbol.  In fact, don't
10173          output any undefined local symbol.  */
10174       if (isec == bfd_und_section_ptr)
10175         continue;
10176
10177       if (ELF_ST_TYPE (isym->st_info) == STT_SECTION)
10178         {
10179           /* We never output section symbols.  Instead, we use the
10180              section symbol of the corresponding section in the output
10181              file.  */
10182           continue;
10183         }
10184
10185       /* If we are stripping all symbols, we don't want to output this
10186          one.  */
10187       if (flinfo->info->strip == strip_all)
10188         continue;
10189
10190       /* If we are discarding all local symbols, we don't want to
10191          output this one.  If we are generating a relocatable output
10192          file, then some of the local symbols may be required by
10193          relocs; we output them below as we discover that they are
10194          needed.  */
10195       if (flinfo->info->discard == discard_all)
10196         continue;
10197
10198       /* If this symbol is defined in a section which we are
10199          discarding, we don't need to keep it.  */
10200       if (isym->st_shndx != SHN_UNDEF
10201           && isym->st_shndx < SHN_LORESERVE
10202           && bfd_section_removed_from_list (output_bfd,
10203                                             isec->output_section))
10204         continue;
10205
10206       /* Get the name of the symbol.  */
10207       name = bfd_elf_string_from_elf_section (input_bfd, symtab_hdr->sh_link,
10208                                               isym->st_name);
10209       if (name == NULL)
10210         return FALSE;
10211
10212       /* See if we are discarding symbols with this name.  */
10213       if ((flinfo->info->strip == strip_some
10214            && (bfd_hash_lookup (flinfo->info->keep_hash, name, FALSE, FALSE)
10215                == NULL))
10216           || (((flinfo->info->discard == discard_sec_merge
10217                 && (isec->flags & SEC_MERGE)
10218                 && !bfd_link_relocatable (flinfo->info))
10219                || flinfo->info->discard == discard_l)
10220               && bfd_is_local_label_name (input_bfd, name)))
10221         continue;
10222
10223       if (ELF_ST_TYPE (isym->st_info) == STT_FILE)
10224         {
10225           if (input_bfd->lto_output)
10226             /* -flto puts a temp file name here.  This means builds
10227                are not reproducible.  Discard the symbol.  */
10228             continue;
10229           have_file_sym = TRUE;
10230           flinfo->filesym_count += 1;
10231         }
10232       if (!have_file_sym)
10233         {
10234           /* In the absence of debug info, bfd_find_nearest_line uses
10235              FILE symbols to determine the source file for local
10236              function symbols.  Provide a FILE symbol here if input
10237              files lack such, so that their symbols won't be
10238              associated with a previous input file.  It's not the
10239              source file, but the best we can do.  */
10240           have_file_sym = TRUE;
10241           flinfo->filesym_count += 1;
10242           memset (&osym, 0, sizeof (osym));
10243           osym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
10244           osym.st_shndx = SHN_ABS;
10245           if (!elf_link_output_symstrtab (flinfo,
10246                                           (input_bfd->lto_output ? NULL
10247                                            : input_bfd->filename),
10248                                           &osym, bfd_abs_section_ptr,
10249                                           NULL))
10250             return FALSE;
10251         }
10252
10253       osym = *isym;
10254
10255       /* Adjust the section index for the output file.  */
10256       osym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
10257                                                          isec->output_section);
10258       if (osym.st_shndx == SHN_BAD)
10259         return FALSE;
10260
10261       /* ELF symbols in relocatable files are section relative, but
10262          in executable files they are virtual addresses.  Note that
10263          this code assumes that all ELF sections have an associated
10264          BFD section with a reasonable value for output_offset; below
10265          we assume that they also have a reasonable value for
10266          output_section.  Any special sections must be set up to meet
10267          these requirements.  */
10268       osym.st_value += isec->output_offset;
10269       if (!bfd_link_relocatable (flinfo->info))
10270         {
10271           osym.st_value += isec->output_section->vma;
10272           if (ELF_ST_TYPE (osym.st_info) == STT_TLS)
10273             {
10274               /* STT_TLS symbols are relative to PT_TLS segment base.  */
10275               BFD_ASSERT (elf_hash_table (flinfo->info)->tls_sec != NULL);
10276               osym.st_value -= elf_hash_table (flinfo->info)->tls_sec->vma;
10277             }
10278         }
10279
10280       indx = bfd_get_symcount (output_bfd);
10281       ret = elf_link_output_symstrtab (flinfo, name, &osym, isec, NULL);
10282       if (ret == 0)
10283         return FALSE;
10284       else if (ret == 1)
10285         *pindex = indx;
10286     }
10287
10288   if (bed->s->arch_size == 32)
10289     {
10290       r_type_mask = 0xff;
10291       r_sym_shift = 8;
10292       address_size = 4;
10293     }
10294   else
10295     {
10296       r_type_mask = 0xffffffff;
10297       r_sym_shift = 32;
10298       address_size = 8;
10299     }
10300
10301   /* Relocate the contents of each section.  */
10302   sym_hashes = elf_sym_hashes (input_bfd);
10303   for (o = input_bfd->sections; o != NULL; o = o->next)
10304     {
10305       bfd_byte *contents;
10306
10307       if (! o->linker_mark)
10308         {
10309           /* This section was omitted from the link.  */
10310           continue;
10311         }
10312
10313       if (!flinfo->info->resolve_section_groups
10314           && (o->flags & (SEC_LINKER_CREATED | SEC_GROUP)) == SEC_GROUP)
10315         {
10316           /* Deal with the group signature symbol.  */
10317           struct bfd_elf_section_data *sec_data = elf_section_data (o);
10318           unsigned long symndx = sec_data->this_hdr.sh_info;
10319           asection *osec = o->output_section;
10320
10321           BFD_ASSERT (bfd_link_relocatable (flinfo->info));
10322           if (symndx >= locsymcount
10323               || (elf_bad_symtab (input_bfd)
10324                   && flinfo->sections[symndx] == NULL))
10325             {
10326               struct elf_link_hash_entry *h = sym_hashes[symndx - extsymoff];
10327               while (h->root.type == bfd_link_hash_indirect
10328                      || h->root.type == bfd_link_hash_warning)
10329                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
10330               /* Arrange for symbol to be output.  */
10331               h->indx = -2;
10332               elf_section_data (osec)->this_hdr.sh_info = -2;
10333             }
10334           else if (ELF_ST_TYPE (isymbuf[symndx].st_info) == STT_SECTION)
10335             {
10336               /* We'll use the output section target_index.  */
10337               asection *sec = flinfo->sections[symndx]->output_section;
10338               elf_section_data (osec)->this_hdr.sh_info = sec->target_index;
10339             }
10340           else
10341             {
10342               if (flinfo->indices[symndx] == -1)
10343                 {
10344                   /* Otherwise output the local symbol now.  */
10345                   Elf_Internal_Sym sym = isymbuf[symndx];
10346                   asection *sec = flinfo->sections[symndx]->output_section;
10347                   const char *name;
10348                   long indx;
10349                   int ret;
10350
10351                   name = bfd_elf_string_from_elf_section (input_bfd,
10352                                                           symtab_hdr->sh_link,
10353                                                           sym.st_name);
10354                   if (name == NULL)
10355                     return FALSE;
10356
10357                   sym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
10358                                                                     sec);
10359                   if (sym.st_shndx == SHN_BAD)
10360                     return FALSE;
10361
10362                   sym.st_value += o->output_offset;
10363
10364                   indx = bfd_get_symcount (output_bfd);
10365                   ret = elf_link_output_symstrtab (flinfo, name, &sym, o,
10366                                                    NULL);
10367                   if (ret == 0)
10368                     return FALSE;
10369                   else if (ret == 1)
10370                     flinfo->indices[symndx] = indx;
10371                   else
10372                     abort ();
10373                 }
10374               elf_section_data (osec)->this_hdr.sh_info
10375                 = flinfo->indices[symndx];
10376             }
10377         }
10378
10379       if ((o->flags & SEC_HAS_CONTENTS) == 0
10380           || (o->size == 0 && (o->flags & SEC_RELOC) == 0))
10381         continue;
10382
10383       if ((o->flags & SEC_LINKER_CREATED) != 0)
10384         {
10385           /* Section was created by _bfd_elf_link_create_dynamic_sections
10386              or somesuch.  */
10387           continue;
10388         }
10389
10390       /* Get the contents of the section.  They have been cached by a
10391          relaxation routine.  Note that o is a section in an input
10392          file, so the contents field will not have been set by any of
10393          the routines which work on output files.  */
10394       if (elf_section_data (o)->this_hdr.contents != NULL)
10395         {
10396           contents = elf_section_data (o)->this_hdr.contents;
10397           if (bed->caches_rawsize
10398               && o->rawsize != 0
10399               && o->rawsize < o->size)
10400             {
10401               memcpy (flinfo->contents, contents, o->rawsize);
10402               contents = flinfo->contents;
10403             }
10404         }
10405       else
10406         {
10407           contents = flinfo->contents;
10408           if (! bfd_get_full_section_contents (input_bfd, o, &contents))
10409             return FALSE;
10410         }
10411
10412       if ((o->flags & SEC_RELOC) != 0)
10413         {
10414           Elf_Internal_Rela *internal_relocs;
10415           Elf_Internal_Rela *rel, *relend;
10416           int action_discarded;
10417           int ret;
10418
10419           /* Get the swapped relocs.  */
10420           internal_relocs
10421             = _bfd_elf_link_read_relocs (input_bfd, o, flinfo->external_relocs,
10422                                          flinfo->internal_relocs, FALSE);
10423           if (internal_relocs == NULL
10424               && o->reloc_count > 0)
10425             return FALSE;
10426
10427           /* We need to reverse-copy input .ctors/.dtors sections if
10428              they are placed in .init_array/.finit_array for output.  */
10429           if (o->size > address_size
10430               && ((strncmp (o->name, ".ctors", 6) == 0
10431                    && strcmp (o->output_section->name,
10432                               ".init_array") == 0)
10433                   || (strncmp (o->name, ".dtors", 6) == 0
10434                       && strcmp (o->output_section->name,
10435                                  ".fini_array") == 0))
10436               && (o->name[6] == 0 || o->name[6] == '.'))
10437             {
10438               if (o->size * bed->s->int_rels_per_ext_rel
10439                   != o->reloc_count * address_size)
10440                 {
10441                   _bfd_error_handler
10442                     /* xgettext:c-format */
10443                     (_("error: %B: size of section %A is not "
10444                        "multiple of address size"),
10445                      input_bfd, o);
10446                   bfd_set_error (bfd_error_bad_value);
10447                   return FALSE;
10448                 }
10449               o->flags |= SEC_ELF_REVERSE_COPY;
10450             }
10451
10452           action_discarded = -1;
10453           if (!elf_section_ignore_discarded_relocs (o))
10454             action_discarded = (*bed->action_discarded) (o);
10455
10456           /* Run through the relocs evaluating complex reloc symbols and
10457              looking for relocs against symbols from discarded sections
10458              or section symbols from removed link-once sections.
10459              Complain about relocs against discarded sections.  Zero
10460              relocs against removed link-once sections.  */
10461
10462           rel = internal_relocs;
10463           relend = rel + o->reloc_count;
10464           for ( ; rel < relend; rel++)
10465             {
10466               unsigned long r_symndx = rel->r_info >> r_sym_shift;
10467               unsigned int s_type;
10468               asection **ps, *sec;
10469               struct elf_link_hash_entry *h = NULL;
10470               const char *sym_name;
10471
10472               if (r_symndx == STN_UNDEF)
10473                 continue;
10474
10475               if (r_symndx >= locsymcount
10476                   || (elf_bad_symtab (input_bfd)
10477                       && flinfo->sections[r_symndx] == NULL))
10478                 {
10479                   h = sym_hashes[r_symndx - extsymoff];
10480
10481                   /* Badly formatted input files can contain relocs that
10482                      reference non-existant symbols.  Check here so that
10483                      we do not seg fault.  */
10484                   if (h == NULL)
10485                     {
10486                       _bfd_error_handler
10487                         /* xgettext:c-format */
10488                         (_("error: %B contains a reloc (%#Lx) for section %A "
10489                            "that references a non-existent global symbol"),
10490                          input_bfd, rel->r_info, o);
10491                       bfd_set_error (bfd_error_bad_value);
10492                       return FALSE;
10493                     }
10494
10495                   while (h->root.type == bfd_link_hash_indirect
10496                          || h->root.type == bfd_link_hash_warning)
10497                     h = (struct elf_link_hash_entry *) h->root.u.i.link;
10498
10499                   s_type = h->type;
10500
10501                   /* If a plugin symbol is referenced from a non-IR file,
10502                      mark the symbol as undefined.  Note that the
10503                      linker may attach linker created dynamic sections
10504                      to the plugin bfd.  Symbols defined in linker
10505                      created sections are not plugin symbols.  */
10506                   if ((h->root.non_ir_ref_regular
10507                        || h->root.non_ir_ref_dynamic)
10508                       && (h->root.type == bfd_link_hash_defined
10509                           || h->root.type == bfd_link_hash_defweak)
10510                       && (h->root.u.def.section->flags
10511                           & SEC_LINKER_CREATED) == 0
10512                       && h->root.u.def.section->owner != NULL
10513                       && (h->root.u.def.section->owner->flags
10514                           & BFD_PLUGIN) != 0)
10515                     {
10516                       h->root.type = bfd_link_hash_undefined;
10517                       h->root.u.undef.abfd = h->root.u.def.section->owner;
10518                     }
10519
10520                   ps = NULL;
10521                   if (h->root.type == bfd_link_hash_defined
10522                       || h->root.type == bfd_link_hash_defweak)
10523                     ps = &h->root.u.def.section;
10524
10525                   sym_name = h->root.root.string;
10526                 }
10527               else
10528                 {
10529                   Elf_Internal_Sym *sym = isymbuf + r_symndx;
10530
10531                   s_type = ELF_ST_TYPE (sym->st_info);
10532                   ps = &flinfo->sections[r_symndx];
10533                   sym_name = bfd_elf_sym_name (input_bfd, symtab_hdr,
10534                                                sym, *ps);
10535                 }
10536
10537               if ((s_type == STT_RELC || s_type == STT_SRELC)
10538                   && !bfd_link_relocatable (flinfo->info))
10539                 {
10540                   bfd_vma val;
10541                   bfd_vma dot = (rel->r_offset
10542                                  + o->output_offset + o->output_section->vma);
10543 #ifdef DEBUG
10544                   printf ("Encountered a complex symbol!");
10545                   printf (" (input_bfd %s, section %s, reloc %ld\n",
10546                           input_bfd->filename, o->name,
10547                           (long) (rel - internal_relocs));
10548                   printf (" symbol: idx  %8.8lx, name %s\n",
10549                           r_symndx, sym_name);
10550                   printf (" reloc : info %8.8lx, addr %8.8lx\n",
10551                           (unsigned long) rel->r_info,
10552                           (unsigned long) rel->r_offset);
10553 #endif
10554                   if (!eval_symbol (&val, &sym_name, input_bfd, flinfo, dot,
10555                                     isymbuf, locsymcount, s_type == STT_SRELC))
10556                     return FALSE;
10557
10558                   /* Symbol evaluated OK.  Update to absolute value.  */
10559                   set_symbol_value (input_bfd, isymbuf, locsymcount,
10560                                     r_symndx, val);
10561                   continue;
10562                 }
10563
10564               if (action_discarded != -1 && ps != NULL)
10565                 {
10566                   /* Complain if the definition comes from a
10567                      discarded section.  */
10568                   if ((sec = *ps) != NULL && discarded_section (sec))
10569                     {
10570                       BFD_ASSERT (r_symndx != STN_UNDEF);
10571                       if (action_discarded & COMPLAIN)
10572                         (*flinfo->info->callbacks->einfo)
10573                           /* xgettext:c-format */
10574                           (_("%X`%s' referenced in section `%A' of %B: "
10575                              "defined in discarded section `%A' of %B\n"),
10576                            sym_name, o, input_bfd, sec, sec->owner);
10577
10578                       /* Try to do the best we can to support buggy old
10579                          versions of gcc.  Pretend that the symbol is
10580                          really defined in the kept linkonce section.
10581                          FIXME: This is quite broken.  Modifying the
10582                          symbol here means we will be changing all later
10583                          uses of the symbol, not just in this section.  */
10584                       if (action_discarded & PRETEND)
10585                         {
10586                           asection *kept;
10587
10588                           kept = _bfd_elf_check_kept_section (sec,
10589                                                               flinfo->info);
10590                           if (kept != NULL)
10591                             {
10592                               *ps = kept;
10593                               continue;
10594                             }
10595                         }
10596                     }
10597                 }
10598             }
10599
10600           /* Relocate the section by invoking a back end routine.
10601
10602              The back end routine is responsible for adjusting the
10603              section contents as necessary, and (if using Rela relocs
10604              and generating a relocatable output file) adjusting the
10605              reloc addend as necessary.
10606
10607              The back end routine does not have to worry about setting
10608              the reloc address or the reloc symbol index.
10609
10610              The back end routine is given a pointer to the swapped in
10611              internal symbols, and can access the hash table entries
10612              for the external symbols via elf_sym_hashes (input_bfd).
10613
10614              When generating relocatable output, the back end routine
10615              must handle STB_LOCAL/STT_SECTION symbols specially.  The
10616              output symbol is going to be a section symbol
10617              corresponding to the output section, which will require
10618              the addend to be adjusted.  */
10619
10620           ret = (*relocate_section) (output_bfd, flinfo->info,
10621                                      input_bfd, o, contents,
10622                                      internal_relocs,
10623                                      isymbuf,
10624                                      flinfo->sections);
10625           if (!ret)
10626             return FALSE;
10627
10628           if (ret == 2
10629               || bfd_link_relocatable (flinfo->info)
10630               || flinfo->info->emitrelocations)
10631             {
10632               Elf_Internal_Rela *irela;
10633               Elf_Internal_Rela *irelaend, *irelamid;
10634               bfd_vma last_offset;
10635               struct elf_link_hash_entry **rel_hash;
10636               struct elf_link_hash_entry **rel_hash_list, **rela_hash_list;
10637               Elf_Internal_Shdr *input_rel_hdr, *input_rela_hdr;
10638               unsigned int next_erel;
10639               bfd_boolean rela_normal;
10640               struct bfd_elf_section_data *esdi, *esdo;
10641
10642               esdi = elf_section_data (o);
10643               esdo = elf_section_data (o->output_section);
10644               rela_normal = FALSE;
10645
10646               /* Adjust the reloc addresses and symbol indices.  */
10647
10648               irela = internal_relocs;
10649               irelaend = irela + o->reloc_count;
10650               rel_hash = esdo->rel.hashes + esdo->rel.count;
10651               /* We start processing the REL relocs, if any.  When we reach
10652                  IRELAMID in the loop, we switch to the RELA relocs.  */
10653               irelamid = irela;
10654               if (esdi->rel.hdr != NULL)
10655                 irelamid += (NUM_SHDR_ENTRIES (esdi->rel.hdr)
10656                              * bed->s->int_rels_per_ext_rel);
10657               rel_hash_list = rel_hash;
10658               rela_hash_list = NULL;
10659               last_offset = o->output_offset;
10660               if (!bfd_link_relocatable (flinfo->info))
10661                 last_offset += o->output_section->vma;
10662               for (next_erel = 0; irela < irelaend; irela++, next_erel++)
10663                 {
10664                   unsigned long r_symndx;
10665                   asection *sec;
10666                   Elf_Internal_Sym sym;
10667
10668                   if (next_erel == bed->s->int_rels_per_ext_rel)
10669                     {
10670                       rel_hash++;
10671                       next_erel = 0;
10672                     }
10673
10674                   if (irela == irelamid)
10675                     {
10676                       rel_hash = esdo->rela.hashes + esdo->rela.count;
10677                       rela_hash_list = rel_hash;
10678                       rela_normal = bed->rela_normal;
10679                     }
10680
10681                   irela->r_offset = _bfd_elf_section_offset (output_bfd,
10682                                                              flinfo->info, o,
10683                                                              irela->r_offset);
10684                   if (irela->r_offset >= (bfd_vma) -2)
10685                     {
10686                       /* This is a reloc for a deleted entry or somesuch.
10687                          Turn it into an R_*_NONE reloc, at the same
10688                          offset as the last reloc.  elf_eh_frame.c and
10689                          bfd_elf_discard_info rely on reloc offsets
10690                          being ordered.  */
10691                       irela->r_offset = last_offset;
10692                       irela->r_info = 0;
10693                       irela->r_addend = 0;
10694                       continue;
10695                     }
10696
10697                   irela->r_offset += o->output_offset;
10698
10699                   /* Relocs in an executable have to be virtual addresses.  */
10700                   if (!bfd_link_relocatable (flinfo->info))
10701                     irela->r_offset += o->output_section->vma;
10702
10703                   last_offset = irela->r_offset;
10704
10705                   r_symndx = irela->r_info >> r_sym_shift;
10706                   if (r_symndx == STN_UNDEF)
10707                     continue;
10708
10709                   if (r_symndx >= locsymcount
10710                       || (elf_bad_symtab (input_bfd)
10711                           && flinfo->sections[r_symndx] == NULL))
10712                     {
10713                       struct elf_link_hash_entry *rh;
10714                       unsigned long indx;
10715
10716                       /* This is a reloc against a global symbol.  We
10717                          have not yet output all the local symbols, so
10718                          we do not know the symbol index of any global
10719                          symbol.  We set the rel_hash entry for this
10720                          reloc to point to the global hash table entry
10721                          for this symbol.  The symbol index is then
10722                          set at the end of bfd_elf_final_link.  */
10723                       indx = r_symndx - extsymoff;
10724                       rh = elf_sym_hashes (input_bfd)[indx];
10725                       while (rh->root.type == bfd_link_hash_indirect
10726                              || rh->root.type == bfd_link_hash_warning)
10727                         rh = (struct elf_link_hash_entry *) rh->root.u.i.link;
10728
10729                       /* Setting the index to -2 tells
10730                          elf_link_output_extsym that this symbol is
10731                          used by a reloc.  */
10732                       BFD_ASSERT (rh->indx < 0);
10733                       rh->indx = -2;
10734                       *rel_hash = rh;
10735
10736                       continue;
10737                     }
10738
10739                   /* This is a reloc against a local symbol.  */
10740
10741                   *rel_hash = NULL;
10742                   sym = isymbuf[r_symndx];
10743                   sec = flinfo->sections[r_symndx];
10744                   if (ELF_ST_TYPE (sym.st_info) == STT_SECTION)
10745                     {
10746                       /* I suppose the backend ought to fill in the
10747                          section of any STT_SECTION symbol against a
10748                          processor specific section.  */
10749                       r_symndx = STN_UNDEF;
10750                       if (bfd_is_abs_section (sec))
10751                         ;
10752                       else if (sec == NULL || sec->owner == NULL)
10753                         {
10754                           bfd_set_error (bfd_error_bad_value);
10755                           return FALSE;
10756                         }
10757                       else
10758                         {
10759                           asection *osec = sec->output_section;
10760
10761                           /* If we have discarded a section, the output
10762                              section will be the absolute section.  In
10763                              case of discarded SEC_MERGE sections, use
10764                              the kept section.  relocate_section should
10765                              have already handled discarded linkonce
10766                              sections.  */
10767                           if (bfd_is_abs_section (osec)
10768                               && sec->kept_section != NULL
10769                               && sec->kept_section->output_section != NULL)
10770                             {
10771                               osec = sec->kept_section->output_section;
10772                               irela->r_addend -= osec->vma;
10773                             }
10774
10775                           if (!bfd_is_abs_section (osec))
10776                             {
10777                               r_symndx = osec->target_index;
10778                               if (r_symndx == STN_UNDEF)
10779                                 {
10780                                   irela->r_addend += osec->vma;
10781                                   osec = _bfd_nearby_section (output_bfd, osec,
10782                                                               osec->vma);
10783                                   irela->r_addend -= osec->vma;
10784                                   r_symndx = osec->target_index;
10785                                 }
10786                             }
10787                         }
10788
10789                       /* Adjust the addend according to where the
10790                          section winds up in the output section.  */
10791                       if (rela_normal)
10792                         irela->r_addend += sec->output_offset;
10793                     }
10794                   else
10795                     {
10796                       if (flinfo->indices[r_symndx] == -1)
10797                         {
10798                           unsigned long shlink;
10799                           const char *name;
10800                           asection *osec;
10801                           long indx;
10802
10803                           if (flinfo->info->strip == strip_all)
10804                             {
10805                               /* You can't do ld -r -s.  */
10806                               bfd_set_error (bfd_error_invalid_operation);
10807                               return FALSE;
10808                             }
10809
10810                           /* This symbol was skipped earlier, but
10811                              since it is needed by a reloc, we
10812                              must output it now.  */
10813                           shlink = symtab_hdr->sh_link;
10814                           name = (bfd_elf_string_from_elf_section
10815                                   (input_bfd, shlink, sym.st_name));
10816                           if (name == NULL)
10817                             return FALSE;
10818
10819                           osec = sec->output_section;
10820                           sym.st_shndx =
10821                             _bfd_elf_section_from_bfd_section (output_bfd,
10822                                                                osec);
10823                           if (sym.st_shndx == SHN_BAD)
10824                             return FALSE;
10825
10826                           sym.st_value += sec->output_offset;
10827                           if (!bfd_link_relocatable (flinfo->info))
10828                             {
10829                               sym.st_value += osec->vma;
10830                               if (ELF_ST_TYPE (sym.st_info) == STT_TLS)
10831                                 {
10832                                   /* STT_TLS symbols are relative to PT_TLS
10833                                      segment base.  */
10834                                   BFD_ASSERT (elf_hash_table (flinfo->info)
10835                                               ->tls_sec != NULL);
10836                                   sym.st_value -= (elf_hash_table (flinfo->info)
10837                                                    ->tls_sec->vma);
10838                                 }
10839                             }
10840
10841                           indx = bfd_get_symcount (output_bfd);
10842                           ret = elf_link_output_symstrtab (flinfo, name,
10843                                                            &sym, sec,
10844                                                            NULL);
10845                           if (ret == 0)
10846                             return FALSE;
10847                           else if (ret == 1)
10848                             flinfo->indices[r_symndx] = indx;
10849                           else
10850                             abort ();
10851                         }
10852
10853                       r_symndx = flinfo->indices[r_symndx];
10854                     }
10855
10856                   irela->r_info = ((bfd_vma) r_symndx << r_sym_shift
10857                                    | (irela->r_info & r_type_mask));
10858                 }
10859
10860               /* Swap out the relocs.  */
10861               input_rel_hdr = esdi->rel.hdr;
10862               if (input_rel_hdr && input_rel_hdr->sh_size != 0)
10863                 {
10864                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
10865                                                      input_rel_hdr,
10866                                                      internal_relocs,
10867                                                      rel_hash_list))
10868                     return FALSE;
10869                   internal_relocs += (NUM_SHDR_ENTRIES (input_rel_hdr)
10870                                       * bed->s->int_rels_per_ext_rel);
10871                   rel_hash_list += NUM_SHDR_ENTRIES (input_rel_hdr);
10872                 }
10873
10874               input_rela_hdr = esdi->rela.hdr;
10875               if (input_rela_hdr && input_rela_hdr->sh_size != 0)
10876                 {
10877                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
10878                                                      input_rela_hdr,
10879                                                      internal_relocs,
10880                                                      rela_hash_list))
10881                     return FALSE;
10882                 }
10883             }
10884         }
10885
10886       /* Write out the modified section contents.  */
10887       if (bed->elf_backend_write_section
10888           && (*bed->elf_backend_write_section) (output_bfd, flinfo->info, o,
10889                                                 contents))
10890         {
10891           /* Section written out.  */
10892         }
10893       else switch (o->sec_info_type)
10894         {
10895         case SEC_INFO_TYPE_STABS:
10896           if (! (_bfd_write_section_stabs
10897                  (output_bfd,
10898                   &elf_hash_table (flinfo->info)->stab_info,
10899                   o, &elf_section_data (o)->sec_info, contents)))
10900             return FALSE;
10901           break;
10902         case SEC_INFO_TYPE_MERGE:
10903           if (! _bfd_write_merged_section (output_bfd, o,
10904                                            elf_section_data (o)->sec_info))
10905             return FALSE;
10906           break;
10907         case SEC_INFO_TYPE_EH_FRAME:
10908           {
10909             if (! _bfd_elf_write_section_eh_frame (output_bfd, flinfo->info,
10910                                                    o, contents))
10911               return FALSE;
10912           }
10913           break;
10914         case SEC_INFO_TYPE_EH_FRAME_ENTRY:
10915           {
10916             if (! _bfd_elf_write_section_eh_frame_entry (output_bfd,
10917                                                          flinfo->info,
10918                                                          o, contents))
10919               return FALSE;
10920           }
10921           break;
10922         default:
10923           {
10924             if (! (o->flags & SEC_EXCLUDE))
10925               {
10926                 file_ptr offset = (file_ptr) o->output_offset;
10927                 bfd_size_type todo = o->size;
10928
10929                 offset *= bfd_octets_per_byte (output_bfd);
10930
10931                 if ((o->flags & SEC_ELF_REVERSE_COPY))
10932                   {
10933                     /* Reverse-copy input section to output.  */
10934                     do
10935                       {
10936                         todo -= address_size;
10937                         if (! bfd_set_section_contents (output_bfd,
10938                                                         o->output_section,
10939                                                         contents + todo,
10940                                                         offset,
10941                                                         address_size))
10942                           return FALSE;
10943                         if (todo == 0)
10944                           break;
10945                         offset += address_size;
10946                       }
10947                     while (1);
10948                   }
10949                 else if (! bfd_set_section_contents (output_bfd,
10950                                                      o->output_section,
10951                                                      contents,
10952                                                      offset, todo))
10953                   return FALSE;
10954               }
10955           }
10956           break;
10957         }
10958     }
10959
10960   return TRUE;
10961 }
10962
10963 /* Generate a reloc when linking an ELF file.  This is a reloc
10964    requested by the linker, and does not come from any input file.  This
10965    is used to build constructor and destructor tables when linking
10966    with -Ur.  */
10967
10968 static bfd_boolean
10969 elf_reloc_link_order (bfd *output_bfd,
10970                       struct bfd_link_info *info,
10971                       asection *output_section,
10972                       struct bfd_link_order *link_order)
10973 {
10974   reloc_howto_type *howto;
10975   long indx;
10976   bfd_vma offset;
10977   bfd_vma addend;
10978   struct bfd_elf_section_reloc_data *reldata;
10979   struct elf_link_hash_entry **rel_hash_ptr;
10980   Elf_Internal_Shdr *rel_hdr;
10981   const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
10982   Elf_Internal_Rela irel[MAX_INT_RELS_PER_EXT_REL];
10983   bfd_byte *erel;
10984   unsigned int i;
10985   struct bfd_elf_section_data *esdo = elf_section_data (output_section);
10986
10987   howto = bfd_reloc_type_lookup (output_bfd, link_order->u.reloc.p->reloc);
10988   if (howto == NULL)
10989     {
10990       bfd_set_error (bfd_error_bad_value);
10991       return FALSE;
10992     }
10993
10994   addend = link_order->u.reloc.p->addend;
10995
10996   if (esdo->rel.hdr)
10997     reldata = &esdo->rel;
10998   else if (esdo->rela.hdr)
10999     reldata = &esdo->rela;
11000   else
11001     {
11002       reldata = NULL;
11003       BFD_ASSERT (0);
11004     }
11005
11006   /* Figure out the symbol index.  */
11007   rel_hash_ptr = reldata->hashes + reldata->count;
11008   if (link_order->type == bfd_section_reloc_link_order)
11009     {
11010       indx = link_order->u.reloc.p->u.section->target_index;
11011       BFD_ASSERT (indx != 0);
11012       *rel_hash_ptr = NULL;
11013     }
11014   else
11015     {
11016       struct elf_link_hash_entry *h;
11017
11018       /* Treat a reloc against a defined symbol as though it were
11019          actually against the section.  */
11020       h = ((struct elf_link_hash_entry *)
11021            bfd_wrapped_link_hash_lookup (output_bfd, info,
11022                                          link_order->u.reloc.p->u.name,
11023                                          FALSE, FALSE, TRUE));
11024       if (h != NULL
11025           && (h->root.type == bfd_link_hash_defined
11026               || h->root.type == bfd_link_hash_defweak))
11027         {
11028           asection *section;
11029
11030           section = h->root.u.def.section;
11031           indx = section->output_section->target_index;
11032           *rel_hash_ptr = NULL;
11033           /* It seems that we ought to add the symbol value to the
11034              addend here, but in practice it has already been added
11035              because it was passed to constructor_callback.  */
11036           addend += section->output_section->vma + section->output_offset;
11037         }
11038       else if (h != NULL)
11039         {
11040           /* Setting the index to -2 tells elf_link_output_extsym that
11041              this symbol is used by a reloc.  */
11042           h->indx = -2;
11043           *rel_hash_ptr = h;
11044           indx = 0;
11045         }
11046       else
11047         {
11048           (*info->callbacks->unattached_reloc)
11049             (info, link_order->u.reloc.p->u.name, NULL, NULL, 0);
11050           indx = 0;
11051         }
11052     }
11053
11054   /* If this is an inplace reloc, we must write the addend into the
11055      object file.  */
11056   if (howto->partial_inplace && addend != 0)
11057     {
11058       bfd_size_type size;
11059       bfd_reloc_status_type rstat;
11060       bfd_byte *buf;
11061       bfd_boolean ok;
11062       const char *sym_name;
11063
11064       size = (bfd_size_type) bfd_get_reloc_size (howto);
11065       buf = (bfd_byte *) bfd_zmalloc (size);
11066       if (buf == NULL && size != 0)
11067         return FALSE;
11068       rstat = _bfd_relocate_contents (howto, output_bfd, addend, buf);
11069       switch (rstat)
11070         {
11071         case bfd_reloc_ok:
11072           break;
11073
11074         default:
11075         case bfd_reloc_outofrange:
11076           abort ();
11077
11078         case bfd_reloc_overflow:
11079           if (link_order->type == bfd_section_reloc_link_order)
11080             sym_name = bfd_section_name (output_bfd,
11081                                          link_order->u.reloc.p->u.section);
11082           else
11083             sym_name = link_order->u.reloc.p->u.name;
11084           (*info->callbacks->reloc_overflow) (info, NULL, sym_name,
11085                                               howto->name, addend, NULL, NULL,
11086                                               (bfd_vma) 0);
11087           break;
11088         }
11089
11090       ok = bfd_set_section_contents (output_bfd, output_section, buf,
11091                                      link_order->offset
11092                                      * bfd_octets_per_byte (output_bfd),
11093                                      size);
11094       free (buf);
11095       if (! ok)
11096         return FALSE;
11097     }
11098
11099   /* The address of a reloc is relative to the section in a
11100      relocatable file, and is a virtual address in an executable
11101      file.  */
11102   offset = link_order->offset;
11103   if (! bfd_link_relocatable (info))
11104     offset += output_section->vma;
11105
11106   for (i = 0; i < bed->s->int_rels_per_ext_rel; i++)
11107     {
11108       irel[i].r_offset = offset;
11109       irel[i].r_info = 0;
11110       irel[i].r_addend = 0;
11111     }
11112   if (bed->s->arch_size == 32)
11113     irel[0].r_info = ELF32_R_INFO (indx, howto->type);
11114   else
11115     irel[0].r_info = ELF64_R_INFO (indx, howto->type);
11116
11117   rel_hdr = reldata->hdr;
11118   erel = rel_hdr->contents;
11119   if (rel_hdr->sh_type == SHT_REL)
11120     {
11121       erel += reldata->count * bed->s->sizeof_rel;
11122       (*bed->s->swap_reloc_out) (output_bfd, irel, erel);
11123     }
11124   else
11125     {
11126       irel[0].r_addend = addend;
11127       erel += reldata->count * bed->s->sizeof_rela;
11128       (*bed->s->swap_reloca_out) (output_bfd, irel, erel);
11129     }
11130
11131   ++reldata->count;
11132
11133   return TRUE;
11134 }
11135
11136
11137 /* Get the output vma of the section pointed to by the sh_link field.  */
11138
11139 static bfd_vma
11140 elf_get_linked_section_vma (struct bfd_link_order *p)
11141 {
11142   Elf_Internal_Shdr **elf_shdrp;
11143   asection *s;
11144   int elfsec;
11145
11146   s = p->u.indirect.section;
11147   elf_shdrp = elf_elfsections (s->owner);
11148   elfsec = _bfd_elf_section_from_bfd_section (s->owner, s);
11149   elfsec = elf_shdrp[elfsec]->sh_link;
11150   /* PR 290:
11151      The Intel C compiler generates SHT_IA_64_UNWIND with
11152      SHF_LINK_ORDER.  But it doesn't set the sh_link or
11153      sh_info fields.  Hence we could get the situation
11154      where elfsec is 0.  */
11155   if (elfsec == 0)
11156     {
11157       const struct elf_backend_data *bed
11158         = get_elf_backend_data (s->owner);
11159       if (bed->link_order_error_handler)
11160         bed->link_order_error_handler
11161           /* xgettext:c-format */
11162           (_("%B: warning: sh_link not set for section `%A'"), s->owner, s);
11163       return 0;
11164     }
11165   else
11166     {
11167       s = elf_shdrp[elfsec]->bfd_section;
11168       return s->output_section->vma + s->output_offset;
11169     }
11170 }
11171
11172
11173 /* Compare two sections based on the locations of the sections they are
11174    linked to.  Used by elf_fixup_link_order.  */
11175
11176 static int
11177 compare_link_order (const void * a, const void * b)
11178 {
11179   bfd_vma apos;
11180   bfd_vma bpos;
11181
11182   apos = elf_get_linked_section_vma (*(struct bfd_link_order **)a);
11183   bpos = elf_get_linked_section_vma (*(struct bfd_link_order **)b);
11184   if (apos < bpos)
11185     return -1;
11186   return apos > bpos;
11187 }
11188
11189
11190 /* Looks for sections with SHF_LINK_ORDER set.  Rearranges them into the same
11191    order as their linked sections.  Returns false if this could not be done
11192    because an output section includes both ordered and unordered
11193    sections.  Ideally we'd do this in the linker proper.  */
11194
11195 static bfd_boolean
11196 elf_fixup_link_order (bfd *abfd, asection *o)
11197 {
11198   int seen_linkorder;
11199   int seen_other;
11200   int n;
11201   struct bfd_link_order *p;
11202   bfd *sub;
11203   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
11204   unsigned elfsec;
11205   struct bfd_link_order **sections;
11206   asection *s, *other_sec, *linkorder_sec;
11207   bfd_vma offset;
11208
11209   other_sec = NULL;
11210   linkorder_sec = NULL;
11211   seen_other = 0;
11212   seen_linkorder = 0;
11213   for (p = o->map_head.link_order; p != NULL; p = p->next)
11214     {
11215       if (p->type == bfd_indirect_link_order)
11216         {
11217           s = p->u.indirect.section;
11218           sub = s->owner;
11219           if (bfd_get_flavour (sub) == bfd_target_elf_flavour
11220               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass
11221               && (elfsec = _bfd_elf_section_from_bfd_section (sub, s))
11222               && elfsec < elf_numsections (sub)
11223               && elf_elfsections (sub)[elfsec]->sh_flags & SHF_LINK_ORDER
11224               && elf_elfsections (sub)[elfsec]->sh_link < elf_numsections (sub))
11225             {
11226               seen_linkorder++;
11227               linkorder_sec = s;
11228             }
11229           else
11230             {
11231               seen_other++;
11232               other_sec = s;
11233             }
11234         }
11235       else
11236         seen_other++;
11237
11238       if (seen_other && seen_linkorder)
11239         {
11240           if (other_sec && linkorder_sec)
11241             _bfd_error_handler
11242               /* xgettext:c-format */
11243               (_("%A has both ordered [`%A' in %B] "
11244                  "and unordered [`%A' in %B] sections"),
11245                o, linkorder_sec, linkorder_sec->owner,
11246                other_sec, other_sec->owner);
11247           else
11248             _bfd_error_handler
11249               (_("%A has both ordered and unordered sections"), o);
11250           bfd_set_error (bfd_error_bad_value);
11251           return FALSE;
11252         }
11253     }
11254
11255   if (!seen_linkorder)
11256     return TRUE;
11257
11258   sections = (struct bfd_link_order **)
11259     bfd_malloc (seen_linkorder * sizeof (struct bfd_link_order *));
11260   if (sections == NULL)
11261     return FALSE;
11262   seen_linkorder = 0;
11263
11264   for (p = o->map_head.link_order; p != NULL; p = p->next)
11265     {
11266       sections[seen_linkorder++] = p;
11267     }
11268   /* Sort the input sections in the order of their linked section.  */
11269   qsort (sections, seen_linkorder, sizeof (struct bfd_link_order *),
11270          compare_link_order);
11271
11272   /* Change the offsets of the sections.  */
11273   offset = 0;
11274   for (n = 0; n < seen_linkorder; n++)
11275     {
11276       s = sections[n]->u.indirect.section;
11277       offset &= ~(bfd_vma) 0 << s->alignment_power;
11278       s->output_offset = offset / bfd_octets_per_byte (abfd);
11279       sections[n]->offset = offset;
11280       offset += sections[n]->size;
11281     }
11282
11283   free (sections);
11284   return TRUE;
11285 }
11286
11287 /* Generate an import library in INFO->implib_bfd from symbols in ABFD.
11288    Returns TRUE upon success, FALSE otherwise.  */
11289
11290 static bfd_boolean
11291 elf_output_implib (bfd *abfd, struct bfd_link_info *info)
11292 {
11293   bfd_boolean ret = FALSE;
11294   bfd *implib_bfd;
11295   const struct elf_backend_data *bed;
11296   flagword flags;
11297   enum bfd_architecture arch;
11298   unsigned int mach;
11299   asymbol **sympp = NULL;
11300   long symsize;
11301   long symcount;
11302   long src_count;
11303   elf_symbol_type *osymbuf;
11304
11305   implib_bfd = info->out_implib_bfd;
11306   bed = get_elf_backend_data (abfd);
11307
11308   if (!bfd_set_format (implib_bfd, bfd_object))
11309     return FALSE;
11310
11311   /* Use flag from executable but make it a relocatable object.  */
11312   flags = bfd_get_file_flags (abfd);
11313   flags &= ~HAS_RELOC;
11314   if (!bfd_set_start_address (implib_bfd, 0)
11315       || !bfd_set_file_flags (implib_bfd, flags & ~EXEC_P))
11316     return FALSE;
11317
11318   /* Copy architecture of output file to import library file.  */
11319   arch = bfd_get_arch (abfd);
11320   mach = bfd_get_mach (abfd);
11321   if (!bfd_set_arch_mach (implib_bfd, arch, mach)
11322       && (abfd->target_defaulted
11323           || bfd_get_arch (abfd) != bfd_get_arch (implib_bfd)))
11324     return FALSE;
11325
11326   /* Get symbol table size.  */
11327   symsize = bfd_get_symtab_upper_bound (abfd);
11328   if (symsize < 0)
11329     return FALSE;
11330
11331   /* Read in the symbol table.  */
11332   sympp = (asymbol **) xmalloc (symsize);
11333   symcount = bfd_canonicalize_symtab (abfd, sympp);
11334   if (symcount < 0)
11335     goto free_sym_buf;
11336
11337   /* Allow the BFD backend to copy any private header data it
11338      understands from the output BFD to the import library BFD.  */
11339   if (! bfd_copy_private_header_data (abfd, implib_bfd))
11340     goto free_sym_buf;
11341
11342   /* Filter symbols to appear in the import library.  */
11343   if (bed->elf_backend_filter_implib_symbols)
11344     symcount = bed->elf_backend_filter_implib_symbols (abfd, info, sympp,
11345                                                        symcount);
11346   else
11347     symcount = _bfd_elf_filter_global_symbols (abfd, info, sympp, symcount);
11348   if (symcount == 0)
11349     {
11350       bfd_set_error (bfd_error_no_symbols);
11351       _bfd_error_handler (_("%B: no symbol found for import library"),
11352                           implib_bfd);
11353       goto free_sym_buf;
11354     }
11355
11356
11357   /* Make symbols absolute.  */
11358   osymbuf = (elf_symbol_type *) bfd_alloc2 (implib_bfd, symcount,
11359                                             sizeof (*osymbuf));
11360   for (src_count = 0; src_count < symcount; src_count++)
11361     {
11362       memcpy (&osymbuf[src_count], (elf_symbol_type *) sympp[src_count],
11363               sizeof (*osymbuf));
11364       osymbuf[src_count].symbol.section = bfd_abs_section_ptr;
11365       osymbuf[src_count].internal_elf_sym.st_shndx = SHN_ABS;
11366       osymbuf[src_count].symbol.value += sympp[src_count]->section->vma;
11367       osymbuf[src_count].internal_elf_sym.st_value =
11368         osymbuf[src_count].symbol.value;
11369       sympp[src_count] = &osymbuf[src_count].symbol;
11370     }
11371
11372   bfd_set_symtab (implib_bfd, sympp, symcount);
11373
11374   /* Allow the BFD backend to copy any private data it understands
11375      from the output BFD to the import library BFD.  This is done last
11376      to permit the routine to look at the filtered symbol table.  */
11377   if (! bfd_copy_private_bfd_data (abfd, implib_bfd))
11378     goto free_sym_buf;
11379
11380   if (!bfd_close (implib_bfd))
11381     goto free_sym_buf;
11382
11383   ret = TRUE;
11384
11385 free_sym_buf:
11386   free (sympp);
11387   return ret;
11388 }
11389
11390 static void
11391 elf_final_link_free (bfd *obfd, struct elf_final_link_info *flinfo)
11392 {
11393   asection *o;
11394
11395   if (flinfo->symstrtab != NULL)
11396     _bfd_elf_strtab_free (flinfo->symstrtab);
11397   if (flinfo->contents != NULL)
11398     free (flinfo->contents);
11399   if (flinfo->external_relocs != NULL)
11400     free (flinfo->external_relocs);
11401   if (flinfo->internal_relocs != NULL)
11402     free (flinfo->internal_relocs);
11403   if (flinfo->external_syms != NULL)
11404     free (flinfo->external_syms);
11405   if (flinfo->locsym_shndx != NULL)
11406     free (flinfo->locsym_shndx);
11407   if (flinfo->internal_syms != NULL)
11408     free (flinfo->internal_syms);
11409   if (flinfo->indices != NULL)
11410     free (flinfo->indices);
11411   if (flinfo->sections != NULL)
11412     free (flinfo->sections);
11413   if (flinfo->symshndxbuf != NULL)
11414     free (flinfo->symshndxbuf);
11415   for (o = obfd->sections; o != NULL; o = o->next)
11416     {
11417       struct bfd_elf_section_data *esdo = elf_section_data (o);
11418       if ((o->flags & SEC_RELOC) != 0 && esdo->rel.hashes != NULL)
11419         free (esdo->rel.hashes);
11420       if ((o->flags & SEC_RELOC) != 0 && esdo->rela.hashes != NULL)
11421         free (esdo->rela.hashes);
11422     }
11423 }
11424
11425 /* Do the final step of an ELF link.  */
11426
11427 bfd_boolean
11428 bfd_elf_final_link (bfd *abfd, struct bfd_link_info *info)
11429 {
11430   bfd_boolean dynamic;
11431   bfd_boolean emit_relocs;
11432   bfd *dynobj;
11433   struct elf_final_link_info flinfo;
11434   asection *o;
11435   struct bfd_link_order *p;
11436   bfd *sub;
11437   bfd_size_type max_contents_size;
11438   bfd_size_type max_external_reloc_size;
11439   bfd_size_type max_internal_reloc_count;
11440   bfd_size_type max_sym_count;
11441   bfd_size_type max_sym_shndx_count;
11442   Elf_Internal_Sym elfsym;
11443   unsigned int i;
11444   Elf_Internal_Shdr *symtab_hdr;
11445   Elf_Internal_Shdr *symtab_shndx_hdr;
11446   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
11447   struct elf_outext_info eoinfo;
11448   bfd_boolean merged;
11449   size_t relativecount = 0;
11450   asection *reldyn = 0;
11451   bfd_size_type amt;
11452   asection *attr_section = NULL;
11453   bfd_vma attr_size = 0;
11454   const char *std_attrs_section;
11455   struct elf_link_hash_table *htab = elf_hash_table (info);
11456
11457   if (!is_elf_hash_table (htab))
11458     return FALSE;
11459
11460   if (bfd_link_pic (info))
11461     abfd->flags |= DYNAMIC;
11462
11463   dynamic = htab->dynamic_sections_created;
11464   dynobj = htab->dynobj;
11465
11466   emit_relocs = (bfd_link_relocatable (info)
11467                  || info->emitrelocations);
11468
11469   flinfo.info = info;
11470   flinfo.output_bfd = abfd;
11471   flinfo.symstrtab = _bfd_elf_strtab_init ();
11472   if (flinfo.symstrtab == NULL)
11473     return FALSE;
11474
11475   if (! dynamic)
11476     {
11477       flinfo.hash_sec = NULL;
11478       flinfo.symver_sec = NULL;
11479     }
11480   else
11481     {
11482       flinfo.hash_sec = bfd_get_linker_section (dynobj, ".hash");
11483       /* Note that dynsym_sec can be NULL (on VMS).  */
11484       flinfo.symver_sec = bfd_get_linker_section (dynobj, ".gnu.version");
11485       /* Note that it is OK if symver_sec is NULL.  */
11486     }
11487
11488   flinfo.contents = NULL;
11489   flinfo.external_relocs = NULL;
11490   flinfo.internal_relocs = NULL;
11491   flinfo.external_syms = NULL;
11492   flinfo.locsym_shndx = NULL;
11493   flinfo.internal_syms = NULL;
11494   flinfo.indices = NULL;
11495   flinfo.sections = NULL;
11496   flinfo.symshndxbuf = NULL;
11497   flinfo.filesym_count = 0;
11498
11499   /* The object attributes have been merged.  Remove the input
11500      sections from the link, and set the contents of the output
11501      secton.  */
11502   std_attrs_section = get_elf_backend_data (abfd)->obj_attrs_section;
11503   for (o = abfd->sections; o != NULL; o = o->next)
11504     {
11505       if ((std_attrs_section && strcmp (o->name, std_attrs_section) == 0)
11506           || strcmp (o->name, ".gnu.attributes") == 0)
11507         {
11508           for (p = o->map_head.link_order; p != NULL; p = p->next)
11509             {
11510               asection *input_section;
11511
11512               if (p->type != bfd_indirect_link_order)
11513                 continue;
11514               input_section = p->u.indirect.section;
11515               /* Hack: reset the SEC_HAS_CONTENTS flag so that
11516                  elf_link_input_bfd ignores this section.  */
11517               input_section->flags &= ~SEC_HAS_CONTENTS;
11518             }
11519
11520           attr_size = bfd_elf_obj_attr_size (abfd);
11521           if (attr_size)
11522             {
11523               bfd_set_section_size (abfd, o, attr_size);
11524               attr_section = o;
11525               /* Skip this section later on.  */
11526               o->map_head.link_order = NULL;
11527             }
11528           else
11529             o->flags |= SEC_EXCLUDE;
11530         }
11531     }
11532
11533   /* Count up the number of relocations we will output for each output
11534      section, so that we know the sizes of the reloc sections.  We
11535      also figure out some maximum sizes.  */
11536   max_contents_size = 0;
11537   max_external_reloc_size = 0;
11538   max_internal_reloc_count = 0;
11539   max_sym_count = 0;
11540   max_sym_shndx_count = 0;
11541   merged = FALSE;
11542   for (o = abfd->sections; o != NULL; o = o->next)
11543     {
11544       struct bfd_elf_section_data *esdo = elf_section_data (o);
11545       o->reloc_count = 0;
11546
11547       for (p = o->map_head.link_order; p != NULL; p = p->next)
11548         {
11549           unsigned int reloc_count = 0;
11550           unsigned int additional_reloc_count = 0;
11551           struct bfd_elf_section_data *esdi = NULL;
11552
11553           if (p->type == bfd_section_reloc_link_order
11554               || p->type == bfd_symbol_reloc_link_order)
11555             reloc_count = 1;
11556           else if (p->type == bfd_indirect_link_order)
11557             {
11558               asection *sec;
11559
11560               sec = p->u.indirect.section;
11561
11562               /* Mark all sections which are to be included in the
11563                  link.  This will normally be every section.  We need
11564                  to do this so that we can identify any sections which
11565                  the linker has decided to not include.  */
11566               sec->linker_mark = TRUE;
11567
11568               if (sec->flags & SEC_MERGE)
11569                 merged = TRUE;
11570
11571               if (sec->rawsize > max_contents_size)
11572                 max_contents_size = sec->rawsize;
11573               if (sec->size > max_contents_size)
11574                 max_contents_size = sec->size;
11575
11576               if (bfd_get_flavour (sec->owner) == bfd_target_elf_flavour
11577                   && (sec->owner->flags & DYNAMIC) == 0)
11578                 {
11579                   size_t sym_count;
11580
11581                   /* We are interested in just local symbols, not all
11582                      symbols.  */
11583                   if (elf_bad_symtab (sec->owner))
11584                     sym_count = (elf_tdata (sec->owner)->symtab_hdr.sh_size
11585                                  / bed->s->sizeof_sym);
11586                   else
11587                     sym_count = elf_tdata (sec->owner)->symtab_hdr.sh_info;
11588
11589                   if (sym_count > max_sym_count)
11590                     max_sym_count = sym_count;
11591
11592                   if (sym_count > max_sym_shndx_count
11593                       && elf_symtab_shndx_list (sec->owner) != NULL)
11594                     max_sym_shndx_count = sym_count;
11595
11596                   if (esdo->this_hdr.sh_type == SHT_REL
11597                       || esdo->this_hdr.sh_type == SHT_RELA)
11598                     /* Some backends use reloc_count in relocation sections
11599                        to count particular types of relocs.  Of course,
11600                        reloc sections themselves can't have relocations.  */
11601                     ;
11602                   else if (emit_relocs)
11603                     {
11604                       reloc_count = sec->reloc_count;
11605                       if (bed->elf_backend_count_additional_relocs)
11606                         {
11607                           int c;
11608                           c = (*bed->elf_backend_count_additional_relocs) (sec);
11609                           additional_reloc_count += c;
11610                         }
11611                     }
11612                   else if (bed->elf_backend_count_relocs)
11613                     reloc_count = (*bed->elf_backend_count_relocs) (info, sec);
11614
11615                   esdi = elf_section_data (sec);
11616
11617                   if ((sec->flags & SEC_RELOC) != 0)
11618                     {
11619                       size_t ext_size = 0;
11620
11621                       if (esdi->rel.hdr != NULL)
11622                         ext_size = esdi->rel.hdr->sh_size;
11623                       if (esdi->rela.hdr != NULL)
11624                         ext_size += esdi->rela.hdr->sh_size;
11625
11626                       if (ext_size > max_external_reloc_size)
11627                         max_external_reloc_size = ext_size;
11628                       if (sec->reloc_count > max_internal_reloc_count)
11629                         max_internal_reloc_count = sec->reloc_count;
11630                     }
11631                 }
11632             }
11633
11634           if (reloc_count == 0)
11635             continue;
11636
11637           reloc_count += additional_reloc_count;
11638           o->reloc_count += reloc_count;
11639
11640           if (p->type == bfd_indirect_link_order && emit_relocs)
11641             {
11642               if (esdi->rel.hdr)
11643                 {
11644                   esdo->rel.count += NUM_SHDR_ENTRIES (esdi->rel.hdr);
11645                   esdo->rel.count += additional_reloc_count;
11646                 }
11647               if (esdi->rela.hdr)
11648                 {
11649                   esdo->rela.count += NUM_SHDR_ENTRIES (esdi->rela.hdr);
11650                   esdo->rela.count += additional_reloc_count;
11651                 }
11652             }
11653           else
11654             {
11655               if (o->use_rela_p)
11656                 esdo->rela.count += reloc_count;
11657               else
11658                 esdo->rel.count += reloc_count;
11659             }
11660         }
11661
11662       if (o->reloc_count > 0)
11663         o->flags |= SEC_RELOC;
11664       else
11665         {
11666           /* Explicitly clear the SEC_RELOC flag.  The linker tends to
11667              set it (this is probably a bug) and if it is set
11668              assign_section_numbers will create a reloc section.  */
11669           o->flags &=~ SEC_RELOC;
11670         }
11671
11672       /* If the SEC_ALLOC flag is not set, force the section VMA to
11673          zero.  This is done in elf_fake_sections as well, but forcing
11674          the VMA to 0 here will ensure that relocs against these
11675          sections are handled correctly.  */
11676       if ((o->flags & SEC_ALLOC) == 0
11677           && ! o->user_set_vma)
11678         o->vma = 0;
11679     }
11680
11681   if (! bfd_link_relocatable (info) && merged)
11682     elf_link_hash_traverse (htab, _bfd_elf_link_sec_merge_syms, abfd);
11683
11684   /* Figure out the file positions for everything but the symbol table
11685      and the relocs.  We set symcount to force assign_section_numbers
11686      to create a symbol table.  */
11687   bfd_get_symcount (abfd) = info->strip != strip_all || emit_relocs;
11688   BFD_ASSERT (! abfd->output_has_begun);
11689   if (! _bfd_elf_compute_section_file_positions (abfd, info))
11690     goto error_return;
11691
11692   /* Set sizes, and assign file positions for reloc sections.  */
11693   for (o = abfd->sections; o != NULL; o = o->next)
11694     {
11695       struct bfd_elf_section_data *esdo = elf_section_data (o);
11696       if ((o->flags & SEC_RELOC) != 0)
11697         {
11698           if (esdo->rel.hdr
11699               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rel)))
11700             goto error_return;
11701
11702           if (esdo->rela.hdr
11703               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rela)))
11704             goto error_return;
11705         }
11706
11707       /* Now, reset REL_COUNT and REL_COUNT2 so that we can use them
11708          to count upwards while actually outputting the relocations.  */
11709       esdo->rel.count = 0;
11710       esdo->rela.count = 0;
11711
11712       if (esdo->this_hdr.sh_offset == (file_ptr) -1)
11713         {
11714           /* Cache the section contents so that they can be compressed
11715              later.  Use bfd_malloc since it will be freed by
11716              bfd_compress_section_contents.  */
11717           unsigned char *contents = esdo->this_hdr.contents;
11718           if ((o->flags & SEC_ELF_COMPRESS) == 0 || contents != NULL)
11719             abort ();
11720           contents
11721             = (unsigned char *) bfd_malloc (esdo->this_hdr.sh_size);
11722           if (contents == NULL)
11723             goto error_return;
11724           esdo->this_hdr.contents = contents;
11725         }
11726     }
11727
11728   /* We have now assigned file positions for all the sections except
11729      .symtab, .strtab, and non-loaded reloc sections.  We start the
11730      .symtab section at the current file position, and write directly
11731      to it.  We build the .strtab section in memory.  */
11732   bfd_get_symcount (abfd) = 0;
11733   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11734   /* sh_name is set in prep_headers.  */
11735   symtab_hdr->sh_type = SHT_SYMTAB;
11736   /* sh_flags, sh_addr and sh_size all start off zero.  */
11737   symtab_hdr->sh_entsize = bed->s->sizeof_sym;
11738   /* sh_link is set in assign_section_numbers.  */
11739   /* sh_info is set below.  */
11740   /* sh_offset is set just below.  */
11741   symtab_hdr->sh_addralign = (bfd_vma) 1 << bed->s->log_file_align;
11742
11743   if (max_sym_count < 20)
11744     max_sym_count = 20;
11745   htab->strtabsize = max_sym_count;
11746   amt = max_sym_count * sizeof (struct elf_sym_strtab);
11747   htab->strtab = (struct elf_sym_strtab *) bfd_malloc (amt);
11748   if (htab->strtab == NULL)
11749     goto error_return;
11750   /* The real buffer will be allocated in elf_link_swap_symbols_out.  */
11751   flinfo.symshndxbuf
11752     = (elf_numsections (abfd) > (SHN_LORESERVE & 0xFFFF)
11753        ? (Elf_External_Sym_Shndx *) -1 : NULL);
11754
11755   if (info->strip != strip_all || emit_relocs)
11756     {
11757       file_ptr off = elf_next_file_pos (abfd);
11758
11759       _bfd_elf_assign_file_position_for_section (symtab_hdr, off, TRUE);
11760
11761       /* Note that at this point elf_next_file_pos (abfd) is
11762          incorrect.  We do not yet know the size of the .symtab section.
11763          We correct next_file_pos below, after we do know the size.  */
11764
11765       /* Start writing out the symbol table.  The first symbol is always a
11766          dummy symbol.  */
11767       elfsym.st_value = 0;
11768       elfsym.st_size = 0;
11769       elfsym.st_info = 0;
11770       elfsym.st_other = 0;
11771       elfsym.st_shndx = SHN_UNDEF;
11772       elfsym.st_target_internal = 0;
11773       if (elf_link_output_symstrtab (&flinfo, NULL, &elfsym,
11774                                      bfd_und_section_ptr, NULL) != 1)
11775         goto error_return;
11776
11777       /* Output a symbol for each section.  We output these even if we are
11778          discarding local symbols, since they are used for relocs.  These
11779          symbols have no names.  We store the index of each one in the
11780          index field of the section, so that we can find it again when
11781          outputting relocs.  */
11782
11783       elfsym.st_size = 0;
11784       elfsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
11785       elfsym.st_other = 0;
11786       elfsym.st_value = 0;
11787       elfsym.st_target_internal = 0;
11788       for (i = 1; i < elf_numsections (abfd); i++)
11789         {
11790           o = bfd_section_from_elf_index (abfd, i);
11791           if (o != NULL)
11792             {
11793               o->target_index = bfd_get_symcount (abfd);
11794               elfsym.st_shndx = i;
11795               if (!bfd_link_relocatable (info))
11796                 elfsym.st_value = o->vma;
11797               if (elf_link_output_symstrtab (&flinfo, NULL, &elfsym, o,
11798                                              NULL) != 1)
11799                 goto error_return;
11800             }
11801         }
11802     }
11803
11804   /* Allocate some memory to hold information read in from the input
11805      files.  */
11806   if (max_contents_size != 0)
11807     {
11808       flinfo.contents = (bfd_byte *) bfd_malloc (max_contents_size);
11809       if (flinfo.contents == NULL)
11810         goto error_return;
11811     }
11812
11813   if (max_external_reloc_size != 0)
11814     {
11815       flinfo.external_relocs = bfd_malloc (max_external_reloc_size);
11816       if (flinfo.external_relocs == NULL)
11817         goto error_return;
11818     }
11819
11820   if (max_internal_reloc_count != 0)
11821     {
11822       amt = max_internal_reloc_count * sizeof (Elf_Internal_Rela);
11823       flinfo.internal_relocs = (Elf_Internal_Rela *) bfd_malloc (amt);
11824       if (flinfo.internal_relocs == NULL)
11825         goto error_return;
11826     }
11827
11828   if (max_sym_count != 0)
11829     {
11830       amt = max_sym_count * bed->s->sizeof_sym;
11831       flinfo.external_syms = (bfd_byte *) bfd_malloc (amt);
11832       if (flinfo.external_syms == NULL)
11833         goto error_return;
11834
11835       amt = max_sym_count * sizeof (Elf_Internal_Sym);
11836       flinfo.internal_syms = (Elf_Internal_Sym *) bfd_malloc (amt);
11837       if (flinfo.internal_syms == NULL)
11838         goto error_return;
11839
11840       amt = max_sym_count * sizeof (long);
11841       flinfo.indices = (long int *) bfd_malloc (amt);
11842       if (flinfo.indices == NULL)
11843         goto error_return;
11844
11845       amt = max_sym_count * sizeof (asection *);
11846       flinfo.sections = (asection **) bfd_malloc (amt);
11847       if (flinfo.sections == NULL)
11848         goto error_return;
11849     }
11850
11851   if (max_sym_shndx_count != 0)
11852     {
11853       amt = max_sym_shndx_count * sizeof (Elf_External_Sym_Shndx);
11854       flinfo.locsym_shndx = (Elf_External_Sym_Shndx *) bfd_malloc (amt);
11855       if (flinfo.locsym_shndx == NULL)
11856         goto error_return;
11857     }
11858
11859   if (htab->tls_sec)
11860     {
11861       bfd_vma base, end = 0;
11862       asection *sec;
11863
11864       for (sec = htab->tls_sec;
11865            sec && (sec->flags & SEC_THREAD_LOCAL);
11866            sec = sec->next)
11867         {
11868           bfd_size_type size = sec->size;
11869
11870           if (size == 0
11871               && (sec->flags & SEC_HAS_CONTENTS) == 0)
11872             {
11873               struct bfd_link_order *ord = sec->map_tail.link_order;
11874
11875               if (ord != NULL)
11876                 size = ord->offset + ord->size;
11877             }
11878           end = sec->vma + size;
11879         }
11880       base = htab->tls_sec->vma;
11881       /* Only align end of TLS section if static TLS doesn't have special
11882          alignment requirements.  */
11883       if (bed->static_tls_alignment == 1)
11884         end = align_power (end, htab->tls_sec->alignment_power);
11885       htab->tls_size = end - base;
11886     }
11887
11888   /* Reorder SHF_LINK_ORDER sections.  */
11889   for (o = abfd->sections; o != NULL; o = o->next)
11890     {
11891       if (!elf_fixup_link_order (abfd, o))
11892         return FALSE;
11893     }
11894
11895   if (!_bfd_elf_fixup_eh_frame_hdr (info))
11896     return FALSE;
11897
11898   /* Since ELF permits relocations to be against local symbols, we
11899      must have the local symbols available when we do the relocations.
11900      Since we would rather only read the local symbols once, and we
11901      would rather not keep them in memory, we handle all the
11902      relocations for a single input file at the same time.
11903
11904      Unfortunately, there is no way to know the total number of local
11905      symbols until we have seen all of them, and the local symbol
11906      indices precede the global symbol indices.  This means that when
11907      we are generating relocatable output, and we see a reloc against
11908      a global symbol, we can not know the symbol index until we have
11909      finished examining all the local symbols to see which ones we are
11910      going to output.  To deal with this, we keep the relocations in
11911      memory, and don't output them until the end of the link.  This is
11912      an unfortunate waste of memory, but I don't see a good way around
11913      it.  Fortunately, it only happens when performing a relocatable
11914      link, which is not the common case.  FIXME: If keep_memory is set
11915      we could write the relocs out and then read them again; I don't
11916      know how bad the memory loss will be.  */
11917
11918   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
11919     sub->output_has_begun = FALSE;
11920   for (o = abfd->sections; o != NULL; o = o->next)
11921     {
11922       for (p = o->map_head.link_order; p != NULL; p = p->next)
11923         {
11924           if (p->type == bfd_indirect_link_order
11925               && (bfd_get_flavour ((sub = p->u.indirect.section->owner))
11926                   == bfd_target_elf_flavour)
11927               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass)
11928             {
11929               if (! sub->output_has_begun)
11930                 {
11931                   if (! elf_link_input_bfd (&flinfo, sub))
11932                     goto error_return;
11933                   sub->output_has_begun = TRUE;
11934                 }
11935             }
11936           else if (p->type == bfd_section_reloc_link_order
11937                    || p->type == bfd_symbol_reloc_link_order)
11938             {
11939               if (! elf_reloc_link_order (abfd, info, o, p))
11940                 goto error_return;
11941             }
11942           else
11943             {
11944               if (! _bfd_default_link_order (abfd, info, o, p))
11945                 {
11946                   if (p->type == bfd_indirect_link_order
11947                       && (bfd_get_flavour (sub)
11948                           == bfd_target_elf_flavour)
11949                       && (elf_elfheader (sub)->e_ident[EI_CLASS]
11950                           != bed->s->elfclass))
11951                     {
11952                       const char *iclass, *oclass;
11953
11954                       switch (bed->s->elfclass)
11955                         {
11956                         case ELFCLASS64: oclass = "ELFCLASS64"; break;
11957                         case ELFCLASS32: oclass = "ELFCLASS32"; break;
11958                         case ELFCLASSNONE: oclass = "ELFCLASSNONE"; break;
11959                         default: abort ();
11960                         }
11961
11962                       switch (elf_elfheader (sub)->e_ident[EI_CLASS])
11963                         {
11964                         case ELFCLASS64: iclass = "ELFCLASS64"; break;
11965                         case ELFCLASS32: iclass = "ELFCLASS32"; break;
11966                         case ELFCLASSNONE: iclass = "ELFCLASSNONE"; break;
11967                         default: abort ();
11968                         }
11969
11970                       bfd_set_error (bfd_error_wrong_format);
11971                       _bfd_error_handler
11972                         /* xgettext:c-format */
11973                         (_("%B: file class %s incompatible with %s"),
11974                          sub, iclass, oclass);
11975                     }
11976
11977                   goto error_return;
11978                 }
11979             }
11980         }
11981     }
11982
11983   /* Free symbol buffer if needed.  */
11984   if (!info->reduce_memory_overheads)
11985     {
11986       for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
11987         if (bfd_get_flavour (sub) == bfd_target_elf_flavour
11988             && elf_tdata (sub)->symbuf)
11989           {
11990             free (elf_tdata (sub)->symbuf);
11991             elf_tdata (sub)->symbuf = NULL;
11992           }
11993     }
11994
11995   /* Output any global symbols that got converted to local in a
11996      version script or due to symbol visibility.  We do this in a
11997      separate step since ELF requires all local symbols to appear
11998      prior to any global symbols.  FIXME: We should only do this if
11999      some global symbols were, in fact, converted to become local.
12000      FIXME: Will this work correctly with the Irix 5 linker?  */
12001   eoinfo.failed = FALSE;
12002   eoinfo.flinfo = &flinfo;
12003   eoinfo.localsyms = TRUE;
12004   eoinfo.file_sym_done = FALSE;
12005   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
12006   if (eoinfo.failed)
12007     return FALSE;
12008
12009   /* If backend needs to output some local symbols not present in the hash
12010      table, do it now.  */
12011   if (bed->elf_backend_output_arch_local_syms
12012       && (info->strip != strip_all || emit_relocs))
12013     {
12014       typedef int (*out_sym_func)
12015         (void *, const char *, Elf_Internal_Sym *, asection *,
12016          struct elf_link_hash_entry *);
12017
12018       if (! ((*bed->elf_backend_output_arch_local_syms)
12019              (abfd, info, &flinfo,
12020               (out_sym_func) elf_link_output_symstrtab)))
12021         return FALSE;
12022     }
12023
12024   /* That wrote out all the local symbols.  Finish up the symbol table
12025      with the global symbols. Even if we want to strip everything we
12026      can, we still need to deal with those global symbols that got
12027      converted to local in a version script.  */
12028
12029   /* The sh_info field records the index of the first non local symbol.  */
12030   symtab_hdr->sh_info = bfd_get_symcount (abfd);
12031
12032   if (dynamic
12033       && htab->dynsym != NULL
12034       && htab->dynsym->output_section != bfd_abs_section_ptr)
12035     {
12036       Elf_Internal_Sym sym;
12037       bfd_byte *dynsym = htab->dynsym->contents;
12038
12039       o = htab->dynsym->output_section;
12040       elf_section_data (o)->this_hdr.sh_info = htab->local_dynsymcount + 1;
12041
12042       /* Write out the section symbols for the output sections.  */
12043       if (bfd_link_pic (info)
12044           || htab->is_relocatable_executable)
12045         {
12046           asection *s;
12047
12048           sym.st_size = 0;
12049           sym.st_name = 0;
12050           sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
12051           sym.st_other = 0;
12052           sym.st_target_internal = 0;
12053
12054           for (s = abfd->sections; s != NULL; s = s->next)
12055             {
12056               int indx;
12057               bfd_byte *dest;
12058               long dynindx;
12059
12060               dynindx = elf_section_data (s)->dynindx;
12061               if (dynindx <= 0)
12062                 continue;
12063               indx = elf_section_data (s)->this_idx;
12064               BFD_ASSERT (indx > 0);
12065               sym.st_shndx = indx;
12066               if (! check_dynsym (abfd, &sym))
12067                 return FALSE;
12068               sym.st_value = s->vma;
12069               dest = dynsym + dynindx * bed->s->sizeof_sym;
12070               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
12071             }
12072         }
12073
12074       /* Write out the local dynsyms.  */
12075       if (htab->dynlocal)
12076         {
12077           struct elf_link_local_dynamic_entry *e;
12078           for (e = htab->dynlocal; e ; e = e->next)
12079             {
12080               asection *s;
12081               bfd_byte *dest;
12082
12083               /* Copy the internal symbol and turn off visibility.
12084                  Note that we saved a word of storage and overwrote
12085                  the original st_name with the dynstr_index.  */
12086               sym = e->isym;
12087               sym.st_other &= ~ELF_ST_VISIBILITY (-1);
12088
12089               s = bfd_section_from_elf_index (e->input_bfd,
12090                                               e->isym.st_shndx);
12091               if (s != NULL)
12092                 {
12093                   sym.st_shndx =
12094                     elf_section_data (s->output_section)->this_idx;
12095                   if (! check_dynsym (abfd, &sym))
12096                     return FALSE;
12097                   sym.st_value = (s->output_section->vma
12098                                   + s->output_offset
12099                                   + e->isym.st_value);
12100                 }
12101
12102               dest = dynsym + e->dynindx * bed->s->sizeof_sym;
12103               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
12104             }
12105         }
12106     }
12107
12108   /* We get the global symbols from the hash table.  */
12109   eoinfo.failed = FALSE;
12110   eoinfo.localsyms = FALSE;
12111   eoinfo.flinfo = &flinfo;
12112   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
12113   if (eoinfo.failed)
12114     return FALSE;
12115
12116   /* If backend needs to output some symbols not present in the hash
12117      table, do it now.  */
12118   if (bed->elf_backend_output_arch_syms
12119       && (info->strip != strip_all || emit_relocs))
12120     {
12121       typedef int (*out_sym_func)
12122         (void *, const char *, Elf_Internal_Sym *, asection *,
12123          struct elf_link_hash_entry *);
12124
12125       if (! ((*bed->elf_backend_output_arch_syms)
12126              (abfd, info, &flinfo,
12127               (out_sym_func) elf_link_output_symstrtab)))
12128         return FALSE;
12129     }
12130
12131   /* Finalize the .strtab section.  */
12132   _bfd_elf_strtab_finalize (flinfo.symstrtab);
12133
12134   /* Swap out the .strtab section. */
12135   if (!elf_link_swap_symbols_out (&flinfo))
12136     return FALSE;
12137
12138   /* Now we know the size of the symtab section.  */
12139   if (bfd_get_symcount (abfd) > 0)
12140     {
12141       /* Finish up and write out the symbol string table (.strtab)
12142          section.  */
12143       Elf_Internal_Shdr *symstrtab_hdr = NULL;
12144       file_ptr off = symtab_hdr->sh_offset + symtab_hdr->sh_size;
12145
12146       if (elf_symtab_shndx_list (abfd))
12147         {
12148           symtab_shndx_hdr = & elf_symtab_shndx_list (abfd)->hdr;
12149
12150           if (symtab_shndx_hdr != NULL && symtab_shndx_hdr->sh_name != 0)
12151             {
12152               symtab_shndx_hdr->sh_type = SHT_SYMTAB_SHNDX;
12153               symtab_shndx_hdr->sh_entsize = sizeof (Elf_External_Sym_Shndx);
12154               symtab_shndx_hdr->sh_addralign = sizeof (Elf_External_Sym_Shndx);
12155               amt = bfd_get_symcount (abfd) * sizeof (Elf_External_Sym_Shndx);
12156               symtab_shndx_hdr->sh_size = amt;
12157
12158               off = _bfd_elf_assign_file_position_for_section (symtab_shndx_hdr,
12159                                                                off, TRUE);
12160
12161               if (bfd_seek (abfd, symtab_shndx_hdr->sh_offset, SEEK_SET) != 0
12162                   || (bfd_bwrite (flinfo.symshndxbuf, amt, abfd) != amt))
12163                 return FALSE;
12164             }
12165         }
12166
12167       symstrtab_hdr = &elf_tdata (abfd)->strtab_hdr;
12168       /* sh_name was set in prep_headers.  */
12169       symstrtab_hdr->sh_type = SHT_STRTAB;
12170       symstrtab_hdr->sh_flags = bed->elf_strtab_flags;
12171       symstrtab_hdr->sh_addr = 0;
12172       symstrtab_hdr->sh_size = _bfd_elf_strtab_size (flinfo.symstrtab);
12173       symstrtab_hdr->sh_entsize = 0;
12174       symstrtab_hdr->sh_link = 0;
12175       symstrtab_hdr->sh_info = 0;
12176       /* sh_offset is set just below.  */
12177       symstrtab_hdr->sh_addralign = 1;
12178
12179       off = _bfd_elf_assign_file_position_for_section (symstrtab_hdr,
12180                                                        off, TRUE);
12181       elf_next_file_pos (abfd) = off;
12182
12183       if (bfd_seek (abfd, symstrtab_hdr->sh_offset, SEEK_SET) != 0
12184           || ! _bfd_elf_strtab_emit (abfd, flinfo.symstrtab))
12185         return FALSE;
12186     }
12187
12188   if (info->out_implib_bfd && !elf_output_implib (abfd, info))
12189     {
12190       _bfd_error_handler (_("%B: failed to generate import library"),
12191                           info->out_implib_bfd);
12192       return FALSE;
12193     }
12194
12195   /* Adjust the relocs to have the correct symbol indices.  */
12196   for (o = abfd->sections; o != NULL; o = o->next)
12197     {
12198       struct bfd_elf_section_data *esdo = elf_section_data (o);
12199       bfd_boolean sort;
12200
12201       if ((o->flags & SEC_RELOC) == 0)
12202         continue;
12203
12204       sort = bed->sort_relocs_p == NULL || (*bed->sort_relocs_p) (o);
12205       if (esdo->rel.hdr != NULL
12206           && !elf_link_adjust_relocs (abfd, o, &esdo->rel, sort, info))
12207         return FALSE;
12208       if (esdo->rela.hdr != NULL
12209           && !elf_link_adjust_relocs (abfd, o, &esdo->rela, sort, info))
12210         return FALSE;
12211
12212       /* Set the reloc_count field to 0 to prevent write_relocs from
12213          trying to swap the relocs out itself.  */
12214       o->reloc_count = 0;
12215     }
12216
12217   if (dynamic && info->combreloc && dynobj != NULL)
12218     relativecount = elf_link_sort_relocs (abfd, info, &reldyn);
12219
12220   /* If we are linking against a dynamic object, or generating a
12221      shared library, finish up the dynamic linking information.  */
12222   if (dynamic)
12223     {
12224       bfd_byte *dyncon, *dynconend;
12225
12226       /* Fix up .dynamic entries.  */
12227       o = bfd_get_linker_section (dynobj, ".dynamic");
12228       BFD_ASSERT (o != NULL);
12229
12230       dyncon = o->contents;
12231       dynconend = o->contents + o->size;
12232       for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
12233         {
12234           Elf_Internal_Dyn dyn;
12235           const char *name;
12236           unsigned int type;
12237           bfd_size_type sh_size;
12238           bfd_vma sh_addr;
12239
12240           bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
12241
12242           switch (dyn.d_tag)
12243             {
12244             default:
12245               continue;
12246             case DT_NULL:
12247               if (relativecount > 0 && dyncon + bed->s->sizeof_dyn < dynconend)
12248                 {
12249                   switch (elf_section_data (reldyn)->this_hdr.sh_type)
12250                     {
12251                     case SHT_REL: dyn.d_tag = DT_RELCOUNT; break;
12252                     case SHT_RELA: dyn.d_tag = DT_RELACOUNT; break;
12253                     default: continue;
12254                     }
12255                   dyn.d_un.d_val = relativecount;
12256                   relativecount = 0;
12257                   break;
12258                 }
12259               continue;
12260
12261             case DT_INIT:
12262               name = info->init_function;
12263               goto get_sym;
12264             case DT_FINI:
12265               name = info->fini_function;
12266             get_sym:
12267               {
12268                 struct elf_link_hash_entry *h;
12269
12270                 h = elf_link_hash_lookup (htab, name, FALSE, FALSE, TRUE);
12271                 if (h != NULL
12272                     && (h->root.type == bfd_link_hash_defined
12273                         || h->root.type == bfd_link_hash_defweak))
12274                   {
12275                     dyn.d_un.d_ptr = h->root.u.def.value;
12276                     o = h->root.u.def.section;
12277                     if (o->output_section != NULL)
12278                       dyn.d_un.d_ptr += (o->output_section->vma
12279                                          + o->output_offset);
12280                     else
12281                       {
12282                         /* The symbol is imported from another shared
12283                            library and does not apply to this one.  */
12284                         dyn.d_un.d_ptr = 0;
12285                       }
12286                     break;
12287                   }
12288               }
12289               continue;
12290
12291             case DT_PREINIT_ARRAYSZ:
12292               name = ".preinit_array";
12293               goto get_out_size;
12294             case DT_INIT_ARRAYSZ:
12295               name = ".init_array";
12296               goto get_out_size;
12297             case DT_FINI_ARRAYSZ:
12298               name = ".fini_array";
12299             get_out_size:
12300               o = bfd_get_section_by_name (abfd, name);
12301               if (o == NULL)
12302                 {
12303                   _bfd_error_handler
12304                     (_("could not find section %s"), name);
12305                   goto error_return;
12306                 }
12307               if (o->size == 0)
12308                 _bfd_error_handler
12309                   (_("warning: %s section has zero size"), name);
12310               dyn.d_un.d_val = o->size;
12311               break;
12312
12313             case DT_PREINIT_ARRAY:
12314               name = ".preinit_array";
12315               goto get_out_vma;
12316             case DT_INIT_ARRAY:
12317               name = ".init_array";
12318               goto get_out_vma;
12319             case DT_FINI_ARRAY:
12320               name = ".fini_array";
12321             get_out_vma:
12322               o = bfd_get_section_by_name (abfd, name);
12323               goto do_vma;
12324
12325             case DT_HASH:
12326               name = ".hash";
12327               goto get_vma;
12328             case DT_GNU_HASH:
12329               name = ".gnu.hash";
12330               goto get_vma;
12331             case DT_STRTAB:
12332               name = ".dynstr";
12333               goto get_vma;
12334             case DT_SYMTAB:
12335               name = ".dynsym";
12336               goto get_vma;
12337             case DT_VERDEF:
12338               name = ".gnu.version_d";
12339               goto get_vma;
12340             case DT_VERNEED:
12341               name = ".gnu.version_r";
12342               goto get_vma;
12343             case DT_VERSYM:
12344               name = ".gnu.version";
12345             get_vma:
12346               o = bfd_get_linker_section (dynobj, name);
12347             do_vma:
12348               if (o == NULL || bfd_is_abs_section (o->output_section))
12349                 {
12350                   _bfd_error_handler
12351                     (_("could not find section %s"), name);
12352                   goto error_return;
12353                 }
12354               if (elf_section_data (o->output_section)->this_hdr.sh_type == SHT_NOTE)
12355                 {
12356                   _bfd_error_handler
12357                     (_("warning: section '%s' is being made into a note"), name);
12358                   bfd_set_error (bfd_error_nonrepresentable_section);
12359                   goto error_return;
12360                 }
12361               dyn.d_un.d_ptr = o->output_section->vma + o->output_offset;
12362               break;
12363
12364             case DT_REL:
12365             case DT_RELA:
12366             case DT_RELSZ:
12367             case DT_RELASZ:
12368               if (dyn.d_tag == DT_REL || dyn.d_tag == DT_RELSZ)
12369                 type = SHT_REL;
12370               else
12371                 type = SHT_RELA;
12372               sh_size = 0;
12373               sh_addr = 0;
12374               for (i = 1; i < elf_numsections (abfd); i++)
12375                 {
12376                   Elf_Internal_Shdr *hdr;
12377
12378                   hdr = elf_elfsections (abfd)[i];
12379                   if (hdr->sh_type == type
12380                       && (hdr->sh_flags & SHF_ALLOC) != 0)
12381                     {
12382                       sh_size += hdr->sh_size;
12383                       if (sh_addr == 0
12384                           || sh_addr > hdr->sh_addr)
12385                         sh_addr = hdr->sh_addr;
12386                     }
12387                 }
12388
12389               if (bed->dtrel_excludes_plt && htab->srelplt != NULL)
12390                 {
12391                   /* Don't count procedure linkage table relocs in the
12392                      overall reloc count.  */
12393                   sh_size -= htab->srelplt->size;
12394                   if (sh_size == 0)
12395                     /* If the size is zero, make the address zero too.
12396                        This is to avoid a glibc bug.  If the backend
12397                        emits DT_RELA/DT_RELASZ even when DT_RELASZ is
12398                        zero, then we'll put DT_RELA at the end of
12399                        DT_JMPREL.  glibc will interpret the end of
12400                        DT_RELA matching the end of DT_JMPREL as the
12401                        case where DT_RELA includes DT_JMPREL, and for
12402                        LD_BIND_NOW will decide that processing DT_RELA
12403                        will process the PLT relocs too.  Net result:
12404                        No PLT relocs applied.  */
12405                     sh_addr = 0;
12406
12407                   /* If .rela.plt is the first .rela section, exclude
12408                      it from DT_RELA.  */
12409                   else if (sh_addr == (htab->srelplt->output_section->vma
12410                                        + htab->srelplt->output_offset))
12411                     sh_addr += htab->srelplt->size;
12412                 }
12413
12414               if (dyn.d_tag == DT_RELSZ || dyn.d_tag == DT_RELASZ)
12415                 dyn.d_un.d_val = sh_size;
12416               else
12417                 dyn.d_un.d_ptr = sh_addr;
12418               break;
12419             }
12420           bed->s->swap_dyn_out (dynobj, &dyn, dyncon);
12421         }
12422     }
12423
12424   /* If we have created any dynamic sections, then output them.  */
12425   if (dynobj != NULL)
12426     {
12427       if (! (*bed->elf_backend_finish_dynamic_sections) (abfd, info))
12428         goto error_return;
12429
12430       /* Check for DT_TEXTREL (late, in case the backend removes it).  */
12431       if (((info->warn_shared_textrel && bfd_link_pic (info))
12432            || info->error_textrel)
12433           && (o = bfd_get_linker_section (dynobj, ".dynamic")) != NULL)
12434         {
12435           bfd_byte *dyncon, *dynconend;
12436
12437           dyncon = o->contents;
12438           dynconend = o->contents + o->size;
12439           for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
12440             {
12441               Elf_Internal_Dyn dyn;
12442
12443               bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
12444
12445               if (dyn.d_tag == DT_TEXTREL)
12446                 {
12447                   if (info->error_textrel)
12448                     info->callbacks->einfo
12449                       (_("%P%X: read-only segment has dynamic relocations.\n"));
12450                   else
12451                     info->callbacks->einfo
12452                       (_("%P: warning: creating a DT_TEXTREL in a shared object.\n"));
12453                   break;
12454                 }
12455             }
12456         }
12457
12458       for (o = dynobj->sections; o != NULL; o = o->next)
12459         {
12460           if ((o->flags & SEC_HAS_CONTENTS) == 0
12461               || o->size == 0
12462               || o->output_section == bfd_abs_section_ptr)
12463             continue;
12464           if ((o->flags & SEC_LINKER_CREATED) == 0)
12465             {
12466               /* At this point, we are only interested in sections
12467                  created by _bfd_elf_link_create_dynamic_sections.  */
12468               continue;
12469             }
12470           if (htab->stab_info.stabstr == o)
12471             continue;
12472           if (htab->eh_info.hdr_sec == o)
12473             continue;
12474           if (strcmp (o->name, ".dynstr") != 0)
12475             {
12476               if (! bfd_set_section_contents (abfd, o->output_section,
12477                                               o->contents,
12478                                               (file_ptr) o->output_offset
12479                                               * bfd_octets_per_byte (abfd),
12480                                               o->size))
12481                 goto error_return;
12482             }
12483           else
12484             {
12485               /* The contents of the .dynstr section are actually in a
12486                  stringtab.  */
12487               file_ptr off;
12488
12489               off = elf_section_data (o->output_section)->this_hdr.sh_offset;
12490               if (bfd_seek (abfd, off, SEEK_SET) != 0
12491                   || !_bfd_elf_strtab_emit (abfd, htab->dynstr))
12492                 goto error_return;
12493             }
12494         }
12495     }
12496
12497   if (!info->resolve_section_groups)
12498     {
12499       bfd_boolean failed = FALSE;
12500
12501       BFD_ASSERT (bfd_link_relocatable (info));
12502       bfd_map_over_sections (abfd, bfd_elf_set_group_contents, &failed);
12503       if (failed)
12504         goto error_return;
12505     }
12506
12507   /* If we have optimized stabs strings, output them.  */
12508   if (htab->stab_info.stabstr != NULL)
12509     {
12510       if (!_bfd_write_stab_strings (abfd, &htab->stab_info))
12511         goto error_return;
12512     }
12513
12514   if (! _bfd_elf_write_section_eh_frame_hdr (abfd, info))
12515     goto error_return;
12516
12517   elf_final_link_free (abfd, &flinfo);
12518
12519   elf_linker (abfd) = TRUE;
12520
12521   if (attr_section)
12522     {
12523       bfd_byte *contents = (bfd_byte *) bfd_malloc (attr_size);
12524       if (contents == NULL)
12525         return FALSE;   /* Bail out and fail.  */
12526       bfd_elf_set_obj_attr_contents (abfd, contents, attr_size);
12527       bfd_set_section_contents (abfd, attr_section, contents, 0, attr_size);
12528       free (contents);
12529     }
12530
12531   return TRUE;
12532
12533  error_return:
12534   elf_final_link_free (abfd, &flinfo);
12535   return FALSE;
12536 }
12537 \f
12538 /* Initialize COOKIE for input bfd ABFD.  */
12539
12540 static bfd_boolean
12541 init_reloc_cookie (struct elf_reloc_cookie *cookie,
12542                    struct bfd_link_info *info, bfd *abfd)
12543 {
12544   Elf_Internal_Shdr *symtab_hdr;
12545   const struct elf_backend_data *bed;
12546
12547   bed = get_elf_backend_data (abfd);
12548   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12549
12550   cookie->abfd = abfd;
12551   cookie->sym_hashes = elf_sym_hashes (abfd);
12552   cookie->bad_symtab = elf_bad_symtab (abfd);
12553   if (cookie->bad_symtab)
12554     {
12555       cookie->locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
12556       cookie->extsymoff = 0;
12557     }
12558   else
12559     {
12560       cookie->locsymcount = symtab_hdr->sh_info;
12561       cookie->extsymoff = symtab_hdr->sh_info;
12562     }
12563
12564   if (bed->s->arch_size == 32)
12565     cookie->r_sym_shift = 8;
12566   else
12567     cookie->r_sym_shift = 32;
12568
12569   cookie->locsyms = (Elf_Internal_Sym *) symtab_hdr->contents;
12570   if (cookie->locsyms == NULL && cookie->locsymcount != 0)
12571     {
12572       cookie->locsyms = bfd_elf_get_elf_syms (abfd, symtab_hdr,
12573                                               cookie->locsymcount, 0,
12574                                               NULL, NULL, NULL);
12575       if (cookie->locsyms == NULL)
12576         {
12577           info->callbacks->einfo (_("%P%X: can not read symbols: %E\n"));
12578           return FALSE;
12579         }
12580       if (info->keep_memory)
12581         symtab_hdr->contents = (bfd_byte *) cookie->locsyms;
12582     }
12583   return TRUE;
12584 }
12585
12586 /* Free the memory allocated by init_reloc_cookie, if appropriate.  */
12587
12588 static void
12589 fini_reloc_cookie (struct elf_reloc_cookie *cookie, bfd *abfd)
12590 {
12591   Elf_Internal_Shdr *symtab_hdr;
12592
12593   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12594   if (cookie->locsyms != NULL
12595       && symtab_hdr->contents != (unsigned char *) cookie->locsyms)
12596     free (cookie->locsyms);
12597 }
12598
12599 /* Initialize the relocation information in COOKIE for input section SEC
12600    of input bfd ABFD.  */
12601
12602 static bfd_boolean
12603 init_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
12604                         struct bfd_link_info *info, bfd *abfd,
12605                         asection *sec)
12606 {
12607   if (sec->reloc_count == 0)
12608     {
12609       cookie->rels = NULL;
12610       cookie->relend = NULL;
12611     }
12612   else
12613     {
12614       cookie->rels = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
12615                                                 info->keep_memory);
12616       if (cookie->rels == NULL)
12617         return FALSE;
12618       cookie->rel = cookie->rels;
12619       cookie->relend = cookie->rels + sec->reloc_count;
12620     }
12621   cookie->rel = cookie->rels;
12622   return TRUE;
12623 }
12624
12625 /* Free the memory allocated by init_reloc_cookie_rels,
12626    if appropriate.  */
12627
12628 static void
12629 fini_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
12630                         asection *sec)
12631 {
12632   if (cookie->rels && elf_section_data (sec)->relocs != cookie->rels)
12633     free (cookie->rels);
12634 }
12635
12636 /* Initialize the whole of COOKIE for input section SEC.  */
12637
12638 static bfd_boolean
12639 init_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
12640                                struct bfd_link_info *info,
12641                                asection *sec)
12642 {
12643   if (!init_reloc_cookie (cookie, info, sec->owner))
12644     goto error1;
12645   if (!init_reloc_cookie_rels (cookie, info, sec->owner, sec))
12646     goto error2;
12647   return TRUE;
12648
12649  error2:
12650   fini_reloc_cookie (cookie, sec->owner);
12651  error1:
12652   return FALSE;
12653 }
12654
12655 /* Free the memory allocated by init_reloc_cookie_for_section,
12656    if appropriate.  */
12657
12658 static void
12659 fini_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
12660                                asection *sec)
12661 {
12662   fini_reloc_cookie_rels (cookie, sec);
12663   fini_reloc_cookie (cookie, sec->owner);
12664 }
12665 \f
12666 /* Garbage collect unused sections.  */
12667
12668 /* Default gc_mark_hook.  */
12669
12670 asection *
12671 _bfd_elf_gc_mark_hook (asection *sec,
12672                        struct bfd_link_info *info ATTRIBUTE_UNUSED,
12673                        Elf_Internal_Rela *rel ATTRIBUTE_UNUSED,
12674                        struct elf_link_hash_entry *h,
12675                        Elf_Internal_Sym *sym)
12676 {
12677   if (h != NULL)
12678     {
12679       switch (h->root.type)
12680         {
12681         case bfd_link_hash_defined:
12682         case bfd_link_hash_defweak:
12683           return h->root.u.def.section;
12684
12685         case bfd_link_hash_common:
12686           return h->root.u.c.p->section;
12687
12688         default:
12689           break;
12690         }
12691     }
12692   else
12693     return bfd_section_from_elf_index (sec->owner, sym->st_shndx);
12694
12695   return NULL;
12696 }
12697
12698 /* Return the global debug definition section.  */
12699
12700 static asection *
12701 elf_gc_mark_debug_section (asection *sec ATTRIBUTE_UNUSED,
12702                            struct bfd_link_info *info ATTRIBUTE_UNUSED,
12703                            Elf_Internal_Rela *rel ATTRIBUTE_UNUSED,
12704                            struct elf_link_hash_entry *h,
12705                            Elf_Internal_Sym *sym ATTRIBUTE_UNUSED)
12706 {
12707   if (h != NULL
12708       && (h->root.type == bfd_link_hash_defined
12709           || h->root.type == bfd_link_hash_defweak)
12710       && (h->root.u.def.section->flags & SEC_DEBUGGING) != 0)
12711     return h->root.u.def.section;
12712
12713   return NULL;
12714 }
12715
12716 /* COOKIE->rel describes a relocation against section SEC, which is
12717    a section we've decided to keep.  Return the section that contains
12718    the relocation symbol, or NULL if no section contains it.  */
12719
12720 asection *
12721 _bfd_elf_gc_mark_rsec (struct bfd_link_info *info, asection *sec,
12722                        elf_gc_mark_hook_fn gc_mark_hook,
12723                        struct elf_reloc_cookie *cookie,
12724                        bfd_boolean *start_stop)
12725 {
12726   unsigned long r_symndx;
12727   struct elf_link_hash_entry *h;
12728
12729   r_symndx = cookie->rel->r_info >> cookie->r_sym_shift;
12730   if (r_symndx == STN_UNDEF)
12731     return NULL;
12732
12733   if (r_symndx >= cookie->locsymcount
12734       || ELF_ST_BIND (cookie->locsyms[r_symndx].st_info) != STB_LOCAL)
12735     {
12736       h = cookie->sym_hashes[r_symndx - cookie->extsymoff];
12737       if (h == NULL)
12738         {
12739           info->callbacks->einfo (_("%F%P: corrupt input: %B\n"),
12740                                   sec->owner);
12741           return NULL;
12742         }
12743       while (h->root.type == bfd_link_hash_indirect
12744              || h->root.type == bfd_link_hash_warning)
12745         h = (struct elf_link_hash_entry *) h->root.u.i.link;
12746       h->mark = 1;
12747       /* If this symbol is weak and there is a non-weak definition, we
12748          keep the non-weak definition because many backends put
12749          dynamic reloc info on the non-weak definition for code
12750          handling copy relocs.  */
12751       if (h->u.weakdef != NULL)
12752         h->u.weakdef->mark = 1;
12753
12754       if (start_stop != NULL)
12755         {
12756           /* To work around a glibc bug, mark XXX input sections
12757              when there is a reference to __start_XXX or __stop_XXX
12758              symbols.  */
12759           if (h->start_stop)
12760             {
12761               asection *s = h->u2.start_stop_section;
12762               *start_stop = !s->gc_mark;
12763               return s;
12764             }
12765         }
12766
12767       return (*gc_mark_hook) (sec, info, cookie->rel, h, NULL);
12768     }
12769
12770   return (*gc_mark_hook) (sec, info, cookie->rel, NULL,
12771                           &cookie->locsyms[r_symndx]);
12772 }
12773
12774 /* COOKIE->rel describes a relocation against section SEC, which is
12775    a section we've decided to keep.  Mark the section that contains
12776    the relocation symbol.  */
12777
12778 bfd_boolean
12779 _bfd_elf_gc_mark_reloc (struct bfd_link_info *info,
12780                         asection *sec,
12781                         elf_gc_mark_hook_fn gc_mark_hook,
12782                         struct elf_reloc_cookie *cookie)
12783 {
12784   asection *rsec;
12785   bfd_boolean start_stop = FALSE;
12786
12787   rsec = _bfd_elf_gc_mark_rsec (info, sec, gc_mark_hook, cookie, &start_stop);
12788   while (rsec != NULL)
12789     {
12790       if (!rsec->gc_mark)
12791         {
12792           if (bfd_get_flavour (rsec->owner) != bfd_target_elf_flavour
12793               || (rsec->owner->flags & DYNAMIC) != 0)
12794             rsec->gc_mark = 1;
12795           else if (!_bfd_elf_gc_mark (info, rsec, gc_mark_hook))
12796             return FALSE;
12797         }
12798       if (!start_stop)
12799         break;
12800       rsec = bfd_get_next_section_by_name (rsec->owner, rsec);
12801     }
12802   return TRUE;
12803 }
12804
12805 /* The mark phase of garbage collection.  For a given section, mark
12806    it and any sections in this section's group, and all the sections
12807    which define symbols to which it refers.  */
12808
12809 bfd_boolean
12810 _bfd_elf_gc_mark (struct bfd_link_info *info,
12811                   asection *sec,
12812                   elf_gc_mark_hook_fn gc_mark_hook)
12813 {
12814   bfd_boolean ret;
12815   asection *group_sec, *eh_frame;
12816
12817   sec->gc_mark = 1;
12818
12819   /* Mark all the sections in the group.  */
12820   group_sec = elf_section_data (sec)->next_in_group;
12821   if (group_sec && !group_sec->gc_mark)
12822     if (!_bfd_elf_gc_mark (info, group_sec, gc_mark_hook))
12823       return FALSE;
12824
12825   /* Look through the section relocs.  */
12826   ret = TRUE;
12827   eh_frame = elf_eh_frame_section (sec->owner);
12828   if ((sec->flags & SEC_RELOC) != 0
12829       && sec->reloc_count > 0
12830       && sec != eh_frame)
12831     {
12832       struct elf_reloc_cookie cookie;
12833
12834       if (!init_reloc_cookie_for_section (&cookie, info, sec))
12835         ret = FALSE;
12836       else
12837         {
12838           for (; cookie.rel < cookie.relend; cookie.rel++)
12839             if (!_bfd_elf_gc_mark_reloc (info, sec, gc_mark_hook, &cookie))
12840               {
12841                 ret = FALSE;
12842                 break;
12843               }
12844           fini_reloc_cookie_for_section (&cookie, sec);
12845         }
12846     }
12847
12848   if (ret && eh_frame && elf_fde_list (sec))
12849     {
12850       struct elf_reloc_cookie cookie;
12851
12852       if (!init_reloc_cookie_for_section (&cookie, info, eh_frame))
12853         ret = FALSE;
12854       else
12855         {
12856           if (!_bfd_elf_gc_mark_fdes (info, sec, eh_frame,
12857                                       gc_mark_hook, &cookie))
12858             ret = FALSE;
12859           fini_reloc_cookie_for_section (&cookie, eh_frame);
12860         }
12861     }
12862
12863   eh_frame = elf_section_eh_frame_entry (sec);
12864   if (ret && eh_frame && !eh_frame->gc_mark)
12865     if (!_bfd_elf_gc_mark (info, eh_frame, gc_mark_hook))
12866       ret = FALSE;
12867
12868   return ret;
12869 }
12870
12871 /* Scan and mark sections in a special or debug section group.  */
12872
12873 static void
12874 _bfd_elf_gc_mark_debug_special_section_group (asection *grp)
12875 {
12876   /* Point to first section of section group.  */
12877   asection *ssec;
12878   /* Used to iterate the section group.  */
12879   asection *msec;
12880
12881   bfd_boolean is_special_grp = TRUE;
12882   bfd_boolean is_debug_grp = TRUE;
12883
12884   /* First scan to see if group contains any section other than debug
12885      and special section.  */
12886   ssec = msec = elf_next_in_group (grp);
12887   do
12888     {
12889       if ((msec->flags & SEC_DEBUGGING) == 0)
12890         is_debug_grp = FALSE;
12891
12892       if ((msec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) != 0)
12893         is_special_grp = FALSE;
12894
12895       msec = elf_next_in_group (msec);
12896     }
12897   while (msec != ssec);
12898
12899   /* If this is a pure debug section group or pure special section group,
12900      keep all sections in this group.  */
12901   if (is_debug_grp || is_special_grp)
12902     {
12903       do
12904         {
12905           msec->gc_mark = 1;
12906           msec = elf_next_in_group (msec);
12907         }
12908       while (msec != ssec);
12909     }
12910 }
12911
12912 /* Keep debug and special sections.  */
12913
12914 bfd_boolean
12915 _bfd_elf_gc_mark_extra_sections (struct bfd_link_info *info,
12916                                  elf_gc_mark_hook_fn mark_hook ATTRIBUTE_UNUSED)
12917 {
12918   bfd *ibfd;
12919
12920   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
12921     {
12922       asection *isec;
12923       bfd_boolean some_kept;
12924       bfd_boolean debug_frag_seen;
12925       bfd_boolean has_kept_debug_info;
12926
12927       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
12928         continue;
12929       isec = ibfd->sections;
12930       if (isec == NULL || isec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
12931         continue;
12932
12933       /* Ensure all linker created sections are kept,
12934          see if any other section is already marked,
12935          and note if we have any fragmented debug sections.  */
12936       debug_frag_seen = some_kept = has_kept_debug_info = FALSE;
12937       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
12938         {
12939           if ((isec->flags & SEC_LINKER_CREATED) != 0)
12940             isec->gc_mark = 1;
12941           else if (isec->gc_mark
12942                    && (isec->flags & SEC_ALLOC) != 0
12943                    && elf_section_type (isec) != SHT_NOTE)
12944             some_kept = TRUE;
12945
12946           if (!debug_frag_seen
12947               && (isec->flags & SEC_DEBUGGING)
12948               && CONST_STRNEQ (isec->name, ".debug_line."))
12949             debug_frag_seen = TRUE;
12950         }
12951
12952       /* If no non-note alloc section in this file will be kept, then
12953          we can toss out the debug and special sections.  */
12954       if (!some_kept)
12955         continue;
12956
12957       /* Keep debug and special sections like .comment when they are
12958          not part of a group.  Also keep section groups that contain
12959          just debug sections or special sections.  */
12960       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
12961         {
12962           if ((isec->flags & SEC_GROUP) != 0)
12963             _bfd_elf_gc_mark_debug_special_section_group (isec);
12964           else if (((isec->flags & SEC_DEBUGGING) != 0
12965                     || (isec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) == 0)
12966                    && elf_next_in_group (isec) == NULL)
12967             isec->gc_mark = 1;
12968           if (isec->gc_mark && (isec->flags & SEC_DEBUGGING) != 0)
12969             has_kept_debug_info = TRUE;
12970         }
12971
12972       /* Look for CODE sections which are going to be discarded,
12973          and find and discard any fragmented debug sections which
12974          are associated with that code section.  */
12975       if (debug_frag_seen)
12976         for (isec = ibfd->sections; isec != NULL; isec = isec->next)
12977           if ((isec->flags & SEC_CODE) != 0
12978               && isec->gc_mark == 0)
12979             {
12980               unsigned int ilen;
12981               asection *dsec;
12982
12983               ilen = strlen (isec->name);
12984
12985               /* Association is determined by the name of the debug
12986                  section containing the name of the code section as
12987                  a suffix.  For example .debug_line.text.foo is a
12988                  debug section associated with .text.foo.  */
12989               for (dsec = ibfd->sections; dsec != NULL; dsec = dsec->next)
12990                 {
12991                   unsigned int dlen;
12992
12993                   if (dsec->gc_mark == 0
12994                       || (dsec->flags & SEC_DEBUGGING) == 0)
12995                     continue;
12996
12997                   dlen = strlen (dsec->name);
12998
12999                   if (dlen > ilen
13000                       && strncmp (dsec->name + (dlen - ilen),
13001                                   isec->name, ilen) == 0)
13002                     dsec->gc_mark = 0;
13003                 }
13004           }
13005
13006       /* Mark debug sections referenced by kept debug sections.  */
13007       if (has_kept_debug_info)
13008         for (isec = ibfd->sections; isec != NULL; isec = isec->next)
13009           if (isec->gc_mark
13010               && (isec->flags & SEC_DEBUGGING) != 0)
13011             if (!_bfd_elf_gc_mark (info, isec,
13012                                    elf_gc_mark_debug_section))
13013               return FALSE;
13014     }
13015   return TRUE;
13016 }
13017
13018 static bfd_boolean
13019 elf_gc_sweep (bfd *abfd, struct bfd_link_info *info)
13020 {
13021   bfd *sub;
13022   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13023
13024   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
13025     {
13026       asection *o;
13027
13028       if (bfd_get_flavour (sub) != bfd_target_elf_flavour
13029           || !(*bed->relocs_compatible) (sub->xvec, abfd->xvec))
13030         continue;
13031       o = sub->sections;
13032       if (o == NULL || o->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13033         continue;
13034
13035       for (o = sub->sections; o != NULL; o = o->next)
13036         {
13037           /* When any section in a section group is kept, we keep all
13038              sections in the section group.  If the first member of
13039              the section group is excluded, we will also exclude the
13040              group section.  */
13041           if (o->flags & SEC_GROUP)
13042             {
13043               asection *first = elf_next_in_group (o);
13044               o->gc_mark = first->gc_mark;
13045             }
13046
13047           if (o->gc_mark)
13048             continue;
13049
13050           /* Skip sweeping sections already excluded.  */
13051           if (o->flags & SEC_EXCLUDE)
13052             continue;
13053
13054           /* Since this is early in the link process, it is simple
13055              to remove a section from the output.  */
13056           o->flags |= SEC_EXCLUDE;
13057
13058           if (info->print_gc_sections && o->size != 0)
13059             /* xgettext:c-format */
13060             _bfd_error_handler (_("Removing unused section '%A' in file '%B'"),
13061                                 o, sub);
13062         }
13063     }
13064
13065   return TRUE;
13066 }
13067
13068 /* Propagate collected vtable information.  This is called through
13069    elf_link_hash_traverse.  */
13070
13071 static bfd_boolean
13072 elf_gc_propagate_vtable_entries_used (struct elf_link_hash_entry *h, void *okp)
13073 {
13074   /* Those that are not vtables.  */
13075   if (h->start_stop
13076       || h->u2.vtable == NULL
13077       || h->u2.vtable->parent == NULL)
13078     return TRUE;
13079
13080   /* Those vtables that do not have parents, we cannot merge.  */
13081   if (h->u2.vtable->parent == (struct elf_link_hash_entry *) -1)
13082     return TRUE;
13083
13084   /* If we've already been done, exit.  */
13085   if (h->u2.vtable->used && h->u2.vtable->used[-1])
13086     return TRUE;
13087
13088   /* Make sure the parent's table is up to date.  */
13089   elf_gc_propagate_vtable_entries_used (h->u2.vtable->parent, okp);
13090
13091   if (h->u2.vtable->used == NULL)
13092     {
13093       /* None of this table's entries were referenced.  Re-use the
13094          parent's table.  */
13095       h->u2.vtable->used = h->u2.vtable->parent->u2.vtable->used;
13096       h->u2.vtable->size = h->u2.vtable->parent->u2.vtable->size;
13097     }
13098   else
13099     {
13100       size_t n;
13101       bfd_boolean *cu, *pu;
13102
13103       /* Or the parent's entries into ours.  */
13104       cu = h->u2.vtable->used;
13105       cu[-1] = TRUE;
13106       pu = h->u2.vtable->parent->u2.vtable->used;
13107       if (pu != NULL)
13108         {
13109           const struct elf_backend_data *bed;
13110           unsigned int log_file_align;
13111
13112           bed = get_elf_backend_data (h->root.u.def.section->owner);
13113           log_file_align = bed->s->log_file_align;
13114           n = h->u2.vtable->parent->u2.vtable->size >> log_file_align;
13115           while (n--)
13116             {
13117               if (*pu)
13118                 *cu = TRUE;
13119               pu++;
13120               cu++;
13121             }
13122         }
13123     }
13124
13125   return TRUE;
13126 }
13127
13128 static bfd_boolean
13129 elf_gc_smash_unused_vtentry_relocs (struct elf_link_hash_entry *h, void *okp)
13130 {
13131   asection *sec;
13132   bfd_vma hstart, hend;
13133   Elf_Internal_Rela *relstart, *relend, *rel;
13134   const struct elf_backend_data *bed;
13135   unsigned int log_file_align;
13136
13137   /* Take care of both those symbols that do not describe vtables as
13138      well as those that are not loaded.  */
13139   if (h->start_stop
13140       || h->u2.vtable == NULL
13141       || h->u2.vtable->parent == NULL)
13142     return TRUE;
13143
13144   BFD_ASSERT (h->root.type == bfd_link_hash_defined
13145               || h->root.type == bfd_link_hash_defweak);
13146
13147   sec = h->root.u.def.section;
13148   hstart = h->root.u.def.value;
13149   hend = hstart + h->size;
13150
13151   relstart = _bfd_elf_link_read_relocs (sec->owner, sec, NULL, NULL, TRUE);
13152   if (!relstart)
13153     return *(bfd_boolean *) okp = FALSE;
13154   bed = get_elf_backend_data (sec->owner);
13155   log_file_align = bed->s->log_file_align;
13156
13157   relend = relstart + sec->reloc_count;
13158
13159   for (rel = relstart; rel < relend; ++rel)
13160     if (rel->r_offset >= hstart && rel->r_offset < hend)
13161       {
13162         /* If the entry is in use, do nothing.  */
13163         if (h->u2.vtable->used
13164             && (rel->r_offset - hstart) < h->u2.vtable->size)
13165           {
13166             bfd_vma entry = (rel->r_offset - hstart) >> log_file_align;
13167             if (h->u2.vtable->used[entry])
13168               continue;
13169           }
13170         /* Otherwise, kill it.  */
13171         rel->r_offset = rel->r_info = rel->r_addend = 0;
13172       }
13173
13174   return TRUE;
13175 }
13176
13177 /* Mark sections containing dynamically referenced symbols.  When
13178    building shared libraries, we must assume that any visible symbol is
13179    referenced.  */
13180
13181 bfd_boolean
13182 bfd_elf_gc_mark_dynamic_ref_symbol (struct elf_link_hash_entry *h, void *inf)
13183 {
13184   struct bfd_link_info *info = (struct bfd_link_info *) inf;
13185   struct bfd_elf_dynamic_list *d = info->dynamic_list;
13186
13187   if ((h->root.type == bfd_link_hash_defined
13188        || h->root.type == bfd_link_hash_defweak)
13189       && (h->ref_dynamic
13190           || ((h->def_regular || ELF_COMMON_DEF_P (h))
13191               && ELF_ST_VISIBILITY (h->other) != STV_INTERNAL
13192               && ELF_ST_VISIBILITY (h->other) != STV_HIDDEN
13193               && (!bfd_link_executable (info)
13194                   || info->gc_keep_exported
13195                   || info->export_dynamic
13196                   || (h->dynamic
13197                       && d != NULL
13198                       && (*d->match) (&d->head, NULL, h->root.root.string)))
13199               && (h->versioned >= versioned
13200                   || !bfd_hide_sym_by_version (info->version_info,
13201                                                h->root.root.string)))))
13202     h->root.u.def.section->flags |= SEC_KEEP;
13203
13204   return TRUE;
13205 }
13206
13207 /* Keep all sections containing symbols undefined on the command-line,
13208    and the section containing the entry symbol.  */
13209
13210 void
13211 _bfd_elf_gc_keep (struct bfd_link_info *info)
13212 {
13213   struct bfd_sym_chain *sym;
13214
13215   for (sym = info->gc_sym_list; sym != NULL; sym = sym->next)
13216     {
13217       struct elf_link_hash_entry *h;
13218
13219       h = elf_link_hash_lookup (elf_hash_table (info), sym->name,
13220                                 FALSE, FALSE, FALSE);
13221
13222       if (h != NULL
13223           && (h->root.type == bfd_link_hash_defined
13224               || h->root.type == bfd_link_hash_defweak)
13225           && !bfd_is_abs_section (h->root.u.def.section)
13226           && !bfd_is_und_section (h->root.u.def.section))
13227         h->root.u.def.section->flags |= SEC_KEEP;
13228     }
13229 }
13230
13231 bfd_boolean
13232 bfd_elf_parse_eh_frame_entries (bfd *abfd ATTRIBUTE_UNUSED,
13233                                 struct bfd_link_info *info)
13234 {
13235   bfd *ibfd = info->input_bfds;
13236
13237   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
13238     {
13239       asection *sec;
13240       struct elf_reloc_cookie cookie;
13241
13242       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
13243         continue;
13244       sec = ibfd->sections;
13245       if (sec == NULL || sec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13246         continue;
13247
13248       if (!init_reloc_cookie (&cookie, info, ibfd))
13249         return FALSE;
13250
13251       for (sec = ibfd->sections; sec; sec = sec->next)
13252         {
13253           if (CONST_STRNEQ (bfd_section_name (ibfd, sec), ".eh_frame_entry")
13254               && init_reloc_cookie_rels (&cookie, info, ibfd, sec))
13255             {
13256               _bfd_elf_parse_eh_frame_entry (info, sec, &cookie);
13257               fini_reloc_cookie_rels (&cookie, sec);
13258             }
13259         }
13260     }
13261   return TRUE;
13262 }
13263
13264 /* Do mark and sweep of unused sections.  */
13265
13266 bfd_boolean
13267 bfd_elf_gc_sections (bfd *abfd, struct bfd_link_info *info)
13268 {
13269   bfd_boolean ok = TRUE;
13270   bfd *sub;
13271   elf_gc_mark_hook_fn gc_mark_hook;
13272   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13273   struct elf_link_hash_table *htab;
13274
13275   if (!bed->can_gc_sections
13276       || !is_elf_hash_table (info->hash))
13277     {
13278       _bfd_error_handler(_("Warning: gc-sections option ignored"));
13279       return TRUE;
13280     }
13281
13282   bed->gc_keep (info);
13283   htab = elf_hash_table (info);
13284
13285   /* Try to parse each bfd's .eh_frame section.  Point elf_eh_frame_section
13286      at the .eh_frame section if we can mark the FDEs individually.  */
13287   for (sub = info->input_bfds;
13288        info->eh_frame_hdr_type != COMPACT_EH_HDR && sub != NULL;
13289        sub = sub->link.next)
13290     {
13291       asection *sec;
13292       struct elf_reloc_cookie cookie;
13293
13294       sec = sub->sections;
13295       if (sec == NULL || sec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13296         continue;
13297       sec = bfd_get_section_by_name (sub, ".eh_frame");
13298       while (sec && init_reloc_cookie_for_section (&cookie, info, sec))
13299         {
13300           _bfd_elf_parse_eh_frame (sub, info, sec, &cookie);
13301           if (elf_section_data (sec)->sec_info
13302               && (sec->flags & SEC_LINKER_CREATED) == 0)
13303             elf_eh_frame_section (sub) = sec;
13304           fini_reloc_cookie_for_section (&cookie, sec);
13305           sec = bfd_get_next_section_by_name (NULL, sec);
13306         }
13307     }
13308
13309   /* Apply transitive closure to the vtable entry usage info.  */
13310   elf_link_hash_traverse (htab, elf_gc_propagate_vtable_entries_used, &ok);
13311   if (!ok)
13312     return FALSE;
13313
13314   /* Kill the vtable relocations that were not used.  */
13315   elf_link_hash_traverse (htab, elf_gc_smash_unused_vtentry_relocs, &ok);
13316   if (!ok)
13317     return FALSE;
13318
13319   /* Mark dynamically referenced symbols.  */
13320   if (htab->dynamic_sections_created || info->gc_keep_exported)
13321     elf_link_hash_traverse (htab, bed->gc_mark_dynamic_ref, info);
13322
13323   /* Grovel through relocs to find out who stays ...  */
13324   gc_mark_hook = bed->gc_mark_hook;
13325   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
13326     {
13327       asection *o;
13328
13329       if (bfd_get_flavour (sub) != bfd_target_elf_flavour
13330           || !(*bed->relocs_compatible) (sub->xvec, abfd->xvec))
13331         continue;
13332
13333       o = sub->sections;
13334       if (o == NULL || o->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13335         continue;
13336
13337       /* Start at sections marked with SEC_KEEP (ref _bfd_elf_gc_keep).
13338          Also treat note sections as a root, if the section is not part
13339          of a group.  */
13340       for (o = sub->sections; o != NULL; o = o->next)
13341         if (!o->gc_mark
13342             && (o->flags & SEC_EXCLUDE) == 0
13343             && ((o->flags & SEC_KEEP) != 0
13344                 || (elf_section_data (o)->this_hdr.sh_type == SHT_NOTE
13345                     && elf_next_in_group (o) == NULL )))
13346           {
13347             if (!_bfd_elf_gc_mark (info, o, gc_mark_hook))
13348               return FALSE;
13349           }
13350     }
13351
13352   /* Allow the backend to mark additional target specific sections.  */
13353   bed->gc_mark_extra_sections (info, gc_mark_hook);
13354
13355   /* ... and mark SEC_EXCLUDE for those that go.  */
13356   return elf_gc_sweep (abfd, info);
13357 }
13358 \f
13359 /* Called from check_relocs to record the existence of a VTINHERIT reloc.  */
13360
13361 bfd_boolean
13362 bfd_elf_gc_record_vtinherit (bfd *abfd,
13363                              asection *sec,
13364                              struct elf_link_hash_entry *h,
13365                              bfd_vma offset)
13366 {
13367   struct elf_link_hash_entry **sym_hashes, **sym_hashes_end;
13368   struct elf_link_hash_entry **search, *child;
13369   size_t extsymcount;
13370   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13371
13372   /* The sh_info field of the symtab header tells us where the
13373      external symbols start.  We don't care about the local symbols at
13374      this point.  */
13375   extsymcount = elf_tdata (abfd)->symtab_hdr.sh_size / bed->s->sizeof_sym;
13376   if (!elf_bad_symtab (abfd))
13377     extsymcount -= elf_tdata (abfd)->symtab_hdr.sh_info;
13378
13379   sym_hashes = elf_sym_hashes (abfd);
13380   sym_hashes_end = sym_hashes + extsymcount;
13381
13382   /* Hunt down the child symbol, which is in this section at the same
13383      offset as the relocation.  */
13384   for (search = sym_hashes; search != sym_hashes_end; ++search)
13385     {
13386       if ((child = *search) != NULL
13387           && (child->root.type == bfd_link_hash_defined
13388               || child->root.type == bfd_link_hash_defweak)
13389           && child->root.u.def.section == sec
13390           && child->root.u.def.value == offset)
13391         goto win;
13392     }
13393
13394   /* xgettext:c-format */
13395   _bfd_error_handler (_("%B: %A+%#Lx: No symbol found for INHERIT"),
13396                       abfd, sec, offset);
13397   bfd_set_error (bfd_error_invalid_operation);
13398   return FALSE;
13399
13400  win:
13401   if (!child->u2.vtable)
13402     {
13403       child->u2.vtable = ((struct elf_link_virtual_table_entry *)
13404                           bfd_zalloc (abfd, sizeof (*child->u2.vtable)));
13405       if (!child->u2.vtable)
13406         return FALSE;
13407     }
13408   if (!h)
13409     {
13410       /* This *should* only be the absolute section.  It could potentially
13411          be that someone has defined a non-global vtable though, which
13412          would be bad.  It isn't worth paging in the local symbols to be
13413          sure though; that case should simply be handled by the assembler.  */
13414
13415       child->u2.vtable->parent = (struct elf_link_hash_entry *) -1;
13416     }
13417   else
13418     child->u2.vtable->parent = h;
13419
13420   return TRUE;
13421 }
13422
13423 /* Called from check_relocs to record the existence of a VTENTRY reloc.  */
13424
13425 bfd_boolean
13426 bfd_elf_gc_record_vtentry (bfd *abfd ATTRIBUTE_UNUSED,
13427                            asection *sec ATTRIBUTE_UNUSED,
13428                            struct elf_link_hash_entry *h,
13429                            bfd_vma addend)
13430 {
13431   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13432   unsigned int log_file_align = bed->s->log_file_align;
13433
13434   if (!h->u2.vtable)
13435     {
13436       h->u2.vtable = ((struct elf_link_virtual_table_entry *)
13437                       bfd_zalloc (abfd, sizeof (*h->u2.vtable)));
13438       if (!h->u2.vtable)
13439         return FALSE;
13440     }
13441
13442   if (addend >= h->u2.vtable->size)
13443     {
13444       size_t size, bytes, file_align;
13445       bfd_boolean *ptr = h->u2.vtable->used;
13446
13447       /* While the symbol is undefined, we have to be prepared to handle
13448          a zero size.  */
13449       file_align = 1 << log_file_align;
13450       if (h->root.type == bfd_link_hash_undefined)
13451         size = addend + file_align;
13452       else
13453         {
13454           size = h->size;
13455           if (addend >= size)
13456             {
13457               /* Oops!  We've got a reference past the defined end of
13458                  the table.  This is probably a bug -- shall we warn?  */
13459               size = addend + file_align;
13460             }
13461         }
13462       size = (size + file_align - 1) & -file_align;
13463
13464       /* Allocate one extra entry for use as a "done" flag for the
13465          consolidation pass.  */
13466       bytes = ((size >> log_file_align) + 1) * sizeof (bfd_boolean);
13467
13468       if (ptr)
13469         {
13470           ptr = (bfd_boolean *) bfd_realloc (ptr - 1, bytes);
13471
13472           if (ptr != NULL)
13473             {
13474               size_t oldbytes;
13475
13476               oldbytes = (((h->u2.vtable->size >> log_file_align) + 1)
13477                           * sizeof (bfd_boolean));
13478               memset (((char *) ptr) + oldbytes, 0, bytes - oldbytes);
13479             }
13480         }
13481       else
13482         ptr = (bfd_boolean *) bfd_zmalloc (bytes);
13483
13484       if (ptr == NULL)
13485         return FALSE;
13486
13487       /* And arrange for that done flag to be at index -1.  */
13488       h->u2.vtable->used = ptr + 1;
13489       h->u2.vtable->size = size;
13490     }
13491
13492   h->u2.vtable->used[addend >> log_file_align] = TRUE;
13493
13494   return TRUE;
13495 }
13496
13497 /* Map an ELF section header flag to its corresponding string.  */
13498 typedef struct
13499 {
13500   char *flag_name;
13501   flagword flag_value;
13502 } elf_flags_to_name_table;
13503
13504 static elf_flags_to_name_table elf_flags_to_names [] =
13505 {
13506   { "SHF_WRITE", SHF_WRITE },
13507   { "SHF_ALLOC", SHF_ALLOC },
13508   { "SHF_EXECINSTR", SHF_EXECINSTR },
13509   { "SHF_MERGE", SHF_MERGE },
13510   { "SHF_STRINGS", SHF_STRINGS },
13511   { "SHF_INFO_LINK", SHF_INFO_LINK},
13512   { "SHF_LINK_ORDER", SHF_LINK_ORDER},
13513   { "SHF_OS_NONCONFORMING", SHF_OS_NONCONFORMING},
13514   { "SHF_GROUP", SHF_GROUP },
13515   { "SHF_TLS", SHF_TLS },
13516   { "SHF_MASKOS", SHF_MASKOS },
13517   { "SHF_EXCLUDE", SHF_EXCLUDE },
13518 };
13519
13520 /* Returns TRUE if the section is to be included, otherwise FALSE.  */
13521 bfd_boolean
13522 bfd_elf_lookup_section_flags (struct bfd_link_info *info,
13523                               struct flag_info *flaginfo,
13524                               asection *section)
13525 {
13526   const bfd_vma sh_flags = elf_section_flags (section);
13527
13528   if (!flaginfo->flags_initialized)
13529     {
13530       bfd *obfd = info->output_bfd;
13531       const struct elf_backend_data *bed = get_elf_backend_data (obfd);
13532       struct flag_info_list *tf = flaginfo->flag_list;
13533       int with_hex = 0;
13534       int without_hex = 0;
13535
13536       for (tf = flaginfo->flag_list; tf != NULL; tf = tf->next)
13537         {
13538           unsigned i;
13539           flagword (*lookup) (char *);
13540
13541           lookup = bed->elf_backend_lookup_section_flags_hook;
13542           if (lookup != NULL)
13543             {
13544               flagword hexval = (*lookup) ((char *) tf->name);
13545
13546               if (hexval != 0)
13547                 {
13548                   if (tf->with == with_flags)
13549                     with_hex |= hexval;
13550                   else if (tf->with == without_flags)
13551                     without_hex |= hexval;
13552                   tf->valid = TRUE;
13553                   continue;
13554                 }
13555             }
13556           for (i = 0; i < ARRAY_SIZE (elf_flags_to_names); ++i)
13557             {
13558               if (strcmp (tf->name, elf_flags_to_names[i].flag_name) == 0)
13559                 {
13560                   if (tf->with == with_flags)
13561                     with_hex |= elf_flags_to_names[i].flag_value;
13562                   else if (tf->with == without_flags)
13563                     without_hex |= elf_flags_to_names[i].flag_value;
13564                   tf->valid = TRUE;
13565                   break;
13566                 }
13567             }
13568           if (!tf->valid)
13569             {
13570               info->callbacks->einfo
13571                 (_("Unrecognized INPUT_SECTION_FLAG %s\n"), tf->name);
13572               return FALSE;
13573             }
13574         }
13575       flaginfo->flags_initialized = TRUE;
13576       flaginfo->only_with_flags |= with_hex;
13577       flaginfo->not_with_flags |= without_hex;
13578     }
13579
13580   if ((flaginfo->only_with_flags & sh_flags) != flaginfo->only_with_flags)
13581     return FALSE;
13582
13583   if ((flaginfo->not_with_flags & sh_flags) != 0)
13584     return FALSE;
13585
13586   return TRUE;
13587 }
13588
13589 struct alloc_got_off_arg {
13590   bfd_vma gotoff;
13591   struct bfd_link_info *info;
13592 };
13593
13594 /* We need a special top-level link routine to convert got reference counts
13595    to real got offsets.  */
13596
13597 static bfd_boolean
13598 elf_gc_allocate_got_offsets (struct elf_link_hash_entry *h, void *arg)
13599 {
13600   struct alloc_got_off_arg *gofarg = (struct alloc_got_off_arg *) arg;
13601   bfd *obfd = gofarg->info->output_bfd;
13602   const struct elf_backend_data *bed = get_elf_backend_data (obfd);
13603
13604   if (h->got.refcount > 0)
13605     {
13606       h->got.offset = gofarg->gotoff;
13607       gofarg->gotoff += bed->got_elt_size (obfd, gofarg->info, h, NULL, 0);
13608     }
13609   else
13610     h->got.offset = (bfd_vma) -1;
13611
13612   return TRUE;
13613 }
13614
13615 /* And an accompanying bit to work out final got entry offsets once
13616    we're done.  Should be called from final_link.  */
13617
13618 bfd_boolean
13619 bfd_elf_gc_common_finalize_got_offsets (bfd *abfd,
13620                                         struct bfd_link_info *info)
13621 {
13622   bfd *i;
13623   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13624   bfd_vma gotoff;
13625   struct alloc_got_off_arg gofarg;
13626
13627   BFD_ASSERT (abfd == info->output_bfd);
13628
13629   if (! is_elf_hash_table (info->hash))
13630     return FALSE;
13631
13632   /* The GOT offset is relative to the .got section, but the GOT header is
13633      put into the .got.plt section, if the backend uses it.  */
13634   if (bed->want_got_plt)
13635     gotoff = 0;
13636   else
13637     gotoff = bed->got_header_size;
13638
13639   /* Do the local .got entries first.  */
13640   for (i = info->input_bfds; i; i = i->link.next)
13641     {
13642       bfd_signed_vma *local_got;
13643       size_t j, locsymcount;
13644       Elf_Internal_Shdr *symtab_hdr;
13645
13646       if (bfd_get_flavour (i) != bfd_target_elf_flavour)
13647         continue;
13648
13649       local_got = elf_local_got_refcounts (i);
13650       if (!local_got)
13651         continue;
13652
13653       symtab_hdr = &elf_tdata (i)->symtab_hdr;
13654       if (elf_bad_symtab (i))
13655         locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
13656       else
13657         locsymcount = symtab_hdr->sh_info;
13658
13659       for (j = 0; j < locsymcount; ++j)
13660         {
13661           if (local_got[j] > 0)
13662             {
13663               local_got[j] = gotoff;
13664               gotoff += bed->got_elt_size (abfd, info, NULL, i, j);
13665             }
13666           else
13667             local_got[j] = (bfd_vma) -1;
13668         }
13669     }
13670
13671   /* Then the global .got entries.  .plt refcounts are handled by
13672      adjust_dynamic_symbol  */
13673   gofarg.gotoff = gotoff;
13674   gofarg.info = info;
13675   elf_link_hash_traverse (elf_hash_table (info),
13676                           elf_gc_allocate_got_offsets,
13677                           &gofarg);
13678   return TRUE;
13679 }
13680
13681 /* Many folk need no more in the way of final link than this, once
13682    got entry reference counting is enabled.  */
13683
13684 bfd_boolean
13685 bfd_elf_gc_common_final_link (bfd *abfd, struct bfd_link_info *info)
13686 {
13687   if (!bfd_elf_gc_common_finalize_got_offsets (abfd, info))
13688     return FALSE;
13689
13690   /* Invoke the regular ELF backend linker to do all the work.  */
13691   return bfd_elf_final_link (abfd, info);
13692 }
13693
13694 bfd_boolean
13695 bfd_elf_reloc_symbol_deleted_p (bfd_vma offset, void *cookie)
13696 {
13697   struct elf_reloc_cookie *rcookie = (struct elf_reloc_cookie *) cookie;
13698
13699   if (rcookie->bad_symtab)
13700     rcookie->rel = rcookie->rels;
13701
13702   for (; rcookie->rel < rcookie->relend; rcookie->rel++)
13703     {
13704       unsigned long r_symndx;
13705
13706       if (! rcookie->bad_symtab)
13707         if (rcookie->rel->r_offset > offset)
13708           return FALSE;
13709       if (rcookie->rel->r_offset != offset)
13710         continue;
13711
13712       r_symndx = rcookie->rel->r_info >> rcookie->r_sym_shift;
13713       if (r_symndx == STN_UNDEF)
13714         return TRUE;
13715
13716       if (r_symndx >= rcookie->locsymcount
13717           || ELF_ST_BIND (rcookie->locsyms[r_symndx].st_info) != STB_LOCAL)
13718         {
13719           struct elf_link_hash_entry *h;
13720
13721           h = rcookie->sym_hashes[r_symndx - rcookie->extsymoff];
13722
13723           while (h->root.type == bfd_link_hash_indirect
13724                  || h->root.type == bfd_link_hash_warning)
13725             h = (struct elf_link_hash_entry *) h->root.u.i.link;
13726
13727           if ((h->root.type == bfd_link_hash_defined
13728                || h->root.type == bfd_link_hash_defweak)
13729               && (h->root.u.def.section->owner != rcookie->abfd
13730                   || h->root.u.def.section->kept_section != NULL
13731                   || discarded_section (h->root.u.def.section)))
13732             return TRUE;
13733         }
13734       else
13735         {
13736           /* It's not a relocation against a global symbol,
13737              but it could be a relocation against a local
13738              symbol for a discarded section.  */
13739           asection *isec;
13740           Elf_Internal_Sym *isym;
13741
13742           /* Need to: get the symbol; get the section.  */
13743           isym = &rcookie->locsyms[r_symndx];
13744           isec = bfd_section_from_elf_index (rcookie->abfd, isym->st_shndx);
13745           if (isec != NULL
13746               && (isec->kept_section != NULL
13747                   || discarded_section (isec)))
13748             return TRUE;
13749         }
13750       return FALSE;
13751     }
13752   return FALSE;
13753 }
13754
13755 /* Discard unneeded references to discarded sections.
13756    Returns -1 on error, 1 if any section's size was changed, 0 if
13757    nothing changed.  This function assumes that the relocations are in
13758    sorted order, which is true for all known assemblers.  */
13759
13760 int
13761 bfd_elf_discard_info (bfd *output_bfd, struct bfd_link_info *info)
13762 {
13763   struct elf_reloc_cookie cookie;
13764   asection *o;
13765   bfd *abfd;
13766   int changed = 0;
13767
13768   if (info->traditional_format
13769       || !is_elf_hash_table (info->hash))
13770     return 0;
13771
13772   o = bfd_get_section_by_name (output_bfd, ".stab");
13773   if (o != NULL)
13774     {
13775       asection *i;
13776
13777       for (i = o->map_head.s; i != NULL; i = i->map_head.s)
13778         {
13779           if (i->size == 0
13780               || i->reloc_count == 0
13781               || i->sec_info_type != SEC_INFO_TYPE_STABS)
13782             continue;
13783
13784           abfd = i->owner;
13785           if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13786             continue;
13787
13788           if (!init_reloc_cookie_for_section (&cookie, info, i))
13789             return -1;
13790
13791           if (_bfd_discard_section_stabs (abfd, i,
13792                                           elf_section_data (i)->sec_info,
13793                                           bfd_elf_reloc_symbol_deleted_p,
13794                                           &cookie))
13795             changed = 1;
13796
13797           fini_reloc_cookie_for_section (&cookie, i);
13798         }
13799     }
13800
13801   o = NULL;
13802   if (info->eh_frame_hdr_type != COMPACT_EH_HDR)
13803     o = bfd_get_section_by_name (output_bfd, ".eh_frame");
13804   if (o != NULL)
13805     {
13806       asection *i;
13807       int eh_changed = 0;
13808       unsigned int eh_alignment;
13809
13810       for (i = o->map_head.s; i != NULL; i = i->map_head.s)
13811         {
13812           if (i->size == 0)
13813             continue;
13814
13815           abfd = i->owner;
13816           if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13817             continue;
13818
13819           if (!init_reloc_cookie_for_section (&cookie, info, i))
13820             return -1;
13821
13822           _bfd_elf_parse_eh_frame (abfd, info, i, &cookie);
13823           if (_bfd_elf_discard_section_eh_frame (abfd, info, i,
13824                                                  bfd_elf_reloc_symbol_deleted_p,
13825                                                  &cookie))
13826             {
13827               eh_changed = 1;
13828               if (i->size != i->rawsize)
13829                 changed = 1;
13830             }
13831
13832           fini_reloc_cookie_for_section (&cookie, i);
13833         }
13834
13835       eh_alignment = 1 << o->alignment_power;
13836       /* Skip over zero terminator, and prevent empty sections from
13837          adding alignment padding at the end.  */
13838       for (i = o->map_tail.s; i != NULL; i = i->map_tail.s)
13839         if (i->size == 0)
13840           i->flags |= SEC_EXCLUDE;
13841         else if (i->size > 4)
13842           break;
13843       /* The last non-empty eh_frame section doesn't need padding.  */
13844       if (i != NULL)
13845         i = i->map_tail.s;
13846       /* Any prior sections must pad the last FDE out to the output
13847          section alignment.  Otherwise we might have zero padding
13848          between sections, which would be seen as a terminator.  */
13849       for (; i != NULL; i = i->map_tail.s)
13850         if (i->size == 4)
13851           /* All but the last zero terminator should have been removed.  */
13852           BFD_FAIL ();
13853         else
13854           {
13855             bfd_size_type size
13856               = (i->size + eh_alignment - 1) & -eh_alignment;
13857             if (i->size != size)
13858               {
13859                 i->size = size;
13860                 changed = 1;
13861                 eh_changed = 1;
13862               }
13863           }
13864       if (eh_changed)
13865         elf_link_hash_traverse (elf_hash_table (info),
13866                                 _bfd_elf_adjust_eh_frame_global_symbol, NULL);
13867     }
13868
13869   for (abfd = info->input_bfds; abfd != NULL; abfd = abfd->link.next)
13870     {
13871       const struct elf_backend_data *bed;
13872       asection *s;
13873
13874       if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13875         continue;
13876       s = abfd->sections;
13877       if (s == NULL || s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13878         continue;
13879
13880       bed = get_elf_backend_data (abfd);
13881
13882       if (bed->elf_backend_discard_info != NULL)
13883         {
13884           if (!init_reloc_cookie (&cookie, info, abfd))
13885             return -1;
13886
13887           if ((*bed->elf_backend_discard_info) (abfd, &cookie, info))
13888             changed = 1;
13889
13890           fini_reloc_cookie (&cookie, abfd);
13891         }
13892     }
13893
13894   if (info->eh_frame_hdr_type == COMPACT_EH_HDR)
13895     _bfd_elf_end_eh_frame_parsing (info);
13896
13897   if (info->eh_frame_hdr_type
13898       && !bfd_link_relocatable (info)
13899       && _bfd_elf_discard_section_eh_frame_hdr (output_bfd, info))
13900     changed = 1;
13901
13902   return changed;
13903 }
13904
13905 bfd_boolean
13906 _bfd_elf_section_already_linked (bfd *abfd,
13907                                  asection *sec,
13908                                  struct bfd_link_info *info)
13909 {
13910   flagword flags;
13911   const char *name, *key;
13912   struct bfd_section_already_linked *l;
13913   struct bfd_section_already_linked_hash_entry *already_linked_list;
13914
13915   if (sec->output_section == bfd_abs_section_ptr)
13916     return FALSE;
13917
13918   flags = sec->flags;
13919
13920   /* Return if it isn't a linkonce section.  A comdat group section
13921      also has SEC_LINK_ONCE set.  */
13922   if ((flags & SEC_LINK_ONCE) == 0)
13923     return FALSE;
13924
13925   /* Don't put group member sections on our list of already linked
13926      sections.  They are handled as a group via their group section.  */
13927   if (elf_sec_group (sec) != NULL)
13928     return FALSE;
13929
13930   /* For a SHT_GROUP section, use the group signature as the key.  */
13931   name = sec->name;
13932   if ((flags & SEC_GROUP) != 0
13933       && elf_next_in_group (sec) != NULL
13934       && elf_group_name (elf_next_in_group (sec)) != NULL)
13935     key = elf_group_name (elf_next_in_group (sec));
13936   else
13937     {
13938       /* Otherwise we should have a .gnu.linkonce.<type>.<key> section.  */
13939       if (CONST_STRNEQ (name, ".gnu.linkonce.")
13940           && (key = strchr (name + sizeof (".gnu.linkonce.") - 1, '.')) != NULL)
13941         key++;
13942       else
13943         /* Must be a user linkonce section that doesn't follow gcc's
13944            naming convention.  In this case we won't be matching
13945            single member groups.  */
13946         key = name;
13947     }
13948
13949   already_linked_list = bfd_section_already_linked_table_lookup (key);
13950
13951   for (l = already_linked_list->entry; l != NULL; l = l->next)
13952     {
13953       /* We may have 2 different types of sections on the list: group
13954          sections with a signature of <key> (<key> is some string),
13955          and linkonce sections named .gnu.linkonce.<type>.<key>.
13956          Match like sections.  LTO plugin sections are an exception.
13957          They are always named .gnu.linkonce.t.<key> and match either
13958          type of section.  */
13959       if (((flags & SEC_GROUP) == (l->sec->flags & SEC_GROUP)
13960            && ((flags & SEC_GROUP) != 0
13961                || strcmp (name, l->sec->name) == 0))
13962           || (l->sec->owner->flags & BFD_PLUGIN) != 0)
13963         {
13964           /* The section has already been linked.  See if we should
13965              issue a warning.  */
13966           if (!_bfd_handle_already_linked (sec, l, info))
13967             return FALSE;
13968
13969           if (flags & SEC_GROUP)
13970             {
13971               asection *first = elf_next_in_group (sec);
13972               asection *s = first;
13973
13974               while (s != NULL)
13975                 {
13976                   s->output_section = bfd_abs_section_ptr;
13977                   /* Record which group discards it.  */
13978                   s->kept_section = l->sec;
13979                   s = elf_next_in_group (s);
13980                   /* These lists are circular.  */
13981                   if (s == first)
13982                     break;
13983                 }
13984             }
13985
13986           return TRUE;
13987         }
13988     }
13989
13990   /* A single member comdat group section may be discarded by a
13991      linkonce section and vice versa.  */
13992   if ((flags & SEC_GROUP) != 0)
13993     {
13994       asection *first = elf_next_in_group (sec);
13995
13996       if (first != NULL && elf_next_in_group (first) == first)
13997         /* Check this single member group against linkonce sections.  */
13998         for (l = already_linked_list->entry; l != NULL; l = l->next)
13999           if ((l->sec->flags & SEC_GROUP) == 0
14000               && bfd_elf_match_symbols_in_sections (l->sec, first, info))
14001             {
14002               first->output_section = bfd_abs_section_ptr;
14003               first->kept_section = l->sec;
14004               sec->output_section = bfd_abs_section_ptr;
14005               break;
14006             }
14007     }
14008   else
14009     /* Check this linkonce section against single member groups.  */
14010     for (l = already_linked_list->entry; l != NULL; l = l->next)
14011       if (l->sec->flags & SEC_GROUP)
14012         {
14013           asection *first = elf_next_in_group (l->sec);
14014
14015           if (first != NULL
14016               && elf_next_in_group (first) == first
14017               && bfd_elf_match_symbols_in_sections (first, sec, info))
14018             {
14019               sec->output_section = bfd_abs_section_ptr;
14020               sec->kept_section = first;
14021               break;
14022             }
14023         }
14024
14025   /* Do not complain on unresolved relocations in `.gnu.linkonce.r.F'
14026      referencing its discarded `.gnu.linkonce.t.F' counterpart - g++-3.4
14027      specific as g++-4.x is using COMDAT groups (without the `.gnu.linkonce'
14028      prefix) instead.  `.gnu.linkonce.r.*' were the `.rodata' part of its
14029      matching `.gnu.linkonce.t.*'.  If `.gnu.linkonce.r.F' is not discarded
14030      but its `.gnu.linkonce.t.F' is discarded means we chose one-only
14031      `.gnu.linkonce.t.F' section from a different bfd not requiring any
14032      `.gnu.linkonce.r.F'.  Thus `.gnu.linkonce.r.F' should be discarded.
14033      The reverse order cannot happen as there is never a bfd with only the
14034      `.gnu.linkonce.r.F' section.  The order of sections in a bfd does not
14035      matter as here were are looking only for cross-bfd sections.  */
14036
14037   if ((flags & SEC_GROUP) == 0 && CONST_STRNEQ (name, ".gnu.linkonce.r."))
14038     for (l = already_linked_list->entry; l != NULL; l = l->next)
14039       if ((l->sec->flags & SEC_GROUP) == 0
14040           && CONST_STRNEQ (l->sec->name, ".gnu.linkonce.t."))
14041         {
14042           if (abfd != l->sec->owner)
14043             sec->output_section = bfd_abs_section_ptr;
14044           break;
14045         }
14046
14047   /* This is the first section with this name.  Record it.  */
14048   if (!bfd_section_already_linked_table_insert (already_linked_list, sec))
14049     info->callbacks->einfo (_("%F%P: already_linked_table: %E\n"));
14050   return sec->output_section == bfd_abs_section_ptr;
14051 }
14052
14053 bfd_boolean
14054 _bfd_elf_common_definition (Elf_Internal_Sym *sym)
14055 {
14056   return sym->st_shndx == SHN_COMMON;
14057 }
14058
14059 unsigned int
14060 _bfd_elf_common_section_index (asection *sec ATTRIBUTE_UNUSED)
14061 {
14062   return SHN_COMMON;
14063 }
14064
14065 asection *
14066 _bfd_elf_common_section (asection *sec ATTRIBUTE_UNUSED)
14067 {
14068   return bfd_com_section_ptr;
14069 }
14070
14071 bfd_vma
14072 _bfd_elf_default_got_elt_size (bfd *abfd,
14073                                struct bfd_link_info *info ATTRIBUTE_UNUSED,
14074                                struct elf_link_hash_entry *h ATTRIBUTE_UNUSED,
14075                                bfd *ibfd ATTRIBUTE_UNUSED,
14076                                unsigned long symndx ATTRIBUTE_UNUSED)
14077 {
14078   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
14079   return bed->s->arch_size / 8;
14080 }
14081
14082 /* Routines to support the creation of dynamic relocs.  */
14083
14084 /* Returns the name of the dynamic reloc section associated with SEC.  */
14085
14086 static const char *
14087 get_dynamic_reloc_section_name (bfd *       abfd,
14088                                 asection *  sec,
14089                                 bfd_boolean is_rela)
14090 {
14091   char *name;
14092   const char *old_name = bfd_get_section_name (NULL, sec);
14093   const char *prefix = is_rela ? ".rela" : ".rel";
14094
14095   if (old_name == NULL)
14096     return NULL;
14097
14098   name = bfd_alloc (abfd, strlen (prefix) + strlen (old_name) + 1);
14099   sprintf (name, "%s%s", prefix, old_name);
14100
14101   return name;
14102 }
14103
14104 /* Returns the dynamic reloc section associated with SEC.
14105    If necessary compute the name of the dynamic reloc section based
14106    on SEC's name (looked up in ABFD's string table) and the setting
14107    of IS_RELA.  */
14108
14109 asection *
14110 _bfd_elf_get_dynamic_reloc_section (bfd *       abfd,
14111                                     asection *  sec,
14112                                     bfd_boolean is_rela)
14113 {
14114   asection * reloc_sec = elf_section_data (sec)->sreloc;
14115
14116   if (reloc_sec == NULL)
14117     {
14118       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
14119
14120       if (name != NULL)
14121         {
14122           reloc_sec = bfd_get_linker_section (abfd, name);
14123
14124           if (reloc_sec != NULL)
14125             elf_section_data (sec)->sreloc = reloc_sec;
14126         }
14127     }
14128
14129   return reloc_sec;
14130 }
14131
14132 /* Returns the dynamic reloc section associated with SEC.  If the
14133    section does not exist it is created and attached to the DYNOBJ
14134    bfd and stored in the SRELOC field of SEC's elf_section_data
14135    structure.
14136
14137    ALIGNMENT is the alignment for the newly created section and
14138    IS_RELA defines whether the name should be .rela.<SEC's name>
14139    or .rel.<SEC's name>.  The section name is looked up in the
14140    string table associated with ABFD.  */
14141
14142 asection *
14143 _bfd_elf_make_dynamic_reloc_section (asection *sec,
14144                                      bfd *dynobj,
14145                                      unsigned int alignment,
14146                                      bfd *abfd,
14147                                      bfd_boolean is_rela)
14148 {
14149   asection * reloc_sec = elf_section_data (sec)->sreloc;
14150
14151   if (reloc_sec == NULL)
14152     {
14153       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
14154
14155       if (name == NULL)
14156         return NULL;
14157
14158       reloc_sec = bfd_get_linker_section (dynobj, name);
14159
14160       if (reloc_sec == NULL)
14161         {
14162           flagword flags = (SEC_HAS_CONTENTS | SEC_READONLY
14163                             | SEC_IN_MEMORY | SEC_LINKER_CREATED);
14164           if ((sec->flags & SEC_ALLOC) != 0)
14165             flags |= SEC_ALLOC | SEC_LOAD;
14166
14167           reloc_sec = bfd_make_section_anyway_with_flags (dynobj, name, flags);
14168           if (reloc_sec != NULL)
14169             {
14170               /* _bfd_elf_get_sec_type_attr chooses a section type by
14171                  name.  Override as it may be wrong, eg. for a user
14172                  section named "auto" we'll get ".relauto" which is
14173                  seen to be a .rela section.  */
14174               elf_section_type (reloc_sec) = is_rela ? SHT_RELA : SHT_REL;
14175               if (! bfd_set_section_alignment (dynobj, reloc_sec, alignment))
14176                 reloc_sec = NULL;
14177             }
14178         }
14179
14180       elf_section_data (sec)->sreloc = reloc_sec;
14181     }
14182
14183   return reloc_sec;
14184 }
14185
14186 /* Copy the ELF symbol type and other attributes for a linker script
14187    assignment from HSRC to HDEST.  Generally this should be treated as
14188    if we found a strong non-dynamic definition for HDEST (except that
14189    ld ignores multiple definition errors).  */
14190 void
14191 _bfd_elf_copy_link_hash_symbol_type (bfd *abfd,
14192                                      struct bfd_link_hash_entry *hdest,
14193                                      struct bfd_link_hash_entry *hsrc)
14194 {
14195   struct elf_link_hash_entry *ehdest = (struct elf_link_hash_entry *) hdest;
14196   struct elf_link_hash_entry *ehsrc = (struct elf_link_hash_entry *) hsrc;
14197   Elf_Internal_Sym isym;
14198
14199   ehdest->type = ehsrc->type;
14200   ehdest->target_internal = ehsrc->target_internal;
14201
14202   isym.st_other = ehsrc->other;
14203   elf_merge_st_other (abfd, ehdest, &isym, NULL, TRUE, FALSE);
14204 }
14205
14206 /* Append a RELA relocation REL to section S in BFD.  */
14207
14208 void
14209 elf_append_rela (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
14210 {
14211   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
14212   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rela);
14213   BFD_ASSERT (loc + bed->s->sizeof_rela <= s->contents + s->size);
14214   bed->s->swap_reloca_out (abfd, rel, loc);
14215 }
14216
14217 /* Append a REL relocation REL to section S in BFD.  */
14218
14219 void
14220 elf_append_rel (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
14221 {
14222   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
14223   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rel);
14224   BFD_ASSERT (loc + bed->s->sizeof_rel <= s->contents + s->size);
14225   bed->s->swap_reloc_out (abfd, rel, loc);
14226 }
14227
14228 /* Define __start, __stop, .startof. or .sizeof. symbol.  */
14229
14230 struct bfd_link_hash_entry *
14231 bfd_elf_define_start_stop (struct bfd_link_info *info,
14232                            const char *symbol, asection *sec)
14233 {
14234   struct elf_link_hash_entry *h;
14235
14236   h = elf_link_hash_lookup (elf_hash_table (info), symbol,
14237                             FALSE, FALSE, TRUE);
14238   if (h != NULL
14239       && (h->root.type == bfd_link_hash_undefined
14240           || h->root.type == bfd_link_hash_undefweak
14241           || (h->ref_regular && !h->def_regular)))
14242     {
14243       h->root.type = bfd_link_hash_defined;
14244       h->root.u.def.section = sec;
14245       h->root.u.def.value = 0;
14246       h->def_regular = 1;
14247       h->def_dynamic = 0;
14248       h->start_stop = 1;
14249       h->u2.start_stop_section = sec;
14250       if (symbol[0] == '.')
14251         {
14252           /* .startof. and .sizeof. symbols are local.  */
14253           const struct elf_backend_data *bed;
14254           bed = get_elf_backend_data (info->output_bfd);
14255           (*bed->elf_backend_hide_symbol) (info, h, TRUE);
14256         }
14257       else if (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT)
14258         h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_PROTECTED;
14259       return &h->root;
14260     }
14261   return NULL;
14262 }