1/* ELF executable support for BFD.
2   Copyright 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
3   2001, 2002, 2003, 2004, 2005, 2006, 2007
4   Free Software Foundation, Inc.
5
6   Written by Fred Fish @ Cygnus Support, from information published
7   in "UNIX System V Release 4, Programmers Guide: ANSI C and
8   Programming Support Tools".  Sufficient support for gdb.
9
10   Rewritten by Mark Eichin @ Cygnus Support, from information
11   published in "System V Application Binary Interface", chapters 4
12   and 5, as well as the various "Processor Supplement" documents
13   derived from it. Added support for assembler and other object file
14   utilities.  Further work done by Ken Raeburn (Cygnus Support), Michael
15   Meissner (Open Software Foundation), and Peter Hoogenboom (University
16   of Utah) to finish and extend this.
17
18   This file is part of BFD, the Binary File Descriptor library.
19
20   This program is free software; you can redistribute it and/or modify
21   it under the terms of the GNU General Public License as published by
22   the Free Software Foundation; either version 3 of the License, or
23   (at your option) any later version.
24
25   This program is distributed in the hope that it will be useful,
26   but WITHOUT ANY WARRANTY; without even the implied warranty of
27   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
28   GNU General Public License for more details.
29
30   You should have received a copy of the GNU General Public License
31   along with this program; if not, write to the Free Software
32   Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
33   MA 02110-1301, USA.  */
34
35
36/* Problems and other issues to resolve.
37
38   (1)	BFD expects there to be some fixed number of "sections" in
39	the object file.  I.E. there is a "section_count" variable in the
40	bfd structure which contains the number of sections.  However, ELF
41	supports multiple "views" of a file.  In particular, with current
42	implementations, executable files typically have two tables, a
43	program header table and a section header table, both of which
44	partition the executable.
45
46	In ELF-speak, the "linking view" of the file uses the section header
47	table to access "sections" within the file, and the "execution view"
48	uses the program header table to access "segments" within the file.
49	"Segments" typically may contain all the data from one or more
50	"sections".
51
52	Note that the section header table is optional in ELF executables,
53	but it is this information that is most useful to gdb.  If the
54	section header table is missing, then gdb should probably try
55	to make do with the program header table.  (FIXME)
56
57   (2)  The code in this file is compiled twice, once in 32-bit mode and
58	once in 64-bit mode.  More of it should be made size-independent
59	and moved into elf.c.
60
61   (3)	ELF section symbols are handled rather sloppily now.  This should
62	be cleaned up, and ELF section symbols reconciled with BFD section
63	symbols.
64
65   (4)  We need a published spec for 64-bit ELF.  We've got some stuff here
66	that we're using for SPARC V9 64-bit chips, but don't assume that
67	it's cast in stone.
68 */
69
70#include "sysdep.h"
71#include "bfd.h"
72#include "libiberty.h"
73#include "bfdlink.h"
74#include "libbfd.h"
75#include "elf-bfd.h"
76
77/* Renaming structures, typedefs, macros and functions to be size-specific.  */
78#define Elf_External_Ehdr	NAME(Elf,External_Ehdr)
79#define Elf_External_Sym	NAME(Elf,External_Sym)
80#define Elf_External_Shdr	NAME(Elf,External_Shdr)
81#define Elf_External_Phdr	NAME(Elf,External_Phdr)
82#define Elf_External_Rel	NAME(Elf,External_Rel)
83#define Elf_External_Rela	NAME(Elf,External_Rela)
84#define Elf_External_Dyn	NAME(Elf,External_Dyn)
85
86#define elf_core_file_failing_command	NAME(bfd_elf,core_file_failing_command)
87#define elf_core_file_failing_signal	NAME(bfd_elf,core_file_failing_signal)
88#define elf_core_file_matches_executable_p \
89  NAME(bfd_elf,core_file_matches_executable_p)
90#define elf_object_p			NAME(bfd_elf,object_p)
91#define elf_core_file_p			NAME(bfd_elf,core_file_p)
92#define elf_get_symtab_upper_bound	NAME(bfd_elf,get_symtab_upper_bound)
93#define elf_get_dynamic_symtab_upper_bound \
94  NAME(bfd_elf,get_dynamic_symtab_upper_bound)
95#define elf_swap_reloc_in		NAME(bfd_elf,swap_reloc_in)
96#define elf_swap_reloca_in		NAME(bfd_elf,swap_reloca_in)
97#define elf_swap_reloc_out		NAME(bfd_elf,swap_reloc_out)
98#define elf_swap_reloca_out		NAME(bfd_elf,swap_reloca_out)
99#define elf_swap_symbol_in		NAME(bfd_elf,swap_symbol_in)
100#define elf_swap_symbol_out		NAME(bfd_elf,swap_symbol_out)
101#define elf_swap_phdr_in		NAME(bfd_elf,swap_phdr_in)
102#define elf_swap_phdr_out		NAME(bfd_elf,swap_phdr_out)
103#define elf_swap_dyn_in			NAME(bfd_elf,swap_dyn_in)
104#define elf_swap_dyn_out		NAME(bfd_elf,swap_dyn_out)
105#define elf_get_reloc_upper_bound	NAME(bfd_elf,get_reloc_upper_bound)
106#define elf_canonicalize_reloc		NAME(bfd_elf,canonicalize_reloc)
107#define elf_slurp_symbol_table		NAME(bfd_elf,slurp_symbol_table)
108#define elf_canonicalize_symtab		NAME(bfd_elf,canonicalize_symtab)
109#define elf_canonicalize_dynamic_symtab \
110  NAME(bfd_elf,canonicalize_dynamic_symtab)
111#define elf_get_synthetic_symtab \
112  NAME(bfd_elf,get_synthetic_symtab)
113#define elf_make_empty_symbol		NAME(bfd_elf,make_empty_symbol)
114#define elf_get_symbol_info		NAME(bfd_elf,get_symbol_info)
115#define elf_get_lineno			NAME(bfd_elf,get_lineno)
116#define elf_set_arch_mach		NAME(bfd_elf,set_arch_mach)
117#define elf_find_nearest_line		NAME(bfd_elf,find_nearest_line)
118#define elf_sizeof_headers		NAME(bfd_elf,sizeof_headers)
119#define elf_set_section_contents	NAME(bfd_elf,set_section_contents)
120#define elf_no_info_to_howto		NAME(bfd_elf,no_info_to_howto)
121#define elf_no_info_to_howto_rel	NAME(bfd_elf,no_info_to_howto_rel)
122#define elf_find_section		NAME(bfd_elf,find_section)
123#define elf_write_shdrs_and_ehdr	NAME(bfd_elf,write_shdrs_and_ehdr)
124#define elf_write_out_phdrs		NAME(bfd_elf,write_out_phdrs)
125#define elf_checksum_contents		NAME(bfd_elf,checksum_contents)
126#define elf_write_relocs		NAME(bfd_elf,write_relocs)
127#define elf_slurp_reloc_table		NAME(bfd_elf,slurp_reloc_table)
128
129#if ARCH_SIZE == 64
130#define ELF_R_INFO(X,Y)	ELF64_R_INFO(X,Y)
131#define ELF_R_SYM(X)	ELF64_R_SYM(X)
132#define ELF_R_TYPE(X)	ELF64_R_TYPE(X)
133#define ELFCLASS	ELFCLASS64
134#define FILE_ALIGN	8
135#define LOG_FILE_ALIGN	3
136#endif
137#if ARCH_SIZE == 32
138#define ELF_R_INFO(X,Y)	ELF32_R_INFO(X,Y)
139#define ELF_R_SYM(X)	ELF32_R_SYM(X)
140#define ELF_R_TYPE(X)	ELF32_R_TYPE(X)
141#define ELFCLASS	ELFCLASS32
142#define FILE_ALIGN	4
143#define LOG_FILE_ALIGN	2
144#endif
145
146#if DEBUG & 2
147static void elf_debug_section (int, Elf_Internal_Shdr *);
148#endif
149#if DEBUG & 1
150static void elf_debug_file (Elf_Internal_Ehdr *);
151#endif
152
153/* Structure swapping routines */
154
155/* Should perhaps use put_offset, put_word, etc.  For now, the two versions
156   can be handled by explicitly specifying 32 bits or "the long type".  */
157#if ARCH_SIZE == 64
158#define H_PUT_WORD		H_PUT_64
159#define H_PUT_SIGNED_WORD	H_PUT_S64
160#define H_GET_WORD		H_GET_64
161#define H_GET_SIGNED_WORD	H_GET_S64
162#endif
163#if ARCH_SIZE == 32
164#define H_PUT_WORD		H_PUT_32
165#define H_PUT_SIGNED_WORD	H_PUT_S32
166#define H_GET_WORD		H_GET_32
167#define H_GET_SIGNED_WORD	H_GET_S32
168#endif
169
170/* Translate an ELF symbol in external format into an ELF symbol in internal
171   format.  */
172
173bfd_boolean
174elf_swap_symbol_in (bfd *abfd,
175		    const void *psrc,
176		    const void *pshn,
177		    Elf_Internal_Sym *dst)
178{
179  const Elf_External_Sym *src = psrc;
180  const Elf_External_Sym_Shndx *shndx = pshn;
181  int signed_vma = get_elf_backend_data (abfd)->sign_extend_vma;
182
183  dst->st_name = H_GET_32 (abfd, src->st_name);
184  if (signed_vma)
185    dst->st_value = H_GET_SIGNED_WORD (abfd, src->st_value);
186  else
187    dst->st_value = H_GET_WORD (abfd, src->st_value);
188  dst->st_size = H_GET_WORD (abfd, src->st_size);
189  dst->st_info = H_GET_8 (abfd, src->st_info);
190  dst->st_other = H_GET_8 (abfd, src->st_other);
191  dst->st_shndx = H_GET_16 (abfd, src->st_shndx);
192  if (dst->st_shndx == SHN_XINDEX)
193    {
194      if (shndx == NULL)
195	return FALSE;
196      dst->st_shndx = H_GET_32 (abfd, shndx->est_shndx);
197    }
198  return TRUE;
199}
200
201/* Translate an ELF symbol in internal format into an ELF symbol in external
202   format.  */
203
204void
205elf_swap_symbol_out (bfd *abfd,
206		     const Elf_Internal_Sym *src,
207		     void *cdst,
208		     void *shndx)
209{
210  unsigned int tmp;
211  Elf_External_Sym *dst = cdst;
212  H_PUT_32 (abfd, src->st_name, dst->st_name);
213  H_PUT_WORD (abfd, src->st_value, dst->st_value);
214  H_PUT_WORD (abfd, src->st_size, dst->st_size);
215  H_PUT_8 (abfd, src->st_info, dst->st_info);
216  H_PUT_8 (abfd, src->st_other, dst->st_other);
217  tmp = src->st_shndx;
218  if (tmp > SHN_HIRESERVE)
219    {
220      if (shndx == NULL)
221	abort ();
222      H_PUT_32 (abfd, tmp, shndx);
223      tmp = SHN_XINDEX;
224    }
225  H_PUT_16 (abfd, tmp, dst->st_shndx);
226}
227
228/* Translate an ELF file header in external format into an ELF file header in
229   internal format.  */
230
231static void
232elf_swap_ehdr_in (bfd *abfd,
233		  const Elf_External_Ehdr *src,
234		  Elf_Internal_Ehdr *dst)
235{
236  int signed_vma = get_elf_backend_data (abfd)->sign_extend_vma;
237  memcpy (dst->e_ident, src->e_ident, EI_NIDENT);
238  dst->e_type = H_GET_16 (abfd, src->e_type);
239  dst->e_machine = H_GET_16 (abfd, src->e_machine);
240  dst->e_version = H_GET_32 (abfd, src->e_version);
241  if (signed_vma)
242    dst->e_entry = H_GET_SIGNED_WORD (abfd, src->e_entry);
243  else
244    dst->e_entry = H_GET_WORD (abfd, src->e_entry);
245  dst->e_phoff = H_GET_WORD (abfd, src->e_phoff);
246  dst->e_shoff = H_GET_WORD (abfd, src->e_shoff);
247  dst->e_flags = H_GET_32 (abfd, src->e_flags);
248  dst->e_ehsize = H_GET_16 (abfd, src->e_ehsize);
249  dst->e_phentsize = H_GET_16 (abfd, src->e_phentsize);
250  dst->e_phnum = H_GET_16 (abfd, src->e_phnum);
251  dst->e_shentsize = H_GET_16 (abfd, src->e_shentsize);
252  dst->e_shnum = H_GET_16 (abfd, src->e_shnum);
253  dst->e_shstrndx = H_GET_16 (abfd, src->e_shstrndx);
254}
255
256/* Translate an ELF file header in internal format into an ELF file header in
257   external format.  */
258
259static void
260elf_swap_ehdr_out (bfd *abfd,
261		   const Elf_Internal_Ehdr *src,
262		   Elf_External_Ehdr *dst)
263{
264  unsigned int tmp;
265  int signed_vma = get_elf_backend_data (abfd)->sign_extend_vma;
266  memcpy (dst->e_ident, src->e_ident, EI_NIDENT);
267  /* note that all elements of dst are *arrays of unsigned char* already...  */
268  H_PUT_16 (abfd, src->e_type, dst->e_type);
269  H_PUT_16 (abfd, src->e_machine, dst->e_machine);
270  H_PUT_32 (abfd, src->e_version, dst->e_version);
271  if (signed_vma)
272    H_PUT_SIGNED_WORD (abfd, src->e_entry, dst->e_entry);
273  else
274    H_PUT_WORD (abfd, src->e_entry, dst->e_entry);
275  H_PUT_WORD (abfd, src->e_phoff, dst->e_phoff);
276  H_PUT_WORD (abfd, src->e_shoff, dst->e_shoff);
277  H_PUT_32 (abfd, src->e_flags, dst->e_flags);
278  H_PUT_16 (abfd, src->e_ehsize, dst->e_ehsize);
279  H_PUT_16 (abfd, src->e_phentsize, dst->e_phentsize);
280  H_PUT_16 (abfd, src->e_phnum, dst->e_phnum);
281  H_PUT_16 (abfd, src->e_shentsize, dst->e_shentsize);
282  tmp = src->e_shnum;
283  if (tmp >= SHN_LORESERVE)
284    tmp = SHN_UNDEF;
285  H_PUT_16 (abfd, tmp, dst->e_shnum);
286  tmp = src->e_shstrndx;
287  if (tmp >= SHN_LORESERVE)
288    tmp = SHN_XINDEX;
289  H_PUT_16 (abfd, tmp, dst->e_shstrndx);
290}
291
292/* Translate an ELF section header table entry in external format into an
293   ELF section header table entry in internal format.  */
294
295static void
296elf_swap_shdr_in (bfd *abfd,
297		  const Elf_External_Shdr *src,
298		  Elf_Internal_Shdr *dst)
299{
300  int signed_vma = get_elf_backend_data (abfd)->sign_extend_vma;
301
302  dst->sh_name = H_GET_32 (abfd, src->sh_name);
303  dst->sh_type = H_GET_32 (abfd, src->sh_type);
304  dst->sh_flags = H_GET_WORD (abfd, src->sh_flags);
305  if (signed_vma)
306    dst->sh_addr = H_GET_SIGNED_WORD (abfd, src->sh_addr);
307  else
308    dst->sh_addr = H_GET_WORD (abfd, src->sh_addr);
309  dst->sh_offset = H_GET_WORD (abfd, src->sh_offset);
310  dst->sh_size = H_GET_WORD (abfd, src->sh_size);
311  dst->sh_link = H_GET_32 (abfd, src->sh_link);
312  dst->sh_info = H_GET_32 (abfd, src->sh_info);
313  dst->sh_addralign = H_GET_WORD (abfd, src->sh_addralign);
314  dst->sh_entsize = H_GET_WORD (abfd, src->sh_entsize);
315  dst->bfd_section = NULL;
316  dst->contents = NULL;
317}
318
319/* Translate an ELF section header table entry in internal format into an
320   ELF section header table entry in external format.  */
321
322static void
323elf_swap_shdr_out (bfd *abfd,
324		   const Elf_Internal_Shdr *src,
325		   Elf_External_Shdr *dst)
326{
327  /* note that all elements of dst are *arrays of unsigned char* already...  */
328  H_PUT_32 (abfd, src->sh_name, dst->sh_name);
329  H_PUT_32 (abfd, src->sh_type, dst->sh_type);
330  H_PUT_WORD (abfd, src->sh_flags, dst->sh_flags);
331  H_PUT_WORD (abfd, src->sh_addr, dst->sh_addr);
332  H_PUT_WORD (abfd, src->sh_offset, dst->sh_offset);
333  H_PUT_WORD (abfd, src->sh_size, dst->sh_size);
334  H_PUT_32 (abfd, src->sh_link, dst->sh_link);
335  H_PUT_32 (abfd, src->sh_info, dst->sh_info);
336  H_PUT_WORD (abfd, src->sh_addralign, dst->sh_addralign);
337  H_PUT_WORD (abfd, src->sh_entsize, dst->sh_entsize);
338}
339
340/* Translate an ELF program header table entry in external format into an
341   ELF program header table entry in internal format.  */
342
343void
344elf_swap_phdr_in (bfd *abfd,
345		  const Elf_External_Phdr *src,
346		  Elf_Internal_Phdr *dst)
347{
348  int signed_vma = get_elf_backend_data (abfd)->sign_extend_vma;
349
350  dst->p_type = H_GET_32 (abfd, src->p_type);
351  dst->p_flags = H_GET_32 (abfd, src->p_flags);
352  dst->p_offset = H_GET_WORD (abfd, src->p_offset);
353  if (signed_vma)
354    {
355      dst->p_vaddr = H_GET_SIGNED_WORD (abfd, src->p_vaddr);
356      dst->p_paddr = H_GET_SIGNED_WORD (abfd, src->p_paddr);
357    }
358  else
359    {
360      dst->p_vaddr = H_GET_WORD (abfd, src->p_vaddr);
361      dst->p_paddr = H_GET_WORD (abfd, src->p_paddr);
362    }
363  dst->p_filesz = H_GET_WORD (abfd, src->p_filesz);
364  dst->p_memsz = H_GET_WORD (abfd, src->p_memsz);
365  dst->p_align = H_GET_WORD (abfd, src->p_align);
366}
367
368void
369elf_swap_phdr_out (bfd *abfd,
370		   const Elf_Internal_Phdr *src,
371		   Elf_External_Phdr *dst)
372{
373  /* note that all elements of dst are *arrays of unsigned char* already...  */
374  H_PUT_32 (abfd, src->p_type, dst->p_type);
375  H_PUT_WORD (abfd, src->p_offset, dst->p_offset);
376  H_PUT_WORD (abfd, src->p_vaddr, dst->p_vaddr);
377  H_PUT_WORD (abfd, src->p_paddr, dst->p_paddr);
378  H_PUT_WORD (abfd, src->p_filesz, dst->p_filesz);
379  H_PUT_WORD (abfd, src->p_memsz, dst->p_memsz);
380  H_PUT_32 (abfd, src->p_flags, dst->p_flags);
381  H_PUT_WORD (abfd, src->p_align, dst->p_align);
382}
383
384/* Translate an ELF reloc from external format to internal format.  */
385void
386elf_swap_reloc_in (bfd *abfd,
387		   const bfd_byte *s,
388		   Elf_Internal_Rela *dst)
389{
390  const Elf_External_Rel *src = (const Elf_External_Rel *) s;
391  dst->r_offset = H_GET_WORD (abfd, src->r_offset);
392  dst->r_info = H_GET_WORD (abfd, src->r_info);
393  dst->r_addend = 0;
394}
395
396void
397elf_swap_reloca_in (bfd *abfd,
398		    const bfd_byte *s,
399		    Elf_Internal_Rela *dst)
400{
401  const Elf_External_Rela *src = (const Elf_External_Rela *) s;
402  dst->r_offset = H_GET_WORD (abfd, src->r_offset);
403  dst->r_info = H_GET_WORD (abfd, src->r_info);
404  dst->r_addend = H_GET_SIGNED_WORD (abfd, src->r_addend);
405}
406
407/* Translate an ELF reloc from internal format to external format.  */
408void
409elf_swap_reloc_out (bfd *abfd,
410		    const Elf_Internal_Rela *src,
411		    bfd_byte *d)
412{
413  Elf_External_Rel *dst = (Elf_External_Rel *) d;
414  H_PUT_WORD (abfd, src->r_offset, dst->r_offset);
415  H_PUT_WORD (abfd, src->r_info, dst->r_info);
416}
417
418void
419elf_swap_reloca_out (bfd *abfd,
420		     const Elf_Internal_Rela *src,
421		     bfd_byte *d)
422{
423  Elf_External_Rela *dst = (Elf_External_Rela *) d;
424  H_PUT_WORD (abfd, src->r_offset, dst->r_offset);
425  H_PUT_WORD (abfd, src->r_info, dst->r_info);
426  H_PUT_SIGNED_WORD (abfd, src->r_addend, dst->r_addend);
427}
428
429void
430elf_swap_dyn_in (bfd *abfd,
431		 const void *p,
432		 Elf_Internal_Dyn *dst)
433{
434  const Elf_External_Dyn *src = p;
435
436  dst->d_tag = H_GET_WORD (abfd, src->d_tag);
437  dst->d_un.d_val = H_GET_WORD (abfd, src->d_un.d_val);
438}
439
440void
441elf_swap_dyn_out (bfd *abfd,
442		  const Elf_Internal_Dyn *src,
443		  void *p)
444{
445  Elf_External_Dyn *dst = p;
446
447  H_PUT_WORD (abfd, src->d_tag, dst->d_tag);
448  H_PUT_WORD (abfd, src->d_un.d_val, dst->d_un.d_val);
449}
450
451/* ELF .o/exec file reading */
452
453/* Begin processing a given object.
454
455   First we validate the file by reading in the ELF header and checking
456   the magic number.  */
457
458static inline bfd_boolean
459elf_file_p (Elf_External_Ehdr *x_ehdrp)
460{
461  return ((x_ehdrp->e_ident[EI_MAG0] == ELFMAG0)
462	  && (x_ehdrp->e_ident[EI_MAG1] == ELFMAG1)
463	  && (x_ehdrp->e_ident[EI_MAG2] == ELFMAG2)
464	  && (x_ehdrp->e_ident[EI_MAG3] == ELFMAG3));
465}
466
467/* Determines if a given section index is valid.  */
468
469static inline bfd_boolean
470valid_section_index_p (unsigned index, unsigned num_sections)
471{
472  /* Note: We allow SHN_UNDEF as a valid section index.  */
473  if (index < SHN_LORESERVE || index > SHN_HIRESERVE)
474    return index < num_sections;
475
476  /* We disallow the use of reserved indcies, except for those
477     with OS or Application specific meaning.  The test make use
478     of the knowledge that:
479       SHN_LORESERVE == SHN_LOPROC
480     and
481       SHN_HIPROC == SHN_LOOS - 1  */
482  /* XXX - Should we allow SHN_XINDEX as a valid index here ?  */
483  return (index >= SHN_LOPROC && index <= SHN_HIOS);
484}
485
486/* Check to see if the file associated with ABFD matches the target vector
487   that ABFD points to.
488
489   Note that we may be called several times with the same ABFD, but different
490   target vectors, most of which will not match.  We have to avoid leaving
491   any side effects in ABFD, or any data it points to (like tdata), if the
492   file does not match the target vector.  */
493
494const bfd_target *
495elf_object_p (bfd *abfd)
496{
497  Elf_External_Ehdr x_ehdr;	/* Elf file header, external form */
498  Elf_Internal_Ehdr *i_ehdrp;	/* Elf file header, internal form */
499  Elf_External_Shdr x_shdr;	/* Section header table entry, external form */
500  Elf_Internal_Shdr i_shdr;
501  Elf_Internal_Shdr *i_shdrp;	/* Section header table, internal form */
502  unsigned int shindex;
503  const struct elf_backend_data *ebd;
504  struct bfd_preserve preserve;
505  asection *s;
506  bfd_size_type amt;
507  const bfd_target *target;
508  const bfd_target * const *target_ptr;
509
510  preserve.marker = NULL;
511
512  /* Read in the ELF header in external format.  */
513
514  if (bfd_bread (&x_ehdr, sizeof (x_ehdr), abfd) != sizeof (x_ehdr))
515    {
516      if (bfd_get_error () != bfd_error_system_call)
517	goto got_wrong_format_error;
518      else
519	goto got_no_match;
520    }
521
522  /* Now check to see if we have a valid ELF file, and one that BFD can
523     make use of.  The magic number must match, the address size ('class')
524     and byte-swapping must match our XVEC entry, and it must have a
525     section header table (FIXME: See comments re sections at top of this
526     file).  */
527
528  if (! elf_file_p (&x_ehdr)
529      || x_ehdr.e_ident[EI_VERSION] != EV_CURRENT
530      || x_ehdr.e_ident[EI_CLASS] != ELFCLASS)
531    goto got_wrong_format_error;
532
533  /* Check that file's byte order matches xvec's */
534  switch (x_ehdr.e_ident[EI_DATA])
535    {
536    case ELFDATA2MSB:		/* Big-endian */
537      if (! bfd_header_big_endian (abfd))
538	goto got_wrong_format_error;
539      break;
540    case ELFDATA2LSB:		/* Little-endian */
541      if (! bfd_header_little_endian (abfd))
542	goto got_wrong_format_error;
543      break;
544    case ELFDATANONE:		/* No data encoding specified */
545    default:			/* Unknown data encoding specified */
546      goto got_wrong_format_error;
547    }
548
549  if (!bfd_preserve_save (abfd, &preserve))
550    goto got_no_match;
551
552  target = abfd->xvec;
553
554  /* Allocate an instance of the elf_obj_tdata structure and hook it up to
555     the tdata pointer in the bfd.  */
556
557  if (! (*target->_bfd_set_format[bfd_object]) (abfd))
558    goto got_no_match;
559  preserve.marker = elf_tdata (abfd);
560
561  /* Now that we know the byte order, swap in the rest of the header */
562  i_ehdrp = elf_elfheader (abfd);
563  elf_swap_ehdr_in (abfd, &x_ehdr, i_ehdrp);
564#if DEBUG & 1
565  elf_debug_file (i_ehdrp);
566#endif
567
568  /* Reject ET_CORE (header indicates core file, not object file) */
569  if (i_ehdrp->e_type == ET_CORE)
570    goto got_wrong_format_error;
571
572  /* If this is a relocatable file and there is no section header
573     table, then we're hosed.  */
574  if (i_ehdrp->e_shoff == 0 && i_ehdrp->e_type == ET_REL)
575    goto got_wrong_format_error;
576
577  /* As a simple sanity check, verify that what BFD thinks is the
578     size of each section header table entry actually matches the size
579     recorded in the file, but only if there are any sections.  */
580  if (i_ehdrp->e_shentsize != sizeof (x_shdr) && i_ehdrp->e_shnum != 0)
581    goto got_wrong_format_error;
582
583  /* Further sanity check.  */
584  if (i_ehdrp->e_shoff == 0 && i_ehdrp->e_shnum != 0)
585    goto got_wrong_format_error;
586
587  ebd = get_elf_backend_data (abfd);
588
589  /* Check that the ELF e_machine field matches what this particular
590     BFD format expects.  */
591  if (ebd->elf_machine_code != i_ehdrp->e_machine
592      && (ebd->elf_machine_alt1 == 0
593	  || i_ehdrp->e_machine != ebd->elf_machine_alt1)
594      && (ebd->elf_machine_alt2 == 0
595	  || i_ehdrp->e_machine != ebd->elf_machine_alt2))
596    {
597      if (ebd->elf_machine_code != EM_NONE)
598	goto got_wrong_format_error;
599
600      /* This is the generic ELF target.  Let it match any ELF target
601	 for which we do not have a specific backend.  */
602      for (target_ptr = bfd_target_vector; *target_ptr != NULL; target_ptr++)
603	{
604	  const struct elf_backend_data *back;
605
606	  if ((*target_ptr)->flavour != bfd_target_elf_flavour)
607	    continue;
608	  back = xvec_get_elf_backend_data (*target_ptr);
609	  if (back->elf_machine_code == i_ehdrp->e_machine
610	      || (back->elf_machine_alt1 != 0
611		  && back->elf_machine_alt1 == i_ehdrp->e_machine)
612	      || (back->elf_machine_alt2 != 0
613		  && back->elf_machine_alt2 == i_ehdrp->e_machine))
614	    {
615	      /* target_ptr is an ELF backend which matches this
616		 object file, so reject the generic ELF target.  */
617	      goto got_wrong_format_error;
618	    }
619	}
620    }
621
622  if (i_ehdrp->e_type == ET_EXEC)
623    abfd->flags |= EXEC_P;
624  else if (i_ehdrp->e_type == ET_DYN)
625    abfd->flags |= DYNAMIC;
626
627  if (i_ehdrp->e_phnum > 0)
628    abfd->flags |= D_PAGED;
629
630  if (! bfd_default_set_arch_mach (abfd, ebd->arch, 0))
631    {
632      /* It's OK if this fails for the generic target.  */
633      if (ebd->elf_machine_code != EM_NONE)
634	goto got_no_match;
635    }
636
637  if (ebd->elf_machine_code != EM_NONE
638      && i_ehdrp->e_ident[EI_OSABI] != ebd->elf_osabi)
639    {
640      if (ebd->elf_osabi != ELFOSABI_NONE)
641	goto got_wrong_format_error;
642
643      /* This is an ELFOSABI_NONE ELF target.  Let it match any ELF
644	 target of the compatible machine for which we do not have a
645	 backend with matching ELFOSABI.  */
646      for (target_ptr = bfd_target_vector;
647	   *target_ptr != NULL;
648	   target_ptr++)
649	{
650	  const struct elf_backend_data *back;
651
652	  /* Skip this target and targets with incompatible byte
653	     order.  */
654	  if (*target_ptr == target
655	      || (*target_ptr)->flavour != bfd_target_elf_flavour
656	      || (*target_ptr)->byteorder != target->byteorder
657	      || ((*target_ptr)->header_byteorder
658		  != target->header_byteorder))
659	    continue;
660
661	  back = xvec_get_elf_backend_data (*target_ptr);
662	  if (back->elf_osabi == i_ehdrp->e_ident[EI_OSABI]
663	      && (back->elf_machine_code == i_ehdrp->e_machine
664		  || (back->elf_machine_alt1 != 0
665		      && back->elf_machine_alt1 == i_ehdrp->e_machine)
666		  || (back->elf_machine_alt2 != 0
667		      && back->elf_machine_alt2 == i_ehdrp->e_machine)))
668	    {
669	      /* target_ptr is an ELF backend which matches this
670		 object file, so reject the ELFOSABI_NONE ELF target.  */
671	      goto got_wrong_format_error;
672	    }
673	}
674    }
675
676  if (i_ehdrp->e_shoff != 0)
677    {
678      bfd_signed_vma where = i_ehdrp->e_shoff;
679
680      if (where != (file_ptr) where)
681	goto got_wrong_format_error;
682
683      /* Seek to the section header table in the file.  */
684      if (bfd_seek (abfd, (file_ptr) where, SEEK_SET) != 0)
685	goto got_no_match;
686
687      /* Read the first section header at index 0, and convert to internal
688	 form.  */
689      if (bfd_bread (&x_shdr, sizeof x_shdr, abfd) != sizeof (x_shdr))
690	goto got_no_match;
691      elf_swap_shdr_in (abfd, &x_shdr, &i_shdr);
692
693      /* If the section count is zero, the actual count is in the first
694	 section header.  */
695      if (i_ehdrp->e_shnum == SHN_UNDEF)
696	{
697	  i_ehdrp->e_shnum = i_shdr.sh_size;
698	  if (i_ehdrp->e_shnum != i_shdr.sh_size
699	      || i_ehdrp->e_shnum == 0)
700	    goto got_wrong_format_error;
701	}
702
703      /* And similarly for the string table index.  */
704      if (i_ehdrp->e_shstrndx == SHN_XINDEX)
705	{
706	  i_ehdrp->e_shstrndx = i_shdr.sh_link;
707	  if (i_ehdrp->e_shstrndx != i_shdr.sh_link)
708	    goto got_wrong_format_error;
709	}
710
711      /* Sanity check that we can read all of the section headers.
712	 It ought to be good enough to just read the last one.  */
713      if (i_ehdrp->e_shnum != 1)
714	{
715	  /* Check that we don't have a totally silly number of sections.  */
716	  if (i_ehdrp->e_shnum > (unsigned int) -1 / sizeof (x_shdr)
717	      || i_ehdrp->e_shnum > (unsigned int) -1 / sizeof (i_shdr))
718	    goto got_wrong_format_error;
719
720	  where += (i_ehdrp->e_shnum - 1) * sizeof (x_shdr);
721	  if (where != (file_ptr) where)
722	    goto got_wrong_format_error;
723	  if ((bfd_size_type) where <= i_ehdrp->e_shoff)
724	    goto got_wrong_format_error;
725
726	  if (bfd_seek (abfd, (file_ptr) where, SEEK_SET) != 0)
727	    goto got_no_match;
728	  if (bfd_bread (&x_shdr, sizeof x_shdr, abfd) != sizeof (x_shdr))
729	    goto got_no_match;
730
731	  /* Back to where we were.  */
732	  where = i_ehdrp->e_shoff + sizeof (x_shdr);
733	  if (bfd_seek (abfd, (file_ptr) where, SEEK_SET) != 0)
734	    goto got_no_match;
735	}
736    }
737
738  /* Allocate space for a copy of the section header table in
739     internal form.  */
740  if (i_ehdrp->e_shnum != 0)
741    {
742      Elf_Internal_Shdr *shdrp;
743      unsigned int num_sec;
744
745      amt = sizeof (*i_shdrp) * i_ehdrp->e_shnum;
746      i_shdrp = bfd_alloc (abfd, amt);
747      if (!i_shdrp)
748	goto got_no_match;
749      num_sec = i_ehdrp->e_shnum;
750      if (num_sec > SHN_LORESERVE)
751	num_sec += SHN_HIRESERVE + 1 - SHN_LORESERVE;
752      elf_numsections (abfd) = num_sec;
753      amt = sizeof (i_shdrp) * num_sec;
754      elf_elfsections (abfd) = bfd_alloc (abfd, amt);
755      if (!elf_elfsections (abfd))
756	goto got_no_match;
757
758      memcpy (i_shdrp, &i_shdr, sizeof (*i_shdrp));
759      shdrp = i_shdrp;
760      shindex = 0;
761      if (num_sec > SHN_LORESERVE)
762	{
763	  for ( ; shindex < SHN_LORESERVE; shindex++)
764	    elf_elfsections (abfd)[shindex] = shdrp++;
765	  for ( ; shindex < SHN_HIRESERVE + 1; shindex++)
766	    elf_elfsections (abfd)[shindex] = i_shdrp;
767	}
768      for ( ; shindex < num_sec; shindex++)
769	elf_elfsections (abfd)[shindex] = shdrp++;
770
771      /* Read in the rest of the section header table and convert it
772	 to internal form.  */
773      for (shindex = 1; shindex < i_ehdrp->e_shnum; shindex++)
774	{
775	  if (bfd_bread (&x_shdr, sizeof x_shdr, abfd) != sizeof (x_shdr))
776	    goto got_no_match;
777	  elf_swap_shdr_in (abfd, &x_shdr, i_shdrp + shindex);
778
779	  /* Sanity check sh_link and sh_info.  */
780	  if (! valid_section_index_p (i_shdrp[shindex].sh_link, num_sec))
781	    goto got_wrong_format_error;
782
783	  if (((i_shdrp[shindex].sh_flags & SHF_INFO_LINK)
784	       || i_shdrp[shindex].sh_type == SHT_RELA
785	       || i_shdrp[shindex].sh_type == SHT_REL)
786	      && ! valid_section_index_p (i_shdrp[shindex].sh_info, num_sec))
787	    goto got_wrong_format_error;
788
789	  /* If the section is loaded, but not page aligned, clear
790	     D_PAGED.  */
791	  if (i_shdrp[shindex].sh_size != 0
792	      && (i_shdrp[shindex].sh_flags & SHF_ALLOC) != 0
793	      && i_shdrp[shindex].sh_type != SHT_NOBITS
794	      && (((i_shdrp[shindex].sh_addr - i_shdrp[shindex].sh_offset)
795		   % ebd->minpagesize)
796		  != 0))
797	    abfd->flags &= ~D_PAGED;
798	}
799    }
800
801  /* A further sanity check.  */
802  if (i_ehdrp->e_shnum != 0)
803    {
804      if (! valid_section_index_p (i_ehdrp->e_shstrndx, elf_numsections (abfd)))
805	{
806	  /* PR 2257:
807	     We used to just goto got_wrong_format_error here
808	     but there are binaries in existance for which this test
809	     will prevent the binutils from working with them at all.
810	     So we are kind, and reset the string index value to 0
811	     so that at least some processing can be done.  */
812	  i_ehdrp->e_shstrndx = SHN_UNDEF;
813	  _bfd_error_handler (_("warning: %s has a corrupt string table index - ignoring"), abfd->filename);
814	}
815    }
816  else if (i_ehdrp->e_shstrndx != SHN_UNDEF)
817    goto got_wrong_format_error;
818
819  /* Read in the program headers.  */
820  if (i_ehdrp->e_phnum == 0)
821    elf_tdata (abfd)->phdr = NULL;
822  else
823    {
824      Elf_Internal_Phdr *i_phdr;
825      unsigned int i;
826
827      amt = i_ehdrp->e_phnum * sizeof (Elf_Internal_Phdr);
828      elf_tdata (abfd)->phdr = bfd_alloc (abfd, amt);
829      if (elf_tdata (abfd)->phdr == NULL)
830	goto got_no_match;
831      if (bfd_seek (abfd, (file_ptr) i_ehdrp->e_phoff, SEEK_SET) != 0)
832	goto got_no_match;
833      i_phdr = elf_tdata (abfd)->phdr;
834      for (i = 0; i < i_ehdrp->e_phnum; i++, i_phdr++)
835	{
836	  Elf_External_Phdr x_phdr;
837
838	  if (bfd_bread (&x_phdr, sizeof x_phdr, abfd) != sizeof x_phdr)
839	    goto got_no_match;
840	  elf_swap_phdr_in (abfd, &x_phdr, i_phdr);
841	}
842    }
843
844  if (i_ehdrp->e_shstrndx != 0 && i_ehdrp->e_shoff != 0)
845    {
846      unsigned int num_sec;
847
848      /* Once all of the section headers have been read and converted, we
849	 can start processing them.  Note that the first section header is
850	 a dummy placeholder entry, so we ignore it.  */
851      num_sec = elf_numsections (abfd);
852      for (shindex = 1; shindex < num_sec; shindex++)
853	{
854	  if (! bfd_section_from_shdr (abfd, shindex))
855	    goto got_no_match;
856	  if (shindex == SHN_LORESERVE - 1)
857	    shindex += SHN_HIRESERVE + 1 - SHN_LORESERVE;
858	}
859
860      /* Set up ELF sections for SHF_GROUP and SHF_LINK_ORDER.  */
861      if (! _bfd_elf_setup_sections (abfd))
862	goto got_wrong_format_error;
863    }
864
865  /* Let the backend double check the format and override global
866     information.  */
867  if (ebd->elf_backend_object_p)
868    {
869      if (! (*ebd->elf_backend_object_p) (abfd))
870	goto got_wrong_format_error;
871    }
872
873  /* Remember the entry point specified in the ELF file header.  */
874  bfd_set_start_address (abfd, i_ehdrp->e_entry);
875
876  /* If we have created any reloc sections that are associated with
877     debugging sections, mark the reloc sections as debugging as well.  */
878  for (s = abfd->sections; s != NULL; s = s->next)
879    {
880      if ((elf_section_data (s)->this_hdr.sh_type == SHT_REL
881	   || elf_section_data (s)->this_hdr.sh_type == SHT_RELA)
882	  && elf_section_data (s)->this_hdr.sh_info > 0)
883	{
884	  unsigned long targ_index;
885	  asection *targ_sec;
886
887	  targ_index = elf_section_data (s)->this_hdr.sh_info;
888	  targ_sec = bfd_section_from_elf_index (abfd, targ_index);
889	  if (targ_sec != NULL
890	      && (targ_sec->flags & SEC_DEBUGGING) != 0)
891	    s->flags |= SEC_DEBUGGING;
892	}
893    }
894
895  bfd_preserve_finish (abfd, &preserve);
896  return target;
897
898 got_wrong_format_error:
899  /* There is way too much undoing of half-known state here.  The caller,
900     bfd_check_format_matches, really shouldn't iterate on live bfd's to
901     check match/no-match like it does.  We have to rely on that a call to
902     bfd_default_set_arch_mach with the previously known mach, undoes what
903     was done by the first bfd_default_set_arch_mach (with mach 0) here.
904     For this to work, only elf-data and the mach may be changed by the
905     target-specific elf_backend_object_p function.  Note that saving the
906     whole bfd here and restoring it would be even worse; the first thing
907     you notice is that the cached bfd file position gets out of sync.  */
908  bfd_set_error (bfd_error_wrong_format);
909
910 got_no_match:
911  if (preserve.marker != NULL)
912    bfd_preserve_restore (abfd, &preserve);
913  return NULL;
914}
915
916/* ELF .o/exec file writing */
917
918/* Write out the relocs.  */
919
920void
921elf_write_relocs (bfd *abfd, asection *sec, void *data)
922{
923  bfd_boolean *failedp = data;
924  Elf_Internal_Shdr *rela_hdr;
925  bfd_vma addr_offset;
926  void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
927  size_t extsize;
928  bfd_byte *dst_rela;
929  unsigned int idx;
930  asymbol *last_sym;
931  int last_sym_idx;
932
933  /* If we have already failed, don't do anything.  */
934  if (*failedp)
935    return;
936
937  if ((sec->flags & SEC_RELOC) == 0)
938    return;
939
940  /* The linker backend writes the relocs out itself, and sets the
941     reloc_count field to zero to inhibit writing them here.  Also,
942     sometimes the SEC_RELOC flag gets set even when there aren't any
943     relocs.  */
944  if (sec->reloc_count == 0)
945    return;
946
947  /* If we have opened an existing file for update, reloc_count may be
948     set even though we are not linking.  In that case we have nothing
949     to do.  */
950  if (sec->orelocation == NULL)
951    return;
952
953  rela_hdr = &elf_section_data (sec)->rel_hdr;
954
955  rela_hdr->sh_size = rela_hdr->sh_entsize * sec->reloc_count;
956  rela_hdr->contents = bfd_alloc (abfd, rela_hdr->sh_size);
957  if (rela_hdr->contents == NULL)
958    {
959      *failedp = TRUE;
960      return;
961    }
962
963  /* Figure out whether the relocations are RELA or REL relocations.  */
964  if (rela_hdr->sh_type == SHT_RELA)
965    {
966      swap_out = elf_swap_reloca_out;
967      extsize = sizeof (Elf_External_Rela);
968    }
969  else if (rela_hdr->sh_type == SHT_REL)
970    {
971      swap_out = elf_swap_reloc_out;
972      extsize = sizeof (Elf_External_Rel);
973    }
974  else
975    /* Every relocation section should be either an SHT_RELA or an
976       SHT_REL section.  */
977    abort ();
978
979  /* The address of an ELF reloc is section relative for an object
980     file, and absolute for an executable file or shared library.
981     The address of a BFD reloc is always section relative.  */
982  addr_offset = 0;
983  if ((abfd->flags & (EXEC_P | DYNAMIC)) != 0)
984    addr_offset = sec->vma;
985
986  /* orelocation has the data, reloc_count has the count...  */
987  last_sym = 0;
988  last_sym_idx = 0;
989  dst_rela = rela_hdr->contents;
990
991  for (idx = 0; idx < sec->reloc_count; idx++, dst_rela += extsize)
992    {
993      Elf_Internal_Rela src_rela;
994      arelent *ptr;
995      asymbol *sym;
996      int n;
997
998      ptr = sec->orelocation[idx];
999      sym = *ptr->sym_ptr_ptr;
1000      if (sym == last_sym)
1001	n = last_sym_idx;
1002      else if (bfd_is_abs_section (sym->section) && sym->value == 0)
1003	n = STN_UNDEF;
1004      else
1005	{
1006	  last_sym = sym;
1007	  n = _bfd_elf_symbol_from_bfd_symbol (abfd, &sym);
1008	  if (n < 0)
1009	    {
1010	      *failedp = TRUE;
1011	      return;
1012	    }
1013	  last_sym_idx = n;
1014	}
1015
1016      if ((*ptr->sym_ptr_ptr)->the_bfd != NULL
1017	  && (*ptr->sym_ptr_ptr)->the_bfd->xvec != abfd->xvec
1018	  && ! _bfd_elf_validate_reloc (abfd, ptr))
1019	{
1020	  *failedp = TRUE;
1021	  return;
1022	}
1023
1024      src_rela.r_offset = ptr->address + addr_offset;
1025      src_rela.r_info = ELF_R_INFO (n, ptr->howto->type);
1026      src_rela.r_addend = ptr->addend;
1027      (*swap_out) (abfd, &src_rela, dst_rela);
1028    }
1029}
1030
1031/* Write out the program headers.  */
1032
1033int
1034elf_write_out_phdrs (bfd *abfd,
1035		     const Elf_Internal_Phdr *phdr,
1036		     unsigned int count)
1037{
1038  while (count--)
1039    {
1040      Elf_External_Phdr extphdr;
1041      elf_swap_phdr_out (abfd, phdr, &extphdr);
1042      if (bfd_bwrite (&extphdr, sizeof (Elf_External_Phdr), abfd)
1043	  != sizeof (Elf_External_Phdr))
1044	return -1;
1045      phdr++;
1046    }
1047  return 0;
1048}
1049
1050/* Write out the section headers and the ELF file header.  */
1051
1052bfd_boolean
1053elf_write_shdrs_and_ehdr (bfd *abfd)
1054{
1055  Elf_External_Ehdr x_ehdr;	/* Elf file header, external form */
1056  Elf_Internal_Ehdr *i_ehdrp;	/* Elf file header, internal form */
1057  Elf_External_Shdr *x_shdrp;	/* Section header table, external form */
1058  Elf_Internal_Shdr **i_shdrp;	/* Section header table, internal form */
1059  unsigned int count;
1060  bfd_size_type amt;
1061
1062  i_ehdrp = elf_elfheader (abfd);
1063  i_shdrp = elf_elfsections (abfd);
1064
1065  /* swap the header before spitting it out...  */
1066
1067#if DEBUG & 1
1068  elf_debug_file (i_ehdrp);
1069#endif
1070  elf_swap_ehdr_out (abfd, i_ehdrp, &x_ehdr);
1071  amt = sizeof (x_ehdr);
1072  if (bfd_seek (abfd, (file_ptr) 0, SEEK_SET) != 0
1073      || bfd_bwrite (&x_ehdr, amt, abfd) != amt)
1074    return FALSE;
1075
1076  /* Some fields in the first section header handle overflow of ehdr
1077     fields.  */
1078  if (i_ehdrp->e_shnum >= SHN_LORESERVE)
1079    i_shdrp[0]->sh_size = i_ehdrp->e_shnum;
1080  if (i_ehdrp->e_shstrndx >= SHN_LORESERVE)
1081    i_shdrp[0]->sh_link = i_ehdrp->e_shstrndx;
1082
1083  /* at this point we've concocted all the ELF sections...  */
1084  amt = i_ehdrp->e_shnum;
1085  amt *= sizeof (*x_shdrp);
1086  x_shdrp = bfd_alloc (abfd, amt);
1087  if (!x_shdrp)
1088    return FALSE;
1089
1090  for (count = 0; count < i_ehdrp->e_shnum; i_shdrp++, count++)
1091    {
1092#if DEBUG & 2
1093      elf_debug_section (count, *i_shdrp);
1094#endif
1095      elf_swap_shdr_out (abfd, *i_shdrp, x_shdrp + count);
1096
1097      if (count == SHN_LORESERVE - 1)
1098	i_shdrp += SHN_HIRESERVE + 1 - SHN_LORESERVE;
1099    }
1100  if (bfd_seek (abfd, (file_ptr) i_ehdrp->e_shoff, SEEK_SET) != 0
1101      || bfd_bwrite (x_shdrp, amt, abfd) != amt)
1102    return FALSE;
1103
1104  /* need to dump the string table too...  */
1105
1106  return TRUE;
1107}
1108
1109bfd_boolean
1110elf_checksum_contents (bfd *abfd,
1111		       void (*process) (const void *, size_t, void *),
1112		       void *arg)
1113{
1114  Elf_Internal_Ehdr *i_ehdrp = elf_elfheader (abfd);
1115  Elf_Internal_Shdr **i_shdrp = elf_elfsections (abfd);
1116  Elf_Internal_Phdr *i_phdrp = elf_tdata (abfd)->phdr;
1117  unsigned int count, num;
1118
1119  {
1120    Elf_External_Ehdr x_ehdr;
1121    Elf_Internal_Ehdr i_ehdr;
1122
1123    i_ehdr = *i_ehdrp;
1124    i_ehdr.e_phoff = i_ehdr.e_shoff = 0;
1125    elf_swap_ehdr_out (abfd, &i_ehdr, &x_ehdr);
1126    (*process) (&x_ehdr, sizeof x_ehdr, arg);
1127  }
1128
1129  num = i_ehdrp->e_phnum;
1130  for (count = 0; count < num; count++)
1131    {
1132      Elf_External_Phdr x_phdr;
1133      elf_swap_phdr_out (abfd, &i_phdrp[count], &x_phdr);
1134      (*process) (&x_phdr, sizeof x_phdr, arg);
1135    }
1136
1137  num = elf_numsections (abfd);
1138  for (count = 0; count < num; count++)
1139    {
1140      Elf_Internal_Shdr i_shdr;
1141      Elf_External_Shdr x_shdr;
1142
1143      i_shdr = *i_shdrp[count];
1144      i_shdr.sh_offset = 0;
1145
1146      elf_swap_shdr_out (abfd, &i_shdr, &x_shdr);
1147      (*process) (&x_shdr, sizeof x_shdr, arg);
1148
1149      if (i_shdr.contents)
1150	(*process) (i_shdr.contents, i_shdr.sh_size, arg);
1151    }
1152
1153  return TRUE;
1154}
1155
1156long
1157elf_slurp_symbol_table (bfd *abfd, asymbol **symptrs, bfd_boolean dynamic)
1158{
1159  Elf_Internal_Shdr *hdr;
1160  Elf_Internal_Shdr *verhdr;
1161  unsigned long symcount;	/* Number of external ELF symbols */
1162  elf_symbol_type *sym;		/* Pointer to current bfd symbol */
1163  elf_symbol_type *symbase;	/* Buffer for generated bfd symbols */
1164  Elf_Internal_Sym *isym;
1165  Elf_Internal_Sym *isymend;
1166  Elf_Internal_Sym *isymbuf = NULL;
1167  Elf_External_Versym *xver;
1168  Elf_External_Versym *xverbuf = NULL;
1169  const struct elf_backend_data *ebd;
1170  bfd_size_type amt;
1171
1172  /* Read each raw ELF symbol, converting from external ELF form to
1173     internal ELF form, and then using the information to create a
1174     canonical bfd symbol table entry.
1175
1176     Note that we allocate the initial bfd canonical symbol buffer
1177     based on a one-to-one mapping of the ELF symbols to canonical
1178     symbols.  We actually use all the ELF symbols, so there will be no
1179     space left over at the end.  When we have all the symbols, we
1180     build the caller's pointer vector.  */
1181
1182  if (! dynamic)
1183    {
1184      hdr = &elf_tdata (abfd)->symtab_hdr;
1185      verhdr = NULL;
1186    }
1187  else
1188    {
1189      hdr = &elf_tdata (abfd)->dynsymtab_hdr;
1190      if (elf_dynversym (abfd) == 0)
1191	verhdr = NULL;
1192      else
1193	verhdr = &elf_tdata (abfd)->dynversym_hdr;
1194      if ((elf_tdata (abfd)->dynverdef_section != 0
1195	   && elf_tdata (abfd)->verdef == NULL)
1196	  || (elf_tdata (abfd)->dynverref_section != 0
1197	      && elf_tdata (abfd)->verref == NULL))
1198	{
1199	  if (!_bfd_elf_slurp_version_tables (abfd, FALSE))
1200	    return -1;
1201	}
1202    }
1203
1204  ebd = get_elf_backend_data (abfd);
1205  symcount = hdr->sh_size / sizeof (Elf_External_Sym);
1206  if (symcount == 0)
1207    sym = symbase = NULL;
1208  else
1209    {
1210      isymbuf = bfd_elf_get_elf_syms (abfd, hdr, symcount, 0,
1211				      NULL, NULL, NULL);
1212      if (isymbuf == NULL)
1213	return -1;
1214
1215      amt = symcount;
1216      amt *= sizeof (elf_symbol_type);
1217      symbase = bfd_zalloc (abfd, amt);
1218      if (symbase == (elf_symbol_type *) NULL)
1219	goto error_return;
1220
1221      /* Read the raw ELF version symbol information.  */
1222      if (verhdr != NULL
1223	  && verhdr->sh_size / sizeof (Elf_External_Versym) != symcount)
1224	{
1225	  (*_bfd_error_handler)
1226	    (_("%s: version count (%ld) does not match symbol count (%ld)"),
1227	     abfd->filename,
1228	     (long) (verhdr->sh_size / sizeof (Elf_External_Versym)),
1229	     symcount);
1230
1231	  /* Slurp in the symbols without the version information,
1232	     since that is more helpful than just quitting.  */
1233	  verhdr = NULL;
1234	}
1235
1236      if (verhdr != NULL)
1237	{
1238	  if (bfd_seek (abfd, verhdr->sh_offset, SEEK_SET) != 0)
1239	    goto error_return;
1240
1241	  xverbuf = bfd_malloc (verhdr->sh_size);
1242	  if (xverbuf == NULL && verhdr->sh_size != 0)
1243	    goto error_return;
1244
1245	  if (bfd_bread (xverbuf, verhdr->sh_size, abfd) != verhdr->sh_size)
1246	    goto error_return;
1247	}
1248
1249      /* Skip first symbol, which is a null dummy.  */
1250      xver = xverbuf;
1251      if (xver != NULL)
1252	++xver;
1253      isymend = isymbuf + symcount;
1254      for (isym = isymbuf + 1, sym = symbase; isym < isymend; isym++, sym++)
1255	{
1256	  memcpy (&sym->internal_elf_sym, isym, sizeof (Elf_Internal_Sym));
1257	  sym->symbol.the_bfd = abfd;
1258
1259	  sym->symbol.name = bfd_elf_sym_name (abfd, hdr, isym, NULL);
1260
1261	  sym->symbol.value = isym->st_value;
1262
1263	  if (isym->st_shndx == SHN_UNDEF)
1264	    {
1265	      sym->symbol.section = bfd_und_section_ptr;
1266	    }
1267	  else if (isym->st_shndx < SHN_LORESERVE
1268		   || isym->st_shndx > SHN_HIRESERVE)
1269	    {
1270	      sym->symbol.section = bfd_section_from_elf_index (abfd,
1271								isym->st_shndx);
1272	      if (sym->symbol.section == NULL)
1273		{
1274		  /* This symbol is in a section for which we did not
1275		     create a BFD section.  Just use bfd_abs_section,
1276		     although it is wrong.  FIXME.  */
1277		  sym->symbol.section = bfd_abs_section_ptr;
1278		}
1279	    }
1280	  else if (isym->st_shndx == SHN_ABS)
1281	    {
1282	      sym->symbol.section = bfd_abs_section_ptr;
1283	    }
1284	  else if (isym->st_shndx == SHN_COMMON)
1285	    {
1286	      sym->symbol.section = bfd_com_section_ptr;
1287	      /* Elf puts the alignment into the `value' field, and
1288		 the size into the `size' field.  BFD wants to see the
1289		 size in the value field, and doesn't care (at the
1290		 moment) about the alignment.  */
1291	      sym->symbol.value = isym->st_size;
1292	    }
1293	  else
1294	    sym->symbol.section = bfd_abs_section_ptr;
1295
1296	  /* If this is a relocatable file, then the symbol value is
1297	     already section relative.  */
1298	  if ((abfd->flags & (EXEC_P | DYNAMIC)) != 0)
1299	    sym->symbol.value -= sym->symbol.section->vma;
1300
1301	  switch (ELF_ST_BIND (isym->st_info))
1302	    {
1303	    case STB_LOCAL:
1304	      sym->symbol.flags |= BSF_LOCAL;
1305	      break;
1306	    case STB_GLOBAL:
1307	      if (isym->st_shndx != SHN_UNDEF && isym->st_shndx != SHN_COMMON)
1308		sym->symbol.flags |= BSF_GLOBAL;
1309	      break;
1310	    case STB_WEAK:
1311	      sym->symbol.flags |= BSF_WEAK;
1312	      break;
1313	    }
1314
1315	  switch (ELF_ST_TYPE (isym->st_info))
1316	    {
1317	    case STT_SECTION:
1318	      sym->symbol.flags |= BSF_SECTION_SYM | BSF_DEBUGGING;
1319	      break;
1320	    case STT_FILE:
1321	      sym->symbol.flags |= BSF_FILE | BSF_DEBUGGING;
1322	      break;
1323	    case STT_FUNC:
1324	      sym->symbol.flags |= BSF_FUNCTION;
1325	      break;
1326	    case STT_OBJECT:
1327	      sym->symbol.flags |= BSF_OBJECT;
1328	      break;
1329	    case STT_TLS:
1330	      sym->symbol.flags |= BSF_THREAD_LOCAL;
1331	      break;
1332	    case STT_RELC:
1333	      sym->symbol.flags |= BSF_RELC;
1334	      break;
1335	    case STT_SRELC:
1336	      sym->symbol.flags |= BSF_SRELC;
1337	      break;
1338	    }
1339
1340	  if (dynamic)
1341	    sym->symbol.flags |= BSF_DYNAMIC;
1342
1343	  if (xver != NULL)
1344	    {
1345	      Elf_Internal_Versym iversym;
1346
1347	      _bfd_elf_swap_versym_in (abfd, xver, &iversym);
1348	      sym->version = iversym.vs_vers;
1349	      xver++;
1350	    }
1351
1352	  /* Do some backend-specific processing on this symbol.  */
1353	  if (ebd->elf_backend_symbol_processing)
1354	    (*ebd->elf_backend_symbol_processing) (abfd, &sym->symbol);
1355	}
1356    }
1357
1358  /* Do some backend-specific processing on this symbol table.  */
1359  if (ebd->elf_backend_symbol_table_processing)
1360    (*ebd->elf_backend_symbol_table_processing) (abfd, symbase, symcount);
1361
1362  /* We rely on the zalloc to clear out the final symbol entry.  */
1363
1364  symcount = sym - symbase;
1365
1366  /* Fill in the user's symbol pointer vector if needed.  */
1367  if (symptrs)
1368    {
1369      long l = symcount;
1370
1371      sym = symbase;
1372      while (l-- > 0)
1373	{
1374	  *symptrs++ = &sym->symbol;
1375	  sym++;
1376	}
1377      *symptrs = 0;		/* Final null pointer */
1378    }
1379
1380  if (xverbuf != NULL)
1381    free (xverbuf);
1382  if (isymbuf != NULL && hdr->contents != (unsigned char *) isymbuf)
1383    free (isymbuf);
1384  return symcount;
1385
1386error_return:
1387  if (xverbuf != NULL)
1388    free (xverbuf);
1389  if (isymbuf != NULL && hdr->contents != (unsigned char *) isymbuf)
1390    free (isymbuf);
1391  return -1;
1392}
1393
1394/* Read relocations for ASECT from REL_HDR.  There are RELOC_COUNT of
1395   them.  */
1396
1397static bfd_boolean
1398elf_slurp_reloc_table_from_section (bfd *abfd,
1399				    asection *asect,
1400				    Elf_Internal_Shdr *rel_hdr,
1401				    bfd_size_type reloc_count,
1402				    arelent *relents,
1403				    asymbol **symbols,
1404				    bfd_boolean dynamic)
1405{
1406  const struct elf_backend_data * const ebd = get_elf_backend_data (abfd);
1407  void *allocated = NULL;
1408  bfd_byte *native_relocs;
1409  arelent *relent;
1410  unsigned int i;
1411  int entsize;
1412  unsigned int symcount;
1413
1414  allocated = bfd_malloc (rel_hdr->sh_size);
1415  if (allocated == NULL)
1416    goto error_return;
1417
1418  if (bfd_seek (abfd, rel_hdr->sh_offset, SEEK_SET) != 0
1419      || (bfd_bread (allocated, rel_hdr->sh_size, abfd)
1420	  != rel_hdr->sh_size))
1421    goto error_return;
1422
1423  native_relocs = allocated;
1424
1425  entsize = rel_hdr->sh_entsize;
1426  BFD_ASSERT (entsize == sizeof (Elf_External_Rel)
1427	      || entsize == sizeof (Elf_External_Rela));
1428
1429  if (dynamic)
1430    symcount = bfd_get_dynamic_symcount (abfd);
1431  else
1432    symcount = bfd_get_symcount (abfd);
1433
1434  for (i = 0, relent = relents;
1435       i < reloc_count;
1436       i++, relent++, native_relocs += entsize)
1437    {
1438      Elf_Internal_Rela rela;
1439
1440      if (entsize == sizeof (Elf_External_Rela))
1441	elf_swap_reloca_in (abfd, native_relocs, &rela);
1442      else
1443	elf_swap_reloc_in (abfd, native_relocs, &rela);
1444
1445      /* The address of an ELF reloc is section relative for an object
1446	 file, and absolute for an executable file or shared library.
1447	 The address of a normal BFD reloc is always section relative,
1448	 and the address of a dynamic reloc is absolute..  */
1449      if ((abfd->flags & (EXEC_P | DYNAMIC)) == 0 || dynamic)
1450	relent->address = rela.r_offset;
1451      else
1452	relent->address = rela.r_offset - asect->vma;
1453
1454      if (ELF_R_SYM (rela.r_info) == 0)
1455	relent->sym_ptr_ptr = bfd_abs_section_ptr->symbol_ptr_ptr;
1456      else if (ELF_R_SYM (rela.r_info) > symcount)
1457	{
1458	  (*_bfd_error_handler)
1459	    (_("%s(%s): relocation %d has invalid symbol index %ld"),
1460	     abfd->filename, asect->name, i, ELF_R_SYM (rela.r_info));
1461	  relent->sym_ptr_ptr = bfd_abs_section.symbol_ptr_ptr;
1462	}
1463      else
1464	{
1465	  asymbol **ps;
1466
1467	  ps = symbols + ELF_R_SYM (rela.r_info) - 1;
1468
1469	  relent->sym_ptr_ptr = ps;
1470	}
1471
1472      relent->addend = rela.r_addend;
1473
1474      if ((entsize == sizeof (Elf_External_Rela)
1475	   && ebd->elf_info_to_howto != NULL)
1476	  || ebd->elf_info_to_howto_rel == NULL)
1477	(*ebd->elf_info_to_howto) (abfd, relent, &rela);
1478      else
1479	(*ebd->elf_info_to_howto_rel) (abfd, relent, &rela);
1480    }
1481
1482  if (allocated != NULL)
1483    free (allocated);
1484
1485  return TRUE;
1486
1487 error_return:
1488  if (allocated != NULL)
1489    free (allocated);
1490  return FALSE;
1491}
1492
1493/* Read in and swap the external relocs.  */
1494
1495bfd_boolean
1496elf_slurp_reloc_table (bfd *abfd,
1497		       asection *asect,
1498		       asymbol **symbols,
1499		       bfd_boolean dynamic)
1500{
1501  struct bfd_elf_section_data * const d = elf_section_data (asect);
1502  Elf_Internal_Shdr *rel_hdr;
1503  Elf_Internal_Shdr *rel_hdr2;
1504  bfd_size_type reloc_count;
1505  bfd_size_type reloc_count2;
1506  arelent *relents;
1507  bfd_size_type amt;
1508
1509  if (asect->relocation != NULL)
1510    return TRUE;
1511
1512  if (! dynamic)
1513    {
1514      if ((asect->flags & SEC_RELOC) == 0
1515	  || asect->reloc_count == 0)
1516	return TRUE;
1517
1518      rel_hdr = &d->rel_hdr;
1519      reloc_count = NUM_SHDR_ENTRIES (rel_hdr);
1520      rel_hdr2 = d->rel_hdr2;
1521      reloc_count2 = (rel_hdr2 ? NUM_SHDR_ENTRIES (rel_hdr2) : 0);
1522
1523      BFD_ASSERT (asect->reloc_count == reloc_count + reloc_count2);
1524      BFD_ASSERT (asect->rel_filepos == rel_hdr->sh_offset
1525		  || (rel_hdr2 && asect->rel_filepos == rel_hdr2->sh_offset));
1526
1527    }
1528  else
1529    {
1530      /* Note that ASECT->RELOC_COUNT tends not to be accurate in this
1531	 case because relocations against this section may use the
1532	 dynamic symbol table, and in that case bfd_section_from_shdr
1533	 in elf.c does not update the RELOC_COUNT.  */
1534      if (asect->size == 0)
1535	return TRUE;
1536
1537      rel_hdr = &d->this_hdr;
1538      reloc_count = NUM_SHDR_ENTRIES (rel_hdr);
1539      rel_hdr2 = NULL;
1540      reloc_count2 = 0;
1541    }
1542
1543  amt = (reloc_count + reloc_count2) * sizeof (arelent);
1544  relents = bfd_alloc (abfd, amt);
1545  if (relents == NULL)
1546    return FALSE;
1547
1548  if (!elf_slurp_reloc_table_from_section (abfd, asect,
1549					   rel_hdr, reloc_count,
1550					   relents,
1551					   symbols, dynamic))
1552    return FALSE;
1553
1554  if (rel_hdr2
1555      && !elf_slurp_reloc_table_from_section (abfd, asect,
1556					      rel_hdr2, reloc_count2,
1557					      relents + reloc_count,
1558					      symbols, dynamic))
1559    return FALSE;
1560
1561  asect->relocation = relents;
1562  return TRUE;
1563}
1564
1565#if DEBUG & 2
1566static void
1567elf_debug_section (int num, Elf_Internal_Shdr *hdr)
1568{
1569  fprintf (stderr, "\nSection#%d '%s' 0x%.8lx\n", num,
1570	   hdr->bfd_section != NULL ? hdr->bfd_section->name : "",
1571	   (long) hdr);
1572  fprintf (stderr,
1573	   "sh_name      = %ld\tsh_type      = %ld\tsh_flags     = %ld\n",
1574	   (long) hdr->sh_name,
1575	   (long) hdr->sh_type,
1576	   (long) hdr->sh_flags);
1577  fprintf (stderr,
1578	   "sh_addr      = %ld\tsh_offset    = %ld\tsh_size      = %ld\n",
1579	   (long) hdr->sh_addr,
1580	   (long) hdr->sh_offset,
1581	   (long) hdr->sh_size);
1582  fprintf (stderr,
1583	   "sh_link      = %ld\tsh_info      = %ld\tsh_addralign = %ld\n",
1584	   (long) hdr->sh_link,
1585	   (long) hdr->sh_info,
1586	   (long) hdr->sh_addralign);
1587  fprintf (stderr, "sh_entsize   = %ld\n",
1588	   (long) hdr->sh_entsize);
1589  fflush (stderr);
1590}
1591#endif
1592
1593#if DEBUG & 1
1594static void
1595elf_debug_file (Elf_Internal_Ehdr *ehdrp)
1596{
1597  fprintf (stderr, "e_entry      = 0x%.8lx\n", (long) ehdrp->e_entry);
1598  fprintf (stderr, "e_phoff      = %ld\n", (long) ehdrp->e_phoff);
1599  fprintf (stderr, "e_phnum      = %ld\n", (long) ehdrp->e_phnum);
1600  fprintf (stderr, "e_phentsize  = %ld\n", (long) ehdrp->e_phentsize);
1601  fprintf (stderr, "e_shoff      = %ld\n", (long) ehdrp->e_shoff);
1602  fprintf (stderr, "e_shnum      = %ld\n", (long) ehdrp->e_shnum);
1603  fprintf (stderr, "e_shentsize  = %ld\n", (long) ehdrp->e_shentsize);
1604}
1605#endif
1606
1607/* Create a new BFD as if by bfd_openr.  Rather than opening a file,
1608   reconstruct an ELF file by reading the segments out of remote memory
1609   based on the ELF file header at EHDR_VMA and the ELF program headers it
1610   points to.  If not null, *LOADBASEP is filled in with the difference
1611   between the VMAs from which the segments were read, and the VMAs the
1612   file headers (and hence BFD's idea of each section's VMA) put them at.
1613
1614   The function TARGET_READ_MEMORY is called to copy LEN bytes from the
1615   remote memory at target address VMA into the local buffer at MYADDR; it
1616   should return zero on success or an `errno' code on failure.  TEMPL must
1617   be a BFD for a target with the word size and byte order found in the
1618   remote memory.  */
1619
1620bfd *
1621NAME(_bfd_elf,bfd_from_remote_memory)
1622  (bfd *templ,
1623   bfd_vma ehdr_vma,
1624   bfd_vma *loadbasep,
1625   int (*target_read_memory) (bfd_vma, bfd_byte *, int))
1626{
1627  Elf_External_Ehdr x_ehdr;	/* Elf file header, external form */
1628  Elf_Internal_Ehdr i_ehdr;	/* Elf file header, internal form */
1629  Elf_External_Phdr *x_phdrs;
1630  Elf_Internal_Phdr *i_phdrs, *last_phdr;
1631  bfd *nbfd;
1632  struct bfd_in_memory *bim;
1633  int contents_size;
1634  bfd_byte *contents;
1635  int err;
1636  unsigned int i;
1637  bfd_vma loadbase;
1638  bfd_boolean loadbase_set;
1639
1640  /* Read in the ELF header in external format.  */
1641  err = target_read_memory (ehdr_vma, (bfd_byte *) &x_ehdr, sizeof x_ehdr);
1642  if (err)
1643    {
1644      bfd_set_error (bfd_error_system_call);
1645      errno = err;
1646      return NULL;
1647    }
1648
1649  /* Now check to see if we have a valid ELF file, and one that BFD can
1650     make use of.  The magic number must match, the address size ('class')
1651     and byte-swapping must match our XVEC entry.  */
1652
1653  if (! elf_file_p (&x_ehdr)
1654      || x_ehdr.e_ident[EI_VERSION] != EV_CURRENT
1655      || x_ehdr.e_ident[EI_CLASS] != ELFCLASS)
1656    {
1657      bfd_set_error (bfd_error_wrong_format);
1658      return NULL;
1659    }
1660
1661  /* Check that file's byte order matches xvec's */
1662  switch (x_ehdr.e_ident[EI_DATA])
1663    {
1664    case ELFDATA2MSB:		/* Big-endian */
1665      if (! bfd_header_big_endian (templ))
1666	{
1667	  bfd_set_error (bfd_error_wrong_format);
1668	  return NULL;
1669	}
1670      break;
1671    case ELFDATA2LSB:		/* Little-endian */
1672      if (! bfd_header_little_endian (templ))
1673	{
1674	  bfd_set_error (bfd_error_wrong_format);
1675	  return NULL;
1676	}
1677      break;
1678    case ELFDATANONE:		/* No data encoding specified */
1679    default:			/* Unknown data encoding specified */
1680      bfd_set_error (bfd_error_wrong_format);
1681      return NULL;
1682    }
1683
1684  elf_swap_ehdr_in (templ, &x_ehdr, &i_ehdr);
1685
1686  /* The file header tells where to find the program headers.
1687     These are what we use to actually choose what to read.  */
1688
1689  if (i_ehdr.e_phentsize != sizeof (Elf_External_Phdr) || i_ehdr.e_phnum == 0)
1690    {
1691      bfd_set_error (bfd_error_wrong_format);
1692      return NULL;
1693    }
1694
1695  x_phdrs = bfd_malloc (i_ehdr.e_phnum * (sizeof *x_phdrs + sizeof *i_phdrs));
1696  if (x_phdrs == NULL)
1697    {
1698      bfd_set_error (bfd_error_no_memory);
1699      return NULL;
1700    }
1701  err = target_read_memory (ehdr_vma + i_ehdr.e_phoff, (bfd_byte *) x_phdrs,
1702			    i_ehdr.e_phnum * sizeof x_phdrs[0]);
1703  if (err)
1704    {
1705      free (x_phdrs);
1706      bfd_set_error (bfd_error_system_call);
1707      errno = err;
1708      return NULL;
1709    }
1710  i_phdrs = (Elf_Internal_Phdr *) &x_phdrs[i_ehdr.e_phnum];
1711
1712  contents_size = 0;
1713  last_phdr = NULL;
1714  loadbase = ehdr_vma;
1715  loadbase_set = FALSE;
1716  for (i = 0; i < i_ehdr.e_phnum; ++i)
1717    {
1718      elf_swap_phdr_in (templ, &x_phdrs[i], &i_phdrs[i]);
1719      if (i_phdrs[i].p_type == PT_LOAD)
1720	{
1721	  bfd_vma segment_end;
1722	  segment_end = (i_phdrs[i].p_offset + i_phdrs[i].p_filesz
1723			 + i_phdrs[i].p_align - 1) & -i_phdrs[i].p_align;
1724	  if (segment_end > (bfd_vma) contents_size)
1725	    contents_size = segment_end;
1726
1727	  /* LOADADDR is the `Base address' from the gELF specification:
1728	     `lowest p_vaddr value for a PT_LOAD segment' is P_VADDR from the
1729	     first PT_LOAD as PT_LOADs are ordered by P_VADDR.  */
1730	  if (!loadbase_set && (i_phdrs[i].p_offset & -i_phdrs[i].p_align) == 0)
1731	    {
1732	      loadbase = ehdr_vma - (i_phdrs[i].p_vaddr & -i_phdrs[i].p_align);
1733	      loadbase_set = TRUE;
1734	    }
1735
1736	  last_phdr = &i_phdrs[i];
1737	}
1738    }
1739  if (last_phdr == NULL)
1740    {
1741      /* There were no PT_LOAD segments, so we don't have anything to read.  */
1742      free (x_phdrs);
1743      bfd_set_error (bfd_error_wrong_format);
1744      return NULL;
1745    }
1746
1747  /* Trim the last segment so we don't bother with zeros in the last page
1748     that are off the end of the file.  However, if the extra bit in that
1749     page includes the section headers, keep them.  */
1750  if ((bfd_vma) contents_size > last_phdr->p_offset + last_phdr->p_filesz
1751      && (bfd_vma) contents_size >= (i_ehdr.e_shoff
1752				     + i_ehdr.e_shnum * i_ehdr.e_shentsize))
1753    {
1754      contents_size = last_phdr->p_offset + last_phdr->p_filesz;
1755      if ((bfd_vma) contents_size < (i_ehdr.e_shoff
1756				     + i_ehdr.e_shnum * i_ehdr.e_shentsize))
1757	contents_size = i_ehdr.e_shoff + i_ehdr.e_shnum * i_ehdr.e_shentsize;
1758    }
1759  else
1760    contents_size = last_phdr->p_offset + last_phdr->p_filesz;
1761
1762  /* Now we know the size of the whole image we want read in.  */
1763  contents = bfd_zmalloc (contents_size);
1764  if (contents == NULL)
1765    {
1766      free (x_phdrs);
1767      bfd_set_error (bfd_error_no_memory);
1768      return NULL;
1769    }
1770
1771  for (i = 0; i < i_ehdr.e_phnum; ++i)
1772    if (i_phdrs[i].p_type == PT_LOAD)
1773      {
1774	bfd_vma start = i_phdrs[i].p_offset & -i_phdrs[i].p_align;
1775	bfd_vma end = (i_phdrs[i].p_offset + i_phdrs[i].p_filesz
1776		       + i_phdrs[i].p_align - 1) & -i_phdrs[i].p_align;
1777	if (end > (bfd_vma) contents_size)
1778	  end = contents_size;
1779	err = target_read_memory ((loadbase + i_phdrs[i].p_vaddr)
1780				  & -i_phdrs[i].p_align,
1781				  contents + start, end - start);
1782	if (err)
1783	  {
1784	    free (x_phdrs);
1785	    free (contents);
1786	    bfd_set_error (bfd_error_system_call);
1787	    errno = err;
1788	    return NULL;
1789	  }
1790      }
1791  free (x_phdrs);
1792
1793  /* If the segments visible in memory didn't include the section headers,
1794     then clear them from the file header.  */
1795  if ((bfd_vma) contents_size < (i_ehdr.e_shoff
1796				 + i_ehdr.e_shnum * i_ehdr.e_shentsize))
1797    {
1798      memset (&x_ehdr.e_shoff, 0, sizeof x_ehdr.e_shoff);
1799      memset (&x_ehdr.e_shnum, 0, sizeof x_ehdr.e_shnum);
1800      memset (&x_ehdr.e_shstrndx, 0, sizeof x_ehdr.e_shstrndx);
1801    }
1802
1803  /* This will normally have been in the first PT_LOAD segment.  But it
1804     conceivably could be missing, and we might have just changed it.  */
1805  memcpy (contents, &x_ehdr, sizeof x_ehdr);
1806
1807  /* Now we have a memory image of the ELF file contents.  Make a BFD.  */
1808  bim = bfd_malloc (sizeof (struct bfd_in_memory));
1809  if (bim == NULL)
1810    {
1811      free (contents);
1812      bfd_set_error (bfd_error_no_memory);
1813      return NULL;
1814    }
1815  nbfd = _bfd_new_bfd ();
1816  if (nbfd == NULL)
1817    {
1818      free (bim);
1819      free (contents);
1820      bfd_set_error (bfd_error_no_memory);
1821      return NULL;
1822    }
1823  nbfd->filename = "<in-memory>";
1824  nbfd->xvec = templ->xvec;
1825  bim->size = contents_size;
1826  bim->buffer = contents;
1827  nbfd->iostream = bim;
1828  nbfd->flags = BFD_IN_MEMORY;
1829  nbfd->direction = read_direction;
1830  nbfd->mtime = time (NULL);
1831  nbfd->mtime_set = TRUE;
1832
1833  if (loadbasep)
1834    *loadbasep = loadbase;
1835  return nbfd;
1836}
1837
1838#include "elfcore.h"
1839
1840/* Size-dependent data and functions.  */
1841const struct elf_size_info NAME(_bfd_elf,size_info) = {
1842  sizeof (Elf_External_Ehdr),
1843  sizeof (Elf_External_Phdr),
1844  sizeof (Elf_External_Shdr),
1845  sizeof (Elf_External_Rel),
1846  sizeof (Elf_External_Rela),
1847  sizeof (Elf_External_Sym),
1848  sizeof (Elf_External_Dyn),
1849  sizeof (Elf_External_Note),
1850  4,
1851  1,
1852  ARCH_SIZE, LOG_FILE_ALIGN,
1853  ELFCLASS, EV_CURRENT,
1854  elf_write_out_phdrs,
1855  elf_write_shdrs_and_ehdr,
1856  elf_checksum_contents,
1857  elf_write_relocs,
1858  elf_swap_symbol_in,
1859  elf_swap_symbol_out,
1860  elf_slurp_reloc_table,
1861  elf_slurp_symbol_table,
1862  elf_swap_dyn_in,
1863  elf_swap_dyn_out,
1864  elf_swap_reloc_in,
1865  elf_swap_reloc_out,
1866  elf_swap_reloca_in,
1867  elf_swap_reloca_out
1868};
1869