Skip to main content

script_bindings/
conversions.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
5use std::{ffi, ptr, slice};
6
7use js::context::JSContext;
8use js::conversions::{
9    ConversionResult, FromJSValConvertible, ToJSValConvertible, jsstr_to_string,
10};
11use js::error::throw_type_error;
12use js::glue::{
13    GetProxyHandlerExtra, GetProxyReservedSlot, IsProxyHandlerFamily, IsWrapper, JS_GetReservedSlot,
14};
15use js::jsapi::{Heap, IsWindowProxy, JS_DeprecatedStringHasLatin1Chars, JSObject};
16use js::jsval::{ObjectValue, StringValue, UndefinedValue};
17use js::rust::wrappers2::{
18    IsArrayObject, JS_GetLatin1StringCharsAndLength, JS_GetTwoByteStringCharsAndLength,
19    JS_NewStringCopyN, UnwrapObjectDynamic,
20};
21use js::rust::{
22    HandleId, HandleObject, HandleValue, MutableHandleValue, ToString, get_object_class,
23    is_dom_class, is_dom_object, maybe_wrap_value,
24};
25use keyboard_types::Modifiers;
26use num_traits::Float;
27
28use crate::JSTraceable;
29use crate::codegen::GenericBindings::EventModifierInitBinding::EventModifierInit;
30use crate::codegen::PrototypeList;
31use crate::error::{Error, Fallible};
32use crate::inheritance::Castable;
33use crate::js::JS_GetProperty;
34use crate::num::Finite;
35use crate::reflector::{DomObject, Reflector};
36use crate::root::{Dom, DomRoot};
37use crate::str::{ByteString, DOMString, USVString};
38use crate::trace::RootedTraceableBox;
39use crate::utils::{DOMClass, DOMJSClass};
40
41/// A trait to check whether a given `JSObject` implements an IDL interface.
42pub trait IDLInterface {
43    /// Returns whether the given DOM class derives that interface.
44    fn derives(_: &'static DOMClass) -> bool;
45
46    /// The concrete type represented by this interface instance.
47    const PROTO_ID: PrototypeList::ID;
48
49    /// First prototype ID in the DFS-ordered range for this interface and its descendants.
50    const PROTO_FIRST: u16 = 0;
51    /// Last prototype ID in the DFS-ordered range for this interface and its descendants.
52    const PROTO_LAST: u16 = u16::MAX;
53}
54
55/// A trait to mark an IDL interface as deriving from another one.
56pub trait DerivedFrom<T: Castable>: Castable {}
57
58// http://heycam.github.io/webidl/#es-USVString
59impl ToJSValConvertible for USVString {
60    fn to_jsval(&self, cx: &mut JSContext, rval: MutableHandleValue) {
61        self.0.to_jsval(cx, rval);
62    }
63}
64
65/// Behavior for stringification of `JSVal`s.
66#[derive(Clone, PartialEq)]
67pub enum StringificationBehavior {
68    /// Convert `null` to the string `"null"`.
69    Default,
70    /// Convert `null` to the empty string.
71    Empty,
72}
73
74// https://heycam.github.io/webidl/#es-DOMString
75impl FromJSValConvertible for DOMString {
76    type Config = StringificationBehavior;
77
78    fn from_jsval(
79        cx: &mut JSContext,
80        value: HandleValue,
81        null_behavior: StringificationBehavior,
82    ) -> Result<ConversionResult<DOMString>, ()> {
83        if null_behavior == StringificationBehavior::Empty && value.get().is_null() {
84            Ok(ConversionResult::Success(DOMString::new()))
85        } else {
86            match DOMString::from_js_string(cx, value) {
87                Ok(domstring) => Ok(ConversionResult::Success(domstring)),
88                Err(_) => Err(()),
89            }
90        }
91    }
92}
93
94// http://heycam.github.io/webidl/#es-USVString
95impl FromJSValConvertible for USVString {
96    type Config = ();
97
98    fn from_jsval(
99        cx: &mut JSContext,
100        value: HandleValue,
101        _: (),
102    ) -> Result<ConversionResult<USVString>, ()> {
103        let Some(jsstr) = ptr::NonNull::new(unsafe { ToString(cx, value) }) else {
104            debug!("ToString failed");
105            return Err(());
106        };
107
108        // FIXME(ajeffrey): Convert directly from DOMString to USVString
109        Ok(ConversionResult::Success(USVString(unsafe {
110            jsstr_to_string(cx, jsstr)
111        })))
112    }
113}
114
115// http://heycam.github.io/webidl/#es-ByteString
116impl ToJSValConvertible for ByteString {
117    fn to_jsval(&self, cx: &mut JSContext, mut rval: MutableHandleValue) {
118        let jsstr = unsafe {
119            JS_NewStringCopyN(
120                cx,
121                self.as_ptr() as *const libc::c_char,
122                self.len() as libc::size_t,
123            )
124        };
125        if jsstr.is_null() {
126            panic!("JS_NewStringCopyN failed");
127        }
128        unsafe { rval.set(StringValue(&*jsstr)) };
129    }
130}
131
132// http://heycam.github.io/webidl/#es-ByteString
133impl FromJSValConvertible for ByteString {
134    type Config = ();
135
136    fn from_jsval(
137        cx: &mut JSContext,
138        value: HandleValue,
139        _option: (),
140    ) -> Result<ConversionResult<ByteString>, ()> {
141        unsafe {
142            let string = ToString(cx, value);
143            if string.is_null() {
144                debug!("ToString failed");
145                return Err(());
146            }
147
148            let latin1 = JS_DeprecatedStringHasLatin1Chars(string);
149            if latin1 {
150                let mut length = 0;
151                let chars = JS_GetLatin1StringCharsAndLength(cx, string, &mut length);
152                assert!(!chars.is_null());
153
154                let char_slice = slice::from_raw_parts(chars as *mut u8, length);
155                return Ok(ConversionResult::Success(ByteString::new(
156                    char_slice.to_vec(),
157                )));
158            }
159
160            let mut length = 0;
161            let chars = JS_GetTwoByteStringCharsAndLength(cx, string, &mut length);
162            let char_vec = slice::from_raw_parts(chars, length);
163
164            if char_vec.iter().any(|&c| c > 0xFF) {
165                throw_type_error(cx, c"Invalid ByteString");
166                Err(())
167            } else {
168                Ok(ConversionResult::Success(ByteString::new(
169                    char_vec.iter().map(|&c| c as u8).collect(),
170                )))
171            }
172        }
173    }
174}
175
176impl<T> ToJSValConvertible for Reflector<T> {
177    fn to_jsval(&self, cx: &mut JSContext, mut rval: MutableHandleValue) {
178        let obj = self.get_jsobject().get();
179        assert!(!obj.is_null());
180        rval.set(ObjectValue(obj));
181        maybe_wrap_value(cx, rval);
182    }
183}
184
185impl<T: DomObject + IDLInterface> FromJSValConvertible for DomRoot<T> {
186    type Config = ();
187
188    fn from_jsval(
189        cx: &mut JSContext,
190        value: HandleValue,
191        _config: Self::Config,
192    ) -> Result<ConversionResult<DomRoot<T>>, ()> {
193        Ok(match root_from_handlevalue(cx, value) {
194            Ok(result) => ConversionResult::Success(result),
195            Err(()) => ConversionResult::Failure(c"value is not an object".into()),
196        })
197    }
198}
199
200impl<T: DomObject> ToJSValConvertible for DomRoot<T> {
201    fn to_jsval(&self, cx: &mut JSContext, rval: MutableHandleValue) {
202        self.reflector().to_jsval(cx, rval);
203    }
204}
205
206impl<T: DomObject> ToJSValConvertible for Dom<T> {
207    fn to_jsval(&self, cx: &mut JSContext, rval: MutableHandleValue) {
208        let root = self.as_rooted();
209        root.to_jsval(cx, rval);
210    }
211}
212
213/// Get the `DOMClass` from `obj`, or `Err(())` if `obj` is not a DOM object.
214///
215/// # Safety
216/// obj must point to a valid, non-null JS object.
217#[allow(clippy::result_unit_err)]
218pub unsafe fn get_dom_class(obj: *mut JSObject) -> Result<&'static DOMClass, ()> {
219    unsafe {
220        let clasp = get_object_class(obj);
221        if is_dom_class(&*clasp) {
222            trace!("plain old dom object");
223            let domjsclass: *const DOMJSClass = clasp as *const DOMJSClass;
224            return Ok(&(*domjsclass).dom_class);
225        }
226        if is_dom_proxy(obj) {
227            trace!("proxy dom object");
228            let dom_class: *const DOMClass = GetProxyHandlerExtra(obj) as *const DOMClass;
229            if dom_class.is_null() {
230                return Err(());
231            }
232            return Ok(&*dom_class);
233        }
234    }
235    trace!("not a dom object");
236    Err(())
237}
238
239/// Returns whether `obj` is a DOM object implemented as a proxy.
240///
241/// # Safety
242/// obj must point to a valid, non-null JS object.
243pub unsafe fn is_dom_proxy(obj: *mut JSObject) -> bool {
244    unsafe {
245        let clasp = get_object_class(obj);
246        ((*clasp).flags & js::JSCLASS_IS_PROXY) != 0 && IsProxyHandlerFamily(obj)
247    }
248}
249
250/// The index of the slot wherein a pointer to the reflected DOM object is
251/// stored for non-proxy bindings.
252// We use slot 0 for holding the raw object.  This is safe for both
253// globals and non-globals.
254pub const DOM_OBJECT_SLOT: u32 = 0;
255
256/// Get the private pointer of a DOM object from a given reflector.
257///
258/// # Safety
259/// obj must point to a valid non-null JS object.
260pub unsafe fn private_from_object(obj: *mut JSObject) -> *const libc::c_void {
261    let mut value = UndefinedValue();
262    unsafe {
263        if is_dom_object(obj) {
264            JS_GetReservedSlot(obj, DOM_OBJECT_SLOT, &mut value);
265        } else {
266            debug_assert!(is_dom_proxy(obj));
267            GetProxyReservedSlot(obj, 0, &mut value);
268        };
269    }
270    if value.is_undefined() {
271        ptr::null()
272    } else {
273        value.to_private()
274    }
275}
276
277pub enum PrototypeCheck {
278    Derive(fn(&'static DOMClass) -> bool),
279    Depth { depth: usize, proto_id: u16 },
280}
281
282/// Get a `*const libc::c_void` for the given DOM object, unwrapping any
283/// wrapper around it first, and checking if the object is of the correct type.
284///
285/// Returns Err(()) if `obj` is an opaque security wrapper or if the object is
286/// not an object for a DOM object of the given type (as defined by the
287/// proto_id and proto_depth).
288///
289/// # Safety
290/// obj must point to a valid, non-null JS object.
291/// cx must point to a valid, non-null JS context.
292#[inline]
293#[allow(clippy::result_unit_err)]
294pub unsafe fn private_from_proto_check(
295    cx: &mut JSContext,
296    mut obj: *mut JSObject,
297    proto_check: PrototypeCheck,
298) -> Result<*const libc::c_void, ()> {
299    let dom_class = unsafe {
300        get_dom_class(obj).or_else(|_| {
301            if IsWrapper(obj) {
302                trace!("found wrapper");
303                obj = UnwrapObjectDynamic(obj, cx, /* stopAtWindowProxy = */ false);
304                if obj.is_null() {
305                    trace!("unwrapping security wrapper failed");
306                    Err(())
307                } else {
308                    assert!(!IsWrapper(obj));
309                    trace!("unwrapped successfully");
310                    get_dom_class(obj)
311                }
312            } else {
313                trace!("not a dom wrapper");
314                Err(())
315            }
316        })?
317    };
318
319    let prototype_matches = match proto_check {
320        PrototypeCheck::Derive(f) => (f)(dom_class),
321        PrototypeCheck::Depth { depth, proto_id } => {
322            dom_class.interface_chain[depth] as u16 == proto_id
323        },
324    };
325
326    if prototype_matches {
327        trace!("good prototype");
328        Ok(unsafe { private_from_object(obj) })
329    } else {
330        trace!("bad prototype");
331        Err(())
332    }
333}
334
335/// Get a `*const T` for a DOM object accessible from a `JSObject`.
336///
337/// # Safety
338/// obj must point to a valid, non-null JS object.
339/// cx must point to a valid, non-null JS context.
340#[allow(clippy::result_unit_err)]
341pub unsafe fn native_from_object<T>(cx: &mut JSContext, obj: *mut JSObject) -> Result<*const T, ()>
342where
343    T: DomObject + IDLInterface,
344{
345    unsafe {
346        private_from_proto_check(cx, obj, PrototypeCheck::Derive(T::derives))
347            .map(|ptr| ptr as *const T)
348    }
349}
350
351/// Get a `DomRoot<T>` for the given DOM object, unwrapping any wrapper
352/// around it first, and checking if the object is of the correct type.
353///
354/// Returns Err(()) if `obj` is an opaque security wrapper or if the object is
355/// not a reflector for a DOM object of the given type (as defined by the
356/// proto_id and proto_depth).
357///
358/// # Safety
359/// obj must point to a valid, non-null JS object.
360/// cx must point to a valid, non-null JS context.
361#[allow(clippy::result_unit_err)]
362pub unsafe fn root_from_object<T>(cx: &mut JSContext, obj: *mut JSObject) -> Result<DomRoot<T>, ()>
363where
364    T: DomObject + IDLInterface,
365{
366    unsafe { native_from_object(cx, obj).map(|ptr| DomRoot::from_ref(&*ptr)) }
367}
368
369/// Get a `DomRoot<T>` for a DOM object accessible from a `HandleValue`.
370/// Caller is responsible for throwing a JS exception if needed in case of error.
371///
372/// # Safety
373/// cx must point to a valid, non-null JS context.
374#[allow(clippy::result_unit_err)]
375pub fn root_from_handlevalue<T>(cx: &mut JSContext, v: HandleValue) -> Result<DomRoot<T>, ()>
376where
377    T: DomObject + IDLInterface,
378{
379    if !v.get().is_object() {
380        return Err(());
381    }
382    #[expect(unsafe_code)]
383    unsafe {
384        root_from_object(cx, v.get().to_object())
385    }
386}
387
388/// Convert `id` to a `DOMString`. Returns `None` if `id` is not a string or
389/// integer.
390///
391/// Handling of invalid UTF-16 in strings depends on the relevant option.
392pub fn jsid_to_string(cx: &js::context::JSContext, id: HandleId) -> Option<DOMString> {
393    let id_raw = *id;
394    if id_raw.is_string() {
395        let jsstr = id_raw.to_string();
396        return Some(unsafe {
397            // Safe as `to_string` should always point to a valid JSString.
398            DOMString::from_raw_js_string(cx, jsstr).expect(
399                "Should always be able to convert a property id that is a string to a DOMString",
400            )
401        });
402    }
403
404    if id_raw.is_int() {
405        return Some(id_raw.to_int().to_string().into());
406    }
407
408    None
409}
410
411impl<T: Float + ToJSValConvertible> ToJSValConvertible for Finite<T> {
412    #[inline]
413    fn to_jsval(&self, cx: &mut JSContext, rval: MutableHandleValue) {
414        let value = **self;
415        value.to_jsval(cx, rval);
416    }
417}
418
419impl<T: Float + FromJSValConvertible<Config = ()>> FromJSValConvertible for Finite<T> {
420    type Config = ();
421
422    fn from_jsval(
423        cx: &mut JSContext,
424        value: HandleValue,
425        option: (),
426    ) -> Result<ConversionResult<Finite<T>>, ()> {
427        let result = match FromJSValConvertible::from_jsval(cx, value, option)? {
428            ConversionResult::Success(v) => v,
429            ConversionResult::Failure(error) => {
430                // FIXME(emilio): Why throwing instead of propagating the error?
431                throw_type_error(cx, &error);
432                return Err(());
433            },
434        };
435        match Finite::new(result) {
436            Some(v) => Ok(ConversionResult::Success(v)),
437            None => {
438                throw_type_error(cx, c"this argument is not a finite floating-point value");
439                Err(())
440            },
441        }
442    }
443}
444
445/// Get a `*const libc::c_void` for the given DOM object, unless it is a DOM
446/// wrapper, and checking if the object is of the correct type.
447///
448/// Returns Err(()) if `obj` is a wrapper or if the object is not an object
449/// for a DOM object of the given type (as defined by the proto_id and proto_depth).
450#[inline]
451#[allow(clippy::result_unit_err)]
452unsafe fn private_from_proto_check_static(
453    obj: *mut JSObject,
454    proto_check: fn(&'static DOMClass) -> bool,
455) -> Result<*const libc::c_void, ()> {
456    unsafe {
457        let dom_class = get_dom_class(obj).map_err(|_| ())?;
458        if proto_check(dom_class) {
459            trace!("good prototype");
460            Ok(private_from_object(obj))
461        } else {
462            trace!("bad prototype");
463            Err(())
464        }
465    }
466}
467
468/// Get a `*const T` for a DOM object accessible from a `JSObject`, where the DOM object
469/// is guaranteed not to be a wrapper.
470///
471/// # Safety
472/// `obj` must point to a valid, non-null JSObject.
473#[allow(clippy::result_unit_err)]
474pub unsafe fn native_from_object_static<T>(obj: *mut JSObject) -> Result<*const T, ()>
475where
476    T: DomObject + IDLInterface,
477{
478    unsafe { private_from_proto_check_static(obj, T::derives).map(|ptr| ptr as *const T) }
479}
480
481/// Get a `*const T` for a DOM object accessible from a `HandleValue`.
482/// Caller is responsible for throwing a JS exception if needed in case of error.
483///
484/// # Safety
485/// `cx` must point to a valid, non-null JSContext.
486#[allow(clippy::result_unit_err)]
487pub fn native_from_handlevalue<T>(cx: &mut JSContext, v: HandleValue) -> Result<*const T, ()>
488where
489    T: DomObject + IDLInterface,
490{
491    if !v.get().is_object() {
492        return Err(());
493    }
494
495    #[expect(unsafe_code)]
496    unsafe {
497        native_from_object(cx, v.get().to_object())
498    }
499}
500
501impl<T: ToJSValConvertible + JSTraceable> ToJSValConvertible for RootedTraceableBox<T> {
502    #[inline]
503    fn to_jsval(&self, cx: &mut JSContext, rval: MutableHandleValue) {
504        let value = &**self;
505        value.to_jsval(cx, rval);
506    }
507}
508
509impl<T> FromJSValConvertible for RootedTraceableBox<Heap<T>>
510where
511    T: FromJSValConvertible + js::rust::GCMethods + Copy,
512    Heap<T>: JSTraceable + Default,
513{
514    type Config = T::Config;
515
516    fn from_jsval(
517        cx: &mut JSContext,
518        value: HandleValue,
519        config: Self::Config,
520    ) -> Result<ConversionResult<Self>, ()> {
521        T::from_jsval(cx, value, config).map(|result| match result {
522            ConversionResult::Success(inner) => {
523                ConversionResult::Success(RootedTraceableBox::from_box(Heap::boxed(inner)))
524            },
525            ConversionResult::Failure(msg) => ConversionResult::Failure(msg),
526        })
527    }
528}
529
530/// Returns whether `value` is an array-like object (Array, FileList,
531/// HTMLCollection, HTMLFormControlsCollection, HTMLOptionsCollection,
532/// NodeList, DOMTokenList).
533pub fn is_array_like<D: crate::DomTypes>(cx: &mut JSContext, value: HandleValue) -> bool {
534    let mut is_array = false;
535    assert!(unsafe { IsArrayObject(cx, value, &mut is_array) });
536    if is_array {
537        return true;
538    }
539
540    let object: *mut JSObject = match FromJSValConvertible::from_jsval(cx, value, ()).unwrap() {
541        ConversionResult::Success(object) => object,
542        _ => return false,
543    };
544
545    unsafe {
546        // TODO: HTMLAllCollection
547        if root_from_object::<D::DOMTokenList>(cx, object).is_ok() {
548            return true;
549        }
550        if root_from_object::<D::FileList>(cx, object).is_ok() {
551            return true;
552        }
553        if root_from_object::<D::HTMLCollection>(cx, object).is_ok() {
554            return true;
555        }
556        if root_from_object::<D::HTMLFormControlsCollection>(cx, object).is_ok() {
557            return true;
558        }
559        if root_from_object::<D::HTMLOptionsCollection>(cx, object).is_ok() {
560            return true;
561        }
562        if root_from_object::<D::NodeList>(cx, object).is_ok() {
563            return true;
564        }
565    }
566
567    false
568}
569
570/// Get a `DomRoot<T>` for a WindowProxy accessible from a `HandleValue`.
571/// Caller is responsible for throwing a JS exception if needed in case of error.
572pub(crate) unsafe fn windowproxy_from_handlevalue<D: crate::DomTypes>(
573    v: HandleValue,
574) -> Result<DomRoot<D::WindowProxy>, ()> {
575    if !v.get().is_object() {
576        return Err(());
577    }
578    let object = v.get().to_object();
579    unsafe {
580        if !IsWindowProxy(object) {
581            return Err(());
582        }
583        let mut value = UndefinedValue();
584        GetProxyReservedSlot(object, 0, &mut value);
585        let ptr = value.to_private() as *const D::WindowProxy;
586        Ok(DomRoot::from_ref(&*ptr))
587    }
588}
589
590#[allow(deprecated)]
591impl<D: crate::DomTypes> EventModifierInit<D> {
592    pub fn modifiers(&self) -> Modifiers {
593        let mut modifiers = Modifiers::empty();
594        if self.altKey {
595            modifiers.insert(Modifiers::ALT);
596        }
597        if self.ctrlKey {
598            modifiers.insert(Modifiers::CONTROL);
599        }
600        if self.shiftKey {
601            modifiers.insert(Modifiers::SHIFT);
602        }
603        if self.metaKey {
604            modifiers.insert(Modifiers::META);
605        }
606        if self.keyModifierStateAltGraph {
607            modifiers.insert(Modifiers::ALT_GRAPH);
608        }
609        if self.keyModifierStateCapsLock {
610            modifiers.insert(Modifiers::CAPS_LOCK);
611        }
612        if self.keyModifierStateFn {
613            modifiers.insert(Modifiers::FN);
614        }
615        if self.keyModifierStateFnLock {
616            modifiers.insert(Modifiers::FN_LOCK);
617        }
618        if self.keyModifierStateHyper {
619            modifiers.insert(Modifiers::HYPER);
620        }
621        if self.keyModifierStateNumLock {
622            modifiers.insert(Modifiers::NUM_LOCK);
623        }
624        if self.keyModifierStateScrollLock {
625            modifiers.insert(Modifiers::SCROLL_LOCK);
626        }
627        if self.keyModifierStateSuper {
628            modifiers.insert(Modifiers::SUPER);
629        }
630        if self.keyModifierStateSymbol {
631            modifiers.insert(Modifiers::SYMBOL);
632        }
633        if self.keyModifierStateSymbolLock {
634            modifiers.insert(Modifiers::SYMBOL_LOCK);
635        }
636        modifiers
637    }
638}
639
640/// Get a property from a JS object.
641pub fn get_property_jsval(
642    cx: &mut JSContext,
643    object: HandleObject,
644    name: &ffi::CStr,
645    rval: MutableHandleValue,
646) -> Fallible<()> {
647    if !JS_GetProperty(cx, object, name, rval) {
648        return Err(Error::JSFailed);
649    }
650
651    Ok(())
652}
653
654/// Get a property from a JS object, and convert it to a Rust value.
655pub fn get_property<T>(
656    cx: &mut JSContext,
657    object: HandleObject,
658    name: &ffi::CStr,
659    option: T::Config,
660) -> Fallible<Option<T>>
661where
662    T: FromJSValConvertible,
663{
664    rooted!(&in(cx) let mut result = UndefinedValue());
665    get_property_jsval(cx, object, name, result.handle_mut())?;
666
667    if result.is_undefined() {
668        return Ok(None);
669    }
670
671    let value = T::from_jsval(cx, result.handle(), option);
672    match value {
673        Ok(ConversionResult::Success(value)) => Ok(Some(value)),
674        Ok(ConversionResult::Failure(error)) => Err(Error::Type(error.into_owned())),
675        Err(()) => Err(Error::JSFailed),
676    }
677}