]> git.lizzy.rs Git - rust.git/blob - library/core/src/ffi/mod.rs
Rollup merge of #106035 - GuillaumeGomez:migrate-css-var-search-tab-title-color,...
[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(
231         not(target_arch = "aarch64"),
232         not(target_arch = "powerpc"),
233         not(target_arch = "s390x"),
234         not(target_arch = "x86_64")
235     ),
236     all(target_arch = "aarch64", any(target_os = "macos", target_os = "ios")),
237     target_family = "wasm",
238     target_arch = "asmjs",
239     target_os = "uefi",
240     windows,
241 ))]
242 #[repr(transparent)]
243 #[unstable(
244     feature = "c_variadic",
245     reason = "the `c_variadic` feature has not been properly tested on \
246               all supported platforms",
247     issue = "44930"
248 )]
249 #[lang = "va_list"]
250 pub struct VaListImpl<'f> {
251     ptr: *mut c_void,
252
253     // Invariant over `'f`, so each `VaListImpl<'f>` object is tied to
254     // the region of the function it's defined in
255     _marker: PhantomData<&'f mut &'f c_void>,
256 }
257
258 #[cfg(any(
259     all(
260         not(target_arch = "aarch64"),
261         not(target_arch = "powerpc"),
262         not(target_arch = "s390x"),
263         not(target_arch = "x86_64")
264     ),
265     all(target_arch = "aarch64", any(target_os = "macos", target_os = "ios")),
266     target_family = "wasm",
267     target_arch = "asmjs",
268     target_os = "uefi",
269     windows,
270 ))]
271 #[unstable(
272     feature = "c_variadic",
273     reason = "the `c_variadic` feature has not been properly tested on \
274               all supported platforms",
275     issue = "44930"
276 )]
277 impl<'f> fmt::Debug for VaListImpl<'f> {
278     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
279         write!(f, "va_list* {:p}", self.ptr)
280     }
281 }
282
283 /// AArch64 ABI implementation of a `va_list`. See the
284 /// [AArch64 Procedure Call Standard] for more details.
285 ///
286 /// [AArch64 Procedure Call Standard]:
287 /// http://infocenter.arm.com/help/topic/com.arm.doc.ihi0055b/IHI0055B_aapcs64.pdf
288 #[cfg(all(
289     target_arch = "aarch64",
290     not(any(target_os = "macos", target_os = "ios")),
291     not(target_os = "uefi"),
292     not(windows),
293 ))]
294 #[repr(C)]
295 #[derive(Debug)]
296 #[unstable(
297     feature = "c_variadic",
298     reason = "the `c_variadic` feature has not been properly tested on \
299               all supported platforms",
300     issue = "44930"
301 )]
302 #[lang = "va_list"]
303 pub struct VaListImpl<'f> {
304     stack: *mut c_void,
305     gr_top: *mut c_void,
306     vr_top: *mut c_void,
307     gr_offs: i32,
308     vr_offs: i32,
309     _marker: PhantomData<&'f mut &'f c_void>,
310 }
311
312 /// PowerPC ABI implementation of a `va_list`.
313 #[cfg(all(target_arch = "powerpc", not(target_os = "uefi"), not(windows)))]
314 #[repr(C)]
315 #[derive(Debug)]
316 #[unstable(
317     feature = "c_variadic",
318     reason = "the `c_variadic` feature has not been properly tested on \
319               all supported platforms",
320     issue = "44930"
321 )]
322 #[lang = "va_list"]
323 pub struct VaListImpl<'f> {
324     gpr: u8,
325     fpr: u8,
326     reserved: u16,
327     overflow_arg_area: *mut c_void,
328     reg_save_area: *mut c_void,
329     _marker: PhantomData<&'f mut &'f c_void>,
330 }
331
332 /// s390x ABI implementation of a `va_list`.
333 #[cfg(target_arch = "s390x")]
334 #[repr(C)]
335 #[derive(Debug)]
336 #[unstable(
337     feature = "c_variadic",
338     reason = "the `c_variadic` feature has not been properly tested on \
339               all supported platforms",
340     issue = "44930"
341 )]
342 #[lang = "va_list"]
343 pub struct VaListImpl<'f> {
344     gpr: i64,
345     fpr: i64,
346     overflow_arg_area: *mut c_void,
347     reg_save_area: *mut c_void,
348     _marker: PhantomData<&'f mut &'f c_void>,
349 }
350
351 /// x86_64 ABI implementation of a `va_list`.
352 #[cfg(all(target_arch = "x86_64", not(target_os = "uefi"), not(windows)))]
353 #[repr(C)]
354 #[derive(Debug)]
355 #[unstable(
356     feature = "c_variadic",
357     reason = "the `c_variadic` feature has not been properly tested on \
358               all supported platforms",
359     issue = "44930"
360 )]
361 #[lang = "va_list"]
362 pub struct VaListImpl<'f> {
363     gp_offset: i32,
364     fp_offset: i32,
365     overflow_arg_area: *mut c_void,
366     reg_save_area: *mut c_void,
367     _marker: PhantomData<&'f mut &'f c_void>,
368 }
369
370 /// A wrapper for a `va_list`
371 #[repr(transparent)]
372 #[derive(Debug)]
373 #[unstable(
374     feature = "c_variadic",
375     reason = "the `c_variadic` feature has not been properly tested on \
376               all supported platforms",
377     issue = "44930"
378 )]
379 pub struct VaList<'a, 'f: 'a> {
380     #[cfg(any(
381         all(
382             not(target_arch = "aarch64"),
383             not(target_arch = "powerpc"),
384             not(target_arch = "s390x"),
385             not(target_arch = "x86_64")
386         ),
387         all(target_arch = "aarch64", any(target_os = "macos", target_os = "ios")),
388         target_family = "wasm",
389         target_arch = "asmjs",
390         target_os = "uefi",
391         windows,
392     ))]
393     inner: VaListImpl<'f>,
394
395     #[cfg(all(
396         any(
397             target_arch = "aarch64",
398             target_arch = "powerpc",
399             target_arch = "s390x",
400             target_arch = "x86_64"
401         ),
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     inner: &'a mut VaListImpl<'f>,
409
410     _marker: PhantomData<&'a mut VaListImpl<'f>>,
411 }
412
413 #[cfg(any(
414     all(
415         not(target_arch = "aarch64"),
416         not(target_arch = "powerpc"),
417         not(target_arch = "s390x"),
418         not(target_arch = "x86_64")
419     ),
420     all(target_arch = "aarch64", any(target_os = "macos", target_os = "ios")),
421     target_family = "wasm",
422     target_arch = "asmjs",
423     target_os = "uefi",
424     windows,
425 ))]
426 #[unstable(
427     feature = "c_variadic",
428     reason = "the `c_variadic` feature has not been properly tested on \
429               all supported platforms",
430     issue = "44930"
431 )]
432 impl<'f> VaListImpl<'f> {
433     /// Convert a `VaListImpl` into a `VaList` that is binary-compatible with C's `va_list`.
434     #[inline]
435     pub fn as_va_list<'a>(&'a mut self) -> VaList<'a, 'f> {
436         VaList { inner: VaListImpl { ..*self }, _marker: PhantomData }
437     }
438 }
439
440 #[cfg(all(
441     any(
442         target_arch = "aarch64",
443         target_arch = "powerpc",
444         target_arch = "s390x",
445         target_arch = "x86_64"
446     ),
447     any(not(target_arch = "aarch64"), not(any(target_os = "macos", target_os = "ios"))),
448     not(target_family = "wasm"),
449     not(target_arch = "asmjs"),
450     not(target_os = "uefi"),
451     not(windows),
452 ))]
453 #[unstable(
454     feature = "c_variadic",
455     reason = "the `c_variadic` feature has not been properly tested on \
456               all supported platforms",
457     issue = "44930"
458 )]
459 impl<'f> VaListImpl<'f> {
460     /// Convert a `VaListImpl` into a `VaList` that is binary-compatible with C's `va_list`.
461     #[inline]
462     pub fn as_va_list<'a>(&'a mut self) -> VaList<'a, 'f> {
463         VaList { inner: self, _marker: PhantomData }
464     }
465 }
466
467 #[unstable(
468     feature = "c_variadic",
469     reason = "the `c_variadic` feature has not been properly tested on \
470               all supported platforms",
471     issue = "44930"
472 )]
473 impl<'a, 'f: 'a> Deref for VaList<'a, 'f> {
474     type Target = VaListImpl<'f>;
475
476     #[inline]
477     fn deref(&self) -> &VaListImpl<'f> {
478         &self.inner
479     }
480 }
481
482 #[unstable(
483     feature = "c_variadic",
484     reason = "the `c_variadic` feature has not been properly tested on \
485               all supported platforms",
486     issue = "44930"
487 )]
488 impl<'a, 'f: 'a> DerefMut for VaList<'a, 'f> {
489     #[inline]
490     fn deref_mut(&mut self) -> &mut VaListImpl<'f> {
491         &mut self.inner
492     }
493 }
494
495 // The VaArgSafe trait needs to be used in public interfaces, however, the trait
496 // itself must not be allowed to be used outside this module. Allowing users to
497 // implement the trait for a new type (thereby allowing the va_arg intrinsic to
498 // be used on a new type) is likely to cause undefined behavior.
499 //
500 // FIXME(dlrobertson): In order to use the VaArgSafe trait in a public interface
501 // but also ensure it cannot be used elsewhere, the trait needs to be public
502 // within a private module. Once RFC 2145 has been implemented look into
503 // improving this.
504 mod sealed_trait {
505     /// Trait which permits the allowed types to be used with [super::VaListImpl::arg].
506     #[unstable(
507         feature = "c_variadic",
508         reason = "the `c_variadic` feature has not been properly tested on \
509                   all supported platforms",
510         issue = "44930"
511     )]
512     pub trait VaArgSafe {}
513 }
514
515 macro_rules! impl_va_arg_safe {
516     ($($t:ty),+) => {
517         $(
518             #[unstable(feature = "c_variadic",
519                        reason = "the `c_variadic` feature has not been properly tested on \
520                                  all supported platforms",
521                        issue = "44930")]
522             impl sealed_trait::VaArgSafe for $t {}
523         )+
524     }
525 }
526
527 impl_va_arg_safe! {i8, i16, i32, i64, usize}
528 impl_va_arg_safe! {u8, u16, u32, u64, isize}
529 impl_va_arg_safe! {f64}
530
531 #[unstable(
532     feature = "c_variadic",
533     reason = "the `c_variadic` feature has not been properly tested on \
534               all supported platforms",
535     issue = "44930"
536 )]
537 impl<T> sealed_trait::VaArgSafe for *mut T {}
538 #[unstable(
539     feature = "c_variadic",
540     reason = "the `c_variadic` feature has not been properly tested on \
541               all supported platforms",
542     issue = "44930"
543 )]
544 impl<T> sealed_trait::VaArgSafe for *const T {}
545
546 #[unstable(
547     feature = "c_variadic",
548     reason = "the `c_variadic` feature has not been properly tested on \
549               all supported platforms",
550     issue = "44930"
551 )]
552 impl<'f> VaListImpl<'f> {
553     /// Advance to the next arg.
554     #[inline]
555     pub unsafe fn arg<T: sealed_trait::VaArgSafe>(&mut self) -> T {
556         // SAFETY: the caller must uphold the safety contract for `va_arg`.
557         unsafe { va_arg(self) }
558     }
559
560     /// Copies the `va_list` at the current location.
561     pub unsafe fn with_copy<F, R>(&self, f: F) -> R
562     where
563         F: for<'copy> FnOnce(VaList<'copy, 'f>) -> R,
564     {
565         let mut ap = self.clone();
566         let ret = f(ap.as_va_list());
567         // SAFETY: the caller must uphold the safety contract for `va_end`.
568         unsafe {
569             va_end(&mut ap);
570         }
571         ret
572     }
573 }
574
575 #[unstable(
576     feature = "c_variadic",
577     reason = "the `c_variadic` feature has not been properly tested on \
578               all supported platforms",
579     issue = "44930"
580 )]
581 impl<'f> Clone for VaListImpl<'f> {
582     #[inline]
583     fn clone(&self) -> Self {
584         let mut dest = crate::mem::MaybeUninit::uninit();
585         // SAFETY: we write to the `MaybeUninit`, thus it is initialized and `assume_init` is legal
586         unsafe {
587             va_copy(dest.as_mut_ptr(), self);
588             dest.assume_init()
589         }
590     }
591 }
592
593 #[unstable(
594     feature = "c_variadic",
595     reason = "the `c_variadic` feature has not been properly tested on \
596               all supported platforms",
597     issue = "44930"
598 )]
599 impl<'f> Drop for VaListImpl<'f> {
600     fn drop(&mut self) {
601         // FIXME: this should call `va_end`, but there's no clean way to
602         // guarantee that `drop` always gets inlined into its caller,
603         // so the `va_end` would get directly called from the same function as
604         // the corresponding `va_copy`. `man va_end` states that C requires this,
605         // and LLVM basically follows the C semantics, so we need to make sure
606         // that `va_end` is always called from the same function as `va_copy`.
607         // For more details, see https://github.com/rust-lang/rust/pull/59625
608         // and https://llvm.org/docs/LangRef.html#llvm-va-end-intrinsic.
609         //
610         // This works for now, since `va_end` is a no-op on all current LLVM targets.
611     }
612 }
613
614 extern "rust-intrinsic" {
615     /// Destroy the arglist `ap` after initialization with `va_start` or
616     /// `va_copy`.
617     fn va_end(ap: &mut VaListImpl<'_>);
618
619     /// Copies the current location of arglist `src` to the arglist `dst`.
620     fn va_copy<'f>(dest: *mut VaListImpl<'f>, src: &VaListImpl<'f>);
621
622     /// Loads an argument of type `T` from the `va_list` `ap` and increment the
623     /// argument `ap` points to.
624     fn va_arg<T: sealed_trait::VaArgSafe>(ap: &mut VaListImpl<'_>) -> T;
625 }