Skip to main content

script/dom/bindings/
error.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5//! Utilities to throw exceptions from Rust bindings.
6
7use std::ffi::CString;
8use std::ptr::NonNull;
9use std::slice::from_raw_parts;
10
11#[cfg(feature = "js_backtrace")]
12use backtrace::Backtrace;
13use embedder_traits::JavaScriptErrorInfo;
14use js::context::JSContext;
15use js::conversions::jsstr_to_string;
16use js::error::{throw_range_error, throw_type_error};
17use js::gc::{HandleObject, HandleValue, MutableHandleValue};
18use js::jsapi::ExceptionStackBehavior;
19#[cfg(feature = "js_backtrace")]
20use js::jsapi::StackFormat as JSStackFormat;
21use js::jsval::UndefinedValue;
22use js::realm::CurrentRealm;
23use js::rust::wrappers2::{
24    JS_ClearPendingException, JS_ErrorFromException, JS_GetPendingException, JS_GetProperty,
25    JS_IsExceptionPending, JS_SetPendingException,
26};
27use js::rust::{describe_scripted_caller_safe, error_info_from_exception_stack_safe};
28use libc::c_uint;
29#[cfg(feature = "js_backtrace")]
30use script_bindings::cell::DomRefCell;
31use script_bindings::conversions::SafeToJSValConvertible;
32pub(crate) use script_bindings::error::*;
33use script_bindings::root::DomRoot;
34use script_bindings::str::DOMString;
35
36use crate::dom::bindings::conversions::{
37    ConversionResult, FromJSValConvertible, root_from_handleobject,
38};
39use crate::dom::bindings::str::USVString;
40use crate::dom::domexception::{DOMErrorName, DOMException};
41use crate::dom::globalscope::GlobalScope;
42use crate::dom::types::QuotaExceededError;
43
44#[cfg(feature = "js_backtrace")]
45thread_local! {
46    /// An optional stringified JS backtrace and stringified native backtrace from the
47    /// the last DOM exception that was reported.
48    pub(crate) static LAST_EXCEPTION_BACKTRACE: DomRefCell<Option<(Option<String>, String)>> = DomRefCell::new(None);
49}
50
51/// Error values that have no equivalent DOMException representation.
52pub(crate) enum JsEngineError {
53    /// An EMCAScript TypeError.
54    Type(CString),
55    /// An ECMAScript RangeError.
56    Range(CString),
57    /// The JS engine reported a thrown exception.
58    JSFailed,
59}
60
61/// Set a pending exception for the given `result` on `cx`.
62pub(crate) fn throw_dom_exception(cx: &mut JSContext, global: &GlobalScope, result: Error) {
63    #[cfg(feature = "js_backtrace")]
64    unsafe {
65        capture_stack!(&in(cx) let stack);
66        let js_stack = stack.and_then(|stack| stack.as_string(None, JSStackFormat::Default));
67        let rust_stack = Backtrace::new();
68        LAST_EXCEPTION_BACKTRACE.with(|backtrace| {
69            *backtrace.borrow_mut() = Some((js_stack, format!("{:?}", rust_stack)));
70        });
71    }
72
73    match create_dom_exception(cx, global, result) {
74        Ok(exception) => unsafe {
75            assert!(!JS_IsExceptionPending(cx));
76            rooted!(&in(cx) let mut thrown = UndefinedValue());
77            exception.safe_to_jsval(cx, thrown.handle_mut());
78            JS_SetPendingException(cx, thrown.handle(), ExceptionStackBehavior::Capture);
79        },
80
81        Err(JsEngineError::Type(message)) => unsafe {
82            assert!(!JS_IsExceptionPending(cx));
83            throw_type_error(cx.raw_cx(), &message);
84        },
85
86        Err(JsEngineError::Range(message)) => unsafe {
87            assert!(!JS_IsExceptionPending(cx));
88            throw_range_error(cx.raw_cx(), &message);
89        },
90
91        Err(JsEngineError::JSFailed) => unsafe {
92            assert!(JS_IsExceptionPending(cx));
93        },
94    }
95}
96
97/// If possible, create a new DOMException representing the provided error.
98/// If no such DOMException exists, return a subset of the original error values
99/// that may need additional handling.
100pub(crate) fn create_dom_exception(
101    cx: &mut JSContext,
102    global: &GlobalScope,
103    result: Error,
104) -> Result<DomRoot<DOMException>, JsEngineError> {
105    let mut new_custom_exception = |error_name, message| {
106        Ok(DOMException::new_with_custom_message(
107            cx, global, error_name, message,
108        ))
109    };
110
111    let code = match result {
112        Error::IndexSize(Some(custom_message)) => {
113            return new_custom_exception(DOMErrorName::IndexSizeError, custom_message);
114        },
115        Error::IndexSize(None) => DOMErrorName::IndexSizeError,
116        Error::NotFound(Some(custom_message)) => {
117            return new_custom_exception(DOMErrorName::NotFoundError, custom_message);
118        },
119        Error::NotFound(None) => DOMErrorName::NotFoundError,
120        Error::HierarchyRequest(Some(custom_message)) => {
121            return new_custom_exception(DOMErrorName::HierarchyRequestError, custom_message);
122        },
123        Error::HierarchyRequest(None) => DOMErrorName::HierarchyRequestError,
124        Error::WrongDocument(Some(doc_err_custom_message)) => {
125            return new_custom_exception(DOMErrorName::WrongDocumentError, doc_err_custom_message);
126        },
127        Error::WrongDocument(None) => DOMErrorName::WrongDocumentError,
128        Error::InvalidCharacter(Some(custom_message)) => {
129            return new_custom_exception(DOMErrorName::InvalidCharacterError, custom_message);
130        },
131        Error::InvalidCharacter(None) => DOMErrorName::InvalidCharacterError,
132        Error::NotSupported(Some(custom_message)) => {
133            return new_custom_exception(DOMErrorName::NotSupportedError, custom_message);
134        },
135        Error::NotSupported(None) => DOMErrorName::NotSupportedError,
136        Error::InUseAttribute(Some(custom_message)) => {
137            return new_custom_exception(DOMErrorName::InUseAttributeError, custom_message);
138        },
139        Error::InUseAttribute(None) => DOMErrorName::InUseAttributeError,
140        Error::InvalidState(Some(custom_message)) => {
141            return new_custom_exception(DOMErrorName::InvalidStateError, custom_message);
142        },
143        Error::InvalidState(None) => DOMErrorName::InvalidStateError,
144        Error::Syntax(Some(custom_message)) => {
145            return new_custom_exception(DOMErrorName::SyntaxError, custom_message);
146        },
147        Error::Syntax(None) => DOMErrorName::SyntaxError,
148        Error::Namespace(Some(custom_message)) => {
149            return new_custom_exception(DOMErrorName::NamespaceError, custom_message);
150        },
151        Error::Namespace(None) => DOMErrorName::NamespaceError,
152        Error::InvalidAccess(Some(custom_message)) => {
153            return new_custom_exception(DOMErrorName::InvalidAccessError, custom_message);
154        },
155        Error::InvalidAccess(None) => DOMErrorName::InvalidAccessError,
156        Error::Security(Some(custom_message)) => {
157            return new_custom_exception(DOMErrorName::SecurityError, custom_message);
158        },
159        Error::Security(None) => DOMErrorName::SecurityError,
160        Error::Network(Some(custom_message)) => {
161            return new_custom_exception(DOMErrorName::NetworkError, custom_message);
162        },
163        Error::Network(None) => DOMErrorName::NetworkError,
164        Error::Abort(Some(custom_message)) => {
165            return new_custom_exception(DOMErrorName::AbortError, custom_message);
166        },
167        Error::Abort(None) => DOMErrorName::AbortError,
168        Error::Timeout(Some(custom_message)) => {
169            return new_custom_exception(DOMErrorName::TimeoutError, custom_message);
170        },
171        Error::Timeout(None) => DOMErrorName::TimeoutError,
172        Error::InvalidNodeType(Some(custom_message)) => {
173            return new_custom_exception(DOMErrorName::InvalidNodeTypeError, custom_message);
174        },
175        Error::InvalidNodeType(None) => DOMErrorName::InvalidNodeTypeError,
176        Error::DataClone(Some(custom_message)) => {
177            return new_custom_exception(DOMErrorName::DataCloneError, custom_message);
178        },
179        Error::DataClone(None) => DOMErrorName::DataCloneError,
180        Error::Data(Some(custom_message)) => {
181            return new_custom_exception(DOMErrorName::DataError, custom_message);
182        },
183        Error::Data(None) => DOMErrorName::DataError,
184        Error::TransactionInactive(Some(custom_message)) => {
185            return new_custom_exception(DOMErrorName::TransactionInactiveError, custom_message);
186        },
187        Error::TransactionInactive(None) => DOMErrorName::TransactionInactiveError,
188        Error::ReadOnly(Some(custom_message)) => {
189            return new_custom_exception(DOMErrorName::ReadOnlyError, custom_message);
190        },
191        Error::ReadOnly(None) => DOMErrorName::ReadOnlyError,
192        Error::Version(Some(custom_message)) => {
193            return new_custom_exception(DOMErrorName::VersionError, custom_message);
194        },
195        Error::Version(None) => DOMErrorName::VersionError,
196        Error::NoModificationAllowed(Some(custom_message)) => {
197            return new_custom_exception(DOMErrorName::NoModificationAllowedError, custom_message);
198        },
199        Error::NoModificationAllowed(None) => DOMErrorName::NoModificationAllowedError,
200        Error::QuotaExceeded { quota, requested } => {
201            return Ok(DomRoot::upcast(QuotaExceededError::new(
202                cx,
203                global,
204                DOMString::new(),
205                quota,
206                requested,
207            )));
208        },
209        Error::TypeMismatch(Some(custom_message)) => {
210            return new_custom_exception(DOMErrorName::TypeMismatchError, custom_message);
211        },
212        Error::TypeMismatch(None) => DOMErrorName::TypeMismatchError,
213        Error::InvalidModification(Some(custom_message)) => {
214            return new_custom_exception(DOMErrorName::InvalidModificationError, custom_message);
215        },
216        Error::InvalidModification(None) => DOMErrorName::InvalidModificationError,
217        Error::NotReadable(Some(custom_message)) => {
218            return new_custom_exception(DOMErrorName::NotReadableError, custom_message);
219        },
220        Error::NotReadable(None) => DOMErrorName::NotReadableError,
221        Error::Operation(Some(custom_message)) => {
222            return new_custom_exception(DOMErrorName::OperationError, custom_message);
223        },
224        Error::Operation(None) => DOMErrorName::OperationError,
225        Error::NotAllowed(Some(custom_message)) => {
226            return new_custom_exception(DOMErrorName::NotAllowedError, custom_message);
227        },
228        Error::NotAllowed(None) => DOMErrorName::NotAllowedError,
229        Error::Encoding(Some(custom_message)) => {
230            return new_custom_exception(DOMErrorName::EncodingError, custom_message);
231        },
232        Error::Encoding(None) => DOMErrorName::EncodingError,
233        Error::Constraint(Some(custom_message)) => {
234            return new_custom_exception(DOMErrorName::ConstraintError, custom_message);
235        },
236        Error::Constraint(None) => DOMErrorName::ConstraintError,
237        Error::Type(message) => return Err(JsEngineError::Type(message)),
238        Error::Range(message) => return Err(JsEngineError::Range(message)),
239        Error::JSFailed => return Err(JsEngineError::JSFailed),
240    };
241    Ok(DOMException::new(cx, global, code))
242}
243
244/// A struct encapsulating information about a runtime script error.
245#[derive(Default)]
246pub(crate) struct ErrorInfo {
247    /// The error message.
248    pub(crate) message: String,
249    /// The file name.
250    pub(crate) filename: String,
251    /// The line number.
252    pub(crate) lineno: c_uint,
253    /// The column number.
254    pub(crate) column: c_uint,
255}
256
257impl ErrorInfo {
258    fn from_native_error(cx: &mut JSContext, object: HandleObject) -> Option<ErrorInfo> {
259        let report = unsafe { JS_ErrorFromException(cx, object) };
260        if report.is_null() {
261            return None;
262        }
263
264        let filename = {
265            let filename = unsafe { (*report)._base.filename.data_ as *const u8 };
266            if !filename.is_null() {
267                let filename = unsafe {
268                    let length = (0..).find(|idx| *filename.offset(*idx) == 0).unwrap();
269                    from_raw_parts(filename, length as usize)
270                };
271                String::from_utf8_lossy(filename).into_owned()
272            } else {
273                "none".to_string()
274            }
275        };
276
277        let lineno = unsafe { (*report)._base.lineno };
278        let column = unsafe { (*report)._base.column._base };
279
280        let message = {
281            let message = unsafe { (*report)._base.message_.data_ as *const u8 };
282            let message = unsafe {
283                let length = (0..).find(|idx| *message.offset(*idx) == 0).unwrap();
284                from_raw_parts(message, length as usize)
285            };
286            String::from_utf8_lossy(message).into_owned()
287        };
288
289        Some(ErrorInfo {
290            filename,
291            message,
292            lineno,
293            column,
294        })
295    }
296
297    fn from_dom_exception(cx: &mut JSContext, object: HandleObject) -> Option<ErrorInfo> {
298        let exception = root_from_handleobject::<DOMException>(cx, object).ok()?;
299        let scripted_caller = describe_scripted_caller_safe(cx).unwrap_or_default();
300        Some(ErrorInfo {
301            message: exception.stringifier().into(),
302            filename: scripted_caller.filename,
303            lineno: scripted_caller.line,
304            column: scripted_caller.col + 1,
305        })
306    }
307
308    fn from_object(cx: &mut JSContext, object: HandleObject) -> Option<ErrorInfo> {
309        if let Some(info) = ErrorInfo::from_native_error(cx, object) {
310            return Some(info);
311        }
312        if let Some(info) = ErrorInfo::from_dom_exception(cx, object) {
313            return Some(info);
314        }
315        None
316    }
317
318    /// <https://html.spec.whatwg.org/multipage/#extract-error>
319    pub(crate) fn from_value(cx: &mut JSContext, value: HandleValue) -> ErrorInfo {
320        if value.is_object() {
321            rooted!(&in(cx) let object = value.to_object());
322            if let Some(info) = ErrorInfo::from_object(cx, object.handle()) {
323                return info;
324            }
325        }
326
327        match USVString::safe_from_jsval(cx, value, ()) {
328            Ok(ConversionResult::Success(USVString(string))) => {
329                let scripted_caller = describe_scripted_caller_safe(cx).unwrap_or_default();
330                ErrorInfo {
331                    message: format!("uncaught exception: {}", string),
332                    filename: scripted_caller.filename,
333                    lineno: scripted_caller.line,
334                    column: scripted_caller.col + 1,
335                }
336            },
337            _ => {
338                panic!("uncaught exception: failed to stringify primitive");
339            },
340        }
341    }
342}
343
344/// Report a pending exception, thereby clearing it.
345pub(crate) fn report_pending_exception(cx: &mut CurrentRealm) {
346    rooted!(&in(cx) let mut value = UndefinedValue());
347    if let Some(error_info) = error_info_from_pending_exception(cx, value.handle_mut()) {
348        GlobalScope::from_current_realm(cx).report_an_error(cx, error_info, value.handle());
349    }
350}
351
352fn error_info_from_pending_exception(
353    cx: &mut JSContext,
354    value: MutableHandleValue,
355) -> Option<ErrorInfo> {
356    if unsafe { !JS_IsExceptionPending(cx) } {
357        return None;
358    }
359
360    let error_info = error_info_from_exception_stack_safe(cx, value)?;
361
362    Some(ErrorInfo {
363        message: error_info.message,
364        filename: error_info.filename,
365        lineno: error_info.line,
366        column: error_info.col,
367    })
368}
369
370pub(crate) fn javascript_error_info_from_error_info(
371    cx: &mut JSContext,
372    error_info: &ErrorInfo,
373    value: HandleValue,
374) -> JavaScriptErrorInfo {
375    let mut stack = || {
376        if !value.is_object() {
377            return None;
378        }
379
380        rooted!(&in(cx) let object = value.to_object());
381        rooted!(&in(cx) let mut stack_value = UndefinedValue());
382        if unsafe {
383            !JS_GetProperty(
384                cx,
385                object.handle(),
386                c"stack".as_ptr(),
387                stack_value.handle_mut(),
388            )
389        } {
390            return None;
391        }
392        if !stack_value.is_string() {
393            return None;
394        }
395        let stack_string = NonNull::new(stack_value.to_string())?;
396        Some(unsafe { jsstr_to_string(cx, stack_string) })
397    };
398
399    JavaScriptErrorInfo {
400        message: error_info.message.clone(),
401        filename: error_info.filename.clone(),
402        line_number: error_info.lineno as u64,
403        column: error_info.column as u64,
404        stack: stack(),
405    }
406}
407
408pub(crate) fn take_and_report_pending_exception_for_api(
409    cx: &mut CurrentRealm,
410) -> Option<JavaScriptErrorInfo> {
411    rooted!(&in(cx) let mut value = UndefinedValue());
412    let error_info = error_info_from_pending_exception(cx, value.handle_mut())?;
413
414    let return_value = javascript_error_info_from_error_info(cx, &error_info, value.handle());
415    GlobalScope::from_current_realm(cx).report_an_error(cx, error_info, value.handle());
416
417    Some(return_value)
418}
419
420pub(crate) trait ErrorToJsval {
421    fn to_jsval(self, cx: &mut JSContext, global: &GlobalScope, rval: MutableHandleValue);
422}
423
424impl ErrorToJsval for Error {
425    /// Convert this error value to a JS value, consuming it in the process.
426    fn to_jsval(self, cx: &mut JSContext, global: &GlobalScope, rval: MutableHandleValue) {
427        match self {
428            Error::JSFailed => (),
429            _ => unsafe { assert!(!JS_IsExceptionPending(cx)) },
430        }
431        throw_dom_exception(cx, global, self);
432        unsafe {
433            assert!(JS_IsExceptionPending(cx));
434            assert!(JS_GetPendingException(cx, rval));
435            JS_ClearPendingException(cx);
436        }
437    }
438}