elf.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. #include "elf.h"
  2. #include "dragonstub/linux-efi.h"
  3. #include "dragonstub/linux/align.h"
  4. #include "dragonstub/printk.h"
  5. #include "dragonstub/riscv64.h"
  6. #include "dragonstub/types.h"
  7. #include "efidef.h"
  8. #include <efi.h>
  9. #include <efiapi.h>
  10. #include <efidevp.h>
  11. #include <efilib.h>
  12. #include <dragonstub/dragonstub.h>
  13. #include <dragonstub/elfloader.h>
  14. /// @brief 校验ELF文件头
  15. /// @param buf 缓冲区
  16. /// @param bufsize 缓冲区大小
  17. /// @return
  18. static bool verify_ident(const void *buf, u64 bufsize)
  19. {
  20. if (bufsize < EI_NIDENT) {
  21. // 太短,不是ELF
  22. return false;
  23. }
  24. // 检查magic number
  25. for (int i = 0; i < EI_CLASS; i++) {
  26. u8 c = *(u8 *)(buf + i);
  27. if (c != ELFMAG[i]) {
  28. // 不是ELF magic number,跳过
  29. efi_err("ELF magic number not match\n");
  30. return false;
  31. }
  32. }
  33. // verify ELF Version
  34. u8 version = *(u8 *)(buf + EI_VERSION);
  35. if (version != EV_CURRENT) {
  36. efi_err("ELF version not match, expected EV_CURRENT(%d), got %d\n",
  37. EV_CURRENT, version);
  38. // 不是当前版本,跳过
  39. return false;
  40. }
  41. // verify ELF Class
  42. u8 class = *(u8 *)(buf + EI_CLASS);
  43. if (class != ELFCLASS64) {
  44. efi_err("ELF class not match, expected ELFCLASS64(%d), got %d\n",
  45. ELFCLASS64, class);
  46. // 不是64位,跳过
  47. return false;
  48. }
  49. return true;
  50. }
  51. bool elf_check(const void *payload_start, u64 payload_size)
  52. {
  53. // 校验ELF文件头
  54. if (!verify_ident(payload_start, payload_size)) {
  55. return false;
  56. }
  57. // 检查架构
  58. Elf64_Ehdr *ehdr = (Elf64_Ehdr *)payload_start;
  59. #ifdef CONFIG_riscv64
  60. if (ehdr->e_machine != EM_RISCV) {
  61. efi_err("ELF machine not match, expected EM_RISCV(%d), got %d\n",
  62. EM_RISCV, ehdr->e_machine);
  63. return false;
  64. }
  65. #else
  66. // 还没有对当前架构进行检查,抛出编译错误
  67. #error "Unimplement ELF arch test for current cross compile arch"
  68. #endif
  69. return true;
  70. }
  71. /// @brief 获取ELF文件头
  72. /// @param payload_start 文件起始地址
  73. /// @param payload_size 文件大小
  74. /// @param ehdr 返回的ELF文件头
  75. /// @return
  76. efi_status_t elf_get_header(const void *payload_start, u64 payload_size,
  77. Elf64_Ehdr **ehdr)
  78. {
  79. if (!verify_ident(payload_start, payload_size)) {
  80. return EFI_INVALID_PARAMETER;
  81. }
  82. *ehdr = (Elf64_Ehdr *)payload_start;
  83. return EFI_SUCCESS;
  84. }
  85. static void print_elf_info(Elf64_Ehdr *ehdr)
  86. {
  87. efi_info("ELF header:\n");
  88. efi_printk(" e_type: %d\n", ehdr->e_type);
  89. efi_printk(" e_machine: %d\n", ehdr->e_machine);
  90. efi_printk(" e_version: %d\n", ehdr->e_version);
  91. efi_printk(" e_entry: %p\n", ehdr->e_entry);
  92. efi_printk(" e_phoff: %p\n", ehdr->e_phoff);
  93. efi_printk(" e_shoff: %p\n", ehdr->e_shoff);
  94. efi_printk(" e_flags: %d\n", ehdr->e_flags);
  95. efi_printk(" e_ehsize: %d\n", ehdr->e_ehsize);
  96. efi_printk(" e_phentsize: %d\n", ehdr->e_phentsize);
  97. efi_printk(" e_phnum: %d\n", ehdr->e_phnum);
  98. efi_printk(" e_shentsize: %d\n", ehdr->e_shentsize);
  99. efi_printk(" e_shnum: %d\n", ehdr->e_shnum);
  100. efi_printk(" e_shstrndx: %d\n", ehdr->e_shstrndx);
  101. }
  102. static efi_status_t parse_phdrs(const void *payload_start, u64 payload_size,
  103. const Elf64_Ehdr *ehdr, u32 *ret_segments_nr,
  104. Elf64_Phdr **ret_phdr)
  105. {
  106. if (ehdr->e_phnum == 0) {
  107. efi_err("No program header\n");
  108. return EFI_INVALID_PARAMETER;
  109. }
  110. if (ehdr->e_phentsize != sizeof(Elf64_Phdr)) {
  111. efi_err("Invalid program header size: %d, expected %d\n",
  112. ehdr->e_phentsize, sizeof(Elf64_Phdr));
  113. return EFI_INVALID_PARAMETER;
  114. }
  115. u16 phnum = ehdr->e_phnum;
  116. if (phnum == PN_XNUM) {
  117. u64 shoff = ehdr->e_shoff;
  118. if (shoff == 0) {
  119. efi_err("No section header\n");
  120. return EFI_INVALID_PARAMETER;
  121. }
  122. if (shoff + sizeof(Elf64_Shdr) > payload_size) {
  123. efi_err("Section header out of range\n");
  124. return EFI_INVALID_PARAMETER;
  125. }
  126. Elf64_Shdr *shdr = (Elf64_Shdr *)(payload_start + shoff);
  127. phnum = shdr[0].sh_info;
  128. if (phnum == 0) {
  129. efi_err("shdr[0].sh_info indicates no program header\n");
  130. return EFI_INVALID_PARAMETER;
  131. }
  132. }
  133. size_t phoff = ehdr->e_phoff;
  134. size_t phsize = ehdr->e_phentsize;
  135. size_t total_size = phnum * phsize;
  136. if (phoff + total_size > payload_size) {
  137. efi_err("Program header out of range\n");
  138. return EFI_INVALID_PARAMETER;
  139. }
  140. Elf64_Phdr *phdr = (Elf64_Phdr *)(payload_start + phoff);
  141. *ret_segments_nr = phnum;
  142. *ret_phdr = phdr;
  143. return EFI_SUCCESS;
  144. }
  145. /*
  146. * Distro versions of GRUB may ignore the BSS allocation entirely (i.e., fail
  147. * to provide space, and fail to zero it). Check for this condition by double
  148. * checking that the first and the last byte of the image are covered by the
  149. * same EFI memory map entry.
  150. */
  151. static bool check_image_region(u64 base, u64 size)
  152. {
  153. struct efi_boot_memmap *map;
  154. efi_status_t status;
  155. bool ret = false;
  156. u64 map_offset;
  157. status = efi_get_memory_map(&map, false);
  158. if (status != EFI_SUCCESS)
  159. return false;
  160. for (map_offset = 0; map_offset < map->map_size;
  161. map_offset += map->desc_size) {
  162. efi_memory_desc_t *md = (void *)map->map + map_offset;
  163. u64 end = md->PhysicalStart + md->NumberOfPages * EFI_PAGE_SIZE;
  164. /*
  165. * Find the region that covers base, and return whether
  166. * it covers base+size bytes.
  167. */
  168. if (base >= md->PhysicalStart && base < end) {
  169. ret = (base + size) <= end;
  170. break;
  171. }
  172. }
  173. efi_bs_call(FreePool, map);
  174. return ret;
  175. }
  176. /**
  177. * efi_remap_image_all_rwx - Remap a loaded image with the appropriate permissions
  178. * for code and data
  179. *
  180. * @image_base: the base of the image in memory
  181. * @alloc_size: the size of the area in memory occupied by the image
  182. *
  183. * efi_remap_image() uses the EFI memory attribute protocol to remap the code
  184. * region of the loaded image read-only/executable, and the remainder
  185. * read-write/non-executable. The code region is assumed to start at the base
  186. * of the image, and will therefore cover the PE/COFF header as well.
  187. */
  188. void efi_remap_image_all_rwx(unsigned long image_base, unsigned alloc_size)
  189. {
  190. efi_guid_t guid = EFI_MEMORY_ATTRIBUTE_PROTOCOL_GUID;
  191. efi_memory_attribute_protocol_t *memattr;
  192. efi_status_t status;
  193. u64 attr;
  194. /*
  195. * If the firmware implements the EFI_MEMORY_ATTRIBUTE_PROTOCOL, let's
  196. * invoke it to remap the text/rodata region of the decompressed image
  197. * as read-only and the data/bss region as non-executable.
  198. */
  199. status = efi_bs_call(LocateProtocol, &guid, NULL, (void **)&memattr);
  200. if (status != EFI_SUCCESS)
  201. return;
  202. // Get the current attributes for the entire region
  203. status = memattr->get_memory_attributes(memattr, image_base, alloc_size,
  204. &attr);
  205. if (status != EFI_SUCCESS) {
  206. efi_warn(
  207. "Failed to retrieve memory attributes for image region: 0x%lx\n",
  208. status);
  209. return;
  210. }
  211. efi_debug("Current attributes for image region: 0x%lx\n", attr);
  212. // If the entire region was already mapped as non-exec, clear the
  213. // attribute from the code region. Otherwise, set it on the data
  214. // region.
  215. if (attr & EFI_MEMORY_XP) {
  216. status = memattr->clear_memory_attributes(
  217. memattr, image_base, alloc_size, EFI_MEMORY_XP);
  218. if (status != EFI_SUCCESS)
  219. efi_warn("Failed to remap region executable\n");
  220. }
  221. if (attr & EFI_MEMORY_WP) {
  222. status = memattr->clear_memory_attributes(
  223. memattr, image_base, alloc_size, EFI_MEMORY_WP);
  224. if (status != EFI_SUCCESS)
  225. efi_warn("Failed to remap region writable\n");
  226. }
  227. if (attr & EFI_MEMORY_RP) {
  228. status = memattr->clear_memory_attributes(
  229. memattr, image_base, alloc_size, EFI_MEMORY_RP);
  230. if (status != EFI_SUCCESS)
  231. efi_warn("Failed to remap region readable\n");
  232. }
  233. }
  234. efi_status_t efi_allocate_kernel_memory(const Elf64_Phdr *phdr_start,
  235. u32 phdrs_nr, u64 *ret_paddr,
  236. u64 *ret_size, u64 *ret_min_paddr,
  237. u64 *ret_max_paddr, u64 *ret_min_vaddr)
  238. {
  239. efi_status_t status = EFI_SUCCESS;
  240. const u64 KERNEL_MEM_ALIGN = 1 << 21; // 2MB
  241. const Elf64_Phdr *phdr = phdr_start;
  242. u64 min_paddr = UINT64_MAX;
  243. u64 max_paddr = 0;
  244. u64 min_vaddr = UINT64_MAX;
  245. for (u32 i = 0; i < phdrs_nr; ++i, ++phdr) {
  246. if (phdr->p_type != PT_LOAD) {
  247. continue;
  248. }
  249. if (phdr->p_align & !EFI_PAGE_SIZE) {
  250. efi_err("ELF segment alignment should be multiple of EFI_PAGE_SIZE(%d), but got %d\n",
  251. EFI_PAGE_SIZE, phdr->p_align);
  252. return EFI_INVALID_PARAMETER;
  253. }
  254. min_paddr = min(min_paddr, (u64)phdr->p_paddr);
  255. min_vaddr = min(min_vaddr, (u64)phdr->p_vaddr);
  256. max_paddr =
  257. max(max_paddr, (u64)(phdr->p_paddr + phdr->p_memsz));
  258. }
  259. if (min_paddr & (KERNEL_MEM_ALIGN - 1)) {
  260. efi_err("min_paddr should be aligned to KERNEL_MEM_ALIGN(%d), but got %p\n",
  261. KERNEL_MEM_ALIGN, min_paddr);
  262. return EFI_INVALID_PARAMETER;
  263. }
  264. u64 mem_size = ALIGN_UP(max_paddr - min_paddr, KERNEL_MEM_ALIGN);
  265. status = efi_allocate_pages_aligned(mem_size, ret_paddr, UINT64_MAX,
  266. KERNEL_MEM_ALIGN, EfiLoaderData);
  267. // status = efi_allocate_pages_exact(mem_size, paddr);
  268. if (status != EFI_SUCCESS) {
  269. efi_err("Failed to allocate pages for ELF segment: status: %d, page_size=%d, min_paddr=%p, max_paddr=%p, mem_size=%d. Maybe an OOM error or section overlaps.\n",
  270. status, KERNEL_MEM_ALIGN, ret_paddr, max_paddr,
  271. mem_size);
  272. return status;
  273. }
  274. *ret_size = mem_size;
  275. *ret_min_paddr = min_paddr;
  276. *ret_max_paddr = max_paddr;
  277. *ret_min_vaddr = min_vaddr;
  278. efi_info("Allocated kernel memory: paddr=%p, mem_size= %d bytes\n",
  279. *ret_paddr, mem_size);
  280. // zeroed the memory
  281. memset((void *)(*ret_paddr), 0, mem_size);
  282. efi_remap_image_all_rwx(*ret_paddr, mem_size);
  283. return EFI_SUCCESS;
  284. }
  285. static efi_status_t load_program(const void *payload_start, u64 payload_size,
  286. const Elf64_Phdr *phdr_start, u32 phdrs_nr,
  287. u64 *ret_program_mem_paddr,
  288. u64 *ret_program_mem_size, u64 *ret_min_paddr,
  289. u64 *ret_min_vaddr)
  290. {
  291. efi_status_t status = EFI_SUCCESS;
  292. u64 allocated_paddr = 0;
  293. u64 allocated_size = 0;
  294. u64 min_paddr = 0;
  295. u64 max_paddr = 0;
  296. u64 min_vaddr = 0;
  297. status = efi_allocate_kernel_memory(phdr_start, phdrs_nr,
  298. &allocated_paddr, &allocated_size,
  299. &min_paddr, &max_paddr, &min_vaddr);
  300. if (status != EFI_SUCCESS) {
  301. efi_err("Failed to allocate kernel memory\n");
  302. return status;
  303. }
  304. // 清空内存
  305. memset((void *)allocated_paddr, 0, allocated_size);
  306. const Elf64_Phdr *phdr = phdr_start;
  307. for (u32 i = 0; i < phdrs_nr; ++i, ++phdr) {
  308. if (phdr->p_type != PT_LOAD) {
  309. continue;
  310. }
  311. if (phdr->p_align & !EFI_PAGE_SIZE) {
  312. efi_err("ELF segment alignment should be multiple of EFI_PAGE_SIZE(%d), but got %d\n",
  313. EFI_PAGE_SIZE, phdr->p_align);
  314. status = EFI_INVALID_PARAMETER;
  315. goto failed;
  316. }
  317. u64 paddr = phdr->p_paddr;
  318. u64 mem_size = phdr->p_memsz;
  319. u64 file_size = phdr->p_filesz;
  320. u64 file_offset = phdr->p_offset;
  321. // efi_debug(
  322. // "loading segment: paddr=%p, mem_size=%d, file_size=%d\n",
  323. // paddr, mem_size, file_size);
  324. if (file_offset + file_size > payload_size) {
  325. status = EFI_INVALID_PARAMETER;
  326. goto failed;
  327. }
  328. if (mem_size < file_size) {
  329. status = EFI_INVALID_PARAMETER;
  330. goto failed;
  331. }
  332. if (mem_size == 0) {
  333. continue;
  334. }
  335. memcpy((void *)(allocated_paddr + (paddr - min_paddr)),
  336. payload_start + file_offset, file_size);
  337. // efi_debug(
  338. // "segment loaded: file_offset: %p paddr=%p, mem_size=%p, file_size=%p\n",
  339. // file_offset, paddr, mem_size, file_size);
  340. }
  341. *ret_program_mem_paddr = allocated_paddr;
  342. *ret_program_mem_size = allocated_size;
  343. *ret_min_paddr = min_paddr;
  344. *ret_min_vaddr = min_vaddr;
  345. return EFI_SUCCESS;
  346. failed:
  347. efi_free(allocated_size, allocated_paddr);
  348. return status;
  349. }
  350. efi_status_t load_elf(struct payload_info *payload_info)
  351. {
  352. const void *payload_start = (void *)payload_info->payload_addr;
  353. u64 payload_size = payload_info->payload_size;
  354. Elf64_Ehdr *ehdr = NULL;
  355. efi_status_t status =
  356. elf_get_header(payload_start, payload_size, &ehdr);
  357. if (status != EFI_SUCCESS) {
  358. efi_err("Failed to get ELF header\n");
  359. return status;
  360. }
  361. ASSERT(ehdr != NULL);
  362. print_elf_info(ehdr);
  363. u32 phdrs_nr = 0;
  364. Elf64_Phdr *phdr_start = NULL;
  365. status = parse_phdrs(payload_start, payload_size, ehdr, &phdrs_nr,
  366. &phdr_start);
  367. if (status != EFI_SUCCESS) {
  368. efi_err("Failed to parse ELF segments\n");
  369. return status;
  370. }
  371. efi_debug("program headers: %d\n", phdrs_nr);
  372. u64 program_paddr = 0;
  373. u64 program_size = 0;
  374. u64 image_link_base_paddr = 0;
  375. u64 image_link_base_vaddr = 0;
  376. load_program(payload_start, payload_size, phdr_start, phdrs_nr,
  377. &program_paddr, &program_size, &image_link_base_paddr,
  378. &image_link_base_vaddr);
  379. payload_info->loaded_paddr = program_paddr;
  380. payload_info->loaded_size = program_size;
  381. payload_info->kernel_entry =
  382. ehdr->e_entry - image_link_base_vaddr + program_paddr;
  383. efi_info("loaded_paddr: %p\n", payload_info->loaded_paddr);
  384. efi_info("loaded_size: %p\n", payload_info->loaded_size);
  385. efi_info("ehdr->e_entry: %lx\n", ehdr->e_entry);
  386. efi_info("image_link_base_paddr: %lx\n", image_link_base_paddr);
  387. efi_info("kernel_entry: %lx\n", payload_info->kernel_entry);
  388. // 处理权限问题
  389. efi_remap_image_all_rwx(program_paddr, program_size);
  390. extern void _start(void);
  391. extern void _image_end(void);
  392. u64 image_size = (u64)&_image_end - (u64)&_start;
  393. efi_debug("image_size: %d\n", image_size);
  394. efi_remap_image_all_rwx((u64)&_start, (image_size + 4095) & ~4095);
  395. // 添加地址到efi configuration table
  396. struct dragonstub_payload_efi *tbl = NULL;
  397. status = efi_bs_call(AllocatePool, EfiLoaderData,
  398. sizeof(struct dragonstub_payload_efi),
  399. (void **)&tbl);
  400. if (status != EFI_SUCCESS) {
  401. efi_err("Failed to allocate memory for dragonstub_payload_efi\n");
  402. return status;
  403. }
  404. tbl->loaded_addr = payload_info->loaded_paddr;
  405. tbl->size = payload_info->loaded_size;
  406. efi_guid_t dragonstub_payload_efi_guid =
  407. DRAGONSTUB_EFI_PAYLOAD_EFI_GUID;
  408. status = efi_bs_call(InstallConfigurationTable,
  409. &dragonstub_payload_efi_guid, tbl);
  410. if (status != EFI_SUCCESS) {
  411. efi_err("Failed to install dragonstub_payload_efi\n");
  412. return status;
  413. }
  414. return EFI_SUCCESS;
  415. }