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