1use std::ffi::CStr;
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: &CStr,
249 rval: MutableHandleValue,
250 _can_gc: CanGc,
251) -> Result<bool, ()> {
252 unsafe fn has_property(
253 cx: *mut JSContext,
254 object: HandleObject,
255 property: &CStr,
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: &CStr,
264 value: MutableHandleValue,
265 ) -> bool {
266 JS_GetProperty(cx, object, property.as_ptr(), value)
267 }
268
269 if object.get().is_null() {
270 return Ok(false);
271 }
272
273 let mut found = false;
274 if !has_property(cx, object, property, &mut found) {
275 return Err(());
276 }
277
278 if !found {
279 return Ok(false);
280 }
281
282 if !get_property(cx, object, property, rval) {
283 return Err(());
284 }
285
286 Ok(true)
287}
288
289#[allow(clippy::result_unit_err)]
293pub fn set_dictionary_property(
294 cx: SafeJSContext,
295 object: HandleObject,
296 property: &CStr,
297 value: HandleValue,
298) -> Result<(), ()> {
299 if object.get().is_null() {
300 return Err(());
301 }
302
303 unsafe {
304 if !JS_SetProperty(*cx, object, property.as_ptr(), value) {
305 return Err(());
306 }
307 }
308
309 Ok(())
310}
311
312pub unsafe fn has_property_on_prototype(
321 cx: *mut JSContext,
322 proxy: HandleObject,
323 id: HandleId,
324 found: &mut bool,
325) -> bool {
326 rooted!(in(cx) let mut proto = ptr::null_mut::<JSObject>());
327 if !JS_GetPrototype(cx, proxy, proto.handle_mut()) {
328 return false;
329 }
330 assert!(!proto.is_null());
331 JS_HasPropertyById(cx, proto.handle(), id, found)
332}
333
334pub(crate) unsafe fn delete_property_by_id(
339 cx: *mut JSContext,
340 object: HandleObject,
341 id: HandleId,
342 bp: *mut ObjectOpResult,
343) -> bool {
344 JS_DeletePropertyById(cx, object, id, bp)
345}
346
347unsafe fn generic_call<const EXCEPTION_TO_REJECTION: bool>(
348 cx: *mut JSContext,
349 argc: libc::c_uint,
350 vp: *mut JSVal,
351 is_lenient: bool,
352 call: unsafe extern "C" fn(
353 *const JSJitInfo,
354 *mut JSContext,
355 RawHandleObject,
356 *mut libc::c_void,
357 u32,
358 *mut JSVal,
359 ) -> bool,
360 can_gc: CanGc,
361) -> bool {
362 let args = CallArgs::from_vp(vp, argc);
363
364 let info = RUST_FUNCTION_VALUE_TO_JITINFO(JS_CALLEE(cx, vp));
365 let proto_id = (*info).__bindgen_anon_2.protoID;
366 let cx = SafeJSContext::from_ptr(cx);
367
368 let thisobj = args.thisv();
369 if !thisobj.get().is_null_or_undefined() && !thisobj.get().is_object() {
370 throw_invalid_this(cx, proto_id);
371 return if EXCEPTION_TO_REJECTION {
372 exception_to_promise(*cx, args.rval(), can_gc)
373 } else {
374 false
375 };
376 }
377
378 rooted!(in(*cx) let obj = if thisobj.get().is_object() {
379 thisobj.get().to_object()
380 } else {
381 GetNonCCWObjectGlobal(JS_CALLEE(*cx, vp).to_object_or_null())
382 });
383 let depth = (*info).__bindgen_anon_3.depth as usize;
384 let proto_check = PrototypeCheck::Depth { depth, proto_id };
385 let this = match private_from_proto_check(obj.get(), *cx, proto_check) {
386 Ok(val) => val,
387 Err(()) => {
388 if is_lenient {
389 debug_assert!(!JS_IsExceptionPending(*cx));
390 *vp = UndefinedValue();
391 return true;
392 } else {
393 throw_invalid_this(cx, proto_id);
394 return if EXCEPTION_TO_REJECTION {
395 exception_to_promise(*cx, args.rval(), can_gc)
396 } else {
397 false
398 };
399 }
400 },
401 };
402 call(
403 info,
404 *cx,
405 obj.handle().into(),
406 this as *mut libc::c_void,
407 argc,
408 vp,
409 )
410}
411
412pub(crate) unsafe extern "C" fn generic_method<const EXCEPTION_TO_REJECTION: bool>(
418 cx: *mut JSContext,
419 argc: libc::c_uint,
420 vp: *mut JSVal,
421) -> bool {
422 generic_call::<EXCEPTION_TO_REJECTION>(cx, argc, vp, false, CallJitMethodOp, CanGc::note())
423}
424
425pub(crate) unsafe extern "C" fn generic_getter<const EXCEPTION_TO_REJECTION: bool>(
431 cx: *mut JSContext,
432 argc: libc::c_uint,
433 vp: *mut JSVal,
434) -> bool {
435 generic_call::<EXCEPTION_TO_REJECTION>(cx, argc, vp, false, CallJitGetterOp, CanGc::note())
436}
437
438pub(crate) unsafe extern "C" fn generic_lenient_getter<const EXCEPTION_TO_REJECTION: bool>(
444 cx: *mut JSContext,
445 argc: libc::c_uint,
446 vp: *mut JSVal,
447) -> bool {
448 generic_call::<EXCEPTION_TO_REJECTION>(cx, argc, vp, true, CallJitGetterOp, CanGc::note())
449}
450
451unsafe extern "C" fn call_setter(
452 info: *const JSJitInfo,
453 cx: *mut JSContext,
454 handle: RawHandleObject,
455 this: *mut libc::c_void,
456 argc: u32,
457 vp: *mut JSVal,
458) -> bool {
459 if !CallJitSetterOp(info, cx, handle, this, argc, vp) {
460 return false;
461 }
462 *vp = UndefinedValue();
463 true
464}
465
466pub(crate) unsafe extern "C" fn generic_setter(
472 cx: *mut JSContext,
473 argc: libc::c_uint,
474 vp: *mut JSVal,
475) -> bool {
476 generic_call::<false>(cx, argc, vp, false, call_setter, CanGc::note())
477}
478
479pub(crate) unsafe extern "C" fn generic_lenient_setter(
485 cx: *mut JSContext,
486 argc: libc::c_uint,
487 vp: *mut JSVal,
488) -> bool {
489 generic_call::<false>(cx, argc, vp, true, call_setter, CanGc::note())
490}
491
492pub(crate) unsafe extern "C" fn generic_static_promise_method(
498 cx: *mut JSContext,
499 argc: libc::c_uint,
500 vp: *mut JSVal,
501) -> bool {
502 let args = CallArgs::from_vp(vp, argc);
503
504 let info = RUST_FUNCTION_VALUE_TO_JITINFO(JS_CALLEE(cx, vp));
505 assert!(!info.is_null());
506 let static_fn = (*info).__bindgen_anon_1.staticMethod.unwrap();
509 if static_fn(cx, argc, vp) {
510 return true;
511 }
512 exception_to_promise(cx, args.rval(), CanGc::note())
513}
514
515pub(crate) unsafe fn exception_to_promise(
522 cx: *mut JSContext,
523 rval: RawMutableHandleValue,
524 _can_gc: CanGc,
525) -> bool {
526 rooted!(in(cx) let mut exception = UndefinedValue());
527 if !JS_GetPendingException(cx, exception.handle_mut()) {
528 return false;
529 }
530 JS_ClearPendingException(cx);
531 if let Some(promise) = NonNull::new(CallOriginalPromiseReject(cx, exception.handle())) {
532 promise.to_jsval(cx, MutableHandleValue::from_raw(rval));
533 true
534 } else {
535 JS_SetPendingException(cx, exception.handle(), ExceptionStackBehavior::Capture);
537 false
538 }
539}
540
541pub(crate) unsafe fn trace_global(tracer: *mut JSTracer, obj: *mut JSObject) {
547 let array = get_proto_or_iface_array(obj);
548 for proto in (*array).iter() {
549 if !proto.is_null() {
550 trace_object(
551 tracer,
552 "prototype",
553 &*(proto as *const *mut JSObject as *const Heap<*mut JSObject>),
554 );
555 }
556 }
557}
558
559pub(crate) unsafe extern "C" fn enumerate_global(
562 cx: *mut JSContext,
563 obj: RawHandleObject,
564 props: RawMutableHandleIdVector,
565 enumerable_only: bool,
566) -> bool {
567 assert!(JS_IsGlobalObject(obj.get()));
568 JS_NewEnumerateStandardClasses(cx, obj, props, enumerable_only)
569}
570
571pub(crate) unsafe extern "C" fn enumerate_window<D: DomTypes>(
574 cx: *mut JSContext,
575 obj: RawHandleObject,
576 props: RawMutableHandleIdVector,
577 enumerable_only: bool,
578) -> bool {
579 let mut cx = js::context::JSContext::from_ptr(NonNull::new(cx).unwrap());
580 if !enumerate_global(cx.raw_cx(), obj, props, enumerable_only) {
581 return false;
582 }
583
584 if enumerable_only {
585 return true;
588 }
589
590 let obj = Handle::from_raw(obj);
591 for (name, interface) in <D as DomHelpers<D>>::interface_map() {
592 if !(interface.enabled)(&mut cx, obj) {
593 continue;
594 }
595 let s = JS_AtomizeStringN(cx.raw_cx(), name.as_ptr() as *const c_char, name.len());
596 rooted!(&in(cx) let id = StringId(s));
597 if s.is_null() || !AppendToIdVector(props, id.handle().into()) {
598 return false;
599 }
600 }
601 true
602}
603
604pub(crate) unsafe extern "C" fn may_resolve_global(
608 names: *const JSAtomState,
609 id: PropertyKey,
610 maybe_obj: *mut JSObject,
611) -> bool {
612 JS_MayResolveStandardClass(names, id, maybe_obj)
613}
614
615pub(crate) unsafe extern "C" fn may_resolve_window<D: DomTypes>(
619 names: *const JSAtomState,
620 id: PropertyKey,
621 maybe_obj: *mut JSObject,
622) -> bool {
623 if may_resolve_global(names, id, maybe_obj) {
624 return true;
625 }
626
627 let cx = Runtime::get()
628 .expect("There must be a JSContext active")
629 .as_ptr();
630 let Ok(bytes) = latin1_bytes_from_id(cx, id) else {
631 return false;
632 };
633
634 <D as DomHelpers<D>>::interface_map().contains_key(bytes)
635}
636
637pub(crate) unsafe extern "C" fn resolve_global(
639 cx: *mut JSContext,
640 obj: RawHandleObject,
641 id: RawHandleId,
642 rval: *mut bool,
643) -> bool {
644 assert!(JS_IsGlobalObject(obj.get()));
645 JS_ResolveStandardClass(cx, obj, id, rval)
646}
647
648pub(crate) unsafe extern "C" fn resolve_window<D: DomTypes>(
650 cx: *mut JSContext,
651 obj: RawHandleObject,
652 id: RawHandleId,
653 rval: *mut bool,
654) -> bool {
655 let mut cx = js::context::JSContext::from_ptr(NonNull::new(cx).unwrap());
656 if !resolve_global(cx.raw_cx(), obj, id, rval) {
657 return false;
658 }
659
660 if *rval {
661 return true;
662 }
663 let Ok(bytes) = latin1_bytes_from_id(cx.raw_cx(), *id) else {
664 *rval = false;
665 return true;
666 };
667
668 if let Some(interface) = <D as DomHelpers<D>>::interface_map().get(bytes) {
669 (interface.define)(&mut cx, Handle::from_raw(obj));
670 *rval = true;
671 } else {
672 *rval = false;
673 }
674 true
675}
676
677unsafe fn latin1_bytes_from_id(cx: *mut JSContext, id: jsid) -> Result<&'static [u8], ()> {
682 if !id.is_string() {
683 return Err(());
684 }
685
686 let string = id.to_string();
687 if !JS_DeprecatedStringHasLatin1Chars(string) {
688 return Err(());
689 }
690 let mut length = 0;
691 let ptr = JS_GetLatin1StringCharsAndLength(cx, ptr::null(), string, &mut length);
692 assert!(!ptr.is_null());
693 Ok(slice::from_raw_parts(ptr, length))
694}