61bb2b265819a45531cd47a3463640fea213df29
[external/binutils.git] / bfd / elf32.c
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.
13    
14 This file is part of BFD, the Binary File Descriptor library.
15
16 This program is free software; you can redistribute it and/or modify
17 it under the terms of the GNU General Public License as published by
18 the Free Software Foundation; either version 2 of the License, or
19 (at your option) any later version.
20
21 This program is distributed in the hope that it will be useful,
22 but WITHOUT ANY WARRANTY; without even the implied warranty of
23 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24 GNU General Public License for more details.
25
26 You should have received a copy of the GNU General Public License
27 along with this program; if not, write to the Free Software
28 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
29
30
31         /****************************************
32
33                         WARNING
34
35         This is only a partial ELF implementation,
36         incorporating only those parts that are
37         required to get gdb up and running.  It is
38         expected that it will be expanded to a full
39         ELF implementation at some future date.
40
41         Unimplemented stubs call abort() to ensure
42         that they get proper attention if they are
43         ever called.  The stubs are here since
44         this version was hacked from the COFF
45         version, and thus they will probably
46         go away or get expanded appropriately in a
47         future version.
48
49         fnf@cygnus.com
50
51         *****************************************/
52
53
54 /* Problems and other issues to resolve.
55
56    (1)  BFD expects there to be some fixed number of "sections" in
57         the object file.  I.E. there is a "section_count" variable in the
58         bfd structure which contains the number of sections.  However, ELF
59         supports multiple "views" of a file.  In particular, with current
60         implementations, executable files typically have two tables, a
61         program header table and a section header table, both of which
62         partition the executable.
63
64         In ELF-speak, the "linking view" of the file uses the section header
65         table to access "sections" within the file, and the "execution view"
66         uses the program header table to access "segments" within the file.
67         "Segments" typically may contain all the data from one or more
68         "sections".
69
70         Note that the section header table is optional in ELF executables,
71         but it is this information that is most useful to gdb.  If the
72         section header table is missing, then gdb should probably try
73         to make do with the program header table.  (FIXME)
74
75 */
76
77 #include <string.h>             /* For strrchr and friends */
78 #include "bfd.h"
79 #include "sysdep.h"
80 #include "libbfd.h"
81 #include "libelf.h"
82
83 #ifdef HAVE_PROCFS      /* Some core file support requires host /proc files */
84 #include <sys/procfs.h>
85 #else
86 #define bfd_prstatus(abfd, descdata, descsz, filepos)   /* Define away */
87 #define bfd_fpregset(abfd, descdata, descsz, filepos)   /* Define away */
88 #define bfd_prpsinfo(abfd, descdata, descsz, filepos)   /* Define away */
89 #endif
90
91 /* Forward declarations of static functions */
92
93 static char *
94 elf_read PARAMS ((bfd *, long, int));
95
96 static struct sec *
97 section_from_elf_index PARAMS ((bfd *, int));
98
99 static int
100 elf_section_from_bfd_section PARAMS ((bfd *, struct sec *));
101
102 static boolean
103 elf_slurp_symbol_table PARAMS ((bfd *, asymbol **));
104
105 static char *
106 elf_get_str_section PARAMS ((bfd *, unsigned int));
107      
108 /* Forward data declarations */
109
110 extern bfd_target elf_little_vec, elf_big_vec;
111
112 /* Currently the elf_symbol_type struct just contains the generic bfd
113    symbol structure. */
114
115 typedef struct
116 {
117   asymbol symbol;
118 } elf_symbol_type;
119
120 /* Some private data is stashed away for future use using the tdata pointer
121    in the bfd structure.  */
122
123 struct elf_obj_tdata
124 {
125   Elf_Internal_Ehdr elf_header[1];      /* Actual data, but ref like ptr */
126   Elf_Internal_Shdr *elf_sect_ptr;
127   struct strtab     *strtab_ptr;
128   int               symtab_section;
129   void              *prstatus;          /* The raw /proc prstatus structure */
130   void              *prpsinfo;          /* The raw /proc prpsinfo structure */
131 };
132
133 #define elf_tdata(bfd)          ((bfd) -> tdata.elf_obj_data)
134 #define elf_elfheader(bfd)      (elf_tdata(bfd) -> elf_header)
135 #define elf_elfsections(bfd)    (elf_tdata(bfd) -> elf_sect_ptr)
136 #define elf_shstrtab(bfd)       (elf_tdata(bfd) -> strtab_ptr)
137 #define elf_onesymtab(bfd)      (elf_tdata(bfd) -> symtab_section)
138 #define core_prpsinfo(bfd)      (elf_tdata(bfd) -> prpsinfo)
139 #define core_prstatus(bfd)      (elf_tdata(bfd) -> prstatus)
140
141 /* Translate an ELF symbol in external format into an ELF symbol in internal
142    format. */
143
144 static void
145 DEFUN(elf_swap_symbol_in,(abfd, src, dst),
146       bfd               *abfd AND
147       Elf_External_Sym *src AND
148       Elf_Internal_Sym *dst)
149 {
150   dst -> st_name = bfd_h_get_32 (abfd, (bfd_byte *) src -> st_name);
151   dst -> st_value = bfd_h_get_32 (abfd, (bfd_byte *) src -> st_value);
152   dst -> st_size = bfd_h_get_32 (abfd, (bfd_byte *) src -> st_size);
153   dst -> st_info = bfd_h_get_8 (abfd, (bfd_byte *) src -> st_info);
154   dst -> st_other = bfd_h_get_8 (abfd, (bfd_byte *) src -> st_other);
155   dst -> st_shndx = bfd_h_get_16 (abfd, (bfd_byte *) src -> st_shndx);
156 }
157
158 /* Translate an ELF symbol in internal format into an ELF symbol in external
159    format. */
160
161 static void
162 DEFUN(elf_swap_symbol_out,(abfd, src, dst),
163       bfd               *abfd AND
164       Elf_Internal_Sym *src AND
165       Elf_External_Sym *dst)
166 {
167   bfd_h_put_32 (abfd, src->st_name, dst->st_name);
168   bfd_h_put_32 (abfd, src->st_value, dst->st_value);
169   bfd_h_put_32 (abfd, src->st_size, dst->st_size);
170   bfd_h_put_8  (abfd, src->st_info, dst->st_info);
171   bfd_h_put_8  (abfd, src->st_other, dst->st_other);
172   bfd_h_put_16 (abfd, src->st_shndx, dst->st_shndx);
173 }
174
175
176 /* Translate an ELF file header in external format into an ELF file header in
177    internal format. */
178
179 static void
180 DEFUN(elf_swap_ehdr_in,(abfd, src, dst),
181       bfd               *abfd AND
182       Elf_External_Ehdr *src AND
183       Elf_Internal_Ehdr *dst)
184 {
185   memcpy (dst -> e_ident, src -> e_ident, EI_NIDENT);
186   dst -> e_type = bfd_h_get_16 (abfd, (bfd_byte *) src -> e_type);
187   dst -> e_machine = bfd_h_get_16 (abfd, (bfd_byte *) src -> e_machine);
188   dst -> e_version = bfd_h_get_32 (abfd, (bfd_byte *) src -> e_version);
189   dst -> e_entry = bfd_h_get_32 (abfd, (bfd_byte *) src -> e_entry);
190   dst -> e_phoff = bfd_h_get_32 (abfd, (bfd_byte *) src -> e_phoff);
191   dst -> e_shoff = bfd_h_get_32 (abfd, (bfd_byte *) src -> e_shoff);
192   dst -> e_flags = bfd_h_get_32 (abfd, (bfd_byte *) src -> e_flags);
193   dst -> e_ehsize = bfd_h_get_16 (abfd, (bfd_byte *) src -> e_ehsize);
194   dst -> e_phentsize = bfd_h_get_16 (abfd, (bfd_byte *) src -> e_phentsize);
195   dst -> e_phnum = bfd_h_get_16 (abfd, (bfd_byte *) src -> e_phnum);
196   dst -> e_shentsize = bfd_h_get_16 (abfd, (bfd_byte *) src -> e_shentsize);
197   dst -> e_shnum = bfd_h_get_16 (abfd, (bfd_byte *) src -> e_shnum);
198   dst -> e_shstrndx = bfd_h_get_16 (abfd, (bfd_byte *) src -> e_shstrndx);
199 }
200
201 /* Translate an ELF file header in internal format into an ELF file header in
202    external format. */
203
204 static void
205 DEFUN(elf_swap_ehdr_out,(abfd, src, dst),
206       bfd               *abfd AND
207       Elf_Internal_Ehdr *src AND
208       Elf_External_Ehdr *dst)
209 {
210   memcpy (dst -> e_ident, src -> e_ident, EI_NIDENT);
211   /* note that all elements of dst are *arrays of unsigned char* already... */
212   bfd_h_put_16 (abfd, src->e_type, dst->e_type);
213   bfd_h_put_16 (abfd, src->e_machine, dst->e_machine);
214   bfd_h_put_32 (abfd, src->e_version, dst->e_version);
215   bfd_h_put_32 (abfd, src->e_entry, dst->e_entry);
216   bfd_h_put_32 (abfd, src->e_phoff, dst->e_phoff);
217   bfd_h_put_32 (abfd, src->e_shoff, dst->e_shoff);
218   bfd_h_put_32 (abfd, src->e_flags, dst->e_flags);
219   bfd_h_put_16 (abfd, src->e_ehsize, dst->e_ehsize);
220   bfd_h_put_16 (abfd, src->e_phentsize, dst->e_phentsize);
221   bfd_h_put_16 (abfd, src->e_phnum, dst->e_phnum);
222   bfd_h_put_16 (abfd, src->e_shentsize, dst->e_shentsize);
223   bfd_h_put_16 (abfd, src->e_shnum, dst->e_shnum);
224   bfd_h_put_16 (abfd, src->e_shstrndx, dst->e_shstrndx);
225 }
226
227
228 /* Translate an ELF section header table entry in external format into an
229    ELF section header table entry in internal format. */
230
231 static void
232 DEFUN(elf_swap_shdr_in,(abfd, src, dst),
233       bfd               *abfd AND
234       Elf_External_Shdr *src AND
235       Elf_Internal_Shdr *dst)
236 {
237   dst->sh_name = bfd_h_get_32 (abfd, (bfd_byte *) src->sh_name);
238   dst->sh_type = bfd_h_get_32 (abfd, (bfd_byte *) src->sh_type);
239   dst->sh_flags = bfd_h_get_32 (abfd, (bfd_byte *) src->sh_flags);
240   dst->sh_addr = bfd_h_get_32 (abfd, (bfd_byte *) src->sh_addr);
241   dst->sh_offset = bfd_h_get_32 (abfd, (bfd_byte *) src->sh_offset);
242   dst->sh_size = bfd_h_get_32 (abfd, (bfd_byte *) src->sh_size);
243   dst->sh_link = bfd_h_get_32 (abfd, (bfd_byte *) src->sh_link);
244   dst->sh_info = bfd_h_get_32 (abfd, (bfd_byte *) src->sh_info);
245   dst->sh_addralign = bfd_h_get_32 (abfd, (bfd_byte *) src->sh_addralign);
246   dst->sh_entsize = bfd_h_get_32 (abfd, (bfd_byte *) src->sh_entsize);
247   /* we haven't done any processing on it yet, so... */
248   dst->rawdata = (void*)0;
249 }
250
251 /* Translate an ELF section header table entry in internal format into an
252    ELF section header table entry in external format. */
253
254 static void
255 DEFUN(elf_swap_shdr_out,(abfd, src, dst),
256       bfd               *abfd AND
257       Elf_Internal_Shdr *src AND
258       Elf_External_Shdr *dst)
259 {
260   /* note that all elements of dst are *arrays of unsigned char* already... */
261   bfd_h_put_32 (abfd, src->sh_name, dst->sh_name);
262   bfd_h_put_32 (abfd, src->sh_type, dst->sh_type);
263   bfd_h_put_32 (abfd, src->sh_flags, dst->sh_flags);
264   bfd_h_put_32 (abfd, src->sh_addr, dst->sh_addr);
265   bfd_h_put_32 (abfd, src->sh_offset, dst->sh_offset);
266   bfd_h_put_32 (abfd, src->sh_size, dst->sh_size);
267   bfd_h_put_32 (abfd, src->sh_link, dst->sh_link);
268   bfd_h_put_32 (abfd, src->sh_info, dst->sh_info);
269   bfd_h_put_32 (abfd, src->sh_addralign, dst->sh_addralign);
270   bfd_h_put_32 (abfd, src->sh_entsize, dst->sh_entsize);
271 }
272
273
274 /* Translate an ELF program header table entry in external format into an
275    ELF program header table entry in internal format. */
276
277 static void
278 DEFUN(elf_swap_phdr_in,(abfd, src, dst),
279       bfd               *abfd AND
280       Elf_External_Phdr *src AND
281       Elf_Internal_Phdr *dst)
282 {
283   dst->p_type = bfd_h_get_32 (abfd, (bfd_byte *) src->p_type);
284   dst->p_offset = bfd_h_get_32 (abfd, (bfd_byte *) src->p_offset);
285   dst->p_vaddr = bfd_h_get_32 (abfd, (bfd_byte *) src->p_vaddr);
286   dst->p_paddr = bfd_h_get_32 (abfd, (bfd_byte *) src->p_paddr);
287   dst->p_filesz = bfd_h_get_32 (abfd, (bfd_byte *) src->p_filesz);
288   dst->p_memsz = bfd_h_get_32 (abfd, (bfd_byte *) src->p_memsz);
289   dst->p_flags = bfd_h_get_32 (abfd, (bfd_byte *) src->p_flags);
290   dst->p_align = bfd_h_get_32 (abfd, (bfd_byte *) src->p_align);
291 }
292
293
294 /* Translate an ELF reloc from external format to internal format. */
295 static void
296 DEFUN(elf_swap_reloc_in,(abfd, src, dst),
297       bfd            *abfd AND
298       Elf_External_Rel *src AND
299       Elf_Internal_Rel *dst)
300 {
301   dst->r_offset = bfd_h_get_32 (abfd, (bfd_byte *) src->r_offset);
302   dst->r_info = bfd_h_get_32 (abfd, (bfd_byte *) src->r_info);
303 }
304
305 static void
306 DEFUN(elf_swap_reloca_in,(abfd, src, dst),
307       bfd            *abfd AND
308       Elf_External_Rela *src AND
309       Elf_Internal_Rela *dst)
310 {
311   dst->r_offset = bfd_h_get_32 (abfd, (bfd_byte *) src->r_offset);
312   dst->r_info = bfd_h_get_32 (abfd, (bfd_byte *) src->r_info);
313   dst->r_addend = bfd_h_get_32 (abfd, (bfd_byte *) src->r_addend);
314 }
315
316 /* Translate an ELF reloc from internal format to external format. */
317 static void
318 DEFUN(elf_swap_reloc_out,(abfd, src, dst),
319       bfd            *abfd AND
320       Elf_Internal_Rel *src AND
321       Elf_External_Rel *dst)
322 {
323   bfd_h_put_32 (abfd, src->r_offset, dst->r_offset);
324   bfd_h_put_32 (abfd, src->r_info, dst->r_info);
325 }
326
327 static void
328 DEFUN(elf_swap_reloca_out,(abfd, src, dst),
329       bfd            *abfd AND
330       Elf_Internal_Rela *src AND
331       Elf_External_Rela *dst)
332 {
333   bfd_h_put_32 (abfd, src->r_offset, dst->r_offset);
334   bfd_h_put_32 (abfd, src->r_info, dst->r_info);
335   bfd_h_put_32 (abfd, src->r_addend, dst->r_addend);
336 }
337
338 /* 
339 INTERNAL_FUNCTION
340         bfd_elf_find_section
341
342 SYNOPSIS
343         struct elf_internal_shdr *bfd_elf_find_section (bfd *abfd, char *name);
344
345 DESCRIPTION
346         Helper functions for GDB to locate the string tables.
347         Since BFD hides string tables from callers, GDB needs to use an
348         internal hook to find them.  Sun's .stabstr, in particular,
349         isn't even pointed to by the .stab section, so ordinary
350         mechanisms wouldn't work to find it, even if we had some.
351 */
352
353 struct elf_internal_shdr *
354 DEFUN(bfd_elf_find_section, (abfd, name),
355       bfd               *abfd AND
356       char              *name)
357 {
358   Elf_Internal_Shdr *i_shdrp;
359   Elf_Internal_Shdr *gotit = NULL;
360   char *shstrtab;
361   unsigned int max;
362   unsigned int i;
363
364   i_shdrp = elf_elfsections (abfd);
365   if (i_shdrp != NULL)
366     {
367       shstrtab = elf_get_str_section (abfd, elf_elfheader (abfd)->e_shstrndx);
368       if (shstrtab != NULL)
369         {
370           max = elf_elfheader (abfd)->e_shnum;
371           for (i = 1; i < max; i++)
372             {
373               if (!strcmp (&shstrtab[i_shdrp[i].sh_name], name))
374                 {
375                   gotit = &i_shdrp[i];
376                 }
377             }
378         }
379     }
380   return (gotit);
381 }
382
383 /* End of GDB support.  */
384
385 static char *
386 DEFUN(elf_get_str_section, (abfd, shindex),
387       bfd               *abfd AND
388       unsigned int      shindex)
389 {
390   Elf_Internal_Shdr *i_shdrp;
391   char *shstrtab = NULL;
392   unsigned int offset;
393   unsigned int shstrtabsize;
394
395   i_shdrp = elf_elfsections (abfd);
396   if (i_shdrp != NULL)
397     {
398       shstrtab = i_shdrp[shindex].rawdata;
399       if (shstrtab == NULL)
400         {
401           /* No cached one, attempt to read, and cache what we read. */
402           offset = i_shdrp[shindex].sh_offset;
403           shstrtabsize = i_shdrp[shindex].sh_size;
404           shstrtab = elf_read (abfd, offset, shstrtabsize);
405           i_shdrp[shindex].rawdata = (void*) shstrtab;
406         }
407     }
408   return (shstrtab);
409 }
410
411 static char *
412 DEFUN(elf_string_from_elf_section, (abfd, shindex, strindex),
413       bfd               *abfd AND
414       unsigned int      shindex AND
415       unsigned int      strindex)
416 {
417   Elf_Internal_Shdr *i_shdrp = elf_elfsections (abfd);
418   Elf_Internal_Shdr *hdr = i_shdrp + shindex;
419
420   if (! hdr->rawdata)
421     {
422       if (elf_get_str_section (abfd, shindex) == NULL)
423         {
424           return NULL;
425         }
426     }
427   return ((char*)hdr->rawdata)+strindex;
428 }
429
430 #define elf_string_from_elf_strtab(abfd, strindex) \
431   elf_string_from_elf_section (abfd, elf_elfheader(abfd)->e_shstrndx, strindex)
432
433 /* Create a new bfd section from an ELF section header. */
434
435 static boolean
436 DEFUN(bfd_section_from_shdr, (abfd, shindex),
437       bfd               *abfd AND
438       unsigned int      shindex)
439 {
440   Elf_Internal_Shdr *i_shdrp = elf_elfsections (abfd);
441   Elf_Internal_Shdr *hdr = i_shdrp + shindex;
442   asection *newsect;
443   char *name;
444
445   name = hdr->sh_name ?
446     elf_string_from_elf_strtab (abfd, hdr->sh_name) : "unnamed";
447
448   switch(hdr->sh_type) {
449
450   case SHT_NULL:
451     /* inactive section. Throw it away. */
452     return true;
453
454   case SHT_PROGBITS:
455   case SHT_NOBITS:
456     /* Bits that get saved. This one is real. */
457     if (! hdr->rawdata ) 
458       {
459         newsect = bfd_make_section (abfd, name);
460         if (newsect != NULL)
461           {
462             newsect->vma = hdr->sh_addr;
463             newsect->_raw_size = hdr->sh_size;
464             newsect->filepos = hdr->sh_offset; /* so we can read back the bits */
465             newsect->flags |= SEC_HAS_CONTENTS;
466             
467             if (hdr->sh_flags & SHF_ALLOC)
468               {
469                 newsect->flags |= SEC_ALLOC;
470                 if (hdr->sh_type != SHT_NOBITS)
471                   newsect->flags |= SEC_LOAD;
472               }
473             
474             if (!(hdr->sh_flags & SHF_WRITE))
475               newsect->flags |= SEC_READONLY;
476             
477             if (hdr->sh_flags & SHF_EXECINSTR)
478               newsect->flags |= SEC_CODE;       /* FIXME: may only contain SOME code */
479             else
480               newsect->flags |= SEC_DATA;
481             
482             hdr->rawdata = (void*)newsect;
483           }
484       }
485     return true;
486     break;
487
488   case SHT_SYMTAB:                      /* A symbol table */
489     BFD_ASSERT (hdr->sh_entsize == sizeof (Elf_External_Sym));
490     elf_onesymtab (abfd) = shindex;
491     abfd->flags |= HAS_SYMS;
492     return true;
493
494   case SHT_STRTAB:                      /* A string table */
495     return true;
496
497   case SHT_REL:
498   case SHT_RELA:
499     /* *these* do a lot of work -- but build no sections! */
500     /* the spec says there can be multiple strtabs, but only one symtab */
501     /* but there can be lots of REL* sections. */
502     /* FIXME:  The above statement is wrong!  There are typically at least
503        two symbol tables in a dynamically linked executable, ".dynsym"
504        which is the dynamic linkage symbol table and ".symtab", which is
505        the "traditional" symbol table.  -fnf */
506        
507     {
508       asection          *target_sect;
509       
510       bfd_section_from_shdr (abfd, hdr->sh_link); /* symbol table */
511       bfd_section_from_shdr (abfd, hdr->sh_info); /* target */
512       target_sect = section_from_elf_index (abfd, hdr->sh_info);
513       if (target_sect == NULL)
514           return false;
515
516 #if 0
517       /* FIXME:  We are only prepared to read one symbol table, so
518          do NOT read the dynamic symbol table since it is only a
519          subset of the full symbol table.  Also see comment above. -fnf */
520       if (!elf_slurp_symbol_table(abfd, i_shdrp + hdr->sh_link))
521         return false;
522 #endif
523
524       target_sect->reloc_count = hdr->sh_size / hdr->sh_entsize;
525       target_sect->flags |= SEC_RELOC;
526       target_sect->relocation = 0;
527       target_sect->rel_filepos = hdr->sh_offset;
528       return true;
529     }
530     break;
531
532   case SHT_HASH:
533   case SHT_DYNAMIC:
534   case SHT_DYNSYM:              /* could treat this like symtab... */
535 #if 0
536     fprintf(stderr, "Dynamic Linking sections not yet supported.\n");
537     abort ();
538 #endif
539     break;
540
541   case SHT_NOTE:
542 #if 0
543     fprintf(stderr, "Note Sections not yet supported.\n");
544     abort ();
545 #endif
546     break;
547
548   case SHT_SHLIB:
549 #if 0
550     fprintf(stderr, "SHLIB Sections not supported (and non conforming.)\n");
551 #endif
552     return true;
553
554   default:
555     break;
556   }
557   
558   return (true);
559 }
560
561
562
563
564 struct strtab {
565   char *tab;
566   int nentries;
567   int length;
568 };
569
570
571 static struct strtab *
572 DEFUN(bfd_new_strtab, (abfd),
573       bfd               *abfd)
574 {
575   struct strtab *ss;
576
577   ss = (struct strtab *) bfd_xmalloc(sizeof(struct strtab));
578   ss->tab = bfd_xmalloc(1);
579   BFD_ASSERT(ss->tab != 0);
580   *ss->tab = 0;
581   ss->nentries = 0;
582   ss->length = 1;
583
584   return ss;
585 }
586
587 static int
588 DEFUN(bfd_add_to_strtab, (abfd, ss, str),
589       bfd               *abfd AND
590       struct strtab     *ss AND
591       CONST char        *str)
592 {
593   /* should search first, but for now: */
594   /* include the trailing NUL */
595   int ln = strlen(str)+1;
596   
597   /* should this be using obstacks? */
598   ss->tab = realloc(ss->tab, ss->length + ln);
599
600   BFD_ASSERT(ss->tab != 0);
601   strcpy(ss->tab + ss->length, str);
602   ss->nentries++;
603   ss->length += ln;
604
605   return ss->length - ln;
606 }
607
608 static int
609 DEFUN(bfd_add_2_to_strtab, (abfd, ss, str, str2),
610       bfd               *abfd AND
611       struct strtab     *ss AND
612       char              *str AND
613       CONST char        *str2)
614 {
615   /* should search first, but for now: */
616   /* include the trailing NUL */
617   int ln = strlen(str)+strlen(str2)+1;
618   
619   /* should this be using obstacks? */
620   if (ss->length)
621     ss->tab = realloc(ss->tab, ss->length + ln);
622   else 
623     ss->tab = bfd_xmalloc(ln);
624
625   BFD_ASSERT(ss->tab != 0);
626   strcpy(ss->tab + ss->length, str);
627   strcpy(ss->tab + ss->length + strlen(str), str2);
628   ss->nentries++;
629   ss->length += ln;
630
631   return ss->length - ln;
632 }
633
634 /* Create a new ELF section from a bfd section. */
635
636 static boolean
637 DEFUN(bfd_shdr_from_section, (abfd, hdr, shstrtab, indx),
638       bfd               *abfd AND
639       Elf_Internal_Shdr *hdr AND
640       struct strtab     *shstrtab AND
641       int               indx)
642 {
643   asection *sect;
644   int ndx;
645   
646   /* figure out out to write the section name from the bfd section name. MWE */
647               
648   sect = abfd->sections;
649   for (ndx = indx; --ndx; )
650     {
651       sect = sect->next;
652     }
653   hdr[indx].sh_name = bfd_add_to_strtab(abfd, shstrtab,
654                                         bfd_section_name(abfd, sect));
655   hdr[indx].sh_addr = sect->vma;
656   hdr[indx].sh_size = sect->_raw_size;
657   hdr[indx].sh_flags = 0;
658   /* these need to be preserved on */
659   hdr[indx].sh_link = 0;
660   hdr[indx].sh_info = 0;
661   hdr[indx].sh_addralign = 0;
662   hdr[indx].sh_entsize = 0;
663
664   hdr[indx].sh_type = 0;
665   if (sect->flags & SEC_RELOC) {
666     hdr[indx].sh_type = SHT_RELA; /* FIXME -- sparc specific */
667   }
668   
669   if (sect->flags & SEC_HAS_CONTENTS)
670     {
671       hdr[indx].sh_offset = sect->filepos;
672       hdr[indx].sh_size = sect->_raw_size;
673     }
674   if (sect->flags & SEC_ALLOC)
675     {
676       hdr[indx].sh_flags |= SHF_ALLOC;
677       if (sect->flags & SEC_LOAD)
678         {
679           /* do something with sh_type ? */
680         }
681     }
682   if (!(sect->flags & SEC_READONLY)) 
683     hdr[indx].sh_flags |= SHF_WRITE;
684
685   if (sect->flags & SEC_CODE)
686     hdr[indx].sh_flags |= SHF_EXECINSTR;
687
688   return (true);
689 }
690
691 /* Create a new bfd section from an ELF program header.
692
693    Since program segments have no names, we generate a synthetic name
694    of the form segment<NUM>, where NUM is generally the index in the
695    program header table.  For segments that are split (see below) we
696    generate the names segment<NUM>a and segment<NUM>b.
697
698    Note that some program segments may have a file size that is different than
699    (less than) the memory size.  All this means is that at execution the
700    system must allocate the amount of memory specified by the memory size,
701    but only initialize it with the first "file size" bytes read from the
702    file.  This would occur for example, with program segments consisting
703    of combined data+bss.
704
705    To handle the above situation, this routine generates TWO bfd sections
706    for the single program segment.  The first has the length specified by
707    the file size of the segment, and the second has the length specified
708    by the difference between the two sizes.  In effect, the segment is split
709    into it's initialized and uninitialized parts.
710
711  */
712
713 static boolean
714 DEFUN(bfd_section_from_phdr, (abfd, hdr, index),
715       bfd               *abfd AND
716       Elf_Internal_Phdr *hdr AND
717       int                index)
718 {
719   asection *newsect;
720   char *name;
721   char namebuf[64];
722   int split;
723
724   split = ((hdr -> p_memsz > 0) &&
725            (hdr -> p_filesz > 0) &&
726            (hdr -> p_memsz > hdr -> p_filesz));
727   sprintf (namebuf, split ? "segment%da" : "segment%d", index);
728   name = bfd_alloc (abfd, strlen (namebuf) + 1);
729   strcpy (name, namebuf);
730   newsect = bfd_make_section (abfd, name);
731   newsect -> vma = hdr -> p_vaddr;
732   newsect -> _raw_size = hdr -> p_filesz;
733   newsect -> filepos = hdr -> p_offset;
734   newsect -> flags |= SEC_HAS_CONTENTS;
735   if (hdr -> p_type == PT_LOAD)
736     {
737       newsect -> flags |= SEC_ALLOC;
738       newsect -> flags |= SEC_LOAD;
739       if (hdr -> p_flags & PF_X)
740         {
741           /* FIXME: all we known is that it has execute PERMISSION,
742              may be data. */
743           newsect -> flags |= SEC_CODE;
744         }
745     }
746   if (!(hdr -> p_flags & PF_W))
747     {
748       newsect -> flags |= SEC_READONLY;
749     }
750
751   if (split)
752     {
753       sprintf (namebuf, "segment%db", index);
754       name = bfd_alloc (abfd, strlen (namebuf) + 1);
755       strcpy (name, namebuf);
756       newsect = bfd_make_section (abfd, name);
757       newsect -> vma = hdr -> p_vaddr + hdr -> p_filesz;
758       newsect -> _raw_size = hdr -> p_memsz - hdr -> p_filesz;
759       if (hdr -> p_type == PT_LOAD)
760         {
761           newsect -> flags |= SEC_ALLOC;
762           if (hdr -> p_flags & PF_X)
763             newsect -> flags |= SEC_CODE;
764         }
765       if (!(hdr -> p_flags & PF_W))
766         newsect -> flags |= SEC_READONLY;
767     }
768
769   return (true);
770 }
771
772 #ifdef HAVE_PROCFS
773
774 static void
775 DEFUN(bfd_prstatus,(abfd, descdata, descsz, filepos),
776       bfd       *abfd AND
777       char      *descdata AND
778       int        descsz AND
779       long       filepos)
780 {
781   asection *newsect;
782   prstatus_t *status = (prstatus_t *)0;
783
784   if (descsz == sizeof (prstatus_t))
785     {
786       newsect = bfd_make_section (abfd, ".reg");
787       newsect -> _raw_size = sizeof (status->pr_reg);
788       newsect -> filepos = filepos + (long) &status->pr_reg;
789       newsect -> flags = SEC_ALLOC | SEC_HAS_CONTENTS;
790       newsect -> alignment_power = 2;
791       if ((core_prstatus (abfd) = bfd_alloc (abfd, descsz)) != NULL)
792         {
793           memcpy (core_prstatus (abfd), descdata, descsz);
794         }
795     }
796 }
797
798 /* Stash a copy of the prpsinfo structure away for future use. */
799
800 static void
801 DEFUN(bfd_prpsinfo,(abfd, descdata, descsz, filepos),
802       bfd       *abfd AND
803       char      *descdata AND
804       int        descsz AND
805       long       filepos)
806 {
807   asection *newsect;
808
809   if (descsz == sizeof (prpsinfo_t))
810     {
811       if ((core_prpsinfo (abfd) = bfd_alloc (abfd, descsz)) != NULL)
812         {
813           memcpy (core_prpsinfo (abfd), descdata, descsz);
814         }
815     }
816 }
817
818 static void
819 DEFUN(bfd_fpregset,(abfd, descdata, descsz, filepos),
820       bfd       *abfd AND
821       char      *descdata AND
822       int        descsz AND
823       long       filepos)
824 {
825   asection *newsect;
826
827   newsect = bfd_make_section (abfd, ".reg2");
828   newsect -> _raw_size = descsz;
829   newsect -> filepos = filepos;
830   newsect -> flags = SEC_ALLOC | SEC_HAS_CONTENTS;
831   newsect -> alignment_power = 2;
832 }
833
834 #endif  /* HAVE_PROCFS */
835
836 /* Return a pointer to the args (including the command name) that were
837    seen by the program that generated the core dump.  Note that for
838    some reason, a spurious space is tacked onto the end of the args
839    in some (at least one anyway) implementations, so strip it off if
840    it exists. */
841
842 char *
843 DEFUN(elf_core_file_failing_command, (abfd),
844      bfd *abfd)
845 {
846 #ifdef HAVE_PROCFS
847   if (core_prpsinfo (abfd))
848     {
849       prpsinfo_t *p = core_prpsinfo (abfd);
850       char *scan = p -> pr_psargs;
851       while (*scan++) {;}
852       scan -= 2;
853       if ((scan > p -> pr_psargs) && (*scan == ' '))
854         {
855           *scan = '\000';
856         }
857       return (p -> pr_psargs);
858     }
859 #endif
860   return (NULL);
861 }
862
863 /* Return the number of the signal that caused the core dump.  Presumably,
864    since we have a core file, we got a signal of some kind, so don't bother
865    checking the other process status fields, just return the signal number.
866    */
867
868 int
869 DEFUN(elf_core_file_failing_signal, (abfd),
870       bfd *abfd)
871 {
872 #ifdef HAVE_PROCFS
873   if (core_prstatus (abfd))
874     {
875       return (((prstatus_t *)(core_prstatus (abfd))) -> pr_cursig);
876     }
877 #endif
878   return (-1);
879 }
880
881 /* Check to see if the core file could reasonably be expected to have
882    come for the current executable file.  Note that by default we return
883    true unless we find something that indicates that there might be a
884    problem.
885    */
886
887 boolean
888 DEFUN(elf_core_file_matches_executable_p, (core_bfd, exec_bfd),
889       bfd *core_bfd AND
890       bfd *exec_bfd)
891 {
892 #ifdef HAVE_PROCFS
893   char *corename;
894   char *execname;
895 #endif
896
897   /* First, xvecs must match since both are ELF files for the same target. */
898
899   if (core_bfd->xvec != exec_bfd->xvec)
900     {
901       bfd_error = system_call_error;
902       return (false);
903     }
904
905 #ifdef HAVE_PROCFS
906
907   /* If no prpsinfo, just return true.  Otherwise, grab the last component
908      of the exec'd pathname from the prpsinfo. */
909
910   if (core_prpsinfo (core_bfd))
911     {
912       corename = (((struct prpsinfo *) core_prpsinfo (core_bfd)) -> pr_fname);
913     }  
914   else
915     {
916       return (true);
917     }
918
919   /* Find the last component of the executable pathname. */
920
921   if ((execname = strrchr (exec_bfd -> filename, '/')) != NULL)
922     {
923       execname++;
924     }
925   else
926     {
927       execname = (char *) exec_bfd -> filename;
928     }
929
930   /* See if they match */
931
932   return (strcmp (execname, corename) ? false : true);
933
934 #else
935
936   return (true);
937
938 #endif  /* HAVE_PROCFS */
939 }
940
941 /* ELF core files contain a segment of type PT_NOTE, that holds much of
942    the information that would normally be available from the /proc interface
943    for the process, at the time the process dumped core.  Currently this
944    includes copies of the prstatus, prpsinfo, and fpregset structures.
945
946    Since these structures are potentially machine dependent in size and
947    ordering, bfd provides two levels of support for them.  The first level,
948    available on all machines since it does not require that the host
949    have /proc support or the relevant include files, is to create a bfd
950    section for each of the prstatus, prpsinfo, and fpregset structures,
951    without any interpretation of their contents.  With just this support,
952    the bfd client will have to interpret the structures itself.  Even with
953    /proc support, it might want these full structures for it's own reasons.
954
955    In the second level of support, where HAVE_PROCFS is defined, bfd will
956    pick apart the structures to gather some additional information that
957    clients may want, such as the general register set, the name of the
958    exec'ed file and its arguments, the signal (if any) that caused the
959    core dump, etc.
960
961    */
962
963 static boolean
964 DEFUN(elf_corefile_note, (abfd, hdr),
965       bfd               *abfd AND
966       Elf_Internal_Phdr *hdr)
967 {
968   Elf_External_Note *x_note_p;  /* Elf note, external form */
969   Elf_Internal_Note i_note;     /* Elf note, internal form */
970   char *buf = NULL;             /* Entire note segment contents */
971   char *namedata;               /* Name portion of the note */
972   char *descdata;               /* Descriptor portion of the note */
973   char *sectname;               /* Name to use for new section */
974   long filepos;                 /* File offset to descriptor data */
975   asection *newsect;
976
977   if (hdr -> p_filesz > 0
978       && (buf = (char *) bfd_xmalloc (hdr -> p_filesz)) != NULL
979       && bfd_seek (abfd, hdr -> p_offset, SEEK_SET) != -1
980       && bfd_read ((PTR) buf, hdr -> p_filesz, 1, abfd) == hdr -> p_filesz)
981     {
982       x_note_p = (Elf_External_Note *) buf;
983       while ((char *) x_note_p < (buf + hdr -> p_filesz))
984         {
985           i_note.namesz = bfd_h_get_32 (abfd, (bfd_byte *) x_note_p -> namesz);
986           i_note.descsz = bfd_h_get_32 (abfd, (bfd_byte *) x_note_p -> descsz);
987           i_note.type = bfd_h_get_32 (abfd, (bfd_byte *) x_note_p -> type);
988           namedata = x_note_p -> name;
989           descdata = namedata + BFD_ALIGN (i_note.namesz, 4);
990           filepos = hdr -> p_offset + (descdata - buf);
991           switch (i_note.type) {
992             case NT_PRSTATUS:
993               /* process descdata as prstatus info */
994               bfd_prstatus (abfd, descdata, i_note.descsz, filepos);
995               sectname = ".prstatus";
996               break;
997             case NT_FPREGSET:
998               /* process descdata as fpregset info */
999               bfd_fpregset (abfd, descdata, i_note.descsz, filepos);
1000               sectname = ".fpregset";
1001               break;
1002             case NT_PRPSINFO:
1003               /* process descdata as prpsinfo */
1004               bfd_prpsinfo (abfd, descdata, i_note.descsz, filepos);
1005               sectname = ".prpsinfo";
1006               break;
1007             default:
1008               /* Unknown descriptor, just ignore it. */
1009               sectname = NULL;
1010               break;
1011           }
1012           if (sectname != NULL)
1013             {
1014               newsect = bfd_make_section (abfd, sectname);
1015               newsect -> _raw_size = i_note.descsz;
1016               newsect -> filepos = filepos;
1017               newsect -> flags = SEC_ALLOC | SEC_HAS_CONTENTS;
1018               newsect -> alignment_power = 2;
1019             }
1020           x_note_p = (Elf_External_Note *)
1021                         (descdata + BFD_ALIGN (i_note.descsz, 4));
1022         }
1023     }
1024   if (buf != NULL)
1025     {
1026       free (buf);
1027     }
1028   return true;
1029   
1030 }
1031
1032
1033 /* Read a specified number of bytes at a specified offset in an ELF
1034    file, into a newly allocated buffer, and return a pointer to the 
1035    buffer. */
1036
1037 static char *
1038 DEFUN(elf_read, (abfd, offset, size),
1039       bfd       *abfd AND
1040       long      offset AND
1041       int       size)
1042 {
1043   char *buf;
1044
1045   if ((buf = bfd_alloc (abfd, size)) == NULL)
1046     {
1047       bfd_error = no_memory;
1048       return (NULL);
1049     }
1050   if (bfd_seek (abfd, offset, SEEK_SET) == -1)
1051     {
1052       bfd_error = system_call_error;
1053       return (NULL);
1054     }
1055   if (bfd_read ((PTR) buf, size, 1, abfd) != size)
1056     {
1057       bfd_error = system_call_error;
1058       return (NULL);
1059     }
1060   return (buf);
1061 }
1062
1063 /* Begin processing a given object.
1064
1065    First we validate the file by reading in the ELF header and checking
1066    the magic number.
1067
1068    */
1069
1070 bfd_target *
1071 DEFUN (elf_object_p, (abfd), bfd *abfd)
1072 {
1073   Elf_External_Ehdr x_ehdr;     /* Elf file header, external form */
1074   Elf_Internal_Ehdr *i_ehdrp;   /* Elf file header, internal form */
1075   Elf_External_Shdr x_shdr;     /* Section header table entry, external form */
1076   Elf_Internal_Shdr *i_shdrp;   /* Section header table, internal form */
1077   int shindex;
1078   char *shstrtab;               /* Internal copy of section header stringtab */
1079   struct elf_backend_data *ebd; /* Use to get ELF_ARCH stored in xvec */
1080   
1081   /* Read in the ELF header in external format.  */
1082
1083   if (bfd_read ((PTR) &x_ehdr, sizeof (x_ehdr), 1, abfd) != sizeof (x_ehdr))
1084     {
1085       bfd_error = system_call_error;
1086       return (NULL);
1087     }
1088
1089   /* Now check to see if we have a valid ELF file, and one that BFD can
1090      make use of.  The magic number must match, the address size ('class')
1091      and byte-swapping must match our XVEC entry, and it must have a
1092      section header table (FIXME: See comments re sections at top of this
1093      file). */
1094
1095   if (x_ehdr.e_ident[EI_MAG0] != ELFMAG0 ||
1096       x_ehdr.e_ident[EI_MAG1] != ELFMAG1 ||
1097       x_ehdr.e_ident[EI_MAG2] != ELFMAG2 ||
1098       x_ehdr.e_ident[EI_MAG3] != ELFMAG3)
1099     {
1100 wrong:
1101       bfd_error = wrong_format;
1102       return (NULL);
1103     }
1104
1105   /* FIXME, Check EI_VERSION here !  */
1106
1107   switch (x_ehdr.e_ident[EI_CLASS])
1108     {
1109     case ELFCLASSNONE:          /* address size not specified */
1110       goto wrong;               /* No support if can't tell address size */
1111     case ELFCLASS32:            /* 32-bit addresses */
1112       break;
1113     case ELFCLASS64:            /* 64-bit addresses */
1114       goto wrong;               /* FIXME: 64 bits not yet supported */
1115     default:
1116       goto wrong;               /* No support if unknown address class */
1117     }
1118
1119   /* Switch xvec to match the specified byte order.  */
1120   switch (x_ehdr.e_ident[EI_DATA])
1121     {
1122     case ELFDATA2MSB:           /* Big-endian */ 
1123       if (!abfd->xvec->header_byteorder_big_p)
1124         goto wrong;
1125       break;
1126     case ELFDATA2LSB:           /* Little-endian */
1127       if (abfd->xvec->header_byteorder_big_p)
1128         goto wrong;
1129       break;
1130     case ELFDATANONE:           /* No data encoding specified */
1131     default:                    /* Unknown data encoding specified */
1132       goto wrong;
1133     }
1134   
1135   /* Allocate an instance of the elf_obj_tdata structure and hook it up to
1136      the tdata pointer in the bfd. */
1137
1138   if (NULL == (elf_tdata (abfd) = (struct elf_obj_tdata *)
1139                bfd_zalloc (abfd, sizeof (struct elf_obj_tdata))))
1140     {
1141       bfd_error = no_memory;
1142       return (NULL);
1143     }
1144
1145   /* FIXME:  Any `wrong' exits below here will leak memory (tdata).  */
1146
1147   /* Now that we know the byte order, swap in the rest of the header */
1148   i_ehdrp = elf_elfheader (abfd);
1149   elf_swap_ehdr_in (abfd, &x_ehdr, i_ehdrp);
1150   
1151   /* If there is no section header table, we're hosed. */
1152   if (i_ehdrp->e_shoff == 0)
1153     goto wrong;
1154
1155   if (i_ehdrp->e_type == ET_EXEC || i_ehdrp->e_type == ET_DYN)
1156     abfd -> flags |= EXEC_P;
1157
1158   /* Retrieve the architecture information from the xvec and verify
1159      that it matches the machine info stored in the ELF header.
1160      This allows us to resolve ambiguous formats that might not
1161      otherwise be distinguishable. */
1162
1163   ebd = (struct elf_backend_data *) (abfd->xvec->backend_data);
1164   switch (i_ehdrp->e_machine)
1165     {
1166     case EM_NONE:
1167     case EM_M32:                /* or should this be bfd_arch_obscure? */
1168       if (ebd -> arch != bfd_arch_unknown)
1169         goto wrong;
1170       bfd_default_set_arch_mach(abfd, bfd_arch_unknown, 0);
1171       break;
1172     case EM_SPARC:
1173       if (ebd -> arch != bfd_arch_sparc)
1174         goto wrong;
1175       bfd_default_set_arch_mach(abfd, bfd_arch_sparc, 0);
1176       break;
1177     case EM_386:
1178       if (ebd -> arch != bfd_arch_i386)
1179         goto wrong;
1180       bfd_default_set_arch_mach(abfd, bfd_arch_i386, 0);
1181       break;
1182     case EM_68K:
1183       if (ebd -> arch != bfd_arch_m68k)
1184         goto wrong;
1185       bfd_default_set_arch_mach(abfd, bfd_arch_m68k, 0);
1186       break;
1187     case EM_88K:
1188       if (ebd -> arch != bfd_arch_m88k)
1189         goto wrong;
1190       bfd_default_set_arch_mach(abfd, bfd_arch_m88k, 0);
1191       break;
1192     case EM_860:
1193       if (ebd -> arch != bfd_arch_i860)
1194         goto wrong;
1195       bfd_default_set_arch_mach(abfd, bfd_arch_i860, 0);
1196       break;
1197     case EM_MIPS:
1198       if (ebd -> arch != bfd_arch_mips)
1199         goto wrong;
1200       bfd_default_set_arch_mach(abfd, bfd_arch_mips, 0);
1201       break;
1202     default:
1203       goto wrong;
1204     }
1205   
1206   /* Allocate space for a copy of the section header table in 
1207      internal form, seek to the section header table in the file,
1208      read it in, and convert it to internal form.  As a simple sanity
1209      check, verify that the what BFD thinks is the size of each section
1210      header table entry actually matches the size recorded in the file. */
1211
1212   if (i_ehdrp->e_shentsize != sizeof (x_shdr))
1213     goto wrong;
1214   i_shdrp = (Elf_Internal_Shdr *)
1215     bfd_alloc (abfd, sizeof (*i_shdrp) * i_ehdrp->e_shnum);
1216   if (! i_shdrp)
1217     {
1218       bfd_error = no_memory;
1219       return (NULL);
1220     }
1221   if (bfd_seek (abfd, i_ehdrp->e_shoff, SEEK_SET) == -1)
1222     {
1223       bfd_error = system_call_error;
1224       return (NULL);
1225     }
1226   for (shindex = 0; shindex < i_ehdrp->e_shnum; shindex++)
1227     {
1228       if (bfd_read ((PTR) &x_shdr, sizeof x_shdr, 1, abfd)
1229           != sizeof (x_shdr))
1230         {
1231           bfd_error = system_call_error;
1232           return (NULL);
1233         }
1234       elf_swap_shdr_in (abfd, &x_shdr, i_shdrp + shindex);
1235     }
1236
1237   elf_elfsections (abfd) = i_shdrp;
1238   
1239   /* Read in the string table containing the names of the sections.  We
1240      will need the base pointer to this table later. */
1241   /* We read this inline now, so that we don't have to go through
1242      bfd_section_from_shdr with it (since this particular strtab is
1243      used to find all of the ELF section names.) */
1244
1245   shstrtab = elf_get_str_section (abfd, i_ehdrp->e_shstrndx);
1246   if (! shstrtab)
1247     return (NULL);
1248   
1249   /* Once all of the section headers have been read and converted, we
1250      can start processing them.  Note that the first section header is
1251      a dummy placeholder entry, so we ignore it.
1252
1253      We also watch for the symbol table section and remember the file
1254      offset and section size for both the symbol table section and the
1255      associated string table section. */
1256
1257   for (shindex = 1; shindex < i_ehdrp->e_shnum; shindex++)
1258     {
1259       bfd_section_from_shdr (abfd, shindex);
1260     }
1261
1262   /* Remember the entry point specified in the ELF file header. */
1263
1264   bfd_get_start_address (abfd) = i_ehdrp->e_entry;
1265
1266   return (abfd->xvec);
1267 }
1268
1269 /*  Core files are simply standard ELF formatted files that partition
1270     the file using the execution view of the file (program header table)
1271     rather than the linking view.  In fact, there is no section header
1272     table in a core file.
1273
1274     The process status information (including the contents of the general
1275     register set) and the floating point register set are stored in a
1276     segment of type PT_NOTE.  We handcraft a couple of extra bfd sections
1277     that allow standard bfd access to the general registers (.reg) and the
1278     floating point registers (.reg2).
1279
1280  */
1281
1282 bfd_target *
1283 DEFUN (elf_core_file_p, (abfd), bfd *abfd)
1284 {
1285   Elf_External_Ehdr x_ehdr;     /* Elf file header, external form */
1286   Elf_Internal_Ehdr *i_ehdrp;   /* Elf file header, internal form */
1287   Elf_External_Phdr x_phdr;     /* Program header table entry, external form */
1288   Elf_Internal_Phdr *i_phdrp;   /* Program header table, internal form */
1289   unsigned int phindex;
1290   
1291   /* Read in the ELF header in external format.  */
1292
1293   if (bfd_read ((PTR) &x_ehdr, sizeof (x_ehdr), 1, abfd) != sizeof (x_ehdr))
1294     {
1295       bfd_error = system_call_error;
1296       return (NULL);
1297     }
1298
1299   /* Now check to see if we have a valid ELF file, and one that BFD can
1300      make use of.  The magic number must match, the address size ('class')
1301      and byte-swapping must match our XVEC entry, and it must have a
1302      program header table (FIXME: See comments re segments at top of this
1303      file). */
1304
1305   if (x_ehdr.e_ident[EI_MAG0] != ELFMAG0 ||
1306       x_ehdr.e_ident[EI_MAG1] != ELFMAG1 ||
1307       x_ehdr.e_ident[EI_MAG2] != ELFMAG2 ||
1308       x_ehdr.e_ident[EI_MAG3] != ELFMAG3)
1309     {
1310 wrong:
1311       bfd_error = wrong_format;
1312       return (NULL);
1313     }
1314
1315   /* FIXME, Check EI_VERSION here !  */
1316
1317   switch (x_ehdr.e_ident[EI_CLASS])
1318     {
1319     case ELFCLASSNONE:          /* address size not specified */
1320       goto wrong;               /* No support if can't tell address size */
1321     case ELFCLASS32:            /* 32-bit addresses */
1322       break;
1323     case ELFCLASS64:            /* 64-bit addresses */
1324       goto wrong;               /* FIXME: 64 bits not yet supported */
1325     default:
1326       goto wrong;               /* No support if unknown address class */
1327     }
1328
1329   /* Switch xvec to match the specified byte order.  */
1330   switch (x_ehdr.e_ident[EI_DATA])
1331     {
1332     case ELFDATA2MSB:           /* Big-endian */ 
1333       if (abfd->xvec->byteorder_big_p == false)
1334         goto wrong;
1335       break;
1336     case ELFDATA2LSB:           /* Little-endian */
1337       if (abfd->xvec->byteorder_big_p == true)
1338         goto wrong;
1339       break;
1340     case ELFDATANONE:           /* No data encoding specified */
1341     default:                    /* Unknown data encoding specified */
1342       goto wrong;
1343     }
1344   
1345   /* Allocate an instance of the elf_obj_tdata structure and hook it up to
1346      the tdata pointer in the bfd. */
1347
1348   elf_tdata (abfd) =
1349     (struct elf_obj_tdata *) bfd_zalloc (abfd, sizeof (struct elf_obj_tdata));
1350   if (elf_tdata (abfd) == NULL)
1351     {
1352       bfd_error = no_memory;
1353       return (NULL);
1354     }
1355
1356   /* FIXME, `wrong' returns from this point onward, leak memory.  */
1357
1358   /* Now that we know the byte order, swap in the rest of the header */
1359   i_ehdrp = elf_elfheader (abfd);
1360   elf_swap_ehdr_in (abfd, &x_ehdr, i_ehdrp);
1361
1362   /* If there is no program header, or the type is not a core file, then
1363      we are hosed. */
1364   if (i_ehdrp->e_phoff == 0 || i_ehdrp->e_type != ET_CORE)
1365     goto wrong;
1366
1367   /* Allocate space for a copy of the program header table in 
1368      internal form, seek to the program header table in the file,
1369      read it in, and convert it to internal form.  As a simple sanity
1370      check, verify that the what BFD thinks is the size of each program
1371      header table entry actually matches the size recorded in the file. */
1372
1373   if (i_ehdrp->e_phentsize != sizeof (x_phdr))
1374     goto wrong;
1375   i_phdrp = (Elf_Internal_Phdr *)
1376     bfd_alloc (abfd, sizeof (*i_phdrp) * i_ehdrp->e_phnum);
1377   if (! i_phdrp)
1378     {
1379       bfd_error = no_memory;
1380       return (NULL);
1381     }
1382   if (bfd_seek (abfd, i_ehdrp->e_phoff, SEEK_SET) == -1)
1383     {
1384       bfd_error = system_call_error;
1385       return (NULL);
1386     }
1387   for (phindex = 0; phindex < i_ehdrp->e_phnum; phindex++)
1388     {
1389       if (bfd_read ((PTR) &x_phdr, sizeof (x_phdr), 1, abfd)
1390           != sizeof (x_phdr))
1391         {
1392           bfd_error = system_call_error;
1393           return (NULL);
1394         }
1395       elf_swap_phdr_in (abfd, &x_phdr, i_phdrp + phindex);
1396     }
1397
1398   /* Once all of the program headers have been read and converted, we
1399      can start processing them. */
1400
1401   for (phindex = 0; phindex < i_ehdrp->e_phnum; phindex++)
1402     {
1403       bfd_section_from_phdr (abfd, i_phdrp + phindex, phindex);
1404       if ((i_phdrp + phindex) -> p_type == PT_NOTE)
1405         {
1406           elf_corefile_note (abfd, i_phdrp + phindex);
1407         }
1408     }
1409
1410   /* Remember the entry point specified in the ELF file header. */
1411
1412   bfd_get_start_address (abfd) = i_ehdrp->e_entry;
1413
1414   return (abfd->xvec);
1415 }
1416
1417 boolean
1418 DEFUN (elf_mkobject, (abfd), bfd *abfd)
1419 {
1420   /* this just does initialization */
1421   /* coff_mkobject zalloc's space for tdata.coff_obj_data ... */
1422   elf_tdata(abfd) = (struct elf_obj_tdata *)
1423     bfd_zalloc (abfd, sizeof(struct elf_obj_tdata));
1424   if (elf_tdata(abfd) == 0) {
1425     bfd_error = no_memory;
1426     return false;
1427   }
1428   /* since everything is done at close time, do we need any
1429      initialization? */
1430   
1431   return (true);
1432 }
1433
1434 /*
1435   Create ELF output from BFD sections.
1436   
1437   Essentially, just create the section header and forget about the program
1438   header for now.   
1439   
1440 */
1441
1442 /* lacking nested functions and nested types, set up for mapping over
1443    BFD sections to produce ELF sections */
1444
1445 typedef struct {
1446   Elf_Internal_Ehdr     *i_ehdr;
1447   Elf_Internal_Shdr     *i_shdrp;
1448   struct strtab         *shstrtab;
1449   int                   symtab_section;
1450 } elf_sect_thunk;
1451
1452
1453
1454 static void
1455 DEFUN (elf_make_sections, (abfd, asect, obj),
1456        bfd              *abfd AND
1457        asection         *asect AND
1458        PTR              obj)
1459 {
1460   elf_sect_thunk *thunk = (elf_sect_thunk*)obj;
1461   /* most of what is in bfd_shdr_from_section goes in here... */
1462   /* and all of these sections generate at *least* one ELF section. */
1463   int this_section;
1464   int idx;
1465   
1466   /* check if we're making a PROGBITS section... */
1467   /* if ((asect->flags & SEC_ALLOC) && (asect->flags & SEC_LOAD)) */
1468   /* this was too strict... what *do* we want to check here? */
1469   if(1)
1470     {
1471       Elf_Internal_Shdr *this_hdr;
1472       this_section = elf_section_from_bfd_section (abfd, asect);
1473       this_hdr = &thunk->i_shdrp[this_section];
1474
1475       this_hdr->sh_addr = asect->vma;
1476       this_hdr->sh_size = asect->_raw_size;
1477       /* contents already set by elf_set_section_contents */
1478
1479       if (asect->flags & SEC_RELOC)
1480         {
1481           /* emit a reloc section, and thus strtab and symtab... */
1482           Elf_Internal_Shdr *rela_hdr;
1483           Elf_Internal_Shdr *symtab_hdr;
1484           Elf_External_Rela *outbound_relocs;
1485           int rela_section;
1486           
1487           symtab_hdr = &thunk->i_shdrp[thunk->symtab_section];
1488
1489           if (thunk->symtab_section == this_section + 1)
1490             rela_section = thunk->symtab_section + 2; /* symtab + symstrtab */
1491           else
1492             rela_section = this_section + 1;
1493           rela_hdr = &thunk->i_shdrp[rela_section];
1494           rela_hdr->sh_type = SHT_RELA;
1495           rela_hdr->sh_link = thunk->symtab_section;
1496           rela_hdr->sh_info = this_section;
1497           rela_hdr->sh_entsize = sizeof (Elf_External_Rela);
1498           /* orelocation has the data, reloc_count has the count... */
1499           rela_hdr->sh_size = rela_hdr->sh_entsize * asect->reloc_count;
1500           outbound_relocs = (Elf_External_Rela *)
1501             bfd_alloc(abfd, asect->reloc_count * sizeof(Elf_External_Rela));
1502           for (idx = 0; idx < asect->reloc_count; idx++)
1503             {
1504               Elf_Internal_Rela dst;
1505               arelent        *ptr;
1506               Elf_External_Rela  *src;
1507               
1508               ptr = asect->orelocation[idx];
1509               src = outbound_relocs + idx;
1510               if (asect->flags & SEC_RELOC)
1511                 dst.r_offset = ptr->address - asect->vma;
1512               else
1513                 dst.r_offset = ptr->address;
1514
1515               dst.r_info = ELF_R_INFO(1 /*ptr->sym_ptr_ptr*/, /* needs index into symtab (FIXME) */
1516                                       ptr->howto->type);
1517
1518               dst.r_addend = ptr->addend;
1519               elf_swap_reloca_out(abfd, &dst, src);
1520             }
1521           rela_hdr->contents = (void*)outbound_relocs;
1522         }
1523     }
1524 }
1525
1526 static void
1527 DEFUN (elf_fake_sections, (abfd, asect, obj),
1528        bfd              *abfd AND
1529        asection         *asect AND
1530        PTR              obj)
1531 {
1532   elf_sect_thunk *thunk = (elf_sect_thunk*)obj;
1533   /* most of what is in bfd_shdr_from_section goes in here... */
1534   /* and all of these sections generate at *least* one ELF section. */
1535   int this_section;
1536   
1537   /* check if we're making a PROGBITS section... */
1538   /* if ((asect->flags & SEC_ALLOC) && (asect->flags & SEC_LOAD)) */
1539   /* this was too strict... what *do* we want to check here? */
1540   if(1)
1541     {
1542       Elf_Internal_Shdr *this_hdr;
1543       this_section = thunk->i_ehdr->e_shnum++;
1544       this_hdr = &thunk->i_shdrp[this_section];
1545       this_hdr->sh_name = 
1546         bfd_add_to_strtab (abfd, thunk->shstrtab, asect->name);
1547       /* we need to log the type *now* so that elf_section_from_bfd_section
1548          can find us... have to set rawdata too. */
1549       this_hdr->rawdata = (void*)asect;
1550       if ((asect->flags & SEC_ALLOC) && (asect->flags & SEC_LOAD))
1551         this_hdr->sh_type = SHT_PROGBITS;
1552       else
1553         /* what *do* we put here? */
1554         this_hdr->sh_type = SHT_PROGBITS;
1555
1556
1557       if (asect->flags & SEC_RELOC)
1558         {
1559           /* emit a reloc section, and thus strtab and symtab... */
1560           Elf_Internal_Shdr *rela_hdr;
1561           Elf_Internal_Shdr *symtab_hdr;
1562           Elf_Internal_Shdr *symstrtab_hdr;
1563           int rela_section;
1564           int symstrtab_section;
1565           
1566           /* note that only one symtab is used, so just remember it
1567              for now */
1568           if (! thunk->symtab_section)
1569             {
1570               thunk->symtab_section = thunk->i_ehdr->e_shnum++;
1571               symtab_hdr = &thunk->i_shdrp[thunk->symtab_section];
1572               symtab_hdr->sh_name =
1573                 bfd_add_to_strtab (abfd, thunk->shstrtab, ".symtab");
1574               symtab_hdr->sh_type = SHT_SYMTAB;
1575               symtab_hdr->sh_entsize = sizeof (Elf_External_Sym);
1576
1577               symstrtab_section = thunk->i_ehdr->e_shnum++;
1578               BFD_ASSERT(symstrtab_section == thunk->symtab_section+1);
1579               symstrtab_hdr = &thunk->i_shdrp[symstrtab_section];
1580               symtab_hdr->sh_link = symstrtab_section;
1581               symstrtab_hdr->sh_name =
1582                 bfd_add_to_strtab (abfd, thunk->shstrtab, ".strtab");
1583               symstrtab_hdr->sh_type = SHT_STRTAB;
1584
1585               symtab_hdr->contents = 0;
1586               symstrtab_hdr->contents = 0;
1587               symstrtab_hdr->sh_size = 0;
1588             } 
1589           else
1590             symtab_hdr = &thunk->i_shdrp[thunk->symtab_section];
1591
1592           rela_section = thunk->i_ehdr->e_shnum++;
1593           rela_hdr = &thunk->i_shdrp[rela_section];
1594           rela_hdr->sh_name =
1595             bfd_add_2_to_strtab (abfd, thunk->shstrtab, ".rela", asect->name);
1596           rela_hdr->sh_type = SHT_RELA;
1597           rela_hdr->sh_link = thunk->symtab_section;
1598           rela_hdr->sh_info = this_section;
1599           rela_hdr->sh_entsize = sizeof (Elf_External_Rela);
1600         }
1601     }
1602 }
1603
1604
1605 static boolean
1606 DEFUN (elf_compute_section_file_positions, (abfd), bfd *abfd)
1607 {
1608   Elf_Internal_Ehdr *i_ehdrp;   /* Elf file header, internal form */
1609   Elf_Internal_Shdr *i_shdrp;   /* Section header table, internal form */
1610   struct strtab *shstrtab;
1611   int count, maxsections;
1612   elf_sect_thunk est;
1613
1614   if (! elf_shstrtab (abfd)) {
1615     i_ehdrp = elf_elfheader (abfd);     /* build new header in tdata memory */
1616     shstrtab = bfd_new_strtab(abfd);
1617     
1618     i_ehdrp->e_ident[EI_MAG0] = ELFMAG0;
1619     i_ehdrp->e_ident[EI_MAG1] = ELFMAG1;
1620     i_ehdrp->e_ident[EI_MAG2] = ELFMAG2;
1621     i_ehdrp->e_ident[EI_MAG3] = ELFMAG3;
1622
1623     i_ehdrp->e_ident[EI_CLASS] = ELFCLASS32; /* FIXME: find out from bfd */
1624     i_ehdrp->e_ident[EI_DATA] =
1625       abfd->xvec->byteorder_big_p ? ELFDATA2MSB : ELFDATA2LSB;
1626     i_ehdrp->e_ident[EI_VERSION] = EV_CURRENT;
1627
1628     for(count = EI_PAD; count < EI_NIDENT; count ++)
1629       i_ehdrp->e_ident[count] = 0;
1630       
1631     i_ehdrp->e_type = (abfd->flags & EXEC_P)? ET_EXEC : ET_REL;
1632     switch(bfd_get_arch(abfd))
1633       {
1634       case bfd_arch_unknown:
1635         i_ehdrp->e_machine = EM_NONE;
1636         break;
1637       case bfd_arch_sparc:
1638         i_ehdrp->e_machine = EM_SPARC;
1639         break;
1640       case bfd_arch_i386:
1641         i_ehdrp->e_machine = EM_386;
1642         break;
1643       case bfd_arch_m68k:
1644         i_ehdrp->e_machine = EM_68K;
1645         break;
1646       case bfd_arch_m88k:
1647         i_ehdrp->e_machine = EM_88K;
1648         break;
1649       case bfd_arch_i860:
1650         i_ehdrp->e_machine = EM_860;
1651         break;
1652       case bfd_arch_mips:                 /* MIPS Rxxxx */
1653         i_ehdrp->e_machine = EM_MIPS; /* only MIPS R3000 */
1654         break;
1655         /* also note that EM_M32, AT&T WE32100 is unknown to bfd */
1656       default:
1657         i_ehdrp->e_machine = EM_NONE;
1658       }
1659     i_ehdrp->e_version = EV_CURRENT;
1660     i_ehdrp->e_ehsize = sizeof(Elf_External_Ehdr);
1661     
1662     /* no program header, for now. */
1663     i_ehdrp->e_phoff = 0;
1664     i_ehdrp->e_phentsize = 0;
1665     i_ehdrp->e_phnum = 0;
1666
1667     /* each bfd section is section header entry */
1668     i_ehdrp->e_entry = bfd_get_start_address (abfd);
1669     i_ehdrp->e_shentsize = sizeof (Elf_External_Shdr);
1670
1671     /* figure at most each section can have a rel, strtab, symtab */
1672     maxsections = 4*bfd_count_sections(abfd)+2;
1673
1674     i_ehdrp->e_shoff = i_ehdrp->e_ehsize;
1675
1676     /* and we'll just have to fix up the offsets later. */
1677     /* outbase += i_ehdr.e_shentsize * i_ehdr.e_shnum; */
1678     
1679     i_shdrp = (Elf_Internal_Shdr *)
1680       bfd_alloc (abfd, sizeof (*i_shdrp) * maxsections);
1681     if (! i_shdrp)
1682       {
1683         bfd_error = no_memory;
1684         return (false);
1685       }
1686     for (count=0; count < maxsections; count++) 
1687       {
1688         i_shdrp[count].rawdata = 0;
1689         i_shdrp[count].contents = 0;
1690       }
1691     
1692     
1693     i_shdrp[0].sh_name = 0;
1694     i_shdrp[0].sh_type = SHT_NULL;
1695     i_shdrp[0].sh_flags = 0;
1696     i_shdrp[0].sh_addr = 0;
1697     i_shdrp[0].sh_offset = 0;
1698     i_shdrp[0].sh_size = 0;
1699     i_shdrp[0].sh_link = SHN_UNDEF;
1700     i_shdrp[0].sh_info = 0;
1701     i_shdrp[0].sh_addralign = 0;
1702     i_shdrp[0].sh_entsize = 0;
1703
1704     i_ehdrp->e_shnum = 1;
1705
1706     elf_elfsections (abfd) = i_shdrp;
1707     elf_shstrtab (abfd) = shstrtab;
1708   }
1709   est.i_ehdr = elf_elfheader(abfd);
1710   est.i_shdrp = elf_elfsections(abfd);
1711   est.shstrtab = elf_shstrtab(abfd);
1712   est.symtab_section = 0;       /* elf_fake_sections fils it in */
1713
1714   bfd_map_over_sections(abfd, elf_fake_sections, &est);
1715   elf_onesymtab (abfd) = est.symtab_section;
1716   return (true);
1717 }
1718
1719 boolean
1720 DEFUN (elf_write_object_contents, (abfd), bfd *abfd)
1721 {
1722   Elf_External_Ehdr x_ehdr;     /* Elf file header, external form */
1723   Elf_Internal_Ehdr *i_ehdrp;   /* Elf file header, internal form */
1724   Elf_External_Shdr *x_shdrp;   /* Section header table, external form */
1725   Elf_Internal_Shdr *i_shdrp;   /* Section header table, internal form */
1726   asection *nsect;
1727   elf_sect_thunk est;
1728   
1729   int outbase = 0;
1730   int count;
1731   struct strtab *shstrtab;
1732   
1733   if(abfd->output_has_begun == false) 
1734     elf_compute_section_file_positions(abfd);
1735
1736   i_ehdrp = elf_elfheader (abfd);
1737   i_shdrp = elf_elfsections (abfd);
1738   shstrtab = elf_shstrtab (abfd);
1739
1740   est.i_ehdr = i_ehdrp;
1741   est.i_shdrp = i_shdrp;
1742   est.shstrtab = shstrtab;
1743   est.symtab_section = elf_onesymtab (abfd); /* filled in by elf_fake */
1744
1745   bfd_map_over_sections(abfd, elf_make_sections, &est);
1746
1747   /* dump out the one symtab */
1748   {
1749     int symcount = bfd_get_symcount (abfd);
1750     asymbol ** syms = bfd_get_outsymbols (abfd);
1751     struct strtab * stt = bfd_new_strtab (abfd);
1752     Elf_Internal_Shdr *symtab_hdr;
1753     Elf_Internal_Shdr *symstrtab_hdr;
1754     int symstrtab_section;
1755     Elf_External_Sym *outbound_syms;
1756     int idx;
1757
1758     symtab_hdr = &i_shdrp[est.symtab_section];
1759     symtab_hdr->sh_type = SHT_SYMTAB;
1760     symtab_hdr->sh_entsize = sizeof (Elf_External_Sym);
1761     symtab_hdr->sh_size = symtab_hdr->sh_entsize * symcount;
1762
1763     /* see assert in elf_fake_sections that supports this: */
1764     symstrtab_section = est.symtab_section+1;
1765     symstrtab_hdr = &i_shdrp[symstrtab_section];
1766     symtab_hdr->sh_link = symstrtab_section;
1767     symstrtab_hdr->sh_type = SHT_STRTAB;
1768
1769     outbound_syms = (Elf_External_Sym*)
1770       bfd_alloc(abfd, (1+symcount) * sizeof(Elf_External_Sym));
1771     /* now generate the data (for "contents") */
1772     for (idx = 0; idx < symcount; idx++)
1773       {
1774         Elf_Internal_Sym sym;
1775         sym.st_name = bfd_add_to_strtab (abfd, stt, syms[idx]->name);
1776         sym.st_value = syms[idx]->value;
1777         sym.st_size =  0; /* we should recover this (FIXME) */
1778         if (syms[idx]->flags & BSF_WEAK)
1779           sym.st_info = ELF_ST_INFO(STB_WEAK, STT_OBJECT);
1780         else if (syms[idx]->flags & BSF_LOCAL)
1781           sym.st_info = ELF_ST_INFO(STB_LOCAL, STT_OBJECT);
1782         else if (syms[idx]->flags & BSF_GLOBAL)
1783           sym.st_info = ELF_ST_INFO(STB_GLOBAL, STT_OBJECT);
1784         else if (syms[idx]->flags & BSF_SECTION_SYM)
1785           sym.st_info = ELF_ST_INFO(STB_LOCAL, STT_SECTION);
1786         else if (syms[idx]->flags & BSF_FILE)
1787           sym.st_info = ELF_ST_INFO(STB_LOCAL, STT_FILE);
1788
1789         sym.st_other = 0;
1790         if (syms[idx]->section) 
1791           sym.st_shndx =
1792             elf_section_from_bfd_section(abfd,
1793                                          syms[idx]->section->output_section);
1794         else
1795           sym.st_shndx = SHN_UNDEF;
1796
1797         elf_swap_symbol_out (abfd, &sym, outbound_syms+idx+1);
1798       }
1799     {
1800       /* fill in 0th symbol */
1801       Elf_Internal_Sym sym;
1802       sym.st_name = 0;
1803       sym.st_value = 0;
1804       sym.st_size = 0;
1805       sym.st_info = 0;
1806       sym.st_other = 0;
1807       sym.st_shndx = SHN_UNDEF;
1808       elf_swap_symbol_out (abfd, &sym, outbound_syms);
1809     }
1810     symtab_hdr->contents = (void*)outbound_syms;
1811     symstrtab_hdr->contents = (void*)stt->tab;
1812     symstrtab_hdr->sh_size = stt->length;
1813   }
1814
1815   /* put the strtab out too... */
1816   {
1817     Elf_Internal_Shdr *this_hdr;
1818     int this_section;
1819
1820     this_section = i_ehdrp->e_shnum++;
1821     i_ehdrp->e_shstrndx = this_section;
1822     this_hdr = &i_shdrp[this_section];
1823     this_hdr->sh_name = bfd_add_to_strtab (abfd, shstrtab, ".shstrtab");
1824     this_hdr->sh_type = SHT_STRTAB;
1825     this_hdr->sh_size = shstrtab->length;
1826     this_hdr->contents = (void*)shstrtab->tab;
1827   }
1828
1829   outbase = i_ehdrp->e_ehsize;
1830
1831   /* swap the header before spitting it out... */
1832   elf_swap_ehdr_out (abfd, i_ehdrp, &x_ehdr);
1833   bfd_seek (abfd, (file_ptr) 0, SEEK_SET);
1834   bfd_write ((PTR) &x_ehdr, sizeof(x_ehdr), 1, abfd);
1835
1836   outbase += i_ehdrp->e_shentsize * i_ehdrp->e_shnum;
1837
1838   /* now we fix up the offsets... */
1839   for (count = 1; count < i_ehdrp->e_shnum; count ++)
1840     {
1841       i_shdrp[count].sh_offset = outbase;
1842       outbase += i_shdrp[count].sh_size;
1843     }
1844
1845   /* at this point we've concocted all the ELF sections... */
1846   x_shdrp = (Elf_External_Shdr *)
1847     bfd_alloc (abfd, sizeof (*x_shdrp) * (i_ehdrp->e_shnum));
1848   if (! x_shdrp)
1849     {
1850       bfd_error = no_memory;
1851       return (false);
1852     }
1853
1854   for (count = 0; count < i_ehdrp->e_shnum; count ++)
1855     {
1856       elf_swap_shdr_out (abfd, i_shdrp+count, x_shdrp+count);
1857     }
1858   bfd_write ((PTR) x_shdrp, sizeof(*x_shdrp), i_ehdrp->e_shnum, abfd);
1859   /* need to dump the string table too... */
1860   
1861   /* after writing the headers, we need to write the sections too... */
1862   nsect = abfd->sections;
1863   for (count = 0; count < i_ehdrp->e_shnum; count ++)
1864     {
1865       if(i_shdrp[count].contents)
1866         {
1867           bfd_seek (abfd, i_shdrp[count].sh_offset, SEEK_SET);
1868           bfd_write (i_shdrp[count].contents, i_shdrp[count].sh_size, 1, abfd);
1869         }
1870     }
1871   
1872   /* sample use of bfd:
1873    * bfd_seek (abfd, (file_ptr) 0, SEEK_SET);
1874    * bfd_write ((PTR) &exec_bytes, 1, EXEC_BYTES_SIZE, abfd);
1875    * if (bfd_seek(abfd, scn_base, SEEK_SET) != 0)
1876    * return false;
1877    * old = bfd_tell(abfd);
1878    */
1879
1880   return true;
1881   
1882 }
1883
1884 /* Given an index of a section, retrieve a pointer to it.  Note
1885    that for our purposes, sections are indexed by {1, 2, ...} with
1886    0 being an illegal index. */
1887
1888 /* In the original, each ELF section went into exactly one BFD
1889    section. This doesn't really make sense, so we need a real mapping.
1890    The mapping has to hide in the Elf_Internal_Shdr since asection
1891    doesn't have anything like a tdata field... */
1892    
1893 static struct sec *
1894 DEFUN (section_from_elf_index, (abfd, index),
1895        bfd            *abfd AND
1896        int             index)
1897 {
1898   Elf_Internal_Shdr *i_shdrp = elf_elfsections (abfd);
1899   Elf_Internal_Shdr *hdr = i_shdrp + index;
1900
1901   switch (hdr->sh_type)
1902     {
1903       /* ELF sections that map to BFD sections */
1904     case SHT_PROGBITS:
1905     case SHT_NOBITS:
1906       if (! hdr->rawdata)
1907         bfd_section_from_shdr (abfd, index);
1908       return (struct sec *)hdr->rawdata;
1909
1910     default:
1911       return (struct sec *)&bfd_abs_section;
1912     }
1913 }
1914
1915 /* given a section, search the header to find them... */
1916 static int
1917 DEFUN (elf_section_from_bfd_section, (abfd, asect),
1918        bfd              *abfd AND
1919        struct sec       *asect)
1920 {
1921   Elf_Internal_Shdr *i_shdrp = elf_elfsections (abfd);
1922   int index;
1923   Elf_Internal_Shdr *hdr;
1924   int maxindex = elf_elfheader (abfd)->e_shnum;
1925   
1926   for(index = 0; index < maxindex; index++) {
1927     hdr = &i_shdrp[index];
1928     switch (hdr->sh_type)
1929       {
1930         /* ELF sections that map to BFD sections */
1931       case SHT_PROGBITS:
1932       case SHT_NOBITS:
1933         if (hdr->rawdata) 
1934           {
1935             if (((struct sec *)(hdr->rawdata)) == asect)
1936               return index;
1937           }
1938         break;
1939       default:
1940         break;
1941       }
1942   }
1943   return 0;
1944 }
1945
1946 static boolean
1947 DEFUN (elf_slurp_symbol_table, (abfd, symptrs),
1948        bfd              *abfd AND
1949        asymbol          **symptrs)      /* Buffer for generated bfd symbols */
1950 {
1951   Elf_Internal_Shdr *i_shdrp = elf_elfsections (abfd);
1952   Elf_Internal_Shdr *hdr = i_shdrp + elf_onesymtab (abfd);
1953   int symcount;         /* Number of external ELF symbols */
1954   int i;
1955   asymbol *sym;         /* Pointer to current bfd symbol */
1956   asymbol *symbase;     /* Buffer for generated bfd symbols */
1957   Elf_Internal_Sym i_sym;
1958   Elf_External_Sym *x_symp;
1959
1960   /* this is only valid because there is only one symtab... */
1961   /* FIXME:  This is incorrect, there may also be a dynamic symbol
1962      table which is a subset of the full symbol table.  We either need
1963      to be prepared to read both (and merge them) or ensure that we
1964      only read the full symbol table.  Currently we only get called to
1965      read the full symbol table.  -fnf */
1966   if (bfd_get_outsymbols (abfd) != NULL)
1967     {
1968       return (true);
1969     }
1970
1971   /* Read each raw ELF symbol, converting from external ELF form to
1972      internal ELF form, and then using the information to create a
1973      canonical bfd symbol table entry.
1974
1975      Note that we allocate the initial bfd canonical symbol buffer
1976      based on a one-to-one mapping of the ELF symbols to canonical
1977      symbols.  We actually use all the ELF symbols, so there will be no
1978      space left over at the end.  When we have all the symbols, we
1979      build the caller's pointer vector. */
1980
1981   if (bfd_seek (abfd, hdr->sh_offset, SEEK_SET) == -1)
1982     {
1983       bfd_error = system_call_error;
1984       return (false);
1985     }
1986
1987   symcount = hdr->sh_size / sizeof (Elf_External_Sym);
1988   symbase = (asymbol *) bfd_zalloc (abfd, symcount * sizeof (asymbol));
1989   sym = symbase;
1990
1991   /* Temporarily allocate room for the raw ELF symbols.  */
1992   x_symp = (Elf_External_Sym *) bfd_xmalloc (symcount * sizeof (Elf_External_Sym));
1993
1994   if (bfd_read ((PTR) x_symp, sizeof (Elf_External_Sym), symcount, abfd) 
1995       != symcount * sizeof (Elf_External_Sym))
1996     {
1997       free ((PTR)x_symp);
1998       bfd_error = system_call_error;
1999       return (false);
2000     }
2001   /* Skip first symbol, which is a null dummy.  */
2002   for (i = 1; i < symcount; i++)
2003     {
2004       elf_swap_symbol_in (abfd, x_symp + i, &i_sym);
2005       sym -> the_bfd = abfd;
2006       if (i_sym.st_name > 0)
2007         sym -> name = elf_string_from_elf_section(abfd, hdr->sh_link,
2008                                                 i_sym.st_name);
2009       else
2010         sym -> name = "unnamed"; /* perhaps should include the number? */
2011       sym -> value = i_sym.st_value;
2012 /* FIXME -- this is almost certainly bogus.  It's from Pace Willisson's
2013 hasty Solaris support, to pass the sizes of object files or functions
2014 down into GDB via the back door, to circumvent some other kludge in
2015 how Sun hacked stabs.   -- gnu@cygnus.com  */
2016       sym -> udata = (PTR)i_sym.st_size;
2017 /* FIXME -- end of bogosity.  */
2018       if (i_sym.st_shndx > 0 && i_sym.st_shndx < SHN_LORESERV)
2019         {
2020           sym -> section = section_from_elf_index (abfd, i_sym.st_shndx);
2021         }
2022       else if (i_sym.st_shndx == SHN_ABS)
2023         {
2024           sym -> section = &bfd_abs_section;
2025         }
2026       else if (i_sym.st_shndx == SHN_COMMON)
2027         {
2028           sym -> section = &bfd_com_section;
2029         }
2030       else if (i_sym.st_shndx == SHN_UNDEF)
2031         {
2032           sym -> section = &bfd_und_section;
2033         }
2034       else
2035         sym -> section = &bfd_abs_section;
2036       
2037       switch (ELF_ST_BIND (i_sym.st_info))
2038         {
2039           case STB_LOCAL:
2040             sym -> flags |= BSF_LOCAL;
2041             break;
2042           case STB_GLOBAL:
2043             sym -> flags |= (BSF_GLOBAL | BSF_EXPORT);
2044             break;
2045           case STB_WEAK:
2046             sym -> flags |= BSF_WEAK;
2047             break;
2048         }
2049
2050       switch (ELF_ST_TYPE (i_sym.st_info))
2051         {
2052           case STT_SECTION:
2053             sym->flags |= BSF_SECTION_SYM | BSF_DEBUGGING;
2054             break;
2055           case STT_FILE:
2056             sym->flags |= BSF_FILE | BSF_DEBUGGING;
2057             break;
2058         }
2059       sym++;
2060     }
2061
2062   /* We rely on the zalloc to clear out the final symbol entry.  */
2063
2064   /* We're now done with the raw symbols.  */
2065   free ((PTR)x_symp);
2066
2067   bfd_get_symcount(abfd) = symcount = sym - symbase;
2068   
2069   /* Fill in the user's symbol pointer vector if needed.  */
2070   if (symptrs)
2071     {
2072       sym = symbase;
2073       while (symcount-- > 0)
2074         {
2075           *symptrs++ = sym++;
2076         }
2077       *symptrs = 0;                     /* Final null pointer */
2078     }
2079
2080   return (true);
2081 }
2082
2083 /* Return the number of bytes required to hold the symtab vector.
2084
2085    Note that we base it on the count plus 1, since we will null terminate
2086    the vector allocated based on this size.  However, the ELF symbol table
2087    always has a dummy entry as symbol #0, so it ends up even.  */
2088
2089 unsigned int
2090 DEFUN (elf_get_symtab_upper_bound, (abfd), bfd *abfd)
2091 {
2092   unsigned int symcount;
2093   unsigned int symtab_size = 0;
2094   Elf_Internal_Shdr *i_shdrp;
2095   Elf_Internal_Shdr *hdr;
2096
2097   i_shdrp = elf_elfsections (abfd);
2098   if (i_shdrp != NULL)
2099     {
2100       hdr = i_shdrp + elf_onesymtab (abfd);
2101       symcount = hdr->sh_size / sizeof (Elf_External_Sym);
2102       symtab_size = (symcount - 1 + 1) * (sizeof (asymbol));
2103     }
2104   return (symtab_size);
2105 }
2106
2107 /*
2108         This function return the number of bytes required to store the
2109         relocation information associated with section <<sect>>
2110         attached to bfd <<abfd>>
2111
2112 */
2113 unsigned int
2114 elf_get_reloc_upper_bound (abfd, asect)
2115 bfd            *abfd;
2116 sec_ptr         asect;
2117 {
2118   if (asect->flags & SEC_RELOC)
2119     {
2120       /* either rel or rela */
2121       return asect->_raw_size;
2122     }
2123   else
2124     return (0);
2125 }
2126
2127 static boolean
2128 DEFUN(elf_slurp_reloca_table,(abfd, asect, symbols),
2129       bfd            *abfd AND
2130       sec_ptr         asect AND
2131       asymbol       **symbols)
2132 {
2133   Elf_External_Rela   *native_relocs;
2134   arelent        *reloc_cache;
2135   arelent        *cache_ptr;
2136
2137   unsigned int idx;
2138   
2139   if (asect->relocation)
2140     return true;
2141   if (asect->reloc_count == 0)
2142     return true;
2143   if (asect->flags & SEC_CONSTRUCTOR)
2144     return true;
2145
2146   bfd_seek (abfd, asect->rel_filepos, SEEK_SET);
2147   native_relocs = (Elf_External_Rela *)
2148     bfd_alloc(abfd, asect->reloc_count * sizeof(Elf_External_Rela));
2149   bfd_read ((PTR) native_relocs,
2150             sizeof(Elf_External_Rela), asect->reloc_count, abfd);
2151   
2152   reloc_cache = (arelent *)
2153     bfd_alloc(abfd, (size_t) (asect->reloc_count * sizeof(arelent)));
2154
2155   if (! reloc_cache) {
2156     bfd_error = no_memory;
2157     return false;
2158   } 
2159   
2160   for (idx = 0; idx < asect->reloc_count; idx ++) 
2161     {
2162 #ifdef RELOC_PROCESSING
2163       /* sparc, 68k, 88k, 860 use rela only. */
2164       /* 386 and we32000 use rel only... fix it for them later. */
2165       Elf_Internal_Rela dst;
2166       Elf_External_Rela  *src;
2167
2168       cache_ptr = reloc_cache + idx;
2169       src = native_relocs + idx;
2170       elf_swap_reloca_in(abfd, src, &dst);
2171
2172       RELOC_PROCESSING(cache_ptr, &dst, symbols, abfd, asect);
2173 #else
2174       Elf_Internal_Rela dst;
2175       Elf_External_Rela  *src;
2176
2177       cache_ptr = reloc_cache + idx;
2178       src = native_relocs + idx;
2179
2180       elf_swap_reloca_in(abfd, src, &dst);
2181
2182       if(asect->flags & SEC_RELOC)
2183         {
2184           /* relocatable, so the offset is off of the section */
2185           cache_ptr->address = dst.r_offset + asect->vma;
2186         }
2187       else
2188         {
2189           /* non-relocatable, so the offset a virtual address */
2190           cache_ptr->address = dst.r_offset;
2191         }
2192       /* ELF_R_SYM(dst.r_info) is the symbol table offset... */
2193       cache_ptr->sym_ptr_ptr = symbols + ELF_R_SYM(dst.r_info);
2194       cache_ptr->addend = dst.r_addend;
2195
2196       /* Fill in the cache_ptr->howto field from dst.r_type */
2197       {
2198         struct elf_backend_data *ebd;
2199         ebd = (struct elf_backend_data *) (abfd->xvec->backend_data);
2200         (*ebd->elf_info_to_howto)(abfd, cache_ptr, &dst);
2201       }
2202 #endif
2203     }
2204
2205   asect->relocation = reloc_cache;
2206   return true;
2207 }
2208
2209
2210 unsigned int
2211 elf_canonicalize_reloc (abfd, section, relptr, symbols)
2212 bfd            *abfd;
2213 sec_ptr         section;
2214 arelent       **relptr;
2215 asymbol       **symbols;
2216 {
2217   arelent        *tblptr = section->relocation;
2218   unsigned int    count = 0;
2219
2220   /* snarfed from coffcode.h */
2221   /* FIXME: this could be reloc... */
2222   elf_slurp_reloca_table(abfd, section, symbols);
2223
2224   tblptr = section->relocation;
2225   if (!tblptr)
2226     return 0;
2227
2228   for (; count++ < section->reloc_count;)
2229     *relptr++ = tblptr++;
2230
2231   *relptr = 0;
2232   return section->reloc_count;
2233 }
2234
2235 unsigned int
2236 DEFUN (elf_get_symtab, (abfd, alocation),
2237        bfd            *abfd AND
2238        asymbol       **alocation)
2239 {
2240
2241   if (!elf_slurp_symbol_table (abfd, alocation))
2242     return (0);
2243   else
2244     return (bfd_get_symcount (abfd));
2245 }
2246
2247 asymbol *
2248 DEFUN (elf_make_empty_symbol, (abfd),
2249        bfd *abfd)
2250 {
2251   elf_symbol_type *newsym;
2252
2253   newsym = (elf_symbol_type *) bfd_zalloc (abfd, sizeof (elf_symbol_type));
2254   if (! newsym)
2255     {
2256       bfd_error = no_memory;
2257       return (NULL);
2258     }
2259   else
2260     {
2261       newsym -> symbol.the_bfd = abfd;
2262       return (&newsym -> symbol);
2263     }
2264 }
2265
2266 void 
2267 DEFUN (elf_print_symbol,(ignore_abfd, filep, symbol, how),
2268       bfd            *ignore_abfd AND
2269       PTR           filep AND
2270       asymbol        *symbol AND
2271       bfd_print_symbol_type how)
2272 {
2273   FILE *file = (FILE *)filep;
2274   switch (how)
2275     {
2276     case bfd_print_symbol_name:
2277       fprintf(file, "%s", symbol->name);
2278       break;
2279     case bfd_print_symbol_more:
2280       fprintf(file, "elf %lx %lx",
2281               symbol->value,
2282               symbol->flags);
2283       break;
2284     case bfd_print_symbol_nm:
2285     case bfd_print_symbol_all:
2286       {
2287         CONST char *section_name;
2288         section_name = symbol->section? symbol->section->name : "(*none*)";
2289         bfd_print_symbol_vandf((PTR) file, symbol);
2290         fprintf(file, " %s\t%s",
2291                 section_name,
2292                 symbol->name);
2293       }
2294       break;
2295     }
2296
2297 }
2298
2299 alent *
2300 DEFUN (elf_get_lineno,(ignore_abfd, symbol),
2301       bfd            *ignore_abfd AND
2302       asymbol        *symbol)
2303 {
2304   fprintf (stderr, "elf_get_lineno unimplemented\n");
2305   fflush (stderr);
2306   abort ();
2307   return (NULL);
2308 }
2309
2310 boolean
2311 DEFUN (elf_set_arch_mach,(abfd, arch, machine),
2312       bfd            *abfd AND
2313       enum bfd_architecture arch AND
2314       unsigned long   machine)
2315 {
2316   /* Allow any architecture to be supported by the elf backend */
2317   switch(arch)
2318     {
2319     case bfd_arch_unknown:      /* EM_NONE */
2320     case bfd_arch_sparc:        /* EM_SPARC */
2321     case bfd_arch_i386:         /* EM_386 */
2322     case bfd_arch_m68k:         /* EM_68K */
2323     case bfd_arch_m88k:         /* EM_88K */
2324     case bfd_arch_i860:         /* EM_860 */
2325     case bfd_arch_mips:         /* EM_MIPS (MIPS R3000) */
2326       return  bfd_default_set_arch_mach(abfd, arch, machine);
2327     default:
2328       return false;
2329     }
2330 }
2331
2332 boolean
2333 DEFUN (elf_find_nearest_line,(abfd,
2334                               section,
2335                               symbols,
2336                               offset,
2337                               filename_ptr,
2338                               functionname_ptr,
2339                               line_ptr),
2340       bfd            *abfd AND
2341       asection       *section AND
2342       asymbol       **symbols AND
2343       bfd_vma         offset AND
2344       CONST char      **filename_ptr AND
2345       CONST char       **functionname_ptr AND
2346       unsigned int   *line_ptr)
2347 {
2348   fprintf (stderr, "elf_find_nearest_line unimplemented\n");
2349   fflush (stderr);
2350   abort ();
2351   return (false);
2352 }
2353
2354 int 
2355 DEFUN (elf_sizeof_headers, (abfd, reloc),
2356       bfd *abfd AND
2357       boolean reloc)
2358 {
2359   fprintf (stderr, "elf_sizeof_headers unimplemented\n");
2360   fflush (stderr);
2361   abort ();
2362   return (0);
2363 }
2364
2365 boolean
2366 DEFUN(elf_set_section_contents, (abfd, section, location, offset, count),
2367       bfd *abfd AND
2368       sec_ptr section AND
2369       PTR location AND
2370       file_ptr offset AND
2371       bfd_size_type count)
2372 {
2373   int dest_sect;
2374   void *contents;
2375   if (abfd->output_has_begun == false) /* set by bfd.c handler? */
2376     {
2377       /* do setup calculations (FIXME) */
2378       elf_compute_section_file_positions(abfd);
2379     }
2380 #if 0
2381   if(bfd_seek (abfd, (file_ptr)section->filepos + offset, SEEK_SET) == -1)
2382     return false;
2383   if(bfd_write (location, (bfd_size_type)1, count, abfd) != count)
2384     return false;
2385 #endif
2386   /* we really just need to save the contents away... */
2387   dest_sect = elf_section_from_bfd_section(abfd, section);
2388   if(!dest_sect)
2389     return false;
2390
2391   /* FIXME: allocate in set_section_size, then copy in here... */
2392   contents = (void*)bfd_alloc(abfd, count);
2393   BFD_ASSERT(contents);
2394   memcpy(contents, location, count);
2395   elf_elfsections (abfd)[dest_sect].contents = contents;
2396
2397   return true;
2398 }
2399
2400 void
2401 DEFUN (elf_no_info_to_howto, (abfd, cache_ptr, dst),
2402        bfd *abfd AND
2403        arelent *cache_ptr AND
2404        Elf_Internal_Rela *dst)
2405 {
2406   abort ();
2407 }