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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
/* This file was autogenerated by ctest; do not modify directly */

/// 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.
 */


/* 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.
 */


/* Compare the size and alignment of the type in Rust and C, making sure they are the same. */

    pub fn ctest_size_align_VecU8() {
        extern "C" {
            fn ctest_size_of__VecU8() -> u64;
            fn ctest_align_of__VecU8() -> u64;
        }

        let rust_size = size_of::<VecU8>() as u64;
        let c_size = unsafe { ctest_size_of__VecU8() };

        let rust_align = align_of::<VecU8>() as u64;
        let c_align = unsafe { ctest_align_of__VecU8() };

        check_same(rust_size, c_size, "`VecU8` size");
        check_same(rust_align, c_align, "`VecU8` align");
    }

    pub fn ctest_size_align_VecU16() {
        extern "C" {
            fn ctest_size_of__VecU16() -> u64;
            fn ctest_align_of__VecU16() -> u64;
        }

        let rust_size = size_of::<VecU16>() as u64;
        let c_size = unsafe { ctest_size_of__VecU16() };

        let rust_align = align_of::<VecU16>() as u64;
        let c_align = unsafe { ctest_align_of__VecU16() };

        check_same(rust_size, c_size, "`VecU16` size");
        check_same(rust_align, c_align, "`VecU16` align");
    }


/* 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.
 */


/* Make sure that the offset and size of a field in a struct/union is the same. */

    pub fn ctest_field_size_offset_VecU8_x() {
        extern "C" {
            fn ctest_offset_of__VecU8__x() -> u64;
            fn ctest_size_of__VecU8__x() -> u64;
        }

        let uninit_ty = MaybeUninit::<VecU8>::zeroed();
        let uninit_ty = uninit_ty.as_ptr();

        
        let ty_ptr = unsafe { &raw const (*uninit_ty).x   };
        
        let val = unsafe { ty_ptr.read_unaligned() };

        
        let ctest_field_offset = unsafe { ctest_offset_of__VecU8__x() };
        check_same(offset_of!(VecU8, x) as u64, ctest_field_offset,
            "field offset `x` of `VecU8`");
        
        let ctest_field_size = unsafe { ctest_size_of__VecU8__x() };
        check_same(size_of_val(&val) as u64, ctest_field_size,
            "field size `x` of `VecU8`");
    }

    pub fn ctest_field_size_offset_VecU8_y() {
        extern "C" {
            fn ctest_offset_of__VecU8__y() -> u64;
            fn ctest_size_of__VecU8__y() -> u64;
        }

        let uninit_ty = MaybeUninit::<VecU8>::zeroed();
        let uninit_ty = uninit_ty.as_ptr();

        
        let ty_ptr = unsafe { &raw const (*uninit_ty).y   };
        
        let val = unsafe { ty_ptr.read_unaligned() };

        
        let ctest_field_offset = unsafe { ctest_offset_of__VecU8__y() };
        check_same(offset_of!(VecU8, y) as u64, ctest_field_offset,
            "field offset `y` of `VecU8`");
        
        let ctest_field_size = unsafe { ctest_size_of__VecU8__y() };
        check_same(size_of_val(&val) as u64, ctest_field_size,
            "field size `y` of `VecU8`");
    }

    pub fn ctest_field_size_offset_VecU16_x() {
        extern "C" {
            fn ctest_offset_of__VecU16__x() -> u64;
            fn ctest_size_of__VecU16__x() -> u64;
        }

        let uninit_ty = MaybeUninit::<VecU16>::zeroed();
        let uninit_ty = uninit_ty.as_ptr();

        
        let ty_ptr = unsafe { &raw const (*uninit_ty).x   };
        
        let val = unsafe { ty_ptr.read_unaligned() };

        
        let ctest_field_offset = unsafe { ctest_offset_of__VecU16__x() };
        check_same(offset_of!(VecU16, x) as u64, ctest_field_offset,
            "field offset `x` of `VecU16`");
        
        let ctest_field_size = unsafe { ctest_size_of__VecU16__x() };
        check_same(size_of_val(&val) as u64, ctest_field_size,
            "field size `x` of `VecU16`");
    }

    pub fn ctest_field_size_offset_VecU16_y() {
        extern "C" {
            fn ctest_offset_of__VecU16__y() -> u64;
            fn ctest_size_of__VecU16__y() -> u64;
        }

        let uninit_ty = MaybeUninit::<VecU16>::zeroed();
        let uninit_ty = uninit_ty.as_ptr();

        
        let ty_ptr = unsafe { &raw const (*uninit_ty).y   };
        
        let val = unsafe { ty_ptr.read_unaligned() };

        
        let ctest_field_offset = unsafe { ctest_offset_of__VecU16__y() };
        check_same(offset_of!(VecU16, y) as u64, ctest_field_offset,
            "field offset `y` of `VecU16`");
        
        let ctest_field_size = unsafe { ctest_size_of__VecU16__y() };
        check_same(size_of_val(&val) as u64, ctest_field_size,
            "field size `y` of `VecU16`");
    }


/* Tests if the pointer to the field is the same in Rust and C. */

    pub fn ctest_field_ptr_VecU8_x() {
        extern "C" {
            fn ctest_field_ptr__VecU8__x(a: *const VecU8) -> *mut u8;
        }

        let uninit_ty = MaybeUninit::<VecU8>::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).x) };

        // SAFETY: FFI call with no preconditions
        let ctest_field_ptr = unsafe { ctest_field_ptr__VecU8__x(ty_ptr) };
        check_same(field_ptr.cast(), ctest_field_ptr,
            "field pointer access `x` of `VecU8`");
    }

    pub fn ctest_field_ptr_VecU8_y() {
        extern "C" {
            fn ctest_field_ptr__VecU8__y(a: *const VecU8) -> *mut u8;
        }

        let uninit_ty = MaybeUninit::<VecU8>::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).y) };

        // SAFETY: FFI call with no preconditions
        let ctest_field_ptr = unsafe { ctest_field_ptr__VecU8__y(ty_ptr) };
        check_same(field_ptr.cast(), ctest_field_ptr,
            "field pointer access `y` of `VecU8`");
    }

    pub fn ctest_field_ptr_VecU16_x() {
        extern "C" {
            fn ctest_field_ptr__VecU16__x(a: *const VecU16) -> *mut u8;
        }

        let uninit_ty = MaybeUninit::<VecU16>::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).x) };

        // SAFETY: FFI call with no preconditions
        let ctest_field_ptr = unsafe { ctest_field_ptr__VecU16__x(ty_ptr) };
        check_same(field_ptr.cast(), ctest_field_ptr,
            "field pointer access `x` of `VecU16`");
    }

    pub fn ctest_field_ptr_VecU16_y() {
        extern "C" {
            fn ctest_field_ptr__VecU16__y(a: *const VecU16) -> *mut u8;
        }

        let uninit_ty = MaybeUninit::<VecU16>::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).y) };

        // SAFETY: FFI call with no preconditions
        let ctest_field_ptr = unsafe { ctest_field_ptr__VecU16__y(ty_ptr) };
        check_same(field_ptr.cast(), ctest_field_ptr,
            "field pointer access `y` of `VecU16`");
    }

/* 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.
 */

    fn roundtrip_padding__VecU8() -> Vec<bool> {
        if 2 == 0 {
            
            return vec![!false; size_of::<VecU8>()]
        }

        
        #[allow(unused_mut)]
        let mut v = Vec::<(usize, usize)>::new();
        #[allow(unused_variables)]
        let bar = MaybeUninit::<VecU8>::zeroed();
        #[allow(unused_variables)]
        let bar = bar.as_ptr();

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

        let size = size_of_val(&val);
        let off = offset_of!(VecU8, x);
        v.push((off, size));

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

        let size = size_of_val(&val);
        let off = offset_of!(VecU8, y);
        v.push((off, size));
        
        let mut is_padding_byte = vec![true; size_of::<VecU8>()];
        for (off, size) in &v {
            for i in 0..*size {
                is_padding_byte[off + i] = false;
            }
        }
        is_padding_byte
    }

    
    pub fn ctest_roundtrip_VecU8() {
        type U = VecU8;
        extern "C" {
            fn ctest_size_of__VecU8() -> u64;
            fn ctest_roundtrip__VecU8(
                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__VecU8();
        let mut expected = vec![0u8; SIZE];
        let mut input = MaybeUninit::<U>::zeroed();

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

        
        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__VecU8() } as usize;
        if SIZE != c_size {
            FAILED.store(true, Ordering::Relaxed);
            eprintln!(
                "size of `struct VecU8` is {c_size} in C and {SIZE} in Rust\n",
            );
            return;
        }

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

        
        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 `VecU8` -> C", i, rust, c);
                FAILED.store(true, Ordering::Relaxed);
            }
        }

        
        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 `VecU8` -> Rust",
                );
                FAILED.store(true, Ordering::Relaxed);
            }
        }
    }

    fn roundtrip_padding__VecU16() -> Vec<bool> {
        if 2 == 0 {
            
            return vec![!false; size_of::<VecU16>()]
        }

        
        #[allow(unused_mut)]
        let mut v = Vec::<(usize, usize)>::new();
        #[allow(unused_variables)]
        let bar = MaybeUninit::<VecU16>::zeroed();
        #[allow(unused_variables)]
        let bar = bar.as_ptr();

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

        let size = size_of_val(&val);
        let off = offset_of!(VecU16, x);
        v.push((off, size));

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

        let size = size_of_val(&val);
        let off = offset_of!(VecU16, y);
        v.push((off, size));
        
        let mut is_padding_byte = vec![true; size_of::<VecU16>()];
        for (off, size) in &v {
            for i in 0..*size {
                is_padding_byte[off + i] = false;
            }
        }
        is_padding_byte
    }

    
    pub fn ctest_roundtrip_VecU16() {
        type U = VecU16;
        extern "C" {
            fn ctest_size_of__VecU16() -> u64;
            fn ctest_roundtrip__VecU16(
                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__VecU16();
        let mut expected = vec![0u8; SIZE];
        let mut input = MaybeUninit::<U>::zeroed();

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

        
        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__VecU16() } as usize;
        if SIZE != c_size {
            FAILED.store(true, Ordering::Relaxed);
            eprintln!(
                "size of `struct VecU16` is {c_size} in C and {SIZE} in Rust\n",
            );
            return;
        }

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

        
        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 `VecU16` -> C", i, rust, c);
                FAILED.store(true, Ordering::Relaxed);
            }
        }

        
        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 `VecU16` -> Rust",
                );
                FAILED.store(true, Ordering::Relaxed);
            }
        }
    }

/* Check if the Rust and C side function pointers point to the same underlying function. */

/* Tests if the pointer to the static variable matches in both Rust and C. */
}

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() {
    ctest_size_align_VecU8();
    ctest_size_align_VecU16();
    ctest_field_size_offset_VecU8_x();
    ctest_field_size_offset_VecU8_y();
    ctest_field_size_offset_VecU16_x();
    ctest_field_size_offset_VecU16_y();
    ctest_field_ptr_VecU8_x();
    ctest_field_ptr_VecU8_y();
    ctest_field_ptr_VecU16_x();
    ctest_field_ptr_VecU16_y();
    ctest_roundtrip_VecU8();
    ctest_roundtrip_VecU16();
}