-
Notifications
You must be signed in to change notification settings - Fork 0
/
loader.c
70 lines (57 loc) · 1.42 KB
/
loader.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include "loader.h"
#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#define X86_BOOT_ADDRESS 0x17C00
static void *load_vm(char *img_name, uintptr_t load_addr) {
int fd;
struct stat sb;
void *alloc;
void *program = NULL;
fd = open(img_name, O_RDONLY);
if (fd == -1) {
perror("open");
goto err;
}
if (fstat(fd, &sb) == -1) {
perror("fstat");
goto err;
}
size_t page_size = getpagesize();
void *text_base = (void *)(load_addr & ~(page_size - 1));
alloc = mmap((void *)(load_addr & ~(page_size - 1)), sb.st_size,
PROT_READ | PROT_WRITE | PROT_EXEC,
MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS, -1, 0);
if (alloc == MAP_FAILED) {
perror("mmap");
goto err;
}
if (read(fd, (void *)load_addr, sb.st_size) == -1) {
perror("read");
goto unmap;
}
if (close(fd) == -1) {
perror("close");
goto unmap;
}
return alloc;
unmap:
if (munmap(alloc, sb.st_size) == -1) {
perror("munmap");
exit(EXIT_FAILURE);
}
err:
return NULL;
}
bool init_vm(struct VM *vm, char *img_name) {
void *text = load_vm(img_name, X86_BOOT_ADDRESS);
if (!text)
return false;
vm->text = text;
vm->entry = (void *)X86_BOOT_ADDRESS;
return true;
}