From d869320da1a689b9af9298ce39d50174dfee2ef0 Mon Sep 17 00:00:00 2001 From: wenxuanjun Date: Sun, 3 Nov 2024 08:28:17 +0800 Subject: [PATCH] Add example code --- README.md | 44 ++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 20 +++++++------------- 2 files changed, 51 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 1f8dff6..3fcd613 100644 --- a/README.md +++ b/README.md @@ -24,3 +24,47 @@ And use `cbindgen` to generate the header file: cargo install cbindgen cbindgen --output elf_parse.h ``` + +## Example + +```c +#include +#include "elf_parser.h" + +extern void *page_table; + +void segment_callback(struct Segment segment) { + printk("Segment address: 0x%lx\n", segment.address); + printk("Segment size: %lu bytes\n", segment.size); + alloc_and_map(page_table, segment.address, segment.size); + write_to_mapped_address(page_table, segment.data, segment.size, segment.address); +} + +void elf_load_example() { + const uint8_t elf_data[] = {}; + size_t elf_size = sizeof(elf_data); + + struct ElfParseResult result = parse_elf(elf_data, elf_size, segment_callback); + + switch (result.tag) { + case EntryPoint: + printk("ELF Entry Point: 0x%lx\n", result.entry_point); + break; + case InvalidElfData: + printk("Invalid ELF data.\n"); + break; + case ElfContainsNoSegments: + printk("ELF contains no segments.\n"); + break; + case FailedToGetSegmentData: + printk("Failed to get segment data.\n"); + break; + case AllocFunctionNotProvided: + printk("Allocation function not provided.\n"); + break; + default: + printk("Unknown error.\n"); + break; + } +} +``` diff --git a/src/lib.rs b/src/lib.rs index 52fbff4..3ecae9d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -15,21 +15,11 @@ unsafe fn panic(_info: &PanicInfo) -> ! { #[repr(C)] pub struct Segment { - address: u64, - size: u64, + address: usize, + size: usize, data: *const u8, } -impl Segment { - pub fn new(address: u64, size: u64, data: *const u8) -> Self { - Self { - address, - size, - data, - } - } -} - #[repr(C)] pub enum ElfParseResult { EntryPoint(usize), @@ -64,7 +54,11 @@ pub unsafe extern "C" fn parse_elf( Err(_) => return ElfParseResult::FailedToGetSegmentData, }; - let segment = Segment::new(header.p_vaddr, header.p_memsz, data.as_ptr()); + let segment = Segment { + address: header.p_vaddr as usize, + size: header.p_memsz as usize, + data: data.as_ptr(), + }; mapping_callback(segment); } }