1#![cfg_attr(crown, allow(crown::jscontext_first_arg))]
6
7use std::ffi::CStr;
8use std::os::raw::{c_char, c_void};
9use std::ptr::{self, NonNull};
10use std::slice;
11
12use js::context::{JSContext, RawJSContext};
13use js::conversions::{ToJSValConvertible, jsstr_to_string};
14use js::gc::Handle;
15use js::glue::{JS_GetReservedSlot, RUST_FUNCTION_VALUE_TO_JITINFO};
16use js::jsapi::{
17 AtomToLinearString, CallArgs, ExceptionStackBehavior, GetLinearStringCharAt,
18 GetLinearStringLength, GetNonCCWObjectGlobal, HandleId as RawHandleId,
19 HandleObject as RawHandleObject, Heap, JS_DeprecatedStringHasLatin1Chars,
20 JS_GetLatin1StringCharsAndLength, JS_IsGlobalObject, JS_MayResolveStandardClass,
21 JS_NewEnumerateStandardClasses, JS_ResolveStandardClass, JSAtom, JSAtomState, JSJitInfo,
22 JSObject, JSPROP_ENUMERATE, JSTracer, MutableHandleIdVector as RawMutableHandleIdVector,
23 MutableHandleValue as RawMutableHandleValue, PropertyKey, StringIsArrayIndex, jsid,
24};
25use js::jsid::StringId;
26use js::jsval::{JSVal, UndefinedValue};
27use js::rust::wrappers2::{
28 AppendToIdVector, CallJitGetterOp, CallJitMethodOp, CallJitSetterOp, CallOriginalPromiseReject,
29 JS_AtomizeStringN, JS_ClearPendingException, JS_DefineProperty, JS_ForwardGetPropertyTo,
30 JS_FreezeObject, JS_GetPendingException, JS_GetProperty, JS_GetPrototype, JS_HasOwnProperty,
31 JS_HasProperty, JS_HasPropertyById, JS_IsExceptionPending, JS_SetPendingException,
32 JS_SetProperty,
33};
34use js::rust::{
35 HandleId, HandleObject, HandleValue, MutableHandleValue, Runtime, ToString, get_object_class,
36};
37use js::{JS_CALLEE, rooted};
38use malloc_size_of::MallocSizeOfOps;
39
40use crate::DomTypes;
41use crate::codegen::Globals::Globals;
42use crate::codegen::InheritTypes::TopTypeId;
43use crate::codegen::PrototypeList::{self, MAX_PROTO_CHAIN_LENGTH, PROTO_OR_IFACE_LENGTH};
44use crate::conversions::{PrototypeCheck, private_from_proto_check};
45use crate::error::throw_invalid_this;
46use crate::interfaces::DomHelpers;
47use crate::proxyhandler::{
48 is_cross_origin_object, is_platform_object_same_origin, report_cross_origin_denial,
49};
50use crate::str::DOMString;
51use crate::trace::trace_object;
52
53#[derive(Clone, Copy)]
55pub struct DOMClass {
56 pub interface_chain: [PrototypeList::ID; MAX_PROTO_CHAIN_LENGTH],
59
60 pub depth: u8,
62
63 pub type_id: TopTypeId,
65
66 pub malloc_size_of: unsafe fn(ops: &mut MallocSizeOfOps, *const c_void) -> usize,
68
69 pub global: Globals,
71}
72unsafe impl Sync for DOMClass {}
73
74#[derive(Copy)]
76#[repr(C)]
77pub struct DOMJSClass {
78 pub base: js::jsapi::JSClass,
80 pub dom_class: DOMClass,
82}
83impl Clone for DOMJSClass {
84 fn clone(&self) -> DOMJSClass {
85 *self
86 }
87}
88unsafe impl Sync for DOMJSClass {}
89
90pub(crate) const DOM_PROTO_UNFORGEABLE_HOLDER_SLOT: u32 = 0;
93
94pub(crate) const DOM_PROTOTYPE_SLOT: u32 = js::JSCLASS_GLOBAL_SLOT_COUNT;
97
98pub(crate) const JSCLASS_DOM_GLOBAL: u32 = js::JSCLASS_USERBIT1;
103
104pub(crate) unsafe fn get_proto_or_iface_array(global: *mut JSObject) -> *mut ProtoOrIfaceArray {
110 unsafe {
111 assert_ne!(((*get_object_class(global)).flags & JSCLASS_DOM_GLOBAL), 0);
112 let mut slot = UndefinedValue();
113 JS_GetReservedSlot(global, DOM_PROTOTYPE_SLOT, &mut slot);
114 slot.to_private() as *mut ProtoOrIfaceArray
115 }
116}
117
118pub type ProtoOrIfaceArray = [*mut JSObject; PROTO_OR_IFACE_LENGTH];
120
121pub(crate) fn get_property_on_prototype(
126 cx: &mut JSContext,
127 proxy: HandleObject,
128 receiver: HandleValue,
129 id: HandleId,
130 found: &mut bool,
131 vp: MutableHandleValue,
132) -> bool {
133 rooted!(&in(cx) let mut proto = ptr::null_mut::<JSObject>());
134 if unsafe { !JS_GetPrototype(cx, proxy, proto.handle_mut()) || proto.is_null() } {
135 *found = false;
136 return true;
137 }
138 let mut has_property = false;
139 if unsafe { !JS_HasPropertyById(cx, proto.handle(), id, &mut has_property) } {
140 return false;
141 }
142 *found = has_property;
143 if !has_property {
144 return true;
145 }
146
147 unsafe { JS_ForwardGetPropertyTo(cx, proto.handle(), id, receiver, vp) }
148}
149
150pub fn get_array_index_from_id(id: HandleId) -> Option<u32> {
153 let raw_id = *id;
154 if raw_id.is_int() {
155 return Some(raw_id.to_int() as u32);
156 }
157
158 if raw_id.is_void() || !raw_id.is_string() {
159 return None;
160 }
161
162 unsafe {
163 let atom = raw_id.to_string() as *mut JSAtom;
164 let s = AtomToLinearString(atom);
165 if GetLinearStringLength(s) == 0 {
166 return None;
167 }
168
169 let chars = [GetLinearStringCharAt(s, 0)];
170 let first_char = char::decode_utf16(chars.iter().cloned())
171 .next()
172 .map_or('\0', |r| r.unwrap_or('\0'));
173 if first_char.is_ascii_lowercase() {
174 return None;
175 }
176
177 let mut i = 0;
178 if StringIsArrayIndex(s, &mut i) {
179 Some(i)
180 } else {
181 None
182 }
183 }
184
185 }
211
212pub(crate) fn find_enum_value<'a, T>(
216 cx: &mut JSContext,
217 v: HandleValue,
218 pairs: &'a [(&'static str, T)],
219) -> Result<(Option<&'a T>, DOMString), ()> {
220 match NonNull::new(unsafe { ToString(cx, v) }) {
221 Some(jsstr) => {
222 let search = unsafe { jsstr_to_string(cx, jsstr) }.into();
223 Ok((
224 pairs
225 .iter()
226 .find(|&&(key, _)| search == key)
227 .map(|(_, ev)| ev),
228 search,
229 ))
230 },
231 None => Err(()),
232 }
233}
234
235pub(crate) fn get_dictionary_property(
239 cx: &mut JSContext,
240 object: HandleObject,
241 property: &CStr,
242 rval: MutableHandleValue,
243) -> Result<bool, ()> {
244 if object.get().is_null() {
245 return Ok(false);
246 }
247
248 let mut found = false;
249 if unsafe { !JS_HasProperty(cx, object, property.as_ptr(), &mut found) } {
250 return Err(());
251 }
252
253 if !found {
254 return Ok(false);
255 }
256
257 if unsafe { !JS_GetProperty(cx, object, property.as_ptr(), rval) } {
258 return Err(());
259 }
260
261 Ok(true)
262}
263
264#[expect(clippy::result_unit_err)]
268pub fn set_dictionary_property(
269 cx: &mut JSContext,
270 object: HandleObject,
271 property: &CStr,
272 value: HandleValue,
273) -> Result<(), ()> {
274 if object.get().is_null() {
275 return Err(());
276 }
277
278 if unsafe { !JS_SetProperty(cx, object, property.as_ptr(), value) } {
279 return Err(());
280 }
281
282 Ok(())
283}
284
285#[expect(clippy::result_unit_err)]
289pub fn define_dictionary_property(
290 cx: &mut JSContext,
291 object: HandleObject,
292 property: &CStr,
293 value: HandleValue,
294) -> Result<(), ()> {
295 if object.get().is_null() {
296 return Err(());
297 }
298
299 if unsafe {
300 !JS_DefineProperty(
301 cx,
302 object,
303 property.as_ptr(),
304 value,
305 JSPROP_ENUMERATE as u32,
306 )
307 } {
308 return Err(());
309 }
310
311 Ok(())
312}
313
314#[expect(clippy::result_unit_err)]
318pub fn has_own_property(
319 cx: &mut JSContext,
320 object: HandleObject,
321 property: &CStr,
322) -> Result<bool, ()> {
323 if object.get().is_null() {
324 return Ok(false);
325 }
326
327 let mut found = false;
328 if unsafe { !JS_HasOwnProperty(cx, object, property.as_ptr(), &mut found) } {
329 return Err(());
330 }
331
332 Ok(found)
333}
334
335pub fn has_property_on_prototype(
341 cx: &mut JSContext,
342 proxy: HandleObject,
343 id: HandleId,
344 found: &mut bool,
345) -> bool {
346 rooted!(&in(cx) let mut proto = ptr::null_mut::<JSObject>());
347 if unsafe { !JS_GetPrototype(cx, proxy, proto.handle_mut()) } {
348 return false;
349 }
350 assert!(!proto.is_null());
351 unsafe { JS_HasPropertyById(cx, proto.handle(), id, found) }
352}
353
354pub trait CallPolicy {
355 const INFO: CallPolicyInfo;
356}
357pub mod call_policies {
358 use super::*;
359 pub struct Normal;
360 pub struct TargetClassMaybeCrossOrigin;
361 pub struct LenientThis;
362 pub struct LenientThisTargetClassMaybeCrossOrigin;
363 pub struct CrossOriginCallable;
364 impl CallPolicy for Normal {
365 const INFO: CallPolicyInfo = CallPolicyInfo {
366 lenient_this: false,
367 needs_security_check_on_interface_match: false,
368 };
369 }
370 impl CallPolicy for TargetClassMaybeCrossOrigin {
371 const INFO: CallPolicyInfo = CallPolicyInfo {
372 lenient_this: false,
373 needs_security_check_on_interface_match: true,
374 };
375 }
376 impl CallPolicy for LenientThis {
377 const INFO: CallPolicyInfo = CallPolicyInfo {
378 lenient_this: true,
379 needs_security_check_on_interface_match: false,
380 };
381 }
382 impl CallPolicy for LenientThisTargetClassMaybeCrossOrigin {
383 const INFO: CallPolicyInfo = CallPolicyInfo {
384 lenient_this: true,
385 needs_security_check_on_interface_match: true,
386 };
387 }
388 impl CallPolicy for CrossOriginCallable {
389 const INFO: CallPolicyInfo = CallPolicyInfo {
390 lenient_this: false,
391 needs_security_check_on_interface_match: false,
392 };
393 }
394}
395#[derive(Clone, Copy, Eq, PartialEq)]
402pub struct CallPolicyInfo {
403 pub lenient_this: bool,
406 pub needs_security_check_on_interface_match: bool,
425}
426
427unsafe fn generic_call<D: DomTypes, const EXCEPTION_TO_REJECTION: bool>(
428 cx: &mut JSContext,
429 argc: libc::c_uint,
430 vp: *mut JSVal,
431 CallPolicyInfo {
432 lenient_this,
433 needs_security_check_on_interface_match,
434 }: CallPolicyInfo,
435 call: unsafe fn(
436 *const JSJitInfo,
437 &mut JSContext,
438 HandleObject,
439 *mut libc::c_void,
440 u32,
441 *mut JSVal,
442 ) -> bool,
443) -> bool {
444 let args = unsafe { CallArgs::from_vp(vp, argc) };
445
446 let info = unsafe { RUST_FUNCTION_VALUE_TO_JITINFO(JS_CALLEE(cx.raw_cx_no_gc(), vp)) };
447 let proto_id = unsafe { (*info).__bindgen_anon_2.protoID };
448
449 let thisobj = args.thisv();
525 if !thisobj.get().is_null_or_undefined() && !thisobj.get().is_object() {
526 throw_invalid_this(cx, proto_id);
529 return if EXCEPTION_TO_REJECTION {
530 exception_to_promise(cx, args.rval())
531 } else {
532 false
533 };
534 }
535
536 rooted!(&in(cx) let obj = if thisobj.get().is_object() {
537 thisobj.get().to_object()
538 } else {
539 unsafe { GetNonCCWObjectGlobal(JS_CALLEE(cx.raw_cx_no_gc(), vp).to_object_or_null()) }
540 });
541 let depth = unsafe { (*info).__bindgen_anon_3.depth as usize };
542 let proto_check = PrototypeCheck::Depth { depth, proto_id };
543 let this = match unsafe { private_from_proto_check(cx, obj.get(), proto_check) } {
544 Ok(val) => val,
545 Err(()) => {
546 if lenient_this {
558 unsafe {
559 debug_assert!(!JS_IsExceptionPending(cx));
560 *vp = UndefinedValue();
561 }
562 return true;
563 } else {
564 throw_invalid_this(cx, proto_id);
565 return if EXCEPTION_TO_REJECTION {
566 exception_to_promise(cx, args.rval())
567 } else {
568 false
569 };
570 }
571 },
572 };
573
574 if needs_security_check_on_interface_match {
577 let mut realm = js::realm::CurrentRealm::assert(cx);
578 if is_cross_origin_object::<D>(&mut realm, obj.handle()) &&
580 !is_platform_object_same_origin(&realm, obj.handle())
581 {
582 rooted!(&in(*realm) let mut void_jsid: jsid);
587 let result = report_cross_origin_denial::<D>(&mut realm, void_jsid.handle(), "call");
588 return if EXCEPTION_TO_REJECTION {
589 exception_to_promise(cx, args.rval())
590 } else {
591 result
592 };
593 }
594 } else {
595 }
598
599 unsafe { call(info, cx, obj.handle(), this as *mut libc::c_void, argc, vp) }
600}
601
602pub(crate) unsafe extern "C" fn generic_method<
608 D: DomTypes,
609 Policy: CallPolicy,
610 const EXCEPTION_TO_REJECTION: bool,
611>(
612 cx: *mut RawJSContext,
613 argc: libc::c_uint,
614 vp: *mut JSVal,
615) -> bool {
616 unsafe {
617 let mut cx = JSContext::from_ptr(NonNull::new(cx).unwrap());
619 let cx = &mut cx;
620
621 generic_call::<D, EXCEPTION_TO_REJECTION>(cx, argc, vp, Policy::INFO, CallJitMethodOp)
622 }
623}
624
625pub(crate) unsafe extern "C" fn generic_getter<
631 D: DomTypes,
632 Policy: CallPolicy,
633 const EXCEPTION_TO_REJECTION: bool,
634>(
635 cx: *mut RawJSContext,
636 argc: libc::c_uint,
637 vp: *mut JSVal,
638) -> bool {
639 unsafe {
640 let mut cx = JSContext::from_ptr(NonNull::new(cx).unwrap());
642 let cx = &mut cx;
643
644 generic_call::<D, EXCEPTION_TO_REJECTION>(cx, argc, vp, Policy::INFO, CallJitGetterOp)
645 }
646}
647
648unsafe fn call_setter(
649 info: *const JSJitInfo,
650 cx: &mut JSContext,
651 handle: HandleObject,
652 this: *mut libc::c_void,
653 argc: u32,
654 vp: *mut JSVal,
655) -> bool {
656 unsafe {
657 if !CallJitSetterOp(info, cx, handle, this, argc, vp) {
658 return false;
659 }
660 *vp = UndefinedValue();
661 }
662 true
663}
664
665pub(crate) unsafe extern "C" fn generic_setter<D: DomTypes, Policy: CallPolicy>(
671 cx: *mut RawJSContext,
672 argc: libc::c_uint,
673 vp: *mut JSVal,
674) -> bool {
675 unsafe {
676 let mut cx = JSContext::from_ptr(NonNull::new(cx).unwrap());
678 let cx = &mut cx;
679
680 generic_call::<D, false>(cx, argc, vp, Policy::INFO, call_setter)
681 }
682}
683
684pub(crate) unsafe extern "C" fn generic_static_promise_method(
690 cx: *mut RawJSContext,
691 argc: libc::c_uint,
692 vp: *mut JSVal,
693) -> bool {
694 unsafe {
695 let mut cx = JSContext::from_ptr(NonNull::new(cx).unwrap());
697 let cx = &mut cx;
698
699 let args = CallArgs::from_vp(vp, argc);
700
701 let info = RUST_FUNCTION_VALUE_TO_JITINFO(JS_CALLEE(cx.raw_cx(), vp));
702 assert!(!info.is_null());
703 let static_fn = (*info).__bindgen_anon_1.staticMethod.unwrap();
706 if static_fn(cx.raw_cx(), argc, vp) {
707 return true;
708 }
709 exception_to_promise(cx, args.rval())
710 }
711}
712
713pub(crate) fn exception_to_promise(cx: &mut JSContext, rval: RawMutableHandleValue) -> bool {
717 unsafe {
718 rooted!(&in(cx) let mut exception = UndefinedValue());
719 if !JS_GetPendingException(cx, exception.handle_mut()) {
720 return false;
721 }
722 JS_ClearPendingException(cx);
723 if let Some(promise) = NonNull::new(CallOriginalPromiseReject(cx, exception.handle())) {
724 promise.to_jsval(cx, MutableHandleValue::from_raw(rval));
725 true
726 } else {
727 JS_SetPendingException(cx, exception.handle(), ExceptionStackBehavior::Capture);
729 false
730 }
731 }
732}
733
734pub(crate) unsafe fn trace_global(tracer: *mut JSTracer, obj: *mut JSObject) {
740 unsafe {
741 let array = get_proto_or_iface_array(obj);
742 for proto in (*array).iter() {
743 if !proto.is_null() {
744 trace_object(
745 tracer,
746 "prototype",
747 &*(proto as *const *mut JSObject as *const Heap<*mut JSObject>),
748 );
749 }
750 }
751 }
752}
753
754pub(crate) unsafe extern "C" fn enumerate_global(
757 cx: *mut RawJSContext,
758 obj: RawHandleObject,
759 props: RawMutableHandleIdVector,
760 enumerable_only: bool,
761) -> bool {
762 unsafe {
763 assert!(JS_IsGlobalObject(obj.get()));
764 JS_NewEnumerateStandardClasses(cx, obj, props, enumerable_only)
765 }
766}
767
768pub(crate) unsafe extern "C" fn enumerate_window<D: DomTypes>(
771 cx: *mut RawJSContext,
772 obj: RawHandleObject,
773 props: RawMutableHandleIdVector,
774 enumerable_only: bool,
775) -> bool {
776 unsafe {
777 let mut cx = JSContext::from_ptr(NonNull::new(cx).unwrap());
778 if !enumerate_global(cx.raw_cx(), obj, props, enumerable_only) {
779 return false;
780 }
781
782 if enumerable_only {
783 return true;
786 }
787
788 let obj = Handle::from_raw(obj);
789 for (name, interface) in <D as DomHelpers<D>>::interface_map() {
790 if !(interface.enabled)(&mut cx, obj) {
791 continue;
792 }
793 let s = JS_AtomizeStringN(&cx, name.as_ptr() as *const c_char, name.len());
794 rooted!(&in(cx) let id = StringId(s));
795 if s.is_null() || !AppendToIdVector(props, id.handle()) {
796 return false;
797 }
798 }
799 }
800 true
801}
802
803pub(crate) unsafe extern "C" fn may_resolve_global(
807 names: *const JSAtomState,
808 id: PropertyKey,
809 maybe_obj: *mut JSObject,
810) -> bool {
811 unsafe { JS_MayResolveStandardClass(names, id, maybe_obj) }
812}
813
814pub(crate) unsafe extern "C" fn may_resolve_window<D: DomTypes>(
818 names: *const JSAtomState,
819 id: PropertyKey,
820 maybe_obj: *mut JSObject,
821) -> bool {
822 if unsafe { may_resolve_global(names, id, maybe_obj) } {
823 return true;
824 }
825
826 let cx = Runtime::get()
827 .expect("There must be a JSContext active")
828 .as_ptr();
829 let Ok(bytes) = (unsafe { latin1_bytes_from_id(cx, id) }) else {
830 return false;
831 };
832
833 <D as DomHelpers<D>>::interface_map().contains_key(bytes)
834}
835
836pub(crate) unsafe extern "C" fn resolve_global(
838 cx: *mut RawJSContext,
839 obj: RawHandleObject,
840 id: RawHandleId,
841 rval: *mut bool,
842) -> bool {
843 unsafe {
844 assert!(JS_IsGlobalObject(obj.get()));
845 JS_ResolveStandardClass(cx, obj, id, rval)
846 }
847}
848
849pub(crate) unsafe extern "C" fn resolve_window<D: DomTypes>(
851 cx: *mut RawJSContext,
852 obj: RawHandleObject,
853 id: RawHandleId,
854 rval: *mut bool,
855) -> bool {
856 unsafe {
857 let mut cx = JSContext::from_ptr(NonNull::new(cx).unwrap());
858 if !resolve_global(cx.raw_cx(), obj, id, rval) {
859 return false;
860 }
861
862 if *rval {
863 return true;
864 }
865 let Ok(bytes) = latin1_bytes_from_id(cx.raw_cx(), *id) else {
866 *rval = false;
867 return true;
868 };
869
870 if let Some(interface) = <D as DomHelpers<D>>::interface_map().get(bytes) {
871 (interface.define)(&mut cx, Handle::from_raw(obj));
872 *rval = true;
873 } else {
874 *rval = false;
875 }
876 }
877 true
878}
879
880unsafe fn latin1_bytes_from_id(cx: *mut RawJSContext, id: jsid) -> Result<&'static [u8], ()> {
885 if !id.is_string() {
886 return Err(());
887 }
888
889 let string = id.to_string();
890 if !unsafe { JS_DeprecatedStringHasLatin1Chars(string) } {
891 return Err(());
892 }
893 let mut length = 0;
894 let ptr = unsafe { JS_GetLatin1StringCharsAndLength(cx, ptr::null(), string, &mut length) };
895 assert!(!ptr.is_null());
896 Ok(unsafe { slice::from_raw_parts(ptr, length) })
897}
898
899pub fn to_frozen_array<T: ToJSValConvertible>(
901 cx: &mut JSContext,
902 convertibles: &[T],
903 mut rval: MutableHandleValue,
904) {
905 convertibles.to_jsval(cx, rval.reborrow());
906
907 rooted!(&in(cx) let obj = rval.to_object());
908 unsafe { JS_FreezeObject(cx, obj.handle()) };
909}