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;
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, 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_ForwardGetPropertyTo, JS_FreezeObject,
30 JS_GetPendingException, JS_GetProperty, JS_GetPrototype, JS_HasOwnProperty, JS_HasProperty,
31 JS_HasPropertyById, JS_IsExceptionPending, JS_SetPendingException, JS_SetProperty,
32};
33use js::rust::{
34 HandleId, HandleObject, HandleValue, MutableHandleValue, Runtime, get_object_class,
35};
36use js::{JS_CALLEE, rooted};
37use malloc_size_of::MallocSizeOfOps;
38
39use crate::DomTypes;
40use crate::codegen::Globals::Globals;
41use crate::codegen::InheritTypes::TopTypeId;
42use crate::codegen::PrototypeList::{self, MAX_PROTO_CHAIN_LENGTH, PROTO_OR_IFACE_LENGTH};
43use crate::conversions::{PrototypeCheck, private_from_proto_check};
44use crate::error::throw_invalid_this;
45use crate::interfaces::DomHelpers;
46use crate::js::{JS_DefineProperty, PropertyFlags};
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 if let Ok(search) = DOMString::from_js_string(cx, v) {
221 let result = pairs
222 .iter()
223 .find(|(key, _)| search == *key)
224 .map(|(_, ev)| ev);
225 Ok((result, search))
226 } else {
227 Err(())
228 }
229}
230
231pub(crate) fn get_dictionary_property(
235 cx: &mut JSContext,
236 object: HandleObject,
237 property: &CStr,
238 rval: MutableHandleValue,
239) -> Result<bool, ()> {
240 if object.get().is_null() {
241 return Ok(false);
242 }
243
244 let mut found = false;
245 if unsafe { !JS_HasProperty(cx, object, property.as_ptr(), &mut found) } {
246 return Err(());
247 }
248
249 if !found {
250 return Ok(false);
251 }
252
253 if unsafe { !JS_GetProperty(cx, object, property.as_ptr(), rval) } {
254 return Err(());
255 }
256
257 Ok(true)
258}
259
260#[expect(clippy::result_unit_err)]
264pub fn set_dictionary_property(
265 cx: &mut JSContext,
266 object: HandleObject,
267 property: &CStr,
268 value: HandleValue,
269) -> Result<(), ()> {
270 if object.get().is_null() {
271 return Err(());
272 }
273
274 if unsafe { !JS_SetProperty(cx, object, property.as_ptr(), value) } {
275 return Err(());
276 }
277
278 Ok(())
279}
280
281#[expect(clippy::result_unit_err)]
285pub fn define_dictionary_property(
286 cx: &mut JSContext,
287 object: HandleObject,
288 property: &CStr,
289 value: HandleValue,
290) -> Result<(), ()> {
291 if object.get().is_null() {
292 return Err(());
293 }
294
295 if !JS_DefineProperty(
296 cx,
297 object,
298 property,
299 value,
300 PropertyFlags::ENUMERABLE | PropertyFlags::WRITABLE | PropertyFlags::CONFIGURABLE,
301 ) {
302 return Err(());
303 }
304
305 Ok(())
306}
307
308#[expect(clippy::result_unit_err)]
312pub fn has_own_property(
313 cx: &mut JSContext,
314 object: HandleObject,
315 property: &CStr,
316) -> Result<bool, ()> {
317 if object.get().is_null() {
318 return Ok(false);
319 }
320
321 let mut found = false;
322 if unsafe { !JS_HasOwnProperty(cx, object, property.as_ptr(), &mut found) } {
323 return Err(());
324 }
325
326 Ok(found)
327}
328
329pub fn has_property_on_prototype(
335 cx: &mut JSContext,
336 proxy: HandleObject,
337 id: HandleId,
338 found: &mut bool,
339) -> bool {
340 rooted!(&in(cx) let mut proto = ptr::null_mut::<JSObject>());
341 if unsafe { !JS_GetPrototype(cx, proxy, proto.handle_mut()) } {
342 return false;
343 }
344 assert!(!proto.is_null());
345 unsafe { JS_HasPropertyById(cx, proto.handle(), id, found) }
346}
347
348pub trait CallPolicy {
349 const INFO: CallPolicyInfo;
350}
351pub mod call_policies {
352 use super::*;
353 pub struct Normal;
354 pub struct TargetClassMaybeCrossOrigin;
355 pub struct LenientThis;
356 pub struct LenientThisTargetClassMaybeCrossOrigin;
357 pub struct CrossOriginCallable;
358 impl CallPolicy for Normal {
359 const INFO: CallPolicyInfo = CallPolicyInfo {
360 lenient_this: false,
361 needs_security_check_on_interface_match: false,
362 };
363 }
364 impl CallPolicy for TargetClassMaybeCrossOrigin {
365 const INFO: CallPolicyInfo = CallPolicyInfo {
366 lenient_this: false,
367 needs_security_check_on_interface_match: true,
368 };
369 }
370 impl CallPolicy for LenientThis {
371 const INFO: CallPolicyInfo = CallPolicyInfo {
372 lenient_this: true,
373 needs_security_check_on_interface_match: false,
374 };
375 }
376 impl CallPolicy for LenientThisTargetClassMaybeCrossOrigin {
377 const INFO: CallPolicyInfo = CallPolicyInfo {
378 lenient_this: true,
379 needs_security_check_on_interface_match: true,
380 };
381 }
382 impl CallPolicy for CrossOriginCallable {
383 const INFO: CallPolicyInfo = CallPolicyInfo {
384 lenient_this: false,
385 needs_security_check_on_interface_match: false,
386 };
387 }
388}
389#[derive(Clone, Copy, Eq, PartialEq)]
396pub struct CallPolicyInfo {
397 pub lenient_this: bool,
400 pub needs_security_check_on_interface_match: bool,
419}
420
421unsafe fn generic_call<D: DomTypes, const EXCEPTION_TO_REJECTION: bool>(
422 cx: &mut JSContext,
423 argc: libc::c_uint,
424 vp: *mut JSVal,
425 CallPolicyInfo {
426 lenient_this,
427 needs_security_check_on_interface_match,
428 }: CallPolicyInfo,
429 call: unsafe fn(
430 *const JSJitInfo,
431 &mut JSContext,
432 HandleObject,
433 *mut libc::c_void,
434 u32,
435 *mut JSVal,
436 ) -> bool,
437) -> bool {
438 let args = unsafe { CallArgs::from_vp(vp, argc) };
439
440 let info = unsafe { RUST_FUNCTION_VALUE_TO_JITINFO(JS_CALLEE(cx.raw_cx_no_gc(), vp)) };
441 let proto_id = unsafe { (*info).__bindgen_anon_2.protoID };
442
443 let thisobj = args.thisv();
519 if !thisobj.get().is_null_or_undefined() && !thisobj.get().is_object() {
520 throw_invalid_this(cx, proto_id);
523 return if EXCEPTION_TO_REJECTION {
524 exception_to_promise(cx, args.rval())
525 } else {
526 false
527 };
528 }
529
530 rooted!(&in(cx) let obj = if thisobj.get().is_object() {
531 thisobj.get().to_object()
532 } else {
533 unsafe { GetNonCCWObjectGlobal(JS_CALLEE(cx.raw_cx_no_gc(), vp).to_object_or_null()) }
534 });
535 let depth = unsafe { (*info).__bindgen_anon_3.depth as usize };
536 let proto_check = PrototypeCheck::Depth { depth, proto_id };
537 let this = match unsafe { private_from_proto_check(cx, obj.get(), proto_check) } {
538 Ok(val) => val,
539 Err(()) => {
540 if lenient_this {
552 unsafe {
553 debug_assert!(!JS_IsExceptionPending(cx));
554 *vp = UndefinedValue();
555 }
556 return true;
557 } else {
558 throw_invalid_this(cx, proto_id);
559 return if EXCEPTION_TO_REJECTION {
560 exception_to_promise(cx, args.rval())
561 } else {
562 false
563 };
564 }
565 },
566 };
567
568 if needs_security_check_on_interface_match {
571 let mut realm = js::realm::CurrentRealm::assert(cx);
572 if is_cross_origin_object::<D>(&mut realm, obj.handle()) &&
574 !is_platform_object_same_origin(&realm, obj.handle())
575 {
576 rooted!(&in(*realm) let mut void_jsid: jsid);
581 let result = report_cross_origin_denial::<D>(&mut realm, void_jsid.handle(), "call");
582 return if EXCEPTION_TO_REJECTION {
583 exception_to_promise(cx, args.rval())
584 } else {
585 result
586 };
587 }
588 } else {
589 }
592
593 unsafe { call(info, cx, obj.handle(), this as *mut libc::c_void, argc, vp) }
594}
595
596pub(crate) unsafe extern "C" fn generic_method<
602 D: DomTypes,
603 Policy: CallPolicy,
604 const EXCEPTION_TO_REJECTION: bool,
605>(
606 cx: *mut RawJSContext,
607 argc: libc::c_uint,
608 vp: *mut JSVal,
609) -> bool {
610 unsafe {
611 let mut cx = JSContext::from_ptr(NonNull::new(cx).unwrap());
613 let cx = &mut cx;
614
615 generic_call::<D, EXCEPTION_TO_REJECTION>(cx, argc, vp, Policy::INFO, CallJitMethodOp)
616 }
617}
618
619pub(crate) unsafe extern "C" fn generic_getter<
625 D: DomTypes,
626 Policy: CallPolicy,
627 const EXCEPTION_TO_REJECTION: bool,
628>(
629 cx: *mut RawJSContext,
630 argc: libc::c_uint,
631 vp: *mut JSVal,
632) -> bool {
633 unsafe {
634 let mut cx = JSContext::from_ptr(NonNull::new(cx).unwrap());
636 let cx = &mut cx;
637
638 generic_call::<D, EXCEPTION_TO_REJECTION>(cx, argc, vp, Policy::INFO, CallJitGetterOp)
639 }
640}
641
642unsafe fn call_setter(
643 info: *const JSJitInfo,
644 cx: &mut JSContext,
645 handle: HandleObject,
646 this: *mut libc::c_void,
647 argc: u32,
648 vp: *mut JSVal,
649) -> bool {
650 unsafe {
651 if !CallJitSetterOp(info, cx, handle, this, argc, vp) {
652 return false;
653 }
654 *vp = UndefinedValue();
655 }
656 true
657}
658
659pub(crate) unsafe extern "C" fn generic_setter<D: DomTypes, Policy: CallPolicy>(
665 cx: *mut RawJSContext,
666 argc: libc::c_uint,
667 vp: *mut JSVal,
668) -> bool {
669 unsafe {
670 let mut cx = JSContext::from_ptr(NonNull::new(cx).unwrap());
672 let cx = &mut cx;
673
674 generic_call::<D, false>(cx, argc, vp, Policy::INFO, call_setter)
675 }
676}
677
678pub(crate) unsafe extern "C" fn generic_static_promise_method(
684 cx: *mut RawJSContext,
685 argc: libc::c_uint,
686 vp: *mut JSVal,
687) -> bool {
688 unsafe {
689 let mut cx = JSContext::from_ptr(NonNull::new(cx).unwrap());
691 let cx = &mut cx;
692
693 let args = CallArgs::from_vp(vp, argc);
694
695 let info = RUST_FUNCTION_VALUE_TO_JITINFO(JS_CALLEE(cx.raw_cx(), vp));
696 assert!(!info.is_null());
697 let static_fn = (*info).__bindgen_anon_1.staticMethod.unwrap();
700 if static_fn(cx.raw_cx(), argc, vp) {
701 return true;
702 }
703 exception_to_promise(cx, args.rval())
704 }
705}
706
707pub(crate) fn exception_to_promise(cx: &mut JSContext, rval: RawMutableHandleValue) -> bool {
711 unsafe {
712 rooted!(&in(cx) let mut exception = UndefinedValue());
713 if !JS_GetPendingException(cx, exception.handle_mut()) {
714 return false;
715 }
716 JS_ClearPendingException(cx);
717 if let Some(promise) = NonNull::new(CallOriginalPromiseReject(cx, exception.handle())) {
718 promise.to_jsval(cx, MutableHandleValue::from_raw(rval));
719 true
720 } else {
721 JS_SetPendingException(cx, exception.handle(), ExceptionStackBehavior::Capture);
723 false
724 }
725 }
726}
727
728pub(crate) unsafe fn trace_global(tracer: *mut JSTracer, obj: *mut JSObject) {
734 unsafe {
735 let array = get_proto_or_iface_array(obj);
736 for proto in (*array).iter() {
737 if !proto.is_null() {
738 trace_object(
739 tracer,
740 "prototype",
741 &*(proto as *const *mut JSObject as *const Heap<*mut JSObject>),
742 );
743 }
744 }
745 }
746}
747
748pub(crate) unsafe extern "C" fn enumerate_global(
751 cx: *mut RawJSContext,
752 obj: RawHandleObject,
753 props: RawMutableHandleIdVector,
754 enumerable_only: bool,
755) -> bool {
756 unsafe {
757 assert!(JS_IsGlobalObject(obj.get()));
758 JS_NewEnumerateStandardClasses(cx, obj, props, enumerable_only)
759 }
760}
761
762pub(crate) unsafe extern "C" fn enumerate_window<D: DomTypes>(
765 cx: *mut RawJSContext,
766 obj: RawHandleObject,
767 props: RawMutableHandleIdVector,
768 enumerable_only: bool,
769) -> bool {
770 unsafe {
771 let mut cx = JSContext::from_ptr(NonNull::new(cx).unwrap());
772 if !enumerate_global(cx.raw_cx(), obj, props, enumerable_only) {
773 return false;
774 }
775
776 if enumerable_only {
777 return true;
780 }
781
782 let obj = Handle::from_raw(obj);
783 for (name, interface) in <D as DomHelpers<D>>::interface_map() {
784 if !(interface.enabled)(&mut cx, obj) {
785 continue;
786 }
787 let s = JS_AtomizeStringN(&cx, name.as_ptr() as *const c_char, name.len());
788 rooted!(&in(cx) let id = StringId(s));
789 if s.is_null() || !AppendToIdVector(props, id.handle()) {
790 return false;
791 }
792 }
793 }
794 true
795}
796
797pub(crate) unsafe extern "C" fn may_resolve_global(
801 names: *const JSAtomState,
802 id: PropertyKey,
803 maybe_obj: *mut JSObject,
804) -> bool {
805 unsafe { JS_MayResolveStandardClass(names, id, maybe_obj) }
806}
807
808pub(crate) unsafe extern "C" fn may_resolve_window<D: DomTypes>(
812 names: *const JSAtomState,
813 id: PropertyKey,
814 maybe_obj: *mut JSObject,
815) -> bool {
816 if unsafe { may_resolve_global(names, id, maybe_obj) } {
817 return true;
818 }
819
820 let cx = Runtime::get()
821 .expect("There must be a JSContext active")
822 .as_ptr();
823 let Ok(bytes) = (unsafe { latin1_bytes_from_id(cx, id) }) else {
824 return false;
825 };
826
827 <D as DomHelpers<D>>::interface_map().contains_key(bytes)
828}
829
830pub(crate) unsafe extern "C" fn resolve_global(
832 cx: *mut RawJSContext,
833 obj: RawHandleObject,
834 id: RawHandleId,
835 rval: *mut bool,
836) -> bool {
837 unsafe {
838 assert!(JS_IsGlobalObject(obj.get()));
839 JS_ResolveStandardClass(cx, obj, id, rval)
840 }
841}
842
843pub(crate) unsafe extern "C" fn resolve_window<D: DomTypes>(
845 cx: *mut RawJSContext,
846 obj: RawHandleObject,
847 id: RawHandleId,
848 rval: *mut bool,
849) -> bool {
850 unsafe {
851 let mut cx = JSContext::from_ptr(NonNull::new(cx).unwrap());
852 if !resolve_global(cx.raw_cx(), obj, id, rval) {
853 return false;
854 }
855
856 if *rval {
857 return true;
858 }
859 let Ok(bytes) = latin1_bytes_from_id(cx.raw_cx(), *id) else {
860 *rval = false;
861 return true;
862 };
863
864 if let Some(interface) = <D as DomHelpers<D>>::interface_map().get(bytes) {
865 (interface.define)(&mut cx, Handle::from_raw(obj));
866 *rval = true;
867 } else {
868 *rval = false;
869 }
870 }
871 true
872}
873
874unsafe fn latin1_bytes_from_id(cx: *mut RawJSContext, id: jsid) -> Result<&'static [u8], ()> {
879 if !id.is_string() {
880 return Err(());
881 }
882
883 let string = id.to_string();
884 if !unsafe { JS_DeprecatedStringHasLatin1Chars(string) } {
885 return Err(());
886 }
887 let mut length = 0;
888 let ptr = unsafe { JS_GetLatin1StringCharsAndLength(cx, ptr::null(), string, &mut length) };
889 assert!(!ptr.is_null());
890 Ok(unsafe { slice::from_raw_parts(ptr, length) })
891}
892
893pub fn to_frozen_array<T: ToJSValConvertible>(
895 cx: &mut JSContext,
896 convertibles: &[T],
897 mut rval: MutableHandleValue,
898) {
899 convertibles.to_jsval(cx, rval.reborrow());
900
901 rooted!(&in(cx) let obj = rval.to_object());
902 unsafe { JS_FreezeObject(cx, obj.handle()) };
903}