]> git.lizzy.rs Git - rust.git/blob - library/core/src/ffi/mod.rs
library/core: Fixes implement of c_uint, c_long, c_ulong
[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 #[unstable(feature = "core_c_str", issue = "94079")]
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         #[unstable(feature = "core_ffi_c", issue = "94501")]
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         ))] {
148             pub type c_char = u8;
149             pub type NonZero_c_char = crate::num::NonZeroU8;
150         } else {
151             // On every other target, c_char is signed.
152             pub type c_char = i8;
153             pub type NonZero_c_char = crate::num::NonZeroI8;
154         }
155     }
156 }
157
158 mod c_int_definition {
159     cfg_if! {
160         if #[cfg(any(target_arch = "avr", target_arch = "msp430"))] {
161             pub type c_int = i16;
162             pub type NonZero_c_int = crate::num::NonZeroI16;
163             pub type c_uint = u16;
164             pub type NonZero_c_uint = crate::num::NonZeroU16;
165         } else {
166             pub type c_int = i32;
167             pub type NonZero_c_int = crate::num::NonZeroI32;
168             pub type c_uint = u32;
169             pub type NonZero_c_uint = crate::num::NonZeroU32;
170         }
171     }
172 }
173
174 mod c_long_definition {
175     cfg_if! {
176         if #[cfg(all(target_pointer_width = "64", not(windows)))] {
177             pub type c_long = i64;
178             pub type NonZero_c_long = crate::num::NonZeroI64;
179             pub type c_ulong = u64;
180             pub type NonZero_c_ulong = crate::num::NonZeroU64;
181         } else {
182             // The minimal size of `long` in c standard are 32 bits
183             pub type c_long = i32;
184             pub type NonZero_c_long = crate::num::NonZeroI32;
185             pub type c_ulong = u32;
186             pub type NonZero_c_ulong = crate::num::NonZeroU32;
187         }
188     }
189 }
190
191 // N.B., for LLVM to recognize the void pointer type and by extension
192 //     functions like malloc(), we need to have it represented as i8* in
193 //     LLVM bitcode. The enum used here ensures this and prevents misuse
194 //     of the "raw" type by only having private variants. We need two
195 //     variants, because the compiler complains about the repr attribute
196 //     otherwise and we need at least one variant as otherwise the enum
197 //     would be uninhabited and at least dereferencing such pointers would
198 //     be UB.
199 #[doc = include_str!("c_void.md")]
200 #[repr(u8)]
201 #[stable(feature = "core_c_void", since = "1.30.0")]
202 pub enum c_void {
203     #[unstable(
204         feature = "c_void_variant",
205         reason = "temporary implementation detail",
206         issue = "none"
207     )]
208     #[doc(hidden)]
209     __variant1,
210     #[unstable(
211         feature = "c_void_variant",
212         reason = "temporary implementation detail",
213         issue = "none"
214     )]
215     #[doc(hidden)]
216     __variant2,
217 }
218
219 #[stable(feature = "std_debug", since = "1.16.0")]
220 impl fmt::Debug for c_void {
221     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
222         f.debug_struct("c_void").finish()
223     }
224 }
225
226 /// Basic implementation of a `va_list`.
227 // The name is WIP, using `VaListImpl` for now.
228 #[cfg(any(
229     all(not(target_arch = "aarch64"), not(target_arch = "powerpc"), not(target_arch = "x86_64")),
230     all(target_arch = "aarch64", any(target_os = "macos", target_os = "ios")),
231     target_family = "wasm",
232     target_arch = "asmjs",
233     windows
234 ))]
235 #[repr(transparent)]
236 #[unstable(
237     feature = "c_variadic",
238     reason = "the `c_variadic` feature has not been properly tested on \
239               all supported platforms",
240     issue = "44930"
241 )]
242 #[lang = "va_list"]
243 pub struct VaListImpl<'f> {
244     ptr: *mut c_void,
245
246     // Invariant over `'f`, so each `VaListImpl<'f>` object is tied to
247     // the region of the function it's defined in
248     _marker: PhantomData<&'f mut &'f c_void>,
249 }
250
251 #[cfg(any(
252     all(not(target_arch = "aarch64"), not(target_arch = "powerpc"), not(target_arch = "x86_64")),
253     all(target_arch = "aarch64", any(target_os = "macos", target_os = "ios")),
254     target_family = "wasm",
255     target_arch = "asmjs",
256     windows
257 ))]
258 #[unstable(
259     feature = "c_variadic",
260     reason = "the `c_variadic` feature has not been properly tested on \
261               all supported platforms",
262     issue = "44930"
263 )]
264 impl<'f> fmt::Debug for VaListImpl<'f> {
265     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
266         write!(f, "va_list* {:p}", self.ptr)
267     }
268 }
269
270 /// AArch64 ABI implementation of a `va_list`. See the
271 /// [AArch64 Procedure Call Standard] for more details.
272 ///
273 /// [AArch64 Procedure Call Standard]:
274 /// http://infocenter.arm.com/help/topic/com.arm.doc.ihi0055b/IHI0055B_aapcs64.pdf
275 #[cfg(all(
276     target_arch = "aarch64",
277     not(any(target_os = "macos", target_os = "ios")),
278     not(windows)
279 ))]
280 #[repr(C)]
281 #[derive(Debug)]
282 #[unstable(
283     feature = "c_variadic",
284     reason = "the `c_variadic` feature has not been properly tested on \
285               all supported platforms",
286     issue = "44930"
287 )]
288 #[lang = "va_list"]
289 pub struct VaListImpl<'f> {
290     stack: *mut c_void,
291     gr_top: *mut c_void,
292     vr_top: *mut c_void,
293     gr_offs: i32,
294     vr_offs: i32,
295     _marker: PhantomData<&'f mut &'f c_void>,
296 }
297
298 /// PowerPC ABI implementation of a `va_list`.
299 #[cfg(all(target_arch = "powerpc", not(windows)))]
300 #[repr(C)]
301 #[derive(Debug)]
302 #[unstable(
303     feature = "c_variadic",
304     reason = "the `c_variadic` feature has not been properly tested on \
305               all supported platforms",
306     issue = "44930"
307 )]
308 #[lang = "va_list"]
309 pub struct VaListImpl<'f> {
310     gpr: u8,
311     fpr: u8,
312     reserved: u16,
313     overflow_arg_area: *mut c_void,
314     reg_save_area: *mut c_void,
315     _marker: PhantomData<&'f mut &'f c_void>,
316 }
317
318 /// x86_64 ABI implementation of a `va_list`.
319 #[cfg(all(target_arch = "x86_64", not(windows)))]
320 #[repr(C)]
321 #[derive(Debug)]
322 #[unstable(
323     feature = "c_variadic",
324     reason = "the `c_variadic` feature has not been properly tested on \
325               all supported platforms",
326     issue = "44930"
327 )]
328 #[lang = "va_list"]
329 pub struct VaListImpl<'f> {
330     gp_offset: i32,
331     fp_offset: i32,
332     overflow_arg_area: *mut c_void,
333     reg_save_area: *mut c_void,
334     _marker: PhantomData<&'f mut &'f c_void>,
335 }
336
337 /// A wrapper for a `va_list`
338 #[repr(transparent)]
339 #[derive(Debug)]
340 #[unstable(
341     feature = "c_variadic",
342     reason = "the `c_variadic` feature has not been properly tested on \
343               all supported platforms",
344     issue = "44930"
345 )]
346 pub struct VaList<'a, 'f: 'a> {
347     #[cfg(any(
348         all(
349             not(target_arch = "aarch64"),
350             not(target_arch = "powerpc"),
351             not(target_arch = "x86_64")
352         ),
353         all(target_arch = "aarch64", any(target_os = "macos", target_os = "ios")),
354         target_family = "wasm",
355         target_arch = "asmjs",
356         windows
357     ))]
358     inner: VaListImpl<'f>,
359
360     #[cfg(all(
361         any(target_arch = "aarch64", target_arch = "powerpc", target_arch = "x86_64"),
362         any(not(target_arch = "aarch64"), not(any(target_os = "macos", target_os = "ios"))),
363         not(target_family = "wasm"),
364         not(target_arch = "asmjs"),
365         not(windows)
366     ))]
367     inner: &'a mut VaListImpl<'f>,
368
369     _marker: PhantomData<&'a mut VaListImpl<'f>>,
370 }
371
372 #[cfg(any(
373     all(not(target_arch = "aarch64"), not(target_arch = "powerpc"), not(target_arch = "x86_64")),
374     all(target_arch = "aarch64", any(target_os = "macos", target_os = "ios")),
375     target_family = "wasm",
376     target_arch = "asmjs",
377     windows
378 ))]
379 #[unstable(
380     feature = "c_variadic",
381     reason = "the `c_variadic` feature has not been properly tested on \
382               all supported platforms",
383     issue = "44930"
384 )]
385 impl<'f> VaListImpl<'f> {
386     /// Convert a `VaListImpl` into a `VaList` that is binary-compatible with C's `va_list`.
387     #[inline]
388     pub fn as_va_list<'a>(&'a mut self) -> VaList<'a, 'f> {
389         VaList { inner: VaListImpl { ..*self }, _marker: PhantomData }
390     }
391 }
392
393 #[cfg(all(
394     any(target_arch = "aarch64", target_arch = "powerpc", target_arch = "x86_64"),
395     any(not(target_arch = "aarch64"), not(any(target_os = "macos", target_os = "ios"))),
396     not(target_family = "wasm"),
397     not(target_arch = "asmjs"),
398     not(windows)
399 ))]
400 #[unstable(
401     feature = "c_variadic",
402     reason = "the `c_variadic` feature has not been properly tested on \
403               all supported platforms",
404     issue = "44930"
405 )]
406 impl<'f> VaListImpl<'f> {
407     /// Convert a `VaListImpl` into a `VaList` that is binary-compatible with C's `va_list`.
408     #[inline]
409     pub fn as_va_list<'a>(&'a mut self) -> VaList<'a, 'f> {
410         VaList { inner: self, _marker: PhantomData }
411     }
412 }
413
414 #[unstable(
415     feature = "c_variadic",
416     reason = "the `c_variadic` feature has not been properly tested on \
417               all supported platforms",
418     issue = "44930"
419 )]
420 impl<'a, 'f: 'a> Deref for VaList<'a, 'f> {
421     type Target = VaListImpl<'f>;
422
423     #[inline]
424     fn deref(&self) -> &VaListImpl<'f> {
425         &self.inner
426     }
427 }
428
429 #[unstable(
430     feature = "c_variadic",
431     reason = "the `c_variadic` feature has not been properly tested on \
432               all supported platforms",
433     issue = "44930"
434 )]
435 impl<'a, 'f: 'a> DerefMut for VaList<'a, 'f> {
436     #[inline]
437     fn deref_mut(&mut self) -> &mut VaListImpl<'f> {
438         &mut self.inner
439     }
440 }
441
442 // The VaArgSafe trait needs to be used in public interfaces, however, the trait
443 // itself must not be allowed to be used outside this module. Allowing users to
444 // implement the trait for a new type (thereby allowing the va_arg intrinsic to
445 // be used on a new type) is likely to cause undefined behavior.
446 //
447 // FIXME(dlrobertson): In order to use the VaArgSafe trait in a public interface
448 // but also ensure it cannot be used elsewhere, the trait needs to be public
449 // within a private module. Once RFC 2145 has been implemented look into
450 // improving this.
451 mod sealed_trait {
452     /// Trait which permits the allowed types to be used with [super::VaListImpl::arg].
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     pub trait VaArgSafe {}
460 }
461
462 macro_rules! impl_va_arg_safe {
463     ($($t:ty),+) => {
464         $(
465             #[unstable(feature = "c_variadic",
466                        reason = "the `c_variadic` feature has not been properly tested on \
467                                  all supported platforms",
468                        issue = "44930")]
469             impl sealed_trait::VaArgSafe for $t {}
470         )+
471     }
472 }
473
474 impl_va_arg_safe! {i8, i16, i32, i64, usize}
475 impl_va_arg_safe! {u8, u16, u32, u64, isize}
476 impl_va_arg_safe! {f64}
477
478 #[unstable(
479     feature = "c_variadic",
480     reason = "the `c_variadic` feature has not been properly tested on \
481               all supported platforms",
482     issue = "44930"
483 )]
484 impl<T> sealed_trait::VaArgSafe for *mut T {}
485 #[unstable(
486     feature = "c_variadic",
487     reason = "the `c_variadic` feature has not been properly tested on \
488               all supported platforms",
489     issue = "44930"
490 )]
491 impl<T> sealed_trait::VaArgSafe for *const T {}
492
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<'f> VaListImpl<'f> {
500     /// Advance to the next arg.
501     #[inline]
502     pub unsafe fn arg<T: sealed_trait::VaArgSafe>(&mut self) -> T {
503         // SAFETY: the caller must uphold the safety contract for `va_arg`.
504         unsafe { va_arg(self) }
505     }
506
507     /// Copies the `va_list` at the current location.
508     pub unsafe fn with_copy<F, R>(&self, f: F) -> R
509     where
510         F: for<'copy> FnOnce(VaList<'copy, 'f>) -> R,
511     {
512         let mut ap = self.clone();
513         let ret = f(ap.as_va_list());
514         // SAFETY: the caller must uphold the safety contract for `va_end`.
515         unsafe {
516             va_end(&mut ap);
517         }
518         ret
519     }
520 }
521
522 #[unstable(
523     feature = "c_variadic",
524     reason = "the `c_variadic` feature has not been properly tested on \
525               all supported platforms",
526     issue = "44930"
527 )]
528 impl<'f> Clone for VaListImpl<'f> {
529     #[inline]
530     fn clone(&self) -> Self {
531         let mut dest = crate::mem::MaybeUninit::uninit();
532         // SAFETY: we write to the `MaybeUninit`, thus it is initialized and `assume_init` is legal
533         unsafe {
534             va_copy(dest.as_mut_ptr(), self);
535             dest.assume_init()
536         }
537     }
538 }
539
540 #[unstable(
541     feature = "c_variadic",
542     reason = "the `c_variadic` feature has not been properly tested on \
543               all supported platforms",
544     issue = "44930"
545 )]
546 impl<'f> Drop for VaListImpl<'f> {
547     fn drop(&mut self) {
548         // FIXME: this should call `va_end`, but there's no clean way to
549         // guarantee that `drop` always gets inlined into its caller,
550         // so the `va_end` would get directly called from the same function as
551         // the corresponding `va_copy`. `man va_end` states that C requires this,
552         // and LLVM basically follows the C semantics, so we need to make sure
553         // that `va_end` is always called from the same function as `va_copy`.
554         // For more details, see https://github.com/rust-lang/rust/pull/59625
555         // and https://llvm.org/docs/LangRef.html#llvm-va-end-intrinsic.
556         //
557         // This works for now, since `va_end` is a no-op on all current LLVM targets.
558     }
559 }
560
561 extern "rust-intrinsic" {
562     /// Destroy the arglist `ap` after initialization with `va_start` or
563     /// `va_copy`.
564     fn va_end(ap: &mut VaListImpl<'_>);
565
566     /// Copies the current location of arglist `src` to the arglist `dst`.
567     fn va_copy<'f>(dest: *mut VaListImpl<'f>, src: &VaListImpl<'f>);
568
569     /// Loads an argument of type `T` from the `va_list` `ap` and increment the
570     /// argument `ap` points to.
571     fn va_arg<T: sealed_trait::VaArgSafe>(ap: &mut VaListImpl<'_>) -> T;
572 }