* elflink.h (elf_gc_sweep): Keep non-alloc, non-load sections.
[external/binutils.git] / bfd / elflink.c
1 /* ELF linking support for BFD.
2    Copyright 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004
3    Free Software Foundation, Inc.
4
5 This file is part of BFD, the Binary File Descriptor library.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
20
21 #include "bfd.h"
22 #include "sysdep.h"
23 #include "bfdlink.h"
24 #include "libbfd.h"
25 #define ARCH_SIZE 0
26 #include "elf-bfd.h"
27 #include "safe-ctype.h"
28 #include "libiberty.h"
29
30 bfd_boolean
31 _bfd_elf_create_got_section (bfd *abfd, struct bfd_link_info *info)
32 {
33   flagword flags;
34   asection *s;
35   struct elf_link_hash_entry *h;
36   struct bfd_link_hash_entry *bh;
37   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
38   int ptralign;
39
40   /* This function may be called more than once.  */
41   s = bfd_get_section_by_name (abfd, ".got");
42   if (s != NULL && (s->flags & SEC_LINKER_CREATED) != 0)
43     return TRUE;
44
45   switch (bed->s->arch_size)
46     {
47     case 32:
48       ptralign = 2;
49       break;
50
51     case 64:
52       ptralign = 3;
53       break;
54
55     default:
56       bfd_set_error (bfd_error_bad_value);
57       return FALSE;
58     }
59
60   flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY
61            | SEC_LINKER_CREATED);
62
63   s = bfd_make_section (abfd, ".got");
64   if (s == NULL
65       || !bfd_set_section_flags (abfd, s, flags)
66       || !bfd_set_section_alignment (abfd, s, ptralign))
67     return FALSE;
68
69   if (bed->want_got_plt)
70     {
71       s = bfd_make_section (abfd, ".got.plt");
72       if (s == NULL
73           || !bfd_set_section_flags (abfd, s, flags)
74           || !bfd_set_section_alignment (abfd, s, ptralign))
75         return FALSE;
76     }
77
78   if (bed->want_got_sym)
79     {
80       /* Define the symbol _GLOBAL_OFFSET_TABLE_ at the start of the .got
81          (or .got.plt) section.  We don't do this in the linker script
82          because we don't want to define the symbol if we are not creating
83          a global offset table.  */
84       bh = NULL;
85       if (!(_bfd_generic_link_add_one_symbol
86             (info, abfd, "_GLOBAL_OFFSET_TABLE_", BSF_GLOBAL, s,
87              bed->got_symbol_offset, NULL, FALSE, bed->collect, &bh)))
88         return FALSE;
89       h = (struct elf_link_hash_entry *) bh;
90       h->elf_link_hash_flags |= ELF_LINK_HASH_DEF_REGULAR;
91       h->type = STT_OBJECT;
92
93       if (! info->executable
94           && ! bfd_elf_link_record_dynamic_symbol (info, h))
95         return FALSE;
96
97       elf_hash_table (info)->hgot = h;
98     }
99
100   /* The first bit of the global offset table is the header.  */
101   s->size += bed->got_header_size + bed->got_symbol_offset;
102
103   return TRUE;
104 }
105 \f
106 /* Create some sections which will be filled in with dynamic linking
107    information.  ABFD is an input file which requires dynamic sections
108    to be created.  The dynamic sections take up virtual memory space
109    when the final executable is run, so we need to create them before
110    addresses are assigned to the output sections.  We work out the
111    actual contents and size of these sections later.  */
112
113 bfd_boolean
114 _bfd_elf_link_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
115 {
116   flagword flags;
117   register asection *s;
118   struct elf_link_hash_entry *h;
119   struct bfd_link_hash_entry *bh;
120   const struct elf_backend_data *bed;
121
122   if (! is_elf_hash_table (info->hash))
123     return FALSE;
124
125   if (elf_hash_table (info)->dynamic_sections_created)
126     return TRUE;
127
128   /* Make sure that all dynamic sections use the same input BFD.  */
129   if (elf_hash_table (info)->dynobj == NULL)
130     elf_hash_table (info)->dynobj = abfd;
131   else
132     abfd = elf_hash_table (info)->dynobj;
133
134   /* Note that we set the SEC_IN_MEMORY flag for all of these
135      sections.  */
136   flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS
137            | SEC_IN_MEMORY | SEC_LINKER_CREATED);
138
139   /* A dynamically linked executable has a .interp section, but a
140      shared library does not.  */
141   if (info->executable)
142     {
143       s = bfd_make_section (abfd, ".interp");
144       if (s == NULL
145           || ! bfd_set_section_flags (abfd, s, flags | SEC_READONLY))
146         return FALSE;
147     }
148
149   if (! info->traditional_format)
150     {
151       s = bfd_make_section (abfd, ".eh_frame_hdr");
152       if (s == NULL
153           || ! bfd_set_section_flags (abfd, s, flags | SEC_READONLY)
154           || ! bfd_set_section_alignment (abfd, s, 2))
155         return FALSE;
156       elf_hash_table (info)->eh_info.hdr_sec = s;
157     }
158
159   bed = get_elf_backend_data (abfd);
160
161   /* Create sections to hold version informations.  These are removed
162      if they are not needed.  */
163   s = bfd_make_section (abfd, ".gnu.version_d");
164   if (s == NULL
165       || ! bfd_set_section_flags (abfd, s, flags | SEC_READONLY)
166       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
167     return FALSE;
168
169   s = bfd_make_section (abfd, ".gnu.version");
170   if (s == NULL
171       || ! bfd_set_section_flags (abfd, s, flags | SEC_READONLY)
172       || ! bfd_set_section_alignment (abfd, s, 1))
173     return FALSE;
174
175   s = bfd_make_section (abfd, ".gnu.version_r");
176   if (s == NULL
177       || ! bfd_set_section_flags (abfd, s, flags | SEC_READONLY)
178       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
179     return FALSE;
180
181   s = bfd_make_section (abfd, ".dynsym");
182   if (s == NULL
183       || ! bfd_set_section_flags (abfd, s, flags | SEC_READONLY)
184       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
185     return FALSE;
186
187   s = bfd_make_section (abfd, ".dynstr");
188   if (s == NULL
189       || ! bfd_set_section_flags (abfd, s, flags | SEC_READONLY))
190     return FALSE;
191
192   /* Create a strtab to hold the dynamic symbol names.  */
193   if (elf_hash_table (info)->dynstr == NULL)
194     {
195       elf_hash_table (info)->dynstr = _bfd_elf_strtab_init ();
196       if (elf_hash_table (info)->dynstr == NULL)
197         return FALSE;
198     }
199
200   s = bfd_make_section (abfd, ".dynamic");
201   if (s == NULL
202       || ! bfd_set_section_flags (abfd, s, flags)
203       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
204     return FALSE;
205
206   /* The special symbol _DYNAMIC is always set to the start of the
207      .dynamic section.  This call occurs before we have processed the
208      symbols for any dynamic object, so we don't have to worry about
209      overriding a dynamic definition.  We could set _DYNAMIC in a
210      linker script, but we only want to define it if we are, in fact,
211      creating a .dynamic section.  We don't want to define it if there
212      is no .dynamic section, since on some ELF platforms the start up
213      code examines it to decide how to initialize the process.  */
214   bh = NULL;
215   if (! (_bfd_generic_link_add_one_symbol
216          (info, abfd, "_DYNAMIC", BSF_GLOBAL, s, 0, NULL, FALSE,
217           get_elf_backend_data (abfd)->collect, &bh)))
218     return FALSE;
219   h = (struct elf_link_hash_entry *) bh;
220   h->elf_link_hash_flags |= ELF_LINK_HASH_DEF_REGULAR;
221   h->type = STT_OBJECT;
222
223   if (! info->executable
224       && ! bfd_elf_link_record_dynamic_symbol (info, h))
225     return FALSE;
226
227   s = bfd_make_section (abfd, ".hash");
228   if (s == NULL
229       || ! bfd_set_section_flags (abfd, s, flags | SEC_READONLY)
230       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
231     return FALSE;
232   elf_section_data (s)->this_hdr.sh_entsize = bed->s->sizeof_hash_entry;
233
234   /* Let the backend create the rest of the sections.  This lets the
235      backend set the right flags.  The backend will normally create
236      the .got and .plt sections.  */
237   if (! (*bed->elf_backend_create_dynamic_sections) (abfd, info))
238     return FALSE;
239
240   elf_hash_table (info)->dynamic_sections_created = TRUE;
241
242   return TRUE;
243 }
244
245 /* Create dynamic sections when linking against a dynamic object.  */
246
247 bfd_boolean
248 _bfd_elf_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
249 {
250   flagword flags, pltflags;
251   asection *s;
252   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
253
254   /* We need to create .plt, .rel[a].plt, .got, .got.plt, .dynbss, and
255      .rel[a].bss sections.  */
256
257   flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY
258            | SEC_LINKER_CREATED);
259
260   pltflags = flags;
261   pltflags |= SEC_CODE;
262   if (bed->plt_not_loaded)
263     pltflags &= ~ (SEC_CODE | SEC_LOAD | SEC_HAS_CONTENTS);
264   if (bed->plt_readonly)
265     pltflags |= SEC_READONLY;
266
267   s = bfd_make_section (abfd, ".plt");
268   if (s == NULL
269       || ! bfd_set_section_flags (abfd, s, pltflags)
270       || ! bfd_set_section_alignment (abfd, s, bed->plt_alignment))
271     return FALSE;
272
273   if (bed->want_plt_sym)
274     {
275       /* Define the symbol _PROCEDURE_LINKAGE_TABLE_ at the start of the
276          .plt section.  */
277       struct elf_link_hash_entry *h;
278       struct bfd_link_hash_entry *bh = NULL;
279
280       if (! (_bfd_generic_link_add_one_symbol
281              (info, abfd, "_PROCEDURE_LINKAGE_TABLE_", BSF_GLOBAL, s, 0, NULL,
282               FALSE, get_elf_backend_data (abfd)->collect, &bh)))
283         return FALSE;
284       h = (struct elf_link_hash_entry *) bh;
285       h->elf_link_hash_flags |= ELF_LINK_HASH_DEF_REGULAR;
286       h->type = STT_OBJECT;
287
288       if (! info->executable
289           && ! bfd_elf_link_record_dynamic_symbol (info, h))
290         return FALSE;
291     }
292
293   s = bfd_make_section (abfd,
294                         bed->default_use_rela_p ? ".rela.plt" : ".rel.plt");
295   if (s == NULL
296       || ! bfd_set_section_flags (abfd, s, flags | SEC_READONLY)
297       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
298     return FALSE;
299
300   if (! _bfd_elf_create_got_section (abfd, info))
301     return FALSE;
302
303   if (bed->want_dynbss)
304     {
305       /* The .dynbss section is a place to put symbols which are defined
306          by dynamic objects, are referenced by regular objects, and are
307          not functions.  We must allocate space for them in the process
308          image and use a R_*_COPY reloc to tell the dynamic linker to
309          initialize them at run time.  The linker script puts the .dynbss
310          section into the .bss section of the final image.  */
311       s = bfd_make_section (abfd, ".dynbss");
312       if (s == NULL
313           || ! bfd_set_section_flags (abfd, s, SEC_ALLOC | SEC_LINKER_CREATED))
314         return FALSE;
315
316       /* The .rel[a].bss section holds copy relocs.  This section is not
317      normally needed.  We need to create it here, though, so that the
318      linker will map it to an output section.  We can't just create it
319      only if we need it, because we will not know whether we need it
320      until we have seen all the input files, and the first time the
321      main linker code calls BFD after examining all the input files
322      (size_dynamic_sections) the input sections have already been
323      mapped to the output sections.  If the section turns out not to
324      be needed, we can discard it later.  We will never need this
325      section when generating a shared object, since they do not use
326      copy relocs.  */
327       if (! info->shared)
328         {
329           s = bfd_make_section (abfd,
330                                 (bed->default_use_rela_p
331                                  ? ".rela.bss" : ".rel.bss"));
332           if (s == NULL
333               || ! bfd_set_section_flags (abfd, s, flags | SEC_READONLY)
334               || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
335             return FALSE;
336         }
337     }
338
339   return TRUE;
340 }
341 \f
342 /* Record a new dynamic symbol.  We record the dynamic symbols as we
343    read the input files, since we need to have a list of all of them
344    before we can determine the final sizes of the output sections.
345    Note that we may actually call this function even though we are not
346    going to output any dynamic symbols; in some cases we know that a
347    symbol should be in the dynamic symbol table, but only if there is
348    one.  */
349
350 bfd_boolean
351 bfd_elf_link_record_dynamic_symbol (struct bfd_link_info *info,
352                                     struct elf_link_hash_entry *h)
353 {
354   if (h->dynindx == -1)
355     {
356       struct elf_strtab_hash *dynstr;
357       char *p;
358       const char *name;
359       bfd_size_type indx;
360
361       /* XXX: The ABI draft says the linker must turn hidden and
362          internal symbols into STB_LOCAL symbols when producing the
363          DSO. However, if ld.so honors st_other in the dynamic table,
364          this would not be necessary.  */
365       switch (ELF_ST_VISIBILITY (h->other))
366         {
367         case STV_INTERNAL:
368         case STV_HIDDEN:
369           if (h->root.type != bfd_link_hash_undefined
370               && h->root.type != bfd_link_hash_undefweak)
371             {
372               h->elf_link_hash_flags |= ELF_LINK_FORCED_LOCAL;
373               return TRUE;
374             }
375
376         default:
377           break;
378         }
379
380       h->dynindx = elf_hash_table (info)->dynsymcount;
381       ++elf_hash_table (info)->dynsymcount;
382
383       dynstr = elf_hash_table (info)->dynstr;
384       if (dynstr == NULL)
385         {
386           /* Create a strtab to hold the dynamic symbol names.  */
387           elf_hash_table (info)->dynstr = dynstr = _bfd_elf_strtab_init ();
388           if (dynstr == NULL)
389             return FALSE;
390         }
391
392       /* We don't put any version information in the dynamic string
393          table.  */
394       name = h->root.root.string;
395       p = strchr (name, ELF_VER_CHR);
396       if (p != NULL)
397         /* We know that the p points into writable memory.  In fact,
398            there are only a few symbols that have read-only names, being
399            those like _GLOBAL_OFFSET_TABLE_ that are created specially
400            by the backends.  Most symbols will have names pointing into
401            an ELF string table read from a file, or to objalloc memory.  */
402         *p = 0;
403
404       indx = _bfd_elf_strtab_add (dynstr, name, p != NULL);
405
406       if (p != NULL)
407         *p = ELF_VER_CHR;
408
409       if (indx == (bfd_size_type) -1)
410         return FALSE;
411       h->dynstr_index = indx;
412     }
413
414   return TRUE;
415 }
416 \f
417 /* Record an assignment to a symbol made by a linker script.  We need
418    this in case some dynamic object refers to this symbol.  */
419
420 bfd_boolean
421 bfd_elf_record_link_assignment (bfd *output_bfd ATTRIBUTE_UNUSED,
422                                 struct bfd_link_info *info,
423                                 const char *name,
424                                 bfd_boolean provide)
425 {
426   struct elf_link_hash_entry *h;
427
428   if (!is_elf_hash_table (info->hash))
429     return TRUE;
430
431   h = elf_link_hash_lookup (elf_hash_table (info), name, TRUE, TRUE, FALSE);
432   if (h == NULL)
433     return FALSE;
434
435   /* Since we're defining the symbol, don't let it seem to have not
436      been defined.  record_dynamic_symbol and size_dynamic_sections
437      may depend on this.  */
438   if (h->root.type == bfd_link_hash_undefweak
439       || h->root.type == bfd_link_hash_undefined)
440     h->root.type = bfd_link_hash_new;
441
442   if (h->root.type == bfd_link_hash_new)
443     h->elf_link_hash_flags &= ~ELF_LINK_NON_ELF;
444
445   /* If this symbol is being provided by the linker script, and it is
446      currently defined by a dynamic object, but not by a regular
447      object, then mark it as undefined so that the generic linker will
448      force the correct value.  */
449   if (provide
450       && (h->elf_link_hash_flags & ELF_LINK_HASH_DEF_DYNAMIC) != 0
451       && (h->elf_link_hash_flags & ELF_LINK_HASH_DEF_REGULAR) == 0)
452     h->root.type = bfd_link_hash_undefined;
453
454   /* If this symbol is not being provided by the linker script, and it is
455      currently defined by a dynamic object, but not by a regular object,
456      then clear out any version information because the symbol will not be
457      associated with the dynamic object any more.  */
458   if (!provide
459       && (h->elf_link_hash_flags & ELF_LINK_HASH_DEF_DYNAMIC) != 0
460       && (h->elf_link_hash_flags & ELF_LINK_HASH_DEF_REGULAR) == 0)
461     h->verinfo.verdef = NULL;
462
463   h->elf_link_hash_flags |= ELF_LINK_HASH_DEF_REGULAR;
464
465   if (((h->elf_link_hash_flags & (ELF_LINK_HASH_DEF_DYNAMIC
466                                   | ELF_LINK_HASH_REF_DYNAMIC)) != 0
467        || info->shared)
468       && h->dynindx == -1)
469     {
470       if (! bfd_elf_link_record_dynamic_symbol (info, h))
471         return FALSE;
472
473       /* If this is a weak defined symbol, and we know a corresponding
474          real symbol from the same dynamic object, make sure the real
475          symbol is also made into a dynamic symbol.  */
476       if (h->weakdef != NULL
477           && h->weakdef->dynindx == -1)
478         {
479           if (! bfd_elf_link_record_dynamic_symbol (info, h->weakdef))
480             return FALSE;
481         }
482     }
483
484   return TRUE;
485 }
486
487 /* Record a new local dynamic symbol.  Returns 0 on failure, 1 on
488    success, and 2 on a failure caused by attempting to record a symbol
489    in a discarded section, eg. a discarded link-once section symbol.  */
490
491 int
492 bfd_elf_link_record_local_dynamic_symbol (struct bfd_link_info *info,
493                                           bfd *input_bfd,
494                                           long input_indx)
495 {
496   bfd_size_type amt;
497   struct elf_link_local_dynamic_entry *entry;
498   struct elf_link_hash_table *eht;
499   struct elf_strtab_hash *dynstr;
500   unsigned long dynstr_index;
501   char *name;
502   Elf_External_Sym_Shndx eshndx;
503   char esym[sizeof (Elf64_External_Sym)];
504
505   if (! is_elf_hash_table (info->hash))
506     return 0;
507
508   /* See if the entry exists already.  */
509   for (entry = elf_hash_table (info)->dynlocal; entry ; entry = entry->next)
510     if (entry->input_bfd == input_bfd && entry->input_indx == input_indx)
511       return 1;
512
513   amt = sizeof (*entry);
514   entry = bfd_alloc (input_bfd, amt);
515   if (entry == NULL)
516     return 0;
517
518   /* Go find the symbol, so that we can find it's name.  */
519   if (!bfd_elf_get_elf_syms (input_bfd, &elf_tdata (input_bfd)->symtab_hdr,
520                              1, input_indx, &entry->isym, esym, &eshndx))
521     {
522       bfd_release (input_bfd, entry);
523       return 0;
524     }
525
526   if (entry->isym.st_shndx != SHN_UNDEF
527       && (entry->isym.st_shndx < SHN_LORESERVE
528           || entry->isym.st_shndx > SHN_HIRESERVE))
529     {
530       asection *s;
531
532       s = bfd_section_from_elf_index (input_bfd, entry->isym.st_shndx);
533       if (s == NULL || bfd_is_abs_section (s->output_section))
534         {
535           /* We can still bfd_release here as nothing has done another
536              bfd_alloc.  We can't do this later in this function.  */
537           bfd_release (input_bfd, entry);
538           return 2;
539         }
540     }
541
542   name = (bfd_elf_string_from_elf_section
543           (input_bfd, elf_tdata (input_bfd)->symtab_hdr.sh_link,
544            entry->isym.st_name));
545
546   dynstr = elf_hash_table (info)->dynstr;
547   if (dynstr == NULL)
548     {
549       /* Create a strtab to hold the dynamic symbol names.  */
550       elf_hash_table (info)->dynstr = dynstr = _bfd_elf_strtab_init ();
551       if (dynstr == NULL)
552         return 0;
553     }
554
555   dynstr_index = _bfd_elf_strtab_add (dynstr, name, FALSE);
556   if (dynstr_index == (unsigned long) -1)
557     return 0;
558   entry->isym.st_name = dynstr_index;
559
560   eht = elf_hash_table (info);
561
562   entry->next = eht->dynlocal;
563   eht->dynlocal = entry;
564   entry->input_bfd = input_bfd;
565   entry->input_indx = input_indx;
566   eht->dynsymcount++;
567
568   /* Whatever binding the symbol had before, it's now local.  */
569   entry->isym.st_info
570     = ELF_ST_INFO (STB_LOCAL, ELF_ST_TYPE (entry->isym.st_info));
571
572   /* The dynindx will be set at the end of size_dynamic_sections.  */
573
574   return 1;
575 }
576
577 /* Return the dynindex of a local dynamic symbol.  */
578
579 long
580 _bfd_elf_link_lookup_local_dynindx (struct bfd_link_info *info,
581                                     bfd *input_bfd,
582                                     long input_indx)
583 {
584   struct elf_link_local_dynamic_entry *e;
585
586   for (e = elf_hash_table (info)->dynlocal; e ; e = e->next)
587     if (e->input_bfd == input_bfd && e->input_indx == input_indx)
588       return e->dynindx;
589   return -1;
590 }
591
592 /* This function is used to renumber the dynamic symbols, if some of
593    them are removed because they are marked as local.  This is called
594    via elf_link_hash_traverse.  */
595
596 static bfd_boolean
597 elf_link_renumber_hash_table_dynsyms (struct elf_link_hash_entry *h,
598                                       void *data)
599 {
600   size_t *count = data;
601
602   if (h->root.type == bfd_link_hash_warning)
603     h = (struct elf_link_hash_entry *) h->root.u.i.link;
604
605   if (h->dynindx != -1)
606     h->dynindx = ++(*count);
607
608   return TRUE;
609 }
610
611 /* Return true if the dynamic symbol for a given section should be
612    omitted when creating a shared library.  */
613 bfd_boolean
614 _bfd_elf_link_omit_section_dynsym (bfd *output_bfd ATTRIBUTE_UNUSED,
615                                    struct bfd_link_info *info,
616                                    asection *p)
617 {
618   switch (elf_section_data (p)->this_hdr.sh_type)
619     {
620     case SHT_PROGBITS:
621     case SHT_NOBITS:
622       /* If sh_type is yet undecided, assume it could be
623          SHT_PROGBITS/SHT_NOBITS.  */
624     case SHT_NULL:
625       if (strcmp (p->name, ".got") == 0
626           || strcmp (p->name, ".got.plt") == 0
627           || strcmp (p->name, ".plt") == 0)
628         {
629           asection *ip;
630           bfd *dynobj = elf_hash_table (info)->dynobj;
631
632           if (dynobj != NULL
633               && (ip = bfd_get_section_by_name (dynobj, p->name))
634               != NULL
635               && (ip->flags & SEC_LINKER_CREATED)
636               && ip->output_section == p)
637             return TRUE;
638         }
639       return FALSE;
640
641       /* There shouldn't be section relative relocations
642          against any other section.  */
643     default:
644       return TRUE;
645     }
646 }
647
648 /* Assign dynsym indices.  In a shared library we generate a section
649    symbol for each output section, which come first.  Next come all of
650    the back-end allocated local dynamic syms, followed by the rest of
651    the global symbols.  */
652
653 unsigned long
654 _bfd_elf_link_renumber_dynsyms (bfd *output_bfd, struct bfd_link_info *info)
655 {
656   unsigned long dynsymcount = 0;
657
658   if (info->shared)
659     {
660       const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
661       asection *p;
662       for (p = output_bfd->sections; p ; p = p->next)
663         if ((p->flags & SEC_EXCLUDE) == 0
664             && (p->flags & SEC_ALLOC) != 0
665             && !(*bed->elf_backend_omit_section_dynsym) (output_bfd, info, p))
666           elf_section_data (p)->dynindx = ++dynsymcount;
667     }
668
669   if (elf_hash_table (info)->dynlocal)
670     {
671       struct elf_link_local_dynamic_entry *p;
672       for (p = elf_hash_table (info)->dynlocal; p ; p = p->next)
673         p->dynindx = ++dynsymcount;
674     }
675
676   elf_link_hash_traverse (elf_hash_table (info),
677                           elf_link_renumber_hash_table_dynsyms,
678                           &dynsymcount);
679
680   /* There is an unused NULL entry at the head of the table which
681      we must account for in our count.  Unless there weren't any
682      symbols, which means we'll have no table at all.  */
683   if (dynsymcount != 0)
684     ++dynsymcount;
685
686   return elf_hash_table (info)->dynsymcount = dynsymcount;
687 }
688
689 /* This function is called when we want to define a new symbol.  It
690    handles the various cases which arise when we find a definition in
691    a dynamic object, or when there is already a definition in a
692    dynamic object.  The new symbol is described by NAME, SYM, PSEC,
693    and PVALUE.  We set SYM_HASH to the hash table entry.  We set
694    OVERRIDE if the old symbol is overriding a new definition.  We set
695    TYPE_CHANGE_OK if it is OK for the type to change.  We set
696    SIZE_CHANGE_OK if it is OK for the size to change.  By OK to
697    change, we mean that we shouldn't warn if the type or size does
698    change.  */
699
700 bfd_boolean
701 _bfd_elf_merge_symbol (bfd *abfd,
702                        struct bfd_link_info *info,
703                        const char *name,
704                        Elf_Internal_Sym *sym,
705                        asection **psec,
706                        bfd_vma *pvalue,
707                        struct elf_link_hash_entry **sym_hash,
708                        bfd_boolean *skip,
709                        bfd_boolean *override,
710                        bfd_boolean *type_change_ok,
711                        bfd_boolean *size_change_ok)
712 {
713   asection *sec;
714   struct elf_link_hash_entry *h;
715   struct elf_link_hash_entry *flip;
716   int bind;
717   bfd *oldbfd;
718   bfd_boolean newdyn, olddyn, olddef, newdef, newdyncommon, olddyncommon;
719   bfd_boolean newweak, oldweak;
720
721   *skip = FALSE;
722   *override = FALSE;
723
724   sec = *psec;
725   bind = ELF_ST_BIND (sym->st_info);
726
727   if (! bfd_is_und_section (sec))
728     h = elf_link_hash_lookup (elf_hash_table (info), name, TRUE, FALSE, FALSE);
729   else
730     h = ((struct elf_link_hash_entry *)
731          bfd_wrapped_link_hash_lookup (abfd, info, name, TRUE, FALSE, FALSE));
732   if (h == NULL)
733     return FALSE;
734   *sym_hash = h;
735
736   /* This code is for coping with dynamic objects, and is only useful
737      if we are doing an ELF link.  */
738   if (info->hash->creator != abfd->xvec)
739     return TRUE;
740
741   /* For merging, we only care about real symbols.  */
742
743   while (h->root.type == bfd_link_hash_indirect
744          || h->root.type == bfd_link_hash_warning)
745     h = (struct elf_link_hash_entry *) h->root.u.i.link;
746
747   /* If we just created the symbol, mark it as being an ELF symbol.
748      Other than that, there is nothing to do--there is no merge issue
749      with a newly defined symbol--so we just return.  */
750
751   if (h->root.type == bfd_link_hash_new)
752     {
753       h->elf_link_hash_flags &=~ ELF_LINK_NON_ELF;
754       return TRUE;
755     }
756
757   /* OLDBFD is a BFD associated with the existing symbol.  */
758
759   switch (h->root.type)
760     {
761     default:
762       oldbfd = NULL;
763       break;
764
765     case bfd_link_hash_undefined:
766     case bfd_link_hash_undefweak:
767       oldbfd = h->root.u.undef.abfd;
768       break;
769
770     case bfd_link_hash_defined:
771     case bfd_link_hash_defweak:
772       oldbfd = h->root.u.def.section->owner;
773       break;
774
775     case bfd_link_hash_common:
776       oldbfd = h->root.u.c.p->section->owner;
777       break;
778     }
779
780   /* In cases involving weak versioned symbols, we may wind up trying
781      to merge a symbol with itself.  Catch that here, to avoid the
782      confusion that results if we try to override a symbol with
783      itself.  The additional tests catch cases like
784      _GLOBAL_OFFSET_TABLE_, which are regular symbols defined in a
785      dynamic object, which we do want to handle here.  */
786   if (abfd == oldbfd
787       && ((abfd->flags & DYNAMIC) == 0
788           || (h->elf_link_hash_flags & ELF_LINK_HASH_DEF_REGULAR) == 0))
789     return TRUE;
790
791   /* NEWDYN and OLDDYN indicate whether the new or old symbol,
792      respectively, is from a dynamic object.  */
793
794   if ((abfd->flags & DYNAMIC) != 0)
795     newdyn = TRUE;
796   else
797     newdyn = FALSE;
798
799   if (oldbfd != NULL)
800     olddyn = (oldbfd->flags & DYNAMIC) != 0;
801   else
802     {
803       asection *hsec;
804
805       /* This code handles the special SHN_MIPS_{TEXT,DATA} section
806          indices used by MIPS ELF.  */
807       switch (h->root.type)
808         {
809         default:
810           hsec = NULL;
811           break;
812
813         case bfd_link_hash_defined:
814         case bfd_link_hash_defweak:
815           hsec = h->root.u.def.section;
816           break;
817
818         case bfd_link_hash_common:
819           hsec = h->root.u.c.p->section;
820           break;
821         }
822
823       if (hsec == NULL)
824         olddyn = FALSE;
825       else
826         olddyn = (hsec->symbol->flags & BSF_DYNAMIC) != 0;
827     }
828
829   /* NEWDEF and OLDDEF indicate whether the new or old symbol,
830      respectively, appear to be a definition rather than reference.  */
831
832   if (bfd_is_und_section (sec) || bfd_is_com_section (sec))
833     newdef = FALSE;
834   else
835     newdef = TRUE;
836
837   if (h->root.type == bfd_link_hash_undefined
838       || h->root.type == bfd_link_hash_undefweak
839       || h->root.type == bfd_link_hash_common)
840     olddef = FALSE;
841   else
842     olddef = TRUE;
843
844   /* We need to remember if a symbol has a definition in a dynamic
845      object or is weak in all dynamic objects. Internal and hidden
846      visibility will make it unavailable to dynamic objects.  */
847   if (newdyn && (h->elf_link_hash_flags & ELF_LINK_DYNAMIC_DEF) == 0)
848     {
849       if (!bfd_is_und_section (sec))
850         h->elf_link_hash_flags |= ELF_LINK_DYNAMIC_DEF;
851       else
852         {
853           /* Check if this symbol is weak in all dynamic objects. If it
854              is the first time we see it in a dynamic object, we mark
855              if it is weak. Otherwise, we clear it.  */
856           if ((h->elf_link_hash_flags & ELF_LINK_HASH_REF_DYNAMIC) == 0)
857             {
858               if (bind == STB_WEAK)
859                 h->elf_link_hash_flags |= ELF_LINK_DYNAMIC_WEAK;
860             }
861           else if (bind != STB_WEAK)
862             h->elf_link_hash_flags &= ~ELF_LINK_DYNAMIC_WEAK;
863         }
864     }
865
866   /* If the old symbol has non-default visibility, we ignore the new
867      definition from a dynamic object.  */
868   if (newdyn
869       && ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
870       && !bfd_is_und_section (sec))
871     {
872       *skip = TRUE;
873       /* Make sure this symbol is dynamic.  */
874       h->elf_link_hash_flags |= ELF_LINK_HASH_REF_DYNAMIC;
875       /* A protected symbol has external availability. Make sure it is
876          recorded as dynamic.
877
878          FIXME: Should we check type and size for protected symbol?  */
879       if (ELF_ST_VISIBILITY (h->other) == STV_PROTECTED)
880         return bfd_elf_link_record_dynamic_symbol (info, h);
881       else
882         return TRUE;
883     }
884   else if (!newdyn
885            && ELF_ST_VISIBILITY (sym->st_other) != STV_DEFAULT
886            && (h->elf_link_hash_flags & ELF_LINK_HASH_DEF_DYNAMIC) != 0)
887     {
888       /* If the new symbol with non-default visibility comes from a
889          relocatable file and the old definition comes from a dynamic
890          object, we remove the old definition.  */
891       if ((*sym_hash)->root.type == bfd_link_hash_indirect)
892         h = *sym_hash;
893
894       if ((h->root.und_next || info->hash->undefs_tail == &h->root)
895           && bfd_is_und_section (sec))
896         {
897           /* If the new symbol is undefined and the old symbol was
898              also undefined before, we need to make sure
899              _bfd_generic_link_add_one_symbol doesn't mess
900              up the linker hash table undefs list. Since the old
901              definition came from a dynamic object, it is still on the
902              undefs list.  */
903           h->root.type = bfd_link_hash_undefined;
904           /* FIXME: What if the new symbol is weak undefined?  */
905           h->root.u.undef.abfd = abfd;
906         }
907       else
908         {
909           h->root.type = bfd_link_hash_new;
910           h->root.u.undef.abfd = NULL;
911         }
912
913       if (h->elf_link_hash_flags & ELF_LINK_HASH_DEF_DYNAMIC)
914         {
915           h->elf_link_hash_flags &= ~ELF_LINK_HASH_DEF_DYNAMIC;
916           h->elf_link_hash_flags |= (ELF_LINK_HASH_REF_DYNAMIC
917                                      | ELF_LINK_DYNAMIC_DEF);
918         }
919       /* FIXME: Should we check type and size for protected symbol?  */
920       h->size = 0;
921       h->type = 0;
922       return TRUE;
923     }
924
925   /* Differentiate strong and weak symbols.  */
926   newweak = bind == STB_WEAK;
927   oldweak = (h->root.type == bfd_link_hash_defweak
928              || h->root.type == bfd_link_hash_undefweak);
929
930   /* If a new weak symbol definition comes from a regular file and the
931      old symbol comes from a dynamic library, we treat the new one as
932      strong.  Similarly, an old weak symbol definition from a regular
933      file is treated as strong when the new symbol comes from a dynamic
934      library.  Further, an old weak symbol from a dynamic library is
935      treated as strong if the new symbol is from a dynamic library.
936      This reflects the way glibc's ld.so works.
937
938      Do this before setting *type_change_ok or *size_change_ok so that
939      we warn properly when dynamic library symbols are overridden.  */
940
941   if (newdef && !newdyn && olddyn)
942     newweak = FALSE;
943   if (olddef && newdyn)
944     oldweak = FALSE;
945
946   /* It's OK to change the type if either the existing symbol or the
947      new symbol is weak.  A type change is also OK if the old symbol
948      is undefined and the new symbol is defined.  */
949
950   if (oldweak
951       || newweak
952       || (newdef
953           && h->root.type == bfd_link_hash_undefined))
954     *type_change_ok = TRUE;
955
956   /* It's OK to change the size if either the existing symbol or the
957      new symbol is weak, or if the old symbol is undefined.  */
958
959   if (*type_change_ok
960       || h->root.type == bfd_link_hash_undefined)
961     *size_change_ok = TRUE;
962
963   /* NEWDYNCOMMON and OLDDYNCOMMON indicate whether the new or old
964      symbol, respectively, appears to be a common symbol in a dynamic
965      object.  If a symbol appears in an uninitialized section, and is
966      not weak, and is not a function, then it may be a common symbol
967      which was resolved when the dynamic object was created.  We want
968      to treat such symbols specially, because they raise special
969      considerations when setting the symbol size: if the symbol
970      appears as a common symbol in a regular object, and the size in
971      the regular object is larger, we must make sure that we use the
972      larger size.  This problematic case can always be avoided in C,
973      but it must be handled correctly when using Fortran shared
974      libraries.
975
976      Note that if NEWDYNCOMMON is set, NEWDEF will be set, and
977      likewise for OLDDYNCOMMON and OLDDEF.
978
979      Note that this test is just a heuristic, and that it is quite
980      possible to have an uninitialized symbol in a shared object which
981      is really a definition, rather than a common symbol.  This could
982      lead to some minor confusion when the symbol really is a common
983      symbol in some regular object.  However, I think it will be
984      harmless.  */
985
986   if (newdyn
987       && newdef
988       && !newweak
989       && (sec->flags & SEC_ALLOC) != 0
990       && (sec->flags & SEC_LOAD) == 0
991       && sym->st_size > 0
992       && ELF_ST_TYPE (sym->st_info) != STT_FUNC)
993     newdyncommon = TRUE;
994   else
995     newdyncommon = FALSE;
996
997   if (olddyn
998       && olddef
999       && h->root.type == bfd_link_hash_defined
1000       && (h->elf_link_hash_flags & ELF_LINK_HASH_DEF_DYNAMIC) != 0
1001       && (h->root.u.def.section->flags & SEC_ALLOC) != 0
1002       && (h->root.u.def.section->flags & SEC_LOAD) == 0
1003       && h->size > 0
1004       && h->type != STT_FUNC)
1005     olddyncommon = TRUE;
1006   else
1007     olddyncommon = FALSE;
1008
1009   /* If both the old and the new symbols look like common symbols in a
1010      dynamic object, set the size of the symbol to the larger of the
1011      two.  */
1012
1013   if (olddyncommon
1014       && newdyncommon
1015       && sym->st_size != h->size)
1016     {
1017       /* Since we think we have two common symbols, issue a multiple
1018          common warning if desired.  Note that we only warn if the
1019          size is different.  If the size is the same, we simply let
1020          the old symbol override the new one as normally happens with
1021          symbols defined in dynamic objects.  */
1022
1023       if (! ((*info->callbacks->multiple_common)
1024              (info, h->root.root.string, oldbfd, bfd_link_hash_common,
1025               h->size, abfd, bfd_link_hash_common, sym->st_size)))
1026         return FALSE;
1027
1028       if (sym->st_size > h->size)
1029         h->size = sym->st_size;
1030
1031       *size_change_ok = TRUE;
1032     }
1033
1034   /* If we are looking at a dynamic object, and we have found a
1035      definition, we need to see if the symbol was already defined by
1036      some other object.  If so, we want to use the existing
1037      definition, and we do not want to report a multiple symbol
1038      definition error; we do this by clobbering *PSEC to be
1039      bfd_und_section_ptr.
1040
1041      We treat a common symbol as a definition if the symbol in the
1042      shared library is a function, since common symbols always
1043      represent variables; this can cause confusion in principle, but
1044      any such confusion would seem to indicate an erroneous program or
1045      shared library.  We also permit a common symbol in a regular
1046      object to override a weak symbol in a shared object.  */
1047
1048   if (newdyn
1049       && newdef
1050       && (olddef
1051           || (h->root.type == bfd_link_hash_common
1052               && (newweak
1053                   || ELF_ST_TYPE (sym->st_info) == STT_FUNC))))
1054     {
1055       *override = TRUE;
1056       newdef = FALSE;
1057       newdyncommon = FALSE;
1058
1059       *psec = sec = bfd_und_section_ptr;
1060       *size_change_ok = TRUE;
1061
1062       /* If we get here when the old symbol is a common symbol, then
1063          we are explicitly letting it override a weak symbol or
1064          function in a dynamic object, and we don't want to warn about
1065          a type change.  If the old symbol is a defined symbol, a type
1066          change warning may still be appropriate.  */
1067
1068       if (h->root.type == bfd_link_hash_common)
1069         *type_change_ok = TRUE;
1070     }
1071
1072   /* Handle the special case of an old common symbol merging with a
1073      new symbol which looks like a common symbol in a shared object.
1074      We change *PSEC and *PVALUE to make the new symbol look like a
1075      common symbol, and let _bfd_generic_link_add_one_symbol will do
1076      the right thing.  */
1077
1078   if (newdyncommon
1079       && h->root.type == bfd_link_hash_common)
1080     {
1081       *override = TRUE;
1082       newdef = FALSE;
1083       newdyncommon = FALSE;
1084       *pvalue = sym->st_size;
1085       *psec = sec = bfd_com_section_ptr;
1086       *size_change_ok = TRUE;
1087     }
1088
1089   /* If the old symbol is from a dynamic object, and the new symbol is
1090      a definition which is not from a dynamic object, then the new
1091      symbol overrides the old symbol.  Symbols from regular files
1092      always take precedence over symbols from dynamic objects, even if
1093      they are defined after the dynamic object in the link.
1094
1095      As above, we again permit a common symbol in a regular object to
1096      override a definition in a shared object if the shared object
1097      symbol is a function or is weak.  */
1098
1099   flip = NULL;
1100   if (! newdyn
1101       && (newdef
1102           || (bfd_is_com_section (sec)
1103               && (oldweak
1104                   || h->type == STT_FUNC)))
1105       && olddyn
1106       && olddef
1107       && (h->elf_link_hash_flags & ELF_LINK_HASH_DEF_DYNAMIC) != 0)
1108     {
1109       /* Change the hash table entry to undefined, and let
1110          _bfd_generic_link_add_one_symbol do the right thing with the
1111          new definition.  */
1112
1113       h->root.type = bfd_link_hash_undefined;
1114       h->root.u.undef.abfd = h->root.u.def.section->owner;
1115       *size_change_ok = TRUE;
1116
1117       olddef = FALSE;
1118       olddyncommon = FALSE;
1119
1120       /* We again permit a type change when a common symbol may be
1121          overriding a function.  */
1122
1123       if (bfd_is_com_section (sec))
1124         *type_change_ok = TRUE;
1125
1126       if ((*sym_hash)->root.type == bfd_link_hash_indirect)
1127         flip = *sym_hash;
1128       else
1129         /* This union may have been set to be non-NULL when this symbol
1130            was seen in a dynamic object.  We must force the union to be
1131            NULL, so that it is correct for a regular symbol.  */
1132         h->verinfo.vertree = NULL;
1133     }
1134
1135   /* Handle the special case of a new common symbol merging with an
1136      old symbol that looks like it might be a common symbol defined in
1137      a shared object.  Note that we have already handled the case in
1138      which a new common symbol should simply override the definition
1139      in the shared library.  */
1140
1141   if (! newdyn
1142       && bfd_is_com_section (sec)
1143       && olddyncommon)
1144     {
1145       /* It would be best if we could set the hash table entry to a
1146          common symbol, but we don't know what to use for the section
1147          or the alignment.  */
1148       if (! ((*info->callbacks->multiple_common)
1149              (info, h->root.root.string, oldbfd, bfd_link_hash_common,
1150               h->size, abfd, bfd_link_hash_common, sym->st_size)))
1151         return FALSE;
1152
1153       /* If the presumed common symbol in the dynamic object is
1154          larger, pretend that the new symbol has its size.  */
1155
1156       if (h->size > *pvalue)
1157         *pvalue = h->size;
1158
1159       /* FIXME: We no longer know the alignment required by the symbol
1160          in the dynamic object, so we just wind up using the one from
1161          the regular object.  */
1162
1163       olddef = FALSE;
1164       olddyncommon = FALSE;
1165
1166       h->root.type = bfd_link_hash_undefined;
1167       h->root.u.undef.abfd = h->root.u.def.section->owner;
1168
1169       *size_change_ok = TRUE;
1170       *type_change_ok = TRUE;
1171
1172       if ((*sym_hash)->root.type == bfd_link_hash_indirect)
1173         flip = *sym_hash;
1174       else
1175         h->verinfo.vertree = NULL;
1176     }
1177
1178   if (flip != NULL)
1179     {
1180       /* Handle the case where we had a versioned symbol in a dynamic
1181          library and now find a definition in a normal object.  In this
1182          case, we make the versioned symbol point to the normal one.  */
1183       const struct elf_backend_data *bed = get_elf_backend_data (abfd);
1184       flip->root.type = h->root.type;
1185       h->root.type = bfd_link_hash_indirect;
1186       h->root.u.i.link = (struct bfd_link_hash_entry *) flip;
1187       (*bed->elf_backend_copy_indirect_symbol) (bed, flip, h);
1188       flip->root.u.undef.abfd = h->root.u.undef.abfd;
1189       if (h->elf_link_hash_flags & ELF_LINK_HASH_DEF_DYNAMIC)
1190         {
1191           h->elf_link_hash_flags &= ~ELF_LINK_HASH_DEF_DYNAMIC;
1192           flip->elf_link_hash_flags |= ELF_LINK_HASH_REF_DYNAMIC;
1193         }
1194     }
1195
1196   return TRUE;
1197 }
1198
1199 /* This function is called to create an indirect symbol from the
1200    default for the symbol with the default version if needed. The
1201    symbol is described by H, NAME, SYM, PSEC, VALUE, and OVERRIDE.  We
1202    set DYNSYM if the new indirect symbol is dynamic.  */
1203
1204 bfd_boolean
1205 _bfd_elf_add_default_symbol (bfd *abfd,
1206                              struct bfd_link_info *info,
1207                              struct elf_link_hash_entry *h,
1208                              const char *name,
1209                              Elf_Internal_Sym *sym,
1210                              asection **psec,
1211                              bfd_vma *value,
1212                              bfd_boolean *dynsym,
1213                              bfd_boolean override)
1214 {
1215   bfd_boolean type_change_ok;
1216   bfd_boolean size_change_ok;
1217   bfd_boolean skip;
1218   char *shortname;
1219   struct elf_link_hash_entry *hi;
1220   struct bfd_link_hash_entry *bh;
1221   const struct elf_backend_data *bed;
1222   bfd_boolean collect;
1223   bfd_boolean dynamic;
1224   char *p;
1225   size_t len, shortlen;
1226   asection *sec;
1227
1228   /* If this symbol has a version, and it is the default version, we
1229      create an indirect symbol from the default name to the fully
1230      decorated name.  This will cause external references which do not
1231      specify a version to be bound to this version of the symbol.  */
1232   p = strchr (name, ELF_VER_CHR);
1233   if (p == NULL || p[1] != ELF_VER_CHR)
1234     return TRUE;
1235
1236   if (override)
1237     {
1238       /* We are overridden by an old definition. We need to check if we
1239          need to create the indirect symbol from the default name.  */
1240       hi = elf_link_hash_lookup (elf_hash_table (info), name, TRUE,
1241                                  FALSE, FALSE);
1242       BFD_ASSERT (hi != NULL);
1243       if (hi == h)
1244         return TRUE;
1245       while (hi->root.type == bfd_link_hash_indirect
1246              || hi->root.type == bfd_link_hash_warning)
1247         {
1248           hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1249           if (hi == h)
1250             return TRUE;
1251         }
1252     }
1253
1254   bed = get_elf_backend_data (abfd);
1255   collect = bed->collect;
1256   dynamic = (abfd->flags & DYNAMIC) != 0;
1257
1258   shortlen = p - name;
1259   shortname = bfd_hash_allocate (&info->hash->table, shortlen + 1);
1260   if (shortname == NULL)
1261     return FALSE;
1262   memcpy (shortname, name, shortlen);
1263   shortname[shortlen] = '\0';
1264
1265   /* We are going to create a new symbol.  Merge it with any existing
1266      symbol with this name.  For the purposes of the merge, act as
1267      though we were defining the symbol we just defined, although we
1268      actually going to define an indirect symbol.  */
1269   type_change_ok = FALSE;
1270   size_change_ok = FALSE;
1271   sec = *psec;
1272   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &sec, value,
1273                               &hi, &skip, &override, &type_change_ok,
1274                               &size_change_ok))
1275     return FALSE;
1276
1277   if (skip)
1278     goto nondefault;
1279
1280   if (! override)
1281     {
1282       bh = &hi->root;
1283       if (! (_bfd_generic_link_add_one_symbol
1284              (info, abfd, shortname, BSF_INDIRECT, bfd_ind_section_ptr,
1285               0, name, FALSE, collect, &bh)))
1286         return FALSE;
1287       hi = (struct elf_link_hash_entry *) bh;
1288     }
1289   else
1290     {
1291       /* In this case the symbol named SHORTNAME is overriding the
1292          indirect symbol we want to add.  We were planning on making
1293          SHORTNAME an indirect symbol referring to NAME.  SHORTNAME
1294          is the name without a version.  NAME is the fully versioned
1295          name, and it is the default version.
1296
1297          Overriding means that we already saw a definition for the
1298          symbol SHORTNAME in a regular object, and it is overriding
1299          the symbol defined in the dynamic object.
1300
1301          When this happens, we actually want to change NAME, the
1302          symbol we just added, to refer to SHORTNAME.  This will cause
1303          references to NAME in the shared object to become references
1304          to SHORTNAME in the regular object.  This is what we expect
1305          when we override a function in a shared object: that the
1306          references in the shared object will be mapped to the
1307          definition in the regular object.  */
1308
1309       while (hi->root.type == bfd_link_hash_indirect
1310              || hi->root.type == bfd_link_hash_warning)
1311         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1312
1313       h->root.type = bfd_link_hash_indirect;
1314       h->root.u.i.link = (struct bfd_link_hash_entry *) hi;
1315       if (h->elf_link_hash_flags & ELF_LINK_HASH_DEF_DYNAMIC)
1316         {
1317           h->elf_link_hash_flags &=~ ELF_LINK_HASH_DEF_DYNAMIC;
1318           hi->elf_link_hash_flags |= ELF_LINK_HASH_REF_DYNAMIC;
1319           if (hi->elf_link_hash_flags
1320               & (ELF_LINK_HASH_REF_REGULAR
1321                  | ELF_LINK_HASH_DEF_REGULAR))
1322             {
1323               if (! bfd_elf_link_record_dynamic_symbol (info, hi))
1324                 return FALSE;
1325             }
1326         }
1327
1328       /* Now set HI to H, so that the following code will set the
1329          other fields correctly.  */
1330       hi = h;
1331     }
1332
1333   /* If there is a duplicate definition somewhere, then HI may not
1334      point to an indirect symbol.  We will have reported an error to
1335      the user in that case.  */
1336
1337   if (hi->root.type == bfd_link_hash_indirect)
1338     {
1339       struct elf_link_hash_entry *ht;
1340
1341       ht = (struct elf_link_hash_entry *) hi->root.u.i.link;
1342       (*bed->elf_backend_copy_indirect_symbol) (bed, ht, hi);
1343
1344       /* See if the new flags lead us to realize that the symbol must
1345          be dynamic.  */
1346       if (! *dynsym)
1347         {
1348           if (! dynamic)
1349             {
1350               if (info->shared
1351                   || ((hi->elf_link_hash_flags
1352                        & ELF_LINK_HASH_REF_DYNAMIC) != 0))
1353                 *dynsym = TRUE;
1354             }
1355           else
1356             {
1357               if ((hi->elf_link_hash_flags
1358                    & ELF_LINK_HASH_REF_REGULAR) != 0)
1359                 *dynsym = TRUE;
1360             }
1361         }
1362     }
1363
1364   /* We also need to define an indirection from the nondefault version
1365      of the symbol.  */
1366
1367 nondefault:
1368   len = strlen (name);
1369   shortname = bfd_hash_allocate (&info->hash->table, len);
1370   if (shortname == NULL)
1371     return FALSE;
1372   memcpy (shortname, name, shortlen);
1373   memcpy (shortname + shortlen, p + 1, len - shortlen);
1374
1375   /* Once again, merge with any existing symbol.  */
1376   type_change_ok = FALSE;
1377   size_change_ok = FALSE;
1378   sec = *psec;
1379   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &sec, value,
1380                               &hi, &skip, &override, &type_change_ok,
1381                               &size_change_ok))
1382     return FALSE;
1383
1384   if (skip)
1385     return TRUE;
1386
1387   if (override)
1388     {
1389       /* Here SHORTNAME is a versioned name, so we don't expect to see
1390          the type of override we do in the case above unless it is
1391          overridden by a versioned definition.  */
1392       if (hi->root.type != bfd_link_hash_defined
1393           && hi->root.type != bfd_link_hash_defweak)
1394         (*_bfd_error_handler)
1395           (_("%B: unexpected redefinition of indirect versioned symbol `%s'"),
1396            abfd, shortname);
1397     }
1398   else
1399     {
1400       bh = &hi->root;
1401       if (! (_bfd_generic_link_add_one_symbol
1402              (info, abfd, shortname, BSF_INDIRECT,
1403               bfd_ind_section_ptr, 0, name, FALSE, collect, &bh)))
1404         return FALSE;
1405       hi = (struct elf_link_hash_entry *) bh;
1406
1407       /* If there is a duplicate definition somewhere, then HI may not
1408          point to an indirect symbol.  We will have reported an error
1409          to the user in that case.  */
1410
1411       if (hi->root.type == bfd_link_hash_indirect)
1412         {
1413           (*bed->elf_backend_copy_indirect_symbol) (bed, h, hi);
1414
1415           /* See if the new flags lead us to realize that the symbol
1416              must be dynamic.  */
1417           if (! *dynsym)
1418             {
1419               if (! dynamic)
1420                 {
1421                   if (info->shared
1422                       || ((hi->elf_link_hash_flags
1423                            & ELF_LINK_HASH_REF_DYNAMIC) != 0))
1424                     *dynsym = TRUE;
1425                 }
1426               else
1427                 {
1428                   if ((hi->elf_link_hash_flags
1429                        & ELF_LINK_HASH_REF_REGULAR) != 0)
1430                     *dynsym = TRUE;
1431                 }
1432             }
1433         }
1434     }
1435
1436   return TRUE;
1437 }
1438 \f
1439 /* This routine is used to export all defined symbols into the dynamic
1440    symbol table.  It is called via elf_link_hash_traverse.  */
1441
1442 bfd_boolean
1443 _bfd_elf_export_symbol (struct elf_link_hash_entry *h, void *data)
1444 {
1445   struct elf_info_failed *eif = data;
1446
1447   /* Ignore indirect symbols.  These are added by the versioning code.  */
1448   if (h->root.type == bfd_link_hash_indirect)
1449     return TRUE;
1450
1451   if (h->root.type == bfd_link_hash_warning)
1452     h = (struct elf_link_hash_entry *) h->root.u.i.link;
1453
1454   if (h->dynindx == -1
1455       && (h->elf_link_hash_flags
1456           & (ELF_LINK_HASH_DEF_REGULAR | ELF_LINK_HASH_REF_REGULAR)) != 0)
1457     {
1458       struct bfd_elf_version_tree *t;
1459       struct bfd_elf_version_expr *d;
1460
1461       for (t = eif->verdefs; t != NULL; t = t->next)
1462         {
1463           if (t->globals.list != NULL)
1464             {
1465               d = (*t->match) (&t->globals, NULL, h->root.root.string);
1466               if (d != NULL)
1467                 goto doit;
1468             }
1469
1470           if (t->locals.list != NULL)
1471             {
1472               d = (*t->match) (&t->locals, NULL, h->root.root.string);
1473               if (d != NULL)
1474                 return TRUE;
1475             }
1476         }
1477
1478       if (!eif->verdefs)
1479         {
1480         doit:
1481           if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
1482             {
1483               eif->failed = TRUE;
1484               return FALSE;
1485             }
1486         }
1487     }
1488
1489   return TRUE;
1490 }
1491 \f
1492 /* Look through the symbols which are defined in other shared
1493    libraries and referenced here.  Update the list of version
1494    dependencies.  This will be put into the .gnu.version_r section.
1495    This function is called via elf_link_hash_traverse.  */
1496
1497 bfd_boolean
1498 _bfd_elf_link_find_version_dependencies (struct elf_link_hash_entry *h,
1499                                          void *data)
1500 {
1501   struct elf_find_verdep_info *rinfo = data;
1502   Elf_Internal_Verneed *t;
1503   Elf_Internal_Vernaux *a;
1504   bfd_size_type amt;
1505
1506   if (h->root.type == bfd_link_hash_warning)
1507     h = (struct elf_link_hash_entry *) h->root.u.i.link;
1508
1509   /* We only care about symbols defined in shared objects with version
1510      information.  */
1511   if ((h->elf_link_hash_flags & ELF_LINK_HASH_DEF_DYNAMIC) == 0
1512       || (h->elf_link_hash_flags & ELF_LINK_HASH_DEF_REGULAR) != 0
1513       || h->dynindx == -1
1514       || h->verinfo.verdef == NULL)
1515     return TRUE;
1516
1517   /* See if we already know about this version.  */
1518   for (t = elf_tdata (rinfo->output_bfd)->verref; t != NULL; t = t->vn_nextref)
1519     {
1520       if (t->vn_bfd != h->verinfo.verdef->vd_bfd)
1521         continue;
1522
1523       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
1524         if (a->vna_nodename == h->verinfo.verdef->vd_nodename)
1525           return TRUE;
1526
1527       break;
1528     }
1529
1530   /* This is a new version.  Add it to tree we are building.  */
1531
1532   if (t == NULL)
1533     {
1534       amt = sizeof *t;
1535       t = bfd_zalloc (rinfo->output_bfd, amt);
1536       if (t == NULL)
1537         {
1538           rinfo->failed = TRUE;
1539           return FALSE;
1540         }
1541
1542       t->vn_bfd = h->verinfo.verdef->vd_bfd;
1543       t->vn_nextref = elf_tdata (rinfo->output_bfd)->verref;
1544       elf_tdata (rinfo->output_bfd)->verref = t;
1545     }
1546
1547   amt = sizeof *a;
1548   a = bfd_zalloc (rinfo->output_bfd, amt);
1549
1550   /* Note that we are copying a string pointer here, and testing it
1551      above.  If bfd_elf_string_from_elf_section is ever changed to
1552      discard the string data when low in memory, this will have to be
1553      fixed.  */
1554   a->vna_nodename = h->verinfo.verdef->vd_nodename;
1555
1556   a->vna_flags = h->verinfo.verdef->vd_flags;
1557   a->vna_nextptr = t->vn_auxptr;
1558
1559   h->verinfo.verdef->vd_exp_refno = rinfo->vers;
1560   ++rinfo->vers;
1561
1562   a->vna_other = h->verinfo.verdef->vd_exp_refno + 1;
1563
1564   t->vn_auxptr = a;
1565
1566   return TRUE;
1567 }
1568
1569 /* Figure out appropriate versions for all the symbols.  We may not
1570    have the version number script until we have read all of the input
1571    files, so until that point we don't know which symbols should be
1572    local.  This function is called via elf_link_hash_traverse.  */
1573
1574 bfd_boolean
1575 _bfd_elf_link_assign_sym_version (struct elf_link_hash_entry *h, void *data)
1576 {
1577   struct elf_assign_sym_version_info *sinfo;
1578   struct bfd_link_info *info;
1579   const struct elf_backend_data *bed;
1580   struct elf_info_failed eif;
1581   char *p;
1582   bfd_size_type amt;
1583
1584   sinfo = data;
1585   info = sinfo->info;
1586
1587   if (h->root.type == bfd_link_hash_warning)
1588     h = (struct elf_link_hash_entry *) h->root.u.i.link;
1589
1590   /* Fix the symbol flags.  */
1591   eif.failed = FALSE;
1592   eif.info = info;
1593   if (! _bfd_elf_fix_symbol_flags (h, &eif))
1594     {
1595       if (eif.failed)
1596         sinfo->failed = TRUE;
1597       return FALSE;
1598     }
1599
1600   /* We only need version numbers for symbols defined in regular
1601      objects.  */
1602   if ((h->elf_link_hash_flags & ELF_LINK_HASH_DEF_REGULAR) == 0)
1603     return TRUE;
1604
1605   bed = get_elf_backend_data (sinfo->output_bfd);
1606   p = strchr (h->root.root.string, ELF_VER_CHR);
1607   if (p != NULL && h->verinfo.vertree == NULL)
1608     {
1609       struct bfd_elf_version_tree *t;
1610       bfd_boolean hidden;
1611
1612       hidden = TRUE;
1613
1614       /* There are two consecutive ELF_VER_CHR characters if this is
1615          not a hidden symbol.  */
1616       ++p;
1617       if (*p == ELF_VER_CHR)
1618         {
1619           hidden = FALSE;
1620           ++p;
1621         }
1622
1623       /* If there is no version string, we can just return out.  */
1624       if (*p == '\0')
1625         {
1626           if (hidden)
1627             h->elf_link_hash_flags |= ELF_LINK_HIDDEN;
1628           return TRUE;
1629         }
1630
1631       /* Look for the version.  If we find it, it is no longer weak.  */
1632       for (t = sinfo->verdefs; t != NULL; t = t->next)
1633         {
1634           if (strcmp (t->name, p) == 0)
1635             {
1636               size_t len;
1637               char *alc;
1638               struct bfd_elf_version_expr *d;
1639
1640               len = p - h->root.root.string;
1641               alc = bfd_malloc (len);
1642               if (alc == NULL)
1643                 return FALSE;
1644               memcpy (alc, h->root.root.string, len - 1);
1645               alc[len - 1] = '\0';
1646               if (alc[len - 2] == ELF_VER_CHR)
1647                 alc[len - 2] = '\0';
1648
1649               h->verinfo.vertree = t;
1650               t->used = TRUE;
1651               d = NULL;
1652
1653               if (t->globals.list != NULL)
1654                 d = (*t->match) (&t->globals, NULL, alc);
1655
1656               /* See if there is anything to force this symbol to
1657                  local scope.  */
1658               if (d == NULL && t->locals.list != NULL)
1659                 {
1660                   d = (*t->match) (&t->locals, NULL, alc);
1661                   if (d != NULL
1662                       && h->dynindx != -1
1663                       && info->shared
1664                       && ! info->export_dynamic)
1665                     (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1666                 }
1667
1668               free (alc);
1669               break;
1670             }
1671         }
1672
1673       /* If we are building an application, we need to create a
1674          version node for this version.  */
1675       if (t == NULL && info->executable)
1676         {
1677           struct bfd_elf_version_tree **pp;
1678           int version_index;
1679
1680           /* If we aren't going to export this symbol, we don't need
1681              to worry about it.  */
1682           if (h->dynindx == -1)
1683             return TRUE;
1684
1685           amt = sizeof *t;
1686           t = bfd_zalloc (sinfo->output_bfd, amt);
1687           if (t == NULL)
1688             {
1689               sinfo->failed = TRUE;
1690               return FALSE;
1691             }
1692
1693           t->name = p;
1694           t->name_indx = (unsigned int) -1;
1695           t->used = TRUE;
1696
1697           version_index = 1;
1698           /* Don't count anonymous version tag.  */
1699           if (sinfo->verdefs != NULL && sinfo->verdefs->vernum == 0)
1700             version_index = 0;
1701           for (pp = &sinfo->verdefs; *pp != NULL; pp = &(*pp)->next)
1702             ++version_index;
1703           t->vernum = version_index;
1704
1705           *pp = t;
1706
1707           h->verinfo.vertree = t;
1708         }
1709       else if (t == NULL)
1710         {
1711           /* We could not find the version for a symbol when
1712              generating a shared archive.  Return an error.  */
1713           (*_bfd_error_handler)
1714             (_("%B: undefined versioned symbol name %s"),
1715              sinfo->output_bfd, h->root.root.string);
1716           bfd_set_error (bfd_error_bad_value);
1717           sinfo->failed = TRUE;
1718           return FALSE;
1719         }
1720
1721       if (hidden)
1722         h->elf_link_hash_flags |= ELF_LINK_HIDDEN;
1723     }
1724
1725   /* If we don't have a version for this symbol, see if we can find
1726      something.  */
1727   if (h->verinfo.vertree == NULL && sinfo->verdefs != NULL)
1728     {
1729       struct bfd_elf_version_tree *t;
1730       struct bfd_elf_version_tree *local_ver;
1731       struct bfd_elf_version_expr *d;
1732
1733       /* See if can find what version this symbol is in.  If the
1734          symbol is supposed to be local, then don't actually register
1735          it.  */
1736       local_ver = NULL;
1737       for (t = sinfo->verdefs; t != NULL; t = t->next)
1738         {
1739           if (t->globals.list != NULL)
1740             {
1741               bfd_boolean matched;
1742
1743               matched = FALSE;
1744               d = NULL;
1745               while ((d = (*t->match) (&t->globals, d,
1746                                        h->root.root.string)) != NULL)
1747                 if (d->symver)
1748                   matched = TRUE;
1749                 else
1750                   {
1751                     /* There is a version without definition.  Make
1752                        the symbol the default definition for this
1753                        version.  */
1754                     h->verinfo.vertree = t;
1755                     local_ver = NULL;
1756                     d->script = 1;
1757                     break;
1758                   }
1759               if (d != NULL)
1760                 break;
1761               else if (matched)
1762                 /* There is no undefined version for this symbol. Hide the
1763                    default one.  */
1764                 (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1765             }
1766
1767           if (t->locals.list != NULL)
1768             {
1769               d = NULL;
1770               while ((d = (*t->match) (&t->locals, d,
1771                                        h->root.root.string)) != NULL)
1772                 {
1773                   local_ver = t;
1774                   /* If the match is "*", keep looking for a more
1775                      explicit, perhaps even global, match.
1776                      XXX: Shouldn't this be !d->wildcard instead?  */
1777                   if (d->pattern[0] != '*' || d->pattern[1] != '\0')
1778                     break;
1779                 }
1780
1781               if (d != NULL)
1782                 break;
1783             }
1784         }
1785
1786       if (local_ver != NULL)
1787         {
1788           h->verinfo.vertree = local_ver;
1789           if (h->dynindx != -1
1790               && info->shared
1791               && ! info->export_dynamic)
1792             {
1793               (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1794             }
1795         }
1796     }
1797
1798   return TRUE;
1799 }
1800 \f
1801 /* Read and swap the relocs from the section indicated by SHDR.  This
1802    may be either a REL or a RELA section.  The relocations are
1803    translated into RELA relocations and stored in INTERNAL_RELOCS,
1804    which should have already been allocated to contain enough space.
1805    The EXTERNAL_RELOCS are a buffer where the external form of the
1806    relocations should be stored.
1807
1808    Returns FALSE if something goes wrong.  */
1809
1810 static bfd_boolean
1811 elf_link_read_relocs_from_section (bfd *abfd,
1812                                    asection *sec,
1813                                    Elf_Internal_Shdr *shdr,
1814                                    void *external_relocs,
1815                                    Elf_Internal_Rela *internal_relocs)
1816 {
1817   const struct elf_backend_data *bed;
1818   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
1819   const bfd_byte *erela;
1820   const bfd_byte *erelaend;
1821   Elf_Internal_Rela *irela;
1822   Elf_Internal_Shdr *symtab_hdr;
1823   size_t nsyms;
1824
1825   /* Position ourselves at the start of the section.  */
1826   if (bfd_seek (abfd, shdr->sh_offset, SEEK_SET) != 0)
1827     return FALSE;
1828
1829   /* Read the relocations.  */
1830   if (bfd_bread (external_relocs, shdr->sh_size, abfd) != shdr->sh_size)
1831     return FALSE;
1832
1833   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
1834   nsyms = symtab_hdr->sh_size / symtab_hdr->sh_entsize;
1835
1836   bed = get_elf_backend_data (abfd);
1837
1838   /* Convert the external relocations to the internal format.  */
1839   if (shdr->sh_entsize == bed->s->sizeof_rel)
1840     swap_in = bed->s->swap_reloc_in;
1841   else if (shdr->sh_entsize == bed->s->sizeof_rela)
1842     swap_in = bed->s->swap_reloca_in;
1843   else
1844     {
1845       bfd_set_error (bfd_error_wrong_format);
1846       return FALSE;
1847     }
1848
1849   erela = external_relocs;
1850   erelaend = erela + shdr->sh_size;
1851   irela = internal_relocs;
1852   while (erela < erelaend)
1853     {
1854       bfd_vma r_symndx;
1855
1856       (*swap_in) (abfd, erela, irela);
1857       r_symndx = ELF32_R_SYM (irela->r_info);
1858       if (bed->s->arch_size == 64)
1859         r_symndx >>= 24;
1860       if ((size_t) r_symndx >= nsyms)
1861         {
1862           (*_bfd_error_handler)
1863             (_("%B: bad reloc symbol index (0x%lx >= 0x%lx)"
1864                " for offset 0x%lx in section `%A'"),
1865              abfd, sec,
1866              (unsigned long) r_symndx, (unsigned long) nsyms, irela->r_offset);
1867           bfd_set_error (bfd_error_bad_value);
1868           return FALSE;
1869         }
1870       irela += bed->s->int_rels_per_ext_rel;
1871       erela += shdr->sh_entsize;
1872     }
1873
1874   return TRUE;
1875 }
1876
1877 /* Read and swap the relocs for a section O.  They may have been
1878    cached.  If the EXTERNAL_RELOCS and INTERNAL_RELOCS arguments are
1879    not NULL, they are used as buffers to read into.  They are known to
1880    be large enough.  If the INTERNAL_RELOCS relocs argument is NULL,
1881    the return value is allocated using either malloc or bfd_alloc,
1882    according to the KEEP_MEMORY argument.  If O has two relocation
1883    sections (both REL and RELA relocations), then the REL_HDR
1884    relocations will appear first in INTERNAL_RELOCS, followed by the
1885    REL_HDR2 relocations.  */
1886
1887 Elf_Internal_Rela *
1888 _bfd_elf_link_read_relocs (bfd *abfd,
1889                            asection *o,
1890                            void *external_relocs,
1891                            Elf_Internal_Rela *internal_relocs,
1892                            bfd_boolean keep_memory)
1893 {
1894   Elf_Internal_Shdr *rel_hdr;
1895   void *alloc1 = NULL;
1896   Elf_Internal_Rela *alloc2 = NULL;
1897   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
1898
1899   if (elf_section_data (o)->relocs != NULL)
1900     return elf_section_data (o)->relocs;
1901
1902   if (o->reloc_count == 0)
1903     return NULL;
1904
1905   rel_hdr = &elf_section_data (o)->rel_hdr;
1906
1907   if (internal_relocs == NULL)
1908     {
1909       bfd_size_type size;
1910
1911       size = o->reloc_count;
1912       size *= bed->s->int_rels_per_ext_rel * sizeof (Elf_Internal_Rela);
1913       if (keep_memory)
1914         internal_relocs = bfd_alloc (abfd, size);
1915       else
1916         internal_relocs = alloc2 = bfd_malloc (size);
1917       if (internal_relocs == NULL)
1918         goto error_return;
1919     }
1920
1921   if (external_relocs == NULL)
1922     {
1923       bfd_size_type size = rel_hdr->sh_size;
1924
1925       if (elf_section_data (o)->rel_hdr2)
1926         size += elf_section_data (o)->rel_hdr2->sh_size;
1927       alloc1 = bfd_malloc (size);
1928       if (alloc1 == NULL)
1929         goto error_return;
1930       external_relocs = alloc1;
1931     }
1932
1933   if (!elf_link_read_relocs_from_section (abfd, o, rel_hdr,
1934                                           external_relocs,
1935                                           internal_relocs))
1936     goto error_return;
1937   if (elf_section_data (o)->rel_hdr2
1938       && (!elf_link_read_relocs_from_section
1939           (abfd, o,
1940            elf_section_data (o)->rel_hdr2,
1941            ((bfd_byte *) external_relocs) + rel_hdr->sh_size,
1942            internal_relocs + (NUM_SHDR_ENTRIES (rel_hdr)
1943                               * bed->s->int_rels_per_ext_rel))))
1944     goto error_return;
1945
1946   /* Cache the results for next time, if we can.  */
1947   if (keep_memory)
1948     elf_section_data (o)->relocs = internal_relocs;
1949
1950   if (alloc1 != NULL)
1951     free (alloc1);
1952
1953   /* Don't free alloc2, since if it was allocated we are passing it
1954      back (under the name of internal_relocs).  */
1955
1956   return internal_relocs;
1957
1958  error_return:
1959   if (alloc1 != NULL)
1960     free (alloc1);
1961   if (alloc2 != NULL)
1962     free (alloc2);
1963   return NULL;
1964 }
1965
1966 /* Compute the size of, and allocate space for, REL_HDR which is the
1967    section header for a section containing relocations for O.  */
1968
1969 bfd_boolean
1970 _bfd_elf_link_size_reloc_section (bfd *abfd,
1971                                   Elf_Internal_Shdr *rel_hdr,
1972                                   asection *o)
1973 {
1974   bfd_size_type reloc_count;
1975   bfd_size_type num_rel_hashes;
1976
1977   /* Figure out how many relocations there will be.  */
1978   if (rel_hdr == &elf_section_data (o)->rel_hdr)
1979     reloc_count = elf_section_data (o)->rel_count;
1980   else
1981     reloc_count = elf_section_data (o)->rel_count2;
1982
1983   num_rel_hashes = o->reloc_count;
1984   if (num_rel_hashes < reloc_count)
1985     num_rel_hashes = reloc_count;
1986
1987   /* That allows us to calculate the size of the section.  */
1988   rel_hdr->sh_size = rel_hdr->sh_entsize * reloc_count;
1989
1990   /* The contents field must last into write_object_contents, so we
1991      allocate it with bfd_alloc rather than malloc.  Also since we
1992      cannot be sure that the contents will actually be filled in,
1993      we zero the allocated space.  */
1994   rel_hdr->contents = bfd_zalloc (abfd, rel_hdr->sh_size);
1995   if (rel_hdr->contents == NULL && rel_hdr->sh_size != 0)
1996     return FALSE;
1997
1998   /* We only allocate one set of hash entries, so we only do it the
1999      first time we are called.  */
2000   if (elf_section_data (o)->rel_hashes == NULL
2001       && num_rel_hashes)
2002     {
2003       struct elf_link_hash_entry **p;
2004
2005       p = bfd_zmalloc (num_rel_hashes * sizeof (struct elf_link_hash_entry *));
2006       if (p == NULL)
2007         return FALSE;
2008
2009       elf_section_data (o)->rel_hashes = p;
2010     }
2011
2012   return TRUE;
2013 }
2014
2015 /* Copy the relocations indicated by the INTERNAL_RELOCS (which
2016    originated from the section given by INPUT_REL_HDR) to the
2017    OUTPUT_BFD.  */
2018
2019 bfd_boolean
2020 _bfd_elf_link_output_relocs (bfd *output_bfd,
2021                              asection *input_section,
2022                              Elf_Internal_Shdr *input_rel_hdr,
2023                              Elf_Internal_Rela *internal_relocs)
2024 {
2025   Elf_Internal_Rela *irela;
2026   Elf_Internal_Rela *irelaend;
2027   bfd_byte *erel;
2028   Elf_Internal_Shdr *output_rel_hdr;
2029   asection *output_section;
2030   unsigned int *rel_countp = NULL;
2031   const struct elf_backend_data *bed;
2032   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
2033
2034   output_section = input_section->output_section;
2035   output_rel_hdr = NULL;
2036
2037   if (elf_section_data (output_section)->rel_hdr.sh_entsize
2038       == input_rel_hdr->sh_entsize)
2039     {
2040       output_rel_hdr = &elf_section_data (output_section)->rel_hdr;
2041       rel_countp = &elf_section_data (output_section)->rel_count;
2042     }
2043   else if (elf_section_data (output_section)->rel_hdr2
2044            && (elf_section_data (output_section)->rel_hdr2->sh_entsize
2045                == input_rel_hdr->sh_entsize))
2046     {
2047       output_rel_hdr = elf_section_data (output_section)->rel_hdr2;
2048       rel_countp = &elf_section_data (output_section)->rel_count2;
2049     }
2050   else
2051     {
2052       (*_bfd_error_handler)
2053         (_("%B: relocation size mismatch in %B section %A"),
2054          output_bfd, input_section->owner, input_section);
2055       bfd_set_error (bfd_error_wrong_object_format);
2056       return FALSE;
2057     }
2058
2059   bed = get_elf_backend_data (output_bfd);
2060   if (input_rel_hdr->sh_entsize == bed->s->sizeof_rel)
2061     swap_out = bed->s->swap_reloc_out;
2062   else if (input_rel_hdr->sh_entsize == bed->s->sizeof_rela)
2063     swap_out = bed->s->swap_reloca_out;
2064   else
2065     abort ();
2066
2067   erel = output_rel_hdr->contents;
2068   erel += *rel_countp * input_rel_hdr->sh_entsize;
2069   irela = internal_relocs;
2070   irelaend = irela + (NUM_SHDR_ENTRIES (input_rel_hdr)
2071                       * bed->s->int_rels_per_ext_rel);
2072   while (irela < irelaend)
2073     {
2074       (*swap_out) (output_bfd, irela, erel);
2075       irela += bed->s->int_rels_per_ext_rel;
2076       erel += input_rel_hdr->sh_entsize;
2077     }
2078
2079   /* Bump the counter, so that we know where to add the next set of
2080      relocations.  */
2081   *rel_countp += NUM_SHDR_ENTRIES (input_rel_hdr);
2082
2083   return TRUE;
2084 }
2085 \f
2086 /* Fix up the flags for a symbol.  This handles various cases which
2087    can only be fixed after all the input files are seen.  This is
2088    currently called by both adjust_dynamic_symbol and
2089    assign_sym_version, which is unnecessary but perhaps more robust in
2090    the face of future changes.  */
2091
2092 bfd_boolean
2093 _bfd_elf_fix_symbol_flags (struct elf_link_hash_entry *h,
2094                            struct elf_info_failed *eif)
2095 {
2096   /* If this symbol was mentioned in a non-ELF file, try to set
2097      DEF_REGULAR and REF_REGULAR correctly.  This is the only way to
2098      permit a non-ELF file to correctly refer to a symbol defined in
2099      an ELF dynamic object.  */
2100   if ((h->elf_link_hash_flags & ELF_LINK_NON_ELF) != 0)
2101     {
2102       while (h->root.type == bfd_link_hash_indirect)
2103         h = (struct elf_link_hash_entry *) h->root.u.i.link;
2104
2105       if (h->root.type != bfd_link_hash_defined
2106           && h->root.type != bfd_link_hash_defweak)
2107         h->elf_link_hash_flags |= (ELF_LINK_HASH_REF_REGULAR
2108                                    | ELF_LINK_HASH_REF_REGULAR_NONWEAK);
2109       else
2110         {
2111           if (h->root.u.def.section->owner != NULL
2112               && (bfd_get_flavour (h->root.u.def.section->owner)
2113                   == bfd_target_elf_flavour))
2114             h->elf_link_hash_flags |= (ELF_LINK_HASH_REF_REGULAR
2115                                        | ELF_LINK_HASH_REF_REGULAR_NONWEAK);
2116           else
2117             h->elf_link_hash_flags |= ELF_LINK_HASH_DEF_REGULAR;
2118         }
2119
2120       if (h->dynindx == -1
2121           && ((h->elf_link_hash_flags & ELF_LINK_HASH_DEF_DYNAMIC) != 0
2122               || (h->elf_link_hash_flags & ELF_LINK_HASH_REF_DYNAMIC) != 0))
2123         {
2124           if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
2125             {
2126               eif->failed = TRUE;
2127               return FALSE;
2128             }
2129         }
2130     }
2131   else
2132     {
2133       /* Unfortunately, ELF_LINK_NON_ELF is only correct if the symbol
2134          was first seen in a non-ELF file.  Fortunately, if the symbol
2135          was first seen in an ELF file, we're probably OK unless the
2136          symbol was defined in a non-ELF file.  Catch that case here.
2137          FIXME: We're still in trouble if the symbol was first seen in
2138          a dynamic object, and then later in a non-ELF regular object.  */
2139       if ((h->root.type == bfd_link_hash_defined
2140            || h->root.type == bfd_link_hash_defweak)
2141           && (h->elf_link_hash_flags & ELF_LINK_HASH_DEF_REGULAR) == 0
2142           && (h->root.u.def.section->owner != NULL
2143               ? (bfd_get_flavour (h->root.u.def.section->owner)
2144                  != bfd_target_elf_flavour)
2145               : (bfd_is_abs_section (h->root.u.def.section)
2146                  && (h->elf_link_hash_flags
2147                      & ELF_LINK_HASH_DEF_DYNAMIC) == 0)))
2148         h->elf_link_hash_flags |= ELF_LINK_HASH_DEF_REGULAR;
2149     }
2150
2151   /* If this is a final link, and the symbol was defined as a common
2152      symbol in a regular object file, and there was no definition in
2153      any dynamic object, then the linker will have allocated space for
2154      the symbol in a common section but the ELF_LINK_HASH_DEF_REGULAR
2155      flag will not have been set.  */
2156   if (h->root.type == bfd_link_hash_defined
2157       && (h->elf_link_hash_flags & ELF_LINK_HASH_DEF_REGULAR) == 0
2158       && (h->elf_link_hash_flags & ELF_LINK_HASH_REF_REGULAR) != 0
2159       && (h->elf_link_hash_flags & ELF_LINK_HASH_DEF_DYNAMIC) == 0
2160       && (h->root.u.def.section->owner->flags & DYNAMIC) == 0)
2161     h->elf_link_hash_flags |= ELF_LINK_HASH_DEF_REGULAR;
2162
2163   /* If -Bsymbolic was used (which means to bind references to global
2164      symbols to the definition within the shared object), and this
2165      symbol was defined in a regular object, then it actually doesn't
2166      need a PLT entry.  Likewise, if the symbol has non-default
2167      visibility.  If the symbol has hidden or internal visibility, we
2168      will force it local.  */
2169   if ((h->elf_link_hash_flags & ELF_LINK_HASH_NEEDS_PLT) != 0
2170       && eif->info->shared
2171       && is_elf_hash_table (eif->info->hash)
2172       && (eif->info->symbolic
2173           || ELF_ST_VISIBILITY (h->other) != STV_DEFAULT)
2174       && (h->elf_link_hash_flags & ELF_LINK_HASH_DEF_REGULAR) != 0)
2175     {
2176       const struct elf_backend_data *bed;
2177       bfd_boolean force_local;
2178
2179       bed = get_elf_backend_data (elf_hash_table (eif->info)->dynobj);
2180
2181       force_local = (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL
2182                      || ELF_ST_VISIBILITY (h->other) == STV_HIDDEN);
2183       (*bed->elf_backend_hide_symbol) (eif->info, h, force_local);
2184     }
2185
2186   /* If a weak undefined symbol has non-default visibility, we also
2187      hide it from the dynamic linker.  */
2188   if (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
2189       && h->root.type == bfd_link_hash_undefweak)
2190     {
2191       const struct elf_backend_data *bed;
2192       bed = get_elf_backend_data (elf_hash_table (eif->info)->dynobj);
2193       (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2194     }
2195
2196   /* If this is a weak defined symbol in a dynamic object, and we know
2197      the real definition in the dynamic object, copy interesting flags
2198      over to the real definition.  */
2199   if (h->weakdef != NULL)
2200     {
2201       struct elf_link_hash_entry *weakdef;
2202
2203       weakdef = h->weakdef;
2204       if (h->root.type == bfd_link_hash_indirect)
2205         h = (struct elf_link_hash_entry *) h->root.u.i.link;
2206
2207       BFD_ASSERT (h->root.type == bfd_link_hash_defined
2208                   || h->root.type == bfd_link_hash_defweak);
2209       BFD_ASSERT (weakdef->root.type == bfd_link_hash_defined
2210                   || weakdef->root.type == bfd_link_hash_defweak);
2211       BFD_ASSERT (weakdef->elf_link_hash_flags & ELF_LINK_HASH_DEF_DYNAMIC);
2212
2213       /* If the real definition is defined by a regular object file,
2214          don't do anything special.  See the longer description in
2215          _bfd_elf_adjust_dynamic_symbol, below.  */
2216       if ((weakdef->elf_link_hash_flags & ELF_LINK_HASH_DEF_REGULAR) != 0)
2217         h->weakdef = NULL;
2218       else
2219         {
2220           const struct elf_backend_data *bed;
2221
2222           bed = get_elf_backend_data (elf_hash_table (eif->info)->dynobj);
2223           (*bed->elf_backend_copy_indirect_symbol) (bed, weakdef, h);
2224         }
2225     }
2226
2227   return TRUE;
2228 }
2229
2230 /* Make the backend pick a good value for a dynamic symbol.  This is
2231    called via elf_link_hash_traverse, and also calls itself
2232    recursively.  */
2233
2234 bfd_boolean
2235 _bfd_elf_adjust_dynamic_symbol (struct elf_link_hash_entry *h, void *data)
2236 {
2237   struct elf_info_failed *eif = data;
2238   bfd *dynobj;
2239   const struct elf_backend_data *bed;
2240
2241   if (! is_elf_hash_table (eif->info->hash))
2242     return FALSE;
2243
2244   if (h->root.type == bfd_link_hash_warning)
2245     {
2246       h->plt = elf_hash_table (eif->info)->init_offset;
2247       h->got = elf_hash_table (eif->info)->init_offset;
2248
2249       /* When warning symbols are created, they **replace** the "real"
2250          entry in the hash table, thus we never get to see the real
2251          symbol in a hash traversal.  So look at it now.  */
2252       h = (struct elf_link_hash_entry *) h->root.u.i.link;
2253     }
2254
2255   /* Ignore indirect symbols.  These are added by the versioning code.  */
2256   if (h->root.type == bfd_link_hash_indirect)
2257     return TRUE;
2258
2259   /* Fix the symbol flags.  */
2260   if (! _bfd_elf_fix_symbol_flags (h, eif))
2261     return FALSE;
2262
2263   /* If this symbol does not require a PLT entry, and it is not
2264      defined by a dynamic object, or is not referenced by a regular
2265      object, ignore it.  We do have to handle a weak defined symbol,
2266      even if no regular object refers to it, if we decided to add it
2267      to the dynamic symbol table.  FIXME: Do we normally need to worry
2268      about symbols which are defined by one dynamic object and
2269      referenced by another one?  */
2270   if ((h->elf_link_hash_flags & ELF_LINK_HASH_NEEDS_PLT) == 0
2271       && ((h->elf_link_hash_flags & ELF_LINK_HASH_DEF_REGULAR) != 0
2272           || (h->elf_link_hash_flags & ELF_LINK_HASH_DEF_DYNAMIC) == 0
2273           || ((h->elf_link_hash_flags & ELF_LINK_HASH_REF_REGULAR) == 0
2274               && (h->weakdef == NULL || h->weakdef->dynindx == -1))))
2275     {
2276       h->plt = elf_hash_table (eif->info)->init_offset;
2277       return TRUE;
2278     }
2279
2280   /* If we've already adjusted this symbol, don't do it again.  This
2281      can happen via a recursive call.  */
2282   if ((h->elf_link_hash_flags & ELF_LINK_HASH_DYNAMIC_ADJUSTED) != 0)
2283     return TRUE;
2284
2285   /* Don't look at this symbol again.  Note that we must set this
2286      after checking the above conditions, because we may look at a
2287      symbol once, decide not to do anything, and then get called
2288      recursively later after REF_REGULAR is set below.  */
2289   h->elf_link_hash_flags |= ELF_LINK_HASH_DYNAMIC_ADJUSTED;
2290
2291   /* If this is a weak definition, and we know a real definition, and
2292      the real symbol is not itself defined by a regular object file,
2293      then get a good value for the real definition.  We handle the
2294      real symbol first, for the convenience of the backend routine.
2295
2296      Note that there is a confusing case here.  If the real definition
2297      is defined by a regular object file, we don't get the real symbol
2298      from the dynamic object, but we do get the weak symbol.  If the
2299      processor backend uses a COPY reloc, then if some routine in the
2300      dynamic object changes the real symbol, we will not see that
2301      change in the corresponding weak symbol.  This is the way other
2302      ELF linkers work as well, and seems to be a result of the shared
2303      library model.
2304
2305      I will clarify this issue.  Most SVR4 shared libraries define the
2306      variable _timezone and define timezone as a weak synonym.  The
2307      tzset call changes _timezone.  If you write
2308        extern int timezone;
2309        int _timezone = 5;
2310        int main () { tzset (); printf ("%d %d\n", timezone, _timezone); }
2311      you might expect that, since timezone is a synonym for _timezone,
2312      the same number will print both times.  However, if the processor
2313      backend uses a COPY reloc, then actually timezone will be copied
2314      into your process image, and, since you define _timezone
2315      yourself, _timezone will not.  Thus timezone and _timezone will
2316      wind up at different memory locations.  The tzset call will set
2317      _timezone, leaving timezone unchanged.  */
2318
2319   if (h->weakdef != NULL)
2320     {
2321       /* If we get to this point, we know there is an implicit
2322          reference by a regular object file via the weak symbol H.
2323          FIXME: Is this really true?  What if the traversal finds
2324          H->WEAKDEF before it finds H?  */
2325       h->weakdef->elf_link_hash_flags |= ELF_LINK_HASH_REF_REGULAR;
2326
2327       if (! _bfd_elf_adjust_dynamic_symbol (h->weakdef, eif))
2328         return FALSE;
2329     }
2330
2331   /* If a symbol has no type and no size and does not require a PLT
2332      entry, then we are probably about to do the wrong thing here: we
2333      are probably going to create a COPY reloc for an empty object.
2334      This case can arise when a shared object is built with assembly
2335      code, and the assembly code fails to set the symbol type.  */
2336   if (h->size == 0
2337       && h->type == STT_NOTYPE
2338       && (h->elf_link_hash_flags & ELF_LINK_HASH_NEEDS_PLT) == 0)
2339     (*_bfd_error_handler)
2340       (_("warning: type and size of dynamic symbol `%s' are not defined"),
2341        h->root.root.string);
2342
2343   dynobj = elf_hash_table (eif->info)->dynobj;
2344   bed = get_elf_backend_data (dynobj);
2345   if (! (*bed->elf_backend_adjust_dynamic_symbol) (eif->info, h))
2346     {
2347       eif->failed = TRUE;
2348       return FALSE;
2349     }
2350
2351   return TRUE;
2352 }
2353
2354 /* Adjust all external symbols pointing into SEC_MERGE sections
2355    to reflect the object merging within the sections.  */
2356
2357 bfd_boolean
2358 _bfd_elf_link_sec_merge_syms (struct elf_link_hash_entry *h, void *data)
2359 {
2360   asection *sec;
2361
2362   if (h->root.type == bfd_link_hash_warning)
2363     h = (struct elf_link_hash_entry *) h->root.u.i.link;
2364
2365   if ((h->root.type == bfd_link_hash_defined
2366        || h->root.type == bfd_link_hash_defweak)
2367       && ((sec = h->root.u.def.section)->flags & SEC_MERGE)
2368       && sec->sec_info_type == ELF_INFO_TYPE_MERGE)
2369     {
2370       bfd *output_bfd = data;
2371
2372       h->root.u.def.value =
2373         _bfd_merged_section_offset (output_bfd,
2374                                     &h->root.u.def.section,
2375                                     elf_section_data (sec)->sec_info,
2376                                     h->root.u.def.value);
2377     }
2378
2379   return TRUE;
2380 }
2381
2382 /* Returns false if the symbol referred to by H should be considered
2383    to resolve local to the current module, and true if it should be
2384    considered to bind dynamically.  */
2385
2386 bfd_boolean
2387 _bfd_elf_dynamic_symbol_p (struct elf_link_hash_entry *h,
2388                            struct bfd_link_info *info,
2389                            bfd_boolean ignore_protected)
2390 {
2391   bfd_boolean binding_stays_local_p;
2392
2393   if (h == NULL)
2394     return FALSE;
2395
2396   while (h->root.type == bfd_link_hash_indirect
2397          || h->root.type == bfd_link_hash_warning)
2398     h = (struct elf_link_hash_entry *) h->root.u.i.link;
2399
2400   /* If it was forced local, then clearly it's not dynamic.  */
2401   if (h->dynindx == -1)
2402     return FALSE;
2403   if (h->elf_link_hash_flags & ELF_LINK_FORCED_LOCAL)
2404     return FALSE;
2405
2406   /* Identify the cases where name binding rules say that a
2407      visible symbol resolves locally.  */
2408   binding_stays_local_p = info->executable || info->symbolic;
2409
2410   switch (ELF_ST_VISIBILITY (h->other))
2411     {
2412     case STV_INTERNAL:
2413     case STV_HIDDEN:
2414       return FALSE;
2415
2416     case STV_PROTECTED:
2417       /* Proper resolution for function pointer equality may require
2418          that these symbols perhaps be resolved dynamically, even though
2419          we should be resolving them to the current module.  */
2420       if (!ignore_protected)
2421         binding_stays_local_p = TRUE;
2422       break;
2423
2424     default:
2425       break;
2426     }
2427
2428   /* If it isn't defined locally, then clearly it's dynamic.  */
2429   if ((h->elf_link_hash_flags & ELF_LINK_HASH_DEF_REGULAR) == 0)
2430     return TRUE;
2431
2432   /* Otherwise, the symbol is dynamic if binding rules don't tell
2433      us that it remains local.  */
2434   return !binding_stays_local_p;
2435 }
2436
2437 /* Return true if the symbol referred to by H should be considered
2438    to resolve local to the current module, and false otherwise.  Differs
2439    from (the inverse of) _bfd_elf_dynamic_symbol_p in the treatment of
2440    undefined symbols and weak symbols.  */
2441
2442 bfd_boolean
2443 _bfd_elf_symbol_refs_local_p (struct elf_link_hash_entry *h,
2444                               struct bfd_link_info *info,
2445                               bfd_boolean local_protected)
2446 {
2447   /* If it's a local sym, of course we resolve locally.  */
2448   if (h == NULL)
2449     return TRUE;
2450
2451   /* Common symbols that become definitions don't get the DEF_REGULAR
2452      flag set, so test it first, and don't bail out.  */
2453   if (ELF_COMMON_DEF_P (h))
2454     /* Do nothing.  */;
2455   /* If we don't have a definition in a regular file, then we can't
2456      resolve locally.  The sym is either undefined or dynamic.  */
2457   else if ((h->elf_link_hash_flags & ELF_LINK_HASH_DEF_REGULAR) == 0)
2458     return FALSE;
2459
2460   /* Forced local symbols resolve locally.  */
2461   if ((h->elf_link_hash_flags & ELF_LINK_FORCED_LOCAL) != 0)
2462     return TRUE;
2463
2464   /* As do non-dynamic symbols.  */
2465   if (h->dynindx == -1)
2466     return TRUE;
2467
2468   /* At this point, we know the symbol is defined and dynamic.  In an
2469      executable it must resolve locally, likewise when building symbolic
2470      shared libraries.  */
2471   if (info->executable || info->symbolic)
2472     return TRUE;
2473
2474   /* Now deal with defined dynamic symbols in shared libraries.  Ones
2475      with default visibility might not resolve locally.  */
2476   if (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT)
2477     return FALSE;
2478
2479   /* However, STV_HIDDEN or STV_INTERNAL ones must be local.  */
2480   if (ELF_ST_VISIBILITY (h->other) != STV_PROTECTED)
2481     return TRUE;
2482
2483   /* Function pointer equality tests may require that STV_PROTECTED
2484      symbols be treated as dynamic symbols, even when we know that the
2485      dynamic linker will resolve them locally.  */
2486   return local_protected;
2487 }
2488
2489 /* Caches some TLS segment info, and ensures that the TLS segment vma is
2490    aligned.  Returns the first TLS output section.  */
2491
2492 struct bfd_section *
2493 _bfd_elf_tls_setup (bfd *obfd, struct bfd_link_info *info)
2494 {
2495   struct bfd_section *sec, *tls;
2496   unsigned int align = 0;
2497
2498   for (sec = obfd->sections; sec != NULL; sec = sec->next)
2499     if ((sec->flags & SEC_THREAD_LOCAL) != 0)
2500       break;
2501   tls = sec;
2502
2503   for (; sec != NULL && (sec->flags & SEC_THREAD_LOCAL) != 0; sec = sec->next)
2504     if (sec->alignment_power > align)
2505       align = sec->alignment_power;
2506
2507   elf_hash_table (info)->tls_sec = tls;
2508
2509   /* Ensure the alignment of the first section is the largest alignment,
2510      so that the tls segment starts aligned.  */
2511   if (tls != NULL)
2512     tls->alignment_power = align;
2513
2514   return tls;
2515 }
2516
2517 /* Return TRUE iff this is a non-common, definition of a non-function symbol.  */
2518 static bfd_boolean
2519 is_global_data_symbol_definition (bfd *abfd ATTRIBUTE_UNUSED,
2520                                   Elf_Internal_Sym *sym)
2521 {
2522   /* Local symbols do not count, but target specific ones might.  */
2523   if (ELF_ST_BIND (sym->st_info) != STB_GLOBAL
2524       && ELF_ST_BIND (sym->st_info) < STB_LOOS)
2525     return FALSE;
2526
2527   /* Function symbols do not count.  */
2528   if (ELF_ST_TYPE (sym->st_info) == STT_FUNC)
2529     return FALSE;
2530
2531   /* If the section is undefined, then so is the symbol.  */
2532   if (sym->st_shndx == SHN_UNDEF)
2533     return FALSE;
2534
2535   /* If the symbol is defined in the common section, then
2536      it is a common definition and so does not count.  */
2537   if (sym->st_shndx == SHN_COMMON)
2538     return FALSE;
2539
2540   /* If the symbol is in a target specific section then we
2541      must rely upon the backend to tell us what it is.  */
2542   if (sym->st_shndx >= SHN_LORESERVE && sym->st_shndx < SHN_ABS)
2543     /* FIXME - this function is not coded yet:
2544
2545        return _bfd_is_global_symbol_definition (abfd, sym);
2546
2547        Instead for now assume that the definition is not global,
2548        Even if this is wrong, at least the linker will behave
2549        in the same way that it used to do.  */
2550     return FALSE;
2551
2552   return TRUE;
2553 }
2554
2555 /* Search the symbol table of the archive element of the archive ABFD
2556    whose archive map contains a mention of SYMDEF, and determine if
2557    the symbol is defined in this element.  */
2558 static bfd_boolean
2559 elf_link_is_defined_archive_symbol (bfd * abfd, carsym * symdef)
2560 {
2561   Elf_Internal_Shdr * hdr;
2562   bfd_size_type symcount;
2563   bfd_size_type extsymcount;
2564   bfd_size_type extsymoff;
2565   Elf_Internal_Sym *isymbuf;
2566   Elf_Internal_Sym *isym;
2567   Elf_Internal_Sym *isymend;
2568   bfd_boolean result;
2569
2570   abfd = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
2571   if (abfd == NULL)
2572     return FALSE;
2573
2574   if (! bfd_check_format (abfd, bfd_object))
2575     return FALSE;
2576
2577   /* If we have already included the element containing this symbol in the
2578      link then we do not need to include it again.  Just claim that any symbol
2579      it contains is not a definition, so that our caller will not decide to
2580      (re)include this element.  */
2581   if (abfd->archive_pass)
2582     return FALSE;
2583
2584   /* Select the appropriate symbol table.  */
2585   if ((abfd->flags & DYNAMIC) == 0 || elf_dynsymtab (abfd) == 0)
2586     hdr = &elf_tdata (abfd)->symtab_hdr;
2587   else
2588     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
2589
2590   symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
2591
2592   /* The sh_info field of the symtab header tells us where the
2593      external symbols start.  We don't care about the local symbols.  */
2594   if (elf_bad_symtab (abfd))
2595     {
2596       extsymcount = symcount;
2597       extsymoff = 0;
2598     }
2599   else
2600     {
2601       extsymcount = symcount - hdr->sh_info;
2602       extsymoff = hdr->sh_info;
2603     }
2604
2605   if (extsymcount == 0)
2606     return FALSE;
2607
2608   /* Read in the symbol table.  */
2609   isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
2610                                   NULL, NULL, NULL);
2611   if (isymbuf == NULL)
2612     return FALSE;
2613
2614   /* Scan the symbol table looking for SYMDEF.  */
2615   result = FALSE;
2616   for (isym = isymbuf, isymend = isymbuf + extsymcount; isym < isymend; isym++)
2617     {
2618       const char *name;
2619
2620       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
2621                                               isym->st_name);
2622       if (name == NULL)
2623         break;
2624
2625       if (strcmp (name, symdef->name) == 0)
2626         {
2627           result = is_global_data_symbol_definition (abfd, isym);
2628           break;
2629         }
2630     }
2631
2632   free (isymbuf);
2633
2634   return result;
2635 }
2636 \f
2637 /* Add an entry to the .dynamic table.  */
2638
2639 bfd_boolean
2640 _bfd_elf_add_dynamic_entry (struct bfd_link_info *info,
2641                             bfd_vma tag,
2642                             bfd_vma val)
2643 {
2644   struct elf_link_hash_table *hash_table;
2645   const struct elf_backend_data *bed;
2646   asection *s;
2647   bfd_size_type newsize;
2648   bfd_byte *newcontents;
2649   Elf_Internal_Dyn dyn;
2650
2651   hash_table = elf_hash_table (info);
2652   if (! is_elf_hash_table (hash_table))
2653     return FALSE;
2654
2655   bed = get_elf_backend_data (hash_table->dynobj);
2656   s = bfd_get_section_by_name (hash_table->dynobj, ".dynamic");
2657   BFD_ASSERT (s != NULL);
2658
2659   newsize = s->size + bed->s->sizeof_dyn;
2660   newcontents = bfd_realloc (s->contents, newsize);
2661   if (newcontents == NULL)
2662     return FALSE;
2663
2664   dyn.d_tag = tag;
2665   dyn.d_un.d_val = val;
2666   bed->s->swap_dyn_out (hash_table->dynobj, &dyn, newcontents + s->size);
2667
2668   s->size = newsize;
2669   s->contents = newcontents;
2670
2671   return TRUE;
2672 }
2673
2674 /* Add a DT_NEEDED entry for this dynamic object if DO_IT is true,
2675    otherwise just check whether one already exists.  Returns -1 on error,
2676    1 if a DT_NEEDED tag already exists, and 0 on success.  */
2677
2678 static int
2679 elf_add_dt_needed_tag (struct bfd_link_info *info,
2680                        const char *soname,
2681                        bfd_boolean do_it)
2682 {
2683   struct elf_link_hash_table *hash_table;
2684   bfd_size_type oldsize;
2685   bfd_size_type strindex;
2686
2687   hash_table = elf_hash_table (info);
2688   oldsize = _bfd_elf_strtab_size (hash_table->dynstr);
2689   strindex = _bfd_elf_strtab_add (hash_table->dynstr, soname, FALSE);
2690   if (strindex == (bfd_size_type) -1)
2691     return -1;
2692
2693   if (oldsize == _bfd_elf_strtab_size (hash_table->dynstr))
2694     {
2695       asection *sdyn;
2696       const struct elf_backend_data *bed;
2697       bfd_byte *extdyn;
2698
2699       bed = get_elf_backend_data (hash_table->dynobj);
2700       sdyn = bfd_get_section_by_name (hash_table->dynobj, ".dynamic");
2701       BFD_ASSERT (sdyn != NULL);
2702
2703       for (extdyn = sdyn->contents;
2704            extdyn < sdyn->contents + sdyn->size;
2705            extdyn += bed->s->sizeof_dyn)
2706         {
2707           Elf_Internal_Dyn dyn;
2708
2709           bed->s->swap_dyn_in (hash_table->dynobj, extdyn, &dyn);
2710           if (dyn.d_tag == DT_NEEDED
2711               && dyn.d_un.d_val == strindex)
2712             {
2713               _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
2714               return 1;
2715             }
2716         }
2717     }
2718
2719   if (do_it)
2720     {
2721       if (!_bfd_elf_add_dynamic_entry (info, DT_NEEDED, strindex))
2722         return -1;
2723     }
2724   else
2725     /* We were just checking for existence of the tag.  */
2726     _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
2727
2728   return 0;
2729 }
2730
2731 /* Sort symbol by value and section.  */
2732 static int
2733 elf_sort_symbol (const void *arg1, const void *arg2)
2734 {
2735   const struct elf_link_hash_entry *h1;
2736   const struct elf_link_hash_entry *h2;
2737   bfd_signed_vma vdiff;
2738
2739   h1 = *(const struct elf_link_hash_entry **) arg1;
2740   h2 = *(const struct elf_link_hash_entry **) arg2;
2741   vdiff = h1->root.u.def.value - h2->root.u.def.value;
2742   if (vdiff != 0)
2743     return vdiff > 0 ? 1 : -1;
2744   else
2745     {
2746       long sdiff = h1->root.u.def.section->id - h2->root.u.def.section->id;
2747       if (sdiff != 0)
2748         return sdiff > 0 ? 1 : -1;
2749     }
2750   return 0;
2751 }
2752
2753 /* This function is used to adjust offsets into .dynstr for
2754    dynamic symbols.  This is called via elf_link_hash_traverse.  */
2755
2756 static bfd_boolean
2757 elf_adjust_dynstr_offsets (struct elf_link_hash_entry *h, void *data)
2758 {
2759   struct elf_strtab_hash *dynstr = data;
2760
2761   if (h->root.type == bfd_link_hash_warning)
2762     h = (struct elf_link_hash_entry *) h->root.u.i.link;
2763
2764   if (h->dynindx != -1)
2765     h->dynstr_index = _bfd_elf_strtab_offset (dynstr, h->dynstr_index);
2766   return TRUE;
2767 }
2768
2769 /* Assign string offsets in .dynstr, update all structures referencing
2770    them.  */
2771
2772 static bfd_boolean
2773 elf_finalize_dynstr (bfd *output_bfd, struct bfd_link_info *info)
2774 {
2775   struct elf_link_hash_table *hash_table = elf_hash_table (info);
2776   struct elf_link_local_dynamic_entry *entry;
2777   struct elf_strtab_hash *dynstr = hash_table->dynstr;
2778   bfd *dynobj = hash_table->dynobj;
2779   asection *sdyn;
2780   bfd_size_type size;
2781   const struct elf_backend_data *bed;
2782   bfd_byte *extdyn;
2783
2784   _bfd_elf_strtab_finalize (dynstr);
2785   size = _bfd_elf_strtab_size (dynstr);
2786
2787   bed = get_elf_backend_data (dynobj);
2788   sdyn = bfd_get_section_by_name (dynobj, ".dynamic");
2789   BFD_ASSERT (sdyn != NULL);
2790
2791   /* Update all .dynamic entries referencing .dynstr strings.  */
2792   for (extdyn = sdyn->contents;
2793        extdyn < sdyn->contents + sdyn->size;
2794        extdyn += bed->s->sizeof_dyn)
2795     {
2796       Elf_Internal_Dyn dyn;
2797
2798       bed->s->swap_dyn_in (dynobj, extdyn, &dyn);
2799       switch (dyn.d_tag)
2800         {
2801         case DT_STRSZ:
2802           dyn.d_un.d_val = size;
2803           break;
2804         case DT_NEEDED:
2805         case DT_SONAME:
2806         case DT_RPATH:
2807         case DT_RUNPATH:
2808         case DT_FILTER:
2809         case DT_AUXILIARY:
2810           dyn.d_un.d_val = _bfd_elf_strtab_offset (dynstr, dyn.d_un.d_val);
2811           break;
2812         default:
2813           continue;
2814         }
2815       bed->s->swap_dyn_out (dynobj, &dyn, extdyn);
2816     }
2817
2818   /* Now update local dynamic symbols.  */
2819   for (entry = hash_table->dynlocal; entry ; entry = entry->next)
2820     entry->isym.st_name = _bfd_elf_strtab_offset (dynstr,
2821                                                   entry->isym.st_name);
2822
2823   /* And the rest of dynamic symbols.  */
2824   elf_link_hash_traverse (hash_table, elf_adjust_dynstr_offsets, dynstr);
2825
2826   /* Adjust version definitions.  */
2827   if (elf_tdata (output_bfd)->cverdefs)
2828     {
2829       asection *s;
2830       bfd_byte *p;
2831       bfd_size_type i;
2832       Elf_Internal_Verdef def;
2833       Elf_Internal_Verdaux defaux;
2834
2835       s = bfd_get_section_by_name (dynobj, ".gnu.version_d");
2836       p = s->contents;
2837       do
2838         {
2839           _bfd_elf_swap_verdef_in (output_bfd, (Elf_External_Verdef *) p,
2840                                    &def);
2841           p += sizeof (Elf_External_Verdef);
2842           for (i = 0; i < def.vd_cnt; ++i)
2843             {
2844               _bfd_elf_swap_verdaux_in (output_bfd,
2845                                         (Elf_External_Verdaux *) p, &defaux);
2846               defaux.vda_name = _bfd_elf_strtab_offset (dynstr,
2847                                                         defaux.vda_name);
2848               _bfd_elf_swap_verdaux_out (output_bfd,
2849                                          &defaux, (Elf_External_Verdaux *) p);
2850               p += sizeof (Elf_External_Verdaux);
2851             }
2852         }
2853       while (def.vd_next);
2854     }
2855
2856   /* Adjust version references.  */
2857   if (elf_tdata (output_bfd)->verref)
2858     {
2859       asection *s;
2860       bfd_byte *p;
2861       bfd_size_type i;
2862       Elf_Internal_Verneed need;
2863       Elf_Internal_Vernaux needaux;
2864
2865       s = bfd_get_section_by_name (dynobj, ".gnu.version_r");
2866       p = s->contents;
2867       do
2868         {
2869           _bfd_elf_swap_verneed_in (output_bfd, (Elf_External_Verneed *) p,
2870                                     &need);
2871           need.vn_file = _bfd_elf_strtab_offset (dynstr, need.vn_file);
2872           _bfd_elf_swap_verneed_out (output_bfd, &need,
2873                                      (Elf_External_Verneed *) p);
2874           p += sizeof (Elf_External_Verneed);
2875           for (i = 0; i < need.vn_cnt; ++i)
2876             {
2877               _bfd_elf_swap_vernaux_in (output_bfd,
2878                                         (Elf_External_Vernaux *) p, &needaux);
2879               needaux.vna_name = _bfd_elf_strtab_offset (dynstr,
2880                                                          needaux.vna_name);
2881               _bfd_elf_swap_vernaux_out (output_bfd,
2882                                          &needaux,
2883                                          (Elf_External_Vernaux *) p);
2884               p += sizeof (Elf_External_Vernaux);
2885             }
2886         }
2887       while (need.vn_next);
2888     }
2889
2890   return TRUE;
2891 }
2892 \f
2893 /* Add symbols from an ELF object file to the linker hash table.  */
2894
2895 static bfd_boolean
2896 elf_link_add_object_symbols (bfd *abfd, struct bfd_link_info *info)
2897 {
2898   bfd_boolean (*add_symbol_hook)
2899     (bfd *, struct bfd_link_info *, Elf_Internal_Sym *,
2900      const char **, flagword *, asection **, bfd_vma *);
2901   bfd_boolean (*check_relocs)
2902     (bfd *, struct bfd_link_info *, asection *, const Elf_Internal_Rela *);
2903   bfd_boolean (*check_directives)
2904     (bfd *, struct bfd_link_info *);
2905   bfd_boolean collect;
2906   Elf_Internal_Shdr *hdr;
2907   bfd_size_type symcount;
2908   bfd_size_type extsymcount;
2909   bfd_size_type extsymoff;
2910   struct elf_link_hash_entry **sym_hash;
2911   bfd_boolean dynamic;
2912   Elf_External_Versym *extversym = NULL;
2913   Elf_External_Versym *ever;
2914   struct elf_link_hash_entry *weaks;
2915   struct elf_link_hash_entry **nondeflt_vers = NULL;
2916   bfd_size_type nondeflt_vers_cnt = 0;
2917   Elf_Internal_Sym *isymbuf = NULL;
2918   Elf_Internal_Sym *isym;
2919   Elf_Internal_Sym *isymend;
2920   const struct elf_backend_data *bed;
2921   bfd_boolean add_needed;
2922   struct elf_link_hash_table * hash_table;
2923   bfd_size_type amt;
2924
2925   hash_table = elf_hash_table (info);
2926
2927   bed = get_elf_backend_data (abfd);
2928   add_symbol_hook = bed->elf_add_symbol_hook;
2929   collect = bed->collect;
2930
2931   if ((abfd->flags & DYNAMIC) == 0)
2932     dynamic = FALSE;
2933   else
2934     {
2935       dynamic = TRUE;
2936
2937       /* You can't use -r against a dynamic object.  Also, there's no
2938          hope of using a dynamic object which does not exactly match
2939          the format of the output file.  */
2940       if (info->relocatable
2941           || !is_elf_hash_table (hash_table)
2942           || hash_table->root.creator != abfd->xvec)
2943         {
2944           bfd_set_error (bfd_error_invalid_operation);
2945           goto error_return;
2946         }
2947     }
2948
2949   /* As a GNU extension, any input sections which are named
2950      .gnu.warning.SYMBOL are treated as warning symbols for the given
2951      symbol.  This differs from .gnu.warning sections, which generate
2952      warnings when they are included in an output file.  */
2953   if (info->executable)
2954     {
2955       asection *s;
2956
2957       for (s = abfd->sections; s != NULL; s = s->next)
2958         {
2959           const char *name;
2960
2961           name = bfd_get_section_name (abfd, s);
2962           if (strncmp (name, ".gnu.warning.", sizeof ".gnu.warning." - 1) == 0)
2963             {
2964               char *msg;
2965               bfd_size_type sz;
2966               bfd_size_type prefix_len;
2967               const char * gnu_warning_prefix = _("warning: ");
2968
2969               name += sizeof ".gnu.warning." - 1;
2970
2971               /* If this is a shared object, then look up the symbol
2972                  in the hash table.  If it is there, and it is already
2973                  been defined, then we will not be using the entry
2974                  from this shared object, so we don't need to warn.
2975                  FIXME: If we see the definition in a regular object
2976                  later on, we will warn, but we shouldn't.  The only
2977                  fix is to keep track of what warnings we are supposed
2978                  to emit, and then handle them all at the end of the
2979                  link.  */
2980               if (dynamic)
2981                 {
2982                   struct elf_link_hash_entry *h;
2983
2984                   h = elf_link_hash_lookup (hash_table, name,
2985                                             FALSE, FALSE, TRUE);
2986
2987                   /* FIXME: What about bfd_link_hash_common?  */
2988                   if (h != NULL
2989                       && (h->root.type == bfd_link_hash_defined
2990                           || h->root.type == bfd_link_hash_defweak))
2991                     {
2992                       /* We don't want to issue this warning.  Clobber
2993                          the section size so that the warning does not
2994                          get copied into the output file.  */
2995                       s->size = 0;
2996                       continue;
2997                     }
2998                 }
2999
3000               sz = s->size;
3001               prefix_len = strlen (gnu_warning_prefix);
3002               msg = bfd_alloc (abfd, prefix_len + sz + 1);
3003               if (msg == NULL)
3004                 goto error_return;
3005
3006               strcpy (msg, gnu_warning_prefix);
3007               if (! bfd_get_section_contents (abfd, s, msg + prefix_len, 0, sz))
3008                 goto error_return;
3009
3010               msg[prefix_len + sz] = '\0';
3011
3012               if (! (_bfd_generic_link_add_one_symbol
3013                      (info, abfd, name, BSF_WARNING, s, 0, msg,
3014                       FALSE, collect, NULL)))
3015                 goto error_return;
3016
3017               if (! info->relocatable)
3018                 {
3019                   /* Clobber the section size so that the warning does
3020                      not get copied into the output file.  */
3021                   s->size = 0;
3022                 }
3023             }
3024         }
3025     }
3026
3027   add_needed = TRUE;
3028   if (! dynamic)
3029     {
3030       /* If we are creating a shared library, create all the dynamic
3031          sections immediately.  We need to attach them to something,
3032          so we attach them to this BFD, provided it is the right
3033          format.  FIXME: If there are no input BFD's of the same
3034          format as the output, we can't make a shared library.  */
3035       if (info->shared
3036           && is_elf_hash_table (hash_table)
3037           && hash_table->root.creator == abfd->xvec
3038           && ! hash_table->dynamic_sections_created)
3039         {
3040           if (! _bfd_elf_link_create_dynamic_sections (abfd, info))
3041             goto error_return;
3042         }
3043     }
3044   else if (!is_elf_hash_table (hash_table))
3045     goto error_return;
3046   else
3047     {
3048       asection *s;
3049       const char *soname = NULL;
3050       struct bfd_link_needed_list *rpath = NULL, *runpath = NULL;
3051       int ret;
3052
3053       /* ld --just-symbols and dynamic objects don't mix very well.
3054          Test for --just-symbols by looking at info set up by
3055          _bfd_elf_link_just_syms.  */
3056       if ((s = abfd->sections) != NULL
3057           && s->sec_info_type == ELF_INFO_TYPE_JUST_SYMS)
3058         goto error_return;
3059
3060       /* If this dynamic lib was specified on the command line with
3061          --as-needed in effect, then we don't want to add a DT_NEEDED
3062          tag unless the lib is actually used.  Similary for libs brought
3063          in by another lib's DT_NEEDED.  When --no-add-needed is used
3064          on a dynamic lib, we don't want to add a DT_NEEDED entry for
3065          any dynamic library in DT_NEEDED tags in the dynamic lib at
3066          all.  */
3067       add_needed = (elf_dyn_lib_class (abfd)
3068                     & (DYN_AS_NEEDED | DYN_DT_NEEDED
3069                        | DYN_NO_NEEDED)) == 0;
3070
3071       s = bfd_get_section_by_name (abfd, ".dynamic");
3072       if (s != NULL)
3073         {
3074           bfd_byte *dynbuf;
3075           bfd_byte *extdyn;
3076           int elfsec;
3077           unsigned long shlink;
3078
3079           if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
3080             goto error_free_dyn;
3081
3082           elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
3083           if (elfsec == -1)
3084             goto error_free_dyn;
3085           shlink = elf_elfsections (abfd)[elfsec]->sh_link;
3086
3087           for (extdyn = dynbuf;
3088                extdyn < dynbuf + s->size;
3089                extdyn += bed->s->sizeof_dyn)
3090             {
3091               Elf_Internal_Dyn dyn;
3092
3093               bed->s->swap_dyn_in (abfd, extdyn, &dyn);
3094               if (dyn.d_tag == DT_SONAME)
3095                 {
3096                   unsigned int tagv = dyn.d_un.d_val;
3097                   soname = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3098                   if (soname == NULL)
3099                     goto error_free_dyn;
3100                 }
3101               if (dyn.d_tag == DT_NEEDED)
3102                 {
3103                   struct bfd_link_needed_list *n, **pn;
3104                   char *fnm, *anm;
3105                   unsigned int tagv = dyn.d_un.d_val;
3106
3107                   amt = sizeof (struct bfd_link_needed_list);
3108                   n = bfd_alloc (abfd, amt);
3109                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3110                   if (n == NULL || fnm == NULL)
3111                     goto error_free_dyn;
3112                   amt = strlen (fnm) + 1;
3113                   anm = bfd_alloc (abfd, amt);
3114                   if (anm == NULL)
3115                     goto error_free_dyn;
3116                   memcpy (anm, fnm, amt);
3117                   n->name = anm;
3118                   n->by = abfd;
3119                   n->next = NULL;
3120                   for (pn = & hash_table->needed;
3121                        *pn != NULL;
3122                        pn = &(*pn)->next)
3123                     ;
3124                   *pn = n;
3125                 }
3126               if (dyn.d_tag == DT_RUNPATH)
3127                 {
3128                   struct bfd_link_needed_list *n, **pn;
3129                   char *fnm, *anm;
3130                   unsigned int tagv = dyn.d_un.d_val;
3131
3132                   amt = sizeof (struct bfd_link_needed_list);
3133                   n = bfd_alloc (abfd, amt);
3134                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3135                   if (n == NULL || fnm == NULL)
3136                     goto error_free_dyn;
3137                   amt = strlen (fnm) + 1;
3138                   anm = bfd_alloc (abfd, amt);
3139                   if (anm == NULL)
3140                     goto error_free_dyn;
3141                   memcpy (anm, fnm, amt);
3142                   n->name = anm;
3143                   n->by = abfd;
3144                   n->next = NULL;
3145                   for (pn = & runpath;
3146                        *pn != NULL;
3147                        pn = &(*pn)->next)
3148                     ;
3149                   *pn = n;
3150                 }
3151               /* Ignore DT_RPATH if we have seen DT_RUNPATH.  */
3152               if (!runpath && dyn.d_tag == DT_RPATH)
3153                 {
3154                   struct bfd_link_needed_list *n, **pn;
3155                   char *fnm, *anm;
3156                   unsigned int tagv = dyn.d_un.d_val;
3157
3158                   amt = sizeof (struct bfd_link_needed_list);
3159                   n = bfd_alloc (abfd, amt);
3160                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3161                   if (n == NULL || fnm == NULL)
3162                     goto error_free_dyn;
3163                   amt = strlen (fnm) + 1;
3164                   anm = bfd_alloc (abfd, amt);
3165                   if (anm == NULL)
3166                     {
3167                     error_free_dyn:
3168                       free (dynbuf);
3169                       goto error_return;
3170                     }
3171                   memcpy (anm, fnm, amt);
3172                   n->name = anm;
3173                   n->by = abfd;
3174                   n->next = NULL;
3175                   for (pn = & rpath;
3176                        *pn != NULL;
3177                        pn = &(*pn)->next)
3178                     ;
3179                   *pn = n;
3180                 }
3181             }
3182
3183           free (dynbuf);
3184         }
3185
3186       /* DT_RUNPATH overrides DT_RPATH.  Do _NOT_ bfd_release, as that
3187          frees all more recently bfd_alloc'd blocks as well.  */
3188       if (runpath)
3189         rpath = runpath;
3190
3191       if (rpath)
3192         {
3193           struct bfd_link_needed_list **pn;
3194           for (pn = & hash_table->runpath;
3195                *pn != NULL;
3196                pn = &(*pn)->next)
3197             ;
3198           *pn = rpath;
3199         }
3200
3201       /* We do not want to include any of the sections in a dynamic
3202          object in the output file.  We hack by simply clobbering the
3203          list of sections in the BFD.  This could be handled more
3204          cleanly by, say, a new section flag; the existing
3205          SEC_NEVER_LOAD flag is not the one we want, because that one
3206          still implies that the section takes up space in the output
3207          file.  */
3208       bfd_section_list_clear (abfd);
3209
3210       /* If this is the first dynamic object found in the link, create
3211          the special sections required for dynamic linking.  */
3212       if (! _bfd_elf_link_create_dynamic_sections (abfd, info))
3213         goto error_return;
3214
3215       /* Find the name to use in a DT_NEEDED entry that refers to this
3216          object.  If the object has a DT_SONAME entry, we use it.
3217          Otherwise, if the generic linker stuck something in
3218          elf_dt_name, we use that.  Otherwise, we just use the file
3219          name.  */
3220       if (soname == NULL || *soname == '\0')
3221         {
3222           soname = elf_dt_name (abfd);
3223           if (soname == NULL || *soname == '\0')
3224             soname = bfd_get_filename (abfd);
3225         }
3226
3227       /* Save the SONAME because sometimes the linker emulation code
3228          will need to know it.  */
3229       elf_dt_name (abfd) = soname;
3230
3231       ret = elf_add_dt_needed_tag (info, soname, add_needed);
3232       if (ret < 0)
3233         goto error_return;
3234
3235       /* If we have already included this dynamic object in the
3236          link, just ignore it.  There is no reason to include a
3237          particular dynamic object more than once.  */
3238       if (ret > 0)
3239         return TRUE;
3240     }
3241
3242   /* If this is a dynamic object, we always link against the .dynsym
3243      symbol table, not the .symtab symbol table.  The dynamic linker
3244      will only see the .dynsym symbol table, so there is no reason to
3245      look at .symtab for a dynamic object.  */
3246
3247   if (! dynamic || elf_dynsymtab (abfd) == 0)
3248     hdr = &elf_tdata (abfd)->symtab_hdr;
3249   else
3250     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
3251
3252   symcount = hdr->sh_size / bed->s->sizeof_sym;
3253
3254   /* The sh_info field of the symtab header tells us where the
3255      external symbols start.  We don't care about the local symbols at
3256      this point.  */
3257   if (elf_bad_symtab (abfd))
3258     {
3259       extsymcount = symcount;
3260       extsymoff = 0;
3261     }
3262   else
3263     {
3264       extsymcount = symcount - hdr->sh_info;
3265       extsymoff = hdr->sh_info;
3266     }
3267
3268   sym_hash = NULL;
3269   if (extsymcount != 0)
3270     {
3271       isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
3272                                       NULL, NULL, NULL);
3273       if (isymbuf == NULL)
3274         goto error_return;
3275
3276       /* We store a pointer to the hash table entry for each external
3277          symbol.  */
3278       amt = extsymcount * sizeof (struct elf_link_hash_entry *);
3279       sym_hash = bfd_alloc (abfd, amt);
3280       if (sym_hash == NULL)
3281         goto error_free_sym;
3282       elf_sym_hashes (abfd) = sym_hash;
3283     }
3284
3285   if (dynamic)
3286     {
3287       /* Read in any version definitions.  */
3288       if (! _bfd_elf_slurp_version_tables (abfd))
3289         goto error_free_sym;
3290
3291       /* Read in the symbol versions, but don't bother to convert them
3292          to internal format.  */
3293       if (elf_dynversym (abfd) != 0)
3294         {
3295           Elf_Internal_Shdr *versymhdr;
3296
3297           versymhdr = &elf_tdata (abfd)->dynversym_hdr;
3298           extversym = bfd_malloc (versymhdr->sh_size);
3299           if (extversym == NULL)
3300             goto error_free_sym;
3301           amt = versymhdr->sh_size;
3302           if (bfd_seek (abfd, versymhdr->sh_offset, SEEK_SET) != 0
3303               || bfd_bread (extversym, amt, abfd) != amt)
3304             goto error_free_vers;
3305         }
3306     }
3307
3308   weaks = NULL;
3309
3310   ever = extversym != NULL ? extversym + extsymoff : NULL;
3311   for (isym = isymbuf, isymend = isymbuf + extsymcount;
3312        isym < isymend;
3313        isym++, sym_hash++, ever = (ever != NULL ? ever + 1 : NULL))
3314     {
3315       int bind;
3316       bfd_vma value;
3317       asection *sec;
3318       flagword flags;
3319       const char *name;
3320       struct elf_link_hash_entry *h;
3321       bfd_boolean definition;
3322       bfd_boolean size_change_ok;
3323       bfd_boolean type_change_ok;
3324       bfd_boolean new_weakdef;
3325       bfd_boolean override;
3326       unsigned int old_alignment;
3327       bfd *old_bfd;
3328
3329       override = FALSE;
3330
3331       flags = BSF_NO_FLAGS;
3332       sec = NULL;
3333       value = isym->st_value;
3334       *sym_hash = NULL;
3335
3336       bind = ELF_ST_BIND (isym->st_info);
3337       if (bind == STB_LOCAL)
3338         {
3339           /* This should be impossible, since ELF requires that all
3340              global symbols follow all local symbols, and that sh_info
3341              point to the first global symbol.  Unfortunately, Irix 5
3342              screws this up.  */
3343           continue;
3344         }
3345       else if (bind == STB_GLOBAL)
3346         {
3347           if (isym->st_shndx != SHN_UNDEF
3348               && isym->st_shndx != SHN_COMMON)
3349             flags = BSF_GLOBAL;
3350         }
3351       else if (bind == STB_WEAK)
3352         flags = BSF_WEAK;
3353       else
3354         {
3355           /* Leave it up to the processor backend.  */
3356         }
3357
3358       if (isym->st_shndx == SHN_UNDEF)
3359         sec = bfd_und_section_ptr;
3360       else if (isym->st_shndx < SHN_LORESERVE || isym->st_shndx > SHN_HIRESERVE)
3361         {
3362           sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
3363           if (sec == NULL)
3364             sec = bfd_abs_section_ptr;
3365           else if ((abfd->flags & (EXEC_P | DYNAMIC)) != 0)
3366             value -= sec->vma;
3367         }
3368       else if (isym->st_shndx == SHN_ABS)
3369         sec = bfd_abs_section_ptr;
3370       else if (isym->st_shndx == SHN_COMMON)
3371         {
3372           sec = bfd_com_section_ptr;
3373           /* What ELF calls the size we call the value.  What ELF
3374              calls the value we call the alignment.  */
3375           value = isym->st_size;
3376         }
3377       else
3378         {
3379           /* Leave it up to the processor backend.  */
3380         }
3381
3382       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
3383                                               isym->st_name);
3384       if (name == NULL)
3385         goto error_free_vers;
3386
3387       if (isym->st_shndx == SHN_COMMON
3388           && ELF_ST_TYPE (isym->st_info) == STT_TLS)
3389         {
3390           asection *tcomm = bfd_get_section_by_name (abfd, ".tcommon");
3391
3392           if (tcomm == NULL)
3393             {
3394               tcomm = bfd_make_section (abfd, ".tcommon");
3395               if (tcomm == NULL
3396                   || !bfd_set_section_flags (abfd, tcomm, (SEC_ALLOC
3397                                                            | SEC_IS_COMMON
3398                                                            | SEC_LINKER_CREATED
3399                                                            | SEC_THREAD_LOCAL)))
3400                 goto error_free_vers;
3401             }
3402           sec = tcomm;
3403         }
3404       else if (add_symbol_hook)
3405         {
3406           if (! (*add_symbol_hook) (abfd, info, isym, &name, &flags, &sec,
3407                                     &value))
3408             goto error_free_vers;
3409
3410           /* The hook function sets the name to NULL if this symbol
3411              should be skipped for some reason.  */
3412           if (name == NULL)
3413             continue;
3414         }
3415
3416       /* Sanity check that all possibilities were handled.  */
3417       if (sec == NULL)
3418         {
3419           bfd_set_error (bfd_error_bad_value);
3420           goto error_free_vers;
3421         }
3422
3423       if (bfd_is_und_section (sec)
3424           || bfd_is_com_section (sec))
3425         definition = FALSE;
3426       else
3427         definition = TRUE;
3428
3429       size_change_ok = FALSE;
3430       type_change_ok = get_elf_backend_data (abfd)->type_change_ok;
3431       old_alignment = 0;
3432       old_bfd = NULL;
3433
3434       if (is_elf_hash_table (hash_table))
3435         {
3436           Elf_Internal_Versym iver;
3437           unsigned int vernum = 0;
3438           bfd_boolean skip;
3439
3440           if (ever != NULL)
3441             {
3442               _bfd_elf_swap_versym_in (abfd, ever, &iver);
3443               vernum = iver.vs_vers & VERSYM_VERSION;
3444
3445               /* If this is a hidden symbol, or if it is not version
3446                  1, we append the version name to the symbol name.
3447                  However, we do not modify a non-hidden absolute
3448                  symbol, because it might be the version symbol
3449                  itself.  FIXME: What if it isn't?  */
3450               if ((iver.vs_vers & VERSYM_HIDDEN) != 0
3451                   || (vernum > 1 && ! bfd_is_abs_section (sec)))
3452                 {
3453                   const char *verstr;
3454                   size_t namelen, verlen, newlen;
3455                   char *newname, *p;
3456
3457                   if (isym->st_shndx != SHN_UNDEF)
3458                     {
3459                       if (vernum > elf_tdata (abfd)->dynverdef_hdr.sh_info)
3460                         {
3461                           (*_bfd_error_handler)
3462                             (_("%B: %s: invalid version %u (max %d)"),
3463                              abfd, name, vernum,
3464                              elf_tdata (abfd)->dynverdef_hdr.sh_info);
3465                           bfd_set_error (bfd_error_bad_value);
3466                           goto error_free_vers;
3467                         }
3468                       else if (vernum > 1)
3469                         verstr =
3470                           elf_tdata (abfd)->verdef[vernum - 1].vd_nodename;
3471                       else
3472                         verstr = "";
3473                     }
3474                   else
3475                     {
3476                       /* We cannot simply test for the number of
3477                          entries in the VERNEED section since the
3478                          numbers for the needed versions do not start
3479                          at 0.  */
3480                       Elf_Internal_Verneed *t;
3481
3482                       verstr = NULL;
3483                       for (t = elf_tdata (abfd)->verref;
3484                            t != NULL;
3485                            t = t->vn_nextref)
3486                         {
3487                           Elf_Internal_Vernaux *a;
3488
3489                           for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
3490                             {
3491                               if (a->vna_other == vernum)
3492                                 {
3493                                   verstr = a->vna_nodename;
3494                                   break;
3495                                 }
3496                             }
3497                           if (a != NULL)
3498                             break;
3499                         }
3500                       if (verstr == NULL)
3501                         {
3502                           (*_bfd_error_handler)
3503                             (_("%B: %s: invalid needed version %d"),
3504                              abfd, name, vernum);
3505                           bfd_set_error (bfd_error_bad_value);
3506                           goto error_free_vers;
3507                         }
3508                     }
3509
3510                   namelen = strlen (name);
3511                   verlen = strlen (verstr);
3512                   newlen = namelen + verlen + 2;
3513                   if ((iver.vs_vers & VERSYM_HIDDEN) == 0
3514                       && isym->st_shndx != SHN_UNDEF)
3515                     ++newlen;
3516
3517                   newname = bfd_alloc (abfd, newlen);
3518                   if (newname == NULL)
3519                     goto error_free_vers;
3520                   memcpy (newname, name, namelen);
3521                   p = newname + namelen;
3522                   *p++ = ELF_VER_CHR;
3523                   /* If this is a defined non-hidden version symbol,
3524                      we add another @ to the name.  This indicates the
3525                      default version of the symbol.  */
3526                   if ((iver.vs_vers & VERSYM_HIDDEN) == 0
3527                       && isym->st_shndx != SHN_UNDEF)
3528                     *p++ = ELF_VER_CHR;
3529                   memcpy (p, verstr, verlen + 1);
3530
3531                   name = newname;
3532                 }
3533             }
3534
3535           if (!_bfd_elf_merge_symbol (abfd, info, name, isym, &sec, &value,
3536                                       sym_hash, &skip, &override,
3537                                       &type_change_ok, &size_change_ok))
3538             goto error_free_vers;
3539
3540           if (skip)
3541             continue;
3542
3543           if (override)
3544             definition = FALSE;
3545
3546           h = *sym_hash;
3547           while (h->root.type == bfd_link_hash_indirect
3548                  || h->root.type == bfd_link_hash_warning)
3549             h = (struct elf_link_hash_entry *) h->root.u.i.link;
3550
3551           /* Remember the old alignment if this is a common symbol, so
3552              that we don't reduce the alignment later on.  We can't
3553              check later, because _bfd_generic_link_add_one_symbol
3554              will set a default for the alignment which we want to
3555              override. We also remember the old bfd where the existing
3556              definition comes from.  */
3557           switch (h->root.type)
3558             {
3559             default:
3560               break;
3561
3562             case bfd_link_hash_defined:
3563             case bfd_link_hash_defweak:
3564               old_bfd = h->root.u.def.section->owner;
3565               break;
3566
3567             case bfd_link_hash_common:
3568               old_bfd = h->root.u.c.p->section->owner;
3569               old_alignment = h->root.u.c.p->alignment_power;
3570               break;
3571             }
3572
3573           if (elf_tdata (abfd)->verdef != NULL
3574               && ! override
3575               && vernum > 1
3576               && definition)
3577             h->verinfo.verdef = &elf_tdata (abfd)->verdef[vernum - 1];
3578         }
3579
3580       if (! (_bfd_generic_link_add_one_symbol
3581              (info, abfd, name, flags, sec, value, NULL, FALSE, collect,
3582               (struct bfd_link_hash_entry **) sym_hash)))
3583         goto error_free_vers;
3584
3585       h = *sym_hash;
3586       while (h->root.type == bfd_link_hash_indirect
3587              || h->root.type == bfd_link_hash_warning)
3588         h = (struct elf_link_hash_entry *) h->root.u.i.link;
3589       *sym_hash = h;
3590
3591       new_weakdef = FALSE;
3592       if (dynamic
3593           && definition
3594           && (flags & BSF_WEAK) != 0
3595           && ELF_ST_TYPE (isym->st_info) != STT_FUNC
3596           && is_elf_hash_table (hash_table)
3597           && h->weakdef == NULL)
3598         {
3599           /* Keep a list of all weak defined non function symbols from
3600              a dynamic object, using the weakdef field.  Later in this
3601              function we will set the weakdef field to the correct
3602              value.  We only put non-function symbols from dynamic
3603              objects on this list, because that happens to be the only
3604              time we need to know the normal symbol corresponding to a
3605              weak symbol, and the information is time consuming to
3606              figure out.  If the weakdef field is not already NULL,
3607              then this symbol was already defined by some previous
3608              dynamic object, and we will be using that previous
3609              definition anyhow.  */
3610
3611           h->weakdef = weaks;
3612           weaks = h;
3613           new_weakdef = TRUE;
3614         }
3615
3616       /* Set the alignment of a common symbol.  */
3617       if (isym->st_shndx == SHN_COMMON
3618           && h->root.type == bfd_link_hash_common)
3619         {
3620           unsigned int align;
3621
3622           align = bfd_log2 (isym->st_value);
3623           if (align > old_alignment
3624               /* Permit an alignment power of zero if an alignment of one
3625                  is specified and no other alignments have been specified.  */
3626               || (isym->st_value == 1 && old_alignment == 0))
3627             h->root.u.c.p->alignment_power = align;
3628           else
3629             h->root.u.c.p->alignment_power = old_alignment;
3630         }
3631
3632       if (is_elf_hash_table (hash_table))
3633         {
3634           int old_flags;
3635           bfd_boolean dynsym;
3636           int new_flag;
3637
3638           /* Check the alignment when a common symbol is involved. This
3639              can change when a common symbol is overridden by a normal
3640              definition or a common symbol is ignored due to the old
3641              normal definition. We need to make sure the maximum
3642              alignment is maintained.  */
3643           if ((old_alignment || isym->st_shndx == SHN_COMMON)
3644               && h->root.type != bfd_link_hash_common)
3645             {
3646               unsigned int common_align;
3647               unsigned int normal_align;
3648               unsigned int symbol_align;
3649               bfd *normal_bfd;
3650               bfd *common_bfd;
3651
3652               symbol_align = ffs (h->root.u.def.value) - 1;
3653               if (h->root.u.def.section->owner != NULL
3654                   && (h->root.u.def.section->owner->flags & DYNAMIC) == 0)
3655                 {
3656                   normal_align = h->root.u.def.section->alignment_power;
3657                   if (normal_align > symbol_align)
3658                     normal_align = symbol_align;
3659                 }
3660               else
3661                 normal_align = symbol_align;
3662
3663               if (old_alignment)
3664                 {
3665                   common_align = old_alignment;
3666                   common_bfd = old_bfd;
3667                   normal_bfd = abfd;
3668                 }
3669               else
3670                 {
3671                   common_align = bfd_log2 (isym->st_value);
3672                   common_bfd = abfd;
3673                   normal_bfd = old_bfd;
3674                 }
3675
3676               if (normal_align < common_align)
3677                 (*_bfd_error_handler)
3678                   (_("Warning: alignment %u of symbol `%s' in %B"
3679                      " is smaller than %u in %B"),
3680                    normal_bfd, common_bfd,
3681                    1 << normal_align, name, 1 << common_align);
3682             }
3683
3684           /* Remember the symbol size and type.  */
3685           if (isym->st_size != 0
3686               && (definition || h->size == 0))
3687             {
3688               if (h->size != 0 && h->size != isym->st_size && ! size_change_ok)
3689                 (*_bfd_error_handler)
3690                   (_("Warning: size of symbol `%s' changed"
3691                      " from %lu in %B to %lu in %B"),
3692                    old_bfd, abfd,
3693                    name, (unsigned long) h->size,
3694                    (unsigned long) isym->st_size);
3695
3696               h->size = isym->st_size;
3697             }
3698
3699           /* If this is a common symbol, then we always want H->SIZE
3700              to be the size of the common symbol.  The code just above
3701              won't fix the size if a common symbol becomes larger.  We
3702              don't warn about a size change here, because that is
3703              covered by --warn-common.  */
3704           if (h->root.type == bfd_link_hash_common)
3705             h->size = h->root.u.c.size;
3706
3707           if (ELF_ST_TYPE (isym->st_info) != STT_NOTYPE
3708               && (definition || h->type == STT_NOTYPE))
3709             {
3710               if (h->type != STT_NOTYPE
3711                   && h->type != ELF_ST_TYPE (isym->st_info)
3712                   && ! type_change_ok)
3713                 (*_bfd_error_handler)
3714                   (_("Warning: type of symbol `%s' changed"
3715                      " from %d to %d in %B"),
3716                    abfd, name, h->type, ELF_ST_TYPE (isym->st_info));
3717
3718               h->type = ELF_ST_TYPE (isym->st_info);
3719             }
3720
3721           /* If st_other has a processor-specific meaning, specific
3722              code might be needed here. We never merge the visibility
3723              attribute with the one from a dynamic object.  */
3724           if (bed->elf_backend_merge_symbol_attribute)
3725             (*bed->elf_backend_merge_symbol_attribute) (h, isym, definition,
3726                                                         dynamic);
3727
3728           if (isym->st_other != 0 && !dynamic)
3729             {
3730               unsigned char hvis, symvis, other, nvis;
3731
3732               /* Take the balance of OTHER from the definition.  */
3733               other = (definition ? isym->st_other : h->other);
3734               other &= ~ ELF_ST_VISIBILITY (-1);
3735
3736               /* Combine visibilities, using the most constraining one.  */
3737               hvis   = ELF_ST_VISIBILITY (h->other);
3738               symvis = ELF_ST_VISIBILITY (isym->st_other);
3739               if (! hvis)
3740                 nvis = symvis;
3741               else if (! symvis)
3742                 nvis = hvis;
3743               else
3744                 nvis = hvis < symvis ? hvis : symvis;
3745
3746               h->other = other | nvis;
3747             }
3748
3749           /* Set a flag in the hash table entry indicating the type of
3750              reference or definition we just found.  Keep a count of
3751              the number of dynamic symbols we find.  A dynamic symbol
3752              is one which is referenced or defined by both a regular
3753              object and a shared object.  */
3754           old_flags = h->elf_link_hash_flags;
3755           dynsym = FALSE;
3756           if (! dynamic)
3757             {
3758               if (! definition)
3759                 {
3760                   new_flag = ELF_LINK_HASH_REF_REGULAR;
3761                   if (bind != STB_WEAK)
3762                     new_flag |= ELF_LINK_HASH_REF_REGULAR_NONWEAK;
3763                 }
3764               else
3765                 new_flag = ELF_LINK_HASH_DEF_REGULAR;
3766               if (! info->executable
3767                   || (old_flags & (ELF_LINK_HASH_DEF_DYNAMIC
3768                                    | ELF_LINK_HASH_REF_DYNAMIC)) != 0)
3769                 dynsym = TRUE;
3770             }
3771           else
3772             {
3773               if (! definition)
3774                 new_flag = ELF_LINK_HASH_REF_DYNAMIC;
3775               else
3776                 new_flag = ELF_LINK_HASH_DEF_DYNAMIC;
3777               if ((old_flags & (ELF_LINK_HASH_DEF_REGULAR
3778                                 | ELF_LINK_HASH_REF_REGULAR)) != 0
3779                   || (h->weakdef != NULL
3780                       && ! new_weakdef
3781                       && h->weakdef->dynindx != -1))
3782                 dynsym = TRUE;
3783             }
3784
3785           h->elf_link_hash_flags |= new_flag;
3786
3787           /* Check to see if we need to add an indirect symbol for
3788              the default name.  */
3789           if (definition || h->root.type == bfd_link_hash_common)
3790             if (!_bfd_elf_add_default_symbol (abfd, info, h, name, isym,
3791                                               &sec, &value, &dynsym,
3792                                               override))
3793               goto error_free_vers;
3794
3795           if (definition && !dynamic)
3796             {
3797               char *p = strchr (name, ELF_VER_CHR);
3798               if (p != NULL && p[1] != ELF_VER_CHR)
3799                 {
3800                   /* Queue non-default versions so that .symver x, x@FOO
3801                      aliases can be checked.  */
3802                   if (! nondeflt_vers)
3803                     {
3804                       amt = (isymend - isym + 1)
3805                             * sizeof (struct elf_link_hash_entry *);
3806                       nondeflt_vers = bfd_malloc (amt);
3807                     }
3808                   nondeflt_vers [nondeflt_vers_cnt++] = h;
3809                 }
3810             }
3811
3812           if (dynsym && h->dynindx == -1)
3813             {
3814               if (! bfd_elf_link_record_dynamic_symbol (info, h))
3815                 goto error_free_vers;
3816               if (h->weakdef != NULL
3817                   && ! new_weakdef
3818                   && h->weakdef->dynindx == -1)
3819                 {
3820                   if (! bfd_elf_link_record_dynamic_symbol (info, h->weakdef))
3821                     goto error_free_vers;
3822                 }
3823             }
3824           else if (dynsym && h->dynindx != -1)
3825             /* If the symbol already has a dynamic index, but
3826                visibility says it should not be visible, turn it into
3827                a local symbol.  */
3828             switch (ELF_ST_VISIBILITY (h->other))
3829               {
3830               case STV_INTERNAL:
3831               case STV_HIDDEN:
3832                 (*bed->elf_backend_hide_symbol) (info, h, TRUE);
3833                 dynsym = FALSE;
3834                 break;
3835               }
3836
3837           if (!add_needed
3838               && definition
3839               && dynsym
3840               && (h->elf_link_hash_flags
3841                   & ELF_LINK_HASH_REF_REGULAR) != 0)
3842             {
3843               int ret;
3844               const char *soname = elf_dt_name (abfd);
3845
3846               /* A symbol from a library loaded via DT_NEEDED of some
3847                  other library is referenced by a regular object.
3848                  Add a DT_NEEDED entry for it.  Issue an error if
3849                  --no-add-needed is used.  */
3850               if ((elf_dyn_lib_class (abfd) & DYN_NO_NEEDED) != 0)
3851                 {
3852                   (*_bfd_error_handler)
3853                     (_("%s: invalid DSO for symbol `%s' definition"),
3854                      abfd, name);
3855                   bfd_set_error (bfd_error_bad_value);
3856                   goto error_free_vers;
3857                 }
3858
3859               add_needed = TRUE;
3860               ret = elf_add_dt_needed_tag (info, soname, add_needed);
3861               if (ret < 0)
3862                 goto error_free_vers;
3863
3864               BFD_ASSERT (ret == 0);
3865             }
3866         }
3867     }
3868
3869   /* Now that all the symbols from this input file are created, handle
3870      .symver foo, foo@BAR such that any relocs against foo become foo@BAR.  */
3871   if (nondeflt_vers != NULL)
3872     {
3873       bfd_size_type cnt, symidx;
3874
3875       for (cnt = 0; cnt < nondeflt_vers_cnt; ++cnt)
3876         {
3877           struct elf_link_hash_entry *h = nondeflt_vers[cnt], *hi;
3878           char *shortname, *p;
3879
3880           p = strchr (h->root.root.string, ELF_VER_CHR);
3881           if (p == NULL
3882               || (h->root.type != bfd_link_hash_defined
3883                   && h->root.type != bfd_link_hash_defweak))
3884             continue;
3885
3886           amt = p - h->root.root.string;
3887           shortname = bfd_malloc (amt + 1);
3888           memcpy (shortname, h->root.root.string, amt);
3889           shortname[amt] = '\0';
3890
3891           hi = (struct elf_link_hash_entry *)
3892                bfd_link_hash_lookup (&hash_table->root, shortname,
3893                                      FALSE, FALSE, FALSE);
3894           if (hi != NULL
3895               && hi->root.type == h->root.type
3896               && hi->root.u.def.value == h->root.u.def.value
3897               && hi->root.u.def.section == h->root.u.def.section)
3898             {
3899               (*bed->elf_backend_hide_symbol) (info, hi, TRUE);
3900               hi->root.type = bfd_link_hash_indirect;
3901               hi->root.u.i.link = (struct bfd_link_hash_entry *) h;
3902               (*bed->elf_backend_copy_indirect_symbol) (bed, h, hi);
3903               sym_hash = elf_sym_hashes (abfd);
3904               if (sym_hash)
3905                 for (symidx = 0; symidx < extsymcount; ++symidx)
3906                   if (sym_hash[symidx] == hi)
3907                     {
3908                       sym_hash[symidx] = h;
3909                       break;
3910                     }
3911             }
3912           free (shortname);
3913         }
3914       free (nondeflt_vers);
3915       nondeflt_vers = NULL;
3916     }
3917
3918   if (extversym != NULL)
3919     {
3920       free (extversym);
3921       extversym = NULL;
3922     }
3923
3924   if (isymbuf != NULL)
3925     free (isymbuf);
3926   isymbuf = NULL;
3927
3928   /* Now set the weakdefs field correctly for all the weak defined
3929      symbols we found.  The only way to do this is to search all the
3930      symbols.  Since we only need the information for non functions in
3931      dynamic objects, that's the only time we actually put anything on
3932      the list WEAKS.  We need this information so that if a regular
3933      object refers to a symbol defined weakly in a dynamic object, the
3934      real symbol in the dynamic object is also put in the dynamic
3935      symbols; we also must arrange for both symbols to point to the
3936      same memory location.  We could handle the general case of symbol
3937      aliasing, but a general symbol alias can only be generated in
3938      assembler code, handling it correctly would be very time
3939      consuming, and other ELF linkers don't handle general aliasing
3940      either.  */
3941   if (weaks != NULL)
3942     {
3943       struct elf_link_hash_entry **hpp;
3944       struct elf_link_hash_entry **hppend;
3945       struct elf_link_hash_entry **sorted_sym_hash;
3946       struct elf_link_hash_entry *h;
3947       size_t sym_count;
3948
3949       /* Since we have to search the whole symbol list for each weak
3950          defined symbol, search time for N weak defined symbols will be
3951          O(N^2). Binary search will cut it down to O(NlogN).  */
3952       amt = extsymcount * sizeof (struct elf_link_hash_entry *);
3953       sorted_sym_hash = bfd_malloc (amt);
3954       if (sorted_sym_hash == NULL)
3955         goto error_return;
3956       sym_hash = sorted_sym_hash;
3957       hpp = elf_sym_hashes (abfd);
3958       hppend = hpp + extsymcount;
3959       sym_count = 0;
3960       for (; hpp < hppend; hpp++)
3961         {
3962           h = *hpp;
3963           if (h != NULL
3964               && h->root.type == bfd_link_hash_defined
3965               && h->type != STT_FUNC)
3966             {
3967               *sym_hash = h;
3968               sym_hash++;
3969               sym_count++;
3970             }
3971         }
3972
3973       qsort (sorted_sym_hash, sym_count,
3974              sizeof (struct elf_link_hash_entry *),
3975              elf_sort_symbol);
3976
3977       while (weaks != NULL)
3978         {
3979           struct elf_link_hash_entry *hlook;
3980           asection *slook;
3981           bfd_vma vlook;
3982           long ilook;
3983           size_t i, j, idx;
3984
3985           hlook = weaks;
3986           weaks = hlook->weakdef;
3987           hlook->weakdef = NULL;
3988
3989           BFD_ASSERT (hlook->root.type == bfd_link_hash_defined
3990                       || hlook->root.type == bfd_link_hash_defweak
3991                       || hlook->root.type == bfd_link_hash_common
3992                       || hlook->root.type == bfd_link_hash_indirect);
3993           slook = hlook->root.u.def.section;
3994           vlook = hlook->root.u.def.value;
3995
3996           ilook = -1;
3997           i = 0;
3998           j = sym_count;
3999           while (i < j)
4000             {
4001               bfd_signed_vma vdiff;
4002               idx = (i + j) / 2;
4003               h = sorted_sym_hash [idx];
4004               vdiff = vlook - h->root.u.def.value;
4005               if (vdiff < 0)
4006                 j = idx;
4007               else if (vdiff > 0)
4008                 i = idx + 1;
4009               else
4010                 {
4011                   long sdiff = slook->id - h->root.u.def.section->id;
4012                   if (sdiff < 0)
4013                     j = idx;
4014                   else if (sdiff > 0)
4015                     i = idx + 1;
4016                   else
4017                     {
4018                       ilook = idx;
4019                       break;
4020                     }
4021                 }
4022             }
4023
4024           /* We didn't find a value/section match.  */
4025           if (ilook == -1)
4026             continue;
4027
4028           for (i = ilook; i < sym_count; i++)
4029             {
4030               h = sorted_sym_hash [i];
4031
4032               /* Stop if value or section doesn't match.  */
4033               if (h->root.u.def.value != vlook
4034                   || h->root.u.def.section != slook)
4035                 break;
4036               else if (h != hlook)
4037                 {
4038                   hlook->weakdef = h;
4039
4040                   /* If the weak definition is in the list of dynamic
4041                      symbols, make sure the real definition is put
4042                      there as well.  */
4043                   if (hlook->dynindx != -1 && h->dynindx == -1)
4044                     {
4045                       if (! bfd_elf_link_record_dynamic_symbol (info, h))
4046                         goto error_return;
4047                     }
4048
4049                   /* If the real definition is in the list of dynamic
4050                      symbols, make sure the weak definition is put
4051                      there as well.  If we don't do this, then the
4052                      dynamic loader might not merge the entries for the
4053                      real definition and the weak definition.  */
4054                   if (h->dynindx != -1 && hlook->dynindx == -1)
4055                     {
4056                       if (! bfd_elf_link_record_dynamic_symbol (info, hlook))
4057                         goto error_return;
4058                     }
4059                   break;
4060                 }
4061             }
4062         }
4063
4064       free (sorted_sym_hash);
4065     }
4066
4067   check_directives = get_elf_backend_data (abfd)->check_directives;
4068   if (check_directives)
4069     check_directives (abfd, info);
4070
4071   /* If this object is the same format as the output object, and it is
4072      not a shared library, then let the backend look through the
4073      relocs.
4074
4075      This is required to build global offset table entries and to
4076      arrange for dynamic relocs.  It is not required for the
4077      particular common case of linking non PIC code, even when linking
4078      against shared libraries, but unfortunately there is no way of
4079      knowing whether an object file has been compiled PIC or not.
4080      Looking through the relocs is not particularly time consuming.
4081      The problem is that we must either (1) keep the relocs in memory,
4082      which causes the linker to require additional runtime memory or
4083      (2) read the relocs twice from the input file, which wastes time.
4084      This would be a good case for using mmap.
4085
4086      I have no idea how to handle linking PIC code into a file of a
4087      different format.  It probably can't be done.  */
4088   check_relocs = get_elf_backend_data (abfd)->check_relocs;
4089   if (! dynamic
4090       && is_elf_hash_table (hash_table)
4091       && hash_table->root.creator == abfd->xvec
4092       && check_relocs != NULL)
4093     {
4094       asection *o;
4095
4096       for (o = abfd->sections; o != NULL; o = o->next)
4097         {
4098           Elf_Internal_Rela *internal_relocs;
4099           bfd_boolean ok;
4100
4101           if ((o->flags & SEC_RELOC) == 0
4102               || o->reloc_count == 0
4103               || ((info->strip == strip_all || info->strip == strip_debugger)
4104                   && (o->flags & SEC_DEBUGGING) != 0)
4105               || bfd_is_abs_section (o->output_section))
4106             continue;
4107
4108           internal_relocs = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
4109                                                        info->keep_memory);
4110           if (internal_relocs == NULL)
4111             goto error_return;
4112
4113           ok = (*check_relocs) (abfd, info, o, internal_relocs);
4114
4115           if (elf_section_data (o)->relocs != internal_relocs)
4116             free (internal_relocs);
4117
4118           if (! ok)
4119             goto error_return;
4120         }
4121     }
4122
4123   /* If this is a non-traditional link, try to optimize the handling
4124      of the .stab/.stabstr sections.  */
4125   if (! dynamic
4126       && ! info->traditional_format
4127       && is_elf_hash_table (hash_table)
4128       && (info->strip != strip_all && info->strip != strip_debugger))
4129     {
4130       asection *stabstr;
4131
4132       stabstr = bfd_get_section_by_name (abfd, ".stabstr");
4133       if (stabstr != NULL)
4134         {
4135           bfd_size_type string_offset = 0;
4136           asection *stab;
4137
4138           for (stab = abfd->sections; stab; stab = stab->next)
4139             if (strncmp (".stab", stab->name, 5) == 0
4140                 && (!stab->name[5] ||
4141                     (stab->name[5] == '.' && ISDIGIT (stab->name[6])))
4142                 && (stab->flags & SEC_MERGE) == 0
4143                 && !bfd_is_abs_section (stab->output_section))
4144               {
4145                 struct bfd_elf_section_data *secdata;
4146
4147                 secdata = elf_section_data (stab);
4148                 if (! _bfd_link_section_stabs (abfd,
4149                                                &hash_table->stab_info,
4150                                                stab, stabstr,
4151                                                &secdata->sec_info,
4152                                                &string_offset))
4153                   goto error_return;
4154                 if (secdata->sec_info)
4155                   stab->sec_info_type = ELF_INFO_TYPE_STABS;
4156             }
4157         }
4158     }
4159
4160   if (is_elf_hash_table (hash_table))
4161     {
4162       /* Add this bfd to the loaded list.  */
4163       struct elf_link_loaded_list *n;
4164
4165       n = bfd_alloc (abfd, sizeof (struct elf_link_loaded_list));
4166       if (n == NULL)
4167         goto error_return;
4168       n->abfd = abfd;
4169       n->next = hash_table->loaded;
4170       hash_table->loaded = n;
4171     }
4172
4173   return TRUE;
4174
4175  error_free_vers:
4176   if (nondeflt_vers != NULL)
4177     free (nondeflt_vers);
4178   if (extversym != NULL)
4179     free (extversym);
4180  error_free_sym:
4181   if (isymbuf != NULL)
4182     free (isymbuf);
4183  error_return:
4184   return FALSE;
4185 }
4186
4187 /* Return the linker hash table entry of a symbol that might be
4188    satisfied by an archive symbol.  Return -1 on error.  */
4189
4190 struct elf_link_hash_entry *
4191 _bfd_elf_archive_symbol_lookup (bfd *abfd,
4192                                 struct bfd_link_info *info,
4193                                 const char *name)
4194 {
4195   struct elf_link_hash_entry *h;
4196   char *p, *copy;
4197   size_t len, first;
4198
4199   h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, FALSE);
4200   if (h != NULL)
4201     return h;
4202
4203   /* If this is a default version (the name contains @@), look up the
4204      symbol again with only one `@' as well as without the version.
4205      The effect is that references to the symbol with and without the
4206      version will be matched by the default symbol in the archive.  */
4207
4208   p = strchr (name, ELF_VER_CHR);
4209   if (p == NULL || p[1] != ELF_VER_CHR)
4210     return h;
4211
4212   /* First check with only one `@'.  */
4213   len = strlen (name);
4214   copy = bfd_alloc (abfd, len);
4215   if (copy == NULL)
4216     return (struct elf_link_hash_entry *) 0 - 1;
4217
4218   first = p - name + 1;
4219   memcpy (copy, name, first);
4220   memcpy (copy + first, name + first + 1, len - first);
4221
4222   h = elf_link_hash_lookup (elf_hash_table (info), copy, FALSE, FALSE, FALSE);
4223   if (h == NULL)
4224     {
4225       /* We also need to check references to the symbol without the
4226          version.  */
4227       copy[first - 1] = '\0';
4228       h = elf_link_hash_lookup (elf_hash_table (info), copy,
4229                                 FALSE, FALSE, FALSE);
4230     }
4231
4232   bfd_release (abfd, copy);
4233   return h;
4234 }
4235
4236 /* Add symbols from an ELF archive file to the linker hash table.  We
4237    don't use _bfd_generic_link_add_archive_symbols because of a
4238    problem which arises on UnixWare.  The UnixWare libc.so is an
4239    archive which includes an entry libc.so.1 which defines a bunch of
4240    symbols.  The libc.so archive also includes a number of other
4241    object files, which also define symbols, some of which are the same
4242    as those defined in libc.so.1.  Correct linking requires that we
4243    consider each object file in turn, and include it if it defines any
4244    symbols we need.  _bfd_generic_link_add_archive_symbols does not do
4245    this; it looks through the list of undefined symbols, and includes
4246    any object file which defines them.  When this algorithm is used on
4247    UnixWare, it winds up pulling in libc.so.1 early and defining a
4248    bunch of symbols.  This means that some of the other objects in the
4249    archive are not included in the link, which is incorrect since they
4250    precede libc.so.1 in the archive.
4251
4252    Fortunately, ELF archive handling is simpler than that done by
4253    _bfd_generic_link_add_archive_symbols, which has to allow for a.out
4254    oddities.  In ELF, if we find a symbol in the archive map, and the
4255    symbol is currently undefined, we know that we must pull in that
4256    object file.
4257
4258    Unfortunately, we do have to make multiple passes over the symbol
4259    table until nothing further is resolved.  */
4260
4261 static bfd_boolean
4262 elf_link_add_archive_symbols (bfd *abfd, struct bfd_link_info *info)
4263 {
4264   symindex c;
4265   bfd_boolean *defined = NULL;
4266   bfd_boolean *included = NULL;
4267   carsym *symdefs;
4268   bfd_boolean loop;
4269   bfd_size_type amt;
4270   const struct elf_backend_data *bed;
4271   struct elf_link_hash_entry * (*archive_symbol_lookup)
4272     (bfd *, struct bfd_link_info *, const char *);
4273
4274   if (! bfd_has_map (abfd))
4275     {
4276       /* An empty archive is a special case.  */
4277       if (bfd_openr_next_archived_file (abfd, NULL) == NULL)
4278         return TRUE;
4279       bfd_set_error (bfd_error_no_armap);
4280       return FALSE;
4281     }
4282
4283   /* Keep track of all symbols we know to be already defined, and all
4284      files we know to be already included.  This is to speed up the
4285      second and subsequent passes.  */
4286   c = bfd_ardata (abfd)->symdef_count;
4287   if (c == 0)
4288     return TRUE;
4289   amt = c;
4290   amt *= sizeof (bfd_boolean);
4291   defined = bfd_zmalloc (amt);
4292   included = bfd_zmalloc (amt);
4293   if (defined == NULL || included == NULL)
4294     goto error_return;
4295
4296   symdefs = bfd_ardata (abfd)->symdefs;
4297   bed = get_elf_backend_data (abfd);
4298   archive_symbol_lookup = bed->elf_backend_archive_symbol_lookup;
4299
4300   do
4301     {
4302       file_ptr last;
4303       symindex i;
4304       carsym *symdef;
4305       carsym *symdefend;
4306
4307       loop = FALSE;
4308       last = -1;
4309
4310       symdef = symdefs;
4311       symdefend = symdef + c;
4312       for (i = 0; symdef < symdefend; symdef++, i++)
4313         {
4314           struct elf_link_hash_entry *h;
4315           bfd *element;
4316           struct bfd_link_hash_entry *undefs_tail;
4317           symindex mark;
4318
4319           if (defined[i] || included[i])
4320             continue;
4321           if (symdef->file_offset == last)
4322             {
4323               included[i] = TRUE;
4324               continue;
4325             }
4326
4327           h = archive_symbol_lookup (abfd, info, symdef->name);
4328           if (h == (struct elf_link_hash_entry *) 0 - 1)
4329             goto error_return;
4330
4331           if (h == NULL)
4332             continue;
4333
4334           if (h->root.type == bfd_link_hash_common)
4335             {
4336               /* We currently have a common symbol.  The archive map contains
4337                  a reference to this symbol, so we may want to include it.  We
4338                  only want to include it however, if this archive element
4339                  contains a definition of the symbol, not just another common
4340                  declaration of it.
4341
4342                  Unfortunately some archivers (including GNU ar) will put
4343                  declarations of common symbols into their archive maps, as
4344                  well as real definitions, so we cannot just go by the archive
4345                  map alone.  Instead we must read in the element's symbol
4346                  table and check that to see what kind of symbol definition
4347                  this is.  */
4348               if (! elf_link_is_defined_archive_symbol (abfd, symdef))
4349                 continue;
4350             }
4351           else if (h->root.type != bfd_link_hash_undefined)
4352             {
4353               if (h->root.type != bfd_link_hash_undefweak)
4354                 defined[i] = TRUE;
4355               continue;
4356             }
4357
4358           /* We need to include this archive member.  */
4359           element = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
4360           if (element == NULL)
4361             goto error_return;
4362
4363           if (! bfd_check_format (element, bfd_object))
4364             goto error_return;
4365
4366           /* Doublecheck that we have not included this object
4367              already--it should be impossible, but there may be
4368              something wrong with the archive.  */
4369           if (element->archive_pass != 0)
4370             {
4371               bfd_set_error (bfd_error_bad_value);
4372               goto error_return;
4373             }
4374           element->archive_pass = 1;
4375
4376           undefs_tail = info->hash->undefs_tail;
4377
4378           if (! (*info->callbacks->add_archive_element) (info, element,
4379                                                          symdef->name))
4380             goto error_return;
4381           if (! bfd_link_add_symbols (element, info))
4382             goto error_return;
4383
4384           /* If there are any new undefined symbols, we need to make
4385              another pass through the archive in order to see whether
4386              they can be defined.  FIXME: This isn't perfect, because
4387              common symbols wind up on undefs_tail and because an
4388              undefined symbol which is defined later on in this pass
4389              does not require another pass.  This isn't a bug, but it
4390              does make the code less efficient than it could be.  */
4391           if (undefs_tail != info->hash->undefs_tail)
4392             loop = TRUE;
4393
4394           /* Look backward to mark all symbols from this object file
4395              which we have already seen in this pass.  */
4396           mark = i;
4397           do
4398             {
4399               included[mark] = TRUE;
4400               if (mark == 0)
4401                 break;
4402               --mark;
4403             }
4404           while (symdefs[mark].file_offset == symdef->file_offset);
4405
4406           /* We mark subsequent symbols from this object file as we go
4407              on through the loop.  */
4408           last = symdef->file_offset;
4409         }
4410     }
4411   while (loop);
4412
4413   free (defined);
4414   free (included);
4415
4416   return TRUE;
4417
4418  error_return:
4419   if (defined != NULL)
4420     free (defined);
4421   if (included != NULL)
4422     free (included);
4423   return FALSE;
4424 }
4425
4426 /* Given an ELF BFD, add symbols to the global hash table as
4427    appropriate.  */
4428
4429 bfd_boolean
4430 bfd_elf_link_add_symbols (bfd *abfd, struct bfd_link_info *info)
4431 {
4432   switch (bfd_get_format (abfd))
4433     {
4434     case bfd_object:
4435       return elf_link_add_object_symbols (abfd, info);
4436     case bfd_archive:
4437       return elf_link_add_archive_symbols (abfd, info);
4438     default:
4439       bfd_set_error (bfd_error_wrong_format);
4440       return FALSE;
4441     }
4442 }
4443 \f
4444 /* This function will be called though elf_link_hash_traverse to store
4445    all hash value of the exported symbols in an array.  */
4446
4447 static bfd_boolean
4448 elf_collect_hash_codes (struct elf_link_hash_entry *h, void *data)
4449 {
4450   unsigned long **valuep = data;
4451   const char *name;
4452   char *p;
4453   unsigned long ha;
4454   char *alc = NULL;
4455
4456   if (h->root.type == bfd_link_hash_warning)
4457     h = (struct elf_link_hash_entry *) h->root.u.i.link;
4458
4459   /* Ignore indirect symbols.  These are added by the versioning code.  */
4460   if (h->dynindx == -1)
4461     return TRUE;
4462
4463   name = h->root.root.string;
4464   p = strchr (name, ELF_VER_CHR);
4465   if (p != NULL)
4466     {
4467       alc = bfd_malloc (p - name + 1);
4468       memcpy (alc, name, p - name);
4469       alc[p - name] = '\0';
4470       name = alc;
4471     }
4472
4473   /* Compute the hash value.  */
4474   ha = bfd_elf_hash (name);
4475
4476   /* Store the found hash value in the array given as the argument.  */
4477   *(*valuep)++ = ha;
4478
4479   /* And store it in the struct so that we can put it in the hash table
4480      later.  */
4481   h->elf_hash_value = ha;
4482
4483   if (alc != NULL)
4484     free (alc);
4485
4486   return TRUE;
4487 }
4488
4489 /* Array used to determine the number of hash table buckets to use
4490    based on the number of symbols there are.  If there are fewer than
4491    3 symbols we use 1 bucket, fewer than 17 symbols we use 3 buckets,
4492    fewer than 37 we use 17 buckets, and so forth.  We never use more
4493    than 32771 buckets.  */
4494
4495 static const size_t elf_buckets[] =
4496 {
4497   1, 3, 17, 37, 67, 97, 131, 197, 263, 521, 1031, 2053, 4099, 8209,
4498   16411, 32771, 0
4499 };
4500
4501 /* Compute bucket count for hashing table.  We do not use a static set
4502    of possible tables sizes anymore.  Instead we determine for all
4503    possible reasonable sizes of the table the outcome (i.e., the
4504    number of collisions etc) and choose the best solution.  The
4505    weighting functions are not too simple to allow the table to grow
4506    without bounds.  Instead one of the weighting factors is the size.
4507    Therefore the result is always a good payoff between few collisions
4508    (= short chain lengths) and table size.  */
4509 static size_t
4510 compute_bucket_count (struct bfd_link_info *info)
4511 {
4512   size_t dynsymcount = elf_hash_table (info)->dynsymcount;
4513   size_t best_size = 0;
4514   unsigned long int *hashcodes;
4515   unsigned long int *hashcodesp;
4516   unsigned long int i;
4517   bfd_size_type amt;
4518
4519   /* Compute the hash values for all exported symbols.  At the same
4520      time store the values in an array so that we could use them for
4521      optimizations.  */
4522   amt = dynsymcount;
4523   amt *= sizeof (unsigned long int);
4524   hashcodes = bfd_malloc (amt);
4525   if (hashcodes == NULL)
4526     return 0;
4527   hashcodesp = hashcodes;
4528
4529   /* Put all hash values in HASHCODES.  */
4530   elf_link_hash_traverse (elf_hash_table (info),
4531                           elf_collect_hash_codes, &hashcodesp);
4532
4533   /* We have a problem here.  The following code to optimize the table
4534      size requires an integer type with more the 32 bits.  If
4535      BFD_HOST_U_64_BIT is set we know about such a type.  */
4536 #ifdef BFD_HOST_U_64_BIT
4537   if (info->optimize)
4538     {
4539       unsigned long int nsyms = hashcodesp - hashcodes;
4540       size_t minsize;
4541       size_t maxsize;
4542       BFD_HOST_U_64_BIT best_chlen = ~((BFD_HOST_U_64_BIT) 0);
4543       unsigned long int *counts ;
4544       bfd *dynobj = elf_hash_table (info)->dynobj;
4545       const struct elf_backend_data *bed = get_elf_backend_data (dynobj);
4546
4547       /* Possible optimization parameters: if we have NSYMS symbols we say
4548          that the hashing table must at least have NSYMS/4 and at most
4549          2*NSYMS buckets.  */
4550       minsize = nsyms / 4;
4551       if (minsize == 0)
4552         minsize = 1;
4553       best_size = maxsize = nsyms * 2;
4554
4555       /* Create array where we count the collisions in.  We must use bfd_malloc
4556          since the size could be large.  */
4557       amt = maxsize;
4558       amt *= sizeof (unsigned long int);
4559       counts = bfd_malloc (amt);
4560       if (counts == NULL)
4561         {
4562           free (hashcodes);
4563           return 0;
4564         }
4565
4566       /* Compute the "optimal" size for the hash table.  The criteria is a
4567          minimal chain length.  The minor criteria is (of course) the size
4568          of the table.  */
4569       for (i = minsize; i < maxsize; ++i)
4570         {
4571           /* Walk through the array of hashcodes and count the collisions.  */
4572           BFD_HOST_U_64_BIT max;
4573           unsigned long int j;
4574           unsigned long int fact;
4575
4576           memset (counts, '\0', i * sizeof (unsigned long int));
4577
4578           /* Determine how often each hash bucket is used.  */
4579           for (j = 0; j < nsyms; ++j)
4580             ++counts[hashcodes[j] % i];
4581
4582           /* For the weight function we need some information about the
4583              pagesize on the target.  This is information need not be 100%
4584              accurate.  Since this information is not available (so far) we
4585              define it here to a reasonable default value.  If it is crucial
4586              to have a better value some day simply define this value.  */
4587 # ifndef BFD_TARGET_PAGESIZE
4588 #  define BFD_TARGET_PAGESIZE   (4096)
4589 # endif
4590
4591           /* We in any case need 2 + NSYMS entries for the size values and
4592              the chains.  */
4593           max = (2 + nsyms) * (bed->s->arch_size / 8);
4594
4595 # if 1
4596           /* Variant 1: optimize for short chains.  We add the squares
4597              of all the chain lengths (which favors many small chain
4598              over a few long chains).  */
4599           for (j = 0; j < i; ++j)
4600             max += counts[j] * counts[j];
4601
4602           /* This adds penalties for the overall size of the table.  */
4603           fact = i / (BFD_TARGET_PAGESIZE / (bed->s->arch_size / 8)) + 1;
4604           max *= fact * fact;
4605 # else
4606           /* Variant 2: Optimize a lot more for small table.  Here we
4607              also add squares of the size but we also add penalties for
4608              empty slots (the +1 term).  */
4609           for (j = 0; j < i; ++j)
4610             max += (1 + counts[j]) * (1 + counts[j]);
4611
4612           /* The overall size of the table is considered, but not as
4613              strong as in variant 1, where it is squared.  */
4614           fact = i / (BFD_TARGET_PAGESIZE / (bed->s->arch_size / 8)) + 1;
4615           max *= fact;
4616 # endif
4617
4618           /* Compare with current best results.  */
4619           if (max < best_chlen)
4620             {
4621               best_chlen = max;
4622               best_size = i;
4623             }
4624         }
4625
4626       free (counts);
4627     }
4628   else
4629 #endif /* defined (BFD_HOST_U_64_BIT) */
4630     {
4631       /* This is the fallback solution if no 64bit type is available or if we
4632          are not supposed to spend much time on optimizations.  We select the
4633          bucket count using a fixed set of numbers.  */
4634       for (i = 0; elf_buckets[i] != 0; i++)
4635         {
4636           best_size = elf_buckets[i];
4637           if (dynsymcount < elf_buckets[i + 1])
4638             break;
4639         }
4640     }
4641
4642   /* Free the arrays we needed.  */
4643   free (hashcodes);
4644
4645   return best_size;
4646 }
4647
4648 /* Set up the sizes and contents of the ELF dynamic sections.  This is
4649    called by the ELF linker emulation before_allocation routine.  We
4650    must set the sizes of the sections before the linker sets the
4651    addresses of the various sections.  */
4652
4653 bfd_boolean
4654 bfd_elf_size_dynamic_sections (bfd *output_bfd,
4655                                const char *soname,
4656                                const char *rpath,
4657                                const char *filter_shlib,
4658                                const char * const *auxiliary_filters,
4659                                struct bfd_link_info *info,
4660                                asection **sinterpptr,
4661                                struct bfd_elf_version_tree *verdefs)
4662 {
4663   bfd_size_type soname_indx;
4664   bfd *dynobj;
4665   const struct elf_backend_data *bed;
4666   struct elf_assign_sym_version_info asvinfo;
4667
4668   *sinterpptr = NULL;
4669
4670   soname_indx = (bfd_size_type) -1;
4671
4672   if (!is_elf_hash_table (info->hash))
4673     return TRUE;
4674
4675   elf_tdata (output_bfd)->relro = info->relro;
4676   if (info->execstack)
4677     elf_tdata (output_bfd)->stack_flags = PF_R | PF_W | PF_X;
4678   else if (info->noexecstack)
4679     elf_tdata (output_bfd)->stack_flags = PF_R | PF_W;
4680   else
4681     {
4682       bfd *inputobj;
4683       asection *notesec = NULL;
4684       int exec = 0;
4685
4686       for (inputobj = info->input_bfds;
4687            inputobj;
4688            inputobj = inputobj->link_next)
4689         {
4690           asection *s;
4691
4692           if (inputobj->flags & DYNAMIC)
4693             continue;
4694           s = bfd_get_section_by_name (inputobj, ".note.GNU-stack");
4695           if (s)
4696             {
4697               if (s->flags & SEC_CODE)
4698                 exec = PF_X;
4699               notesec = s;
4700             }
4701           else
4702             exec = PF_X;
4703         }
4704       if (notesec)
4705         {
4706           elf_tdata (output_bfd)->stack_flags = PF_R | PF_W | exec;
4707           if (exec && info->relocatable
4708               && notesec->output_section != bfd_abs_section_ptr)
4709             notesec->output_section->flags |= SEC_CODE;
4710         }
4711     }
4712
4713   /* Any syms created from now on start with -1 in
4714      got.refcount/offset and plt.refcount/offset.  */
4715   elf_hash_table (info)->init_refcount = elf_hash_table (info)->init_offset;
4716
4717   /* The backend may have to create some sections regardless of whether
4718      we're dynamic or not.  */
4719   bed = get_elf_backend_data (output_bfd);
4720   if (bed->elf_backend_always_size_sections
4721       && ! (*bed->elf_backend_always_size_sections) (output_bfd, info))
4722     return FALSE;
4723
4724   dynobj = elf_hash_table (info)->dynobj;
4725
4726   /* If there were no dynamic objects in the link, there is nothing to
4727      do here.  */
4728   if (dynobj == NULL)
4729     return TRUE;
4730
4731   if (! _bfd_elf_maybe_strip_eh_frame_hdr (info))
4732     return FALSE;
4733
4734   if (elf_hash_table (info)->dynamic_sections_created)
4735     {
4736       struct elf_info_failed eif;
4737       struct elf_link_hash_entry *h;
4738       asection *dynstr;
4739       struct bfd_elf_version_tree *t;
4740       struct bfd_elf_version_expr *d;
4741       bfd_boolean all_defined;
4742
4743       *sinterpptr = bfd_get_section_by_name (dynobj, ".interp");
4744       BFD_ASSERT (*sinterpptr != NULL || !info->executable);
4745
4746       if (soname != NULL)
4747         {
4748           soname_indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
4749                                              soname, TRUE);
4750           if (soname_indx == (bfd_size_type) -1
4751               || !_bfd_elf_add_dynamic_entry (info, DT_SONAME, soname_indx))
4752             return FALSE;
4753         }
4754
4755       if (info->symbolic)
4756         {
4757           if (!_bfd_elf_add_dynamic_entry (info, DT_SYMBOLIC, 0))
4758             return FALSE;
4759           info->flags |= DF_SYMBOLIC;
4760         }
4761
4762       if (rpath != NULL)
4763         {
4764           bfd_size_type indx;
4765
4766           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, rpath,
4767                                       TRUE);
4768           if (indx == (bfd_size_type) -1
4769               || !_bfd_elf_add_dynamic_entry (info, DT_RPATH, indx))
4770             return FALSE;
4771
4772           if  (info->new_dtags)
4773             {
4774               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr, indx);
4775               if (!_bfd_elf_add_dynamic_entry (info, DT_RUNPATH, indx))
4776                 return FALSE;
4777             }
4778         }
4779
4780       if (filter_shlib != NULL)
4781         {
4782           bfd_size_type indx;
4783
4784           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
4785                                       filter_shlib, TRUE);
4786           if (indx == (bfd_size_type) -1
4787               || !_bfd_elf_add_dynamic_entry (info, DT_FILTER, indx))
4788             return FALSE;
4789         }
4790
4791       if (auxiliary_filters != NULL)
4792         {
4793           const char * const *p;
4794
4795           for (p = auxiliary_filters; *p != NULL; p++)
4796             {
4797               bfd_size_type indx;
4798
4799               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
4800                                           *p, TRUE);
4801               if (indx == (bfd_size_type) -1
4802                   || !_bfd_elf_add_dynamic_entry (info, DT_AUXILIARY, indx))
4803                 return FALSE;
4804             }
4805         }
4806
4807       eif.info = info;
4808       eif.verdefs = verdefs;
4809       eif.failed = FALSE;
4810
4811       /* If we are supposed to export all symbols into the dynamic symbol
4812          table (this is not the normal case), then do so.  */
4813       if (info->export_dynamic)
4814         {
4815           elf_link_hash_traverse (elf_hash_table (info),
4816                                   _bfd_elf_export_symbol,
4817                                   &eif);
4818           if (eif.failed)
4819             return FALSE;
4820         }
4821
4822       /* Make all global versions with definition.  */
4823       for (t = verdefs; t != NULL; t = t->next)
4824         for (d = t->globals.list; d != NULL; d = d->next)
4825           if (!d->symver && d->symbol)
4826             {
4827               const char *verstr, *name;
4828               size_t namelen, verlen, newlen;
4829               char *newname, *p;
4830               struct elf_link_hash_entry *newh;
4831
4832               name = d->symbol;
4833               namelen = strlen (name);
4834               verstr = t->name;
4835               verlen = strlen (verstr);
4836               newlen = namelen + verlen + 3;
4837
4838               newname = bfd_malloc (newlen);
4839               if (newname == NULL)
4840                 return FALSE;
4841               memcpy (newname, name, namelen);
4842
4843               /* Check the hidden versioned definition.  */
4844               p = newname + namelen;
4845               *p++ = ELF_VER_CHR;
4846               memcpy (p, verstr, verlen + 1);
4847               newh = elf_link_hash_lookup (elf_hash_table (info),
4848                                            newname, FALSE, FALSE,
4849                                            FALSE);
4850               if (newh == NULL
4851                   || (newh->root.type != bfd_link_hash_defined
4852                       && newh->root.type != bfd_link_hash_defweak))
4853                 {
4854                   /* Check the default versioned definition.  */
4855                   *p++ = ELF_VER_CHR;
4856                   memcpy (p, verstr, verlen + 1);
4857                   newh = elf_link_hash_lookup (elf_hash_table (info),
4858                                                newname, FALSE, FALSE,
4859                                                FALSE);
4860                 }
4861               free (newname);
4862
4863               /* Mark this version if there is a definition and it is
4864                  not defined in a shared object.  */
4865               if (newh != NULL
4866                   && ((newh->elf_link_hash_flags
4867                        & ELF_LINK_HASH_DEF_DYNAMIC) == 0)
4868                   && (newh->root.type == bfd_link_hash_defined
4869                       || newh->root.type == bfd_link_hash_defweak))
4870                 d->symver = 1;
4871             }
4872
4873       /* Attach all the symbols to their version information.  */
4874       asvinfo.output_bfd = output_bfd;
4875       asvinfo.info = info;
4876       asvinfo.verdefs = verdefs;
4877       asvinfo.failed = FALSE;
4878
4879       elf_link_hash_traverse (elf_hash_table (info),
4880                               _bfd_elf_link_assign_sym_version,
4881                               &asvinfo);
4882       if (asvinfo.failed)
4883         return FALSE;
4884
4885       if (!info->allow_undefined_version)
4886         {
4887           /* Check if all global versions have a definition.  */
4888           all_defined = TRUE;
4889           for (t = verdefs; t != NULL; t = t->next)
4890             for (d = t->globals.list; d != NULL; d = d->next)
4891               if (!d->symver && !d->script)
4892                 {
4893                   (*_bfd_error_handler)
4894                     (_("%s: undefined version: %s"),
4895                      d->pattern, t->name);
4896                   all_defined = FALSE;
4897                 }
4898
4899           if (!all_defined)
4900             {
4901               bfd_set_error (bfd_error_bad_value);
4902               return FALSE;
4903             }
4904         }
4905
4906       /* Find all symbols which were defined in a dynamic object and make
4907          the backend pick a reasonable value for them.  */
4908       elf_link_hash_traverse (elf_hash_table (info),
4909                               _bfd_elf_adjust_dynamic_symbol,
4910                               &eif);
4911       if (eif.failed)
4912         return FALSE;
4913
4914       /* Add some entries to the .dynamic section.  We fill in some of the
4915          values later, in elf_bfd_final_link, but we must add the entries
4916          now so that we know the final size of the .dynamic section.  */
4917
4918       /* If there are initialization and/or finalization functions to
4919          call then add the corresponding DT_INIT/DT_FINI entries.  */
4920       h = (info->init_function
4921            ? elf_link_hash_lookup (elf_hash_table (info),
4922                                    info->init_function, FALSE,
4923                                    FALSE, FALSE)
4924            : NULL);
4925       if (h != NULL
4926           && (h->elf_link_hash_flags & (ELF_LINK_HASH_REF_REGULAR
4927                                         | ELF_LINK_HASH_DEF_REGULAR)) != 0)
4928         {
4929           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT, 0))
4930             return FALSE;
4931         }
4932       h = (info->fini_function
4933            ? elf_link_hash_lookup (elf_hash_table (info),
4934                                    info->fini_function, FALSE,
4935                                    FALSE, FALSE)
4936            : NULL);
4937       if (h != NULL
4938           && (h->elf_link_hash_flags & (ELF_LINK_HASH_REF_REGULAR
4939                                         | ELF_LINK_HASH_DEF_REGULAR)) != 0)
4940         {
4941           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI, 0))
4942             return FALSE;
4943         }
4944
4945       if (bfd_get_section_by_name (output_bfd, ".preinit_array") != NULL)
4946         {
4947           /* DT_PREINIT_ARRAY is not allowed in shared library.  */
4948           if (! info->executable)
4949             {
4950               bfd *sub;
4951               asection *o;
4952
4953               for (sub = info->input_bfds; sub != NULL;
4954                    sub = sub->link_next)
4955                 for (o = sub->sections; o != NULL; o = o->next)
4956                   if (elf_section_data (o)->this_hdr.sh_type
4957                       == SHT_PREINIT_ARRAY)
4958                     {
4959                       (*_bfd_error_handler)
4960                         (_("%B: .preinit_array section is not allowed in DSO"),
4961                          sub);
4962                       break;
4963                     }
4964
4965               bfd_set_error (bfd_error_nonrepresentable_section);
4966               return FALSE;
4967             }
4968
4969           if (!_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAY, 0)
4970               || !_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAYSZ, 0))
4971             return FALSE;
4972         }
4973       if (bfd_get_section_by_name (output_bfd, ".init_array") != NULL)
4974         {
4975           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAY, 0)
4976               || !_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAYSZ, 0))
4977             return FALSE;
4978         }
4979       if (bfd_get_section_by_name (output_bfd, ".fini_array") != NULL)
4980         {
4981           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAY, 0)
4982               || !_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAYSZ, 0))
4983             return FALSE;
4984         }
4985
4986       dynstr = bfd_get_section_by_name (dynobj, ".dynstr");
4987       /* If .dynstr is excluded from the link, we don't want any of
4988          these tags.  Strictly, we should be checking each section
4989          individually;  This quick check covers for the case where
4990          someone does a /DISCARD/ : { *(*) }.  */
4991       if (dynstr != NULL && dynstr->output_section != bfd_abs_section_ptr)
4992         {
4993           bfd_size_type strsize;
4994
4995           strsize = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
4996           if (!_bfd_elf_add_dynamic_entry (info, DT_HASH, 0)
4997               || !_bfd_elf_add_dynamic_entry (info, DT_STRTAB, 0)
4998               || !_bfd_elf_add_dynamic_entry (info, DT_SYMTAB, 0)
4999               || !_bfd_elf_add_dynamic_entry (info, DT_STRSZ, strsize)
5000               || !_bfd_elf_add_dynamic_entry (info, DT_SYMENT,
5001                                               bed->s->sizeof_sym))
5002             return FALSE;
5003         }
5004     }
5005
5006   /* The backend must work out the sizes of all the other dynamic
5007      sections.  */
5008   if (bed->elf_backend_size_dynamic_sections
5009       && ! (*bed->elf_backend_size_dynamic_sections) (output_bfd, info))
5010     return FALSE;
5011
5012   if (elf_hash_table (info)->dynamic_sections_created)
5013     {
5014       bfd_size_type dynsymcount;
5015       asection *s;
5016       size_t bucketcount = 0;
5017       size_t hash_entry_size;
5018       unsigned int dtagcount;
5019
5020       /* Set up the version definition section.  */
5021       s = bfd_get_section_by_name (dynobj, ".gnu.version_d");
5022       BFD_ASSERT (s != NULL);
5023
5024       /* We may have created additional version definitions if we are
5025          just linking a regular application.  */
5026       verdefs = asvinfo.verdefs;
5027
5028       /* Skip anonymous version tag.  */
5029       if (verdefs != NULL && verdefs->vernum == 0)
5030         verdefs = verdefs->next;
5031
5032       if (verdefs == NULL)
5033         _bfd_strip_section_from_output (info, s);
5034       else
5035         {
5036           unsigned int cdefs;
5037           bfd_size_type size;
5038           struct bfd_elf_version_tree *t;
5039           bfd_byte *p;
5040           Elf_Internal_Verdef def;
5041           Elf_Internal_Verdaux defaux;
5042
5043           cdefs = 0;
5044           size = 0;
5045
5046           /* Make space for the base version.  */
5047           size += sizeof (Elf_External_Verdef);
5048           size += sizeof (Elf_External_Verdaux);
5049           ++cdefs;
5050
5051           for (t = verdefs; t != NULL; t = t->next)
5052             {
5053               struct bfd_elf_version_deps *n;
5054
5055               size += sizeof (Elf_External_Verdef);
5056               size += sizeof (Elf_External_Verdaux);
5057               ++cdefs;
5058
5059               for (n = t->deps; n != NULL; n = n->next)
5060                 size += sizeof (Elf_External_Verdaux);
5061             }
5062
5063           s->size = size;
5064           s->contents = bfd_alloc (output_bfd, s->size);
5065           if (s->contents == NULL && s->size != 0)
5066             return FALSE;
5067
5068           /* Fill in the version definition section.  */
5069
5070           p = s->contents;
5071
5072           def.vd_version = VER_DEF_CURRENT;
5073           def.vd_flags = VER_FLG_BASE;
5074           def.vd_ndx = 1;
5075           def.vd_cnt = 1;
5076           def.vd_aux = sizeof (Elf_External_Verdef);
5077           def.vd_next = (sizeof (Elf_External_Verdef)
5078                          + sizeof (Elf_External_Verdaux));
5079
5080           if (soname_indx != (bfd_size_type) -1)
5081             {
5082               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
5083                                       soname_indx);
5084               def.vd_hash = bfd_elf_hash (soname);
5085               defaux.vda_name = soname_indx;
5086             }
5087           else
5088             {
5089               const char *name;
5090               bfd_size_type indx;
5091
5092               name = basename (output_bfd->filename);
5093               def.vd_hash = bfd_elf_hash (name);
5094               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5095                                           name, FALSE);
5096               if (indx == (bfd_size_type) -1)
5097                 return FALSE;
5098               defaux.vda_name = indx;
5099             }
5100           defaux.vda_next = 0;
5101
5102           _bfd_elf_swap_verdef_out (output_bfd, &def,
5103                                     (Elf_External_Verdef *) p);
5104           p += sizeof (Elf_External_Verdef);
5105           _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
5106                                      (Elf_External_Verdaux *) p);
5107           p += sizeof (Elf_External_Verdaux);
5108
5109           for (t = verdefs; t != NULL; t = t->next)
5110             {
5111               unsigned int cdeps;
5112               struct bfd_elf_version_deps *n;
5113               struct elf_link_hash_entry *h;
5114               struct bfd_link_hash_entry *bh;
5115
5116               cdeps = 0;
5117               for (n = t->deps; n != NULL; n = n->next)
5118                 ++cdeps;
5119
5120               /* Add a symbol representing this version.  */
5121               bh = NULL;
5122               if (! (_bfd_generic_link_add_one_symbol
5123                      (info, dynobj, t->name, BSF_GLOBAL, bfd_abs_section_ptr,
5124                       0, NULL, FALSE,
5125                       get_elf_backend_data (dynobj)->collect, &bh)))
5126                 return FALSE;
5127               h = (struct elf_link_hash_entry *) bh;
5128               h->elf_link_hash_flags &= ~ ELF_LINK_NON_ELF;
5129               h->elf_link_hash_flags |= ELF_LINK_HASH_DEF_REGULAR;
5130               h->type = STT_OBJECT;
5131               h->verinfo.vertree = t;
5132
5133               if (! bfd_elf_link_record_dynamic_symbol (info, h))
5134                 return FALSE;
5135
5136               def.vd_version = VER_DEF_CURRENT;
5137               def.vd_flags = 0;
5138               if (t->globals.list == NULL
5139                   && t->locals.list == NULL
5140                   && ! t->used)
5141                 def.vd_flags |= VER_FLG_WEAK;
5142               def.vd_ndx = t->vernum + 1;
5143               def.vd_cnt = cdeps + 1;
5144               def.vd_hash = bfd_elf_hash (t->name);
5145               def.vd_aux = sizeof (Elf_External_Verdef);
5146               def.vd_next = 0;
5147               if (t->next != NULL)
5148                 def.vd_next = (sizeof (Elf_External_Verdef)
5149                                + (cdeps + 1) * sizeof (Elf_External_Verdaux));
5150
5151               _bfd_elf_swap_verdef_out (output_bfd, &def,
5152                                         (Elf_External_Verdef *) p);
5153               p += sizeof (Elf_External_Verdef);
5154
5155               defaux.vda_name = h->dynstr_index;
5156               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
5157                                       h->dynstr_index);
5158               defaux.vda_next = 0;
5159               if (t->deps != NULL)
5160                 defaux.vda_next = sizeof (Elf_External_Verdaux);
5161               t->name_indx = defaux.vda_name;
5162
5163               _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
5164                                          (Elf_External_Verdaux *) p);
5165               p += sizeof (Elf_External_Verdaux);
5166
5167               for (n = t->deps; n != NULL; n = n->next)
5168                 {
5169                   if (n->version_needed == NULL)
5170                     {
5171                       /* This can happen if there was an error in the
5172                          version script.  */
5173                       defaux.vda_name = 0;
5174                     }
5175                   else
5176                     {
5177                       defaux.vda_name = n->version_needed->name_indx;
5178                       _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
5179                                               defaux.vda_name);
5180                     }
5181                   if (n->next == NULL)
5182                     defaux.vda_next = 0;
5183                   else
5184                     defaux.vda_next = sizeof (Elf_External_Verdaux);
5185
5186                   _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
5187                                              (Elf_External_Verdaux *) p);
5188                   p += sizeof (Elf_External_Verdaux);
5189                 }
5190             }
5191
5192           if (!_bfd_elf_add_dynamic_entry (info, DT_VERDEF, 0)
5193               || !_bfd_elf_add_dynamic_entry (info, DT_VERDEFNUM, cdefs))
5194             return FALSE;
5195
5196           elf_tdata (output_bfd)->cverdefs = cdefs;
5197         }
5198
5199       if ((info->new_dtags && info->flags) || (info->flags & DF_STATIC_TLS))
5200         {
5201           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS, info->flags))
5202             return FALSE;
5203         }
5204       else if (info->flags & DF_BIND_NOW)
5205         {
5206           if (!_bfd_elf_add_dynamic_entry (info, DT_BIND_NOW, 0))
5207             return FALSE;
5208         }
5209
5210       if (info->flags_1)
5211         {
5212           if (info->executable)
5213             info->flags_1 &= ~ (DF_1_INITFIRST
5214                                 | DF_1_NODELETE
5215                                 | DF_1_NOOPEN);
5216           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS_1, info->flags_1))
5217             return FALSE;
5218         }
5219
5220       /* Work out the size of the version reference section.  */
5221
5222       s = bfd_get_section_by_name (dynobj, ".gnu.version_r");
5223       BFD_ASSERT (s != NULL);
5224       {
5225         struct elf_find_verdep_info sinfo;
5226
5227         sinfo.output_bfd = output_bfd;
5228         sinfo.info = info;
5229         sinfo.vers = elf_tdata (output_bfd)->cverdefs;
5230         if (sinfo.vers == 0)
5231           sinfo.vers = 1;
5232         sinfo.failed = FALSE;
5233
5234         elf_link_hash_traverse (elf_hash_table (info),
5235                                 _bfd_elf_link_find_version_dependencies,
5236                                 &sinfo);
5237
5238         if (elf_tdata (output_bfd)->verref == NULL)
5239           _bfd_strip_section_from_output (info, s);
5240         else
5241           {
5242             Elf_Internal_Verneed *t;
5243             unsigned int size;
5244             unsigned int crefs;
5245             bfd_byte *p;
5246
5247             /* Build the version definition section.  */
5248             size = 0;
5249             crefs = 0;
5250             for (t = elf_tdata (output_bfd)->verref;
5251                  t != NULL;
5252                  t = t->vn_nextref)
5253               {
5254                 Elf_Internal_Vernaux *a;
5255
5256                 size += sizeof (Elf_External_Verneed);
5257                 ++crefs;
5258                 for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
5259                   size += sizeof (Elf_External_Vernaux);
5260               }
5261
5262             s->size = size;
5263             s->contents = bfd_alloc (output_bfd, s->size);
5264             if (s->contents == NULL)
5265               return FALSE;
5266
5267             p = s->contents;
5268             for (t = elf_tdata (output_bfd)->verref;
5269                  t != NULL;
5270                  t = t->vn_nextref)
5271               {
5272                 unsigned int caux;
5273                 Elf_Internal_Vernaux *a;
5274                 bfd_size_type indx;
5275
5276                 caux = 0;
5277                 for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
5278                   ++caux;
5279
5280                 t->vn_version = VER_NEED_CURRENT;
5281                 t->vn_cnt = caux;
5282                 indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5283                                             elf_dt_name (t->vn_bfd) != NULL
5284                                             ? elf_dt_name (t->vn_bfd)
5285                                             : basename (t->vn_bfd->filename),
5286                                             FALSE);
5287                 if (indx == (bfd_size_type) -1)
5288                   return FALSE;
5289                 t->vn_file = indx;
5290                 t->vn_aux = sizeof (Elf_External_Verneed);
5291                 if (t->vn_nextref == NULL)
5292                   t->vn_next = 0;
5293                 else
5294                   t->vn_next = (sizeof (Elf_External_Verneed)
5295                                 + caux * sizeof (Elf_External_Vernaux));
5296
5297                 _bfd_elf_swap_verneed_out (output_bfd, t,
5298                                            (Elf_External_Verneed *) p);
5299                 p += sizeof (Elf_External_Verneed);
5300
5301                 for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
5302                   {
5303                     a->vna_hash = bfd_elf_hash (a->vna_nodename);
5304                     indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5305                                                 a->vna_nodename, FALSE);
5306                     if (indx == (bfd_size_type) -1)
5307                       return FALSE;
5308                     a->vna_name = indx;
5309                     if (a->vna_nextptr == NULL)
5310                       a->vna_next = 0;
5311                     else
5312                       a->vna_next = sizeof (Elf_External_Vernaux);
5313
5314                     _bfd_elf_swap_vernaux_out (output_bfd, a,
5315                                                (Elf_External_Vernaux *) p);
5316                     p += sizeof (Elf_External_Vernaux);
5317                   }
5318               }
5319
5320             if (!_bfd_elf_add_dynamic_entry (info, DT_VERNEED, 0)
5321                 || !_bfd_elf_add_dynamic_entry (info, DT_VERNEEDNUM, crefs))
5322               return FALSE;
5323
5324             elf_tdata (output_bfd)->cverrefs = crefs;
5325           }
5326       }
5327
5328       /* Assign dynsym indicies.  In a shared library we generate a
5329          section symbol for each output section, which come first.
5330          Next come all of the back-end allocated local dynamic syms,
5331          followed by the rest of the global symbols.  */
5332
5333       dynsymcount = _bfd_elf_link_renumber_dynsyms (output_bfd, info);
5334
5335       /* Work out the size of the symbol version section.  */
5336       s = bfd_get_section_by_name (dynobj, ".gnu.version");
5337       BFD_ASSERT (s != NULL);
5338       if (dynsymcount == 0
5339           || (verdefs == NULL && elf_tdata (output_bfd)->verref == NULL))
5340         {
5341           _bfd_strip_section_from_output (info, s);
5342           /* The DYNSYMCOUNT might have changed if we were going to
5343              output a dynamic symbol table entry for S.  */
5344           dynsymcount = _bfd_elf_link_renumber_dynsyms (output_bfd, info);
5345         }
5346       else
5347         {
5348           s->size = dynsymcount * sizeof (Elf_External_Versym);
5349           s->contents = bfd_zalloc (output_bfd, s->size);
5350           if (s->contents == NULL)
5351             return FALSE;
5352
5353           if (!_bfd_elf_add_dynamic_entry (info, DT_VERSYM, 0))
5354             return FALSE;
5355         }
5356
5357       /* Set the size of the .dynsym and .hash sections.  We counted
5358          the number of dynamic symbols in elf_link_add_object_symbols.
5359          We will build the contents of .dynsym and .hash when we build
5360          the final symbol table, because until then we do not know the
5361          correct value to give the symbols.  We built the .dynstr
5362          section as we went along in elf_link_add_object_symbols.  */
5363       s = bfd_get_section_by_name (dynobj, ".dynsym");
5364       BFD_ASSERT (s != NULL);
5365       s->size = dynsymcount * bed->s->sizeof_sym;
5366       s->contents = bfd_alloc (output_bfd, s->size);
5367       if (s->contents == NULL && s->size != 0)
5368         return FALSE;
5369
5370       if (dynsymcount != 0)
5371         {
5372           Elf_Internal_Sym isym;
5373
5374           /* The first entry in .dynsym is a dummy symbol.  */
5375           isym.st_value = 0;
5376           isym.st_size = 0;
5377           isym.st_name = 0;
5378           isym.st_info = 0;
5379           isym.st_other = 0;
5380           isym.st_shndx = 0;
5381           bed->s->swap_symbol_out (output_bfd, &isym, s->contents, 0);
5382         }
5383
5384       /* Compute the size of the hashing table.  As a side effect this
5385          computes the hash values for all the names we export.  */
5386       bucketcount = compute_bucket_count (info);
5387
5388       s = bfd_get_section_by_name (dynobj, ".hash");
5389       BFD_ASSERT (s != NULL);
5390       hash_entry_size = elf_section_data (s)->this_hdr.sh_entsize;
5391       s->size = ((2 + bucketcount + dynsymcount) * hash_entry_size);
5392       s->contents = bfd_zalloc (output_bfd, s->size);
5393       if (s->contents == NULL)
5394         return FALSE;
5395
5396       bfd_put (8 * hash_entry_size, output_bfd, bucketcount, s->contents);
5397       bfd_put (8 * hash_entry_size, output_bfd, dynsymcount,
5398                s->contents + hash_entry_size);
5399
5400       elf_hash_table (info)->bucketcount = bucketcount;
5401
5402       s = bfd_get_section_by_name (dynobj, ".dynstr");
5403       BFD_ASSERT (s != NULL);
5404
5405       elf_finalize_dynstr (output_bfd, info);
5406
5407       s->size = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
5408
5409       for (dtagcount = 0; dtagcount <= info->spare_dynamic_tags; ++dtagcount)
5410         if (!_bfd_elf_add_dynamic_entry (info, DT_NULL, 0))
5411           return FALSE;
5412     }
5413
5414   return TRUE;
5415 }
5416
5417 /* Final phase of ELF linker.  */
5418
5419 /* A structure we use to avoid passing large numbers of arguments.  */
5420
5421 struct elf_final_link_info
5422 {
5423   /* General link information.  */
5424   struct bfd_link_info *info;
5425   /* Output BFD.  */
5426   bfd *output_bfd;
5427   /* Symbol string table.  */
5428   struct bfd_strtab_hash *symstrtab;
5429   /* .dynsym section.  */
5430   asection *dynsym_sec;
5431   /* .hash section.  */
5432   asection *hash_sec;
5433   /* symbol version section (.gnu.version).  */
5434   asection *symver_sec;
5435   /* Buffer large enough to hold contents of any section.  */
5436   bfd_byte *contents;
5437   /* Buffer large enough to hold external relocs of any section.  */
5438   void *external_relocs;
5439   /* Buffer large enough to hold internal relocs of any section.  */
5440   Elf_Internal_Rela *internal_relocs;
5441   /* Buffer large enough to hold external local symbols of any input
5442      BFD.  */
5443   bfd_byte *external_syms;
5444   /* And a buffer for symbol section indices.  */
5445   Elf_External_Sym_Shndx *locsym_shndx;
5446   /* Buffer large enough to hold internal local symbols of any input
5447      BFD.  */
5448   Elf_Internal_Sym *internal_syms;
5449   /* Array large enough to hold a symbol index for each local symbol
5450      of any input BFD.  */
5451   long *indices;
5452   /* Array large enough to hold a section pointer for each local
5453      symbol of any input BFD.  */
5454   asection **sections;
5455   /* Buffer to hold swapped out symbols.  */
5456   bfd_byte *symbuf;
5457   /* And one for symbol section indices.  */
5458   Elf_External_Sym_Shndx *symshndxbuf;
5459   /* Number of swapped out symbols in buffer.  */
5460   size_t symbuf_count;
5461   /* Number of symbols which fit in symbuf.  */
5462   size_t symbuf_size;
5463   /* And same for symshndxbuf.  */
5464   size_t shndxbuf_size;
5465 };
5466
5467 /* This struct is used to pass information to elf_link_output_extsym.  */
5468
5469 struct elf_outext_info
5470 {
5471   bfd_boolean failed;
5472   bfd_boolean localsyms;
5473   struct elf_final_link_info *finfo;
5474 };
5475
5476 /* When performing a relocatable link, the input relocations are
5477    preserved.  But, if they reference global symbols, the indices
5478    referenced must be updated.  Update all the relocations in
5479    REL_HDR (there are COUNT of them), using the data in REL_HASH.  */
5480
5481 static void
5482 elf_link_adjust_relocs (bfd *abfd,
5483                         Elf_Internal_Shdr *rel_hdr,
5484                         unsigned int count,
5485                         struct elf_link_hash_entry **rel_hash)
5486 {
5487   unsigned int i;
5488   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
5489   bfd_byte *erela;
5490   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
5491   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
5492   bfd_vma r_type_mask;
5493   int r_sym_shift;
5494
5495   if (rel_hdr->sh_entsize == bed->s->sizeof_rel)
5496     {
5497       swap_in = bed->s->swap_reloc_in;
5498       swap_out = bed->s->swap_reloc_out;
5499     }
5500   else if (rel_hdr->sh_entsize == bed->s->sizeof_rela)
5501     {
5502       swap_in = bed->s->swap_reloca_in;
5503       swap_out = bed->s->swap_reloca_out;
5504     }
5505   else
5506     abort ();
5507
5508   if (bed->s->int_rels_per_ext_rel > MAX_INT_RELS_PER_EXT_REL)
5509     abort ();
5510
5511   if (bed->s->arch_size == 32)
5512     {
5513       r_type_mask = 0xff;
5514       r_sym_shift = 8;
5515     }
5516   else
5517     {
5518       r_type_mask = 0xffffffff;
5519       r_sym_shift = 32;
5520     }
5521
5522   erela = rel_hdr->contents;
5523   for (i = 0; i < count; i++, rel_hash++, erela += rel_hdr->sh_entsize)
5524     {
5525       Elf_Internal_Rela irela[MAX_INT_RELS_PER_EXT_REL];
5526       unsigned int j;
5527
5528       if (*rel_hash == NULL)
5529         continue;
5530
5531       BFD_ASSERT ((*rel_hash)->indx >= 0);
5532
5533       (*swap_in) (abfd, erela, irela);
5534       for (j = 0; j < bed->s->int_rels_per_ext_rel; j++)
5535         irela[j].r_info = ((bfd_vma) (*rel_hash)->indx << r_sym_shift
5536                            | (irela[j].r_info & r_type_mask));
5537       (*swap_out) (abfd, irela, erela);
5538     }
5539 }
5540
5541 struct elf_link_sort_rela
5542 {
5543   union {
5544     bfd_vma offset;
5545     bfd_vma sym_mask;
5546   } u;
5547   enum elf_reloc_type_class type;
5548   /* We use this as an array of size int_rels_per_ext_rel.  */
5549   Elf_Internal_Rela rela[1];
5550 };
5551
5552 static int
5553 elf_link_sort_cmp1 (const void *A, const void *B)
5554 {
5555   const struct elf_link_sort_rela *a = A;
5556   const struct elf_link_sort_rela *b = B;
5557   int relativea, relativeb;
5558
5559   relativea = a->type == reloc_class_relative;
5560   relativeb = b->type == reloc_class_relative;
5561
5562   if (relativea < relativeb)
5563     return 1;
5564   if (relativea > relativeb)
5565     return -1;
5566   if ((a->rela->r_info & a->u.sym_mask) < (b->rela->r_info & b->u.sym_mask))
5567     return -1;
5568   if ((a->rela->r_info & a->u.sym_mask) > (b->rela->r_info & b->u.sym_mask))
5569     return 1;
5570   if (a->rela->r_offset < b->rela->r_offset)
5571     return -1;
5572   if (a->rela->r_offset > b->rela->r_offset)
5573     return 1;
5574   return 0;
5575 }
5576
5577 static int
5578 elf_link_sort_cmp2 (const void *A, const void *B)
5579 {
5580   const struct elf_link_sort_rela *a = A;
5581   const struct elf_link_sort_rela *b = B;
5582   int copya, copyb;
5583
5584   if (a->u.offset < b->u.offset)
5585     return -1;
5586   if (a->u.offset > b->u.offset)
5587     return 1;
5588   copya = (a->type == reloc_class_copy) * 2 + (a->type == reloc_class_plt);
5589   copyb = (b->type == reloc_class_copy) * 2 + (b->type == reloc_class_plt);
5590   if (copya < copyb)
5591     return -1;
5592   if (copya > copyb)
5593     return 1;
5594   if (a->rela->r_offset < b->rela->r_offset)
5595     return -1;
5596   if (a->rela->r_offset > b->rela->r_offset)
5597     return 1;
5598   return 0;
5599 }
5600
5601 static size_t
5602 elf_link_sort_relocs (bfd *abfd, struct bfd_link_info *info, asection **psec)
5603 {
5604   asection *reldyn;
5605   bfd_size_type count, size;
5606   size_t i, ret, sort_elt, ext_size;
5607   bfd_byte *sort, *s_non_relative, *p;
5608   struct elf_link_sort_rela *sq;
5609   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
5610   int i2e = bed->s->int_rels_per_ext_rel;
5611   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
5612   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
5613   struct bfd_link_order *lo;
5614   bfd_vma r_sym_mask;
5615
5616   reldyn = bfd_get_section_by_name (abfd, ".rela.dyn");
5617   if (reldyn == NULL || reldyn->size == 0)
5618     {
5619       reldyn = bfd_get_section_by_name (abfd, ".rel.dyn");
5620       if (reldyn == NULL || reldyn->size == 0)
5621         return 0;
5622       ext_size = bed->s->sizeof_rel;
5623       swap_in = bed->s->swap_reloc_in;
5624       swap_out = bed->s->swap_reloc_out;
5625     }
5626   else
5627     {
5628       ext_size = bed->s->sizeof_rela;
5629       swap_in = bed->s->swap_reloca_in;
5630       swap_out = bed->s->swap_reloca_out;
5631     }
5632   count = reldyn->size / ext_size;
5633
5634   size = 0;
5635   for (lo = reldyn->link_order_head; lo != NULL; lo = lo->next)
5636     if (lo->type == bfd_indirect_link_order)
5637       {
5638         asection *o = lo->u.indirect.section;
5639         size += o->size;
5640       }
5641
5642   if (size != reldyn->size)
5643     return 0;
5644
5645   sort_elt = (sizeof (struct elf_link_sort_rela)
5646               + (i2e - 1) * sizeof (Elf_Internal_Rela));
5647   sort = bfd_zmalloc (sort_elt * count);
5648   if (sort == NULL)
5649     {
5650       (*info->callbacks->warning)
5651         (info, _("Not enough memory to sort relocations"), 0, abfd, 0, 0);
5652       return 0;
5653     }
5654
5655   if (bed->s->arch_size == 32)
5656     r_sym_mask = ~(bfd_vma) 0xff;
5657   else
5658     r_sym_mask = ~(bfd_vma) 0xffffffff;
5659
5660   for (lo = reldyn->link_order_head; lo != NULL; lo = lo->next)
5661     if (lo->type == bfd_indirect_link_order)
5662       {
5663         bfd_byte *erel, *erelend;
5664         asection *o = lo->u.indirect.section;
5665
5666         erel = o->contents;
5667         erelend = o->contents + o->size;
5668         p = sort + o->output_offset / ext_size * sort_elt;
5669         while (erel < erelend)
5670           {
5671             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
5672             (*swap_in) (abfd, erel, s->rela);
5673             s->type = (*bed->elf_backend_reloc_type_class) (s->rela);
5674             s->u.sym_mask = r_sym_mask;
5675             p += sort_elt;
5676             erel += ext_size;
5677           }
5678       }
5679
5680   qsort (sort, count, sort_elt, elf_link_sort_cmp1);
5681
5682   for (i = 0, p = sort; i < count; i++, p += sort_elt)
5683     {
5684       struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
5685       if (s->type != reloc_class_relative)
5686         break;
5687     }
5688   ret = i;
5689   s_non_relative = p;
5690
5691   sq = (struct elf_link_sort_rela *) s_non_relative;
5692   for (; i < count; i++, p += sort_elt)
5693     {
5694       struct elf_link_sort_rela *sp = (struct elf_link_sort_rela *) p;
5695       if (((sp->rela->r_info ^ sq->rela->r_info) & r_sym_mask) != 0)
5696         sq = sp;
5697       sp->u.offset = sq->rela->r_offset;
5698     }
5699
5700   qsort (s_non_relative, count - ret, sort_elt, elf_link_sort_cmp2);
5701
5702   for (lo = reldyn->link_order_head; lo != NULL; lo = lo->next)
5703     if (lo->type == bfd_indirect_link_order)
5704       {
5705         bfd_byte *erel, *erelend;
5706         asection *o = lo->u.indirect.section;
5707
5708         erel = o->contents;
5709         erelend = o->contents + o->size;
5710         p = sort + o->output_offset / ext_size * sort_elt;
5711         while (erel < erelend)
5712           {
5713             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
5714             (*swap_out) (abfd, s->rela, erel);
5715             p += sort_elt;
5716             erel += ext_size;
5717           }
5718       }
5719
5720   free (sort);
5721   *psec = reldyn;
5722   return ret;
5723 }
5724
5725 /* Flush the output symbols to the file.  */
5726
5727 static bfd_boolean
5728 elf_link_flush_output_syms (struct elf_final_link_info *finfo,
5729                             const struct elf_backend_data *bed)
5730 {
5731   if (finfo->symbuf_count > 0)
5732     {
5733       Elf_Internal_Shdr *hdr;
5734       file_ptr pos;
5735       bfd_size_type amt;
5736
5737       hdr = &elf_tdata (finfo->output_bfd)->symtab_hdr;
5738       pos = hdr->sh_offset + hdr->sh_size;
5739       amt = finfo->symbuf_count * bed->s->sizeof_sym;
5740       if (bfd_seek (finfo->output_bfd, pos, SEEK_SET) != 0
5741           || bfd_bwrite (finfo->symbuf, amt, finfo->output_bfd) != amt)
5742         return FALSE;
5743
5744       hdr->sh_size += amt;
5745       finfo->symbuf_count = 0;
5746     }
5747
5748   return TRUE;
5749 }
5750
5751 /* Add a symbol to the output symbol table.  */
5752
5753 static bfd_boolean
5754 elf_link_output_sym (struct elf_final_link_info *finfo,
5755                      const char *name,
5756                      Elf_Internal_Sym *elfsym,
5757                      asection *input_sec,
5758                      struct elf_link_hash_entry *h)
5759 {
5760   bfd_byte *dest;
5761   Elf_External_Sym_Shndx *destshndx;
5762   bfd_boolean (*output_symbol_hook)
5763     (struct bfd_link_info *, const char *, Elf_Internal_Sym *, asection *,
5764      struct elf_link_hash_entry *);
5765   const struct elf_backend_data *bed;
5766
5767   bed = get_elf_backend_data (finfo->output_bfd);
5768   output_symbol_hook = bed->elf_backend_link_output_symbol_hook;
5769   if (output_symbol_hook != NULL)
5770     {
5771       if (! (*output_symbol_hook) (finfo->info, name, elfsym, input_sec, h))
5772         return FALSE;
5773     }
5774
5775   if (name == NULL || *name == '\0')
5776     elfsym->st_name = 0;
5777   else if (input_sec->flags & SEC_EXCLUDE)
5778     elfsym->st_name = 0;
5779   else
5780     {
5781       elfsym->st_name = (unsigned long) _bfd_stringtab_add (finfo->symstrtab,
5782                                                             name, TRUE, FALSE);
5783       if (elfsym->st_name == (unsigned long) -1)
5784         return FALSE;
5785     }
5786
5787   if (finfo->symbuf_count >= finfo->symbuf_size)
5788     {
5789       if (! elf_link_flush_output_syms (finfo, bed))
5790         return FALSE;
5791     }
5792
5793   dest = finfo->symbuf + finfo->symbuf_count * bed->s->sizeof_sym;
5794   destshndx = finfo->symshndxbuf;
5795   if (destshndx != NULL)
5796     {
5797       if (bfd_get_symcount (finfo->output_bfd) >= finfo->shndxbuf_size)
5798         {
5799           bfd_size_type amt;
5800
5801           amt = finfo->shndxbuf_size * sizeof (Elf_External_Sym_Shndx);
5802           finfo->symshndxbuf = destshndx = bfd_realloc (destshndx, amt * 2);
5803           if (destshndx == NULL)
5804             return FALSE;
5805           memset ((char *) destshndx + amt, 0, amt);
5806           finfo->shndxbuf_size *= 2;
5807         }
5808       destshndx += bfd_get_symcount (finfo->output_bfd);
5809     }
5810
5811   bed->s->swap_symbol_out (finfo->output_bfd, elfsym, dest, destshndx);
5812   finfo->symbuf_count += 1;
5813   bfd_get_symcount (finfo->output_bfd) += 1;
5814
5815   return TRUE;
5816 }
5817
5818 /* For DSOs loaded in via a DT_NEEDED entry, emulate ld.so in
5819    allowing an unsatisfied unversioned symbol in the DSO to match a
5820    versioned symbol that would normally require an explicit version.
5821    We also handle the case that a DSO references a hidden symbol
5822    which may be satisfied by a versioned symbol in another DSO.  */
5823
5824 static bfd_boolean
5825 elf_link_check_versioned_symbol (struct bfd_link_info *info,
5826                                  const struct elf_backend_data *bed,
5827                                  struct elf_link_hash_entry *h)
5828 {
5829   bfd *abfd;
5830   struct elf_link_loaded_list *loaded;
5831
5832   if (!is_elf_hash_table (info->hash))
5833     return FALSE;
5834
5835   switch (h->root.type)
5836     {
5837     default:
5838       abfd = NULL;
5839       break;
5840
5841     case bfd_link_hash_undefined:
5842     case bfd_link_hash_undefweak:
5843       abfd = h->root.u.undef.abfd;
5844       if ((abfd->flags & DYNAMIC) == 0
5845           || (elf_dyn_lib_class (abfd) & DYN_DT_NEEDED) == 0)
5846         return FALSE;
5847       break;
5848
5849     case bfd_link_hash_defined:
5850     case bfd_link_hash_defweak:
5851       abfd = h->root.u.def.section->owner;
5852       break;
5853
5854     case bfd_link_hash_common:
5855       abfd = h->root.u.c.p->section->owner;
5856       break;
5857     }
5858   BFD_ASSERT (abfd != NULL);
5859
5860   for (loaded = elf_hash_table (info)->loaded;
5861        loaded != NULL;
5862        loaded = loaded->next)
5863     {
5864       bfd *input;
5865       Elf_Internal_Shdr *hdr;
5866       bfd_size_type symcount;
5867       bfd_size_type extsymcount;
5868       bfd_size_type extsymoff;
5869       Elf_Internal_Shdr *versymhdr;
5870       Elf_Internal_Sym *isym;
5871       Elf_Internal_Sym *isymend;
5872       Elf_Internal_Sym *isymbuf;
5873       Elf_External_Versym *ever;
5874       Elf_External_Versym *extversym;
5875
5876       input = loaded->abfd;
5877
5878       /* We check each DSO for a possible hidden versioned definition.  */
5879       if (input == abfd
5880           || (input->flags & DYNAMIC) == 0
5881           || elf_dynversym (input) == 0)
5882         continue;
5883
5884       hdr = &elf_tdata (input)->dynsymtab_hdr;
5885
5886       symcount = hdr->sh_size / bed->s->sizeof_sym;
5887       if (elf_bad_symtab (input))
5888         {
5889           extsymcount = symcount;
5890           extsymoff = 0;
5891         }
5892       else
5893         {
5894           extsymcount = symcount - hdr->sh_info;
5895           extsymoff = hdr->sh_info;
5896         }
5897
5898       if (extsymcount == 0)
5899         continue;
5900
5901       isymbuf = bfd_elf_get_elf_syms (input, hdr, extsymcount, extsymoff,
5902                                       NULL, NULL, NULL);
5903       if (isymbuf == NULL)
5904         return FALSE;
5905
5906       /* Read in any version definitions.  */
5907       versymhdr = &elf_tdata (input)->dynversym_hdr;
5908       extversym = bfd_malloc (versymhdr->sh_size);
5909       if (extversym == NULL)
5910         goto error_ret;
5911
5912       if (bfd_seek (input, versymhdr->sh_offset, SEEK_SET) != 0
5913           || (bfd_bread (extversym, versymhdr->sh_size, input)
5914               != versymhdr->sh_size))
5915         {
5916           free (extversym);
5917         error_ret:
5918           free (isymbuf);
5919           return FALSE;
5920         }
5921
5922       ever = extversym + extsymoff;
5923       isymend = isymbuf + extsymcount;
5924       for (isym = isymbuf; isym < isymend; isym++, ever++)
5925         {
5926           const char *name;
5927           Elf_Internal_Versym iver;
5928           unsigned short version_index;
5929
5930           if (ELF_ST_BIND (isym->st_info) == STB_LOCAL
5931               || isym->st_shndx == SHN_UNDEF)
5932             continue;
5933
5934           name = bfd_elf_string_from_elf_section (input,
5935                                                   hdr->sh_link,
5936                                                   isym->st_name);
5937           if (strcmp (name, h->root.root.string) != 0)
5938             continue;
5939
5940           _bfd_elf_swap_versym_in (input, ever, &iver);
5941
5942           if ((iver.vs_vers & VERSYM_HIDDEN) == 0)
5943             {
5944               /* If we have a non-hidden versioned sym, then it should
5945                  have provided a definition for the undefined sym.  */
5946               abort ();
5947             }
5948
5949           version_index = iver.vs_vers & VERSYM_VERSION;
5950           if (version_index == 1 || version_index == 2)
5951             {
5952               /* This is the base or first version.  We can use it.  */
5953               free (extversym);
5954               free (isymbuf);
5955               return TRUE;
5956             }
5957         }
5958
5959       free (extversym);
5960       free (isymbuf);
5961     }
5962
5963   return FALSE;
5964 }
5965
5966 /* Add an external symbol to the symbol table.  This is called from
5967    the hash table traversal routine.  When generating a shared object,
5968    we go through the symbol table twice.  The first time we output
5969    anything that might have been forced to local scope in a version
5970    script.  The second time we output the symbols that are still
5971    global symbols.  */
5972
5973 static bfd_boolean
5974 elf_link_output_extsym (struct elf_link_hash_entry *h, void *data)
5975 {
5976   struct elf_outext_info *eoinfo = data;
5977   struct elf_final_link_info *finfo = eoinfo->finfo;
5978   bfd_boolean strip;
5979   Elf_Internal_Sym sym;
5980   asection *input_sec;
5981   const struct elf_backend_data *bed;
5982
5983   if (h->root.type == bfd_link_hash_warning)
5984     {
5985       h = (struct elf_link_hash_entry *) h->root.u.i.link;
5986       if (h->root.type == bfd_link_hash_new)
5987         return TRUE;
5988     }
5989
5990   /* Decide whether to output this symbol in this pass.  */
5991   if (eoinfo->localsyms)
5992     {
5993       if ((h->elf_link_hash_flags & ELF_LINK_FORCED_LOCAL) == 0)
5994         return TRUE;
5995     }
5996   else
5997     {
5998       if ((h->elf_link_hash_flags & ELF_LINK_FORCED_LOCAL) != 0)
5999         return TRUE;
6000     }
6001
6002   bed = get_elf_backend_data (finfo->output_bfd);
6003
6004   /* If we have an undefined symbol reference here then it must have
6005      come from a shared library that is being linked in.  (Undefined
6006      references in regular files have already been handled).  If we
6007      are reporting errors for this situation then do so now.  */
6008   if (h->root.type == bfd_link_hash_undefined
6009       && (h->elf_link_hash_flags & ELF_LINK_HASH_REF_DYNAMIC) != 0
6010       && (h->elf_link_hash_flags & ELF_LINK_HASH_REF_REGULAR) == 0
6011       && ! elf_link_check_versioned_symbol (finfo->info, bed, h)
6012       && finfo->info->unresolved_syms_in_shared_libs != RM_IGNORE)
6013     {
6014       if (! ((*finfo->info->callbacks->undefined_symbol)
6015              (finfo->info, h->root.root.string, h->root.u.undef.abfd,
6016               NULL, 0, finfo->info->unresolved_syms_in_shared_libs == RM_GENERATE_ERROR)))
6017         {
6018           eoinfo->failed = TRUE;
6019           return FALSE;
6020         }
6021     }
6022
6023   /* We should also warn if a forced local symbol is referenced from
6024      shared libraries.  */
6025   if (! finfo->info->relocatable
6026       && (! finfo->info->shared)
6027       && (h->elf_link_hash_flags
6028           & (ELF_LINK_FORCED_LOCAL | ELF_LINK_HASH_REF_DYNAMIC | ELF_LINK_DYNAMIC_DEF | ELF_LINK_DYNAMIC_WEAK))
6029          == (ELF_LINK_FORCED_LOCAL | ELF_LINK_HASH_REF_DYNAMIC)
6030       && ! elf_link_check_versioned_symbol (finfo->info, bed, h))
6031     {
6032       (*_bfd_error_handler)
6033         (_("%B: %s symbol `%s' in %B is referenced by DSO"),
6034          finfo->output_bfd, h->root.u.def.section->owner,
6035          ELF_ST_VISIBILITY (h->other) == STV_INTERNAL
6036          ? "internal"
6037          : ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
6038          ? "hidden" : "local",
6039          h->root.root.string);
6040       eoinfo->failed = TRUE;
6041       return FALSE;
6042     }
6043
6044   /* We don't want to output symbols that have never been mentioned by
6045      a regular file, or that we have been told to strip.  However, if
6046      h->indx is set to -2, the symbol is used by a reloc and we must
6047      output it.  */
6048   if (h->indx == -2)
6049     strip = FALSE;
6050   else if (((h->elf_link_hash_flags & ELF_LINK_HASH_DEF_DYNAMIC) != 0
6051             || (h->elf_link_hash_flags & ELF_LINK_HASH_REF_DYNAMIC) != 0)
6052            && (h->elf_link_hash_flags & ELF_LINK_HASH_DEF_REGULAR) == 0
6053            && (h->elf_link_hash_flags & ELF_LINK_HASH_REF_REGULAR) == 0)
6054     strip = TRUE;
6055   else if (finfo->info->strip == strip_all)
6056     strip = TRUE;
6057   else if (finfo->info->strip == strip_some
6058            && bfd_hash_lookup (finfo->info->keep_hash,
6059                                h->root.root.string, FALSE, FALSE) == NULL)
6060     strip = TRUE;
6061   else if (finfo->info->strip_discarded
6062            && (h->root.type == bfd_link_hash_defined
6063                || h->root.type == bfd_link_hash_defweak)
6064            && elf_discarded_section (h->root.u.def.section))
6065     strip = TRUE;
6066   else
6067     strip = FALSE;
6068
6069   /* If we're stripping it, and it's not a dynamic symbol, there's
6070      nothing else to do unless it is a forced local symbol.  */
6071   if (strip
6072       && h->dynindx == -1
6073       && (h->elf_link_hash_flags & ELF_LINK_FORCED_LOCAL) == 0)
6074     return TRUE;
6075
6076   sym.st_value = 0;
6077   sym.st_size = h->size;
6078   sym.st_other = h->other;
6079   if ((h->elf_link_hash_flags & ELF_LINK_FORCED_LOCAL) != 0)
6080     sym.st_info = ELF_ST_INFO (STB_LOCAL, h->type);
6081   else if (h->root.type == bfd_link_hash_undefweak
6082            || h->root.type == bfd_link_hash_defweak)
6083     sym.st_info = ELF_ST_INFO (STB_WEAK, h->type);
6084   else
6085     sym.st_info = ELF_ST_INFO (STB_GLOBAL, h->type);
6086
6087   switch (h->root.type)
6088     {
6089     default:
6090     case bfd_link_hash_new:
6091     case bfd_link_hash_warning:
6092       abort ();
6093       return FALSE;
6094
6095     case bfd_link_hash_undefined:
6096     case bfd_link_hash_undefweak:
6097       input_sec = bfd_und_section_ptr;
6098       sym.st_shndx = SHN_UNDEF;
6099       break;
6100
6101     case bfd_link_hash_defined:
6102     case bfd_link_hash_defweak:
6103       {
6104         input_sec = h->root.u.def.section;
6105         if (input_sec->output_section != NULL)
6106           {
6107             sym.st_shndx =
6108               _bfd_elf_section_from_bfd_section (finfo->output_bfd,
6109                                                  input_sec->output_section);
6110             if (sym.st_shndx == SHN_BAD)
6111               {
6112                 (*_bfd_error_handler)
6113                   (_("%B: could not find output section %A for input section %A"),
6114                    finfo->output_bfd, input_sec->output_section, input_sec);
6115                 eoinfo->failed = TRUE;
6116                 return FALSE;
6117               }
6118
6119             /* ELF symbols in relocatable files are section relative,
6120                but in nonrelocatable files they are virtual
6121                addresses.  */
6122             sym.st_value = h->root.u.def.value + input_sec->output_offset;
6123             if (! finfo->info->relocatable)
6124               {
6125                 sym.st_value += input_sec->output_section->vma;
6126                 if (h->type == STT_TLS)
6127                   {
6128                     /* STT_TLS symbols are relative to PT_TLS segment
6129                        base.  */
6130                     BFD_ASSERT (elf_hash_table (finfo->info)->tls_sec != NULL);
6131                     sym.st_value -= elf_hash_table (finfo->info)->tls_sec->vma;
6132                   }
6133               }
6134           }
6135         else
6136           {
6137             BFD_ASSERT (input_sec->owner == NULL
6138                         || (input_sec->owner->flags & DYNAMIC) != 0);
6139             sym.st_shndx = SHN_UNDEF;
6140             input_sec = bfd_und_section_ptr;
6141           }
6142       }
6143       break;
6144
6145     case bfd_link_hash_common:
6146       input_sec = h->root.u.c.p->section;
6147       sym.st_shndx = SHN_COMMON;
6148       sym.st_value = 1 << h->root.u.c.p->alignment_power;
6149       break;
6150
6151     case bfd_link_hash_indirect:
6152       /* These symbols are created by symbol versioning.  They point
6153          to the decorated version of the name.  For example, if the
6154          symbol foo@@GNU_1.2 is the default, which should be used when
6155          foo is used with no version, then we add an indirect symbol
6156          foo which points to foo@@GNU_1.2.  We ignore these symbols,
6157          since the indirected symbol is already in the hash table.  */
6158       return TRUE;
6159     }
6160
6161   /* Give the processor backend a chance to tweak the symbol value,
6162      and also to finish up anything that needs to be done for this
6163      symbol.  FIXME: Not calling elf_backend_finish_dynamic_symbol for
6164      forced local syms when non-shared is due to a historical quirk.  */
6165   if ((h->dynindx != -1
6166        || (h->elf_link_hash_flags & ELF_LINK_FORCED_LOCAL) != 0)
6167       && ((finfo->info->shared
6168            && (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
6169                || h->root.type != bfd_link_hash_undefweak))
6170           || (h->elf_link_hash_flags & ELF_LINK_FORCED_LOCAL) == 0)
6171       && elf_hash_table (finfo->info)->dynamic_sections_created)
6172     {
6173       if (! ((*bed->elf_backend_finish_dynamic_symbol)
6174              (finfo->output_bfd, finfo->info, h, &sym)))
6175         {
6176           eoinfo->failed = TRUE;
6177           return FALSE;
6178         }
6179     }
6180
6181   /* If we are marking the symbol as undefined, and there are no
6182      non-weak references to this symbol from a regular object, then
6183      mark the symbol as weak undefined; if there are non-weak
6184      references, mark the symbol as strong.  We can't do this earlier,
6185      because it might not be marked as undefined until the
6186      finish_dynamic_symbol routine gets through with it.  */
6187   if (sym.st_shndx == SHN_UNDEF
6188       && (h->elf_link_hash_flags & ELF_LINK_HASH_REF_REGULAR) != 0
6189       && (ELF_ST_BIND (sym.st_info) == STB_GLOBAL
6190           || ELF_ST_BIND (sym.st_info) == STB_WEAK))
6191     {
6192       int bindtype;
6193
6194       if ((h->elf_link_hash_flags & ELF_LINK_HASH_REF_REGULAR_NONWEAK) != 0)
6195         bindtype = STB_GLOBAL;
6196       else
6197         bindtype = STB_WEAK;
6198       sym.st_info = ELF_ST_INFO (bindtype, ELF_ST_TYPE (sym.st_info));
6199     }
6200
6201   /* If a non-weak symbol with non-default visibility is not defined
6202      locally, it is a fatal error.  */
6203   if (! finfo->info->relocatable
6204       && ELF_ST_VISIBILITY (sym.st_other) != STV_DEFAULT
6205       && ELF_ST_BIND (sym.st_info) != STB_WEAK
6206       && h->root.type == bfd_link_hash_undefined
6207       && (h->elf_link_hash_flags & ELF_LINK_HASH_DEF_REGULAR) == 0)
6208     {
6209       (*_bfd_error_handler)
6210         (_("%B: %s symbol `%s' isn't defined"),
6211          finfo->output_bfd,
6212          ELF_ST_VISIBILITY (sym.st_other) == STV_PROTECTED
6213          ? "protected"
6214          : ELF_ST_VISIBILITY (sym.st_other) == STV_INTERNAL
6215          ? "internal" : "hidden",
6216          h->root.root.string);
6217       eoinfo->failed = TRUE;
6218       return FALSE;
6219     }
6220
6221   /* If this symbol should be put in the .dynsym section, then put it
6222      there now.  We already know the symbol index.  We also fill in
6223      the entry in the .hash section.  */
6224   if (h->dynindx != -1
6225       && elf_hash_table (finfo->info)->dynamic_sections_created)
6226     {
6227       size_t bucketcount;
6228       size_t bucket;
6229       size_t hash_entry_size;
6230       bfd_byte *bucketpos;
6231       bfd_vma chain;
6232       bfd_byte *esym;
6233
6234       sym.st_name = h->dynstr_index;
6235       esym = finfo->dynsym_sec->contents + h->dynindx * bed->s->sizeof_sym;
6236       bed->s->swap_symbol_out (finfo->output_bfd, &sym, esym, 0);
6237
6238       bucketcount = elf_hash_table (finfo->info)->bucketcount;
6239       bucket = h->elf_hash_value % bucketcount;
6240       hash_entry_size
6241         = elf_section_data (finfo->hash_sec)->this_hdr.sh_entsize;
6242       bucketpos = ((bfd_byte *) finfo->hash_sec->contents
6243                    + (bucket + 2) * hash_entry_size);
6244       chain = bfd_get (8 * hash_entry_size, finfo->output_bfd, bucketpos);
6245       bfd_put (8 * hash_entry_size, finfo->output_bfd, h->dynindx, bucketpos);
6246       bfd_put (8 * hash_entry_size, finfo->output_bfd, chain,
6247                ((bfd_byte *) finfo->hash_sec->contents
6248                 + (bucketcount + 2 + h->dynindx) * hash_entry_size));
6249
6250       if (finfo->symver_sec != NULL && finfo->symver_sec->contents != NULL)
6251         {
6252           Elf_Internal_Versym iversym;
6253           Elf_External_Versym *eversym;
6254
6255           if ((h->elf_link_hash_flags & ELF_LINK_HASH_DEF_REGULAR) == 0)
6256             {
6257               if (h->verinfo.verdef == NULL)
6258                 iversym.vs_vers = 0;
6259               else
6260                 iversym.vs_vers = h->verinfo.verdef->vd_exp_refno + 1;
6261             }
6262           else
6263             {
6264               if (h->verinfo.vertree == NULL)
6265                 iversym.vs_vers = 1;
6266               else
6267                 iversym.vs_vers = h->verinfo.vertree->vernum + 1;
6268             }
6269
6270           if ((h->elf_link_hash_flags & ELF_LINK_HIDDEN) != 0)
6271             iversym.vs_vers |= VERSYM_HIDDEN;
6272
6273           eversym = (Elf_External_Versym *) finfo->symver_sec->contents;
6274           eversym += h->dynindx;
6275           _bfd_elf_swap_versym_out (finfo->output_bfd, &iversym, eversym);
6276         }
6277     }
6278
6279   /* If we're stripping it, then it was just a dynamic symbol, and
6280      there's nothing else to do.  */
6281   if (strip || (input_sec->flags & SEC_EXCLUDE) != 0)
6282     return TRUE;
6283
6284   h->indx = bfd_get_symcount (finfo->output_bfd);
6285
6286   if (! elf_link_output_sym (finfo, h->root.root.string, &sym, input_sec, h))
6287     {
6288       eoinfo->failed = TRUE;
6289       return FALSE;
6290     }
6291
6292   return TRUE;
6293 }
6294
6295 /* Return TRUE if special handling is done for relocs in SEC against
6296    symbols defined in discarded sections.  */
6297
6298 static bfd_boolean
6299 elf_section_ignore_discarded_relocs (asection *sec)
6300 {
6301   const struct elf_backend_data *bed;
6302
6303   switch (sec->sec_info_type)
6304     {
6305     case ELF_INFO_TYPE_STABS:
6306     case ELF_INFO_TYPE_EH_FRAME:
6307       return TRUE;
6308     default:
6309       break;
6310     }
6311
6312   bed = get_elf_backend_data (sec->owner);
6313   if (bed->elf_backend_ignore_discarded_relocs != NULL
6314       && (*bed->elf_backend_ignore_discarded_relocs) (sec))
6315     return TRUE;
6316
6317   return FALSE;
6318 }
6319
6320 /* Return TRUE if we should complain about a reloc in SEC against a
6321    symbol defined in a discarded section.  */
6322
6323 static bfd_boolean
6324 elf_section_complain_discarded (asection *sec)
6325 {
6326   if (strncmp (".stab", sec->name, 5) == 0
6327       && (!sec->name[5] ||
6328           (sec->name[5] == '.' && ISDIGIT (sec->name[6]))))
6329     return FALSE;
6330
6331   if (strcmp (".eh_frame", sec->name) == 0)
6332     return FALSE;
6333
6334   if (strcmp (".gcc_except_table", sec->name) == 0)
6335     return FALSE;
6336
6337   if (strcmp (".PARISC.unwind", sec->name) == 0)
6338     return FALSE;
6339
6340   if (strcmp (".fixup", sec->name) == 0)
6341     return FALSE;
6342
6343   return TRUE;
6344 }
6345
6346 /* Find a match between a section and a member of a section group.  */
6347
6348 static asection *
6349 match_group_member (asection *sec, asection *group)
6350 {
6351   asection *first = elf_next_in_group (group);
6352   asection *s = first;
6353
6354   while (s != NULL)
6355     {
6356       if (bfd_elf_match_symbols_in_sections (s, sec))
6357         return s;
6358
6359       if (s == first)
6360         break;
6361     }
6362
6363   return NULL;
6364 }
6365
6366 /* Link an input file into the linker output file.  This function
6367    handles all the sections and relocations of the input file at once.
6368    This is so that we only have to read the local symbols once, and
6369    don't have to keep them in memory.  */
6370
6371 static bfd_boolean
6372 elf_link_input_bfd (struct elf_final_link_info *finfo, bfd *input_bfd)
6373 {
6374   bfd_boolean (*relocate_section)
6375     (bfd *, struct bfd_link_info *, bfd *, asection *, bfd_byte *,
6376      Elf_Internal_Rela *, Elf_Internal_Sym *, asection **);
6377   bfd *output_bfd;
6378   Elf_Internal_Shdr *symtab_hdr;
6379   size_t locsymcount;
6380   size_t extsymoff;
6381   Elf_Internal_Sym *isymbuf;
6382   Elf_Internal_Sym *isym;
6383   Elf_Internal_Sym *isymend;
6384   long *pindex;
6385   asection **ppsection;
6386   asection *o;
6387   const struct elf_backend_data *bed;
6388   bfd_boolean emit_relocs;
6389   struct elf_link_hash_entry **sym_hashes;
6390
6391   output_bfd = finfo->output_bfd;
6392   bed = get_elf_backend_data (output_bfd);
6393   relocate_section = bed->elf_backend_relocate_section;
6394
6395   /* If this is a dynamic object, we don't want to do anything here:
6396      we don't want the local symbols, and we don't want the section
6397      contents.  */
6398   if ((input_bfd->flags & DYNAMIC) != 0)
6399     return TRUE;
6400
6401   emit_relocs = (finfo->info->relocatable
6402                  || finfo->info->emitrelocations
6403                  || bed->elf_backend_emit_relocs);
6404
6405   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
6406   if (elf_bad_symtab (input_bfd))
6407     {
6408       locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
6409       extsymoff = 0;
6410     }
6411   else
6412     {
6413       locsymcount = symtab_hdr->sh_info;
6414       extsymoff = symtab_hdr->sh_info;
6415     }
6416
6417   /* Read the local symbols.  */
6418   isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
6419   if (isymbuf == NULL && locsymcount != 0)
6420     {
6421       isymbuf = bfd_elf_get_elf_syms (input_bfd, symtab_hdr, locsymcount, 0,
6422                                       finfo->internal_syms,
6423                                       finfo->external_syms,
6424                                       finfo->locsym_shndx);
6425       if (isymbuf == NULL)
6426         return FALSE;
6427     }
6428
6429   /* Find local symbol sections and adjust values of symbols in
6430      SEC_MERGE sections.  Write out those local symbols we know are
6431      going into the output file.  */
6432   isymend = isymbuf + locsymcount;
6433   for (isym = isymbuf, pindex = finfo->indices, ppsection = finfo->sections;
6434        isym < isymend;
6435        isym++, pindex++, ppsection++)
6436     {
6437       asection *isec;
6438       const char *name;
6439       Elf_Internal_Sym osym;
6440
6441       *pindex = -1;
6442
6443       if (elf_bad_symtab (input_bfd))
6444         {
6445           if (ELF_ST_BIND (isym->st_info) != STB_LOCAL)
6446             {
6447               *ppsection = NULL;
6448               continue;
6449             }
6450         }
6451
6452       if (isym->st_shndx == SHN_UNDEF)
6453         isec = bfd_und_section_ptr;
6454       else if (isym->st_shndx < SHN_LORESERVE
6455                || isym->st_shndx > SHN_HIRESERVE)
6456         {
6457           isec = bfd_section_from_elf_index (input_bfd, isym->st_shndx);
6458           if (isec
6459               && isec->sec_info_type == ELF_INFO_TYPE_MERGE
6460               && ELF_ST_TYPE (isym->st_info) != STT_SECTION)
6461             isym->st_value =
6462               _bfd_merged_section_offset (output_bfd, &isec,
6463                                           elf_section_data (isec)->sec_info,
6464                                           isym->st_value);
6465         }
6466       else if (isym->st_shndx == SHN_ABS)
6467         isec = bfd_abs_section_ptr;
6468       else if (isym->st_shndx == SHN_COMMON)
6469         isec = bfd_com_section_ptr;
6470       else
6471         {
6472           /* Who knows?  */
6473           isec = NULL;
6474         }
6475
6476       *ppsection = isec;
6477
6478       /* Don't output the first, undefined, symbol.  */
6479       if (ppsection == finfo->sections)
6480         continue;
6481
6482       if (ELF_ST_TYPE (isym->st_info) == STT_SECTION)
6483         {
6484           /* We never output section symbols.  Instead, we use the
6485              section symbol of the corresponding section in the output
6486              file.  */
6487           continue;
6488         }
6489
6490       /* If we are stripping all symbols, we don't want to output this
6491          one.  */
6492       if (finfo->info->strip == strip_all)
6493         continue;
6494
6495       /* If we are discarding all local symbols, we don't want to
6496          output this one.  If we are generating a relocatable output
6497          file, then some of the local symbols may be required by
6498          relocs; we output them below as we discover that they are
6499          needed.  */
6500       if (finfo->info->discard == discard_all)
6501         continue;
6502
6503       /* If this symbol is defined in a section which we are
6504          discarding, we don't need to keep it, but note that
6505          linker_mark is only reliable for sections that have contents.
6506          For the benefit of the MIPS ELF linker, we check SEC_EXCLUDE
6507          as well as linker_mark.  */
6508       if ((isym->st_shndx < SHN_LORESERVE || isym->st_shndx > SHN_HIRESERVE)
6509           && isec != NULL
6510           && ((! isec->linker_mark && (isec->flags & SEC_HAS_CONTENTS) != 0)
6511               || (! finfo->info->relocatable
6512                   && (isec->flags & SEC_EXCLUDE) != 0)))
6513         continue;
6514
6515       /* Get the name of the symbol.  */
6516       name = bfd_elf_string_from_elf_section (input_bfd, symtab_hdr->sh_link,
6517                                               isym->st_name);
6518       if (name == NULL)
6519         return FALSE;
6520
6521       /* See if we are discarding symbols with this name.  */
6522       if ((finfo->info->strip == strip_some
6523            && (bfd_hash_lookup (finfo->info->keep_hash, name, FALSE, FALSE)
6524                == NULL))
6525           || (((finfo->info->discard == discard_sec_merge
6526                 && (isec->flags & SEC_MERGE) && ! finfo->info->relocatable)
6527                || finfo->info->discard == discard_l)
6528               && bfd_is_local_label_name (input_bfd, name)))
6529         continue;
6530
6531       /* If we get here, we are going to output this symbol.  */
6532
6533       osym = *isym;
6534
6535       /* Adjust the section index for the output file.  */
6536       osym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
6537                                                          isec->output_section);
6538       if (osym.st_shndx == SHN_BAD)
6539         return FALSE;
6540
6541       *pindex = bfd_get_symcount (output_bfd);
6542
6543       /* ELF symbols in relocatable files are section relative, but
6544          in executable files they are virtual addresses.  Note that
6545          this code assumes that all ELF sections have an associated
6546          BFD section with a reasonable value for output_offset; below
6547          we assume that they also have a reasonable value for
6548          output_section.  Any special sections must be set up to meet
6549          these requirements.  */
6550       osym.st_value += isec->output_offset;
6551       if (! finfo->info->relocatable)
6552         {
6553           osym.st_value += isec->output_section->vma;
6554           if (ELF_ST_TYPE (osym.st_info) == STT_TLS)
6555             {
6556               /* STT_TLS symbols are relative to PT_TLS segment base.  */
6557               BFD_ASSERT (elf_hash_table (finfo->info)->tls_sec != NULL);
6558               osym.st_value -= elf_hash_table (finfo->info)->tls_sec->vma;
6559             }
6560         }
6561
6562       if (! elf_link_output_sym (finfo, name, &osym, isec, NULL))
6563         return FALSE;
6564     }
6565
6566   /* Relocate the contents of each section.  */
6567   sym_hashes = elf_sym_hashes (input_bfd);
6568   for (o = input_bfd->sections; o != NULL; o = o->next)
6569     {
6570       bfd_byte *contents;
6571
6572       if (! o->linker_mark)
6573         {
6574           /* This section was omitted from the link.  */
6575           continue;
6576         }
6577
6578       if ((o->flags & SEC_HAS_CONTENTS) == 0
6579           || (o->size == 0 && (o->flags & SEC_RELOC) == 0))
6580         continue;
6581
6582       if ((o->flags & SEC_LINKER_CREATED) != 0)
6583         {
6584           /* Section was created by _bfd_elf_link_create_dynamic_sections
6585              or somesuch.  */
6586           continue;
6587         }
6588
6589       /* Get the contents of the section.  They have been cached by a
6590          relaxation routine.  Note that o is a section in an input
6591          file, so the contents field will not have been set by any of
6592          the routines which work on output files.  */
6593       if (elf_section_data (o)->this_hdr.contents != NULL)
6594         contents = elf_section_data (o)->this_hdr.contents;
6595       else
6596         {
6597           bfd_size_type amt = o->rawsize ? o->rawsize : o->size;
6598
6599           contents = finfo->contents;
6600           if (! bfd_get_section_contents (input_bfd, o, contents, 0, amt))
6601             return FALSE;
6602         }
6603
6604       if ((o->flags & SEC_RELOC) != 0)
6605         {
6606           Elf_Internal_Rela *internal_relocs;
6607           bfd_vma r_type_mask;
6608           int r_sym_shift;
6609
6610           /* Get the swapped relocs.  */
6611           internal_relocs
6612             = _bfd_elf_link_read_relocs (input_bfd, o, finfo->external_relocs,
6613                                          finfo->internal_relocs, FALSE);
6614           if (internal_relocs == NULL
6615               && o->reloc_count > 0)
6616             return FALSE;
6617
6618           if (bed->s->arch_size == 32)
6619             {
6620               r_type_mask = 0xff;
6621               r_sym_shift = 8;
6622             }
6623           else
6624             {
6625               r_type_mask = 0xffffffff;
6626               r_sym_shift = 32;
6627             }
6628
6629           /* Run through the relocs looking for any against symbols
6630              from discarded sections and section symbols from
6631              removed link-once sections.  Complain about relocs
6632              against discarded sections.  Zero relocs against removed
6633              link-once sections.  Preserve debug information as much
6634              as we can.  */
6635           if (!elf_section_ignore_discarded_relocs (o))
6636             {
6637               Elf_Internal_Rela *rel, *relend;
6638               bfd_boolean complain = elf_section_complain_discarded (o);
6639
6640               rel = internal_relocs;
6641               relend = rel + o->reloc_count * bed->s->int_rels_per_ext_rel;
6642               for ( ; rel < relend; rel++)
6643                 {
6644                   unsigned long r_symndx = rel->r_info >> r_sym_shift;
6645                   asection **ps, *sec;
6646                   struct elf_link_hash_entry *h = NULL;
6647                   const char *sym_name;
6648
6649                   if (r_symndx >= locsymcount
6650                       || (elf_bad_symtab (input_bfd)
6651                           && finfo->sections[r_symndx] == NULL))
6652                     {
6653                       h = sym_hashes[r_symndx - extsymoff];
6654                       while (h->root.type == bfd_link_hash_indirect
6655                              || h->root.type == bfd_link_hash_warning)
6656                         h = (struct elf_link_hash_entry *) h->root.u.i.link;
6657
6658                       if (h->root.type != bfd_link_hash_defined
6659                           && h->root.type != bfd_link_hash_defweak)
6660                         continue;
6661
6662                       ps = &h->root.u.def.section;
6663                       sym_name = h->root.root.string;
6664                     }
6665                   else
6666                     {
6667                       Elf_Internal_Sym *sym = isymbuf + r_symndx;
6668                       ps = &finfo->sections[r_symndx];
6669                       sym_name = bfd_elf_local_sym_name (input_bfd, sym);
6670                     }
6671
6672                   /* Complain if the definition comes from a
6673                      discarded section.  */
6674                   if ((sec = *ps) != NULL && elf_discarded_section (sec))
6675                     {
6676                       if ((o->flags & SEC_DEBUGGING) != 0)
6677                         {
6678                           BFD_ASSERT (r_symndx != 0);
6679
6680                           /* Try to preserve debug information.
6681                              FIXME: This is quite broken.  Modifying
6682                              the symbol here means we will be changing
6683                              all uses of the symbol, not just those in
6684                              debug sections.  The only thing that makes
6685                              this half reasonable is that debug sections
6686                              tend to come after other sections.  Of
6687                              course, that doesn't help with globals.
6688                              ??? All link-once sections of the same name
6689                              ought to define the same set of symbols, so
6690                              it would seem that globals ought to always
6691                              be defined in the kept section.  */
6692                           if (sec->kept_section != NULL)
6693                             {
6694                               asection *member;
6695
6696                               /* Check if it is a linkonce section or
6697                                  member of a comdat group.  */
6698                               if (elf_sec_group (sec) == NULL
6699                                   && sec->size == sec->kept_section->size)
6700                                 {
6701                                   *ps = sec->kept_section;
6702                                   continue;
6703                                 }
6704                               else if (elf_sec_group (sec) != NULL
6705                                        && (member = match_group_member (sec, sec->kept_section))
6706                                        && sec->size == member->size)
6707                                 {
6708                                   *ps = member;
6709                                   continue;
6710                                 }
6711                             }
6712                         }
6713                       else if (complain)
6714                         {
6715                           (*_bfd_error_handler)
6716                             (_("`%s' referenced in section `%A' of %B: "
6717                                "defined in discarded section `%A' of %B\n"),
6718                              o, input_bfd, sec, sec->owner, sym_name);
6719                         }
6720
6721                       /* Remove the symbol reference from the reloc, but
6722                          don't kill the reloc completely.  This is so that
6723                          a zero value will be written into the section,
6724                          which may have non-zero contents put there by the
6725                          assembler.  Zero in things like an eh_frame fde
6726                          pc_begin allows stack unwinders to recognize the
6727                          fde as bogus.  */
6728                       rel->r_info &= r_type_mask;
6729                       rel->r_addend = 0;
6730                     }
6731                 }
6732             }
6733
6734           /* Relocate the section by invoking a back end routine.
6735
6736              The back end routine is responsible for adjusting the
6737              section contents as necessary, and (if using Rela relocs
6738              and generating a relocatable output file) adjusting the
6739              reloc addend as necessary.
6740
6741              The back end routine does not have to worry about setting
6742              the reloc address or the reloc symbol index.
6743
6744              The back end routine is given a pointer to the swapped in
6745              internal symbols, and can access the hash table entries
6746              for the external symbols via elf_sym_hashes (input_bfd).
6747
6748              When generating relocatable output, the back end routine
6749              must handle STB_LOCAL/STT_SECTION symbols specially.  The
6750              output symbol is going to be a section symbol
6751              corresponding to the output section, which will require
6752              the addend to be adjusted.  */
6753
6754           if (! (*relocate_section) (output_bfd, finfo->info,
6755                                      input_bfd, o, contents,
6756                                      internal_relocs,
6757                                      isymbuf,
6758                                      finfo->sections))
6759             return FALSE;
6760
6761           if (emit_relocs)
6762             {
6763               Elf_Internal_Rela *irela;
6764               Elf_Internal_Rela *irelaend;
6765               bfd_vma last_offset;
6766               struct elf_link_hash_entry **rel_hash;
6767               Elf_Internal_Shdr *input_rel_hdr, *input_rel_hdr2;
6768               unsigned int next_erel;
6769               bfd_boolean (*reloc_emitter)
6770                 (bfd *, asection *, Elf_Internal_Shdr *, Elf_Internal_Rela *);
6771               bfd_boolean rela_normal;
6772
6773               input_rel_hdr = &elf_section_data (o)->rel_hdr;
6774               rela_normal = (bed->rela_normal
6775                              && (input_rel_hdr->sh_entsize
6776                                  == bed->s->sizeof_rela));
6777
6778               /* Adjust the reloc addresses and symbol indices.  */
6779
6780               irela = internal_relocs;
6781               irelaend = irela + o->reloc_count * bed->s->int_rels_per_ext_rel;
6782               rel_hash = (elf_section_data (o->output_section)->rel_hashes
6783                           + elf_section_data (o->output_section)->rel_count
6784                           + elf_section_data (o->output_section)->rel_count2);
6785               last_offset = o->output_offset;
6786               if (!finfo->info->relocatable)
6787                 last_offset += o->output_section->vma;
6788               for (next_erel = 0; irela < irelaend; irela++, next_erel++)
6789                 {
6790                   unsigned long r_symndx;
6791                   asection *sec;
6792                   Elf_Internal_Sym sym;
6793
6794                   if (next_erel == bed->s->int_rels_per_ext_rel)
6795                     {
6796                       rel_hash++;
6797                       next_erel = 0;
6798                     }
6799
6800                   irela->r_offset = _bfd_elf_section_offset (output_bfd,
6801                                                              finfo->info, o,
6802                                                              irela->r_offset);
6803                   if (irela->r_offset >= (bfd_vma) -2)
6804                     {
6805                       /* This is a reloc for a deleted entry or somesuch.
6806                          Turn it into an R_*_NONE reloc, at the same
6807                          offset as the last reloc.  elf_eh_frame.c and
6808                          elf_bfd_discard_info rely on reloc offsets
6809                          being ordered.  */
6810                       irela->r_offset = last_offset;
6811                       irela->r_info = 0;
6812                       irela->r_addend = 0;
6813                       continue;
6814                     }
6815
6816                   irela->r_offset += o->output_offset;
6817
6818                   /* Relocs in an executable have to be virtual addresses.  */
6819                   if (!finfo->info->relocatable)
6820                     irela->r_offset += o->output_section->vma;
6821
6822                   last_offset = irela->r_offset;
6823
6824                   r_symndx = irela->r_info >> r_sym_shift;
6825                   if (r_symndx == STN_UNDEF)
6826                     continue;
6827
6828                   if (r_symndx >= locsymcount
6829                       || (elf_bad_symtab (input_bfd)
6830                           && finfo->sections[r_symndx] == NULL))
6831                     {
6832                       struct elf_link_hash_entry *rh;
6833                       unsigned long indx;
6834
6835                       /* This is a reloc against a global symbol.  We
6836                          have not yet output all the local symbols, so
6837                          we do not know the symbol index of any global
6838                          symbol.  We set the rel_hash entry for this
6839                          reloc to point to the global hash table entry
6840                          for this symbol.  The symbol index is then
6841                          set at the end of elf_bfd_final_link.  */
6842                       indx = r_symndx - extsymoff;
6843                       rh = elf_sym_hashes (input_bfd)[indx];
6844                       while (rh->root.type == bfd_link_hash_indirect
6845                              || rh->root.type == bfd_link_hash_warning)
6846                         rh = (struct elf_link_hash_entry *) rh->root.u.i.link;
6847
6848                       /* Setting the index to -2 tells
6849                          elf_link_output_extsym that this symbol is
6850                          used by a reloc.  */
6851                       BFD_ASSERT (rh->indx < 0);
6852                       rh->indx = -2;
6853
6854                       *rel_hash = rh;
6855
6856                       continue;
6857                     }
6858
6859                   /* This is a reloc against a local symbol.  */
6860
6861                   *rel_hash = NULL;
6862                   sym = isymbuf[r_symndx];
6863                   sec = finfo->sections[r_symndx];
6864                   if (ELF_ST_TYPE (sym.st_info) == STT_SECTION)
6865                     {
6866                       /* I suppose the backend ought to fill in the
6867                          section of any STT_SECTION symbol against a
6868                          processor specific section.  */
6869                       r_symndx = 0;
6870                       if (bfd_is_abs_section (sec))
6871                         ;
6872                       else if (sec == NULL || sec->owner == NULL)
6873                         {
6874                           bfd_set_error (bfd_error_bad_value);
6875                           return FALSE;
6876                         }
6877                       else
6878                         {
6879                           asection *osec = sec->output_section;
6880
6881                           /* If we have discarded a section, the output
6882                              section will be the absolute section.  In
6883                              case of discarded link-once and discarded
6884                              SEC_MERGE sections, use the kept section.  */
6885                           if (bfd_is_abs_section (osec)
6886                               && sec->kept_section != NULL
6887                               && sec->kept_section->output_section != NULL)
6888                             {
6889                               osec = sec->kept_section->output_section;
6890                               irela->r_addend -= osec->vma;
6891                             }
6892
6893                           if (!bfd_is_abs_section (osec))
6894                             {
6895                               r_symndx = osec->target_index;
6896                               BFD_ASSERT (r_symndx != 0);
6897                             }
6898                         }
6899
6900                       /* Adjust the addend according to where the
6901                          section winds up in the output section.  */
6902                       if (rela_normal)
6903                         irela->r_addend += sec->output_offset;
6904                     }
6905                   else
6906                     {
6907                       if (finfo->indices[r_symndx] == -1)
6908                         {
6909                           unsigned long shlink;
6910                           const char *name;
6911                           asection *osec;
6912
6913                           if (finfo->info->strip == strip_all)
6914                             {
6915                               /* You can't do ld -r -s.  */
6916                               bfd_set_error (bfd_error_invalid_operation);
6917                               return FALSE;
6918                             }
6919
6920                           /* This symbol was skipped earlier, but
6921                              since it is needed by a reloc, we
6922                              must output it now.  */
6923                           shlink = symtab_hdr->sh_link;
6924                           name = (bfd_elf_string_from_elf_section
6925                                   (input_bfd, shlink, sym.st_name));
6926                           if (name == NULL)
6927                             return FALSE;
6928
6929                           osec = sec->output_section;
6930                           sym.st_shndx =
6931                             _bfd_elf_section_from_bfd_section (output_bfd,
6932                                                                osec);
6933                           if (sym.st_shndx == SHN_BAD)
6934                             return FALSE;
6935
6936                           sym.st_value += sec->output_offset;
6937                           if (! finfo->info->relocatable)
6938                             {
6939                               sym.st_value += osec->vma;
6940                               if (ELF_ST_TYPE (sym.st_info) == STT_TLS)
6941                                 {
6942                                   /* STT_TLS symbols are relative to PT_TLS
6943                                      segment base.  */
6944                                   BFD_ASSERT (elf_hash_table (finfo->info)
6945                                               ->tls_sec != NULL);
6946                                   sym.st_value -= (elf_hash_table (finfo->info)
6947                                                    ->tls_sec->vma);
6948                                 }
6949                             }
6950
6951                           finfo->indices[r_symndx]
6952                             = bfd_get_symcount (output_bfd);
6953
6954                           if (! elf_link_output_sym (finfo, name, &sym, sec,
6955                                                      NULL))
6956                             return FALSE;
6957                         }
6958
6959                       r_symndx = finfo->indices[r_symndx];
6960                     }
6961
6962                   irela->r_info = ((bfd_vma) r_symndx << r_sym_shift
6963                                    | (irela->r_info & r_type_mask));
6964                 }
6965
6966               /* Swap out the relocs.  */
6967               if (bed->elf_backend_emit_relocs
6968                   && !(finfo->info->relocatable
6969                        || finfo->info->emitrelocations))
6970                 reloc_emitter = bed->elf_backend_emit_relocs;
6971               else
6972                 reloc_emitter = _bfd_elf_link_output_relocs;
6973
6974               if (input_rel_hdr->sh_size != 0
6975                   && ! (*reloc_emitter) (output_bfd, o, input_rel_hdr,
6976                                          internal_relocs))
6977                 return FALSE;
6978
6979               input_rel_hdr2 = elf_section_data (o)->rel_hdr2;
6980               if (input_rel_hdr2 && input_rel_hdr2->sh_size != 0)
6981                 {
6982                   internal_relocs += (NUM_SHDR_ENTRIES (input_rel_hdr)
6983                                       * bed->s->int_rels_per_ext_rel);
6984                   if (! (*reloc_emitter) (output_bfd, o, input_rel_hdr2,
6985                                           internal_relocs))
6986                     return FALSE;
6987                 }
6988             }
6989         }
6990
6991       /* Write out the modified section contents.  */
6992       if (bed->elf_backend_write_section
6993           && (*bed->elf_backend_write_section) (output_bfd, o, contents))
6994         {
6995           /* Section written out.  */
6996         }
6997       else switch (o->sec_info_type)
6998         {
6999         case ELF_INFO_TYPE_STABS:
7000           if (! (_bfd_write_section_stabs
7001                  (output_bfd,
7002                   &elf_hash_table (finfo->info)->stab_info,
7003                   o, &elf_section_data (o)->sec_info, contents)))
7004             return FALSE;
7005           break;
7006         case ELF_INFO_TYPE_MERGE:
7007           if (! _bfd_write_merged_section (output_bfd, o,
7008                                            elf_section_data (o)->sec_info))
7009             return FALSE;
7010           break;
7011         case ELF_INFO_TYPE_EH_FRAME:
7012           {
7013             if (! _bfd_elf_write_section_eh_frame (output_bfd, finfo->info,
7014                                                    o, contents))
7015               return FALSE;
7016           }
7017           break;
7018         default:
7019           {
7020             if (! (o->flags & SEC_EXCLUDE)
7021                 && ! bfd_set_section_contents (output_bfd, o->output_section,
7022                                                contents,
7023                                                (file_ptr) o->output_offset,
7024                                                o->size))
7025               return FALSE;
7026           }
7027           break;
7028         }
7029     }
7030
7031   return TRUE;
7032 }
7033
7034 /* Generate a reloc when linking an ELF file.  This is a reloc
7035    requested by the linker, and does come from any input file.  This
7036    is used to build constructor and destructor tables when linking
7037    with -Ur.  */
7038
7039 static bfd_boolean
7040 elf_reloc_link_order (bfd *output_bfd,
7041                       struct bfd_link_info *info,
7042                       asection *output_section,
7043                       struct bfd_link_order *link_order)
7044 {
7045   reloc_howto_type *howto;
7046   long indx;
7047   bfd_vma offset;
7048   bfd_vma addend;
7049   struct elf_link_hash_entry **rel_hash_ptr;
7050   Elf_Internal_Shdr *rel_hdr;
7051   const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
7052   Elf_Internal_Rela irel[MAX_INT_RELS_PER_EXT_REL];
7053   bfd_byte *erel;
7054   unsigned int i;
7055
7056   howto = bfd_reloc_type_lookup (output_bfd, link_order->u.reloc.p->reloc);
7057   if (howto == NULL)
7058     {
7059       bfd_set_error (bfd_error_bad_value);
7060       return FALSE;
7061     }
7062
7063   addend = link_order->u.reloc.p->addend;
7064
7065   /* Figure out the symbol index.  */
7066   rel_hash_ptr = (elf_section_data (output_section)->rel_hashes
7067                   + elf_section_data (output_section)->rel_count
7068                   + elf_section_data (output_section)->rel_count2);
7069   if (link_order->type == bfd_section_reloc_link_order)
7070     {
7071       indx = link_order->u.reloc.p->u.section->target_index;
7072       BFD_ASSERT (indx != 0);
7073       *rel_hash_ptr = NULL;
7074     }
7075   else
7076     {
7077       struct elf_link_hash_entry *h;
7078
7079       /* Treat a reloc against a defined symbol as though it were
7080          actually against the section.  */
7081       h = ((struct elf_link_hash_entry *)
7082            bfd_wrapped_link_hash_lookup (output_bfd, info,
7083                                          link_order->u.reloc.p->u.name,
7084                                          FALSE, FALSE, TRUE));
7085       if (h != NULL
7086           && (h->root.type == bfd_link_hash_defined
7087               || h->root.type == bfd_link_hash_defweak))
7088         {
7089           asection *section;
7090
7091           section = h->root.u.def.section;
7092           indx = section->output_section->target_index;
7093           *rel_hash_ptr = NULL;
7094           /* It seems that we ought to add the symbol value to the
7095              addend here, but in practice it has already been added
7096              because it was passed to constructor_callback.  */
7097           addend += section->output_section->vma + section->output_offset;
7098         }
7099       else if (h != NULL)
7100         {
7101           /* Setting the index to -2 tells elf_link_output_extsym that
7102              this symbol is used by a reloc.  */
7103           h->indx = -2;
7104           *rel_hash_ptr = h;
7105           indx = 0;
7106         }
7107       else
7108         {
7109           if (! ((*info->callbacks->unattached_reloc)
7110                  (info, link_order->u.reloc.p->u.name, NULL, NULL, 0)))
7111             return FALSE;
7112           indx = 0;
7113         }
7114     }
7115
7116   /* If this is an inplace reloc, we must write the addend into the
7117      object file.  */
7118   if (howto->partial_inplace && addend != 0)
7119     {
7120       bfd_size_type size;
7121       bfd_reloc_status_type rstat;
7122       bfd_byte *buf;
7123       bfd_boolean ok;
7124       const char *sym_name;
7125
7126       size = bfd_get_reloc_size (howto);
7127       buf = bfd_zmalloc (size);
7128       if (buf == NULL)
7129         return FALSE;
7130       rstat = _bfd_relocate_contents (howto, output_bfd, addend, buf);
7131       switch (rstat)
7132         {
7133         case bfd_reloc_ok:
7134           break;
7135
7136         default:
7137         case bfd_reloc_outofrange:
7138           abort ();
7139
7140         case bfd_reloc_overflow:
7141           if (link_order->type == bfd_section_reloc_link_order)
7142             sym_name = bfd_section_name (output_bfd,
7143                                          link_order->u.reloc.p->u.section);
7144           else
7145             sym_name = link_order->u.reloc.p->u.name;
7146           if (! ((*info->callbacks->reloc_overflow)
7147                  (info, sym_name, howto->name, addend, NULL, NULL, 0)))
7148             {
7149               free (buf);
7150               return FALSE;
7151             }
7152           break;
7153         }
7154       ok = bfd_set_section_contents (output_bfd, output_section, buf,
7155                                      link_order->offset, size);
7156       free (buf);
7157       if (! ok)
7158         return FALSE;
7159     }
7160
7161   /* The address of a reloc is relative to the section in a
7162      relocatable file, and is a virtual address in an executable
7163      file.  */
7164   offset = link_order->offset;
7165   if (! info->relocatable)
7166     offset += output_section->vma;
7167
7168   for (i = 0; i < bed->s->int_rels_per_ext_rel; i++)
7169     {
7170       irel[i].r_offset = offset;
7171       irel[i].r_info = 0;
7172       irel[i].r_addend = 0;
7173     }
7174   if (bed->s->arch_size == 32)
7175     irel[0].r_info = ELF32_R_INFO (indx, howto->type);
7176   else
7177     irel[0].r_info = ELF64_R_INFO (indx, howto->type);
7178
7179   rel_hdr = &elf_section_data (output_section)->rel_hdr;
7180   erel = rel_hdr->contents;
7181   if (rel_hdr->sh_type == SHT_REL)
7182     {
7183       erel += (elf_section_data (output_section)->rel_count
7184                * bed->s->sizeof_rel);
7185       (*bed->s->swap_reloc_out) (output_bfd, irel, erel);
7186     }
7187   else
7188     {
7189       irel[0].r_addend = addend;
7190       erel += (elf_section_data (output_section)->rel_count
7191                * bed->s->sizeof_rela);
7192       (*bed->s->swap_reloca_out) (output_bfd, irel, erel);
7193     }
7194
7195   ++elf_section_data (output_section)->rel_count;
7196
7197   return TRUE;
7198 }
7199
7200
7201 /* Get the output vma of the section pointed to by the sh_link field.  */
7202
7203 static bfd_vma
7204 elf_get_linked_section_vma (struct bfd_link_order *p)
7205 {
7206   Elf_Internal_Shdr **elf_shdrp;
7207   asection *s;
7208   int elfsec;
7209
7210   s = p->u.indirect.section;
7211   elf_shdrp = elf_elfsections (s->owner);
7212   elfsec = _bfd_elf_section_from_bfd_section (s->owner, s);
7213   elfsec = elf_shdrp[elfsec]->sh_link;
7214   /* PR 290:
7215      The Intel C compiler generates SHT_IA_64_UNWIND with
7216      SHF_LINK_ORDER.  But it doesn't set theh sh_link or
7217      sh_info fields.  Hence we could get the situation
7218      where elfsec is 0.  */
7219   if (elfsec == 0)
7220     {
7221       const struct elf_backend_data *bed
7222         = get_elf_backend_data (s->owner);
7223       if (bed->link_order_error_handler)
7224         bed->link_order_error_handler
7225           (_("%B: warning: sh_link not set for section `%A'"), s->owner, s);
7226       return 0;
7227     }
7228   else
7229     {
7230       s = elf_shdrp[elfsec]->bfd_section;
7231       return s->output_section->vma + s->output_offset;
7232     }
7233 }
7234
7235
7236 /* Compare two sections based on the locations of the sections they are
7237    linked to.  Used by elf_fixup_link_order.  */
7238
7239 static int
7240 compare_link_order (const void * a, const void * b)
7241 {
7242   bfd_vma apos;
7243   bfd_vma bpos;
7244
7245   apos = elf_get_linked_section_vma (*(struct bfd_link_order **)a);
7246   bpos = elf_get_linked_section_vma (*(struct bfd_link_order **)b);
7247   if (apos < bpos)
7248     return -1;
7249   return apos > bpos;
7250 }
7251
7252
7253 /* Looks for sections with SHF_LINK_ORDER set.  Rearranges them into the same
7254    order as their linked sections.  Returns false if this could not be done
7255    because an output section includes both ordered and unordered
7256    sections.  Ideally we'd do this in the linker proper.  */
7257
7258 static bfd_boolean
7259 elf_fixup_link_order (bfd *abfd, asection *o)
7260 {
7261   int seen_linkorder;
7262   int seen_other;
7263   int n;
7264   struct bfd_link_order *p;
7265   bfd *sub;
7266   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
7267   int elfsec;
7268   struct bfd_link_order **sections;
7269   asection *s;
7270   bfd_vma offset;
7271   
7272   seen_other = 0;
7273   seen_linkorder = 0;
7274   for (p = o->link_order_head; p != NULL; p = p->next)
7275     {
7276       if (p->type == bfd_indirect_link_order
7277           && (bfd_get_flavour ((sub = p->u.indirect.section->owner))
7278               == bfd_target_elf_flavour)
7279           && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass)
7280         {
7281           s = p->u.indirect.section;
7282           elfsec = _bfd_elf_section_from_bfd_section (sub, s);
7283           if (elfsec != -1
7284               && elf_elfsections (sub)[elfsec]->sh_flags & SHF_LINK_ORDER)
7285             seen_linkorder++;
7286           else
7287             seen_other++;
7288         }
7289       else
7290         seen_other++;
7291     }
7292
7293   if (!seen_linkorder)
7294     return TRUE;
7295
7296   if (seen_other && seen_linkorder)
7297     {
7298       (*_bfd_error_handler) (_("%A has both ordered and unordered sections"),
7299                              o);
7300       bfd_set_error (bfd_error_bad_value);
7301       return FALSE;
7302     }
7303   
7304   sections = (struct bfd_link_order **)
7305     xmalloc (seen_linkorder * sizeof (struct bfd_link_order *));
7306   seen_linkorder = 0;
7307   
7308   for (p = o->link_order_head; p != NULL; p = p->next)
7309     {
7310       sections[seen_linkorder++] = p;
7311     }
7312   /* Sort the input sections in the order of their linked section.  */
7313   qsort (sections, seen_linkorder, sizeof (struct bfd_link_order *),
7314          compare_link_order);
7315
7316   /* Change the offsets of the sections.  */
7317   offset = 0;
7318   for (n = 0; n < seen_linkorder; n++)
7319     {
7320       s = sections[n]->u.indirect.section;
7321       offset &= ~(bfd_vma)((1 << s->alignment_power) - 1);
7322       s->output_offset = offset;
7323       sections[n]->offset = offset;
7324       offset += sections[n]->size;
7325     }
7326
7327   return TRUE;
7328 }
7329
7330
7331 /* Do the final step of an ELF link.  */
7332
7333 bfd_boolean
7334 bfd_elf_final_link (bfd *abfd, struct bfd_link_info *info)
7335 {
7336   bfd_boolean dynamic;
7337   bfd_boolean emit_relocs;
7338   bfd *dynobj;
7339   struct elf_final_link_info finfo;
7340   register asection *o;
7341   register struct bfd_link_order *p;
7342   register bfd *sub;
7343   bfd_size_type max_contents_size;
7344   bfd_size_type max_external_reloc_size;
7345   bfd_size_type max_internal_reloc_count;
7346   bfd_size_type max_sym_count;
7347   bfd_size_type max_sym_shndx_count;
7348   file_ptr off;
7349   Elf_Internal_Sym elfsym;
7350   unsigned int i;
7351   Elf_Internal_Shdr *symtab_hdr;
7352   Elf_Internal_Shdr *symtab_shndx_hdr;
7353   Elf_Internal_Shdr *symstrtab_hdr;
7354   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
7355   struct elf_outext_info eoinfo;
7356   bfd_boolean merged;
7357   size_t relativecount = 0;
7358   asection *reldyn = 0;
7359   bfd_size_type amt;
7360
7361   if (! is_elf_hash_table (info->hash))
7362     return FALSE;
7363
7364   if (info->shared)
7365     abfd->flags |= DYNAMIC;
7366
7367   dynamic = elf_hash_table (info)->dynamic_sections_created;
7368   dynobj = elf_hash_table (info)->dynobj;
7369
7370   emit_relocs = (info->relocatable
7371                  || info->emitrelocations
7372                  || bed->elf_backend_emit_relocs);
7373
7374   finfo.info = info;
7375   finfo.output_bfd = abfd;
7376   finfo.symstrtab = _bfd_elf_stringtab_init ();
7377   if (finfo.symstrtab == NULL)
7378     return FALSE;
7379
7380   if (! dynamic)
7381     {
7382       finfo.dynsym_sec = NULL;
7383       finfo.hash_sec = NULL;
7384       finfo.symver_sec = NULL;
7385     }
7386   else
7387     {
7388       finfo.dynsym_sec = bfd_get_section_by_name (dynobj, ".dynsym");
7389       finfo.hash_sec = bfd_get_section_by_name (dynobj, ".hash");
7390       BFD_ASSERT (finfo.dynsym_sec != NULL && finfo.hash_sec != NULL);
7391       finfo.symver_sec = bfd_get_section_by_name (dynobj, ".gnu.version");
7392       /* Note that it is OK if symver_sec is NULL.  */
7393     }
7394
7395   finfo.contents = NULL;
7396   finfo.external_relocs = NULL;
7397   finfo.internal_relocs = NULL;
7398   finfo.external_syms = NULL;
7399   finfo.locsym_shndx = NULL;
7400   finfo.internal_syms = NULL;
7401   finfo.indices = NULL;
7402   finfo.sections = NULL;
7403   finfo.symbuf = NULL;
7404   finfo.symshndxbuf = NULL;
7405   finfo.symbuf_count = 0;
7406   finfo.shndxbuf_size = 0;
7407
7408   /* Count up the number of relocations we will output for each output
7409      section, so that we know the sizes of the reloc sections.  We
7410      also figure out some maximum sizes.  */
7411   max_contents_size = 0;
7412   max_external_reloc_size = 0;
7413   max_internal_reloc_count = 0;
7414   max_sym_count = 0;
7415   max_sym_shndx_count = 0;
7416   merged = FALSE;
7417   for (o = abfd->sections; o != NULL; o = o->next)
7418     {
7419       struct bfd_elf_section_data *esdo = elf_section_data (o);
7420       o->reloc_count = 0;
7421
7422       for (p = o->link_order_head; p != NULL; p = p->next)
7423         {
7424           unsigned int reloc_count = 0;
7425           struct bfd_elf_section_data *esdi = NULL;
7426           unsigned int *rel_count1;
7427
7428           if (p->type == bfd_section_reloc_link_order
7429               || p->type == bfd_symbol_reloc_link_order)
7430             reloc_count = 1;
7431           else if (p->type == bfd_indirect_link_order)
7432             {
7433               asection *sec;
7434
7435               sec = p->u.indirect.section;
7436               esdi = elf_section_data (sec);
7437
7438               /* Mark all sections which are to be included in the
7439                  link.  This will normally be every section.  We need
7440                  to do this so that we can identify any sections which
7441                  the linker has decided to not include.  */
7442               sec->linker_mark = TRUE;
7443
7444               if (sec->flags & SEC_MERGE)
7445                 merged = TRUE;
7446
7447               if (info->relocatable || info->emitrelocations)
7448                 reloc_count = sec->reloc_count;
7449               else if (bed->elf_backend_count_relocs)
7450                 {
7451                   Elf_Internal_Rela * relocs;
7452
7453                   relocs = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
7454                                                       info->keep_memory);
7455
7456                   reloc_count = (*bed->elf_backend_count_relocs) (sec, relocs);
7457
7458                   if (elf_section_data (o)->relocs != relocs)
7459                     free (relocs);
7460                 }
7461
7462               if (sec->rawsize > max_contents_size)
7463                 max_contents_size = sec->rawsize;
7464               if (sec->size > max_contents_size)
7465                 max_contents_size = sec->size;
7466
7467               /* We are interested in just local symbols, not all
7468                  symbols.  */
7469               if (bfd_get_flavour (sec->owner) == bfd_target_elf_flavour
7470                   && (sec->owner->flags & DYNAMIC) == 0)
7471                 {
7472                   size_t sym_count;
7473
7474                   if (elf_bad_symtab (sec->owner))
7475                     sym_count = (elf_tdata (sec->owner)->symtab_hdr.sh_size
7476                                  / bed->s->sizeof_sym);
7477                   else
7478                     sym_count = elf_tdata (sec->owner)->symtab_hdr.sh_info;
7479
7480                   if (sym_count > max_sym_count)
7481                     max_sym_count = sym_count;
7482
7483                   if (sym_count > max_sym_shndx_count
7484                       && elf_symtab_shndx (sec->owner) != 0)
7485                     max_sym_shndx_count = sym_count;
7486
7487                   if ((sec->flags & SEC_RELOC) != 0)
7488                     {
7489                       size_t ext_size;
7490
7491                       ext_size = elf_section_data (sec)->rel_hdr.sh_size;
7492                       if (ext_size > max_external_reloc_size)
7493                         max_external_reloc_size = ext_size;
7494                       if (sec->reloc_count > max_internal_reloc_count)
7495                         max_internal_reloc_count = sec->reloc_count;
7496                     }
7497                 }
7498             }
7499
7500           if (reloc_count == 0)
7501             continue;
7502
7503           o->reloc_count += reloc_count;
7504
7505           /* MIPS may have a mix of REL and RELA relocs on sections.
7506              To support this curious ABI we keep reloc counts in
7507              elf_section_data too.  We must be careful to add the
7508              relocations from the input section to the right output
7509              count.  FIXME: Get rid of one count.  We have
7510              o->reloc_count == esdo->rel_count + esdo->rel_count2.  */
7511           rel_count1 = &esdo->rel_count;
7512           if (esdi != NULL)
7513             {
7514               bfd_boolean same_size;
7515               bfd_size_type entsize1;
7516
7517               entsize1 = esdi->rel_hdr.sh_entsize;
7518               BFD_ASSERT (entsize1 == bed->s->sizeof_rel
7519                           || entsize1 == bed->s->sizeof_rela);
7520               same_size = !o->use_rela_p == (entsize1 == bed->s->sizeof_rel);
7521
7522               if (!same_size)
7523                 rel_count1 = &esdo->rel_count2;
7524
7525               if (esdi->rel_hdr2 != NULL)
7526                 {
7527                   bfd_size_type entsize2 = esdi->rel_hdr2->sh_entsize;
7528                   unsigned int alt_count;
7529                   unsigned int *rel_count2;
7530
7531                   BFD_ASSERT (entsize2 != entsize1
7532                               && (entsize2 == bed->s->sizeof_rel
7533                                   || entsize2 == bed->s->sizeof_rela));
7534
7535                   rel_count2 = &esdo->rel_count2;
7536                   if (!same_size)
7537                     rel_count2 = &esdo->rel_count;
7538
7539                   /* The following is probably too simplistic if the
7540                      backend counts output relocs unusually.  */
7541                   BFD_ASSERT (bed->elf_backend_count_relocs == NULL);
7542                   alt_count = NUM_SHDR_ENTRIES (esdi->rel_hdr2);
7543                   *rel_count2 += alt_count;
7544                   reloc_count -= alt_count;
7545                 }
7546             }
7547           *rel_count1 += reloc_count;
7548         }
7549
7550       if (o->reloc_count > 0)
7551         o->flags |= SEC_RELOC;
7552       else
7553         {
7554           /* Explicitly clear the SEC_RELOC flag.  The linker tends to
7555              set it (this is probably a bug) and if it is set
7556              assign_section_numbers will create a reloc section.  */
7557           o->flags &=~ SEC_RELOC;
7558         }
7559
7560       /* If the SEC_ALLOC flag is not set, force the section VMA to
7561          zero.  This is done in elf_fake_sections as well, but forcing
7562          the VMA to 0 here will ensure that relocs against these
7563          sections are handled correctly.  */
7564       if ((o->flags & SEC_ALLOC) == 0
7565           && ! o->user_set_vma)
7566         o->vma = 0;
7567     }
7568
7569   if (! info->relocatable && merged)
7570     elf_link_hash_traverse (elf_hash_table (info),
7571                             _bfd_elf_link_sec_merge_syms, abfd);
7572
7573   /* Figure out the file positions for everything but the symbol table
7574      and the relocs.  We set symcount to force assign_section_numbers
7575      to create a symbol table.  */
7576   bfd_get_symcount (abfd) = info->strip == strip_all ? 0 : 1;
7577   BFD_ASSERT (! abfd->output_has_begun);
7578   if (! _bfd_elf_compute_section_file_positions (abfd, info))
7579     goto error_return;
7580
7581   /* That created the reloc sections.  Set their sizes, and assign
7582      them file positions, and allocate some buffers.  */
7583   for (o = abfd->sections; o != NULL; o = o->next)
7584     {
7585       if ((o->flags & SEC_RELOC) != 0)
7586         {
7587           if (!(_bfd_elf_link_size_reloc_section
7588                 (abfd, &elf_section_data (o)->rel_hdr, o)))
7589             goto error_return;
7590
7591           if (elf_section_data (o)->rel_hdr2
7592               && !(_bfd_elf_link_size_reloc_section
7593                    (abfd, elf_section_data (o)->rel_hdr2, o)))
7594             goto error_return;
7595         }
7596
7597       /* Now, reset REL_COUNT and REL_COUNT2 so that we can use them
7598          to count upwards while actually outputting the relocations.  */
7599       elf_section_data (o)->rel_count = 0;
7600       elf_section_data (o)->rel_count2 = 0;
7601     }
7602
7603   _bfd_elf_assign_file_positions_for_relocs (abfd);
7604
7605   /* We have now assigned file positions for all the sections except
7606      .symtab and .strtab.  We start the .symtab section at the current
7607      file position, and write directly to it.  We build the .strtab
7608      section in memory.  */
7609   bfd_get_symcount (abfd) = 0;
7610   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
7611   /* sh_name is set in prep_headers.  */
7612   symtab_hdr->sh_type = SHT_SYMTAB;
7613   /* sh_flags, sh_addr and sh_size all start off zero.  */
7614   symtab_hdr->sh_entsize = bed->s->sizeof_sym;
7615   /* sh_link is set in assign_section_numbers.  */
7616   /* sh_info is set below.  */
7617   /* sh_offset is set just below.  */
7618   symtab_hdr->sh_addralign = 1 << bed->s->log_file_align;
7619
7620   off = elf_tdata (abfd)->next_file_pos;
7621   off = _bfd_elf_assign_file_position_for_section (symtab_hdr, off, TRUE);
7622
7623   /* Note that at this point elf_tdata (abfd)->next_file_pos is
7624      incorrect.  We do not yet know the size of the .symtab section.
7625      We correct next_file_pos below, after we do know the size.  */
7626
7627   /* Allocate a buffer to hold swapped out symbols.  This is to avoid
7628      continuously seeking to the right position in the file.  */
7629   if (! info->keep_memory || max_sym_count < 20)
7630     finfo.symbuf_size = 20;
7631   else
7632     finfo.symbuf_size = max_sym_count;
7633   amt = finfo.symbuf_size;
7634   amt *= bed->s->sizeof_sym;
7635   finfo.symbuf = bfd_malloc (amt);
7636   if (finfo.symbuf == NULL)
7637     goto error_return;
7638   if (elf_numsections (abfd) > SHN_LORESERVE)
7639     {
7640       /* Wild guess at number of output symbols.  realloc'd as needed.  */
7641       amt = 2 * max_sym_count + elf_numsections (abfd) + 1000;
7642       finfo.shndxbuf_size = amt;
7643       amt *= sizeof (Elf_External_Sym_Shndx);
7644       finfo.symshndxbuf = bfd_zmalloc (amt);
7645       if (finfo.symshndxbuf == NULL)
7646         goto error_return;
7647     }
7648
7649   /* Start writing out the symbol table.  The first symbol is always a
7650      dummy symbol.  */
7651   if (info->strip != strip_all
7652       || emit_relocs)
7653     {
7654       elfsym.st_value = 0;
7655       elfsym.st_size = 0;
7656       elfsym.st_info = 0;
7657       elfsym.st_other = 0;
7658       elfsym.st_shndx = SHN_UNDEF;
7659       if (! elf_link_output_sym (&finfo, NULL, &elfsym, bfd_und_section_ptr,
7660                                  NULL))
7661         goto error_return;
7662     }
7663
7664 #if 0
7665   /* Some standard ELF linkers do this, but we don't because it causes
7666      bootstrap comparison failures.  */
7667   /* Output a file symbol for the output file as the second symbol.
7668      We output this even if we are discarding local symbols, although
7669      I'm not sure if this is correct.  */
7670   elfsym.st_value = 0;
7671   elfsym.st_size = 0;
7672   elfsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
7673   elfsym.st_other = 0;
7674   elfsym.st_shndx = SHN_ABS;
7675   if (! elf_link_output_sym (&finfo, bfd_get_filename (abfd),
7676                              &elfsym, bfd_abs_section_ptr, NULL))
7677     goto error_return;
7678 #endif
7679
7680   /* Output a symbol for each section.  We output these even if we are
7681      discarding local symbols, since they are used for relocs.  These
7682      symbols have no names.  We store the index of each one in the
7683      index field of the section, so that we can find it again when
7684      outputting relocs.  */
7685   if (info->strip != strip_all
7686       || emit_relocs)
7687     {
7688       elfsym.st_size = 0;
7689       elfsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
7690       elfsym.st_other = 0;
7691       for (i = 1; i < elf_numsections (abfd); i++)
7692         {
7693           o = bfd_section_from_elf_index (abfd, i);
7694           if (o != NULL)
7695             o->target_index = bfd_get_symcount (abfd);
7696           elfsym.st_shndx = i;
7697           if (info->relocatable || o == NULL)
7698             elfsym.st_value = 0;
7699           else
7700             elfsym.st_value = o->vma;
7701           if (! elf_link_output_sym (&finfo, NULL, &elfsym, o, NULL))
7702             goto error_return;
7703           if (i == SHN_LORESERVE - 1)
7704             i += SHN_HIRESERVE + 1 - SHN_LORESERVE;
7705         }
7706     }
7707
7708   /* Allocate some memory to hold information read in from the input
7709      files.  */
7710   if (max_contents_size != 0)
7711     {
7712       finfo.contents = bfd_malloc (max_contents_size);
7713       if (finfo.contents == NULL)
7714         goto error_return;
7715     }
7716
7717   if (max_external_reloc_size != 0)
7718     {
7719       finfo.external_relocs = bfd_malloc (max_external_reloc_size);
7720       if (finfo.external_relocs == NULL)
7721         goto error_return;
7722     }
7723
7724   if (max_internal_reloc_count != 0)
7725     {
7726       amt = max_internal_reloc_count * bed->s->int_rels_per_ext_rel;
7727       amt *= sizeof (Elf_Internal_Rela);
7728       finfo.internal_relocs = bfd_malloc (amt);
7729       if (finfo.internal_relocs == NULL)
7730         goto error_return;
7731     }
7732
7733   if (max_sym_count != 0)
7734     {
7735       amt = max_sym_count * bed->s->sizeof_sym;
7736       finfo.external_syms = bfd_malloc (amt);
7737       if (finfo.external_syms == NULL)
7738         goto error_return;
7739
7740       amt = max_sym_count * sizeof (Elf_Internal_Sym);
7741       finfo.internal_syms = bfd_malloc (amt);
7742       if (finfo.internal_syms == NULL)
7743         goto error_return;
7744
7745       amt = max_sym_count * sizeof (long);
7746       finfo.indices = bfd_malloc (amt);
7747       if (finfo.indices == NULL)
7748         goto error_return;
7749
7750       amt = max_sym_count * sizeof (asection *);
7751       finfo.sections = bfd_malloc (amt);
7752       if (finfo.sections == NULL)
7753         goto error_return;
7754     }
7755
7756   if (max_sym_shndx_count != 0)
7757     {
7758       amt = max_sym_shndx_count * sizeof (Elf_External_Sym_Shndx);
7759       finfo.locsym_shndx = bfd_malloc (amt);
7760       if (finfo.locsym_shndx == NULL)
7761         goto error_return;
7762     }
7763
7764   if (elf_hash_table (info)->tls_sec)
7765     {
7766       bfd_vma base, end = 0;
7767       asection *sec;
7768
7769       for (sec = elf_hash_table (info)->tls_sec;
7770            sec && (sec->flags & SEC_THREAD_LOCAL);
7771            sec = sec->next)
7772         {
7773           bfd_vma size = sec->size;
7774
7775           if (size == 0 && (sec->flags & SEC_HAS_CONTENTS) == 0)
7776             {
7777               struct bfd_link_order *o;
7778
7779               for (o = sec->link_order_head; o != NULL; o = o->next)
7780                 if (size < o->offset + o->size)
7781                   size = o->offset + o->size;
7782             }
7783           end = sec->vma + size;
7784         }
7785       base = elf_hash_table (info)->tls_sec->vma;
7786       end = align_power (end, elf_hash_table (info)->tls_sec->alignment_power);
7787       elf_hash_table (info)->tls_size = end - base;
7788     }
7789
7790   /* Reorder SHF_LINK_ORDER sections.  */
7791   for (o = abfd->sections; o != NULL; o = o->next)
7792     {
7793       if (!elf_fixup_link_order (abfd, o))
7794         return FALSE;
7795     }
7796
7797   /* Since ELF permits relocations to be against local symbols, we
7798      must have the local symbols available when we do the relocations.
7799      Since we would rather only read the local symbols once, and we
7800      would rather not keep them in memory, we handle all the
7801      relocations for a single input file at the same time.
7802
7803      Unfortunately, there is no way to know the total number of local
7804      symbols until we have seen all of them, and the local symbol
7805      indices precede the global symbol indices.  This means that when
7806      we are generating relocatable output, and we see a reloc against
7807      a global symbol, we can not know the symbol index until we have
7808      finished examining all the local symbols to see which ones we are
7809      going to output.  To deal with this, we keep the relocations in
7810      memory, and don't output them until the end of the link.  This is
7811      an unfortunate waste of memory, but I don't see a good way around
7812      it.  Fortunately, it only happens when performing a relocatable
7813      link, which is not the common case.  FIXME: If keep_memory is set
7814      we could write the relocs out and then read them again; I don't
7815      know how bad the memory loss will be.  */
7816
7817   for (sub = info->input_bfds; sub != NULL; sub = sub->link_next)
7818     sub->output_has_begun = FALSE;
7819   for (o = abfd->sections; o != NULL; o = o->next)
7820     {
7821       for (p = o->link_order_head; p != NULL; p = p->next)
7822         {
7823           if (p->type == bfd_indirect_link_order
7824               && (bfd_get_flavour ((sub = p->u.indirect.section->owner))
7825                   == bfd_target_elf_flavour)
7826               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass)
7827             {
7828               if (! sub->output_has_begun)
7829                 {
7830                   if (! elf_link_input_bfd (&finfo, sub))
7831                     goto error_return;
7832                   sub->output_has_begun = TRUE;
7833                 }
7834             }
7835           else if (p->type == bfd_section_reloc_link_order
7836                    || p->type == bfd_symbol_reloc_link_order)
7837             {
7838               if (! elf_reloc_link_order (abfd, info, o, p))
7839                 goto error_return;
7840             }
7841           else
7842             {
7843               if (! _bfd_default_link_order (abfd, info, o, p))
7844                 goto error_return;
7845             }
7846         }
7847     }
7848
7849   /* Output any global symbols that got converted to local in a
7850      version script or due to symbol visibility.  We do this in a
7851      separate step since ELF requires all local symbols to appear
7852      prior to any global symbols.  FIXME: We should only do this if
7853      some global symbols were, in fact, converted to become local.
7854      FIXME: Will this work correctly with the Irix 5 linker?  */
7855   eoinfo.failed = FALSE;
7856   eoinfo.finfo = &finfo;
7857   eoinfo.localsyms = TRUE;
7858   elf_link_hash_traverse (elf_hash_table (info), elf_link_output_extsym,
7859                           &eoinfo);
7860   if (eoinfo.failed)
7861     return FALSE;
7862
7863   /* That wrote out all the local symbols.  Finish up the symbol table
7864      with the global symbols. Even if we want to strip everything we
7865      can, we still need to deal with those global symbols that got
7866      converted to local in a version script.  */
7867
7868   /* The sh_info field records the index of the first non local symbol.  */
7869   symtab_hdr->sh_info = bfd_get_symcount (abfd);
7870
7871   if (dynamic
7872       && finfo.dynsym_sec->output_section != bfd_abs_section_ptr)
7873     {
7874       Elf_Internal_Sym sym;
7875       bfd_byte *dynsym = finfo.dynsym_sec->contents;
7876       long last_local = 0;
7877
7878       /* Write out the section symbols for the output sections.  */
7879       if (info->shared)
7880         {
7881           asection *s;
7882
7883           sym.st_size = 0;
7884           sym.st_name = 0;
7885           sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
7886           sym.st_other = 0;
7887
7888           for (s = abfd->sections; s != NULL; s = s->next)
7889             {
7890               int indx;
7891               bfd_byte *dest;
7892               long dynindx;
7893
7894               dynindx = elf_section_data (s)->dynindx;
7895               if (dynindx <= 0)
7896                 continue;
7897               indx = elf_section_data (s)->this_idx;
7898               BFD_ASSERT (indx > 0);
7899               sym.st_shndx = indx;
7900               sym.st_value = s->vma;
7901               dest = dynsym + dynindx * bed->s->sizeof_sym;
7902               if (last_local < dynindx)
7903                 last_local = dynindx;
7904               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
7905             }
7906         }
7907
7908       /* Write out the local dynsyms.  */
7909       if (elf_hash_table (info)->dynlocal)
7910         {
7911           struct elf_link_local_dynamic_entry *e;
7912           for (e = elf_hash_table (info)->dynlocal; e ; e = e->next)
7913             {
7914               asection *s;
7915               bfd_byte *dest;
7916
7917               sym.st_size = e->isym.st_size;
7918               sym.st_other = e->isym.st_other;
7919
7920               /* Copy the internal symbol as is.
7921                  Note that we saved a word of storage and overwrote
7922                  the original st_name with the dynstr_index.  */
7923               sym = e->isym;
7924
7925               if (e->isym.st_shndx != SHN_UNDEF
7926                   && (e->isym.st_shndx < SHN_LORESERVE
7927                       || e->isym.st_shndx > SHN_HIRESERVE))
7928                 {
7929                   s = bfd_section_from_elf_index (e->input_bfd,
7930                                                   e->isym.st_shndx);
7931
7932                   sym.st_shndx =
7933                     elf_section_data (s->output_section)->this_idx;
7934                   sym.st_value = (s->output_section->vma
7935                                   + s->output_offset
7936                                   + e->isym.st_value);
7937                 }
7938
7939               if (last_local < e->dynindx)
7940                 last_local = e->dynindx;
7941
7942               dest = dynsym + e->dynindx * bed->s->sizeof_sym;
7943               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
7944             }
7945         }
7946
7947       elf_section_data (finfo.dynsym_sec->output_section)->this_hdr.sh_info =
7948         last_local + 1;
7949     }
7950
7951   /* We get the global symbols from the hash table.  */
7952   eoinfo.failed = FALSE;
7953   eoinfo.localsyms = FALSE;
7954   eoinfo.finfo = &finfo;
7955   elf_link_hash_traverse (elf_hash_table (info), elf_link_output_extsym,
7956                           &eoinfo);
7957   if (eoinfo.failed)
7958     return FALSE;
7959
7960   /* If backend needs to output some symbols not present in the hash
7961      table, do it now.  */
7962   if (bed->elf_backend_output_arch_syms)
7963     {
7964       typedef bfd_boolean (*out_sym_func)
7965         (void *, const char *, Elf_Internal_Sym *, asection *,
7966          struct elf_link_hash_entry *);
7967
7968       if (! ((*bed->elf_backend_output_arch_syms)
7969              (abfd, info, &finfo, (out_sym_func) elf_link_output_sym)))
7970         return FALSE;
7971     }
7972
7973   /* Flush all symbols to the file.  */
7974   if (! elf_link_flush_output_syms (&finfo, bed))
7975     return FALSE;
7976
7977   /* Now we know the size of the symtab section.  */
7978   off += symtab_hdr->sh_size;
7979
7980   symtab_shndx_hdr = &elf_tdata (abfd)->symtab_shndx_hdr;
7981   if (symtab_shndx_hdr->sh_name != 0)
7982     {
7983       symtab_shndx_hdr->sh_type = SHT_SYMTAB_SHNDX;
7984       symtab_shndx_hdr->sh_entsize = sizeof (Elf_External_Sym_Shndx);
7985       symtab_shndx_hdr->sh_addralign = sizeof (Elf_External_Sym_Shndx);
7986       amt = bfd_get_symcount (abfd) * sizeof (Elf_External_Sym_Shndx);
7987       symtab_shndx_hdr->sh_size = amt;
7988
7989       off = _bfd_elf_assign_file_position_for_section (symtab_shndx_hdr,
7990                                                        off, TRUE);
7991
7992       if (bfd_seek (abfd, symtab_shndx_hdr->sh_offset, SEEK_SET) != 0
7993           || (bfd_bwrite (finfo.symshndxbuf, amt, abfd) != amt))
7994         return FALSE;
7995     }
7996
7997
7998   /* Finish up and write out the symbol string table (.strtab)
7999      section.  */
8000   symstrtab_hdr = &elf_tdata (abfd)->strtab_hdr;
8001   /* sh_name was set in prep_headers.  */
8002   symstrtab_hdr->sh_type = SHT_STRTAB;
8003   symstrtab_hdr->sh_flags = 0;
8004   symstrtab_hdr->sh_addr = 0;
8005   symstrtab_hdr->sh_size = _bfd_stringtab_size (finfo.symstrtab);
8006   symstrtab_hdr->sh_entsize = 0;
8007   symstrtab_hdr->sh_link = 0;
8008   symstrtab_hdr->sh_info = 0;
8009   /* sh_offset is set just below.  */
8010   symstrtab_hdr->sh_addralign = 1;
8011
8012   off = _bfd_elf_assign_file_position_for_section (symstrtab_hdr, off, TRUE);
8013   elf_tdata (abfd)->next_file_pos = off;
8014
8015   if (bfd_get_symcount (abfd) > 0)
8016     {
8017       if (bfd_seek (abfd, symstrtab_hdr->sh_offset, SEEK_SET) != 0
8018           || ! _bfd_stringtab_emit (abfd, finfo.symstrtab))
8019         return FALSE;
8020     }
8021
8022   /* Adjust the relocs to have the correct symbol indices.  */
8023   for (o = abfd->sections; o != NULL; o = o->next)
8024     {
8025       if ((o->flags & SEC_RELOC) == 0)
8026         continue;
8027
8028       elf_link_adjust_relocs (abfd, &elf_section_data (o)->rel_hdr,
8029                               elf_section_data (o)->rel_count,
8030                               elf_section_data (o)->rel_hashes);
8031       if (elf_section_data (o)->rel_hdr2 != NULL)
8032         elf_link_adjust_relocs (abfd, elf_section_data (o)->rel_hdr2,
8033                                 elf_section_data (o)->rel_count2,
8034                                 (elf_section_data (o)->rel_hashes
8035                                  + elf_section_data (o)->rel_count));
8036
8037       /* Set the reloc_count field to 0 to prevent write_relocs from
8038          trying to swap the relocs out itself.  */
8039       o->reloc_count = 0;
8040     }
8041
8042   if (dynamic && info->combreloc && dynobj != NULL)
8043     relativecount = elf_link_sort_relocs (abfd, info, &reldyn);
8044
8045   /* If we are linking against a dynamic object, or generating a
8046      shared library, finish up the dynamic linking information.  */
8047   if (dynamic)
8048     {
8049       bfd_byte *dyncon, *dynconend;
8050
8051       /* Fix up .dynamic entries.  */
8052       o = bfd_get_section_by_name (dynobj, ".dynamic");
8053       BFD_ASSERT (o != NULL);
8054
8055       dyncon = o->contents;
8056       dynconend = o->contents + o->size;
8057       for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
8058         {
8059           Elf_Internal_Dyn dyn;
8060           const char *name;
8061           unsigned int type;
8062
8063           bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
8064
8065           switch (dyn.d_tag)
8066             {
8067             default:
8068               continue;
8069             case DT_NULL:
8070               if (relativecount > 0 && dyncon + bed->s->sizeof_dyn < dynconend)
8071                 {
8072                   switch (elf_section_data (reldyn)->this_hdr.sh_type)
8073                     {
8074                     case SHT_REL: dyn.d_tag = DT_RELCOUNT; break;
8075                     case SHT_RELA: dyn.d_tag = DT_RELACOUNT; break;
8076                     default: continue;
8077                     }
8078                   dyn.d_un.d_val = relativecount;
8079                   relativecount = 0;
8080                   break;
8081                 }
8082               continue;
8083
8084             case DT_INIT:
8085               name = info->init_function;
8086               goto get_sym;
8087             case DT_FINI:
8088               name = info->fini_function;
8089             get_sym:
8090               {
8091                 struct elf_link_hash_entry *h;
8092
8093                 h = elf_link_hash_lookup (elf_hash_table (info), name,
8094                                           FALSE, FALSE, TRUE);
8095                 if (h != NULL
8096                     && (h->root.type == bfd_link_hash_defined
8097                         || h->root.type == bfd_link_hash_defweak))
8098                   {
8099                     dyn.d_un.d_val = h->root.u.def.value;
8100                     o = h->root.u.def.section;
8101                     if (o->output_section != NULL)
8102                       dyn.d_un.d_val += (o->output_section->vma
8103                                          + o->output_offset);
8104                     else
8105                       {
8106                         /* The symbol is imported from another shared
8107                            library and does not apply to this one.  */
8108                         dyn.d_un.d_val = 0;
8109                       }
8110                     break;
8111                   }
8112               }
8113               continue;
8114
8115             case DT_PREINIT_ARRAYSZ:
8116               name = ".preinit_array";
8117               goto get_size;
8118             case DT_INIT_ARRAYSZ:
8119               name = ".init_array";
8120               goto get_size;
8121             case DT_FINI_ARRAYSZ:
8122               name = ".fini_array";
8123             get_size:
8124               o = bfd_get_section_by_name (abfd, name);
8125               if (o == NULL)
8126                 {
8127                   (*_bfd_error_handler)
8128                     (_("%B: could not find output section %s"), abfd, name);
8129                   goto error_return;
8130                 }
8131               if (o->size == 0)
8132                 (*_bfd_error_handler)
8133                   (_("warning: %s section has zero size"), name);
8134               dyn.d_un.d_val = o->size;
8135               break;
8136
8137             case DT_PREINIT_ARRAY:
8138               name = ".preinit_array";
8139               goto get_vma;
8140             case DT_INIT_ARRAY:
8141               name = ".init_array";
8142               goto get_vma;
8143             case DT_FINI_ARRAY:
8144               name = ".fini_array";
8145               goto get_vma;
8146
8147             case DT_HASH:
8148               name = ".hash";
8149               goto get_vma;
8150             case DT_STRTAB:
8151               name = ".dynstr";
8152               goto get_vma;
8153             case DT_SYMTAB:
8154               name = ".dynsym";
8155               goto get_vma;
8156             case DT_VERDEF:
8157               name = ".gnu.version_d";
8158               goto get_vma;
8159             case DT_VERNEED:
8160               name = ".gnu.version_r";
8161               goto get_vma;
8162             case DT_VERSYM:
8163               name = ".gnu.version";
8164             get_vma:
8165               o = bfd_get_section_by_name (abfd, name);
8166               if (o == NULL)
8167                 {
8168                   (*_bfd_error_handler)
8169                     (_("%B: could not find output section %s"), abfd, name);
8170                   goto error_return;
8171                 }
8172               dyn.d_un.d_ptr = o->vma;
8173               break;
8174
8175             case DT_REL:
8176             case DT_RELA:
8177             case DT_RELSZ:
8178             case DT_RELASZ:
8179               if (dyn.d_tag == DT_REL || dyn.d_tag == DT_RELSZ)
8180                 type = SHT_REL;
8181               else
8182                 type = SHT_RELA;
8183               dyn.d_un.d_val = 0;
8184               for (i = 1; i < elf_numsections (abfd); i++)
8185                 {
8186                   Elf_Internal_Shdr *hdr;
8187
8188                   hdr = elf_elfsections (abfd)[i];
8189                   if (hdr->sh_type == type
8190                       && (hdr->sh_flags & SHF_ALLOC) != 0)
8191                     {
8192                       if (dyn.d_tag == DT_RELSZ || dyn.d_tag == DT_RELASZ)
8193                         dyn.d_un.d_val += hdr->sh_size;
8194                       else
8195                         {
8196                           if (dyn.d_un.d_val == 0
8197                               || hdr->sh_addr < dyn.d_un.d_val)
8198                             dyn.d_un.d_val = hdr->sh_addr;
8199                         }
8200                     }
8201                 }
8202               break;
8203             }
8204           bed->s->swap_dyn_out (dynobj, &dyn, dyncon);
8205         }
8206     }
8207
8208   /* If we have created any dynamic sections, then output them.  */
8209   if (dynobj != NULL)
8210     {
8211       if (! (*bed->elf_backend_finish_dynamic_sections) (abfd, info))
8212         goto error_return;
8213
8214       for (o = dynobj->sections; o != NULL; o = o->next)
8215         {
8216           if ((o->flags & SEC_HAS_CONTENTS) == 0
8217               || o->size == 0
8218               || o->output_section == bfd_abs_section_ptr)
8219             continue;
8220           if ((o->flags & SEC_LINKER_CREATED) == 0)
8221             {
8222               /* At this point, we are only interested in sections
8223                  created by _bfd_elf_link_create_dynamic_sections.  */
8224               continue;
8225             }
8226           if (elf_hash_table (info)->stab_info.stabstr == o)
8227             continue;
8228           if (elf_hash_table (info)->eh_info.hdr_sec == o)
8229             continue;
8230           if ((elf_section_data (o->output_section)->this_hdr.sh_type
8231                != SHT_STRTAB)
8232               || strcmp (bfd_get_section_name (abfd, o), ".dynstr") != 0)
8233             {
8234               if (! bfd_set_section_contents (abfd, o->output_section,
8235                                               o->contents,
8236                                               (file_ptr) o->output_offset,
8237                                               o->size))
8238                 goto error_return;
8239             }
8240           else
8241             {
8242               /* The contents of the .dynstr section are actually in a
8243                  stringtab.  */
8244               off = elf_section_data (o->output_section)->this_hdr.sh_offset;
8245               if (bfd_seek (abfd, off, SEEK_SET) != 0
8246                   || ! _bfd_elf_strtab_emit (abfd,
8247                                              elf_hash_table (info)->dynstr))
8248                 goto error_return;
8249             }
8250         }
8251     }
8252
8253   if (info->relocatable)
8254     {
8255       bfd_boolean failed = FALSE;
8256
8257       bfd_map_over_sections (abfd, bfd_elf_set_group_contents, &failed);
8258       if (failed)
8259         goto error_return;
8260     }
8261
8262   /* If we have optimized stabs strings, output them.  */
8263   if (elf_hash_table (info)->stab_info.stabstr != NULL)
8264     {
8265       if (! _bfd_write_stab_strings (abfd, &elf_hash_table (info)->stab_info))
8266         goto error_return;
8267     }
8268
8269   if (info->eh_frame_hdr)
8270     {
8271       if (! _bfd_elf_write_section_eh_frame_hdr (abfd, info))
8272         goto error_return;
8273     }
8274
8275   if (finfo.symstrtab != NULL)
8276     _bfd_stringtab_free (finfo.symstrtab);
8277   if (finfo.contents != NULL)
8278     free (finfo.contents);
8279   if (finfo.external_relocs != NULL)
8280     free (finfo.external_relocs);
8281   if (finfo.internal_relocs != NULL)
8282     free (finfo.internal_relocs);
8283   if (finfo.external_syms != NULL)
8284     free (finfo.external_syms);
8285   if (finfo.locsym_shndx != NULL)
8286     free (finfo.locsym_shndx);
8287   if (finfo.internal_syms != NULL)
8288     free (finfo.internal_syms);
8289   if (finfo.indices != NULL)
8290     free (finfo.indices);
8291   if (finfo.sections != NULL)
8292     free (finfo.sections);
8293   if (finfo.symbuf != NULL)
8294     free (finfo.symbuf);
8295   if (finfo.symshndxbuf != NULL)
8296     free (finfo.symshndxbuf);
8297   for (o = abfd->sections; o != NULL; o = o->next)
8298     {
8299       if ((o->flags & SEC_RELOC) != 0
8300           && elf_section_data (o)->rel_hashes != NULL)
8301         free (elf_section_data (o)->rel_hashes);
8302     }
8303
8304   elf_tdata (abfd)->linker = TRUE;
8305
8306   return TRUE;
8307
8308  error_return:
8309   if (finfo.symstrtab != NULL)
8310     _bfd_stringtab_free (finfo.symstrtab);
8311   if (finfo.contents != NULL)
8312     free (finfo.contents);
8313   if (finfo.external_relocs != NULL)
8314     free (finfo.external_relocs);
8315   if (finfo.internal_relocs != NULL)
8316     free (finfo.internal_relocs);
8317   if (finfo.external_syms != NULL)
8318     free (finfo.external_syms);
8319   if (finfo.locsym_shndx != NULL)
8320     free (finfo.locsym_shndx);
8321   if (finfo.internal_syms != NULL)
8322     free (finfo.internal_syms);
8323   if (finfo.indices != NULL)
8324     free (finfo.indices);
8325   if (finfo.sections != NULL)
8326     free (finfo.sections);
8327   if (finfo.symbuf != NULL)
8328     free (finfo.symbuf);
8329   if (finfo.symshndxbuf != NULL)
8330     free (finfo.symshndxbuf);
8331   for (o = abfd->sections; o != NULL; o = o->next)
8332     {
8333       if ((o->flags & SEC_RELOC) != 0
8334           && elf_section_data (o)->rel_hashes != NULL)
8335         free (elf_section_data (o)->rel_hashes);
8336     }
8337
8338   return FALSE;
8339 }
8340 \f
8341 /* Garbage collect unused sections.  */
8342
8343 /* The mark phase of garbage collection.  For a given section, mark
8344    it and any sections in this section's group, and all the sections
8345    which define symbols to which it refers.  */
8346
8347 typedef asection * (*gc_mark_hook_fn)
8348   (asection *, struct bfd_link_info *, Elf_Internal_Rela *,
8349    struct elf_link_hash_entry *, Elf_Internal_Sym *);
8350
8351 bfd_boolean
8352 _bfd_elf_gc_mark (struct bfd_link_info *info,
8353                   asection *sec,
8354                   gc_mark_hook_fn gc_mark_hook)
8355 {
8356   bfd_boolean ret;
8357   asection *group_sec;
8358
8359   sec->gc_mark = 1;
8360
8361   /* Mark all the sections in the group.  */
8362   group_sec = elf_section_data (sec)->next_in_group;
8363   if (group_sec && !group_sec->gc_mark)
8364     if (!_bfd_elf_gc_mark (info, group_sec, gc_mark_hook))
8365       return FALSE;
8366
8367   /* Look through the section relocs.  */
8368   ret = TRUE;
8369   if ((sec->flags & SEC_RELOC) != 0 && sec->reloc_count > 0)
8370     {
8371       Elf_Internal_Rela *relstart, *rel, *relend;
8372       Elf_Internal_Shdr *symtab_hdr;
8373       struct elf_link_hash_entry **sym_hashes;
8374       size_t nlocsyms;
8375       size_t extsymoff;
8376       bfd *input_bfd = sec->owner;
8377       const struct elf_backend_data *bed = get_elf_backend_data (input_bfd);
8378       Elf_Internal_Sym *isym = NULL;
8379       int r_sym_shift;
8380
8381       symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
8382       sym_hashes = elf_sym_hashes (input_bfd);
8383
8384       /* Read the local symbols.  */
8385       if (elf_bad_symtab (input_bfd))
8386         {
8387           nlocsyms = symtab_hdr->sh_size / bed->s->sizeof_sym;
8388           extsymoff = 0;
8389         }
8390       else
8391         extsymoff = nlocsyms = symtab_hdr->sh_info;
8392
8393       isym = (Elf_Internal_Sym *) symtab_hdr->contents;
8394       if (isym == NULL && nlocsyms != 0)
8395         {
8396           isym = bfd_elf_get_elf_syms (input_bfd, symtab_hdr, nlocsyms, 0,
8397                                        NULL, NULL, NULL);
8398           if (isym == NULL)
8399             return FALSE;
8400         }
8401
8402       /* Read the relocations.  */
8403       relstart = _bfd_elf_link_read_relocs (input_bfd, sec, NULL, NULL,
8404                                             info->keep_memory);
8405       if (relstart == NULL)
8406         {
8407           ret = FALSE;
8408           goto out1;
8409         }
8410       relend = relstart + sec->reloc_count * bed->s->int_rels_per_ext_rel;
8411
8412       if (bed->s->arch_size == 32)
8413         r_sym_shift = 8;
8414       else
8415         r_sym_shift = 32;
8416
8417       for (rel = relstart; rel < relend; rel++)
8418         {
8419           unsigned long r_symndx;
8420           asection *rsec;
8421           struct elf_link_hash_entry *h;
8422
8423           r_symndx = rel->r_info >> r_sym_shift;
8424           if (r_symndx == 0)
8425             continue;
8426
8427           if (r_symndx >= nlocsyms
8428               || ELF_ST_BIND (isym[r_symndx].st_info) != STB_LOCAL)
8429             {
8430               h = sym_hashes[r_symndx - extsymoff];
8431               while (h->root.type == bfd_link_hash_indirect
8432                      || h->root.type == bfd_link_hash_warning)
8433                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
8434               rsec = (*gc_mark_hook) (sec, info, rel, h, NULL);
8435             }
8436           else
8437             {
8438               rsec = (*gc_mark_hook) (sec, info, rel, NULL, &isym[r_symndx]);
8439             }
8440
8441           if (rsec && !rsec->gc_mark)
8442             {
8443               if (bfd_get_flavour (rsec->owner) != bfd_target_elf_flavour)
8444                 rsec->gc_mark = 1;
8445               else if (!_bfd_elf_gc_mark (info, rsec, gc_mark_hook))
8446                 {
8447                   ret = FALSE;
8448                   goto out2;
8449                 }
8450             }
8451         }
8452
8453     out2:
8454       if (elf_section_data (sec)->relocs != relstart)
8455         free (relstart);
8456     out1:
8457       if (isym != NULL && symtab_hdr->contents != (unsigned char *) isym)
8458         {
8459           if (! info->keep_memory)
8460             free (isym);
8461           else
8462             symtab_hdr->contents = (unsigned char *) isym;
8463         }
8464     }
8465
8466   return ret;
8467 }
8468
8469 /* Sweep symbols in swept sections.  Called via elf_link_hash_traverse.  */
8470
8471 static bfd_boolean
8472 elf_gc_sweep_symbol (struct elf_link_hash_entry *h, void *idxptr)
8473 {
8474   int *idx = idxptr;
8475
8476   if (h->root.type == bfd_link_hash_warning)
8477     h = (struct elf_link_hash_entry *) h->root.u.i.link;
8478
8479   if (h->dynindx != -1
8480       && ((h->root.type != bfd_link_hash_defined
8481            && h->root.type != bfd_link_hash_defweak)
8482           || h->root.u.def.section->gc_mark))
8483     h->dynindx = (*idx)++;
8484
8485   return TRUE;
8486 }
8487
8488 /* The sweep phase of garbage collection.  Remove all garbage sections.  */
8489
8490 typedef bfd_boolean (*gc_sweep_hook_fn)
8491   (bfd *, struct bfd_link_info *, asection *, const Elf_Internal_Rela *);
8492
8493 static bfd_boolean
8494 elf_gc_sweep (struct bfd_link_info *info, gc_sweep_hook_fn gc_sweep_hook)
8495 {
8496   bfd *sub;
8497
8498   for (sub = info->input_bfds; sub != NULL; sub = sub->link_next)
8499     {
8500       asection *o;
8501
8502       if (bfd_get_flavour (sub) != bfd_target_elf_flavour)
8503         continue;
8504
8505       for (o = sub->sections; o != NULL; o = o->next)
8506         {
8507           /* Keep debug and special sections.  */
8508           if ((o->flags & (SEC_DEBUGGING | SEC_LINKER_CREATED)) != 0
8509               || (o->flags & (SEC_ALLOC | SEC_LOAD)) == 0)
8510             o->gc_mark = 1;
8511
8512           if (o->gc_mark)
8513             continue;
8514
8515           /* Skip sweeping sections already excluded.  */
8516           if (o->flags & SEC_EXCLUDE)
8517             continue;
8518
8519           /* Since this is early in the link process, it is simple
8520              to remove a section from the output.  */
8521           o->flags |= SEC_EXCLUDE;
8522
8523           /* But we also have to update some of the relocation
8524              info we collected before.  */
8525           if (gc_sweep_hook
8526               && (o->flags & SEC_RELOC) && o->reloc_count > 0)
8527             {
8528               Elf_Internal_Rela *internal_relocs;
8529               bfd_boolean r;
8530
8531               internal_relocs
8532                 = _bfd_elf_link_read_relocs (o->owner, o, NULL, NULL,
8533                                              info->keep_memory);
8534               if (internal_relocs == NULL)
8535                 return FALSE;
8536
8537               r = (*gc_sweep_hook) (o->owner, info, o, internal_relocs);
8538
8539               if (elf_section_data (o)->relocs != internal_relocs)
8540                 free (internal_relocs);
8541
8542               if (!r)
8543                 return FALSE;
8544             }
8545         }
8546     }
8547
8548   /* Remove the symbols that were in the swept sections from the dynamic
8549      symbol table.  GCFIXME: Anyone know how to get them out of the
8550      static symbol table as well?  */
8551   {
8552     int i = 0;
8553
8554     elf_link_hash_traverse (elf_hash_table (info), elf_gc_sweep_symbol, &i);
8555
8556     elf_hash_table (info)->dynsymcount = i;
8557   }
8558
8559   return TRUE;
8560 }
8561
8562 /* Propagate collected vtable information.  This is called through
8563    elf_link_hash_traverse.  */
8564
8565 static bfd_boolean
8566 elf_gc_propagate_vtable_entries_used (struct elf_link_hash_entry *h, void *okp)
8567 {
8568   if (h->root.type == bfd_link_hash_warning)
8569     h = (struct elf_link_hash_entry *) h->root.u.i.link;
8570
8571   /* Those that are not vtables.  */
8572   if (h->vtable_parent == NULL)
8573     return TRUE;
8574
8575   /* Those vtables that do not have parents, we cannot merge.  */
8576   if (h->vtable_parent == (struct elf_link_hash_entry *) -1)
8577     return TRUE;
8578
8579   /* If we've already been done, exit.  */
8580   if (h->vtable_entries_used && h->vtable_entries_used[-1])
8581     return TRUE;
8582
8583   /* Make sure the parent's table is up to date.  */
8584   elf_gc_propagate_vtable_entries_used (h->vtable_parent, okp);
8585
8586   if (h->vtable_entries_used == NULL)
8587     {
8588       /* None of this table's entries were referenced.  Re-use the
8589          parent's table.  */
8590       h->vtable_entries_used = h->vtable_parent->vtable_entries_used;
8591       h->vtable_entries_size = h->vtable_parent->vtable_entries_size;
8592     }
8593   else
8594     {
8595       size_t n;
8596       bfd_boolean *cu, *pu;
8597
8598       /* Or the parent's entries into ours.  */
8599       cu = h->vtable_entries_used;
8600       cu[-1] = TRUE;
8601       pu = h->vtable_parent->vtable_entries_used;
8602       if (pu != NULL)
8603         {
8604           const struct elf_backend_data *bed;
8605           unsigned int log_file_align;
8606
8607           bed = get_elf_backend_data (h->root.u.def.section->owner);
8608           log_file_align = bed->s->log_file_align;
8609           n = h->vtable_parent->vtable_entries_size >> log_file_align;
8610           while (n--)
8611             {
8612               if (*pu)
8613                 *cu = TRUE;
8614               pu++;
8615               cu++;
8616             }
8617         }
8618     }
8619
8620   return TRUE;
8621 }
8622
8623 static bfd_boolean
8624 elf_gc_smash_unused_vtentry_relocs (struct elf_link_hash_entry *h, void *okp)
8625 {
8626   asection *sec;
8627   bfd_vma hstart, hend;
8628   Elf_Internal_Rela *relstart, *relend, *rel;
8629   const struct elf_backend_data *bed;
8630   unsigned int log_file_align;
8631
8632   if (h->root.type == bfd_link_hash_warning)
8633     h = (struct elf_link_hash_entry *) h->root.u.i.link;
8634
8635   /* Take care of both those symbols that do not describe vtables as
8636      well as those that are not loaded.  */
8637   if (h->vtable_parent == NULL)
8638     return TRUE;
8639
8640   BFD_ASSERT (h->root.type == bfd_link_hash_defined
8641               || h->root.type == bfd_link_hash_defweak);
8642
8643   sec = h->root.u.def.section;
8644   hstart = h->root.u.def.value;
8645   hend = hstart + h->size;
8646
8647   relstart = _bfd_elf_link_read_relocs (sec->owner, sec, NULL, NULL, TRUE);
8648   if (!relstart)
8649     return *(bfd_boolean *) okp = FALSE;
8650   bed = get_elf_backend_data (sec->owner);
8651   log_file_align = bed->s->log_file_align;
8652
8653   relend = relstart + sec->reloc_count * bed->s->int_rels_per_ext_rel;
8654
8655   for (rel = relstart; rel < relend; ++rel)
8656     if (rel->r_offset >= hstart && rel->r_offset < hend)
8657       {
8658         /* If the entry is in use, do nothing.  */
8659         if (h->vtable_entries_used
8660             && (rel->r_offset - hstart) < h->vtable_entries_size)
8661           {
8662             bfd_vma entry = (rel->r_offset - hstart) >> log_file_align;
8663             if (h->vtable_entries_used[entry])
8664               continue;
8665           }
8666         /* Otherwise, kill it.  */
8667         rel->r_offset = rel->r_info = rel->r_addend = 0;
8668       }
8669
8670   return TRUE;
8671 }
8672
8673 /* Mark sections containing dynamically referenced symbols.  This is called
8674    through elf_link_hash_traverse.  */
8675
8676 static bfd_boolean
8677 elf_gc_mark_dynamic_ref_symbol (struct elf_link_hash_entry *h,
8678                                 void *okp ATTRIBUTE_UNUSED)
8679 {
8680   if (h->root.type == bfd_link_hash_warning)
8681     h = (struct elf_link_hash_entry *) h->root.u.i.link;
8682
8683   if ((h->root.type == bfd_link_hash_defined
8684        || h->root.type == bfd_link_hash_defweak)
8685       && (h->elf_link_hash_flags & ELF_LINK_HASH_REF_DYNAMIC))
8686     h->root.u.def.section->flags |= SEC_KEEP;
8687
8688   return TRUE;
8689 }
8690
8691 /* Do mark and sweep of unused sections.  */
8692
8693 bfd_boolean
8694 bfd_elf_gc_sections (bfd *abfd, struct bfd_link_info *info)
8695 {
8696   bfd_boolean ok = TRUE;
8697   bfd *sub;
8698   asection * (*gc_mark_hook)
8699     (asection *, struct bfd_link_info *, Elf_Internal_Rela *,
8700      struct elf_link_hash_entry *h, Elf_Internal_Sym *);
8701
8702   if (!get_elf_backend_data (abfd)->can_gc_sections
8703       || info->relocatable
8704       || info->emitrelocations
8705       || info->shared
8706       || !is_elf_hash_table (info->hash))
8707     {
8708       (*_bfd_error_handler)(_("Warning: gc-sections option ignored"));
8709       return TRUE;
8710     }
8711
8712   /* Apply transitive closure to the vtable entry usage info.  */
8713   elf_link_hash_traverse (elf_hash_table (info),
8714                           elf_gc_propagate_vtable_entries_used,
8715                           &ok);
8716   if (!ok)
8717     return FALSE;
8718
8719   /* Kill the vtable relocations that were not used.  */
8720   elf_link_hash_traverse (elf_hash_table (info),
8721                           elf_gc_smash_unused_vtentry_relocs,
8722                           &ok);
8723   if (!ok)
8724     return FALSE;
8725
8726   /* Mark dynamically referenced symbols.  */
8727   if (elf_hash_table (info)->dynamic_sections_created)
8728     elf_link_hash_traverse (elf_hash_table (info),
8729                             elf_gc_mark_dynamic_ref_symbol,
8730                             &ok);
8731   if (!ok)
8732     return FALSE;
8733
8734   /* Grovel through relocs to find out who stays ...  */
8735   gc_mark_hook = get_elf_backend_data (abfd)->gc_mark_hook;
8736   for (sub = info->input_bfds; sub != NULL; sub = sub->link_next)
8737     {
8738       asection *o;
8739
8740       if (bfd_get_flavour (sub) != bfd_target_elf_flavour)
8741         continue;
8742
8743       for (o = sub->sections; o != NULL; o = o->next)
8744         {
8745           if (o->flags & SEC_KEEP)
8746             {
8747               /* _bfd_elf_discard_section_eh_frame knows how to discard
8748                  orphaned FDEs so don't mark sections referenced by the
8749                  EH frame section.  */  
8750               if (strcmp (o->name, ".eh_frame") == 0)
8751                 o->gc_mark = 1;
8752               else if (!_bfd_elf_gc_mark (info, o, gc_mark_hook))
8753                 return FALSE;
8754             }
8755         }
8756     }
8757
8758   /* ... and mark SEC_EXCLUDE for those that go.  */
8759   if (!elf_gc_sweep (info, get_elf_backend_data (abfd)->gc_sweep_hook))
8760     return FALSE;
8761
8762   return TRUE;
8763 }
8764 \f
8765 /* Called from check_relocs to record the existence of a VTINHERIT reloc.  */
8766
8767 bfd_boolean
8768 bfd_elf_gc_record_vtinherit (bfd *abfd,
8769                              asection *sec,
8770                              struct elf_link_hash_entry *h,
8771                              bfd_vma offset)
8772 {
8773   struct elf_link_hash_entry **sym_hashes, **sym_hashes_end;
8774   struct elf_link_hash_entry **search, *child;
8775   bfd_size_type extsymcount;
8776   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8777
8778   /* The sh_info field of the symtab header tells us where the
8779      external symbols start.  We don't care about the local symbols at
8780      this point.  */
8781   extsymcount = elf_tdata (abfd)->symtab_hdr.sh_size / bed->s->sizeof_sym;
8782   if (!elf_bad_symtab (abfd))
8783     extsymcount -= elf_tdata (abfd)->symtab_hdr.sh_info;
8784
8785   sym_hashes = elf_sym_hashes (abfd);
8786   sym_hashes_end = sym_hashes + extsymcount;
8787
8788   /* Hunt down the child symbol, which is in this section at the same
8789      offset as the relocation.  */
8790   for (search = sym_hashes; search != sym_hashes_end; ++search)
8791     {
8792       if ((child = *search) != NULL
8793           && (child->root.type == bfd_link_hash_defined
8794               || child->root.type == bfd_link_hash_defweak)
8795           && child->root.u.def.section == sec
8796           && child->root.u.def.value == offset)
8797         goto win;
8798     }
8799
8800   (*_bfd_error_handler) ("%B: %A+%lu: No symbol found for INHERIT",
8801                          abfd, sec, (unsigned long) offset);
8802   bfd_set_error (bfd_error_invalid_operation);
8803   return FALSE;
8804
8805  win:
8806   if (!h)
8807     {
8808       /* This *should* only be the absolute section.  It could potentially
8809          be that someone has defined a non-global vtable though, which
8810          would be bad.  It isn't worth paging in the local symbols to be
8811          sure though; that case should simply be handled by the assembler.  */
8812
8813       child->vtable_parent = (struct elf_link_hash_entry *) -1;
8814     }
8815   else
8816     child->vtable_parent = h;
8817
8818   return TRUE;
8819 }
8820
8821 /* Called from check_relocs to record the existence of a VTENTRY reloc.  */
8822
8823 bfd_boolean
8824 bfd_elf_gc_record_vtentry (bfd *abfd ATTRIBUTE_UNUSED,
8825                            asection *sec ATTRIBUTE_UNUSED,
8826                            struct elf_link_hash_entry *h,
8827                            bfd_vma addend)
8828 {
8829   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8830   unsigned int log_file_align = bed->s->log_file_align;
8831
8832   if (addend >= h->vtable_entries_size)
8833     {
8834       size_t size, bytes, file_align;
8835       bfd_boolean *ptr = h->vtable_entries_used;
8836
8837       /* While the symbol is undefined, we have to be prepared to handle
8838          a zero size.  */
8839       file_align = 1 << log_file_align;
8840       if (h->root.type == bfd_link_hash_undefined)
8841         size = addend + file_align;
8842       else
8843         {
8844           size = h->size;
8845           if (addend >= size)
8846             {
8847               /* Oops!  We've got a reference past the defined end of
8848                  the table.  This is probably a bug -- shall we warn?  */
8849               size = addend + file_align;
8850             }
8851         }
8852       size = (size + file_align - 1) & -file_align;
8853
8854       /* Allocate one extra entry for use as a "done" flag for the
8855          consolidation pass.  */
8856       bytes = ((size >> log_file_align) + 1) * sizeof (bfd_boolean);
8857
8858       if (ptr)
8859         {
8860           ptr = bfd_realloc (ptr - 1, bytes);
8861
8862           if (ptr != NULL)
8863             {
8864               size_t oldbytes;
8865
8866               oldbytes = (((h->vtable_entries_size >> log_file_align) + 1)
8867                           * sizeof (bfd_boolean));
8868               memset (((char *) ptr) + oldbytes, 0, bytes - oldbytes);
8869             }
8870         }
8871       else
8872         ptr = bfd_zmalloc (bytes);
8873
8874       if (ptr == NULL)
8875         return FALSE;
8876
8877       /* And arrange for that done flag to be at index -1.  */
8878       h->vtable_entries_used = ptr + 1;
8879       h->vtable_entries_size = size;
8880     }
8881
8882   h->vtable_entries_used[addend >> log_file_align] = TRUE;
8883
8884   return TRUE;
8885 }
8886
8887 struct alloc_got_off_arg {
8888   bfd_vma gotoff;
8889   unsigned int got_elt_size;
8890 };
8891
8892 /* We need a special top-level link routine to convert got reference counts
8893    to real got offsets.  */
8894
8895 static bfd_boolean
8896 elf_gc_allocate_got_offsets (struct elf_link_hash_entry *h, void *arg)
8897 {
8898   struct alloc_got_off_arg *gofarg = arg;
8899
8900   if (h->root.type == bfd_link_hash_warning)
8901     h = (struct elf_link_hash_entry *) h->root.u.i.link;
8902
8903   if (h->got.refcount > 0)
8904     {
8905       h->got.offset = gofarg->gotoff;
8906       gofarg->gotoff += gofarg->got_elt_size;
8907     }
8908   else
8909     h->got.offset = (bfd_vma) -1;
8910
8911   return TRUE;
8912 }
8913
8914 /* And an accompanying bit to work out final got entry offsets once
8915    we're done.  Should be called from final_link.  */
8916
8917 bfd_boolean
8918 bfd_elf_gc_common_finalize_got_offsets (bfd *abfd,
8919                                         struct bfd_link_info *info)
8920 {
8921   bfd *i;
8922   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8923   bfd_vma gotoff;
8924   unsigned int got_elt_size = bed->s->arch_size / 8;
8925   struct alloc_got_off_arg gofarg;
8926
8927   if (! is_elf_hash_table (info->hash))
8928     return FALSE;
8929
8930   /* The GOT offset is relative to the .got section, but the GOT header is
8931      put into the .got.plt section, if the backend uses it.  */
8932   if (bed->want_got_plt)
8933     gotoff = 0;
8934   else
8935     gotoff = bed->got_header_size;
8936
8937   /* Do the local .got entries first.  */
8938   for (i = info->input_bfds; i; i = i->link_next)
8939     {
8940       bfd_signed_vma *local_got;
8941       bfd_size_type j, locsymcount;
8942       Elf_Internal_Shdr *symtab_hdr;
8943
8944       if (bfd_get_flavour (i) != bfd_target_elf_flavour)
8945         continue;
8946
8947       local_got = elf_local_got_refcounts (i);
8948       if (!local_got)
8949         continue;
8950
8951       symtab_hdr = &elf_tdata (i)->symtab_hdr;
8952       if (elf_bad_symtab (i))
8953         locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
8954       else
8955         locsymcount = symtab_hdr->sh_info;
8956
8957       for (j = 0; j < locsymcount; ++j)
8958         {
8959           if (local_got[j] > 0)
8960             {
8961               local_got[j] = gotoff;
8962               gotoff += got_elt_size;
8963             }
8964           else
8965             local_got[j] = (bfd_vma) -1;
8966         }
8967     }
8968
8969   /* Then the global .got entries.  .plt refcounts are handled by
8970      adjust_dynamic_symbol  */
8971   gofarg.gotoff = gotoff;
8972   gofarg.got_elt_size = got_elt_size;
8973   elf_link_hash_traverse (elf_hash_table (info),
8974                           elf_gc_allocate_got_offsets,
8975                           &gofarg);
8976   return TRUE;
8977 }
8978
8979 /* Many folk need no more in the way of final link than this, once
8980    got entry reference counting is enabled.  */
8981
8982 bfd_boolean
8983 bfd_elf_gc_common_final_link (bfd *abfd, struct bfd_link_info *info)
8984 {
8985   if (!bfd_elf_gc_common_finalize_got_offsets (abfd, info))
8986     return FALSE;
8987
8988   /* Invoke the regular ELF backend linker to do all the work.  */
8989   return bfd_elf_final_link (abfd, info);
8990 }
8991
8992 bfd_boolean
8993 bfd_elf_reloc_symbol_deleted_p (bfd_vma offset, void *cookie)
8994 {
8995   struct elf_reloc_cookie *rcookie = cookie;
8996
8997   if (rcookie->bad_symtab)
8998     rcookie->rel = rcookie->rels;
8999
9000   for (; rcookie->rel < rcookie->relend; rcookie->rel++)
9001     {
9002       unsigned long r_symndx;
9003
9004       if (! rcookie->bad_symtab)
9005         if (rcookie->rel->r_offset > offset)
9006           return FALSE;
9007       if (rcookie->rel->r_offset != offset)
9008         continue;
9009
9010       r_symndx = rcookie->rel->r_info >> rcookie->r_sym_shift;
9011       if (r_symndx == SHN_UNDEF)
9012         return TRUE;
9013
9014       if (r_symndx >= rcookie->locsymcount
9015           || ELF_ST_BIND (rcookie->locsyms[r_symndx].st_info) != STB_LOCAL)
9016         {
9017           struct elf_link_hash_entry *h;
9018
9019           h = rcookie->sym_hashes[r_symndx - rcookie->extsymoff];
9020
9021           while (h->root.type == bfd_link_hash_indirect
9022                  || h->root.type == bfd_link_hash_warning)
9023             h = (struct elf_link_hash_entry *) h->root.u.i.link;
9024
9025           if ((h->root.type == bfd_link_hash_defined
9026                || h->root.type == bfd_link_hash_defweak)
9027               && elf_discarded_section (h->root.u.def.section))
9028             return TRUE;
9029           else
9030             return FALSE;
9031         }
9032       else
9033         {
9034           /* It's not a relocation against a global symbol,
9035              but it could be a relocation against a local
9036              symbol for a discarded section.  */
9037           asection *isec;
9038           Elf_Internal_Sym *isym;
9039
9040           /* Need to: get the symbol; get the section.  */
9041           isym = &rcookie->locsyms[r_symndx];
9042           if (isym->st_shndx < SHN_LORESERVE || isym->st_shndx > SHN_HIRESERVE)
9043             {
9044               isec = bfd_section_from_elf_index (rcookie->abfd, isym->st_shndx);
9045               if (isec != NULL && elf_discarded_section (isec))
9046                 return TRUE;
9047             }
9048         }
9049       return FALSE;
9050     }
9051   return FALSE;
9052 }
9053
9054 /* Discard unneeded references to discarded sections.
9055    Returns TRUE if any section's size was changed.  */
9056 /* This function assumes that the relocations are in sorted order,
9057    which is true for all known assemblers.  */
9058
9059 bfd_boolean
9060 bfd_elf_discard_info (bfd *output_bfd, struct bfd_link_info *info)
9061 {
9062   struct elf_reloc_cookie cookie;
9063   asection *stab, *eh;
9064   Elf_Internal_Shdr *symtab_hdr;
9065   const struct elf_backend_data *bed;
9066   bfd *abfd;
9067   unsigned int count;
9068   bfd_boolean ret = FALSE;
9069
9070   if (info->traditional_format
9071       || !is_elf_hash_table (info->hash))
9072     return FALSE;
9073
9074   for (abfd = info->input_bfds; abfd != NULL; abfd = abfd->link_next)
9075     {
9076       if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
9077         continue;
9078
9079       bed = get_elf_backend_data (abfd);
9080
9081       if ((abfd->flags & DYNAMIC) != 0)
9082         continue;
9083
9084       eh = bfd_get_section_by_name (abfd, ".eh_frame");
9085       if (info->relocatable
9086           || (eh != NULL
9087               && (eh->size == 0
9088                   || bfd_is_abs_section (eh->output_section))))
9089         eh = NULL;
9090
9091       stab = bfd_get_section_by_name (abfd, ".stab");
9092       if (stab != NULL
9093           && (stab->size == 0
9094               || bfd_is_abs_section (stab->output_section)
9095               || stab->sec_info_type != ELF_INFO_TYPE_STABS))
9096         stab = NULL;
9097
9098       if (stab == NULL
9099           && eh == NULL
9100           && bed->elf_backend_discard_info == NULL)
9101         continue;
9102
9103       symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
9104       cookie.abfd = abfd;
9105       cookie.sym_hashes = elf_sym_hashes (abfd);
9106       cookie.bad_symtab = elf_bad_symtab (abfd);
9107       if (cookie.bad_symtab)
9108         {
9109           cookie.locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
9110           cookie.extsymoff = 0;
9111         }
9112       else
9113         {
9114           cookie.locsymcount = symtab_hdr->sh_info;
9115           cookie.extsymoff = symtab_hdr->sh_info;
9116         }
9117
9118       if (bed->s->arch_size == 32)
9119         cookie.r_sym_shift = 8;
9120       else
9121         cookie.r_sym_shift = 32;
9122
9123       cookie.locsyms = (Elf_Internal_Sym *) symtab_hdr->contents;
9124       if (cookie.locsyms == NULL && cookie.locsymcount != 0)
9125         {
9126           cookie.locsyms = bfd_elf_get_elf_syms (abfd, symtab_hdr,
9127                                                  cookie.locsymcount, 0,
9128                                                  NULL, NULL, NULL);
9129           if (cookie.locsyms == NULL)
9130             return FALSE;
9131         }
9132
9133       if (stab != NULL)
9134         {
9135           cookie.rels = NULL;
9136           count = stab->reloc_count;
9137           if (count != 0)
9138             cookie.rels = _bfd_elf_link_read_relocs (abfd, stab, NULL, NULL,
9139                                                      info->keep_memory);
9140           if (cookie.rels != NULL)
9141             {
9142               cookie.rel = cookie.rels;
9143               cookie.relend = cookie.rels;
9144               cookie.relend += count * bed->s->int_rels_per_ext_rel;
9145               if (_bfd_discard_section_stabs (abfd, stab,
9146                                               elf_section_data (stab)->sec_info,
9147                                               bfd_elf_reloc_symbol_deleted_p,
9148                                               &cookie))
9149                 ret = TRUE;
9150               if (elf_section_data (stab)->relocs != cookie.rels)
9151                 free (cookie.rels);
9152             }
9153         }
9154
9155       if (eh != NULL)
9156         {
9157           cookie.rels = NULL;
9158           count = eh->reloc_count;
9159           if (count != 0)
9160             cookie.rels = _bfd_elf_link_read_relocs (abfd, eh, NULL, NULL,
9161                                                      info->keep_memory);
9162           cookie.rel = cookie.rels;
9163           cookie.relend = cookie.rels;
9164           if (cookie.rels != NULL)
9165             cookie.relend += count * bed->s->int_rels_per_ext_rel;
9166
9167           if (_bfd_elf_discard_section_eh_frame (abfd, info, eh,
9168                                                  bfd_elf_reloc_symbol_deleted_p,
9169                                                  &cookie))
9170             ret = TRUE;
9171
9172           if (cookie.rels != NULL
9173               && elf_section_data (eh)->relocs != cookie.rels)
9174             free (cookie.rels);
9175         }
9176
9177       if (bed->elf_backend_discard_info != NULL
9178           && (*bed->elf_backend_discard_info) (abfd, &cookie, info))
9179         ret = TRUE;
9180
9181       if (cookie.locsyms != NULL
9182           && symtab_hdr->contents != (unsigned char *) cookie.locsyms)
9183         {
9184           if (! info->keep_memory)
9185             free (cookie.locsyms);
9186           else
9187             symtab_hdr->contents = (unsigned char *) cookie.locsyms;
9188         }
9189     }
9190
9191   if (info->eh_frame_hdr
9192       && !info->relocatable
9193       && _bfd_elf_discard_section_eh_frame_hdr (output_bfd, info))
9194     ret = TRUE;
9195
9196   return ret;
9197 }
9198
9199 struct already_linked_section
9200 {
9201   asection *sec;
9202   asection *linked;
9203 };
9204
9205 /* Check if the member of a single member comdat group matches a
9206    linkonce section and vice versa.  */
9207 static bfd_boolean
9208 try_match_symbols_in_sections
9209   (struct bfd_section_already_linked_hash_entry *h, void *info)
9210 {
9211   struct bfd_section_already_linked *l;
9212   struct already_linked_section *s
9213     = (struct already_linked_section *) info;
9214
9215   if (elf_sec_group (s->sec) == NULL)
9216     {
9217       /* It is a linkonce section. Try to match it with the member of a
9218          single member comdat group. */
9219       for (l = h->entry; l != NULL; l = l->next)
9220         if ((l->sec->flags & SEC_GROUP))
9221           {
9222             asection *first = elf_next_in_group (l->sec);
9223
9224             if (first != NULL
9225                 && elf_next_in_group (first) == first
9226                 && bfd_elf_match_symbols_in_sections (first, s->sec))
9227               {
9228                 s->linked = first;
9229                 return FALSE;
9230               }
9231           }
9232     }
9233   else
9234     {
9235       /* It is the member of a single member comdat group. Try to match
9236          it with a linkonce section.  */
9237       for (l = h->entry; l != NULL; l = l->next)
9238         if ((l->sec->flags & SEC_GROUP) == 0
9239             && bfd_coff_get_comdat_section (l->sec->owner, l->sec) == NULL
9240             && bfd_elf_match_symbols_in_sections (l->sec, s->sec))
9241           {
9242             s->linked = l->sec;
9243             return FALSE;
9244           }
9245     }
9246
9247   return TRUE;
9248 }
9249
9250 static bfd_boolean
9251 already_linked (asection *sec, asection *group)
9252 {
9253   struct already_linked_section result;
9254
9255   result.sec = sec;
9256   result.linked = NULL;
9257
9258   bfd_section_already_linked_table_traverse
9259     (try_match_symbols_in_sections, &result);
9260
9261   if (result.linked)
9262     {
9263       sec->output_section = bfd_abs_section_ptr;
9264       sec->kept_section = result.linked;
9265
9266       /* Also discard the group section.  */
9267       if (group)
9268         group->output_section = bfd_abs_section_ptr;
9269
9270       return TRUE;
9271     }
9272
9273   return FALSE;
9274 }
9275
9276 void
9277 _bfd_elf_section_already_linked (bfd *abfd, struct bfd_section * sec)
9278 {
9279   flagword flags;
9280   const char *name;
9281   struct bfd_section_already_linked *l;
9282   struct bfd_section_already_linked_hash_entry *already_linked_list;
9283   asection *group;
9284
9285   /* A single member comdat group section may be discarded by a
9286      linkonce section. See below.  */
9287   if (sec->output_section == bfd_abs_section_ptr)
9288     return;
9289
9290   flags = sec->flags;
9291
9292   /* Check if it belongs to a section group.  */
9293   group = elf_sec_group (sec);
9294
9295   /* Return if it isn't a linkonce section nor a member of a group.  A
9296      comdat group section also has SEC_LINK_ONCE set.  */
9297   if ((flags & SEC_LINK_ONCE) == 0 && group == NULL)
9298     return;
9299
9300   if (group)
9301     {
9302       /* If this is the member of a single member comdat group, check if
9303          the group should be discarded.  */
9304       if (elf_next_in_group (sec) == sec
9305           && (group->flags & SEC_LINK_ONCE) != 0)
9306         sec = group;
9307       else
9308         return;
9309     }
9310
9311   /* FIXME: When doing a relocatable link, we may have trouble
9312      copying relocations in other sections that refer to local symbols
9313      in the section being discarded.  Those relocations will have to
9314      be converted somehow; as of this writing I'm not sure that any of
9315      the backends handle that correctly.
9316
9317      It is tempting to instead not discard link once sections when
9318      doing a relocatable link (technically, they should be discarded
9319      whenever we are building constructors).  However, that fails,
9320      because the linker winds up combining all the link once sections
9321      into a single large link once section, which defeats the purpose
9322      of having link once sections in the first place.
9323
9324      Also, not merging link once sections in a relocatable link
9325      causes trouble for MIPS ELF, which relies on link once semantics
9326      to handle the .reginfo section correctly.  */
9327
9328   name = bfd_get_section_name (abfd, sec);
9329
9330   already_linked_list = bfd_section_already_linked_table_lookup (name);
9331
9332   for (l = already_linked_list->entry; l != NULL; l = l->next)
9333     {
9334       /* We may have 3 different sections on the list: group section,
9335          comdat section and linkonce section. SEC may be a linkonce or
9336          group section. We match a group section with a group section,
9337          a linkonce section with a linkonce section, and ignore comdat
9338          section.  */
9339       if ((flags & SEC_GROUP) == (l->sec->flags & SEC_GROUP)
9340           && bfd_coff_get_comdat_section (l->sec->owner, l->sec) == NULL)
9341         {
9342           /* The section has already been linked.  See if we should
9343              issue a warning.  */
9344           switch (flags & SEC_LINK_DUPLICATES)
9345             {
9346             default:
9347               abort ();
9348
9349             case SEC_LINK_DUPLICATES_DISCARD:
9350               break;
9351
9352             case SEC_LINK_DUPLICATES_ONE_ONLY:
9353               (*_bfd_error_handler)
9354                 (_("%B: ignoring duplicate section `%A'\n"),
9355                  abfd, sec);
9356               break;
9357
9358             case SEC_LINK_DUPLICATES_SAME_SIZE:
9359               if (sec->size != l->sec->size)
9360                 (*_bfd_error_handler)
9361                   (_("%B: duplicate section `%A' has different size\n"),
9362                    abfd, sec);
9363               break;
9364             }
9365
9366           /* Set the output_section field so that lang_add_section
9367              does not create a lang_input_section structure for this
9368              section.  Since there might be a symbol in the section
9369              being discarded, we must retain a pointer to the section
9370              which we are really going to use.  */
9371           sec->output_section = bfd_abs_section_ptr;
9372           sec->kept_section = l->sec;
9373           
9374           if (flags & SEC_GROUP)
9375             {
9376               asection *first = elf_next_in_group (sec);
9377               asection *s = first;
9378
9379               while (s != NULL)
9380                 {
9381                   s->output_section = bfd_abs_section_ptr;
9382                   /* Record which group discards it.  */
9383                   s->kept_section = l->sec;
9384                   s = elf_next_in_group (s);
9385                   /* These lists are circular.  */
9386                   if (s == first)
9387                     break;
9388                 }
9389             }
9390
9391           return;
9392         }
9393     }
9394
9395   if (group)
9396     {
9397       /* If this is the member of a single member comdat group and the
9398          group hasn't be discarded, we check if it matches a linkonce
9399          section. We only record the discarded comdat group. Otherwise
9400          the undiscarded group will be discarded incorrectly later since
9401          itself has been recorded.  */
9402       if (! already_linked (elf_next_in_group (sec), group))
9403         return;
9404     }
9405   else
9406     /* There is no direct match. But for linkonce section, we should
9407        check if there is a match with comdat group member. We always
9408        record the linkonce section, discarded or not.  */
9409     already_linked (sec, group);
9410   
9411   /* This is the first section with this name.  Record it.  */
9412   bfd_section_already_linked_table_insert (already_linked_list, sec);
9413 }