]> git.lizzy.rs Git - rust.git/blob - src/libcore/ffi.rs
Rollup merge of #64996 - lzutao:inline-ptr-null, r=oli-obk
[rust.git] / src / libcore / ffi.rs
1 #![stable(feature = "", since = "1.30.0")]
2
3 #![allow(non_camel_case_types)]
4
5 //! Utilities related to FFI bindings.
6
7 use crate::fmt;
8 use crate::marker::PhantomData;
9 use crate::ops::{Deref, DerefMut};
10
11 /// Equivalent to C's `void` type when used as a [pointer].
12 ///
13 /// In essence, `*const c_void` is equivalent to C's `const void*`
14 /// and `*mut c_void` is equivalent to C's `void*`. That said, this is
15 /// *not* the same as C's `void` return type, which is Rust's `()` type.
16 ///
17 /// To model pointers to opaque types in FFI, until `extern type` is
18 /// stabilized, it is recommended to use a newtype wrapper around an empty
19 /// byte array. See the [Nomicon] for details.
20 ///
21 /// [pointer]: ../../std/primitive.pointer.html
22 /// [Nomicon]: https://doc.rust-lang.org/nomicon/ffi.html#representing-opaque-structs
23 // N.B., for LLVM to recognize the void pointer type and by extension
24 //     functions like malloc(), we need to have it represented as i8* in
25 //     LLVM bitcode. The enum used here ensures this and prevents misuse
26 //     of the "raw" type by only having private variants. We need two
27 //     variants, because the compiler complains about the repr attribute
28 //     otherwise and we need at least one variant as otherwise the enum
29 //     would be uninhabited and at least dereferencing such pointers would
30 //     be UB.
31 #[repr(u8)]
32 #[stable(feature = "raw_os", since = "1.1.0")]
33 pub enum c_void {
34     #[unstable(feature = "c_void_variant", reason = "temporary implementation detail",
35                issue = "0")]
36     #[doc(hidden)] __variant1,
37     #[unstable(feature = "c_void_variant", reason = "temporary implementation detail",
38                issue = "0")]
39     #[doc(hidden)] __variant2,
40 }
41
42 #[stable(feature = "std_debug", since = "1.16.0")]
43 impl fmt::Debug for c_void {
44     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45         f.pad("c_void")
46     }
47 }
48
49 /// Basic implementation of a `va_list`.
50 // The name is WIP, using `VaListImpl` for now.
51 #[cfg(any(all(not(target_arch = "aarch64"), not(target_arch = "powerpc"),
52               not(target_arch = "x86_64")),
53           all(target_arch = "aarch64", target_os = "ios"),
54           target_arch = "wasm32",
55           target_arch = "asmjs",
56           windows))]
57 #[repr(transparent)]
58 #[unstable(feature = "c_variadic",
59            reason = "the `c_variadic` feature has not been properly tested on \
60                      all supported platforms",
61            issue = "44930")]
62 #[lang = "va_list"]
63 pub struct VaListImpl<'f> {
64     ptr: *mut c_void,
65
66     // Invariant over `'f`, so each `VaListImpl<'f>` object is tied to
67     // the region of the function it's defined in
68     _marker: PhantomData<&'f mut &'f c_void>,
69 }
70
71 #[cfg(any(all(not(target_arch = "aarch64"), not(target_arch = "powerpc"),
72               not(target_arch = "x86_64")),
73           all(target_arch = "aarch64", target_os = "ios"),
74           target_arch = "wasm32",
75           target_arch = "asmjs",
76           windows))]
77 #[unstable(feature = "c_variadic",
78            reason = "the `c_variadic` feature has not been properly tested on \
79                      all supported platforms",
80            issue = "44930")]
81 impl<'f> fmt::Debug for VaListImpl<'f> {
82     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83         write!(f, "va_list* {:p}", self.ptr)
84     }
85 }
86
87 /// AArch64 ABI implementation of a `va_list`. See the
88 /// [AArch64 Procedure Call Standard] for more details.
89 ///
90 /// [AArch64 Procedure Call Standard]:
91 /// http://infocenter.arm.com/help/topic/com.arm.doc.ihi0055b/IHI0055B_aapcs64.pdf
92 #[cfg(all(target_arch = "aarch64", not(target_os = "ios"), not(windows)))]
93 #[repr(C)]
94 #[derive(Debug)]
95 #[unstable(feature = "c_variadic",
96            reason = "the `c_variadic` feature has not been properly tested on \
97                      all supported platforms",
98            issue = "44930")]
99 #[lang = "va_list"]
100 pub struct VaListImpl<'f> {
101     stack: *mut c_void,
102     gr_top: *mut c_void,
103     vr_top: *mut c_void,
104     gr_offs: i32,
105     vr_offs: i32,
106     _marker: PhantomData<&'f mut &'f c_void>,
107 }
108
109 /// PowerPC ABI implementation of a `va_list`.
110 #[cfg(all(target_arch = "powerpc", not(windows)))]
111 #[repr(C)]
112 #[derive(Debug)]
113 #[unstable(feature = "c_variadic",
114            reason = "the `c_variadic` feature has not been properly tested on \
115                      all supported platforms",
116            issue = "44930")]
117 #[lang = "va_list"]
118 pub struct VaListImpl<'f> {
119     gpr: u8,
120     fpr: u8,
121     reserved: u16,
122     overflow_arg_area: *mut c_void,
123     reg_save_area: *mut c_void,
124     _marker: PhantomData<&'f mut &'f c_void>,
125 }
126
127 /// x86_64 ABI implementation of a `va_list`.
128 #[cfg(all(target_arch = "x86_64", not(windows)))]
129 #[repr(C)]
130 #[derive(Debug)]
131 #[unstable(feature = "c_variadic",
132            reason = "the `c_variadic` feature has not been properly tested on \
133                      all supported platforms",
134            issue = "44930")]
135 #[lang = "va_list"]
136 pub struct VaListImpl<'f> {
137     gp_offset: i32,
138     fp_offset: i32,
139     overflow_arg_area: *mut c_void,
140     reg_save_area: *mut c_void,
141     _marker: PhantomData<&'f mut &'f c_void>,
142 }
143
144 /// A wrapper for a `va_list`
145 #[repr(transparent)]
146 #[derive(Debug)]
147 #[unstable(feature = "c_variadic",
148            reason = "the `c_variadic` feature has not been properly tested on \
149                      all supported platforms",
150            issue = "44930")]
151 pub struct VaList<'a, 'f: 'a> {
152     #[cfg(any(all(not(target_arch = "aarch64"), not(target_arch = "powerpc"),
153                   not(target_arch = "x86_64")),
154               all(target_arch = "aarch64", target_os = "ios"),
155               target_arch = "wasm32",
156               target_arch = "asmjs",
157               windows))]
158     inner: VaListImpl<'f>,
159
160     #[cfg(all(any(target_arch = "aarch64", target_arch = "powerpc",
161                   target_arch = "x86_64"),
162               any(not(target_arch = "aarch64"), not(target_os = "ios")),
163               not(target_arch = "wasm32"),
164               not(target_arch = "asmjs"),
165               not(windows)))]
166     inner: &'a mut VaListImpl<'f>,
167
168     _marker: PhantomData<&'a mut VaListImpl<'f>>,
169 }
170
171 #[cfg(any(all(not(target_arch = "aarch64"), not(target_arch = "powerpc"),
172               not(target_arch = "x86_64")),
173           all(target_arch = "aarch64", target_os = "ios"),
174           target_arch = "wasm32",
175           target_arch = "asmjs",
176           windows))]
177 #[unstable(feature = "c_variadic",
178            reason = "the `c_variadic` feature has not been properly tested on \
179                      all supported platforms",
180            issue = "44930")]
181 impl<'f> VaListImpl<'f> {
182     /// Convert a `VaListImpl` into a `VaList` that is binary-compatible with C's `va_list`.
183     #[inline]
184     pub fn as_va_list<'a>(&'a mut self) -> VaList<'a, 'f> {
185         VaList {
186             inner: VaListImpl { ..*self },
187             _marker: PhantomData,
188         }
189     }
190 }
191
192 #[cfg(all(any(target_arch = "aarch64", target_arch = "powerpc",
193               target_arch = "x86_64"),
194           any(not(target_arch = "aarch64"), not(target_os = "ios")),
195           not(target_arch = "wasm32"),
196           not(target_arch = "asmjs"),
197           not(windows)))]
198 #[unstable(feature = "c_variadic",
199            reason = "the `c_variadic` feature has not been properly tested on \
200                      all supported platforms",
201            issue = "44930")]
202 impl<'f> VaListImpl<'f> {
203     /// Convert a `VaListImpl` into a `VaList` that is binary-compatible with C's `va_list`.
204     #[inline]
205     pub fn as_va_list<'a>(&'a mut self) -> VaList<'a, 'f> {
206         VaList {
207             inner: self,
208             _marker: PhantomData,
209         }
210     }
211 }
212
213 #[unstable(feature = "c_variadic",
214            reason = "the `c_variadic` feature has not been properly tested on \
215                      all supported platforms",
216            issue = "44930")]
217 impl<'a, 'f: 'a> Deref for VaList<'a, 'f> {
218     type Target = VaListImpl<'f>;
219
220     #[inline]
221     fn deref(&self) -> &VaListImpl<'f> {
222         &self.inner
223     }
224 }
225
226 #[unstable(feature = "c_variadic",
227            reason = "the `c_variadic` feature has not been properly tested on \
228                      all supported platforms",
229            issue = "44930")]
230 impl<'a, 'f: 'a> DerefMut for VaList<'a, 'f> {
231     #[inline]
232     fn deref_mut(&mut self) -> &mut VaListImpl<'f> {
233         &mut self.inner
234     }
235 }
236
237 // The VaArgSafe trait needs to be used in public interfaces, however, the trait
238 // itself must not be allowed to be used outside this module. Allowing users to
239 // implement the trait for a new type (thereby allowing the va_arg intrinsic to
240 // be used on a new type) is likely to cause undefined behavior.
241 //
242 // FIXME(dlrobertson): In order to use the VaArgSafe trait in a public interface
243 // but also ensure it cannot be used elsewhere, the trait needs to be public
244 // within a private module. Once RFC 2145 has been implemented look into
245 // improving this.
246 mod sealed_trait {
247     /// Trait which whitelists the allowed types to be used with [VaList::arg]
248     ///
249     /// [VaList::va_arg]: struct.VaList.html#method.arg
250     #[unstable(feature = "c_variadic",
251                reason = "the `c_variadic` feature has not been properly tested on \
252                          all supported platforms",
253                issue = "44930")]
254     pub trait VaArgSafe {}
255 }
256
257 macro_rules! impl_va_arg_safe {
258     ($($t:ty),+) => {
259         $(
260             #[unstable(feature = "c_variadic",
261                        reason = "the `c_variadic` feature has not been properly tested on \
262                                  all supported platforms",
263                        issue = "44930")]
264             impl sealed_trait::VaArgSafe for $t {}
265         )+
266     }
267 }
268
269 impl_va_arg_safe!{i8, i16, i32, i64, usize}
270 impl_va_arg_safe!{u8, u16, u32, u64, isize}
271 impl_va_arg_safe!{f64}
272
273 #[unstable(feature = "c_variadic",
274            reason = "the `c_variadic` feature has not been properly tested on \
275                      all supported platforms",
276            issue = "44930")]
277 impl<T> sealed_trait::VaArgSafe for *mut T {}
278 #[unstable(feature = "c_variadic",
279            reason = "the `c_variadic` feature has not been properly tested on \
280                      all supported platforms",
281            issue = "44930")]
282 impl<T> sealed_trait::VaArgSafe for *const T {}
283
284 #[unstable(feature = "c_variadic",
285            reason = "the `c_variadic` feature has not been properly tested on \
286                      all supported platforms",
287            issue = "44930")]
288 impl<'f> VaListImpl<'f> {
289     /// Advance to the next arg.
290     #[inline]
291     pub unsafe fn arg<T: sealed_trait::VaArgSafe>(&mut self) -> T {
292         va_arg(self)
293     }
294
295     /// Copies the `va_list` at the current location.
296     pub unsafe fn with_copy<F, R>(&self, f: F) -> R
297             where F: for<'copy> FnOnce(VaList<'copy, 'f>) -> R {
298         let mut ap = self.clone();
299         let ret = f(ap.as_va_list());
300         va_end(&mut ap);
301         ret
302     }
303 }
304
305 #[unstable(feature = "c_variadic",
306            reason = "the `c_variadic` feature has not been properly tested on \
307                      all supported platforms",
308            issue = "44930")]
309 impl<'f> Clone for VaListImpl<'f> {
310     #[inline]
311     fn clone(&self) -> Self {
312         let mut dest = crate::mem::MaybeUninit::uninit();
313         unsafe {
314             va_copy(dest.as_mut_ptr(), self);
315             dest.assume_init()
316         }
317     }
318 }
319
320 #[unstable(feature = "c_variadic",
321            reason = "the `c_variadic` feature has not been properly tested on \
322                      all supported platforms",
323            issue = "44930")]
324 impl<'f> Drop for VaListImpl<'f> {
325     fn drop(&mut self) {
326         // FIXME: this should call `va_end`, but there's no clean way to
327         // guarantee that `drop` always gets inlined into its caller,
328         // so the `va_end` would get directly called from the same function as
329         // the corresponding `va_copy`. `man va_end` states that C requires this,
330         // and LLVM basically follows the C semantics, so we need to make sure
331         // that `va_end` is always called from the same function as `va_copy`.
332         // For more details, see https://github.com/rust-lang/rust/pull/59625
333         // and https://llvm.org/docs/LangRef.html#llvm-va-end-intrinsic.
334         //
335         // This works for now, since `va_end` is a no-op on all current LLVM targets.
336     }
337 }
338
339 extern "rust-intrinsic" {
340     /// Destroy the arglist `ap` after initialization with `va_start` or
341     /// `va_copy`.
342     fn va_end(ap: &mut VaListImpl<'_>);
343
344     /// Copies the current location of arglist `src` to the arglist `dst`.
345     fn va_copy<'f>(dest: *mut VaListImpl<'f>, src: &VaListImpl<'f>);
346
347     /// Loads an argument of type `T` from the `va_list` `ap` and increment the
348     /// argument `ap` points to.
349     fn va_arg<T: sealed_trait::VaArgSafe>(ap: &mut VaListImpl<'_>) -> T;
350 }