Merge branch 'master' into isa/arm64
[lunaix-os.git] / lunaix-os / includes / lunaix / exebi / elf.h
1 /**
2  * @file elf.h
3  * @author Lunaixsky (lunaxisky@qq.com)
4  * @brief 
5  * @version 0.1
6  * @date 2024-07-05
7  * 
8  * Define generic structure that described in Executable and Linking Format
9  * specification.
10  * 
11  * Define interface on manipulate such structure
12  * 
13  * @copyright Copyright (c) 2024
14  * 
15  */
16
17 #ifndef __LUNAIX_ELF32_H
18 #define __LUNAIX_ELF32_H
19
20 #include <lunaix/types.h>
21 #include <sys/elf.h>
22
23 #define ET_EXEC 2
24 #define ET_DYN 3
25
26 #define PT_LOAD 1
27 #define PT_INTERP 3
28
29 #define PF_X 0x1
30 #define PF_W 0x2
31 #define PF_R 0x4
32
33 #define EV_CURRENT 1
34
35 // [0x7f, 'E', 'L', 'F']
36 #define ELFMAGIC_LE 0x464c457fU
37
38 #define EI_CLASS 4
39 #define EI_DATA 5
40
41 #define NO_LOADER 0
42 #define DEFAULT_LOADER "usr/ld"
43
44 struct elf_ehdr;
45 struct elf_phdr;
46
47 struct elf
48 {
49     const void* elf_file;
50     struct elf_ehdr eheader;
51     struct elf_phdr* pheaders;
52 };
53
54 #define declare_elf32(elf, elf_vfile)                                          \
55     struct elf elf = { .elf_file = elf_vfile, .pheaders = (void*)0 }
56
57 int
58 elf_check_exec(const struct elf* elf, int type);
59
60 int
61 elf_check_arch(const struct elf* elf);
62
63 int
64 elf_open(struct elf* elf, const char* path);
65
66 int
67 elf_openat(struct elf* elf, void* elf_vfile);
68
69 int
70 elf_static_linked(const struct elf* elf);
71
72 int
73 elf_close(struct elf* elf);
74
75 /**
76  * @brief Try to find the PT_INTERP section. If found, copy it's content to
77  * path_out
78  *
79  * @param elf Opened elf32 descriptor
80  * @param path_out
81  * @param len size of path_out buffer
82  * @return int
83  */
84 int
85 elf_find_loader(const struct elf* elf, char* path_out, size_t len);
86
87 int
88 elf_read_ehdr(struct elf* elf);
89
90 int
91 elf_read_phdr(struct elf* elf);
92
93 /**
94  * @brief Estimate how much memeory will be acquired if we load all loadable
95  * sections.、
96  *
97  * @param elf
98  * @return size_t
99  */
100 size_t
101 elf_loadable_memsz(const struct elf* elf);
102
103 #define SIZE_EHDR sizeof(struct elf_ehdr)
104 #define SIZE_PHDR sizeof(struct elf_phdr)
105
106 #endif /* __LUNAIX_ELF32_H */