]> git.lizzy.rs Git - rust.git/blob - src/libcore/ffi.rs
Auto merge of #61361 - estebank:infer-type, r=varkor
[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
9 /// Equivalent to C's `void` type when used as a [pointer].
10 ///
11 /// In essence, `*const c_void` is equivalent to C's `const void*`
12 /// and `*mut c_void` is equivalent to C's `void*`. That said, this is
13 /// *not* the same as C's `void` return type, which is Rust's `()` type.
14 ///
15 /// To model pointers to opaque types in FFI, until `extern type` is
16 /// stabilized, it is recommended to use a newtype wrapper around an empty
17 /// byte array. See the [Nomicon] for details.
18 ///
19 /// [pointer]: ../../std/primitive.pointer.html
20 /// [Nomicon]: https://doc.rust-lang.org/nomicon/ffi.html#representing-opaque-structs
21 // N.B., for LLVM to recognize the void pointer type and by extension
22 //     functions like malloc(), we need to have it represented as i8* in
23 //     LLVM bitcode. The enum used here ensures this and prevents misuse
24 //     of the "raw" type by only having private variants. We need two
25 //     variants, because the compiler complains about the repr attribute
26 //     otherwise and we need at least one variant as otherwise the enum
27 //     would be uninhabited and at least dereferencing such pointers would
28 //     be UB.
29 #[repr(u8)]
30 #[stable(feature = "raw_os", since = "1.1.0")]
31 pub enum c_void {
32     #[unstable(feature = "c_void_variant", reason = "temporary implementation detail",
33                issue = "0")]
34     #[doc(hidden)] __variant1,
35     #[unstable(feature = "c_void_variant", reason = "temporary implementation detail",
36                issue = "0")]
37     #[doc(hidden)] __variant2,
38 }
39
40 #[stable(feature = "std_debug", since = "1.16.0")]
41 impl fmt::Debug for c_void {
42     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43         f.pad("c_void")
44     }
45 }
46
47 /// Basic implementation of a `va_list`.
48 #[cfg(any(all(not(target_arch = "aarch64"), not(target_arch = "powerpc"),
49               not(target_arch = "x86_64")),
50           all(target_arch = "aarch64", target_os = "ios"),
51           windows))]
52 #[unstable(feature = "c_variadic",
53            reason = "the `c_variadic` feature has not been properly tested on \
54                      all supported platforms",
55            issue = "44930")]
56 extern {
57     type VaListImpl;
58 }
59
60 #[cfg(any(all(not(target_arch = "aarch64"), not(target_arch = "powerpc"),
61               not(target_arch = "x86_64")),
62           all(target_arch = "aarch64", target_os = "ios"),
63           windows))]
64 impl fmt::Debug for VaListImpl {
65     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66         write!(f, "va_list* {:p}", self)
67     }
68 }
69
70 /// AArch64 ABI implementation of a `va_list`. See the
71 /// [AArch64 Procedure Call Standard] for more details.
72 ///
73 /// [AArch64 Procedure Call Standard]:
74 /// http://infocenter.arm.com/help/topic/com.arm.doc.ihi0055b/IHI0055B_aapcs64.pdf
75 #[cfg(all(target_arch = "aarch64", not(target_os = "ios"), not(windows)))]
76 #[repr(C)]
77 #[derive(Debug)]
78 #[unstable(feature = "c_variadic",
79            reason = "the `c_variadic` feature has not been properly tested on \
80                      all supported platforms",
81            issue = "44930")]
82 struct VaListImpl {
83     stack: *mut c_void,
84     gr_top: *mut c_void,
85     vr_top: *mut c_void,
86     gr_offs: i32,
87     vr_offs: i32,
88 }
89
90 /// PowerPC ABI implementation of a `va_list`.
91 #[cfg(all(target_arch = "powerpc", not(windows)))]
92 #[repr(C)]
93 #[derive(Debug)]
94 #[unstable(feature = "c_variadic",
95            reason = "the `c_variadic` feature has not been properly tested on \
96                      all supported platforms",
97            issue = "44930")]
98 struct VaListImpl {
99     gpr: u8,
100     fpr: u8,
101     reserved: u16,
102     overflow_arg_area: *mut c_void,
103     reg_save_area: *mut c_void,
104 }
105
106 /// x86_64 ABI implementation of a `va_list`.
107 #[cfg(all(target_arch = "x86_64", not(windows)))]
108 #[repr(C)]
109 #[derive(Debug)]
110 #[unstable(feature = "c_variadic",
111            reason = "the `c_variadic` feature has not been properly tested on \
112                      all supported platforms",
113            issue = "44930")]
114 struct VaListImpl {
115     gp_offset: i32,
116     fp_offset: i32,
117     overflow_arg_area: *mut c_void,
118     reg_save_area: *mut c_void,
119 }
120
121 /// A wrapper for a `va_list`
122 #[lang = "va_list"]
123 #[derive(Debug)]
124 #[unstable(feature = "c_variadic",
125            reason = "the `c_variadic` feature has not been properly tested on \
126                      all supported platforms",
127            issue = "44930")]
128 #[repr(transparent)]
129 pub struct VaList<'a>(&'a mut VaListImpl);
130
131 // The VaArgSafe trait needs to be used in public interfaces, however, the trait
132 // itself must not be allowed to be used outside this module. Allowing users to
133 // implement the trait for a new type (thereby allowing the va_arg intrinsic to
134 // be used on a new type) is likely to cause undefined behavior.
135 //
136 // FIXME(dlrobertson): In order to use the VaArgSafe trait in a public interface
137 // but also ensure it cannot be used elsewhere, the trait needs to be public
138 // within a private module. Once RFC 2145 has been implemented look into
139 // improving this.
140 mod sealed_trait {
141     /// Trait which whitelists the allowed types to be used with [VaList::arg]
142     ///
143     /// [VaList::va_arg]: struct.VaList.html#method.arg
144     #[unstable(feature = "c_variadic",
145                reason = "the `c_variadic` feature has not been properly tested on \
146                          all supported platforms",
147                issue = "44930")]
148     pub trait VaArgSafe {}
149 }
150
151 macro_rules! impl_va_arg_safe {
152     ($($t:ty),+) => {
153         $(
154             #[unstable(feature = "c_variadic",
155                        reason = "the `c_variadic` feature has not been properly tested on \
156                                  all supported platforms",
157                        issue = "44930")]
158             impl sealed_trait::VaArgSafe for $t {}
159         )+
160     }
161 }
162
163 impl_va_arg_safe!{i8, i16, i32, i64, usize}
164 impl_va_arg_safe!{u8, u16, u32, u64, isize}
165 impl_va_arg_safe!{f64}
166
167 #[unstable(feature = "c_variadic",
168            reason = "the `c_variadic` feature has not been properly tested on \
169                      all supported platforms",
170            issue = "44930")]
171 impl<T> sealed_trait::VaArgSafe for *mut T {}
172 #[unstable(feature = "c_variadic",
173            reason = "the `c_variadic` feature has not been properly tested on \
174                      all supported platforms",
175            issue = "44930")]
176 impl<T> sealed_trait::VaArgSafe for *const T {}
177
178 impl<'a> VaList<'a> {
179     /// Advance to the next arg.
180     #[unstable(feature = "c_variadic",
181                reason = "the `c_variadic` feature has not been properly tested on \
182                          all supported platforms",
183                issue = "44930")]
184     pub unsafe fn arg<T: sealed_trait::VaArgSafe>(&mut self) -> T {
185         va_arg(self)
186     }
187
188     /// Copies the `va_list` at the current location.
189     #[unstable(feature = "c_variadic",
190                reason = "the `c_variadic` feature has not been properly tested on \
191                          all supported platforms",
192                issue = "44930")]
193     pub unsafe fn with_copy<F, R>(&self, f: F) -> R
194             where F: for<'copy> FnOnce(VaList<'copy>) -> R {
195         #[cfg(any(all(not(target_arch = "aarch64"), not(target_arch = "powerpc"),
196                       not(target_arch = "x86_64")),
197                   all(target_arch = "aarch64", target_os = "ios"),
198                   windows))]
199         let mut ap = va_copy(self);
200         #[cfg(all(any(target_arch = "aarch64", target_arch = "powerpc", target_arch = "x86_64"),
201                   not(windows), not(all(target_arch = "aarch64", target_os = "ios"))))]
202         let mut ap_inner = va_copy(self);
203         #[cfg(all(any(target_arch = "aarch64", target_arch = "powerpc", target_arch = "x86_64"),
204                   not(windows), not(all(target_arch = "aarch64", target_os = "ios"))))]
205         let mut ap = VaList(&mut ap_inner);
206         let ret = f(VaList(ap.0));
207         va_end(&mut ap);
208         ret
209     }
210 }
211
212 extern "rust-intrinsic" {
213     /// Destroy the arglist `ap` after initialization with `va_start` or
214     /// `va_copy`.
215     fn va_end(ap: &mut VaList<'_>);
216
217     /// Copies the current location of arglist `src` to the arglist `dst`.
218     #[cfg(any(all(not(target_arch = "aarch64"), not(target_arch = "powerpc"),
219                   not(target_arch = "x86_64")),
220               all(target_arch = "aarch64", target_os = "ios"),
221               windows))]
222     fn va_copy<'a>(src: &VaList<'a>) -> VaList<'a>;
223     #[cfg(all(any(target_arch = "aarch64", target_arch = "powerpc", target_arch = "x86_64"),
224               not(windows), not(all(target_arch = "aarch64", target_os = "ios"))))]
225     fn va_copy(src: &VaList<'_>) -> VaListImpl;
226
227     /// Loads an argument of type `T` from the `va_list` `ap` and increment the
228     /// argument `ap` points to.
229     fn va_arg<T: sealed_trait::VaArgSafe>(ap: &mut VaList<'_>) -> T;
230 }