1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
//! Module containing the error structures used in the crate.

/// Legacy error handling for macos, where we cannot (yet) use a `rustix` API.
#[cfg(target_os = "macos")]
mod sys_err {
    #[cfg(not(feature = "std"))]
    mod internal {
        use core::fmt;

        #[derive(Debug)]
        pub(crate) struct SysErr;

        impl fmt::Display for SysErr {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str("system error")
            }
        }

        impl SysErr {
            pub fn create() -> Self {
                Self
            }

            pub fn create_anyhow() -> anyhow::Error {
                anyhow::anyhow!(Self::create())
            }
        }
    }

    #[cfg(feature = "std")]
    mod internal {
        use core::fmt;

        #[derive(Debug, thiserror::Error)]
        pub(crate) struct SysErr(std::io::Error);

        impl fmt::Display for SysErr {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                write!(f, "system error: {}", self.0)
            }
        }

        impl SysErr {
            pub fn create() -> Self {
                Self(std::io::Error::last_os_error())
            }

            pub fn create_anyhow() -> anyhow::Error {
                anyhow::anyhow!(Self::create())
            }
        }
    }

    pub(crate) use internal::SysErr;
}

#[cfg(target_os = "macos")]
pub(crate) use sys_err::SysErr;

/// Private error types.
pub(crate) mod private {
    use core::fmt;

    /// Error indicating that the global allocator returned a zero pointer,
    /// possibly due to OOM.
    #[derive(Debug, Clone)]
    #[cfg_attr(feature = "std", derive(thiserror::Error))]
    pub(crate) struct AllocError(core::alloc::Layout);

    impl fmt::Display for AllocError {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.write_str("allocation error, possibly OOM")
        }
    }

    impl AllocError {
        /// Create a new alloc error from a layout.
        #[must_use]
        pub(crate) fn new(layout: core::alloc::Layout) -> Self {
            Self(layout)
        }
    }

    pub(crate) fn alloc_err_from_size_align(size: usize, align: usize) -> anyhow::Error {
        let layout = core::alloc::Layout::from_size_align(size, align);
        match layout {
            Ok(layout) => anyhow::anyhow!(AllocError::new(layout)),
            Err(layout_err) => anyhow::anyhow!(layout_err),
        }
    }

    pub(crate) trait ResultExt {
        type T;
        fn map_anyhow(self) -> anyhow::Result<Self::T>;
    }

    impl<T, E: Send + Sync + fmt::Debug + fmt::Display + 'static> ResultExt
        for core::result::Result<T, E>
    {
        type T = T;

        fn map_anyhow(self) -> anyhow::Result<Self::T> {
            self.map_err(|e| anyhow::anyhow!(e))
        }
    }
}

// Public error types

/// The result type used throughout the public API of this crate.
pub type Result = core::result::Result<(), Error>;

/// Error that occurred during hardening.
///
/// Either an internal error occurred (`Err` variant), or a debugger was
/// detected (`BeingTraced` variant). This type implements
/// [`Display`](core::fmt::Display) in a way that clearly distinguishes these
/// cases, and prints more information about the detected debugger/tracer if
/// available.
#[must_use]
#[cfg_attr(feature = "std", derive(thiserror::Error))]
#[derive(Debug)]
pub enum Error {
    /// A debugger was detected. The [`Traced`] typed field might contain more
    /// information about the debugger/tracer.
    BeingTraced(Traced),
    /// An internal error occurred. Contains an [`anyhow::Error`] with the
    /// internal error.
    Err(anyhow::Error),
}

/// A structure potentially containing more information about a detected
/// debugger/tracer.
#[derive(Debug, Clone)]
pub struct Traced {
    #[cfg(unix)]
    pid: Option<rustix::process::Pid>,
}

#[cfg(unix)]
impl Traced {
    pub(crate) fn from_pid(pid: rustix::process::Pid) -> Self {
        Self { pid: Some(pid) }
    }
}

#[cfg(not(unix))]
impl Traced {
    pub(crate) const DEFAULT: Self = Self {};
}

impl core::fmt::Display for Traced {
    #[cfg(unix)]
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self.pid {
            Some(pid) => write!(
                formatter,
                "program is being traced by the process with pid {}",
                pid.as_raw_nonzero()
            ),
            None => formatter.write_str("program is being traced"),
        }
    }

    #[cfg(not(unix))]
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        formatter.write_str("program is being traced")
    }
}

impl core::fmt::Display for Error {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::BeingTraced(tr) => tr.fmt(formatter),
            Self::Err(e) => e.fmt(formatter),
        }
    }
}

impl From<anyhow::Error> for Error {
    fn from(err: anyhow::Error) -> Self {
        Error::Err(err)
    }
}

pub(crate) trait ResultExt {
    fn create_ok() -> Self;
    fn create_being_traced(traced: Traced) -> Self;
    fn create_err(e: anyhow::Error) -> Self;
}

impl ResultExt for Result {
    fn create_ok() -> Self {
        Ok(())
    }

    fn create_being_traced(traced: Traced) -> Self {
        Err(Error::BeingTraced(traced))
    }

    fn create_err(e: anyhow::Error) -> Self {
        Err(Error::Err(e))
    }
}