core/ffi/
va_list.rs

1//! C's "variable arguments"
2//!
3//! Better known as "varargs".
4
5use crate::ffi::c_void;
6#[allow(unused_imports)]
7use crate::fmt;
8use crate::marker::PhantomData;
9use crate::ops::{Deref, DerefMut};
10
11/// Basic implementation of a `va_list`.
12// The name is WIP, using `VaListImpl` for now.
13#[cfg(any(
14    all(
15        not(target_arch = "aarch64"),
16        not(target_arch = "powerpc"),
17        not(target_arch = "s390x"),
18        not(target_arch = "xtensa"),
19        not(target_arch = "sw64"),
20        not(target_arch = "x86_64")
21    ),
22    all(target_arch = "aarch64", target_vendor = "apple"),
23    target_family = "wasm",
24    target_os = "uefi",
25    windows,
26))]
27#[repr(transparent)]
28#[lang = "va_list"]
29pub struct VaListImpl<'f> {
30    ptr: *mut c_void,
31
32    // Invariant over `'f`, so each `VaListImpl<'f>` object is tied to
33    // the region of the function it's defined in
34    _marker: PhantomData<&'f mut &'f c_void>,
35}
36
37#[cfg(any(
38    all(
39        not(target_arch = "aarch64"),
40        not(target_arch = "powerpc"),
41        not(target_arch = "s390x"),
42        not(target_arch = "xtensa"),
43        not(target_arch = "sw64"),
44        not(target_arch = "x86_64")
45    ),
46    all(target_arch = "aarch64", target_vendor = "apple"),
47    target_family = "wasm",
48    target_os = "uefi",
49    windows,
50))]
51impl<'f> fmt::Debug for VaListImpl<'f> {
52    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53        write!(f, "va_list* {:p}", self.ptr)
54    }
55}
56
57/// AArch64 ABI implementation of a `va_list`. See the
58/// [AArch64 Procedure Call Standard] for more details.
59///
60/// [AArch64 Procedure Call Standard]:
61/// http://infocenter.arm.com/help/topic/com.arm.doc.ihi0055b/IHI0055B_aapcs64.pdf
62#[cfg(all(
63    target_arch = "aarch64",
64    not(target_vendor = "apple"),
65    not(target_os = "uefi"),
66    not(windows),
67))]
68#[cfg_attr(not(doc), repr(C))] // work around https://github.com/rust-lang/rust/issues/66401
69#[derive(Debug)]
70#[lang = "va_list"]
71pub struct VaListImpl<'f> {
72    stack: *mut c_void,
73    gr_top: *mut c_void,
74    vr_top: *mut c_void,
75    gr_offs: i32,
76    vr_offs: i32,
77    _marker: PhantomData<&'f mut &'f c_void>,
78}
79
80/// PowerPC ABI implementation of a `va_list`.
81#[cfg(all(target_arch = "powerpc", not(target_os = "uefi"), not(windows)))]
82#[cfg_attr(not(doc), repr(C))] // work around https://github.com/rust-lang/rust/issues/66401
83#[derive(Debug)]
84#[lang = "va_list"]
85pub struct VaListImpl<'f> {
86    gpr: u8,
87    fpr: u8,
88    reserved: u16,
89    overflow_arg_area: *mut c_void,
90    reg_save_area: *mut c_void,
91    _marker: PhantomData<&'f mut &'f c_void>,
92}
93
94/// s390x ABI implementation of a `va_list`.
95#[cfg(target_arch = "s390x")]
96#[cfg_attr(not(doc), repr(C))] // work around https://github.com/rust-lang/rust/issues/66401
97#[derive(Debug)]
98#[lang = "va_list"]
99pub struct VaListImpl<'f> {
100    gpr: i64,
101    fpr: i64,
102    overflow_arg_area: *mut c_void,
103    reg_save_area: *mut c_void,
104    _marker: PhantomData<&'f mut &'f c_void>,
105}
106
107/// sw64 ABI implementation of a `va_list`.
108#[cfg(target_arch = "sw64")]
109#[cfg_attr(not(doc), repr(C))] // work around https://github.com/rust-lang/rust/issues/66401
110#[derive(Debug)]
111#[lang = "va_list"]
112pub struct VaListImpl<'f> {
113    stack: *mut c_void,
114    offs: i32,
115    _marker: PhantomData<&'f mut &'f c_void>,
116}
117
118/// x86_64 ABI implementation of a `va_list`.
119#[cfg(all(target_arch = "x86_64", not(target_os = "uefi"), not(windows)))]
120#[cfg_attr(not(doc), repr(C))] // work around https://github.com/rust-lang/rust/issues/66401
121#[derive(Debug)]
122#[lang = "va_list"]
123pub struct VaListImpl<'f> {
124    gp_offset: i32,
125    fp_offset: i32,
126    overflow_arg_area: *mut c_void,
127    reg_save_area: *mut c_void,
128    _marker: PhantomData<&'f mut &'f c_void>,
129}
130
131/// Xtensa ABI implementation of a `va_list`.
132#[cfg(target_arch = "xtensa")]
133#[repr(C)]
134#[derive(Debug)]
135#[lang = "va_list"]
136pub struct VaListImpl<'f> {
137    stk: *mut i32,
138    reg: *mut i32,
139    ndx: i32,
140    _marker: PhantomData<&'f mut &'f c_void>,
141}
142
143/// A wrapper for a `va_list`
144#[repr(transparent)]
145#[derive(Debug)]
146pub struct VaList<'a, 'f: 'a> {
147    #[cfg(any(
148        all(
149            not(target_arch = "aarch64"),
150            not(target_arch = "powerpc"),
151            not(target_arch = "s390x"),
152            not(target_arch = "x86_64")
153        ),
154        target_arch = "xtensa",
155        all(target_arch = "aarch64", target_vendor = "apple"),
156        target_family = "wasm",
157        target_os = "uefi",
158        windows,
159    ))]
160    inner: VaListImpl<'f>,
161
162    #[cfg(all(
163        any(
164            target_arch = "aarch64",
165            target_arch = "powerpc",
166            target_arch = "s390x",
167            target_arch = "x86_64"
168        ),
169        not(target_arch = "xtensa"),
170        any(not(target_arch = "aarch64"), not(target_vendor = "apple")),
171        not(target_family = "wasm"),
172        not(target_os = "uefi"),
173        not(windows),
174    ))]
175    inner: &'a mut VaListImpl<'f>,
176
177    _marker: PhantomData<&'a mut VaListImpl<'f>>,
178}
179
180#[cfg(any(
181    all(
182        not(target_arch = "aarch64"),
183        not(target_arch = "powerpc"),
184        not(target_arch = "s390x"),
185        not(target_arch = "x86_64")
186    ),
187    target_arch = "xtensa",
188    all(target_arch = "aarch64", target_vendor = "apple"),
189    target_family = "wasm",
190    target_os = "uefi",
191    windows,
192))]
193impl<'f> VaListImpl<'f> {
194    /// Converts a `VaListImpl` into a `VaList` that is binary-compatible with C's `va_list`.
195    #[inline]
196    pub fn as_va_list<'a>(&'a mut self) -> VaList<'a, 'f> {
197        VaList { inner: VaListImpl { ..*self }, _marker: PhantomData }
198    }
199}
200
201#[cfg(all(
202    any(
203        target_arch = "aarch64",
204        target_arch = "powerpc",
205        target_arch = "s390x",
206        target_arch = "xtensa",
207        target_arch = "x86_64"
208    ),
209    not(target_arch = "xtensa"),
210    any(not(target_arch = "aarch64"), not(target_vendor = "apple")),
211    not(target_family = "wasm"),
212    not(target_os = "uefi"),
213    not(windows),
214))]
215impl<'f> VaListImpl<'f> {
216    /// Converts a `VaListImpl` into a `VaList` that is binary-compatible with C's `va_list`.
217    #[inline]
218    pub fn as_va_list<'a>(&'a mut self) -> VaList<'a, 'f> {
219        VaList { inner: self, _marker: PhantomData }
220    }
221}
222
223impl<'a, 'f: 'a> Deref for VaList<'a, 'f> {
224    type Target = VaListImpl<'f>;
225
226    #[inline]
227    fn deref(&self) -> &VaListImpl<'f> {
228        &self.inner
229    }
230}
231
232impl<'a, 'f: 'a> DerefMut for VaList<'a, 'f> {
233    #[inline]
234    fn deref_mut(&mut self) -> &mut VaListImpl<'f> {
235        &mut self.inner
236    }
237}
238
239// The VaArgSafe trait needs to be used in public interfaces, however, the trait
240// itself must not be allowed to be used outside this module. Allowing users to
241// implement the trait for a new type (thereby allowing the va_arg intrinsic to
242// be used on a new type) is likely to cause undefined behavior.
243//
244// FIXME(dlrobertson): In order to use the VaArgSafe trait in a public interface
245// but also ensure it cannot be used elsewhere, the trait needs to be public
246// within a private module. Once RFC 2145 has been implemented look into
247// improving this.
248mod sealed_trait {
249    /// Trait which permits the allowed types to be used with [super::VaListImpl::arg].
250    pub unsafe trait VaArgSafe {}
251}
252
253macro_rules! impl_va_arg_safe {
254    ($($t:ty),+) => {
255        $(
256            unsafe impl sealed_trait::VaArgSafe for $t {}
257        )+
258    }
259}
260
261impl_va_arg_safe! {i8, i16, i32, i64, usize}
262impl_va_arg_safe! {u8, u16, u32, u64, isize}
263impl_va_arg_safe! {f64}
264
265unsafe impl<T> sealed_trait::VaArgSafe for *mut T {}
266unsafe impl<T> sealed_trait::VaArgSafe for *const T {}
267
268impl<'f> VaListImpl<'f> {
269    /// Advance to the next arg.
270    #[inline]
271    pub unsafe fn arg<T: sealed_trait::VaArgSafe>(&mut self) -> T {
272        // SAFETY: the caller must uphold the safety contract for `va_arg`.
273        unsafe { va_arg(self) }
274    }
275
276    /// Copies the `va_list` at the current location.
277    pub unsafe fn with_copy<F, R>(&self, f: F) -> R
278    where
279        F: for<'copy> FnOnce(VaList<'copy, 'f>) -> R,
280    {
281        let mut ap = self.clone();
282        let ret = f(ap.as_va_list());
283        // SAFETY: the caller must uphold the safety contract for `va_end`.
284        unsafe {
285            va_end(&mut ap);
286        }
287        ret
288    }
289}
290
291impl<'f> Clone for VaListImpl<'f> {
292    #[inline]
293    fn clone(&self) -> Self {
294        let mut dest = crate::mem::MaybeUninit::uninit();
295        // SAFETY: we write to the `MaybeUninit`, thus it is initialized and `assume_init` is legal
296        unsafe {
297            va_copy(dest.as_mut_ptr(), self);
298            dest.assume_init()
299        }
300    }
301}
302
303impl<'f> Drop for VaListImpl<'f> {
304    fn drop(&mut self) {
305        // FIXME: this should call `va_end`, but there's no clean way to
306        // guarantee that `drop` always gets inlined into its caller,
307        // so the `va_end` would get directly called from the same function as
308        // the corresponding `va_copy`. `man va_end` states that C requires this,
309        // and LLVM basically follows the C semantics, so we need to make sure
310        // that `va_end` is always called from the same function as `va_copy`.
311        // For more details, see https://github.com/rust-lang/rust/pull/59625
312        // and https://llvm.org/docs/LangRef.html#llvm-va-end-intrinsic.
313        //
314        // This works for now, since `va_end` is a no-op on all current LLVM targets.
315    }
316}
317
318/// Destroy the arglist `ap` after initialization with `va_start` or
319/// `va_copy`.
320#[rustc_intrinsic]
321#[rustc_intrinsic_must_be_overridden]
322#[rustc_nounwind]
323unsafe fn va_end(_ap: &mut VaListImpl<'_>) {
324    unreachable!()
325}
326
327/// Copies the current location of arglist `src` to the arglist `dst`.
328#[rustc_intrinsic]
329#[rustc_intrinsic_must_be_overridden]
330#[rustc_nounwind]
331unsafe fn va_copy<'f>(_dest: *mut VaListImpl<'f>, _src: &VaListImpl<'f>) {
332    unreachable!()
333}
334
335/// Loads an argument of type `T` from the `va_list` `ap` and increment the
336/// argument `ap` points to.
337#[rustc_intrinsic]
338#[rustc_intrinsic_must_be_overridden]
339#[rustc_nounwind]
340unsafe fn va_arg<T: sealed_trait::VaArgSafe>(_ap: &mut VaListImpl<'_>) -> T {
341    unreachable!()
342}