11 #include <sys/types.h>
15 #define FATAL do { fprintf(stderr, "Error at %s:%d (%d) [%s]\n", \
16 __FILE__, __LINE__, errno, strerror(errno)); exit(1); } while(0)
18 #define MAP_SIZE 131072
19 #define MAP_MASK (4096 - 1)
21 char * snarf_file(char * fname) {
23 int fd = open(fname, O_RDONLY);
27 if (fstat(fd, &st) < 0) FATAL;
29 char * buf = malloc(st.st_size);
31 if (read(fd, buf, st.st_size) != st.st_size) FATAL;
33 printf("Loaded %d bytes.\n", st.st_size);
37 void dump_to_ram (void * src, int target, int size) {
39 printf("Copying %d bytes to 0x%08x...\n", size, target);
41 int fd = open("/dev/mem", O_RDWR | O_SYNC);
44 void * map_base = mmap(0, MAP_SIZE, PROT_READ | PROT_WRITE,
45 MAP_SHARED, fd, target & ~MAP_MASK);
47 if (map_base == (void *) -1) FATAL;
49 void * virt_addr = map_base + (target & MAP_MASK);
50 memcpy(virt_addr, src, size);
54 static const unsigned char elf_ident[4] = { 0x7F, 'E', 'L', 'F' };
56 int load_elf (char * buf) {
58 Elf32_Ehdr * elf_hdr = (Elf32_Ehdr *) buf;
59 Elf32_Shdr * elf_sec_hdrs = (Elf32_Shdr *) (buf + elf_hdr->e_shoff);
61 if (memcmp(elf_hdr->e_ident, elf_ident, sizeof(elf_ident))) FATAL;
62 if (elf_hdr->e_type != ET_EXEC) FATAL;
63 if (elf_hdr->e_machine != EM_386) FATAL;
64 if (elf_hdr->e_version != EV_CURRENT) FATAL;
66 char * string_table = buf + elf_sec_hdrs[elf_hdr->e_shstrndx].sh_offset;
69 for (i = 0; i < elf_hdr->e_shnum; i++) {
70 if (elf_sec_hdrs[i].sh_name == SHN_UNDEF) {
74 char * section_name = string_table + elf_sec_hdrs[i].sh_name;
76 if (elf_sec_hdrs[i].sh_type != SHT_PROGBITS) {
77 printf("Skipping %s...\n", section_name);
81 printf("Loading %s...\n", section_name);
83 dump_to_ram(buf + elf_sec_hdrs[i].sh_offset,
84 elf_sec_hdrs[i].sh_addr,
85 elf_sec_hdrs[i].sh_size);
91 int main(int argc, char **argv) {
93 printf("Usage: %s elffile\n", argv[0]);
97 printf("Loading file...\n");
99 char * buf = snarf_file(argv[1]);