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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
|
#include <posix/unistd.h>
#include <posix/fcntl.h>
#include <kjarna/interface.h>
#include <libc/string.h>
#include <libc/stdio.h>
#include <libc/stdlib.h>
#include <lib/elf.h>
#include <posix/unistd.h>
#include <posix/sys/mman.h>
#include "kjarna_efi.h"
#include "config.h"
#include <efi/error.h>
static int create_image_buffer(int fd, struct image_buffer *buffer)
{
if ((buffer->length = elf64_size_fd(fd)) == 0)
{
return -1;
}
printf("creating image buffer, %d bytes\n", buffer->length);
if((buffer->base = mmap(nullptr, buffer->length, 0, 0, -1, 0)) == MAP_FAILED)
{
buffer->length = 0;
buffer->base = nullptr;
return -1;
}
printf("image buffer base %p\n", buffer->base);
return 0;
}
static struct image_buffer load_image(void)
{
const char *image_entry_path = SERVICE_FILE_PATH;
int image_fd;
struct image_buffer buffer = { nullptr, 0 };
if ((image_fd = open(image_entry_path, O_RDONLY, 0)) == -1)
{
return buffer;
}
if (!elf64_validate_fd(image_fd, ET_DYN, EM_X86_64))
{
return buffer;
}
if (create_image_buffer(image_fd, &buffer) < 0)
{
return buffer;
}
if (buffer.base != nullptr && elf64_load_segments(image_fd, buffer.length, buffer.base) < 0)
{
printf("error detected: buffer {base: %p, length: %zu}\n", buffer.base, buffer.length);
munmap(buffer.base, buffer.length);
buffer.base = nullptr;
}
close(image_fd);
return buffer;
}
kjarna_image_entry_func *image_entry_addr(struct image_buffer *buffer)
{
if (buffer->base == nullptr)
{
return nullptr;
}
Elf64_Ehdr *ehdr = (Elf64_Ehdr *)buffer->base;
return (kjarna_image_entry_func *)(buffer->base + ehdr->e_entry);
}
struct kjarna_boot_image get_boot_image(void)
{
struct kjarna_boot_image image =
{
{ nullptr, 0 },
nullptr
};
image.buffer = load_image();
if (image.buffer.base != nullptr)
{
image.entry = image_entry_addr(&image.buffer);
}
return image;
}
|