cff442c2f806ceee73b793796f57aac26596cb9a
[lunaix-os.git] / lunaix-os / includes / lunaix / elf.h
1 #ifndef __LUNAIX_ELF_H
2 #define __LUNAIX_ELF_H
3
4 #include <lunaix/types.h>
5
6 typedef unsigned int elf32_ptr_t;
7 typedef unsigned short elf32_hlf_t;
8 typedef unsigned int elf32_off_t;
9 typedef unsigned int elf32_swd_t;
10 typedef unsigned int elf32_wrd_t;
11
12 #define ET_NONE 0
13 #define ET_EXEC 2
14
15 #define PT_LOAD 1
16 #define PT_INTERP 3
17
18 #define PF_X 0x1
19 #define PF_W 0x2
20 #define PF_R 0x4
21
22 #define EM_NONE 0
23 #define EM_386 3
24
25 #define EV_CURRENT 1
26
27 // [0x7f, 'E', 'L', 'F']
28 #define ELFMAGIC 0x464c457fU
29 #define ELFCLASS32 1
30 #define ELFCLASS64 2
31 #define ELFDATA2LSB 1
32 #define ELFDATA2MSB 2
33
34 #define EI_CLASS 4
35 #define EI_DATA 5
36
37 struct elf32_ehdr
38 {
39     u8_t e_ident[16];
40     elf32_hlf_t e_type;
41     elf32_hlf_t e_machine;
42     elf32_wrd_t e_version;
43     elf32_ptr_t e_entry;
44     elf32_off_t e_phoff;
45     elf32_off_t e_shoff;
46     elf32_wrd_t e_flags;
47     elf32_hlf_t e_ehsize;
48     elf32_hlf_t e_phentsize;
49     elf32_hlf_t e_phnum;
50     elf32_hlf_t e_shentsize;
51     elf32_hlf_t e_shnum;
52     elf32_hlf_t e_shstrndx;
53 };
54
55 struct elf32_phdr
56 {
57     elf32_wrd_t p_type;
58     elf32_off_t p_offset;
59     elf32_ptr_t p_va;
60     elf32_ptr_t p_pa;
61     elf32_wrd_t p_filesz;
62     elf32_wrd_t p_memsz;
63     elf32_wrd_t p_flags;
64     elf32_wrd_t p_align;
65 };
66
67 struct elf32
68 {
69     void* elf_file;
70     struct elf32_ehdr eheader;
71     struct elf32_phdr* pheaders;
72 };
73
74 #define declare_elf32(elf, elf_vfile)                                          \
75     struct elf32 elf = { .elf_file = elf_vfile, .pheaders = (void*)0 }
76
77 int
78 elf32_open(struct elf32* elf, const char* path);
79
80 int
81 elf32_openat(struct elf32* elf, void* elf_vfile);
82
83 int
84 elf32_static_linked(const struct elf32* elf);
85
86 int
87 elf32_close(struct elf32* elf);
88
89 /**
90  * @brief Try to find the PT_INTERP section. If found, copy it's content to
91  * path_out
92  *
93  * @param elf Opened elf32 descriptor
94  * @param path_out
95  * @param len size of path_out buffer
96  * @return int
97  */
98 int
99 elf32_find_loader(const struct elf32* elf, char* path_out, size_t len);
100
101 int
102 elf32_read_ehdr(struct elf32* elf);
103
104 int
105 elf32_read_phdr(struct elf32* elf);
106
107 /**
108  * @brief Estimate how much memeory will be acquired if we load all loadable
109  * sections.、
110  *
111  * @param elf
112  * @return size_t
113  */
114 size_t
115 elf32_loadable_memsz(const struct elf32* elf);
116
117 int
118 elf32_load(struct load_context* ldctx, const struct elf32* elf);
119
120 #define SIZE_EHDR sizeof(struct elf32_ehdr)
121 #define SIZE_PHDR sizeof(struct elf32_phdr)
122
123 #endif /* __LUNAIX_ELF_H */