guest_ptr/
guest_ptr.rs

1use panda::mem::{map_memory, physical_memory_write, PAGE_SIZE};
2use panda::prelude::*;
3use panda::{GuestPtr, GuestType};
4
5#[derive(GuestType, Debug, PartialEq)]
6struct Test {
7    x: u32,
8    y: u32,
9}
10
11const ADDRESS: target_ptr_t = 0x1000;
12
13#[panda::after_machine_init]
14fn setup(_: &mut CPUState) {
15    // Map 2MB memory for this emulation
16    map_memory("mymem", 2 * 1024 * PAGE_SIZE, ADDRESS).unwrap();
17
18    // Write code into memory
19    physical_memory_write(ADDRESS, b"\x34\x12\x00\x00\x20\x00\x00\x00");
20
21    // read memory back using GuestPtr
22    let ptr: GuestPtr<u32> = ADDRESS.into();
23
24    assert_eq!(*ptr, 0x1234);
25    assert_eq!(*ptr.offset(1), 0x20);
26    println!("u32 ptr read success!");
27
28    let mut ptr = ptr.cast::<Test>();
29    assert_eq!(*ptr, Test { x: 0x1234, y: 0x20 });
30    println!("Struct read success!");
31
32    ptr.write(|test| {
33        test.x = 0x2345;
34        test.y = 0x21;
35    });
36
37    assert_eq!(*ptr, Test { x: 0x2345, y: 0x21 });
38    println!("Write to GuestPtr cache success");
39
40    ptr.clear_cache();
41
42    assert_eq!(*ptr, Test { x: 0x2345, y: 0x21 });
43    println!("Write to memory success");
44}
45
46fn main() {
47    Panda::new().arch(panda::Arch::x86_64).configurable().run();
48}