elf.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  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. const Elf64_Phdr *phdr = phdr_start;
  305. for (u32 i = 0; i < phdrs_nr; ++i, ++phdr) {
  306. if (phdr->p_type != PT_LOAD) {
  307. continue;
  308. }
  309. if (phdr->p_align & !EFI_PAGE_SIZE) {
  310. efi_err("ELF segment alignment should be multiple of EFI_PAGE_SIZE(%d), but got %d\n",
  311. EFI_PAGE_SIZE, phdr->p_align);
  312. status = EFI_INVALID_PARAMETER;
  313. goto failed;
  314. }
  315. u64 paddr = phdr->p_paddr;
  316. u64 mem_size = phdr->p_memsz;
  317. u64 file_size = phdr->p_filesz;
  318. u64 file_offset = phdr->p_offset;
  319. // efi_debug(
  320. // "loading segment: paddr=%p, mem_size=%d, file_size=%d\n",
  321. // paddr, mem_size, file_size);
  322. if (file_offset + file_size > payload_size) {
  323. status = EFI_INVALID_PARAMETER;
  324. goto failed;
  325. }
  326. if (mem_size < file_size) {
  327. status = EFI_INVALID_PARAMETER;
  328. goto failed;
  329. }
  330. if (mem_size == 0) {
  331. continue;
  332. }
  333. memcpy((void *)(allocated_paddr + (paddr - min_paddr)),
  334. payload_start + file_offset, file_size);
  335. // efi_debug(
  336. // "segment loaded: paddr=%p, mem_size=%d, file_size=%d\n",
  337. // paddr, mem_size, file_size);
  338. }
  339. *ret_program_mem_paddr = allocated_paddr;
  340. *ret_program_mem_size = allocated_size;
  341. *ret_min_paddr = min_paddr;
  342. *ret_min_vaddr = min_vaddr;
  343. return EFI_SUCCESS;
  344. failed:
  345. efi_free(allocated_size, allocated_paddr);
  346. return status;
  347. }
  348. efi_status_t load_elf(struct payload_info *payload_info)
  349. {
  350. const void *payload_start = (void *)payload_info->payload_addr;
  351. u64 payload_size = payload_info->payload_size;
  352. Elf64_Ehdr *ehdr = NULL;
  353. efi_status_t status =
  354. elf_get_header(payload_start, payload_size, &ehdr);
  355. if (status != EFI_SUCCESS) {
  356. efi_err("Failed to get ELF header\n");
  357. return status;
  358. }
  359. ASSERT(ehdr != NULL);
  360. print_elf_info(ehdr);
  361. u32 phdrs_nr = 0;
  362. Elf64_Phdr *phdr_start = NULL;
  363. status = parse_phdrs(payload_start, payload_size, ehdr, &phdrs_nr,
  364. &phdr_start);
  365. if (status != EFI_SUCCESS) {
  366. efi_err("Failed to parse ELF segments\n");
  367. return status;
  368. }
  369. efi_debug("program headers: %d\n", phdrs_nr);
  370. u64 program_paddr = 0;
  371. u64 program_size = 0;
  372. u64 image_link_base_paddr = 0;
  373. u64 image_link_base_vaddr = 0;
  374. load_program(payload_start, payload_size, phdr_start, phdrs_nr,
  375. &program_paddr, &program_size, &image_link_base_paddr,
  376. &image_link_base_vaddr);
  377. payload_info->loaded_paddr = program_paddr;
  378. payload_info->loaded_size = program_size;
  379. payload_info->kernel_entry =
  380. ehdr->e_entry - image_link_base_vaddr + program_paddr;
  381. efi_info("loaded_paddr: %p\n", payload_info->loaded_paddr);
  382. efi_info("loaded_size: %p\n", payload_info->loaded_size);
  383. efi_info("ehdr->e_entry: %lx\n", ehdr->e_entry);
  384. efi_info("image_link_base_paddr: %lx\n", image_link_base_paddr);
  385. efi_info("kernel_entry: %lx\n", payload_info->kernel_entry);
  386. // 处理权限问题
  387. efi_remap_image_all_rwx(program_paddr, program_size);
  388. extern void _start(void);
  389. extern void _image_end(void);
  390. u64 image_size = (u64)&_image_end - (u64)&_start;
  391. efi_debug("image_size: %d\n", image_size);
  392. efi_remap_image_all_rwx((u64)&_start, (image_size + 4095) & ~4095);
  393. // 添加地址到efi configuration table
  394. struct dragonstub_payload_efi *tbl = NULL;
  395. status = efi_bs_call(AllocatePool, EfiLoaderData,
  396. sizeof(struct dragonstub_payload_efi),
  397. (void **)&tbl);
  398. if (status != EFI_SUCCESS) {
  399. efi_err("Failed to allocate memory for dragonstub_payload_efi\n");
  400. return status;
  401. }
  402. tbl->payload_addr = payload_info->payload_addr;
  403. tbl->payload_size = payload_info->payload_size;
  404. efi_guid_t dragonstub_payload_efi_guid =
  405. DRAGONSTUB_EFI_PAYLOAD_EFI_GUID;
  406. status = efi_bs_call(InstallConfigurationTable,
  407. &dragonstub_payload_efi_guid, tbl);
  408. if (status != EFI_SUCCESS) {
  409. efi_err("Failed to install dragonstub_payload_efi\n");
  410. return status;
  411. }
  412. return EFI_SUCCESS;
  413. }