Skip to content

Commit

Permalink
Add example code
Browse files Browse the repository at this point in the history
  • Loading branch information
wenxuanjun committed Nov 3, 2024
1 parent 0d81a00 commit d869320
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 13 deletions.
44 changes: 44 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,47 @@ And use `cbindgen` to generate the header file:
cargo install cbindgen
cbindgen --output elf_parse.h
```

## Example

```c
#include <stdint.h>
#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;
}
}
```
20 changes: 7 additions & 13 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down Expand Up @@ -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);
}
}
Expand Down

0 comments on commit d869320

Please sign in to comment.