]> git.lizzy.rs Git - rust.git/blob - library/core/src/ffi/mod.rs
Rollup merge of #99307 - JohnTitor:issue-64401, r=compiler-errors
[rust.git] / library / core / src / ffi / mod.rs
1 //! Platform-specific types, as defined by C.
2 //!
3 //! Code that interacts via FFI will almost certainly be using the
4 //! base types provided by C, which aren't nearly as nicely defined
5 //! as Rust's primitive types. This module provides types which will
6 //! match those defined by C, so that code that interacts with C will
7 //! refer to the correct types.
8
9 #![stable(feature = "", since = "1.30.0")]
10 #![allow(non_camel_case_types)]
11
12 use crate::fmt;
13 use crate::marker::PhantomData;
14 use crate::num::*;
15 use crate::ops::{Deref, DerefMut};
16
17 #[stable(feature = "core_c_str", since = "1.64.0")]
18 pub use self::c_str::{CStr, FromBytesUntilNulError, FromBytesWithNulError};
19
20 mod c_str;
21
22 macro_rules! type_alias_no_nz {
23     {
24       $Docfile:tt, $Alias:ident = $Real:ty;
25       $( $Cfg:tt )*
26     } => {
27         #[doc = include_str!($Docfile)]
28         $( $Cfg )*
29         #[stable(feature = "core_ffi_c", since = "1.64.0")]
30         pub type $Alias = $Real;
31     }
32 }
33
34 // To verify that the NonZero types in this file's macro invocations correspond
35 //
36 //  perl -n < library/std/src/os/raw/mod.rs -e 'next unless m/type_alias\!/; die "$_ ?" unless m/, (c_\w+) = (\w+), NonZero_(\w+) = NonZero(\w+)/; die "$_ ?" unless $3 eq $1 and $4 eq ucfirst $2'
37 //
38 // NB this does not check that the main c_* types are right.
39
40 macro_rules! type_alias {
41     {
42       $Docfile:tt, $Alias:ident = $Real:ty, $NZAlias:ident = $NZReal:ty;
43       $( $Cfg:tt )*
44     } => {
45         type_alias_no_nz! { $Docfile, $Alias = $Real; $( $Cfg )* }
46
47         #[doc = concat!("Type alias for `NonZero` version of [`", stringify!($Alias), "`]")]
48         #[unstable(feature = "raw_os_nonzero", issue = "82363")]
49         $( $Cfg )*
50         pub type $NZAlias = $NZReal;
51     }
52 }
53
54 type_alias! { "c_char.md", c_char = c_char_definition::c_char, NonZero_c_char = c_char_definition::NonZero_c_char;
55 // Make this type alias appear cfg-dependent so that Clippy does not suggest
56 // replacing `0 as c_char` with `0_i8`/`0_u8`. This #[cfg(all())] can be removed
57 // after the false positive in https://github.com/rust-lang/rust-clippy/issues/8093
58 // is fixed.
59 #[cfg(all())]
60 #[doc(cfg(all()))] }
61
62 type_alias! { "c_schar.md", c_schar = i8, NonZero_c_schar = NonZeroI8; }
63 type_alias! { "c_uchar.md", c_uchar = u8, NonZero_c_uchar = NonZeroU8; }
64 type_alias! { "c_short.md", c_short = i16, NonZero_c_short = NonZeroI16; }
65 type_alias! { "c_ushort.md", c_ushort = u16, NonZero_c_ushort = NonZeroU16; }
66
67 type_alias! { "c_int.md", c_int = c_int_definition::c_int, NonZero_c_int = c_int_definition::NonZero_c_int;
68 #[doc(cfg(all()))] }
69 type_alias! { "c_uint.md", c_uint = c_int_definition::c_uint, NonZero_c_uint = c_int_definition::NonZero_c_uint;
70 #[doc(cfg(all()))] }
71
72 type_alias! { "c_long.md", c_long = c_long_definition::c_long, NonZero_c_long = c_long_definition::NonZero_c_long;
73 #[doc(cfg(all()))] }
74 type_alias! { "c_ulong.md", c_ulong = c_long_definition::c_ulong, NonZero_c_ulong = c_long_definition::NonZero_c_ulong;
75 #[doc(cfg(all()))] }
76
77 type_alias! { "c_longlong.md", c_longlong = i64, NonZero_c_longlong = NonZeroI64; }
78 type_alias! { "c_ulonglong.md", c_ulonglong = u64, NonZero_c_ulonglong = NonZeroU64; }
79
80 type_alias_no_nz! { "c_float.md", c_float = f32; }
81 type_alias_no_nz! { "c_double.md", c_double = f64; }
82
83 /// Equivalent to C's `size_t` type, from `stddef.h` (or `cstddef` for C++).
84 ///
85 /// This type is currently always [`usize`], however in the future there may be
86 /// platforms where this is not the case.
87 #[unstable(feature = "c_size_t", issue = "88345")]
88 pub type c_size_t = usize;
89
90 /// Equivalent to C's `ptrdiff_t` type, from `stddef.h` (or `cstddef` for C++).
91 ///
92 /// This type is currently always [`isize`], however in the future there may be
93 /// platforms where this is not the case.
94 #[unstable(feature = "c_size_t", issue = "88345")]
95 pub type c_ptrdiff_t = isize;
96
97 /// Equivalent to C's `ssize_t` (on POSIX) or `SSIZE_T` (on Windows) type.
98 ///
99 /// This type is currently always [`isize`], however in the future there may be
100 /// platforms where this is not the case.
101 #[unstable(feature = "c_size_t", issue = "88345")]
102 pub type c_ssize_t = isize;
103
104 mod c_char_definition {
105     cfg_if! {
106         // These are the targets on which c_char is unsigned.
107         if #[cfg(any(
108             all(
109                 target_os = "linux",
110                 any(
111                     target_arch = "aarch64",
112                     target_arch = "arm",
113                     target_arch = "hexagon",
114                     target_arch = "powerpc",
115                     target_arch = "powerpc64",
116                     target_arch = "s390x",
117                     target_arch = "riscv64",
118                     target_arch = "riscv32"
119                 )
120             ),
121             all(target_os = "android", any(target_arch = "aarch64", target_arch = "arm")),
122             all(target_os = "l4re", target_arch = "x86_64"),
123             all(
124                 any(target_os = "freebsd", target_os = "openbsd"),
125                 any(
126                     target_arch = "aarch64",
127                     target_arch = "arm",
128                     target_arch = "powerpc",
129                     target_arch = "powerpc64",
130                     target_arch = "riscv64"
131                 )
132             ),
133             all(
134                 target_os = "netbsd",
135                 any(target_arch = "aarch64", target_arch = "arm", target_arch = "powerpc")
136             ),
137             all(
138                 target_os = "vxworks",
139                 any(
140                     target_arch = "aarch64",
141                     target_arch = "arm",
142                     target_arch = "powerpc64",
143                     target_arch = "powerpc"
144                 )
145             ),
146             all(target_os = "fuchsia", target_arch = "aarch64"),
147             target_os = "horizon"
148         ))] {
149             pub type c_char = u8;
150             pub type NonZero_c_char = crate::num::NonZeroU8;
151         } else {
152             // On every other target, c_char is signed.
153             pub type c_char = i8;
154             pub type NonZero_c_char = crate::num::NonZeroI8;
155         }
156     }
157 }
158
159 mod c_int_definition {
160     cfg_if! {
161         if #[cfg(any(target_arch = "avr", target_arch = "msp430"))] {
162             pub type c_int = i16;
163             pub type NonZero_c_int = crate::num::NonZeroI16;
164             pub type c_uint = u16;
165             pub type NonZero_c_uint = crate::num::NonZeroU16;
166         } else {
167             pub type c_int = i32;
168             pub type NonZero_c_int = crate::num::NonZeroI32;
169             pub type c_uint = u32;
170             pub type NonZero_c_uint = crate::num::NonZeroU32;
171         }
172     }
173 }
174
175 mod c_long_definition {
176     cfg_if! {
177         if #[cfg(all(target_pointer_width = "64", not(windows)))] {
178             pub type c_long = i64;
179             pub type NonZero_c_long = crate::num::NonZeroI64;
180             pub type c_ulong = u64;
181             pub type NonZero_c_ulong = crate::num::NonZeroU64;
182         } else {
183             // The minimal size of `long` in the C standard is 32 bits
184             pub type c_long = i32;
185             pub type NonZero_c_long = crate::num::NonZeroI32;
186             pub type c_ulong = u32;
187             pub type NonZero_c_ulong = crate::num::NonZeroU32;
188         }
189     }
190 }
191
192 // N.B., for LLVM to recognize the void pointer type and by extension
193 //     functions like malloc(), we need to have it represented as i8* in
194 //     LLVM bitcode. The enum used here ensures this and prevents misuse
195 //     of the "raw" type by only having private variants. We need two
196 //     variants, because the compiler complains about the repr attribute
197 //     otherwise and we need at least one variant as otherwise the enum
198 //     would be uninhabited and at least dereferencing such pointers would
199 //     be UB.
200 #[doc = include_str!("c_void.md")]
201 #[repr(u8)]
202 #[stable(feature = "core_c_void", since = "1.30.0")]
203 pub enum c_void {
204     #[unstable(
205         feature = "c_void_variant",
206         reason = "temporary implementation detail",
207         issue = "none"
208     )]
209     #[doc(hidden)]
210     __variant1,
211     #[unstable(
212         feature = "c_void_variant",
213         reason = "temporary implementation detail",
214         issue = "none"
215     )]
216     #[doc(hidden)]
217     __variant2,
218 }
219
220 #[stable(feature = "std_debug", since = "1.16.0")]
221 impl fmt::Debug for c_void {
222     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
223         f.debug_struct("c_void").finish()
224     }
225 }
226
227 /// Basic implementation of a `va_list`.
228 // The name is WIP, using `VaListImpl` for now.
229 #[cfg(any(
230     all(not(target_arch = "aarch64"), not(target_arch = "powerpc"), not(target_arch = "x86_64")),
231     all(target_arch = "aarch64", any(target_os = "macos", target_os = "ios")),
232     target_family = "wasm",
233     target_arch = "asmjs",
234     target_os = "uefi",
235     windows,
236 ))]
237 #[repr(transparent)]
238 #[unstable(
239     feature = "c_variadic",
240     reason = "the `c_variadic` feature has not been properly tested on \
241               all supported platforms",
242     issue = "44930"
243 )]
244 #[lang = "va_list"]
245 pub struct VaListImpl<'f> {
246     ptr: *mut c_void,
247
248     // Invariant over `'f`, so each `VaListImpl<'f>` object is tied to
249     // the region of the function it's defined in
250     _marker: PhantomData<&'f mut &'f c_void>,
251 }
252
253 #[cfg(any(
254     all(not(target_arch = "aarch64"), not(target_arch = "powerpc"), not(target_arch = "x86_64")),
255     all(target_arch = "aarch64", any(target_os = "macos", target_os = "ios")),
256     target_family = "wasm",
257     target_arch = "asmjs",
258     target_os = "uefi",
259     windows,
260 ))]
261 #[unstable(
262     feature = "c_variadic",
263     reason = "the `c_variadic` feature has not been properly tested on \
264               all supported platforms",
265     issue = "44930"
266 )]
267 impl<'f> fmt::Debug for VaListImpl<'f> {
268     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
269         write!(f, "va_list* {:p}", self.ptr)
270     }
271 }
272
273 /// AArch64 ABI implementation of a `va_list`. See the
274 /// [AArch64 Procedure Call Standard] for more details.
275 ///
276 /// [AArch64 Procedure Call Standard]:
277 /// http://infocenter.arm.com/help/topic/com.arm.doc.ihi0055b/IHI0055B_aapcs64.pdf
278 #[cfg(all(
279     target_arch = "aarch64",
280     not(any(target_os = "macos", target_os = "ios")),
281     not(target_os = "uefi"),
282     not(windows),
283 ))]
284 #[repr(C)]
285 #[derive(Debug)]
286 #[unstable(
287     feature = "c_variadic",
288     reason = "the `c_variadic` feature has not been properly tested on \
289               all supported platforms",
290     issue = "44930"
291 )]
292 #[lang = "va_list"]
293 pub struct VaListImpl<'f> {
294     stack: *mut c_void,
295     gr_top: *mut c_void,
296     vr_top: *mut c_void,
297     gr_offs: i32,
298     vr_offs: i32,
299     _marker: PhantomData<&'f mut &'f c_void>,
300 }
301
302 /// PowerPC ABI implementation of a `va_list`.
303 #[cfg(all(target_arch = "powerpc", not(target_os = "uefi"), not(windows)))]
304 #[repr(C)]
305 #[derive(Debug)]
306 #[unstable(
307     feature = "c_variadic",
308     reason = "the `c_variadic` feature has not been properly tested on \
309               all supported platforms",
310     issue = "44930"
311 )]
312 #[lang = "va_list"]
313 pub struct VaListImpl<'f> {
314     gpr: u8,
315     fpr: u8,
316     reserved: u16,
317     overflow_arg_area: *mut c_void,
318     reg_save_area: *mut c_void,
319     _marker: PhantomData<&'f mut &'f c_void>,
320 }
321
322 /// x86_64 ABI implementation of a `va_list`.
323 #[cfg(all(target_arch = "x86_64", not(target_os = "uefi"), not(windows)))]
324 #[repr(C)]
325 #[derive(Debug)]
326 #[unstable(
327     feature = "c_variadic",
328     reason = "the `c_variadic` feature has not been properly tested on \
329               all supported platforms",
330     issue = "44930"
331 )]
332 #[lang = "va_list"]
333 pub struct VaListImpl<'f> {
334     gp_offset: i32,
335     fp_offset: i32,
336     overflow_arg_area: *mut c_void,
337     reg_save_area: *mut c_void,
338     _marker: PhantomData<&'f mut &'f c_void>,
339 }
340
341 /// A wrapper for a `va_list`
342 #[repr(transparent)]
343 #[derive(Debug)]
344 #[unstable(
345     feature = "c_variadic",
346     reason = "the `c_variadic` feature has not been properly tested on \
347               all supported platforms",
348     issue = "44930"
349 )]
350 pub struct VaList<'a, 'f: 'a> {
351     #[cfg(any(
352         all(
353             not(target_arch = "aarch64"),
354             not(target_arch = "powerpc"),
355             not(target_arch = "x86_64")
356         ),
357         all(target_arch = "aarch64", any(target_os = "macos", target_os = "ios")),
358         target_family = "wasm",
359         target_arch = "asmjs",
360         target_os = "uefi",
361         windows,
362     ))]
363     inner: VaListImpl<'f>,
364
365     #[cfg(all(
366         any(target_arch = "aarch64", target_arch = "powerpc", target_arch = "x86_64"),
367         any(not(target_arch = "aarch64"), not(any(target_os = "macos", target_os = "ios"))),
368         not(target_family = "wasm"),
369         not(target_arch = "asmjs"),
370         not(target_os = "uefi"),
371         not(windows),
372     ))]
373     inner: &'a mut VaListImpl<'f>,
374
375     _marker: PhantomData<&'a mut VaListImpl<'f>>,
376 }
377
378 #[cfg(any(
379     all(not(target_arch = "aarch64"), not(target_arch = "powerpc"), not(target_arch = "x86_64")),
380     all(target_arch = "aarch64", any(target_os = "macos", target_os = "ios")),
381     target_family = "wasm",
382     target_arch = "asmjs",
383     target_os = "uefi",
384     windows,
385 ))]
386 #[unstable(
387     feature = "c_variadic",
388     reason = "the `c_variadic` feature has not been properly tested on \
389               all supported platforms",
390     issue = "44930"
391 )]
392 impl<'f> VaListImpl<'f> {
393     /// Convert a `VaListImpl` into a `VaList` that is binary-compatible with C's `va_list`.
394     #[inline]
395     pub fn as_va_list<'a>(&'a mut self) -> VaList<'a, 'f> {
396         VaList { inner: VaListImpl { ..*self }, _marker: PhantomData }
397     }
398 }
399
400 #[cfg(all(
401     any(target_arch = "aarch64", target_arch = "powerpc", target_arch = "x86_64"),
402     any(not(target_arch = "aarch64"), not(any(target_os = "macos", target_os = "ios"))),
403     not(target_family = "wasm"),
404     not(target_arch = "asmjs"),
405     not(target_os = "uefi"),
406     not(windows),
407 ))]
408 #[unstable(
409     feature = "c_variadic",
410     reason = "the `c_variadic` feature has not been properly tested on \
411               all supported platforms",
412     issue = "44930"
413 )]
414 impl<'f> VaListImpl<'f> {
415     /// Convert a `VaListImpl` into a `VaList` that is binary-compatible with C's `va_list`.
416     #[inline]
417     pub fn as_va_list<'a>(&'a mut self) -> VaList<'a, 'f> {
418         VaList { inner: self, _marker: PhantomData }
419     }
420 }
421
422 #[unstable(
423     feature = "c_variadic",
424     reason = "the `c_variadic` feature has not been properly tested on \
425               all supported platforms",
426     issue = "44930"
427 )]
428 impl<'a, 'f: 'a> Deref for VaList<'a, 'f> {
429     type Target = VaListImpl<'f>;
430
431     #[inline]
432     fn deref(&self) -> &VaListImpl<'f> {
433         &self.inner
434     }
435 }
436
437 #[unstable(
438     feature = "c_variadic",
439     reason = "the `c_variadic` feature has not been properly tested on \
440               all supported platforms",
441     issue = "44930"
442 )]
443 impl<'a, 'f: 'a> DerefMut for VaList<'a, 'f> {
444     #[inline]
445     fn deref_mut(&mut self) -> &mut VaListImpl<'f> {
446         &mut self.inner
447     }
448 }
449
450 // The VaArgSafe trait needs to be used in public interfaces, however, the trait
451 // itself must not be allowed to be used outside this module. Allowing users to
452 // implement the trait for a new type (thereby allowing the va_arg intrinsic to
453 // be used on a new type) is likely to cause undefined behavior.
454 //
455 // FIXME(dlrobertson): In order to use the VaArgSafe trait in a public interface
456 // but also ensure it cannot be used elsewhere, the trait needs to be public
457 // within a private module. Once RFC 2145 has been implemented look into
458 // improving this.
459 mod sealed_trait {
460     /// Trait which permits the allowed types to be used with [super::VaListImpl::arg].
461     #[unstable(
462         feature = "c_variadic",
463         reason = "the `c_variadic` feature has not been properly tested on \
464                   all supported platforms",
465         issue = "44930"
466     )]
467     pub trait VaArgSafe {}
468 }
469
470 macro_rules! impl_va_arg_safe {
471     ($($t:ty),+) => {
472         $(
473             #[unstable(feature = "c_variadic",
474                        reason = "the `c_variadic` feature has not been properly tested on \
475                                  all supported platforms",
476                        issue = "44930")]
477             impl sealed_trait::VaArgSafe for $t {}
478         )+
479     }
480 }
481
482 impl_va_arg_safe! {i8, i16, i32, i64, usize}
483 impl_va_arg_safe! {u8, u16, u32, u64, isize}
484 impl_va_arg_safe! {f64}
485
486 #[unstable(
487     feature = "c_variadic",
488     reason = "the `c_variadic` feature has not been properly tested on \
489               all supported platforms",
490     issue = "44930"
491 )]
492 impl<T> sealed_trait::VaArgSafe for *mut T {}
493 #[unstable(
494     feature = "c_variadic",
495     reason = "the `c_variadic` feature has not been properly tested on \
496               all supported platforms",
497     issue = "44930"
498 )]
499 impl<T> sealed_trait::VaArgSafe for *const T {}
500
501 #[unstable(
502     feature = "c_variadic",
503     reason = "the `c_variadic` feature has not been properly tested on \
504               all supported platforms",
505     issue = "44930"
506 )]
507 impl<'f> VaListImpl<'f> {
508     /// Advance to the next arg.
509     #[inline]
510     pub unsafe fn arg<T: sealed_trait::VaArgSafe>(&mut self) -> T {
511         // SAFETY: the caller must uphold the safety contract for `va_arg`.
512         unsafe { va_arg(self) }
513     }
514
515     /// Copies the `va_list` at the current location.
516     pub unsafe fn with_copy<F, R>(&self, f: F) -> R
517     where
518         F: for<'copy> FnOnce(VaList<'copy, 'f>) -> R,
519     {
520         let mut ap = self.clone();
521         let ret = f(ap.as_va_list());
522         // SAFETY: the caller must uphold the safety contract for `va_end`.
523         unsafe {
524             va_end(&mut ap);
525         }
526         ret
527     }
528 }
529
530 #[unstable(
531     feature = "c_variadic",
532     reason = "the `c_variadic` feature has not been properly tested on \
533               all supported platforms",
534     issue = "44930"
535 )]
536 impl<'f> Clone for VaListImpl<'f> {
537     #[inline]
538     fn clone(&self) -> Self {
539         let mut dest = crate::mem::MaybeUninit::uninit();
540         // SAFETY: we write to the `MaybeUninit`, thus it is initialized and `assume_init` is legal
541         unsafe {
542             va_copy(dest.as_mut_ptr(), self);
543             dest.assume_init()
544         }
545     }
546 }
547
548 #[unstable(
549     feature = "c_variadic",
550     reason = "the `c_variadic` feature has not been properly tested on \
551               all supported platforms",
552     issue = "44930"
553 )]
554 impl<'f> Drop for VaListImpl<'f> {
555     fn drop(&mut self) {
556         // FIXME: this should call `va_end`, but there's no clean way to
557         // guarantee that `drop` always gets inlined into its caller,
558         // so the `va_end` would get directly called from the same function as
559         // the corresponding `va_copy`. `man va_end` states that C requires this,
560         // and LLVM basically follows the C semantics, so we need to make sure
561         // that `va_end` is always called from the same function as `va_copy`.
562         // For more details, see https://github.com/rust-lang/rust/pull/59625
563         // and https://llvm.org/docs/LangRef.html#llvm-va-end-intrinsic.
564         //
565         // This works for now, since `va_end` is a no-op on all current LLVM targets.
566     }
567 }
568
569 extern "rust-intrinsic" {
570     /// Destroy the arglist `ap` after initialization with `va_start` or
571     /// `va_copy`.
572     fn va_end(ap: &mut VaListImpl<'_>);
573
574     /// Copies the current location of arglist `src` to the arglist `dst`.
575     fn va_copy<'f>(dest: *mut VaListImpl<'f>, src: &VaListImpl<'f>);
576
577     /// Loads an argument of type `T` from the `va_list` `ap` and increment the
578     /// argument `ap` points to.
579     fn va_arg<T: sealed_trait::VaArgSafe>(ap: &mut VaListImpl<'_>) -> T;
580 }