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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
use crate::{
    budget::AsBudget,
    events::Events,
    xdr::{self, ScError},
    EnvBase, Error, Host,
};
use backtrace::{Backtrace, BacktraceFrame};
use core::fmt::Debug;
use soroban_env_common::{
    xdr::{ScErrorCode, ScErrorType},
    ConversionError, TryFromVal, U32Val, Val,
};
use std::ops::DerefMut;

#[derive(Clone)]
pub(crate) struct DebugInfo {
    pub(crate) events: Events,
    pub(crate) backtrace: Backtrace,
}

#[derive(Clone)]
pub struct HostError {
    pub error: Error,
    pub(crate) info: Option<Box<DebugInfo>>,
}

impl std::error::Error for HostError {}

impl Debug for HostError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // We do a little trimming here, skipping the first two frames (which
        // are always into, from, and one or more Host::err_foo calls) and all
        // the frames _after_ the short-backtrace marker that rust compiles-in.

        fn frame_name_matches(frame: &BacktraceFrame, pat: &str) -> bool {
            for sym in frame.symbols() {
                match sym.name() {
                    Some(sn) if format!("{:}", sn).contains(pat) => {
                        return true;
                    }
                    _ => (),
                }
            }
            false
        }

        fn frame_is_short_backtrace_start(frame: &BacktraceFrame) -> bool {
            frame_name_matches(frame, "__rust_begin_short_backtrace")
        }

        fn frame_is_initial_error_plumbing(frame: &BacktraceFrame) -> bool {
            frame_name_matches(frame, "::from")
                || frame_name_matches(frame, "::into")
                || frame_name_matches(frame, "host::err")
                || frame_name_matches(frame, "Host::err")
                || frame_name_matches(frame, "Host>::err")
                || frame_name_matches(frame, "::map_err")
        }

        writeln!(f, "HostError: {:?}", self.error)?;
        if let Some(info) = &self.info {
            let mut bt = info.backtrace.clone();
            bt.resolve();
            let frames: Vec<BacktraceFrame> = bt
                .frames()
                .iter()
                .skip_while(|f| frame_is_initial_error_plumbing(f))
                .take_while(|f| !frame_is_short_backtrace_start(f))
                .cloned()
                .collect();
            let bt: Backtrace = frames.into();
            // TODO: maybe make this something users can adjust?
            const MAX_EVENTS: usize = 25;
            let mut wrote_heading = false;
            for (i, e) in info.events.0.iter().rev().take(MAX_EVENTS).enumerate() {
                if !wrote_heading {
                    writeln!(f)?;
                    writeln!(f, "Event log (newest first):")?;
                    wrote_heading = true;
                }
                writeln!(f, "   {}: {}", i, e)?;
            }
            if info.events.0.len() > MAX_EVENTS {
                writeln!(f, "   {}: ... elided ...", MAX_EVENTS)?;
            }
            writeln!(f)?;
            writeln!(f, "Backtrace (newest first):")?;
            writeln!(f, "{:?}", bt)
        } else {
            writeln!(f, "DebugInfo not available")
        }
    }
}

impl HostError {
    #[cfg(test)]
    pub fn result_matches_err<T, C>(res: Result<T, HostError>, code: C) -> bool
    where
        Error: From<C>,
    {
        match res {
            Ok(_) => false,
            Err(he) => {
                let error: Error = code.into();
                he.error == error
            }
        }
    }
}

impl<T> From<T> for HostError
where
    Error: From<T>,
{
    fn from(error: T) -> Self {
        let error = error.into();
        Self { error, info: None }
    }
}

impl std::fmt::Display for HostError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        <HostError as Debug>::fmt(self, f)
    }
}

impl TryFrom<&HostError> for ScError {
    type Error = xdr::Error;
    fn try_from(err: &HostError) -> Result<Self, Self::Error> {
        err.error.try_into()
    }
}

impl From<HostError> for std::io::Error {
    fn from(e: HostError) -> Self {
        std::io::Error::new(std::io::ErrorKind::Other, e)
    }
}

impl Host {
    /// Convenience function that only evaluates the auxiliary debug arguments
    /// to [Host::error] when [Host::is_debug] is `true`.
    pub fn error_lazy<'a>(
        &self,
        error: Error,
        msg: &str,
        debug_args: impl FnOnce() -> &'a [Val] + 'a,
    ) -> HostError {
        if self.is_debug() {
            self.error(error, msg, debug_args())
        } else {
            self.error(error, msg, &[])
        }
    }

    /// Convenience function to construct an [Error] and pass to [Host::error].
    pub fn err(&self, type_: ScErrorType, code: ScErrorCode, msg: &str, args: &[Val]) -> HostError {
        let error = Error::from_type_and_code(type_, code);
        self.error(error, msg, args)
    }

    /// At minimum constructs and returns a [HostError] build from the provided
    /// [Error], and when running in [DiagnosticMode::Debug] additionally
    /// records a diagnostic event with the provided `msg` and `args` and then
    /// enriches the returned [Error] with [DebugInfo] in the form of a
    /// [Backtrace] and snapshot of the [Events] buffer.
    pub fn error(&self, error: Error, msg: &str, args: &[Val]) -> HostError {
        if self.is_debug() {
            // We _try_ to take a mutable borrow of the events buffer refcell
            // while building up the event we're going to emit into the events
            // log, failing gracefully (just emitting a no-debug-info
            // `HostError` wrapping the supplied `Error`) if we cannot acquire
            // the refcell. This is to handle the "double fault" case where we
            // get an error _while performing_ any of the steps needed to record
            // an error as an event, below.
            if let Ok(mut events_refmut) = self.0.events.try_borrow_mut() {
                if let Err(e) = self.err_diagnostics(events_refmut.deref_mut(), error, msg, args) {
                    return e;
                }
                let events = match self
                    .as_budget()
                    .with_free_budget(|| events_refmut.externalize(self))
                {
                    Ok(events) => events,
                    Err(e) => return e,
                };
                let backtrace = Backtrace::new_unresolved();
                let info = Some(Box::new(DebugInfo { backtrace, events }));
                return HostError { error, info };
            }
        }
        error.into()
    }

    // Some common error patterns here.

    pub(crate) fn err_arith_overflow(&self) -> HostError {
        self.err(
            ScErrorType::Value,
            ScErrorCode::ArithDomain,
            "arithmetic overflow",
            &[],
        )
    }

    pub(crate) fn err_oob_linear_memory(&self) -> HostError {
        self.err(
            ScErrorType::WasmVm,
            ScErrorCode::IndexBounds,
            "out-of-bounds access to WASM linear memory",
            &[],
        )
    }

    pub(crate) fn err_wasmi_fuel_metering_disabled(&self) -> HostError {
        self.err(
            ScErrorType::WasmVm,
            ScErrorCode::InternalError,
            "wasmi fuel metering is disabled",
            &[],
        )
    }

    /// Given a result carrying some error type that can be converted to an
    /// [Error] and supports [core::fmt::Debug], calls [Host::error] with the
    /// error when there's an error, also passing the result of
    /// [core::fmt::Debug::fmt] when [Host::is_debug] is `true`. Returns a
    /// [Result] over [HostError].
    ///
    /// If you have an error type `T` you want to record as a detailed debug
    /// event and a less-detailed [Error] code embedded in a [HostError], add an
    /// `impl From<T> for Error` over in `soroban_env_common::error`, or in the
    /// module defining `T`, and call this where the error is generated.
    ///
    /// Note: we do _not_ want to `impl From<T> for HostError` for such types,
    /// as doing so will avoid routing them through the host in order to record
    /// their extended diagnostic information into the event log. This means you
    /// will wind up writing `host.map_err(...)?` a bunch in code that you used
    /// to be able to get away with just writing `...?`, there's no way around
    /// this if we want to record the diagnostic information.
    pub fn map_err<T, E>(&self, res: Result<T, E>) -> Result<T, HostError>
    where
        Error: From<E>,
        E: Debug,
    {
        res.map_err(|e| {
            if self.is_debug() {
                let msg = format!("{:?}", e);
                self.error(e.into(), &msg, &[])
            } else {
                self.error(e.into(), "", &[])
            }
        })
    }
}

pub(crate) trait DebugArg {
    fn debug_arg(host: &Host, arg: &Self) -> Val {
        // We similarly guard against double-faulting here by try-acquiring the event buffer,
        // which will fail if we're re-entering error reporting _while_ forming a debug argument.
        if let Ok(guard) = host.0.events.try_borrow_mut() {
            host.as_budget()
                .with_free_budget(|| Self::debug_arg_maybe_expensive_or_fallible(host, arg))
                .unwrap_or(
                    Error::from_type_and_code(ScErrorType::Events, ScErrorCode::InternalError)
                        .into(),
                )
        } else {
            Error::from_type_and_code(ScErrorType::Events, ScErrorCode::InternalError).into()
        }
    }
    fn debug_arg_maybe_expensive_or_fallible(host: &Host, arg: &Self) -> Result<Val, HostError>;
}

impl<T> DebugArg for T
where
    Val: TryFromVal<Host, T>,
    HostError: From<<Val as TryFromVal<Host, T>>::Error>,
{
    fn debug_arg_maybe_expensive_or_fallible(host: &Host, arg: &Self) -> Result<Val, HostError> {
        Val::try_from_val(host, arg).map_err(|e| e.into())
    }
}

impl DebugArg for xdr::Hash {
    fn debug_arg_maybe_expensive_or_fallible(host: &Host, arg: &Self) -> Result<Val, HostError> {
        host.bytes_new_from_slice(arg.as_slice()).map(|b| b.into())
    }
}

impl DebugArg for str {
    fn debug_arg_maybe_expensive_or_fallible(host: &Host, arg: &Self) -> Result<Val, HostError> {
        host.string_new_from_slice(arg).map(|s| s.into())
    }
}

impl DebugArg for usize {
    fn debug_arg_maybe_expensive_or_fallible(host: &Host, arg: &Self) -> Result<Val, HostError> {
        u32::try_from(*arg)
            .map(|x| U32Val::from(x).into())
            .map_err(|_| HostError::from(ConversionError))
    }
}

/// Helper for building multi-argument errors.
/// For example:
/// ```ignore
/// err!(host, error, "message", arg1, arg2);
/// ```
/// All arguments must be convertible to [Val] with [TryIntoVal]. This is
/// expected to be called from within a function that returns
/// `Result<_, HostError>`. If these requirements can't be fulfilled, use
/// the [Host::error] or [Host::error_lazy] functions directly.
#[macro_export]
macro_rules! err {
    ($host:expr, $error:expr, $msg:literal, $($args:expr),*) => {
        {
            if $host.is_debug() {
                $host.error($error.into(), $msg, &[])
            } else {
                $host.error($error.into(), $msg, &[$(<_ as $crate::host::error::DebugArg>::debug_arg($host, &$args)),*])
            }
        }
    };
}