ctest 0.5.1

Automated testing of FFI bindings in Rust.
Documentation
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
/* This file was autogenerated by ctest; do not modify directly */
{#- ↑ Doesn't apply here, this is the template! +#}

{%- let ctx = self.template +%}
{%- let ctest_extern = self.extern_keyword +%}

/// As this file is sometimes built using rustc, crate level attributes
/// are not allowed at the top-level, so we hack around this by keeping it
/// inside of a module.
mod generated_tests {
    #![allow(non_snake_case)]
    // FIXME: rustc raises this lint on `#[non_exhaustive]` structs, even via a pointer. Once
    // this is fixed we should deny it.
    #![allow(improper_ctypes)]
    #![deny(improper_ctypes_definitions)]
    #[allow(unused_imports)]
    use std::ffi::{CStr, c_int, c_char, c_uint};
    use std::fmt::{Debug, Write};
    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
    #[allow(unused_imports)]
    use std::{mem, ptr, slice};
    #[allow(unused_imports)]
    use std::mem::{MaybeUninit, offset_of};

    use super::*;

    pub static FAILED: AtomicBool = AtomicBool::new(false);
    pub static NTESTS: AtomicUsize = AtomicUsize::new(0);

    /// Check that the value returned from the Rust and C side in a certain test is equivalent.
    ///
    /// Internally it will remember which checks failed and how many tests have been run.
    fn check_same<T: PartialEq + Debug>(rust: T, c: T, attr: &str) {
        if rust != c {
            eprintln!("bad {attr}: rust: {rust:?} != c {c:?}");
            FAILED.store(true, Ordering::Relaxed);
        } else {
            NTESTS.fetch_add(1, Ordering::Relaxed);
        }
    }

    fn check_same_bytes(rust: &[u8], c: &[u8], attr: &str) {
        if rust == c {
            NTESTS.fetch_add(1, Ordering::Relaxed);
            return;
        }

        FAILED.store(true, Ordering::Relaxed);
        // Buffer to a string so we don't write individual bytes to stdio
        let mut s = String::new();
        if rust.len() == c.len() {
            for (i, (&rb, &cb)) in rust.iter().zip(c.iter()).enumerate() {
                if rb != cb {
                    writeln!(
                        s, "bad {attr} at byte {i}: rust: {rb:?} ({rb:#x}) != c {cb:?} ({cb:#x})"
                    ).unwrap();
                    break;
                }
            }
        } else {
            writeln!(s, "bad {attr}: rust len {} != c len {}", rust.len(), c.len()).unwrap();
        }

        write!(s, "    rust bytes:").unwrap();
        for b in rust {
            write!(s, " {b:02x}").unwrap();
        }
        write!(s, "\n    c bytes:   ").unwrap();
        for b in c {
            write!(s, " {b:02x}").unwrap();
        }
        eprintln!("{s}");
    }


/* Test that the string constant is the same in both Rust and C.
 * While fat pointers can't be translated, we instead use * const c_char.
 */
{%- for const_cstr in ctx.const_cstr_tests +%}

    pub fn {{ const_cstr.test_name }}() {
        {{ ctest_extern }} "C" {
            fn ctest_const_cstr__{{ const_cstr.id }}() -> *const c_char;
        }

        {# /* SAFETY: we assume that `c_char` pointer consts are for C strings. */ #}
        let r_val = unsafe {
            let r_ptr: *const c_char = {{ const_cstr.rust_val }};
            assert!(!r_ptr.is_null(), "const `{{ const_cstr.rust_val }}` is null");
            CStr::from_ptr(r_ptr)
        };

        {# /* SAFETY: FFI call returns a valid C string. */ #}
        let c_val = unsafe {
            let c_ptr: *const c_char = ctest_const_cstr__{{ const_cstr.id }}();
            CStr::from_ptr(c_ptr)
        };

        check_same(r_val, c_val, "const `{{ const_cstr.rust_val }}` string");
    }
{%- endfor +%}


/* Test that the value of the constant is the same in both Rust and C.
 *
 * This performs a byte by byte comparison of the constant value.
 */
{%- for constant in ctx.const_tests +%}

    pub fn {{ constant.test_name }}() {
        type T = {{ constant.rust_ty }};
        {{ ctest_extern }} "C" {
            fn ctest_const__{{ constant.id }}() -> *const T;
        }

        {#
            /* HACK: The slices may contain uninitialized data! We do this because
             * there isn't a good way to recursively iterate all fields. */
        #}

        let r_val: T = {{ constant.rust_val }};
        let r_bytes = unsafe {
            slice::from_raw_parts(ptr::from_ref(&r_val).cast::<u8>(), size_of::<T>())
        };

        let c_bytes = unsafe {
            let c_ptr: *const T = ctest_const__{{ constant.id }}();
            slice::from_raw_parts(c_ptr.cast::<u8>(), size_of::<T>())
        };

        check_same_bytes(r_bytes, c_bytes, "`{{ constant.rust_val }}` value");
    }
{%- endfor +%}


/* Compare the size and alignment of the type in Rust and C, making sure they are the same. */
{%- for item in ctx.size_align_tests +%}

    pub fn {{ item.test_name }}() {
        {{ ctest_extern }} "C" {
            fn ctest_size_of__{{ item.id }}() -> u64;
            fn ctest_align_of__{{ item.id }}() -> u64;
        }

        let rust_size = size_of::<{{ item.rust_ty }}>() as u64;
        let c_size = unsafe { ctest_size_of__{{ item.id }}() };

        let rust_align = align_of::<{{ item.rust_ty }}>() as u64;
        let c_align = unsafe { ctest_align_of__{{ item.id }}() };

        check_same(rust_size, c_size, "`{{ item.id }}` size");
        check_same(rust_align, c_align, "`{{ item.id }}` align");
    }
{%- endfor +%}


/* Make sure that the signededness of a type alias in Rust and C is the same.
 *
 * This is done by casting 0 to that type and flipping all of its bits. For unsigned types,
 * this would result in a value larger than zero. For signed types, this results in a value
 * smaller than 0.
 */
{%- for alias in ctx.signededness_tests +%}

    pub fn {{ alias.test_name }}() {
        {{ ctest_extern }} "C" {
            fn ctest_signededness_of__{{ alias.id }}() -> u32;
        }
        let all_ones = !(0 as {{ alias.id }});
        let all_zeros = 0 as {{ alias.id }};
        let c_is_signed = unsafe { ctest_signededness_of__{{ alias.id }}() };

        check_same((all_ones < all_zeros) as u32, c_is_signed, "`{{ alias.id }}` signed");
    }
{%- endfor +%}


/* Make sure that the offset and size of a field in a struct/union is the same. */
{%- for item in ctx.field_size_offset_tests +%}

    pub fn {{ item.test_name }}() {
        {{ ctest_extern }} "C" {
            fn ctest_offset_of__{{ item.id }}__{{ item.field.ident() }}() -> u64;
            fn ctest_size_of__{{ item.id }}__{{ item.field.ident() }}() -> u64;
        }

        let uninit_ty = MaybeUninit::<{{ item.id }}>::zeroed();
        let uninit_ty = uninit_ty.as_ptr();

        {# /* SAFETY: we assume the field access doesn't wrap */ #}
        let ty_ptr = unsafe { &raw const (*uninit_ty).{{ item.field.rust_ident() }}   };
        {# /* SAFETY: we assume that all zeros is a valid bitpattern for `ty_ptr`, otherwise the
            * test should be skipped. */ #}
        let val = unsafe { ty_ptr.read_unaligned() };

        {# /* SAFETY: FFI call with no preconditions */ #}
        let ctest_field_offset = unsafe { ctest_offset_of__{{ item.id }}__{{ item.field.ident() }}() };
        check_same(offset_of!({{ item.id }}, {{ item.field.rust_ident() }}) as u64, ctest_field_offset,
            "field offset `{{ item.field.rust_ident() }}` of `{{ item.id }}`");
        {# /* SAFETY: FFI call with no preconditions */ #}
        let ctest_field_size = unsafe { ctest_size_of__{{ item.id }}__{{ item.field.ident() }}() };
        check_same(size_of_val(&val) as u64, ctest_field_size,
            "field size `{{ item.field.rust_ident() }}` of `{{ item.id }}`");
    }
{%- endfor +%}


/* Tests if the pointer to the field is the same in Rust and C. */
{%- for item in ctx.field_ptr_tests +%}

    pub fn {{ item.test_name }}() {
        {{ ctest_extern }} "C" {
            fn ctest_field_ptr__{{ item.id }}__{{ item.field.ident() }}(a: *const {{ item.id }}) -> *mut u8;
        }

        let uninit_ty = MaybeUninit::<{{ item.id }}>::zeroed();
        let ty_ptr = uninit_ty.as_ptr();
        // SAFETY: We don't read `field_ptr`, only compare the pointer itself.
        // The assumption is made that this does not wrap the address space.
        let field_ptr = unsafe { &raw const ((*ty_ptr).{{ item.field.rust_ident() }}) };

        // SAFETY: FFI call with no preconditions
        let ctest_field_ptr = unsafe { ctest_field_ptr__{{ item.id }}__{{ item.field.ident() }}(ty_ptr) };
        check_same(field_ptr.cast(), ctest_field_ptr,
            "field pointer access `{{ item.field.rust_ident() }}` of `{{ item.id }}`");
    }

{%- endfor +%}

/* Generates a padding map for a specific type.
 *
 * Essentially, it returns a list of bytes, whose length is equal to the size of the type in
 * bytes. Each element corresponds to a byte and has two values. `true` if the byte is padding,
 * and `false` if the byte is not padding.
 *
 * For aliases we assume that there are no padding bytes, for structs and unions,
 * if there are no fields, then everything is padding, if there are fields, then we have to
 * go through each field and figure out the padding.
 */
{%- for item in ctx.roundtrip_tests +%}

    fn roundtrip_padding__{{ item.id }}() -> Vec<bool> {
        if {{ item.fields.len() }} == 0 {
            {# /* FIXME(ctest): What if it's an alias to a struct/union? */ #}
            return vec![!{{ item.is_alias }}; size_of::<{{ item.id }}>()]
        }

        {# /* If there are no fields, v and bar become unused. */ #}
        #[allow(unused_mut)]
        let mut v = Vec::<(usize, usize)>::new();
        #[allow(unused_variables)]
        let bar = MaybeUninit::<{{ item.id }}>::zeroed();
        #[allow(unused_variables)]
        let bar = bar.as_ptr();
        {%- for field in item.fields +%}

        let ty_ptr = unsafe { &raw const ((*bar).{{ field.rust_ident() }}) };
        let val = unsafe { ty_ptr.read_unaligned() };

        let size = size_of_val(&val);
        let off = offset_of!({{ item.id }}, {{ field.rust_ident() }});
        v.push((off, size));
        {%- endfor +%}
        {# /* This vector contains `true` if the byte is padding and `false` if the byte is not
         * padding. Initialize all bytes as:
         *  - padding if we have fields, this means that only the fields will be checked
         *  - no-padding if we have a type alias: if this causes problems the type alias should
         *    be skipped */ #}
        let mut is_padding_byte = vec![true; size_of::<{{ item.id }}>()];
        for (off, size) in &v {
            for i in 0..*size {
                is_padding_byte[off + i] = false;
            }
        }
        is_padding_byte
    }

    {# /* Tests whether a type alias when passed to C and back to Rust remains unchanged.
     *
     * It checks if the size is the same as well as if the padding bytes are all in the
     * correct place. For this test to be sound, `T` must be valid for any bitpattern. */ #}
    pub fn {{ item.test_name }}() {
        type U = {{ item.id }};
        {{ ctest_extern }} "C" {
            fn ctest_size_of__{{ item.id }}() -> u64;
            fn ctest_roundtrip__{{ item.id }}(
                input: MaybeUninit<U>, is_padding_byte: *const bool, value_bytes: *mut u8
            ) -> U;
        }

        const SIZE: usize = size_of::<U>();

        let is_padding_byte = roundtrip_padding__{{ item.id }}();
        let mut expected = vec![0u8; SIZE];
        let mut input = MaybeUninit::<U>::zeroed();

        let input_ptr = input.as_mut_ptr().cast::<u8>();

        {# /* Fill the uninitialized memory with a deterministic pattern.
         * From Rust to C: every byte will be labelled from 1 to 255, with 0 turning into 42.
         * From C to Rust: every byte will be inverted from before (254 -> 1), but 0 is still 42.
         */ #}
        for i in 0..SIZE {
            let c: u8 = (i % 256) as u8;
            let c = if c == 0 { 42 } else { c };
            let d: u8 = 255_u8 - (i % 256) as u8;
            let d = if d == 0 { 42 } else { d };
            unsafe {
                input_ptr.add(i).write_volatile(c);
                expected[i] = d;
            }
        }

        let c_size = unsafe { ctest_size_of__{{ item.id }}() } as usize;
        if SIZE != c_size {
            FAILED.store(true, Ordering::Relaxed);
            eprintln!(
                "size of `{{ item.c_ty }}` is {c_size} in C and {SIZE} in Rust\n",
            );
            return;
        }

        let mut c_value_bytes = vec![0; size_of::<{{ item.id }}>()];
        let r: U = unsafe {
            ctest_roundtrip__{{ item.id }}(input, is_padding_byte.as_ptr(), c_value_bytes.as_mut_ptr())
        };

        {# /* Check that the value bytes as read from C match the byte we sent from Rust. */ #}
        for (i, is_padding_byte) in is_padding_byte.iter().enumerate() {
            if *is_padding_byte { continue; }
            let rust = unsafe { *input_ptr.add(i) };
            let c = c_value_bytes[i];
            if rust != c {
                eprintln!("rust[{}] = {} != {} (C): Rust `{{ item.id }}` -> C", i, rust, c);
                FAILED.store(true, Ordering::Relaxed);
            }
        }

        {# /* Check that value returned from C contains the bytes we expect. */ #}
        for (i, is_padding_byte) in is_padding_byte.iter().enumerate() {
            if *is_padding_byte { continue; }
            let rust = expected[i] as usize;
            let c = unsafe { (&raw const r).cast::<u8>().add(i).read_volatile() as usize };
            if rust != c {
                eprintln!(
                    "rust [{i}] = {rust} != {c} (C): C `{{ item.id }}` -> Rust",
                );
                FAILED.store(true, Ordering::Relaxed);
            }
        }
    }
{%- endfor +%}

/* Check if the Rust and C side function pointers point to the same underlying function. */
{%- for item in ctx.foreign_fn_tests +%}

    pub fn {{ item.test_name }}() {
        {{ ctest_extern }} "C" {
            fn ctest_foreign_fn__{{ item.id }}() -> unsafe extern "C" fn();
        }
        let actual = unsafe { ctest_foreign_fn__{{ item.id }}() } as u64;
        let expected = {{ item.id }} as *const () as u64;
        check_same(actual, expected, "`{{ item.id }}` function pointer");
    }
{%- endfor +%}

/* Tests if the pointer to the static variable matches in both Rust and C. */
{%- for static_ in ctx.foreign_static_tests +%}

    pub fn {{ static_.test_name }}() {
        {{ ctest_extern }} "C" {
            fn ctest_static__{{ static_.id }}() -> *const {{ static_.rust_ty }};
        }
        let actual = (&raw const {{ static_.id }}).addr();
        let expected = unsafe {
            ctest_static__{{ static_.id }}().addr()
        };
        check_same(actual, expected, "`{{ static_.id }}` static");
    }
{%- endfor +%}
}

use generated_tests::*;

fn main() {
    println!("RUNNING ALL TESTS");
    run_all();
    if FAILED.load(std::sync::atomic::Ordering::Relaxed) {
        panic!("some tests failed");
    } else {
        println!(
            "PASSED {} tests",
            NTESTS.load(std::sync::atomic::Ordering::Relaxed)
        );
    }
}

// Run all tests by calling the functions that define them.
// FIXME(ctest): Maybe consider running the tests in parallel, since everything is independent
// and we already use atomics.
fn run_all() {
    {%- for test in ctx.test_idents +%}
    {{ test }}();
    {%- endfor +%}
}