Debian Codegraph @

common/rom2c.c

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