Debian Codegraph @

debian/missing-sources/zerocopy-derive/tests/include.rs

raw
1 // Copyright 2019 The Fuchsia Authors
2 //
3 // Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0
4 // <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
5 // license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
6 // This file may not be copied, modified, or distributed except according to
7 // those terms.
8
9 // ON THE PRELUDE: All of the tests in this directory (excepting UI tests)
10 // disable the prelude via `#![no_implicit_prelude]`. This ensures that all code
11 // emitted by our derives doesn't accidentally assume that the prelude is
12 // included, which helps ensure that items are referred to by absolute path,
13 // which in turn ensures that these items can't accidentally refer to names
14 // which have been shadowed. For example, the code `x == None` could behave
15 // incorrectly if, in the scope in which the derive is invoked, `None` has been
16 // shadowed by `CONST None: Option<usize> = Some(1)`.
17 //
18 // `mod imp` allows us to import items and refer to them in this module without
19 // introducing the risk that this hides bugs in which derive-emitted code uses
20 // names which are not fully-qualified. For such a bug to manifest, it would
21 // need to be of the form `imp::Foo`, which is unlikely to happen by accident.
22 mod imp {
23 // Since this file is included in every test file, and since not every test
24 // file uses every item here, we allow unused imports to avoid generating
25 // warnings.
26 #[allow(unused)]
27 pub use {
28 ::core::{
29 self, assert_eq, assert_ne,
30 cell::UnsafeCell,
31 convert::TryFrom,
32 hash,
33 marker::PhantomData,
34 mem::{ManuallyDrop, MaybeUninit},
35 option::IntoIter,
36 prelude::v1::*,
37 primitive::*,
38 },
39 ::std::{collections::hash_map::DefaultHasher, prelude::v1::*},
40 ::zerocopy_renamed::*,
41 };
42 }
43
44 // These items go in their own module (rather than the top level) for the same
45 // reason that we use `mod imp` above. See its comment for more details.
46 pub mod util {
47 /// A type that doesn't implement any zerocopy traits.
48 pub struct NotZerocopy<T = ()>(pub T);
49
50 /// A `u16` with alignment 2.
51 ///
52 /// Though `u16` has alignment 2 on some platforms, it's not guaranteed. By
53 /// contrast, `util::AU16` is guaranteed to have alignment 2.
54 #[derive(
55 super::imp::KnownLayout,
56 super::imp::Immutable,
57 super::imp::FromBytes,
58 super::imp::IntoBytes,
59 Copy,
60 Clone,
61 )]
62 #[zerocopy(crate = "zerocopy_renamed")]
63 #[repr(C, align(2))]
64 pub struct AU16(pub u16);
65
66 // Since we can't import these by path (ie, `util::assert_impl_all!`), use a
67 // name prefix to ensure our derive-emitted code isn't accidentally relying
68 // on `assert_impl_all!` being in scope.
69 #[macro_export]
70 macro_rules! util_assert_impl_all {
71 ($type:ty: $($trait:path),+ $(,)?) => {
72 const _: fn() = || {
73 use ::core::prelude::v1::*;
74 ::static_assertions::assert_impl_all!($type: $($trait),+);
75 };
76 };
77 }
78
79 // Since we can't import these by path (ie, `util::assert_not_impl_any!`),
80 // use a name prefix to ensure our derive-emitted code isn't accidentally
81 // relying on `assert_not_impl_any!` being in scope.
82 #[macro_export]
83 macro_rules! util_assert_not_impl_any {
84 ($x:ty: $($t:path),+ $(,)?) => {
85 const _: fn() = || {
86 use ::core::prelude::v1::*;
87 ::static_assertions::assert_not_impl_any!($x: $($t),+);
88 };
89 };
90 }
91
92 #[macro_export]
93 macro_rules! test_trivial_is_bit_valid {
94 ($x:ty => $name:ident) => {
95 #[test]
96 fn $name() {
97 util::test_trivial_is_bit_valid::<$x>();
98 }
99 };
100 }
101
102 // Under some circumstances, our `TryFromBytes` derive generates a trivial
103 // `is_bit_valid` impl that unconditionally returns `true`. This test
104 // attempts to validate that this is, indeed, the behavior of our
105 // `TryFromBytes` derive. It is not foolproof, but is likely to catch some
106 // mistakes.
107 //
108 // As of this writing, this happens when deriving `TryFromBytes` thanks to a
109 // top-level `#[derive(FromBytes)]`.
110 pub fn test_trivial_is_bit_valid<T: super::imp::TryFromBytes>() {
111 use super::imp::{MaybeUninit, Ptr, ReadOnly};
112
113 // This test works based on the insight that a trivial `is_bit_valid`
114 // impl should never load any bytes from memory. Thus, while it is
115 // technically a violation of `is_bit_valid`'s safety precondition to
116 // pass a pointer to uninitialized memory, the `is_bit_valid` impl we
117 // expect our derives to generate should never touch this memory, and
118 // thus should never exhibit UB. By contrast, if our derives are
119 // spuriously generating non-trivial `is_bit_valid` impls, this should
120 // cause UB which may be caught by Miri.
121
122 let mut buf = MaybeUninit::<T>::uninit();
123 let ptr = Ptr::from_mut(&mut buf);
124 // SAFETY: This is intentionally unsound; see the preceding comment.
125 let ptr = unsafe { ptr.assume_initialized() };
126 let mut ptr = ptr.transmute::<ReadOnly<MaybeUninit<T>>, _, _>();
127 let ptr = ptr.reborrow_shared();
128
129 let ptr = ptr.cast::<_, ::zerocopy_renamed::pointer::cast::CastSized, _>();
130 assert!(<T as super::imp::TryFromBytes>::is_bit_valid(ptr));
131 }
132
133 pub fn test_is_bit_valid<T: super::imp::TryFromBytes, V: super::imp::IntoBytes>(
134 val: V,
135 is_bit_valid: bool,
136 ) {
137 use super::imp::{
138 pointer::{cast::CastSized, BecauseImmutable},
139 ReadOnly,
140 };
141
142 let ro = ReadOnly::new(val);
143 let candidate = ::zerocopy_renamed::Ptr::from_ref(&ro);
144 let candidate = candidate.recall_validity();
145 let candidate = candidate.cast::<ReadOnly<T>, CastSized, (_, BecauseImmutable)>();
146
147 super::imp::assert_eq!(T::is_bit_valid(candidate), is_bit_valid);
148 }
149 }