about summary refs log tree commit diff
path: root/src/tools/miri/tests/native-lib/pass/ptr_read_access.rs
blob: bab73f7cf17824f853dccd3a1d069c01a36bedb8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
//@revisions: trace notrace
//@[trace] only-target: x86_64-unknown-linux-gnu i686-unknown-linux-gnu
//@[trace] compile-flags: -Zmiri-native-lib-enable-tracing
//@compile-flags: -Zmiri-permissive-provenance

fn main() {
    test_access_pointer();
    test_access_simple();
    test_access_nested();
    test_access_static();
}

/// Test function that dereferences an int pointer and prints its contents from C.
fn test_access_pointer() {
    extern "C" {
        fn print_pointer(ptr: *const i32);
    }

    let x = 42;

    unsafe { print_pointer(&x) };
}

/// Test function that dereferences a simple struct pointer and accesses a field.
fn test_access_simple() {
    #[repr(C)]
    struct Simple {
        field: i32,
    }

    extern "C" {
        fn access_simple(s_ptr: *const Simple) -> i32;
    }

    let simple = Simple { field: -42 };

    assert_eq!(unsafe { access_simple(&simple) }, -42);
}

/// Test function that dereferences nested struct pointers and accesses fields.
fn test_access_nested() {
    use std::ptr::NonNull;

    #[derive(Debug, PartialEq, Eq)]
    #[repr(C)]
    struct Nested {
        value: i32,
        next: Option<NonNull<Nested>>,
    }

    extern "C" {
        fn access_nested(n_ptr: *const Nested) -> i32;
    }

    let mut nested_0 = Nested { value: 97, next: None };
    let mut nested_1 = Nested { value: 98, next: NonNull::new(&mut nested_0) };
    let nested_2 = Nested { value: 99, next: NonNull::new(&mut nested_1) };

    assert_eq!(unsafe { access_nested(&nested_2) }, 97);
}

/// Test function that dereferences a static struct pointer and accesses fields.
fn test_access_static() {
    #[repr(C)]
    struct Static {
        value: i32,
        recurse: &'static Static,
    }

    extern "C" {
        fn access_static(n_ptr: *const Static) -> i32;
    }

    static STATIC: Static = Static { value: 9001, recurse: &STATIC };

    assert_eq!(unsafe { access_static(&STATIC) }, 9001);
}