diff --git a/CLAUDE.md b/CLAUDE.md index c3db849c..3bdc29ff 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,7 +1,7 @@ # v82jsc — agent playbook (test hill-climb) `v82jsc` is a **v8 C-ABI compatibility layer** backed by pluggable JS engines. -The crate is literally named `v8` (version `149.4.0`) so it drops into Deno via +The crate is literally named `v8` (version `158.0.0`) so it drops into Deno via `[patch.crates-io]`. Backends (exactly one active at a time, feature-gated): | backend id | features | engine | OS | diff --git a/Cargo.lock b/Cargo.lock index 7d2c16bf..73217127 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -659,7 +659,7 @@ checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" [[package]] name = "v8x" -version = "149.4.0-rc.4" +version = "158.0.0-rc.1" dependencies = [ "align-data", "bindgen", diff --git a/Cargo.toml b/Cargo.toml index 3333d64a..53a167c6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ # can run unmodified. Downstream crates should depend on this package under an # explicit alias when both rusty_v8 and v8x are available. name = "v8x" -version = "149.4.0-rc.4" +version = "158.0.0-rc.1" edition = "2024" authors = ["Divy Srivastava "] description = "Engine agnostic JavaScript" diff --git a/README.md b/README.md index b7e82e42..2118f363 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ Docs: https://littledivy.github.io/v8x · Test dashboard: https://littledivy.git Supported engines: -- V8 14.9.207.2-rusty +- V8 15.2.124.1-rusty - JavaScriptCore / WebKit 625.1+ and System-framework path uses the OS's JSC. - QuickJS-ng 0.15.1 @@ -31,7 +31,7 @@ on the chosen engine, so the swap is a drop-in — `deno_core` compiles unchange | engine | deno size | engine size | | --- | --- | --- | -| Deno V8 14.9 | 78.7 MB | ~40 MB static | +| Deno V8 15.2 | 78.7 MB | ~40 MB static | | Deno JSC | 80.7 MB | ~48 MB static | | Deno system JSC | 54.2 MB | 0 | | Deno quickjs-ng | 56.1 MB | ~1 MB static | diff --git a/build.rs b/build.rs index 5f9c8f95..a21e8619 100644 --- a/build.rs +++ b/build.rs @@ -85,7 +85,7 @@ fn main() { // bindings for this target. The C ABI symbols are *defined* by our own // engine shim (linked below); only the declarations come from here. // - // The files in gen/ are unmodified upstream rusty_v8 v149.4.0 release + // The files in gen/ are unmodified upstream rusty_v8 v158.0.0 release // assets. Their content varies only by OS family — the per-arch and // debug/release/simdutf variants upstream publishes are byte-identical // within one OS (verified; see gen/README.md) — so one file per OS family diff --git a/gen/README.md b/gen/README.md index f54fcee2..1b0b15ae 100644 --- a/gen/README.md +++ b/gen/README.md @@ -1,14 +1,15 @@ # gen/ — pre-generated rusty_v8 bindings -Unmodified upstream release assets from -https://github.com/denoland/rusty_v8/releases/tag/v149.4.0 (the bindgen output +Unmodified upstream bindgen output for rusty_v8 v158.0.0 (V8 15.8), taken +from the CI artifacts of https://github.com/denoland/rusty_v8/pull/2098 until +the v158.0.0 release is tagged (the bindgen output rusty_v8's `binding.rs` includes via `RUSTY_V8_SRC_BINDING_PATH`; build.rs picks one per target). The C ABI symbols these declare are *defined* by our engine shims — only the declarations come from here. One file per OS family is enough: upstream publishes per-arch, debug/release, and simdutf variants, but within one OS family they are all -byte-identical (verified by diffing the v149.4.0 assets). What actually varies +byte-identical (verified by diffing the v158.0.0 assets). What actually varies across OS families: - mangled C++ `link_name`s: Itanium with a leading underscore on Apple, diff --git a/gen/src_binding_debug_aarch64-apple-darwin.rs b/gen/src_binding_debug_aarch64-apple-darwin.rs index 69769d73..2a57f045 100644 --- a/gen/src_binding_debug_aarch64-apple-darwin.rs +++ b/gen/src_binding_debug_aarch64-apple-darwin.rs @@ -792,7 +792,13 @@ pub enum v8_Isolate_UseCounterFeature { kOBSOLETE_WasmResizableBuffers = 183, kInvalidatedArrayBufferMutableProtector = 184, kHoleyArrayReadthrough = 185, - kUseCounterFeatureCount = 186, + kWasmGCAllocation = 186, + kModuleNamespaceMissingDefaultWithStarExport = 187, + kRegExpMatcherFlagsMismatch = 188, + kRegExpCustomSpecies = 189, + kWasmWideArithmetic = 190, + kBigInt = 191, + kUseCounterFeatureCount = 192, } #[repr(u32)] #[doc = " Interceptor callbacks use this value to indicate whether the request was\n intercepted or not.\n\n The values for constants and type are chosen this way for better\n performance."] @@ -862,6 +868,9 @@ pub const v8__TracedReference_SIZE: usize = 8; pub const v8__Eternal_SIZE: usize = 8; pub const v8__String__ValueView_SIZE: usize = 32; pub const v8__String__kMaxLength: ::std::os::raw::c_int = 536870888; +pub const v8__String__WriteFlags__kNullTerminate: ::std::os::raw::c_int = 1; +pub const v8__String__WriteFlags__kReplaceInvalidUtf8: ::std::os::raw::c_int = + 2; pub const v8__TypedArray__kMaxByteLength: usize = 9007199254740991; pub const v8__TYPED_ARRAY_MAX_SIZE_IN_HEAP: usize = 0; pub const v8__Uint8Array__kMaxLength: usize = 9007199254740991; @@ -894,11 +903,11 @@ pub use self::v8_GCCallbackFlags as v8__GCCallbackFlags; pub use self::v8_GCType as v8__GCType; #[doc = " Interceptor callbacks use this value to indicate whether the request was\n intercepted or not.\n\n The values for constants and type are chosen this way for better\n performance."] pub use self::v8_Intercepted as v8__Intercepted; -pub const v8__MAJOR_VERSION: u32 = 14; -pub const v8__MINOR_VERSION: u32 = 9; -pub const v8__BUILD_NUMBER: u32 = 207; -pub const v8__PATCH_LEVEL: u32 = 2; -pub const v8__VERSION_STRING: &::std::ffi::CStr = c"14.9.207.2-rusty"; +pub const v8__MAJOR_VERSION: u32 = 15; +pub const v8__MINOR_VERSION: u32 = 8; +pub const v8__BUILD_NUMBER: u32 = 62; +pub const v8__PATCH_LEVEL: u32 = 23; +pub const v8__VERSION_STRING: &::std::ffi::CStr = c"15.8.62.23-rusty"; #[repr(C)] #[derive(Debug)] pub struct ExternalConstOneByteStringResource { diff --git a/gen/src_binding_debug_x86_64-unknown-linux-gnu.rs b/gen/src_binding_debug_x86_64-unknown-linux-gnu.rs index 9234b330..b6de51a4 100644 --- a/gen/src_binding_debug_x86_64-unknown-linux-gnu.rs +++ b/gen/src_binding_debug_x86_64-unknown-linux-gnu.rs @@ -792,7 +792,13 @@ pub enum v8_Isolate_UseCounterFeature { kOBSOLETE_WasmResizableBuffers = 183, kInvalidatedArrayBufferMutableProtector = 184, kHoleyArrayReadthrough = 185, - kUseCounterFeatureCount = 186, + kWasmGCAllocation = 186, + kModuleNamespaceMissingDefaultWithStarExport = 187, + kRegExpMatcherFlagsMismatch = 188, + kRegExpCustomSpecies = 189, + kWasmWideArithmetic = 190, + kBigInt = 191, + kUseCounterFeatureCount = 192, } #[repr(u32)] #[doc = " Interceptor callbacks use this value to indicate whether the request was\n intercepted or not.\n\n The values for constants and type are chosen this way for better\n performance."] @@ -862,6 +868,9 @@ pub const v8__TracedReference_SIZE: usize = 8; pub const v8__Eternal_SIZE: usize = 8; pub const v8__String__ValueView_SIZE: usize = 32; pub const v8__String__kMaxLength: ::std::os::raw::c_int = 536870888; +pub const v8__String__WriteFlags__kNullTerminate: ::std::os::raw::c_int = 1; +pub const v8__String__WriteFlags__kReplaceInvalidUtf8: ::std::os::raw::c_int = + 2; pub const v8__TypedArray__kMaxByteLength: usize = 9007199254740991; pub const v8__TYPED_ARRAY_MAX_SIZE_IN_HEAP: usize = 0; pub const v8__Uint8Array__kMaxLength: usize = 9007199254740991; @@ -894,11 +903,11 @@ pub use self::v8_GCCallbackFlags as v8__GCCallbackFlags; pub use self::v8_GCType as v8__GCType; #[doc = " Interceptor callbacks use this value to indicate whether the request was\n intercepted or not.\n\n The values for constants and type are chosen this way for better\n performance."] pub use self::v8_Intercepted as v8__Intercepted; -pub const v8__MAJOR_VERSION: u32 = 14; -pub const v8__MINOR_VERSION: u32 = 9; -pub const v8__BUILD_NUMBER: u32 = 207; -pub const v8__PATCH_LEVEL: u32 = 2; -pub const v8__VERSION_STRING: &::std::ffi::CStr = c"14.9.207.2-rusty"; +pub const v8__MAJOR_VERSION: u32 = 15; +pub const v8__MINOR_VERSION: u32 = 8; +pub const v8__BUILD_NUMBER: u32 = 62; +pub const v8__PATCH_LEVEL: u32 = 23; +pub const v8__VERSION_STRING: &::std::ffi::CStr = c"15.8.62.23-rusty"; #[repr(C)] #[derive(Debug)] pub struct ExternalConstOneByteStringResource { diff --git a/gen/src_binding_release_x86_64-pc-windows-msvc.rs b/gen/src_binding_release_x86_64-pc-windows-msvc.rs index 5d0abe7a..bde95918 100644 --- a/gen/src_binding_release_x86_64-pc-windows-msvc.rs +++ b/gen/src_binding_release_x86_64-pc-windows-msvc.rs @@ -10,18 +10,6 @@ pub type cppgc_GarbageCollected_IsGarbageCollectedTypeMarker = ::std::os::raw::c_void; pub type cppgc_GarbageCollected_ParentMostGarbageCollectedType = T; #[repr(C)] -#[derive(Debug, Copy, Clone)] -pub struct cppgc_Visitor_Key { - pub _address: u8, -} -#[allow(clippy::unnecessary_operation, clippy::identity_op)] -const _: () = { - ["Size of cppgc_Visitor_Key"] - [::std::mem::size_of::() - 1usize]; - ["Alignment of cppgc_Visitor_Key"] - [::std::mem::align_of::() - 1usize]; -}; -#[repr(C)] pub struct cppgc_NameProvider__bindgen_vtable(::std::os::raw::c_void); #[doc = " NameProvider allows for providing a human-readable name for garbage-collected\n objects.\n\n There's two cases of names to distinguish:\n a. Explicitly specified names via using NameProvider. Such names are always\n preserved in the system.\n b. Internal names that Oilpan infers from a C++ type on the class hierarchy\n of the object. This is not necessarily the type of the actually\n instantiated object.\n\n Depending on the build configuration, Oilpan may hide names, i.e., represent\n them with kHiddenName, of case b. to avoid exposing internal details."] #[repr(C)] @@ -42,112 +30,6 @@ const _: () = { }; #[repr(C)] #[derive(Debug, Copy, Clone)] -pub struct v8_String_WriteFlags { - pub _address: u8, -} -pub const v8_String_WriteFlags_kNone: v8_String_WriteFlags__bindgen_ty_1 = 0; -pub const v8_String_WriteFlags_kNullTerminate: - v8_String_WriteFlags__bindgen_ty_1 = 1; -pub const v8_String_WriteFlags_kReplaceInvalidUtf8: - v8_String_WriteFlags__bindgen_ty_1 = 2; -pub type v8_String_WriteFlags__bindgen_ty_1 = ::std::os::raw::c_int; -#[allow(clippy::unnecessary_operation, clippy::identity_op)] -const _: () = { - ["Size of v8_String_WriteFlags"] - [::std::mem::size_of::() - 1usize]; - ["Alignment of v8_String_WriteFlags"] - [::std::mem::align_of::() - 1usize]; -}; -#[repr(C)] -pub struct v8_String_ExternalStringResourceBase__bindgen_vtable( - ::std::os::raw::c_void, -); -#[repr(C)] -#[derive(Debug)] -pub struct v8_String_ExternalStringResourceBase { - pub vtable_: *const v8_String_ExternalStringResourceBase__bindgen_vtable, -} -#[repr(C)] -pub struct v8_String_ExternalStringResourceBase_SharedMemoryUsageRecorder__bindgen_vtable( - ::std::os::raw::c_void, -); -#[repr(C)] -#[derive(Debug, Copy, Clone)] -pub struct v8_String_ExternalStringResourceBase_SharedMemoryUsageRecorder { pub vtable_ : * const v8_String_ExternalStringResourceBase_SharedMemoryUsageRecorder__bindgen_vtable , } -#[allow(clippy::unnecessary_operation, clippy::identity_op)] -const _: () = { - ["Size of v8_String_ExternalStringResourceBase_SharedMemoryUsageRecorder"] - [::std::mem::size_of::< - v8_String_ExternalStringResourceBase_SharedMemoryUsageRecorder, - >() - - 8usize]; - [ - "Alignment of v8_String_ExternalStringResourceBase_SharedMemoryUsageRecorder", - ][::std::mem::align_of::< - v8_String_ExternalStringResourceBase_SharedMemoryUsageRecorder, - >() - - 8usize]; -}; -unsafe extern "C" { - #[link_name = "\u{1}?kDefaultMemoryEstimate@ExternalStringResourceBase@String@v8@@2_KB"] - pub static v8_String_ExternalStringResourceBase_kDefaultMemoryEstimate: usize; -} -#[allow(clippy::unnecessary_operation, clippy::identity_op)] -const _: () = { - ["Size of v8_String_ExternalStringResourceBase"] - [::std::mem::size_of::() - 8usize]; - ["Alignment of v8_String_ExternalStringResourceBase"] - [::std::mem::align_of::() - 8usize]; -}; -#[doc = " An ExternalOneByteStringResource is a wrapper around an one-byte\n string buffer that resides outside V8's heap. Implement an\n ExternalOneByteStringResource to manage the life cycle of the\n underlying buffer. Note that the string data must be immutable\n and that the data must be Latin-1 and not UTF-8, which would require\n special treatment internally in the engine and do not allow efficient\n indexing. Use String::New or convert to 16 bit data for non-Latin1."] -#[repr(C)] -#[derive(Debug)] -pub struct v8_String_ExternalOneByteStringResource { - pub _base: v8_String_ExternalStringResourceBase, - pub cached_data_: *const ::std::os::raw::c_char, -} -#[allow(clippy::unnecessary_operation, clippy::identity_op)] -const _: () = { - ["Size of v8_String_ExternalOneByteStringResource"][::std::mem::size_of::< - v8_String_ExternalOneByteStringResource, - >() - - 16usize]; - ["Alignment of v8_String_ExternalOneByteStringResource"][::std::mem::align_of::< - v8_String_ExternalOneByteStringResource, - >() - 8usize]; - ["Offset of field: v8_String_ExternalOneByteStringResource::cached_data_"][::std::mem::offset_of!( - v8_String_ExternalOneByteStringResource, - cached_data_ - ) - - 8usize]; -}; -unsafe extern "C" { - #[doc = " Update {cached_data_} with the data from the underlying buffer. This can\n be called only for cacheable resources."] - #[link_name = "\u{1}?UpdateDataCache@ExternalOneByteStringResource@String@v8@@QEAAXXZ"] - pub fn v8_String_ExternalOneByteStringResource_UpdateDataCache( - this: *mut v8_String_ExternalOneByteStringResource, - ); -} -impl v8_String_ExternalOneByteStringResource { - #[inline] - pub unsafe fn UpdateDataCache(&mut self) { - v8_String_ExternalOneByteStringResource_UpdateDataCache(self) - } -} -#[repr(C)] -#[derive(Debug)] -pub struct v8_Object_Wrappable { - pub _base_1: cppgc_NameProvider, -} -#[allow(clippy::unnecessary_operation, clippy::identity_op)] -const _: () = { - ["Size of v8_Object_Wrappable"] - [::std::mem::size_of::() - 8usize]; - ["Alignment of v8_Object_Wrappable"] - [::std::mem::align_of::() - 8usize]; -}; -#[repr(C)] -#[derive(Debug, Copy, Clone)] pub struct v8_CTypeInfo { pub type_: v8_CTypeInfo_Type, pub flags_: v8_CTypeInfo_Flags, @@ -602,10 +484,220 @@ impl v8_HeapCodeStatistics { __bindgen_tmp.assume_init() } } +#[repr(u32)] +#[doc = " Interceptor callbacks use this value to indicate whether the request was\n intercepted or not.\n\n The values for constants and type are chosen this way for better\n performance."] +#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] +pub enum v8_Intercepted { + kNo = 1, + kYes = 0, +} +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct memory_span_t { + pub data: *mut u8, + pub size: usize, +} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of memory_span_t"][::std::mem::size_of::() - 16usize]; + ["Alignment of memory_span_t"] + [::std::mem::align_of::() - 8usize]; + ["Offset of field: memory_span_t::data"] + [::std::mem::offset_of!(memory_span_t, data) - 0usize]; + ["Offset of field: memory_span_t::size"] + [::std::mem::offset_of!(memory_span_t, size) - 8usize]; +}; +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct const_memory_span_t { + pub data: *const u8, + pub size: usize, +} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of const_memory_span_t"] + [::std::mem::size_of::() - 16usize]; + ["Alignment of const_memory_span_t"] + [::std::mem::align_of::() - 8usize]; + ["Offset of field: const_memory_span_t::data"] + [::std::mem::offset_of!(const_memory_span_t, data) - 0usize]; + ["Offset of field: const_memory_span_t::size"] + [::std::mem::offset_of!(const_memory_span_t, size) - 8usize]; +}; +#[repr(C)] +#[derive(Debug)] +pub struct RustObj { + pub _base: Wrappable, +} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of RustObj"][::std::mem::size_of::() - 8usize]; + ["Alignment of RustObj"][::std::mem::align_of::() - 8usize]; +}; +unsafe extern "C" { + #[link_name = "\u{1}??1RustObj@@UEAA@XZ"] + pub fn RustObj_RustObj_destructor(this: *mut RustObj); +} +unsafe extern "C" { + #[link_name = "\u{1}?GetHumanReadableName@RustObj@@UEBAPEBDXZ"] + pub fn RustObj_GetHumanReadableName( + this: *mut ::std::os::raw::c_void, + ) -> *const ::std::os::raw::c_char; +} +#[doc = " Types defined here will be compiled with bindgen\n and made available in `crate::binding` in rust."] +pub const v8__ScriptOrigin_SIZE: usize = 40; +pub const cppgc__Member_SIZE: usize = 4; +pub const cppgc__WeakMember_SIZE: usize = 4; +pub const v8__TracedReference_SIZE: usize = 8; +pub const v8__Eternal_SIZE: usize = 8; +pub const v8__String__ValueView_SIZE: usize = 32; +pub const v8__String__kMaxLength: ::std::os::raw::c_int = 536870888; +pub const v8__String__WriteFlags__kNullTerminate: ::std::os::raw::c_int = 1; +pub const v8__String__WriteFlags__kReplaceInvalidUtf8: ::std::os::raw::c_int = + 2; +pub const v8__TypedArray__kMaxByteLength: usize = 9007199254740991; +pub const v8__TYPED_ARRAY_MAX_SIZE_IN_HEAP: usize = 0; +pub const v8__Uint8Array__kMaxLength: usize = 9007199254740991; +pub const v8__Uint8ClampedArray__kMaxLength: usize = 9007199254740991; +pub const v8__Int8Array__kMaxLength: usize = 9007199254740991; +pub const v8__Uint16Array__kMaxLength: usize = 4503599627370495; +pub const v8__Int16Array__kMaxLength: usize = 4503599627370495; +pub const v8__Uint32Array__kMaxLength: usize = 2251799813685247; +pub const v8__Int32Array__kMaxLength: usize = 2251799813685247; +pub const v8__Float16Array__kMaxLength: usize = 4503599627370495; +pub const v8__Float32Array__kMaxLength: usize = 2251799813685247; +pub const v8__Float64Array__kMaxLength: usize = 1125899906842623; +pub const v8__BigUint64Array__kMaxLength: usize = 1125899906842623; +pub const v8__BigInt64Array__kMaxLength: usize = 1125899906842623; +pub type v8__CFunction = v8_CFunction; +pub type v8__CFunctionInfo = v8_CFunctionInfo; +pub type v8__FastOneByteString = v8_FastOneByteString; +#[doc = " Features reported via the SetUseCounterCallback callback. Do not change\n assigned numbers of existing items; add new features to the end of this\n list.\n Dead features can be marked `V8_DEPRECATE_SOON`, then `V8_DEPRECATED`, and\n then finally be renamed to `kOBSOLETE_...` to stop embedders from using\n them."] +pub use self::UseCounterFeature as v8__Isolate__UseCounterFeature; +pub type v8__String__WriteFlags = WriteFlags; +#[doc = " Import phases in import requests."] +pub use self::v8_ModuleImportPhase as v8__ModuleImportPhase; +#[doc = " Collection of V8 heap information.\n\n Instances of this class can be passed to v8::Isolate::GetHeapStatistics to\n get heap statistics from V8."] +pub type v8__HeapStatistics = v8_HeapStatistics; +pub type v8__HeapSpaceStatistics = v8_HeapSpaceStatistics; +pub type v8__HeapCodeStatistics = v8_HeapCodeStatistics; +#[doc = " GCCallbackFlags is used to notify additional information about the GC\n callback.\n - kGCCallbackFlagConstructRetainedObjectInfos: The GC callback is for\n constructing retained object infos.\n - kGCCallbackFlagForced: The GC callback is for a forced GC for testing.\n - kGCCallbackFlagSynchronousPhantomCallbackProcessing: The GC callback\n is called synchronously without getting posted to an idle task.\n - kGCCallbackFlagCollectAllAvailableGarbage: The GC callback is called\n in a phase where V8 is trying to collect all available garbage\n (e.g., handling a low memory notification).\n - kGCCallbackScheduleIdleGarbageCollection: The GC callback is called to\n trigger an idle garbage collection."] +pub use self::v8_GCCallbackFlags as v8__GCCallbackFlags; +#[doc = " Applications can register callback functions which will be called before and\n after certain garbage collection operations. Allocations are not allowed in\n the callback functions, you therefore cannot manipulate objects (set or\n delete properties for example) since it is possible such operations will\n result in the allocation of objects.\n TODO(v8:12612): Deprecate kGCTypeMinorMarkSweep after updating blink."] +pub use self::v8_GCType as v8__GCType; +#[doc = " Interceptor callbacks use this value to indicate whether the request was\n intercepted or not.\n\n The values for constants and type are chosen this way for better\n performance."] +pub use self::v8_Intercepted as v8__Intercepted; +pub const v8__MAJOR_VERSION: u32 = 15; +pub const v8__MINOR_VERSION: u32 = 8; +pub const v8__BUILD_NUMBER: u32 = 62; +pub const v8__PATCH_LEVEL: u32 = 23; +pub const v8__VERSION_STRING: &::std::ffi::CStr = c"15.8.62.23-rusty"; +#[repr(C)] +#[derive(Debug)] +pub struct ExternalConstOneByteStringResource { + pub _base: ExternalOneByteStringResource, + pub _length: ::std::os::raw::c_int, +} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of ExternalConstOneByteStringResource"] + [::std::mem::size_of::() - 24usize]; + ["Alignment of ExternalConstOneByteStringResource"] + [::std::mem::align_of::() - 8usize]; + ["Offset of field: ExternalConstOneByteStringResource::_length"][::std::mem::offset_of!( + ExternalConstOneByteStringResource, + _length + ) - 16usize]; +}; +#[repr(C)] +#[derive(Debug)] +pub struct Wrappable { + pub _base_1: cppgc_NameProvider, + _unused: [u8; 0], +} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: cppgc_GarbageCollected_open0_Wrappable_close0", + ][::std::mem::size_of::() - 1usize]; + [ + "Align of template specialization: cppgc_GarbageCollected_open0_Wrappable_close0", + ][::std::mem::align_of::() - 1usize]; +}; +#[doc = " An ExternalOneByteStringResource is a wrapper around an one-byte\n string buffer that resides outside V8's heap. Implement an\n ExternalOneByteStringResource to manage the life cycle of the\n underlying buffer. Note that the string data must be immutable\n and that the data must be Latin-1 and not UTF-8, which would require\n special treatment internally in the engine and do not allow efficient\n indexing. Use String::New or convert to 16 bit data for non-Latin1."] +#[repr(C)] +#[derive(Debug)] +pub struct ExternalOneByteStringResource { + pub _base: ExternalStringResourceBase, + pub cached_data_: *const ::std::os::raw::c_char, +} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of ExternalOneByteStringResource"] + [::std::mem::size_of::() - 16usize]; + ["Alignment of ExternalOneByteStringResource"] + [::std::mem::align_of::() - 8usize]; + ["Offset of field: ExternalOneByteStringResource::cached_data_"][::std::mem::offset_of!( + ExternalOneByteStringResource, + cached_data_ + ) - 8usize]; +}; +unsafe extern "C" { + #[doc = " Update {cached_data_} with the data from the underlying buffer. This can\n be called only for cacheable resources."] + #[link_name = "\u{1}?UpdateDataCache@ExternalOneByteStringResource@String@v8@@QEAAXXZ"] + pub fn ExternalOneByteStringResource_UpdateDataCache( + this: *const ExternalOneByteStringResource, + ); +} +impl ExternalOneByteStringResource { + #[inline] + pub unsafe fn UpdateDataCache(&mut self) { + ExternalOneByteStringResource_UpdateDataCache(self) + } +} +#[repr(C)] +pub struct ExternalStringResourceBase__bindgen_vtable(::std::os::raw::c_void); +#[repr(C)] +#[derive(Debug)] +pub struct ExternalStringResourceBase { + pub vtable_: *const ExternalStringResourceBase__bindgen_vtable, +} +#[repr(C)] +pub struct ExternalStringResourceBase_SharedMemoryUsageRecorder__bindgen_vtable( + ::std::os::raw::c_void, +); +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct ExternalStringResourceBase_SharedMemoryUsageRecorder { + pub vtable_: + *const ExternalStringResourceBase_SharedMemoryUsageRecorder__bindgen_vtable, +} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of ExternalStringResourceBase_SharedMemoryUsageRecorder"] + [::std::mem::size_of::( + ) - 8usize]; + ["Alignment of ExternalStringResourceBase_SharedMemoryUsageRecorder"] + [::std::mem::align_of::< + ExternalStringResourceBase_SharedMemoryUsageRecorder, + >() + - 8usize]; +}; +unsafe extern "C" { + #[link_name = "\u{1}?kDefaultMemoryEstimate@ExternalStringResourceBase@String@v8@@2_KB"] + pub static ExternalStringResourceBase_kDefaultMemoryEstimate: usize; +} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of ExternalStringResourceBase"] + [::std::mem::size_of::() - 8usize]; + ["Alignment of ExternalStringResourceBase"] + [::std::mem::align_of::() - 8usize]; +}; #[repr(i32)] #[doc = " Features reported via the SetUseCounterCallback callback. Do not change\n assigned numbers of existing items; add new features to the end of this\n list.\n Dead features can be marked `V8_DEPRECATE_SOON`, then `V8_DEPRECATED`, and\n then finally be renamed to `kOBSOLETE_...` to stop embedders from using\n them."] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] -pub enum v8_Isolate_UseCounterFeature { +pub enum UseCounterFeature { kUseAsm = 0, kBreakIterator = 1, kOBSOLETE_LegacyConst = 2, @@ -792,136 +884,25 @@ pub enum v8_Isolate_UseCounterFeature { kOBSOLETE_WasmResizableBuffers = 183, kInvalidatedArrayBufferMutableProtector = 184, kHoleyArrayReadthrough = 185, - kUseCounterFeatureCount = 186, -} -#[repr(u32)] -#[doc = " Interceptor callbacks use this value to indicate whether the request was\n intercepted or not.\n\n The values for constants and type are chosen this way for better\n performance."] -#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] -pub enum v8_Intercepted { - kNo = 1, - kYes = 0, + kWasmGCAllocation = 186, + kModuleNamespaceMissingDefaultWithStarExport = 187, + kRegExpMatcherFlagsMismatch = 188, + kRegExpCustomSpecies = 189, + kWasmWideArithmetic = 190, + kBigInt = 191, + kUseCounterFeatureCount = 192, } #[repr(C)] #[derive(Debug, Copy, Clone)] -pub struct memory_span_t { - pub data: *mut u8, - pub size: usize, -} -#[allow(clippy::unnecessary_operation, clippy::identity_op)] -const _: () = { - ["Size of memory_span_t"][::std::mem::size_of::() - 16usize]; - ["Alignment of memory_span_t"] - [::std::mem::align_of::() - 8usize]; - ["Offset of field: memory_span_t::data"] - [::std::mem::offset_of!(memory_span_t, data) - 0usize]; - ["Offset of field: memory_span_t::size"] - [::std::mem::offset_of!(memory_span_t, size) - 8usize]; -}; -#[repr(C)] -#[derive(Debug, Copy, Clone)] -pub struct const_memory_span_t { - pub data: *const u8, - pub size: usize, -} -#[allow(clippy::unnecessary_operation, clippy::identity_op)] -const _: () = { - ["Size of const_memory_span_t"] - [::std::mem::size_of::() - 16usize]; - ["Alignment of const_memory_span_t"] - [::std::mem::align_of::() - 8usize]; - ["Offset of field: const_memory_span_t::data"] - [::std::mem::offset_of!(const_memory_span_t, data) - 0usize]; - ["Offset of field: const_memory_span_t::size"] - [::std::mem::offset_of!(const_memory_span_t, size) - 8usize]; -}; -#[repr(C)] -#[derive(Debug)] -pub struct RustObj { - pub _base: v8_Object_Wrappable, -} -#[allow(clippy::unnecessary_operation, clippy::identity_op)] -const _: () = { - ["Size of RustObj"][::std::mem::size_of::() - 8usize]; - ["Alignment of RustObj"][::std::mem::align_of::() - 8usize]; -}; -unsafe extern "C" { - #[link_name = "\u{1}??1RustObj@@UEAA@XZ"] - pub fn RustObj_RustObj_destructor(this: *mut RustObj); -} -unsafe extern "C" { - #[link_name = "\u{1}?GetHumanReadableName@RustObj@@UEBAPEBDXZ"] - pub fn RustObj_GetHumanReadableName( - this: *mut ::std::os::raw::c_void, - ) -> *const ::std::os::raw::c_char; -} -#[doc = " Types defined here will be compiled with bindgen\n and made available in `crate::binding` in rust."] -pub const v8__ScriptOrigin_SIZE: usize = 40; -pub const cppgc__Member_SIZE: usize = 4; -pub const cppgc__WeakMember_SIZE: usize = 4; -pub const v8__TracedReference_SIZE: usize = 8; -pub const v8__Eternal_SIZE: usize = 8; -pub const v8__String__ValueView_SIZE: usize = 32; -pub const v8__String__kMaxLength: ::std::os::raw::c_int = 536870888; -pub const v8__TypedArray__kMaxByteLength: usize = 9007199254740991; -pub const v8__TYPED_ARRAY_MAX_SIZE_IN_HEAP: usize = 0; -pub const v8__Uint8Array__kMaxLength: usize = 9007199254740991; -pub const v8__Uint8ClampedArray__kMaxLength: usize = 9007199254740991; -pub const v8__Int8Array__kMaxLength: usize = 9007199254740991; -pub const v8__Uint16Array__kMaxLength: usize = 4503599627370495; -pub const v8__Int16Array__kMaxLength: usize = 4503599627370495; -pub const v8__Uint32Array__kMaxLength: usize = 2251799813685247; -pub const v8__Int32Array__kMaxLength: usize = 2251799813685247; -pub const v8__Float16Array__kMaxLength: usize = 4503599627370495; -pub const v8__Float32Array__kMaxLength: usize = 2251799813685247; -pub const v8__Float64Array__kMaxLength: usize = 1125899906842623; -pub const v8__BigUint64Array__kMaxLength: usize = 1125899906842623; -pub const v8__BigInt64Array__kMaxLength: usize = 1125899906842623; -pub type v8__CFunction = v8_CFunction; -pub type v8__CFunctionInfo = v8_CFunctionInfo; -pub type v8__FastOneByteString = v8_FastOneByteString; -#[doc = " Features reported via the SetUseCounterCallback callback. Do not change\n assigned numbers of existing items; add new features to the end of this\n list.\n Dead features can be marked `V8_DEPRECATE_SOON`, then `V8_DEPRECATED`, and\n then finally be renamed to `kOBSOLETE_...` to stop embedders from using\n them."] -pub use self::v8_Isolate_UseCounterFeature as v8__Isolate__UseCounterFeature; -pub type v8__String__WriteFlags = v8_String_WriteFlags; -#[doc = " Import phases in import requests."] -pub use self::v8_ModuleImportPhase as v8__ModuleImportPhase; -#[doc = " Collection of V8 heap information.\n\n Instances of this class can be passed to v8::Isolate::GetHeapStatistics to\n get heap statistics from V8."] -pub type v8__HeapStatistics = v8_HeapStatistics; -pub type v8__HeapSpaceStatistics = v8_HeapSpaceStatistics; -pub type v8__HeapCodeStatistics = v8_HeapCodeStatistics; -#[doc = " GCCallbackFlags is used to notify additional information about the GC\n callback.\n - kGCCallbackFlagConstructRetainedObjectInfos: The GC callback is for\n constructing retained object infos.\n - kGCCallbackFlagForced: The GC callback is for a forced GC for testing.\n - kGCCallbackFlagSynchronousPhantomCallbackProcessing: The GC callback\n is called synchronously without getting posted to an idle task.\n - kGCCallbackFlagCollectAllAvailableGarbage: The GC callback is called\n in a phase where V8 is trying to collect all available garbage\n (e.g., handling a low memory notification).\n - kGCCallbackScheduleIdleGarbageCollection: The GC callback is called to\n trigger an idle garbage collection."] -pub use self::v8_GCCallbackFlags as v8__GCCallbackFlags; -#[doc = " Applications can register callback functions which will be called before and\n after certain garbage collection operations. Allocations are not allowed in\n the callback functions, you therefore cannot manipulate objects (set or\n delete properties for example) since it is possible such operations will\n result in the allocation of objects.\n TODO(v8:12612): Deprecate kGCTypeMinorMarkSweep after updating blink."] -pub use self::v8_GCType as v8__GCType; -#[doc = " Interceptor callbacks use this value to indicate whether the request was\n intercepted or not.\n\n The values for constants and type are chosen this way for better\n performance."] -pub use self::v8_Intercepted as v8__Intercepted; -pub const v8__MAJOR_VERSION: u32 = 14; -pub const v8__MINOR_VERSION: u32 = 9; -pub const v8__BUILD_NUMBER: u32 = 207; -pub const v8__PATCH_LEVEL: u32 = 2; -pub const v8__VERSION_STRING: &::std::ffi::CStr = c"14.9.207.2-rusty"; -#[repr(C)] -#[derive(Debug)] -pub struct ExternalConstOneByteStringResource { - pub _base: v8_String_ExternalOneByteStringResource, - pub _length: ::std::os::raw::c_int, +pub struct WriteFlags { + pub _address: u8, } +pub const WriteFlags_kNone: WriteFlags__bindgen_ty_1 = 0; +pub const WriteFlags_kNullTerminate: WriteFlags__bindgen_ty_1 = 1; +pub const WriteFlags_kReplaceInvalidUtf8: WriteFlags__bindgen_ty_1 = 2; +pub type WriteFlags__bindgen_ty_1 = ::std::os::raw::c_int; #[allow(clippy::unnecessary_operation, clippy::identity_op)] const _: () = { - ["Size of ExternalConstOneByteStringResource"] - [::std::mem::size_of::() - 24usize]; - ["Alignment of ExternalConstOneByteStringResource"] - [::std::mem::align_of::() - 8usize]; - ["Offset of field: ExternalConstOneByteStringResource::_length"][::std::mem::offset_of!( - ExternalConstOneByteStringResource, - _length - ) - 16usize]; -}; -#[allow(clippy::unnecessary_operation, clippy::identity_op)] -const _: () = { - [ - "Size of template specialization: cppgc_GarbageCollected_open0_v8_Object_Wrappable_close0", - ][::std::mem::size_of::() - 1usize]; - [ - "Align of template specialization: cppgc_GarbageCollected_open0_v8_Object_Wrappable_close0", - ][::std::mem::align_of::() - 1usize]; + ["Size of WriteFlags"][::std::mem::size_of::() - 1usize]; + ["Alignment of WriteFlags"][::std::mem::align_of::() - 1usize]; }; diff --git a/patches/rusty_v8-01-escape-slot.patch b/patches/rusty_v8-01-escape-slot.patch index 9d93ce68..26925653 100644 --- a/patches/rusty_v8-01-escape-slot.patch +++ b/patches/rusty_v8-01-escape-slot.patch @@ -1,15 +1,15 @@ diff --git a/src/scope.rs b/src/scope.rs -index 293e4b2..81ea7d3 100644 +index 8da79f7..c062c3f 100644 --- a/src/scope.rs +++ b/src/scope.rs -@@ -143,6 +143,7 @@ use std::{ +@@ -173,6 +173,7 @@ use std::{ pin::Pin, ptr::NonNull, }; +#[path = "scope/raw.rs"] pub(crate) mod raw; - pub type PinScope<'s, 'i, C = Context> = PinnedRef<'s, HandleScope<'i, C>>; + /// Tracks which `Isolate` owns the scopes that are open on the current thread diff --git a/src/scope/raw.rs b/src/scope/raw.rs index 4e443c2..66d9c1e 100644 --- a/src/scope/raw.rs diff --git a/site/getting-started.typ b/site/getting-started.typ index 8862cfe4..7e6035e7 100644 --- a/site/getting-started.typ +++ b/site/getting-started.typ @@ -15,7 +15,7 @@ Replace the `v8` dependency with `v8x` and pick an engine feature: ```toml [dependencies] -v8 = { package = "v8x", version = "149.4.0", features = ["quickjs"] } +v8 = { package = "v8x", version = "158.0.0", features = ["quickjs"] } ``` Engine features are mutually exclusive; enable exactly one: @@ -39,7 +39,7 @@ the swap: ```toml # deno's workspace Cargo.toml [patch.crates-io] -v8 = { package = "v8x", version = "149.4.0", features = ["jsc"] } +v8 = { package = "v8x", version = "158.0.0", features = ["jsc"] } ``` ```sh diff --git a/site/index.typ b/site/index.typ index c216c7e1..234941d6 100644 --- a/site/index.typ +++ b/site/index.typ @@ -14,8 +14,8 @@ JavaScript engine: ```diff --v8 = "149.4.0" -+v8 = { package = "v8x", version = "149.4.0", features = ["jsc"] } +-v8 = "158.0.0" ++v8 = { package = "v8x", version = "158.0.0", features = ["jsc"] } ``` Anything built on rusty_v8, including `deno_core` and Deno itself, compiles @@ -36,7 +36,7 @@ One engine is active at a time. The usual reason to swap is binary size: #table( columns: 3, [*engine*], [*deno binary*], [*engine size*], - [V8 14.9], [78.7 MB], [\~40 MB static], + [V8 15.2], [78.7 MB], [\~40 MB static], [JSC (vendored)], [80.7 MB], [\~48 MB static], [system JSC], [54.2 MB], [0, ships with the OS], [quickjs-ng], [56.1 MB], [\~1 MB static], diff --git a/src/crdtp_shim.rs b/src/crdtp_shim.rs index 450f9888..7592dcc6 100644 --- a/src/crdtp_shim.rs +++ b/src/crdtp_shim.rs @@ -410,6 +410,31 @@ pub(crate) struct Dispatchable { method: Vec, session_id: Vec, params: Vec, + /// The serialized message exactly as it arrived. The fallthrough callback + /// is handed it verbatim. + message: Vec, + /// Embedder blob carried alongside the message, handed back verbatim by + /// `associatedData` and to the fallthrough callback. + associated_data: Vec, + /// Owned `FallthroughCallbackData` from the Rust side, released with + /// `crdtp__FallthroughCallback__Drop`. Null when the embedder gave none. + fallthrough: *mut c_void, +} + +unsafe extern "C" { + /// Both are defined by the vendored `crdtp.rs`, which owns the boxed Rust + /// closure this shim only stores and hands back. + fn crdtp__FallthroughCallback__Run( + callback: *mut c_void, + call_id: i32, + method_data: *const u8, + method_len: usize, + message_data: *const u8, + message_len: usize, + associated_data: *const u8, + associated_data_len: usize, + ); + fn crdtp__FallthroughCallback__Drop(callback: *mut c_void); } #[derive(Clone, Copy, PartialEq)] @@ -435,27 +460,6 @@ pub(crate) struct DomainDispatcher { rust_dispatcher: *mut c_void, } -enum Runnable { - /// No handler found: send a MethodNotFound error response (if it has an id). - NotFound { - channel: *mut c_void, - call_id: i32, - has_call_id: bool, - method: Vec, - }, - /// Handler found: run the execute phase against the Rust dispatcher. - Execute { - rust_dispatcher: *mut c_void, - command: Vec, - dispatchable: *const c_void, - }, -} - -pub(crate) struct DispatchResult { - method_found: bool, - runnable: Option, -} - #[inline] fn box_raw(v: T) -> *mut T { Box::into_raw(Box::new(v)) @@ -516,6 +520,9 @@ pub unsafe extern "C" fn crdtp__Serializable__AppendSerialized( pub unsafe extern "C" fn crdtp__Dispatchable__new( data: *const u8, len: usize, + associated_data: *const u8, + associated_data_len: usize, + fallthrough_callback: *mut c_void, ) -> *mut Dispatchable { let bytes = if data.is_null() || len == 0 { &[][..] @@ -523,6 +530,17 @@ pub unsafe extern "C" fn crdtp__Dispatchable__new( unsafe { std::slice::from_raw_parts(data, len) } }; + // Copied rather than borrowed: the C++ Dispatchable borrows the caller's + // buffers and rusty_v8 keeps them alive for it, but this shim outlives + // nothing in particular, so it owns what it reports. + let associated_data = if associated_data.is_null() || associated_data_len == 0 + { + Vec::new() + } else { + unsafe { std::slice::from_raw_parts(associated_data, associated_data_len) } + .to_vec() + }; + let mut d = Dispatchable { ok: false, has_call_id: false, @@ -530,6 +548,9 @@ pub unsafe extern "C" fn crdtp__Dispatchable__new( method: Vec::new(), session_id: Vec::new(), params: Vec::new(), + message: bytes.to_vec(), + associated_data, + fallthrough: fallthrough_callback, }; if let Some(Json::Obj(members)) = parse_json(bytes) { @@ -572,9 +593,39 @@ pub unsafe extern "C" fn crdtp__Dispatchable__new( #[unsafe(no_mangle)] pub unsafe extern "C" fn crdtp__Dispatchable__DELETE(this: *mut Dispatchable) { + if this.is_null() { + return; + } + let fallthrough = unsafe { (*this).fallthrough }; + if !fallthrough.is_null() { + unsafe { crdtp__FallthroughCallback__Drop(fallthrough) }; + } unsafe { free_box(this) }; } +#[unsafe(no_mangle)] +pub unsafe extern "C" fn crdtp__Dispatchable__associatedDataLen( + this: *const Dispatchable, +) -> usize { + if this.is_null() { + 0 + } else { + unsafe { &*this }.associated_data.len() + } +} + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn crdtp__Dispatchable__associatedDataCopy( + this: *const Dispatchable, + out: *mut u8, +) { + if this.is_null() || out.is_null() { + return; + } + let d = unsafe { &(*this).associated_data }; + unsafe { std::ptr::copy_nonoverlapping(d.as_ptr(), out, d.len()) }; +} + #[unsafe(no_mangle)] pub unsafe extern "C" fn crdtp__Dispatchable__ok( this: *const Dispatchable, @@ -1056,8 +1107,8 @@ fn split_method(method: &[u8]) -> (&[u8], &[u8]) { #[unsafe(no_mangle)] pub unsafe extern "C" fn crdtp__UberDispatcher__Dispatch( this: *mut UberDispatcher, - dispatchable: *const Dispatchable, -) -> *mut DispatchResult { + dispatchable: *mut Dispatchable, +) { let uber = unsafe { &mut *this }; let d = unsafe { &*dispatchable }; @@ -1070,106 +1121,62 @@ pub unsafe extern "C" fn crdtp__UberDispatcher__Dispatch( .find(|(dom, _)| dom.as_slice() == domain) .map(|(_, p)| *p); - let not_found = || DispatchResult { - method_found: false, - runnable: Some(Runnable::NotFound { - channel: uber.channel, - call_id: d.call_id, - has_call_id: d.has_call_id, - method: d.method.clone(), - }), - }; - - let result = match dd_ptr { - None => not_found(), - Some(dd) => { - let rust_dispatcher = unsafe { (*dd).rust_dispatcher }; - // Probe phase: null dispatchable, ask whether the command is handled. - let found = unsafe { - crdtp__DomainDispatcher__BASE__Dispatch( - rust_dispatcher, - command.as_ptr(), - command.len(), - std::ptr::null(), - ) - }; - if found { - DispatchResult { - method_found: true, - runnable: Some(Runnable::Execute { - rust_dispatcher, - command: command.to_vec(), - dispatchable: dispatchable as *const c_void, - }), - } - } else { - not_found() - } - } - }; - - box_raw(result) -} - -#[unsafe(no_mangle)] -pub unsafe extern "C" fn crdtp__DispatchResult__DELETE( - this: *mut DispatchResult, -) { - unsafe { free_box(this) }; -} - -#[unsafe(no_mangle)] -pub unsafe extern "C" fn crdtp__DispatchResult__MethodFound( - this: *const DispatchResult, -) -> bool { - !this.is_null() && unsafe { (*this).method_found } -} - -#[unsafe(no_mangle)] -pub unsafe extern "C" fn crdtp__DispatchResult__Run(this: *mut DispatchResult) { - if this.is_null() { - return; - } - let runnable = unsafe { &mut *this }.runnable.take(); - match runnable { - Some(Runnable::Execute { - rust_dispatcher, - command, - dispatchable, - }) => unsafe { + // Since rusty_v8 v152.0.0 there is no probe phase: `BASE__Dispatch` takes a + // live `&Dispatchable` and runs the command, reporting whether it handled it. + // Calling it twice, as the probe-then-execute split did, would run the + // command twice and send two responses. + let handled = match dd_ptr { + None => false, + Some(dd) => unsafe { crdtp__DomainDispatcher__BASE__Dispatch( - rust_dispatcher, + (*dd).rust_dispatcher, command.as_ptr(), command.len(), - dispatchable, - ); + dispatchable as *const c_void, + ) }, - Some(Runnable::NotFound { - channel, - call_id, - has_call_id, - method, - }) => { - // Real crdtp replies with a MethodNotFound error response. - if has_call_id && !channel.is_null() { - let method_str = String::from_utf8_lossy(&method); - let resp = DispatchResponse { - kind: RespKind::Error, - code: -32601, - message: format!("'{method_str}' wasn't found"), - }; - let bytes = error_response_json(call_id, &resp); - let msg = serializable_ptr(bytes); - unsafe { - crdtp__FrontendChannel__BASE__sendProtocolResponse( - channel, - call_id, - msg as *mut c_void, - ); - } + }; + + if !handled { + // An unhandled method goes to the embedder's fallthrough callback when one + // was registered. Only without it does crdtp answer the request itself, + // with a MethodNotFound error response. + let channel = uber.channel; + let call_id = d.call_id; + let has_call_id = d.has_call_id; + let method = d.method.clone(); + if !d.fallthrough.is_null() { + unsafe { + crdtp__FallthroughCallback__Run( + d.fallthrough, + call_id, + method.as_ptr(), + method.len(), + d.message.as_ptr(), + d.message.len(), + d.associated_data.as_ptr(), + d.associated_data.len(), + ); + } + return; + } + if has_call_id && !channel.is_null() { + let method_str = String::from_utf8_lossy(&method); + let resp = DispatchResponse { + kind: RespKind::Error, + code: -32601, + message: format!("'{method_str}' wasn't found"), + }; + let bytes = error_response_json(call_id, &resp); + let msg = serializable_ptr(bytes); + unsafe { + crdtp__FrontendChannel__BASE__sendProtocolResponse( + channel, + call_id, + msg as *mut c_void, + ); } } - None => {} } } diff --git a/src/jsc/arraybuffer.rs b/src/jsc/arraybuffer.rs index 0b1e7a0d..ed1a6572 100644 --- a/src/jsc/arraybuffer.rs +++ b/src/jsc/arraybuffer.rs @@ -75,12 +75,20 @@ fn is_marked_detached(ctx: JSContextRef, obj: JSObjectRef) -> bool { } } +/// `v8::ArrayBuffer::kMaxByteLength` (2^53 - 1 on 64-bit targets). +const MAX_BYTE_LENGTH: usize = crate::binding::v8__TypedArray__kMaxByteLength; + struct BsInner { refcount: AtomicUsize, data: *mut c_void, byte_length: usize, is_shared: bool, + /// The length the store may grow to. Equal to `byte_length` unless the + /// store is resizable, in which case `data` already spans this many bytes. + max_byte_length: usize, + resizable: bool, + deleter: BackingStoreDeleterCallback, deleter_data: *mut c_void, @@ -114,6 +122,8 @@ impl BsInner { data, byte_length, is_shared, + max_byte_length: byte_length, + resizable: false, deleter, deleter_data, owns_malloc, @@ -136,6 +146,42 @@ impl BsInner { ) } + /// Allocates a store per `BackingStoreInitializationMode`. Returns null if + /// the length exceeds what an ArrayBuffer may hold or allocation fails. + fn try_allocate( + byte_length: usize, + is_shared: bool, + mode: crate::BackingStoreInitializationMode, + ) -> *mut BsInner { + if byte_length > MAX_BYTE_LENGTH { + return ptr::null_mut(); + } + let data = if byte_length == 0 { + ptr::null_mut() + } else { + let p = match mode { + crate::BackingStoreInitializationMode::ZeroInitialized => unsafe { + calloc(byte_length, 1) + }, + crate::BackingStoreInitializationMode::Uninitialized => unsafe { + malloc(byte_length) + }, + }; + if p.is_null() { + return ptr::null_mut(); + } + p + }; + BsInner::boxed( + data, + byte_length, + is_shared, + noop_deleter, + ptr::null_mut(), + true, + ) + } + unsafe fn destroy(ptr: *mut BsInner) { if ptr.is_null() { return; @@ -205,9 +251,71 @@ fn backing_store_for_buffer( }; let inner = BsInner::boxed(data, len, false, noop_deleter, ptr::null_mut(), false); + if let Some(max) = buffer_max_byte_length(ctx, buf) { + unsafe { + (*inner).resizable = true; + (*inner).max_byte_length = max; + } + } make_shared_ref(inner) } +/// `maxByteLength` of a resizable ArrayBuffer or growable SharedArrayBuffer, +/// or `None` for a fixed-length one. +fn buffer_max_byte_length(ctx: JSContextRef, buf: JSValueRef) -> Option { + let r = unsafe { + crate::jsc::core::call_js_fn( + ctx, + c"(function(b){try{return b.resizable===true||b.growable===true?\ + b.maxByteLength:-1}catch(e){return -1}})", + &[buf], + ) + } + .ok()?; + let n = unsafe { JSValueToNumber(ctx, r, ptr::null_mut()) }; + if n >= 0.0 { Some(n as usize) } else { None } +} + +/// `new ArrayBuffer(len, {maxByteLength: max})` holding a copy of `data`. +/// +/// JSC's C API can only wrap foreign memory in a fixed-length buffer, so a +/// resizable backing store cannot be shared with the ArrayBuffer made from it +/// the way V8 shares it. The buffer starts out with the store's contents, +/// but later writes on either side are not seen by the other. +fn make_resizable_buffer_copy( + ctx: JSContextRef, + data: *const c_void, + len: usize, + max: usize, +) -> JSValueRef { + let args = unsafe { + [ + JSValueMakeNumber(ctx, len as f64), + JSValueMakeNumber(ctx, max as f64), + ] + }; + let Ok(buf) = (unsafe { + crate::jsc::core::call_js_fn( + ctx, + c"(function(l,m){return new ArrayBuffer(l,{maxByteLength:m})})", + &args, + ) + }) else { + return ptr::null(); + }; + if len > 0 && !data.is_null() { + let dst = unsafe { + JSObjectGetArrayBufferBytesPtr(ctx, buf as JSObjectRef, ptr::null_mut()) + }; + if !dst.is_null() { + unsafe { + ptr::copy_nonoverlapping(data as *const u8, dst as *mut u8, len) + }; + } + } + buf +} + #[unsafe(no_mangle)] pub extern "C" fn v8__ArrayBuffer__New__with_byte_length( isolate: *mut RealIsolate, @@ -259,6 +367,14 @@ pub extern "C" fn v8__ArrayBuffer__New__with_backing_store( return ptr::null(); } let (data, len) = unsafe { ((*inner).data, (*inner).byte_length) }; + if unsafe { (*inner).resizable } { + let max = unsafe { (*inner).max_byte_length }; + let buf = make_resizable_buffer_copy(ctx, data, len, max); + if buf.is_null() { + return ptr::null(); + } + return intern_ctx::(ctx, buf); + } unsafe { (*inner).refcount.fetch_add(1, Ordering::SeqCst) }; unsafe extern "C" fn dealloc(_bytes: *mut c_void, ctx: *mut c_void) { @@ -459,7 +575,176 @@ pub extern "C" fn v8__BackingStore__IsShared( pub extern "C" fn v8__BackingStore__IsResizableByUserJavaScript( this: *const BackingStore, ) -> bool { - false + bs_inner(this).is_some_and(|b| b.resizable) +} + +#[unsafe(no_mangle)] +pub extern "C" fn v8__BackingStore__MaxByteLength( + this: *const BackingStore, +) -> usize { + bs_inner(this).map_or(0, |b| b.max_byte_length) +} + +/// V8's `kOutOfMemory` failure mode: a failed allocation is fatal. +fn backing_store_oom(byte_length: usize) -> ! { + panic!( + "v8x: out of memory allocating an ArrayBuffer backing store of \ + {byte_length} bytes" + ) +} + +fn new_backing_store_with_mode( + byte_length: usize, + is_shared: bool, + initialization_mode: crate::BackingStoreInitializationMode, + on_failure: crate::BackingStoreOnFailureMode, +) -> *mut BackingStore { + let inner = + BsInner::try_allocate(byte_length, is_shared, initialization_mode); + if inner.is_null() + && matches!(on_failure, crate::BackingStoreOnFailureMode::OutOfMemory) + { + backing_store_oom(byte_length); + } + inner as *mut BackingStore +} + +#[unsafe(no_mangle)] +pub extern "C" fn v8__ArrayBuffer__NewBackingStore__with_mode( + _isolate: *mut RealIsolate, + byte_length: usize, + initialization_mode: crate::BackingStoreInitializationMode, + on_failure: crate::BackingStoreOnFailureMode, +) -> *mut BackingStore { + new_backing_store_with_mode( + byte_length, + false, + initialization_mode, + on_failure, + ) +} + +#[unsafe(no_mangle)] +pub extern "C" fn v8__SharedArrayBuffer__NewBackingStore__with_mode( + _isolate: *mut RealIsolate, + byte_length: usize, + initialization_mode: crate::BackingStoreInitializationMode, + on_failure: crate::BackingStoreOnFailureMode, +) -> *mut BackingStore { + new_backing_store_with_mode( + byte_length, + true, + initialization_mode, + on_failure, + ) +} + +/// A zero-filled store that reserves `max_byte_length` bytes up front, as +/// V8's does, so growing it never moves the data. +#[unsafe(no_mangle)] +pub extern "C" fn v8__ArrayBuffer__NewResizableBackingStore( + byte_length: usize, + max_byte_length: usize, +) -> *mut BackingStore { + assert!( + byte_length <= max_byte_length && max_byte_length <= MAX_BYTE_LENGTH, + "v8x: invalid resizable backing store length {byte_length} / maximum \ + {max_byte_length}" + ); + let data = unsafe { calloc(max_byte_length.max(1), 1) }; + if data.is_null() { + backing_store_oom(max_byte_length); + } + let inner = BsInner::boxed( + data, + byte_length, + false, + noop_deleter, + ptr::null_mut(), + true, + ); + unsafe { + (*inner).resizable = true; + (*inner).max_byte_length = max_byte_length; + } + inner as *mut BackingStore +} + +#[unsafe(no_mangle)] +pub extern "C" fn v8__ArrayBuffer__MaybeNew( + isolate: *mut RealIsolate, + byte_length: usize, + initialization_mode: crate::BackingStoreInitializationMode, +) -> *const ArrayBuffer { + let st = iso_state(isolate); + let ctx = + st.contexts.last().copied().unwrap_or(ptr::null_mut()) as JSContextRef; + if ctx.is_null() || byte_length > MAX_BYTE_LENGTH { + return ptr::null(); + } + // As in `New__with_byte_length`, never hand JSC a null data pointer. + let data = match initialization_mode { + crate::BackingStoreInitializationMode::ZeroInitialized => unsafe { + calloc(byte_length.max(1), 1) + }, + crate::BackingStoreInitializationMode::Uninitialized => unsafe { + malloc(byte_length.max(1)) + }, + }; + if data.is_null() { + return ptr::null(); + } + unsafe extern "C" fn dealloc(bytes: *mut c_void, _ctx: *mut c_void) { + if !bytes.is_null() { + unsafe { free(bytes) }; + } + } + let obj = unsafe { + JSObjectMakeArrayBufferWithBytesNoCopy( + ctx, + data, + byte_length, + Some(dealloc), + ptr::null_mut(), + ptr::null_mut(), + ) + }; + if obj.is_null() { + unsafe { free(data) }; + return ptr::null(); + } + intern_ctx::(ctx, obj as JSValueRef) +} + +#[unsafe(no_mangle)] +pub extern "C" fn v8__ArrayBuffer__IsResizableByUserJavaScript( + this: *const ArrayBuffer, +) -> bool { + let ctx = current_ctx(); + if ctx.is_null() || this.is_null() { + return false; + } + buffer_max_byte_length(ctx, jsval(this)).is_some() +} + +/// Immutable ArrayBuffers (the TC39 proposal) report `immutable === true`; +/// JavaScriptCore builds without the proposal never create one. +#[unsafe(no_mangle)] +pub extern "C" fn v8__ArrayBuffer__IsImmutable( + this: *const ArrayBuffer, +) -> bool { + let ctx = current_ctx(); + if ctx.is_null() || this.is_null() { + return false; + } + let r = unsafe { + crate::jsc::core::call_js_fn( + ctx, + c"(function(b){try{return b.immutable===true}catch(e){return false}})", + &[jsval(this)], + ) + }; + matches!(r, Ok(v) if unsafe { JSValueToBoolean(ctx, v) }) } #[unsafe(no_mangle)] @@ -536,6 +821,15 @@ pub extern "C" fn v8__ArrayBuffer__Allocator__NewDefaultAllocator() Box::into_raw(Box::new(0u8)) as *mut Allocator } +/// V8 only has a group-scoped allocator with multi-cage pointer compression, +/// and returns null otherwise. This backend has a single isolate group. +#[unsafe(no_mangle)] +pub extern "C" fn v8__ArrayBuffer__Allocator__NewDefaultAllocator__with_group( + _group: *const c_void, +) -> *mut Allocator { + ptr::null_mut() +} + #[unsafe(no_mangle)] pub extern "C" fn v8__ArrayBuffer__Allocator__DELETE(this: *mut Allocator) { if !this.is_null() { @@ -957,6 +1251,119 @@ typed_array_new!( kJSTypedArrayTypeBigUint64Array ); +// Views over a SharedArrayBuffer. JSC's typed array constructors take either +// kind of buffer, so these share `make_typed_array` with the ArrayBuffer +// versions. +macro_rules! typed_array_new_shared { + ($fn_name:ident, $ty_name:ident, $jsc_ty:expr) => { + #[unsafe(no_mangle)] + pub extern "C" fn $fn_name( + buf_ptr: *const SharedArrayBuffer, + byte_offset: usize, + length: usize, + ) -> *const crate::$ty_name { + let v = make_typed_array( + buf_ptr as *const ArrayBuffer, + byte_offset, + length, + $jsc_ty, + ); + intern::(v) + } + }; +} + +typed_array_new_shared!( + v8__Uint8Array__New__with_shared_buffer, + Uint8Array, + kJSTypedArrayTypeUint8Array +); +typed_array_new_shared!( + v8__Uint8ClampedArray__New__with_shared_buffer, + Uint8ClampedArray, + kJSTypedArrayTypeUint8ClampedArray +); +typed_array_new_shared!( + v8__Int8Array__New__with_shared_buffer, + Int8Array, + kJSTypedArrayTypeInt8Array +); +typed_array_new_shared!( + v8__Uint16Array__New__with_shared_buffer, + Uint16Array, + kJSTypedArrayTypeUint16Array +); +typed_array_new_shared!( + v8__Int16Array__New__with_shared_buffer, + Int16Array, + kJSTypedArrayTypeInt16Array +); +typed_array_new_shared!( + v8__Uint32Array__New__with_shared_buffer, + Uint32Array, + kJSTypedArrayTypeUint32Array +); +typed_array_new_shared!( + v8__Int32Array__New__with_shared_buffer, + Int32Array, + kJSTypedArrayTypeInt32Array +); +typed_array_new_shared!( + v8__Float32Array__New__with_shared_buffer, + Float32Array, + kJSTypedArrayTypeFloat32Array +); +typed_array_new_shared!( + v8__Float64Array__New__with_shared_buffer, + Float64Array, + kJSTypedArrayTypeFloat64Array +); +typed_array_new_shared!( + v8__BigInt64Array__New__with_shared_buffer, + BigInt64Array, + kJSTypedArrayTypeBigInt64Array +); +typed_array_new_shared!( + v8__BigUint64Array__New__with_shared_buffer, + BigUint64Array, + kJSTypedArrayTypeBigUint64Array +); + +#[unsafe(no_mangle)] +pub extern "C" fn v8__Float16Array__New__with_shared_buffer( + buf_ptr: *const SharedArrayBuffer, + byte_offset: usize, + length: usize, +) -> *const crate::Float16Array { + v8__Float16Array__New(buf_ptr as *const ArrayBuffer, byte_offset, length) +} + +#[unsafe(no_mangle)] +pub extern "C" fn v8__DataView__New__with_shared_buffer( + sab: *const SharedArrayBuffer, + byte_offset: usize, + length: usize, +) -> *const DataView { + v8__DataView__New(sab as *const ArrayBuffer, byte_offset, length) +} + +#[unsafe(no_mangle)] +pub extern "C" fn v8__SharedArrayBuffer__Data( + this: *const SharedArrayBuffer, +) -> *mut c_void { + let ctx = current_ctx(); + if ctx.is_null() || this.is_null() { + return ptr::null_mut(); + } + unsafe { + JSObjectGetArrayBufferBytesPtr( + ctx, + jsval(this) as JSObjectRef, + ptr::null_mut(), + ) + } +} + #[unsafe(no_mangle)] pub extern "C" fn v8__ArrayBuffer__SetDetachKey( _this: *const ArrayBuffer, @@ -1148,10 +1555,30 @@ pub extern "C" fn v8__SharedArrayBuffer__NewBackingStore__with_data( std::ptr::null_mut() } +/// `new SharedArrayBuffer(n)`: the C API can only make plain ArrayBuffers. #[unsafe(no_mangle)] pub extern "C" fn v8__SharedArrayBuffer__New__with_byte_length( - _isolate: *mut std::os::raw::c_void, - _byte_length: usize, -) -> *const std::os::raw::c_void { - std::ptr::null() + isolate: *mut RealIsolate, + byte_length: usize, +) -> *const SharedArrayBuffer { + if isolate.is_null() { + return ptr::null(); + } + let st = iso_state(isolate); + let ctx = + st.contexts.last().copied().unwrap_or(ptr::null_mut()) as JSContextRef; + if ctx.is_null() { + return ptr::null(); + } + let len = unsafe { JSValueMakeNumber(ctx, byte_length as f64) }; + match unsafe { + crate::jsc::core::call_js_fn( + ctx, + c"(function(n){return new SharedArrayBuffer(n)})", + &[len], + ) + } { + Ok(v) => intern_ctx::(ctx, v), + Err(_) => ptr::null(), + } } diff --git a/src/jsc/cli_extra.rs b/src/jsc/cli_extra.rs index b0bdcb12..b8a523de 100644 --- a/src/jsc/cli_extra.rs +++ b/src/jsc/cli_extra.rs @@ -67,6 +67,91 @@ pub extern "C" fn icu_get_default_locale( n } +// The default time zone lives in ICU, which JavaScriptCore consults for +// local time: both the system framework and the vendored build use Apple's +// libicucore, whose C API is exported without version suffixes. +#[link(name = "icucore")] +unsafe extern "C" { + fn ucal_getDefaultTimeZone( + result: *mut u16, + result_capacity: i32, + ec: *mut i32, + ) -> i32; + fn ucal_setDefaultTimeZone(zone_id: *const u16, ec: *mut i32); + fn ucal_getCanonicalTimeZoneID( + id: *const u16, + len: i32, + result: *mut u16, + result_capacity: i32, + is_system_id: *mut i8, + status: *mut i32, + ) -> i32; +} + +/// ICU's `U_FAILURE`: warnings are negative, errors positive. +fn icu_failed(status: i32) -> bool { + status > 0 +} + +#[unsafe(no_mangle)] +pub extern "C" fn icu_get_default_time_zone( + output: *mut c_char, + output_len: usize, +) -> usize { + let mut buf = [0u16; 128]; + let mut status = 0; + let n = unsafe { + ucal_getDefaultTimeZone(buf.as_mut_ptr(), buf.len() as i32, &mut status) + }; + if icu_failed(status) || n < 0 || output.is_null() { + return 0; + } + let id = String::from_utf16_lossy(&buf[..(n as usize).min(buf.len())]); + // Like ICU's `CheckedArrayByteSink`, write what fits and report that. + let len = id.len().min(output_len); + unsafe { + std::ptr::copy_nonoverlapping(id.as_ptr() as *const c_char, output, len) + }; + len +} + +/// Installs `time_zone_id` as ICU's default if ICU recognizes it. Like +/// rusty_v8's ICU binding, ICU's "unknown" zone counts as unrecognized. +#[unsafe(no_mangle)] +pub extern "C" fn icu_set_default_time_zone( + time_zone_id: *const c_char, +) -> bool { + if time_zone_id.is_null() { + return false; + } + let id = unsafe { std::ffi::CStr::from_ptr(time_zone_id) }.to_string_lossy(); + let mut units: Vec = id.encode_utf16().collect(); + let mut canonical = [0u16; 128]; + let mut is_system = 0i8; + let mut status = 0; + let n = unsafe { + ucal_getCanonicalTimeZoneID( + units.as_ptr(), + units.len() as i32, + canonical.as_mut_ptr(), + canonical.len() as i32, + &mut is_system, + &mut status, + ) + }; + if icu_failed(status) || n <= 0 { + return false; + } + let unknown: Vec = "Etc/Unknown".encode_utf16().collect(); + if canonical[..(n as usize).min(canonical.len())] == unknown[..] { + return false; + } + units.push(0); + let mut status = 0; + unsafe { ucal_setDefaultTimeZone(units.as_ptr(), &mut status) }; + !icu_failed(status) +} + #[unsafe(no_mangle)] pub extern "C" fn v8__Isolate__AddNearHeapLimitCallback( isolate: *mut c_void, diff --git a/src/jsc/core.rs b/src/jsc/core.rs index c8336fbe..f45ca940 100644 --- a/src/jsc/core.rs +++ b/src/jsc/core.rs @@ -38,6 +38,10 @@ pub(crate) struct GcCallbackEntry { pub(crate) struct IsoState { pub group: JSContextGroupRef, + /// Serializes the threads that use this isolate, for `v8::Locker`. Unused + /// until the embedder converts the isolate with `try_into_shared`. + pub lock: super::locker::IsolateLock, + pub contexts: Vec, pub owned_contexts: Vec, @@ -70,6 +74,11 @@ pub(crate) struct IsoState { pub gc_prologue_callbacks: Vec, pub gc_epilogue_callbacks: Vec, + + /// The canonical string for each distinct contents passed to + /// `String::InternalizeString`, protected until the isolate is disposed so + /// that internalizing equal strings always yields the same handle. + pub internalized: std::collections::HashMap, JSValueRef>, } thread_local! { @@ -330,11 +339,53 @@ pub(crate) fn peek_pending_exception(iso: *mut RealIsolate) -> JSValueRef { st.pending_exception.map(|(_, v)| v).unwrap_or(ptr::null()) } +/// Calls the JS function that `src` evaluates to with `args` in `ctx`. +/// +/// Returns `Err(exception)` if evaluating `src` or the call throws (the +/// exception may be null if JSC reported none), so callers can choose whether +/// to surface it as the isolate's pending exception. +pub(crate) unsafe fn call_js_fn( + ctx: JSContextRef, + src: &std::ffi::CStr, + args: &[JSValueRef], +) -> Result { + if ctx.is_null() { + return Err(ptr::null()); + } + unsafe { + let mut exc: JSValueRef = ptr::null(); + let s = JSStringCreateWithUTF8CString(src.as_ptr()); + let f = + JSEvaluateScript(ctx, s, ptr::null_mut(), ptr::null_mut(), 1, &mut exc); + JSStringRelease(s); + if !exc.is_null() || f.is_null() || !JSValueIsObject(ctx, f) { + return Err(exc); + } + let r = JSObjectCallAsFunction( + ctx, + f as JSObjectRef, + ptr::null_mut(), + args.len(), + if args.is_empty() { + ptr::null() + } else { + args.as_ptr() + }, + &mut exc, + ); + if !exc.is_null() || r.is_null() { + return Err(exc); + } + Ok(r) + } +} + #[unsafe(no_mangle)] pub extern "C" fn v8__Isolate__New(params: *const c_void) -> *mut RealIsolate { let group = unsafe { JSContextGroupCreate() }; let state = Box::new(IsoState { group, + lock: super::locker::IsolateLock::new(), contexts: Vec::new(), owned_contexts: Vec::new(), handles: Vec::new(), @@ -348,6 +399,7 @@ pub extern "C" fn v8__Isolate__New(params: *const c_void) -> *mut RealIsolate { weak_handles: Vec::new(), gc_prologue_callbacks: Vec::new(), gc_epilogue_callbacks: Vec::new(), + internalized: std::collections::HashMap::new(), }); let iso = Box::into_raw(state) as *mut RealIsolate; // Arm the execution-time-limit watchdog so `TerminateExecution` and the @@ -356,6 +408,78 @@ pub extern "C" fn v8__Isolate__New(params: *const c_void) -> *mut RealIsolate { iso } +// Isolate groups. V8 partitions isolates into groups that each own a pointer +// compression cage; JSC has no such cage, and every isolate here already owns +// its own `JSContextGroupRef`. So there is exactly one process-wide group, the +// default one, and V8's answer for a build without multi-cage pointer +// compression applies: `CanCreateNewGroups` is false. The `IsolateGroup` +// handle Rust holds is that group's address; it carries no reference count, +// so cloning and destroying it are free. + +static DEFAULT_ISOLATE_GROUP: u8 = 0; + +#[inline] +fn default_isolate_group() -> *const c_void { + &DEFAULT_ISOLATE_GROUP as *const u8 as *const c_void +} + +#[unsafe(no_mangle)] +pub extern "C" fn v8__IsolateGroup__GetDefault() -> *const c_void { + default_isolate_group() +} + +#[unsafe(no_mangle)] +pub extern "C" fn v8__IsolateGroup__CanCreateNewGroups() -> bool { + false +} + +/// Unreachable through rusty_v8, which checks `CanCreateNewGroups` first +/// because V8 aborts here. Answer with the only group there is. +#[unsafe(no_mangle)] +pub extern "C" fn v8__IsolateGroup__Create() -> *const c_void { + default_isolate_group() +} + +#[unsafe(no_mangle)] +pub extern "C" fn v8__IsolateGroup__CLONE( + this: *const *const c_void, +) -> *const c_void { + if this.is_null() { + return default_isolate_group(); + } + unsafe { *this } +} + +#[unsafe(no_mangle)] +pub extern "C" fn v8__IsolateGroup__DESTRUCT(_this: *mut *const c_void) {} + +#[unsafe(no_mangle)] +pub extern "C" fn v8__IsolateGroup__EQ( + this: *const *const c_void, + other: *const *const c_void, +) -> bool { + if this.is_null() || other.is_null() { + return this == other; + } + unsafe { *this == *other } +} + +#[unsafe(no_mangle)] +pub extern "C" fn v8__Isolate__GetGroup( + _isolate: *const RealIsolate, +) -> *const c_void { + default_isolate_group() +} + +/// Every isolate is in the default group, so this is `Isolate::New`. +#[unsafe(no_mangle)] +pub extern "C" fn v8__Isolate__NewInGroup( + _group: *const *const c_void, + params: *const c_void, +) -> *mut RealIsolate { + v8__Isolate__New(params) +} + /// Pull the configured max heap size out of a raw `CreateParams` pointer, if /// any. Layout (see `isolate_create_params::raw`): word 0 is the /// `code_event_handler` pointer, then `ResourceConstraints` whose second word @@ -402,6 +526,11 @@ pub extern "C" fn v8__Isolate__Dispose(this: *mut RealIsolate) { JSValueUnprotect(ctx, v); } } + if !st.base_ctx.is_null() { + for (_, v) in st.internalized.drain() { + JSValueUnprotect(st.base_ctx, v); + } + } for ctx in st.owned_contexts.drain(..) { JSGlobalContextRelease(ctx); } @@ -431,6 +560,17 @@ pub extern "C" fn v8__Isolate__GetCurrent() -> *mut RealIsolate { current_iso() } +/// Unlike `GetCurrent`, this reports only an isolate that is actually entered. +/// `current_iso` falls back to the last isolate this thread ran, which is what +/// callbacks arriving outside an Enter/Exit pair need, but `v8::Locker` uses +/// this to assert that no isolate is entered before it takes the lock, and +/// that fallback would make the assert fire on a thread that had merely used +/// an isolate earlier. +#[unsafe(no_mangle)] +pub extern "C" fn v8__Isolate__TryGetCurrent() -> *mut RealIsolate { + CURRENT_ISO.with(|c| *c.borrow()) +} + #[unsafe(no_mangle)] pub extern "C" fn v8__Isolate__GetNumberOfDataSlots( _this: *const RealIsolate, diff --git a/src/jsc/function.rs b/src/jsc/function.rs index 64338990..d207acf1 100644 --- a/src/jsc/function.rs +++ b/src/jsc/function.rs @@ -81,6 +81,10 @@ struct FnTemplate { constructable: bool, cached_proto: JSValueRef, + + /// `Template::SetNativeDataProperty` / `SetLazyDataProperty` entries, + /// installed on the function object. + natives: Vec, } struct TemplAccessor { @@ -95,6 +99,14 @@ struct ObjTemplate { props: Vec<(JSValueRef, JSValueRef, u32)>, accessors: Vec, + /// Set by `SetCallAsFunctionHandler`: instances of this template are + /// callable and invoke this callback with this data. + call_handler: Option<(FunctionCallback, JSValueRef)>, + + /// `Template::SetNativeDataProperty` / `SetLazyDataProperty` entries, + /// installed on each instance. + natives: Vec, + parent_fn: *const FnTemplate, } @@ -869,6 +881,568 @@ pub extern "C" fn v8__Template__Set( }); } +// --------------------------------------------------------------------------- +// Native data properties (`Template::SetNativeDataProperty`, +// `SetLazyDataProperty`, and the `Object` variants). +// +// V8 stores these as AccessorInfo and calls the embedder's getter on every +// read. JSC's C API has no accessor that calls back into C with the property +// name, so each one is installed as a JS accessor pair whose functions carry a +// `NativeBridge`. The getter builds a `PropCbInfo`, which is what the +// `v8__PropertyCallbackInfo__*` accessors below read. +// +// Without a setter, a write turns the property into an ordinary data property +// holding the written value, which is what V8 does by installing +// `Accessors::ReconfigureToDataProperty` as the default setter. A lazy data +// property does the same with the getter's result on first read. +// --------------------------------------------------------------------------- + +const ATTR_READ_ONLY: u32 = 1; +const ATTR_DONT_ENUM: u32 = 2; +const ATTR_DONT_DELETE: u32 = 4; + +#[derive(Clone, Copy)] +struct TemplNative { + key: JSValueRef, + getter: crate::AccessorNameGetterCallback, + setter: Option, + data: JSValueRef, + attr: u32, + lazy: bool, +} + +/// What a `PropertyCallbackInfo` pointer handed to a native accessor points +/// at. +#[repr(C)] +struct PropCbInfo { + isolate: *mut RealIsolate, + ctx: JSContextRef, + holder: JSValueRef, + data: JSValueRef, + return_slot: JSValueRef, +} + +struct NativeBridge { + native: TemplNative, + is_setter: bool, +} + +thread_local! { + static NATIVE_CLASS: std::cell::Cell = const { std::cell::Cell::new(ptr::null_mut()) }; +} + +fn native_class() -> JSClassRef { + NATIVE_CLASS.with(|c| { + let existing = c.get(); + if !existing.is_null() { + return existing; + } + let def = FnJSClassDefinition { + version: 0, + attributes: 0, + className: c"v8jsc_native_accessor".as_ptr(), + parentClass: ptr::null_mut(), + staticValues: ptr::null(), + staticFunctions: ptr::null(), + initialize: ptr::null(), + finalize: native_finalize as *const c_void, + hasProperty: ptr::null(), + getProperty: ptr::null(), + setProperty: ptr::null(), + deleteProperty: ptr::null(), + getPropertyNames: ptr::null(), + callAsFunction: native_trampoline as *const c_void, + callAsConstructor: ptr::null(), + hasInstance: ptr::null(), + convertToType: ptr::null(), + }; + let cls = + unsafe { JSClassCreate(&def as *const _ as *const JSClassDefinition) }; + c.set(cls); + cls + }) +} + +unsafe extern "C" fn native_finalize(object: JSObjectRef) { + crate::jsc::core::ffi_guard( + || { + let p = unsafe { JSObjectGetPrivate(object) } as *mut NativeBridge; + if !p.is_null() { + drop(unsafe { Box::from_raw(p) }); + } + }, + || (), + ) +} + +/// `Object.defineProperty(obj, key, {value, writable, enumerable, +/// configurable})` with the flags taken from a V8 `PropertyAttribute`. +unsafe fn define_data_property( + ctx: JSContextRef, + obj: JSValueRef, + key: JSValueRef, + value: JSValueRef, + attr: u32, +) -> Result { + unsafe { + let args = [ + obj, + key, + value, + JSValueMakeBoolean(ctx, attr & ATTR_READ_ONLY == 0), + JSValueMakeBoolean(ctx, attr & ATTR_DONT_ENUM == 0), + JSValueMakeBoolean(ctx, attr & ATTR_DONT_DELETE == 0), + ]; + crate::jsc::core::call_js_fn( + ctx, + c"(function(o,k,v,w,e,c){Object.defineProperty(o,k,\ + {value:v,writable:w,enumerable:e,configurable:c})})", + &args, + ) + } +} + +/// Hands a pending exception left by an embedder callback to JSC. +unsafe fn take_callback_exception( + iso: *mut RealIsolate, + out_exc: *mut JSValueRef, +) -> bool { + let pending = crate::jsc::core::peek_pending_exception(iso); + if pending.is_null() { + return false; + } + if !out_exc.is_null() { + unsafe { *out_exc = pending }; + } + crate::jsc::core::clear_pending_exception(iso); + true +} + +unsafe extern "C" fn native_trampoline( + ctx: JSContextRef, + function: JSObjectRef, + this_object: JSObjectRef, + argc: usize, + argv: *const JSValueRef, + exception: *mut JSValueRef, +) -> JSValueRef { + crate::jsc::core::ffi_guard( + || unsafe { + let undefined = JSValueMakeUndefined(ctx); + let bridge = JSObjectGetPrivate(function) as *const NativeBridge; + if bridge.is_null() { + return undefined; + } + let bridge = &*bridge; + let n = bridge.native; + let holder = if this_object.is_null() { + undefined + } else { + this_object as JSValueRef + }; + let iso = current_iso(); + let data = if n.data.is_null() { undefined } else { n.data }; + let key = intern_ctx::(ctx, n.key); + let Some(key) = std::ptr::NonNull::new(key as *mut crate::Name) else { + return undefined; + }; + if bridge.is_setter { + let value = if argc > 0 { *argv } else { undefined }; + match n.setter { + Some(setter) => { + crate::jsc::core::clear_pending_exception(iso); + let mut info = PropCbInfo { + isolate: iso, + ctx, + holder, + data, + return_slot: ptr::null(), + }; + let value = intern_ctx::(ctx, value); + if let Some(value) = std::ptr::NonNull::new(value as *mut Value) { + setter( + crate::SealedLocal(key), + crate::SealedLocal(value), + &mut info as *mut PropCbInfo + as *const crate::PropertyCallbackInfo<()>, + ); + } + take_callback_exception(iso, exception); + } + None if n.attr & ATTR_READ_ONLY == 0 && !this_object.is_null() => { + if let Err(exc) = + define_data_property(ctx, holder, n.key, value, n.attr) + && !exception.is_null() + { + *exception = exc; + } + } + None => {} + } + return undefined; + } + + crate::jsc::core::clear_pending_exception(iso); + let mut info = PropCbInfo { + isolate: iso, + ctx, + holder, + data, + return_slot: ptr::null(), + }; + (n.getter)( + crate::SealedLocal(key), + &mut info as *mut PropCbInfo + as *const crate::PropertyCallbackInfo, + ); + if take_callback_exception(iso, exception) { + return undefined; + } + let ret = if info.return_slot.is_null() { + undefined + } else { + info.return_slot + }; + if n.lazy + && !this_object.is_null() + && let Err(exc) = define_data_property(ctx, holder, n.key, ret, n.attr) + { + if !exception.is_null() { + *exception = exc; + } + return undefined; + } + ret + }, + || unsafe { panic_to_exception(ctx, exception) }, + ) +} + +/// Installs `n` on `obj` as an accessor pair. Returns false if JS refused the +/// definition (for example on a non-extensible object). +fn install_native( + ctx: JSContextRef, + obj: JSObjectRef, + n: &TemplNative, +) -> bool { + if ctx.is_null() || obj.is_null() || n.key.is_null() { + return false; + } + unsafe { + let gctx = JSContextGetGlobalContext(ctx); + JSValueProtect(gctx, n.key); + if !n.data.is_null() { + JSValueProtect(gctx, n.data); + } + let make = |is_setter: bool| { + let bridge = Box::new(NativeBridge { + native: *n, + is_setter, + }); + let f = + JSObjectMake(ctx, native_class(), Box::into_raw(bridge) as *mut c_void); + let fp = function_prototype(ctx); + if !fp.is_null() { + JSObjectSetPrototype(ctx, f, fp); + } + f as JSValueRef + }; + let getter = make(false); + let setter = make(true); + // Lazy properties and setter-less ones redefine themselves as data + // properties, which needs the accessor to stay configurable. + let configurable = + n.lazy || n.setter.is_none() || n.attr & ATTR_DONT_DELETE == 0; + let args = [ + obj as JSValueRef, + n.key, + getter, + setter, + JSValueMakeBoolean(ctx, n.attr & ATTR_DONT_ENUM == 0), + JSValueMakeBoolean(ctx, configurable), + ]; + crate::jsc::core::call_js_fn( + ctx, + c"(function(o,k,g,s,e,c){Object.defineProperty(o,k,\ + {get:g,set:s,enumerable:e,configurable:c})})", + &args, + ) + .is_ok() + } +} + +fn apply_natives(ctx: JSContextRef, obj: JSObjectRef, natives: &[TemplNative]) { + for n in natives { + install_native(ctx, obj, n); + } +} + +/// The `data` a native accessor reports: `undefined` when none was given, as +/// `PropertyCallbackArguments::data` requires a value. +fn native_data(data_or_null: *const Value) -> JSValueRef { + if !data_or_null.is_null() { + return jsval(data_or_null); + } + let ctx = crate::jsc::core::ensure_ctx(current_iso()); + if ctx.is_null() { + return ptr::null(); + } + unsafe { JSValueMakeUndefined(ctx) } +} + +fn push_template_native(this: *const c_void, native: TemplNative) { + if this.is_null() || native.key.is_null() { + return; + } + let p = this as usize; + match TEMPLATES.with(|t| t.borrow().get(&p).copied()) { + Some(TemplKind::Func) => { + unsafe { &mut *(p as *mut FnTemplate) }.natives.push(native) + } + Some(TemplKind::Obj) => unsafe { &mut *(p as *mut ObjTemplate) } + .natives + .push(native), + Some(TemplKind::Dict) | None => {} + } +} + +#[unsafe(no_mangle)] +pub extern "C" fn v8__Template__SetNativeDataProperty( + this: *const crate::Template, + key: *const Name, + getter: crate::AccessorNameGetterCallback, + setter: Option, + data_or_null: *const Value, + attr: PropertyAttribute, +) { + push_template_native( + this as *const c_void, + TemplNative { + key: jsval(key), + getter, + setter, + data: native_data(data_or_null), + attr: attr.as_u32_lenient(), + lazy: false, + }, + ); +} + +#[unsafe(no_mangle)] +pub extern "C" fn v8__Template__SetLazyDataProperty( + this: *const crate::Template, + key: *const Name, + getter: crate::AccessorNameGetterCallback, + data_or_null: *const Value, + attr: PropertyAttribute, +) { + push_template_native( + this as *const c_void, + TemplNative { + key: jsval(key), + getter, + setter: None, + data: native_data(data_or_null), + attr: attr.as_u32_lenient(), + lazy: true, + }, + ); +} + +/// Installs a native data property directly on an object, for +/// `Object::SetNativeDataProperty` (rusty_v8's `set_accessor`). +pub(crate) fn object_set_native( + context: *const Context, + obj: *const Object, + key: *const Name, + getter: crate::AccessorNameGetterCallback, + setter: Option, + data_or_null: *const Value, + attr: PropertyAttribute, +) -> bool { + object_install_native( + context, + obj, + TemplNative { + key: jsval(key), + getter, + setter, + data: native_data(data_or_null), + attr: attr.as_u32_lenient(), + lazy: false, + }, + ) +} + +/// Installs a lazy data property directly on an object, for +/// `Object::SetLazyDataProperty`. +pub(crate) fn object_set_lazy( + context: *const Context, + obj: *const Object, + key: *const Name, + getter: crate::AccessorNameGetterCallback, + data_or_null: *const Value, + attr: PropertyAttribute, +) -> bool { + object_install_native( + context, + obj, + TemplNative { + key: jsval(key), + getter, + setter: None, + data: native_data(data_or_null), + attr: attr.as_u32_lenient(), + lazy: true, + }, + ) +} + +fn object_install_native( + context: *const Context, + obj: *const Object, + native: TemplNative, +) -> bool { + let ctx = ctx_of(context) as JSContextRef; + if ctx.is_null() || obj.is_null() { + return false; + } + let o = jsval(obj); + if !unsafe { JSValueIsObject(ctx, o) } { + return false; + } + install_native(ctx, o as JSObjectRef, &native) +} + +// --------------------------------------------------------------------------- +// DictionaryTemplate: a fixed list of property names, instantiated with one +// value per name (a missing value leaves the property out). +// --------------------------------------------------------------------------- + +struct DictTemplate { + names: Vec, +} + +pub(crate) fn is_dictionary_template(p: *const c_void) -> bool { + !p.is_null() + && matches!( + TEMPLATES.with(|t| t.borrow().get(&(p as usize)).copied()), + Some(TemplKind::Dict) + ) +} + +#[unsafe(no_mangle)] +pub extern "C" fn v8__DictionaryTemplate__New( + _isolate: *mut RealIsolate, + names: *const *const c_char, + name_lengths: *const usize, + names_len: usize, +) -> *const c_void { + let mut out = Vec::with_capacity(names_len); + for i in 0..names_len { + let bytes = unsafe { + std::slice::from_raw_parts( + *names.add(i) as *const u8, + *name_lengths.add(i), + ) + }; + // An interior NUL cannot be a JS property name passed through the C API; + // V8 only accepts ASCII names here anyway. + out.push(std::ffi::CString::new(bytes).unwrap_or_default()); + } + let t = Box::into_raw(Box::new(DictTemplate { names: out })); + register_template(t as usize, TemplKind::Dict); + t as *const c_void +} + +#[unsafe(no_mangle)] +pub extern "C" fn v8__DictionaryTemplate__NewInstance( + this: *const c_void, + context: *const Context, + values: *const *const Value, + values_len: usize, +) -> *const Object { + let ctx = ctx_of(context) as JSContextRef; + if ctx.is_null() || !is_dictionary_template(this) { + return ptr::null(); + } + let t = unsafe { &*(this as *const DictTemplate) }; + let obj = unsafe { JSObjectMake(ctx, ptr::null_mut(), ptr::null_mut()) }; + for (i, name) in t.names.iter().enumerate().take(values_len) { + let v = unsafe { *values.add(i) }; + if v.is_null() { + continue; + } + unsafe { + let key = JSStringCreateWithUTF8CString(name.as_ptr()); + let mut exc: JSValueRef = ptr::null(); + JSObjectSetProperty(ctx, obj, key, jsval(v), 0, &mut exc); + JSStringRelease(key); + } + } + intern_ctx::(ctx, obj as JSValueRef) +} + +// --------------------------------------------------------------------------- +// FunctionTemplate::HasInstance +// --------------------------------------------------------------------------- + +/// Whether `v` was created from `tmpl` or a template that inherits from it. +/// +/// V8 answers from the object's map, which records the constructor's +/// template. JSC objects carry no such link, so this goes by the prototype +/// both construction paths give an instance: `new F()` and +/// `InstanceTemplate()->NewInstance()` set it to the template's cached +/// prototype object. An object whose prototype JS code set to that object by +/// hand is therefore also reported as an instance. +pub(crate) fn template_has_instance( + ctx: JSContextRef, + tmpl: *const FunctionTemplate, + v: JSValueRef, +) -> bool { + if ctx.is_null() || tmpl.is_null() || v.is_null() { + return false; + } + if !unsafe { JSValueIsObject(ctx, v) } { + return false; + } + let proto = unsafe { JSObjectGetPrototype(ctx, v as JSObjectRef) }; + if proto.is_null() { + return false; + } + let target = tmpl as *const FnTemplate; + TEMPLATES.with(|t| { + t.borrow().iter().any(|(&p, kind)| { + if !matches!(kind, TemplKind::Func) { + return false; + } + let f = unsafe { &*(p as *const FnTemplate) }; + if f.cached_proto.is_null() || f.cached_proto != proto { + return false; + } + // `f` built this object's prototype; it counts if `f` is `tmpl` or + // inherits from it. + let mut cur = p as *const FnTemplate; + while !cur.is_null() { + if cur == target { + return true; + } + cur = unsafe { (*cur).parent }; + } + false + }) + }) +} + +#[unsafe(no_mangle)] +pub extern "C" fn v8__FunctionTemplate__HasInstance( + this: *const FunctionTemplate, + object: *const Value, +) -> bool { + let ctx = current_ctx(); + template_has_instance(ctx, this, jsval(object)) +} + trait AttrU32 { fn as_u32_lenient(&self) -> u32; } @@ -887,6 +1461,7 @@ thread_local! { enum TemplKind { Func, Obj, + Dict, } fn register_template(p: usize, kind: TemplKind) { @@ -916,7 +1491,7 @@ fn with_template_props( let t = unsafe { &mut *(p as *mut ObjTemplate) }; f(&mut t.props); } - None => {} + Some(TemplKind::Dict) | None => {} } } @@ -945,12 +1520,16 @@ pub extern "C" fn v8__FunctionTemplate__New( internal_field_count: 0, props: Vec::new(), accessors: Vec::new(), + call_handler: None, + natives: Vec::new(), parent_fn: ptr::null(), })); let instance = Box::into_raw(Box::new(ObjTemplate { internal_field_count: 0, props: Vec::new(), accessors: Vec::new(), + call_handler: None, + natives: Vec::new(), parent_fn: ptr::null(), })); register_template(proto as usize, TemplKind::Obj); @@ -966,6 +1545,7 @@ pub extern "C" fn v8__FunctionTemplate__New( props: Vec::new(), constructable, cached_proto: ptr::null(), + natives: Vec::new(), })); unsafe { (*instance).parent_fn = t }; @@ -1003,6 +1583,7 @@ pub extern "C" fn v8__FunctionTemplate__GetFunction( } apply_props(ctx, f, &t.props); + apply_natives(ctx, f, &t.natives); if t.constructable { let proto_obj = @@ -1032,6 +1613,7 @@ unsafe fn build_prototype_object( apply_props(ctx, proto_obj, &proto.props); } apply_accessors(ctx, proto_obj, &proto.accessors); + apply_natives(ctx, proto_obj, &proto.natives); if !t.parent.is_null() { let parent_proto = unsafe { build_prototype_object(ctx, t.parent) }; @@ -1091,7 +1673,7 @@ fn materialize_template_value( ); if o.is_null() { value } else { jsval(o) } } - None => value, + Some(TemplKind::Dict) | None => value, } } @@ -1170,6 +1752,8 @@ pub extern "C" fn v8__ObjectTemplate__New( internal_field_count: 0, props: Vec::new(), accessors: Vec::new(), + call_handler: None, + natives: Vec::new(), parent_fn: ptr::null(), })); register_template(t as usize, TemplKind::Obj); @@ -1185,7 +1769,21 @@ pub extern "C" fn v8__ObjectTemplate__NewInstance( if ctx.is_null() { return ptr::null(); } - let obj = unsafe { JSObjectMake(ctx, ptr::null_mut(), ptr::null_mut()) }; + // A call handler makes the instance a function object. JSC cannot add a + // [[Call]] slot to an ordinary object after the fact, so the instance is + // built as one from the start; the property and accessor installation below + // is the same for both shapes. + let call_handler = if this.is_null() { + None + } else { + unsafe { &*(this as *const ObjTemplate) }.call_handler + }; + let obj = match call_handler { + Some((callback, data)) => unsafe { + make_function_len(ctx, callback, data, 0) + }, + None => unsafe { JSObjectMake(ctx, ptr::null_mut(), ptr::null_mut()) }, + }; if !this.is_null() { let t = unsafe { &*(this as *const ObjTemplate) }; @@ -1196,6 +1794,7 @@ pub extern "C" fn v8__ObjectTemplate__NewInstance( apply_props(ctx, obj, &t.props); apply_accessors(ctx, obj, &t.accessors); + apply_natives(ctx, obj, &t.natives); } intern_ctx::(ctx, obj as JSValueRef) } @@ -1391,25 +1990,39 @@ pub extern "C" fn v8__FunctionCallbackInfo__NewTarget( (unsafe { JSValueMakeUndefined(info.ctx) }) as *const Value } +#[inline] +fn prop_cbinfo<'a>(this: *const c_void) -> Option<&'a mut PropCbInfo> { + unsafe { (this as *mut PropCbInfo).as_mut() } +} + #[unsafe(no_mangle)] pub extern "C" fn v8__PropertyCallbackInfo__GetIsolate( - _this: *const c_void, + this: *const c_void, ) -> *mut RealIsolate { - crate::jsc::core::current_iso() + match prop_cbinfo(this) { + Some(info) if !info.isolate.is_null() => info.isolate, + _ => crate::jsc::core::current_iso(), + } } #[unsafe(no_mangle)] pub extern "C" fn v8__PropertyCallbackInfo__GetReturnValue( - _this: *const c_void, + this: *const c_void, ) -> usize { - 0 + match prop_cbinfo(this) { + Some(info) => (&mut info.return_slot as *mut JSValueRef) as usize, + None => 0, + } } #[unsafe(no_mangle)] pub extern "C" fn v8__PropertyCallbackInfo__Holder( - _this: *const c_void, + this: *const c_void, ) -> *const Object { - ptr::null() + match prop_cbinfo(this) { + Some(info) => intern_ctx::(info.ctx, info.holder), + None => ptr::null(), + } } #[unsafe(no_mangle)] @@ -1486,6 +2099,19 @@ pub extern "C" fn v8__ObjectTemplate__InternalFieldCount( 0 } +#[unsafe(no_mangle)] +pub extern "C" fn v8__ObjectTemplate__SetCallAsFunctionHandler( + this: *const std::os::raw::c_void, + callback: FunctionCallback, + data_or_null: *const Value, +) { + if this.is_null() { + return; + } + let t = unsafe { &mut *(this as *mut ObjTemplate) }; + t.call_handler = Some((callback, jsval(data_or_null))); +} + #[unsafe(no_mangle)] pub extern "C" fn v8__ObjectTemplate__SetImmutableProto( _this: *const std::os::raw::c_void, @@ -1494,20 +2120,31 @@ pub extern "C" fn v8__ObjectTemplate__SetImmutableProto( #[unsafe(no_mangle)] pub extern "C" fn v8__ObjectTemplate__SetNativeDataProperty( - _this: *const std::os::raw::c_void, - _key: *const std::os::raw::c_void, - _getter: *const std::os::raw::c_void, - _setter: *const std::os::raw::c_void, - _data_or_null: *const std::os::raw::c_void, - _attr: crate::PropertyAttribute, + this: *const ObjectTemplate, + key: *const Name, + getter: crate::AccessorNameGetterCallback, + setter: Option, + data_or_null: *const Value, + attr: PropertyAttribute, ) { + v8__Template__SetNativeDataProperty( + this as *const crate::Template, + key, + getter, + setter, + data_or_null, + attr, + ); } #[unsafe(no_mangle)] pub extern "C" fn v8__PropertyCallbackInfo__Data( - _this: *const std::os::raw::c_void, -) -> *const std::os::raw::c_void { - std::ptr::null() + this: *const c_void, +) -> *const Value { + match prop_cbinfo(this) { + Some(info) => intern_ctx::(info.ctx, info.data), + None => ptr::null(), + } } #[unsafe(no_mangle)] diff --git a/src/jsc/init.rs b/src/jsc/init.rs index 5c4012eb..1b8ad453 100644 --- a/src/jsc/init.rs +++ b/src/jsc/init.rs @@ -57,6 +57,17 @@ pub extern "C" fn v8__V8__InitializePlatform(_platform: *mut Platform) { #[unsafe(no_mangle)] pub extern "C" fn v8__V8__Initialize() {} +/// WebAssembly runs on the vendored WAMR interpreter here, which detects +/// out-of-bounds accesses with explicit bounds checks instead of guard pages, +/// so there is no trap handler to install. Report failure, which is what V8 +/// does on a build without trap-handler support. +#[unsafe(no_mangle)] +pub extern "C" fn v8__V8__EnableWebAssemblyTrapHandler( + _use_v8_signal_handler: bool, +) -> bool { + false +} + #[unsafe(no_mangle)] pub extern "C" fn v8__V8__Dispose() -> bool { if std::env::var_os("V82JSC_COMPILE_STATS").is_some() { diff --git a/src/jsc/inspector.rs b/src/jsc/inspector.rs index d96c54d9..12c74387 100644 --- a/src/jsc/inspector.rs +++ b/src/jsc/inspector.rs @@ -165,6 +165,187 @@ pub extern "C" fn v8_inspector__V8InspectorSession__cancelPauseOnNextStatement( ) { } +/// An owned `Runtime.RemoteObject`. V8 hands back an opaque C++ object that +/// serializes on demand; this backend serializes eagerly and carries the bytes, +/// which is all `toBytes` needs. +pub(crate) struct RemoteObjectBytes(Vec); + +/// Wraps `value` in a `Runtime.RemoteObject`. Objects get an `objectId` the +/// session can resolve again with `unwrapObject`, and stay alive until their +/// object group is released, as V8's injected script keeps them. +#[unsafe(no_mangle)] +pub extern "C" fn v8_inspector__V8InspectorSession__wrapObject( + session: *mut RawV8InspectorSession, + context: *const Context, + value: *const Value, + object_group: StringView, + _generate_preview: bool, +) -> *mut RemoteObjectBytes { + use crate::jsc::jsc_sys::*; + if value.is_null() { + return std::ptr::null_mut(); + } + let ctx = if context.is_null() { + crate::jsc::core::current_ctx() + } else { + crate::jsc::core::ctx_of(context) as JSContextRef + }; + let v = crate::jsc::core::jsval(value); + let ty = if ctx.is_null() { + "object" + } else { + match unsafe { JSValueGetType(ctx, v) } { + t if t == kJSTypeUndefined => "undefined", + t if t == kJSTypeBoolean => "boolean", + t if t == kJSTypeNumber => "number", + t if t == kJSTypeString => "string", + t if t == kJSTypeSymbol => "symbol", + t if t == kJSTypeBigInt => "bigint", + t if t == kJSTypeObject + && unsafe { JSObjectIsFunction(ctx, v as JSObjectRef) } => + { + "function" + } + _ => "object", + } + }; + let is_object = !ctx.is_null() + && unsafe { JSValueIsObject(ctx, v) } + && !unsafe { JSValueIsNull(ctx, v) }; + let json = if is_object && !session.is_null() { + let sess = unsafe { &mut *(session.cast::()) }; + unsafe { JSValueProtect(ctx, v) }; + let id = sess.add_remote_object(cdp::RemoteRef { + value: v, + context, + ctx, + group: string_view_to_utf16(&object_group), + }); + format!(r#"{{"type":"{ty}","objectId":"{id}"}}"#) + } else { + format!(r#"{{"type":"{ty}"}}"#) + }; + Box::into_raw(Box::new(RemoteObjectBytes(json.into_bytes()))) +} + +#[unsafe(no_mangle)] +pub extern "C" fn v8_inspector__V8InspectorSession__unwrapObject( + session: *mut RawV8InspectorSession, + error: *mut *mut StringBuffer, + object_id: StringView, + value: *mut *const Value, + context: *mut *const Context, + object_group: *mut *mut StringBuffer, +) -> bool { + let id = string_view_to_string(&object_id); + let found = if session.is_null() { + None + } else { + let sess = unsafe { &*(session.cast::()) }; + sess + .remote_object(&id) + .map(|r| (r.value, r.context, r.ctx, r.group.clone())) + }; + let Some((v, ctx_handle, ctx, group)) = found else { + if !error.is_null() { + let units: Vec = "Invalid remote object id".encode_utf16().collect(); + unsafe { *error = RealStringBuffer::boxed_from_utf16(units) }; + } + return false; + }; + unsafe { + if !value.is_null() { + *value = crate::jsc::core::intern_ctx::(ctx, v); + } + if !context.is_null() { + *context = ctx_handle; + } + if !object_group.is_null() { + *object_group = RealStringBuffer::boxed_from_utf16(group); + } + } + true +} + +#[unsafe(no_mangle)] +pub extern "C" fn v8_inspector__RemoteObject__DELETE( + this: *mut RemoteObjectBytes, +) { + if !this.is_null() { + drop(unsafe { Box::from_raw(this) }); + } +} + +#[unsafe(no_mangle)] +pub extern "C" fn v8_inspector__RemoteObject__toBytes( + this: *const RemoteObjectBytes, +) -> *mut crate::crdtp_shim::CppVecU8 { + let bytes = if this.is_null() { + Vec::new() + } else { + unsafe { &*this }.0.clone() + }; + Box::into_raw(Box::new(bytes)) +} + +#[unsafe(no_mangle)] +pub extern "C" fn v8_inspector__V8InspectorSession__releaseObjectGroup( + session: *mut RawV8InspectorSession, + object_group: StringView, +) { + if session.is_null() { + return; + } + let sess = unsafe { &mut *(session.cast::()) }; + for r in sess.release_group(&string_view_to_utf16(&object_group)) { + unsafe { crate::jsc::jsc_sys::JSValueUnprotect(r.ctx, r.value) }; + } +} + +unsafe extern "C" { + /// Defined by the vendored `inspector.rs`; releases the boxed Rust closure + /// an `Inspectable` was built from. + fn v8_inspector__V8InspectorSession__Inspectable__BASE__DROP( + rust_impl: *mut c_void, + ); +} + +/// Owns the Rust closure behind an `Inspectable` until it is deleted. +pub(crate) struct InspectableHandle(*mut c_void); + +#[unsafe(no_mangle)] +pub extern "C" fn v8_inspector__V8InspectorSession__Inspectable__NEW( + rust_impl: *mut c_void, +) -> *mut InspectableHandle { + Box::into_raw(Box::new(InspectableHandle(rust_impl))) +} + +#[unsafe(no_mangle)] +pub extern "C" fn v8_inspector__V8InspectorSession__Inspectable__DELETE( + inspectable: *mut InspectableHandle, +) { + if inspectable.is_null() { + return; + } + let handle = unsafe { Box::from_raw(inspectable) }; + if !handle.0.is_null() { + unsafe { + v8_inspector__V8InspectorSession__Inspectable__BASE__DROP(handle.0); + } + } +} + +#[unsafe(no_mangle)] +pub extern "C" fn v8_inspector__V8InspectorSession__addInspectedObject( + _session: *mut RawV8InspectorSession, + inspectable: *mut InspectableHandle, +) { + // V8 keeps the object so the console can reach it through `$0` to `$4`. This + // backend serves no console history, so nothing can ever dereference it. + // Ownership still transfers here, so release it rather than leak it. + v8_inspector__V8InspectorSession__Inspectable__DELETE(inspectable); +} + #[unsafe(no_mangle)] pub extern "C" fn v8_inspector__V8InspectorSession__canDispatchMethod( method: StringView, @@ -387,13 +568,55 @@ mod cdp { ); } + /// An object handed out by `wrapObject`, protected until its group is + /// released. Dropping the session does not unprotect: it may outlive the + /// context, and the values go away with the isolate's VM regardless. + pub struct RemoteRef { + pub value: crate::jsc::jsc_sys::JSValueRef, + pub context: *const crate::Context, + pub ctx: crate::jsc::jsc_sys::JSContextRef, + pub group: Vec, + } + pub struct CdpSession { channel: *mut RawChannel, + remote_objects: std::collections::HashMap, + next_object_id: u64, } impl CdpSession { pub fn new(channel: *mut RawChannel) -> Self { - CdpSession { channel } + CdpSession { + channel, + remote_objects: std::collections::HashMap::new(), + next_object_id: 1, + } + } + + /// Registers `r` and returns its `objectId`. The format follows V8's + /// `..`. + pub fn add_remote_object(&mut self, r: RemoteRef) -> String { + let id = format!("1.1.{}", self.next_object_id); + self.next_object_id += 1; + self.remote_objects.insert(id.clone(), r); + id + } + + pub fn remote_object(&self, id: &str) -> Option<&RemoteRef> { + self.remote_objects.get(id) + } + + pub fn release_group(&mut self, group: &[u16]) -> Vec { + let ids: Vec = self + .remote_objects + .iter() + .filter(|(_, r)| r.group == group) + .map(|(id, _)| id.clone()) + .collect(); + ids + .iter() + .filter_map(|id| self.remote_objects.remove(id)) + .collect() } } diff --git a/src/jsc/isolate.rs b/src/jsc/isolate.rs index 2fad2ed2..f8174411 100644 --- a/src/jsc/isolate.rs +++ b/src/jsc/isolate.rs @@ -101,6 +101,20 @@ pub extern "C" fn v8__Context__AllowCodeGenerationFromStrings( ) { } +/// JSC cannot detach a context's global proxy from its global object: the +/// two are created together and stay bound for the context's lifetime, so +/// the context keeps its global. +#[unsafe(no_mangle)] +pub extern "C" fn v8__Context__DetachGlobal(_this: *const Context) {} + +/// Temporal's `Temporal.Now` reads JSC's own clock; JSC offers no override. +#[unsafe(no_mangle)] +pub extern "C" fn v8__Context__SetTemporalHostSystemUTCEpochNanosecondsCallback( + _this: *const Context, + _callback: crate::context::TemporalHostSystemUTCEpochNanosecondsCallback, +) { +} + #[unsafe(no_mangle)] pub extern "C" fn v8__Context_IsCodeGenerationFromStringsAllowed( _this: *const Context, @@ -390,6 +404,27 @@ pub extern "C" fn v8__Isolate__SetIdle( ) { } +/// A GC heuristic hint in V8 (a disposed context usually leaves garbage). +/// JSC schedules its own collections and the hint has no equivalent. +#[unsafe(no_mangle)] +pub extern "C" fn v8__Isolate__ContextDisposedNotification( + _isolate: *mut RealIsolate, + _dependants: crate::isolate::ContextDependants, +) { +} + +/// Code generation from strings is always allowed on this backend +/// (`Context::AllowCodeGenerationFromStrings` is a no-op), and V8 only +/// consults this callback for a context where it is disallowed or when the +/// source is not a string. JSC's C API has no hook on `eval` / `Function` +/// compilation to call it from, so the callback is not consulted. +#[unsafe(no_mangle)] +pub extern "C" fn v8__Isolate__SetModifyCodeGenerationFromStringsCallback( + _isolate: *mut RealIsolate, + _callback: *const c_void, +) { +} + #[unsafe(no_mangle)] pub extern "C" fn v8__Isolate__HasPendingBackgroundTasks( _isolate: *const RealIsolate, @@ -707,20 +742,50 @@ pub extern "C" fn v8__Isolate__CreateParams__SIZEOF() -> usize { std::mem::size_of::() } +/// What a `MicrotaskQueue` pointer points at: microtasks run on JSC's own +/// per-VM queue, so all this records is the isolate the queue was made for. +struct QueueState { + isolate: *mut RealIsolate, +} + +/// Since rusty_v8 v152.0.0 the owning handle and the queue it points at are +/// separate types (`MicrotaskQueueHandle` owns, `MicrotaskQueue` is borrowed +/// from it). This backend keeps one allocation for both, so the handle is the +/// queue pointer and `Get` is the identity. #[unsafe(no_mangle)] -pub extern "C" fn v8__MicrotaskQueue__New( - _isolate: *mut RealIsolate, +pub extern "C" fn v8__MicrotaskQueueHandle__New( + isolate: *mut RealIsolate, _policy: MicrotasksPolicy, ) -> *mut MicrotaskQueue { - let b: Box = Box::new(0); - Box::into_raw(b) as *mut MicrotaskQueue + Box::into_raw(Box::new(QueueState { isolate })) as *mut MicrotaskQueue +} + +/// Only queues made by `MicrotaskQueueHandle::New` exist on this backend +/// (`Context::GetMicrotaskQueue` reports none), so a queue belongs to the +/// isolate it was created for. +#[unsafe(no_mangle)] +pub extern "C" fn v8__MicrotaskQueue__BelongsTo( + queue: *const MicrotaskQueue, + isolate: *mut RealIsolate, +) -> bool { + !queue.is_null() + && unsafe { (*(queue as *const QueueState)).isolate } == isolate +} + +#[unsafe(no_mangle)] +pub extern "C" fn v8__MicrotaskQueueHandle__Get( + handle: *const MicrotaskQueue, +) -> *mut MicrotaskQueue { + handle as *mut MicrotaskQueue } #[unsafe(no_mangle)] -pub extern "C" fn v8__MicrotaskQueue__DESTRUCT(queue: *mut MicrotaskQueue) { - if !queue.is_null() { +pub extern "C" fn v8__MicrotaskQueueHandle__DELETE( + handle: *mut MicrotaskQueue, +) { + if !handle.is_null() { unsafe { - drop(Box::from_raw(queue as *mut u8)); + drop(Box::from_raw(handle as *mut QueueState)); } } } diff --git a/src/jsc/locker.rs b/src/jsc/locker.rs new file mode 100644 index 00000000..6c9aef00 --- /dev/null +++ b/src/jsc/locker.rs @@ -0,0 +1,173 @@ +//! Family: Locker +//! +//! `v8::Locker` and `v8::Unlocker` over a JSC context group. +//! +//! JSC serializes its own heap access with the JSLock, so what this layer has +//! to add is the shape `v8::Locker` promises: one thread at a time owns the +//! isolate, other threads block until it lets go, and the shim's per-isolate +//! bookkeeping (the entered context, the handle list) belongs to whoever holds +//! it. A per-isolate mutex provides exactly that. +//! +//! `v8__Locker__IsLocked` sits on the `Global` clone, drop, hash and compare +//! paths, so the owning thread is published in an atomic and read without +//! taking the mutex. + +use std::sync::Condvar; +use std::sync::Mutex; +use std::sync::atomic::AtomicU64; +use std::sync::atomic::Ordering; + +use crate::isolate::RealIsolate; + +use super::core::iso_state; + +/// Identifies a thread by a small integer. `std::thread::ThreadId::as_u64` is +/// unstable, and a `u64` thread-local has no destructor, so reading this stays +/// valid even from a late TLS destructor where `LocalKey::with` would panic +/// for a droppable type. +fn thread_id() -> u64 { + static NEXT: AtomicU64 = AtomicU64::new(1); + thread_local! { + static ID: u64 = NEXT.fetch_add(1, Ordering::Relaxed); + } + ID.with(|id| *id) +} + +/// The isolate's lock. Zero in `owner` means unlocked; ids start at 1. +pub(crate) struct IsolateLock { + owner: Mutex, + released: Condvar, + /// `owner.tid` republished for lock-free reads. Written under `owner`. + owner_tid: AtomicU64, +} + +struct Owner { + tid: u64, + /// How many times the owner took the lock. `v8::Locker` is recursive in + /// C++, so the count is tracked even though the Rust wrapper rejects + /// recursive locking. + depth: usize, +} + +impl IsolateLock { + pub(crate) fn new() -> Self { + Self { + owner: Mutex::new(Owner { tid: 0, depth: 0 }), + released: Condvar::new(), + owner_tid: AtomicU64::new(0), + } + } + + fn acquire(&self) { + let me = thread_id(); + let mut owner = self.owner.lock().unwrap(); + while owner.tid != 0 && owner.tid != me { + owner = self.released.wait(owner).unwrap(); + } + owner.tid = me; + owner.depth += 1; + self.owner_tid.store(me, Ordering::Release); + } + + /// Give up one level of the lock. + fn release(&self) { + let mut owner = self.owner.lock().unwrap(); + owner.depth -= 1; + if owner.depth == 0 { + owner.tid = 0; + self.owner_tid.store(0, Ordering::Release); + self.released.notify_one(); + } + } + + /// Give up every level at once and report how many there were, for + /// `v8::Unlocker`, which releases the lock outright however deeply the + /// thread holds it. + fn release_all(&self) -> usize { + let mut owner = self.owner.lock().unwrap(); + let depth = owner.depth; + owner.depth = 0; + owner.tid = 0; + self.owner_tid.store(0, Ordering::Release); + self.released.notify_one(); + depth + } + + fn reacquire(&self, depth: usize) { + self.acquire(); + if depth > 1 { + let mut owner = self.owner.lock().unwrap(); + owner.depth = depth; + } + } + + fn held_by_current_thread(&self) -> bool { + self.owner_tid.load(Ordering::Acquire) == thread_id() + } +} + +fn lock_of<'a>(isolate: *mut RealIsolate) -> &'a IsolateLock { + &iso_state(isolate).lock +} + +/// `RawLocker` in `vendor/rusty_v8/src/locker.rs`: two words the Rust side +/// allocates and never reads. Slot 0 holds the isolate, slot 1 is unused. +#[repr(C)] +pub struct RawLocker([*mut RealIsolate; 2]); + +/// `RawUnlocker`: one word, holding the isolate its window belongs to. The +/// released depth rides on a thread-local stack instead, because unlock +/// windows are strictly nested per thread and one word cannot carry both. +#[repr(C)] +pub struct RawUnlocker([*mut RealIsolate; 1]); + +thread_local! { + static UNLOCK_DEPTHS: std::cell::RefCell> = + const { std::cell::RefCell::new(Vec::new()) }; +} + +#[unsafe(no_mangle)] +pub extern "C" fn v8__Locker__CONSTRUCT( + buf: *mut RawLocker, + isolate: *mut RealIsolate, +) { + lock_of(isolate).acquire(); + unsafe { (*buf).0 = [isolate, std::ptr::null_mut()] }; +} + +#[unsafe(no_mangle)] +pub extern "C" fn v8__Locker__DESTRUCT(this: *mut RawLocker) { + let isolate = unsafe { (*this).0[0] }; + if isolate.is_null() { + return; + } + lock_of(isolate).release(); +} + +#[unsafe(no_mangle)] +pub extern "C" fn v8__Locker__IsLocked(isolate: *const RealIsolate) -> bool { + if isolate.is_null() { + return false; + } + lock_of(isolate as *mut RealIsolate).held_by_current_thread() +} + +#[unsafe(no_mangle)] +pub extern "C" fn v8__Unlocker__CONSTRUCT( + buf: *mut RawUnlocker, + isolate: *mut RealIsolate, +) { + let depth = lock_of(isolate).release_all(); + UNLOCK_DEPTHS.with(|d| d.borrow_mut().push(depth)); + unsafe { (*buf).0 = [isolate] }; +} + +#[unsafe(no_mangle)] +pub extern "C" fn v8__Unlocker__DESTRUCT(this: *mut RawUnlocker) { + let isolate = unsafe { (*this).0[0] }; + if isolate.is_null() { + return; + } + let depth = UNLOCK_DEPTHS.with(|d| d.borrow_mut().pop()).unwrap_or(1); + lock_of(isolate).reacquire(depth); +} diff --git a/src/jsc/misc.rs b/src/jsc/misc.rs index 4c571e6d..bb817bae 100644 --- a/src/jsc/misc.rs +++ b/src/jsc/misc.rs @@ -505,6 +505,69 @@ pub extern "C" fn v8__Date__ValueOf(this: *const crate::Date) -> f64 { } } +/// `Date.parse` followed by `new Date`, which is what V8's `Date::Parse` does: +/// an unparsable string yields a Date whose time value is NaN. +#[unsafe(no_mangle)] +pub extern "C" fn v8__Date__Parse( + context: *const Context, + date_string: *const V8String, +) -> *const crate::Date { + if context.is_null() || date_string.is_null() { + return ptr::null(); + } + let ctx = ctx_of(context) as JSContextRef; + match unsafe { + crate::jsc::core::call_js_fn( + ctx, + c"(function(s){return new Date(Date.parse(s))})", + &[jsval(date_string)], + ) + } { + Ok(d) => intern_ctx::(ctx, d), + Err(exc) => { + crate::jsc::core::record_pending_exception(ctx, exc); + ptr::null() + } + } +} + +/// Runs one of the Date-to-string conversions V8 exposes as infallible. +/// `src` must not throw for a NaN date, which V8 formats as "Invalid Date". +fn date_to_string( + this: *const crate::Date, + src: &std::ffi::CStr, +) -> *const V8String { + let ctx = current_ctx(); + if ctx.is_null() || this.is_null() { + return ptr::null(); + } + match unsafe { crate::jsc::core::call_js_fn(ctx, src, &[jsval(this)]) } { + Ok(v) => intern_ctx::(ctx, v), + Err(_) => ptr::null(), + } +} + +#[unsafe(no_mangle)] +pub extern "C" fn v8__Date__ToISOString( + this: *const crate::Date, +) -> *const V8String { + date_to_string( + this, + c"(function(d){var t=Date.prototype.valueOf.call(d);\ + return t!==t?'Invalid Date':Date.prototype.toISOString.call(d)})", + ) +} + +#[unsafe(no_mangle)] +pub extern "C" fn v8__Date__ToUTCString( + this: *const crate::Date, +) -> *const V8String { + date_to_string( + this, + c"(function(d){return Date.prototype.toUTCString.call(d)})", + ) +} + #[unsafe(no_mangle)] pub extern "C" fn v8__Proxy__GetHandler(this: *const c_void) -> *const Value { // Native read of ProxyObject::handler() (introspect.cpp) — JSC's C API has @@ -620,7 +683,7 @@ pub extern "C" fn v8__StartupData__data__DELETE(_this: *const c_char) {} // must return `U_INVALID_FORMAT_ERROR`. No length crosses this C ABI, so we read // only the 4 header bytes every real caller is guaranteed to provide. #[unsafe(no_mangle)] -pub extern "C" fn udata_setCommonData_77( +pub extern "C" fn udata_setCommonData_78( data: *const u8, error_code: *mut i32, ) { diff --git a/src/jsc/mod.rs b/src/jsc/mod.rs index 890f1826..b55aff6e 100644 --- a/src/jsc/mod.rs +++ b/src/jsc/mod.rs @@ -11,6 +11,7 @@ pub(crate) mod inspector; pub(crate) mod introspect; pub(crate) mod isolate; pub(crate) mod jsc_sys; +pub(crate) mod locker; pub(crate) mod misc; pub(crate) mod module; pub(crate) mod object; diff --git a/src/jsc/module.rs b/src/jsc/module.rs index bb77a020..2bb0f7c0 100644 --- a/src/jsc/module.rs +++ b/src/jsc/module.rs @@ -990,6 +990,41 @@ pub extern "C" fn v8__Script__Compile( intern_ctx::