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