aboutsummaryrefslogtreecommitdiff
path: root/pk/elf.c
diff options
context:
space:
mode:
authorAndrew Waterman <waterman@s144.Millennium.Berkeley.EDU>2011-04-08 01:57:38 -0700
committerAndrew Waterman <waterman@s144.Millennium.Berkeley.EDU>2011-04-08 02:11:57 -0700
commit666ae0c9e5355e578c2487b81f48b4b74cc16dda (patch)
treec8e5ddbb6cd1dfe2c4fe0e5995c57efaf65d4299 /pk/elf.c
parentc6fef75003abf36c618b9fff4f64f3bda76af804 (diff)
downloadpk-666ae0c9e5355e578c2487b81f48b4b74cc16dda.zip
pk-666ae0c9e5355e578c2487b81f48b4b74cc16dda.tar.gz
pk-666ae0c9e5355e578c2487b81f48b4b74cc16dda.tar.bz2
[pk,fesvr] pk now loads elfs itself
this allows it to detect 32b binaries
Diffstat (limited to 'pk/elf.c')
-rw-r--r--pk/elf.c57
1 files changed, 57 insertions, 0 deletions
diff --git a/pk/elf.c b/pk/elf.c
new file mode 100644
index 0000000..51debb3
--- /dev/null
+++ b/pk/elf.c
@@ -0,0 +1,57 @@
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <elf.h>
+#include <string.h>
+#include "file.h"
+#include "pk.h"
+
+long load_elf(const char* fn, int* user64)
+{
+ sysret_t ret = file_open(fn, strlen(fn)+1, O_RDONLY, 0);
+ file_t* file = (file_t*)ret.result;
+ if(file == NULL)
+ panic("couldn't open %s!", fn);
+
+ char buf[2048]; // XXX
+ int header_size = file_read(file, buf, sizeof(buf)).result;
+ kassert(header_size >= (int)sizeof(Elf64_Ehdr));
+
+ const Elf64_Ehdr* eh64 = (const Elf64_Ehdr*)buf;
+ kassert(eh64->e_ident[0] == '\177' && eh64->e_ident[1] == 'E' &&
+ eh64->e_ident[2] == 'L' && eh64->e_ident[3] == 'F');
+
+ #define LOAD_ELF do { \
+ eh = (typeof(eh))buf; \
+ kassert(header_size >= eh->e_phoff + eh->e_phnum*sizeof(*ph)); \
+ ph = (typeof(ph))(buf+eh->e_phoff); \
+ for(int i = 0; i < eh->e_phnum; i++, ph++) { \
+ if(ph->p_type == SHT_PROGBITS && ph->p_memsz) { \
+ kassert(file_pread(file, (char*)(long)ph->p_vaddr, ph->p_filesz, ph->p_offset).result == ph->p_filesz); \
+ memset((char*)(long)ph->p_vaddr+ph->p_filesz, 0, ph->p_memsz-ph->p_filesz); \
+ } \
+ } \
+ } while(0)
+
+ long entry;
+ if(eh64->e_ident[EI_CLASS] == ELFCLASS32)
+ {
+ Elf32_Ehdr* eh;
+ Elf32_Phdr* ph;
+ LOAD_ELF;
+ entry = eh->e_entry;
+ }
+ else
+ {
+ kassert(eh64->e_ident[EI_CLASS] == ELFCLASS64);
+ Elf64_Ehdr* eh;
+ Elf64_Phdr* ph;
+ LOAD_ELF;
+ entry = eh->e_entry;
+ }
+
+ *user64 = eh64->e_ident[EI_CLASS] == ELFCLASS64;
+
+ file_decref(file);
+
+ return entry;
+}