]> Git Repo - binutils.git/blob - bfd/elfcode.h
Don't let netbsd386.c get sanitized out.
[binutils.git] / bfd / elfcode.h
1 /* ELF executable support for BFD.
2    Copyright 1991, 1992, 1993 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
62 #include <assert.h>
63 #include <string.h>             /* For strrchr and friends */
64 #include "bfd.h"
65 #include "sysdep.h"
66 #include "libbfd.h"
67 #include "libelf.h"
68
69 #ifndef alloca
70 PTR alloca ();
71 #endif
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
81 #define elf_symbol_type         NAME(elf,symbol_type)
82
83 #define elf_core_file_failing_command   NAME(bfd_elf,core_file_failing_command)
84 #define elf_core_file_failing_signal    NAME(bfd_elf,core_file_failing_signal)
85 #define elf_core_file_matches_executable_p 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_reloc_upper_bound       NAME(bfd_elf,get_reloc_upper_bound)
90 #define elf_canonicalize_reloc          NAME(bfd_elf,canonicalize_reloc)
91 #define elf_get_symtab                  NAME(bfd_elf,get_symtab)
92 #define elf_make_empty_symbol           NAME(bfd_elf,make_empty_symbol)
93 #define elf_get_symbol_info             NAME(bfd_elf,get_symbol_info)
94 #define elf_print_symbol                NAME(bfd_elf,print_symbol)
95 #define elf_get_lineno                  NAME(bfd_elf,get_lineno)
96 #define elf_set_arch_mach               NAME(bfd_elf,set_arch_mach)
97 #define elf_find_nearest_line           NAME(bfd_elf,find_nearest_line)
98 #define elf_sizeof_headers              NAME(bfd_elf,sizeof_headers)
99 #define elf_set_section_contents        NAME(bfd_elf,set_section_contents)
100 #define elf_no_info_to_howto            NAME(bfd_elf,no_info_to_howto)
101 #define elf_no_info_to_howto_rel        NAME(bfd_elf,no_info_to_howto_rel)
102 #define elf_new_section_hook            NAME(bfd_elf,new_section_hook)
103 #define write_relocs                    NAME(bfd_elf,_write_relocs)
104
105 #if ARCH_SIZE == 64
106 #define ELF_R_INFO(X,Y) ELF64_R_INFO(X,Y)
107 #define ELF_R_SYM(X)    ELF64_R_SYM(X)
108 #define ELFCLASS        ELFCLASS64
109 #endif
110 #if ARCH_SIZE == 32
111 #define ELF_R_INFO(X,Y) ELF32_R_INFO(X,Y)
112 #define ELF_R_SYM(X)    ELF32_R_SYM(X)
113 #define ELFCLASS        ELFCLASS32
114 #endif
115
116 static int shstrtab_length_fixed;
117
118 struct elf_sect_data {
119   int reloc_sec;
120   /* more? */
121 };
122
123 /* Forward declarations of static functions */
124
125 static struct sec * section_from_elf_index PARAMS ((bfd *, int));
126
127 static int elf_section_from_bfd_section PARAMS ((bfd *, struct sec *));
128
129 static boolean elf_slurp_symbol_table PARAMS ((bfd *, asymbol **));
130
131 static int elf_symbol_from_bfd_symbol PARAMS ((bfd *,
132                                                struct symbol_cache_entry **));
133
134 static void elf_map_symbols PARAMS ((bfd *));
135 static void swap_out_syms PARAMS ((bfd *));
136
137 #ifdef DEBUG
138 static void elf_debug_section PARAMS ((char *, int, Elf_Internal_Shdr *));
139 static void elf_debug_file PARAMS ((Elf_Internal_Ehdr *));
140 #endif
141
142 #define elf_string_from_elf_strtab(abfd,strindex) \
143      elf_string_from_elf_section(abfd,elf_elfheader(abfd)->e_shstrndx,strindex)
144
145 \f
146 /* Structure swapping routines */
147
148 /* Should perhaps use put_offset, put_word, etc.  For now, the two versions
149    can be handled by explicitly specifying 32 bits or "the long type".  */
150 #if ARCH_SIZE == 64
151 #define put_word        bfd_h_put_64
152 #define get_word        bfd_h_get_64
153 #endif
154 #if ARCH_SIZE == 32
155 #define put_word        bfd_h_put_32
156 #define get_word        bfd_h_get_32
157 #endif
158
159 /* Translate an ELF symbol in external format into an ELF symbol in internal
160    format. */
161
162 static void
163 DEFUN (elf_swap_symbol_in, (abfd, src, dst),
164        bfd * abfd AND
165        Elf_External_Sym * src AND
166        Elf_Internal_Sym * dst)
167 {
168   dst->st_name = bfd_h_get_32 (abfd, (bfd_byte *) src->st_name);
169   dst->st_value = get_word (abfd, (bfd_byte *) src->st_value);
170   dst->st_size = get_word (abfd, (bfd_byte *) src->st_size);
171   dst->st_info = bfd_h_get_8 (abfd, (bfd_byte *) src->st_info);
172   dst->st_other = bfd_h_get_8 (abfd, (bfd_byte *) src->st_other);
173   dst->st_shndx = bfd_h_get_16 (abfd, (bfd_byte *) src->st_shndx);
174 }
175
176 /* Translate an ELF symbol in internal format into an ELF symbol in external
177    format. */
178
179 static void
180 DEFUN (elf_swap_symbol_out, (abfd, src, dst),
181        bfd * abfd AND
182        Elf_Internal_Sym * src AND
183        Elf_External_Sym * dst)
184 {
185   bfd_h_put_32 (abfd, src->st_name, dst->st_name);
186   put_word (abfd, src->st_value, dst->st_value);
187   put_word (abfd, src->st_size, dst->st_size);
188   bfd_h_put_8 (abfd, src->st_info, dst->st_info);
189   bfd_h_put_8 (abfd, src->st_other, dst->st_other);
190   bfd_h_put_16 (abfd, src->st_shndx, dst->st_shndx);
191 }
192
193
194 /* Translate an ELF file header in external format into an ELF file header in
195    internal format. */
196
197 static void
198 DEFUN (elf_swap_ehdr_in, (abfd, src, dst),
199        bfd * abfd AND
200        Elf_External_Ehdr * src AND
201        Elf_Internal_Ehdr * dst)
202 {
203   memcpy (dst->e_ident, src->e_ident, EI_NIDENT);
204   dst->e_type = bfd_h_get_16 (abfd, (bfd_byte *) src->e_type);
205   dst->e_machine = bfd_h_get_16 (abfd, (bfd_byte *) src->e_machine);
206   dst->e_version = bfd_h_get_32 (abfd, (bfd_byte *) src->e_version);
207   dst->e_entry = get_word (abfd, (bfd_byte *) src->e_entry);
208   dst->e_phoff = get_word (abfd, (bfd_byte *) src->e_phoff);
209   dst->e_shoff = get_word (abfd, (bfd_byte *) src->e_shoff);
210   dst->e_flags = bfd_h_get_32 (abfd, (bfd_byte *) src->e_flags);
211   dst->e_ehsize = bfd_h_get_16 (abfd, (bfd_byte *) src->e_ehsize);
212   dst->e_phentsize = bfd_h_get_16 (abfd, (bfd_byte *) src->e_phentsize);
213   dst->e_phnum = bfd_h_get_16 (abfd, (bfd_byte *) src->e_phnum);
214   dst->e_shentsize = bfd_h_get_16 (abfd, (bfd_byte *) src->e_shentsize);
215   dst->e_shnum = bfd_h_get_16 (abfd, (bfd_byte *) src->e_shnum);
216   dst->e_shstrndx = bfd_h_get_16 (abfd, (bfd_byte *) src->e_shstrndx);
217 }
218
219 /* Translate an ELF file header in internal format into an ELF file header in
220    external format. */
221
222 static void
223 DEFUN (elf_swap_ehdr_out, (abfd, src, dst),
224        bfd * abfd AND
225        Elf_Internal_Ehdr * src AND
226        Elf_External_Ehdr * dst)
227 {
228   memcpy (dst->e_ident, src->e_ident, EI_NIDENT);
229   /* note that all elements of dst are *arrays of unsigned char* already... */
230   bfd_h_put_16 (abfd, src->e_type, dst->e_type);
231   bfd_h_put_16 (abfd, src->e_machine, dst->e_machine);
232   bfd_h_put_32 (abfd, src->e_version, dst->e_version);
233   put_word (abfd, src->e_entry, dst->e_entry);
234   put_word (abfd, src->e_phoff, dst->e_phoff);
235   put_word (abfd, src->e_shoff, dst->e_shoff);
236   bfd_h_put_32 (abfd, src->e_flags, dst->e_flags);
237   bfd_h_put_16 (abfd, src->e_ehsize, dst->e_ehsize);
238   bfd_h_put_16 (abfd, src->e_phentsize, dst->e_phentsize);
239   bfd_h_put_16 (abfd, src->e_phnum, dst->e_phnum);
240   bfd_h_put_16 (abfd, src->e_shentsize, dst->e_shentsize);
241   bfd_h_put_16 (abfd, src->e_shnum, dst->e_shnum);
242   bfd_h_put_16 (abfd, src->e_shstrndx, dst->e_shstrndx);
243 }
244
245
246 /* Translate an ELF section header table entry in external format into an
247    ELF section header table entry in internal format. */
248
249 static void
250 DEFUN (elf_swap_shdr_in, (abfd, src, dst),
251        bfd * abfd AND
252        Elf_External_Shdr * src AND
253        Elf_Internal_Shdr * dst)
254 {
255   dst->sh_name = bfd_h_get_32 (abfd, (bfd_byte *) src->sh_name);
256   dst->sh_type = bfd_h_get_32 (abfd, (bfd_byte *) src->sh_type);
257   dst->sh_flags = get_word (abfd, (bfd_byte *) src->sh_flags);
258   dst->sh_addr = get_word (abfd, (bfd_byte *) src->sh_addr);
259   dst->sh_offset = get_word (abfd, (bfd_byte *) src->sh_offset);
260   dst->sh_size = get_word (abfd, (bfd_byte *) src->sh_size);
261   dst->sh_link = bfd_h_get_32 (abfd, (bfd_byte *) src->sh_link);
262   dst->sh_info = bfd_h_get_32 (abfd, (bfd_byte *) src->sh_info);
263   dst->sh_addralign = get_word (abfd, (bfd_byte *) src->sh_addralign);
264   dst->sh_entsize = get_word (abfd, (bfd_byte *) src->sh_entsize);
265   /* we haven't done any processing on it yet, so... */
266   dst->rawdata = (void *) 0;
267 }
268
269 /* Translate an ELF section header table entry in internal format into an
270    ELF section header table entry in external format. */
271
272 static void
273 DEFUN (elf_swap_shdr_out, (abfd, src, dst),
274        bfd * abfd AND
275        Elf_Internal_Shdr * src AND
276        Elf_External_Shdr * dst)
277 {
278   /* note that all elements of dst are *arrays of unsigned char* already... */
279   bfd_h_put_32 (abfd, src->sh_name, dst->sh_name);
280   bfd_h_put_32 (abfd, src->sh_type, dst->sh_type);
281   put_word (abfd, src->sh_flags, dst->sh_flags);
282   put_word (abfd, src->sh_addr, dst->sh_addr);
283   put_word (abfd, src->sh_offset, dst->sh_offset);
284   put_word (abfd, src->sh_size, dst->sh_size);
285   bfd_h_put_32 (abfd, src->sh_link, dst->sh_link);
286   bfd_h_put_32 (abfd, src->sh_info, dst->sh_info);
287   put_word (abfd, src->sh_addralign, dst->sh_addralign);
288   put_word (abfd, src->sh_entsize, dst->sh_entsize);
289 }
290
291
292 /* Translate an ELF program header table entry in external format into an
293    ELF program header table entry in internal format. */
294
295 static void
296 DEFUN (elf_swap_phdr_in, (abfd, src, dst),
297        bfd * abfd AND
298        Elf_External_Phdr * src AND
299        Elf_Internal_Phdr * dst)
300 {
301   dst->p_type = bfd_h_get_32 (abfd, (bfd_byte *) src->p_type);
302   dst->p_flags = bfd_h_get_32 (abfd, (bfd_byte *) src->p_flags);
303   dst->p_offset = get_word (abfd, (bfd_byte *) src->p_offset);
304   dst->p_vaddr = get_word (abfd, (bfd_byte *) src->p_vaddr);
305   dst->p_paddr = get_word (abfd, (bfd_byte *) src->p_paddr);
306   dst->p_filesz = get_word (abfd, (bfd_byte *) src->p_filesz);
307   dst->p_memsz = get_word (abfd, (bfd_byte *) src->p_memsz);
308   dst->p_align = get_word (abfd, (bfd_byte *) src->p_align);
309 }
310
311 static void
312 DEFUN (elf_swap_phdr_out, (abfd, src, dst),
313        bfd * abfd AND
314        Elf_Internal_Phdr * src AND
315        Elf_External_Phdr * dst)
316 {
317   /* note that all elements of dst are *arrays of unsigned char* already... */
318   bfd_h_put_32 (abfd, src->p_type, dst->p_type);
319   put_word (abfd, src->p_offset, dst->p_offset);
320   put_word (abfd, src->p_vaddr, dst->p_vaddr);
321   put_word (abfd, src->p_paddr, dst->p_paddr);
322   put_word (abfd, src->p_filesz, dst->p_filesz);
323   put_word (abfd, src->p_memsz, dst->p_memsz);
324   bfd_h_put_32 (abfd, src->p_flags, dst->p_flags);
325   put_word (abfd, src->p_align, dst->p_align);
326 }
327
328 /* Translate an ELF reloc from external format to internal format. */
329 static INLINE void
330 DEFUN (elf_swap_reloc_in, (abfd, src, dst),
331        bfd * abfd AND
332        Elf_External_Rel * src AND
333        Elf_Internal_Rel * dst)
334 {
335   dst->r_offset = get_word (abfd, (bfd_byte *) src->r_offset);
336   dst->r_info = get_word (abfd, (bfd_byte *) src->r_info);
337 }
338
339 static INLINE void
340 DEFUN (elf_swap_reloca_in, (abfd, src, dst),
341        bfd * abfd AND
342        Elf_External_Rela * src AND
343        Elf_Internal_Rela * dst)
344 {
345   dst->r_offset = get_word (abfd, (bfd_byte *) src->r_offset);
346   dst->r_info = get_word (abfd, (bfd_byte *) src->r_info);
347   dst->r_addend = get_word (abfd, (bfd_byte *) src->r_addend);
348 }
349
350 /* Translate an ELF reloc from internal format to external format. */
351 static INLINE void
352 DEFUN (elf_swap_reloc_out, (abfd, src, dst),
353        bfd * abfd AND
354        Elf_Internal_Rel * src AND
355        Elf_External_Rel * dst)
356 {
357   put_word (abfd, src->r_offset, dst->r_offset);
358   put_word (abfd, src->r_info, dst->r_info);
359 }
360
361 static INLINE void
362 DEFUN (elf_swap_reloca_out, (abfd, src, dst),
363        bfd * abfd AND
364        Elf_Internal_Rela * src AND
365        Elf_External_Rela * dst)
366 {
367   put_word (abfd, src->r_offset, dst->r_offset);
368   put_word (abfd, src->r_info, dst->r_info);
369   put_word (abfd, src->r_addend, dst->r_addend);
370 }
371
372 \f
373
374 /* String table creation/manipulation routines */
375
376 static struct strtab *
377 DEFUN (bfd_new_strtab, (abfd),
378        bfd * abfd)
379 {
380   struct strtab *ss;
381
382   ss = (struct strtab *) bfd_xmalloc (sizeof (struct strtab));
383   ss->tab = bfd_xmalloc (1);
384   BFD_ASSERT (ss->tab != 0);
385   *ss->tab = 0;
386   ss->nentries = 0;
387   ss->length = 1;
388
389   return ss;
390 }
391
392 static int
393 DEFUN (bfd_add_to_strtab, (abfd, ss, str),
394        bfd * abfd AND
395        struct strtab *ss AND
396        CONST char *str)
397 {
398   /* should search first, but for now: */
399   /* include the trailing NUL */
400   int ln = strlen (str) + 1;
401
402   /* should this be using obstacks? */
403   ss->tab = realloc (ss->tab, ss->length + ln);
404
405   BFD_ASSERT (ss->tab != 0);
406   strcpy (ss->tab + ss->length, str);
407   ss->nentries++;
408   ss->length += ln;
409
410   return ss->length - ln;
411 }
412
413 static int
414 DEFUN (bfd_add_2_to_strtab, (abfd, ss, str, str2),
415        bfd * abfd AND
416        struct strtab *ss AND
417        char *str AND
418        CONST char *str2)
419 {
420   /* should search first, but for now: */
421   /* include the trailing NUL */
422   int ln = strlen (str) + strlen (str2) + 1;
423
424   /* should this be using obstacks? */
425   if (ss->length)
426     ss->tab = realloc (ss->tab, ss->length + ln);
427   else
428     ss->tab = bfd_xmalloc (ln);
429
430   BFD_ASSERT (ss->tab != 0);
431   strcpy (ss->tab + ss->length, str);
432   strcpy (ss->tab + ss->length + strlen (str), str2);
433   ss->nentries++;
434   ss->length += ln;
435
436   return ss->length - ln;
437 }
438
439 \f
440 /* ELF .o/exec file reading */
441
442 /* Create a new bfd section from an ELF section header. */
443
444 static boolean
445 DEFUN (bfd_section_from_shdr, (abfd, shindex),
446        bfd * abfd AND
447        unsigned int shindex)
448 {
449   Elf_Internal_Shdr *hdr = elf_elfsections (abfd)[shindex];
450   Elf_Internal_Ehdr *ehdr = elf_elfheader (abfd);
451   asection *newsect;
452   char *name;
453
454   name = elf_string_from_elf_strtab (abfd, hdr->sh_name);
455
456   switch (hdr->sh_type)
457     {
458
459     case SHT_NULL:
460       /* inactive section. Throw it away. */
461       return true;
462
463     case SHT_PROGBITS:
464       /* Bits that get saved. This one is real. */
465       if (!hdr->rawdata)
466         {
467           newsect = bfd_make_section (abfd, name);
468           if (newsect != NULL)
469             {
470               newsect->filepos = hdr->sh_offset; /* so we can read back the bits */
471               newsect->flags |= SEC_HAS_CONTENTS;
472               newsect->vma = hdr->sh_addr;
473               newsect->_raw_size = hdr->sh_size;
474               newsect->alignment_power = bfd_log2 (hdr->sh_addralign);
475
476               if (hdr->sh_flags & SHF_ALLOC)
477                 {
478                   newsect->flags |= SEC_ALLOC;
479                   newsect->flags |= SEC_LOAD;
480                 }
481
482               if (!(hdr->sh_flags & SHF_WRITE))
483                 newsect->flags |= SEC_READONLY;
484
485               if (hdr->sh_flags & SHF_EXECINSTR)
486                 newsect->flags |= SEC_CODE; /* FIXME: may only contain SOME code */
487               else
488                 newsect->flags |= SEC_DATA;
489
490               hdr->rawdata = (void *) newsect;
491             }
492           else
493             hdr->rawdata = (void *) bfd_get_section_by_name (abfd, name);
494         }
495       return true;
496
497     case SHT_NOBITS:
498       /* Bits that get saved. This one is real. */
499       if (!hdr->rawdata)
500         {
501           newsect = bfd_make_section (abfd, name);
502           if (newsect != NULL)
503             {
504               newsect->vma = hdr->sh_addr;
505               newsect->_raw_size = hdr->sh_size;
506               newsect->filepos = hdr->sh_offset;        /* fake */
507               newsect->alignment_power = bfd_log2 (hdr->sh_addralign);
508               if (hdr->sh_flags & SHF_ALLOC)
509                 newsect->flags |= SEC_ALLOC;
510
511               if (!(hdr->sh_flags & SHF_WRITE))
512                 newsect->flags |= SEC_READONLY;
513
514               if (hdr->sh_flags & SHF_EXECINSTR)
515                 newsect->flags |= SEC_CODE;     /* FIXME: may only contain SOME code */
516               else
517                 newsect->flags |= SEC_DATA;
518
519               hdr->rawdata = (void *) newsect;
520             }
521         }
522       return true;
523
524     case SHT_SYMTAB:            /* A symbol table */
525       if (elf_onesymtab (abfd) == shindex)
526         return true;
527
528       BFD_ASSERT (hdr->sh_entsize == sizeof (Elf_External_Sym));
529       BFD_ASSERT (elf_onesymtab (abfd) == 0);
530       elf_onesymtab (abfd) = shindex;
531       elf_tdata(abfd)->symtab_hdr = *hdr;
532       elf_elfsections(abfd)[shindex] = &elf_tdata(abfd)->symtab_hdr;
533       abfd->flags |= HAS_SYMS;
534       return true;
535
536     case SHT_STRTAB:            /* A string table */
537       if (hdr->rawdata)
538         return true;
539       if (ehdr->e_shstrndx == shindex)
540         {
541           elf_tdata(abfd)->shstrtab_hdr = *hdr;
542           elf_elfsections(abfd)[shindex] = &elf_tdata(abfd)->shstrtab_hdr;
543           hdr->rawdata = (PTR) &elf_tdata(abfd)->shstrtab_hdr;
544           return true;
545         }
546       {
547         int i;
548
549         for (i = 1; i < ehdr->e_shnum; i++)
550           {
551             Elf_Internal_Shdr *hdr2 = elf_elfsections(abfd)[i];
552             if (hdr2->sh_link == shindex)
553               {
554                 bfd_section_from_shdr (abfd, i);
555                 if (elf_onesymtab (abfd) == i)
556                   {
557                     elf_tdata(abfd)->strtab_hdr = *hdr;
558                     elf_elfsections(abfd)[shindex] = &elf_tdata(abfd)->strtab_hdr;
559                     return true;
560                   }
561 #if 0 /* Not handling other string tables specially right now.  */
562                 hdr2 = elf_elfsections(abfd)[i]; /* in case it moved */
563                 /* We have a strtab for some random other section.  */
564                 newsect = (asection *) hdr2->rawdata;
565                 if (!newsect)
566                   break;
567                 hdr->rawdata = (PTR) newsect;
568                 hdr2 = &elf_section_data (newsect)->str_hdr;
569                 *hdr2 = *hdr;
570                 elf_elfsections(abfd)[shindex] = hdr2;
571 #endif
572               }
573           }
574       }
575
576       newsect = bfd_make_section (abfd, name);
577       if (newsect)
578         {
579           newsect->flags = SEC_HAS_CONTENTS;
580           hdr->rawdata = (PTR) newsect;
581           newsect->_raw_size = hdr->sh_size;
582           newsect->alignment_power = 0;
583           newsect->vma = 0;
584
585           if (hdr->sh_flags & SHF_ALLOC)
586             newsect->flags |= SEC_ALLOC|SEC_LOAD;
587           if (!(hdr->sh_flags & SHF_WRITE))
588             newsect->flags |= SEC_READONLY;
589           if (hdr->sh_flags & SHF_EXECINSTR)
590             newsect->flags |= SEC_CODE;
591           else
592             newsect->flags |= SEC_DATA;
593         }
594
595       return true;
596
597     case SHT_REL:
598     case SHT_RELA:
599       /* *These* do a lot of work -- but build no sections!
600          The spec says there can be multiple strtabs, but only one symtab,
601          but there can be lots of REL* sections. */
602       /* FIXME:  The above statement is wrong!  There are typically at least
603          two symbol tables in a dynamically linked executable, ".dynsym"
604          which is the dynamic linkage symbol table and ".symtab", which is
605          the "traditional" symbol table.  -fnf */
606
607       {
608         asection *target_sect;
609         Elf_Internal_Shdr *hdr2;
610         int use_rela_p = get_elf_backend_data (abfd)->use_rela_p;
611
612         /* Don't allow REL relocations on a machine that uses RELA and
613            vice versa.  */
614         /* @@ Actually, the generic ABI does suggest that both might be
615            used in one file.  But the four ABI Processor Supplements I
616            have access to right now all specify that only one is used on
617            each of those architectures.  It's conceivable that, e.g., a
618            bunch of absolute 32-bit relocs might be more compact in REL
619            form even on a RELA machine...  */
620         BFD_ASSERT (!(use_rela_p && (hdr->sh_type == SHT_REL)));
621         BFD_ASSERT (!(!use_rela_p && (hdr->sh_type == SHT_RELA)));
622         BFD_ASSERT (hdr->sh_entsize ==
623                     (use_rela_p
624                      ? sizeof (Elf_External_Rela)
625                      : sizeof (Elf_External_Rel)));
626
627         bfd_section_from_shdr (abfd, hdr->sh_info);     /* target */
628         bfd_section_from_shdr (abfd, hdr->sh_link);     /* symbol table */
629         target_sect = section_from_elf_index (abfd, hdr->sh_info);
630         if (target_sect == NULL)
631           return false;
632
633         hdr2 = &elf_section_data (target_sect)->rel_hdr;
634         *hdr2 = *hdr;
635         elf_elfsections(abfd)[shindex] = hdr2;
636         target_sect->reloc_count = hdr->sh_size / hdr->sh_entsize;
637         target_sect->flags |= SEC_RELOC;
638         target_sect->relocation = 0;
639         target_sect->rel_filepos = hdr->sh_offset;
640         abfd->flags |= HAS_RELOC;
641         return true;
642       }
643       break;
644
645     case SHT_HASH:
646     case SHT_DYNAMIC:
647     case SHT_DYNSYM:            /* could treat this like symtab... */
648 #if 0
649       fprintf (stderr, "Dynamic Linking sections not yet supported.\n");
650       BFD_FAIL ();
651 #endif
652       break;
653
654     case SHT_NOTE:
655 #if 0
656       fprintf (stderr, "Note Sections not yet supported.\n");
657       BFD_FAIL ();
658 #endif
659       break;
660
661     case SHT_SHLIB:
662 #if 0
663       fprintf (stderr, "SHLIB Sections not supported (and non conforming.)\n");
664 #endif
665       return true;
666
667     default:
668       break;
669     }
670
671   return true;
672 }
673
674 boolean
675 DEFUN (elf_new_section_hook, (abfd, sec),
676        bfd *abfd
677        AND asection *sec)
678 {
679   struct bfd_elf_section_data *sdata;
680
681   sdata = (struct bfd_elf_section_data *) bfd_alloc (abfd, sizeof (*sdata));
682   sec->used_by_bfd = (PTR) sdata;
683   memset (sdata, 0, sizeof (*sdata));
684   return true;
685 }
686
687 /* Create a new bfd section from an ELF program header.
688
689    Since program segments have no names, we generate a synthetic name
690    of the form segment<NUM>, where NUM is generally the index in the
691    program header table.  For segments that are split (see below) we
692    generate the names segment<NUM>a and segment<NUM>b.
693
694    Note that some program segments may have a file size that is different than
695    (less than) the memory size.  All this means is that at execution the
696    system must allocate the amount of memory specified by the memory size,
697    but only initialize it with the first "file size" bytes read from the
698    file.  This would occur for example, with program segments consisting
699    of combined data+bss.
700
701    To handle the above situation, this routine generates TWO bfd sections
702    for the single program segment.  The first has the length specified by
703    the file size of the segment, and the second has the length specified
704    by the difference between the two sizes.  In effect, the segment is split
705    into it's initialized and uninitialized parts.
706
707  */
708
709 static boolean
710 DEFUN (bfd_section_from_phdr, (abfd, hdr, index),
711        bfd * abfd AND
712        Elf_Internal_Phdr * hdr AND
713        int index)
714 {
715   asection *newsect;
716   char *name;
717   char namebuf[64];
718   int split;
719
720   split = ((hdr->p_memsz > 0) &&
721            (hdr->p_filesz > 0) &&
722            (hdr->p_memsz > hdr->p_filesz));
723   sprintf (namebuf, split ? "segment%da" : "segment%d", index);
724   name = bfd_alloc (abfd, strlen (namebuf) + 1);
725   strcpy (name, namebuf);
726   newsect = bfd_make_section (abfd, name);
727   newsect->vma = hdr->p_vaddr;
728   newsect->_raw_size = hdr->p_filesz;
729   newsect->filepos = hdr->p_offset;
730   newsect->flags |= SEC_HAS_CONTENTS;
731   if (hdr->p_type == PT_LOAD)
732     {
733       newsect->flags |= SEC_ALLOC;
734       newsect->flags |= SEC_LOAD;
735       if (hdr->p_flags & PF_X)
736         {
737           /* FIXME: all we known is that it has execute PERMISSION,
738              may be data. */
739           newsect->flags |= SEC_CODE;
740         }
741     }
742   if (!(hdr->p_flags & PF_W))
743     {
744       newsect->flags |= SEC_READONLY;
745     }
746
747   if (split)
748     {
749       sprintf (namebuf, "segment%db", index);
750       name = bfd_alloc (abfd, strlen (namebuf) + 1);
751       strcpy (name, namebuf);
752       newsect = bfd_make_section (abfd, name);
753       newsect->vma = hdr->p_vaddr + hdr->p_filesz;
754       newsect->_raw_size = hdr->p_memsz - hdr->p_filesz;
755       if (hdr->p_type == PT_LOAD)
756         {
757           newsect->flags |= SEC_ALLOC;
758           if (hdr->p_flags & PF_X)
759             newsect->flags |= SEC_CODE;
760         }
761       if (!(hdr->p_flags & PF_W))
762         newsect->flags |= SEC_READONLY;
763     }
764
765   return true;
766 }
767
768 /* Begin processing a given object.
769
770    First we validate the file by reading in the ELF header and checking
771    the magic number.  */
772
773 static INLINE boolean
774 DEFUN (elf_file_p, (x_ehdrp), Elf_External_Ehdr * x_ehdrp)
775 {
776   return ((x_ehdrp->e_ident[EI_MAG0] == ELFMAG0)
777           && (x_ehdrp->e_ident[EI_MAG1] == ELFMAG1)
778           && (x_ehdrp->e_ident[EI_MAG2] == ELFMAG2)
779           && (x_ehdrp->e_ident[EI_MAG3] == ELFMAG3));
780 }
781
782 /* Check to see if the file associated with ABFD matches the target vector
783    that ABFD points to.
784
785    Note that we may be called several times with the same ABFD, but different
786    target vectors, most of which will not match.  We have to avoid leaving
787    any side effects in ABFD, or any data it points to (like tdata), if the
788    file does not match the target vector.
789
790    FIXME:  There is memory leak if we are called more than once with the same
791    ABFD, and that bfd already has tdata allocated, since we allocate more tdata
792    and the old tdata is orphaned.  Since it's in the bfd obstack, there isn't
793    much we can do about this except possibly rewrite the code.  There are 
794    also other bfd_allocs that may be the source of memory leaks as well. */
795
796 bfd_target *
797 DEFUN (elf_object_p, (abfd), bfd * abfd)
798 {
799   Elf_External_Ehdr x_ehdr;     /* Elf file header, external form */
800   Elf_Internal_Ehdr *i_ehdrp;   /* Elf file header, internal form */
801   Elf_External_Shdr x_shdr;     /* Section header table entry, external form */
802   Elf_Internal_Shdr *i_shdrp;   /* Section header table, internal form */
803   int shindex;
804   char *shstrtab;               /* Internal copy of section header stringtab */
805   struct elf_backend_data *ebd; /* Use to get ELF_ARCH stored in xvec */
806   struct elf_obj_tdata *preserved_tdata = elf_tdata (abfd);
807
808   /* Read in the ELF header in external format.  */
809
810   if (bfd_read ((PTR) & x_ehdr, sizeof (x_ehdr), 1, abfd) != sizeof (x_ehdr))
811     goto got_system_call_error;
812
813   /* Now check to see if we have a valid ELF file, and one that BFD can
814      make use of.  The magic number must match, the address size ('class')
815      and byte-swapping must match our XVEC entry, and it must have a
816      section header table (FIXME: See comments re sections at top of this
817      file). */
818
819   if ((elf_file_p (&x_ehdr) == false) ||
820       (x_ehdr.e_ident[EI_VERSION] != EV_CURRENT) ||
821       (x_ehdr.e_ident[EI_CLASS] != ELFCLASS))
822     goto got_wrong_format_error;
823
824   /* Check that file's byte order matches xvec's */
825   switch (x_ehdr.e_ident[EI_DATA])
826     {
827     case ELFDATA2MSB:           /* Big-endian */
828       if (!abfd->xvec->header_byteorder_big_p)
829         goto got_wrong_format_error;
830       break;
831     case ELFDATA2LSB:           /* Little-endian */
832       if (abfd->xvec->header_byteorder_big_p)
833         goto got_wrong_format_error;
834       break;
835     case ELFDATANONE:           /* No data encoding specified */
836     default:                    /* Unknown data encoding specified */
837       goto got_wrong_format_error;
838     }
839
840   /* Allocate an instance of the elf_obj_tdata structure and hook it up to
841      the tdata pointer in the bfd.  FIXME:  memory leak, see above. */
842
843   elf_tdata (abfd) =
844     (struct elf_obj_tdata *) bfd_zalloc (abfd, sizeof (struct elf_obj_tdata));
845   if (elf_tdata (abfd) == NULL)
846     goto got_no_memory_error;
847
848   /* Now that we know the byte order, swap in the rest of the header */
849   i_ehdrp = elf_elfheader (abfd);
850   elf_swap_ehdr_in (abfd, &x_ehdr, i_ehdrp);
851 #if DEBUG & 1
852   elf_debug_file (i_ehdrp);
853 #endif
854
855   /* If there is no section header table, we're hosed. */
856   if (i_ehdrp->e_shoff == 0)
857     goto got_wrong_format_error;
858
859   if (i_ehdrp->e_type == ET_EXEC || i_ehdrp->e_type == ET_DYN)
860     abfd->flags |= EXEC_P;
861
862   /* Retrieve the architecture information from the xvec and verify
863      that it matches the machine info stored in the ELF header.
864      This allows us to resolve ambiguous formats that might not
865      otherwise be distinguishable. */
866
867   ebd = get_elf_backend_data (abfd);
868
869   /* Perhaps the elf architecture value should be another field in the
870      elf backend data?  If you change this to work that way, make sure
871      that you still get bfd_arch_unknown for unknown architecture types,
872      and that it still gets accepted by the `generic' elf target.  */
873   {
874     int i;
875     enum bfd_architecture arch = bfd_arch_unknown;
876
877     for (i = 0; i < bfd_elf_arch_map_size; i++)
878       {
879         if (bfd_elf_arch_map[i].elf_arch == i_ehdrp->e_machine)
880           {
881             arch = bfd_elf_arch_map[i].bfd_arch;
882             break;
883           }
884       }
885     /* start-sanitize-v9 */
886     if (i_ehdrp->e_machine == EM_SPARC64)
887       arch = bfd_arch_sparc;
888     /* end-sanitize-v9 */
889     if (ebd->arch != arch)
890       goto got_wrong_format_error;
891     bfd_default_set_arch_mach (abfd, arch, 0);
892   }
893
894   /* Allocate space for a copy of the section header table in
895      internal form, seek to the section header table in the file,
896      read it in, and convert it to internal form.  As a simple sanity
897      check, verify that the what BFD thinks is the size of each section
898      header table entry actually matches the size recorded in the file. */
899
900   if (i_ehdrp->e_shentsize != sizeof (x_shdr))
901     goto got_wrong_format_error;
902   i_shdrp = (Elf_Internal_Shdr *)
903     bfd_alloc (abfd, sizeof (*i_shdrp) * i_ehdrp->e_shnum);
904   elf_elfsections (abfd) =
905     (Elf_Internal_Shdr **) bfd_alloc (abfd, sizeof (i_shdrp) * i_ehdrp->e_shnum);
906   if (!i_shdrp || !elf_elfsections(abfd))
907     goto got_no_memory_error;
908   if (bfd_seek (abfd, i_ehdrp->e_shoff, SEEK_SET) == -1)
909     goto got_system_call_error;
910   for (shindex = 0; shindex < i_ehdrp->e_shnum; shindex++)
911     {
912       if (bfd_read ((PTR) & x_shdr, sizeof x_shdr, 1, abfd) != sizeof (x_shdr))
913         goto got_system_call_error;
914       elf_swap_shdr_in (abfd, &x_shdr, i_shdrp + shindex);
915       elf_elfsections(abfd)[shindex] = i_shdrp + shindex;
916     }
917   if (i_ehdrp->e_shstrndx)
918     {
919       bfd_section_from_shdr (abfd, i_ehdrp->e_shstrndx);
920     }
921
922 #if 0
923   for (shindex = i_ehdrp->e_shnum - 1; shindex >= 0; shindex--)
924     {
925       if (!strcmp (elf_string_from_elf_strtab (abfd,
926                                                i_shdrp[shindex].sh_name),
927                    ".strtab"))
928         {
929           elf_tdata(abfd)->strtab_hdr = i_shdrp[shindex];
930           elf_elfsections(abfd)[shindex] = &elf_tdata(abfd)->strtab_hdr;
931         }
932       else if (!strcmp (elf_string_from_elf_strtab (abfd,
933                                                     i_shdrp[shindex].sh_name),
934                         ".symtab"))
935         {
936           elf_tdata(abfd)->symtab_hdr = i_shdrp[shindex];
937           elf_elfsections(abfd)[shindex] = &elf_tdata(abfd)->symtab_hdr;
938           elf_onesymtab (abfd) = shindex;
939         }
940     }
941 #endif
942
943   /* Read in the string table containing the names of the sections.  We
944      will need the base pointer to this table later. */
945   /* We read this inline now, so that we don't have to go through
946      bfd_section_from_shdr with it (since this particular strtab is
947      used to find all of the ELF section names.) */
948
949   shstrtab = elf_get_str_section (abfd, i_ehdrp->e_shstrndx);
950   if (!shstrtab)
951     goto got_wrong_format_error;
952
953   /* Once all of the section headers have been read and converted, we
954      can start processing them.  Note that the first section header is
955      a dummy placeholder entry, so we ignore it.
956
957      We also watch for the symbol table section and remember the file
958      offset and section size for both the symbol table section and the
959      associated string table section. */
960
961   for (shindex = 1; shindex < i_ehdrp->e_shnum; shindex++)
962     {
963       bfd_section_from_shdr (abfd, shindex);
964     }
965
966   /* Remember the entry point specified in the ELF file header. */
967
968   bfd_get_start_address (abfd) = i_ehdrp->e_entry;
969
970   return (abfd->xvec);
971
972   /* If we are going to use goto's to avoid duplicating error setting
973      and return(NULL) code, then this at least makes it more maintainable. */
974
975  got_system_call_error:
976   bfd_error = system_call_error;
977   goto got_no_match;
978  got_wrong_format_error:
979   bfd_error = wrong_format;
980   goto got_no_match;
981  got_no_memory_error:
982   bfd_error = no_memory;
983   goto got_no_match;
984  got_no_match:
985   elf_tdata (abfd) = preserved_tdata;
986   return (NULL);
987 }
988
989 \f
990 /* ELF .o/exec file writing */
991
992 /* Takes a bfd and a symbol, returns a pointer to the elf specific area
993    of the symbol if there is one.  */
994 static INLINE elf_symbol_type *
995 DEFUN (elf_symbol_from, (ignore_abfd, symbol),
996        bfd * ignore_abfd AND
997        asymbol * symbol)
998 {
999   if (symbol->the_bfd->xvec->flavour != bfd_target_elf_flavour)
1000     return 0;
1001
1002   if (symbol->the_bfd->tdata.elf_obj_data == (struct elf_obj_tdata *) NULL)
1003     return 0;
1004
1005   return (elf_symbol_type *) symbol;
1006 }
1007
1008 /* Create ELF output from BFD sections.
1009
1010    Essentially, just create the section header and forget about the program
1011    header for now.  */
1012
1013 static void
1014 DEFUN (elf_make_sections, (abfd, asect, obj),
1015        bfd * abfd AND
1016        asection * asect AND
1017        PTR obj)
1018 {
1019   /* most of what is in bfd_shdr_from_section goes in here... */
1020   /* and all of these sections generate at *least* one ELF section. */
1021   int idx;
1022
1023   Elf_Internal_Shdr *this_hdr;
1024   this_hdr = &elf_section_data (asect)->this_hdr;
1025
1026   this_hdr->sh_addr = asect->vma;
1027   this_hdr->sh_size = asect->_raw_size;
1028   /* contents already set by elf_set_section_contents */
1029
1030   if (asect->flags & SEC_RELOC)
1031     {
1032       /* emit a reloc section, and thus strtab and symtab... */
1033       Elf_Internal_Shdr *rela_hdr;
1034       Elf_External_Rela *outbound_relocas;
1035       Elf_External_Rel *outbound_relocs;
1036       int use_rela_p = get_elf_backend_data (abfd)->use_rela_p;
1037
1038       rela_hdr = &elf_section_data (asect)->rel_hdr;
1039
1040       /* orelocation has the data, reloc_count has the count... */
1041       if (use_rela_p)
1042         {
1043           rela_hdr->sh_type = SHT_RELA;
1044           rela_hdr->sh_entsize = sizeof (Elf_External_Rela);
1045         }
1046       else
1047         /* REL relocations */
1048         {
1049           rela_hdr->sh_type = SHT_REL;
1050           rela_hdr->sh_entsize = sizeof (Elf_External_Rel);
1051         }
1052       rela_hdr->sh_flags = 0;
1053       rela_hdr->sh_addr = 0;
1054       rela_hdr->sh_offset = 0;
1055       rela_hdr->sh_addralign = 0;
1056       rela_hdr->size = 0;
1057     }
1058   if (asect->flags & SEC_ALLOC)
1059     {
1060       this_hdr->sh_flags |= SHF_ALLOC;
1061       if (asect->flags & SEC_LOAD)
1062         {
1063           /* @@ Do something with sh_type? */
1064         }
1065     }
1066   if (!(asect->flags & SEC_READONLY))
1067     this_hdr->sh_flags |= SHF_WRITE;
1068
1069   if (asect->flags & SEC_CODE)
1070     this_hdr->sh_flags |= SHF_EXECINSTR;
1071 }
1072
1073 void
1074 write_relocs (abfd, sec, xxx)
1075      bfd *abfd;
1076      asection *sec;
1077      PTR xxx;
1078 {
1079   Elf_Internal_Shdr *rela_hdr;
1080   Elf_External_Rela *outbound_relocas;
1081   Elf_External_Rel *outbound_relocs;
1082   int idx;
1083   int use_rela_p = get_elf_backend_data (abfd)->use_rela_p;
1084   asymbol *last_sym = 0;
1085   int last_sym_idx;
1086
1087   if ((sec->flags & SEC_RELOC) == 0)
1088     return;
1089   /* Flags are sometimes inconsistent.  */
1090   if (sec->reloc_count == 0)
1091     return;
1092
1093   rela_hdr = &elf_section_data (sec)->rel_hdr;
1094
1095   rela_hdr->sh_size = rela_hdr->sh_entsize * sec->reloc_count;
1096   rela_hdr->contents = (void *) bfd_alloc (abfd, rela_hdr->sh_size);
1097
1098   /* orelocation has the data, reloc_count has the count... */
1099   if (use_rela_p)
1100     {
1101       outbound_relocas = (Elf_External_Rela *) rela_hdr->contents;
1102
1103       for (idx = 0; idx < sec->reloc_count; idx++)
1104         {
1105           Elf_Internal_Rela dst_rela;
1106           Elf_External_Rela *src_rela;
1107           arelent *ptr;
1108           asymbol *sym;
1109           int n;
1110
1111           ptr = sec->orelocation[idx];
1112           src_rela = outbound_relocas + idx;
1113           if (!(abfd->flags & EXEC_P))
1114             dst_rela.r_offset = ptr->address - sec->vma;
1115           else
1116             dst_rela.r_offset = ptr->address;
1117
1118           sym = *ptr->sym_ptr_ptr;
1119           if (sym == last_sym)
1120             n = last_sym_idx;
1121           else
1122             {
1123               last_sym = sym;
1124               last_sym_idx = n = elf_symbol_from_bfd_symbol (abfd, &sym);
1125             }
1126           dst_rela.r_info = ELF_R_INFO (n, ptr->howto->type);
1127
1128           dst_rela.r_addend = ptr->addend;
1129           elf_swap_reloca_out (abfd, &dst_rela, src_rela);
1130         }
1131     }
1132   else
1133     /* REL relocations */
1134     {
1135       outbound_relocs = (Elf_External_Rel *) rela_hdr->contents;
1136
1137       for (idx = 0; idx < sec->reloc_count; idx++)
1138         {
1139           Elf_Internal_Rel dst_rel;
1140           Elf_External_Rel *src_rel;
1141           arelent *ptr;
1142           int n;
1143           asymbol *sym;
1144
1145           ptr = sec->orelocation[idx];
1146           sym = *ptr->sym_ptr_ptr;
1147           src_rel = outbound_relocs + idx;
1148           if (!(abfd->flags & EXEC_P))
1149             dst_rel.r_offset = ptr->address - sec->vma;
1150           else
1151             dst_rel.r_offset = ptr->address;
1152
1153           if (sym == last_sym)
1154             n = last_sym_idx;
1155           else
1156             {
1157               last_sym = sym;
1158               last_sym_idx = n = elf_symbol_from_bfd_symbol (abfd, &sym);
1159             }
1160           dst_rel.r_info = ELF_R_INFO (n, ptr->howto->type);
1161
1162           elf_swap_reloc_out (abfd, &dst_rel, src_rel);
1163         }
1164     }
1165 }
1166
1167 static void
1168 fix_up_strtabs (abfd, asect, obj)
1169      bfd *abfd;
1170      asection *asect;
1171      PTR obj;
1172 {
1173   Elf_Internal_Shdr *this_hdr = &elf_section_data (asect)->this_hdr;
1174   int this_idx = elf_section_data(asect)->this_idx;
1175
1176   /* @@ Check flags!  */
1177   if (!strncmp (asect->name, ".stab", 5)
1178       && !strcmp ("str", asect->name + strlen (asect->name) - 3))
1179     {
1180       size_t len = strlen (asect->name) + 1;
1181       char *s = (char *) alloca (len);
1182       strcpy (s, asect->name);
1183       s[len - 4] = 0;
1184       asect = bfd_get_section_by_name (abfd, s);
1185       if (!asect)
1186         abort ();
1187       elf_section_data(asect)->this_hdr.sh_link = this_idx;
1188
1189       /* @@ Assuming 32 bits!  */
1190       this_hdr->sh_entsize = 0xc;
1191     }
1192 }
1193
1194 static void
1195 DEFUN (elf_fake_sections, (abfd, asect, obj),
1196        bfd * abfd AND
1197        asection * asect AND
1198        PTR obj)
1199 {
1200   /* most of what is in bfd_shdr_from_section goes in here... */
1201   /* and all of these sections generate at *least* one ELF section. */
1202
1203   Elf_Internal_Shdr *this_hdr;
1204   this_hdr = &elf_section_data (asect)->this_hdr;
1205   this_hdr->sh_name =
1206     bfd_add_to_strtab (abfd, elf_shstrtab (abfd), asect->name);
1207   /* We need to log the type *now* so that elf_section_from_bfd_section
1208      can find us... have to set rawdata too. */
1209   this_hdr->rawdata = (void *) asect;
1210   this_hdr->sh_addralign = 1 << asect->alignment_power;
1211   if ((asect->flags & SEC_ALLOC) && (asect->flags & SEC_LOAD))
1212     this_hdr->sh_type = SHT_PROGBITS;
1213   /* @@ Select conditions correctly!  */
1214   else if (!strcmp (asect->name, ".bss"))
1215     this_hdr->sh_type = SHT_NOBITS;
1216   else
1217     /* what *do* we put here? */
1218     this_hdr->sh_type = SHT_PROGBITS;
1219
1220   this_hdr->sh_flags = 0;
1221   this_hdr->sh_addr = 0;
1222   this_hdr->sh_size = 0;
1223   this_hdr->sh_entsize = 0;
1224   this_hdr->sh_info = 0;
1225   this_hdr->sh_link = 0;
1226   this_hdr->sh_offset = 0;
1227   this_hdr->size = 0;
1228
1229   {
1230     /* Emit a strtab and symtab, and possibly a reloc section.  */
1231     Elf_Internal_Shdr *rela_hdr;
1232     Elf_Internal_Shdr *symstrtab_hdr;
1233
1234     /* Note that only one symtab is used, so just remember it
1235        for now.  */
1236
1237     if (asect->flags & SEC_RELOC)
1238       {
1239         int use_rela_p = get_elf_backend_data (abfd)->use_rela_p;
1240
1241         rela_hdr = &elf_section_data (asect)->rel_hdr;
1242         rela_hdr->sh_name =
1243           bfd_add_2_to_strtab (abfd, elf_shstrtab (abfd),
1244                                use_rela_p ? ".rela" : ".rel",
1245                                asect->name);
1246         rela_hdr->sh_type = use_rela_p ? SHT_RELA : SHT_REL;
1247         rela_hdr->sh_entsize = (use_rela_p
1248                                 ? sizeof (Elf_External_Rela)
1249                                 : sizeof (Elf_External_Rel));
1250
1251         rela_hdr->sh_flags = 0;
1252         rela_hdr->sh_addr = 0;
1253         rela_hdr->sh_size = 0;
1254         rela_hdr->sh_offset = 0;
1255         rela_hdr->sh_addralign = 0;
1256         rela_hdr->size = 0;
1257       }
1258   }
1259   if (asect->flags & SEC_ALLOC)
1260     {
1261       this_hdr->sh_flags |= SHF_ALLOC;
1262       if (asect->flags & SEC_LOAD)
1263         {
1264           /* @@ Do something with sh_type?  */
1265         }
1266     }
1267   if (!(asect->flags & SEC_READONLY))
1268     this_hdr->sh_flags |= SHF_WRITE;
1269   if (asect->flags & SEC_CODE)
1270     this_hdr->sh_flags |= SHF_EXECINSTR;
1271 }
1272
1273
1274 #if 0
1275 /*
1276 xxxINTERNAL_FUNCTION
1277         bfd_elf_locate_sh
1278
1279 xxxSYNOPSIS
1280         struct elf_internal_shdr *bfd_elf_locate_sh (bfd *abfd,
1281                                                      struct strtab *strtab,
1282                                                      struct elf_internal_shdr *shdrp,
1283                                                      CONST char *name);
1284
1285 xxxDESCRIPTION
1286         Helper function to locate an ELF section header given the
1287         name of a BFD section.
1288 */
1289
1290 static struct elf_internal_shdr *
1291 DEFUN (elf_locate_sh, (abfd, strtab, shdrp, name),
1292        bfd * abfd AND
1293        struct strtab *strtab AND
1294        struct elf_internal_shdr *shdrp AND
1295        CONST char *name)
1296 {
1297   Elf_Internal_Shdr *gotit = NULL;
1298   int max, i;
1299
1300   if (shdrp != NULL && strtab != NULL)
1301     {
1302       max = elf_elfheader (abfd)->e_shnum;
1303       for (i = 1; i < max; i++)
1304         {
1305           if (!strcmp (strtab->tab + shdrp[i].sh_name, name))
1306             {
1307               gotit = &shdrp[i];
1308             }
1309         }
1310     }
1311   return gotit;
1312 }
1313 #endif
1314
1315 /* Map symbol from it's internal number to the external number, moving
1316    all local symbols to be at the head of the list.  */
1317
1318 static INLINE int
1319 sym_is_global (sym)
1320      asymbol *sym;
1321 {
1322   if (sym->flags & (BSF_GLOBAL | BSF_WEAK))
1323     {
1324       if (sym->flags & BSF_LOCAL)
1325         abort ();
1326       return 1;
1327     }
1328   if (sym->section == 0)
1329     {
1330       /* Is this valid?  */
1331       abort ();
1332
1333       return 1;
1334     }
1335   if (sym->section == &bfd_und_section)
1336     return 1;
1337   if (bfd_is_com_section (sym->section))
1338     return 1;
1339   if (sym->flags & (BSF_LOCAL | BSF_SECTION_SYM | BSF_FILE))
1340     return 0;
1341   return 0;
1342 }
1343
1344 static void
1345 DEFUN (elf_map_symbols, (abfd), bfd * abfd)
1346 {
1347   int symcount = bfd_get_symcount (abfd);
1348   asymbol **syms = bfd_get_outsymbols (abfd);
1349   asymbol **sect_syms;
1350   int num_locals = 0;
1351   int num_globals = 0;
1352   int num_locals2 = 0;
1353   int num_globals2 = 0;
1354   int max_index = 0;
1355   int num_sections = 0;
1356   Elf_Sym_Extra *sym_extra;
1357   int idx;
1358   asection *asect;
1359
1360 #ifdef DEBUG
1361   fprintf (stderr, "elf_map_symbols\n");
1362   fflush (stderr);
1363 #endif
1364
1365   /* Add local symbols for each allocated section.
1366      FIXME -- we should only put out symbols for sections that
1367      are actually relocated against.  */
1368   for (asect = abfd->sections; asect; asect = asect->next)
1369     {
1370       if (max_index < asect->index)
1371         max_index = asect->index;
1372     }
1373
1374   max_index++;
1375   elf_num_section_syms (abfd) = max_index;
1376   sect_syms = (asymbol **) bfd_zalloc (abfd, max_index * sizeof (asymbol *));
1377   elf_section_syms (abfd) = sect_syms;
1378
1379   BFD_ASSERT (sect_syms != 0);
1380
1381   for (asect = abfd->sections; asect; asect = asect->next)
1382     if ((asect->flags & SEC_ALLOC) && asect->_raw_size > 0)
1383       {
1384         asymbol *sym = bfd_make_empty_symbol (abfd);
1385         sym->the_bfd = abfd;
1386         sym->name = asect->name;
1387         sym->value = asect->vma;
1388         sym->flags = BSF_SECTION_SYM;
1389         sym->section = asect;
1390         sect_syms[asect->index] = sym;
1391         num_sections++;
1392 #ifdef DEBUG
1393         fprintf (stderr,
1394                  "creating section symbol, name = %s, value = 0x%.8lx, index = %d, section = 0x%.8lx\n",
1395                  asect->name, (long) asect->vma, asect->index, (long) asect);
1396 #endif
1397       }
1398
1399   if (num_sections)
1400     {
1401       if (syms)
1402         syms = (asymbol **) bfd_realloc (abfd, syms,
1403                                          ((symcount + num_sections + 1)
1404                                           * sizeof (asymbol *)));
1405       else
1406         syms = (asymbol **) bfd_alloc (abfd,
1407                                        (num_sections + 1) * sizeof (asymbol *));
1408
1409       for (asect = abfd->sections; asect; asect = asect->next)
1410         {
1411           if (sect_syms[asect->index])
1412             syms[symcount++] = sect_syms[asect->index];
1413         }
1414
1415       syms[symcount] = (asymbol *) 0;
1416       bfd_set_symtab (abfd, syms, symcount);
1417     }
1418
1419   elf_sym_extra (abfd) = sym_extra
1420     = (Elf_Sym_Extra *) bfd_alloc (abfd, symcount * sizeof (Elf_Sym_Extra));
1421
1422   /* Identify and classify all of the symbols.  */
1423   for (idx = 0; idx < symcount; idx++)
1424     {
1425       if (!sym_is_global (syms[idx]))
1426         num_locals++;
1427       else
1428         num_globals++;
1429     }
1430
1431   /* Now provide mapping information.  Add +1 for skipping over the
1432      dummy symbol.  */
1433   for (idx = 0; idx < symcount; idx++)
1434     {
1435       syms[idx]->udata = (PTR) &sym_extra[idx];
1436       if (!sym_is_global (syms[idx]))
1437         sym_extra[idx].elf_sym_num = 1 + num_locals2++;
1438       else
1439         sym_extra[idx].elf_sym_num = 1 + num_locals + num_globals2++;
1440     }
1441
1442   elf_num_locals (abfd) = num_locals;
1443   elf_num_globals (abfd) = num_globals;
1444 }
1445
1446 static void assign_section_numbers ();
1447 static void assign_file_positions_except_relocs ();
1448
1449 static boolean
1450 DEFUN (elf_compute_section_file_positions, (abfd), bfd * abfd)
1451 {
1452   Elf_Internal_Ehdr *i_ehdrp;   /* Elf file header, internal form */
1453   Elf_Internal_Shdr *i_shdrp;   /* Section header table, internal form */
1454   struct strtab *shstrtab;
1455   int count, maxsections;
1456
1457   bfd_map_over_sections (abfd, elf_fake_sections, 0);
1458
1459   assign_section_numbers (abfd);
1460
1461   bfd_map_over_sections (abfd, elf_make_sections, 0);
1462
1463   bfd_map_over_sections (abfd, fix_up_strtabs, 0); /* .stab/.stabstr &c */
1464
1465   swap_out_syms (abfd);
1466
1467   assign_file_positions_except_relocs (abfd);
1468
1469   return true;
1470 }
1471
1472 static boolean
1473 DEFUN (elf_write_phdrs, (abfd, i_ehdrp, i_phdrp, phdr_cnt),
1474        bfd * abfd AND
1475        Elf_Internal_Ehdr * i_ehdrp AND
1476        Elf_Internal_Phdr * i_phdrp AND
1477        Elf32_Half phdr_cnt)
1478 {
1479   /* first program header entry goes after the file header */
1480   int outbase = i_ehdrp->e_phoff;
1481   int i;
1482   Elf_External_Phdr x_phdr;
1483
1484   for (i = 0; i < phdr_cnt; i++)
1485     {
1486       elf_swap_phdr_out (abfd, i_phdrp + i, &x_phdr);
1487       bfd_seek (abfd, outbase, SEEK_SET);
1488       bfd_write ((PTR) & x_phdr, sizeof (x_phdr), 1, abfd);
1489       outbase += sizeof (x_phdr);
1490     }
1491
1492   return true;
1493 }
1494
1495 static const Elf_Internal_Shdr null_shdr;
1496
1497 /* Assign all ELF section numbers.  The dummy first section is handled here
1498    too.  The link/info pointers for the standard section types are filled
1499    in here too, while we're at it.  (Link pointers for .stab sections are
1500    not filled in here.)  */
1501 static void
1502 assign_section_numbers (abfd)
1503      bfd *abfd;
1504 {
1505   struct elf_obj_tdata *t = elf_tdata (abfd);
1506   asection *sec;
1507   int section_number = 1;
1508   int i;
1509   Elf_Internal_Shdr **i_shdrp;
1510
1511   t->shstrtab_hdr.sh_size = elf_shstrtab(abfd)->length;
1512   t->shstrtab_hdr.contents = (void *) elf_shstrtab(abfd)->tab;
1513   shstrtab_length_fixed = 1;
1514
1515   t->shstrtab_section = section_number++;
1516   elf_elfheader(abfd)->e_shstrndx = t->shstrtab_section;
1517   if (abfd->symcount)
1518     {
1519       t->symtab_section = section_number++;
1520       t->strtab_section = section_number++;
1521       t->symtab_hdr.sh_link = t->strtab_section;
1522     }
1523   for (sec = abfd->sections; sec; sec = sec->next)
1524     {
1525       struct bfd_elf_section_data *d = elf_section_data (sec);
1526       d->this_idx = section_number++;
1527       if (sec->flags & SEC_RELOC)
1528         {
1529           d->rel_idx = section_number++;
1530           d->rel_hdr.sh_link = t->symtab_section;
1531           d->rel_hdr.sh_info = d->this_idx;
1532         }
1533       else
1534         d->rel_idx = 0;
1535       /* No handling for per-section string tables currently.  */
1536     }
1537   elf_elfheader(abfd)->e_shnum = section_number;
1538
1539   /* Set up the list of section header pointers, in agreement with the
1540      indices.  */
1541   i_shdrp = (Elf_Internal_Shdr **)
1542     bfd_alloc (abfd, section_number * sizeof (Elf_Internal_Shdr *));
1543   elf_elfsections(abfd) = i_shdrp;
1544   for (i = 0; i < section_number; i++)
1545     i_shdrp[i] = 0;
1546
1547   i_shdrp[0] = (Elf_Internal_Shdr *) &null_shdr;
1548   i_shdrp[t->shstrtab_section] = &t->shstrtab_hdr;
1549   if (abfd->symcount)
1550     {
1551       i_shdrp[t->symtab_section] = &t->symtab_hdr;
1552       i_shdrp[t->strtab_section] = &t->strtab_hdr;
1553     }
1554   for (sec = abfd->sections; sec; sec = sec->next)
1555     {
1556       struct bfd_elf_section_data *d = elf_section_data (sec);
1557       i_shdrp[d->this_idx] = &d->this_hdr;
1558       if (d->rel_idx)
1559         i_shdrp[d->rel_idx] = &d->rel_hdr;
1560     }
1561   /* Make sure we got everything.... */
1562   for (i = 0; i < section_number; i++)
1563     if (i_shdrp[i] == 0)
1564       abort ();
1565 }
1566
1567 static INLINE file_ptr
1568 assign_file_position_for_section (i_shdrp, offset)
1569      Elf_Internal_Shdr *i_shdrp;
1570      file_ptr offset;
1571 {
1572   i_shdrp->sh_offset = offset;
1573   if (i_shdrp->sh_type != SHT_NOBITS)
1574     offset += i_shdrp->sh_size;
1575   return offset;
1576 }
1577
1578 static INLINE file_ptr
1579 assign_file_positions_for_symtab_and_strtabs (abfd, off)
1580      bfd *abfd;
1581      file_ptr off;
1582 {
1583   struct elf_obj_tdata *t = elf_tdata (abfd);
1584
1585   off = assign_file_position_for_section (&t->shstrtab_hdr, off);
1586   off = assign_file_position_for_section (&t->symtab_hdr, off);
1587   off = assign_file_position_for_section (&t->strtab_hdr, off);
1588   return off;
1589 }
1590
1591 struct seg_info {
1592   bfd_vma low, mem_size;
1593   file_ptr file_size;
1594   int start_pos;
1595   int sh_flags;
1596   struct seg_info *next;
1597 };
1598
1599 static void
1600 map_program_segments (abfd)
1601      bfd *abfd;
1602 {
1603   Elf_Internal_Shdr **i_shdrpp = elf_elfsections (abfd);
1604   Elf_Internal_Ehdr *i_ehdrp = elf_elfheader (abfd);
1605   Elf_Internal_Shdr *i_shdrp;
1606   Elf_Internal_Phdr *phdr;
1607   char *done;
1608   int i, n_left = 0;
1609   file_ptr lowest_offset = 0;
1610   struct seg_info *seg = 0;
1611
1612   done = (char *) alloca (i_ehdrp->e_shnum);
1613   memset (done, 0, i_ehdrp->e_shnum);
1614   for (i = 0; i < i_ehdrp->e_shnum; i++)
1615     {
1616       i_shdrp = i_shdrpp[i];
1617       /* If it's going to be mapped in, it's been assigned a position.  */
1618       if (i_shdrp->sh_offset + 1 == 0)
1619         {
1620           /* Well, not really, but we won't process it here.   */
1621           done[i] = 1;
1622           continue;
1623         }
1624       if (i_shdrp->sh_offset < lowest_offset
1625           || lowest_offset == 0)
1626         lowest_offset = i_shdrp->sh_offset;
1627       /* Only interested in PROGBITS or NOBITS for generating segments.  */
1628       switch (i_shdrp->sh_type)
1629         {
1630         case SHT_PROGBITS:
1631         case SHT_NOBITS:
1632           break;
1633         default:
1634           done[i] = 1;
1635         }
1636       if (!done[i])
1637         n_left++;
1638     }
1639   while (n_left)
1640     {
1641       bfd_vma lowest_vma = -1, high;
1642       int low_sec = 0;
1643       int mem_size;
1644       int file_size = 0;
1645
1646       for (i = 1; i < i_ehdrp->e_shnum; i++)
1647         {
1648           i_shdrp = i_shdrpp[i];
1649           if (!done[i] && i_shdrp->sh_addr < lowest_vma)
1650             {
1651               lowest_vma = i_shdrp->sh_addr;
1652               low_sec = i;
1653             }
1654         }
1655       if (low_sec == 0)
1656         abort ();
1657       /* So now we know the lowest vma of any unassigned sections; start
1658          a segment there.  */
1659       {
1660         struct seg_info *s;
1661         s = (struct seg_info *) bfd_alloc (abfd, sizeof (struct seg_info));
1662         s->next = seg;
1663         seg = s;
1664       }
1665       seg->low = lowest_vma;
1666       i_shdrp = i_shdrpp[low_sec];
1667       seg->start_pos = i_shdrp->sh_offset;
1668       seg->sh_flags = i_shdrp->sh_flags;
1669       done[low_sec] = 1, n_left--;
1670       mem_size = i_shdrp->sh_size;
1671       high = lowest_vma + i_shdrp->sh_size;
1672
1673       if (i_shdrp->sh_type == SHT_PROGBITS)
1674         file_size = i_shdrp->sh_size;
1675
1676       for (i = 0; i < i_ehdrp->e_shnum; i++)
1677         {
1678           file_ptr f1;
1679
1680           if (file_size != mem_size)
1681             break;
1682           if (done[i])
1683             continue;
1684           i_shdrp = i_shdrpp[i];
1685           /* position of next byte on disk */
1686           f1 = seg->start_pos + file_size;
1687           if (i_shdrp->sh_type == SHT_PROGBITS)
1688             {
1689               if (i_shdrp->sh_offset - f1 != i_shdrp->sh_addr - high)
1690                 continue;
1691             }
1692           else /* sh_type == NOBITS */
1693             {
1694               /* If the section in question has no contents in the disk
1695                  file, we really don't care where it supposedly starts.
1696                  But we don't want to bother merging it into this segment
1697                  if it doesn't start on this memory page.  */
1698               bfd_vma page1, page2;
1699               bfd_vma maxpagesize = get_elf_backend_data (abfd)->maxpagesize;
1700
1701               /* page number in address space of current end of seg */
1702               page1 = (high - 1 + maxpagesize - 1) / maxpagesize;
1703               /* page number in address space of start of this section */
1704               page2 = (i_shdrp->sh_addr + maxpagesize - 1) / maxpagesize;
1705
1706               if (page1 != page2)
1707                 continue;
1708             }
1709           done[i] = 1, n_left--;
1710           if (i_shdrp->sh_type == SHT_PROGBITS)
1711             file_size = i_shdrp->sh_offset + i_shdrp->sh_size - seg->start_pos;
1712           mem_size = i_shdrp->sh_addr + i_shdrp->sh_size - seg->low;
1713           high = i_shdrp->sh_addr + i_shdrp->sh_size;
1714           i = 0;
1715         }
1716       seg->file_size = file_size;
1717       seg->mem_size = mem_size;
1718     }
1719   /* Now do something with the list of segments we've built up.  */
1720   {
1721     bfd_vma maxpagesize = get_elf_backend_data (abfd)->maxpagesize;
1722     struct seg_info *s;
1723     int n_segs = 0;
1724     int sz;
1725
1726     for (s = seg; s; s = s->next)
1727       {
1728         n_segs++;
1729       }
1730     i_ehdrp->e_phentsize = sizeof (Elf_External_Phdr);
1731     sz = sizeof (Elf_External_Phdr) * n_segs;
1732     if (i_ehdrp->e_ehsize + sz <= lowest_offset)
1733       i_ehdrp->e_phoff = i_ehdrp->e_ehsize;
1734     else
1735       {
1736         i_ehdrp->e_phoff = elf_tdata (abfd)->next_file_pos;
1737         elf_tdata (abfd)->next_file_pos += sz;
1738       }
1739     phdr = (Elf_Internal_Phdr*) bfd_alloc (abfd,
1740                                            n_segs * sizeof (Elf_Internal_Phdr));
1741     elf_tdata (abfd)->phdr = phdr;
1742     while (seg)
1743       {
1744         phdr->p_type = PT_LOAD; /* only type we really support so far */
1745         phdr->p_offset = seg->start_pos;
1746         phdr->p_vaddr = seg->low;
1747         phdr->p_paddr = 0;
1748         phdr->p_filesz = seg->file_size;
1749         phdr->p_memsz = seg->mem_size;
1750         phdr->p_flags = PF_R;
1751         phdr->p_align = maxpagesize; /* ? */
1752         if (seg->sh_flags & SHF_WRITE)
1753           phdr->p_flags |= PF_W;
1754         if (seg->sh_flags & SHF_EXECINSTR)
1755           phdr->p_flags |= PF_X;
1756         phdr++;
1757         seg = seg->next;
1758       }
1759     i_ehdrp->e_phnum = n_segs;
1760   }
1761   elf_write_phdrs (abfd, i_ehdrp, elf_tdata (abfd)->phdr, i_ehdrp->e_phnum);
1762 }
1763
1764 static void
1765 assign_file_positions_except_relocs (abfd)
1766      bfd *abfd;
1767 {
1768   /* For now, we ignore the possibility of having program segments, which
1769      may require some alignment in the file.  That'll require padding, and
1770      some interesting calculations to optimize file space usage.
1771
1772      Also, since the application may change the list of relocations for
1773      a given section, we don't figure them in here.  We'll put them at the
1774      end of the file, at positions computed during bfd_close.
1775
1776      The order, for now: <ehdr> <shdr> <sec1> <sec2> <sec3> ... <rel1> ...
1777      or:                 <ehdr> <phdr> <sec1> <sec2> ... <shdr> <rel1> ... */
1778
1779   file_ptr off;
1780   int i;
1781   Elf_Internal_Shdr **i_shdrpp = elf_elfsections (abfd);
1782   Elf_Internal_Shdr *i_shdrp;
1783   Elf_Internal_Ehdr *i_ehdrp = elf_elfheader (abfd);
1784   int exec_p = (abfd->flags & EXEC_P) != 0;
1785
1786   /* Everything starts after the ELF file header.  */
1787   off = i_ehdrp->e_ehsize;
1788
1789   if (!exec_p)
1790     {
1791       /* Section headers.  */
1792       i_ehdrp->e_shoff = off;
1793       off += i_ehdrp->e_shnum * i_ehdrp->e_shentsize;
1794
1795       off = assign_file_positions_for_symtab_and_strtabs (abfd, off);
1796     }
1797   for (i = 0; i < i_ehdrp->e_shnum; i++)
1798     {
1799       i_shdrp = i_shdrpp[i];
1800       if (i_shdrp->sh_type == SHT_REL || i_shdrp->sh_type == SHT_RELA)
1801         {
1802           i_shdrp->sh_offset = -1;
1803           continue;
1804         }
1805       if (exec_p)
1806         {
1807           bfd_vma maxpagesize = get_elf_backend_data (abfd)->maxpagesize;
1808           if (maxpagesize == 0)
1809             maxpagesize = 1;    /* make the arithmetic work */
1810           /* This isn't necessarily going to give the best packing, if the
1811              segments require padding between them, but since that isn't
1812              usually the case, this'll do.  */
1813           if ((i_shdrp->sh_flags & SHF_ALLOC) == 0)
1814             {
1815               i_shdrp->sh_offset = -1;
1816               continue;
1817             }
1818           /* Blindly assume that the segments are ordered optimally.  With
1819              the default LD script, they will be.  */
1820           {
1821             /* need big unsigned type */
1822             bfd_vma addtl_off;
1823             addtl_off = i_shdrp->sh_addr - off;
1824             addtl_off = addtl_off % maxpagesize;
1825             if (addtl_off)
1826               {
1827                 off += addtl_off;
1828               }
1829           }
1830           if (i_shdrp->sh_type == SHT_NOBITS)
1831             {
1832               file_ptr off2;
1833               i_shdrp->sh_offset = off;
1834               if (off % maxpagesize != 0)
1835                 off2 = maxpagesize - (off % maxpagesize);
1836               if (off2 > i_shdrp->sh_size)
1837                 off2 = i_shdrp->sh_size;
1838               off += off2;
1839             }
1840         }
1841       off = assign_file_position_for_section (i_shdrp, off);
1842       if (exec_p
1843           && get_elf_backend_data(abfd)->maxpagesize > 1
1844           && i_shdrp->sh_type == SHT_PROGBITS
1845           && (i_shdrp->sh_flags & SHF_ALLOC)
1846           && (i_shdrp->sh_offset - i_shdrp->sh_addr) % get_elf_backend_data(abfd)->maxpagesize != 0)
1847         abort ();
1848     }
1849   if (exec_p)
1850     {
1851       elf_tdata (abfd)->next_file_pos = off;
1852       map_program_segments (abfd);
1853       off = elf_tdata (abfd)->next_file_pos;
1854
1855       /* Section headers.  */
1856       i_ehdrp->e_shoff = off;
1857       off += i_ehdrp->e_shnum * i_ehdrp->e_shentsize;
1858
1859       off = assign_file_positions_for_symtab_and_strtabs (abfd, off);
1860
1861       for (i = 0; i < i_ehdrp->e_shnum; i++)
1862         {
1863           i_shdrp = i_shdrpp[i];
1864           if (i_shdrp->sh_offset + 1 == 0
1865               && i_shdrp->sh_type != SHT_REL
1866               && i_shdrp->sh_type != SHT_RELA)
1867             off = assign_file_position_for_section (i_shdrp, off);
1868         }
1869     }
1870   elf_tdata (abfd)->next_file_pos = off;
1871 }
1872
1873 static boolean
1874 prep_headers (abfd)
1875      bfd *abfd;
1876 {
1877   Elf_External_Ehdr x_ehdr;     /* Elf file header, external form */
1878   Elf_Internal_Ehdr *i_ehdrp;   /* Elf file header, internal form */
1879   Elf_Internal_Phdr *i_phdrp = 0; /* Program header table, internal form */
1880   Elf_External_Shdr *x_shdrp;   /* Section header table, external form */
1881   Elf_Internal_Shdr **i_shdrp;  /* Section header table, internal form */
1882
1883   int count;
1884   int scnt;
1885   struct strtab *shstrtab;
1886
1887   i_ehdrp = elf_elfheader (abfd);
1888   i_shdrp = elf_elfsections (abfd);
1889
1890   shstrtab = bfd_new_strtab (abfd);
1891   elf_shstrtab (abfd) = shstrtab;
1892
1893   i_ehdrp->e_ident[EI_MAG0] = ELFMAG0;
1894   i_ehdrp->e_ident[EI_MAG1] = ELFMAG1;
1895   i_ehdrp->e_ident[EI_MAG2] = ELFMAG2;
1896   i_ehdrp->e_ident[EI_MAG3] = ELFMAG3;
1897
1898   i_ehdrp->e_ident[EI_CLASS] = ELFCLASS;
1899   i_ehdrp->e_ident[EI_DATA] =
1900     abfd->xvec->byteorder_big_p ? ELFDATA2MSB : ELFDATA2LSB;
1901   i_ehdrp->e_ident[EI_VERSION] = EV_CURRENT;
1902
1903   for (count = EI_PAD; count < EI_NIDENT; count++)
1904     i_ehdrp->e_ident[count] = 0;
1905
1906   i_ehdrp->e_type = (abfd->flags & EXEC_P) ? ET_EXEC : ET_REL;
1907   switch (bfd_get_arch (abfd))
1908     {
1909     case bfd_arch_unknown:
1910       i_ehdrp->e_machine = EM_NONE;
1911       break;
1912     case bfd_arch_sparc:
1913       i_ehdrp->e_machine = EM_SPARC;
1914       /* start-sanitize-v9 */
1915 #if ARCH_SIZE == 64
1916       i_ehdrp->e_machine = EM_SPARC64;
1917 #endif
1918       /* end-sanitize-v9 */
1919       break;
1920     case bfd_arch_i386:
1921       i_ehdrp->e_machine = EM_386;
1922       break;
1923     case bfd_arch_m68k:
1924       i_ehdrp->e_machine = EM_68K;
1925       break;
1926     case bfd_arch_m88k:
1927       i_ehdrp->e_machine = EM_88K;
1928       break;
1929     case bfd_arch_i860:
1930       i_ehdrp->e_machine = EM_860;
1931       break;
1932     case bfd_arch_mips: /* MIPS Rxxxx */
1933       i_ehdrp->e_machine = EM_MIPS;     /* only MIPS R3000 */
1934       break;
1935     case bfd_arch_hppa:
1936       i_ehdrp->e_machine = EM_HPPA;
1937       break;
1938       /* also note that EM_M32, AT&T WE32100 is unknown to bfd */
1939     default:
1940       i_ehdrp->e_machine = EM_NONE;
1941     }
1942   i_ehdrp->e_version = EV_CURRENT;
1943   i_ehdrp->e_ehsize = sizeof (Elf_External_Ehdr);
1944
1945   /* no program header, for now. */
1946   i_ehdrp->e_phoff = 0;
1947   i_ehdrp->e_phentsize = 0;
1948   i_ehdrp->e_phnum = 0;
1949
1950   /* each bfd section is section header entry */
1951   i_ehdrp->e_entry = bfd_get_start_address (abfd);
1952   i_ehdrp->e_shentsize = sizeof (Elf_External_Shdr);
1953
1954   /* if we're building an executable, we'll need a program header table */
1955   if (abfd->flags & EXEC_P)
1956     {
1957       /* it all happens later */
1958 #if 0
1959       i_ehdrp->e_phentsize = sizeof (Elf_External_Phdr);
1960
1961       /* elf_build_phdrs() returns a (NULL-terminated) array of
1962          Elf_Internal_Phdrs */
1963       i_phdrp = elf_build_phdrs (abfd, i_ehdrp, i_shdrp, &i_ehdrp->e_phnum);
1964       i_ehdrp->e_phoff = outbase;
1965       outbase += i_ehdrp->e_phentsize * i_ehdrp->e_phnum;
1966 #endif
1967     }
1968   else
1969     {
1970       i_ehdrp->e_phentsize = 0;
1971       i_phdrp = 0;
1972       i_ehdrp->e_phoff = 0;
1973     }
1974
1975   elf_tdata (abfd)->symtab_hdr.sh_name = bfd_add_to_strtab (abfd, shstrtab,
1976                                                             ".symtab");
1977   elf_tdata (abfd)->strtab_hdr.sh_name = bfd_add_to_strtab (abfd, shstrtab,
1978                                                             ".strtab");
1979   elf_tdata (abfd)->shstrtab_hdr.sh_name = bfd_add_to_strtab (abfd, shstrtab,
1980                                                               ".shstrtab");
1981
1982 }
1983
1984 static void
1985 swap_out_syms (abfd)
1986      bfd *abfd;
1987 {
1988   struct strtab *shstrtab = elf_shstrtab (abfd);
1989
1990   elf_map_symbols (abfd);
1991
1992   /* Dump out the symtabs. */
1993   {
1994     int symcount = bfd_get_symcount (abfd);
1995     asymbol **syms = bfd_get_outsymbols (abfd);
1996     struct strtab *stt = bfd_new_strtab (abfd);
1997     Elf_Internal_Shdr *symtab_hdr;
1998     Elf_Internal_Shdr *symstrtab_hdr;
1999     Elf_External_Sym *outbound_syms;
2000     int idx;
2001
2002     symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
2003     symtab_hdr->sh_type = SHT_SYMTAB;
2004     symtab_hdr->sh_entsize = sizeof (Elf_External_Sym);
2005     symtab_hdr->sh_size = symtab_hdr->sh_entsize * (symcount + 1);
2006     symtab_hdr->sh_info = elf_num_locals (abfd) + 1;
2007
2008     /* see assert in elf_fake_sections that supports this: */
2009     symstrtab_hdr = &elf_tdata (abfd)->strtab_hdr;
2010     symstrtab_hdr->sh_type = SHT_STRTAB;
2011
2012     outbound_syms = (Elf_External_Sym *)
2013       bfd_alloc (abfd, (1 + symcount) * sizeof (Elf_External_Sym));
2014     /* now generate the data (for "contents") */
2015     {
2016       /* Fill in zeroth symbol and swap it out.  */
2017       Elf_Internal_Sym sym;
2018       sym.st_name = 0;
2019       sym.st_value = 0;
2020       sym.st_size = 0;
2021       sym.st_info = 0;
2022       sym.st_other = 0;
2023       sym.st_shndx = SHN_UNDEF;
2024       elf_swap_symbol_out (abfd, &sym, outbound_syms);
2025     }
2026     for (idx = 0; idx < symcount; idx++)
2027       {
2028         Elf_Internal_Sym sym;
2029         bfd_vma value = syms[idx]->value;
2030
2031         if (syms[idx]->flags & BSF_SECTION_SYM)
2032           /* Section symbols have no names.  */
2033           sym.st_name = 0;
2034         else
2035           sym.st_name = bfd_add_to_strtab (abfd, stt, syms[idx]->name);
2036
2037         if (bfd_is_com_section (syms[idx]->section))
2038           {
2039             /* ELF common symbols put the alignment into the `value' field,
2040                and the size into the `size' field.  This is backwards from
2041                how BFD handles it, so reverse it here.  */
2042             sym.st_size = value;
2043             /* Should retrieve this from somewhere... */
2044             sym.st_value = 16;
2045             sym.st_shndx = SHN_COMMON;
2046           }
2047         else
2048           {
2049             asection *sec = syms[idx]->section;
2050             elf_symbol_type *type_ptr;
2051             int shndx;
2052
2053             if (sec->output_section)
2054               {
2055                 value += sec->output_offset;
2056                 sec = sec->output_section;
2057               }
2058             value += sec->vma;
2059             sym.st_value = value;
2060             type_ptr = elf_symbol_from (abfd, syms[idx]);
2061             sym.st_size = type_ptr ? type_ptr->internal_elf_sym.st_size : 0;
2062             sym.st_shndx = shndx = elf_section_from_bfd_section (abfd, sec);
2063             if (shndx == -1)
2064               {
2065                 asection *sec2;
2066                 /* Writing this would be a hell of a lot easier if we had
2067                    some decent documentation on bfd, and knew what to expect
2068                    of the library, and what to demand of applications.  For
2069                    example, it appears that `objcopy' might not set the
2070                    section of a symbol to be a section that is actually in
2071                    the output file.  */
2072                 sec2 = bfd_get_section_by_name (abfd, sec->name);
2073                 assert (sec2 != 0);
2074                 sym.st_shndx = shndx = elf_section_from_bfd_section (abfd, sec2);
2075                 assert (shndx != -1);
2076               }
2077           }
2078
2079         if (bfd_is_com_section (syms[idx]->section))
2080           sym.st_info = ELF_ST_INFO (STB_GLOBAL, STT_NOTYPE);
2081         else if (syms[idx]->section == &bfd_und_section)
2082           sym.st_info = ELF_ST_INFO (STB_GLOBAL, STT_NOTYPE);
2083         else if (syms[idx]->flags & BSF_SECTION_SYM)
2084           sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
2085         else if (syms[idx]->flags & BSF_FILE)
2086           sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
2087         else
2088           {
2089             int bind = STB_LOCAL;
2090             int type = STT_OBJECT;
2091             unsigned int flags = syms[idx]->flags;
2092
2093             if (flags & BSF_LOCAL)
2094               bind = STB_LOCAL;
2095             else if (flags & BSF_WEAK)
2096               bind = STB_WEAK;
2097             else if (flags & BSF_GLOBAL)
2098               bind = STB_GLOBAL;
2099
2100             if (flags & BSF_FUNCTION)
2101               type = STT_FUNC;
2102
2103             sym.st_info = ELF_ST_INFO (bind, type);
2104           }
2105
2106         sym.st_other = 0;
2107         elf_swap_symbol_out (abfd, &sym,
2108                              (outbound_syms
2109                               + elf_sym_extra (abfd)[idx].elf_sym_num));
2110       }
2111
2112     symtab_hdr->contents = (PTR) outbound_syms;
2113     symstrtab_hdr->contents = (PTR) stt->tab;
2114     symstrtab_hdr->sh_size = stt->length;
2115     symstrtab_hdr->sh_type = SHT_STRTAB;
2116
2117     symstrtab_hdr->sh_flags = 0;
2118     symstrtab_hdr->sh_addr = 0;
2119     symstrtab_hdr->sh_entsize = 0;
2120     symstrtab_hdr->sh_link = 0;
2121     symstrtab_hdr->sh_info = 0;
2122     symstrtab_hdr->sh_addralign = 0;
2123     symstrtab_hdr->size = 0;
2124   }
2125
2126   /* put the strtab out too... */
2127   {
2128     Elf_Internal_Shdr *this_hdr;
2129
2130     this_hdr = &elf_tdata(abfd)->shstrtab_hdr;
2131     this_hdr->contents = (PTR) elf_shstrtab (abfd)->tab;
2132     this_hdr->sh_size = elf_shstrtab (abfd)->length;
2133     this_hdr->sh_type = SHT_STRTAB;
2134     this_hdr->sh_flags = 0;
2135     this_hdr->sh_addr = 0;
2136     this_hdr->sh_entsize = 0;
2137     this_hdr->sh_addralign = 0;
2138     this_hdr->size = 0;
2139   }
2140 }
2141
2142 static boolean
2143 write_shdrs_and_ehdr (abfd)
2144      bfd *abfd;
2145 {
2146   Elf_External_Ehdr x_ehdr;     /* Elf file header, external form */
2147   Elf_Internal_Ehdr *i_ehdrp;   /* Elf file header, internal form */
2148   Elf_Internal_Phdr *i_phdrp = 0; /* Program header table, internal form */
2149   Elf_External_Shdr *x_shdrp;   /* Section header table, external form */
2150   Elf_Internal_Shdr **i_shdrp;  /* Section header table, internal form */
2151
2152   int count;
2153   int scnt;
2154   struct strtab *shstrtab;
2155
2156   i_ehdrp = elf_elfheader (abfd);
2157   i_shdrp = elf_elfsections (abfd);
2158   shstrtab = elf_shstrtab (abfd);
2159
2160   /* swap the header before spitting it out... */
2161
2162 #if DEBUG & 1
2163   elf_debug_file (i_ehdrp);
2164 #endif
2165   elf_swap_ehdr_out (abfd, i_ehdrp, &x_ehdr);
2166   bfd_seek (abfd, (file_ptr) 0, SEEK_SET);
2167   bfd_write ((PTR) & x_ehdr, sizeof (x_ehdr), 1, abfd);
2168
2169   /* at this point we've concocted all the ELF sections... */
2170   x_shdrp = (Elf_External_Shdr *)
2171     bfd_alloc (abfd, sizeof (*x_shdrp) * (i_ehdrp->e_shnum));
2172   if (!x_shdrp)
2173     {
2174       bfd_error = no_memory;
2175       return false;
2176     }
2177
2178   for (count = 0; count < i_ehdrp->e_shnum; count++)
2179     {
2180 #if DEBUG & 2
2181       elf_debug_section (shstrtab->tab + i_shdrp[count]->sh_name, count,
2182                          i_shdrp[count]);
2183 #endif
2184       elf_swap_shdr_out (abfd, i_shdrp[count], x_shdrp + count);
2185     }
2186   bfd_seek (abfd, (file_ptr) i_ehdrp->e_shoff, SEEK_SET);
2187   bfd_write ((PTR) x_shdrp, sizeof (*x_shdrp), i_ehdrp->e_shnum, abfd);
2188   /* need to dump the string table too... */
2189
2190   return true;
2191 }
2192
2193 static void
2194 assign_file_positions_for_relocs (abfd)
2195      bfd *abfd;
2196 {
2197   file_ptr off = elf_tdata(abfd)->next_file_pos;
2198   int i;
2199   Elf_Internal_Shdr **shdrpp = elf_elfsections (abfd);
2200   Elf_Internal_Shdr *shdrp;
2201   for (i = 0; i < elf_elfheader(abfd)->e_shnum; i++)
2202     {
2203       shdrp = shdrpp[i];
2204       if (shdrp->sh_type != SHT_REL && shdrp->sh_type != SHT_RELA)
2205         continue;
2206       off = assign_file_position_for_section (shdrp, off);
2207     }
2208   elf_tdata(abfd)->next_file_pos = off;
2209 }
2210
2211 boolean
2212 DEFUN (NAME(bfd_elf,write_object_contents), (abfd), bfd * abfd)
2213 {
2214   Elf_Internal_Ehdr *i_ehdrp;
2215   Elf_Internal_Shdr **i_shdrp;
2216   int count;
2217
2218   if (abfd->output_has_begun == false)
2219     {
2220       prep_headers (abfd);
2221       elf_compute_section_file_positions (abfd);
2222       abfd->output_has_begun = true;
2223     }
2224
2225   i_shdrp = elf_elfsections (abfd);
2226   i_ehdrp = elf_elfheader (abfd);
2227
2228   bfd_map_over_sections (abfd, write_relocs, (PTR) 0);
2229   assign_file_positions_for_relocs (abfd);
2230
2231   /* After writing the headers, we need to write the sections too... */
2232   for (count = 0; count < i_ehdrp->e_shnum; count++)
2233     if (i_shdrp[count]->contents)
2234       {
2235         bfd_seek (abfd, i_shdrp[count]->sh_offset, SEEK_SET);
2236         bfd_write (i_shdrp[count]->contents, i_shdrp[count]->sh_size, 1, abfd);
2237       }
2238   return write_shdrs_and_ehdr (abfd);
2239 }
2240
2241 /* Given an index of a section, retrieve a pointer to it.  Note
2242    that for our purposes, sections are indexed by {1, 2, ...} with
2243    0 being an illegal index. */
2244
2245 /* In the original, each ELF section went into exactly one BFD
2246    section. This doesn't really make sense, so we need a real mapping.
2247    The mapping has to hide in the Elf_Internal_Shdr since asection
2248    doesn't have anything like a tdata field... */
2249
2250 static struct sec *
2251 DEFUN (section_from_elf_index, (abfd, index),
2252        bfd * abfd AND
2253        int index)
2254 {
2255   /* @@ Is bfd_com_section really correct in all the places it could
2256      be returned from this routine?  */
2257
2258   if (index == SHN_ABS)
2259     return &bfd_com_section;    /* not abs? */
2260   if (index == SHN_COMMON)
2261     return &bfd_com_section;
2262
2263   if (index > elf_elfheader (abfd)->e_shnum)
2264     return 0;
2265
2266   {
2267     Elf_Internal_Shdr *hdr = elf_elfsections (abfd)[index];
2268
2269     switch (hdr->sh_type)
2270       {
2271         /* ELF sections that map to BFD sections */
2272       case SHT_PROGBITS:
2273       case SHT_NOBITS:
2274         if (!hdr->rawdata)
2275           bfd_section_from_shdr (abfd, index);
2276         return (struct sec *) hdr->rawdata;
2277
2278       default:
2279         return (struct sec *) &bfd_abs_section;
2280       }
2281   }
2282 }
2283
2284 /* given a section, search the header to find them... */
2285 static int
2286 DEFUN (elf_section_from_bfd_section, (abfd, asect),
2287        bfd * abfd AND
2288        struct sec *asect)
2289 {
2290   Elf_Internal_Shdr **i_shdrp = elf_elfsections (abfd);
2291   int index;
2292   Elf_Internal_Shdr *hdr;
2293   int maxindex = elf_elfheader (abfd)->e_shnum;
2294
2295   if (asect == &bfd_abs_section)
2296     return SHN_ABS;
2297   if (asect == &bfd_com_section)
2298     return SHN_COMMON;
2299   if (asect == &bfd_und_section)
2300     return SHN_UNDEF;
2301
2302   for (index = 0; index < maxindex; index++)
2303     {
2304       hdr = i_shdrp[index];
2305       switch (hdr->sh_type)
2306         {
2307           /* ELF sections that map to BFD sections */
2308         case SHT_PROGBITS:
2309         case SHT_NOBITS:
2310           if (hdr->rawdata)
2311             {
2312               if (((struct sec *) (hdr->rawdata)) == asect)
2313                 return index;
2314             }
2315           break;
2316         default:
2317           break;
2318         }
2319     }
2320   return -1;
2321 }
2322
2323 /* given a symbol, return the bfd index for that symbol.  */
2324 static int
2325 DEFUN (elf_symbol_from_bfd_symbol, (abfd, asym_ptr_ptr),
2326        bfd * abfd AND
2327        struct symbol_cache_entry **asym_ptr_ptr)
2328 {
2329   struct symbol_cache_entry *asym_ptr = *asym_ptr_ptr;
2330   CONST char *name = asym_ptr->name;
2331   int idx;
2332   int symcount = bfd_get_symcount (abfd);
2333   flagword flags = asym_ptr->flags;
2334   asymbol **syms = bfd_get_outsymbols (abfd);
2335
2336   /* When gas creates relocations against local labels, it creates its
2337      own symbol for the section, but does put the symbol into the
2338      symbol chain, so udata is 0.  */
2339   if (asym_ptr->udata == (PTR) 0
2340       && (flags & BSF_SECTION_SYM)
2341       && asym_ptr->section
2342       && elf_section_syms (abfd)[asym_ptr->section->index])
2343     asym_ptr->udata = elf_section_syms (abfd)[asym_ptr->section->index]->udata;
2344   
2345   if (asym_ptr->udata)
2346     idx = ((Elf_Sym_Extra *)asym_ptr->udata)->elf_sym_num;
2347   else
2348     {
2349       abort ();
2350     }
2351
2352 #if DEBUG & 4
2353   {
2354
2355     fprintf (stderr,
2356              "elf_symbol_from_bfd_symbol 0x%.8lx, name = %s, sym num = %d, flags = 0x%.8lx %s\n",
2357              (long) asym_ptr, asym_ptr->name, idx, flags, elf_symbol_flags (flags));
2358     fflush (stderr);
2359   }
2360 #endif
2361
2362   return idx;
2363 }
2364
2365 static boolean
2366 DEFUN (elf_slurp_symbol_table, (abfd, symptrs),
2367        bfd * abfd AND
2368        asymbol ** symptrs)      /* Buffer for generated bfd symbols */
2369 {
2370   Elf_Internal_Shdr *hdr = &elf_tdata(abfd)->symtab_hdr;
2371   int symcount;                 /* Number of external ELF symbols */
2372   int i;
2373   elf_symbol_type *sym;         /* Pointer to current bfd symbol */
2374   elf_symbol_type *symbase;     /* Buffer for generated bfd symbols */
2375   Elf_Internal_Sym i_sym;
2376   Elf_External_Sym *x_symp;
2377
2378   /* this is only valid because there is only one symtab... */
2379   /* FIXME:  This is incorrect, there may also be a dynamic symbol
2380      table which is a subset of the full symbol table.  We either need
2381      to be prepared to read both (and merge them) or ensure that we
2382      only read the full symbol table.  Currently we only get called to
2383      read the full symbol table.  -fnf */
2384   if (bfd_get_outsymbols (abfd) != NULL)
2385     {
2386       return true;
2387     }
2388
2389   /* Read each raw ELF symbol, converting from external ELF form to
2390      internal ELF form, and then using the information to create a
2391      canonical bfd symbol table entry.
2392
2393      Note that we allocate the initial bfd canonical symbol buffer
2394      based on a one-to-one mapping of the ELF symbols to canonical
2395      symbols.  We actually use all the ELF symbols, so there will be no
2396      space left over at the end.  When we have all the symbols, we
2397      build the caller's pointer vector. */
2398
2399   if (bfd_seek (abfd, hdr->sh_offset, SEEK_SET) == -1)
2400     {
2401       bfd_error = system_call_error;
2402       return false;
2403     }
2404
2405   symcount = hdr->sh_size / sizeof (Elf_External_Sym);
2406   symbase = (elf_symbol_type *) bfd_zalloc (abfd, symcount * sizeof (elf_symbol_type));
2407   sym = symbase;
2408
2409   /* Temporarily allocate room for the raw ELF symbols.  */
2410   x_symp = (Elf_External_Sym *) bfd_xmalloc (symcount * sizeof (Elf_External_Sym));
2411
2412   if (bfd_read ((PTR) x_symp, sizeof (Elf_External_Sym), symcount, abfd)
2413       != symcount * sizeof (Elf_External_Sym))
2414     {
2415       free ((PTR) x_symp);
2416       bfd_error = system_call_error;
2417       return false;
2418     }
2419   /* Skip first symbol, which is a null dummy.  */
2420   for (i = 1; i < symcount; i++)
2421     {
2422       elf_swap_symbol_in (abfd, x_symp + i, &i_sym);
2423       memcpy (&sym->internal_elf_sym, &i_sym, sizeof (Elf_Internal_Sym));
2424       memcpy (&sym->native_elf_sym, x_symp + i, sizeof (Elf_External_Sym));
2425       sym->symbol.the_bfd = abfd;
2426
2427       sym->symbol.name = elf_string_from_elf_section (abfd, hdr->sh_link,
2428                                                       i_sym.st_name);
2429
2430       sym->symbol.value = i_sym.st_value;
2431
2432       if (i_sym.st_shndx > 0 && i_sym.st_shndx < SHN_LORESERV)
2433         {
2434           sym->symbol.section = section_from_elf_index (abfd, i_sym.st_shndx);
2435         }
2436       else if (i_sym.st_shndx == SHN_ABS)
2437         {
2438           sym->symbol.section = &bfd_abs_section;
2439         }
2440       else if (i_sym.st_shndx == SHN_COMMON)
2441         {
2442           sym->symbol.section = &bfd_com_section;
2443           /* Elf puts the alignment into the `value' field, and the size
2444              into the `size' field.  BFD wants to see the size in the
2445              value field, and doesn't care (at the moment) about the
2446              alignment.  */
2447           sym->symbol.value = i_sym.st_size;
2448         }
2449       else if (i_sym.st_shndx == SHN_UNDEF)
2450         {
2451           sym->symbol.section = &bfd_und_section;
2452         }
2453       else
2454         sym->symbol.section = &bfd_abs_section;
2455
2456       sym->symbol.value -= sym->symbol.section->vma;
2457
2458       switch (ELF_ST_BIND (i_sym.st_info))
2459         {
2460         case STB_LOCAL:
2461           sym->symbol.flags |= BSF_LOCAL;
2462           break;
2463         case STB_GLOBAL:
2464           sym->symbol.flags |= BSF_GLOBAL;
2465           break;
2466         case STB_WEAK:
2467           sym->symbol.flags |= BSF_WEAK;
2468           break;
2469         }
2470
2471       switch (ELF_ST_TYPE (i_sym.st_info))
2472         {
2473         case STT_SECTION:
2474           sym->symbol.flags |= BSF_SECTION_SYM | BSF_DEBUGGING;
2475           break;
2476         case STT_FILE:
2477           sym->symbol.flags |= BSF_FILE | BSF_DEBUGGING;
2478           break;
2479         case STT_FUNC:
2480           sym->symbol.flags |= BSF_FUNCTION;
2481           break;
2482         }
2483
2484       /* Is this a definition of $global$?  If so, keep it because it will be
2485          needed if any relocations are performed.  */
2486       if (!strcmp (sym->symbol.name, "$global$")
2487           && sym->symbol.section != &bfd_und_section)
2488         {
2489           /* @@ Why is this referring to backend data and not a field of
2490              abfd?  FIXME */
2491           struct elf_backend_data *be_data = (struct elf_backend_data *) abfd->xvec->backend_data;
2492
2493           be_data->global_sym = (PTR) sym;
2494         }
2495       sym++;
2496     }
2497
2498   /* We rely on the zalloc to clear out the final symbol entry.  */
2499
2500   /* obj_raw_syms macro uses a cast... */
2501   elf_tdata (abfd)->raw_syms = (PTR) x_symp;
2502
2503   bfd_get_symcount (abfd) = symcount = sym - symbase;
2504
2505   /* Fill in the user's symbol pointer vector if needed.  */
2506   if (symptrs)
2507     {
2508       sym = symbase;
2509       while (symcount-- > 0)
2510         {
2511           *symptrs++ = &sym->symbol;
2512           sym++;
2513         }
2514       *symptrs = 0;             /* Final null pointer */
2515     }
2516
2517   return true;
2518 }
2519
2520 /* Return the number of bytes required to hold the symtab vector.
2521
2522    Note that we base it on the count plus 1, since we will null terminate
2523    the vector allocated based on this size.  However, the ELF symbol table
2524    always has a dummy entry as symbol #0, so it ends up even.  */
2525
2526 unsigned int
2527 DEFUN (elf_get_symtab_upper_bound, (abfd), bfd * abfd)
2528 {
2529   unsigned int symcount;
2530   unsigned int symtab_size = 0;
2531
2532   Elf_Internal_Shdr *hdr = &elf_tdata(abfd)->symtab_hdr;
2533   symcount = hdr->sh_size / sizeof (Elf_External_Sym);
2534   symtab_size = (symcount - 1 + 1) * (sizeof (asymbol));
2535
2536   return symtab_size;
2537 }
2538
2539 /*
2540         This function return the number of bytes required to store the
2541         relocation information associated with section <<sect>>
2542         attached to bfd <<abfd>>
2543
2544 */
2545 unsigned int
2546 elf_get_reloc_upper_bound (abfd, asect)
2547      bfd *abfd;
2548      sec_ptr asect;
2549 {
2550   if (asect->flags & SEC_RELOC)
2551     {
2552       /* either rel or rela */
2553       return elf_section_data(asect)->rel_hdr.sh_size;
2554     }
2555   else
2556     return 0;
2557 }
2558
2559 static boolean
2560 DEFUN (elf_slurp_reloca_table, (abfd, asect, symbols),
2561        bfd * abfd AND
2562        sec_ptr asect AND
2563        asymbol ** symbols)
2564 {
2565   Elf_External_Rela *native_relocs;
2566   arelent *reloc_cache;
2567   arelent *cache_ptr;
2568
2569   unsigned int idx;
2570
2571   if (asect->relocation)
2572     return true;
2573   if (asect->reloc_count == 0)
2574     return true;
2575   if (asect->flags & SEC_CONSTRUCTOR)
2576     return true;
2577
2578   bfd_seek (abfd, asect->rel_filepos, SEEK_SET);
2579   native_relocs = (Elf_External_Rela *)
2580     bfd_alloc (abfd, asect->reloc_count * sizeof (Elf_External_Rela));
2581   bfd_read ((PTR) native_relocs,
2582             sizeof (Elf_External_Rela), asect->reloc_count, abfd);
2583
2584   reloc_cache = (arelent *)
2585     bfd_alloc (abfd, (size_t) (asect->reloc_count * sizeof (arelent)));
2586
2587   if (!reloc_cache)
2588     {
2589       bfd_error = no_memory;
2590       return false;
2591     }
2592
2593   for (idx = 0; idx < asect->reloc_count; idx++)
2594     {
2595       Elf_Internal_Rela dst;
2596       Elf_External_Rela *src;
2597
2598       cache_ptr = reloc_cache + idx;
2599       src = native_relocs + idx;
2600       elf_swap_reloca_in (abfd, src, &dst);
2601
2602 #ifdef RELOC_PROCESSING
2603       RELOC_PROCESSING (cache_ptr, &dst, symbols, abfd, asect);
2604 #else
2605       if (asect->flags & SEC_RELOC)
2606         {
2607           /* relocatable, so the offset is off of the section */
2608           cache_ptr->address = dst.r_offset + asect->vma;
2609         }
2610       else
2611         {
2612           /* non-relocatable, so the offset a virtual address */
2613           cache_ptr->address = dst.r_offset;
2614         }
2615       /* ELF_R_SYM(dst.r_info) is the symbol table offset; subtract 1
2616          because the first entry is NULL.  */
2617       cache_ptr->sym_ptr_ptr = symbols + ELF_R_SYM (dst.r_info) - 1;
2618       {
2619         /* Is it an ELF section symbol?  If so, translate it into a
2620            BFD section symbol.  */
2621         asymbol *s = *(cache_ptr->sym_ptr_ptr);
2622         if (s->flags & BSF_SECTION_SYM)
2623           {
2624             cache_ptr->sym_ptr_ptr = s->section->symbol_ptr_ptr;
2625             s = *cache_ptr->sym_ptr_ptr;
2626             if (s->name == 0 || s->name[0] == 0)
2627               abort ();
2628           }
2629       }
2630       cache_ptr->addend = dst.r_addend;
2631
2632       /* Fill in the cache_ptr->howto field from dst.r_type */
2633       {
2634         struct elf_backend_data *ebd = get_elf_backend_data (abfd);
2635         (*ebd->elf_info_to_howto) (abfd, cache_ptr, &dst);
2636       }
2637 #endif
2638     }
2639
2640   asect->relocation = reloc_cache;
2641   return true;
2642 }
2643
2644 #ifdef DEBUG
2645 static void
2646 elf_debug_section (str, num, hdr)
2647      char *str;
2648      int num;
2649      Elf_Internal_Shdr *hdr;
2650 {
2651   fprintf (stderr, "\nSection#%d '%s' 0x%.8lx\n", num, str, (long) hdr);
2652   fprintf (stderr,
2653            "sh_name      = %ld\tsh_type      = %ld\tsh_flags     = %ld\n",
2654            (long) hdr->sh_name,
2655            (long) hdr->sh_type,
2656            (long) hdr->sh_flags);
2657   fprintf (stderr,
2658            "sh_addr      = %ld\tsh_offset    = %ld\tsh_size      = %ld\n",
2659            (long) hdr->sh_addr,
2660            (long) hdr->sh_offset,
2661            (long) hdr->sh_size);
2662   fprintf (stderr,
2663            "sh_link      = %ld\tsh_info      = %ld\tsh_addralign = %ld\n",
2664            (long) hdr->sh_link,
2665            (long) hdr->sh_info,
2666            (long) hdr->sh_addralign);
2667   fprintf (stderr, "sh_entsize   = %ld\n",
2668            (long) hdr->sh_entsize);
2669   fprintf (stderr, "rawdata      = 0x%.8lx\n", (long) hdr->rawdata);
2670   fprintf (stderr, "contents     = 0x%.8lx\n", (long) hdr->contents);
2671   fprintf (stderr, "size         = %ld\n", (long) hdr->size);
2672   fflush (stderr);
2673 }
2674
2675 static void
2676 elf_debug_file (ehdrp)
2677      Elf_Internal_Ehdr *ehdrp;
2678 {
2679   fprintf (stderr, "e_entry      = 0x%.8lx\n", (long) ehdrp->e_entry);
2680   fprintf (stderr, "e_phoff      = %ld\n", (long) ehdrp->e_phoff);
2681   fprintf (stderr, "e_phnum      = %ld\n", (long) ehdrp->e_phnum);
2682   fprintf (stderr, "e_phentsize  = %ld\n", (long) ehdrp->e_phentsize);
2683   fprintf (stderr, "e_shoff      = %ld\n", (long) ehdrp->e_shoff);
2684   fprintf (stderr, "e_shnum      = %ld\n", (long) ehdrp->e_shnum);
2685   fprintf (stderr, "e_shentsize  = %ld\n", (long) ehdrp->e_shentsize);
2686 }
2687 #endif
2688
2689 static boolean
2690 DEFUN (elf_slurp_reloc_table, (abfd, asect, symbols),
2691        bfd * abfd AND
2692        sec_ptr asect AND
2693        asymbol ** symbols)
2694 {
2695   Elf_External_Rel *native_relocs;
2696   arelent *reloc_cache;
2697   arelent *cache_ptr;
2698   Elf_Internal_Shdr *data_hdr;
2699   ElfNAME (Off) data_off;
2700   ElfNAME (Word) data_max;
2701   char buf[4];                  /* FIXME -- might be elf64 */
2702
2703   unsigned int idx;
2704
2705   if (asect->relocation)
2706     return true;
2707   if (asect->reloc_count == 0)
2708     return true;
2709   if (asect->flags & SEC_CONSTRUCTOR)
2710     return true;
2711
2712   bfd_seek (abfd, asect->rel_filepos, SEEK_SET);
2713   native_relocs = (Elf_External_Rel *)
2714     bfd_alloc (abfd, asect->reloc_count * sizeof (Elf_External_Rel));
2715   bfd_read ((PTR) native_relocs,
2716             sizeof (Elf_External_Rel), asect->reloc_count, abfd);
2717
2718   reloc_cache = (arelent *)
2719     bfd_alloc (abfd, (size_t) (asect->reloc_count * sizeof (arelent)));
2720
2721   if (!reloc_cache)
2722     {
2723       bfd_error = no_memory;
2724       return false;
2725     }
2726
2727   /* Get the offset of the start of the segment we are relocating to read in
2728      the implicit addend.  */
2729   data_hdr = &elf_section_data(asect)->this_hdr;
2730   data_off = data_hdr->sh_offset;
2731   data_max = data_hdr->sh_size - sizeof (buf) + 1;
2732
2733 #if DEBUG & 2
2734   elf_debug_section ("data section", -1, data_hdr);
2735 #endif
2736
2737   for (idx = 0; idx < asect->reloc_count; idx++)
2738     {
2739 #ifdef RELOC_PROCESSING
2740       Elf_Internal_Rel dst;
2741       Elf_External_Rel *src;
2742
2743       cache_ptr = reloc_cache + idx;
2744       src = native_relocs + idx;
2745       elf_swap_reloc_in (abfd, src, &dst);
2746
2747       RELOC_PROCESSING (cache_ptr, &dst, symbols, abfd, asect);
2748 #else
2749       Elf_Internal_Rel dst;
2750       Elf_External_Rel *src;
2751
2752       cache_ptr = reloc_cache + idx;
2753       src = native_relocs + idx;
2754
2755       elf_swap_reloc_in (abfd, src, &dst);
2756
2757       if (asect->flags & SEC_RELOC)
2758         {
2759           /* relocatable, so the offset is off of the section */
2760           cache_ptr->address = dst.r_offset + asect->vma;
2761         }
2762       else
2763         {
2764           /* non-relocatable, so the offset a virtual address */
2765           cache_ptr->address = dst.r_offset;
2766         }
2767       /* ELF_R_SYM(dst.r_info) is the symbol table offset...
2768          -1 is to skip the dummy symbol table entry */
2769       cache_ptr->sym_ptr_ptr = symbols + ELF_R_SYM (dst.r_info) - 1;
2770       {
2771         /* Is it an ELF section symbol?  If so, translate it into a
2772            BFD section symbol.  */
2773         asymbol *s = *(cache_ptr->sym_ptr_ptr);
2774         if (s->flags & BSF_SECTION_SYM)
2775           {
2776             cache_ptr->sym_ptr_ptr = s->section->symbol_ptr_ptr;
2777             s = *cache_ptr->sym_ptr_ptr;
2778             if (s->name == 0 || s->name[0] == 0)
2779               abort ();
2780           }
2781       }
2782       BFD_ASSERT (dst.r_offset <= data_max);
2783       cache_ptr->addend = 0;
2784
2785       /* Fill in the cache_ptr->howto field from dst.r_type */
2786       {
2787         struct elf_backend_data *ebd = get_elf_backend_data (abfd);
2788         (*ebd->elf_info_to_howto_rel) (abfd, cache_ptr, &dst);
2789       }
2790 #endif
2791     }
2792
2793   asect->relocation = reloc_cache;
2794   return true;
2795 }
2796
2797 unsigned int
2798 elf_canonicalize_reloc (abfd, section, relptr, symbols)
2799      bfd *abfd;
2800      sec_ptr section;
2801      arelent **relptr;
2802      asymbol **symbols;
2803 {
2804   arelent *tblptr = section->relocation;
2805   unsigned int count = 0;
2806   int use_rela_p = get_elf_backend_data (abfd)->use_rela_p;
2807
2808   /* snarfed from coffcode.h */
2809   if (use_rela_p)
2810     elf_slurp_reloca_table (abfd, section, symbols);
2811   else
2812     elf_slurp_reloc_table (abfd, section, symbols);
2813
2814   tblptr = section->relocation;
2815   if (!tblptr)
2816     return 0;
2817
2818   for (; count++ < section->reloc_count;)
2819     *relptr++ = tblptr++;
2820
2821   *relptr = 0;
2822   return section->reloc_count;
2823 }
2824
2825 unsigned int
2826 DEFUN (elf_get_symtab, (abfd, alocation),
2827        bfd * abfd AND
2828        asymbol ** alocation)
2829 {
2830
2831   if (!elf_slurp_symbol_table (abfd, alocation))
2832     return 0;
2833   else
2834     return bfd_get_symcount (abfd);
2835 }
2836
2837 asymbol *
2838 DEFUN (elf_make_empty_symbol, (abfd),
2839        bfd * abfd)
2840 {
2841   elf_symbol_type *newsym;
2842
2843   newsym = (elf_symbol_type *) bfd_zalloc (abfd, sizeof (elf_symbol_type));
2844   if (!newsym)
2845     {
2846       bfd_error = no_memory;
2847       return NULL;
2848     }
2849   else
2850     {
2851       newsym->symbol.the_bfd = abfd;
2852       return &newsym->symbol;
2853     }
2854 }
2855
2856 void
2857 DEFUN (elf_get_symbol_info, (ignore_abfd, symbol, ret),
2858        bfd * ignore_abfd AND
2859        asymbol * symbol AND
2860        symbol_info * ret)
2861 {
2862   bfd_symbol_info (symbol, ret);
2863 }
2864
2865 void
2866 DEFUN (elf_print_symbol, (ignore_abfd, filep, symbol, how),
2867        bfd * ignore_abfd AND
2868        PTR filep AND
2869        asymbol * symbol AND
2870        bfd_print_symbol_type how)
2871 {
2872   FILE *file = (FILE *) filep;
2873   switch (how)
2874     {
2875     case bfd_print_symbol_name:
2876       fprintf (file, "%s", symbol->name);
2877       break;
2878     case bfd_print_symbol_more:
2879       fprintf (file, "elf ");
2880       fprintf_vma (file, symbol->value);
2881       fprintf (file, " %lx", (long) symbol->flags);
2882       break;
2883     case bfd_print_symbol_all:
2884       {
2885         CONST char *section_name;
2886         section_name = symbol->section ? symbol->section->name : "(*none*)";
2887         bfd_print_symbol_vandf ((PTR) file, symbol);
2888         fprintf (file, " %s\t%s",
2889                  section_name,
2890                  symbol->name);
2891       }
2892       break;
2893     }
2894
2895 }
2896
2897 alent *
2898 DEFUN (elf_get_lineno, (ignore_abfd, symbol),
2899        bfd * ignore_abfd AND
2900        asymbol * symbol)
2901 {
2902   fprintf (stderr, "elf_get_lineno unimplemented\n");
2903   fflush (stderr);
2904   BFD_FAIL ();
2905   return NULL;
2906 }
2907
2908 boolean
2909 DEFUN (elf_set_arch_mach, (abfd, arch, machine),
2910        bfd * abfd AND
2911        enum bfd_architecture arch AND
2912        unsigned long machine)
2913 {
2914   /* Allow any architecture to be supported by the elf backend */
2915   switch (arch)
2916     {
2917     case bfd_arch_unknown:      /* EM_NONE */
2918     case bfd_arch_sparc:        /* EM_SPARC */
2919     case bfd_arch_i386: /* EM_386 */
2920     case bfd_arch_m68k: /* EM_68K */
2921     case bfd_arch_m88k: /* EM_88K */
2922     case bfd_arch_i860: /* EM_860 */
2923     case bfd_arch_mips: /* EM_MIPS (MIPS R3000) */
2924     case bfd_arch_hppa: /* EM_HPPA (HP PA_RISC) */
2925       return bfd_default_set_arch_mach (abfd, arch, machine);
2926     default:
2927       return false;
2928     }
2929 }
2930
2931 boolean
2932 DEFUN (elf_find_nearest_line, (abfd,
2933                                section,
2934                                symbols,
2935                                offset,
2936                                filename_ptr,
2937                                functionname_ptr,
2938                                line_ptr),
2939        bfd * abfd AND
2940        asection * section AND
2941        asymbol ** symbols AND
2942        bfd_vma offset AND
2943        CONST char **filename_ptr AND
2944        CONST char **functionname_ptr AND
2945        unsigned int *line_ptr)
2946 {
2947   return false;
2948 }
2949
2950 int
2951 DEFUN (elf_sizeof_headers, (abfd, reloc),
2952        bfd * abfd AND
2953        boolean reloc)
2954 {
2955   fprintf (stderr, "elf_sizeof_headers unimplemented\n");
2956   fflush (stderr);
2957   BFD_FAIL ();
2958   return 0;
2959 }
2960
2961 boolean
2962 DEFUN (elf_set_section_contents, (abfd, section, location, offset, count),
2963        bfd * abfd AND
2964        sec_ptr section AND
2965        PTR location AND
2966        file_ptr offset AND
2967        bfd_size_type count)
2968 {
2969   Elf_Internal_Shdr *hdr;
2970
2971   if (abfd->output_has_begun == false)  /* set by bfd.c handler? */
2972     {
2973       /* do setup calculations (FIXME) */
2974       prep_headers (abfd);
2975       elf_compute_section_file_positions (abfd);
2976       abfd->output_has_begun = true;
2977     }
2978
2979   hdr = &elf_section_data(section)->this_hdr;
2980
2981   if (bfd_seek (abfd, hdr->sh_offset + offset, SEEK_SET) == -1)
2982     return false;
2983   if (bfd_write (location, 1, count, abfd) != count)
2984     return false;
2985
2986   return true;
2987 }
2988
2989 void
2990 DEFUN (elf_no_info_to_howto, (abfd, cache_ptr, dst),
2991        bfd * abfd AND
2992        arelent * cache_ptr AND
2993        Elf_Internal_Rela * dst)
2994 {
2995   fprintf (stderr, "elf RELA relocation support for target machine unimplemented\n");
2996   fflush (stderr);
2997   BFD_FAIL ();
2998 }
2999
3000 void
3001 DEFUN (elf_no_info_to_howto_rel, (abfd, cache_ptr, dst),
3002        bfd * abfd AND
3003        arelent * cache_ptr AND
3004        Elf_Internal_Rel * dst)
3005 {
3006   fprintf (stderr, "elf REL relocation support for target machine unimplemented\n");
3007   fflush (stderr);
3008   BFD_FAIL ();
3009 }
3010
3011 \f
3012 /* Core file support */
3013
3014 #ifdef HAVE_PROCFS              /* Some core file support requires host /proc files */
3015 #include <sys/procfs.h>
3016 #else
3017 #define bfd_prstatus(abfd, descdata, descsz, filepos)   /* Define away */
3018 #define bfd_fpregset(abfd, descdata, descsz, filepos)   /* Define away */
3019 #define bfd_prpsinfo(abfd, descdata, descsz, filepos)   /* Define away */
3020 #endif
3021
3022 #ifdef HAVE_PROCFS
3023
3024 static void
3025 DEFUN (bfd_prstatus, (abfd, descdata, descsz, filepos),
3026        bfd * abfd AND
3027        char *descdata AND
3028        int descsz AND
3029        long filepos)
3030 {
3031   asection *newsect;
3032   prstatus_t *status = (prstatus_t *) 0;
3033
3034   if (descsz == sizeof (prstatus_t))
3035     {
3036       newsect = bfd_make_section (abfd, ".reg");
3037       newsect->_raw_size = sizeof (status->pr_reg);
3038       newsect->filepos = filepos + (long) &status->pr_reg;
3039       newsect->flags = SEC_ALLOC | SEC_HAS_CONTENTS;
3040       newsect->alignment_power = 2;
3041       if ((core_prstatus (abfd) = bfd_alloc (abfd, descsz)) != NULL)
3042         {
3043           memcpy (core_prstatus (abfd), descdata, descsz);
3044         }
3045     }
3046 }
3047
3048 /* Stash a copy of the prpsinfo structure away for future use. */
3049
3050 static void
3051 DEFUN (bfd_prpsinfo, (abfd, descdata, descsz, filepos),
3052        bfd * abfd AND
3053        char *descdata AND
3054        int descsz AND
3055        long filepos)
3056 {
3057   asection *newsect;
3058
3059   if (descsz == sizeof (prpsinfo_t))
3060     {
3061       if ((core_prpsinfo (abfd) = bfd_alloc (abfd, descsz)) != NULL)
3062         {
3063           memcpy (core_prpsinfo (abfd), descdata, descsz);
3064         }
3065     }
3066 }
3067
3068 static void
3069 DEFUN (bfd_fpregset, (abfd, descdata, descsz, filepos),
3070        bfd * abfd AND
3071        char *descdata AND
3072        int descsz AND
3073        long filepos)
3074 {
3075   asection *newsect;
3076
3077   newsect = bfd_make_section (abfd, ".reg2");
3078   newsect->_raw_size = descsz;
3079   newsect->filepos = filepos;
3080   newsect->flags = SEC_ALLOC | SEC_HAS_CONTENTS;
3081   newsect->alignment_power = 2;
3082 }
3083
3084 #endif /* HAVE_PROCFS */
3085
3086 /* Return a pointer to the args (including the command name) that were
3087    seen by the program that generated the core dump.  Note that for
3088    some reason, a spurious space is tacked onto the end of the args
3089    in some (at least one anyway) implementations, so strip it off if
3090    it exists. */
3091
3092 char *
3093 DEFUN (elf_core_file_failing_command, (abfd),
3094        bfd * abfd)
3095 {
3096 #ifdef HAVE_PROCFS
3097   if (core_prpsinfo (abfd))
3098     {
3099       prpsinfo_t *p = core_prpsinfo (abfd);
3100       char *scan = p->pr_psargs;
3101       while (*scan++)
3102         {;
3103         }
3104       scan -= 2;
3105       if ((scan > p->pr_psargs) && (*scan == ' '))
3106         {
3107           *scan = '\000';
3108         }
3109       return p->pr_psargs;
3110     }
3111 #endif
3112   return NULL;
3113 }
3114
3115 /* Return the number of the signal that caused the core dump.  Presumably,
3116    since we have a core file, we got a signal of some kind, so don't bother
3117    checking the other process status fields, just return the signal number.
3118    */
3119
3120 int
3121 DEFUN (elf_core_file_failing_signal, (abfd),
3122        bfd * abfd)
3123 {
3124 #ifdef HAVE_PROCFS
3125   if (core_prstatus (abfd))
3126     {
3127       return ((prstatus_t *) (core_prstatus (abfd)))->pr_cursig;
3128     }
3129 #endif
3130   return -1;
3131 }
3132
3133 /* Check to see if the core file could reasonably be expected to have
3134    come for the current executable file.  Note that by default we return
3135    true unless we find something that indicates that there might be a
3136    problem.
3137    */
3138
3139 boolean
3140 DEFUN (elf_core_file_matches_executable_p, (core_bfd, exec_bfd),
3141        bfd * core_bfd AND
3142        bfd * exec_bfd)
3143 {
3144 #ifdef HAVE_PROCFS
3145   char *corename;
3146   char *execname;
3147 #endif
3148
3149   /* First, xvecs must match since both are ELF files for the same target. */
3150
3151   if (core_bfd->xvec != exec_bfd->xvec)
3152     {
3153       bfd_error = system_call_error;
3154       return false;
3155     }
3156
3157 #ifdef HAVE_PROCFS
3158
3159   /* If no prpsinfo, just return true.  Otherwise, grab the last component
3160      of the exec'd pathname from the prpsinfo. */
3161
3162   if (core_prpsinfo (core_bfd))
3163     {
3164       corename = (((struct prpsinfo *) core_prpsinfo (core_bfd))->pr_fname);
3165     }
3166   else
3167     {
3168       return true;
3169     }
3170
3171   /* Find the last component of the executable pathname. */
3172
3173   if ((execname = strrchr (exec_bfd->filename, '/')) != NULL)
3174     {
3175       execname++;
3176     }
3177   else
3178     {
3179       execname = (char *) exec_bfd->filename;
3180     }
3181
3182   /* See if they match */
3183
3184   return strcmp (execname, corename) ? false : true;
3185
3186 #else
3187
3188   return true;
3189
3190 #endif /* HAVE_PROCFS */
3191 }
3192
3193 /* ELF core files contain a segment of type PT_NOTE, that holds much of
3194    the information that would normally be available from the /proc interface
3195    for the process, at the time the process dumped core.  Currently this
3196    includes copies of the prstatus, prpsinfo, and fpregset structures.
3197
3198    Since these structures are potentially machine dependent in size and
3199    ordering, bfd provides two levels of support for them.  The first level,
3200    available on all machines since it does not require that the host
3201    have /proc support or the relevant include files, is to create a bfd
3202    section for each of the prstatus, prpsinfo, and fpregset structures,
3203    without any interpretation of their contents.  With just this support,
3204    the bfd client will have to interpret the structures itself.  Even with
3205    /proc support, it might want these full structures for it's own reasons.
3206
3207    In the second level of support, where HAVE_PROCFS is defined, bfd will
3208    pick apart the structures to gather some additional information that
3209    clients may want, such as the general register set, the name of the
3210    exec'ed file and its arguments, the signal (if any) that caused the
3211    core dump, etc.
3212
3213    */
3214
3215 static boolean
3216 DEFUN (elf_corefile_note, (abfd, hdr),
3217        bfd * abfd AND
3218        Elf_Internal_Phdr * hdr)
3219 {
3220   Elf_External_Note *x_note_p;  /* Elf note, external form */
3221   Elf_Internal_Note i_note;     /* Elf note, internal form */
3222   char *buf = NULL;             /* Entire note segment contents */
3223   char *namedata;               /* Name portion of the note */
3224   char *descdata;               /* Descriptor portion of the note */
3225   char *sectname;               /* Name to use for new section */
3226   long filepos;                 /* File offset to descriptor data */
3227   asection *newsect;
3228
3229   if (hdr->p_filesz > 0
3230       && (buf = (char *) bfd_xmalloc (hdr->p_filesz)) != NULL
3231       && bfd_seek (abfd, hdr->p_offset, SEEK_SET) != -1
3232       && bfd_read ((PTR) buf, hdr->p_filesz, 1, abfd) == hdr->p_filesz)
3233     {
3234       x_note_p = (Elf_External_Note *) buf;
3235       while ((char *) x_note_p < (buf + hdr->p_filesz))
3236         {
3237           i_note.namesz = bfd_h_get_32 (abfd, (bfd_byte *) x_note_p->namesz);
3238           i_note.descsz = bfd_h_get_32 (abfd, (bfd_byte *) x_note_p->descsz);
3239           i_note.type = bfd_h_get_32 (abfd, (bfd_byte *) x_note_p->type);
3240           namedata = x_note_p->name;
3241           descdata = namedata + BFD_ALIGN (i_note.namesz, 4);
3242           filepos = hdr->p_offset + (descdata - buf);
3243           switch (i_note.type)
3244             {
3245             case NT_PRSTATUS:
3246               /* process descdata as prstatus info */
3247               bfd_prstatus (abfd, descdata, i_note.descsz, filepos);
3248               sectname = ".prstatus";
3249               break;
3250             case NT_FPREGSET:
3251               /* process descdata as fpregset info */
3252               bfd_fpregset (abfd, descdata, i_note.descsz, filepos);
3253               sectname = ".fpregset";
3254               break;
3255             case NT_PRPSINFO:
3256               /* process descdata as prpsinfo */
3257               bfd_prpsinfo (abfd, descdata, i_note.descsz, filepos);
3258               sectname = ".prpsinfo";
3259               break;
3260             default:
3261               /* Unknown descriptor, just ignore it. */
3262               sectname = NULL;
3263               break;
3264             }
3265           if (sectname != NULL)
3266             {
3267               newsect = bfd_make_section (abfd, sectname);
3268               newsect->_raw_size = i_note.descsz;
3269               newsect->filepos = filepos;
3270               newsect->flags = SEC_ALLOC | SEC_HAS_CONTENTS;
3271               newsect->alignment_power = 2;
3272             }
3273           x_note_p = (Elf_External_Note *)
3274             (descdata + BFD_ALIGN (i_note.descsz, 4));
3275         }
3276     }
3277   if (buf != NULL)
3278     {
3279       free (buf);
3280     }
3281   return true;
3282
3283 }
3284
3285 /*  Core files are simply standard ELF formatted files that partition
3286     the file using the execution view of the file (program header table)
3287     rather than the linking view.  In fact, there is no section header
3288     table in a core file.
3289
3290     The process status information (including the contents of the general
3291     register set) and the floating point register set are stored in a
3292     segment of type PT_NOTE.  We handcraft a couple of extra bfd sections
3293     that allow standard bfd access to the general registers (.reg) and the
3294     floating point registers (.reg2).
3295
3296  */
3297
3298 bfd_target *
3299 DEFUN (elf_core_file_p, (abfd), bfd * abfd)
3300 {
3301   Elf_External_Ehdr x_ehdr;     /* Elf file header, external form */
3302   Elf_Internal_Ehdr *i_ehdrp;   /* Elf file header, internal form */
3303   Elf_External_Phdr x_phdr;     /* Program header table entry, external form */
3304   Elf_Internal_Phdr *i_phdrp;   /* Program header table, internal form */
3305   unsigned int phindex;
3306
3307   /* Read in the ELF header in external format.  */
3308
3309   if (bfd_read ((PTR) & x_ehdr, sizeof (x_ehdr), 1, abfd) != sizeof (x_ehdr))
3310     {
3311       bfd_error = system_call_error;
3312       return NULL;
3313     }
3314
3315   /* Now check to see if we have a valid ELF file, and one that BFD can
3316      make use of.  The magic number must match, the address size ('class')
3317      and byte-swapping must match our XVEC entry, and it must have a
3318      program header table (FIXME: See comments re segments at top of this
3319      file). */
3320
3321   if (elf_file_p (&x_ehdr) == false)
3322     {
3323     wrong:
3324       bfd_error = wrong_format;
3325       return NULL;
3326     }
3327
3328   /* FIXME, Check EI_VERSION here !  */
3329
3330   {
3331 #if ARCH_SIZE == 32
3332     int desired_address_size = ELFCLASS32;
3333 #endif
3334 #if ARCH_SIZE == 64
3335     int desired_address_size = ELFCLASS64;
3336 #endif
3337
3338     if (x_ehdr.e_ident[EI_CLASS] != desired_address_size)
3339       goto wrong;
3340   }
3341
3342   /* Switch xvec to match the specified byte order.  */
3343   switch (x_ehdr.e_ident[EI_DATA])
3344     {
3345     case ELFDATA2MSB:           /* Big-endian */
3346       if (abfd->xvec->byteorder_big_p == false)
3347         goto wrong;
3348       break;
3349     case ELFDATA2LSB:           /* Little-endian */
3350       if (abfd->xvec->byteorder_big_p == true)
3351         goto wrong;
3352       break;
3353     case ELFDATANONE:           /* No data encoding specified */
3354     default:                    /* Unknown data encoding specified */
3355       goto wrong;
3356     }
3357
3358   /* Allocate an instance of the elf_obj_tdata structure and hook it up to
3359      the tdata pointer in the bfd. */
3360
3361   elf_tdata (abfd) =
3362     (struct elf_obj_tdata *) bfd_zalloc (abfd, sizeof (struct elf_obj_tdata));
3363   if (elf_tdata (abfd) == NULL)
3364     {
3365       bfd_error = no_memory;
3366       return NULL;
3367     }
3368
3369   /* FIXME, `wrong' returns from this point onward, leak memory.  */
3370
3371   /* Now that we know the byte order, swap in the rest of the header */
3372   i_ehdrp = elf_elfheader (abfd);
3373   elf_swap_ehdr_in (abfd, &x_ehdr, i_ehdrp);
3374 #if DEBUG & 1
3375   elf_debug_file (i_ehdrp);
3376 #endif
3377
3378   /* If there is no program header, or the type is not a core file, then
3379      we are hosed. */
3380   if (i_ehdrp->e_phoff == 0 || i_ehdrp->e_type != ET_CORE)
3381     goto wrong;
3382
3383   /* Allocate space for a copy of the program header table in
3384      internal form, seek to the program header table in the file,
3385      read it in, and convert it to internal form.  As a simple sanity
3386      check, verify that the what BFD thinks is the size of each program
3387      header table entry actually matches the size recorded in the file. */
3388
3389   if (i_ehdrp->e_phentsize != sizeof (x_phdr))
3390     goto wrong;
3391   i_phdrp = (Elf_Internal_Phdr *)
3392     bfd_alloc (abfd, sizeof (*i_phdrp) * i_ehdrp->e_phnum);
3393   if (!i_phdrp)
3394     {
3395       bfd_error = no_memory;
3396       return NULL;
3397     }
3398   if (bfd_seek (abfd, i_ehdrp->e_phoff, SEEK_SET) == -1)
3399     {
3400       bfd_error = system_call_error;
3401       return NULL;
3402     }
3403   for (phindex = 0; phindex < i_ehdrp->e_phnum; phindex++)
3404     {
3405       if (bfd_read ((PTR) & x_phdr, sizeof (x_phdr), 1, abfd)
3406           != sizeof (x_phdr))
3407         {
3408           bfd_error = system_call_error;
3409           return NULL;
3410         }
3411       elf_swap_phdr_in (abfd, &x_phdr, i_phdrp + phindex);
3412     }
3413
3414   /* Once all of the program headers have been read and converted, we
3415      can start processing them. */
3416
3417   for (phindex = 0; phindex < i_ehdrp->e_phnum; phindex++)
3418     {
3419       bfd_section_from_phdr (abfd, i_phdrp + phindex, phindex);
3420       if ((i_phdrp + phindex)->p_type == PT_NOTE)
3421         {
3422           elf_corefile_note (abfd, i_phdrp + phindex);
3423         }
3424     }
3425
3426   /* Remember the entry point specified in the ELF file header. */
3427
3428   bfd_get_start_address (abfd) = i_ehdrp->e_entry;
3429
3430   return abfd->xvec;
3431 }
This page took 0.208274 seconds and 4 git commands to generate.