1 |
/* |
2 |
* Cisco router simulation platform. |
3 |
* Copyright (c) 2006 Christophe Fillot (cf@utc.fr) |
4 |
*/ |
5 |
|
6 |
#include <stdio.h> |
7 |
#include <stdlib.h> |
8 |
#include <unistd.h> |
9 |
#include <string.h> |
10 |
#include <sys/types.h> |
11 |
#include <sys/stat.h> |
12 |
#include <sys/mman.h> |
13 |
#include <signal.h> |
14 |
#include <fcntl.h> |
15 |
#include <assert.h> |
16 |
#include <libelf.h> |
17 |
|
18 |
#include "utils.h" |
19 |
|
20 |
/* Extract ROM code+data from an ELF file and convert it into a C array */ |
21 |
int main(int argc,char *argv[]) |
22 |
{ |
23 |
unsigned char buffer[8]; |
24 |
m_uint32_t vaddr,start; |
25 |
Elf32_Ehdr *ehdr; |
26 |
Elf32_Phdr *phdr; |
27 |
Elf *img_elf; |
28 |
size_t len,clen; |
29 |
int i,j,fd; |
30 |
FILE *bfd,*fd_out; |
31 |
|
32 |
if (argc != 4) { |
33 |
fprintf(stderr,"Usage: %s <input_file> <output_file> <addr>\n",argv[0]); |
34 |
exit(EXIT_FAILURE); |
35 |
} |
36 |
|
37 |
start = strtoul(argv[3],NULL,0); |
38 |
|
39 |
if ((fd = open(argv[1],O_RDONLY)) == -1) |
40 |
return(-1); |
41 |
|
42 |
if (elf_version(EV_CURRENT) == EV_NONE) { |
43 |
fprintf(stderr,"load_elf_image: library out of date\n"); |
44 |
return(-1); |
45 |
} |
46 |
|
47 |
if (!(img_elf = elf_begin(fd,ELF_C_READ,NULL))) { |
48 |
fprintf(stderr,"load_elf_image: elf_begin: %s\n", |
49 |
elf_errmsg(elf_errno())); |
50 |
return(-1); |
51 |
} |
52 |
|
53 |
if (!(phdr = elf32_getphdr(img_elf))) { |
54 |
fprintf(stderr,"load_elf_image: elf32_getphdr: %s\n", |
55 |
elf_errmsg(elf_errno())); |
56 |
return(-1); |
57 |
} |
58 |
|
59 |
if (!(fd_out = fopen(argv[2],"w"))) { |
60 |
fprintf(stderr,"Unable to create file \"%s\"\n",argv[2]); |
61 |
exit(EXIT_FAILURE); |
62 |
} |
63 |
|
64 |
ehdr = elf32_getehdr(img_elf); |
65 |
phdr = elf32_getphdr(img_elf); |
66 |
|
67 |
printf("Extracting ROM from ELF file '%s'...\n",argv[1]); |
68 |
bfd = fdopen(fd,"r"); |
69 |
|
70 |
if (!bfd) { |
71 |
perror("load_elf_image: fdopen"); |
72 |
return(-1); |
73 |
} |
74 |
|
75 |
for(i=0;i<ehdr->e_phnum;i++,phdr++) |
76 |
{ |
77 |
fseek(bfd,phdr->p_offset,SEEK_SET); |
78 |
|
79 |
vaddr = (m_uint64_t)phdr->p_vaddr; |
80 |
len = phdr->p_filesz; |
81 |
|
82 |
if (vaddr != start) |
83 |
continue; |
84 |
|
85 |
while(len > 0) |
86 |
{ |
87 |
clen = fread(buffer,1,sizeof(buffer),bfd); |
88 |
|
89 |
if (clen == 0) |
90 |
break; |
91 |
|
92 |
fprintf(fd_out," "); |
93 |
|
94 |
for(j=0;j<clen;j++) |
95 |
fprintf(fd_out,"0x%2.2x, ",buffer[j]); |
96 |
|
97 |
fprintf(fd_out,"\n"); |
98 |
len -= clen; |
99 |
} |
100 |
} |
101 |
|
102 |
fclose(fd_out); |
103 |
return(0); |
104 |
} |