Skip to main content

reverie_syscalls/
display.rs

1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 * All rights reserved.
4 *
5 * This source code is licensed under the BSD-style license found in the
6 * LICENSE file in the root directory of this source tree.
7 */
8
9use core::fmt;
10
11use nix::fcntl::AtFlags;
12use nix::fcntl::OFlag;
13use nix::sched::CloneFlags;
14use nix::sys::epoll::EpollCreateFlags;
15use nix::sys::eventfd::EfdFlags;
16use nix::sys::inotify::InitFlags;
17use nix::sys::mman::MapFlags;
18use nix::sys::mman::ProtFlags;
19use nix::sys::signalfd::SfdFlags;
20use nix::sys::socket::AddressFamily;
21use nix::sys::socket::SockFlag;
22use nix::sys::socket::SockProtocol;
23use nix::sys::stat::Mode;
24use nix::sys::stat::SFlag;
25use nix::sys::timerfd::TimerFlags;
26use nix::sys::wait::WaitPidFlag;
27use nix::unistd::Pid;
28
29use crate::Addr;
30use crate::AddrMut;
31use crate::Errno;
32use crate::MemoryAccess;
33
34/// A wrapper that combines an address space and a syscall. This is useful for
35/// displaying the contents of syscall pointer inputs.
36pub struct Display<'a, M, T> {
37    /// How we access memory.
38    memory: &'a M,
39
40    /// The syscall arguments we need to display.
41    syscall: &'a T,
42
43    /// Whether or not to display output arguments.
44    outputs: bool,
45}
46
47impl<'a, M, T> Display<'a, M, T> {
48    /// Allocate a new display struct from a memory and a syscall whose
49    /// arguments read from that memory.
50    pub fn new(memory: &'a M, syscall: &'a T, outputs: bool) -> Self {
51        Display {
52            memory,
53            syscall,
54            outputs,
55        }
56    }
57}
58
59impl<'a, M, T> fmt::Display for Display<'a, M, T>
60where
61    M: MemoryAccess,
62    T: Displayable,
63{
64    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
65        self.syscall.fmt(self.memory, self.outputs, f)
66    }
67}
68
69/// Trait that all syscalls and their arguments need to implement in order to be
70/// printed out.
71///
72/// This is deliberately not [`std::fmt::Display`]. Pointer arguments such as
73/// [`PathPtr`](crate::PathPtr) are addresses in the *guest's* address space, so
74/// printing what they point to needs a way to read that memory, which
75/// `std::fmt::Display::fmt` has no room for. Implementors provide only
76/// [`Displayable::fmt`], which takes the memory explicitly; the provided
77/// [`display`](Displayable::display) and
78/// [`display_with_outputs`](Displayable::display_with_outputs) methods pair a
79/// value with a memory and return something that does implement
80/// `std::fmt::Display`. To get the value itself rather than text, use
81/// [`ReadAddr::read`](crate::ReadAddr::read).
82///
83/// ```
84/// use reverie_syscalls::Displayable;
85/// use reverie_syscalls::LocalMemory;
86/// use reverie_syscalls::PathPtr;
87/// use reverie_syscalls::ReadAddr;
88///
89/// // A path in "guest" memory; here the guest is this process.
90/// let raw = c"/etc/hostname";
91/// let path: Option<PathPtr> = PathPtr::from_ptr(raw.as_ptr());
92/// let memory = LocalMemory::new();
93///
94/// // `format!("{}", path)` does not compile: pair the pointer with the memory.
95/// let shown = format!("{}", path.display(&memory));
96/// assert!(shown.ends_with(r#" -> "/etc/hostname""#), "{shown}");
97///
98/// // Read the pointed-to value itself.
99/// assert_eq!(
100///     path.unwrap().read(&memory).unwrap(),
101///     std::path::PathBuf::from("/etc/hostname")
102/// );
103/// assert_eq!(format!("{}", None::<PathPtr>.display(&memory)), "NULL");
104/// ```
105pub trait Displayable {
106    /// Displays a syscall with all of its arguments.
107    fn fmt<M: MemoryAccess>(
108        &self,
109        memory: &M,
110        outputs: bool,
111        f: &mut fmt::Formatter,
112    ) -> fmt::Result;
113
114    /// Returns an object that implements `std::fmt::Display` and displays only
115    /// syscall inputs.
116    fn display<'a, M>(&'a self, memory: &'a M) -> Display<'a, M, Self>
117    where
118        M: MemoryAccess,
119        Self: Sized,
120    {
121        Display::new(memory, self, false)
122    }
123
124    /// Returns an object that implements `std::fmt::Display` and displays
125    /// syscall inputs as well as outputs. Useful for displaying pointer
126    /// arguments that are only valid after a syscall has been executed.
127    fn display_with_outputs<'a, M>(&'a self, memory: &'a M) -> Display<'a, M, Self>
128    where
129        M: MemoryAccess,
130        Self: Sized,
131    {
132        Display::new(memory, self, true)
133    }
134}
135
136impl<'a, T> Displayable for Option<Addr<'a, T>> {
137    fn fmt<M: MemoryAccess>(
138        &self,
139        _memory: &M,
140        _outputs: bool,
141        f: &mut fmt::Formatter,
142    ) -> fmt::Result {
143        match self {
144            None => write!(f, "NULL"),
145            Some(addr) => write!(f, "{:?}", addr),
146        }
147    }
148}
149
150impl<'a, T> Displayable for Option<AddrMut<'a, T>> {
151    fn fmt<M: MemoryAccess>(
152        &self,
153        _memory: &M,
154        _outputs: bool,
155        f: &mut fmt::Formatter,
156    ) -> fmt::Result {
157        match self {
158            None => write!(f, "NULL"),
159            Some(addr) => write!(f, "{:?}", addr),
160        }
161    }
162}
163
164impl Displayable for OFlag {
165    fn fmt<M: MemoryAccess>(
166        &self,
167        _memory: &M,
168        _outputs: bool,
169        f: &mut fmt::Formatter,
170    ) -> fmt::Result {
171        if self.is_empty() {
172            // Without this special case, the default Debug implementation will
173            // print "O_LARGEFILE | O_RDONLY" because both of those flags are
174            // zeros.
175            f.write_str("0")
176        } else {
177            fmt::Debug::fmt(self, f)
178        }
179    }
180}
181
182impl<T> Displayable for Result<T, Errno>
183where
184    T: fmt::Display,
185{
186    fn fmt<M: MemoryAccess>(
187        &self,
188        _memory: &M,
189        _outputs: bool,
190        f: &mut fmt::Formatter,
191    ) -> fmt::Result {
192        match self {
193            Ok(x) => fmt::Display::fmt(x, f),
194            Err(err) => fmt::Display::fmt(err, f),
195        }
196    }
197}
198
199/// Macro that implements ['Displayable'] trait for a given type based on
200/// another trait implementation e.g. ['Debug'] or ['Display'], etc
201#[macro_export]
202macro_rules! impl_displayable {
203    ($fmt:ident $t:ty) => {
204        impl $crate::Displayable for $t {
205            fn fmt<M: $crate::MemoryAccess>(
206                &self,
207                _memory: &M,
208                _outputs: bool,
209                f: &mut ::core::fmt::Formatter,
210            ) -> ::core::fmt::Result {
211                ::core::fmt::$fmt::fmt(self, f)
212            }
213        }
214    };
215}
216
217/// Macro that implements a wrapper for a pointer e.g. ['AddrMut']
218/// or ['Addr] with custom ['Displayable'] implementation
219#[macro_export]
220macro_rules! displayable_ptr {
221    ($type:ident, $pointer:ident<$value:ident>) => {
222        /// A pointer to a `timeval` buffer.
223        #[derive(Copy, Clone, Debug, Eq, PartialEq)]
224        #[allow(missing_docs)]
225        pub struct $type<'a>(pub $crate::$pointer<'a, $value>);
226
227        impl<'a> $crate::FromToRaw for std::option::Option<$type<'a>> {
228            fn from_raw(raw: usize) -> Self {
229                $crate::$pointer::from_ptr(raw as *const $value).map($type)
230            }
231
232            fn into_raw(self) -> usize {
233                self.map(|p| p.0).into_raw()
234            }
235        }
236
237        impl<'a> $crate::ReadAddr for $type<'a> {
238            type Target = $value;
239            type Error = $crate::Errno;
240
241            fn read<M: $crate::MemoryAccess>(
242                &self,
243                memory: &M,
244            ) -> Result<Self::Target, Self::Error> {
245                memory.read_value(self.0)
246            }
247        }
248
249        impl<'a> $crate::Displayable for std::option::Option<$type<'a>> {
250            fn fmt<M: $crate::MemoryAccess>(
251                &self,
252                memory: &M,
253                outputs: bool,
254                f: &mut std::fmt::Formatter,
255            ) -> std::fmt::Result {
256                $crate::fmt_nullable_ptr(f, &self.map(|x| x.0), memory, outputs)
257            }
258        }
259
260        impl<'a> From<$type<'a>> for $crate::AddrMut<'a, $value> {
261            fn from(time_ptr: $type<'a>) -> Self {
262                time_ptr.0
263            }
264        }
265
266        impl<'a> From<$type<'a>> for $crate::Addr<'a, $value> {
267            fn from(time_ptr: $type<'a>) -> Self {
268                time_ptr.0.into()
269            }
270        }
271    };
272}
273
274impl_displayable!(Debug AtFlags);
275impl_displayable!(Debug CloneFlags);
276impl_displayable!(Debug Mode);
277impl_displayable!(Debug SFlag);
278impl_displayable!(Debug WaitPidFlag);
279impl_displayable!(Debug MapFlags);
280impl_displayable!(Debug ProtFlags);
281impl_displayable!(Debug EpollCreateFlags);
282impl_displayable!(Debug EfdFlags);
283impl_displayable!(Debug SfdFlags);
284impl_displayable!(Debug InitFlags);
285impl_displayable!(Debug SockFlag);
286impl_displayable!(Debug AddressFamily);
287impl_displayable!(Debug SockProtocol);
288impl_displayable!(Debug Option<SockProtocol>);
289impl_displayable!(Debug TimerFlags);
290
291impl_displayable!(Display Pid);
292impl_displayable!(Display i32);
293impl_displayable!(Display u32);
294impl_displayable!(Display i64);
295impl_displayable!(Display u64);
296impl_displayable!(Display isize);
297impl_displayable!(Display usize);