1use std::ffi::CString;
6use std::os::raw::{c_char, c_void};
7use std::ptr::{self, NonNull};
8use std::slice;
9
10use js::conversions::{ToJSValConvertible, jsstr_to_string};
11use js::gc::Handle;
12use js::glue::{
13 AppendToIdVector, CallJitGetterOp, CallJitMethodOp, CallJitSetterOp, JS_GetReservedSlot,
14 RUST_FUNCTION_VALUE_TO_JITINFO,
15};
16use js::jsapi::{
17 AtomToLinearString, CallArgs, ExceptionStackBehavior, GetLinearStringCharAt,
18 GetLinearStringLength, GetNonCCWObjectGlobal, HandleId as RawHandleId,
19 HandleObject as RawHandleObject, Heap, JS_AtomizeStringN, JS_ClearPendingException,
20 JS_DeprecatedStringHasLatin1Chars, JS_GetLatin1StringCharsAndLength, JS_IsExceptionPending,
21 JS_IsGlobalObject, JS_MayResolveStandardClass, JS_NewEnumerateStandardClasses,
22 JS_ResolveStandardClass, JSAtom, JSAtomState, JSContext, JSJitInfo, JSObject, JSTracer,
23 MutableHandleIdVector as RawMutableHandleIdVector, MutableHandleValue as RawMutableHandleValue,
24 ObjectOpResult, PropertyKey, StringIsArrayIndex, jsid,
25};
26use js::jsid::StringId;
27use js::jsval::{JSVal, UndefinedValue};
28use js::rust::wrappers::{
29 CallOriginalPromiseReject, JS_DeletePropertyById, JS_ForwardGetPropertyTo,
30 JS_GetPendingException, JS_GetProperty, JS_GetPrototype, JS_HasProperty, JS_HasPropertyById,
31 JS_SetPendingException, JS_SetProperty,
32};
33use js::rust::{
34 HandleId, HandleObject, HandleValue, MutableHandleValue, Runtime, ToString, 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::script_runtime::{CanGc, JSContext as SafeJSContext};
47use crate::str::DOMString;
48use crate::trace::trace_object;
49
50#[derive(Clone, Copy)]
52pub struct DOMClass {
53 pub interface_chain: [PrototypeList::ID; MAX_PROTO_CHAIN_LENGTH],
56
57 pub depth: u8,
59
60 pub type_id: TopTypeId,
62
63 pub malloc_size_of: unsafe fn(ops: &mut MallocSizeOfOps, *const c_void) -> usize,
65
66 pub global: Globals,
68}
69unsafe impl Sync for DOMClass {}
70
71#[derive(Copy)]
73#[repr(C)]
74pub struct DOMJSClass {
75 pub base: js::jsapi::JSClass,
77 pub dom_class: DOMClass,
79}
80impl Clone for DOMJSClass {
81 fn clone(&self) -> DOMJSClass {
82 *self
83 }
84}
85unsafe impl Sync for DOMJSClass {}
86
87pub(crate) const DOM_PROTO_UNFORGEABLE_HOLDER_SLOT: u32 = 0;
90
91pub(crate) const DOM_PROTOTYPE_SLOT: u32 = js::JSCLASS_GLOBAL_SLOT_COUNT;
94
95pub(crate) const JSCLASS_DOM_GLOBAL: u32 = js::JSCLASS_USERBIT1;
100
101pub(crate) unsafe fn get_proto_or_iface_array(global: *mut JSObject) -> *mut ProtoOrIfaceArray {
107 assert_ne!(((*get_object_class(global)).flags & JSCLASS_DOM_GLOBAL), 0);
108 let mut slot = UndefinedValue();
109 JS_GetReservedSlot(global, DOM_PROTOTYPE_SLOT, &mut slot);
110 slot.to_private() as *mut ProtoOrIfaceArray
111}
112
113pub type ProtoOrIfaceArray = [*mut JSObject; PROTO_OR_IFACE_LENGTH];
115
116pub(crate) unsafe fn get_property_on_prototype(
125 cx: *mut JSContext,
126 proxy: HandleObject,
127 receiver: HandleValue,
128 id: HandleId,
129 found: *mut bool,
130 vp: MutableHandleValue,
131) -> bool {
132 rooted!(in(cx) let mut proto = ptr::null_mut::<JSObject>());
133 if !JS_GetPrototype(cx, proxy, proto.handle_mut()) || proto.is_null() {
134 *found = false;
135 return true;
136 }
137 let mut has_property = false;
138 if !JS_HasPropertyById(cx, proto.handle(), id, &mut has_property) {
139 return false;
140 }
141 *found = has_property;
142 if !has_property {
143 return true;
144 }
145
146 JS_ForwardGetPropertyTo(cx, proto.handle(), id, receiver, vp)
147}
148
149pub fn get_array_index_from_id(id: HandleId) -> Option<u32> {
152 let raw_id = *id;
153 if raw_id.is_int() {
154 return Some(raw_id.to_int() as u32);
155 }
156
157 if raw_id.is_void() || !raw_id.is_string() {
158 return None;
159 }
160
161 unsafe {
162 let atom = raw_id.to_string() as *mut JSAtom;
163 let s = AtomToLinearString(atom);
164 if GetLinearStringLength(s) == 0 {
165 return None;
166 }
167
168 let chars = [GetLinearStringCharAt(s, 0)];
169 let first_char = char::decode_utf16(chars.iter().cloned())
170 .next()
171 .map_or('\0', |r| r.unwrap_or('\0'));
172 if first_char.is_ascii_lowercase() {
173 return None;
174 }
175
176 let mut i = 0;
177 if StringIsArrayIndex(s, &mut i) {
178 Some(i)
179 } else {
180 None
181 }
182 }
183
184 }
210
211#[allow(clippy::result_unit_err)]
218pub(crate) unsafe fn find_enum_value<'a, T>(
219 cx: *mut JSContext,
220 v: HandleValue,
221 pairs: &'a [(&'static str, T)],
222) -> Result<(Option<&'a T>, DOMString), ()> {
223 match ptr::NonNull::new(ToString(cx, v)) {
224 Some(jsstr) => {
225 let search = DOMString::from_string(jsstr_to_string(cx, jsstr));
226 Ok((
227 pairs
228 .iter()
229 .find(|&&(key, _)| search == *key)
230 .map(|(_, ev)| ev),
231 search,
232 ))
233 },
234 None => Err(()),
235 }
236}
237
238#[allow(clippy::result_unit_err)]
245pub unsafe fn get_dictionary_property(
246 cx: *mut JSContext,
247 object: HandleObject,
248 property: &str,
249 rval: MutableHandleValue,
250 _can_gc: CanGc,
251) -> Result<bool, ()> {
252 unsafe fn has_property(
253 cx: *mut JSContext,
254 object: HandleObject,
255 property: &CString,
256 found: &mut bool,
257 ) -> bool {
258 JS_HasProperty(cx, object, property.as_ptr(), found)
259 }
260 unsafe fn get_property(
261 cx: *mut JSContext,
262 object: HandleObject,
263 property: &CString,
264 value: MutableHandleValue,
265 ) -> bool {
266 JS_GetProperty(cx, object, property.as_ptr(), value)
267 }
268
269 let property = CString::new(property).unwrap();
270 if object.get().is_null() {
271 return Ok(false);
272 }
273
274 let mut found = false;
275 if !has_property(cx, object, &property, &mut found) {
276 return Err(());
277 }
278
279 if !found {
280 return Ok(false);
281 }
282
283 if !get_property(cx, object, &property, rval) {
284 return Err(());
285 }
286
287 Ok(true)
288}
289
290#[allow(clippy::result_unit_err)]
294pub fn set_dictionary_property(
295 cx: SafeJSContext,
296 object: HandleObject,
297 property: &str,
298 value: HandleValue,
299) -> Result<(), ()> {
300 if object.get().is_null() {
301 return Err(());
302 }
303
304 let property = CString::new(property).unwrap();
305 unsafe {
306 if !JS_SetProperty(*cx, object, property.as_ptr(), value) {
307 return Err(());
308 }
309 }
310
311 Ok(())
312}
313
314pub unsafe fn has_property_on_prototype(
323 cx: *mut JSContext,
324 proxy: HandleObject,
325 id: HandleId,
326 found: &mut bool,
327) -> bool {
328 rooted!(in(cx) let mut proto = ptr::null_mut::<JSObject>());
329 if !JS_GetPrototype(cx, proxy, proto.handle_mut()) {
330 return false;
331 }
332 assert!(!proto.is_null());
333 JS_HasPropertyById(cx, proto.handle(), id, found)
334}
335
336pub(crate) unsafe fn delete_property_by_id(
341 cx: *mut JSContext,
342 object: HandleObject,
343 id: HandleId,
344 bp: *mut ObjectOpResult,
345) -> bool {
346 JS_DeletePropertyById(cx, object, id, bp)
347}
348
349unsafe fn generic_call<const EXCEPTION_TO_REJECTION: bool>(
350 cx: *mut JSContext,
351 argc: libc::c_uint,
352 vp: *mut JSVal,
353 is_lenient: bool,
354 call: unsafe extern "C" fn(
355 *const JSJitInfo,
356 *mut JSContext,
357 RawHandleObject,
358 *mut libc::c_void,
359 u32,
360 *mut JSVal,
361 ) -> bool,
362 can_gc: CanGc,
363) -> bool {
364 let args = CallArgs::from_vp(vp, argc);
365
366 let info = RUST_FUNCTION_VALUE_TO_JITINFO(JS_CALLEE(cx, vp));
367 let proto_id = (*info).__bindgen_anon_2.protoID;
368 let cx = SafeJSContext::from_ptr(cx);
369
370 let thisobj = args.thisv();
371 if !thisobj.get().is_null_or_undefined() && !thisobj.get().is_object() {
372 throw_invalid_this(cx, proto_id);
373 return if EXCEPTION_TO_REJECTION {
374 exception_to_promise(*cx, args.rval(), can_gc)
375 } else {
376 false
377 };
378 }
379
380 rooted!(in(*cx) let obj = if thisobj.get().is_object() {
381 thisobj.get().to_object()
382 } else {
383 GetNonCCWObjectGlobal(JS_CALLEE(*cx, vp).to_object_or_null())
384 });
385 let depth = (*info).__bindgen_anon_3.depth as usize;
386 let proto_check = PrototypeCheck::Depth { depth, proto_id };
387 let this = match private_from_proto_check(obj.get(), *cx, proto_check) {
388 Ok(val) => val,
389 Err(()) => {
390 if is_lenient {
391 debug_assert!(!JS_IsExceptionPending(*cx));
392 *vp = UndefinedValue();
393 return true;
394 } else {
395 throw_invalid_this(cx, proto_id);
396 return if EXCEPTION_TO_REJECTION {
397 exception_to_promise(*cx, args.rval(), can_gc)
398 } else {
399 false
400 };
401 }
402 },
403 };
404 call(
405 info,
406 *cx,
407 obj.handle().into(),
408 this as *mut libc::c_void,
409 argc,
410 vp,
411 )
412}
413
414pub(crate) unsafe extern "C" fn generic_method<const EXCEPTION_TO_REJECTION: bool>(
420 cx: *mut JSContext,
421 argc: libc::c_uint,
422 vp: *mut JSVal,
423) -> bool {
424 generic_call::<EXCEPTION_TO_REJECTION>(cx, argc, vp, false, CallJitMethodOp, CanGc::note())
425}
426
427pub(crate) unsafe extern "C" fn generic_getter<const EXCEPTION_TO_REJECTION: bool>(
433 cx: *mut JSContext,
434 argc: libc::c_uint,
435 vp: *mut JSVal,
436) -> bool {
437 generic_call::<EXCEPTION_TO_REJECTION>(cx, argc, vp, false, CallJitGetterOp, CanGc::note())
438}
439
440pub(crate) unsafe extern "C" fn generic_lenient_getter<const EXCEPTION_TO_REJECTION: bool>(
446 cx: *mut JSContext,
447 argc: libc::c_uint,
448 vp: *mut JSVal,
449) -> bool {
450 generic_call::<EXCEPTION_TO_REJECTION>(cx, argc, vp, true, CallJitGetterOp, CanGc::note())
451}
452
453unsafe extern "C" fn call_setter(
454 info: *const JSJitInfo,
455 cx: *mut JSContext,
456 handle: RawHandleObject,
457 this: *mut libc::c_void,
458 argc: u32,
459 vp: *mut JSVal,
460) -> bool {
461 if !CallJitSetterOp(info, cx, handle, this, argc, vp) {
462 return false;
463 }
464 *vp = UndefinedValue();
465 true
466}
467
468pub(crate) unsafe extern "C" fn generic_setter(
474 cx: *mut JSContext,
475 argc: libc::c_uint,
476 vp: *mut JSVal,
477) -> bool {
478 generic_call::<false>(cx, argc, vp, false, call_setter, CanGc::note())
479}
480
481pub(crate) unsafe extern "C" fn generic_lenient_setter(
487 cx: *mut JSContext,
488 argc: libc::c_uint,
489 vp: *mut JSVal,
490) -> bool {
491 generic_call::<false>(cx, argc, vp, true, call_setter, CanGc::note())
492}
493
494pub(crate) unsafe extern "C" fn generic_static_promise_method(
500 cx: *mut JSContext,
501 argc: libc::c_uint,
502 vp: *mut JSVal,
503) -> bool {
504 let args = CallArgs::from_vp(vp, argc);
505
506 let info = RUST_FUNCTION_VALUE_TO_JITINFO(JS_CALLEE(cx, vp));
507 assert!(!info.is_null());
508 let static_fn = (*info).__bindgen_anon_1.staticMethod.unwrap();
511 if static_fn(cx, argc, vp) {
512 return true;
513 }
514 exception_to_promise(cx, args.rval(), CanGc::note())
515}
516
517pub(crate) unsafe fn exception_to_promise(
524 cx: *mut JSContext,
525 rval: RawMutableHandleValue,
526 _can_gc: CanGc,
527) -> bool {
528 rooted!(in(cx) let mut exception = UndefinedValue());
529 if !JS_GetPendingException(cx, exception.handle_mut()) {
530 return false;
531 }
532 JS_ClearPendingException(cx);
533 if let Some(promise) = NonNull::new(CallOriginalPromiseReject(cx, exception.handle())) {
534 promise.to_jsval(cx, MutableHandleValue::from_raw(rval));
535 true
536 } else {
537 JS_SetPendingException(cx, exception.handle(), ExceptionStackBehavior::Capture);
539 false
540 }
541}
542
543pub(crate) unsafe fn trace_global(tracer: *mut JSTracer, obj: *mut JSObject) {
549 let array = get_proto_or_iface_array(obj);
550 for proto in (*array).iter() {
551 if !proto.is_null() {
552 trace_object(
553 tracer,
554 "prototype",
555 &*(proto as *const *mut JSObject as *const Heap<*mut JSObject>),
556 );
557 }
558 }
559}
560
561pub trait AsVoidPtr {
563 fn as_void_ptr(&self) -> *const libc::c_void;
564}
565impl<T> AsVoidPtr for T {
566 fn as_void_ptr(&self) -> *const libc::c_void {
567 self as *const T as *const libc::c_void
568 }
569}
570
571pub(crate) trait AsCCharPtrPtr {
573 fn as_c_char_ptr(&self) -> *const c_char;
574}
575
576impl AsCCharPtrPtr for [u8] {
577 fn as_c_char_ptr(&self) -> *const c_char {
578 self as *const [u8] as *const c_char
579 }
580}
581
582pub(crate) unsafe extern "C" fn enumerate_global(
585 cx: *mut JSContext,
586 obj: RawHandleObject,
587 props: RawMutableHandleIdVector,
588 enumerable_only: bool,
589) -> bool {
590 assert!(JS_IsGlobalObject(obj.get()));
591 JS_NewEnumerateStandardClasses(cx, obj, props, enumerable_only)
592}
593
594pub(crate) unsafe extern "C" fn enumerate_window<D: DomTypes>(
597 cx: *mut JSContext,
598 obj: RawHandleObject,
599 props: RawMutableHandleIdVector,
600 enumerable_only: bool,
601) -> bool {
602 if !enumerate_global(cx, obj, props, enumerable_only) {
603 return false;
604 }
605
606 if enumerable_only {
607 return true;
610 }
611
612 let cx = SafeJSContext::from_ptr(cx);
613 let obj = Handle::from_raw(obj);
614 for (name, interface) in <D as DomHelpers<D>>::interface_map() {
615 if !(interface.enabled)(cx, obj) {
616 continue;
617 }
618 let s = JS_AtomizeStringN(*cx, name.as_c_char_ptr(), name.len());
619 rooted!(in(*cx) let id = StringId(s));
620 if s.is_null() || !AppendToIdVector(props, id.handle().into()) {
621 return false;
622 }
623 }
624 true
625}
626
627pub(crate) unsafe extern "C" fn may_resolve_global(
631 names: *const JSAtomState,
632 id: PropertyKey,
633 maybe_obj: *mut JSObject,
634) -> bool {
635 JS_MayResolveStandardClass(names, id, maybe_obj)
636}
637
638pub(crate) unsafe extern "C" fn may_resolve_window<D: DomTypes>(
642 names: *const JSAtomState,
643 id: PropertyKey,
644 maybe_obj: *mut JSObject,
645) -> bool {
646 if may_resolve_global(names, id, maybe_obj) {
647 return true;
648 }
649
650 let cx = Runtime::get()
651 .expect("There must be a JSContext active")
652 .as_ptr();
653 let Ok(bytes) = latin1_bytes_from_id(cx, id) else {
654 return false;
655 };
656
657 <D as DomHelpers<D>>::interface_map().contains_key(bytes)
658}
659
660pub(crate) unsafe extern "C" fn resolve_global(
662 cx: *mut JSContext,
663 obj: RawHandleObject,
664 id: RawHandleId,
665 rval: *mut bool,
666) -> bool {
667 assert!(JS_IsGlobalObject(obj.get()));
668 JS_ResolveStandardClass(cx, obj, id, rval)
669}
670
671pub(crate) unsafe extern "C" fn resolve_window<D: DomTypes>(
673 cx: *mut JSContext,
674 obj: RawHandleObject,
675 id: RawHandleId,
676 rval: *mut bool,
677) -> bool {
678 if !resolve_global(cx, obj, id, rval) {
679 return false;
680 }
681
682 if *rval {
683 return true;
684 }
685 let Ok(bytes) = latin1_bytes_from_id(cx, *id) else {
686 *rval = false;
687 return true;
688 };
689
690 if let Some(interface) = <D as DomHelpers<D>>::interface_map().get(bytes) {
691 (interface.define)(SafeJSContext::from_ptr(cx), Handle::from_raw(obj));
692 *rval = true;
693 } else {
694 *rval = false;
695 }
696 true
697}
698
699unsafe fn latin1_bytes_from_id(cx: *mut JSContext, id: jsid) -> Result<&'static [u8], ()> {
704 if !id.is_string() {
705 return Err(());
706 }
707
708 let string = id.to_string();
709 if !JS_DeprecatedStringHasLatin1Chars(string) {
710 return Err(());
711 }
712 let mut length = 0;
713 let ptr = JS_GetLatin1StringCharsAndLength(cx, ptr::null(), string, &mut length);
714 assert!(!ptr.is_null());
715 Ok(slice::from_raw_parts(ptr, length))
716}