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_HasOwnProperty, JS_HasProperty, JS_HasPropertyById, JS_SetProperty,
31};
32use js::rust::{
33 HandleId, HandleObject, HandleValue, MutableHandleValue, Runtime, get_object_class,
34};
35use js::{JS_CALLEE, rooted};
36use malloc_size_of::MallocSizeOfOps;
37
38use crate::DomTypes;
39use crate::codegen::Globals::Globals;
40use crate::codegen::InheritTypes::TopTypeId;
41use crate::codegen::PrototypeList::{self, MAX_PROTO_CHAIN_LENGTH, PROTO_OR_IFACE_LENGTH};
42use crate::conversions::{PrototypeCheck, private_from_proto_check};
43use crate::error::throw_invalid_this;
44use crate::interfaces::DomHelpers;
45use crate::js::{
46 JS_DefineProperty, JS_GetProperty, JS_GetPrototype, JS_IsExceptionPending,
47 JS_SetPendingException, PropertyFlags,
48};
49use crate::proxyhandler::{
50 is_cross_origin_object, is_platform_object_same_origin, report_cross_origin_denial,
51};
52use crate::str::DOMString;
53use crate::trace::trace_object;
54
55#[derive(Clone, Copy)]
57pub struct DOMClass {
58 pub interface_chain: [PrototypeList::ID; MAX_PROTO_CHAIN_LENGTH],
61
62 pub depth: u8,
64
65 pub type_id: TopTypeId,
67
68 pub malloc_size_of: unsafe fn(ops: &mut MallocSizeOfOps, *const c_void) -> usize,
70
71 pub global: Globals,
73}
74unsafe impl Sync for DOMClass {}
75
76#[derive(Copy)]
78#[repr(C)]
79pub struct DOMJSClass {
80 pub base: js::jsapi::JSClass,
82 pub dom_class: DOMClass,
84}
85impl Clone for DOMJSClass {
86 fn clone(&self) -> DOMJSClass {
87 *self
88 }
89}
90unsafe impl Sync for DOMJSClass {}
91
92pub(crate) const DOM_PROTO_UNFORGEABLE_HOLDER_SLOT: u32 = 0;
95
96pub(crate) const DOM_PROTOTYPE_SLOT: u32 = js::JSCLASS_GLOBAL_SLOT_COUNT;
99
100pub(crate) const JSCLASS_DOM_GLOBAL: u32 = js::JSCLASS_USERBIT1;
105
106pub(crate) unsafe fn get_proto_or_iface_array(global: *mut JSObject) -> *mut ProtoOrIfaceArray {
112 unsafe {
113 assert_ne!(((*get_object_class(global)).flags & JSCLASS_DOM_GLOBAL), 0);
114 let mut slot = UndefinedValue();
115 JS_GetReservedSlot(global, DOM_PROTOTYPE_SLOT, &mut slot);
116 slot.to_private() as *mut ProtoOrIfaceArray
117 }
118}
119
120pub type ProtoOrIfaceArray = [*mut JSObject; PROTO_OR_IFACE_LENGTH];
122
123pub(crate) fn get_property_on_prototype(
128 cx: &mut JSContext,
129 proxy: HandleObject,
130 receiver: HandleValue,
131 id: HandleId,
132 found: &mut bool,
133 vp: MutableHandleValue,
134) -> bool {
135 rooted!(&in(cx) let mut proto = ptr::null_mut::<JSObject>());
136 if !JS_GetPrototype(cx, proxy, proto.handle_mut()) || proto.is_null() {
137 *found = false;
138 return true;
139 }
140 let mut has_property = false;
141 if unsafe { !JS_HasPropertyById(cx, proto.handle(), id, &mut has_property) } {
142 return false;
143 }
144 *found = has_property;
145 if !has_property {
146 return true;
147 }
148
149 unsafe { JS_ForwardGetPropertyTo(cx, proto.handle(), id, receiver, vp) }
150}
151
152pub fn get_array_index_from_id(id: HandleId) -> Option<u32> {
155 let raw_id = *id;
156 if raw_id.is_int() {
157 return Some(raw_id.to_int() as u32);
158 }
159
160 if raw_id.is_void() || !raw_id.is_string() {
161 return None;
162 }
163
164 unsafe {
165 let atom = raw_id.to_string() as *mut JSAtom;
166 let s = AtomToLinearString(atom);
167 if GetLinearStringLength(s) == 0 {
168 return None;
169 }
170
171 let chars = [GetLinearStringCharAt(s, 0)];
172 let first_char = char::decode_utf16(chars.iter().cloned())
173 .next()
174 .map_or('\0', |r| r.unwrap_or('\0'));
175 if first_char.is_ascii_lowercase() {
176 return None;
177 }
178
179 let mut i = 0;
180 if StringIsArrayIndex(s, &mut i) {
181 Some(i)
182 } else {
183 None
184 }
185 }
186
187 }
213
214pub(crate) fn find_enum_value<'a, T>(
218 cx: &mut JSContext,
219 v: HandleValue,
220 pairs: &'a [(&'static str, T)],
221) -> Result<(Option<&'a T>, DOMString), ()> {
222 if let Ok(search) = DOMString::from_js_string(cx, v) {
223 let result = pairs
224 .iter()
225 .find(|(key, _)| search == *key)
226 .map(|(_, ev)| ev);
227 Ok((result, search))
228 } else {
229 Err(())
230 }
231}
232
233pub(crate) fn get_dictionary_property(
237 cx: &mut JSContext,
238 object: HandleObject,
239 property: &CStr,
240 rval: MutableHandleValue,
241) -> Result<bool, ()> {
242 if object.get().is_null() {
243 return Ok(false);
244 }
245
246 let mut found = false;
247 if unsafe { !JS_HasProperty(cx, object, property.as_ptr(), &mut found) } {
248 return Err(());
249 }
250
251 if !found {
252 return Ok(false);
253 }
254
255 if !JS_GetProperty(cx, object, property, rval) {
256 return Err(());
257 }
258
259 Ok(true)
260}
261
262#[expect(clippy::result_unit_err)]
266pub fn set_dictionary_property(
267 cx: &mut JSContext,
268 object: HandleObject,
269 property: &CStr,
270 value: HandleValue,
271) -> Result<(), ()> {
272 if object.get().is_null() {
273 return Err(());
274 }
275
276 if unsafe { !JS_SetProperty(cx, object, property.as_ptr(), value) } {
277 return Err(());
278 }
279
280 Ok(())
281}
282
283#[expect(clippy::result_unit_err)]
287pub fn define_dictionary_property(
288 cx: &mut JSContext,
289 object: HandleObject,
290 property: &CStr,
291 value: HandleValue,
292) -> Result<(), ()> {
293 if object.get().is_null() {
294 return Err(());
295 }
296
297 if !JS_DefineProperty(
298 cx,
299 object,
300 property,
301 value,
302 PropertyFlags::ENUMERABLE | PropertyFlags::WRITABLE | PropertyFlags::CONFIGURABLE,
303 ) {
304 return Err(());
305 }
306
307 Ok(())
308}
309
310#[expect(clippy::result_unit_err)]
314pub fn has_own_property(
315 cx: &mut JSContext,
316 object: HandleObject,
317 property: &CStr,
318) -> Result<bool, ()> {
319 if object.get().is_null() {
320 return Ok(false);
321 }
322
323 let mut found = false;
324 if unsafe { !JS_HasOwnProperty(cx, object, property.as_ptr(), &mut found) } {
325 return Err(());
326 }
327
328 Ok(found)
329}
330
331pub fn has_property_on_prototype(
337 cx: &mut JSContext,
338 proxy: HandleObject,
339 id: HandleId,
340 found: &mut bool,
341) -> bool {
342 rooted!(&in(cx) let mut proto = ptr::null_mut::<JSObject>());
343 if !JS_GetPrototype(cx, proxy, proto.handle_mut()) {
344 return false;
345 }
346 assert!(!proto.is_null());
347 unsafe { JS_HasPropertyById(cx, proto.handle(), id, found) }
348}
349
350pub trait CallPolicy {
351 const INFO: CallPolicyInfo;
352}
353pub mod call_policies {
354 use super::*;
355 pub struct Normal;
356 pub struct TargetClassMaybeCrossOrigin;
357 pub struct LenientThis;
358 pub struct LenientThisTargetClassMaybeCrossOrigin;
359 pub struct CrossOriginCallable;
360 impl CallPolicy for Normal {
361 const INFO: CallPolicyInfo = CallPolicyInfo {
362 lenient_this: false,
363 needs_security_check_on_interface_match: false,
364 };
365 }
366 impl CallPolicy for TargetClassMaybeCrossOrigin {
367 const INFO: CallPolicyInfo = CallPolicyInfo {
368 lenient_this: false,
369 needs_security_check_on_interface_match: true,
370 };
371 }
372 impl CallPolicy for LenientThis {
373 const INFO: CallPolicyInfo = CallPolicyInfo {
374 lenient_this: true,
375 needs_security_check_on_interface_match: false,
376 };
377 }
378 impl CallPolicy for LenientThisTargetClassMaybeCrossOrigin {
379 const INFO: CallPolicyInfo = CallPolicyInfo {
380 lenient_this: true,
381 needs_security_check_on_interface_match: true,
382 };
383 }
384 impl CallPolicy for CrossOriginCallable {
385 const INFO: CallPolicyInfo = CallPolicyInfo {
386 lenient_this: false,
387 needs_security_check_on_interface_match: false,
388 };
389 }
390}
391#[derive(Clone, Copy, Eq, PartialEq)]
398pub struct CallPolicyInfo {
399 pub lenient_this: bool,
402 pub needs_security_check_on_interface_match: bool,
421}
422
423unsafe fn generic_call<D: DomTypes, const EXCEPTION_TO_REJECTION: bool>(
424 cx: &mut JSContext,
425 argc: libc::c_uint,
426 vp: *mut JSVal,
427 CallPolicyInfo {
428 lenient_this,
429 needs_security_check_on_interface_match,
430 }: CallPolicyInfo,
431 call: unsafe fn(
432 *const JSJitInfo,
433 &mut JSContext,
434 HandleObject,
435 *mut libc::c_void,
436 u32,
437 *mut JSVal,
438 ) -> bool,
439) -> bool {
440 let args = unsafe { CallArgs::from_vp(vp, argc) };
441
442 let info = unsafe { RUST_FUNCTION_VALUE_TO_JITINFO(JS_CALLEE(cx.raw_cx_no_gc(), vp)) };
443 let proto_id = unsafe { (*info).__bindgen_anon_2.protoID };
444
445 let thisobj = args.thisv();
521 if !thisobj.get().is_null_or_undefined() && !thisobj.get().is_object() {
522 throw_invalid_this(cx, proto_id);
525 return if EXCEPTION_TO_REJECTION {
526 exception_to_promise(cx, args.rval())
527 } else {
528 false
529 };
530 }
531
532 rooted!(&in(cx) let obj = if thisobj.get().is_object() {
533 thisobj.get().to_object()
534 } else {
535 unsafe { GetNonCCWObjectGlobal(JS_CALLEE(cx.raw_cx_no_gc(), vp).to_object_or_null()) }
536 });
537 let depth = unsafe { (*info).__bindgen_anon_3.depth as usize };
538 let proto_check = PrototypeCheck::Depth { depth, proto_id };
539 let this = match unsafe { private_from_proto_check(cx, obj.get(), proto_check) } {
540 Ok(val) => val,
541 Err(()) => {
542 if lenient_this {
554 unsafe {
555 debug_assert!(!JS_IsExceptionPending(cx));
556 *vp = UndefinedValue();
557 }
558 return true;
559 } else {
560 throw_invalid_this(cx, proto_id);
561 return if EXCEPTION_TO_REJECTION {
562 exception_to_promise(cx, args.rval())
563 } else {
564 false
565 };
566 }
567 },
568 };
569
570 if needs_security_check_on_interface_match {
573 let mut realm = js::realm::CurrentRealm::assert(cx);
574 if is_cross_origin_object::<D>(&mut realm, obj.handle()) &&
576 !is_platform_object_same_origin(&realm, obj.handle())
577 {
578 rooted!(&in(*realm) let mut void_jsid: jsid);
583 let result = report_cross_origin_denial::<D>(&mut realm, void_jsid.handle(), "call");
584 return if EXCEPTION_TO_REJECTION {
585 exception_to_promise(cx, args.rval())
586 } else {
587 result
588 };
589 }
590 } else {
591 }
594
595 unsafe { call(info, cx, obj.handle(), this as *mut libc::c_void, argc, vp) }
596}
597
598pub(crate) unsafe extern "C" fn generic_method<
604 D: DomTypes,
605 Policy: CallPolicy,
606 const EXCEPTION_TO_REJECTION: bool,
607>(
608 cx: *mut RawJSContext,
609 argc: libc::c_uint,
610 vp: *mut JSVal,
611) -> bool {
612 unsafe {
613 let mut cx = JSContext::from_ptr(NonNull::new(cx).unwrap());
615 let cx = &mut cx;
616
617 generic_call::<D, EXCEPTION_TO_REJECTION>(cx, argc, vp, Policy::INFO, CallJitMethodOp)
618 }
619}
620
621pub(crate) unsafe extern "C" fn generic_getter<
627 D: DomTypes,
628 Policy: CallPolicy,
629 const EXCEPTION_TO_REJECTION: bool,
630>(
631 cx: *mut RawJSContext,
632 argc: libc::c_uint,
633 vp: *mut JSVal,
634) -> bool {
635 unsafe {
636 let mut cx = JSContext::from_ptr(NonNull::new(cx).unwrap());
638 let cx = &mut cx;
639
640 generic_call::<D, EXCEPTION_TO_REJECTION>(cx, argc, vp, Policy::INFO, CallJitGetterOp)
641 }
642}
643
644unsafe fn call_setter(
645 info: *const JSJitInfo,
646 cx: &mut JSContext,
647 handle: HandleObject,
648 this: *mut libc::c_void,
649 argc: u32,
650 vp: *mut JSVal,
651) -> bool {
652 unsafe {
653 if !CallJitSetterOp(info, cx, handle, this, argc, vp) {
654 return false;
655 }
656 *vp = UndefinedValue();
657 }
658 true
659}
660
661pub(crate) unsafe extern "C" fn generic_setter<D: DomTypes, Policy: CallPolicy>(
667 cx: *mut RawJSContext,
668 argc: libc::c_uint,
669 vp: *mut JSVal,
670) -> bool {
671 unsafe {
672 let mut cx = JSContext::from_ptr(NonNull::new(cx).unwrap());
674 let cx = &mut cx;
675
676 generic_call::<D, false>(cx, argc, vp, Policy::INFO, call_setter)
677 }
678}
679
680pub(crate) unsafe extern "C" fn generic_static_promise_method(
686 cx: *mut RawJSContext,
687 argc: libc::c_uint,
688 vp: *mut JSVal,
689) -> bool {
690 unsafe {
691 let mut cx = JSContext::from_ptr(NonNull::new(cx).unwrap());
693 let cx = &mut cx;
694
695 let args = CallArgs::from_vp(vp, argc);
696
697 let info = RUST_FUNCTION_VALUE_TO_JITINFO(JS_CALLEE(cx.raw_cx(), vp));
698 assert!(!info.is_null());
699 let static_fn = (*info).__bindgen_anon_1.staticMethod.unwrap();
702 if static_fn(cx.raw_cx(), argc, vp) {
703 return true;
704 }
705 exception_to_promise(cx, args.rval())
706 }
707}
708
709pub(crate) fn exception_to_promise(cx: &mut JSContext, rval: RawMutableHandleValue) -> bool {
713 unsafe {
714 rooted!(&in(cx) let mut exception = UndefinedValue());
715 if !JS_GetPendingException(cx, exception.handle_mut()) {
716 return false;
717 }
718 JS_ClearPendingException(cx);
719 if let Some(promise) = NonNull::new(CallOriginalPromiseReject(cx, exception.handle())) {
720 promise.to_jsval(cx, MutableHandleValue::from_raw(rval));
721 true
722 } else {
723 JS_SetPendingException(cx, exception.handle(), ExceptionStackBehavior::Capture);
725 false
726 }
727 }
728}
729
730pub(crate) unsafe fn trace_global(tracer: *mut JSTracer, obj: *mut JSObject) {
736 unsafe {
737 let array = get_proto_or_iface_array(obj);
738 for proto in (*array).iter() {
739 if !proto.is_null() {
740 trace_object(
741 tracer,
742 "prototype",
743 &*(proto as *const *mut JSObject as *const Heap<*mut JSObject>),
744 );
745 }
746 }
747 }
748}
749
750pub(crate) unsafe extern "C" fn enumerate_global(
753 cx: *mut RawJSContext,
754 obj: RawHandleObject,
755 props: RawMutableHandleIdVector,
756 enumerable_only: bool,
757) -> bool {
758 unsafe {
759 assert!(JS_IsGlobalObject(obj.get()));
760 JS_NewEnumerateStandardClasses(cx, obj, props, enumerable_only)
761 }
762}
763
764pub(crate) unsafe extern "C" fn enumerate_window<D: DomTypes>(
767 cx: *mut RawJSContext,
768 obj: RawHandleObject,
769 props: RawMutableHandleIdVector,
770 enumerable_only: bool,
771) -> bool {
772 unsafe {
773 let mut cx = JSContext::from_ptr(NonNull::new(cx).unwrap());
774 if !enumerate_global(cx.raw_cx(), obj, props, enumerable_only) {
775 return false;
776 }
777
778 if enumerable_only {
779 return true;
782 }
783
784 let obj = Handle::from_raw(obj);
785 for (name, interface) in <D as DomHelpers<D>>::interface_map() {
786 if !(interface.enabled)(&mut cx, obj) {
787 continue;
788 }
789 let s = JS_AtomizeStringN(&cx, name.as_ptr() as *const c_char, name.len());
790 rooted!(&in(cx) let id = StringId(s));
791 if s.is_null() || !AppendToIdVector(props, id.handle()) {
792 return false;
793 }
794 }
795 }
796 true
797}
798
799pub(crate) unsafe extern "C" fn may_resolve_global(
803 names: *const JSAtomState,
804 id: PropertyKey,
805 maybe_obj: *mut JSObject,
806) -> bool {
807 unsafe { JS_MayResolveStandardClass(names, id, maybe_obj) }
808}
809
810pub(crate) unsafe extern "C" fn may_resolve_window<D: DomTypes>(
814 names: *const JSAtomState,
815 id: PropertyKey,
816 maybe_obj: *mut JSObject,
817) -> bool {
818 if unsafe { may_resolve_global(names, id, maybe_obj) } {
819 return true;
820 }
821
822 let cx = Runtime::get()
823 .expect("There must be a JSContext active")
824 .as_ptr();
825 let Ok(bytes) = (unsafe { latin1_bytes_from_id(cx, id) }) else {
826 return false;
827 };
828
829 <D as DomHelpers<D>>::interface_map().contains_key(bytes)
830}
831
832pub(crate) unsafe extern "C" fn resolve_global(
834 cx: *mut RawJSContext,
835 obj: RawHandleObject,
836 id: RawHandleId,
837 rval: *mut bool,
838) -> bool {
839 unsafe {
840 assert!(JS_IsGlobalObject(obj.get()));
841 JS_ResolveStandardClass(cx, obj, id, rval)
842 }
843}
844
845pub(crate) unsafe extern "C" fn resolve_window<D: DomTypes>(
847 cx: *mut RawJSContext,
848 obj: RawHandleObject,
849 id: RawHandleId,
850 rval: *mut bool,
851) -> bool {
852 unsafe {
853 let mut cx = JSContext::from_ptr(NonNull::new(cx).unwrap());
854 if !resolve_global(cx.raw_cx(), obj, id, rval) {
855 return false;
856 }
857
858 if *rval {
859 return true;
860 }
861 let Ok(bytes) = latin1_bytes_from_id(cx.raw_cx(), *id) else {
862 *rval = false;
863 return true;
864 };
865
866 if let Some(interface) = <D as DomHelpers<D>>::interface_map().get(bytes) {
867 (interface.define)(&mut cx, Handle::from_raw(obj));
868 *rval = true;
869 } else {
870 *rval = false;
871 }
872 }
873 true
874}
875
876unsafe fn latin1_bytes_from_id(cx: *mut RawJSContext, id: jsid) -> Result<&'static [u8], ()> {
881 if !id.is_string() {
882 return Err(());
883 }
884
885 let string = id.to_string();
886 if !unsafe { JS_DeprecatedStringHasLatin1Chars(string) } {
887 return Err(());
888 }
889 let mut length = 0;
890 let ptr = unsafe { JS_GetLatin1StringCharsAndLength(cx, ptr::null(), string, &mut length) };
891 assert!(!ptr.is_null());
892 Ok(unsafe { slice::from_raw_parts(ptr, length) })
893}
894
895pub fn to_frozen_array<T: ToJSValConvertible>(
897 cx: &mut JSContext,
898 convertibles: &[T],
899 mut rval: MutableHandleValue,
900) {
901 convertibles.to_jsval(cx, rval.reborrow());
902
903 rooted!(&in(cx) let obj = rval.to_object());
904 unsafe { JS_FreezeObject(cx, obj.handle()) };
905}