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