]> git.lizzy.rs Git - rust.git/blob - src/libcore/ffi.rs
Rollup merge of #65037 - anp:track-caller, 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"), not(target_arch = "asmjs")),
53           all(target_arch = "aarch64", target_os = "ios"),
54           windows))]
55 #[repr(transparent)]
56 #[unstable(feature = "c_variadic",
57            reason = "the `c_variadic` feature has not been properly tested on \
58                      all supported platforms",
59            issue = "44930")]
60 #[lang = "va_list"]
61 pub struct VaListImpl<'f> {
62     ptr: *mut c_void,
63
64     // Invariant over `'f`, so each `VaListImpl<'f>` object is tied to
65     // the region of the function it's defined in
66     _marker: PhantomData<&'f mut &'f c_void>,
67 }
68
69 #[cfg(any(all(not(target_arch = "aarch64"), not(target_arch = "powerpc"),
70               not(target_arch = "x86_64"), not(target_arch = "asmjs")),
71           all(target_arch = "aarch64", target_os = "ios"),
72           windows))]
73 #[unstable(feature = "c_variadic",
74            reason = "the `c_variadic` feature has not been properly tested on \
75                      all supported platforms",
76            issue = "44930")]
77 impl<'f> fmt::Debug for VaListImpl<'f> {
78     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79         write!(f, "va_list* {:p}", self.ptr)
80     }
81 }
82
83 /// AArch64 ABI implementation of a `va_list`. See the
84 /// [AArch64 Procedure Call Standard] for more details.
85 ///
86 /// [AArch64 Procedure Call Standard]:
87 /// http://infocenter.arm.com/help/topic/com.arm.doc.ihi0055b/IHI0055B_aapcs64.pdf
88 #[cfg(all(target_arch = "aarch64", not(target_os = "ios"), not(windows)))]
89 #[repr(C)]
90 #[derive(Debug)]
91 #[unstable(feature = "c_variadic",
92            reason = "the `c_variadic` feature has not been properly tested on \
93                      all supported platforms",
94            issue = "44930")]
95 #[lang = "va_list"]
96 pub struct VaListImpl<'f> {
97     stack: *mut c_void,
98     gr_top: *mut c_void,
99     vr_top: *mut c_void,
100     gr_offs: i32,
101     vr_offs: i32,
102     _marker: PhantomData<&'f mut &'f c_void>,
103 }
104
105 /// PowerPC ABI implementation of a `va_list`.
106 #[cfg(all(target_arch = "powerpc", not(windows)))]
107 #[repr(C)]
108 #[derive(Debug)]
109 #[unstable(feature = "c_variadic",
110            reason = "the `c_variadic` feature has not been properly tested on \
111                      all supported platforms",
112            issue = "44930")]
113 #[lang = "va_list"]
114 pub struct VaListImpl<'f> {
115     gpr: u8,
116     fpr: u8,
117     reserved: u16,
118     overflow_arg_area: *mut c_void,
119     reg_save_area: *mut c_void,
120     _marker: PhantomData<&'f mut &'f c_void>,
121 }
122
123 /// x86_64 ABI implementation of a `va_list`.
124 #[cfg(all(target_arch = "x86_64", not(windows)))]
125 #[repr(C)]
126 #[derive(Debug)]
127 #[unstable(feature = "c_variadic",
128            reason = "the `c_variadic` feature has not been properly tested on \
129                      all supported platforms",
130            issue = "44930")]
131 #[lang = "va_list"]
132 pub struct VaListImpl<'f> {
133     gp_offset: i32,
134     fp_offset: i32,
135     overflow_arg_area: *mut c_void,
136     reg_save_area: *mut c_void,
137     _marker: PhantomData<&'f mut &'f c_void>,
138 }
139
140 /// asm.js ABI implementation of a `va_list`.
141 // asm.js uses the PNaCl ABI, which specifies that a `va_list` is
142 // an array of 4 32-bit integers, according to the old PNaCl docs at
143 // https://web.archive.org/web/20130518054430/https://www.chromium.org/nativeclient/pnacl/bitcode-abi#TOC-Derived-Types
144 // and clang does the same in `CreatePNaClABIBuiltinVaListDecl` from `lib/AST/ASTContext.cpp`
145 #[cfg(all(target_arch = "asmjs", not(windows)))]
146 #[repr(C)]
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 #[lang = "va_list"]
152 pub struct VaListImpl<'f> {
153     inner: [crate::mem::MaybeUninit<i32>; 4],
154     _marker: PhantomData<&'f mut &'f c_void>,
155 }
156
157 #[cfg(all(target_arch = "asmjs", not(windows)))]
158 #[unstable(feature = "c_variadic",
159            reason = "the `c_variadic` feature has not been properly tested on \
160                      all supported platforms",
161            issue = "44930")]
162 impl<'f> fmt::Debug for VaListImpl<'f> {
163     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
164         unsafe {
165             write!(f, "va_list* [{:#x}, {:#x}, {:#x}, {:#x}]",
166                    self.inner[0].read(), self.inner[1].read(),
167                    self.inner[2].read(), self.inner[3].read())
168         }
169     }
170 }
171
172 /// A wrapper for a `va_list`
173 #[repr(transparent)]
174 #[derive(Debug)]
175 #[unstable(feature = "c_variadic",
176            reason = "the `c_variadic` feature has not been properly tested on \
177                      all supported platforms",
178            issue = "44930")]
179 pub struct VaList<'a, 'f: 'a> {
180     #[cfg(any(all(not(target_arch = "aarch64"), not(target_arch = "powerpc"),
181                   not(target_arch = "x86_64"), not(target_arch = "asmjs")),
182               all(target_arch = "aarch64", target_os = "ios"),
183               windows))]
184     inner: VaListImpl<'f>,
185
186     #[cfg(all(any(target_arch = "aarch64", target_arch = "powerpc",
187                   target_arch = "x86_64", target_arch = "asmjs"),
188               any(not(target_arch = "aarch64"), not(target_os = "ios")),
189               not(windows)))]
190     inner: &'a mut VaListImpl<'f>,
191
192     _marker: PhantomData<&'a mut VaListImpl<'f>>,
193 }
194
195 #[cfg(any(all(not(target_arch = "aarch64"), not(target_arch = "powerpc"),
196               not(target_arch = "x86_64"), not(target_arch = "asmjs")),
197           all(target_arch = "aarch64", target_os = "ios"),
198           windows))]
199 #[unstable(feature = "c_variadic",
200            reason = "the `c_variadic` feature has not been properly tested on \
201                      all supported platforms",
202            issue = "44930")]
203 impl<'f> VaListImpl<'f> {
204     /// Convert a `VaListImpl` into a `VaList` that is binary-compatible with C's `va_list`.
205     #[inline]
206     pub fn as_va_list<'a>(&'a mut self) -> VaList<'a, 'f> {
207         VaList {
208             inner: VaListImpl { ..*self },
209             _marker: PhantomData,
210         }
211     }
212 }
213
214 #[cfg(all(any(target_arch = "aarch64", target_arch = "powerpc",
215               target_arch = "x86_64", target_arch = "asmjs"),
216           any(not(target_arch = "aarch64"), not(target_os = "ios")),
217           not(windows)))]
218 #[unstable(feature = "c_variadic",
219            reason = "the `c_variadic` feature has not been properly tested on \
220                      all supported platforms",
221            issue = "44930")]
222 impl<'f> VaListImpl<'f> {
223     /// Convert a `VaListImpl` into a `VaList` that is binary-compatible with C's `va_list`.
224     #[inline]
225     pub fn as_va_list<'a>(&'a mut self) -> VaList<'a, 'f> {
226         VaList {
227             inner: self,
228             _marker: PhantomData,
229         }
230     }
231 }
232
233 #[unstable(feature = "c_variadic",
234            reason = "the `c_variadic` feature has not been properly tested on \
235                      all supported platforms",
236            issue = "44930")]
237 impl<'a, 'f: 'a> Deref for VaList<'a, 'f> {
238     type Target = VaListImpl<'f>;
239
240     #[inline]
241     fn deref(&self) -> &VaListImpl<'f> {
242         &self.inner
243     }
244 }
245
246 #[unstable(feature = "c_variadic",
247            reason = "the `c_variadic` feature has not been properly tested on \
248                      all supported platforms",
249            issue = "44930")]
250 impl<'a, 'f: 'a> DerefMut for VaList<'a, 'f> {
251     #[inline]
252     fn deref_mut(&mut self) -> &mut VaListImpl<'f> {
253         &mut self.inner
254     }
255 }
256
257 // The VaArgSafe trait needs to be used in public interfaces, however, the trait
258 // itself must not be allowed to be used outside this module. Allowing users to
259 // implement the trait for a new type (thereby allowing the va_arg intrinsic to
260 // be used on a new type) is likely to cause undefined behavior.
261 //
262 // FIXME(dlrobertson): In order to use the VaArgSafe trait in a public interface
263 // but also ensure it cannot be used elsewhere, the trait needs to be public
264 // within a private module. Once RFC 2145 has been implemented look into
265 // improving this.
266 mod sealed_trait {
267     /// Trait which whitelists the allowed types to be used with [VaList::arg]
268     ///
269     /// [VaList::va_arg]: struct.VaList.html#method.arg
270     #[unstable(feature = "c_variadic",
271                reason = "the `c_variadic` feature has not been properly tested on \
272                          all supported platforms",
273                issue = "44930")]
274     pub trait VaArgSafe {}
275 }
276
277 macro_rules! impl_va_arg_safe {
278     ($($t:ty),+) => {
279         $(
280             #[unstable(feature = "c_variadic",
281                        reason = "the `c_variadic` feature has not been properly tested on \
282                                  all supported platforms",
283                        issue = "44930")]
284             impl sealed_trait::VaArgSafe for $t {}
285         )+
286     }
287 }
288
289 impl_va_arg_safe!{i8, i16, i32, i64, usize}
290 impl_va_arg_safe!{u8, u16, u32, u64, isize}
291 impl_va_arg_safe!{f64}
292
293 #[unstable(feature = "c_variadic",
294            reason = "the `c_variadic` feature has not been properly tested on \
295                      all supported platforms",
296            issue = "44930")]
297 impl<T> sealed_trait::VaArgSafe for *mut T {}
298 #[unstable(feature = "c_variadic",
299            reason = "the `c_variadic` feature has not been properly tested on \
300                      all supported platforms",
301            issue = "44930")]
302 impl<T> sealed_trait::VaArgSafe for *const T {}
303
304 #[unstable(feature = "c_variadic",
305            reason = "the `c_variadic` feature has not been properly tested on \
306                      all supported platforms",
307            issue = "44930")]
308 impl<'f> VaListImpl<'f> {
309     /// Advance to the next arg.
310     #[inline]
311     pub unsafe fn arg<T: sealed_trait::VaArgSafe>(&mut self) -> T {
312         va_arg(self)
313     }
314
315     /// Copies the `va_list` at the current location.
316     pub unsafe fn with_copy<F, R>(&self, f: F) -> R
317             where F: for<'copy> FnOnce(VaList<'copy, 'f>) -> R {
318         let mut ap = self.clone();
319         let ret = f(ap.as_va_list());
320         va_end(&mut ap);
321         ret
322     }
323 }
324
325 #[unstable(feature = "c_variadic",
326            reason = "the `c_variadic` feature has not been properly tested on \
327                      all supported platforms",
328            issue = "44930")]
329 impl<'f> Clone for VaListImpl<'f> {
330     #[inline]
331     fn clone(&self) -> Self {
332         let mut dest = crate::mem::MaybeUninit::uninit();
333         unsafe {
334             va_copy(dest.as_mut_ptr(), self);
335             dest.assume_init()
336         }
337     }
338 }
339
340 #[unstable(feature = "c_variadic",
341            reason = "the `c_variadic` feature has not been properly tested on \
342                      all supported platforms",
343            issue = "44930")]
344 impl<'f> Drop for VaListImpl<'f> {
345     fn drop(&mut self) {
346         // FIXME: this should call `va_end`, but there's no clean way to
347         // guarantee that `drop` always gets inlined into its caller,
348         // so the `va_end` would get directly called from the same function as
349         // the corresponding `va_copy`. `man va_end` states that C requires this,
350         // and LLVM basically follows the C semantics, so we need to make sure
351         // that `va_end` is always called from the same function as `va_copy`.
352         // For more details, see https://github.com/rust-lang/rust/pull/59625
353         // and https://llvm.org/docs/LangRef.html#llvm-va-end-intrinsic.
354         //
355         // This works for now, since `va_end` is a no-op on all current LLVM targets.
356     }
357 }
358
359 extern "rust-intrinsic" {
360     /// Destroy the arglist `ap` after initialization with `va_start` or
361     /// `va_copy`.
362     fn va_end(ap: &mut VaListImpl<'_>);
363
364     /// Copies the current location of arglist `src` to the arglist `dst`.
365     fn va_copy<'f>(dest: *mut VaListImpl<'f>, src: &VaListImpl<'f>);
366
367     /// Loads an argument of type `T` from the `va_list` `ap` and increment the
368     /// argument `ap` points to.
369     fn va_arg<T: sealed_trait::VaArgSafe>(ap: &mut VaListImpl<'_>) -> T;
370 }