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 http://mozilla.org/MPL/2.0/. */
4 
5 //! Utilities to throw exceptions from Rust bindings.
6 
7 use dom::bindings::codegen::Bindings::DOMExceptionBinding::DOMExceptionMethods;
8 use dom::bindings::codegen::PrototypeList::proto_id_to_name;
9 use dom::bindings::conversions::{ConversionResult, FromJSValConvertible, ToJSValConvertible};
10 use dom::bindings::conversions::root_from_object;
11 use dom::bindings::str::USVString;
12 use dom::domexception::{DOMErrorName, DOMException};
13 use dom::globalscope::GlobalScope;
14 use js::error::{throw_range_error, throw_type_error};
15 use js::jsapi::HandleObject;
16 use js::jsapi::JSContext;
17 use js::jsapi::JS_ClearPendingException;
18 use js::jsapi::JS_ErrorFromException;
19 use js::jsapi::JS_GetPendingException;
20 use js::jsapi::JS_IsExceptionPending;
21 use js::jsapi::JS_SetPendingException;
22 use js::jsapi::MutableHandleValue;
23 use js::jsval::UndefinedValue;
24 use libc::c_uint;
25 use std::slice::from_raw_parts;
26 
27 /// DOM exceptions that can be thrown by a native DOM method.
28 #[derive(Clone, Debug, MallocSizeOf)]
29 pub enum Error {
30     /// IndexSizeError DOMException
31     IndexSize,
32     /// NotFoundError DOMException
33     NotFound,
34     /// HierarchyRequestError DOMException
35     HierarchyRequest,
36     /// WrongDocumentError DOMException
37     WrongDocument,
38     /// InvalidCharacterError DOMException
39     InvalidCharacter,
40     /// NotSupportedError DOMException
41     NotSupported,
42     /// InUseAttributeError DOMException
43     InUseAttribute,
44     /// InvalidStateError DOMException
45     InvalidState,
46     /// SyntaxError DOMException
47     Syntax,
48     /// NamespaceError DOMException
49     Namespace,
50     /// InvalidAccessError DOMException
51     InvalidAccess,
52     /// SecurityError DOMException
53     Security,
54     /// NetworkError DOMException
55     Network,
56     /// AbortError DOMException
57     Abort,
58     /// TimeoutError DOMException
59     Timeout,
60     /// InvalidNodeTypeError DOMException
61     InvalidNodeType,
62     /// DataCloneError DOMException
63     DataClone,
64     /// NoModificationAllowedError DOMException
65     NoModificationAllowed,
66     /// QuotaExceededError DOMException
67     QuotaExceeded,
68     /// TypeMismatchError DOMException
69     TypeMismatch,
70     /// InvalidModificationError DOMException
71     InvalidModification,
72 
73     /// TypeError JavaScript Error
74     Type(String),
75     /// RangeError JavaScript Error
76     Range(String),
77 
78     /// A JavaScript exception is already pending.
79     JSFailed,
80 }
81 
82 /// The return type for IDL operations that can throw DOM exceptions.
83 pub type Fallible<T> = Result<T, Error>;
84 
85 /// The return type for IDL operations that can throw DOM exceptions and
86 /// return `()`.
87 pub type ErrorResult = Fallible<()>;
88 
89 /// Set a pending exception for the given `result` on `cx`.
throw_dom_exception(cx: *mut JSContext, global: &GlobalScope, result: Error)90 pub unsafe fn throw_dom_exception(cx: *mut JSContext, global: &GlobalScope, result: Error) {
91     let code = match result {
92         Error::IndexSize => DOMErrorName::IndexSizeError,
93         Error::NotFound => DOMErrorName::NotFoundError,
94         Error::HierarchyRequest => DOMErrorName::HierarchyRequestError,
95         Error::WrongDocument => DOMErrorName::WrongDocumentError,
96         Error::InvalidCharacter => DOMErrorName::InvalidCharacterError,
97         Error::NotSupported => DOMErrorName::NotSupportedError,
98         Error::InUseAttribute => DOMErrorName::InUseAttributeError,
99         Error::InvalidState => DOMErrorName::InvalidStateError,
100         Error::Syntax => DOMErrorName::SyntaxError,
101         Error::Namespace => DOMErrorName::NamespaceError,
102         Error::InvalidAccess => DOMErrorName::InvalidAccessError,
103         Error::Security => DOMErrorName::SecurityError,
104         Error::Network => DOMErrorName::NetworkError,
105         Error::Abort => DOMErrorName::AbortError,
106         Error::Timeout => DOMErrorName::TimeoutError,
107         Error::InvalidNodeType => DOMErrorName::InvalidNodeTypeError,
108         Error::DataClone => DOMErrorName::DataCloneError,
109         Error::NoModificationAllowed => DOMErrorName::NoModificationAllowedError,
110         Error::QuotaExceeded => DOMErrorName::QuotaExceededError,
111         Error::TypeMismatch => DOMErrorName::TypeMismatchError,
112         Error::InvalidModification => DOMErrorName::InvalidModificationError,
113         Error::Type(message) => {
114             assert!(!JS_IsExceptionPending(cx));
115             throw_type_error(cx, &message);
116             return;
117         },
118         Error::Range(message) => {
119             assert!(!JS_IsExceptionPending(cx));
120             throw_range_error(cx, &message);
121             return;
122         },
123         Error::JSFailed => {
124             assert!(JS_IsExceptionPending(cx));
125             return;
126         }
127     };
128 
129     assert!(!JS_IsExceptionPending(cx));
130     let exception = DOMException::new(global, code);
131     rooted!(in(cx) let mut thrown = UndefinedValue());
132     exception.to_jsval(cx, thrown.handle_mut());
133     JS_SetPendingException(cx, thrown.handle());
134 }
135 
136 /// A struct encapsulating information about a runtime script error.
137 pub struct ErrorInfo {
138     /// The error message.
139     pub message: String,
140     /// The file name.
141     pub filename: String,
142     /// The line number.
143     pub lineno: c_uint,
144     /// The column number.
145     pub column: c_uint,
146 }
147 
148 impl ErrorInfo {
from_native_error(cx: *mut JSContext, object: HandleObject) -> Option<ErrorInfo>149     unsafe fn from_native_error(cx: *mut JSContext, object: HandleObject)
150                                 -> Option<ErrorInfo> {
151         let report = JS_ErrorFromException(cx, object);
152         if report.is_null() {
153             return None;
154         }
155 
156         let filename = {
157             let filename = (*report).filename as *const u8;
158             if !filename.is_null() {
159                 let length = (0..).find(|idx| *filename.offset(*idx) == 0).unwrap();
160                 let filename = from_raw_parts(filename, length as usize);
161                 String::from_utf8_lossy(filename).into_owned()
162             } else {
163                 "none".to_string()
164             }
165         };
166 
167         let lineno = (*report).lineno;
168         let column = (*report).column;
169 
170         let message = {
171             let message = (*report).ucmessage;
172             let length = (0..).find(|idx| *message.offset(*idx) == 0).unwrap();
173             let message = from_raw_parts(message, length as usize);
174             String::from_utf16_lossy(message)
175         };
176 
177         Some(ErrorInfo {
178             filename: filename,
179             message: message,
180             lineno: lineno,
181             column: column,
182         })
183     }
184 
from_dom_exception(object: HandleObject) -> Option<ErrorInfo>185     fn from_dom_exception(object: HandleObject) -> Option<ErrorInfo> {
186         let exception = match root_from_object::<DOMException>(object.get()) {
187             Ok(exception) => exception,
188             Err(_) => return None,
189         };
190 
191         Some(ErrorInfo {
192             filename: "".to_string(),
193             message: exception.Stringifier().into(),
194             lineno: 0,
195             column: 0,
196         })
197     }
198 }
199 
200 /// Report a pending exception, thereby clearing it.
201 ///
202 /// The `dispatch_event` argument is temporary and non-standard; passing false
203 /// prevents dispatching the `error` event.
report_pending_exception(cx: *mut JSContext, dispatch_event: bool)204 pub unsafe fn report_pending_exception(cx: *mut JSContext, dispatch_event: bool) {
205     if !JS_IsExceptionPending(cx) { return; }
206 
207     rooted!(in(cx) let mut value = UndefinedValue());
208     if !JS_GetPendingException(cx, value.handle_mut()) {
209         JS_ClearPendingException(cx);
210         error!("Uncaught exception: JS_GetPendingException failed");
211         return;
212     }
213 
214     JS_ClearPendingException(cx);
215     let error_info = if value.is_object() {
216         rooted!(in(cx) let object = value.to_object());
217         ErrorInfo::from_native_error(cx, object.handle())
218             .or_else(|| ErrorInfo::from_dom_exception(object.handle()))
219             .unwrap_or_else(|| {
220                 ErrorInfo {
221                     message: format!("uncaught exception: unknown (can't convert to string)"),
222                     filename: String::new(),
223                     lineno: 0,
224                     column: 0,
225                 }
226             })
227     } else {
228         match USVString::from_jsval(cx, value.handle(), ()) {
229             Ok(ConversionResult::Success(USVString(string))) => {
230                 ErrorInfo {
231                     message: format!("uncaught exception: {}", string),
232                     filename: String::new(),
233                     lineno: 0,
234                     column: 0,
235                 }
236             },
237             _ => {
238                 panic!("Uncaught exception: failed to stringify primitive");
239             },
240         }
241     };
242 
243     error!("Error at {}:{}:{} {}",
244            error_info.filename,
245            error_info.lineno,
246            error_info.column,
247            error_info.message);
248 
249     if dispatch_event {
250         GlobalScope::from_context(cx)
251             .report_an_error(error_info, value.handle());
252     }
253 }
254 
255 /// Throw an exception to signal that a `JSVal` can not be converted to any of
256 /// the types in an IDL union type.
throw_not_in_union(cx: *mut JSContext, names: &'static str)257 pub unsafe fn throw_not_in_union(cx: *mut JSContext, names: &'static str) {
258     assert!(!JS_IsExceptionPending(cx));
259     let error = format!("argument could not be converted to any of: {}", names);
260     throw_type_error(cx, &error);
261 }
262 
263 /// Throw an exception to signal that a `JSObject` can not be converted to a
264 /// given DOM type.
throw_invalid_this(cx: *mut JSContext, proto_id: u16)265 pub unsafe fn throw_invalid_this(cx: *mut JSContext, proto_id: u16) {
266     debug_assert!(!JS_IsExceptionPending(cx));
267     let error = format!("\"this\" object does not implement interface {}.",
268                         proto_id_to_name(proto_id));
269     throw_type_error(cx, &error);
270 }
271 
272 impl Error {
273     /// Convert this error value to a JS value, consuming it in the process.
to_jsval(self, cx: *mut JSContext, global: &GlobalScope, rval: MutableHandleValue)274     pub unsafe fn to_jsval(self, cx: *mut JSContext, global: &GlobalScope, rval: MutableHandleValue) {
275         assert!(!JS_IsExceptionPending(cx));
276         throw_dom_exception(cx, global, self);
277         assert!(JS_IsExceptionPending(cx));
278         assert!(JS_GetPendingException(cx, rval));
279         JS_ClearPendingException(cx);
280     }
281 }
282