* elfcode.h (elf_link_add_object_symbols): Only examine weakdef if
[external/binutils.git] / bfd / elfcode.h
1 /* ELF executable support for BFD.
2    Copyright 1991, 1992, 1993, 1994, 1995 Free Software Foundation, Inc.
3
4    Written by Fred Fish @ Cygnus Support, from information published
5    in "UNIX System V Release 4, Programmers Guide: ANSI C and
6    Programming Support Tools".  Sufficient support for gdb.
7
8    Rewritten by Mark Eichin @ Cygnus Support, from information
9    published in "System V Application Binary Interface", chapters 4
10    and 5, as well as the various "Processor Supplement" documents
11    derived from it. Added support for assembler and other object file
12    utilities.  Further work done by Ken Raeburn (Cygnus Support), Michael
13    Meissner (Open Software Foundation), and Peter Hoogenboom (University
14    of Utah) to finish and extend this.
15
16 This file is part of BFD, the Binary File Descriptor library.
17
18 This program is free software; you can redistribute it and/or modify
19 it under the terms of the GNU General Public License as published by
20 the Free Software Foundation; either version 2 of the License, or
21 (at your option) any later version.
22
23 This program is distributed in the hope that it will be useful,
24 but WITHOUT ANY WARRANTY; without even the implied warranty of
25 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
26 GNU General Public License for more details.
27
28 You should have received a copy of the GNU General Public License
29 along with this program; if not, write to the Free Software
30 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
31
32 /* Problems and other issues to resolve.
33
34    (1)  BFD expects there to be some fixed number of "sections" in
35         the object file.  I.E. there is a "section_count" variable in the
36         bfd structure which contains the number of sections.  However, ELF
37         supports multiple "views" of a file.  In particular, with current
38         implementations, executable files typically have two tables, a
39         program header table and a section header table, both of which
40         partition the executable.
41
42         In ELF-speak, the "linking view" of the file uses the section header
43         table to access "sections" within the file, and the "execution view"
44         uses the program header table to access "segments" within the file.
45         "Segments" typically may contain all the data from one or more
46         "sections".
47
48         Note that the section header table is optional in ELF executables,
49         but it is this information that is most useful to gdb.  If the
50         section header table is missing, then gdb should probably try
51         to make do with the program header table.  (FIXME)
52
53    (2)  The code in this file is compiled twice, once in 32-bit mode and
54         once in 64-bit mode.  More of it should be made size-independent
55         and moved into elf.c.
56
57    (3)  ELF section symbols are handled rather sloppily now.  This should
58         be cleaned up, and ELF section symbols reconciled with BFD section
59         symbols.
60
61    (4)  We need a published spec for 64-bit ELF.  We've got some stuff here
62         that we're using for SPARC V9 64-bit chips, but don't assume that
63         it's cast in stone.
64  */
65
66 #include <string.h>             /* For strrchr and friends */
67 #include "bfd.h"
68 #include "sysdep.h"
69 #include "bfdlink.h"
70 #include "libbfd.h"
71 #include "libelf.h"
72
73 /* Renaming structures, typedefs, macros and functions to be size-specific.  */
74 #define Elf_External_Ehdr       NAME(Elf,External_Ehdr)
75 #define Elf_External_Sym        NAME(Elf,External_Sym)
76 #define Elf_External_Shdr       NAME(Elf,External_Shdr)
77 #define Elf_External_Phdr       NAME(Elf,External_Phdr)
78 #define Elf_External_Rel        NAME(Elf,External_Rel)
79 #define Elf_External_Rela       NAME(Elf,External_Rela)
80 #define Elf_External_Dyn        NAME(Elf,External_Dyn)
81
82 #define elf_core_file_failing_command   NAME(bfd_elf,core_file_failing_command)
83 #define elf_core_file_failing_signal    NAME(bfd_elf,core_file_failing_signal)
84 #define elf_core_file_matches_executable_p \
85   NAME(bfd_elf,core_file_matches_executable_p)
86 #define elf_object_p                    NAME(bfd_elf,object_p)
87 #define elf_core_file_p                 NAME(bfd_elf,core_file_p)
88 #define elf_get_symtab_upper_bound      NAME(bfd_elf,get_symtab_upper_bound)
89 #define elf_get_dynamic_symtab_upper_bound \
90   NAME(bfd_elf,get_dynamic_symtab_upper_bound)
91 #define elf_swap_reloc_in               NAME(bfd_elf,swap_reloc_in)
92 #define elf_swap_reloca_in              NAME(bfd_elf,swap_reloca_in)
93 #define elf_swap_reloc_out              NAME(bfd_elf,swap_reloc_out)
94 #define elf_swap_reloca_out             NAME(bfd_elf,swap_reloca_out)
95 #define elf_swap_symbol_in              NAME(bfd_elf,swap_symbol_in)
96 #define elf_swap_symbol_out             NAME(bfd_elf,swap_symbol_out)
97 #define elf_swap_dyn_in                 NAME(bfd_elf,swap_dyn_in)
98 #define elf_swap_dyn_out                NAME(bfd_elf,swap_dyn_out)
99 #define elf_get_reloc_upper_bound       NAME(bfd_elf,get_reloc_upper_bound)
100 #define elf_canonicalize_reloc          NAME(bfd_elf,canonicalize_reloc)
101 #define elf_get_symtab                  NAME(bfd_elf,get_symtab)
102 #define elf_canonicalize_dynamic_symtab \
103   NAME(bfd_elf,canonicalize_dynamic_symtab)
104 #define elf_make_empty_symbol           NAME(bfd_elf,make_empty_symbol)
105 #define elf_get_symbol_info             NAME(bfd_elf,get_symbol_info)
106 #define elf_get_lineno                  NAME(bfd_elf,get_lineno)
107 #define elf_set_arch_mach               NAME(bfd_elf,set_arch_mach)
108 #define elf_find_nearest_line           NAME(bfd_elf,find_nearest_line)
109 #define elf_sizeof_headers              NAME(bfd_elf,sizeof_headers)
110 #define elf_set_section_contents        NAME(bfd_elf,set_section_contents)
111 #define elf_no_info_to_howto            NAME(bfd_elf,no_info_to_howto)
112 #define elf_no_info_to_howto_rel        NAME(bfd_elf,no_info_to_howto_rel)
113 #define elf_new_section_hook            NAME(bfd_elf,new_section_hook)
114 #define write_relocs                    NAME(bfd_elf,_write_relocs)
115 #define elf_find_section                NAME(bfd_elf,find_section)
116 #define elf_bfd_link_add_symbols        NAME(bfd_elf,bfd_link_add_symbols)
117 #define elf_add_dynamic_entry           NAME(bfd_elf,add_dynamic_entry)
118 #define elf_link_create_dynamic_sections \
119   NAME(bfd_elf,link_create_dynamic_sections)
120 #define elf_link_record_dynamic_symbol  \
121   NAME(bfd_elf,link_record_dynamic_symbol)
122 #define elf_bfd_final_link              NAME(bfd_elf,bfd_final_link)
123
124 #if ARCH_SIZE == 64
125 #define ELF_R_INFO(X,Y) ELF64_R_INFO(X,Y)
126 #define ELF_R_SYM(X)    ELF64_R_SYM(X)
127 #define ELF_R_TYPE(X)   ELF64_R_TYPE(X)
128 #define ELFCLASS        ELFCLASS64
129 #define FILE_ALIGN      8
130 #define LOG_FILE_ALIGN  3
131 #endif
132 #if ARCH_SIZE == 32
133 #define ELF_R_INFO(X,Y) ELF32_R_INFO(X,Y)
134 #define ELF_R_SYM(X)    ELF32_R_SYM(X)
135 #define ELF_R_TYPE(X)   ELF32_R_TYPE(X)
136 #define ELFCLASS        ELFCLASS32
137 #define FILE_ALIGN      4
138 #define LOG_FILE_ALIGN  2
139 #endif
140
141 /* Forward declarations of static functions */
142
143 static struct bfd_strtab_hash *elf_stringtab_init PARAMS ((void));
144 static asection *section_from_elf_index PARAMS ((bfd *, unsigned int));
145
146 static int elf_section_from_bfd_section PARAMS ((bfd *, struct sec *));
147
148 static long elf_slurp_symbol_table PARAMS ((bfd *, asymbol **, boolean));
149
150 static boolean elf_slurp_reloc_table PARAMS ((bfd *, asection *, asymbol **));
151
152 static int elf_symbol_from_bfd_symbol PARAMS ((bfd *,
153                                              struct symbol_cache_entry **));
154
155 static boolean elf_compute_section_file_positions
156   PARAMS ((bfd *, struct bfd_link_info *));
157 static boolean prep_headers PARAMS ((bfd *));
158 static void elf_fake_sections PARAMS ((bfd *, asection *, PTR));
159 static boolean assign_section_numbers PARAMS ((bfd *));
160 static file_ptr align_file_position PARAMS ((file_ptr));
161 static file_ptr assign_file_position_for_section
162   PARAMS ((Elf_Internal_Shdr *, file_ptr, boolean));
163 static boolean assign_file_positions_except_relocs PARAMS ((bfd *, boolean));
164 static int elf_sort_hdrs PARAMS ((const PTR, const PTR));
165 static void assign_file_positions_for_relocs PARAMS ((bfd *));
166 static bfd_size_type get_program_header_size PARAMS ((bfd *));
167 static file_ptr map_program_segments
168   PARAMS ((bfd *, file_ptr, Elf_Internal_Shdr *, bfd_size_type));
169
170 static boolean elf_map_symbols PARAMS ((bfd *));
171 static boolean swap_out_syms PARAMS ((bfd *, struct bfd_strtab_hash **));
172
173 static boolean bfd_section_from_shdr PARAMS ((bfd *, unsigned int shindex));
174
175 #ifdef DEBUG
176 static void elf_debug_section PARAMS ((int, Elf_Internal_Shdr *));
177 static void elf_debug_file PARAMS ((Elf_Internal_Ehdr *));
178 #endif
179
180 #define elf_string_from_elf_strtab(abfd,strindex) \
181      elf_string_from_elf_section(abfd,elf_elfheader(abfd)->e_shstrndx,strindex)
182 \f
183 /* Structure swapping routines */
184
185 /* Should perhaps use put_offset, put_word, etc.  For now, the two versions
186    can be handled by explicitly specifying 32 bits or "the long type".  */
187 #if ARCH_SIZE == 64
188 #define put_word        bfd_h_put_64
189 #define get_word        bfd_h_get_64
190 #endif
191 #if ARCH_SIZE == 32
192 #define put_word        bfd_h_put_32
193 #define get_word        bfd_h_get_32
194 #endif
195
196 /* Translate an ELF symbol in external format into an ELF symbol in internal
197    format. */
198
199 void
200 elf_swap_symbol_in (abfd, src, dst)
201      bfd *abfd;
202      Elf_External_Sym *src;
203      Elf_Internal_Sym *dst;
204 {
205   dst->st_name = bfd_h_get_32 (abfd, (bfd_byte *) src->st_name);
206   dst->st_value = get_word (abfd, (bfd_byte *) src->st_value);
207   dst->st_size = get_word (abfd, (bfd_byte *) src->st_size);
208   dst->st_info = bfd_h_get_8 (abfd, (bfd_byte *) src->st_info);
209   dst->st_other = bfd_h_get_8 (abfd, (bfd_byte *) src->st_other);
210   dst->st_shndx = bfd_h_get_16 (abfd, (bfd_byte *) src->st_shndx);
211 }
212
213 /* Translate an ELF symbol in internal format into an ELF symbol in external
214    format. */
215
216 void
217 elf_swap_symbol_out (abfd, src, dst)
218      bfd *abfd;
219      Elf_Internal_Sym *src;
220      Elf_External_Sym *dst;
221 {
222   bfd_h_put_32 (abfd, src->st_name, dst->st_name);
223   put_word (abfd, src->st_value, dst->st_value);
224   put_word (abfd, src->st_size, dst->st_size);
225   bfd_h_put_8 (abfd, src->st_info, dst->st_info);
226   bfd_h_put_8 (abfd, src->st_other, dst->st_other);
227   bfd_h_put_16 (abfd, src->st_shndx, dst->st_shndx);
228 }
229
230
231 /* Translate an ELF file header in external format into an ELF file header in
232    internal format. */
233
234 static void
235 elf_swap_ehdr_in (abfd, src, dst)
236      bfd *abfd;
237      Elf_External_Ehdr *src;
238      Elf_Internal_Ehdr *dst;
239 {
240   memcpy (dst->e_ident, src->e_ident, EI_NIDENT);
241   dst->e_type = bfd_h_get_16 (abfd, (bfd_byte *) src->e_type);
242   dst->e_machine = bfd_h_get_16 (abfd, (bfd_byte *) src->e_machine);
243   dst->e_version = bfd_h_get_32 (abfd, (bfd_byte *) src->e_version);
244   dst->e_entry = get_word (abfd, (bfd_byte *) src->e_entry);
245   dst->e_phoff = get_word (abfd, (bfd_byte *) src->e_phoff);
246   dst->e_shoff = get_word (abfd, (bfd_byte *) src->e_shoff);
247   dst->e_flags = bfd_h_get_32 (abfd, (bfd_byte *) src->e_flags);
248   dst->e_ehsize = bfd_h_get_16 (abfd, (bfd_byte *) src->e_ehsize);
249   dst->e_phentsize = bfd_h_get_16 (abfd, (bfd_byte *) src->e_phentsize);
250   dst->e_phnum = bfd_h_get_16 (abfd, (bfd_byte *) src->e_phnum);
251   dst->e_shentsize = bfd_h_get_16 (abfd, (bfd_byte *) src->e_shentsize);
252   dst->e_shnum = bfd_h_get_16 (abfd, (bfd_byte *) src->e_shnum);
253   dst->e_shstrndx = bfd_h_get_16 (abfd, (bfd_byte *) src->e_shstrndx);
254 }
255
256 /* Translate an ELF file header in internal format into an ELF file header in
257    external format. */
258
259 static void
260 elf_swap_ehdr_out (abfd, src, dst)
261      bfd *abfd;
262      Elf_Internal_Ehdr *src;
263      Elf_External_Ehdr *dst;
264 {
265   memcpy (dst->e_ident, src->e_ident, EI_NIDENT);
266   /* note that all elements of dst are *arrays of unsigned char* already... */
267   bfd_h_put_16 (abfd, src->e_type, dst->e_type);
268   bfd_h_put_16 (abfd, src->e_machine, dst->e_machine);
269   bfd_h_put_32 (abfd, src->e_version, dst->e_version);
270   put_word (abfd, src->e_entry, dst->e_entry);
271   put_word (abfd, src->e_phoff, dst->e_phoff);
272   put_word (abfd, src->e_shoff, dst->e_shoff);
273   bfd_h_put_32 (abfd, src->e_flags, dst->e_flags);
274   bfd_h_put_16 (abfd, src->e_ehsize, dst->e_ehsize);
275   bfd_h_put_16 (abfd, src->e_phentsize, dst->e_phentsize);
276   bfd_h_put_16 (abfd, src->e_phnum, dst->e_phnum);
277   bfd_h_put_16 (abfd, src->e_shentsize, dst->e_shentsize);
278   bfd_h_put_16 (abfd, src->e_shnum, dst->e_shnum);
279   bfd_h_put_16 (abfd, src->e_shstrndx, dst->e_shstrndx);
280 }
281
282
283 /* Translate an ELF section header table entry in external format into an
284    ELF section header table entry in internal format. */
285
286 static void
287 elf_swap_shdr_in (abfd, src, dst)
288      bfd *abfd;
289      Elf_External_Shdr *src;
290      Elf_Internal_Shdr *dst;
291 {
292   dst->sh_name = bfd_h_get_32 (abfd, (bfd_byte *) src->sh_name);
293   dst->sh_type = bfd_h_get_32 (abfd, (bfd_byte *) src->sh_type);
294   dst->sh_flags = get_word (abfd, (bfd_byte *) src->sh_flags);
295   dst->sh_addr = get_word (abfd, (bfd_byte *) src->sh_addr);
296   dst->sh_offset = get_word (abfd, (bfd_byte *) src->sh_offset);
297   dst->sh_size = get_word (abfd, (bfd_byte *) src->sh_size);
298   dst->sh_link = bfd_h_get_32 (abfd, (bfd_byte *) src->sh_link);
299   dst->sh_info = bfd_h_get_32 (abfd, (bfd_byte *) src->sh_info);
300   dst->sh_addralign = get_word (abfd, (bfd_byte *) src->sh_addralign);
301   dst->sh_entsize = get_word (abfd, (bfd_byte *) src->sh_entsize);
302   dst->bfd_section = NULL;
303   dst->contents = NULL;
304 }
305
306 /* Translate an ELF section header table entry in internal format into an
307    ELF section header table entry in external format. */
308
309 static void
310 elf_swap_shdr_out (abfd, src, dst)
311      bfd *abfd;
312      Elf_Internal_Shdr *src;
313      Elf_External_Shdr *dst;
314 {
315   /* note that all elements of dst are *arrays of unsigned char* already... */
316   bfd_h_put_32 (abfd, src->sh_name, dst->sh_name);
317   bfd_h_put_32 (abfd, src->sh_type, dst->sh_type);
318   put_word (abfd, src->sh_flags, dst->sh_flags);
319   put_word (abfd, src->sh_addr, dst->sh_addr);
320   put_word (abfd, src->sh_offset, dst->sh_offset);
321   put_word (abfd, src->sh_size, dst->sh_size);
322   bfd_h_put_32 (abfd, src->sh_link, dst->sh_link);
323   bfd_h_put_32 (abfd, src->sh_info, dst->sh_info);
324   put_word (abfd, src->sh_addralign, dst->sh_addralign);
325   put_word (abfd, src->sh_entsize, dst->sh_entsize);
326 }
327
328
329 /* Translate an ELF program header table entry in external format into an
330    ELF program header table entry in internal format. */
331
332 static void
333 elf_swap_phdr_in (abfd, src, dst)
334      bfd *abfd;
335      Elf_External_Phdr *src;
336      Elf_Internal_Phdr *dst;
337 {
338   dst->p_type = bfd_h_get_32 (abfd, (bfd_byte *) src->p_type);
339   dst->p_flags = bfd_h_get_32 (abfd, (bfd_byte *) src->p_flags);
340   dst->p_offset = get_word (abfd, (bfd_byte *) src->p_offset);
341   dst->p_vaddr = get_word (abfd, (bfd_byte *) src->p_vaddr);
342   dst->p_paddr = get_word (abfd, (bfd_byte *) src->p_paddr);
343   dst->p_filesz = get_word (abfd, (bfd_byte *) src->p_filesz);
344   dst->p_memsz = get_word (abfd, (bfd_byte *) src->p_memsz);
345   dst->p_align = get_word (abfd, (bfd_byte *) src->p_align);
346 }
347
348 static void
349 elf_swap_phdr_out (abfd, src, dst)
350      bfd *abfd;
351      Elf_Internal_Phdr *src;
352      Elf_External_Phdr *dst;
353 {
354   /* note that all elements of dst are *arrays of unsigned char* already... */
355   bfd_h_put_32 (abfd, src->p_type, dst->p_type);
356   put_word (abfd, src->p_offset, dst->p_offset);
357   put_word (abfd, src->p_vaddr, dst->p_vaddr);
358   put_word (abfd, src->p_paddr, dst->p_paddr);
359   put_word (abfd, src->p_filesz, dst->p_filesz);
360   put_word (abfd, src->p_memsz, dst->p_memsz);
361   bfd_h_put_32 (abfd, src->p_flags, dst->p_flags);
362   put_word (abfd, src->p_align, dst->p_align);
363 }
364
365 /* Translate an ELF reloc from external format to internal format. */
366 INLINE void
367 elf_swap_reloc_in (abfd, src, dst)
368      bfd *abfd;
369      Elf_External_Rel *src;
370      Elf_Internal_Rel *dst;
371 {
372   dst->r_offset = get_word (abfd, (bfd_byte *) src->r_offset);
373   dst->r_info = get_word (abfd, (bfd_byte *) src->r_info);
374 }
375
376 INLINE void
377 elf_swap_reloca_in (abfd, src, dst)
378      bfd *abfd;
379      Elf_External_Rela *src;
380      Elf_Internal_Rela *dst;
381 {
382   dst->r_offset = get_word (abfd, (bfd_byte *) src->r_offset);
383   dst->r_info = get_word (abfd, (bfd_byte *) src->r_info);
384   dst->r_addend = get_word (abfd, (bfd_byte *) src->r_addend);
385 }
386
387 /* Translate an ELF reloc from internal format to external format. */
388 INLINE void
389 elf_swap_reloc_out (abfd, src, dst)
390      bfd *abfd;
391      Elf_Internal_Rel *src;
392      Elf_External_Rel *dst;
393 {
394   put_word (abfd, src->r_offset, dst->r_offset);
395   put_word (abfd, src->r_info, dst->r_info);
396 }
397
398 INLINE void
399 elf_swap_reloca_out (abfd, src, dst)
400      bfd *abfd;
401      Elf_Internal_Rela *src;
402      Elf_External_Rela *dst;
403 {
404   put_word (abfd, src->r_offset, dst->r_offset);
405   put_word (abfd, src->r_info, dst->r_info);
406   put_word (abfd, src->r_addend, dst->r_addend);
407 }
408
409 INLINE void
410 elf_swap_dyn_in (abfd, src, dst)
411      bfd *abfd;
412      const Elf_External_Dyn *src;
413      Elf_Internal_Dyn *dst;
414 {
415   dst->d_tag = get_word (abfd, src->d_tag);
416   dst->d_un.d_val = get_word (abfd, src->d_un.d_val);
417 }
418
419 INLINE void
420 elf_swap_dyn_out (abfd, src, dst)
421      bfd *abfd;
422      const Elf_Internal_Dyn *src;
423      Elf_External_Dyn *dst;
424 {
425   put_word (abfd, src->d_tag, dst->d_tag);
426   put_word (abfd, src->d_un.d_val, dst->d_un.d_val);
427 }
428 \f
429 /* Allocate an ELF string table--force the first byte to be zero.  */
430
431 static struct bfd_strtab_hash *
432 elf_stringtab_init ()
433 {
434   struct bfd_strtab_hash *ret;
435
436   ret = _bfd_stringtab_init ();
437   if (ret != NULL)
438     {
439       bfd_size_type loc;
440
441       loc = _bfd_stringtab_add (ret, "", true, false);
442       BFD_ASSERT (loc == 0 || loc == (bfd_size_type) -1);
443       if (loc == (bfd_size_type) -1)
444         {
445           _bfd_stringtab_free (ret);
446           ret = NULL;
447         }
448     }
449   return ret;
450 }
451 \f
452 /* ELF .o/exec file reading */
453
454 /* Create a new bfd section from an ELF section header. */
455
456 static boolean
457 bfd_section_from_shdr (abfd, shindex)
458      bfd *abfd;
459      unsigned int shindex;
460 {
461   Elf_Internal_Shdr *hdr = elf_elfsections (abfd)[shindex];
462   Elf_Internal_Ehdr *ehdr = elf_elfheader (abfd);
463   char *name;
464
465   name = elf_string_from_elf_strtab (abfd, hdr->sh_name);
466
467   switch (hdr->sh_type)
468     {
469     case SHT_NULL:
470       /* Inactive section. Throw it away.  */
471       return true;
472
473     case SHT_PROGBITS:  /* Normal section with contents.  */
474     case SHT_DYNAMIC:   /* Dynamic linking information.  */
475     case SHT_NOBITS:    /* .bss section.  */
476     case SHT_HASH:      /* .hash section.  */
477       return _bfd_elf_make_section_from_shdr (abfd, hdr, name);
478
479     case SHT_SYMTAB:            /* A symbol table */
480       if (elf_onesymtab (abfd) == shindex)
481         return true;
482
483       BFD_ASSERT (hdr->sh_entsize == sizeof (Elf_External_Sym));
484       BFD_ASSERT (elf_onesymtab (abfd) == 0);
485       elf_onesymtab (abfd) = shindex;
486       elf_tdata (abfd)->symtab_hdr = *hdr;
487       elf_elfsections (abfd)[shindex] = &elf_tdata (abfd)->symtab_hdr;
488       abfd->flags |= HAS_SYMS;
489
490       /* Sometimes a shared object will map in the symbol table.  If
491          SHF_ALLOC is set, and this is a shared object, then we also
492          treat this section as a BFD section.  We can not base the
493          decision purely on SHF_ALLOC, because that flag is sometimes
494          set in a relocateable object file, which would confuse the
495          linker.  */
496       if ((hdr->sh_flags & SHF_ALLOC) != 0
497           && (abfd->flags & DYNAMIC) != 0
498           && ! _bfd_elf_make_section_from_shdr (abfd, hdr, name))
499         return false;
500
501       return true;
502
503     case SHT_DYNSYM:            /* A dynamic symbol table */
504       if (elf_dynsymtab (abfd) == shindex)
505         return true;
506
507       BFD_ASSERT (hdr->sh_entsize == sizeof (Elf_External_Sym));
508       BFD_ASSERT (elf_dynsymtab (abfd) == 0);
509       elf_dynsymtab (abfd) = shindex;
510       elf_tdata (abfd)->dynsymtab_hdr = *hdr;
511       elf_elfsections (abfd)[shindex] = &elf_tdata (abfd)->dynsymtab_hdr;
512       abfd->flags |= HAS_SYMS;
513
514       /* Besides being a symbol table, we also treat this as a regular
515          section, so that objcopy can handle it.  */
516       return _bfd_elf_make_section_from_shdr (abfd, hdr, name);
517
518     case SHT_STRTAB:            /* A string table */
519       if (hdr->bfd_section != NULL)
520         return true;
521       if (ehdr->e_shstrndx == shindex)
522         {
523           elf_tdata (abfd)->shstrtab_hdr = *hdr;
524           elf_elfsections (abfd)[shindex] = &elf_tdata (abfd)->shstrtab_hdr;
525           return true;
526         }
527       {
528         unsigned int i;
529
530         for (i = 1; i < ehdr->e_shnum; i++)
531           {
532             Elf_Internal_Shdr *hdr2 = elf_elfsections (abfd)[i];
533             if (hdr2->sh_link == shindex)
534               {
535                 if (! bfd_section_from_shdr (abfd, i))
536                   return false;
537                 if (elf_onesymtab (abfd) == i)
538                   {
539                     elf_tdata (abfd)->strtab_hdr = *hdr;
540                     elf_elfsections (abfd)[shindex] =
541                       &elf_tdata (abfd)->strtab_hdr;
542                     return true;
543                   }
544                 if (elf_dynsymtab (abfd) == i)
545                   {
546                     elf_tdata (abfd)->dynstrtab_hdr = *hdr;
547                     elf_elfsections (abfd)[shindex] =
548                       &elf_tdata (abfd)->dynstrtab_hdr;
549                     /* We also treat this as a regular section, so
550                        that objcopy can handle it.  */
551                     break;
552                   }
553 #if 0 /* Not handling other string tables specially right now.  */
554                 hdr2 = elf_elfsections (abfd)[i];       /* in case it moved */
555                 /* We have a strtab for some random other section.  */
556                 newsect = (asection *) hdr2->bfd_section;
557                 if (!newsect)
558                   break;
559                 hdr->bfd_section = newsect;
560                 hdr2 = &elf_section_data (newsect)->str_hdr;
561                 *hdr2 = *hdr;
562                 elf_elfsections (abfd)[shindex] = hdr2;
563 #endif
564               }
565           }
566       }
567
568       return _bfd_elf_make_section_from_shdr (abfd, hdr, name);
569
570     case SHT_REL:
571     case SHT_RELA:
572       /* *These* do a lot of work -- but build no sections!  */
573       {
574         asection *target_sect;
575         Elf_Internal_Shdr *hdr2;
576         int use_rela_p = get_elf_backend_data (abfd)->use_rela_p;
577
578         /* Get the symbol table.  */
579         if (! bfd_section_from_shdr (abfd, hdr->sh_link))
580           return false;
581
582         /* If this reloc section does not use the main symbol table we
583            don't treat it as a reloc section.  BFD can't adequately
584            represent such a section, so at least for now, we don't
585            try.  We just present it as a normal section.  */
586         if (hdr->sh_link != elf_onesymtab (abfd))
587           return _bfd_elf_make_section_from_shdr (abfd, hdr, name);
588
589         /* Don't allow REL relocations on a machine that uses RELA and
590            vice versa.  */
591         /* @@ Actually, the generic ABI does suggest that both might be
592            used in one file.  But the four ABI Processor Supplements I
593            have access to right now all specify that only one is used on
594            each of those architectures.  It's conceivable that, e.g., a
595            bunch of absolute 32-bit relocs might be more compact in REL
596            form even on a RELA machine...  */
597         BFD_ASSERT (use_rela_p
598                     ? (hdr->sh_type == SHT_RELA
599                        && hdr->sh_entsize == sizeof (Elf_External_Rela))
600                     : (hdr->sh_type == SHT_REL
601                        && hdr->sh_entsize == sizeof (Elf_External_Rel)));
602
603         if (! bfd_section_from_shdr (abfd, hdr->sh_info))
604           return false;
605         target_sect = section_from_elf_index (abfd, hdr->sh_info);
606         if (target_sect == NULL)
607           return false;
608
609         hdr2 = &elf_section_data (target_sect)->rel_hdr;
610         *hdr2 = *hdr;
611         elf_elfsections (abfd)[shindex] = hdr2;
612         target_sect->reloc_count = hdr->sh_size / hdr->sh_entsize;
613         target_sect->flags |= SEC_RELOC;
614         target_sect->relocation = NULL;
615         target_sect->rel_filepos = hdr->sh_offset;
616         abfd->flags |= HAS_RELOC;
617         return true;
618       }
619       break;
620
621     case SHT_NOTE:
622 #if 0
623       fprintf (stderr, "Note Sections not yet supported.\n");
624       BFD_FAIL ();
625 #endif
626       break;
627
628     case SHT_SHLIB:
629 #if 0
630       fprintf (stderr, "SHLIB Sections not supported (and non conforming.)\n");
631 #endif
632       return true;
633
634     default:
635       /* Check for any processor-specific section types.  */
636       {
637         struct elf_backend_data *bed = get_elf_backend_data (abfd);
638
639         if (bed->elf_backend_section_from_shdr)
640           (*bed->elf_backend_section_from_shdr) (abfd, hdr, name);
641       }
642       break;
643     }
644
645   return true;
646 }
647
648 boolean
649 elf_new_section_hook (abfd, sec)
650      bfd *abfd
651       ;
652      asection *sec;
653 {
654   struct bfd_elf_section_data *sdata;
655
656   sdata = (struct bfd_elf_section_data *) bfd_alloc (abfd, sizeof (*sdata));
657   if (!sdata)
658     {
659       bfd_set_error (bfd_error_no_memory);
660       return false;
661     }
662   sec->used_by_bfd = (PTR) sdata;
663   memset (sdata, 0, sizeof (*sdata));
664   return true;
665 }
666
667 /* Create a new bfd section from an ELF program header.
668
669    Since program segments have no names, we generate a synthetic name
670    of the form segment<NUM>, where NUM is generally the index in the
671    program header table.  For segments that are split (see below) we
672    generate the names segment<NUM>a and segment<NUM>b.
673
674    Note that some program segments may have a file size that is different than
675    (less than) the memory size.  All this means is that at execution the
676    system must allocate the amount of memory specified by the memory size,
677    but only initialize it with the first "file size" bytes read from the
678    file.  This would occur for example, with program segments consisting
679    of combined data+bss.
680
681    To handle the above situation, this routine generates TWO bfd sections
682    for the single program segment.  The first has the length specified by
683    the file size of the segment, and the second has the length specified
684    by the difference between the two sizes.  In effect, the segment is split
685    into it's initialized and uninitialized parts.
686
687  */
688
689 static boolean
690 bfd_section_from_phdr (abfd, hdr, index)
691      bfd *abfd;
692      Elf_Internal_Phdr *hdr;
693      int index;
694 {
695   asection *newsect;
696   char *name;
697   char namebuf[64];
698   int split;
699
700   split = ((hdr->p_memsz > 0) &&
701            (hdr->p_filesz > 0) &&
702            (hdr->p_memsz > hdr->p_filesz));
703   sprintf (namebuf, split ? "segment%da" : "segment%d", index);
704   name = bfd_alloc (abfd, strlen (namebuf) + 1);
705   if (!name)
706     {
707       bfd_set_error (bfd_error_no_memory);
708       return false;
709     }
710   strcpy (name, namebuf);
711   newsect = bfd_make_section (abfd, name);
712   if (newsect == NULL)
713     return false;
714   newsect->vma = hdr->p_vaddr;
715   newsect->_raw_size = hdr->p_filesz;
716   newsect->filepos = hdr->p_offset;
717   newsect->flags |= SEC_HAS_CONTENTS;
718   if (hdr->p_type == PT_LOAD)
719     {
720       newsect->flags |= SEC_ALLOC;
721       newsect->flags |= SEC_LOAD;
722       if (hdr->p_flags & PF_X)
723         {
724           /* FIXME: all we known is that it has execute PERMISSION,
725              may be data. */
726           newsect->flags |= SEC_CODE;
727         }
728     }
729   if (!(hdr->p_flags & PF_W))
730     {
731       newsect->flags |= SEC_READONLY;
732     }
733
734   if (split)
735     {
736       sprintf (namebuf, "segment%db", index);
737       name = bfd_alloc (abfd, strlen (namebuf) + 1);
738       if (!name)
739         {
740           bfd_set_error (bfd_error_no_memory);
741           return false;
742         }
743       strcpy (name, namebuf);
744       newsect = bfd_make_section (abfd, name);
745       if (newsect == NULL)
746         return false;
747       newsect->vma = hdr->p_vaddr + hdr->p_filesz;
748       newsect->_raw_size = hdr->p_memsz - hdr->p_filesz;
749       if (hdr->p_type == PT_LOAD)
750         {
751           newsect->flags |= SEC_ALLOC;
752           if (hdr->p_flags & PF_X)
753             newsect->flags |= SEC_CODE;
754         }
755       if (!(hdr->p_flags & PF_W))
756         newsect->flags |= SEC_READONLY;
757     }
758
759   return true;
760 }
761
762 /* Begin processing a given object.
763
764    First we validate the file by reading in the ELF header and checking
765    the magic number.  */
766
767 static INLINE boolean
768 elf_file_p (x_ehdrp)
769      Elf_External_Ehdr *x_ehdrp;
770 {
771   return ((x_ehdrp->e_ident[EI_MAG0] == ELFMAG0)
772           && (x_ehdrp->e_ident[EI_MAG1] == ELFMAG1)
773           && (x_ehdrp->e_ident[EI_MAG2] == ELFMAG2)
774           && (x_ehdrp->e_ident[EI_MAG3] == ELFMAG3));
775 }
776
777 /* Check to see if the file associated with ABFD matches the target vector
778    that ABFD points to.
779
780    Note that we may be called several times with the same ABFD, but different
781    target vectors, most of which will not match.  We have to avoid leaving
782    any side effects in ABFD, or any data it points to (like tdata), if the
783    file does not match the target vector.  */
784
785 const bfd_target *
786 elf_object_p (abfd)
787      bfd *abfd;
788 {
789   Elf_External_Ehdr x_ehdr;     /* Elf file header, external form */
790   Elf_Internal_Ehdr *i_ehdrp;   /* Elf file header, internal form */
791   Elf_External_Shdr x_shdr;     /* Section header table entry, external form */
792   Elf_Internal_Shdr *i_shdrp = NULL; /* Section header table, internal form */
793   unsigned int shindex;
794   char *shstrtab;               /* Internal copy of section header stringtab */
795   struct elf_backend_data *ebd;
796   struct elf_obj_tdata *preserved_tdata = elf_tdata (abfd);
797   struct elf_obj_tdata *new_tdata = NULL;
798
799   /* Read in the ELF header in external format.  */
800
801   if (bfd_read ((PTR) & x_ehdr, sizeof (x_ehdr), 1, abfd) != sizeof (x_ehdr))
802     {
803       if (bfd_get_error () != bfd_error_system_call)
804         goto got_wrong_format_error;
805       else
806         goto got_no_match;
807     }
808
809   /* Now check to see if we have a valid ELF file, and one that BFD can
810      make use of.  The magic number must match, the address size ('class')
811      and byte-swapping must match our XVEC entry, and it must have a
812      section header table (FIXME: See comments re sections at top of this
813      file). */
814
815   if ((elf_file_p (&x_ehdr) == false) ||
816       (x_ehdr.e_ident[EI_VERSION] != EV_CURRENT) ||
817       (x_ehdr.e_ident[EI_CLASS] != ELFCLASS))
818     goto got_wrong_format_error;
819
820   /* Check that file's byte order matches xvec's */
821   switch (x_ehdr.e_ident[EI_DATA])
822     {
823     case ELFDATA2MSB:           /* Big-endian */
824       if (!abfd->xvec->header_byteorder_big_p)
825         goto got_wrong_format_error;
826       break;
827     case ELFDATA2LSB:           /* Little-endian */
828       if (abfd->xvec->header_byteorder_big_p)
829         goto got_wrong_format_error;
830       break;
831     case ELFDATANONE:           /* No data encoding specified */
832     default:                    /* Unknown data encoding specified */
833       goto got_wrong_format_error;
834     }
835
836   /* Allocate an instance of the elf_obj_tdata structure and hook it up to
837      the tdata pointer in the bfd.  */
838
839   new_tdata = ((struct elf_obj_tdata *)
840                bfd_zalloc (abfd, sizeof (struct elf_obj_tdata)));
841   if (new_tdata == NULL)
842     goto got_no_memory_error;
843   elf_tdata (abfd) = new_tdata;
844
845   /* Now that we know the byte order, swap in the rest of the header */
846   i_ehdrp = elf_elfheader (abfd);
847   elf_swap_ehdr_in (abfd, &x_ehdr, i_ehdrp);
848 #if DEBUG & 1
849   elf_debug_file (i_ehdrp);
850 #endif
851
852   /* If there is no section header table, we're hosed. */
853   if (i_ehdrp->e_shoff == 0)
854     goto got_wrong_format_error;
855
856   /* As a simple sanity check, verify that the what BFD thinks is the
857      size of each section header table entry actually matches the size
858      recorded in the file. */
859   if (i_ehdrp->e_shentsize != sizeof (x_shdr))
860     goto got_wrong_format_error;
861
862   ebd = get_elf_backend_data (abfd);
863
864   /* Check that the ELF e_machine field matches what this particular
865      BFD format expects.  */
866   if (ebd->elf_machine_code != i_ehdrp->e_machine)
867     {
868       const bfd_target * const *target_ptr;
869
870       if (ebd->elf_machine_code != EM_NONE)
871         goto got_wrong_format_error;
872
873       /* This is the generic ELF target.  Let it match any ELF target
874          for which we do not have a specific backend.  */
875       for (target_ptr = bfd_target_vector; *target_ptr != NULL; target_ptr++)
876         {
877           struct elf_backend_data *back;
878
879           if ((*target_ptr)->flavour != bfd_target_elf_flavour)
880             continue;
881           back = (struct elf_backend_data *) (*target_ptr)->backend_data;
882           if (back->elf_machine_code == i_ehdrp->e_machine)
883             {
884               /* target_ptr is an ELF backend which matches this
885                  object file, so reject the generic ELF target.  */
886               goto got_wrong_format_error;
887             }
888         }
889     }
890
891   if (i_ehdrp->e_type == ET_EXEC)
892     abfd->flags |= EXEC_P;
893   else if (i_ehdrp->e_type == ET_DYN)
894     abfd->flags |= DYNAMIC;
895
896   if (i_ehdrp->e_phnum > 0)
897     abfd->flags |= D_PAGED;
898
899   if (! bfd_default_set_arch_mach (abfd, ebd->arch, 0))
900     goto got_no_match;
901
902   /* Remember the entry point specified in the ELF file header. */
903   bfd_get_start_address (abfd) = i_ehdrp->e_entry;
904
905   /* Allocate space for a copy of the section header table in
906      internal form, seek to the section header table in the file,
907      read it in, and convert it to internal form.  */
908   i_shdrp = ((Elf_Internal_Shdr *)
909              bfd_alloc (abfd, sizeof (*i_shdrp) * i_ehdrp->e_shnum));
910   elf_elfsections (abfd) = ((Elf_Internal_Shdr **)
911                             bfd_alloc (abfd,
912                                        sizeof (i_shdrp) * i_ehdrp->e_shnum));
913   if (!i_shdrp || !elf_elfsections (abfd))
914     goto got_no_memory_error;
915   if (bfd_seek (abfd, i_ehdrp->e_shoff, SEEK_SET) != 0)
916     goto got_no_match;
917   for (shindex = 0; shindex < i_ehdrp->e_shnum; shindex++)
918     {
919       if (bfd_read ((PTR) & x_shdr, sizeof x_shdr, 1, abfd) != sizeof (x_shdr))
920         goto got_no_match;
921       elf_swap_shdr_in (abfd, &x_shdr, i_shdrp + shindex);
922       elf_elfsections (abfd)[shindex] = i_shdrp + shindex;
923     }
924   if (i_ehdrp->e_shstrndx)
925     {
926       if (! bfd_section_from_shdr (abfd, i_ehdrp->e_shstrndx))
927         goto got_no_match;
928     }
929
930   /* Read in the string table containing the names of the sections.  We
931      will need the base pointer to this table later. */
932   /* We read this inline now, so that we don't have to go through
933      bfd_section_from_shdr with it (since this particular strtab is
934      used to find all of the ELF section names.) */
935
936   shstrtab = elf_get_str_section (abfd, i_ehdrp->e_shstrndx);
937   if (!shstrtab)
938     goto got_no_match;
939
940   /* Once all of the section headers have been read and converted, we
941      can start processing them.  Note that the first section header is
942      a dummy placeholder entry, so we ignore it.  */
943
944   for (shindex = 1; shindex < i_ehdrp->e_shnum; shindex++)
945     {
946       if (! bfd_section_from_shdr (abfd, shindex))
947         goto got_no_match;
948     }
949
950   /* Let the backend double check the format and override global
951      information.  */
952   if (ebd->elf_backend_object_p)
953     {
954       if ((*ebd->elf_backend_object_p) (abfd) == false)
955         goto got_wrong_format_error;
956     }
957
958   return (abfd->xvec);
959
960 got_wrong_format_error:
961   bfd_set_error (bfd_error_wrong_format);
962   goto got_no_match;
963 got_no_memory_error:
964   bfd_set_error (bfd_error_no_memory);
965   goto got_no_match;
966 got_no_match:
967   if (new_tdata != NULL
968       && new_tdata->elf_sect_ptr != NULL)
969     bfd_release (abfd, new_tdata->elf_sect_ptr);
970   if (i_shdrp != NULL)
971     bfd_release (abfd, i_shdrp);
972   if (new_tdata != NULL)
973     bfd_release (abfd, new_tdata);
974   elf_tdata (abfd) = preserved_tdata;
975   return (NULL);
976 }
977 \f
978
979 /* ELF .o/exec file writing */
980
981 /* Takes a bfd and a symbol, returns a pointer to the elf specific area
982    of the symbol if there is one.  */
983 static INLINE elf_symbol_type *
984 elf_symbol_from (ignore_abfd, symbol)
985      bfd *ignore_abfd;
986      asymbol *symbol;
987 {
988   if (symbol->the_bfd->xvec->flavour != bfd_target_elf_flavour)
989     return 0;
990
991   if (symbol->the_bfd->tdata.elf_obj_data == (struct elf_obj_tdata *) NULL)
992     return 0;
993
994   return (elf_symbol_type *) symbol;
995 }
996
997 void
998 write_relocs (abfd, sec, xxx)
999      bfd *abfd;
1000      asection *sec;
1001      PTR xxx;
1002 {
1003   Elf_Internal_Shdr *rela_hdr;
1004   Elf_External_Rela *outbound_relocas;
1005   Elf_External_Rel *outbound_relocs;
1006   int idx;
1007   int use_rela_p = get_elf_backend_data (abfd)->use_rela_p;
1008   asymbol *last_sym = 0;
1009   int last_sym_idx = 9999999;   /* should always be written before use */
1010
1011   if ((sec->flags & SEC_RELOC) == 0)
1012     return;
1013
1014   /* The linker backend writes the relocs out itself, and sets the
1015      reloc_count field to zero to inhibit writing them here.  Also,
1016      sometimes the SEC_RELOC flag gets set even when there aren't any
1017      relocs.  */
1018   if (sec->reloc_count == 0)
1019     return;
1020
1021   rela_hdr = &elf_section_data (sec)->rel_hdr;
1022
1023   rela_hdr->sh_size = rela_hdr->sh_entsize * sec->reloc_count;
1024   rela_hdr->contents = (void *) bfd_alloc (abfd, rela_hdr->sh_size);
1025   if (!rela_hdr->contents)
1026     {
1027       bfd_set_error (bfd_error_no_memory);
1028       abort ();                 /* FIXME */
1029     }
1030
1031   /* orelocation has the data, reloc_count has the count... */
1032   if (use_rela_p)
1033     {
1034       outbound_relocas = (Elf_External_Rela *) rela_hdr->contents;
1035
1036       for (idx = 0; idx < sec->reloc_count; idx++)
1037         {
1038           Elf_Internal_Rela dst_rela;
1039           Elf_External_Rela *src_rela;
1040           arelent *ptr;
1041           asymbol *sym;
1042           int n;
1043
1044           ptr = sec->orelocation[idx];
1045           src_rela = outbound_relocas + idx;
1046
1047           /* The address of an ELF reloc is section relative for an object
1048              file, and absolute for an executable file or shared library.
1049              The address of a BFD reloc is always section relative.  */
1050           if ((abfd->flags & (EXEC_P | DYNAMIC)) == 0)
1051             dst_rela.r_offset = ptr->address;
1052           else
1053             dst_rela.r_offset = ptr->address + sec->vma;
1054
1055           sym = *ptr->sym_ptr_ptr;
1056           if (sym == last_sym)
1057             n = last_sym_idx;
1058           else
1059             {
1060               last_sym = sym;
1061               last_sym_idx = n = elf_symbol_from_bfd_symbol (abfd, &sym);
1062             }
1063           dst_rela.r_info = ELF_R_INFO (n, ptr->howto->type);
1064
1065           dst_rela.r_addend = ptr->addend;
1066           elf_swap_reloca_out (abfd, &dst_rela, src_rela);
1067         }
1068     }
1069   else
1070     /* REL relocations */
1071     {
1072       outbound_relocs = (Elf_External_Rel *) rela_hdr->contents;
1073
1074       for (idx = 0; idx < sec->reloc_count; idx++)
1075         {
1076           Elf_Internal_Rel dst_rel;
1077           Elf_External_Rel *src_rel;
1078           arelent *ptr;
1079           int n;
1080           asymbol *sym;
1081
1082           ptr = sec->orelocation[idx];
1083           sym = *ptr->sym_ptr_ptr;
1084           src_rel = outbound_relocs + idx;
1085
1086           /* The address of an ELF reloc is section relative for an object
1087              file, and absolute for an executable file or shared library.
1088              The address of a BFD reloc is always section relative.  */
1089           if ((abfd->flags & (EXEC_P | DYNAMIC)) == 0)
1090             dst_rel.r_offset = ptr->address;
1091           else
1092             dst_rel.r_offset = ptr->address + sec->vma;
1093
1094           if (sym == last_sym)
1095             n = last_sym_idx;
1096           else
1097             {
1098               last_sym = sym;
1099               last_sym_idx = n = elf_symbol_from_bfd_symbol (abfd, &sym);
1100             }
1101           dst_rel.r_info = ELF_R_INFO (n, ptr->howto->type);
1102
1103           elf_swap_reloc_out (abfd, &dst_rel, src_rel);
1104         }
1105     }
1106 }
1107
1108 /* Set up an ELF internal section header for a section.  */
1109
1110 /*ARGSUSED*/
1111 static void
1112 elf_fake_sections (abfd, asect, failedptrarg)
1113      bfd *abfd;
1114      asection *asect;
1115      PTR failedptrarg;
1116 {
1117   boolean *failedptr = (boolean *) failedptrarg;
1118   Elf_Internal_Shdr *this_hdr;
1119
1120   if (*failedptr)
1121     {
1122       /* We already failed; just get out of the bfd_map_over_sections
1123          loop.  */
1124       return;
1125     }
1126
1127   this_hdr = &elf_section_data (asect)->this_hdr;
1128
1129   this_hdr->sh_name = (unsigned long) _bfd_stringtab_add (elf_shstrtab (abfd),
1130                                                           asect->name,
1131                                                           true, false);
1132   if (this_hdr->sh_name == (unsigned long) -1)
1133     {
1134       *failedptr = true;
1135       return;
1136     }
1137
1138   this_hdr->sh_flags = 0;
1139   if ((asect->flags & SEC_ALLOC) != 0)
1140     this_hdr->sh_addr = asect->vma;
1141   else
1142     this_hdr->sh_addr = 0;
1143   this_hdr->sh_offset = 0;
1144   this_hdr->sh_size = asect->_raw_size;
1145   this_hdr->sh_link = 0;
1146   this_hdr->sh_info = 0;
1147   this_hdr->sh_addralign = 1 << asect->alignment_power;
1148   this_hdr->sh_entsize = 0;
1149
1150   this_hdr->bfd_section = asect;
1151   this_hdr->contents = NULL;
1152
1153   /* FIXME: This should not be based on section names.  */
1154   if (strcmp (asect->name, ".dynstr") == 0)
1155     this_hdr->sh_type = SHT_STRTAB;
1156   else if (strcmp (asect->name, ".hash") == 0)
1157     {
1158       this_hdr->sh_type = SHT_HASH;
1159       this_hdr->sh_entsize = ARCH_SIZE / 8;
1160     }
1161   else if (strcmp (asect->name, ".dynsym") == 0)
1162     {
1163       this_hdr->sh_type = SHT_DYNSYM;
1164       this_hdr->sh_entsize = sizeof (Elf_External_Sym);
1165     }
1166   else if (strcmp (asect->name, ".dynamic") == 0)
1167     {
1168       this_hdr->sh_type = SHT_DYNAMIC;
1169       this_hdr->sh_entsize = sizeof (Elf_External_Dyn);
1170     }
1171   else if (strncmp (asect->name, ".rela", 5) == 0
1172            && get_elf_backend_data (abfd)->use_rela_p)
1173     {
1174       this_hdr->sh_type = SHT_RELA;
1175       this_hdr->sh_entsize = sizeof (Elf_External_Rela);
1176     }
1177   else if (strncmp (asect->name, ".rel", 4) == 0
1178            && ! get_elf_backend_data (abfd)->use_rela_p)
1179     {
1180       this_hdr->sh_type = SHT_REL;
1181       this_hdr->sh_entsize = sizeof (Elf_External_Rel);
1182     }
1183   else if (strcmp (asect->name, ".note") == 0)
1184     this_hdr->sh_type = SHT_NOTE;
1185   else if (strncmp (asect->name, ".stab", 5) == 0
1186            && strcmp (asect->name + strlen (asect->name) - 3, "str") == 0)
1187     this_hdr->sh_type = SHT_STRTAB;
1188   else if ((asect->flags & SEC_ALLOC) != 0
1189            && (asect->flags & SEC_LOAD) != 0)
1190     this_hdr->sh_type = SHT_PROGBITS;
1191   else if ((asect->flags & SEC_ALLOC) != 0
1192            && ((asect->flags & SEC_LOAD) == 0))
1193     {
1194       BFD_ASSERT (strcmp (asect->name, ".bss") == 0
1195                   || strcmp (asect->name, ".sbss") == 0);
1196       this_hdr->sh_type = SHT_NOBITS;
1197     }
1198   else
1199     {
1200       /* Who knows?  */
1201       this_hdr->sh_type = SHT_PROGBITS;
1202     }
1203
1204   if ((asect->flags & SEC_ALLOC) != 0)
1205     this_hdr->sh_flags |= SHF_ALLOC;
1206   if ((asect->flags & SEC_READONLY) == 0)
1207     this_hdr->sh_flags |= SHF_WRITE;
1208   if ((asect->flags & SEC_CODE) != 0)
1209     this_hdr->sh_flags |= SHF_EXECINSTR;
1210
1211   /* Check for processor-specific section types.  */
1212   {
1213     struct elf_backend_data *bed = get_elf_backend_data (abfd);
1214
1215     if (bed->elf_backend_fake_sections)
1216       (*bed->elf_backend_fake_sections) (abfd, this_hdr, asect);
1217   }
1218
1219   /* If the section has relocs, set up a section header for the
1220      SHT_REL[A] section.  */
1221   if ((asect->flags & SEC_RELOC) != 0)
1222     {
1223       Elf_Internal_Shdr *rela_hdr;
1224       int use_rela_p = get_elf_backend_data (abfd)->use_rela_p;
1225       char *name;
1226
1227       rela_hdr = &elf_section_data (asect)->rel_hdr;
1228       name = bfd_alloc (abfd, sizeof ".rela" + strlen (asect->name));
1229       if (name == NULL)
1230         {
1231           bfd_set_error (bfd_error_no_memory);
1232           *failedptr = true;
1233           return;
1234         }
1235       sprintf (name, "%s%s", use_rela_p ? ".rela" : ".rel", asect->name);
1236       rela_hdr->sh_name =
1237         (unsigned int) _bfd_stringtab_add (elf_shstrtab (abfd), name,
1238                                            true, false);
1239       if (rela_hdr->sh_name == (unsigned int) -1)
1240         {
1241           *failedptr = true;
1242           return;
1243         }
1244       rela_hdr->sh_type = use_rela_p ? SHT_RELA : SHT_REL;
1245       rela_hdr->sh_entsize = (use_rela_p
1246                               ? sizeof (Elf_External_Rela)
1247                               : sizeof (Elf_External_Rel));
1248       rela_hdr->sh_addralign = FILE_ALIGN;
1249       rela_hdr->sh_flags = 0;
1250       rela_hdr->sh_addr = 0;
1251       rela_hdr->sh_size = 0;
1252       rela_hdr->sh_offset = 0;
1253     }
1254 }
1255
1256 /* Assign all ELF section numbers.  The dummy first section is handled here
1257    too.  The link/info pointers for the standard section types are filled
1258    in here too, while we're at it.  */
1259
1260 static boolean
1261 assign_section_numbers (abfd)
1262      bfd *abfd;
1263 {
1264   struct elf_obj_tdata *t = elf_tdata (abfd);
1265   asection *sec;
1266   unsigned int section_number;
1267   Elf_Internal_Shdr **i_shdrp;
1268
1269   section_number = 1;
1270
1271   for (sec = abfd->sections; sec; sec = sec->next)
1272     {
1273       struct bfd_elf_section_data *d = elf_section_data (sec);
1274
1275       d->this_idx = section_number++;
1276       if ((sec->flags & SEC_RELOC) == 0)
1277         d->rel_idx = 0;
1278       else
1279         d->rel_idx = section_number++;
1280     }
1281
1282   t->shstrtab_section = section_number++;
1283   elf_elfheader (abfd)->e_shstrndx = t->shstrtab_section;
1284   t->shstrtab_hdr.sh_size = _bfd_stringtab_size (elf_shstrtab (abfd));
1285
1286   if (abfd->symcount > 0)
1287     {
1288       t->symtab_section = section_number++;
1289       t->strtab_section = section_number++;
1290     }
1291
1292   elf_elfheader (abfd)->e_shnum = section_number;
1293
1294   /* Set up the list of section header pointers, in agreement with the
1295      indices.  */
1296   i_shdrp = ((Elf_Internal_Shdr **)
1297              bfd_alloc (abfd, section_number * sizeof (Elf_Internal_Shdr *)));
1298   if (i_shdrp == NULL)
1299     {
1300       bfd_set_error (bfd_error_no_memory);
1301       return false;
1302     }
1303
1304   i_shdrp[0] = ((Elf_Internal_Shdr *)
1305                 bfd_alloc (abfd, sizeof (Elf_Internal_Shdr)));
1306   if (i_shdrp[0] == NULL)
1307     {
1308       bfd_release (abfd, i_shdrp);
1309       bfd_set_error (bfd_error_no_memory);
1310       return false;
1311     }
1312   memset (i_shdrp[0], 0, sizeof (Elf_Internal_Shdr));
1313
1314   elf_elfsections (abfd) = i_shdrp;
1315
1316   i_shdrp[t->shstrtab_section] = &t->shstrtab_hdr;
1317   if (abfd->symcount > 0)
1318     {
1319       i_shdrp[t->symtab_section] = &t->symtab_hdr;
1320       i_shdrp[t->strtab_section] = &t->strtab_hdr;
1321       t->symtab_hdr.sh_link = t->strtab_section;
1322     }
1323   for (sec = abfd->sections; sec; sec = sec->next)
1324     {
1325       struct bfd_elf_section_data *d = elf_section_data (sec);
1326       asection *s;
1327       const char *name;
1328
1329       i_shdrp[d->this_idx] = &d->this_hdr;
1330       if (d->rel_idx != 0)
1331         i_shdrp[d->rel_idx] = &d->rel_hdr;
1332
1333       /* Fill in the sh_link and sh_info fields while we're at it.  */
1334
1335       /* sh_link of a reloc section is the section index of the symbol
1336          table.  sh_info is the section index of the section to which
1337          the relocation entries apply.  */
1338       if (d->rel_idx != 0)
1339         {
1340           d->rel_hdr.sh_link = t->symtab_section;
1341           d->rel_hdr.sh_info = d->this_idx;
1342         }
1343
1344       switch (d->this_hdr.sh_type)
1345         {
1346         case SHT_REL:
1347         case SHT_RELA:
1348           /* A reloc section which we are treating as a normal BFD
1349              section.  sh_link is the section index of the symbol
1350              table.  sh_info is the section index of the section to
1351              which the relocation entries apply.  We assume that an
1352              allocated reloc section uses the dynamic symbol table.
1353              FIXME: How can we be sure?  */
1354           s = bfd_get_section_by_name (abfd, ".dynsym");
1355           if (s != NULL)
1356             d->this_hdr.sh_link = elf_section_data (s)->this_idx;
1357
1358           /* We look up the section the relocs apply to by name.  */
1359           name = sec->name;
1360           if (d->this_hdr.sh_type == SHT_REL)
1361             name += 4;
1362           else
1363             name += 5;
1364           s = bfd_get_section_by_name (abfd, name);
1365           if (s != NULL)
1366             d->this_hdr.sh_info = elf_section_data (s)->this_idx;
1367           break;
1368
1369         case SHT_STRTAB:
1370           /* We assume that a section named .stab*str is a stabs
1371              string section.  We look for a section with the same name
1372              but without the trailing ``str'', and set its sh_link
1373              field to point to this section.  */
1374           if (strncmp (sec->name, ".stab", sizeof ".stab" - 1) == 0
1375               && strcmp (sec->name + strlen (sec->name) - 3, "str") == 0)
1376             {
1377               size_t len;
1378               char *alc;
1379
1380               len = strlen (sec->name);
1381               alc = (char *) malloc (len - 2);
1382               if (alc == NULL)
1383                 {
1384                   bfd_set_error (bfd_error_no_memory);
1385                   return false;
1386                 }
1387               strncpy (alc, sec->name, len - 3);
1388               alc[len - 3] = '\0';
1389               s = bfd_get_section_by_name (abfd, alc);
1390               free (alc);
1391               if (s != NULL)
1392                 {
1393                   elf_section_data (s)->this_hdr.sh_link = d->this_idx;
1394
1395                   /* This is a .stab section.  */
1396                   elf_section_data (s)->this_hdr.sh_entsize =
1397                     4 + 2 * (ARCH_SIZE / 8);
1398                 }
1399             }
1400           break;
1401
1402         case SHT_DYNAMIC:
1403         case SHT_DYNSYM:
1404           /* sh_link is the section header index of the string table
1405              used for the dynamic entries or symbol table.  */
1406           s = bfd_get_section_by_name (abfd, ".dynstr");
1407           if (s != NULL)
1408             d->this_hdr.sh_link = elf_section_data (s)->this_idx;
1409           break;
1410
1411         case SHT_HASH:
1412           /* sh_link is the section header index of the symbol table
1413              this hash table is for.  */
1414           s = bfd_get_section_by_name (abfd, ".dynsym");
1415           if (s != NULL)
1416             d->this_hdr.sh_link = elf_section_data (s)->this_idx;
1417           break;
1418         }
1419     }
1420
1421   return true;
1422 }
1423
1424 /* Map symbol from it's internal number to the external number, moving
1425    all local symbols to be at the head of the list.  */
1426
1427 static INLINE int
1428 sym_is_global (abfd, sym)
1429      bfd *abfd;
1430      asymbol *sym;
1431 {
1432   /* If the backend has a special mapping, use it.  */
1433   if (get_elf_backend_data (abfd)->elf_backend_sym_is_global)
1434     return ((*get_elf_backend_data (abfd)->elf_backend_sym_is_global)
1435             (abfd, sym));
1436
1437   if (sym->flags & (BSF_GLOBAL | BSF_WEAK))
1438     {
1439       if (sym->flags & BSF_LOCAL)
1440         abort ();
1441       return 1;
1442     }
1443   if (sym->section == 0)
1444     {
1445       /* Is this valid?  */
1446       abort ();
1447
1448       return 1;
1449     }
1450   if (bfd_is_und_section (sym->section))
1451     return 1;
1452   if (bfd_is_com_section (sym->section))
1453     return 1;
1454   if (sym->flags & (BSF_LOCAL | BSF_SECTION_SYM | BSF_FILE))
1455     return 0;
1456   return 0;
1457 }
1458
1459 static boolean
1460 elf_map_symbols (abfd)
1461      bfd *abfd;
1462 {
1463   int symcount = bfd_get_symcount (abfd);
1464   asymbol **syms = bfd_get_outsymbols (abfd);
1465   asymbol **sect_syms;
1466   int num_locals = 0;
1467   int num_globals = 0;
1468   int num_locals2 = 0;
1469   int num_globals2 = 0;
1470   int max_index = 0;
1471   int num_sections = 0;
1472   int idx;
1473   asection *asect;
1474   asymbol **new_syms;
1475
1476 #ifdef DEBUG
1477   fprintf (stderr, "elf_map_symbols\n");
1478   fflush (stderr);
1479 #endif
1480
1481   /* Add a section symbol for each BFD section.  FIXME: Is this really
1482      necessary?  */
1483   for (asect = abfd->sections; asect; asect = asect->next)
1484     {
1485       if (max_index < asect->index)
1486         max_index = asect->index;
1487     }
1488
1489   max_index++;
1490   sect_syms = (asymbol **) bfd_zalloc (abfd, max_index * sizeof (asymbol *));
1491   if (sect_syms == NULL)
1492     {
1493       bfd_set_error (bfd_error_no_memory);
1494       return false;
1495     }
1496   elf_section_syms (abfd) = sect_syms;
1497
1498   for (idx = 0; idx < symcount; idx++)
1499     {
1500       if ((syms[idx]->flags & BSF_SECTION_SYM) != 0
1501           && syms[idx]->value == 0)
1502         {
1503           asection *sec;
1504
1505           sec = syms[idx]->section;
1506           if (sec->owner != NULL)
1507             {
1508               if (sec->owner != abfd)
1509                 {
1510                   if (sec->output_offset != 0)
1511                     continue;
1512                   sec = sec->output_section;
1513                   BFD_ASSERT (sec->owner == abfd);
1514                 }
1515               sect_syms[sec->index] = syms[idx];
1516             }
1517         }
1518     }
1519
1520   for (asect = abfd->sections; asect; asect = asect->next)
1521     {
1522       asymbol *sym;
1523
1524       if (sect_syms[asect->index] != NULL)
1525         continue;
1526
1527       sym = bfd_make_empty_symbol (abfd);
1528       if (sym == NULL)
1529         return false;
1530       sym->the_bfd = abfd;
1531       sym->name = asect->name;
1532       sym->value = 0;
1533       /* Set the flags to 0 to indicate that this one was newly added.  */
1534       sym->flags = 0;
1535       sym->section = asect;
1536       sect_syms[asect->index] = sym;
1537       num_sections++;
1538 #ifdef DEBUG
1539       fprintf (stderr,
1540                "creating section symbol, name = %s, value = 0x%.8lx, index = %d, section = 0x%.8lx\n",
1541                asect->name, (long) asect->vma, asect->index, (long) asect);
1542 #endif
1543     }
1544
1545   /* Classify all of the symbols.  */
1546   for (idx = 0; idx < symcount; idx++)
1547     {
1548       if (!sym_is_global (abfd, syms[idx]))
1549         num_locals++;
1550       else
1551         num_globals++;
1552     }
1553   for (asect = abfd->sections; asect; asect = asect->next)
1554     {
1555       if (sect_syms[asect->index] != NULL
1556           && sect_syms[asect->index]->flags == 0)
1557         {
1558           sect_syms[asect->index]->flags = BSF_SECTION_SYM;
1559           if (!sym_is_global (abfd, sect_syms[asect->index]))
1560             num_locals++;
1561           else
1562             num_globals++;
1563           sect_syms[asect->index]->flags = 0;
1564         }
1565     }
1566
1567   /* Now sort the symbols so the local symbols are first.  */
1568   new_syms = ((asymbol **)
1569               bfd_alloc (abfd,
1570                          (num_locals + num_globals) * sizeof (asymbol *)));
1571   if (new_syms == NULL)
1572     {
1573       bfd_set_error (bfd_error_no_memory);
1574       return false;
1575     }
1576
1577   for (idx = 0; idx < symcount; idx++)
1578     {
1579       asymbol *sym = syms[idx];
1580       int i;
1581
1582       if (!sym_is_global (abfd, sym))
1583         i = num_locals2++;
1584       else
1585         i = num_locals + num_globals2++;
1586       new_syms[i] = sym;
1587       sym->udata.i = i + 1;
1588     }
1589   for (asect = abfd->sections; asect; asect = asect->next)
1590     {
1591       if (sect_syms[asect->index] != NULL
1592           && sect_syms[asect->index]->flags == 0)
1593         {
1594           asymbol *sym = sect_syms[asect->index];
1595           int i;
1596
1597           sym->flags = BSF_SECTION_SYM;
1598           if (!sym_is_global (abfd, sym))
1599             i = num_locals2++;
1600           else
1601             i = num_locals + num_globals2++;
1602           new_syms[i] = sym;
1603           sym->udata.i = i + 1;
1604         }
1605     }
1606
1607   bfd_set_symtab (abfd, new_syms, num_locals + num_globals);
1608
1609   elf_num_locals (abfd) = num_locals;
1610   elf_num_globals (abfd) = num_globals;
1611   return true;
1612 }
1613
1614 /* Compute the file positions we are going to put the sections at, and
1615    otherwise prepare to begin writing out the ELF file.  If LINK_INFO
1616    is not NULL, this is being called by the ELF backend linker.  */
1617
1618 static boolean
1619 elf_compute_section_file_positions (abfd, link_info)
1620      bfd *abfd;
1621      struct bfd_link_info *link_info;
1622 {
1623   struct elf_backend_data *bed = get_elf_backend_data (abfd);
1624   boolean failed;
1625   struct bfd_strtab_hash *strtab;
1626   Elf_Internal_Shdr *shstrtab_hdr;
1627
1628   if (abfd->output_has_begun)
1629     return true;
1630
1631   /* Do any elf backend specific processing first.  */
1632   if (bed->elf_backend_begin_write_processing)
1633     (*bed->elf_backend_begin_write_processing) (abfd, link_info);
1634
1635   if (! prep_headers (abfd))
1636     return false;
1637
1638   failed = false;
1639   bfd_map_over_sections (abfd, elf_fake_sections, &failed);
1640   if (failed)
1641     return false;
1642
1643   if (!assign_section_numbers (abfd))
1644     return false;
1645
1646   /* The backend linker builds symbol table information itself.  */
1647   if (link_info == NULL)
1648     {
1649       if (! swap_out_syms (abfd, &strtab))
1650         return false;
1651     }
1652
1653   shstrtab_hdr = &elf_tdata (abfd)->shstrtab_hdr;
1654   /* sh_name was set in prep_headers.  */
1655   shstrtab_hdr->sh_type = SHT_STRTAB;
1656   shstrtab_hdr->sh_flags = 0;
1657   shstrtab_hdr->sh_addr = 0;
1658   shstrtab_hdr->sh_size = _bfd_stringtab_size (elf_shstrtab (abfd));
1659   shstrtab_hdr->sh_entsize = 0;
1660   shstrtab_hdr->sh_link = 0;
1661   shstrtab_hdr->sh_info = 0;
1662   /* sh_offset is set in assign_file_positions_for_symtabs_and_strtabs.  */
1663   shstrtab_hdr->sh_addralign = 1;
1664
1665   if (!assign_file_positions_except_relocs (abfd,
1666                                             link_info == NULL ? true : false))
1667     return false;
1668
1669   if (link_info == NULL)
1670     {
1671       /* Now that we know where the .strtab section goes, write it
1672          out.  */
1673       if ((bfd_seek (abfd, elf_tdata (abfd)->strtab_hdr.sh_offset, SEEK_SET)
1674            != 0)
1675           || ! _bfd_stringtab_emit (abfd, strtab))
1676         return false;
1677       _bfd_stringtab_free (strtab);
1678     }
1679
1680   abfd->output_has_begun = true;
1681
1682   return true;
1683 }
1684
1685
1686 /* Align to the maximum file alignment that could be required for any
1687    ELF data structure.  */
1688
1689 static INLINE file_ptr
1690 align_file_position (off)
1691      file_ptr off;
1692 {
1693   return (off + FILE_ALIGN - 1) & ~(FILE_ALIGN - 1);
1694 }
1695
1696 /* Assign a file position to a section, optionally aligning to the
1697    required section alignment.  */
1698
1699 static INLINE file_ptr
1700 assign_file_position_for_section (i_shdrp, offset, align)
1701      Elf_Internal_Shdr *i_shdrp;
1702      file_ptr offset;
1703      boolean align;
1704 {
1705   if (align)
1706     {
1707       unsigned int al;
1708
1709       al = i_shdrp->sh_addralign;
1710       if (al > 1)
1711         offset = BFD_ALIGN (offset, al);
1712     }
1713   i_shdrp->sh_offset = offset;
1714   if (i_shdrp->bfd_section != NULL)
1715     i_shdrp->bfd_section->filepos = offset;
1716   if (i_shdrp->sh_type != SHT_NOBITS)
1717     offset += i_shdrp->sh_size;
1718   return offset;
1719 }
1720
1721 /* Get the size of the program header.  This is called by the linker
1722    before any of the section VMA's are set, so it can't calculate the
1723    correct value for a strange memory layout.  */
1724
1725 static bfd_size_type
1726 get_program_header_size (abfd)
1727      bfd *abfd;
1728 {
1729   size_t segs;
1730   asection *s;
1731
1732   /* Assume we will need exactly two PT_LOAD segments: one for text
1733      and one for data.  */
1734   segs = 2;
1735
1736   s = bfd_get_section_by_name (abfd, ".interp");
1737   if (s != NULL && (s->flags & SEC_LOAD) != 0)
1738     {
1739       /* If we have a loadable interpreter section, we need a
1740          PT_INTERP segment.  In this case, assume we also need a
1741          PT_PHDR segment, although that may not be true for all
1742          targets.  */
1743       segs += 2;
1744     }
1745
1746   if (bfd_get_section_by_name (abfd, ".dynamic") != NULL)
1747     {
1748       /* We need a PT_DYNAMIC segment.  */
1749       ++segs;
1750     }
1751
1752   return segs * sizeof (Elf_External_Phdr);
1753 }
1754
1755 /* Create the program header.  OFF is the file offset where the
1756    program header should be written.  FIRST is the first loadable ELF
1757    section.  PHDR_SIZE is the size of the program header as returned
1758    by get_program_header_size.  */
1759
1760 static file_ptr
1761 map_program_segments (abfd, off, first, phdr_size)
1762      bfd *abfd;
1763      file_ptr off;
1764      Elf_Internal_Shdr *first;
1765      bfd_size_type phdr_size;
1766 {
1767   Elf_Internal_Phdr phdrs[10];
1768   unsigned int phdr_count;
1769   Elf_Internal_Phdr *phdr;
1770   int phdr_size_adjust;
1771   unsigned int i;
1772   Elf_Internal_Shdr **hdrpp;
1773   asection *sinterp, *sdyn;
1774   unsigned int last_type;
1775   Elf_Internal_Ehdr *i_ehdrp;
1776
1777   BFD_ASSERT ((abfd->flags & (EXEC_P | DYNAMIC)) != 0);
1778   BFD_ASSERT (phdr_size / sizeof (Elf_Internal_Phdr)
1779               <= sizeof phdrs / sizeof (phdrs[0]));
1780
1781   phdr_count = 0;
1782   phdr = phdrs;
1783
1784   phdr_size_adjust = 0;
1785
1786   /* If we have a loadable .interp section, we must create a PT_INTERP
1787      segment which must precede all PT_LOAD segments.  We assume that
1788      we must also create a PT_PHDR segment, although that may not be
1789      true for all targets.  */
1790   sinterp = bfd_get_section_by_name (abfd, ".interp");
1791   if (sinterp != NULL && (sinterp->flags & SEC_LOAD) != 0)
1792     {
1793       BFD_ASSERT (first != NULL);
1794
1795       phdr->p_type = PT_PHDR;
1796
1797       phdr->p_offset = off;
1798
1799       /* Account for any adjustment made because of the alignment of
1800          the first loadable section.  */
1801       phdr_size_adjust = (first->sh_offset - phdr_size) - off;
1802       BFD_ASSERT (phdr_size_adjust >= 0 && phdr_size_adjust < 128);
1803
1804       /* The program header precedes all loadable sections.  This lets
1805          us compute its loadable address.  This depends on the linker
1806          script.  */
1807       phdr->p_vaddr = first->sh_addr - (phdr_size + phdr_size_adjust);
1808
1809       phdr->p_paddr = 0;
1810       phdr->p_filesz = phdr_size;
1811       phdr->p_memsz = phdr_size;
1812
1813       /* FIXME: UnixWare and Solaris set PF_X, Irix 5 does not.  */
1814       phdr->p_flags = PF_R | PF_X;
1815
1816       phdr->p_align = FILE_ALIGN;
1817       BFD_ASSERT ((phdr->p_vaddr - phdr->p_offset) % FILE_ALIGN == 0);
1818
1819       /* Include the ELF header in the first loadable segment.  */
1820       phdr_size_adjust += off;
1821
1822       ++phdr_count;
1823       ++phdr;
1824
1825       phdr->p_type = PT_INTERP;
1826       phdr->p_offset = sinterp->filepos;
1827       phdr->p_vaddr = sinterp->vma;
1828       phdr->p_paddr = 0;
1829       phdr->p_filesz = sinterp->_raw_size;
1830       phdr->p_memsz = sinterp->_raw_size;
1831       phdr->p_flags = PF_R;
1832       phdr->p_align = 1 << bfd_get_section_alignment (abfd, sinterp);
1833
1834       ++phdr_count;
1835       ++phdr;
1836     }
1837
1838   /* Look through the sections to see how they will be divided into
1839      program segments.  The sections must be arranged in order by
1840      sh_addr for this to work correctly.  */
1841   phdr->p_type = PT_NULL;
1842   last_type = SHT_PROGBITS;
1843   for (i = 1, hdrpp = elf_elfsections (abfd) + 1;
1844        i < elf_elfheader (abfd)->e_shnum;
1845        i++, hdrpp++)
1846     {
1847       Elf_Internal_Shdr *hdr;
1848
1849       hdr = *hdrpp;
1850
1851       /* Ignore any section which will not be part of the process
1852          image.  */
1853       if ((hdr->sh_flags & SHF_ALLOC) == 0)
1854         continue;
1855
1856       /* If this section fits in the segment we are constructing, add
1857          it in.  */
1858       if (phdr->p_type != PT_NULL
1859           && (hdr->sh_offset - (phdr->p_offset + phdr->p_memsz)
1860               == hdr->sh_addr - (phdr->p_vaddr + phdr->p_memsz))
1861           && (last_type != SHT_NOBITS || hdr->sh_type == SHT_NOBITS))
1862         {
1863           bfd_size_type adjust;
1864
1865           adjust = hdr->sh_addr - (phdr->p_vaddr + phdr->p_memsz);
1866           phdr->p_memsz += hdr->sh_size + adjust;
1867           if (hdr->sh_type != SHT_NOBITS)
1868             phdr->p_filesz += hdr->sh_size + adjust;
1869           if ((hdr->sh_flags & SHF_WRITE) != 0)
1870             phdr->p_flags |= PF_W;
1871           if ((hdr->sh_flags & SHF_EXECINSTR) != 0)
1872             phdr->p_flags |= PF_X;
1873           last_type = hdr->sh_type;
1874           continue;
1875         }
1876
1877       /* If we have a segment, move to the next one.  */
1878       if (phdr->p_type != PT_NULL)
1879         {
1880           ++phdr;
1881           ++phdr_count;
1882         }
1883
1884       /* Start a new segment.  */
1885       phdr->p_type = PT_LOAD;
1886       phdr->p_offset = hdr->sh_offset;
1887       phdr->p_vaddr = hdr->sh_addr;
1888       phdr->p_paddr = 0;
1889       if (hdr->sh_type == SHT_NOBITS)
1890         phdr->p_filesz = 0;
1891       else
1892         phdr->p_filesz = hdr->sh_size;
1893       phdr->p_memsz = hdr->sh_size;
1894       phdr->p_flags = PF_R;
1895       if ((hdr->sh_flags & SHF_WRITE) != 0)
1896         phdr->p_flags |= PF_W;
1897       if ((hdr->sh_flags & SHF_EXECINSTR) != 0)
1898         phdr->p_flags |= PF_X;
1899       phdr->p_align = get_elf_backend_data (abfd)->maxpagesize;
1900
1901       if (hdr == first
1902           && sinterp != NULL
1903           && (sinterp->flags & SEC_LOAD) != 0)
1904         {
1905           phdr->p_offset -= phdr_size + phdr_size_adjust;
1906           phdr->p_vaddr -= phdr_size + phdr_size_adjust;
1907           phdr->p_filesz += phdr_size + phdr_size_adjust;
1908           phdr->p_memsz += phdr_size + phdr_size_adjust;
1909         }
1910
1911       last_type = hdr->sh_type;
1912     }
1913
1914   if (phdr->p_type != PT_NULL)
1915     {
1916       ++phdr;
1917       ++phdr_count;
1918     }
1919
1920   /* If we have a .dynamic section, create a PT_DYNAMIC segment.  */
1921   sdyn = bfd_get_section_by_name (abfd, ".dynamic");
1922   if (sdyn != NULL && (sdyn->flags & SEC_LOAD) != 0)
1923     {
1924       phdr->p_type = PT_DYNAMIC;
1925       phdr->p_offset = sdyn->filepos;
1926       phdr->p_vaddr = sdyn->vma;
1927       phdr->p_paddr = 0;
1928       phdr->p_filesz = sdyn->_raw_size;
1929       phdr->p_memsz = sdyn->_raw_size;
1930       phdr->p_flags = PF_R;
1931       if ((sdyn->flags & SEC_READONLY) == 0)
1932         phdr->p_flags |= PF_W;
1933       if ((sdyn->flags & SEC_CODE) != 0)
1934         phdr->p_flags |= PF_X;
1935       phdr->p_align = 1 << bfd_get_section_alignment (abfd, sdyn);
1936
1937       ++phdr;
1938       ++phdr_count;
1939     }
1940
1941   /* Make sure the return value from get_program_header_size matches
1942      what we computed here.  Actually, it's OK if we allocated too
1943      much space in the program header.  */
1944   if (phdr_count > phdr_size / sizeof (Elf_External_Phdr))
1945     abort ();
1946
1947   /* Set up program header information.  */
1948   i_ehdrp = elf_elfheader (abfd);
1949   i_ehdrp->e_phentsize = sizeof (Elf_External_Phdr);
1950   i_ehdrp->e_phoff = off;
1951   i_ehdrp->e_phnum = phdr_count;
1952
1953   /* Save the program headers away.  I don't think anybody uses this
1954      information right now.  */
1955   elf_tdata (abfd)->phdr = ((Elf_Internal_Phdr *)
1956                             bfd_alloc (abfd,
1957                                        (phdr_count
1958                                         * sizeof (Elf_Internal_Phdr))));
1959   if (elf_tdata (abfd)->phdr == NULL && phdr_count != 0)
1960     {
1961       bfd_set_error (bfd_error_no_memory);
1962       return (file_ptr) -1;
1963     }
1964   memcpy (elf_tdata (abfd)->phdr, phdrs,
1965           phdr_count * sizeof (Elf_Internal_Phdr));
1966
1967   /* Write out the program headers.  */
1968   if (bfd_seek (abfd, off, SEEK_SET) != 0)
1969     return (file_ptr) -1;
1970
1971   for (i = 0, phdr = phdrs; i < phdr_count; i++, phdr++)
1972     {
1973       Elf_External_Phdr extphdr;
1974
1975       elf_swap_phdr_out (abfd, phdr, &extphdr);
1976       if (bfd_write (&extphdr, sizeof (Elf_External_Phdr), 1, abfd)
1977           != sizeof (Elf_External_Phdr))
1978         return (file_ptr) -1;
1979     }
1980
1981   return off + phdr_count * sizeof (Elf_External_Phdr);
1982 }
1983
1984 /* Work out the file positions of all the sections.  This is called by
1985    elf_compute_section_file_positions.  All the section sizes and VMAs
1986    must be known before this is called.
1987
1988    We do not consider reloc sections at this point, unless they form
1989    part of the loadable image.  Reloc sections are assigned file
1990    positions in assign_file_positions_for_relocs, which is called by
1991    write_object_contents and final_link.
1992
1993    If DOSYMS is false, we do not assign file positions for the symbol
1994    table or the string table.  */
1995
1996 static boolean
1997 assign_file_positions_except_relocs (abfd, dosyms)
1998      bfd *abfd;
1999      boolean dosyms;
2000 {
2001   struct elf_obj_tdata * const tdata = elf_tdata (abfd);
2002   Elf_Internal_Ehdr * const i_ehdrp = elf_elfheader (abfd);
2003   Elf_Internal_Shdr ** const i_shdrpp = elf_elfsections (abfd);
2004   file_ptr off;
2005
2006   /* Start after the ELF header.  */
2007   off = i_ehdrp->e_ehsize;
2008
2009   if ((abfd->flags & (EXEC_P | DYNAMIC)) == 0)
2010     {
2011       Elf_Internal_Shdr **hdrpp;
2012       unsigned int i;
2013
2014       /* We are not creating an executable, which means that we are
2015          not creating a program header, and that the actual order of
2016          the sections in the file is unimportant.  */
2017       for (i = 1, hdrpp = i_shdrpp + 1; i < i_ehdrp->e_shnum; i++, hdrpp++)
2018         {
2019           Elf_Internal_Shdr *hdr;
2020
2021           hdr = *hdrpp;
2022           if (hdr->sh_type == SHT_REL || hdr->sh_type == SHT_RELA)
2023             {
2024               hdr->sh_offset = -1;
2025               continue;
2026             }
2027           if (! dosyms
2028               && (i == tdata->symtab_section
2029                   || i == tdata->strtab_section))
2030             {
2031               hdr->sh_offset = -1;
2032               continue;
2033             }
2034           
2035           off = assign_file_position_for_section (hdr, off, true);
2036         }
2037     }
2038   else
2039     {
2040       file_ptr phdr_off;
2041       bfd_size_type phdr_size;
2042       bfd_vma maxpagesize;
2043       size_t hdrppsize;
2044       Elf_Internal_Shdr **sorted_hdrs;
2045       Elf_Internal_Shdr **hdrpp;
2046       unsigned int i;
2047       Elf_Internal_Shdr *first;
2048       file_ptr phdr_map;
2049
2050       /* We are creating an executable.  We must create a program
2051          header.  We can't actually create the program header until we
2052          have set the file positions for the sections, but we can
2053          figure out how big it is going to be.  */
2054       off = align_file_position (off);
2055       phdr_size = get_program_header_size (abfd);
2056       if (phdr_size == (file_ptr) -1)
2057         return false;
2058       phdr_off = off;
2059       off += phdr_size;
2060
2061       maxpagesize = get_elf_backend_data (abfd)->maxpagesize;
2062       if (maxpagesize == 0)
2063         maxpagesize = 1;
2064
2065       /* We must sort the sections.  The GNU linker will always create
2066          the sections in an appropriate order, but the Irix 5 linker
2067          will not.  We don't include the dummy first section in the
2068          sort.  We sort sections which are not SHF_ALLOC to the end.  */
2069       hdrppsize = (i_ehdrp->e_shnum - 1) * sizeof (Elf_Internal_Shdr *);
2070       sorted_hdrs = (Elf_Internal_Shdr **) malloc (hdrppsize);
2071       if (sorted_hdrs == NULL)
2072         {
2073           bfd_set_error (bfd_error_no_memory);
2074           return false;
2075         }
2076
2077       memcpy (sorted_hdrs, i_shdrpp + 1, hdrppsize);
2078       qsort (sorted_hdrs, i_ehdrp->e_shnum - 1, sizeof (Elf_Internal_Shdr *),
2079              elf_sort_hdrs);
2080
2081       first = NULL;
2082       for (i = 1, hdrpp = sorted_hdrs; i < i_ehdrp->e_shnum; i++, hdrpp++)
2083         {
2084           Elf_Internal_Shdr *hdr;
2085
2086           hdr = *hdrpp;
2087           if ((hdr->sh_flags & SHF_ALLOC) == 0)
2088             {
2089               if (hdr->sh_type == SHT_REL || hdr->sh_type == SHT_RELA)
2090                 {
2091                   hdr->sh_offset = -1;
2092                   continue;
2093                 }
2094               if (! dosyms
2095                   && (hdr == i_shdrpp[tdata->symtab_section]
2096                       || hdr == i_shdrpp[tdata->strtab_section]))
2097                 {
2098                   hdr->sh_offset = -1;
2099                   continue;
2100                 }
2101             }
2102           else
2103             {
2104               if (first == NULL)
2105                 first = hdr;
2106
2107               /* The section VMA must equal the file position modulo
2108                  the page size.  This is required by the program
2109                  header.  */
2110               off += (hdr->sh_addr - off) % maxpagesize;
2111             }
2112
2113           off = assign_file_position_for_section (hdr, off, false);
2114         }
2115
2116       phdr_map = map_program_segments (abfd, phdr_off, first, phdr_size);
2117       if (phdr_map == (file_ptr) -1)
2118         return false;
2119       BFD_ASSERT ((bfd_size_type) phdr_map <= (bfd_size_type) phdr_off + phdr_size);
2120     }
2121
2122   /* Place the section headers.  */
2123   off = align_file_position (off);
2124   i_ehdrp->e_shoff = off;
2125   off += i_ehdrp->e_shnum * i_ehdrp->e_shentsize;
2126
2127   elf_tdata (abfd)->next_file_pos = off;
2128
2129   return true;
2130 }
2131
2132 /* Sort the ELF headers by VMA.  We sort headers which are not
2133    SHF_ALLOC to the end.  */
2134
2135 static int
2136 elf_sort_hdrs (arg1, arg2)
2137      const PTR arg1;
2138      const PTR arg2;
2139 {
2140   const Elf_Internal_Shdr *hdr1 = *(const Elf_Internal_Shdr **) arg1;
2141   const Elf_Internal_Shdr *hdr2 = *(const Elf_Internal_Shdr **) arg2;
2142
2143   if ((hdr1->sh_flags & SHF_ALLOC) != 0)
2144     {
2145       if ((hdr2->sh_flags & SHF_ALLOC) == 0)
2146         return -1;
2147       if (hdr1->sh_addr < hdr2->sh_addr)
2148         return -1;
2149       else if (hdr1->sh_addr > hdr2->sh_addr)
2150         return 1;
2151       else
2152         return 0;
2153     }
2154   else
2155     {
2156       if ((hdr1->sh_flags & SHF_ALLOC) != 0)
2157         return 1;
2158       return 0;
2159     }
2160 }
2161
2162 static boolean
2163 prep_headers (abfd)
2164      bfd *abfd;
2165 {
2166   Elf_Internal_Ehdr *i_ehdrp;   /* Elf file header, internal form */
2167   Elf_Internal_Phdr *i_phdrp = 0;       /* Program header table, internal form */
2168   Elf_Internal_Shdr **i_shdrp;  /* Section header table, internal form */
2169   int count;
2170   struct bfd_strtab_hash *shstrtab;
2171
2172   i_ehdrp = elf_elfheader (abfd);
2173   i_shdrp = elf_elfsections (abfd);
2174
2175   shstrtab = elf_stringtab_init ();
2176   if (shstrtab == NULL)
2177     return false;
2178
2179   elf_shstrtab (abfd) = shstrtab;
2180
2181   i_ehdrp->e_ident[EI_MAG0] = ELFMAG0;
2182   i_ehdrp->e_ident[EI_MAG1] = ELFMAG1;
2183   i_ehdrp->e_ident[EI_MAG2] = ELFMAG2;
2184   i_ehdrp->e_ident[EI_MAG3] = ELFMAG3;
2185
2186   i_ehdrp->e_ident[EI_CLASS] = ELFCLASS;
2187   i_ehdrp->e_ident[EI_DATA] =
2188     abfd->xvec->byteorder_big_p ? ELFDATA2MSB : ELFDATA2LSB;
2189   i_ehdrp->e_ident[EI_VERSION] = EV_CURRENT;
2190
2191   for (count = EI_PAD; count < EI_NIDENT; count++)
2192     i_ehdrp->e_ident[count] = 0;
2193
2194   if ((abfd->flags & DYNAMIC) != 0)
2195     i_ehdrp->e_type = ET_DYN;
2196   else if ((abfd->flags & EXEC_P) != 0)
2197     i_ehdrp->e_type = ET_EXEC;
2198   else
2199     i_ehdrp->e_type = ET_REL;
2200
2201   switch (bfd_get_arch (abfd))
2202     {
2203     case bfd_arch_unknown:
2204       i_ehdrp->e_machine = EM_NONE;
2205       break;
2206     case bfd_arch_sparc:
2207 #if ARCH_SIZE == 64
2208       i_ehdrp->e_machine = EM_SPARC64;
2209 #else
2210       i_ehdrp->e_machine = EM_SPARC;
2211 #endif
2212       break;
2213     case bfd_arch_i386:
2214       i_ehdrp->e_machine = EM_386;
2215       break;
2216     case bfd_arch_m68k:
2217       i_ehdrp->e_machine = EM_68K;
2218       break;
2219     case bfd_arch_m88k:
2220       i_ehdrp->e_machine = EM_88K;
2221       break;
2222     case bfd_arch_i860:
2223       i_ehdrp->e_machine = EM_860;
2224       break;
2225     case bfd_arch_mips: /* MIPS Rxxxx */
2226       i_ehdrp->e_machine = EM_MIPS;     /* only MIPS R3000 */
2227       break;
2228     case bfd_arch_hppa:
2229       i_ehdrp->e_machine = EM_PARISC;
2230       break;
2231     case bfd_arch_powerpc:
2232       i_ehdrp->e_machine = EM_PPC;
2233       break;
2234 /* start-sanitize-arc */
2235     case bfd_arch_arc:
2236       i_ehdrp->e_machine = EM_CYGNUS_ARC;
2237       break;
2238 /* end-sanitize-arc */
2239       /* also note that EM_M32, AT&T WE32100 is unknown to bfd */
2240     default:
2241       i_ehdrp->e_machine = EM_NONE;
2242     }
2243   i_ehdrp->e_version = EV_CURRENT;
2244   i_ehdrp->e_ehsize = sizeof (Elf_External_Ehdr);
2245
2246   /* no program header, for now. */
2247   i_ehdrp->e_phoff = 0;
2248   i_ehdrp->e_phentsize = 0;
2249   i_ehdrp->e_phnum = 0;
2250
2251   /* each bfd section is section header entry */
2252   i_ehdrp->e_entry = bfd_get_start_address (abfd);
2253   i_ehdrp->e_shentsize = sizeof (Elf_External_Shdr);
2254
2255   /* if we're building an executable, we'll need a program header table */
2256   if (abfd->flags & EXEC_P)
2257     {
2258       /* it all happens later */
2259 #if 0
2260       i_ehdrp->e_phentsize = sizeof (Elf_External_Phdr);
2261
2262       /* elf_build_phdrs() returns a (NULL-terminated) array of
2263          Elf_Internal_Phdrs */
2264       i_phdrp = elf_build_phdrs (abfd, i_ehdrp, i_shdrp, &i_ehdrp->e_phnum);
2265       i_ehdrp->e_phoff = outbase;
2266       outbase += i_ehdrp->e_phentsize * i_ehdrp->e_phnum;
2267 #endif
2268     }
2269   else
2270     {
2271       i_ehdrp->e_phentsize = 0;
2272       i_phdrp = 0;
2273       i_ehdrp->e_phoff = 0;
2274     }
2275
2276   elf_tdata (abfd)->symtab_hdr.sh_name =
2277     (unsigned int) _bfd_stringtab_add (shstrtab, ".symtab", true, false);
2278   elf_tdata (abfd)->strtab_hdr.sh_name =
2279     (unsigned int) _bfd_stringtab_add (shstrtab, ".strtab", true, false);
2280   elf_tdata (abfd)->shstrtab_hdr.sh_name =
2281     (unsigned int) _bfd_stringtab_add (shstrtab, ".shstrtab", true, false);
2282   if (elf_tdata (abfd)->symtab_hdr.sh_name == (unsigned int) -1
2283       || elf_tdata (abfd)->symtab_hdr.sh_name == (unsigned int) -1
2284       || elf_tdata (abfd)->shstrtab_hdr.sh_name == (unsigned int) -1)
2285     return false;
2286
2287   return true;
2288 }
2289
2290 static boolean
2291 swap_out_syms (abfd, sttp)
2292      bfd *abfd;
2293      struct bfd_strtab_hash **sttp;
2294 {
2295   if (!elf_map_symbols (abfd))
2296     return false;
2297
2298   /* Dump out the symtabs. */
2299   {
2300     int symcount = bfd_get_symcount (abfd);
2301     asymbol **syms = bfd_get_outsymbols (abfd);
2302     struct bfd_strtab_hash *stt;
2303     Elf_Internal_Shdr *symtab_hdr;
2304     Elf_Internal_Shdr *symstrtab_hdr;
2305     Elf_External_Sym *outbound_syms;
2306     int idx;
2307
2308     stt = elf_stringtab_init ();
2309     if (stt == NULL)
2310       return false;
2311
2312     symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
2313     symtab_hdr->sh_type = SHT_SYMTAB;
2314     symtab_hdr->sh_entsize = sizeof (Elf_External_Sym);
2315     symtab_hdr->sh_size = symtab_hdr->sh_entsize * (symcount + 1);
2316     symtab_hdr->sh_info = elf_num_locals (abfd) + 1;
2317     symtab_hdr->sh_addralign = FILE_ALIGN;
2318
2319     symstrtab_hdr = &elf_tdata (abfd)->strtab_hdr;
2320     symstrtab_hdr->sh_type = SHT_STRTAB;
2321
2322     outbound_syms = ((Elf_External_Sym *)
2323                      bfd_alloc (abfd,
2324                                 (1 + symcount) * sizeof (Elf_External_Sym)));
2325     if (outbound_syms == NULL)
2326       {
2327         bfd_set_error (bfd_error_no_memory);
2328         return false;
2329       }
2330     symtab_hdr->contents = (PTR) outbound_syms;
2331
2332     /* now generate the data (for "contents") */
2333     {
2334       /* Fill in zeroth symbol and swap it out.  */
2335       Elf_Internal_Sym sym;
2336       sym.st_name = 0;
2337       sym.st_value = 0;
2338       sym.st_size = 0;
2339       sym.st_info = 0;
2340       sym.st_other = 0;
2341       sym.st_shndx = SHN_UNDEF;
2342       elf_swap_symbol_out (abfd, &sym, outbound_syms);
2343       ++outbound_syms;
2344     }
2345     for (idx = 0; idx < symcount; idx++)
2346       {
2347         Elf_Internal_Sym sym;
2348         bfd_vma value = syms[idx]->value;
2349         elf_symbol_type *type_ptr;
2350
2351         if (syms[idx]->flags & BSF_SECTION_SYM)
2352           /* Section symbols have no names.  */
2353           sym.st_name = 0;
2354         else
2355           {
2356             sym.st_name = (unsigned long) _bfd_stringtab_add (stt,
2357                                                               syms[idx]->name,
2358                                                               true, false);
2359             if (sym.st_name == (unsigned long) -1)
2360               return false;
2361           }
2362
2363         type_ptr = elf_symbol_from (abfd, syms[idx]);
2364
2365         if (bfd_is_com_section (syms[idx]->section))
2366           {
2367             /* ELF common symbols put the alignment into the `value' field,
2368                and the size into the `size' field.  This is backwards from
2369                how BFD handles it, so reverse it here.  */
2370             sym.st_size = value;
2371             if (type_ptr == NULL
2372                 || type_ptr->internal_elf_sym.st_value == 0)
2373               sym.st_value = value >= 16 ? 16 : (1 << bfd_log2 (value));
2374             else
2375               sym.st_value = type_ptr->internal_elf_sym.st_value;
2376             sym.st_shndx = elf_section_from_bfd_section (abfd,
2377                                                          syms[idx]->section);
2378           }
2379         else
2380           {
2381             asection *sec = syms[idx]->section;
2382             int shndx;
2383
2384             if (sec->output_section)
2385               {
2386                 value += sec->output_offset;
2387                 sec = sec->output_section;
2388               }
2389             value += sec->vma;
2390             sym.st_value = value;
2391             sym.st_size = type_ptr ? type_ptr->internal_elf_sym.st_size : 0;
2392             sym.st_shndx = shndx = elf_section_from_bfd_section (abfd, sec);
2393             if (shndx == -1)
2394               {
2395                 asection *sec2;
2396                 /* Writing this would be a hell of a lot easier if we had
2397                    some decent documentation on bfd, and knew what to expect
2398                    of the library, and what to demand of applications.  For
2399                    example, it appears that `objcopy' might not set the
2400                    section of a symbol to be a section that is actually in
2401                    the output file.  */
2402                 sec2 = bfd_get_section_by_name (abfd, sec->name);
2403                 BFD_ASSERT (sec2 != 0);
2404                 sym.st_shndx = shndx = elf_section_from_bfd_section (abfd, sec2);
2405                 BFD_ASSERT (shndx != -1);
2406               }
2407           }
2408
2409         if (bfd_is_com_section (syms[idx]->section))
2410           sym.st_info = ELF_ST_INFO (STB_GLOBAL, STT_OBJECT);
2411         else if (bfd_is_und_section (syms[idx]->section))
2412           sym.st_info = ELF_ST_INFO (STB_GLOBAL,
2413                                      ((syms[idx]->flags & BSF_FUNCTION)
2414                                       ? STT_FUNC
2415                                       : STT_NOTYPE));
2416         else if (syms[idx]->flags & BSF_SECTION_SYM)
2417           sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
2418         else if (syms[idx]->flags & BSF_FILE)
2419           sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
2420         else
2421           {
2422             int bind = STB_LOCAL;
2423             int type = STT_OBJECT;
2424             unsigned int flags = syms[idx]->flags;
2425
2426             if (flags & BSF_LOCAL)
2427               bind = STB_LOCAL;
2428             else if (flags & BSF_WEAK)
2429               bind = STB_WEAK;
2430             else if (flags & BSF_GLOBAL)
2431               bind = STB_GLOBAL;
2432
2433             if (flags & BSF_FUNCTION)
2434               type = STT_FUNC;
2435
2436             sym.st_info = ELF_ST_INFO (bind, type);
2437           }
2438
2439         sym.st_other = 0;
2440         elf_swap_symbol_out (abfd, &sym, outbound_syms);
2441         ++outbound_syms;
2442       }
2443
2444     *sttp = stt;
2445     symstrtab_hdr->sh_size = _bfd_stringtab_size (stt);
2446     symstrtab_hdr->sh_type = SHT_STRTAB;
2447
2448     symstrtab_hdr->sh_flags = 0;
2449     symstrtab_hdr->sh_addr = 0;
2450     symstrtab_hdr->sh_entsize = 0;
2451     symstrtab_hdr->sh_link = 0;
2452     symstrtab_hdr->sh_info = 0;
2453     symstrtab_hdr->sh_addralign = 1;
2454   }
2455
2456   return true;
2457 }
2458
2459 static boolean
2460 write_shdrs_and_ehdr (abfd)
2461      bfd *abfd;
2462 {
2463   Elf_External_Ehdr x_ehdr;     /* Elf file header, external form */
2464   Elf_Internal_Ehdr *i_ehdrp;   /* Elf file header, internal form */
2465   Elf_External_Shdr *x_shdrp;   /* Section header table, external form */
2466   Elf_Internal_Shdr **i_shdrp;  /* Section header table, internal form */
2467   unsigned int count;
2468
2469   i_ehdrp = elf_elfheader (abfd);
2470   i_shdrp = elf_elfsections (abfd);
2471
2472   /* swap the header before spitting it out... */
2473
2474 #if DEBUG & 1
2475   elf_debug_file (i_ehdrp);
2476 #endif
2477   elf_swap_ehdr_out (abfd, i_ehdrp, &x_ehdr);
2478   if (bfd_seek (abfd, (file_ptr) 0, SEEK_SET) != 0
2479       || (bfd_write ((PTR) & x_ehdr, sizeof (x_ehdr), 1, abfd)
2480           != sizeof (x_ehdr)))
2481     return false;
2482
2483   /* at this point we've concocted all the ELF sections... */
2484   x_shdrp = (Elf_External_Shdr *)
2485     bfd_alloc (abfd, sizeof (*x_shdrp) * (i_ehdrp->e_shnum));
2486   if (!x_shdrp)
2487     {
2488       bfd_set_error (bfd_error_no_memory);
2489       return false;
2490     }
2491
2492   for (count = 0; count < i_ehdrp->e_shnum; count++)
2493     {
2494 #if DEBUG & 2
2495       elf_debug_section (count, i_shdrp[count]);
2496 #endif
2497       elf_swap_shdr_out (abfd, i_shdrp[count], x_shdrp + count);
2498     }
2499   if (bfd_seek (abfd, (file_ptr) i_ehdrp->e_shoff, SEEK_SET) != 0
2500       || (bfd_write ((PTR) x_shdrp, sizeof (*x_shdrp), i_ehdrp->e_shnum, abfd)
2501           != sizeof (*x_shdrp) * i_ehdrp->e_shnum))
2502     return false;
2503
2504   /* need to dump the string table too... */
2505
2506   return true;
2507 }
2508
2509 /* Assign file positions for all the reloc sections which are not part
2510    of the loadable file image.  */
2511
2512 static void
2513 assign_file_positions_for_relocs (abfd)
2514      bfd *abfd;
2515 {
2516   file_ptr off;
2517   unsigned int i;
2518   Elf_Internal_Shdr **shdrpp;
2519
2520   off = elf_tdata (abfd)->next_file_pos;
2521
2522   for (i = 1, shdrpp = elf_elfsections (abfd) + 1;
2523        i < elf_elfheader (abfd)->e_shnum;
2524        i++, shdrpp++)
2525     {
2526       Elf_Internal_Shdr *shdrp;
2527
2528       shdrp = *shdrpp;
2529       if ((shdrp->sh_type == SHT_REL || shdrp->sh_type == SHT_RELA)
2530           && shdrp->sh_offset == -1)
2531         off = assign_file_position_for_section (shdrp, off, true);
2532     }
2533
2534   elf_tdata (abfd)->next_file_pos = off;
2535 }
2536
2537 boolean
2538 NAME(bfd_elf,write_object_contents) (abfd)
2539      bfd *abfd;
2540 {
2541   struct elf_backend_data *bed = get_elf_backend_data (abfd);
2542   Elf_Internal_Ehdr *i_ehdrp;
2543   Elf_Internal_Shdr **i_shdrp;
2544   unsigned int count;
2545
2546   if (! abfd->output_has_begun
2547       && ! elf_compute_section_file_positions (abfd,
2548                                                (struct bfd_link_info *) NULL))
2549     return false;
2550
2551   i_shdrp = elf_elfsections (abfd);
2552   i_ehdrp = elf_elfheader (abfd);
2553
2554   bfd_map_over_sections (abfd, write_relocs, (PTR) 0);
2555   assign_file_positions_for_relocs (abfd);
2556
2557   /* After writing the headers, we need to write the sections too... */
2558   for (count = 1; count < i_ehdrp->e_shnum; count++)
2559     {
2560       if (bed->elf_backend_section_processing)
2561         (*bed->elf_backend_section_processing) (abfd, i_shdrp[count]);
2562       if (i_shdrp[count]->contents)
2563         {
2564           if (bfd_seek (abfd, i_shdrp[count]->sh_offset, SEEK_SET) != 0
2565               || (bfd_write (i_shdrp[count]->contents, i_shdrp[count]->sh_size,
2566                              1, abfd)
2567                   != i_shdrp[count]->sh_size))
2568             return false;
2569         }
2570     }
2571
2572   /* Write out the section header names.  */
2573   if (bfd_seek (abfd, elf_tdata (abfd)->shstrtab_hdr.sh_offset, SEEK_SET) != 0
2574       || ! _bfd_stringtab_emit (abfd, elf_shstrtab (abfd)))
2575     return false;
2576
2577   if (bed->elf_backend_final_write_processing)
2578     (*bed->elf_backend_final_write_processing) (abfd,
2579                                                 elf_tdata (abfd)->linker);
2580
2581   return write_shdrs_and_ehdr (abfd);
2582 }
2583
2584 /* Given an ELF section number, retrieve the corresponding BFD
2585    section.  */
2586
2587 static asection *
2588 section_from_elf_index (abfd, index)
2589      bfd *abfd;
2590      unsigned int index;
2591 {
2592   BFD_ASSERT (index > 0 && index < SHN_LORESERVE);
2593   if (index >= elf_elfheader (abfd)->e_shnum)
2594     return NULL;
2595   return elf_elfsections (abfd)[index]->bfd_section;
2596 }
2597
2598 /* given a section, search the header to find them... */
2599 static int
2600 elf_section_from_bfd_section (abfd, asect)
2601      bfd *abfd;
2602      struct sec *asect;
2603 {
2604   struct elf_backend_data *bed = get_elf_backend_data (abfd);
2605   Elf_Internal_Shdr **i_shdrp = elf_elfsections (abfd);
2606   int index;
2607   Elf_Internal_Shdr *hdr;
2608   int maxindex = elf_elfheader (abfd)->e_shnum;
2609
2610   for (index = 0; index < maxindex; index++)
2611     {
2612       hdr = i_shdrp[index];
2613       if (hdr->bfd_section == asect)
2614         return index;
2615     }
2616
2617   if (bed->elf_backend_section_from_bfd_section)
2618     {
2619       for (index = 0; index < maxindex; index++)
2620         {
2621           int retval;
2622
2623           hdr = i_shdrp[index];
2624           retval = index;
2625           if ((*bed->elf_backend_section_from_bfd_section)
2626               (abfd, hdr, asect, &retval))
2627             return retval;
2628         }
2629     }
2630
2631   if (bfd_is_abs_section (asect))
2632     return SHN_ABS;
2633   if (bfd_is_com_section (asect))
2634     return SHN_COMMON;
2635   if (bfd_is_und_section (asect))
2636     return SHN_UNDEF;
2637
2638   return -1;
2639 }
2640
2641 /* given a symbol, return the bfd index for that symbol.  */
2642 static int
2643 elf_symbol_from_bfd_symbol (abfd, asym_ptr_ptr)
2644      bfd *abfd;
2645      struct symbol_cache_entry **asym_ptr_ptr;
2646 {
2647   struct symbol_cache_entry *asym_ptr = *asym_ptr_ptr;
2648   int idx;
2649   flagword flags = asym_ptr->flags;
2650
2651   /* When gas creates relocations against local labels, it creates its
2652      own symbol for the section, but does put the symbol into the
2653      symbol chain, so udata is 0.  When the linker is generating
2654      relocatable output, this section symbol may be for one of the
2655      input sections rather than the output section.  */
2656   if (asym_ptr->udata.i == 0
2657       && (flags & BSF_SECTION_SYM)
2658       && asym_ptr->section)
2659     {
2660       int indx;
2661
2662       if (asym_ptr->section->output_section != NULL)
2663         indx = asym_ptr->section->output_section->index;
2664       else
2665         indx = asym_ptr->section->index;
2666       if (elf_section_syms (abfd)[indx])
2667         asym_ptr->udata.i = elf_section_syms (abfd)[indx]->udata.i;
2668     }
2669
2670   idx = asym_ptr->udata.i;
2671   if (idx == 0)
2672     abort ();
2673
2674 #if DEBUG & 4
2675   {
2676
2677     fprintf (stderr,
2678              "elf_symbol_from_bfd_symbol 0x%.8lx, name = %s, sym num = %d, flags = 0x%.8lx %s\n",
2679      (long) asym_ptr, asym_ptr->name, idx, flags, elf_symbol_flags (flags));
2680     fflush (stderr);
2681   }
2682 #endif
2683
2684   return idx;
2685 }
2686
2687 static long
2688 elf_slurp_symbol_table (abfd, symptrs, dynamic)
2689      bfd *abfd;
2690      asymbol **symptrs;         /* Buffer for generated bfd symbols */
2691      boolean dynamic;
2692 {
2693   Elf_Internal_Shdr *hdr;
2694   long symcount;                /* Number of external ELF symbols */
2695   elf_symbol_type *sym;         /* Pointer to current bfd symbol */
2696   elf_symbol_type *symbase;     /* Buffer for generated bfd symbols */
2697   Elf_Internal_Sym i_sym;
2698   Elf_External_Sym *x_symp = NULL;
2699
2700   /* Read each raw ELF symbol, converting from external ELF form to
2701      internal ELF form, and then using the information to create a
2702      canonical bfd symbol table entry.
2703
2704      Note that we allocate the initial bfd canonical symbol buffer
2705      based on a one-to-one mapping of the ELF symbols to canonical
2706      symbols.  We actually use all the ELF symbols, so there will be no
2707      space left over at the end.  When we have all the symbols, we
2708      build the caller's pointer vector. */
2709
2710   if (dynamic)
2711     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
2712   else
2713     hdr = &elf_tdata (abfd)->symtab_hdr;
2714   if (bfd_seek (abfd, hdr->sh_offset, SEEK_SET) == -1)
2715     return -1;
2716
2717   symcount = hdr->sh_size / sizeof (Elf_External_Sym);
2718
2719   if (symcount == 0)
2720     sym = symbase = NULL;
2721   else
2722     {
2723       long i;
2724
2725       if (bfd_seek (abfd, hdr->sh_offset, SEEK_SET) == -1)
2726         return -1;
2727
2728       symbase = ((elf_symbol_type *)
2729                  bfd_zalloc (abfd, symcount * sizeof (elf_symbol_type)));
2730       if (symbase == (elf_symbol_type *) NULL)
2731         {
2732           bfd_set_error (bfd_error_no_memory);
2733           return -1;
2734         }
2735       sym = symbase;
2736
2737       /* Temporarily allocate room for the raw ELF symbols.  */
2738       x_symp = ((Elf_External_Sym *)
2739                 malloc (symcount * sizeof (Elf_External_Sym)));
2740       if (x_symp == NULL && symcount != 0)
2741         {
2742           bfd_set_error (bfd_error_no_memory);
2743           goto error_return;
2744         }
2745
2746       if (bfd_read ((PTR) x_symp, sizeof (Elf_External_Sym), symcount, abfd)
2747           != symcount * sizeof (Elf_External_Sym))
2748         goto error_return;
2749       /* Skip first symbol, which is a null dummy.  */
2750       for (i = 1; i < symcount; i++)
2751         {
2752           elf_swap_symbol_in (abfd, x_symp + i, &i_sym);
2753           memcpy (&sym->internal_elf_sym, &i_sym, sizeof (Elf_Internal_Sym));
2754 #ifdef ELF_KEEP_EXTSYM
2755           memcpy (&sym->native_elf_sym, x_symp + i, sizeof (Elf_External_Sym));
2756 #endif
2757           sym->symbol.the_bfd = abfd;
2758
2759           sym->symbol.name = elf_string_from_elf_section (abfd, hdr->sh_link,
2760                                                           i_sym.st_name);
2761
2762           sym->symbol.value = i_sym.st_value;
2763
2764           if (i_sym.st_shndx > 0 && i_sym.st_shndx < SHN_LORESERVE)
2765             {
2766               sym->symbol.section = section_from_elf_index (abfd,
2767                                                             i_sym.st_shndx);
2768               if (sym->symbol.section == NULL)
2769                 {
2770                   /* This symbol is in a section for which we did not
2771                      create a BFD section.  Just use bfd_abs_section,
2772                      although it is wrong.  FIXME.  */
2773                   sym->symbol.section = bfd_abs_section_ptr;
2774                 }
2775             }
2776           else if (i_sym.st_shndx == SHN_ABS)
2777             {
2778               sym->symbol.section = bfd_abs_section_ptr;
2779             }
2780           else if (i_sym.st_shndx == SHN_COMMON)
2781             {
2782               sym->symbol.section = bfd_com_section_ptr;
2783               /* Elf puts the alignment into the `value' field, and
2784                  the size into the `size' field.  BFD wants to see the
2785                  size in the value field, and doesn't care (at the
2786                  moment) about the alignment.  */
2787               sym->symbol.value = i_sym.st_size;
2788             }
2789           else if (i_sym.st_shndx == SHN_UNDEF)
2790             {
2791               sym->symbol.section = bfd_und_section_ptr;
2792             }
2793           else
2794             sym->symbol.section = bfd_abs_section_ptr;
2795
2796           sym->symbol.value -= sym->symbol.section->vma;
2797
2798           switch (ELF_ST_BIND (i_sym.st_info))
2799             {
2800             case STB_LOCAL:
2801               sym->symbol.flags |= BSF_LOCAL;
2802               break;
2803             case STB_GLOBAL:
2804               if (i_sym.st_shndx != SHN_UNDEF
2805                   && i_sym.st_shndx != SHN_COMMON)
2806                 sym->symbol.flags |= BSF_GLOBAL;
2807               break;
2808             case STB_WEAK:
2809               sym->symbol.flags |= BSF_WEAK;
2810               break;
2811             }
2812
2813           switch (ELF_ST_TYPE (i_sym.st_info))
2814             {
2815             case STT_SECTION:
2816               sym->symbol.flags |= BSF_SECTION_SYM | BSF_DEBUGGING;
2817               break;
2818             case STT_FILE:
2819               sym->symbol.flags |= BSF_FILE | BSF_DEBUGGING;
2820               break;
2821             case STT_FUNC:
2822               sym->symbol.flags |= BSF_FUNCTION;
2823               break;
2824             }
2825
2826           if (dynamic)
2827             sym->symbol.flags |= BSF_DYNAMIC;
2828
2829           /* Do some backend-specific processing on this symbol.  */
2830           {
2831             struct elf_backend_data *ebd = get_elf_backend_data (abfd);
2832             if (ebd->elf_backend_symbol_processing)
2833               (*ebd->elf_backend_symbol_processing) (abfd, &sym->symbol);
2834           }
2835
2836           sym++;
2837         }
2838     }
2839
2840   /* Do some backend-specific processing on this symbol table.  */
2841   {
2842     struct elf_backend_data *ebd = get_elf_backend_data (abfd);
2843     if (ebd->elf_backend_symbol_table_processing)
2844       (*ebd->elf_backend_symbol_table_processing) (abfd, symbase, symcount);
2845   }
2846
2847   /* We rely on the zalloc to clear out the final symbol entry.  */
2848
2849   symcount = sym - symbase;
2850
2851   /* Fill in the user's symbol pointer vector if needed.  */
2852   if (symptrs)
2853     {
2854       long l = symcount;
2855
2856       sym = symbase;
2857       while (l-- > 0)
2858         {
2859           *symptrs++ = &sym->symbol;
2860           sym++;
2861         }
2862       *symptrs = 0;             /* Final null pointer */
2863     }
2864
2865   if (x_symp != NULL)
2866     free (x_symp);
2867   return symcount;
2868 error_return:
2869   if (x_symp != NULL)
2870     free (x_symp);
2871   return -1;
2872 }
2873
2874 /* Return the number of bytes required to hold the symtab vector.
2875
2876    Note that we base it on the count plus 1, since we will null terminate
2877    the vector allocated based on this size.  However, the ELF symbol table
2878    always has a dummy entry as symbol #0, so it ends up even.  */
2879
2880 long
2881 elf_get_symtab_upper_bound (abfd)
2882      bfd *abfd;
2883 {
2884   long symcount;
2885   long symtab_size;
2886   Elf_Internal_Shdr *hdr = &elf_tdata (abfd)->symtab_hdr;
2887
2888   symcount = hdr->sh_size / sizeof (Elf_External_Sym);
2889   symtab_size = (symcount - 1 + 1) * (sizeof (asymbol *));
2890
2891   return symtab_size;
2892 }
2893
2894 long
2895 elf_get_dynamic_symtab_upper_bound (abfd)
2896      bfd *abfd;
2897 {
2898   long symcount;
2899   long symtab_size;
2900   Elf_Internal_Shdr *hdr = &elf_tdata (abfd)->dynsymtab_hdr;
2901
2902   if (elf_dynsymtab (abfd) == 0)
2903     {
2904       bfd_set_error (bfd_error_invalid_operation);
2905       return -1;
2906     }
2907
2908   symcount = hdr->sh_size / sizeof (Elf_External_Sym);
2909   symtab_size = (symcount - 1 + 1) * (sizeof (asymbol *));
2910
2911   return symtab_size;
2912 }
2913
2914 long
2915 elf_get_reloc_upper_bound (abfd, asect)
2916      bfd *abfd;
2917      sec_ptr asect;
2918 {
2919   return (asect->reloc_count + 1) * sizeof (arelent *);
2920 }
2921
2922 /* Read in and swap the external relocs.  */
2923
2924 static boolean
2925 elf_slurp_reloc_table (abfd, asect, symbols)
2926      bfd *abfd;
2927      asection *asect;
2928      asymbol **symbols;
2929 {
2930   struct elf_backend_data * const ebd = get_elf_backend_data (abfd);
2931   struct bfd_elf_section_data * const d = elf_section_data (asect);
2932   PTR allocated = NULL;
2933   bfd_byte *native_relocs;
2934   arelent *relents;
2935   arelent *relent;
2936   unsigned int i;
2937   int entsize;
2938
2939   if (asect->relocation != NULL
2940       || (asect->flags & SEC_RELOC) == 0
2941       || asect->reloc_count == 0)
2942     return true;
2943
2944   BFD_ASSERT (asect->rel_filepos == d->rel_hdr.sh_offset
2945               && (asect->reloc_count
2946                   == d->rel_hdr.sh_size / d->rel_hdr.sh_entsize));
2947
2948   allocated = (PTR) malloc (d->rel_hdr.sh_size);
2949   if (allocated == NULL)
2950     {
2951       bfd_set_error (bfd_error_no_memory);
2952       goto error_return;
2953     }
2954
2955   if (bfd_seek (abfd, asect->rel_filepos, SEEK_SET) != 0
2956       || (bfd_read (allocated, 1, d->rel_hdr.sh_size, abfd)
2957           != d->rel_hdr.sh_size))
2958     goto error_return;
2959
2960   native_relocs = (bfd_byte *) allocated;
2961
2962   relents = ((arelent *)
2963              bfd_alloc (abfd, asect->reloc_count * sizeof (arelent)));
2964   if (relents == NULL)
2965     {
2966       bfd_set_error (bfd_error_no_memory);
2967       goto error_return;
2968     }
2969
2970   entsize = d->rel_hdr.sh_entsize;
2971   BFD_ASSERT (entsize == sizeof (Elf_External_Rel)
2972               || entsize == sizeof (Elf_External_Rela));
2973
2974   for (i = 0, relent = relents;
2975        i < asect->reloc_count;
2976        i++, relent++, native_relocs += entsize)
2977     {
2978       Elf_Internal_Rela rela;
2979       Elf_Internal_Rel rel;
2980
2981       if (entsize == sizeof (Elf_External_Rela))
2982         elf_swap_reloca_in (abfd, (Elf_External_Rela *) native_relocs, &rela);
2983       else
2984         {
2985           elf_swap_reloc_in (abfd, (Elf_External_Rel *) native_relocs, &rel);
2986           rela.r_offset = rel.r_offset;
2987           rela.r_info = rel.r_info;
2988           rela.r_addend = 0;
2989         }
2990
2991       /* The address of an ELF reloc is section relative for an object
2992          file, and absolute for an executable file or shared library.
2993          The address of a BFD reloc is always section relative.  */
2994       if ((abfd->flags & (EXEC_P | DYNAMIC)) == 0)
2995         relent->address = rela.r_offset;
2996       else
2997         relent->address = rela.r_offset - asect->vma;
2998
2999       if (ELF_R_SYM (rela.r_info) == 0)
3000         relent->sym_ptr_ptr = bfd_abs_section_ptr->symbol_ptr_ptr;
3001       else
3002         {
3003           asymbol **ps, *s;
3004
3005           ps = symbols + ELF_R_SYM (rela.r_info) - 1;
3006           s = *ps;
3007
3008           /* Canonicalize ELF section symbols.  FIXME: Why?  */
3009           if ((s->flags & BSF_SECTION_SYM) == 0)
3010             relent->sym_ptr_ptr = ps;
3011           else
3012             relent->sym_ptr_ptr = s->section->symbol_ptr_ptr;
3013         }
3014
3015       relent->addend = rela.r_addend;
3016
3017       if (entsize == sizeof (Elf_External_Rela))
3018         (*ebd->elf_info_to_howto) (abfd, relent, &rela);
3019       else
3020         (*ebd->elf_info_to_howto_rel) (abfd, relent, &rel);
3021     }
3022
3023   asect->relocation = relents;
3024
3025   if (allocated != NULL)
3026     free (allocated);
3027
3028   return true;
3029
3030  error_return:
3031   if (allocated != NULL)
3032     free (allocated);
3033   return false;
3034 }
3035
3036 #ifdef DEBUG
3037 static void
3038 elf_debug_section (num, hdr)
3039      int num;
3040      Elf_Internal_Shdr *hdr;
3041 {
3042   fprintf (stderr, "\nSection#%d '%s' 0x%.8lx\n", num,
3043            hdr->bfd_section != NULL ? hfd->bfd_section->name : "",
3044            (long) hdr);
3045   fprintf (stderr,
3046            "sh_name      = %ld\tsh_type      = %ld\tsh_flags     = %ld\n",
3047            (long) hdr->sh_name,
3048            (long) hdr->sh_type,
3049            (long) hdr->sh_flags);
3050   fprintf (stderr,
3051            "sh_addr      = %ld\tsh_offset    = %ld\tsh_size      = %ld\n",
3052            (long) hdr->sh_addr,
3053            (long) hdr->sh_offset,
3054            (long) hdr->sh_size);
3055   fprintf (stderr,
3056            "sh_link      = %ld\tsh_info      = %ld\tsh_addralign = %ld\n",
3057            (long) hdr->sh_link,
3058            (long) hdr->sh_info,
3059            (long) hdr->sh_addralign);
3060   fprintf (stderr, "sh_entsize   = %ld\n",
3061            (long) hdr->sh_entsize);
3062   fflush (stderr);
3063 }
3064
3065 static void
3066 elf_debug_file (ehdrp)
3067      Elf_Internal_Ehdr *ehdrp;
3068 {
3069   fprintf (stderr, "e_entry      = 0x%.8lx\n", (long) ehdrp->e_entry);
3070   fprintf (stderr, "e_phoff      = %ld\n", (long) ehdrp->e_phoff);
3071   fprintf (stderr, "e_phnum      = %ld\n", (long) ehdrp->e_phnum);
3072   fprintf (stderr, "e_phentsize  = %ld\n", (long) ehdrp->e_phentsize);
3073   fprintf (stderr, "e_shoff      = %ld\n", (long) ehdrp->e_shoff);
3074   fprintf (stderr, "e_shnum      = %ld\n", (long) ehdrp->e_shnum);
3075   fprintf (stderr, "e_shentsize  = %ld\n", (long) ehdrp->e_shentsize);
3076 }
3077 #endif
3078
3079 /* Canonicalize the relocs.  */
3080
3081 long
3082 elf_canonicalize_reloc (abfd, section, relptr, symbols)
3083      bfd *abfd;
3084      sec_ptr section;
3085      arelent **relptr;
3086      asymbol **symbols;
3087 {
3088   arelent *tblptr;
3089   unsigned int i;
3090
3091   if (! elf_slurp_reloc_table (abfd, section, symbols))
3092     return -1;
3093
3094   tblptr = section->relocation;
3095   for (i = 0; i < section->reloc_count; i++)
3096     *relptr++ = tblptr++;
3097
3098   *relptr = NULL;
3099
3100   return section->reloc_count;
3101 }
3102
3103 long
3104 elf_get_symtab (abfd, alocation)
3105      bfd *abfd;
3106      asymbol **alocation;
3107 {
3108   long symcount = elf_slurp_symbol_table (abfd, alocation, false);
3109
3110   if (symcount >= 0)
3111     bfd_get_symcount (abfd) = symcount;
3112   return symcount;
3113 }
3114
3115 long
3116 elf_canonicalize_dynamic_symtab (abfd, alocation)
3117      bfd *abfd;
3118      asymbol **alocation;
3119 {
3120   return elf_slurp_symbol_table (abfd, alocation, true);
3121 }
3122
3123 asymbol *
3124 elf_make_empty_symbol (abfd)
3125      bfd *abfd;
3126 {
3127   elf_symbol_type *newsym;
3128
3129   newsym = (elf_symbol_type *) bfd_zalloc (abfd, sizeof (elf_symbol_type));
3130   if (!newsym)
3131     {
3132       bfd_set_error (bfd_error_no_memory);
3133       return NULL;
3134     }
3135   else
3136     {
3137       newsym->symbol.the_bfd = abfd;
3138       return &newsym->symbol;
3139     }
3140 }
3141
3142 void
3143 elf_get_symbol_info (ignore_abfd, symbol, ret)
3144      bfd *ignore_abfd;
3145      asymbol *symbol;
3146      symbol_info *ret;
3147 {
3148   bfd_symbol_info (symbol, ret);
3149 }
3150
3151 alent *
3152 elf_get_lineno (ignore_abfd, symbol)
3153      bfd *ignore_abfd;
3154      asymbol *symbol;
3155 {
3156   fprintf (stderr, "elf_get_lineno unimplemented\n");
3157   fflush (stderr);
3158   BFD_FAIL ();
3159   return NULL;
3160 }
3161
3162 boolean
3163 elf_set_arch_mach (abfd, arch, machine)
3164      bfd *abfd;
3165      enum bfd_architecture arch;
3166      unsigned long machine;
3167 {
3168   /* If this isn't the right architecture for this backend, and this
3169      isn't the generic backend, fail.  */
3170   if (arch != get_elf_backend_data (abfd)->arch
3171       && arch != bfd_arch_unknown
3172       && get_elf_backend_data (abfd)->arch != bfd_arch_unknown)
3173     return false;
3174
3175   return bfd_default_set_arch_mach (abfd, arch, machine);
3176 }
3177
3178 boolean
3179 elf_find_nearest_line (abfd,
3180                        section,
3181                        symbols,
3182                        offset,
3183                        filename_ptr,
3184                        functionname_ptr,
3185                        line_ptr)
3186      bfd *abfd;
3187      asection *section;
3188      asymbol **symbols;
3189      bfd_vma offset;
3190      CONST char **filename_ptr;
3191      CONST char **functionname_ptr;
3192      unsigned int *line_ptr;
3193 {
3194   return false;
3195 }
3196
3197 int
3198 elf_sizeof_headers (abfd, reloc)
3199      bfd *abfd;
3200      boolean reloc;
3201 {
3202   int ret;
3203
3204   ret = sizeof (Elf_External_Ehdr);
3205   if (! reloc)
3206     ret += get_program_header_size (abfd);
3207   return ret;
3208 }
3209
3210 boolean
3211 elf_set_section_contents (abfd, section, location, offset, count)
3212      bfd *abfd;
3213      sec_ptr section;
3214      PTR location;
3215      file_ptr offset;
3216      bfd_size_type count;
3217 {
3218   Elf_Internal_Shdr *hdr;
3219
3220   if (! abfd->output_has_begun
3221       && ! elf_compute_section_file_positions (abfd,
3222                                                (struct bfd_link_info *) NULL))
3223     return false;
3224
3225   hdr = &elf_section_data (section)->this_hdr;
3226
3227   if (bfd_seek (abfd, hdr->sh_offset + offset, SEEK_SET) == -1)
3228     return false;
3229   if (bfd_write (location, 1, count, abfd) != count)
3230     return false;
3231
3232   return true;
3233 }
3234
3235 void
3236 elf_no_info_to_howto (abfd, cache_ptr, dst)
3237      bfd *abfd;
3238      arelent *cache_ptr;
3239      Elf_Internal_Rela *dst;
3240 {
3241   fprintf (stderr, "elf RELA relocation support for target machine unimplemented\n");
3242   fflush (stderr);
3243   BFD_FAIL ();
3244 }
3245
3246 void
3247 elf_no_info_to_howto_rel (abfd, cache_ptr, dst)
3248      bfd *abfd;
3249      arelent *cache_ptr;
3250      Elf_Internal_Rel *dst;
3251 {
3252   fprintf (stderr, "elf REL relocation support for target machine unimplemented\n");
3253   fflush (stderr);
3254   BFD_FAIL ();
3255 }
3256 \f
3257
3258 /* Core file support */
3259
3260 #ifdef HAVE_PROCFS              /* Some core file support requires host /proc files */
3261 #include <sys/procfs.h>
3262 #else
3263 #define bfd_prstatus(abfd, descdata, descsz, filepos) true
3264 #define bfd_fpregset(abfd, descdata, descsz, filepos) true
3265 #define bfd_prpsinfo(abfd, descdata, descsz, filepos) true
3266 #endif
3267
3268 #ifdef HAVE_PROCFS
3269
3270 static boolean
3271 bfd_prstatus (abfd, descdata, descsz, filepos)
3272      bfd *abfd;
3273      char *descdata;
3274      int descsz;
3275      long filepos;
3276 {
3277   asection *newsect;
3278   prstatus_t *status = (prstatus_t *) 0;
3279
3280   if (descsz == sizeof (prstatus_t))
3281     {
3282       newsect = bfd_make_section (abfd, ".reg");
3283       if (newsect == NULL)
3284         return false;
3285       newsect->_raw_size = sizeof (status->pr_reg);
3286       newsect->filepos = filepos + (long) &status->pr_reg;
3287       newsect->flags = SEC_HAS_CONTENTS;
3288       newsect->alignment_power = 2;
3289       if ((core_prstatus (abfd) = bfd_alloc (abfd, descsz)) != NULL)
3290         {
3291           memcpy (core_prstatus (abfd), descdata, descsz);
3292         }
3293     }
3294   return true;
3295 }
3296
3297 /* Stash a copy of the prpsinfo structure away for future use. */
3298
3299 static boolean
3300 bfd_prpsinfo (abfd, descdata, descsz, filepos)
3301      bfd *abfd;
3302      char *descdata;
3303      int descsz;
3304      long filepos;
3305 {
3306   if (descsz == sizeof (prpsinfo_t))
3307     {
3308       if ((core_prpsinfo (abfd) = bfd_alloc (abfd, descsz)) == NULL)
3309         {
3310           bfd_set_error (bfd_error_no_memory);
3311           return false;
3312         }
3313       memcpy (core_prpsinfo (abfd), descdata, descsz);
3314     }
3315   return true;
3316 }
3317
3318 static boolean
3319 bfd_fpregset (abfd, descdata, descsz, filepos)
3320      bfd *abfd;
3321      char *descdata;
3322      int descsz;
3323      long filepos;
3324 {
3325   asection *newsect;
3326
3327   newsect = bfd_make_section (abfd, ".reg2");
3328   if (newsect == NULL)
3329     return false;
3330   newsect->_raw_size = descsz;
3331   newsect->filepos = filepos;
3332   newsect->flags = SEC_HAS_CONTENTS;
3333   newsect->alignment_power = 2;
3334   return true;
3335 }
3336
3337 #endif /* HAVE_PROCFS */
3338
3339 /* Return a pointer to the args (including the command name) that were
3340    seen by the program that generated the core dump.  Note that for
3341    some reason, a spurious space is tacked onto the end of the args
3342    in some (at least one anyway) implementations, so strip it off if
3343    it exists. */
3344
3345 char *
3346 elf_core_file_failing_command (abfd)
3347      bfd *abfd;
3348 {
3349 #ifdef HAVE_PROCFS
3350   if (core_prpsinfo (abfd))
3351     {
3352       prpsinfo_t *p = core_prpsinfo (abfd);
3353       char *scan = p->pr_psargs;
3354       while (*scan++)
3355         {;
3356         }
3357       scan -= 2;
3358       if ((scan > p->pr_psargs) && (*scan == ' '))
3359         {
3360           *scan = '\000';
3361         }
3362       return p->pr_psargs;
3363     }
3364 #endif
3365   return NULL;
3366 }
3367
3368 /* Return the number of the signal that caused the core dump.  Presumably,
3369    since we have a core file, we got a signal of some kind, so don't bother
3370    checking the other process status fields, just return the signal number.
3371    */
3372
3373 int
3374 elf_core_file_failing_signal (abfd)
3375      bfd *abfd;
3376 {
3377 #ifdef HAVE_PROCFS
3378   if (core_prstatus (abfd))
3379     {
3380       return ((prstatus_t *) (core_prstatus (abfd)))->pr_cursig;
3381     }
3382 #endif
3383   return -1;
3384 }
3385
3386 /* Check to see if the core file could reasonably be expected to have
3387    come for the current executable file.  Note that by default we return
3388    true unless we find something that indicates that there might be a
3389    problem.
3390    */
3391
3392 boolean
3393 elf_core_file_matches_executable_p (core_bfd, exec_bfd)
3394      bfd *core_bfd;
3395      bfd *exec_bfd;
3396 {
3397 #ifdef HAVE_PROCFS
3398   char *corename;
3399   char *execname;
3400 #endif
3401
3402   /* First, xvecs must match since both are ELF files for the same target. */
3403
3404   if (core_bfd->xvec != exec_bfd->xvec)
3405     {
3406       bfd_set_error (bfd_error_system_call);
3407       return false;
3408     }
3409
3410 #ifdef HAVE_PROCFS
3411
3412   /* If no prpsinfo, just return true.  Otherwise, grab the last component
3413      of the exec'd pathname from the prpsinfo. */
3414
3415   if (core_prpsinfo (core_bfd))
3416     {
3417       corename = (((struct prpsinfo *) core_prpsinfo (core_bfd))->pr_fname);
3418     }
3419   else
3420     {
3421       return true;
3422     }
3423
3424   /* Find the last component of the executable pathname. */
3425
3426   if ((execname = strrchr (exec_bfd->filename, '/')) != NULL)
3427     {
3428       execname++;
3429     }
3430   else
3431     {
3432       execname = (char *) exec_bfd->filename;
3433     }
3434
3435   /* See if they match */
3436
3437   return strcmp (execname, corename) ? false : true;
3438
3439 #else
3440
3441   return true;
3442
3443 #endif /* HAVE_PROCFS */
3444 }
3445
3446 /* ELF core files contain a segment of type PT_NOTE, that holds much of
3447    the information that would normally be available from the /proc interface
3448    for the process, at the time the process dumped core.  Currently this
3449    includes copies of the prstatus, prpsinfo, and fpregset structures.
3450
3451    Since these structures are potentially machine dependent in size and
3452    ordering, bfd provides two levels of support for them.  The first level,
3453    available on all machines since it does not require that the host
3454    have /proc support or the relevant include files, is to create a bfd
3455    section for each of the prstatus, prpsinfo, and fpregset structures,
3456    without any interpretation of their contents.  With just this support,
3457    the bfd client will have to interpret the structures itself.  Even with
3458    /proc support, it might want these full structures for it's own reasons.
3459
3460    In the second level of support, where HAVE_PROCFS is defined, bfd will
3461    pick apart the structures to gather some additional information that
3462    clients may want, such as the general register set, the name of the
3463    exec'ed file and its arguments, the signal (if any) that caused the
3464    core dump, etc.
3465
3466    */
3467
3468 static boolean
3469 elf_corefile_note (abfd, hdr)
3470      bfd *abfd;
3471      Elf_Internal_Phdr *hdr;
3472 {
3473   Elf_External_Note *x_note_p;  /* Elf note, external form */
3474   Elf_Internal_Note i_note;     /* Elf note, internal form */
3475   char *buf = NULL;             /* Entire note segment contents */
3476   char *namedata;               /* Name portion of the note */
3477   char *descdata;               /* Descriptor portion of the note */
3478   char *sectname;               /* Name to use for new section */
3479   long filepos;                 /* File offset to descriptor data */
3480   asection *newsect;
3481
3482   if (hdr->p_filesz > 0
3483       && (buf = (char *) malloc (hdr->p_filesz)) != NULL
3484       && bfd_seek (abfd, hdr->p_offset, SEEK_SET) != -1
3485       && bfd_read ((PTR) buf, hdr->p_filesz, 1, abfd) == hdr->p_filesz)
3486     {
3487       x_note_p = (Elf_External_Note *) buf;
3488       while ((char *) x_note_p < (buf + hdr->p_filesz))
3489         {
3490           i_note.namesz = bfd_h_get_32 (abfd, (bfd_byte *) x_note_p->namesz);
3491           i_note.descsz = bfd_h_get_32 (abfd, (bfd_byte *) x_note_p->descsz);
3492           i_note.type = bfd_h_get_32 (abfd, (bfd_byte *) x_note_p->type);
3493           namedata = x_note_p->name;
3494           descdata = namedata + BFD_ALIGN (i_note.namesz, 4);
3495           filepos = hdr->p_offset + (descdata - buf);
3496           switch (i_note.type)
3497             {
3498             case NT_PRSTATUS:
3499               /* process descdata as prstatus info */
3500               if (! bfd_prstatus (abfd, descdata, i_note.descsz, filepos))
3501                 return false;
3502               sectname = ".prstatus";
3503               break;
3504             case NT_FPREGSET:
3505               /* process descdata as fpregset info */
3506               if (! bfd_fpregset (abfd, descdata, i_note.descsz, filepos))
3507                 return false;
3508               sectname = ".fpregset";
3509               break;
3510             case NT_PRPSINFO:
3511               /* process descdata as prpsinfo */
3512               if (! bfd_prpsinfo (abfd, descdata, i_note.descsz, filepos))
3513                 return false;
3514               sectname = ".prpsinfo";
3515               break;
3516             default:
3517               /* Unknown descriptor, just ignore it. */
3518               sectname = NULL;
3519               break;
3520             }
3521           if (sectname != NULL)
3522             {
3523               newsect = bfd_make_section (abfd, sectname);
3524               if (newsect == NULL)
3525                 return false;
3526               newsect->_raw_size = i_note.descsz;
3527               newsect->filepos = filepos;
3528               newsect->flags = SEC_ALLOC | SEC_HAS_CONTENTS;
3529               newsect->alignment_power = 2;
3530             }
3531           x_note_p = (Elf_External_Note *)
3532             (descdata + BFD_ALIGN (i_note.descsz, 4));
3533         }
3534     }
3535   if (buf != NULL)
3536     {
3537       free (buf);
3538     }
3539   else if (hdr->p_filesz > 0)
3540     {
3541       bfd_set_error (bfd_error_no_memory);
3542       return false;
3543     }
3544   return true;
3545
3546 }
3547
3548 /*  Core files are simply standard ELF formatted files that partition
3549     the file using the execution view of the file (program header table)
3550     rather than the linking view.  In fact, there is no section header
3551     table in a core file.
3552
3553     The process status information (including the contents of the general
3554     register set) and the floating point register set are stored in a
3555     segment of type PT_NOTE.  We handcraft a couple of extra bfd sections
3556     that allow standard bfd access to the general registers (.reg) and the
3557     floating point registers (.reg2).
3558
3559  */
3560
3561 const bfd_target *
3562 elf_core_file_p (abfd)
3563      bfd *abfd;
3564 {
3565   Elf_External_Ehdr x_ehdr;     /* Elf file header, external form */
3566   Elf_Internal_Ehdr *i_ehdrp;   /* Elf file header, internal form */
3567   Elf_External_Phdr x_phdr;     /* Program header table entry, external form */
3568   Elf_Internal_Phdr *i_phdrp;   /* Program header table, internal form */
3569   unsigned int phindex;
3570   struct elf_backend_data *ebd;
3571
3572   /* Read in the ELF header in external format.  */
3573
3574   if (bfd_read ((PTR) & x_ehdr, sizeof (x_ehdr), 1, abfd) != sizeof (x_ehdr))
3575     {
3576       if (bfd_get_error () != bfd_error_system_call)
3577         bfd_set_error (bfd_error_wrong_format);
3578       return NULL;
3579     }
3580
3581   /* Now check to see if we have a valid ELF file, and one that BFD can
3582      make use of.  The magic number must match, the address size ('class')
3583      and byte-swapping must match our XVEC entry, and it must have a
3584      program header table (FIXME: See comments re segments at top of this
3585      file). */
3586
3587   if (elf_file_p (&x_ehdr) == false)
3588     {
3589     wrong:
3590       bfd_set_error (bfd_error_wrong_format);
3591       return NULL;
3592     }
3593
3594   /* FIXME, Check EI_VERSION here !  */
3595
3596   {
3597 #if ARCH_SIZE == 32
3598     int desired_address_size = ELFCLASS32;
3599 #endif
3600 #if ARCH_SIZE == 64
3601     int desired_address_size = ELFCLASS64;
3602 #endif
3603
3604     if (x_ehdr.e_ident[EI_CLASS] != desired_address_size)
3605       goto wrong;
3606   }
3607
3608   /* Switch xvec to match the specified byte order.  */
3609   switch (x_ehdr.e_ident[EI_DATA])
3610     {
3611     case ELFDATA2MSB:           /* Big-endian */
3612       if (abfd->xvec->byteorder_big_p == false)
3613         goto wrong;
3614       break;
3615     case ELFDATA2LSB:           /* Little-endian */
3616       if (abfd->xvec->byteorder_big_p == true)
3617         goto wrong;
3618       break;
3619     case ELFDATANONE:           /* No data encoding specified */
3620     default:                    /* Unknown data encoding specified */
3621       goto wrong;
3622     }
3623
3624   /* Allocate an instance of the elf_obj_tdata structure and hook it up to
3625      the tdata pointer in the bfd. */
3626
3627   elf_tdata (abfd) =
3628     (struct elf_obj_tdata *) bfd_zalloc (abfd, sizeof (struct elf_obj_tdata));
3629   if (elf_tdata (abfd) == NULL)
3630     {
3631       bfd_set_error (bfd_error_no_memory);
3632       return NULL;
3633     }
3634
3635   /* FIXME, `wrong' returns from this point onward, leak memory.  */
3636
3637   /* Now that we know the byte order, swap in the rest of the header */
3638   i_ehdrp = elf_elfheader (abfd);
3639   elf_swap_ehdr_in (abfd, &x_ehdr, i_ehdrp);
3640 #if DEBUG & 1
3641   elf_debug_file (i_ehdrp);
3642 #endif
3643
3644   ebd = get_elf_backend_data (abfd);
3645
3646   /* Check that the ELF e_machine field matches what this particular
3647      BFD format expects.  */
3648   if (ebd->elf_machine_code != i_ehdrp->e_machine)
3649     {
3650       const bfd_target * const *target_ptr;
3651
3652       if (ebd->elf_machine_code != EM_NONE)
3653         goto wrong;
3654
3655       /* This is the generic ELF target.  Let it match any ELF target
3656          for which we do not have a specific backend.  */
3657       for (target_ptr = bfd_target_vector; *target_ptr != NULL; target_ptr++)
3658         {
3659           struct elf_backend_data *back;
3660
3661           if ((*target_ptr)->flavour != bfd_target_elf_flavour)
3662             continue;
3663           back = (struct elf_backend_data *) (*target_ptr)->backend_data;
3664           if (back->elf_machine_code == i_ehdrp->e_machine)
3665             {
3666               /* target_ptr is an ELF backend which matches this
3667                  object file, so reject the generic ELF target.  */
3668               goto wrong;
3669             }
3670         }
3671     }
3672
3673   /* If there is no program header, or the type is not a core file, then
3674      we are hosed. */
3675   if (i_ehdrp->e_phoff == 0 || i_ehdrp->e_type != ET_CORE)
3676     goto wrong;
3677
3678   /* Allocate space for a copy of the program header table in
3679      internal form, seek to the program header table in the file,
3680      read it in, and convert it to internal form.  As a simple sanity
3681      check, verify that the what BFD thinks is the size of each program
3682      header table entry actually matches the size recorded in the file. */
3683
3684   if (i_ehdrp->e_phentsize != sizeof (x_phdr))
3685     goto wrong;
3686   i_phdrp = (Elf_Internal_Phdr *)
3687     bfd_alloc (abfd, sizeof (*i_phdrp) * i_ehdrp->e_phnum);
3688   if (!i_phdrp)
3689     {
3690       bfd_set_error (bfd_error_no_memory);
3691       return NULL;
3692     }
3693   if (bfd_seek (abfd, i_ehdrp->e_phoff, SEEK_SET) == -1)
3694     return NULL;
3695   for (phindex = 0; phindex < i_ehdrp->e_phnum; phindex++)
3696     {
3697       if (bfd_read ((PTR) & x_phdr, sizeof (x_phdr), 1, abfd)
3698           != sizeof (x_phdr))
3699         return NULL;
3700       elf_swap_phdr_in (abfd, &x_phdr, i_phdrp + phindex);
3701     }
3702
3703   /* Once all of the program headers have been read and converted, we
3704      can start processing them. */
3705
3706   for (phindex = 0; phindex < i_ehdrp->e_phnum; phindex++)
3707     {
3708       bfd_section_from_phdr (abfd, i_phdrp + phindex, phindex);
3709       if ((i_phdrp + phindex)->p_type == PT_NOTE)
3710         {
3711           if (! elf_corefile_note (abfd, i_phdrp + phindex))
3712             return NULL;
3713         }
3714     }
3715
3716   /* Remember the entry point specified in the ELF file header. */
3717
3718   bfd_get_start_address (abfd) = i_ehdrp->e_entry;
3719
3720   return abfd->xvec;
3721 }
3722 \f
3723 /* ELF linker code.  */
3724
3725 static boolean elf_link_add_object_symbols
3726   PARAMS ((bfd *, struct bfd_link_info *));
3727 static boolean elf_link_add_archive_symbols
3728   PARAMS ((bfd *, struct bfd_link_info *));
3729 static Elf_Internal_Rela *elf_link_read_relocs
3730   PARAMS ((bfd *, asection *, PTR, Elf_Internal_Rela *, boolean));
3731 static boolean elf_export_symbol
3732   PARAMS ((struct elf_link_hash_entry *, PTR));
3733 static boolean elf_adjust_dynamic_symbol
3734   PARAMS ((struct elf_link_hash_entry *, PTR));
3735
3736 /* Given an ELF BFD, add symbols to the global hash table as
3737    appropriate.  */
3738
3739 boolean
3740 elf_bfd_link_add_symbols (abfd, info)
3741      bfd *abfd;
3742      struct bfd_link_info *info;
3743 {
3744   bfd *first;
3745
3746   switch (bfd_get_format (abfd))
3747     {
3748     case bfd_object:
3749       return elf_link_add_object_symbols (abfd, info);
3750     case bfd_archive:
3751       first = bfd_openr_next_archived_file (abfd, (bfd *) NULL);
3752       if (first == NULL)
3753         return false;
3754       if (! bfd_check_format (first, bfd_object))
3755         return false;
3756       if (bfd_get_flavour (first) != bfd_target_elf_flavour)
3757         {
3758           /* On Linux, we may have an a.out archive which got
3759              recognized as an ELF archive.  Therefore, we treat all
3760              archives as though they were actually of the flavour of
3761              their first element.  */
3762           return (*first->xvec->_bfd_link_add_symbols) (abfd, info);
3763         }
3764       return elf_link_add_archive_symbols (abfd, info);
3765     default:
3766       bfd_set_error (bfd_error_wrong_format);
3767       return false;
3768     }
3769 }
3770
3771 /* Add symbols from an ELF archive file to the linker hash table.  We
3772    don't use _bfd_generic_link_add_archive_symbols because of a
3773    problem which arises on UnixWare.  The UnixWare libc.so is an
3774    archive which includes an entry libc.so.1 which defines a bunch of
3775    symbols.  The libc.so archive also includes a number of other
3776    object files, which also define symbols, some of which are the same
3777    as those defined in libc.so.1.  Correct linking requires that we
3778    consider each object file in turn, and include it if it defines any
3779    symbols we need.  _bfd_generic_link_add_archive_symbols does not do
3780    this; it looks through the list of undefined symbols, and includes
3781    any object file which defines them.  When this algorithm is used on
3782    UnixWare, it winds up pulling in libc.so.1 early and defining a
3783    bunch of symbols.  This means that some of the other objects in the
3784    archive are not included in the link, which is incorrect since they
3785    precede libc.so.1 in the archive.
3786
3787    Fortunately, ELF archive handling is simpler than that done by
3788    _bfd_generic_link_add_archive_symbols, which has to allow for a.out
3789    oddities.  In ELF, if we find a symbol in the archive map, and the
3790    symbol is currently undefined, we know that we must pull in that
3791    object file.
3792
3793    Unfortunately, we do have to make multiple passes over the symbol
3794    table until nothing further is resolved.  */
3795
3796 static boolean
3797 elf_link_add_archive_symbols (abfd, info)
3798      bfd *abfd;
3799      struct bfd_link_info *info;
3800 {
3801   symindex c;
3802   boolean *defined = NULL;
3803   boolean *included = NULL;
3804   carsym *symdefs;
3805   boolean loop;
3806
3807   if (! bfd_has_map (abfd))
3808     {
3809       /* An empty archive is a special case.  */
3810       if (bfd_openr_next_archived_file (abfd, (bfd *) NULL) == NULL)
3811         return true;
3812       bfd_set_error (bfd_error_no_symbols);
3813       return false;
3814     }
3815
3816   /* Keep track of all symbols we know to be already defined, and all
3817      files we know to be already included.  This is to speed up the
3818      second and subsequent passes.  */
3819   c = bfd_ardata (abfd)->symdef_count;
3820   if (c == 0)
3821     return true;
3822   defined = (boolean *) malloc (c * sizeof (boolean));
3823   included = (boolean *) malloc (c * sizeof (boolean));
3824   if (defined == (boolean *) NULL || included == (boolean *) NULL)
3825     {
3826       bfd_set_error (bfd_error_no_memory);
3827       goto error_return;
3828     }
3829   memset (defined, 0, c * sizeof (boolean));
3830   memset (included, 0, c * sizeof (boolean));
3831
3832   symdefs = bfd_ardata (abfd)->symdefs;
3833
3834   do
3835     {
3836       file_ptr last;
3837       symindex i;
3838       carsym *symdef;
3839       carsym *symdefend;
3840
3841       loop = false;
3842       last = -1;
3843
3844       symdef = symdefs;
3845       symdefend = symdef + c;
3846       for (i = 0; symdef < symdefend; symdef++, i++)
3847         {
3848           struct elf_link_hash_entry *h;
3849           bfd *element;
3850           struct bfd_link_hash_entry *undefs_tail;
3851           symindex mark;
3852
3853           if (defined[i] || included[i])
3854             continue;
3855           if (symdef->file_offset == last)
3856             {
3857               included[i] = true;
3858               continue;
3859             }
3860
3861           h = elf_link_hash_lookup (elf_hash_table (info), symdef->name,
3862                                     false, false, false);
3863           if (h == (struct elf_link_hash_entry *) NULL)
3864             continue;
3865           if (h->root.type != bfd_link_hash_undefined)
3866             {
3867               defined[i] = true;
3868               continue;
3869             }
3870
3871           /* We need to include this archive member.  */
3872
3873           element = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
3874           if (element == (bfd *) NULL)
3875             goto error_return;
3876
3877           if (! bfd_check_format (element, bfd_object))
3878             goto error_return;
3879
3880           /* Doublecheck that we have not included this object
3881              already--it should be impossible, but there may be
3882              something wrong with the archive.  */
3883           if (element->archive_pass != 0)
3884             {
3885               bfd_set_error (bfd_error_bad_value);
3886               goto error_return;
3887             }
3888           element->archive_pass = 1;
3889
3890           undefs_tail = info->hash->undefs_tail;
3891
3892           if (! (*info->callbacks->add_archive_element) (info, element,
3893                                                          symdef->name))
3894             goto error_return;
3895           if (! elf_link_add_object_symbols (element, info))
3896             goto error_return;
3897
3898           /* If there are any new undefined symbols, we need to make
3899              another pass through the archive in order to see whether
3900              they can be defined.  FIXME: This isn't perfect, because
3901              common symbols wind up on undefs_tail and because an
3902              undefined symbol which is defined later on in this pass
3903              does not require another pass.  This isn't a bug, but it
3904              does make the code less efficient than it could be.  */
3905           if (undefs_tail != info->hash->undefs_tail)
3906             loop = true;
3907
3908           /* Look backward to mark all symbols from this object file
3909              which we have already seen in this pass.  */
3910           mark = i;
3911           do
3912             {
3913               included[mark] = true;
3914               if (mark == 0)
3915                 break;
3916               --mark;
3917             }
3918           while (symdefs[mark].file_offset == symdef->file_offset);
3919
3920           /* We mark subsequent symbols from this object file as we go
3921              on through the loop.  */
3922           last = symdef->file_offset;
3923         }
3924     }
3925   while (loop);
3926
3927   free (defined);
3928   free (included);
3929
3930   return true;
3931
3932  error_return:
3933   if (defined != (boolean *) NULL)
3934     free (defined);
3935   if (included != (boolean *) NULL)
3936     free (included);
3937   return false;
3938 }
3939
3940 /* Record a new dynamic symbol.  We record the dynamic symbols as we
3941    read the input files, since we need to have a list of all of them
3942    before we can determine the final sizes of the output sections.
3943    Note that we may actually call this function even though we are not
3944    going to output any dynamic symbols; in some cases we know that a
3945    symbol should be in the dynamic symbol table, but only if there is
3946    one.  */
3947
3948 boolean
3949 elf_link_record_dynamic_symbol (info, h)
3950      struct bfd_link_info *info;
3951      struct elf_link_hash_entry *h;
3952 {
3953   if (h->dynindx == -1)
3954     {
3955       struct bfd_strtab_hash *dynstr;
3956
3957       h->dynindx = elf_hash_table (info)->dynsymcount;
3958       ++elf_hash_table (info)->dynsymcount;
3959
3960       dynstr = elf_hash_table (info)->dynstr;
3961       if (dynstr == NULL)
3962         {
3963           /* Create a strtab to hold the dynamic symbol names.  */
3964           elf_hash_table (info)->dynstr = dynstr = elf_stringtab_init ();
3965           if (dynstr == NULL)
3966             return false;
3967         }
3968
3969       h->dynstr_index = ((unsigned long)
3970                          _bfd_stringtab_add (dynstr, h->root.root.string,
3971                                              true, false));
3972       if (h->dynstr_index == (unsigned long) -1)
3973         return false;
3974     }
3975
3976   return true;
3977 }
3978
3979 /* Add symbols from an ELF object file to the linker hash table.  */
3980
3981 static boolean
3982 elf_link_add_object_symbols (abfd, info)
3983      bfd *abfd;
3984      struct bfd_link_info *info;
3985 {
3986   boolean (*add_symbol_hook) PARAMS ((bfd *, struct bfd_link_info *,
3987                                       const Elf_Internal_Sym *,
3988                                       const char **, flagword *,
3989                                       asection **, bfd_vma *));
3990   boolean (*check_relocs) PARAMS ((bfd *, struct bfd_link_info *,
3991                                    asection *, const Elf_Internal_Rela *));
3992   boolean collect;
3993   Elf_Internal_Shdr *hdr;
3994   size_t symcount;
3995   size_t extsymcount;
3996   size_t extsymoff;
3997   Elf_External_Sym *buf = NULL;
3998   struct elf_link_hash_entry **sym_hash;
3999   boolean dynamic;
4000   Elf_External_Dyn *dynbuf = NULL;
4001   struct elf_link_hash_entry *weaks;
4002   Elf_External_Sym *esym;
4003   Elf_External_Sym *esymend;
4004
4005   add_symbol_hook = get_elf_backend_data (abfd)->elf_add_symbol_hook;
4006   collect = get_elf_backend_data (abfd)->collect;
4007
4008   /* A stripped shared library might only have a dynamic symbol table,
4009      not a regular symbol table.  In that case we can still go ahead
4010      and link using the dynamic symbol table.  */
4011   if (elf_onesymtab (abfd) == 0
4012       && elf_dynsymtab (abfd) != 0)
4013     {
4014       elf_onesymtab (abfd) = elf_dynsymtab (abfd);
4015       elf_tdata (abfd)->symtab_hdr = elf_tdata (abfd)->dynsymtab_hdr;
4016     }
4017
4018   hdr = &elf_tdata (abfd)->symtab_hdr;
4019   symcount = hdr->sh_size / sizeof (Elf_External_Sym);
4020
4021   /* The sh_info field of the symtab header tells us where the
4022      external symbols start.  We don't care about the local symbols at
4023      this point.  */
4024   if (elf_bad_symtab (abfd))
4025     {
4026       extsymcount = symcount;
4027       extsymoff = 0;
4028     }
4029   else
4030     {
4031       extsymcount = symcount - hdr->sh_info;
4032       extsymoff = hdr->sh_info;
4033     }
4034
4035   buf = (Elf_External_Sym *) malloc (extsymcount * sizeof (Elf_External_Sym));
4036   if (buf == NULL && extsymcount != 0)
4037     {
4038       bfd_set_error (bfd_error_no_memory);
4039       goto error_return;
4040     }
4041
4042   /* We store a pointer to the hash table entry for each external
4043      symbol.  */
4044   sym_hash = ((struct elf_link_hash_entry **)
4045               bfd_alloc (abfd,
4046                          extsymcount * sizeof (struct elf_link_hash_entry *)));
4047   if (sym_hash == NULL)
4048     {
4049       bfd_set_error (bfd_error_no_memory);
4050       goto error_return;
4051     }
4052   elf_sym_hashes (abfd) = sym_hash;
4053
4054   if (elf_elfheader (abfd)->e_type != ET_DYN)
4055     {
4056       dynamic = false;
4057
4058       /* If we are creating a shared library, create all the dynamic
4059          sections immediately.  We need to attach them to something,
4060          so we attach them to this BFD, provided it is the right
4061          format.  FIXME: If there are no input BFD's of the same
4062          format as the output, we can't make a shared library.  */
4063       if (info->shared
4064           && ! elf_hash_table (info)->dynamic_sections_created
4065           && abfd->xvec == info->hash->creator)
4066         {
4067           if (! elf_link_create_dynamic_sections (abfd, info))
4068             goto error_return;
4069         }
4070     }
4071   else
4072     {
4073       asection *s;
4074       const char *name;
4075       bfd_size_type strindex;
4076
4077       dynamic = true;
4078
4079       /* You can't use -r against a dynamic object.  Also, there's no
4080          hope of using a dynamic object which does not exactly match
4081          the format of the output file.  */
4082       if (info->relocateable
4083           || info->hash->creator != abfd->xvec)
4084         {
4085           bfd_set_error (bfd_error_invalid_operation);
4086           goto error_return;
4087         }
4088
4089       /* Find the name to use in a DT_NEEDED entry that refers to this
4090          object.  If the object has a DT_SONAME entry, we use it.
4091          Otherwise, if the generic linker stuck something in
4092          elf_dt_needed_name, we use that.  Otherwise, we just use the
4093          file name.  */
4094       name = bfd_get_filename (abfd);
4095       if (elf_dt_needed_name (abfd) != NULL)
4096         name = elf_dt_needed_name (abfd);
4097       s = bfd_get_section_by_name (abfd, ".dynamic");
4098       if (s != NULL)
4099         {
4100           Elf_External_Dyn *extdyn;
4101           Elf_External_Dyn *extdynend;
4102
4103           dynbuf = (Elf_External_Dyn *) malloc (s->_raw_size);
4104           if (dynbuf == NULL)
4105             {
4106               bfd_set_error (bfd_error_no_memory);
4107               goto error_return;
4108             }
4109
4110           if (! bfd_get_section_contents (abfd, s, (PTR) dynbuf,
4111                                           (file_ptr) 0, s->_raw_size))
4112             goto error_return;
4113
4114           extdyn = dynbuf;
4115           extdynend = extdyn + s->_raw_size / sizeof (Elf_External_Dyn);
4116           for (; extdyn < extdynend; extdyn++)
4117             {
4118               Elf_Internal_Dyn dyn;
4119
4120               elf_swap_dyn_in (abfd, extdyn, &dyn);
4121               if (dyn.d_tag == DT_SONAME)
4122                 {
4123                   int elfsec;
4124                   unsigned long link;
4125
4126                   elfsec = elf_section_from_bfd_section (abfd, s);
4127                   if (elfsec == -1)
4128                     goto error_return;
4129                   link = elf_elfsections (abfd)[elfsec]->sh_link;
4130                   name = elf_string_from_elf_section (abfd, link,
4131                                                       dyn.d_un.d_val);
4132                   if (name == NULL)
4133                     goto error_return;
4134
4135                   break;
4136                 }
4137             }
4138
4139           free (dynbuf);
4140           dynbuf = NULL;
4141         }
4142
4143       /* We do not want to include any of the sections in a dynamic
4144          object in the output file.  We hack by simply clobbering the
4145          list of sections in the BFD.  This could be handled more
4146          cleanly by, say, a new section flag; the existing
4147          SEC_NEVER_LOAD flag is not the one we want, because that one
4148          still implies that the section takes up space in the output
4149          file.  */
4150       abfd->sections = NULL;
4151
4152       /* If this is the first dynamic object found in the link, create
4153          the special sections required for dynamic linking.  */
4154       if (! elf_hash_table (info)->dynamic_sections_created)
4155         {
4156           if (! elf_link_create_dynamic_sections (abfd, info))
4157             goto error_return;
4158         }
4159
4160       /* Add a DT_NEEDED entry for this dynamic object.  */
4161       strindex = _bfd_stringtab_add (elf_hash_table (info)->dynstr, name,
4162                                      true, false);
4163       if (strindex == (bfd_size_type) -1)
4164         goto error_return;
4165       if (! elf_add_dynamic_entry (info, DT_NEEDED, strindex))
4166         goto error_return;
4167     }
4168
4169   if (bfd_seek (abfd,
4170                 hdr->sh_offset + extsymoff * sizeof (Elf_External_Sym),
4171                 SEEK_SET) != 0
4172       || (bfd_read ((PTR) buf, sizeof (Elf_External_Sym), extsymcount, abfd)
4173           != extsymcount * sizeof (Elf_External_Sym)))
4174     goto error_return;
4175
4176   weaks = NULL;
4177
4178   esymend = buf + extsymcount;
4179   for (esym = buf; esym < esymend; esym++, sym_hash++)
4180     {
4181       Elf_Internal_Sym sym;
4182       int bind;
4183       bfd_vma value;
4184       asection *sec;
4185       flagword flags;
4186       const char *name;
4187       struct elf_link_hash_entry *h = NULL;
4188       boolean definition;
4189
4190       elf_swap_symbol_in (abfd, esym, &sym);
4191
4192       flags = BSF_NO_FLAGS;
4193       sec = NULL;
4194       value = sym.st_value;
4195       *sym_hash = NULL;
4196
4197       bind = ELF_ST_BIND (sym.st_info);
4198       if (bind == STB_LOCAL)
4199         {
4200           /* This should be impossible, since ELF requires that all
4201              global symbols follow all local symbols, and that sh_info
4202              point to the first global symbol.  Unfortunatealy, Irix 5
4203              screws this up.  */
4204           continue;
4205         }
4206       else if (bind == STB_GLOBAL)
4207         {
4208           if (sym.st_shndx != SHN_UNDEF
4209               && sym.st_shndx != SHN_COMMON)
4210             flags = BSF_GLOBAL;
4211           else
4212             flags = 0;
4213         }
4214       else if (bind == STB_WEAK)
4215         flags = BSF_WEAK;
4216       else
4217         {
4218           /* Leave it up to the processor backend.  */
4219         }
4220
4221       if (sym.st_shndx == SHN_UNDEF)
4222         sec = bfd_und_section_ptr;
4223       else if (sym.st_shndx > 0 && sym.st_shndx < SHN_LORESERVE)
4224         {
4225           sec = section_from_elf_index (abfd, sym.st_shndx);
4226           if (sec != NULL)
4227             value -= sec->vma;
4228           else
4229             sec = bfd_abs_section_ptr;
4230         }
4231       else if (sym.st_shndx == SHN_ABS)
4232         sec = bfd_abs_section_ptr;
4233       else if (sym.st_shndx == SHN_COMMON)
4234         {
4235           sec = bfd_com_section_ptr;
4236           /* What ELF calls the size we call the value.  What ELF
4237              calls the value we call the alignment.  */
4238           value = sym.st_size;
4239         }
4240       else
4241         {
4242           /* Leave it up to the processor backend.  */
4243         }
4244
4245       name = elf_string_from_elf_section (abfd, hdr->sh_link, sym.st_name);
4246       if (name == (const char *) NULL)
4247         goto error_return;
4248
4249       if (add_symbol_hook)
4250         {
4251           if (! (*add_symbol_hook) (abfd, info, &sym, &name, &flags, &sec,
4252                                     &value))
4253             goto error_return;
4254
4255           /* The hook function sets the name to NULL if this symbol
4256              should be skipped for some reason.  */
4257           if (name == (const char *) NULL)
4258             continue;
4259         }
4260
4261       /* Sanity check that all possibilities were handled.  */
4262       if (sec == (asection *) NULL)
4263         {
4264           bfd_set_error (bfd_error_bad_value);
4265           goto error_return;
4266         }
4267
4268       if (bfd_is_und_section (sec)
4269           || bfd_is_com_section (sec))
4270         definition = false;
4271       else
4272         definition = true;
4273
4274       if (info->hash->creator->flavour == bfd_target_elf_flavour)
4275         {
4276           /* We need to look up the symbol now in order to get some of
4277              the dynamic object handling right.  We pass the hash
4278              table entry in to _bfd_generic_link_add_one_symbol so
4279              that it does not have to look it up again.  */
4280           h = elf_link_hash_lookup (elf_hash_table (info), name,
4281                                     true, false, false);
4282           if (h == NULL)
4283             goto error_return;
4284           *sym_hash = h;
4285
4286           /* If we are looking at a dynamic object, and this is a
4287              definition, we need to see if it has already been defined
4288              by some other object.  If it has, we want to use the
4289              existing definition, and we do not want to report a
4290              multiple symbol definition error; we do this by
4291              clobbering sec to be bfd_und_section_ptr.  */
4292           if (dynamic && definition)
4293             {
4294               if (h->root.type == bfd_link_hash_defined)
4295                 sec = bfd_und_section_ptr;
4296             }
4297
4298           /* Similarly, if we are not looking at a dynamic object, and
4299              we have a definition, we want to override any definition
4300              we may have from a dynamic object.  Symbols from regular
4301              files always take precedence over symbols from dynamic
4302              objects, even if they are defined after the dynamic
4303              object in the link.  */
4304           if (! dynamic
4305               && definition
4306               && h->root.type == bfd_link_hash_defined
4307               && (h->elf_link_hash_flags & ELF_LINK_HASH_DEF_DYNAMIC) != 0
4308               && (bfd_get_flavour (h->root.u.def.section->owner)
4309                   == bfd_target_elf_flavour)
4310               && (elf_elfheader (h->root.u.def.section->owner)->e_type
4311                   == ET_DYN))
4312             {
4313               /* Change the hash table entry to undefined, and let
4314                  _bfd_generic_link_add_one_symbol do the right thing
4315                  with the new definition.  */
4316               h->root.type = bfd_link_hash_undefined;
4317               h->root.u.undef.abfd = h->root.u.def.section->owner;
4318               h->elf_link_hash_flags &=~ ELF_LINK_HASH_DEFINED_WEAK;
4319             }
4320
4321           /* If this is a weak definition which we are going to use,
4322              and the symbol is currently undefined, record that the
4323              definition is weak.  */
4324           if (definition
4325               && (flags & BSF_WEAK) != 0
4326               && ! bfd_is_und_section (sec)
4327               && (h->root.type == bfd_link_hash_new
4328                   || h->root.type == bfd_link_hash_undefined
4329                   || h->root.type == bfd_link_hash_weak))
4330             h->elf_link_hash_flags |= ELF_LINK_HASH_DEFINED_WEAK;
4331         }
4332
4333       if (! (_bfd_generic_link_add_one_symbol
4334              (info, abfd, name, flags, sec, value, (const char *) NULL,
4335               false, collect, (struct bfd_link_hash_entry **) sym_hash)))
4336         goto error_return;
4337
4338       if (dynamic
4339           && definition
4340           && (flags & BSF_WEAK) != 0
4341           && ELF_ST_TYPE (sym.st_info) != STT_FUNC
4342           && info->hash->creator->flavour == bfd_target_elf_flavour
4343           && (*sym_hash)->weakdef == NULL)
4344         {
4345           /* Keep a list of all weak defined non function symbols from
4346              a dynamic object, using the weakdef field.  Later in this
4347              function we will set the weakdef field to the correct
4348              value.  We only put non-function symbols from dynamic
4349              objects on this list, because that happens to be the only
4350              time we need to know the normal symbol corresponding to a
4351              weak symbol, and the information is time consuming to
4352              figure out.  If the weakdef field is not already NULL,
4353              then this symbol was already defined by some previous
4354              dynamic object, and we will be using that previous
4355              definition anyhow.  */
4356
4357           (*sym_hash)->weakdef = weaks;
4358           weaks = *sym_hash;
4359         }
4360
4361       /* Get the alignment of a common symbol.  */
4362       if (sym.st_shndx == SHN_COMMON
4363           && h->root.type == bfd_link_hash_common)
4364         h->root.u.c.alignment_power = bfd_log2 (sym.st_value);
4365
4366       if (info->hash->creator->flavour == bfd_target_elf_flavour)
4367         {
4368           int old_flags;
4369           boolean dynsym;
4370           int new_flag;
4371
4372           /* Remember the symbol size and type.  */
4373           if (sym.st_size != 0)
4374             {
4375               /* FIXME: We should probably somehow give a warning if
4376                  the symbol size changes.  */
4377               h->size = sym.st_size;
4378             }
4379           if (ELF_ST_TYPE (sym.st_info) != STT_NOTYPE)
4380             {
4381               /* FIXME: We should probably somehow give a warning if
4382                  the symbol type changes.  */
4383               h->type = ELF_ST_TYPE (sym.st_info);
4384             }
4385
4386           /* Set a flag in the hash table entry indicating the type of
4387              reference or definition we just found.  Keep a count of
4388              the number of dynamic symbols we find.  A dynamic symbol
4389              is one which is referenced or defined by both a regular
4390              object and a shared object, or one which is referenced or
4391              defined by more than one shared object.  */
4392           old_flags = h->elf_link_hash_flags;
4393           dynsym = false;
4394           if (! dynamic)
4395             {
4396               if (! definition)
4397                 new_flag = ELF_LINK_HASH_REF_REGULAR;
4398               else
4399                 new_flag = ELF_LINK_HASH_DEF_REGULAR;
4400               if (info->shared
4401                   || (old_flags & (ELF_LINK_HASH_DEF_DYNAMIC
4402                                    | ELF_LINK_HASH_REF_DYNAMIC)) != 0)
4403                 dynsym = true;
4404             }
4405           else
4406             {
4407               if (! definition)
4408                 new_flag = ELF_LINK_HASH_REF_DYNAMIC;
4409               else
4410                 new_flag = ELF_LINK_HASH_DEF_DYNAMIC;
4411               if ((old_flags & new_flag) != 0
4412                   || (old_flags & (ELF_LINK_HASH_DEF_REGULAR
4413                                    | ELF_LINK_HASH_REF_REGULAR)) != 0)
4414                 dynsym = true;
4415             }
4416
4417           h->elf_link_hash_flags |= new_flag;
4418           if (dynsym && h->dynindx == -1)
4419             {
4420               if (! elf_link_record_dynamic_symbol (info, h))
4421                 goto error_return;
4422             }
4423         }
4424     }
4425
4426   /* Now set the weakdefs field correctly for all the weak defined
4427      symbols we found.  The only way to do this is to search all the
4428      symbols.  Since we only need the information for non functions in
4429      dynamic objects, that's the only time we actually put anything on
4430      the list WEAKS.  We need this information so that if a regular
4431      object refers to a symbol defined weakly in a dynamic object, the
4432      real symbol in the dynamic object is also put in the dynamic
4433      symbols; we also must arrange for both symbols to point to the
4434      same memory location.  We could handle the general case of symbol
4435      aliasing, but a general symbol alias can only be generated in
4436      assembler code, handling it correctly would be very time
4437      consuming, and other ELF linkers don't handle general aliasing
4438      either.  */
4439   while (weaks != NULL)
4440     {
4441       struct elf_link_hash_entry *hlook;
4442       asection *slook;
4443       bfd_vma vlook;
4444       struct elf_link_hash_entry **hpp;
4445       struct elf_link_hash_entry **hppend;
4446
4447       hlook = weaks;
4448       weaks = hlook->weakdef;
4449       hlook->weakdef = NULL;
4450
4451       BFD_ASSERT (hlook->root.type == bfd_link_hash_defined);
4452       slook = hlook->root.u.def.section;
4453       vlook = hlook->root.u.def.value;
4454
4455       hpp = elf_sym_hashes (abfd);
4456       hppend = hpp + extsymcount;
4457       for (; hpp < hppend; hpp++)
4458         {
4459           struct elf_link_hash_entry *h;
4460
4461           h = *hpp;
4462           if (h != hlook
4463               && h->root.type == bfd_link_hash_defined
4464               && h->root.u.def.section == slook
4465               && h->root.u.def.value == vlook)
4466             {
4467               hlook->weakdef = h;
4468
4469               /* If the weak definition is in the list of dynamic
4470                  symbols, make sure the real definition is put there
4471                  as well.  */
4472               if (hlook->dynindx != -1
4473                   && h->dynindx == -1)
4474                 {
4475                   if (! elf_link_record_dynamic_symbol (info, h))
4476                     goto error_return;
4477                 }
4478
4479               break;
4480             }
4481         }
4482     }
4483
4484   if (buf != NULL)
4485     {
4486       free (buf);
4487       buf = NULL;
4488     }
4489
4490   /* If this object is the same format as the output object, and it is
4491      not a shared library, then let the backend look through the
4492      relocs.
4493
4494      This is required to build global offset table entries and to
4495      arrange for dynamic relocs.  It is not required for the
4496      particular common case of linking non PIC code, even when linking
4497      against shared libraries, but unfortunately there is no way of
4498      knowing whether an object file has been compiled PIC or not.
4499      Looking through the relocs is not particularly time consuming.
4500      The problem is that we must either (1) keep the relocs in memory,
4501      which causes the linker to require additional runtime memory or
4502      (2) read the relocs twice from the input file, which wastes time.
4503      This would be a good case for using mmap.
4504
4505      I have no idea how to handle linking PIC code into a file of a
4506      different format.  It probably can't be done.  */
4507   check_relocs = get_elf_backend_data (abfd)->check_relocs;
4508   if (! dynamic
4509       && abfd->xvec == info->hash->creator
4510       && check_relocs != NULL)
4511     {
4512       asection *o;
4513
4514       for (o = abfd->sections; o != NULL; o = o->next)
4515         {
4516           Elf_Internal_Rela *internal_relocs;
4517           boolean ok;
4518
4519           if ((o->flags & SEC_RELOC) == 0
4520               || o->reloc_count == 0)
4521             continue;
4522
4523           /* I believe we can ignore the relocs for any section which
4524              does not form part of the final process image, such as a
4525              debugging section.  */
4526           if ((o->flags & SEC_ALLOC) == 0)
4527             continue;
4528
4529           internal_relocs = elf_link_read_relocs (abfd, o, (PTR) NULL,
4530                                                   (Elf_Internal_Rela *) NULL,
4531                                                   info->keep_memory);
4532           if (internal_relocs == NULL)
4533             goto error_return;
4534
4535           ok = (*check_relocs) (abfd, info, o, internal_relocs);
4536
4537           if (! info->keep_memory)
4538             free (internal_relocs);
4539
4540           if (! ok)
4541             goto error_return;
4542         }
4543     }
4544
4545   return true;
4546
4547  error_return:
4548   if (buf != NULL)
4549     free (buf);
4550   if (dynbuf != NULL)
4551     free (dynbuf);
4552   return false;
4553 }
4554
4555 /* Create some sections which will be filled in with dynamic linking
4556    information.  ABFD is an input file which requires dynamic sections
4557    to be created.  The dynamic sections take up virtual memory space
4558    when the final executable is run, so we need to create them before
4559    addresses are assigned to the output sections.  We work out the
4560    actual contents and size of these sections later.  */
4561
4562 boolean
4563 elf_link_create_dynamic_sections (abfd, info)
4564      bfd *abfd;
4565      struct bfd_link_info *info;
4566 {
4567   flagword flags;
4568   register asection *s;
4569   struct elf_link_hash_entry *h;
4570   struct elf_backend_data *bed;
4571
4572   if (elf_hash_table (info)->dynamic_sections_created)
4573     return true;
4574
4575   /* Make sure that all dynamic sections use the same input BFD.  */
4576   if (elf_hash_table (info)->dynobj == NULL)
4577     elf_hash_table (info)->dynobj = abfd;
4578   else
4579     abfd = elf_hash_table (info)->dynobj;
4580
4581   /* Note that we set the SEC_IN_MEMORY flag for all of these
4582      sections.  */
4583   flags = SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY;
4584
4585   /* A dynamically linked executable has a .interp section, but a
4586      shared library does not.  */
4587   if (! info->shared)
4588     {
4589       s = bfd_make_section (abfd, ".interp");
4590       if (s == NULL
4591           || ! bfd_set_section_flags (abfd, s, flags | SEC_READONLY))
4592         return false;
4593     }
4594
4595   s = bfd_make_section (abfd, ".dynsym");
4596   if (s == NULL
4597       || ! bfd_set_section_flags (abfd, s, flags | SEC_READONLY)
4598       || ! bfd_set_section_alignment (abfd, s, LOG_FILE_ALIGN))
4599     return false;
4600
4601   s = bfd_make_section (abfd, ".dynstr");
4602   if (s == NULL
4603       || ! bfd_set_section_flags (abfd, s, flags | SEC_READONLY))
4604     return false;
4605
4606   /* Create a strtab to hold the dynamic symbol names.  */
4607   if (elf_hash_table (info)->dynstr == NULL)
4608     {
4609       elf_hash_table (info)->dynstr = elf_stringtab_init ();
4610       if (elf_hash_table (info)->dynstr == NULL)
4611         return false;
4612     }
4613
4614   s = bfd_make_section (abfd, ".dynamic");
4615   if (s == NULL
4616       || ! bfd_set_section_flags (abfd, s, flags)
4617       || ! bfd_set_section_alignment (abfd, s, LOG_FILE_ALIGN))
4618     return false;
4619
4620   /* The special symbol _DYNAMIC is always set to the start of the
4621      .dynamic section.  This call occurs before we have processed the
4622      symbols for any dynamic object, so we don't have to worry about
4623      overriding a dynamic definition.  We could set _DYNAMIC in a
4624      linker script, but we only want to define it if we are, in fact,
4625      creating a .dynamic section.  We don't want to define it if there
4626      is no .dynamic section, since on some ELF platforms the start up
4627      code examines it to decide how to initialize the process.  */
4628   h = NULL;
4629   if (! (_bfd_generic_link_add_one_symbol
4630          (info, abfd, "_DYNAMIC", BSF_GLOBAL, s, (bfd_vma) 0,
4631           (const char *) NULL, false, get_elf_backend_data (abfd)->collect,
4632           (struct bfd_link_hash_entry **) &h)))
4633     return false;
4634   h->elf_link_hash_flags |= ELF_LINK_HASH_DEF_REGULAR;
4635   h->type = STT_OBJECT;
4636
4637   if (info->shared
4638       && ! elf_link_record_dynamic_symbol (info, h))
4639     return false;
4640
4641   s = bfd_make_section (abfd, ".hash");
4642   if (s == NULL
4643       || ! bfd_set_section_flags (abfd, s, flags | SEC_READONLY)
4644       || ! bfd_set_section_alignment (abfd, s, LOG_FILE_ALIGN))
4645     return false;
4646
4647   /* Let the backend create the rest of the sections.  This lets the
4648      backend set the right flags.  The backend will normally create
4649      the .got and .plt sections.  */
4650   bed = get_elf_backend_data (abfd);
4651   if (! (*bed->elf_backend_create_dynamic_sections) (abfd, info))
4652     return false;
4653
4654   elf_hash_table (info)->dynamic_sections_created = true;
4655
4656   return true;
4657 }
4658
4659 /* Add an entry to the .dynamic table.  */
4660
4661 boolean
4662 elf_add_dynamic_entry (info, tag, val)
4663      struct bfd_link_info *info;
4664      bfd_vma tag;
4665      bfd_vma val;
4666 {
4667   Elf_Internal_Dyn dyn;
4668   bfd *dynobj;
4669   asection *s;
4670   size_t newsize;
4671   bfd_byte *newcontents;
4672
4673   dynobj = elf_hash_table (info)->dynobj;
4674
4675   s = bfd_get_section_by_name (dynobj, ".dynamic");
4676   BFD_ASSERT (s != NULL);
4677
4678   newsize = s->_raw_size + sizeof (Elf_External_Dyn);
4679   if (s->contents == NULL)
4680     newcontents = (bfd_byte *) malloc (newsize);
4681   else
4682     newcontents = (bfd_byte *) realloc (s->contents, newsize);
4683   if (newcontents == NULL)
4684     {
4685       bfd_set_error (bfd_error_no_memory);
4686       return false;
4687     }
4688
4689   dyn.d_tag = tag;
4690   dyn.d_un.d_val = val;
4691   elf_swap_dyn_out (dynobj, &dyn,
4692                     (Elf_External_Dyn *) (newcontents + s->_raw_size));
4693
4694   s->_raw_size = newsize;
4695   s->contents = newcontents;
4696
4697   return true;
4698 }
4699
4700 /* Read and swap the relocs for a section.  They may have been cached.
4701    If the EXTERNAL_RELOCS and INTERNAL_RELOCS arguments are not NULL,
4702    they are used as buffers to read into.  They are known to be large
4703    enough.  If the INTERNAL_RELOCS relocs argument is NULL, the return
4704    value is allocated using either malloc or bfd_alloc, according to
4705    the KEEP_MEMORY argument.  */
4706
4707 static Elf_Internal_Rela *
4708 elf_link_read_relocs (abfd, o, external_relocs, internal_relocs, keep_memory)
4709      bfd *abfd;
4710      asection *o;
4711      PTR external_relocs;
4712      Elf_Internal_Rela *internal_relocs;
4713      boolean keep_memory;
4714 {
4715   Elf_Internal_Shdr *rel_hdr;
4716   PTR alloc1 = NULL;
4717   Elf_Internal_Rela *alloc2 = NULL;
4718
4719   if (elf_section_data (o)->relocs != NULL)
4720     return elf_section_data (o)->relocs;
4721
4722   if (o->reloc_count == 0)
4723     return NULL;
4724
4725   rel_hdr = &elf_section_data (o)->rel_hdr;
4726
4727   if (internal_relocs == NULL)
4728     {
4729       size_t size;
4730
4731       size = o->reloc_count * sizeof (Elf_Internal_Rela);
4732       if (keep_memory)
4733         internal_relocs = (Elf_Internal_Rela *) bfd_alloc (abfd, size);
4734       else
4735         internal_relocs = alloc2 = (Elf_Internal_Rela *) malloc (size);
4736       if (internal_relocs == NULL)
4737         {
4738           bfd_set_error (bfd_error_no_memory);
4739           goto error_return;
4740         }
4741     }
4742
4743   if (external_relocs == NULL)
4744     {
4745       alloc1 = (PTR) malloc (rel_hdr->sh_size);
4746       if (alloc1 == NULL)
4747         {
4748           bfd_set_error (bfd_error_no_memory);
4749           goto error_return;
4750         }
4751       external_relocs = alloc1;
4752     }
4753
4754   if ((bfd_seek (abfd, rel_hdr->sh_offset, SEEK_SET) != 0)
4755       || (bfd_read (external_relocs, 1, rel_hdr->sh_size, abfd)
4756           != rel_hdr->sh_size))
4757     goto error_return;
4758
4759   /* Swap in the relocs.  For convenience, we always produce an
4760      Elf_Internal_Rela array; if the relocs are Rel, we set the addend
4761      to 0.  */
4762   if (rel_hdr->sh_entsize == sizeof (Elf_External_Rel))
4763     {
4764       Elf_External_Rel *erel;
4765       Elf_External_Rel *erelend;
4766       Elf_Internal_Rela *irela;
4767
4768       erel = (Elf_External_Rel *) external_relocs;
4769       erelend = erel + o->reloc_count;
4770       irela = internal_relocs;
4771       for (; erel < erelend; erel++, irela++)
4772         {
4773           Elf_Internal_Rel irel;
4774
4775           elf_swap_reloc_in (abfd, erel, &irel);
4776           irela->r_offset = irel.r_offset;
4777           irela->r_info = irel.r_info;
4778           irela->r_addend = 0;
4779         }
4780     }
4781   else
4782     {
4783       Elf_External_Rela *erela;
4784       Elf_External_Rela *erelaend;
4785       Elf_Internal_Rela *irela;
4786
4787       BFD_ASSERT (rel_hdr->sh_entsize == sizeof (Elf_External_Rela));
4788
4789       erela = (Elf_External_Rela *) external_relocs;
4790       erelaend = erela + o->reloc_count;
4791       irela = internal_relocs;
4792       for (; erela < erelaend; erela++, irela++)
4793         elf_swap_reloca_in (abfd, erela, irela);
4794     }
4795
4796   /* Cache the results for next time, if we can.  */
4797   if (keep_memory)
4798     elf_section_data (o)->relocs = internal_relocs;
4799                  
4800   if (alloc1 != NULL)
4801     free (alloc1);
4802
4803   /* Don't free alloc2, since if it was allocated we are passing it
4804      back (under the name of internal_relocs).  */
4805
4806   return internal_relocs;
4807
4808  error_return:
4809   if (alloc1 != NULL)
4810     free (alloc1);
4811   if (alloc2 != NULL)
4812     free (alloc2);
4813   return NULL;
4814 }
4815
4816 /* Record an assignment to a symbol made by a linker script.  We need
4817    this in case some dynamic object refers to this symbol.  */
4818
4819 /*ARGSUSED*/
4820 boolean
4821 NAME(bfd_elf,record_link_assignment) (output_bfd, info, name)
4822      bfd *output_bfd;
4823      struct bfd_link_info *info;
4824      const char *name;
4825 {
4826   struct elf_link_hash_entry *h;
4827
4828   h = elf_link_hash_lookup (elf_hash_table (info), name, true, true, false);
4829   if (h == NULL)
4830     return false;
4831
4832   h->elf_link_hash_flags |= ELF_LINK_HASH_DEF_REGULAR;
4833   h->type = STT_OBJECT;
4834
4835   if (((h->elf_link_hash_flags & (ELF_LINK_HASH_DEF_DYNAMIC
4836                                   | ELF_LINK_HASH_REF_DYNAMIC)) != 0
4837        || info->shared)
4838       && h->dynindx == -1)
4839     {
4840       if (! elf_link_record_dynamic_symbol (info, h))
4841         return false;
4842
4843       /* If this is a weak defined symbol, and we know a corresponding
4844          real symbol from the same dynamic object, make sure the real
4845          symbol is also made into a dynamic symbol.  */
4846       if (h->weakdef != NULL
4847           && h->weakdef->dynindx == -1)
4848         {
4849           if (! elf_link_record_dynamic_symbol (info, h->weakdef))
4850             return false;
4851         }
4852     }
4853
4854   return true;
4855 }
4856
4857 /* Array used to determine the number of hash table buckets to use
4858    based on the number of symbols there are.  If there are fewer than
4859    3 symbols we use 1 bucket, fewer than 17 symbols we use 3 buckets,
4860    fewer than 37 we use 17 buckets, and so forth.  We never use more
4861    than 521 buckets.  */
4862
4863 static const size_t elf_buckets[] =
4864 {
4865   1, 3, 17, 37, 67, 97, 131, 197, 263, 521, 0
4866 };
4867
4868 /* Set up the sizes and contents of the ELF dynamic sections.  This is
4869    called by the ELF linker emulation before_allocation routine.  We
4870    must set the sizes of the sections before the linker sets the
4871    addresses of the various sections.  */
4872
4873 boolean
4874 NAME(bfd_elf,size_dynamic_sections) (output_bfd, soname, rpath,
4875                                      export_dynamic, info, sinterpptr)
4876      bfd *output_bfd;
4877      const char *soname;
4878      const char *rpath;
4879      boolean export_dynamic;
4880      struct bfd_link_info *info;
4881      asection **sinterpptr;
4882 {
4883   bfd *dynobj;
4884   asection *s;
4885   Elf_Internal_Sym isym;
4886   size_t i;
4887   size_t bucketcount;
4888   struct elf_backend_data *bed;
4889
4890   *sinterpptr = NULL;
4891
4892   dynobj = elf_hash_table (info)->dynobj;
4893
4894   /* If there were no dynamic objects in the link, there is nothing to
4895      do here.  */
4896   if (dynobj == NULL)
4897     return true;
4898
4899   /* If we are supposed to export all symbols into the dynamic symbol
4900      table (this is not the normal case), then do so.  */
4901   if (export_dynamic)
4902     elf_link_hash_traverse (elf_hash_table (info), elf_export_symbol,
4903                             (PTR) info);
4904
4905   if (elf_hash_table (info)->dynamic_sections_created)
4906     {
4907       bfd_size_type strsize;
4908
4909       *sinterpptr = bfd_get_section_by_name (dynobj, ".interp");
4910       BFD_ASSERT (*sinterpptr != NULL || info->shared);
4911
4912       if (soname != NULL)
4913         {
4914           bfd_size_type indx;
4915
4916           indx = _bfd_stringtab_add (elf_hash_table (info)->dynstr, soname,
4917                                      true, true);
4918           if (indx == (bfd_size_type) -1
4919               || ! elf_add_dynamic_entry (info, DT_SONAME, indx))
4920             return false;
4921         }      
4922
4923       if (rpath != NULL)
4924         {
4925           bfd_size_type indx;
4926
4927           indx = _bfd_stringtab_add (elf_hash_table (info)->dynstr, rpath,
4928                                      true, true);
4929           if (indx == (bfd_size_type) -1
4930               || ! elf_add_dynamic_entry (info, DT_RPATH, indx))
4931             return false;
4932         }
4933
4934       /* Find all symbols which were defined in a dynamic object and make
4935          the backend pick a reasonable value for them.  */
4936       elf_link_hash_traverse (elf_hash_table (info),
4937                               elf_adjust_dynamic_symbol,
4938                               (PTR) info);
4939
4940       /* Add some entries to the .dynamic section.  We fill in some of the
4941          values later, in elf_bfd_final_link, but we must add the entries
4942          now so that we know the final size of the .dynamic section.  */
4943       if (elf_link_hash_lookup (elf_hash_table (info), "_init", false,
4944                                 false, false) != NULL)
4945         {
4946           if (! elf_add_dynamic_entry (info, DT_INIT, 0))
4947             return false;
4948         }
4949       if (elf_link_hash_lookup (elf_hash_table (info), "_fini", false,
4950                                 false, false) != NULL)
4951         {
4952           if (! elf_add_dynamic_entry (info, DT_FINI, 0))
4953             return false;
4954         }
4955       strsize = _bfd_stringtab_size (elf_hash_table (info)->dynstr);
4956       if (! elf_add_dynamic_entry (info, DT_HASH, 0)
4957           || ! elf_add_dynamic_entry (info, DT_STRTAB, 0)
4958           || ! elf_add_dynamic_entry (info, DT_SYMTAB, 0)
4959           || ! elf_add_dynamic_entry (info, DT_STRSZ, strsize)
4960           || ! elf_add_dynamic_entry (info, DT_SYMENT,
4961                                       sizeof (Elf_External_Sym)))
4962         return false;
4963     }
4964
4965   /* The backend must work out the sizes of all the other dynamic
4966      sections.  */
4967   bed = get_elf_backend_data (output_bfd);
4968   if (! (*bed->elf_backend_size_dynamic_sections) (output_bfd, info))
4969     return false;
4970
4971   if (elf_hash_table (info)->dynamic_sections_created)
4972     {
4973       size_t dynsymcount;
4974
4975       /* Set the size of the .dynsym and .hash sections.  We counted
4976          the number of dynamic symbols in elf_link_add_object_symbols.
4977          We will build the contents of .dynsym and .hash when we build
4978          the final symbol table, because until then we do not know the
4979          correct value to give the symbols.  We built the .dynstr
4980          section as we went along in elf_link_add_object_symbols.  */
4981       dynsymcount = elf_hash_table (info)->dynsymcount;
4982       s = bfd_get_section_by_name (dynobj, ".dynsym");
4983       BFD_ASSERT (s != NULL);
4984       s->_raw_size = dynsymcount * sizeof (Elf_External_Sym);
4985       s->contents = (bfd_byte *) bfd_alloc (output_bfd, s->_raw_size);
4986       if (s->contents == NULL && s->_raw_size != 0)
4987         {
4988           bfd_set_error (bfd_error_no_memory);
4989           return false;
4990         }
4991
4992       /* The first entry in .dynsym is a dummy symbol.  */
4993       isym.st_value = 0;
4994       isym.st_size = 0;
4995       isym.st_name = 0;
4996       isym.st_info = 0;
4997       isym.st_other = 0;
4998       isym.st_shndx = 0;
4999       elf_swap_symbol_out (output_bfd, &isym,
5000                            (Elf_External_Sym *) s->contents);
5001
5002       for (i = 0; elf_buckets[i] != 0; i++)
5003         {
5004           bucketcount = elf_buckets[i];
5005           if (dynsymcount < elf_buckets[i + 1])
5006             break;
5007         }
5008
5009       s = bfd_get_section_by_name (dynobj, ".hash");
5010       BFD_ASSERT (s != NULL);
5011       s->_raw_size = (2 + bucketcount + dynsymcount) * (ARCH_SIZE / 8);
5012       s->contents = (bfd_byte *) bfd_alloc (output_bfd, s->_raw_size);
5013       if (s->contents == NULL)
5014         {
5015           bfd_set_error (bfd_error_no_memory);
5016           return false;
5017         }
5018       memset (s->contents, 0, s->_raw_size);
5019
5020       put_word (output_bfd, bucketcount, s->contents);
5021       put_word (output_bfd, dynsymcount, s->contents + (ARCH_SIZE / 8));
5022
5023       elf_hash_table (info)->bucketcount = bucketcount;
5024
5025       s = bfd_get_section_by_name (dynobj, ".dynstr");
5026       BFD_ASSERT (s != NULL);
5027       s->_raw_size = _bfd_stringtab_size (elf_hash_table (info)->dynstr);
5028
5029       if (! elf_add_dynamic_entry (info, DT_NULL, 0))
5030         return false;
5031     }
5032
5033   return true;
5034 }
5035
5036 /* This routine is used to export all defined symbols into the dynamic
5037    symbol table.  It is called via elf_link_hash_traverse.  */
5038
5039 static boolean
5040 elf_export_symbol (h, data)
5041      struct elf_link_hash_entry *h;
5042      PTR data;
5043 {
5044   struct bfd_link_info *info = (struct bfd_link_info *) data;
5045
5046   if (h->dynindx == -1
5047       && (h->elf_link_hash_flags
5048           & (ELF_LINK_HASH_DEF_REGULAR | ELF_LINK_HASH_REF_REGULAR)) != 0)
5049     {
5050       if (! elf_link_record_dynamic_symbol (info, h))
5051         {
5052           /* FIXME: No way to report error.  */
5053           abort ();
5054         }
5055     }
5056
5057   return true;
5058 }
5059
5060 /* Make the backend pick a good value for a dynamic symbol.  This is
5061    called via elf_link_hash_traverse, and also calls itself
5062    recursively.  */
5063
5064 static boolean
5065 elf_adjust_dynamic_symbol (h, data)
5066      struct elf_link_hash_entry *h;
5067      PTR data;
5068 {
5069   struct bfd_link_info *info = (struct bfd_link_info *) data;
5070   bfd *dynobj;
5071   struct elf_backend_data *bed;
5072
5073   /* If this symbol does not require a PLT entry, and it is not
5074      defined by a dynamic object, or is not referenced by a regular
5075      object, ignore it.  FIXME: Do we need to worry about symbols
5076      which are defined by one dynamic object and referenced by another
5077      one?  */
5078   if ((h->elf_link_hash_flags & ELF_LINK_HASH_NEEDS_PLT) == 0
5079       && ((h->elf_link_hash_flags & ELF_LINK_HASH_DEF_REGULAR) != 0
5080           || (h->elf_link_hash_flags & ELF_LINK_HASH_DEF_DYNAMIC) == 0
5081           || (h->elf_link_hash_flags & ELF_LINK_HASH_REF_REGULAR) == 0))
5082     return true;
5083
5084   /* If we've already adjusted this symbol, don't do it again.  This
5085      can happen via a recursive call.  */
5086   if ((h->elf_link_hash_flags & ELF_LINK_HASH_DYNAMIC_ADJUSTED) != 0)
5087     return true;
5088
5089   /* Don't look at this symbol again.  Note that we must set this
5090      after checking the above conditions, because we may look at a
5091      symbol once, decide not to do anything, and then get called
5092      recursively later after REF_REGULAR is set below.  */
5093   h->elf_link_hash_flags |= ELF_LINK_HASH_DYNAMIC_ADJUSTED;
5094
5095   /* If this is a weak definition, and we know a real definition, and
5096      the real symbol is not itself defined by a regular object file,
5097      then get a good value for the real definition.  We handle the
5098      real symbol first, for the convenience of the backend routine.
5099
5100      Note that there is a confusing case here.  If the real definition
5101      is defined by a regular object file, we don't get the real symbol
5102      from the dynamic object, but we do get the weak symbol.  If the
5103      processor backend uses a COPY reloc, then if some routine in the
5104      dynamic object changes the real symbol, we will not see that
5105      change in the corresponding weak symbol.  This is the way other
5106      ELF linkers work as well, and seems to be a result of the shared
5107      library model.
5108
5109      I will clarify this issue.  Most SVR4 shared libraries define the
5110      variable _timezone and define timezone as a weak synonym.  The
5111      tzset call changes _timezone.  If you write
5112        extern int timezone;
5113        int _timezone = 5;
5114        int main () { tzset (); printf ("%d %d\n", timezone, _timezone); }
5115      you might expect that, since timezone is a synonym for _timezone,
5116      the same number will print both times.  However, if the processor
5117      backend uses a COPY reloc, then actually timezone will be copied
5118      into your process image, and, since you define _timezone
5119      yourself, _timezone will not.  Thus timezone and _timezone will
5120      wind up at different memory locations.  The tzset call will set
5121      _timezone, leaving timezone unchanged.  */
5122
5123   if (h->weakdef != NULL)
5124     {
5125       struct elf_link_hash_entry *weakdef;
5126
5127       BFD_ASSERT (h->root.type == bfd_link_hash_defined);
5128       weakdef = h->weakdef;
5129       BFD_ASSERT (weakdef->root.type == bfd_link_hash_defined);
5130       BFD_ASSERT (weakdef->elf_link_hash_flags & ELF_LINK_HASH_DEF_DYNAMIC);
5131       if ((weakdef->elf_link_hash_flags & ELF_LINK_HASH_DEF_REGULAR) != 0)
5132         {
5133           /* This symbol is defined by a regular object file, so we
5134              will not do anything special.  Clear weakdef for the
5135              convenience of the processor backend.  */
5136           h->weakdef = NULL;
5137         }
5138       else
5139         {
5140           /* There is an implicit reference by a regular object file
5141              via the weak symbol.  */
5142           weakdef->elf_link_hash_flags |= ELF_LINK_HASH_REF_REGULAR;
5143           if (! elf_adjust_dynamic_symbol (weakdef, (PTR) info))
5144             return false;
5145         }
5146     }
5147
5148   dynobj = elf_hash_table (info)->dynobj;
5149   bed = get_elf_backend_data (dynobj);
5150   if (! (*bed->elf_backend_adjust_dynamic_symbol) (info, h))
5151     {
5152       /* FIXME: No way to return error.  */
5153       abort ();
5154     }
5155
5156   return true;
5157 }
5158 \f
5159 /* Final phase of ELF linker.  */
5160
5161 /* A structure we use to avoid passing large numbers of arguments.  */
5162
5163 struct elf_final_link_info
5164 {
5165   /* General link information.  */
5166   struct bfd_link_info *info;
5167   /* Output BFD.  */
5168   bfd *output_bfd;
5169   /* Symbol string table.  */
5170   struct bfd_strtab_hash *symstrtab;
5171   /* .dynsym section.  */
5172   asection *dynsym_sec;
5173   /* .hash section.  */
5174   asection *hash_sec;
5175   /* Buffer large enough to hold contents of any section.  */
5176   bfd_byte *contents;
5177   /* Buffer large enough to hold external relocs of any section.  */
5178   PTR external_relocs;
5179   /* Buffer large enough to hold internal relocs of any section.  */
5180   Elf_Internal_Rela *internal_relocs;
5181   /* Buffer large enough to hold external local symbols of any input
5182      BFD.  */
5183   Elf_External_Sym *external_syms;
5184   /* Buffer large enough to hold internal local symbols of any input
5185      BFD.  */
5186   Elf_Internal_Sym *internal_syms;
5187   /* Array large enough to hold a symbol index for each local symbol
5188      of any input BFD.  */
5189   long *indices;
5190   /* Array large enough to hold a section pointer for each local
5191      symbol of any input BFD.  */
5192   asection **sections;
5193   /* Buffer to hold swapped out symbols.  */
5194   Elf_External_Sym *symbuf;
5195   /* Number of swapped out symbols in buffer.  */
5196   size_t symbuf_count;
5197   /* Number of symbols which fit in symbuf.  */
5198   size_t symbuf_size;
5199 };
5200
5201 static boolean elf_link_output_sym
5202   PARAMS ((struct elf_final_link_info *, const char *,
5203            Elf_Internal_Sym *, asection *));
5204 static boolean elf_link_flush_output_syms
5205   PARAMS ((struct elf_final_link_info *));
5206 static boolean elf_link_output_extsym
5207   PARAMS ((struct elf_link_hash_entry *, PTR));
5208 static boolean elf_link_input_bfd
5209   PARAMS ((struct elf_final_link_info *, bfd *));
5210 static boolean elf_reloc_link_order
5211   PARAMS ((bfd *, struct bfd_link_info *, asection *,
5212            struct bfd_link_order *));
5213
5214 /* Do the final step of an ELF link.  */
5215
5216 boolean
5217 elf_bfd_final_link (abfd, info)
5218      bfd *abfd;
5219      struct bfd_link_info *info;
5220 {
5221   boolean dynamic;
5222   bfd *dynobj;
5223   struct elf_final_link_info finfo;
5224   register asection *o;
5225   register struct bfd_link_order *p;
5226   register bfd *sub;
5227   size_t max_contents_size;
5228   size_t max_external_reloc_size;
5229   size_t max_internal_reloc_count;
5230   size_t max_sym_count;
5231   file_ptr off;
5232   Elf_Internal_Sym elfsym;
5233   unsigned int i;
5234   Elf_Internal_Shdr *symtab_hdr;
5235   Elf_Internal_Shdr *symstrtab_hdr;
5236   struct elf_backend_data *bed = get_elf_backend_data (abfd);
5237
5238   if (info->shared)
5239     abfd->flags |= DYNAMIC;
5240
5241   dynamic = elf_hash_table (info)->dynamic_sections_created;
5242   dynobj = elf_hash_table (info)->dynobj;
5243
5244   finfo.info = info;
5245   finfo.output_bfd = abfd;
5246   finfo.symstrtab = elf_stringtab_init ();
5247   if (finfo.symstrtab == NULL)
5248     return false;
5249   if (! dynamic)
5250     {
5251       finfo.dynsym_sec = NULL;
5252       finfo.hash_sec = NULL;
5253     }
5254   else
5255     {
5256       finfo.dynsym_sec = bfd_get_section_by_name (dynobj, ".dynsym");
5257       finfo.hash_sec = bfd_get_section_by_name (dynobj, ".hash");
5258       if (finfo.dynsym_sec == NULL
5259           || finfo.hash_sec == NULL)
5260         abort ();
5261     }
5262   finfo.contents = NULL;
5263   finfo.external_relocs = NULL;
5264   finfo.internal_relocs = NULL;
5265   finfo.external_syms = NULL;
5266   finfo.internal_syms = NULL;
5267   finfo.indices = NULL;
5268   finfo.sections = NULL;
5269   finfo.symbuf = NULL;
5270   finfo.symbuf_count = 0;
5271
5272   /* Count up the number of relocations we will output for each output
5273      section, so that we know the sizes of the reloc sections.  We
5274      also figure out some maximum sizes.  */
5275   max_contents_size = 0;
5276   max_external_reloc_size = 0;
5277   max_internal_reloc_count = 0;
5278   max_sym_count = 0;
5279   for (o = abfd->sections; o != (asection *) NULL; o = o->next)
5280     {
5281       o->reloc_count = 0;
5282
5283       for (p = o->link_order_head; p != NULL; p = p->next)
5284         {
5285           if (p->type == bfd_section_reloc_link_order
5286               || p->type == bfd_symbol_reloc_link_order)
5287             ++o->reloc_count;
5288           else if (p->type == bfd_indirect_link_order)
5289             {
5290               asection *sec;
5291
5292               sec = p->u.indirect.section;
5293
5294               if (info->relocateable)
5295                 o->reloc_count += sec->reloc_count;
5296
5297               if (sec->_raw_size > max_contents_size)
5298                 max_contents_size = sec->_raw_size;
5299               if (sec->_cooked_size > max_contents_size)
5300                 max_contents_size = sec->_cooked_size;
5301
5302               /* We are interested in just local symbols, not all
5303                  symbols.  */
5304               if (bfd_get_flavour (sec->owner) == bfd_target_elf_flavour)
5305                 {
5306                   size_t sym_count;
5307
5308                   if (elf_bad_symtab (sec->owner))
5309                     sym_count = (elf_tdata (sec->owner)->symtab_hdr.sh_size
5310                                  / sizeof (Elf_External_Sym));
5311                   else
5312                     sym_count = elf_tdata (sec->owner)->symtab_hdr.sh_info;
5313
5314                   if (sym_count > max_sym_count)
5315                     max_sym_count = sym_count;
5316
5317                   if ((sec->flags & SEC_RELOC) != 0)
5318                     {
5319                       size_t ext_size;
5320
5321                       ext_size = elf_section_data (sec)->rel_hdr.sh_size;
5322                       if (ext_size > max_external_reloc_size)
5323                         max_external_reloc_size = ext_size;
5324                       if (sec->reloc_count > max_internal_reloc_count)
5325                         max_internal_reloc_count = sec->reloc_count;
5326                     }
5327                 }
5328             }
5329         }
5330
5331       if (o->reloc_count > 0)
5332         o->flags |= SEC_RELOC;
5333       else
5334         {
5335           /* Explicitly clear the SEC_RELOC flag.  The linker tends to
5336              set it (this is probably a bug) and if it is set
5337              assign_section_numbers will create a reloc section.  */
5338           o->flags &=~ SEC_RELOC;
5339         }
5340
5341       /* If the SEC_ALLOC flag is not set, force the section VMA to
5342          zero.  This is done in elf_fake_sections as well, but forcing
5343          the VMA to 0 here will ensure that relocs against these
5344          sections are handled correctly.  */
5345       if ((o->flags & SEC_ALLOC) == 0)
5346         o->vma = 0;
5347     }
5348
5349   /* Figure out the file positions for everything but the symbol table
5350      and the relocs.  We set symcount to force assign_section_numbers
5351      to create a symbol table.  */
5352   abfd->symcount = info->strip == strip_all ? 0 : 1;
5353   BFD_ASSERT (! abfd->output_has_begun);
5354   if (! elf_compute_section_file_positions (abfd, info))
5355     goto error_return;
5356
5357   /* That created the reloc sections.  Set their sizes, and assign
5358      them file positions, and allocate some buffers.  */
5359   for (o = abfd->sections; o != NULL; o = o->next)
5360     {
5361       if ((o->flags & SEC_RELOC) != 0)
5362         {
5363           Elf_Internal_Shdr *rel_hdr;
5364           register struct elf_link_hash_entry **p, **pend;
5365
5366           rel_hdr = &elf_section_data (o)->rel_hdr;
5367
5368           rel_hdr->sh_size = rel_hdr->sh_entsize * o->reloc_count;
5369
5370           /* The contents field must last into write_object_contents,
5371              so we allocate it with bfd_alloc rather than malloc.  */
5372           rel_hdr->contents = (PTR) bfd_alloc (abfd, rel_hdr->sh_size);
5373           if (rel_hdr->contents == NULL && rel_hdr->sh_size != 0)
5374             {
5375               bfd_set_error (bfd_error_no_memory);
5376               goto error_return;
5377             }
5378
5379           p = ((struct elf_link_hash_entry **)
5380                malloc (o->reloc_count
5381                        * sizeof (struct elf_link_hash_entry *)));
5382           if (p == NULL && o->reloc_count != 0)
5383             {
5384               bfd_set_error (bfd_error_no_memory);
5385               goto error_return;
5386             }
5387           elf_section_data (o)->rel_hashes = p;
5388           pend = p + o->reloc_count;
5389           for (; p < pend; p++)
5390             *p = NULL;
5391
5392           /* Use the reloc_count field as an index when outputting the
5393              relocs.  */
5394           o->reloc_count = 0;
5395         }
5396     }
5397
5398   assign_file_positions_for_relocs (abfd);
5399
5400   /* We have now assigned file positions for all the sections except
5401      .symtab and .strtab.  We start the .symtab section at the current
5402      file position, and write directly to it.  We build the .strtab
5403      section in memory.  When we add .dynsym support, we will build
5404      that in memory as well (.dynsym is smaller than .symtab).  */
5405   abfd->symcount = 0;
5406   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
5407   /* sh_name is set in prep_headers.  */
5408   symtab_hdr->sh_type = SHT_SYMTAB;
5409   symtab_hdr->sh_flags = 0;
5410   symtab_hdr->sh_addr = 0;
5411   symtab_hdr->sh_size = 0;
5412   symtab_hdr->sh_entsize = sizeof (Elf_External_Sym);
5413   /* sh_link is set in assign_section_numbers.  */
5414   /* sh_info is set below.  */
5415   /* sh_offset is set just below.  */
5416   symtab_hdr->sh_addralign = 4;  /* FIXME: system dependent?  */
5417
5418   off = elf_tdata (abfd)->next_file_pos;
5419   off = assign_file_position_for_section (symtab_hdr, off, true);
5420
5421   /* Note that at this point elf_tdata (abfd)->next_file_pos is
5422      incorrect.  We do not yet know the size of the .symtab section.
5423      We correct next_file_pos below, after we do know the size.  */
5424
5425   /* Allocate a buffer to hold swapped out symbols.  This is to avoid
5426      continuously seeking to the right position in the file.  */
5427   if (! info->keep_memory || max_sym_count < 20)
5428     finfo.symbuf_size = 20;
5429   else
5430     finfo.symbuf_size = max_sym_count;
5431   finfo.symbuf = ((Elf_External_Sym *)
5432                   malloc (finfo.symbuf_size * sizeof (Elf_External_Sym)));
5433   if (finfo.symbuf == NULL)
5434     {
5435       bfd_set_error (bfd_error_no_memory);
5436       goto error_return;
5437     }
5438
5439   /* Start writing out the symbol table.  The first symbol is always a
5440      dummy symbol.  */
5441   elfsym.st_value = 0;
5442   elfsym.st_size = 0;
5443   elfsym.st_info = 0;
5444   elfsym.st_other = 0;
5445   elfsym.st_shndx = SHN_UNDEF;
5446   if (! elf_link_output_sym (&finfo, (const char *) NULL,
5447                              &elfsym, bfd_und_section_ptr))
5448     goto error_return;
5449
5450 #if 0
5451   /* Some standard ELF linkers do this, but we don't because it causes
5452      bootstrap comparison failures.  */
5453   /* Output a file symbol for the output file as the second symbol.
5454      We output this even if we are discarding local symbols, although
5455      I'm not sure if this is correct.  */
5456   elfsym.st_value = 0;
5457   elfsym.st_size = 0;
5458   elfsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
5459   elfsym.st_other = 0;
5460   elfsym.st_shndx = SHN_ABS;
5461   if (! elf_link_output_sym (&finfo, bfd_get_filename (abfd),
5462                              &elfsym, bfd_abs_section_ptr))
5463     goto error_return;
5464 #endif
5465
5466   /* Output a symbol for each section.  We output these even if we are
5467      discarding local symbols, since they are used for relocs.  These
5468      symbols have no names.  We store the index of each one in the
5469      index field of the section, so that we can find it again when
5470      outputting relocs.  */
5471   elfsym.st_value = 0;
5472   elfsym.st_size = 0;
5473   elfsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
5474   elfsym.st_other = 0;
5475   for (i = 1; i < elf_elfheader (abfd)->e_shnum; i++)
5476     {
5477       o = section_from_elf_index (abfd, i);
5478       if (o != NULL)
5479         o->target_index = abfd->symcount;
5480       elfsym.st_shndx = i;
5481       if (! elf_link_output_sym (&finfo, (const char *) NULL,
5482                                  &elfsym, o))
5483         goto error_return;
5484     }
5485
5486   /* Allocate some memory to hold information read in from the input
5487      files.  */
5488   finfo.contents = (bfd_byte *) malloc (max_contents_size);
5489   finfo.external_relocs = (PTR) malloc (max_external_reloc_size);
5490   finfo.internal_relocs = ((Elf_Internal_Rela *)
5491                            malloc (max_internal_reloc_count
5492                                    * sizeof (Elf_Internal_Rela)));
5493   finfo.external_syms = ((Elf_External_Sym *)
5494                          malloc (max_sym_count * sizeof (Elf_External_Sym)));
5495   finfo.internal_syms = ((Elf_Internal_Sym *)
5496                          malloc (max_sym_count * sizeof (Elf_Internal_Sym)));
5497   finfo.indices = (long *) malloc (max_sym_count * sizeof (long));
5498   finfo.sections = (asection **) malloc (max_sym_count * sizeof (asection *));
5499   if ((finfo.contents == NULL && max_contents_size != 0)
5500       || (finfo.external_relocs == NULL && max_external_reloc_size != 0)
5501       || (finfo.internal_relocs == NULL && max_internal_reloc_count != 0)
5502       || (finfo.external_syms == NULL && max_sym_count != 0)
5503       || (finfo.internal_syms == NULL && max_sym_count != 0)
5504       || (finfo.indices == NULL && max_sym_count != 0)
5505       || (finfo.sections == NULL && max_sym_count != 0))
5506     {
5507       bfd_set_error (bfd_error_no_memory);
5508       goto error_return;
5509     }
5510
5511   /* Since ELF permits relocations to be against local symbols, we
5512      must have the local symbols available when we do the relocations.
5513      Since we would rather only read the local symbols once, and we
5514      would rather not keep them in memory, we handle all the
5515      relocations for a single input file at the same time.
5516
5517      Unfortunately, there is no way to know the total number of local
5518      symbols until we have seen all of them, and the local symbol
5519      indices precede the global symbol indices.  This means that when
5520      we are generating relocateable output, and we see a reloc against
5521      a global symbol, we can not know the symbol index until we have
5522      finished examining all the local symbols to see which ones we are
5523      going to output.  To deal with this, we keep the relocations in
5524      memory, and don't output them until the end of the link.  This is
5525      an unfortunate waste of memory, but I don't see a good way around
5526      it.  Fortunately, it only happens when performing a relocateable
5527      link, which is not the common case.  FIXME: If keep_memory is set
5528      we could write the relocs out and then read them again; I don't
5529      know how bad the memory loss will be.  */
5530
5531   for (sub = info->input_bfds; sub != NULL; sub = sub->next)
5532     sub->output_has_begun = false;
5533   for (o = abfd->sections; o != NULL; o = o->next)
5534     {
5535       for (p = o->link_order_head; p != NULL; p = p->next)
5536         {
5537           if (p->type == bfd_indirect_link_order
5538               && (bfd_get_flavour (p->u.indirect.section->owner)
5539                   == bfd_target_elf_flavour))
5540             {
5541               sub = p->u.indirect.section->owner;
5542               if (! sub->output_has_begun)
5543                 {
5544                   if (! elf_link_input_bfd (&finfo, sub))
5545                     goto error_return;
5546                   sub->output_has_begun = true;
5547                 }
5548             }
5549           else if (p->type == bfd_section_reloc_link_order
5550                    || p->type == bfd_symbol_reloc_link_order)
5551             {
5552               if (! elf_reloc_link_order (abfd, info, o, p))
5553                 goto error_return;
5554             }
5555           else
5556             {
5557               if (! _bfd_default_link_order (abfd, info, o, p))
5558                 goto error_return;
5559             }
5560         }
5561     }
5562
5563   /* That wrote out all the local symbols.  Finish up the symbol table
5564      with the global symbols.  */
5565
5566   /* The sh_info field records the index of the first non local
5567      symbol.  */
5568   symtab_hdr->sh_info = abfd->symcount;
5569   if (dynamic)
5570     elf_section_data (finfo.dynsym_sec->output_section)->this_hdr.sh_info = 1;
5571
5572   /* We get the global symbols from the hash table.  */
5573   elf_link_hash_traverse (elf_hash_table (info), elf_link_output_extsym,
5574                           (PTR) &finfo);
5575
5576   /* Flush all symbols to the file.  */
5577   if (! elf_link_flush_output_syms (&finfo))
5578     return false;
5579
5580   /* Now we know the size of the symtab section.  */
5581   off += symtab_hdr->sh_size;
5582
5583   /* Finish up and write out the symbol string table (.strtab)
5584      section.  */
5585   symstrtab_hdr = &elf_tdata (abfd)->strtab_hdr;
5586   /* sh_name was set in prep_headers.  */
5587   symstrtab_hdr->sh_type = SHT_STRTAB;
5588   symstrtab_hdr->sh_flags = 0;
5589   symstrtab_hdr->sh_addr = 0;
5590   symstrtab_hdr->sh_size = _bfd_stringtab_size (finfo.symstrtab);
5591   symstrtab_hdr->sh_entsize = 0;
5592   symstrtab_hdr->sh_link = 0;
5593   symstrtab_hdr->sh_info = 0;
5594   /* sh_offset is set just below.  */
5595   symstrtab_hdr->sh_addralign = 1;
5596
5597   off = assign_file_position_for_section (symstrtab_hdr, off, true);
5598   elf_tdata (abfd)->next_file_pos = off;
5599
5600   if (bfd_seek (abfd, symstrtab_hdr->sh_offset, SEEK_SET) != 0
5601       || ! _bfd_stringtab_emit (abfd, finfo.symstrtab))
5602     return false;
5603
5604   /* Adjust the relocs to have the correct symbol indices.  */
5605   for (o = abfd->sections; o != NULL; o = o->next)
5606     {
5607       struct elf_link_hash_entry **rel_hash;
5608       Elf_Internal_Shdr *rel_hdr;
5609
5610       if ((o->flags & SEC_RELOC) == 0)
5611         continue;
5612
5613       rel_hash = elf_section_data (o)->rel_hashes;
5614       rel_hdr = &elf_section_data (o)->rel_hdr;
5615       for (i = 0; i < o->reloc_count; i++, rel_hash++)
5616         {
5617           if (*rel_hash == NULL)
5618             continue;
5619               
5620           BFD_ASSERT ((*rel_hash)->indx >= 0);
5621
5622           if (rel_hdr->sh_entsize == sizeof (Elf_External_Rel))
5623             {
5624               Elf_External_Rel *erel;
5625               Elf_Internal_Rel irel;
5626
5627               erel = (Elf_External_Rel *) rel_hdr->contents + i;
5628               elf_swap_reloc_in (abfd, erel, &irel);
5629               irel.r_info = ELF_R_INFO ((*rel_hash)->indx,
5630                                         ELF_R_TYPE (irel.r_info));
5631               elf_swap_reloc_out (abfd, &irel, erel);
5632             }
5633           else
5634             {
5635               Elf_External_Rela *erela;
5636               Elf_Internal_Rela irela;
5637
5638               BFD_ASSERT (rel_hdr->sh_entsize
5639                           == sizeof (Elf_External_Rela));
5640
5641               erela = (Elf_External_Rela *) rel_hdr->contents + i;
5642               elf_swap_reloca_in (abfd, erela, &irela);
5643               irela.r_info = ELF_R_INFO ((*rel_hash)->indx,
5644                                          ELF_R_TYPE (irela.r_info));
5645               elf_swap_reloca_out (abfd, &irela, erela);
5646             }
5647         }
5648
5649       /* Set the reloc_count field to 0 to prevent write_relocs from
5650          trying to swap the relocs out itself.  */
5651       o->reloc_count = 0;
5652     }
5653
5654   /* If we are linking against a dynamic object, or generating a
5655      shared library, finish up the dynamic linking information.  */
5656   if (dynamic)
5657     {
5658       Elf_External_Dyn *dyncon, *dynconend;
5659
5660       /* Fix up .dynamic entries.  */
5661       o = bfd_get_section_by_name (dynobj, ".dynamic");
5662       BFD_ASSERT (o != NULL);
5663
5664       dyncon = (Elf_External_Dyn *) o->contents;
5665       dynconend = (Elf_External_Dyn *) (o->contents + o->_raw_size);
5666       for (; dyncon < dynconend; dyncon++)
5667         {
5668           Elf_Internal_Dyn dyn;
5669           const char *name;
5670           unsigned int type;
5671
5672           elf_swap_dyn_in (dynobj, dyncon, &dyn);
5673
5674           switch (dyn.d_tag)
5675             {
5676             default:
5677               break;
5678
5679               /* SVR4 linkers seem to set DT_INIT and DT_FINI based on
5680                  magic _init and _fini symbols.  This is pretty ugly,
5681                  but we are compatible.  */
5682             case DT_INIT:
5683               name = "_init";
5684               goto get_sym;
5685             case DT_FINI:
5686               name = "_fini";
5687             get_sym:
5688               {
5689                 struct elf_link_hash_entry *h;
5690
5691                 h = elf_link_hash_lookup (elf_hash_table (info), name,
5692                                           false, false, true);
5693                 BFD_ASSERT (h != NULL);
5694                 if (h->root.type == bfd_link_hash_defined)
5695                   {
5696                     dyn.d_un.d_val = h->root.u.def.value;
5697                     o = h->root.u.def.section;
5698                     if (o->output_section != NULL)
5699                       dyn.d_un.d_val += (o->output_section->vma
5700                                          + o->output_offset);
5701                     else
5702                       dyn.d_un.d_val += o->vma;
5703                   }
5704                 elf_swap_dyn_out (dynobj, &dyn, dyncon);
5705               }
5706               break;
5707
5708             case DT_HASH:
5709               name = ".hash";
5710               goto get_vma;
5711             case DT_STRTAB:
5712               name = ".dynstr";
5713               goto get_vma;
5714             case DT_SYMTAB:
5715               name = ".dynsym";
5716             get_vma:
5717               o = bfd_get_section_by_name (abfd, name);
5718               BFD_ASSERT (o != NULL);
5719               dyn.d_un.d_ptr = o->vma;
5720               elf_swap_dyn_out (dynobj, &dyn, dyncon);
5721               break;
5722
5723             case DT_REL:
5724             case DT_RELA:
5725             case DT_RELSZ:
5726             case DT_RELASZ:
5727               if (dyn.d_tag == DT_REL || dyn.d_tag == DT_RELSZ)
5728                 type = SHT_REL;
5729               else
5730                 type = SHT_RELA;
5731               dyn.d_un.d_val = 0;
5732               for (i = 1; i < elf_elfheader (abfd)->e_shnum; i++)
5733                 {
5734                   Elf_Internal_Shdr *hdr;
5735
5736                   hdr = elf_elfsections (abfd)[i];
5737                   if (hdr->sh_type == type
5738                       && (hdr->sh_flags & SHF_ALLOC) != 0)
5739                     {
5740                       if (dyn.d_tag == DT_RELSZ || dyn.d_tag == DT_RELASZ)
5741                         dyn.d_un.d_val += hdr->sh_size;
5742                       else
5743                         {
5744                           if (dyn.d_un.d_val == 0
5745                               || hdr->sh_addr < dyn.d_un.d_val)
5746                             dyn.d_un.d_val = hdr->sh_addr;
5747                         }
5748                     }
5749                 }
5750               elf_swap_dyn_out (dynobj, &dyn, dyncon);
5751               break;
5752             }
5753         }
5754     }
5755
5756   /* If we have created any dynamic sections, then output them.  */
5757   if (dynobj != NULL)
5758     {
5759       if (! (*bed->elf_backend_finish_dynamic_sections) (abfd, info))
5760         goto error_return;
5761
5762       for (o = dynobj->sections; o != NULL; o = o->next)
5763         {
5764           if ((o->flags & SEC_HAS_CONTENTS) == 0
5765               || o->_raw_size == 0)
5766             continue;
5767           if ((o->flags & SEC_IN_MEMORY) == 0)
5768             {
5769               /* At this point, we are only interested in sections
5770                  created by elf_link_create_dynamic_sections.  FIXME:
5771                  This test is fragile.  */
5772               continue;
5773             }
5774           if ((elf_section_data (o->output_section)->this_hdr.sh_type
5775                != SHT_STRTAB)
5776               || strcmp (bfd_get_section_name (abfd, o), ".dynstr") != 0)
5777             {
5778               if (! bfd_set_section_contents (abfd, o->output_section,
5779                                               o->contents, o->output_offset,
5780                                               o->_raw_size))
5781                 goto error_return;
5782             }
5783           else
5784             {
5785               file_ptr off;
5786
5787               /* The contents of the .dynstr section are actually in a
5788                  stringtab.  */
5789               off = elf_section_data (o->output_section)->this_hdr.sh_offset;
5790               if (bfd_seek (abfd, off, SEEK_SET) != 0
5791                   || ! _bfd_stringtab_emit (abfd,
5792                                             elf_hash_table (info)->dynstr))
5793                 goto error_return;
5794             }
5795         }
5796     }
5797
5798   if (finfo.symstrtab != NULL)
5799     _bfd_stringtab_free (finfo.symstrtab);
5800   if (finfo.contents != NULL)
5801     free (finfo.contents);
5802   if (finfo.external_relocs != NULL)
5803     free (finfo.external_relocs);
5804   if (finfo.internal_relocs != NULL)
5805     free (finfo.internal_relocs);
5806   if (finfo.external_syms != NULL)
5807     free (finfo.external_syms);
5808   if (finfo.internal_syms != NULL)
5809     free (finfo.internal_syms);
5810   if (finfo.indices != NULL)
5811     free (finfo.indices);
5812   if (finfo.sections != NULL)
5813     free (finfo.sections);
5814   if (finfo.symbuf != NULL)
5815     free (finfo.symbuf);
5816   for (o = abfd->sections; o != NULL; o = o->next)
5817     {
5818       if ((o->flags & SEC_RELOC) != 0
5819           && elf_section_data (o)->rel_hashes != NULL)
5820         free (elf_section_data (o)->rel_hashes);
5821     }
5822
5823   elf_tdata (abfd)->linker = true;
5824
5825   return true;
5826
5827  error_return:
5828   if (finfo.symstrtab != NULL)
5829     _bfd_stringtab_free (finfo.symstrtab);
5830   if (finfo.contents != NULL)
5831     free (finfo.contents);
5832   if (finfo.external_relocs != NULL)
5833     free (finfo.external_relocs);
5834   if (finfo.internal_relocs != NULL)
5835     free (finfo.internal_relocs);
5836   if (finfo.external_syms != NULL)
5837     free (finfo.external_syms);
5838   if (finfo.internal_syms != NULL)
5839     free (finfo.internal_syms);
5840   if (finfo.indices != NULL)
5841     free (finfo.indices);
5842   if (finfo.sections != NULL)
5843     free (finfo.sections);
5844   if (finfo.symbuf != NULL)
5845     free (finfo.symbuf);
5846   for (o = abfd->sections; o != NULL; o = o->next)
5847     {
5848       if ((o->flags & SEC_RELOC) != 0
5849           && elf_section_data (o)->rel_hashes != NULL)
5850         free (elf_section_data (o)->rel_hashes);
5851     }
5852
5853   return false;
5854 }
5855
5856 /* Add a symbol to the output symbol table.  */
5857
5858 static boolean
5859 elf_link_output_sym (finfo, name, elfsym, input_sec)
5860      struct elf_final_link_info *finfo;
5861      const char *name;
5862      Elf_Internal_Sym *elfsym;
5863      asection *input_sec;
5864 {
5865   boolean (*output_symbol_hook) PARAMS ((bfd *,
5866                                          struct bfd_link_info *info,
5867                                          const char *,
5868                                          Elf_Internal_Sym *,
5869                                          asection *));
5870
5871   output_symbol_hook = get_elf_backend_data (finfo->output_bfd)->
5872     elf_backend_link_output_symbol_hook;
5873   if (output_symbol_hook != NULL)
5874     {
5875       if (! ((*output_symbol_hook)
5876              (finfo->output_bfd, finfo->info, name, elfsym, input_sec)))
5877         return false;
5878     }
5879
5880   if (name == (const char *) NULL || *name == '\0')
5881     elfsym->st_name = 0;
5882   else
5883     {
5884       elfsym->st_name = (unsigned long) _bfd_stringtab_add (finfo->symstrtab,
5885                                                             name, true,
5886                                                             false);
5887       if (elfsym->st_name == (unsigned long) -1)
5888         return false;
5889     }
5890
5891   if (finfo->symbuf_count >= finfo->symbuf_size)
5892     {
5893       if (! elf_link_flush_output_syms (finfo))
5894         return false;
5895     }
5896
5897   elf_swap_symbol_out (finfo->output_bfd, elfsym,
5898                        finfo->symbuf + finfo->symbuf_count);
5899   ++finfo->symbuf_count;
5900
5901   ++finfo->output_bfd->symcount;
5902
5903   return true;
5904 }
5905
5906 /* Flush the output symbols to the file.  */
5907
5908 static boolean
5909 elf_link_flush_output_syms (finfo)
5910      struct elf_final_link_info *finfo;
5911 {
5912   Elf_Internal_Shdr *symtab;
5913
5914   symtab = &elf_tdata (finfo->output_bfd)->symtab_hdr;
5915
5916   if (bfd_seek (finfo->output_bfd, symtab->sh_offset + symtab->sh_size,
5917                 SEEK_SET) != 0
5918       || (bfd_write ((PTR) finfo->symbuf, finfo->symbuf_count,
5919                      sizeof (Elf_External_Sym), finfo->output_bfd)
5920           != finfo->symbuf_count * sizeof (Elf_External_Sym)))
5921     return false;
5922
5923   symtab->sh_size += finfo->symbuf_count * sizeof (Elf_External_Sym);
5924
5925   finfo->symbuf_count = 0;
5926
5927   return true;
5928 }
5929
5930 /* Add an external symbol to the symbol table.  This is called from
5931    the hash table traversal routine.  */
5932
5933 static boolean
5934 elf_link_output_extsym (h, data)
5935      struct elf_link_hash_entry *h;
5936      PTR data;
5937 {
5938   struct elf_final_link_info *finfo = (struct elf_final_link_info *) data;
5939   boolean strip;
5940   Elf_Internal_Sym sym;
5941   asection *input_sec;
5942
5943   /* We don't want to output symbols that have never been mentioned by
5944      a regular file, or that we have been told to strip.  However, if
5945      h->indx is set to -2, the symbol is used by a reloc and we must
5946      output it.  */
5947   if (h->indx == -2)
5948     strip = false;
5949   else if (((h->elf_link_hash_flags & ELF_LINK_HASH_DEF_DYNAMIC) != 0
5950             || (h->elf_link_hash_flags & ELF_LINK_HASH_REF_DYNAMIC) != 0)
5951            && (h->elf_link_hash_flags & ELF_LINK_HASH_DEF_REGULAR) == 0
5952            && (h->elf_link_hash_flags & ELF_LINK_HASH_REF_REGULAR) == 0)
5953     strip = true;
5954   else if (finfo->info->strip == strip_all
5955            || (finfo->info->strip == strip_some
5956                && bfd_hash_lookup (finfo->info->keep_hash,
5957                                    h->root.root.string,
5958                                    false, false) == NULL))
5959     strip = true;
5960   else
5961     strip = false;
5962
5963   /* If we're stripping it, and it's not a dynamic symbol, there's
5964      nothing else to do.  */
5965   if (strip && h->dynindx == -1)
5966     return true;
5967
5968   sym.st_value = 0;
5969   sym.st_size = h->size;
5970   sym.st_other = 0;
5971   if (h->root.type == bfd_link_hash_weak
5972       || (h->elf_link_hash_flags & ELF_LINK_HASH_DEFINED_WEAK) != 0)
5973     sym.st_info = ELF_ST_INFO (STB_WEAK, h->type);
5974   else
5975     sym.st_info = ELF_ST_INFO (STB_GLOBAL, h->type);
5976
5977   switch (h->root.type)
5978     {
5979     default:
5980     case bfd_link_hash_new:
5981       abort ();
5982       return false;
5983
5984     case bfd_link_hash_undefined:
5985       input_sec = bfd_und_section_ptr;
5986       sym.st_shndx = SHN_UNDEF;
5987       break;
5988
5989     case bfd_link_hash_weak:
5990       input_sec = bfd_und_section_ptr;
5991       sym.st_shndx = SHN_UNDEF;
5992       break;
5993
5994     case bfd_link_hash_defined:
5995       {
5996         input_sec = h->root.u.def.section;
5997         if (input_sec->output_section != NULL)
5998           {
5999             sym.st_shndx =
6000               elf_section_from_bfd_section (finfo->output_bfd,
6001                                             input_sec->output_section);
6002             if (sym.st_shndx == (unsigned short) -1)
6003               {
6004                 /* FIXME: No way to handle errors.  */
6005                 abort ();
6006               }
6007
6008             /* ELF symbols in relocateable files are section relative,
6009                but in nonrelocateable files they are virtual
6010                addresses.  */
6011             sym.st_value = h->root.u.def.value + input_sec->output_offset;
6012             if (! finfo->info->relocateable)
6013               sym.st_value += input_sec->output_section->vma;
6014           }
6015         else
6016           {
6017             BFD_ASSERT ((bfd_get_flavour (input_sec->owner)
6018                          == bfd_target_elf_flavour)
6019                         && elf_elfheader (input_sec->owner)->e_type == ET_DYN);
6020             sym.st_shndx = SHN_UNDEF;
6021             input_sec = bfd_und_section_ptr;
6022           }
6023       }
6024       break;
6025
6026     case bfd_link_hash_common:
6027       input_sec = bfd_com_section_ptr;
6028       sym.st_shndx = SHN_COMMON;
6029       sym.st_value = 1 << h->root.u.c.alignment_power;
6030       break;
6031
6032     case bfd_link_hash_indirect:
6033     case bfd_link_hash_warning:
6034       /* I have no idea how these should be handled.  */
6035       return true;
6036     }
6037
6038   /* If this symbol should be put in the .dynsym section, then put it
6039      there now.  We have already know the symbol index.  We also fill
6040      in the entry in the .hash section.  */
6041   if (h->dynindx != -1
6042       && elf_hash_table (finfo->info)->dynamic_sections_created)
6043     {
6044       struct elf_backend_data *bed;
6045       size_t bucketcount;
6046       size_t bucket;
6047       bfd_byte *bucketpos;
6048       bfd_vma chain;
6049
6050       sym.st_name = h->dynstr_index;
6051
6052       /* Give the processor backend a chance to tweak the symbol
6053          value, and also to finish up anything that needs to be done
6054          for this symbol.  */
6055       bed = get_elf_backend_data (finfo->output_bfd);
6056       if (! ((*bed->elf_backend_finish_dynamic_symbol)
6057              (finfo->output_bfd, finfo->info, h, &sym)))
6058         {
6059           /* FIXME: No way to return error.  */
6060           abort ();
6061         }
6062
6063       elf_swap_symbol_out (finfo->output_bfd, &sym,
6064                            ((Elf_External_Sym *) finfo->dynsym_sec->contents
6065                             + h->dynindx));
6066
6067       bucketcount = elf_hash_table (finfo->info)->bucketcount;
6068       bucket = (bfd_elf_hash ((const unsigned char *) h->root.root.string)
6069                 % bucketcount);
6070       bucketpos = ((bfd_byte *) finfo->hash_sec->contents
6071                    + (bucket + 2) * (ARCH_SIZE / 8));
6072       chain = get_word (finfo->output_bfd, bucketpos);
6073       put_word (finfo->output_bfd, h->dynindx, bucketpos);
6074       put_word (finfo->output_bfd, chain,
6075                 ((bfd_byte *) finfo->hash_sec->contents
6076                  + (bucketcount + 2 + h->dynindx) * (ARCH_SIZE / 8)));
6077     }
6078
6079   /* If we're stripping it, then it was just a dynamic symbol, and
6080      there's nothing else to do.  */
6081   if (strip)
6082     return true;
6083
6084   h->indx = finfo->output_bfd->symcount;
6085
6086   if (! elf_link_output_sym (finfo, h->root.root.string, &sym, input_sec))
6087     {
6088       /* FIXME: No way to return error.  */
6089       abort ();
6090     }
6091
6092   return true;
6093 }
6094
6095 /* Link an input file into the linker output file.  This function
6096    handles all the sections and relocations of the input file at once.
6097    This is so that we only have to read the local symbols once, and
6098    don't have to keep them in memory.  */
6099
6100 static boolean
6101 elf_link_input_bfd (finfo, input_bfd)
6102      struct elf_final_link_info *finfo;
6103      bfd *input_bfd;
6104 {
6105   boolean (*relocate_section) PARAMS ((bfd *, struct bfd_link_info *,
6106                                        bfd *, asection *, bfd_byte *,
6107                                        Elf_Internal_Rela *,
6108                                        Elf_Internal_Sym *, asection **));
6109   bfd *output_bfd;
6110   Elf_Internal_Shdr *symtab_hdr;
6111   size_t locsymcount;
6112   size_t extsymoff;
6113   Elf_External_Sym *esym;
6114   Elf_External_Sym *esymend;
6115   Elf_Internal_Sym *isym;
6116   long *pindex;
6117   asection **ppsection;
6118   asection *o;
6119
6120   output_bfd = finfo->output_bfd;
6121   relocate_section =
6122     get_elf_backend_data (output_bfd)->elf_backend_relocate_section;
6123
6124   /* If this is a dynamic object, we don't want to do anything here:
6125      we don't want the local symbols, and we don't want the section
6126      contents.  */
6127   if (elf_elfheader (input_bfd)->e_type == ET_DYN)
6128     return true;
6129
6130   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
6131   if (elf_bad_symtab (input_bfd))
6132     {
6133       locsymcount = symtab_hdr->sh_size / sizeof (Elf_External_Sym);
6134       extsymoff = 0;
6135     }
6136   else
6137     {
6138       locsymcount = symtab_hdr->sh_info;
6139       extsymoff = symtab_hdr->sh_info;
6140     }
6141
6142   /* Read the local symbols.  */
6143   if (locsymcount > 0
6144       && (bfd_seek (input_bfd, symtab_hdr->sh_offset, SEEK_SET) != 0
6145           || (bfd_read (finfo->external_syms, sizeof (Elf_External_Sym),
6146                         locsymcount, input_bfd)
6147               != locsymcount * sizeof (Elf_External_Sym))))
6148     return false;
6149
6150   /* Swap in the local symbols and write out the ones which we know
6151      are going into the output file.  */
6152   esym = finfo->external_syms;
6153   esymend = esym + locsymcount;
6154   isym = finfo->internal_syms;
6155   pindex = finfo->indices;
6156   ppsection = finfo->sections;
6157   for (; esym < esymend; esym++, isym++, pindex++, ppsection++)
6158     {
6159       asection *isec;
6160       const char *name;
6161       Elf_Internal_Sym osym;
6162
6163       elf_swap_symbol_in (input_bfd, esym, isym);
6164       *pindex = -1;
6165
6166       if (elf_bad_symtab (input_bfd))
6167         {
6168           if (ELF_ST_BIND (isym->st_info) != STB_LOCAL)
6169             {
6170               *ppsection = NULL;
6171               continue;
6172             }
6173         }
6174
6175       if (isym->st_shndx == SHN_UNDEF)
6176         isec = bfd_und_section_ptr;
6177       else if (isym->st_shndx > 0 && isym->st_shndx < SHN_LORESERVE)
6178         isec = section_from_elf_index (input_bfd, isym->st_shndx);
6179       else if (isym->st_shndx == SHN_ABS)
6180         isec = bfd_abs_section_ptr;
6181       else if (isym->st_shndx == SHN_COMMON)
6182         isec = bfd_com_section_ptr;
6183       else
6184         {
6185           /* Who knows?  */
6186           isec = NULL;
6187         }
6188
6189       *ppsection = isec;
6190
6191       /* Don't output the first, undefined, symbol.  */
6192       if (esym == finfo->external_syms)
6193         continue;
6194
6195       /* If we are stripping all symbols, we don't want to output this
6196          one.  */
6197       if (finfo->info->strip == strip_all)
6198         continue;
6199
6200       /* We never output section symbols.  Instead, we use the section
6201          symbol of the corresponding section in the output file.  */
6202       if (ELF_ST_TYPE (isym->st_info) == STT_SECTION)
6203         continue;
6204
6205       /* If we are discarding all local symbols, we don't want to
6206          output this one.  If we are generating a relocateable output
6207          file, then some of the local symbols may be required by
6208          relocs; we output them below as we discover that they are
6209          needed.  */
6210       if (finfo->info->discard == discard_all)
6211         continue;
6212
6213       /* Get the name of the symbol.  */
6214       name = elf_string_from_elf_section (input_bfd, symtab_hdr->sh_link,
6215                                           isym->st_name);
6216       if (name == NULL)
6217         return false;
6218
6219       /* See if we are discarding symbols with this name.  */
6220       if ((finfo->info->strip == strip_some
6221            && (bfd_hash_lookup (finfo->info->keep_hash, name, false, false)
6222                == NULL))
6223           || (finfo->info->discard == discard_l
6224               && strncmp (name, finfo->info->lprefix,
6225                           finfo->info->lprefix_len) == 0))
6226         continue;
6227
6228       /* If we get here, we are going to output this symbol.  */
6229
6230       osym = *isym;
6231
6232       /* Adjust the section index for the output file.  */
6233       osym.st_shndx = elf_section_from_bfd_section (output_bfd,
6234                                                     isec->output_section);
6235       if (osym.st_shndx == (unsigned short) -1)
6236         return false;
6237
6238       *pindex = output_bfd->symcount;
6239
6240       /* ELF symbols in relocateable files are section relative, but
6241          in executable files they are virtual addresses.  Note that
6242          this code assumes that all ELF sections have an associated
6243          BFD section with a reasonable value for output_offset; below
6244          we assume that they also have a reasonable value for
6245          output_section.  Any special sections must be set up to meet
6246          these requirements.  */
6247       osym.st_value += isec->output_offset;
6248       if (! finfo->info->relocateable)
6249         osym.st_value += isec->output_section->vma;
6250
6251       if (! elf_link_output_sym (finfo, name, &osym, isec))
6252         return false;
6253     }
6254
6255   /* Relocate the contents of each section.  */
6256   for (o = input_bfd->sections; o != NULL; o = o->next)
6257     {
6258       if ((o->flags & SEC_HAS_CONTENTS) == 0)
6259         continue;
6260
6261       if ((o->flags & SEC_IN_MEMORY) != 0
6262           && input_bfd == elf_hash_table (finfo->info)->dynobj)
6263         {
6264           /* Section was created by elf_link_create_dynamic_sections.
6265              FIXME: This test is fragile.  */
6266           continue;
6267         }
6268
6269       /* Read the contents of the section.  */
6270       if (! bfd_get_section_contents (input_bfd, o, finfo->contents,
6271                                       (file_ptr) 0, o->_raw_size))
6272         return false;
6273
6274       if ((o->flags & SEC_RELOC) != 0)
6275         {
6276           Elf_Internal_Rela *internal_relocs;
6277
6278           /* Get the swapped relocs.  */
6279           internal_relocs = elf_link_read_relocs (input_bfd, o,
6280                                                   finfo->external_relocs,
6281                                                   finfo->internal_relocs,
6282                                                   false);
6283           if (internal_relocs == NULL
6284               && o->reloc_count > 0)
6285             return false;
6286
6287           /* Relocate the section by invoking a back end routine.
6288
6289              The back end routine is responsible for adjusting the
6290              section contents as necessary, and (if using Rela relocs
6291              and generating a relocateable output file) adjusting the
6292              reloc addend as necessary.
6293
6294              The back end routine does not have to worry about setting
6295              the reloc address or the reloc symbol index.
6296
6297              The back end routine is given a pointer to the swapped in
6298              internal symbols, and can access the hash table entries
6299              for the external symbols via elf_sym_hashes (input_bfd).
6300
6301              When generating relocateable output, the back end routine
6302              must handle STB_LOCAL/STT_SECTION symbols specially.  The
6303              output symbol is going to be a section symbol
6304              corresponding to the output section, which will require
6305              the addend to be adjusted.  */
6306
6307           if (! (*relocate_section) (output_bfd, finfo->info,
6308                                      input_bfd, o,
6309                                      finfo->contents,
6310                                      internal_relocs,
6311                                      finfo->internal_syms,
6312                                      finfo->sections))
6313             return false;
6314
6315           if (finfo->info->relocateable)
6316             {
6317               Elf_Internal_Rela *irela;
6318               Elf_Internal_Rela *irelaend;
6319               struct elf_link_hash_entry **rel_hash;
6320               Elf_Internal_Shdr *input_rel_hdr;
6321               Elf_Internal_Shdr *output_rel_hdr;
6322
6323               /* Adjust the reloc addresses and symbol indices.  */
6324
6325               irela = internal_relocs;
6326               irelaend = irela + o->reloc_count;
6327               rel_hash = (elf_section_data (o->output_section)->rel_hashes
6328                           + o->output_section->reloc_count);
6329               for (; irela < irelaend; irela++, rel_hash++)
6330                 {
6331                   long r_symndx;
6332                   Elf_Internal_Sym *isym;
6333                   asection *sec;
6334
6335                   irela->r_offset += o->output_offset;
6336
6337                   r_symndx = ELF_R_SYM (irela->r_info);
6338
6339                   if (r_symndx == 0)
6340                     continue;
6341
6342                   if (r_symndx >= locsymcount
6343                       || (elf_bad_symtab (input_bfd)
6344                           && finfo->sections[r_symndx] == NULL))
6345                     {
6346                       long indx;
6347
6348                       /* This is a reloc against a global symbol.  We
6349                          have not yet output all the local symbols, so
6350                          we do not know the symbol index of any global
6351                          symbol.  We set the rel_hash entry for this
6352                          reloc to point to the global hash table entry
6353                          for this symbol.  The symbol index is then
6354                          set at the end of elf_bfd_final_link.  */
6355                       indx = r_symndx - extsymoff;
6356                       *rel_hash = elf_sym_hashes (input_bfd)[indx];
6357
6358                       /* Setting the index to -2 tells
6359                          elf_link_output_extsym that this symbol is
6360                          used by a reloc.  */
6361                       BFD_ASSERT ((*rel_hash)->indx < 0);
6362                       (*rel_hash)->indx = -2;
6363
6364                       continue;
6365                     }
6366
6367                   /* This is a reloc against a local symbol. */
6368
6369                   *rel_hash = NULL;
6370                   isym = finfo->internal_syms + r_symndx;
6371                   sec = finfo->sections[r_symndx];
6372                   if (ELF_ST_TYPE (isym->st_info) == STT_SECTION)
6373                     {
6374                       /* I suppose the backend ought to fill in the
6375                          section of any STT_SECTION symbol against a
6376                          processor specific section.  */
6377                       if (sec != NULL && bfd_is_abs_section (sec))
6378                         r_symndx = 0;
6379                       else if (sec == NULL || sec->owner == NULL)
6380                         {
6381                           bfd_set_error (bfd_error_bad_value);
6382                           return false;
6383                         }
6384                       else
6385                         {
6386                           r_symndx = sec->output_section->target_index;
6387                           if (r_symndx == 0)
6388                             abort ();
6389                         }
6390                     }
6391                   else
6392                     {
6393                       if (finfo->indices[r_symndx] == -1)
6394                         {
6395                           unsigned long link;
6396                           const char *name;
6397                           asection *osec;
6398
6399                           if (finfo->info->strip == strip_all)
6400                             {
6401                               /* You can't do ld -r -s.  */
6402                               bfd_set_error (bfd_error_invalid_operation);
6403                               return false;
6404                             }
6405
6406                           /* This symbol was skipped earlier, but
6407                              since it is needed by a reloc, we
6408                              must output it now.  */
6409                           link = symtab_hdr->sh_link;
6410                           name = elf_string_from_elf_section (input_bfd,
6411                                                               link,
6412                                                               isym->st_name);
6413                           if (name == NULL)
6414                             return false;
6415
6416                           osec = sec->output_section;
6417                           isym->st_shndx =
6418                             elf_section_from_bfd_section (output_bfd,
6419                                                           osec);
6420                           if (isym->st_shndx == (unsigned short) -1)
6421                             return false;
6422
6423                           isym->st_value += sec->output_offset;
6424                           if (! finfo->info->relocateable)
6425                             isym->st_value += osec->vma;
6426
6427                           finfo->indices[r_symndx] = output_bfd->symcount;
6428
6429                           if (! elf_link_output_sym (finfo, name, isym, sec))
6430                             return false;
6431                         }
6432
6433                       r_symndx = finfo->indices[r_symndx];
6434                     }
6435
6436                   irela->r_info = ELF_R_INFO (r_symndx,
6437                                               ELF_R_TYPE (irela->r_info));
6438                 }
6439
6440               /* Swap out the relocs.  */
6441               input_rel_hdr = &elf_section_data (o)->rel_hdr;
6442               output_rel_hdr = &elf_section_data (o->output_section)->rel_hdr;
6443               BFD_ASSERT (output_rel_hdr->sh_entsize
6444                           == input_rel_hdr->sh_entsize);
6445               irela = internal_relocs;
6446               irelaend = irela + o->reloc_count;
6447               if (input_rel_hdr->sh_entsize == sizeof (Elf_External_Rel))
6448                 {
6449                   Elf_External_Rel *erel;
6450
6451                   erel = ((Elf_External_Rel *) output_rel_hdr->contents
6452                           + o->output_section->reloc_count);
6453                   for (; irela < irelaend; irela++, erel++)
6454                     {
6455                       Elf_Internal_Rel irel;
6456
6457                       irel.r_offset = irela->r_offset;
6458                       irel.r_info = irela->r_info;
6459                       BFD_ASSERT (irela->r_addend == 0);
6460                       elf_swap_reloc_out (output_bfd, &irel, erel);
6461                     }
6462                 }
6463               else
6464                 {
6465                   Elf_External_Rela *erela;
6466
6467                   BFD_ASSERT (input_rel_hdr->sh_entsize
6468                               == sizeof (Elf_External_Rela));
6469                   erela = ((Elf_External_Rela *) output_rel_hdr->contents
6470                            + o->output_section->reloc_count);
6471                   for (; irela < irelaend; irela++, erela++)
6472                     elf_swap_reloca_out (output_bfd, irela, erela);
6473                 }
6474
6475               o->output_section->reloc_count += o->reloc_count;
6476             }
6477         }
6478
6479       /* Write out the modified section contents.  */
6480       if (! bfd_set_section_contents (output_bfd, o->output_section,
6481                                       finfo->contents, o->output_offset,
6482                                       (o->_cooked_size != 0
6483                                        ? o->_cooked_size
6484                                        : o->_raw_size)))
6485         return false;
6486     }
6487
6488   return true;
6489 }
6490
6491 /* Generate a reloc when linking an ELF file.  This is a reloc
6492    requested by the linker, and does come from any input file.  This
6493    is used to build constructor and destructor tables when linking
6494    with -Ur.  */
6495
6496 static boolean
6497 elf_reloc_link_order (output_bfd, info, output_section, link_order)
6498      bfd *output_bfd;
6499      struct bfd_link_info *info;
6500      asection *output_section;
6501      struct bfd_link_order *link_order;
6502 {
6503   reloc_howto_type *howto;
6504   long indx;
6505   bfd_vma offset;
6506   struct elf_link_hash_entry **rel_hash_ptr;
6507   Elf_Internal_Shdr *rel_hdr;
6508
6509   howto = bfd_reloc_type_lookup (output_bfd, link_order->u.reloc.p->reloc);
6510   if (howto == NULL)
6511     {
6512       bfd_set_error (bfd_error_bad_value);
6513       return false;
6514     }
6515
6516   /* If this is an inplace reloc, we must write the addend into the
6517      object file.  */
6518   if (howto->partial_inplace
6519       && link_order->u.reloc.p->addend != 0)
6520     {
6521       bfd_size_type size;
6522       bfd_reloc_status_type rstat;
6523       bfd_byte *buf;
6524       boolean ok;
6525
6526       size = bfd_get_reloc_size (howto);
6527       buf = (bfd_byte *) bfd_zmalloc (size);
6528       if (buf == (bfd_byte *) NULL)
6529         {
6530           bfd_set_error (bfd_error_no_memory);
6531           return false;
6532         }
6533       rstat = _bfd_relocate_contents (howto, output_bfd,
6534                                       link_order->u.reloc.p->addend, buf);
6535       switch (rstat)
6536         {
6537         case bfd_reloc_ok:
6538           break;
6539         default:
6540         case bfd_reloc_outofrange:
6541           abort ();
6542         case bfd_reloc_overflow:
6543           if (! ((*info->callbacks->reloc_overflow)
6544                  (info,
6545                   (link_order->type == bfd_section_reloc_link_order
6546                    ? bfd_section_name (output_bfd,
6547                                        link_order->u.reloc.p->u.section)
6548                    : link_order->u.reloc.p->u.name),
6549                   howto->name, link_order->u.reloc.p->addend,
6550                   (bfd *) NULL, (asection *) NULL, (bfd_vma) 0)))
6551             {
6552               free (buf);
6553               return false;
6554             }
6555           break;
6556         }
6557       ok = bfd_set_section_contents (output_bfd, output_section, (PTR) buf,
6558                                      (file_ptr) link_order->offset, size);
6559       free (buf);
6560       if (! ok)
6561         return false;
6562     }
6563
6564   /* Figure out the symbol index.  */
6565   rel_hash_ptr = (elf_section_data (output_section)->rel_hashes
6566                   + output_section->reloc_count);
6567   if (link_order->type == bfd_section_reloc_link_order)
6568     {
6569       indx = link_order->u.reloc.p->u.section->target_index;
6570       if (indx == 0)
6571         abort ();
6572       *rel_hash_ptr = NULL;
6573     }
6574   else
6575     {
6576       struct elf_link_hash_entry *h;
6577
6578       h = elf_link_hash_lookup (elf_hash_table (info),
6579                                 link_order->u.reloc.p->u.name,
6580                                 false, false, true);
6581       if (h != NULL)
6582         {
6583           /* Setting the index to -2 tells elf_link_output_extsym that
6584              this symbol is used by a reloc.  */
6585           h->indx = -2;
6586           *rel_hash_ptr = h;
6587           indx = 0;
6588         }
6589       else
6590         {
6591           if (! ((*info->callbacks->unattached_reloc)
6592                  (info, link_order->u.reloc.p->u.name, (bfd *) NULL,
6593                   (asection *) NULL, (bfd_vma) 0)))
6594             return false;
6595           indx = 0;
6596         }
6597     }
6598
6599   /* The address of a reloc is relative to the section in a
6600      relocateable file, and is a virtual address in an executable
6601      file.  */
6602   offset = link_order->offset;
6603   if (! info->relocateable)
6604     offset += output_section->vma;
6605
6606   rel_hdr = &elf_section_data (output_section)->rel_hdr;
6607
6608   if (rel_hdr->sh_type == SHT_REL)
6609     {
6610       Elf_Internal_Rel irel;
6611       Elf_External_Rel *erel;
6612
6613       irel.r_offset = offset;
6614       irel.r_info = ELF_R_INFO (indx, howto->type);
6615       erel = ((Elf_External_Rel *) rel_hdr->contents
6616               + output_section->reloc_count);
6617       elf_swap_reloc_out (output_bfd, &irel, erel);
6618     }
6619   else
6620     {
6621       Elf_Internal_Rela irela;
6622       Elf_External_Rela *erela;
6623
6624       irela.r_offset = offset;
6625       irela.r_info = ELF_R_INFO (indx, howto->type);
6626       irela.r_addend = link_order->u.reloc.p->addend;
6627       erela = ((Elf_External_Rela *) rel_hdr->contents
6628                + output_section->reloc_count);
6629       elf_swap_reloca_out (output_bfd, &irela, erela);
6630     }
6631
6632   ++output_section->reloc_count;
6633
6634   return true;
6635 }