Skip to main content

core/fmt/
rt.rs

1#![allow(missing_debug_implementations)]
2#![unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
3
4//! All types and methods in this file are used by the compiler in
5//! the expansion/lowering of format_args!().
6//!
7//! Do not modify them without understanding the consequences for the format_args!() macro.
8
9use super::*;
10use crate::hint::unreachable_unchecked;
11use crate::ptr::NonNull;
12
13#[derive(Copy, Clone)]
14#[ferrocene::prevalidated]
15enum ArgumentType<'a> {
16    Placeholder {
17        // INVARIANT: `formatter` has type `fn(&T, _) -> _` for some `T`, and `value`
18        // was derived from a `&'a T`.
19        value: NonNull<()>,
20        formatter: unsafe fn(NonNull<()>, &mut Formatter<'_>) -> Result,
21        _lifetime: PhantomData<&'a ()>,
22    },
23    Count(u16),
24}
25
26/// This struct represents a generic "argument" which is taken by format_args!().
27///
28/// This can be either a placeholder argument or a count argument.
29/// * A placeholder argument contains a function to format the given value. At
30///   compile time it is ensured that the function and the value have the correct
31///   types, and then this struct is used to canonicalize arguments to one type.
32///   Placeholder arguments are essentially an optimized partially applied formatting
33///   function, equivalent to `exists T.(&T, fn(&T, &mut Formatter<'_>) -> Result`.
34/// * A count argument contains a count for dynamic formatting parameters like
35///   precision and width.
36#[lang = "format_argument"]
37#[derive(Copy, Clone)]
38#[repr(align(2))] // To ensure pointers to this struct always have their lowest bit cleared.
39#[ferrocene::prevalidated]
40pub struct Argument<'a> {
41    ty: ArgumentType<'a>,
42}
43
44macro_rules! argument_new {
45    ($t:ty, $x:expr, $f:expr) => {
46        Argument {
47            // INVARIANT: this creates an `ArgumentType<'a>` from a `&'a T` and
48            // a `fn(&T, ...)`, so the invariant is maintained.
49            ty: ArgumentType::Placeholder {
50                value: NonNull::<$t>::from_ref($x).cast(),
51                // The Rust ABI considers all pointers to be equivalent, so transmuting a fn(&T) to
52                // fn(NonNull<()>) and calling it with a NonNull<()> that points at a T is allowed.
53                // However, the CFI sanitizer does not allow this, and triggers a crash when it
54                // happens.
55                //
56                // To avoid this crash, we use a helper function when CFI is enabled. To avoid the
57                // cost of this helper function (mainly code-size) when it is not needed, we
58                // transmute the function pointer otherwise.
59                //
60                // This is similar to what the Rust compiler does internally with vtables when KCFI
61                // is enabled, where it generates trampoline functions that only serve to adjust the
62                // expected type of the argument. `ArgumentType::Placeholder` is a bit like a
63                // manually constructed trait object, so it is not surprising that the same approach
64                // has to be applied here as well.
65                //
66                // It is still considered problematic (from the Rust side) that CFI rejects entirely
67                // legal Rust programs, so we do not consider anything done here a stable guarantee,
68                // but meanwhile we carry this work-around to keep Rust compatible with CFI and
69                // KCFI.
70                #[cfg(not(any(sanitize = "cfi", sanitize = "kcfi")))]
71                formatter: {
72                    let f: fn(&$t, &mut Formatter<'_>) -> Result = $f;
73                    // SAFETY: This is only called with `value`, which has the right type.
74                    unsafe { core::mem::transmute(f) }
75                },
76                #[cfg(any(sanitize = "cfi", sanitize = "kcfi"))]
77                formatter: |ptr: NonNull<()>, fmt: &mut Formatter<'_>| {
78                    let func = $f;
79                    // SAFETY: This is the same type as the `value` field.
80                    let r = unsafe { ptr.cast::<$t>().as_ref() };
81                    (func)(r, fmt)
82                },
83                _lifetime: PhantomData,
84            },
85        }
86    };
87}
88
89impl Argument<'_> {
90    #[inline]
91    #[ferrocene::prevalidated]
92    pub const fn new_display<T: Display>(x: &T) -> Argument<'_> {
93        argument_new!(T, x, <T as Display>::fmt)
94    }
95    #[inline]
96    #[ferrocene::prevalidated]
97    pub const fn new_debug<T: Debug>(x: &T) -> Argument<'_> {
98        argument_new!(T, x, <T as Debug>::fmt)
99    }
100    #[ferrocene::annotation(
101        "This function is not publicly available in stable Rust. It is only available in nightly with the \"fmt_internals\" feature enabled. \
102        Also it is not emitted by the compiler unless the unstable compiler option `-Z fmt-debug=none` is passed to `rustc`. Unstable compiler options are not qualified, therefore this function will never be used in qualified code. \
103        See https://github.com/ferrocene/ferrocene/blob/205b3a16164939e0da17deb74285418b3d4991ae/compiler/rustc_ast_lowering/src/format.rs#L247."
104    )]
105    #[inline]
106    #[ferrocene::prevalidated]
107    pub const fn new_debug_noop<T: Debug>(x: &T) -> Argument<'_> {
108        argument_new!(T, x, |_: &T, _| Ok(()))
109    }
110    #[inline]
111    #[ferrocene::prevalidated]
112    pub const fn new_octal<T: Octal>(x: &T) -> Argument<'_> {
113        argument_new!(T, x, <T as Octal>::fmt)
114    }
115    #[inline]
116    #[ferrocene::prevalidated]
117    pub const fn new_lower_hex<T: LowerHex>(x: &T) -> Argument<'_> {
118        argument_new!(T, x, <T as LowerHex>::fmt)
119    }
120    #[inline]
121    #[ferrocene::prevalidated]
122    pub const fn new_upper_hex<T: UpperHex>(x: &T) -> Argument<'_> {
123        argument_new!(T, x, <T as UpperHex>::fmt)
124    }
125    #[inline]
126    #[ferrocene::prevalidated]
127    pub const fn new_pointer<T: Pointer>(x: &T) -> Argument<'_> {
128        argument_new!(T, x, <T as Pointer>::fmt)
129    }
130    #[inline]
131    #[ferrocene::prevalidated]
132    pub const fn new_binary<T: Binary>(x: &T) -> Argument<'_> {
133        argument_new!(T, x, <T as Binary>::fmt)
134    }
135    #[inline]
136    #[ferrocene::prevalidated]
137    pub const fn new_lower_exp<T: LowerExp>(x: &T) -> Argument<'_> {
138        argument_new!(T, x, <T as LowerExp>::fmt)
139    }
140    #[inline]
141    #[ferrocene::prevalidated]
142    pub const fn new_upper_exp<T: UpperExp>(x: &T) -> Argument<'_> {
143        argument_new!(T, x, <T as UpperExp>::fmt)
144    }
145    #[inline]
146    #[track_caller]
147    #[ferrocene::prevalidated]
148    pub const fn from_usize(x: &usize) -> Argument<'_> {
149        if *x > u16::MAX as usize {
150            panic!("Formatting argument out of range");
151        }
152        Argument { ty: ArgumentType::Count(*x as u16) }
153    }
154
155    /// Format this placeholder argument.
156    ///
157    /// # Safety
158    ///
159    /// This argument must actually be a placeholder argument.
160    #[inline]
161    #[ferrocene::prevalidated]
162    pub(super) unsafe fn fmt(&self, f: &mut Formatter<'_>) -> Result {
163        match self.ty {
164            // SAFETY:
165            // Because of the invariant that if `formatter` had the type
166            // `fn(&T, _) -> _` then `value` has type `&'b T` where `'b` is
167            // the lifetime of the `ArgumentType`, and because references
168            // and `NonNull` are ABI-compatible, this is completely equivalent
169            // to calling the original function passed to `new` with the
170            // original reference, which is sound.
171            ArgumentType::Placeholder { formatter, value, .. } => unsafe { formatter(value, f) },
172            #[ferrocene::annotation(
173                "Cannot be covered as this code is unreachable. See the SAFETY comment."
174            )]
175            // SAFETY: the caller promised this.
176            ArgumentType::Count(_) => unsafe { unreachable_unchecked() },
177        }
178    }
179
180    #[inline]
181    #[ferrocene::prevalidated]
182    pub(super) const fn as_u16(&self) -> Option<u16> {
183        match self.ty {
184            ArgumentType::Count(count) => Some(count),
185            ArgumentType::Placeholder { .. } => None,
186        }
187    }
188}