From 8eaf8050001a5eb71ae2bd6812b33dfa0ebaeb89 Mon Sep 17 00:00:00 2001 From: Jarred Sumner Date: Sun, 23 Aug 2026 22:11:07 +0000 Subject: [PATCH 01/11] napi: take the Node-API lifecycle code to safe Rust Every napi_* entry point is now a safe fn exported through a generated extern "C" thunk (HOST_EXPORT) whose parameter types spell the N-API pointer contract: Option<&NapiEnv> for a nullable env, Out = Option<&mut MaybeUninit> for out-parameters, Option> / Option<&T> for handles the addon keeps using, Option>> for handles it gives back. The C++ napi_env / handle-scope glue moves to bun_jsc::napi with `safe fn` declarations and is shared with bun:ffi. ThreadSafeFunction is thread-safe ref-counted: the JS side, the addon threads (while thread_count > 0), a queued dispatch task and the queued finalize task each hold one typed reference, so whoever lets go last frees it; JS-thread state lives in a JsCell and is released on the JS thread before the JS side's reference is dropped. Finalization is its own task tag instead of re-entering the dispatch drain. napi_async_work reaches the pool through bun_threading::SharedWorkTask (interior-mutable intrusive node, re-entered as a ThisPtr) and completes through a TaskHop; NapiFinalizerTask is a BoxedTask / owned cleanup hook. VmHandle gains post_hop / post_boxed (gated posts that cannot be refused after allocating), VirtualMachine gains event_loop_of(kind). The address-only C/C++ symbol lists for linker retention move to napi/link_symbols.rs. Also fixes a lost wake-up on bounded threadsafe-function queues: a slot opening now always signals one blocked producer, instead of only on the full -> not-full edge, which stranded the remaining waiters once the one woken producer had nothing more to push. --- src/codegen/generate-host-exports.ts | 40 +- src/event_loop/ConcurrentTask.rs | 100 +- src/event_loop/lib.rs | 2 +- src/jsc/JSGlobalObject.rs | 12 +- src/jsc/Napi.rs | 180 + src/jsc/VirtualMachine.rs | 13 + src/jsc/VmHandle.rs | 112 +- src/jsc/lib.rs | 3 + src/jsc/rare_data.rs | 22 + src/runtime/dispatch.rs | 63 +- src/runtime/ffi/ffi_body.rs | 31 +- src/runtime/napi/libc_check.rs | 45 +- src/runtime/napi/link_symbols.rs | 1882 +++++++ src/runtime/napi/mod.rs | 26 +- src/runtime/napi/napi_body.rs | 4993 ++++------------- src/threading/lib.rs | 4 +- src/threading/work_pool.rs | 63 + .../vm-thread-door.inventory.json | 5 +- .../source-lints/vm-thread-door.test.ts | 7 +- 19 files changed, 3635 insertions(+), 3968 deletions(-) create mode 100644 src/jsc/Napi.rs create mode 100644 src/runtime/napi/link_symbols.rs diff --git a/src/codegen/generate-host-exports.ts b/src/codegen/generate-host-exports.ts index 5448dfb9372b..ab53343731db 100644 --- a/src/codegen/generate-host-exports.ts +++ b/src/codegen/generate-host-exports.ts @@ -144,7 +144,18 @@ function ptrify(ty: string): { cTy: string; deref: (n: string) => string; extraL `{\n // SAFETY: C++ caller passes \`${n}_len\` live elements at \`${n}\` (or 0).\n unsafe { ::bun_core::ffi::slice(${n}, ${n}_len) }\n }`, }; } - // Other slice shapes (`&mut [T]`, `&'a [T]`) and `&str` are NOT FFI-safe; reject. + // `&mut [T]` — C passes `(T* name, size_t name_len)`; as above, writable. + const sliceMut = /^&\s*mut\s*\[\s*([^;]+?)\s*\]$/.exec(ty); + if (sliceMut) { + const elem = sliceMut[1].trim(); + return { + cTy: `*mut ${elem}`, + extraLen: true, + deref: n => + `{\n // SAFETY: C++ caller passes \`${n}_len\` live, exclusively borrowed elements at \`${n}\` (or 0).\n unsafe { ::bun_core::ffi::slice_mut(${n}, ${n}_len) }\n }`, + }; + } + // Other slice shapes (`&'a [T]`) and `&str` are NOT FFI-safe; reject. if (/^&[^\[]*\[/.test(ty) || /^&\s*str\b/.test(ty)) { throw new Error(`slice/str param \`${ty}\` is not FFI-safe; use \`&[T]\` (const) or (ptr, len)`); } @@ -564,6 +575,33 @@ const importCandidates: Array<[string, string]> = [ ["crate::bake::dev_server::inspector_agent", "InspectorBunFrontendDevServerAgentHandle"], ["bun_jsc::debugger", "LifecycleHandle"], ["bun_jsc::debugger", "TestReporterHandle"], + ["core::mem", "ManuallyDrop"], + ["core::mem", "MaybeUninit"], + ["bun_ptr", "ThisPtr"], + ["bun_jsc", "JSPromiseStrong"], + ["bun_jsc", "NapiEnv"], + ["bun_jsc", "NapiHandleScope"], + // Node-API ABI types (`crate::napi`'s exported entry points). + ...[ + "Out", + "ThreadSafeFunction", + "char16_t", + "napi_async_complete_callback", + "napi_async_execute_callback", + "napi_async_work", + "napi_deferred", + "napi_escapable_handle_scope", + "napi_event_loop", + "napi_finalize", + "napi_handle_scope", + "napi_node_version", + "napi_status", + "napi_threadsafe_function_call_js", + "napi_threadsafe_function_call_mode", + "napi_threadsafe_function_release_mode", + "napi_typedarray_type", + "napi_value", + ].map(n => ["crate::napi::napi_body", n] as [string, string]), ]; const importLines: string[] = []; for (const [modPath, name] of importCandidates) { diff --git a/src/event_loop/ConcurrentTask.rs b/src/event_loop/ConcurrentTask.rs index 245c9500ea3c..caa44b69fcc3 100644 --- a/src/event_loop/ConcurrentTask.rs +++ b/src/event_loop/ConcurrentTask.rs @@ -119,6 +119,7 @@ pub mod task_tag { ShellAsyncCpTask, StreamPending, ThreadSafeFunction, + ThreadSafeFunctionFinalize, ValkeyDeferredClose, WindowsNamedPipeContext, Write, @@ -164,6 +165,98 @@ pub trait Taskable { unsafe fn release_unrun(this: *mut Self); } +/// A task whose queued pointer is a [`ThisPtr`](bun_ptr::ThisPtr) to +/// `Target`, which keeps itself alive for the task; the dispatcher runs it or +/// releases it through here. A zero-sized hop type per tag, declared with +/// [`task_hop!`] next to `Target` so the ref protocol lives there. +/// +/// # Safety +/// `TAG` is dispatched (in `bun_runtime::dispatch`) to this impl and no other +/// task type uses it; and `Target`'s protocol keeps the pointee of every +/// [`task`](Self::task) it queues alive until `run` / `release_unrun` (a +/// `RefPtr` slot held for the queued task, or an owner that outlives the queue). +pub unsafe trait TaskHop { + type Target; + /// The tag constant from [`task_tag`]; the `bun_runtime::dispatch` match + /// arms MUST agree. + const TAG: TaskTag; + fn run(this: bun_ptr::ThisPtr) -> crate::JsResult<()>; + /// As [`Taskable::release_unrun`]. + fn release_unrun(this: bun_ptr::ThisPtr); + + #[inline] + fn task(this: bun_ptr::ThisPtr) -> Task { + Task::new(Self::TAG, this.as_ptr().cast::<()>()) + } +} + +/// Declares `$hop`, the [`TaskHop`] that `task_tag::$tag` dispatches to for +/// `$target`, forwarding to `$run` / `$release`. The doc comment on the +/// invocation is where `$target`'s liveness protocol for the queued task is +/// stated. +#[macro_export] +macro_rules! task_hop { + ($(#[$m:meta])* $v:vis $hop:ident for $target:ty => $tag:ident; run = $run:expr; release_unrun = $release:expr $(;)?) => { + $(#[$m])* + $v struct $hop; + // SAFETY: see macro doc — one hop per tag; the invoker documents the liveness protocol. + unsafe impl $crate::TaskHop for $hop { + type Target = $target; + const TAG: $crate::TaskTag = $crate::task_tag::$tag; + #[inline] + fn run(this: ::bun_ptr::ThisPtr<$target>) -> $crate::JsResult<()> { + ($run)(this) + } + #[inline] + fn release_unrun(this: ::bun_ptr::ThisPtr<$target>) { + ($release)(this) + } + } + }; +} + +/// A task that owns its payload: queued as the `Box` leaked into +/// [`Task::ptr`], handed back as that box when the dispatcher runs or +/// releases it. Implement via [`boxed_task!`]. +/// +/// # Safety +/// `TAG` is dispatched (in `bun_runtime::dispatch`) to this impl and no other +/// task type uses it, so the dispatcher's `Box::::from_raw` gets back +/// what [`into_task`](Self::into_task) leaked. +pub unsafe trait BoxedTask: Sized { + /// The tag constant from [`task_tag`]; the `bun_runtime::dispatch` match + /// arms MUST agree. + const TAG: TaskTag; + fn run(self: Box) -> crate::JsResult<()>; + /// As [`Taskable::release_unrun`]. + fn release_unrun(self: Box); + + #[inline] + fn into_task(self: Box) -> Task { + Task::new(Self::TAG, Box::into_raw(self).cast::<()>()) + } +} + +/// Implements [`BoxedTask`] for `$ty` as the task `task_tag::$tag` dispatches +/// to, forwarding to `$run` / `$release` (each `fn(Box<$ty>)`). +#[macro_export] +macro_rules! boxed_task { + ($ty:ty => $tag:ident; run = $run:expr; release_unrun = $release:expr $(;)?) => { + // SAFETY: see macro doc — one boxed task type per tag. + unsafe impl $crate::BoxedTask for $ty { + const TAG: $crate::TaskTag = $crate::task_tag::$tag; + #[inline] + fn run(self: ::std::boxed::Box) -> $crate::JsResult<()> { + ($run)(self) + } + #[inline] + fn release_unrun(self: ::std::boxed::Box) { + ($release)(self) + } + } + }; +} + impl TaskTag { /// The tag's identifier, for diagnostics. pub fn name(self) -> &'static str { @@ -302,9 +395,14 @@ impl ConcurrentTask { of: *mut T, auto_deinit: AutoDeinit, ) -> &mut ConcurrentTask { + self.from_task(Task::init(of), auto_deinit) + } + + /// Load this (intrusive) carrier with `task`, ready to post. + pub fn from_task(&mut self, task: Task, auto_deinit: AutoDeinit) -> &mut ConcurrentTask { bun_core::mark_binding!(); *self = ConcurrentTask { - task: Task::init(of), + task, next: Link::new(), auto_delete: auto_deinit == AutoDeinit::AutoDeinit, }; diff --git a/src/event_loop/lib.rs b/src/event_loop/lib.rs index 9a0be447363f..0bcc34362dc6 100644 --- a/src/event_loop/lib.rs +++ b/src/event_loop/lib.rs @@ -29,7 +29,7 @@ pub mod any_event_loop; // ─── public surface ───────────────────────────────────────────────────────── pub type JsResult = core::result::Result; -pub use ConcurrentTask::{Task, TaskTag, Taskable, task_tag}; +pub use ConcurrentTask::{BoxedTask, Task, TaskHop, TaskTag, Taskable, task_tag}; // snake_case alias for the file-level-struct module so higher tiers avoid // the type/module namespace collision on the PascalCase form. diff --git a/src/jsc/JSGlobalObject.rs b/src/jsc/JSGlobalObject.rs index 11115339f3f0..e7c1f7d0cbc2 100644 --- a/src/jsc/JSGlobalObject.rs +++ b/src/jsc/JSGlobalObject.rs @@ -1158,12 +1158,10 @@ impl JSGlobalObject { }) } - /// Returns a freshly-created `napi_env` owned by this global, for use by - /// the FFI module. The concrete `NapiEnv` struct lives in `bun_runtime` - /// (which depends on `bun_jsc`), so this returns the raw pointer untyped; - /// callers in `bun_runtime` cast to `*mut NapiEnv`. - pub fn make_napi_env_for_ffi(&self) -> *mut c_void { - ZigGlobalObject__makeNapiEnvForFFI(self) + /// A freshly-created `napi_env` owned by this global (it lives as long as + /// the global does), for use by the FFI module. + pub fn make_napi_env_for_ffi(&self) -> &crate::NapiEnv { + crate::NapiEnv::opaque_ref(ZigGlobalObject__makeNapiEnvForFFI(self)) } // returns false if it throws @@ -1568,7 +1566,7 @@ unsafe extern "C" { safe fn ZigGlobalObject__readableStreamToBlob(this: &JSGlobalObject, value: JSValue) -> JSValue; - safe fn ZigGlobalObject__makeNapiEnvForFFI(this: &JSGlobalObject) -> *mut c_void; + safe fn ZigGlobalObject__makeNapiEnvForFFI(this: &JSGlobalObject) -> *mut crate::NapiEnv; safe fn JSC__JSGlobalObject__bunVM(this: &JSGlobalObject) -> *mut c_void; safe fn JSC__JSGlobalObject__vm(this: &JSGlobalObject) -> *mut VM; diff --git a/src/jsc/Napi.rs b/src/jsc/Napi.rs new file mode 100644 index 000000000000..fc75bd380540 --- /dev/null +++ b/src/jsc/Napi.rs @@ -0,0 +1,180 @@ +//! FFI glue for the C++ Node-API objects (`src/jsc/bindings/napi.h`, +//! `napi_handle_scope.h`): the `napi_env` handle, handle scopes and the +//! `NapiUngatedScope`. The Node-API implementation itself is `bun_runtime::napi`. + +use core::mem::MaybeUninit; + +use crate::{JSGlobalObject, JSValue, VmHandle, vm_handle}; + +bun_opaque::opaque_ffi! { + /// `struct napi_env__` (napi.h `NapiEnv`): C++-owned and `WTF::RefCounted`. + /// C++ mutates it (last error, handle-scope stack) through pointers derived + /// from `&self`, which the opaque body permits. + pub struct NapiEnv; + /// napi_handle_scope.h `NapiHandleScopeImpl`. + pub struct NapiHandleScope; +} + +#[allow(improper_ctypes)] // `vm_handle::Shared` is opaque to C++ (`BunVmHandleRef`) +unsafe extern "C" { + safe fn NapiEnv__globalObject(env: &NapiEnv) -> *mut JSGlobalObject; + safe fn NapiEnv__getAndClearPendingException(env: &NapiEnv, out: &mut JSValue) -> bool; + safe fn NapiEnv__hasPendingException(env: &NapiEnv) -> bool; + safe fn NapiEnv__ref(env: &NapiEnv); + safe fn NapiEnv__deref(env: &NapiEnv); + /// The reference to its VM's handle the env holds (`BunVmHandleRef`). + safe fn NapiEnv__vmHandle(env: &NapiEnv) -> *const vm_handle::Shared; + safe fn NapiUngatedScope__construct(storage: &mut MaybeUninit, env: &NapiEnv); + fn NapiUngatedScope__destruct(storage: &mut UngatedScope); +} + +// `bun_runtime::ffi` hands these two addresses to TinyCC. +#[allow(clashing_extern_declarations)] +unsafe extern "C" { + pub safe fn NapiHandleScope__open(env: &NapiEnv, escapable: bool) -> *mut NapiHandleScope; + pub safe fn NapiHandleScope__close(env: &NapiEnv, current: Option<&NapiHandleScope>); + safe fn NapiHandleScope__append(env: &NapiEnv, value: JSValue); + safe fn NapiHandleScope__escape(handle_scope: &NapiHandleScope, value: JSValue) -> bool; +} + +impl NapiEnv { + #[inline] + pub fn to_js(&self) -> &JSGlobalObject { + JSGlobalObject::opaque_ref(NapiEnv__globalObject(self)) + } + + /// Any thread holding an env ref: (a clone of) the env's VM handle. + pub fn vm_handle(&self) -> VmHandle { + // SAFETY: the env holds this reference for its whole lifetime, which `&self` is within. + (*unsafe { VmHandle::borrow_ref(NapiEnv__vmHandle(self)) }).clone() + } + + /// Checks both `env->m_pendingException` (set by `napi_throw*`) and the JSC + /// VM exception slot. This is the gate Node.js's `NAPI_PREAMBLE` enforces. + #[inline] + pub fn has_pending_exception(&self) -> bool { + NapiEnv__hasPendingException(self) + } + + pub fn get_and_clear_pending_exception(&self) -> Option { + let mut exception = JSValue::ZERO; + NapiEnv__getAndClearPendingException(self, &mut exception).then_some(exception) + } + + /// One more reference on this env (JS thread: the C++ count is not atomic). + #[inline] + pub fn to_ref(&self) -> NapiEnvRef { + // SAFETY: `&NapiEnv` only ever refers to a live C++ `napi_env`. + unsafe { NapiEnvRef::clone_from_raw(self.as_mut_ptr()) } + } +} + +// SAFETY: the count is the C++ `WTF::RefCounted` one; the env stays alive +// while it is > 0, and a `NapiEnv` is only ever seen by reference to one. +unsafe impl bun_ptr::ExternalSharedDescriptor for NapiEnv { + unsafe fn ext_ref(this: *mut Self) { + NapiEnv__ref(Self::opaque_ref(this)) + } + unsafe fn ext_deref(this: *mut Self) { + NapiEnv__deref(Self::opaque_ref(this)) + } +} + +/// A counted reference to a `napi_env` (`Ref`). +pub type NapiEnvRef = bun_ptr::ExternalShared; + +#[derive(Debug, thiserror::Error, strum::IntoStaticStr)] +pub enum EscapeError { + #[error("escape called twice")] + EscapeCalledTwice, +} + +impl NapiHandleScope { + /// Create a new handle scope in the given environment, or return null if + /// creating one now is unsafe (i.e. inside a finalizer). + #[inline] + pub fn open(env: &NapiEnv, escapable: bool) -> *mut NapiHandleScope { + NapiHandleScope__open(env, escapable) + } + + /// Closes the given handle scope, releasing all values inside it, if it is + /// safe to do so. Asserts that `scope` is the current handle scope in env. + #[inline] + pub fn close(scope: Option<&NapiHandleScope>, env: &NapiEnv) { + NapiHandleScope__close(env, scope) + } + + /// Place a value in the handle scope. Must be done while returning any JS + /// value into NAPI callbacks, as the value must remain alive as long as the + /// handle scope is active, even if the native module doesn't keep it + /// visible on the stack. + #[inline] + pub fn append(env: &NapiEnv, value: JSValue) { + NapiHandleScope__append(env, value) + } + + /// Move a value from the current handle scope (which must be escapable) to + /// the reserved escape slot in the parent handle scope, allowing that + /// value to outlive the current handle scope. + pub fn escape(&self, value: JSValue) -> Result<(), EscapeError> { + if NapiHandleScope__escape(self, value) { + Ok(()) + } else { + Err(EscapeError::EscapeCalledTwice) + } + } + + /// Open a non-escapable handle scope that closes when the guard drops. If + /// opening returns null (inside a finalizer), the guard's `Drop` is a no-op. + #[must_use] + pub fn open_scoped(env: &NapiEnv) -> NapiHandleScopeGuard<'_> { + NapiHandleScopeGuard { + scope: Self::open(env, false), + env, + } + } +} + +/// RAII guard for [`NapiHandleScope::open`] / [`NapiHandleScope::close`]. +pub struct NapiHandleScopeGuard<'a> { + scope: *mut NapiHandleScope, + env: &'a NapiEnv, +} + +impl Drop for NapiHandleScopeGuard<'_> { + fn drop(&mut self) { + if !self.scope.is_null() { + NapiHandleScope::close(Some(NapiHandleScope::opaque_ref(self.scope)), self.env); + } + } +} + +/// napi.cpp's `NapiUngatedScope` (see the comment there), constructed in +/// place in caller-provided storage by [`UngatedScope::enter`]. +#[repr(C, align(8))] +pub struct UngatedScope([MaybeUninit; 80]); + +/// Destroys the [`UngatedScope`] it was returned for. +pub struct UngatedScopeGuard<'a>(&'a mut UngatedScope); + +impl UngatedScope { + /// The rest of the caller's frame runs with no JS or addon code (traps + /// deferred, a pending exception suspended). + #[inline] + pub fn enter<'a>( + storage: &'a mut MaybeUninit, + env: &NapiEnv, + ) -> UngatedScopeGuard<'a> { + NapiUngatedScope__construct(storage, env); + // SAFETY: constructed just above; napi.cpp static_asserts the C++ object fits. + UngatedScopeGuard(unsafe { storage.assume_init_mut() }) + } +} + +impl Drop for UngatedScopeGuard<'_> { + #[inline] + fn drop(&mut self) { + // SAFETY: a guard only exists for storage `enter` constructed; destroyed once, here. + unsafe { NapiUngatedScope__destruct(self.0) }; + } +} diff --git a/src/jsc/VirtualMachine.rs b/src/jsc/VirtualMachine.rs index 9c913d8f135b..aa7653cc8dc2 100644 --- a/src/jsc/VirtualMachine.rs +++ b/src/jsc/VirtualMachine.rs @@ -932,6 +932,19 @@ impl VirtualMachine { unsafe { &mut *self.event_loop } } + /// [`Self::event_loop_mut`] for the loop of the given kind rather than the + /// current one (what an off-thread completion recorded with + /// [`Self::current_loop_kind`]). Same single-JS-thread contract. + #[inline] + #[allow(clippy::mut_from_ref)] + pub fn event_loop_of(&self, kind: crate::LoopKind) -> &mut EventLoop { + let vm = self.as_mut(); + match kind { + crate::LoopKind::Regular => &mut vm.regular_event_loop, + crate::LoopKind::Macro => &mut vm.macro_event_loop, + } + } + /// Safe `&EventLoop` accessor — shared variant of [`Self::event_loop_mut`]. /// Prefer when only reading event-loop fields (queue lengths, pending /// refs) to avoid minting an unnecessary `&mut`. diff --git a/src/jsc/VmHandle.rs b/src/jsc/VmHandle.rs index 8b767f90b8a7..37fd749c5818 100644 --- a/src/jsc/VmHandle.rs +++ b/src/jsc/VmHandle.rs @@ -335,13 +335,68 @@ impl VmHandle { /// the VM is closed. For posters that hold no ticket (their payload is /// their own to free on refusal). pub fn post(&self, kind: LoopKind, task: NonNull) -> Posted { - test_gate::weak_post(&self.0, task, |task| { - let Some(_a) = self.enter() else { - return Posted::Refused(task); - }; - self.0.deliver(kind, task); + // SAFETY: handed over by the caller and not yet queued anywhere. + let tag = || unsafe { task.as_ref() }.task.tag; + if self.post_with(tag, |s| s.deliver(kind, task)) { Posted::Queued - }) + } else { + Posted::Refused(task) + } + } + + /// The weak-post gate: `deliver` runs iff the VM is not closed (and then + /// inside the gate, so the close waits for it). Whether it ran. `tag` is + /// only for the debug build's late-post report. + fn post_with( + &self, + tag: impl FnOnce() -> bun_event_loop::TaskTag, + deliver: impl FnOnce(&Shared), + ) -> bool { + test_gate::before_weak_post(&self.0); + let queued = match self.enter() { + Some(_a) => { + deliver(&self.0); + true + } + None => false, + }; + test_gate::after_weak_post(&self.0, tag, queued); + queued + } + + /// Queue `H`'s hop for `this` on the VM's `kind` loop and wake it. `false` + /// if the VM is closed: nothing was queued, and whatever the hop would have + /// carried is still the caller's. + pub fn post_hop( + &self, + kind: LoopKind, + this: bun_ptr::ThisPtr, + ) -> bool { + self.post_with( + || H::TAG, + |s| s.deliver(kind, ConcurrentTaskItem::create(H::task(this))), + ) + } + + /// Queue a [`BoxedTask`](bun_event_loop::BoxedTask) on the VM's `kind` + /// loop and wake it, or hand it back if the VM is closed. + pub fn post_boxed( + &self, + kind: LoopKind, + task: Box, + ) -> Result<(), Box> { + let mut task = Some(task); + self.post_with( + || T::TAG, + |s| { + let task = task.take().expect("posted once").into_task(); + s.deliver(kind, ConcurrentTaskItem::create(task)); + }, + ); + match task { + None => Ok(()), + Some(task) => Err(task), + } } /// Queue a C++ `EventLoopTask` on the VM's `kind` loop from another @@ -543,8 +598,7 @@ pub extern "C" fn Bun__VM__currentLoopKind(vm: &VirtualMachine) -> LoopKind { // under the gate, not in production. #[cfg(debug_assertions)] mod test_gate { - use super::{Ordering, Posted, Shared, State, Ticket, VmHandle}; - type Task = core::ptr::NonNull; + use super::{Ordering, Shared, State, Ticket, VmHandle}; impl VmHandle { pub(crate) fn arm_test_gate(&self) { @@ -592,20 +646,24 @@ mod test_gate { )); } } - pub(super) fn weak_post(s: &Shared, task: Task, post: impl FnOnce(Task) -> Posted) -> Posted { - if !armed(s) { - return post(task); + pub(super) fn before_weak_post(s: &Shared) { + if armed(s) { + park_until_draining(s); + } + } + pub(super) fn after_weak_post( + s: &Shared, + tag: impl FnOnce() -> bun_event_loop::TaskTag, + queued: bool, + ) { + if armed(s) { + let outcome = if queued { + "released by the wait" + } else { + "refused" + }; + say(format_args!("late post: {} ({outcome})", tag().name())); } - park_until_draining(s); - // SAFETY: handed over by the caller and not yet queued anywhere. - let tag = unsafe { task.as_ref() }.task.tag; - let r = post(task); - let outcome = match r { - Posted::Queued => "released by the wait", - Posted::Refused(_) => "refused", - }; - say(format_args!("late post: {} ({outcome})", tag.name())); - r } /// The wait began: parked posts go now. pub(super) fn draining(h: &VmHandle) { @@ -621,8 +679,7 @@ mod test_gate { } #[cfg(not(debug_assertions))] mod test_gate { - use super::{Posted, Shared, Ticket, VmHandle}; - type Task = core::ptr::NonNull; + use super::{Shared, Ticket, VmHandle}; impl VmHandle { #[inline(always)] pub(crate) fn arm_test_gate(&self) {} @@ -630,8 +687,13 @@ mod test_gate { #[inline(always)] pub(super) fn before_ticket_post(_: &Ticket) {} #[inline(always)] - pub(super) fn weak_post(_: &Shared, task: Task, post: impl FnOnce(Task) -> Posted) -> Posted { - post(task) + pub(super) fn before_weak_post(_: &Shared) {} + #[inline(always)] + pub(super) fn after_weak_post( + _: &Shared, + _: impl FnOnce() -> bun_event_loop::TaskTag, + _: bool, + ) { } #[inline(always)] pub(super) fn draining(_: &VmHandle) {} diff --git a/src/jsc/lib.rs b/src/jsc/lib.rs index 03faa8dec0e7..8da15550a627 100644 --- a/src/jsc/lib.rs +++ b/src/jsc/lib.rs @@ -1190,10 +1190,13 @@ pub use self::saved_source_map as SavedSourceMap; // (`VirtualMachine`, `ModuleLoader`, `EventLoop`, `VirtualMachineInitOptions`) // are preserved. // ────────────────────────────────────────────────────────────────────────── +#[path = "Napi.rs"] +pub mod napi; #[path = "VirtualMachine.rs"] pub mod virtual_machine; #[path = "VmHandle.rs"] pub mod vm_handle; +pub use self::napi::{NapiEnv, NapiEnvRef, NapiHandleScope}; pub use self::virtual_machine as VirtualMachine; pub use self::virtual_machine::InitOptions as VirtualMachineInitOptions; pub use self::vm_handle::{ConcurrentPoster, LoopKind, Posted, Ticket, VmHandle}; diff --git a/src/jsc/rare_data.rs b/src/jsc/rare_data.rs index 379823158ef6..e014f5e1811e 100644 --- a/src/jsc/rare_data.rs +++ b/src/jsc/rare_data.rs @@ -165,6 +165,12 @@ impl EntropyCache { // cast/deref locally, so invoking the pointer carries no caller-side precondition. pub(crate) type CleanupHookFunction = extern "C" fn(*mut c_void); +/// The context of a [`RareData::push_owned_cleanup_hook`]. +pub trait OwnedCleanupHook: Sized + 'static { + /// JS thread, VM exiting (script forbidden, JSC heap alive). + fn run(self: Box); +} + #[derive(Clone, Copy)] pub struct CleanupHook { pub ctx: *mut c_void, @@ -801,6 +807,22 @@ impl RareData { .push(CleanupHook::from(global_this, ctx, func)); } + /// A cleanup hook that owns `ctx`: [`OwnedCleanupHook::run`] gets it back + /// when the hooks run (once, at VM exit), or it leaks with the list if they + /// never do. + pub fn push_owned_cleanup_hook( + &mut self, + global_this: &JSGlobalObject, + ctx: Box, + ) { + extern "C" fn run(ctx: *mut c_void) { + // SAFETY: only installed below, with the `Box` leaked beside it; + // a hook is taken off the list before it runs, so this runs once. + T::run(unsafe { Box::from_raw(ctx.cast::()) }); + } + self.push_cleanup_hook(global_this, Box::into_raw(ctx).cast(), run::); + } + pub fn spawn_sync_event_loop(&mut self, vm: &mut VirtualMachine) -> &mut SpawnSyncEventLoop { if self.spawn_sync_event_loop_.is_none() { // In-place out-param init: `event_loop` inside captures the diff --git a/src/runtime/dispatch.rs b/src/runtime/dispatch.rs index afae984518da..da1aed89c27c 100644 --- a/src/runtime/dispatch.rs +++ b/src/runtime/dispatch.rs @@ -96,7 +96,7 @@ use crate::api::native_promise_context::DeferredDerefTask as NativePromiseContex #[cfg(not(windows))] use bun_spawn::static_pipe_writer::Poll as StaticPipeWriterPoll; -use crate::napi::{NapiFinalizerTask, ThreadSafeFunction, napi_async_work}; +use crate::napi::{AsyncWorkCompletion, NapiFinalizerTask, TsfnDispatch, TsfnFinalize}; use bun_jsc::PosixSignalTask; use bun_jsc::RuntimeTranspilerStore; @@ -189,6 +189,26 @@ pub(crate) fn run_task( task.ptr.cast::<$ty>() }; } + /// `<$hop as TaskHop>::run` on the queued `ThisPtr`, SAFETY spelled once. + macro_rules! hop { + ($hop:ty) => {{ + // SAFETY: §Dispatch — `task.tag` is `<$hop>::TAG`, set together with + // `task.ptr` from a `ThisPtr` whose pointee keeps itself alive for + // the queued task; not touched here after the call. + <$hop as bun_event_loop::TaskHop>::run(unsafe { + bun_ptr::ThisPtr::new(cast_ptr!(<$hop as bun_event_loop::TaskHop>::Target)) + }) + }}; + } + /// `<$ty as BoxedTask>::run` on the queued box, SAFETY spelled once. + macro_rules! boxed { + ($ty:ty) => {{ + // SAFETY: §Dispatch — `task.tag` is `<$ty as BoxedTask>::TAG`, set by + // `BoxedTask::into_task` together with the `Box<$ty>` it leaked into + // `task.ptr`; reclaimed exactly once, here. + <$ty as bun_event_loop::BoxedTask>::run(unsafe { Box::from_raw(cast_ptr!($ty)) }) + }}; + } /// `CompressionStream::::run_from_js_thread` takes `*mut T` (full /// allocation provenance — R-2) so its trailing `T::deref()` may free the box. macro_rules! compression_arm { @@ -354,15 +374,10 @@ pub(crate) fn run_task( } // ── napi ───────────────────────────────────────────────────────── - task_tag::NapiAsyncWork => { - cast!(napi_async_work).run_from_js(global)?; - } - task_tag::ThreadSafeFunction => { - ThreadSafeFunction::on_dispatch(cast_ptr!(ThreadSafeFunction)); - } - task_tag::NapiFinalizerTask => { - NapiFinalizerTask::run_on_js_thread(cast_ptr!(NapiFinalizerTask))?; - } + task_tag::NapiAsyncWork => hop!(AsyncWorkCompletion)?, + task_tag::ThreadSafeFunction => hop!(TsfnDispatch)?, + task_tag::ThreadSafeFunctionFinalize => hop!(TsfnFinalize)?, + task_tag::NapiFinalizerTask => boxed!(NapiFinalizerTask)?, // ── JSC scheduler / module loader ──────────────────────────────── task_tag::JSCDeferredWorkTask => { @@ -589,7 +604,7 @@ fn run_task_cold(task: Task) { /// `release_task_unrun` track `bun_event_loop::task_tag::COUNT`. Bump when /// adding a variant — and give it an arm in both. const _: () = assert!( - task_tag::COUNT == 61, + task_tag::COUNT == 62, "dispatch::run_task / release_task_unrun arm count out of sync with bun_event_loop::task_tag", ); @@ -1219,6 +1234,25 @@ fn __bun_release_task_unrun(task: bun_event_loop::Task) { unsafe { <$ty as Taskable>::release_unrun(task.ptr.cast::<$ty>()) } }}; } + /// `<$hop as TaskHop>::release_unrun` on the queued `ThisPtr`, SAFETY spelled once. + macro_rules! release_hop { + ($hop:ty) => {{ + // SAFETY: as `release!`; the tag is `<$hop>::TAG`. + <$hop as bun_event_loop::TaskHop>::release_unrun(unsafe { + bun_ptr::ThisPtr::new(task.ptr.cast::<<$hop as bun_event_loop::TaskHop>::Target>()) + }) + }}; + } + /// `<$ty as BoxedTask>::release_unrun` on the queued box, SAFETY spelled once. + macro_rules! release_boxed { + ($ty:ty) => {{ + // SAFETY: as `release!`; the tag is `<$ty as BoxedTask>::TAG` and + // `task.ptr` the `Box<$ty>` `into_task` leaked. + <$ty as bun_event_loop::BoxedTask>::release_unrun(unsafe { + Box::from_raw(task.ptr.cast::<$ty>()) + }) + }}; + } match task.tag { task_tag::AnyTaskJob => { // The one erased tag: every payload is a `Job` reached through its header. @@ -1248,8 +1282,9 @@ fn __bun_release_task_unrun(task: bun_event_loop::Task) { } task_tag::JSCDeferredWorkTask => release!(JSCDeferredWorkTask), task_tag::ManagedTask => release!(ManagedTask), - task_tag::NapiAsyncWork => release!(napi_async_work), - task_tag::NapiFinalizerTask => release!(NapiFinalizerTask), + task_tag::NapiAsyncWork => release_hop!(AsyncWorkCompletion), + task_tag::NapiFinalizerTask => release_boxed!(NapiFinalizerTask), + task_tag::ThreadSafeFunctionFinalize => release_hop!(TsfnFinalize), task_tag::NativePromiseContextDeferredDerefTask => { release!(NativePromiseContextDeferredDerefTask) } @@ -1289,7 +1324,7 @@ fn __bun_release_task_unrun(task: bun_event_loop::Task) { task_tag::AsyncCpTask => release!(crate::node::fs::AsyncCpTask), task_tag::ShellAsyncCpTask => release!(crate::node::fs::ShellAsyncCpTask), task_tag::StreamPending => release!(StreamPending), - task_tag::ThreadSafeFunction => release!(ThreadSafeFunction), + task_tag::ThreadSafeFunction => release_hop!(TsfnDispatch), task_tag::ValkeyDeferredClose => { release!(crate::valkey_jsc::js_valkey::ValkeyDeferredClose) } diff --git a/src/runtime/ffi/ffi_body.rs b/src/runtime/ffi/ffi_body.rs index 165996377a81..88ff89d90013 100644 --- a/src/runtime/ffi/ffi_body.rs +++ b/src/runtime/ffi/ffi_body.rs @@ -804,7 +804,7 @@ impl CompileC { state .add_symbol( zstr!("Bun__thisFFIModuleNapiEnv"), - global_this.make_napi_env_for_ffi().cast_const(), + core::ptr::from_ref(global_this.make_napi_env_for_ffi()).cast::(), ) .map_err(|_| crate::Error::DeferredErrors)?; break; @@ -2519,26 +2519,16 @@ impl CompilerRT { state .add_symbol(zstr!("memcpy"), Self::memcpy as *const c_void) .expect("unreachable"); - // Re-declare the C++ NapiHandleScope hooks locally — the canonical - // declarations live in `crate::napi::napi_body` which is private, and - // we only need the symbol addresses to hand to TCC. The canonical - // signatures use `*mut NapiHandleScope` (an opaque type not re-exported - // here); `*mut c_void` is ABI-identical for address-taking purposes. - #[allow(clashing_extern_declarations)] - unsafe extern "C" { - fn NapiHandleScope__open(env: *mut napi::NapiEnv, escapable: bool) -> *mut c_void; - fn NapiHandleScope__close(env: *mut napi::NapiEnv, current: *mut c_void); - } state .add_symbol( zstr!("NapiHandleScope__open"), - NapiHandleScope__open as *const c_void, + bun_jsc::napi::NapiHandleScope__open as *const c_void, ) .expect("unreachable"); state .add_symbol( zstr!("NapiHandleScope__close"), - NapiHandleScope__close as *const c_void, + bun_jsc::napi::NapiHandleScope__close as *const c_void, ) .expect("unreachable"); @@ -2593,20 +2583,13 @@ pub(crate) fn bun__ffi__cc(global: &JSGlobalObject, callframe: &CallFrame) -> Js FFI::bun_ffi_cc(global, callframe) } -fn make_napi_env_if_needed<'a>( +fn make_napi_env_if_needed<'a, 'g>( functions: impl IntoIterator, - global_this: &JSGlobalObject, -) -> Option<&'static napi::NapiEnv> { - // Return is `'static`, not `'a` — the env is heap-allocated by C++ - // (`makeNapiEnvForFFI`) and owned by the VM for process lifetime; tying it - // to `'a` (the iterator borrow) is over-restrictive and blocks the - // immediate-after `values_mut()` loop at every call site. + global_this: &'g JSGlobalObject, +) -> Option<&'g napi::NapiEnv> { for function in functions { if function.needs_napi_env() { - // SAFETY: C++ returns a non-null fresh NapiEnv; we hand back a shared `&` only. - // `bun_jsc` exposes `*mut c_void` to avoid an upward dep on - // `bun_runtime::napi`; the concrete type lives here, so cast at the boundary. - return Some(unsafe { &*global_this.make_napi_env_for_ffi().cast::() }); + return Some(global_this.make_napi_env_for_ffi()); } } None diff --git a/src/runtime/napi/libc_check.rs b/src/runtime/napi/libc_check.rs index 1fee058550ef..391f495d0df5 100644 --- a/src/runtime/napi/libc_check.rs +++ b/src/runtime/napi/libc_check.rs @@ -7,43 +7,28 @@ //! ELF `PT_DYNAMIC` segment before calling `dlopen` and surface a //! `ERR_DLOPEN_FAILED` that names the problem. See issue #15753. -use core::ffi::c_char; - /// Called from `Process_functionDlopen` (BunProcess.cpp) immediately before -/// `dlopen`. Returns `1` when the file at `path_ptr[..path_len]` is an ELF -/// shared object whose `DT_NEEDED` list references glibc and this process is -/// musl-linked (or the test-only `BUN_INTERNAL_NAPI_FORCE_MUSL_CHECK` env var -/// is set). The matching soname is copied NUL-terminated into -/// `soname_out[..soname_cap]` so the thrown error can quote the actual -/// rejected entry. Returns `0` for every other outcome, including I/O and -/// parse errors: a false negative falls through to `dlopen` which is today's -/// behaviour, whereas a false positive would refuse a working addon. -/// -/// # Safety -/// `path_ptr` must be valid for reads of `path_len` bytes; `soname_out` must -/// be valid for writes of `soname_cap` bytes. -#[unsafe(no_mangle)] -pub(crate) unsafe extern "C" fn Bun__addonNeedsGlibcOnMusl( - path_ptr: *const c_char, - path_len: usize, - soname_out: *mut u8, - soname_cap: usize, -) -> i32 { - let _ = (path_ptr, path_len, soname_out, soname_cap); +/// `dlopen`. Returns `1` when the file at `path` is an ELF shared object whose +/// `DT_NEEDED` list references glibc and this process is musl-linked (or the +/// test-only `BUN_INTERNAL_NAPI_FORCE_MUSL_CHECK` env var is set). The +/// matching soname is copied NUL-terminated into `soname_out` so the thrown +/// error can quote the actual rejected entry. Returns `0` for every other +/// outcome, including I/O and parse errors: a false negative falls through to +/// `dlopen` which is today's behaviour, whereas a false positive would refuse +/// a working addon. +// HOST_EXPORT(Bun__addonNeedsGlibcOnMusl, c) +pub fn addon_needs_glibc_on_musl(path: &[u8], soname_out: &mut [u8]) -> i32 { + let _ = (path, &soname_out); #[cfg(any(target_os = "linux", target_os = "android"))] { if !check_enabled() { return 0; } - // SAFETY: caller contract. - let path = unsafe { bun_core::ffi::slice(path_ptr.cast::(), path_len) }; if let Some(name) = elf_glibc_needed(path) { - if !soname_out.is_null() && soname_cap > 0 { - // SAFETY: caller contract. - let out = unsafe { core::slice::from_raw_parts_mut(soname_out, soname_cap) }; - let n = name.len().min(soname_cap - 1); - out[..n].copy_from_slice(&name[..n]); - out[n] = 0; + if let Some(cap) = soname_out.len().checked_sub(1) { + let n = name.len().min(cap); + soname_out[..n].copy_from_slice(&name[..n]); + soname_out[n] = 0; } return 1; } diff --git a/src/runtime/napi/link_symbols.rs b/src/runtime/napi/link_symbols.rs new file mode 100644 index 000000000000..923733836c23 --- /dev/null +++ b/src/runtime/napi/link_symbols.rs @@ -0,0 +1,1882 @@ +//! Link-time references to the C/C++ symbols a native addon resolves against +//! the Bun binary (the C++ half of Node-API, the `v8::` shim, the `uv_*` +//! polyfills), so the linker keeps them. Only their addresses are taken +//! ([`keep`]); the declarations carry no signature and are never called. + +use bun_core::keep_symbols; + +// Node-API functions implemented in C++ (napi.cpp). +unsafe extern "C" { + pub(super) fn napi_add_async_cleanup_hook(); + pub(super) fn napi_add_env_cleanup_hook(); + pub(super) fn napi_add_finalizer(); + pub(super) fn napi_adjust_external_memory(); + pub(super) fn napi_call_function(); + pub(super) fn napi_check_object_type_tag(); + pub(super) fn napi_coerce_to_bool(); + pub(super) fn napi_coerce_to_number(); + pub(super) fn napi_coerce_to_object(); + pub(super) fn napi_create_arraybuffer(); + pub(super) fn napi_create_bigint_int64(); + pub(super) fn napi_create_bigint_uint64(); + pub(super) fn napi_create_bigint_words(); + pub(super) fn napi_create_buffer(); + pub(super) fn napi_create_buffer_copy(); + pub(super) fn napi_create_dataview(); + pub(super) fn napi_create_double(); + pub(super) fn napi_create_error(); + pub(super) fn napi_create_external(); + pub(super) fn napi_create_external_arraybuffer(); + pub(super) fn napi_create_external_buffer(); + pub(super) fn napi_create_object(); + pub(super) fn napi_create_range_error(); + pub(super) fn napi_create_reference(); + pub(super) fn napi_create_symbol(); + pub(super) fn napi_create_type_error(); + pub(super) fn napi_create_typedarray(); + pub(super) fn napi_define_class(); + pub(super) fn napi_define_properties(); + pub(super) fn napi_delete_element(); + pub(super) fn napi_delete_reference(); + pub(super) fn napi_detach_arraybuffer(); + pub(super) fn napi_fatal_exception(); + pub(super) fn napi_get_all_property_names(); + pub(super) fn napi_get_and_clear_last_exception(); + pub(super) fn napi_get_cb_info(); + pub(super) fn napi_get_date_value(); + pub(super) fn napi_get_element(); + pub(super) fn napi_get_global(); + pub(super) fn napi_get_instance_data(); + pub(super) fn napi_get_last_error_info(); + pub(super) fn napi_get_new_target(); + pub(super) fn napi_get_reference_value(); + pub(super) fn napi_get_value_bigint_int64(); + pub(super) fn napi_get_value_bigint_uint64(); + pub(super) fn napi_get_value_bigint_words(); + pub(super) fn napi_get_value_bool(); + pub(super) fn napi_get_value_double(); + pub(super) fn napi_get_value_external(); + pub(super) fn napi_get_value_int32(); + pub(super) fn napi_get_value_int64(); + pub(super) fn napi_get_value_string_latin1(); + pub(super) fn napi_get_value_string_utf16(); + pub(super) fn napi_get_value_string_utf8(); + pub(super) fn napi_get_value_uint32(); + pub(super) fn napi_has_element(); + pub(super) fn napi_instanceof(); + pub(super) fn napi_is_buffer(); + pub(super) fn napi_is_detached_arraybuffer(); + pub(super) fn napi_is_exception_pending(); + pub(super) fn napi_is_typedarray(); + pub(super) fn napi_new_instance(); + pub(super) fn napi_reference_ref(); + pub(super) fn napi_reference_unref(); + pub(super) fn napi_remove_async_cleanup_hook(); + pub(super) fn napi_remove_env_cleanup_hook(); + pub(super) fn napi_remove_wrap(); + pub(super) fn napi_run_script(); + pub(super) fn napi_set_element(); + pub(super) fn napi_set_instance_data(); + pub(super) fn napi_throw(); + pub(super) fn napi_throw_error(); + pub(super) fn napi_throw_range_error(); + pub(super) fn napi_throw_type_error(); + pub(super) fn napi_type_tag_object(); + pub(super) fn napi_typeof(); + pub(super) fn napi_unwrap(); + pub(super) fn napi_wrap(); + pub(super) fn node_api_create_syntax_error(); + pub(super) fn node_api_symbol_for(); + pub(super) fn node_api_throw_syntax_error(); + pub(super) fn node_api_create_external_string_latin1(); + pub(super) fn node_api_create_external_string_utf16(); + pub(super) fn node_api_set_prototype(); + pub(super) fn node_api_create_object_with_properties(); + pub(super) fn node_api_create_sharedarraybuffer(); + pub(super) fn node_api_create_external_sharedarraybuffer(); + pub(super) fn node_api_is_sharedarraybuffer(); +} +// v8:: C++ symbols defined in v8.cpp. +// TODO: write a script to generate this list. ideally it wouldn't even need to be committed to source. +#[cfg(not(windows))] +mod v8_api { + unsafe extern "C" { + pub(super) fn _ZN2v87Isolate10GetCurrentEv(); + pub(super) fn _ZN2v87Isolate13TryGetCurrentEv(); + pub(super) fn _ZN2v87Isolate17GetCurrentContextEv(); + pub(super) fn _ZN2v87Isolate28GetEnteredOrMicrotaskContextEv(); + pub(super) fn _ZN2v87Isolate36GetContinuationPreservedEmbedderDataEv(); + pub(super) fn _ZN2v87Isolate7IsInUseEv(); + pub(super) fn _ZN2v87Isolate21LowMemoryNotificationEv(); + pub(super) fn _ZN2v87Isolate36AutomaticallyRestoreInitialHeapLimitEd(); + pub(super) fn _ZN2v87Isolate30NumberOfTrackedHeapObjectTypesEv(); + pub(super) fn _ZN2v87Isolate31GetHeapObjectStatisticsAtLastGCEPNS_20HeapObjectStatisticsEm(); + pub(super) fn _ZN2v87Isolate21AddGCPrologueCallbackEPFvPS0_NS_6GCTypeENS_15GCCallbackFlagsEPvES4_S2_() + ; + pub(super) fn _ZN2v87Isolate24RemoveGCPrologueCallbackEPFvPS0_NS_6GCTypeENS_15GCCallbackFlagsEPvES4_() + ; + pub(super) fn _ZN2v87Isolate21AddGCEpilogueCallbackEPFvPS0_NS_6GCTypeENS_15GCCallbackFlagsEPvES4_S2_() + ; + pub(super) fn _ZN2v87Isolate24RemoveGCEpilogueCallbackEPFvPS0_NS_6GCTypeENS_15GCCallbackFlagsEPvES4_() + ; + pub(super) fn _ZN2v87Isolate24AddNearHeapLimitCallbackEPFmPvmmES1_(); + pub(super) fn _ZN2v87Isolate27RemoveNearHeapLimitCallbackEPFmPvmmEm(); + pub(super) fn _ZN2v87Isolate16RequestInterruptEPFvPS0_PvES2_(); + pub(super) fn _ZN2v87Isolate14ThrowExceptionENS_5LocalINS_5ValueEEE(); + pub(super) fn _ZN2v87Isolate10ThrowErrorENS_5LocalINS_6StringEEE(); + pub(super) fn _ZN2v89Exception5ErrorENS_5LocalINS_6StringEEENS1_INS_5ValueEEE(); + pub(super) fn _ZN2v89Exception9TypeErrorENS_5LocalINS_6StringEEENS1_INS_5ValueEEE(); + pub(super) fn _ZN2v87Isolate15GetHeapProfilerEv(); + pub(super) fn _ZN2v812HeapProfiler24StopSamplingHeapProfilerEv(); + pub(super) fn _ZN2v812HeapProfiler20GetAllocationProfileEv(); + pub(super) fn _ZN4node25AddEnvironmentCleanupHookEPN2v87IsolateEPFvPvES3_(); + pub(super) fn _ZN4node28RemoveEnvironmentCleanupHookEPN2v87IsolateEPFvPvES3_(); + pub(super) fn _ZN4node19GetCurrentEventLoopEPN2v87IsolateE(); + pub(super) fn _ZN4node29AsyncHooksGetExecutionAsyncIdEN2v85LocalINS0_7ContextEEE(); + pub(super) fn _ZN4node13EmitAsyncInitEPN2v87IsolateENS0_5LocalINS0_6ObjectEEENS3_INS0_6StringEEEd() + ; + pub(super) fn _ZN4node16EmitAsyncDestroyEPN2v87IsolateENS_13async_contextE(); + pub(super) fn _ZN4node12MakeCallbackEPN2v87IsolateENS0_5LocalINS0_6ObjectEEENS3_INS0_8FunctionEEEiPNS3_INS0_5ValueEEENS_13async_contextE() + ; + pub(super) fn _ZN2v84base9TimeTicks3NowEv(); + pub(super) fn _ZN2v86Number3NewEPNS_7IsolateEd(); + pub(super) fn _ZNK2v86Number5ValueEv(); + pub(super) fn _ZN2v86Number12NewFromInt32EPNS_7IsolateEi(); + pub(super) fn _ZN2v86Number13NewFromUint32EPNS_7IsolateEj(); + pub(super) fn _ZN2v86String11NewFromUtf8EPNS_7IsolateEPKcNS_13NewStringTypeEi(); + pub(super) fn _ZNK2v86String9WriteUtf8EPNS_7IsolateEPciPii(); + pub(super) fn _ZN2v812api_internal12ToLocalEmptyEv(); + pub(super) fn _ZNK2v86String6LengthEv(); + pub(super) fn _ZN2v88External3NewEPNS_7IsolateEPv(); + pub(super) fn _ZNK2v88External5ValueEv(); + pub(super) fn _ZN2v88External3NewEPNS_7IsolateEPvt(); + pub(super) fn _ZNK2v88External5ValueEt(); + pub(super) fn _ZN2v86Object3NewEPNS_7IsolateE(); + pub(super) fn _ZN2v86Object3SetENS_5LocalINS_7ContextEEENS1_INS_5ValueEEES5_(); + pub(super) fn _ZN2v86Object3SetENS_5LocalINS_7ContextEEEjNS1_INS_5ValueEEE(); + pub(super) fn _ZN2v86Object16SetInternalFieldEiNS_5LocalINS_4DataEEE(); + pub(super) fn _ZN2v86Object20SlowGetInternalFieldEi(); + pub(super) fn _ZN2v86Object32SetAlignedPointerInInternalFieldEiPvt(); + pub(super) fn _ZN2v86Object38SlowGetAlignedPointerFromInternalFieldEit(); + pub(super) fn _ZN2v86Object3GetENS_5LocalINS_7ContextEEENS1_INS_5ValueEEE(); + pub(super) fn _ZN2v86Object3GetENS_5LocalINS_7ContextEEEj(); + pub(super) fn _ZN2v811HandleScope12CreateHandleEPNS_8internal7IsolateEm(); + pub(super) fn _ZN2v811HandleScope12CreateHandleEPNS_7IsolateEm(); + pub(super) fn _ZN2v811HandleScope10InitializeEPNS_7IsolateE(); + pub(super) fn _ZNK2v85Value16QuickIsUndefinedEv(); + pub(super) fn _ZNK2v85Value11QuickIsNullEv(); + pub(super) fn _ZNK2v85Value22QuickIsNullOrUndefinedEv(); + pub(super) fn _ZNK2v85Value13QuickIsStringEv(); + pub(super) fn _ZN2v811HandleScope6ExtendEPNS_7IsolateE(); + pub(super) fn _ZN2v811HandleScope16DeleteExtensionsEPNS_7IsolateE(); + pub(super) fn _ZN2v811HandleScopeC1EPNS_7IsolateE(); + pub(super) fn _ZN2v811HandleScopeD1Ev(); + pub(super) fn _ZN2v811HandleScopeD2Ev(); + pub(super) fn _ZN2v816FunctionTemplate11GetFunctionENS_5LocalINS_7ContextEEE(); + pub(super) fn _ZN2v816FunctionTemplate12SetClassNameENS_5LocalINS_6StringEEE(); + pub(super) fn _ZN2v816FunctionTemplate3NewEPNS_7IsolateEPFvRKNS_20FunctionCallbackInfoINS_5ValueEEEENS_5LocalIS4_EENSA_INS_9SignatureEEEiNS_19ConstructorBehaviorENS_14SideEffectTypeEPKNS_9CFunctionEttt() + ; + pub(super) fn _ZN2v814ObjectTemplate11NewInstanceENS_5LocalINS_7ContextEEE(); + pub(super) fn _ZN2v814ObjectTemplate21SetInternalFieldCountEi(); + pub(super) fn _ZNK2v814ObjectTemplate18InternalFieldCountEv(); + pub(super) fn _ZN2v814ObjectTemplate3NewEPNS_7IsolateENS_5LocalINS_16FunctionTemplateEEE(); + pub(super) fn _ZN2v816FunctionTemplate16InstanceTemplateEv(); + pub(super) fn _ZN2v816FunctionTemplate17PrototypeTemplateEv(); + pub(super) fn _ZN2v88Template3SetENS_5LocalINS_4NameEEENS1_INS_4DataEEENS_17PropertyAttributeE() + ; + pub(super) fn _ZN2v88Template21SetNativeDataPropertyENS_5LocalINS_4NameEEEPFvS3_RKNS_20PropertyCallbackInfoINS_5ValueEEEEPFvS3_NS1_IS5_EERKNS4_IvEEESB_NS_17PropertyAttributeENS_14SideEffectTypeESI_() + ; + pub(super) fn _ZN2v89Signature3NewEPNS_7IsolateENS_5LocalINS_16FunctionTemplateEEE(); + pub(super) fn _ZN2v824EscapableHandleScopeBase10EscapeSlotEPm(); + pub(super) fn _ZN2v824EscapableHandleScopeBaseC2EPNS_7IsolateE(); + pub(super) fn _ZN2v88internal35IsolateFromNeverReadOnlySpaceObjectEm(); + pub(super) fn _ZN2v85Array3NewEPNS_7IsolateEPNS_5LocalINS_5ValueEEEm(); + pub(super) fn _ZNK2v85Array6LengthEv(); + pub(super) fn _ZN2v85Array3NewEPNS_7IsolateEi(); + pub(super) fn _ZN2v85Array7IterateENS_5LocalINS_7ContextEEEPFNS0_14CallbackResultEjNS1_INS_5ValueEEEPvES7_() + ; + pub(super) fn _ZN2v85Array9CheckCastEPNS_5ValueE(); + pub(super) fn _ZN2v88Function7SetNameENS_5LocalINS_6StringEEE(); + pub(super) fn _ZN2v88Function4CallENS_5LocalINS_7ContextEEENS1_INS_5ValueEEEiPS5_(); + pub(super) fn _ZNK2v88Function11NewInstanceENS_5LocalINS_7ContextEEEiPNS1_INS_5ValueEEE(); + pub(super) fn _ZNK2v85Value9IsBooleanEv(); + pub(super) fn _ZNK2v87Boolean5ValueEv(); + pub(super) fn _ZNK2v85Value10FullIsTrueEv(); + pub(super) fn _ZNK2v85Value11FullIsFalseEv(); + pub(super) fn _ZN2v820EscapableHandleScopeC1EPNS_7IsolateE(); + pub(super) fn _ZN2v820EscapableHandleScopeC2EPNS_7IsolateE(); + pub(super) fn _ZN2v820EscapableHandleScopeD1Ev(); + pub(super) fn _ZN2v820EscapableHandleScopeD2Ev(); + pub(super) fn _ZNK2v85Value8IsObjectEv(); + pub(super) fn _ZNK2v85Value8IsNumberEv(); + pub(super) fn _ZNK2v85Value8IsUint32Ev(); + pub(super) fn _ZNK2v85Value11Uint32ValueENS_5LocalINS_7ContextEEE(); + pub(super) fn _ZNK2v85Value11IsUndefinedEv(); + pub(super) fn _ZNK2v85Value6IsNullEv(); + pub(super) fn _ZNK2v85Value17IsNullOrUndefinedEv(); + pub(super) fn _ZNK2v85Value6IsTrueEv(); + pub(super) fn _ZNK2v85Value7IsFalseEv(); + pub(super) fn _ZNK2v85Value8IsStringEv(); + pub(super) fn _ZNK2v85Value12StrictEqualsENS_5LocalIS0_EE(); + pub(super) fn _ZN2v87Boolean3NewEPNS_7IsolateEb(); + pub(super) fn _ZN2v811ArrayBuffer3NewEPNS_7IsolateEmNS_30BackingStoreInitializationModeE(); + pub(super) fn _ZN2v811ArrayBuffer15GetBackingStoreEv(); + pub(super) fn _ZNK2v812BackingStore4DataEv(); + pub(super) fn _ZN2v815ArrayBufferView6BufferEv(); + pub(super) fn _ZN2v815ArrayBufferView10ByteLengthEv(); + pub(super) fn _ZN2v815ArrayBufferView10ByteOffsetEv(); + pub(super) fn _ZN2v810Uint8Array3NewENS_5LocalINS_11ArrayBufferEEEmm(); + pub(super) fn _ZN2v811Uint32Array3NewENS_5LocalINS_11ArrayBufferEEEmm(); + pub(super) fn _ZN2v86Object16GetInternalFieldEi(); + pub(super) fn _ZN2v87Context10GetIsolateEv(); + pub(super) fn _ZN2v86String14NewFromOneByteEPNS_7IsolateEPKhNS_13NewStringTypeEi(); + pub(super) fn _ZNK2v86String10Utf8LengthEPNS_7IsolateE(); + pub(super) fn _ZNK2v86String10IsExternalEv(); + pub(super) fn _ZNK2v86String17IsExternalOneByteEv(); + pub(super) fn _ZNK2v86String17IsExternalTwoByteEv(); + pub(super) fn _ZNK2v86String9IsOneByteEv(); + pub(super) fn _ZNK2v86String19ContainsOnlyOneByteEv(); + pub(super) fn _ZNK2v86String7WriteV2EPNS_7IsolateEjjPti(); + pub(super) fn _ZNK2v86String14WriteOneByteV2EPNS_7IsolateEjjPhi(); + pub(super) fn _ZNK2v86String11WriteUtf8V2EPNS_7IsolateEPcmiPm(); + pub(super) fn _ZNK2v86String12Utf8LengthV2EPNS_7IsolateE(); + pub(super) fn _ZN2v812api_internal18GlobalizeReferenceEPNS_8internal7IsolateEm(); + pub(super) fn _ZN2v812api_internal13DisposeGlobalEPm(); + pub(super) fn _ZN2v812api_internal8MakeWeakEPmPvPFvRKNS_16WeakCallbackInfoIvEEENS_16WeakCallbackTypeE() + ; + pub(super) fn _ZN2v812api_internal9ClearWeakEPm(); + pub(super) fn _ZN2v812api_internal19MoveGlobalReferenceEPPmS2_(); + pub(super) fn _ZN2v812api_internal23GetFunctionTemplateDataEPNS_7IsolateENS_5LocalINS_4DataEEE() + ; + pub(super) fn _ZNK2v88Function7GetNameEv(); + pub(super) fn _ZNK2v85Value10IsFunctionEv(); + pub(super) fn _ZNK2v85Value5IsMapEv(); + pub(super) fn _ZNK2v85Value7IsArrayEv(); + pub(super) fn _ZNK2v85Value7IsInt32Ev(); + pub(super) fn _ZNK2v85Value8IsBigIntEv(); + pub(super) fn _ZN2v812api_internal17FromJustIsNothingEv(); + pub(super) fn _ZN2v87Integer3NewEPNS_7IsolateEi(); + pub(super) fn _ZN2v87Integer15NewFromUnsignedEPNS_7IsolateEj(); + pub(super) fn _ZNK2v87Integer5ValueEv(); + pub(super) fn _ZN2v86String18NewFromUtf8LiteralEPNS_7IsolateEPKcNS_13NewStringTypeEi(); + pub(super) fn _ZNK2v85Value12IsUint8ArrayEv(); + pub(super) fn _ZNK2v85Value8ToStringENS_5LocalINS_7ContextEEE(); + pub(super) fn _ZNK2v85Value9ToIntegerENS_5LocalINS_7ContextEEE(); + pub(super) fn _ZN2v87Context6GlobalEv(); + pub(super) fn _ZNK2v86Object18InternalFieldCountEv(); + pub(super) fn _ZN2v86Object15GetIdentityHashEv(); + pub(super) fn _ZN2v86Object17DefineOwnPropertyENS_5LocalINS_7ContextEEENS1_INS_4NameEEENS1_INS_5ValueEEENS_17PropertyAttributeE() + ; + pub(super) fn _ZN2v820ToExternalPointerTagEt(); + pub(super) fn _ZN2v88internal9Internals17GetCurrentIsolateEv(); + pub(super) fn _ZN2v820HeapObjectStatisticsC1Ev(); + pub(super) fn _ZN2v811CpuProfiler3NewEPNS_7IsolateENS_22CpuProfilingNamingModeENS_23CpuProfilingLoggingModeE() + ; + pub(super) fn _ZN2v811CpuProfiler7DisposeEv(); + pub(super) fn _ZN2v811CpuProfiler19SetSamplingIntervalEi(); + pub(super) fn _ZN2v811CpuProfiler5StartENS_5LocalINS_6StringEEENS_16CpuProfilingModeEbj(); + pub(super) fn _ZN2v811CpuProfiler4StopEj(); + pub(super) fn _ZN2v811CpuProfiler14StartProfilingENS_5LocalINS_6StringEEENS_16CpuProfilingModeEbj() + ; + pub(super) fn _ZN2v811CpuProfiler14StartProfilingENS_5LocalINS_6StringEEEb(); + pub(super) fn _ZN2v811CpuProfiler13StopProfilingENS_5LocalINS_6StringEEE(); + pub(super) fn _ZN2v810CpuProfile6DeleteEv(); + pub(super) fn _ZNK2v810CpuProfile8GetTitleEv(); + pub(super) fn _ZNK2v810CpuProfile10GetEndTimeEv(); + pub(super) fn _ZNK2v810CpuProfile12GetStartTimeEv(); + pub(super) fn _ZNK2v810CpuProfile14GetTopDownRootEv(); + pub(super) fn _ZNK2v810CpuProfile15GetSamplesCountEv(); + pub(super) fn _ZNK2v810CpuProfile18GetSampleTimestampEi(); + pub(super) fn _ZNK2v810CpuProfile9GetSampleEi(); + pub(super) fn _ZNK2v814CpuProfileNode11GetHitCountEv(); + pub(super) fn _ZNK2v814CpuProfileNode11GetScriptIdEv(); + pub(super) fn _ZNK2v814CpuProfileNode12GetLineTicksEPNS0_8LineTickEj(); + pub(super) fn _ZNK2v814CpuProfileNode13GetLineNumberEv(); + pub(super) fn _ZNK2v814CpuProfileNode15GetColumnNumberEv(); + pub(super) fn _ZNK2v814CpuProfileNode15GetFunctionNameEv(); + pub(super) fn _ZNK2v814CpuProfileNode15GetHitLineCountEv(); + pub(super) fn _ZNK2v814CpuProfileNode16GetChildrenCountEv(); + pub(super) fn _ZNK2v814CpuProfileNode18GetFunctionNameStrEv(); + pub(super) fn _ZNK2v814CpuProfileNode21GetScriptResourceNameEv(); + pub(super) fn _ZNK2v814CpuProfileNode8GetChildEi(); + pub(super) fn _ZN2v83Map3SetENS_5LocalINS_7ContextEEENS1_INS_5ValueEEES5_(); + pub(super) fn _ZN2v83Map6DeleteENS_5LocalINS_7ContextEEENS1_INS_5ValueEEE(); + pub(super) fn uv_os_getpid(); + pub(super) fn uv_os_getppid(); + } +} +#[cfg(windows)] +mod v8_api { + // MSVC name mangling is different than it is on unix. + // To make this easier to deal with, this script generates the list of functions. + // + // dumpbin .\build\CMakeFiles\bun-debug.dir\src\bun.js\bindings\v8\*.cpp.obj /symbols | where-object { $_.Contains(' node::') -or $_.Contains(' v8::') } | foreach-object { (($_ -split "\|")[1] -split " ")[1] } | ForEach-Object { "extern fn @`"${_}`"() *anyopaque;" } + // + // MSVC-mangled symbol names contain `?@$` and are not valid Rust identifiers, so each entry + // is exposed under a Rust-safe alias via `#[link_name = "..."]`. + #[rustfmt::skip] + unsafe extern "C" { + #[link_name = "?TryGetCurrent@Isolate@v8@@SAPEAV12@XZ"] + pub(super) fn v8_Isolate_TryGetCurrent(); + #[link_name = "?GetCurrent@Isolate@v8@@SAPEAV12@XZ"] + pub(super) fn v8_Isolate_GetCurrent(); + #[link_name = "?GetCurrentContext@Isolate@v8@@QEAA?AV?$Local@VContext@v8@@@2@XZ"] + pub(super) fn v8_Isolate_GetCurrentContext(); + #[link_name = "?GetEnteredOrMicrotaskContext@Isolate@v8@@QEAA?AV?$Local@VContext@v8@@@2@XZ"] + pub(super) fn v8_Isolate_GetEnteredOrMicrotaskContext(); + #[link_name = "?GetContinuationPreservedEmbedderData@Isolate@v8@@QEAA?AV?$Local@VValue@v8@@@2@XZ"] + pub(super) fn v8_Isolate_GetContinuationPreservedEmbedderData(); + #[link_name = "?IsInUse@Isolate@v8@@QEAA_NXZ"] + pub(super) fn v8_Isolate_IsInUse(); + #[link_name = "?LowMemoryNotification@Isolate@v8@@QEAAXXZ"] + pub(super) fn v8_Isolate_LowMemoryNotification(); + #[link_name = "?AutomaticallyRestoreInitialHeapLimit@Isolate@v8@@QEAAXN@Z"] + pub(super) fn v8_Isolate_AutomaticallyRestoreInitialHeapLimit(); + #[link_name = "?NumberOfTrackedHeapObjectTypes@Isolate@v8@@QEAA_KXZ"] + pub(super) fn v8_Isolate_NumberOfTrackedHeapObjectTypes(); + #[link_name = "?GetHeapObjectStatisticsAtLastGC@Isolate@v8@@QEAA_NPEAVHeapObjectStatistics@2@_K@Z"] + pub(super) fn v8_Isolate_GetHeapObjectStatisticsAtLastGC(); + #[link_name = "?AddGCPrologueCallback@Isolate@v8@@QEAAXP6AXPEAV12@W4GCType@2@W4GCCallbackFlags@2@PEAX@Z31@Z"] + pub(super) fn v8_Isolate_AddGCPrologueCallback(); + #[link_name = "?RemoveGCPrologueCallback@Isolate@v8@@QEAAXP6AXPEAV12@W4GCType@2@W4GCCallbackFlags@2@PEAX@Z3@Z"] + pub(super) fn v8_Isolate_RemoveGCPrologueCallback(); + #[link_name = "?AddGCEpilogueCallback@Isolate@v8@@QEAAXP6AXPEAV12@W4GCType@2@W4GCCallbackFlags@2@PEAX@Z31@Z"] + pub(super) fn v8_Isolate_AddGCEpilogueCallback(); + #[link_name = "?RemoveGCEpilogueCallback@Isolate@v8@@QEAAXP6AXPEAV12@W4GCType@2@W4GCCallbackFlags@2@PEAX@Z3@Z"] + pub(super) fn v8_Isolate_RemoveGCEpilogueCallback(); + #[link_name = "?AddNearHeapLimitCallback@Isolate@v8@@QEAAXP6A_KPEAX_K1@Z0@Z"] + pub(super) fn v8_Isolate_AddNearHeapLimitCallback(); + #[link_name = "?RemoveNearHeapLimitCallback@Isolate@v8@@QEAAXP6A_KPEAX_K1@Z1@Z"] + pub(super) fn v8_Isolate_RemoveNearHeapLimitCallback(); + #[link_name = "?RequestInterrupt@Isolate@v8@@QEAAXP6AXPEAV12@PEAX@Z1@Z"] + pub(super) fn v8_Isolate_RequestInterrupt(); + #[link_name = "?ThrowException@Isolate@v8@@QEAA?AV?$Local@VValue@v8@@@2@V32@@Z"] + pub(super) fn v8_Isolate_ThrowException(); + #[link_name = "?ThrowError@Isolate@v8@@QEAA?AV?$Local@VValue@v8@@@2@V?$Local@VString@v8@@@2@@Z"] + pub(super) fn v8_Isolate_ThrowError(); + #[link_name = "?Error@Exception@v8@@SA?AV?$Local@VValue@v8@@@2@V?$Local@VString@v8@@@2@V32@@Z"] + pub(super) fn v8_Exception_Error(); + #[link_name = "?TypeError@Exception@v8@@SA?AV?$Local@VValue@v8@@@2@V?$Local@VString@v8@@@2@V32@@Z"] + pub(super) fn v8_Exception_TypeError(); + #[link_name = "?GetHeapProfiler@Isolate@v8@@QEAAPEAVHeapProfiler@2@XZ"] + pub(super) fn v8_Isolate_GetHeapProfiler(); + #[link_name = "?StartSamplingHeapProfiler@HeapProfiler@v8@@QEAA_N_KHW4SamplingFlags@12@@Z"] + pub(super) fn v8_HeapProfiler_StartSamplingHeapProfiler(); + #[link_name = "?StopSamplingHeapProfiler@HeapProfiler@v8@@QEAAXXZ"] + pub(super) fn v8_HeapProfiler_StopSamplingHeapProfiler(); + #[link_name = "?GetAllocationProfile@HeapProfiler@v8@@QEAAPEAVAllocationProfile@2@XZ"] + pub(super) fn v8_HeapProfiler_GetAllocationProfile(); + #[link_name = "?AddEnvironmentCleanupHook@node@@YAXPEAVIsolate@v8@@P6AXPEAX@Z1@Z"] + pub(super) fn node_AddEnvironmentCleanupHook(); + #[link_name = "?RemoveEnvironmentCleanupHook@node@@YAXPEAVIsolate@v8@@P6AXPEAX@Z1@Z"] + pub(super) fn node_RemoveEnvironmentCleanupHook(); + #[link_name = "?GetCurrentEventLoop@node@@YAPEAUuv_loop_s@@PEAVIsolate@v8@@@Z"] + pub(super) fn node_GetCurrentEventLoop(); + #[link_name = "?AsyncHooksGetExecutionAsyncId@node@@YANV?$Local@VContext@v8@@@v8@@@Z"] + pub(super) fn node_AsyncHooksGetExecutionAsyncId(); + #[link_name = "?EmitAsyncInit@node@@YA?AUasync_context@1@PEAVIsolate@v8@@V?$Local@VObject@v8@@@4@V?$Local@VString@v8@@@4@N@Z"] + pub(super) fn node_EmitAsyncInit(); + #[link_name = "?EmitAsyncDestroy@node@@YAXPEAVIsolate@v8@@Uasync_context@1@@Z"] + pub(super) fn node_EmitAsyncDestroy(); + #[link_name = "?MakeCallback@node@@YA?AV?$MaybeLocal@VValue@v8@@@v8@@PEAVIsolate@3@V?$Local@VObject@v8@@@3@V?$Local@VFunction@v8@@@3@HPEAV?$Local@VValue@v8@@@3@Uasync_context@1@@Z"] + pub(super) fn node_MakeCallback(); + #[link_name = "?Now@TimeTicks@base@v8@@SA?AV123@XZ"] + pub(super) fn v8_base_TimeTicks_Now(); + #[link_name = "?New@Number@v8@@SA?AV?$Local@VNumber@v8@@@2@PEAVIsolate@2@N@Z"] + pub(super) fn v8_Number_New(); + #[link_name = "?Value@Number@v8@@QEBANXZ"] + pub(super) fn v8_Number_Value(); + #[link_name = "?NewFromInt32@Number@v8@@CA?AV?$Local@VNumber@v8@@@2@PEAVIsolate@2@H@Z"] + pub(super) fn v8_Number_NewFromInt32(); + #[link_name = "?NewFromUint32@Number@v8@@CA?AV?$Local@VNumber@v8@@@2@PEAVIsolate@2@I@Z"] + pub(super) fn v8_Number_NewFromUint32(); + #[link_name = "?NewFromUtf8@String@v8@@SA?AV?$MaybeLocal@VString@v8@@@2@PEAVIsolate@2@PEBDW4NewStringType@2@H@Z"] + pub(super) fn v8_String_NewFromUtf8(); + #[link_name = "?WriteUtf8@String@v8@@QEBAHPEAVIsolate@2@PEADHPEAHH@Z"] + pub(super) fn v8_String_WriteUtf8(); + #[link_name = "?ToLocalEmpty@api_internal@v8@@YAXXZ"] + pub(super) fn v8_api_internal_ToLocalEmpty(); + #[link_name = "?Length@String@v8@@QEBAHXZ"] + pub(super) fn v8_String_Length(); + #[link_name = "?New@External@v8@@SA?AV?$Local@VExternal@v8@@@2@PEAVIsolate@2@PEAX@Z"] + pub(super) fn v8_External_New(); + #[link_name = "?Value@External@v8@@QEBAPEAXXZ"] + pub(super) fn v8_External_Value(); + #[link_name = "?New@External@v8@@SA?AV?$Local@VExternal@v8@@@2@PEAVIsolate@2@PEAXG@Z"] + pub(super) fn v8_External_New_tagged(); + #[link_name = "?Value@External@v8@@QEBAPEAXG@Z"] + pub(super) fn v8_External_Value_tagged(); + #[link_name = "?New@Object@v8@@SA?AV?$Local@VObject@v8@@@2@PEAVIsolate@2@@Z"] + pub(super) fn v8_Object_New(); + #[link_name = "?Set@Object@v8@@QEAA?AV?$Maybe@_N@2@V?$Local@VContext@v8@@@2@V?$Local@VValue@v8@@@2@1@Z"] + pub(super) fn v8_Object_Set_key(); + #[link_name = "?Set@Object@v8@@QEAA?AV?$Maybe@_N@2@V?$Local@VContext@v8@@@2@IV?$Local@VValue@v8@@@2@@Z"] + pub(super) fn v8_Object_Set_index(); + #[link_name = "?SetInternalField@Object@v8@@QEAAXHV?$Local@VData@v8@@@2@@Z"] + pub(super) fn v8_Object_SetInternalField(); + #[link_name = "?SlowGetInternalField@Object@v8@@AEAA?AV?$Local@VData@v8@@@2@H@Z"] + pub(super) fn v8_Object_SlowGetInternalField(); + #[link_name = "?SetAlignedPointerInInternalField@Object@v8@@QEAAXHPEAXG@Z"] + pub(super) fn v8_Object_SetAlignedPointerInInternalField(); + #[link_name = "?SlowGetAlignedPointerFromInternalField@Object@v8@@AEAAPEAXHG@Z"] + pub(super) fn v8_Object_SlowGetAlignedPointerFromInternalField(); + #[link_name = "?Get@Object@v8@@QEAA?AV?$MaybeLocal@VValue@v8@@@2@V?$Local@VContext@v8@@@2@I@Z"] + pub(super) fn v8_Object_Get_index(); + #[link_name = "?Get@Object@v8@@QEAA?AV?$MaybeLocal@VValue@v8@@@2@V?$Local@VContext@v8@@@2@V?$Local@VValue@v8@@@2@@Z"] + pub(super) fn v8_Object_Get_key(); + #[link_name = "?CreateHandle@HandleScope@v8@@KAPEA_KPEAVIsolate@internal@2@_K@Z"] + pub(super) fn v8_HandleScope_CreateHandle(); + #[link_name = "?Extend@HandleScope@v8@@CAPEA_KPEAVIsolate@2@@Z"] + pub(super) fn v8_HandleScope_Extend(); + #[link_name = "?DeleteExtensions@HandleScope@v8@@AEAAXPEAVIsolate@2@@Z"] + pub(super) fn v8_HandleScope_DeleteExtensions(); + #[link_name = "??0HandleScope@v8@@QEAA@PEAVIsolate@1@@Z"] + pub(super) fn v8_HandleScope_ctor(); + #[link_name = "??1HandleScope@v8@@QEAA@XZ"] + pub(super) fn v8_HandleScope_dtor(); + #[link_name = "?GetFunction@FunctionTemplate@v8@@QEAA?AV?$MaybeLocal@VFunction@v8@@@2@V?$Local@VContext@v8@@@2@@Z"] + pub(super) fn v8_FunctionTemplate_GetFunction(); + #[link_name = "?SetClassName@FunctionTemplate@v8@@QEAAXV?$Local@VString@v8@@@2@@Z"] + pub(super) fn v8_FunctionTemplate_SetClassName(); + #[link_name = "?New@FunctionTemplate@v8@@SA?AV?$Local@VFunctionTemplate@v8@@@2@PEAVIsolate@2@P6AXAEBV?$FunctionCallbackInfo@VValue@v8@@@2@@ZV?$Local@VValue@v8@@@2@V?$Local@VSignature@v8@@@2@HW4ConstructorBehavior@2@W4SideEffectType@2@PEBVCFunction@2@GGG@Z"] + pub(super) fn v8_FunctionTemplate_New(); + #[link_name = "?NewInstance@ObjectTemplate@v8@@QEAA?AV?$MaybeLocal@VObject@v8@@@2@V?$Local@VContext@v8@@@2@@Z"] + pub(super) fn v8_ObjectTemplate_NewInstance(); + #[link_name = "?SetInternalFieldCount@ObjectTemplate@v8@@QEAAXH@Z"] + pub(super) fn v8_ObjectTemplate_SetInternalFieldCount(); + #[link_name = "?InternalFieldCount@ObjectTemplate@v8@@QEBAHXZ"] + pub(super) fn v8_ObjectTemplate_InternalFieldCount(); + #[link_name = "?New@ObjectTemplate@v8@@SA?AV?$Local@VObjectTemplate@v8@@@2@PEAVIsolate@2@V?$Local@VFunctionTemplate@v8@@@2@@Z"] + pub(super) fn v8_ObjectTemplate_New(); + #[link_name = "?InstanceTemplate@FunctionTemplate@v8@@QEAA?AV?$Local@VObjectTemplate@v8@@@2@XZ"] + pub(super) fn v8_FunctionTemplate_InstanceTemplate(); + #[link_name = "?PrototypeTemplate@FunctionTemplate@v8@@QEAA?AV?$Local@VObjectTemplate@v8@@@2@XZ"] + pub(super) fn v8_FunctionTemplate_PrototypeTemplate(); + #[link_name = "?Set@Template@v8@@QEAAXV?$Local@VName@v8@@@2@V?$Local@VData@v8@@@2@W4PropertyAttribute@2@@Z"] + pub(super) fn v8_Template_Set(); + #[link_name = "?SetNativeDataProperty@Template@v8@@QEAAXV?$Local@VName@v8@@@2@P6AX0AEBV?$PropertyCallbackInfo@VValue@v8@@@2@@ZP6AX0V?$Local@VValue@v8@@@2@AEBV?$PropertyCallbackInfo@X@2@@Z3W4PropertyAttribute@2@W4SideEffectType@2@7@Z"] + pub(super) fn v8_Template_SetNativeDataProperty(); + #[link_name = "?New@Signature@v8@@SA?AV?$Local@VSignature@v8@@@2@PEAVIsolate@2@V?$Local@VFunctionTemplate@v8@@@2@@Z"] + pub(super) fn v8_Signature_New(); + #[link_name = "?EscapeSlot@EscapableHandleScopeBase@v8@@IEAAPEA_KPEA_K@Z"] + pub(super) fn v8_EscapableHandleScopeBase_EscapeSlot(); + #[link_name = "??0EscapableHandleScopeBase@v8@@QEAA@PEAVIsolate@1@@Z"] + pub(super) fn v8_EscapableHandleScopeBase_ctor(); + #[link_name = "?IsolateFromNeverReadOnlySpaceObject@internal@v8@@YAPEAVIsolate@12@_K@Z"] + pub(super) fn v8_internal_IsolateFromNeverReadOnlySpaceObject(); + #[link_name = "?New@Array@v8@@SA?AV?$Local@VArray@v8@@@2@PEAVIsolate@2@PEAV?$Local@VValue@v8@@@2@_K@Z"] + pub(super) fn v8_Array_New_elements(); + #[link_name = "?Length@Array@v8@@QEBAIXZ"] + pub(super) fn v8_Array_Length(); + #[link_name = "?New@Array@v8@@SA?AV?$Local@VArray@v8@@@2@PEAVIsolate@2@H@Z"] + pub(super) fn v8_Array_New_len(); + #[link_name = "?New@Array@v8@@SA?AV?$MaybeLocal@VArray@v8@@@2@V?$Local@VContext@v8@@@2@_KV?$function@$$A6A?AV?$MaybeLocal@VValue@v8@@@v8@@XZ@std@@@Z"] + pub(super) fn v8_Array_New_fn(); + #[link_name = "?Iterate@Array@v8@@QEAA?AV?$Maybe@X@2@V?$Local@VContext@v8@@@2@P6A?AW4CallbackResult@12@IV?$Local@VValue@v8@@@2@PEAX@Z2@Z"] + pub(super) fn v8_Array_Iterate(); + #[link_name = "?CheckCast@Array@v8@@CAXPEAVValue@2@@Z"] + pub(super) fn v8_Array_CheckCast(); + #[link_name = "?SetName@Function@v8@@QEAAXV?$Local@VString@v8@@@2@@Z"] + pub(super) fn v8_Function_SetName(); + #[link_name = "?Call@Function@v8@@QEAA?AV?$MaybeLocal@VValue@v8@@@2@V?$Local@VContext@v8@@@2@V?$Local@VValue@v8@@@2@HQEAV52@@Z"] + pub(super) fn v8_Function_Call(); + #[link_name = "?NewInstance@Function@v8@@QEBA?AV?$MaybeLocal@VObject@v8@@@2@V?$Local@VContext@v8@@@2@HQEAV?$Local@VValue@v8@@@2@@Z"] + pub(super) fn v8_Function_NewInstance(); + #[link_name = "?NewInstance@Function@v8@@QEBA?AV?$MaybeLocal@VObject@v8@@@2@V?$Local@VContext@v8@@@2@@Z"] + pub(super) fn v8_Function_NewInstance_noargs(); + #[link_name = "?GetAlignedPointerFromInternalField@Object@v8@@QEAAPEAXHG@Z"] + pub(super) fn v8_Object_GetAlignedPointerFromInternalField(); + #[link_name = "?IsBoolean@Value@v8@@QEBA_NXZ"] + pub(super) fn v8_Value_IsBoolean(); + #[link_name = "?Value@Boolean@v8@@QEBA_NXZ"] + pub(super) fn v8_Boolean_Value(); + #[link_name = "?FullIsTrue@Value@v8@@AEBA_NXZ"] + pub(super) fn v8_Value_FullIsTrue(); + #[link_name = "?FullIsFalse@Value@v8@@AEBA_NXZ"] + pub(super) fn v8_Value_FullIsFalse(); + #[link_name = "??1EscapableHandleScope@v8@@QEAA@XZ"] + pub(super) fn v8_EscapableHandleScope_dtor(); + #[link_name = "??0EscapableHandleScope@v8@@QEAA@PEAVIsolate@1@@Z"] + pub(super) fn v8_EscapableHandleScope_ctor(); + #[link_name = "?IsObject@Value@v8@@QEBA_NXZ"] + pub(super) fn v8_Value_IsObject(); + #[link_name = "?IsNumber@Value@v8@@QEBA_NXZ"] + pub(super) fn v8_Value_IsNumber(); + #[link_name = "?IsUint32@Value@v8@@QEBA_NXZ"] + pub(super) fn v8_Value_IsUint32(); + #[link_name = "?Uint32Value@Value@v8@@QEBA?AV?$Maybe@I@2@V?$Local@VContext@v8@@@2@@Z"] + pub(super) fn v8_Value_Uint32Value(); + #[link_name = "?IsUndefined@Value@v8@@QEBA_NXZ"] + pub(super) fn v8_Value_IsUndefined(); + #[link_name = "?IsNull@Value@v8@@QEBA_NXZ"] + pub(super) fn v8_Value_IsNull(); + #[link_name = "?IsNullOrUndefined@Value@v8@@QEBA_NXZ"] + pub(super) fn v8_Value_IsNullOrUndefined(); + #[link_name = "?IsTrue@Value@v8@@QEBA_NXZ"] + pub(super) fn v8_Value_IsTrue(); + #[link_name = "?IsFalse@Value@v8@@QEBA_NXZ"] + pub(super) fn v8_Value_IsFalse(); + #[link_name = "?IsString@Value@v8@@QEBA_NXZ"] + pub(super) fn v8_Value_IsString(); + #[link_name = "?StrictEquals@Value@v8@@QEBA_NV?$Local@VValue@v8@@@2@@Z"] + pub(super) fn v8_Value_StrictEquals(); + #[link_name = "?New@Boolean@v8@@SA?AV?$Local@VBoolean@v8@@@2@PEAVIsolate@2@_N@Z"] + pub(super) fn v8_Boolean_New(); + #[link_name = "?GetInternalField@Object@v8@@QEAA?AV?$Local@VData@v8@@@2@H@Z"] + pub(super) fn v8_Object_GetInternalField(); + #[link_name = "?GetIsolate@Context@v8@@QEAAPEAVIsolate@2@XZ"] + pub(super) fn v8_Context_GetIsolate(); + #[link_name = "?NewFromOneByte@String@v8@@SA?AV?$MaybeLocal@VString@v8@@@2@PEAVIsolate@2@PEBEW4NewStringType@2@H@Z"] + pub(super) fn v8_String_NewFromOneByte(); + #[link_name = "?IsExternal@String@v8@@QEBA_NXZ"] + pub(super) fn v8_String_IsExternal(); + #[link_name = "?IsExternalOneByte@String@v8@@QEBA_NXZ"] + pub(super) fn v8_String_IsExternalOneByte(); + #[link_name = "?IsExternalTwoByte@String@v8@@QEBA_NXZ"] + pub(super) fn v8_String_IsExternalTwoByte(); + #[link_name = "?IsOneByte@String@v8@@QEBA_NXZ"] + pub(super) fn v8_String_IsOneByte(); + #[link_name = "?Utf8Length@String@v8@@QEBAHPEAVIsolate@2@@Z"] + pub(super) fn v8_String_Utf8Length(); + #[link_name = "?ContainsOnlyOneByte@String@v8@@QEBA_NXZ"] + pub(super) fn v8_String_ContainsOnlyOneByte(); + #[link_name = "?WriteV2@String@v8@@QEBAXPEAVIsolate@2@IIPEAGH@Z"] + pub(super) fn v8_String_WriteV2(); + #[link_name = "?WriteOneByteV2@String@v8@@QEBAXPEAVIsolate@2@IIPEAEH@Z"] + pub(super) fn v8_String_WriteOneByteV2(); + #[link_name = "?WriteUtf8V2@String@v8@@QEBA_KPEAVIsolate@2@PEAD_KHPEA_K@Z"] + pub(super) fn v8_String_WriteUtf8V2(); + #[link_name = "?Utf8LengthV2@String@v8@@QEBA_KPEAVIsolate@2@@Z"] + pub(super) fn v8_String_Utf8LengthV2(); + #[link_name = "?GlobalizeReference@api_internal@v8@@YAPEA_KPEAVIsolate@internal@2@_K@Z"] + pub(super) fn v8_api_internal_GlobalizeReference(); + #[link_name = "?DisposeGlobal@api_internal@v8@@YAXPEA_K@Z"] + pub(super) fn v8_api_internal_DisposeGlobal(); + #[link_name = "?MakeWeak@api_internal@v8@@YAXPEA_KPEAXP6AXAEBV?$WeakCallbackInfo@X@2@@ZW4WeakCallbackType@2@@Z"] + pub(super) fn v8_api_internal_MakeWeak(); + #[link_name = "?ClearWeak@api_internal@v8@@YAPEAXPEA_K@Z"] + pub(super) fn v8_api_internal_ClearWeak(); + #[link_name = "?MoveGlobalReference@api_internal@v8@@YAXPEAPEA_K0@Z"] + pub(super) fn v8_api_internal_MoveGlobalReference(); + #[link_name = "?GetFunctionTemplateData@api_internal@v8@@YA?AV?$Local@VValue@v8@@@2@PEAVIsolate@2@V?$Local@VData@v8@@@2@@Z"] + pub(super) fn v8_api_internal_GetFunctionTemplateData(); + #[link_name = "?GetName@Function@v8@@QEBA?AV?$Local@VValue@v8@@@2@XZ"] + pub(super) fn v8_Function_GetName(); + #[link_name = "?IsFunction@Value@v8@@QEBA_NXZ"] + pub(super) fn v8_Value_IsFunction(); + #[link_name = "?IsMap@Value@v8@@QEBA_NXZ"] + pub(super) fn v8_Value_IsMap(); + #[link_name = "?IsArray@Value@v8@@QEBA_NXZ"] + pub(super) fn v8_Value_IsArray(); + #[link_name = "?IsInt32@Value@v8@@QEBA_NXZ"] + pub(super) fn v8_Value_IsInt32(); + #[link_name = "?IsBigInt@Value@v8@@QEBA_NXZ"] + pub(super) fn v8_Value_IsBigInt(); + #[link_name = "?FromJustIsNothing@api_internal@v8@@YAXXZ"] + pub(super) fn v8_api_internal_FromJustIsNothing(); + #[link_name = "?New@Integer@v8@@SA?AV?$Local@VInteger@v8@@@2@PEAVIsolate@2@H@Z"] + pub(super) fn v8_Integer_New(); + #[link_name = "?NewFromUnsigned@Integer@v8@@SA?AV?$Local@VInteger@v8@@@2@PEAVIsolate@2@I@Z"] + pub(super) fn v8_Integer_NewFromUnsigned(); + #[link_name = "?Value@Integer@v8@@QEBA_JXZ"] + pub(super) fn v8_Integer_Value(); + #[link_name = "?New@BigInt@v8@@SA?AV?$Local@VBigInt@v8@@@2@PEAVIsolate@2@_J@Z"] + pub(super) fn v8_BigInt_New(); + #[link_name = "?NewFromUtf8Literal@String@v8@@CA?AV?$Local@VString@v8@@@2@PEAVIsolate@2@PEBDW4NewStringType@2@H@Z"] + pub(super) fn v8_String_NewFromUtf8Literal(); + #[link_name = "?IsUint8Array@Value@v8@@QEBA_NXZ"] + pub(super) fn v8_Value_IsUint8Array(); + #[link_name = "?ToString@Value@v8@@QEBA?AV?$MaybeLocal@VString@v8@@@2@V?$Local@VContext@v8@@@2@@Z"] + pub(super) fn v8_Value_ToString(); + #[link_name = "?ToInteger@Value@v8@@QEBA?AV?$MaybeLocal@VInteger@v8@@@2@V?$Local@VContext@v8@@@2@@Z"] + pub(super) fn v8_Value_ToInteger(); + #[link_name = "?Global@Context@v8@@QEAA?AV?$Local@VObject@v8@@@2@XZ"] + pub(super) fn v8_Context_Global(); + #[link_name = "?InternalFieldCount@Object@v8@@QEBAHXZ"] + pub(super) fn v8_Object_InternalFieldCount(); + #[link_name = "?GetIdentityHash@Object@v8@@QEAAHXZ"] + pub(super) fn v8_Object_GetIdentityHash(); + #[link_name = "?DefineOwnProperty@Object@v8@@QEAA?AV?$Maybe@_N@2@V?$Local@VContext@v8@@@2@V?$Local@VName@v8@@@2@V?$Local@VValue@v8@@@2@W4PropertyAttribute@2@@Z"] + pub(super) fn v8_Object_DefineOwnProperty(); + #[link_name = "?ToExternalPointerTag@v8@@YA?AW4ExternalPointerTag@internal@1@G@Z"] + pub(super) fn v8_ToExternalPointerTag(); + #[link_name = "?GetCurrentIsolate@Internals@internal@v8@@SAPEAVIsolate@3@XZ"] + pub(super) fn v8_internal_Internals_GetCurrentIsolate(); + #[link_name = "??0HeapObjectStatistics@v8@@QEAA@XZ"] + pub(super) fn v8_HeapObjectStatistics_ctor(); + #[link_name = "?New@ArrayBuffer@v8@@SA?AV?$Local@VArrayBuffer@v8@@@2@PEAVIsolate@2@_KW4BackingStoreInitializationMode@2@@Z"] + pub(super) fn v8_ArrayBuffer_New(); + #[link_name = "?GetBackingStore@ArrayBuffer@v8@@QEAA?AV?$shared_ptr@VBackingStore@v8@@@std@@XZ"] + pub(super) fn v8_ArrayBuffer_GetBackingStore(); + #[link_name = "?Data@BackingStore@v8@@QEBAPEAXXZ"] + pub(super) fn v8_BackingStore_Data(); + #[link_name = "?Buffer@ArrayBufferView@v8@@QEAA?AV?$Local@VArrayBuffer@v8@@@2@XZ"] + pub(super) fn v8_ArrayBufferView_Buffer(); + #[link_name = "?ByteLength@ArrayBufferView@v8@@QEAA_KXZ"] + pub(super) fn v8_ArrayBufferView_ByteLength(); + #[link_name = "?ByteOffset@ArrayBufferView@v8@@QEAA_KXZ"] + pub(super) fn v8_ArrayBufferView_ByteOffset(); + #[link_name = "?New@Uint8Array@v8@@SA?AV?$Local@VUint8Array@v8@@@2@V?$Local@VArrayBuffer@v8@@@2@_K1@Z"] + pub(super) fn v8_Uint8Array_New(); + #[link_name = "?New@Uint32Array@v8@@SA?AV?$Local@VUint32Array@v8@@@2@V?$Local@VArrayBuffer@v8@@@2@_K1@Z"] + pub(super) fn v8_Uint32Array_New(); + #[link_name = "?New@CpuProfiler@v8@@SAPEAV12@PEAVIsolate@2@W4CpuProfilingNamingMode@2@W4CpuProfilingLoggingMode@2@@Z"] + pub(super) fn v8_CpuProfiler_New(); + #[link_name = "?Dispose@CpuProfiler@v8@@QEAAXXZ"] + pub(super) fn v8_CpuProfiler_Dispose(); + #[link_name = "?SetSamplingInterval@CpuProfiler@v8@@QEAAXH@Z"] + pub(super) fn v8_CpuProfiler_SetSamplingInterval(); + #[link_name = "?Start@CpuProfiler@v8@@QEAA?AUCpuProfilingResult@2@V?$Local@VString@v8@@@2@W4CpuProfilingMode@2@_NI@Z"] + pub(super) fn v8_CpuProfiler_Start(); + #[link_name = "?Stop@CpuProfiler@v8@@QEAAPEAVCpuProfile@2@I@Z"] + pub(super) fn v8_CpuProfiler_Stop(); + #[link_name = "?StartProfiling@CpuProfiler@v8@@QEAA?AW4CpuProfilingStatus@2@V?$Local@VString@v8@@@2@W4CpuProfilingMode@2@_NI@Z"] + pub(super) fn v8_CpuProfiler_StartProfiling_mode(); + #[link_name = "?StartProfiling@CpuProfiler@v8@@QEAA?AW4CpuProfilingStatus@2@V?$Local@VString@v8@@@2@_N@Z"] + pub(super) fn v8_CpuProfiler_StartProfiling(); + #[link_name = "?StopProfiling@CpuProfiler@v8@@QEAAPEAVCpuProfile@2@V?$Local@VString@v8@@@2@@Z"] + pub(super) fn v8_CpuProfiler_StopProfiling(); + #[link_name = "?CollectSample@CpuProfiler@v8@@SAXPEAVIsolate@2@V?$optional@_K@std@@@Z"] + pub(super) fn v8_CpuProfiler_CollectSample(); + #[link_name = "?Delete@CpuProfile@v8@@QEAAXXZ"] + pub(super) fn v8_CpuProfile_Delete(); + #[link_name = "?GetTitle@CpuProfile@v8@@QEBA?AV?$Local@VString@v8@@@2@XZ"] + pub(super) fn v8_CpuProfile_GetTitle(); + #[link_name = "?GetEndTime@CpuProfile@v8@@QEBA_JXZ"] + pub(super) fn v8_CpuProfile_GetEndTime(); + #[link_name = "?GetStartTime@CpuProfile@v8@@QEBA_JXZ"] + pub(super) fn v8_CpuProfile_GetStartTime(); + #[link_name = "?GetTopDownRoot@CpuProfile@v8@@QEBAPEBVCpuProfileNode@2@XZ"] + pub(super) fn v8_CpuProfile_GetTopDownRoot(); + #[link_name = "?GetSamplesCount@CpuProfile@v8@@QEBAHXZ"] + pub(super) fn v8_CpuProfile_GetSamplesCount(); + #[link_name = "?GetSampleTimestamp@CpuProfile@v8@@QEBA_JH@Z"] + pub(super) fn v8_CpuProfile_GetSampleTimestamp(); + #[link_name = "?GetSample@CpuProfile@v8@@QEBAPEBVCpuProfileNode@2@H@Z"] + pub(super) fn v8_CpuProfile_GetSample(); + #[link_name = "?GetHitCount@CpuProfileNode@v8@@QEBAIXZ"] + pub(super) fn v8_CpuProfileNode_GetHitCount(); + #[link_name = "?GetScriptId@CpuProfileNode@v8@@QEBAHXZ"] + pub(super) fn v8_CpuProfileNode_GetScriptId(); + #[link_name = "?GetLineTicks@CpuProfileNode@v8@@QEBA_NPEAULineTick@12@I@Z"] + pub(super) fn v8_CpuProfileNode_GetLineTicks(); + #[link_name = "?GetLineNumber@CpuProfileNode@v8@@QEBAHXZ"] + pub(super) fn v8_CpuProfileNode_GetLineNumber(); + #[link_name = "?GetColumnNumber@CpuProfileNode@v8@@QEBAHXZ"] + pub(super) fn v8_CpuProfileNode_GetColumnNumber(); + #[link_name = "?GetFunctionName@CpuProfileNode@v8@@QEBA?AV?$Local@VString@v8@@@2@XZ"] + pub(super) fn v8_CpuProfileNode_GetFunctionName(); + #[link_name = "?GetHitLineCount@CpuProfileNode@v8@@QEBAIXZ"] + pub(super) fn v8_CpuProfileNode_GetHitLineCount(); + #[link_name = "?GetChildrenCount@CpuProfileNode@v8@@QEBAHXZ"] + pub(super) fn v8_CpuProfileNode_GetChildrenCount(); + #[link_name = "?GetFunctionNameStr@CpuProfileNode@v8@@QEBAPEBDXZ"] + pub(super) fn v8_CpuProfileNode_GetFunctionNameStr(); + #[link_name = "?GetScriptResourceName@CpuProfileNode@v8@@QEBA?AV?$Local@VString@v8@@@2@XZ"] + pub(super) fn v8_CpuProfileNode_GetScriptResourceName(); + #[link_name = "?GetChild@CpuProfileNode@v8@@QEBAPEBV12@H@Z"] + pub(super) fn v8_CpuProfileNode_GetChild(); + #[link_name = "?Set@Map@v8@@QEAA?AV?$MaybeLocal@VMap@v8@@@2@V?$Local@VContext@v8@@@2@V?$Local@VValue@v8@@@2@1@Z"] + pub(super) fn v8_Map_Set(); + #[link_name = "?Delete@Map@v8@@QEAA?AV?$Maybe@_N@2@V?$Local@VContext@v8@@@2@V?$Local@VValue@v8@@@2@@Z"] + pub(super) fn v8_Map_Delete(); + } +} +// Per-platform v8 symbols whose mangling differs by C++ standard library. +#[cfg(windows)] +mod posix_platform_specific_v8_apis {} +#[cfg(all(not(windows), target_os = "android"))] +mod posix_platform_specific_v8_apis { + unsafe extern "C" { + pub(super) fn _ZN2v85Array3NewENS_5LocalINS_7ContextEEEmNSt6__ndk18functionIFNS_10MaybeLocalINS_5ValueEEEvEEE() + ; + pub(super) fn _ZN2v811CpuProfiler13CollectSampleEPNS_7IsolateENSt6__ndk18optionalImEE(); + pub(super) fn _ZN2v86BigInt3NewEPNS_7IsolateEl(); + pub(super) fn _ZN2v812HeapProfiler25StartSamplingHeapProfilerEmiNS0_13SamplingFlagsE(); + } +} +#[cfg(all(not(windows), target_os = "macos"))] +mod posix_platform_specific_v8_apis { + unsafe extern "C" { + pub(super) fn _ZN2v85Array3NewENS_5LocalINS_7ContextEEEmNSt3__18functionIFNS_10MaybeLocalINS_5ValueEEEvEEE() + ; + pub(super) fn _ZN2v811CpuProfiler13CollectSampleEPNS_7IsolateENSt3__18optionalIyEE(); + pub(super) fn _ZN2v86BigInt3NewEPNS_7IsolateEx(); + pub(super) fn _ZN2v812HeapProfiler25StartSamplingHeapProfilerEyiNS0_13SamplingFlagsE(); + } +} +#[cfg(all(not(windows), target_os = "freebsd"))] +mod posix_platform_specific_v8_apis { + unsafe extern "C" { + pub(super) fn _ZN2v85Array3NewENS_5LocalINS_7ContextEEEmNSt3__18functionIFNS_10MaybeLocalINS_5ValueEEEvEEE() + ; + pub(super) fn _ZN2v811CpuProfiler13CollectSampleEPNS_7IsolateENSt3__18optionalImEE(); + pub(super) fn _ZN2v86BigInt3NewEPNS_7IsolateEl(); + pub(super) fn _ZN2v812HeapProfiler25StartSamplingHeapProfilerEmiNS0_13SamplingFlagsE(); + } +} +#[cfg(all( + not(windows), + not(target_os = "android"), + not(target_os = "macos"), + not(target_os = "freebsd") +))] +mod posix_platform_specific_v8_apis { + unsafe extern "C" { + pub(super) fn _ZN2v85Array3NewENS_5LocalINS_7ContextEEEmSt8functionIFNS_10MaybeLocalINS_5ValueEEEvEE() + ; + pub(super) fn _ZN2v811CpuProfiler13CollectSampleEPNS_7IsolateESt8optionalImE(); + pub(super) fn _ZN2v86BigInt3NewEPNS_7IsolateEl(); + pub(super) fn _ZN2v812HeapProfiler25StartSamplingHeapProfilerEmiNS0_13SamplingFlagsE(); + } +} +// uv_* symbols (the posix polyfills; on Windows libuv itself is linked). +#[cfg(unix)] +mod uv_functions_to_export { + unsafe extern "C" { + pub(super) fn uv_accept(); + pub(super) fn uv_async_init(); + pub(super) fn uv_async_send(); + pub(super) fn uv_available_parallelism(); + pub(super) fn uv_backend_fd(); + pub(super) fn uv_backend_timeout(); + pub(super) fn uv_barrier_destroy(); + pub(super) fn uv_barrier_init(); + pub(super) fn uv_barrier_wait(); + pub(super) fn uv_buf_init(); + pub(super) fn uv_cancel(); + pub(super) fn uv_chdir(); + pub(super) fn uv_check_init(); + pub(super) fn uv_check_start(); + pub(super) fn uv_check_stop(); + pub(super) fn uv_clock_gettime(); + pub(super) fn uv_close(); + pub(super) fn uv_cond_broadcast(); + pub(super) fn uv_cond_destroy(); + pub(super) fn uv_cond_init(); + pub(super) fn uv_cond_signal(); + pub(super) fn uv_cond_timedwait(); + pub(super) fn uv_cond_wait(); + pub(super) fn uv_cpu_info(); + pub(super) fn uv_cpumask_size(); + pub(super) fn uv_cwd(); + pub(super) fn uv_default_loop(); + pub(super) fn uv_disable_stdio_inheritance(); + pub(super) fn uv_dlclose(); + pub(super) fn uv_dlerror(); + pub(super) fn uv_dlopen(); + pub(super) fn uv_dlsym(); + pub(super) fn uv_err_name(); + pub(super) fn uv_err_name_r(); + pub(super) fn uv_exepath(); + pub(super) fn uv_fileno(); + pub(super) fn uv_free_cpu_info(); + pub(super) fn uv_free_interface_addresses(); + pub(super) fn uv_freeaddrinfo(); + pub(super) fn uv_fs_access(); + pub(super) fn uv_fs_chmod(); + pub(super) fn uv_fs_chown(); + pub(super) fn uv_fs_close(); + pub(super) fn uv_fs_closedir(); + pub(super) fn uv_fs_copyfile(); + pub(super) fn uv_fs_event_getpath(); + pub(super) fn uv_fs_event_init(); + pub(super) fn uv_fs_event_start(); + pub(super) fn uv_fs_event_stop(); + pub(super) fn uv_fs_fchmod(); + pub(super) fn uv_fs_fchown(); + pub(super) fn uv_fs_fdatasync(); + pub(super) fn uv_fs_fstat(); + pub(super) fn uv_fs_fsync(); + pub(super) fn uv_fs_ftruncate(); + pub(super) fn uv_fs_futime(); + pub(super) fn uv_fs_get_path(); + pub(super) fn uv_fs_get_ptr(); + pub(super) fn uv_fs_get_result(); + pub(super) fn uv_fs_get_statbuf(); + pub(super) fn uv_fs_get_system_error(); + pub(super) fn uv_fs_get_type(); + pub(super) fn uv_fs_lchown(); + pub(super) fn uv_fs_link(); + pub(super) fn uv_fs_lstat(); + pub(super) fn uv_fs_lutime(); + pub(super) fn uv_fs_mkdir(); + pub(super) fn uv_fs_mkdtemp(); + pub(super) fn uv_fs_mkstemp(); + pub(super) fn uv_fs_open(); + pub(super) fn uv_fs_opendir(); + pub(super) fn uv_fs_poll_getpath(); + pub(super) fn uv_fs_poll_init(); + pub(super) fn uv_fs_poll_start(); + pub(super) fn uv_fs_poll_stop(); + pub(super) fn uv_fs_read(); + pub(super) fn uv_fs_readdir(); + pub(super) fn uv_fs_readlink(); + pub(super) fn uv_fs_realpath(); + pub(super) fn uv_fs_rename(); + pub(super) fn uv_fs_req_cleanup(); + pub(super) fn uv_fs_rmdir(); + pub(super) fn uv_fs_scandir(); + pub(super) fn uv_fs_scandir_next(); + pub(super) fn uv_fs_sendfile(); + pub(super) fn uv_fs_stat(); + pub(super) fn uv_fs_statfs(); + pub(super) fn uv_fs_symlink(); + pub(super) fn uv_fs_unlink(); + pub(super) fn uv_fs_utime(); + pub(super) fn uv_fs_write(); + pub(super) fn uv_get_available_memory(); + pub(super) fn uv_get_constrained_memory(); + pub(super) fn uv_get_free_memory(); + pub(super) fn uv_get_osfhandle(); + pub(super) fn uv_get_process_title(); + pub(super) fn uv_get_total_memory(); + pub(super) fn uv_getaddrinfo(); + pub(super) fn uv_getnameinfo(); + pub(super) fn uv_getrusage(); + pub(super) fn uv_getrusage_thread(); + pub(super) fn uv_gettimeofday(); + pub(super) fn uv_guess_handle(); + pub(super) fn uv_handle_get_data(); + pub(super) fn uv_handle_get_loop(); + pub(super) fn uv_handle_get_type(); + pub(super) fn uv_handle_set_data(); + pub(super) fn uv_handle_size(); + pub(super) fn uv_handle_type_name(); + pub(super) fn uv_has_ref(); + pub(super) fn uv_hrtime(); + pub(super) fn uv_idle_init(); + pub(super) fn uv_idle_start(); + pub(super) fn uv_idle_stop(); + pub(super) fn uv_if_indextoiid(); + pub(super) fn uv_if_indextoname(); + pub(super) fn uv_inet_ntop(); + pub(super) fn uv_inet_pton(); + pub(super) fn uv_interface_addresses(); + pub(super) fn uv_ip_name(); + pub(super) fn uv_ip4_addr(); + pub(super) fn uv_ip4_name(); + pub(super) fn uv_ip6_addr(); + pub(super) fn uv_ip6_name(); + pub(super) fn uv_is_active(); + pub(super) fn uv_is_closing(); + pub(super) fn uv_is_readable(); + pub(super) fn uv_is_writable(); + pub(super) fn uv_key_create(); + pub(super) fn uv_key_delete(); + pub(super) fn uv_key_get(); + pub(super) fn uv_key_set(); + pub(super) fn uv_kill(); + pub(super) fn uv_library_shutdown(); + pub(super) fn uv_listen(); + pub(super) fn uv_loadavg(); + pub(super) fn uv_loop_alive(); + pub(super) fn uv_loop_close(); + pub(super) fn uv_loop_configure(); + pub(super) fn uv_loop_delete(); + pub(super) fn uv_loop_fork(); + pub(super) fn uv_loop_get_data(); + pub(super) fn uv_loop_init(); + pub(super) fn uv_loop_new(); + pub(super) fn uv_loop_set_data(); + pub(super) fn uv_loop_size(); + pub(super) fn uv_metrics_idle_time(); + pub(super) fn uv_metrics_info(); + pub(super) fn uv_mutex_destroy(); + pub(super) fn uv_mutex_init(); + pub(super) fn uv_mutex_init_recursive(); + pub(super) fn uv_mutex_lock(); + pub(super) fn uv_mutex_trylock(); + pub(super) fn uv_mutex_unlock(); + pub(super) fn uv_now(); + pub(super) fn uv_once(); + pub(super) fn uv_open_osfhandle(); + pub(super) fn uv_os_environ(); + pub(super) fn uv_os_free_environ(); + pub(super) fn uv_os_free_group(); + pub(super) fn uv_os_free_passwd(); + pub(super) fn uv_os_get_group(); + pub(super) fn uv_os_get_passwd(); + pub(super) fn uv_os_get_passwd2(); + pub(super) fn uv_os_getenv(); + pub(super) fn uv_os_gethostname(); + pub(super) fn uv_os_getpid(); + pub(super) fn uv_os_getppid(); + pub(super) fn uv_os_getpriority(); + pub(super) fn uv_os_homedir(); + pub(super) fn uv_os_setenv(); + pub(super) fn uv_os_setpriority(); + pub(super) fn uv_os_tmpdir(); + pub(super) fn uv_os_uname(); + pub(super) fn uv_os_unsetenv(); + pub(super) fn uv_pipe(); + pub(super) fn uv_pipe_bind(); + pub(super) fn uv_pipe_bind2(); + pub(super) fn uv_pipe_chmod(); + pub(super) fn uv_pipe_connect(); + pub(super) fn uv_pipe_connect2(); + pub(super) fn uv_pipe_getpeername(); + pub(super) fn uv_pipe_getsockname(); + pub(super) fn uv_pipe_init(); + pub(super) fn uv_pipe_open(); + pub(super) fn uv_pipe_pending_count(); + pub(super) fn uv_pipe_pending_instances(); + pub(super) fn uv_pipe_pending_type(); + pub(super) fn uv_poll_init(); + pub(super) fn uv_poll_init_socket(); + pub(super) fn uv_poll_start(); + pub(super) fn uv_poll_stop(); + pub(super) fn uv_prepare_init(); + pub(super) fn uv_prepare_start(); + pub(super) fn uv_prepare_stop(); + pub(super) fn uv_print_active_handles(); + pub(super) fn uv_print_all_handles(); + pub(super) fn uv_process_get_pid(); + pub(super) fn uv_process_kill(); + pub(super) fn uv_queue_work(); + pub(super) fn uv_random(); + pub(super) fn uv_read_start(); + pub(super) fn uv_read_stop(); + pub(super) fn uv_recv_buffer_size(); + pub(super) fn uv_ref(); + pub(super) fn uv_replace_allocator(); + pub(super) fn uv_req_get_data(); + pub(super) fn uv_req_get_type(); + pub(super) fn uv_req_set_data(); + pub(super) fn uv_req_size(); + pub(super) fn uv_req_type_name(); + pub(super) fn uv_resident_set_memory(); + pub(super) fn uv_run(); + pub(super) fn uv_rwlock_destroy(); + pub(super) fn uv_rwlock_init(); + pub(super) fn uv_rwlock_rdlock(); + pub(super) fn uv_rwlock_rdunlock(); + pub(super) fn uv_rwlock_tryrdlock(); + pub(super) fn uv_rwlock_trywrlock(); + pub(super) fn uv_rwlock_wrlock(); + pub(super) fn uv_rwlock_wrunlock(); + pub(super) fn uv_sem_destroy(); + pub(super) fn uv_sem_init(); + pub(super) fn uv_sem_post(); + pub(super) fn uv_sem_trywait(); + pub(super) fn uv_sem_wait(); + pub(super) fn uv_send_buffer_size(); + pub(super) fn uv_set_process_title(); + pub(super) fn uv_setup_args(); + pub(super) fn uv_shutdown(); + pub(super) fn uv_signal_init(); + pub(super) fn uv_signal_start(); + pub(super) fn uv_signal_start_oneshot(); + pub(super) fn uv_signal_stop(); + pub(super) fn uv_sleep(); + pub(super) fn uv_socketpair(); + pub(super) fn uv_spawn(); + pub(super) fn uv_stop(); + pub(super) fn uv_stream_get_write_queue_size(); + pub(super) fn uv_stream_set_blocking(); + pub(super) fn uv_strerror(); + pub(super) fn uv_strerror_r(); + pub(super) fn uv_tcp_bind(); + pub(super) fn uv_tcp_close_reset(); + pub(super) fn uv_tcp_connect(); + pub(super) fn uv_tcp_getpeername(); + pub(super) fn uv_tcp_getsockname(); + pub(super) fn uv_tcp_init(); + pub(super) fn uv_tcp_init_ex(); + pub(super) fn uv_tcp_keepalive(); + pub(super) fn uv_tcp_nodelay(); + pub(super) fn uv_tcp_open(); + pub(super) fn uv_tcp_simultaneous_accepts(); + pub(super) fn uv_thread_create(); + pub(super) fn uv_thread_create_ex(); + pub(super) fn uv_thread_detach(); + pub(super) fn uv_thread_equal(); + pub(super) fn uv_thread_getaffinity(); + pub(super) fn uv_thread_getcpu(); + pub(super) fn uv_thread_getname(); + pub(super) fn uv_thread_getpriority(); + pub(super) fn uv_thread_join(); + pub(super) fn uv_thread_self(); + pub(super) fn uv_thread_setaffinity(); + pub(super) fn uv_thread_setname(); + pub(super) fn uv_thread_setpriority(); + pub(super) fn uv_timer_again(); + pub(super) fn uv_timer_get_due_in(); + pub(super) fn uv_timer_get_repeat(); + pub(super) fn uv_timer_init(); + pub(super) fn uv_timer_set_repeat(); + pub(super) fn uv_timer_start(); + pub(super) fn uv_timer_stop(); + pub(super) fn uv_translate_sys_error(); + pub(super) fn uv_try_write(); + pub(super) fn uv_try_write2(); + pub(super) fn uv_tty_get_vterm_state(); + pub(super) fn uv_tty_get_winsize(); + pub(super) fn uv_tty_init(); + pub(super) fn uv_tty_reset_mode(); + pub(super) fn uv_tty_set_mode(); + pub(super) fn uv_tty_set_vterm_state(); + pub(super) fn uv_udp_bind(); + pub(super) fn uv_udp_connect(); + pub(super) fn uv_udp_get_send_queue_count(); + pub(super) fn uv_udp_get_send_queue_size(); + pub(super) fn uv_udp_getpeername(); + pub(super) fn uv_udp_getsockname(); + pub(super) fn uv_udp_init(); + pub(super) fn uv_udp_init_ex(); + pub(super) fn uv_udp_open(); + pub(super) fn uv_udp_recv_start(); + pub(super) fn uv_udp_recv_stop(); + pub(super) fn uv_udp_send(); + pub(super) fn uv_udp_set_broadcast(); + pub(super) fn uv_udp_set_membership(); + pub(super) fn uv_udp_set_multicast_interface(); + pub(super) fn uv_udp_set_multicast_loop(); + pub(super) fn uv_udp_set_multicast_ttl(); + pub(super) fn uv_udp_set_source_membership(); + pub(super) fn uv_udp_set_ttl(); + pub(super) fn uv_udp_try_send(); + pub(super) fn uv_udp_try_send2(); + pub(super) fn uv_udp_using_recvmmsg(); + pub(super) fn uv_unref(); + pub(super) fn uv_update_time(); + pub(super) fn uv_uptime(); + pub(super) fn uv_utf16_length_as_wtf8(); + pub(super) fn uv_utf16_to_wtf8(); + pub(super) fn uv_version(); + pub(super) fn uv_version_string(); + pub(super) fn uv_walk(); + pub(super) fn uv_write(); + pub(super) fn uv_write2(); + pub(super) fn uv_wtf8_length_as_utf16(); + pub(super) fn uv_wtf8_to_utf16(); + } +} +pub(super) fn keep() { + keep_symbols!( + napi_add_async_cleanup_hook, + napi_add_env_cleanup_hook, + napi_add_finalizer, + napi_adjust_external_memory, + napi_call_function, + napi_check_object_type_tag, + napi_coerce_to_bool, + napi_coerce_to_number, + napi_coerce_to_object, + napi_create_arraybuffer, + napi_create_bigint_int64, + napi_create_bigint_uint64, + napi_create_bigint_words, + napi_create_buffer, + napi_create_buffer_copy, + napi_create_dataview, + napi_create_double, + napi_create_error, + napi_create_external, + napi_create_external_arraybuffer, + napi_create_external_buffer, + napi_create_object, + napi_create_range_error, + napi_create_reference, + napi_create_symbol, + napi_create_type_error, + napi_create_typedarray, + napi_define_class, + napi_define_properties, + napi_delete_element, + napi_delete_reference, + napi_detach_arraybuffer, + napi_fatal_exception, + napi_get_all_property_names, + napi_get_and_clear_last_exception, + napi_get_cb_info, + napi_get_date_value, + napi_get_element, + napi_get_global, + napi_get_instance_data, + napi_get_last_error_info, + napi_get_new_target, + napi_get_reference_value, + napi_get_value_bigint_int64, + napi_get_value_bigint_uint64, + napi_get_value_bigint_words, + napi_get_value_bool, + napi_get_value_double, + napi_get_value_external, + napi_get_value_int32, + napi_get_value_int64, + napi_get_value_string_latin1, + napi_get_value_string_utf16, + napi_get_value_string_utf8, + napi_get_value_uint32, + napi_has_element, + napi_instanceof, + napi_is_buffer, + napi_is_detached_arraybuffer, + napi_is_exception_pending, + napi_is_typedarray, + napi_new_instance, + napi_reference_ref, + napi_reference_unref, + napi_remove_async_cleanup_hook, + napi_remove_env_cleanup_hook, + napi_remove_wrap, + napi_run_script, + napi_set_element, + napi_set_instance_data, + napi_throw, + napi_throw_error, + napi_throw_range_error, + napi_throw_type_error, + napi_type_tag_object, + napi_typeof, + napi_unwrap, + napi_wrap, + node_api_create_syntax_error, + node_api_symbol_for, + node_api_throw_syntax_error, + node_api_create_external_string_latin1, + node_api_create_external_string_utf16, + node_api_set_prototype, + node_api_create_object_with_properties, + node_api_create_sharedarraybuffer, + node_api_create_external_sharedarraybuffer, + node_api_is_sharedarraybuffer, + ); + #[cfg(unix)] + { + use uv_functions_to_export::*; + keep_symbols!( + uv_accept, + uv_async_init, + uv_async_send, + uv_available_parallelism, + uv_backend_fd, + uv_backend_timeout, + uv_barrier_destroy, + uv_barrier_init, + uv_barrier_wait, + uv_buf_init, + uv_cancel, + uv_chdir, + uv_check_init, + uv_check_start, + uv_check_stop, + uv_clock_gettime, + uv_close, + uv_cond_broadcast, + uv_cond_destroy, + uv_cond_init, + uv_cond_signal, + uv_cond_timedwait, + uv_cond_wait, + uv_cpu_info, + uv_cpumask_size, + uv_cwd, + uv_default_loop, + uv_disable_stdio_inheritance, + uv_dlclose, + uv_dlerror, + uv_dlopen, + uv_dlsym, + uv_err_name, + uv_err_name_r, + uv_exepath, + uv_fileno, + uv_free_cpu_info, + uv_free_interface_addresses, + uv_freeaddrinfo, + uv_fs_access, + uv_fs_chmod, + uv_fs_chown, + uv_fs_close, + uv_fs_closedir, + uv_fs_copyfile, + uv_fs_event_getpath, + uv_fs_event_init, + uv_fs_event_start, + uv_fs_event_stop, + uv_fs_fchmod, + uv_fs_fchown, + uv_fs_fdatasync, + uv_fs_fstat, + uv_fs_fsync, + uv_fs_ftruncate, + uv_fs_futime, + uv_fs_get_path, + uv_fs_get_ptr, + uv_fs_get_result, + uv_fs_get_statbuf, + uv_fs_get_system_error, + uv_fs_get_type, + uv_fs_lchown, + uv_fs_link, + uv_fs_lstat, + uv_fs_lutime, + uv_fs_mkdir, + uv_fs_mkdtemp, + uv_fs_mkstemp, + uv_fs_open, + uv_fs_opendir, + uv_fs_poll_getpath, + uv_fs_poll_init, + uv_fs_poll_start, + uv_fs_poll_stop, + uv_fs_read, + uv_fs_readdir, + uv_fs_readlink, + uv_fs_realpath, + uv_fs_rename, + uv_fs_req_cleanup, + uv_fs_rmdir, + uv_fs_scandir, + uv_fs_scandir_next, + uv_fs_sendfile, + uv_fs_stat, + uv_fs_statfs, + uv_fs_symlink, + uv_fs_unlink, + uv_fs_utime, + uv_fs_write, + uv_get_available_memory, + uv_get_constrained_memory, + uv_get_free_memory, + uv_get_osfhandle, + uv_get_process_title, + uv_get_total_memory, + uv_getaddrinfo, + uv_getnameinfo, + uv_getrusage, + uv_getrusage_thread, + uv_gettimeofday, + uv_guess_handle, + uv_handle_get_data, + uv_handle_get_loop, + uv_handle_get_type, + uv_handle_set_data, + uv_handle_size, + uv_handle_type_name, + uv_has_ref, + uv_hrtime, + uv_idle_init, + uv_idle_start, + uv_idle_stop, + uv_if_indextoiid, + uv_if_indextoname, + uv_inet_ntop, + uv_inet_pton, + uv_interface_addresses, + uv_ip_name, + uv_ip4_addr, + uv_ip4_name, + uv_ip6_addr, + uv_ip6_name, + uv_is_active, + uv_is_closing, + uv_is_readable, + uv_is_writable, + uv_key_create, + uv_key_delete, + uv_key_get, + uv_key_set, + uv_kill, + uv_library_shutdown, + uv_listen, + uv_loadavg, + uv_loop_alive, + uv_loop_close, + uv_loop_configure, + uv_loop_delete, + uv_loop_fork, + uv_loop_get_data, + uv_loop_init, + uv_loop_new, + uv_loop_set_data, + uv_loop_size, + uv_metrics_idle_time, + uv_metrics_info, + uv_mutex_destroy, + uv_mutex_init, + uv_mutex_init_recursive, + uv_mutex_lock, + uv_mutex_trylock, + uv_mutex_unlock, + uv_now, + uv_once, + uv_open_osfhandle, + uv_os_environ, + uv_os_free_environ, + uv_os_free_group, + uv_os_free_passwd, + uv_os_get_group, + uv_os_get_passwd, + uv_os_get_passwd2, + uv_os_getenv, + uv_os_gethostname, + uv_os_getpid, + uv_os_getppid, + uv_os_getpriority, + uv_os_homedir, + uv_os_setenv, + uv_os_setpriority, + uv_os_tmpdir, + uv_os_uname, + uv_os_unsetenv, + uv_pipe, + uv_pipe_bind, + uv_pipe_bind2, + uv_pipe_chmod, + uv_pipe_connect, + uv_pipe_connect2, + uv_pipe_getpeername, + uv_pipe_getsockname, + uv_pipe_init, + uv_pipe_open, + uv_pipe_pending_count, + uv_pipe_pending_instances, + uv_pipe_pending_type, + uv_poll_init, + uv_poll_init_socket, + uv_poll_start, + uv_poll_stop, + uv_prepare_init, + uv_prepare_start, + uv_prepare_stop, + uv_print_active_handles, + uv_print_all_handles, + uv_process_get_pid, + uv_process_kill, + uv_queue_work, + uv_random, + uv_read_start, + uv_read_stop, + uv_recv_buffer_size, + uv_ref, + uv_replace_allocator, + uv_req_get_data, + uv_req_get_type, + uv_req_set_data, + uv_req_size, + uv_req_type_name, + uv_resident_set_memory, + uv_run, + uv_rwlock_destroy, + uv_rwlock_init, + uv_rwlock_rdlock, + uv_rwlock_rdunlock, + uv_rwlock_tryrdlock, + uv_rwlock_trywrlock, + uv_rwlock_wrlock, + uv_rwlock_wrunlock, + uv_sem_destroy, + uv_sem_init, + uv_sem_post, + uv_sem_trywait, + uv_sem_wait, + uv_send_buffer_size, + uv_set_process_title, + uv_setup_args, + uv_shutdown, + uv_signal_init, + uv_signal_start, + uv_signal_start_oneshot, + uv_signal_stop, + uv_sleep, + uv_socketpair, + uv_spawn, + uv_stop, + uv_stream_get_write_queue_size, + uv_stream_set_blocking, + uv_strerror, + uv_strerror_r, + uv_tcp_bind, + uv_tcp_close_reset, + uv_tcp_connect, + uv_tcp_getpeername, + uv_tcp_getsockname, + uv_tcp_init, + uv_tcp_init_ex, + uv_tcp_keepalive, + uv_tcp_nodelay, + uv_tcp_open, + uv_tcp_simultaneous_accepts, + uv_thread_create, + uv_thread_create_ex, + uv_thread_detach, + uv_thread_equal, + uv_thread_getaffinity, + uv_thread_getcpu, + uv_thread_getname, + uv_thread_getpriority, + uv_thread_join, + uv_thread_self, + uv_thread_setaffinity, + uv_thread_setname, + uv_thread_setpriority, + uv_timer_again, + uv_timer_get_due_in, + uv_timer_get_repeat, + uv_timer_init, + uv_timer_set_repeat, + uv_timer_start, + uv_timer_stop, + uv_translate_sys_error, + uv_try_write, + uv_try_write2, + uv_tty_get_vterm_state, + uv_tty_get_winsize, + uv_tty_init, + uv_tty_reset_mode, + uv_tty_set_mode, + uv_tty_set_vterm_state, + uv_udp_bind, + uv_udp_connect, + uv_udp_get_send_queue_count, + uv_udp_get_send_queue_size, + uv_udp_getpeername, + uv_udp_getsockname, + uv_udp_init, + uv_udp_init_ex, + uv_udp_open, + uv_udp_recv_start, + uv_udp_recv_stop, + uv_udp_send, + uv_udp_set_broadcast, + uv_udp_set_membership, + uv_udp_set_multicast_interface, + uv_udp_set_multicast_loop, + uv_udp_set_multicast_ttl, + uv_udp_set_source_membership, + uv_udp_set_ttl, + uv_udp_try_send, + uv_udp_try_send2, + uv_udp_using_recvmmsg, + uv_unref, + uv_update_time, + uv_uptime, + uv_utf16_length_as_wtf8, + uv_utf16_to_wtf8, + uv_version, + uv_version_string, + uv_walk, + uv_write, + uv_write2, + uv_wtf8_length_as_utf16, + uv_wtf8_to_utf16, + ); + } + #[cfg(not(windows))] + { + use v8_api::*; + keep_symbols!( + _ZN2v87Isolate10GetCurrentEv, + _ZN2v87Isolate13TryGetCurrentEv, + _ZN2v87Isolate17GetCurrentContextEv, + _ZN2v87Isolate28GetEnteredOrMicrotaskContextEv, + _ZN2v87Isolate36GetContinuationPreservedEmbedderDataEv, + _ZN2v87Isolate7IsInUseEv, + _ZN2v87Isolate21LowMemoryNotificationEv, + _ZN2v87Isolate36AutomaticallyRestoreInitialHeapLimitEd, + _ZN2v87Isolate30NumberOfTrackedHeapObjectTypesEv, + _ZN2v87Isolate31GetHeapObjectStatisticsAtLastGCEPNS_20HeapObjectStatisticsEm, + _ZN2v87Isolate21AddGCPrologueCallbackEPFvPS0_NS_6GCTypeENS_15GCCallbackFlagsEPvES4_S2_, + _ZN2v87Isolate24RemoveGCPrologueCallbackEPFvPS0_NS_6GCTypeENS_15GCCallbackFlagsEPvES4_, + _ZN2v87Isolate21AddGCEpilogueCallbackEPFvPS0_NS_6GCTypeENS_15GCCallbackFlagsEPvES4_S2_, + _ZN2v87Isolate24RemoveGCEpilogueCallbackEPFvPS0_NS_6GCTypeENS_15GCCallbackFlagsEPvES4_, + _ZN2v87Isolate24AddNearHeapLimitCallbackEPFmPvmmES1_, + _ZN2v87Isolate27RemoveNearHeapLimitCallbackEPFmPvmmEm, + _ZN2v87Isolate16RequestInterruptEPFvPS0_PvES2_, + _ZN2v87Isolate14ThrowExceptionENS_5LocalINS_5ValueEEE, + _ZN2v87Isolate10ThrowErrorENS_5LocalINS_6StringEEE, + _ZN2v89Exception5ErrorENS_5LocalINS_6StringEEENS1_INS_5ValueEEE, + _ZN2v89Exception9TypeErrorENS_5LocalINS_6StringEEENS1_INS_5ValueEEE, + _ZN2v87Isolate15GetHeapProfilerEv, + _ZN2v812HeapProfiler24StopSamplingHeapProfilerEv, + _ZN2v812HeapProfiler20GetAllocationProfileEv, + _ZN4node25AddEnvironmentCleanupHookEPN2v87IsolateEPFvPvES3_, + _ZN4node28RemoveEnvironmentCleanupHookEPN2v87IsolateEPFvPvES3_, + _ZN4node19GetCurrentEventLoopEPN2v87IsolateE, + _ZN4node29AsyncHooksGetExecutionAsyncIdEN2v85LocalINS0_7ContextEEE, + _ZN4node13EmitAsyncInitEPN2v87IsolateENS0_5LocalINS0_6ObjectEEENS3_INS0_6StringEEEd, + _ZN4node16EmitAsyncDestroyEPN2v87IsolateENS_13async_contextE, + _ZN4node12MakeCallbackEPN2v87IsolateENS0_5LocalINS0_6ObjectEEENS3_INS0_8FunctionEEEiPNS3_INS0_5ValueEEENS_13async_contextE, + _ZN2v84base9TimeTicks3NowEv, + _ZN2v86Number3NewEPNS_7IsolateEd, + _ZNK2v86Number5ValueEv, + _ZN2v86Number12NewFromInt32EPNS_7IsolateEi, + _ZN2v86Number13NewFromUint32EPNS_7IsolateEj, + _ZN2v86String11NewFromUtf8EPNS_7IsolateEPKcNS_13NewStringTypeEi, + _ZNK2v86String9WriteUtf8EPNS_7IsolateEPciPii, + _ZN2v812api_internal12ToLocalEmptyEv, + _ZNK2v86String6LengthEv, + _ZN2v88External3NewEPNS_7IsolateEPv, + _ZNK2v88External5ValueEv, + _ZN2v88External3NewEPNS_7IsolateEPvt, + _ZNK2v88External5ValueEt, + _ZN2v86Object3NewEPNS_7IsolateE, + _ZN2v86Object3SetENS_5LocalINS_7ContextEEENS1_INS_5ValueEEES5_, + _ZN2v86Object3SetENS_5LocalINS_7ContextEEEjNS1_INS_5ValueEEE, + _ZN2v86Object16SetInternalFieldEiNS_5LocalINS_4DataEEE, + _ZN2v86Object20SlowGetInternalFieldEi, + _ZN2v86Object32SetAlignedPointerInInternalFieldEiPvt, + _ZN2v86Object38SlowGetAlignedPointerFromInternalFieldEit, + _ZN2v86Object3GetENS_5LocalINS_7ContextEEENS1_INS_5ValueEEE, + _ZN2v86Object3GetENS_5LocalINS_7ContextEEEj, + _ZN2v811HandleScope12CreateHandleEPNS_8internal7IsolateEm, + _ZN2v811HandleScope12CreateHandleEPNS_7IsolateEm, + _ZN2v811HandleScope10InitializeEPNS_7IsolateE, + _ZNK2v85Value16QuickIsUndefinedEv, + _ZNK2v85Value11QuickIsNullEv, + _ZNK2v85Value22QuickIsNullOrUndefinedEv, + _ZNK2v85Value13QuickIsStringEv, + _ZN2v811HandleScope6ExtendEPNS_7IsolateE, + _ZN2v811HandleScope16DeleteExtensionsEPNS_7IsolateE, + _ZN2v811HandleScopeC1EPNS_7IsolateE, + _ZN2v811HandleScopeD1Ev, + _ZN2v811HandleScopeD2Ev, + _ZN2v816FunctionTemplate11GetFunctionENS_5LocalINS_7ContextEEE, + _ZN2v816FunctionTemplate12SetClassNameENS_5LocalINS_6StringEEE, + _ZN2v816FunctionTemplate3NewEPNS_7IsolateEPFvRKNS_20FunctionCallbackInfoINS_5ValueEEEENS_5LocalIS4_EENSA_INS_9SignatureEEEiNS_19ConstructorBehaviorENS_14SideEffectTypeEPKNS_9CFunctionEttt, + _ZN2v814ObjectTemplate11NewInstanceENS_5LocalINS_7ContextEEE, + _ZN2v814ObjectTemplate21SetInternalFieldCountEi, + _ZNK2v814ObjectTemplate18InternalFieldCountEv, + _ZN2v814ObjectTemplate3NewEPNS_7IsolateENS_5LocalINS_16FunctionTemplateEEE, + _ZN2v816FunctionTemplate16InstanceTemplateEv, + _ZN2v816FunctionTemplate17PrototypeTemplateEv, + _ZN2v88Template3SetENS_5LocalINS_4NameEEENS1_INS_4DataEEENS_17PropertyAttributeE, + _ZN2v88Template21SetNativeDataPropertyENS_5LocalINS_4NameEEEPFvS3_RKNS_20PropertyCallbackInfoINS_5ValueEEEEPFvS3_NS1_IS5_EERKNS4_IvEEESB_NS_17PropertyAttributeENS_14SideEffectTypeESI_, + _ZN2v89Signature3NewEPNS_7IsolateENS_5LocalINS_16FunctionTemplateEEE, + _ZN2v824EscapableHandleScopeBase10EscapeSlotEPm, + _ZN2v824EscapableHandleScopeBaseC2EPNS_7IsolateE, + _ZN2v88internal35IsolateFromNeverReadOnlySpaceObjectEm, + _ZN2v85Array3NewEPNS_7IsolateEPNS_5LocalINS_5ValueEEEm, + _ZNK2v85Array6LengthEv, + _ZN2v85Array3NewEPNS_7IsolateEi, + _ZN2v85Array7IterateENS_5LocalINS_7ContextEEEPFNS0_14CallbackResultEjNS1_INS_5ValueEEEPvES7_, + _ZN2v85Array9CheckCastEPNS_5ValueE, + _ZN2v88Function7SetNameENS_5LocalINS_6StringEEE, + _ZN2v88Function4CallENS_5LocalINS_7ContextEEENS1_INS_5ValueEEEiPS5_, + _ZNK2v88Function11NewInstanceENS_5LocalINS_7ContextEEEiPNS1_INS_5ValueEEE, + _ZNK2v85Value9IsBooleanEv, + _ZNK2v87Boolean5ValueEv, + _ZNK2v85Value10FullIsTrueEv, + _ZNK2v85Value11FullIsFalseEv, + _ZN2v820EscapableHandleScopeC1EPNS_7IsolateE, + _ZN2v820EscapableHandleScopeC2EPNS_7IsolateE, + _ZN2v820EscapableHandleScopeD1Ev, + _ZN2v820EscapableHandleScopeD2Ev, + _ZNK2v85Value8IsObjectEv, + _ZNK2v85Value8IsNumberEv, + _ZNK2v85Value8IsUint32Ev, + _ZNK2v85Value11Uint32ValueENS_5LocalINS_7ContextEEE, + _ZNK2v85Value11IsUndefinedEv, + _ZNK2v85Value6IsNullEv, + _ZNK2v85Value17IsNullOrUndefinedEv, + _ZNK2v85Value6IsTrueEv, + _ZNK2v85Value7IsFalseEv, + _ZNK2v85Value8IsStringEv, + _ZNK2v85Value12StrictEqualsENS_5LocalIS0_EE, + _ZN2v87Boolean3NewEPNS_7IsolateEb, + _ZN2v811ArrayBuffer3NewEPNS_7IsolateEmNS_30BackingStoreInitializationModeE, + _ZN2v811ArrayBuffer15GetBackingStoreEv, + _ZNK2v812BackingStore4DataEv, + _ZN2v815ArrayBufferView6BufferEv, + _ZN2v815ArrayBufferView10ByteLengthEv, + _ZN2v815ArrayBufferView10ByteOffsetEv, + _ZN2v810Uint8Array3NewENS_5LocalINS_11ArrayBufferEEEmm, + _ZN2v811Uint32Array3NewENS_5LocalINS_11ArrayBufferEEEmm, + _ZN2v86Object16GetInternalFieldEi, + _ZN2v87Context10GetIsolateEv, + _ZN2v86String14NewFromOneByteEPNS_7IsolateEPKhNS_13NewStringTypeEi, + _ZNK2v86String10Utf8LengthEPNS_7IsolateE, + _ZNK2v86String10IsExternalEv, + _ZNK2v86String17IsExternalOneByteEv, + _ZNK2v86String17IsExternalTwoByteEv, + _ZNK2v86String9IsOneByteEv, + _ZNK2v86String19ContainsOnlyOneByteEv, + _ZNK2v86String7WriteV2EPNS_7IsolateEjjPti, + _ZNK2v86String14WriteOneByteV2EPNS_7IsolateEjjPhi, + _ZNK2v86String11WriteUtf8V2EPNS_7IsolateEPcmiPm, + _ZNK2v86String12Utf8LengthV2EPNS_7IsolateE, + _ZN2v812api_internal18GlobalizeReferenceEPNS_8internal7IsolateEm, + _ZN2v812api_internal13DisposeGlobalEPm, + _ZN2v812api_internal8MakeWeakEPmPvPFvRKNS_16WeakCallbackInfoIvEEENS_16WeakCallbackTypeE, + _ZN2v812api_internal9ClearWeakEPm, + _ZN2v812api_internal19MoveGlobalReferenceEPPmS2_, + _ZN2v812api_internal23GetFunctionTemplateDataEPNS_7IsolateENS_5LocalINS_4DataEEE, + _ZNK2v88Function7GetNameEv, + _ZNK2v85Value10IsFunctionEv, + _ZNK2v85Value5IsMapEv, + _ZNK2v85Value7IsArrayEv, + _ZNK2v85Value7IsInt32Ev, + _ZNK2v85Value8IsBigIntEv, + _ZN2v812api_internal17FromJustIsNothingEv, + _ZN2v87Integer3NewEPNS_7IsolateEi, + _ZN2v87Integer15NewFromUnsignedEPNS_7IsolateEj, + _ZNK2v87Integer5ValueEv, + _ZN2v86String18NewFromUtf8LiteralEPNS_7IsolateEPKcNS_13NewStringTypeEi, + _ZNK2v85Value12IsUint8ArrayEv, + _ZNK2v85Value8ToStringENS_5LocalINS_7ContextEEE, + _ZNK2v85Value9ToIntegerENS_5LocalINS_7ContextEEE, + _ZN2v87Context6GlobalEv, + _ZNK2v86Object18InternalFieldCountEv, + _ZN2v86Object15GetIdentityHashEv, + _ZN2v86Object17DefineOwnPropertyENS_5LocalINS_7ContextEEENS1_INS_4NameEEENS1_INS_5ValueEEENS_17PropertyAttributeE, + _ZN2v820ToExternalPointerTagEt, + _ZN2v88internal9Internals17GetCurrentIsolateEv, + _ZN2v820HeapObjectStatisticsC1Ev, + _ZN2v811CpuProfiler3NewEPNS_7IsolateENS_22CpuProfilingNamingModeENS_23CpuProfilingLoggingModeE, + _ZN2v811CpuProfiler7DisposeEv, + _ZN2v811CpuProfiler19SetSamplingIntervalEi, + _ZN2v811CpuProfiler5StartENS_5LocalINS_6StringEEENS_16CpuProfilingModeEbj, + _ZN2v811CpuProfiler4StopEj, + _ZN2v811CpuProfiler14StartProfilingENS_5LocalINS_6StringEEENS_16CpuProfilingModeEbj, + _ZN2v811CpuProfiler14StartProfilingENS_5LocalINS_6StringEEEb, + _ZN2v811CpuProfiler13StopProfilingENS_5LocalINS_6StringEEE, + _ZN2v810CpuProfile6DeleteEv, + _ZNK2v810CpuProfile8GetTitleEv, + _ZNK2v810CpuProfile10GetEndTimeEv, + _ZNK2v810CpuProfile12GetStartTimeEv, + _ZNK2v810CpuProfile14GetTopDownRootEv, + _ZNK2v810CpuProfile15GetSamplesCountEv, + _ZNK2v810CpuProfile18GetSampleTimestampEi, + _ZNK2v810CpuProfile9GetSampleEi, + _ZNK2v814CpuProfileNode11GetHitCountEv, + _ZNK2v814CpuProfileNode11GetScriptIdEv, + _ZNK2v814CpuProfileNode12GetLineTicksEPNS0_8LineTickEj, + _ZNK2v814CpuProfileNode13GetLineNumberEv, + _ZNK2v814CpuProfileNode15GetColumnNumberEv, + _ZNK2v814CpuProfileNode15GetFunctionNameEv, + _ZNK2v814CpuProfileNode15GetHitLineCountEv, + _ZNK2v814CpuProfileNode16GetChildrenCountEv, + _ZNK2v814CpuProfileNode18GetFunctionNameStrEv, + _ZNK2v814CpuProfileNode21GetScriptResourceNameEv, + _ZNK2v814CpuProfileNode8GetChildEi, + _ZN2v83Map3SetENS_5LocalINS_7ContextEEENS1_INS_5ValueEEES5_, + _ZN2v83Map6DeleteENS_5LocalINS_7ContextEEENS1_INS_5ValueEEE, + uv_os_getpid, + uv_os_getppid, + ); + } + #[cfg(windows)] + { + use v8_api::*; + keep_symbols!( + v8_Isolate_TryGetCurrent, + v8_Isolate_GetCurrent, + v8_Isolate_GetCurrentContext, + v8_Isolate_GetEnteredOrMicrotaskContext, + v8_Isolate_GetContinuationPreservedEmbedderData, + v8_Isolate_IsInUse, + v8_Isolate_LowMemoryNotification, + v8_Isolate_AutomaticallyRestoreInitialHeapLimit, + v8_Isolate_NumberOfTrackedHeapObjectTypes, + v8_Isolate_GetHeapObjectStatisticsAtLastGC, + v8_Isolate_AddGCPrologueCallback, + v8_Isolate_RemoveGCPrologueCallback, + v8_Isolate_AddGCEpilogueCallback, + v8_Isolate_RemoveGCEpilogueCallback, + v8_Isolate_AddNearHeapLimitCallback, + v8_Isolate_RemoveNearHeapLimitCallback, + v8_Isolate_RequestInterrupt, + v8_Isolate_ThrowException, + v8_Isolate_ThrowError, + v8_Exception_Error, + v8_Exception_TypeError, + v8_Isolate_GetHeapProfiler, + v8_HeapProfiler_StartSamplingHeapProfiler, + v8_HeapProfiler_StopSamplingHeapProfiler, + v8_HeapProfiler_GetAllocationProfile, + node_AddEnvironmentCleanupHook, + node_RemoveEnvironmentCleanupHook, + node_GetCurrentEventLoop, + node_AsyncHooksGetExecutionAsyncId, + node_EmitAsyncInit, + node_EmitAsyncDestroy, + node_MakeCallback, + v8_base_TimeTicks_Now, + v8_Number_New, + v8_Number_Value, + v8_Number_NewFromInt32, + v8_Number_NewFromUint32, + v8_String_NewFromUtf8, + v8_String_WriteUtf8, + v8_api_internal_ToLocalEmpty, + v8_String_Length, + v8_External_New, + v8_External_Value, + v8_External_New_tagged, + v8_External_Value_tagged, + v8_Object_New, + v8_Object_Set_key, + v8_Object_Set_index, + v8_Object_SetInternalField, + v8_Object_SlowGetInternalField, + v8_Object_SetAlignedPointerInInternalField, + v8_Object_SlowGetAlignedPointerFromInternalField, + v8_Object_Get_index, + v8_Object_Get_key, + v8_HandleScope_CreateHandle, + v8_HandleScope_Extend, + v8_HandleScope_DeleteExtensions, + v8_HandleScope_ctor, + v8_HandleScope_dtor, + v8_FunctionTemplate_GetFunction, + v8_FunctionTemplate_SetClassName, + v8_FunctionTemplate_New, + v8_ObjectTemplate_NewInstance, + v8_ObjectTemplate_SetInternalFieldCount, + v8_ObjectTemplate_InternalFieldCount, + v8_ObjectTemplate_New, + v8_FunctionTemplate_InstanceTemplate, + v8_FunctionTemplate_PrototypeTemplate, + v8_Template_Set, + v8_Template_SetNativeDataProperty, + v8_Signature_New, + v8_EscapableHandleScopeBase_EscapeSlot, + v8_EscapableHandleScopeBase_ctor, + v8_internal_IsolateFromNeverReadOnlySpaceObject, + v8_Array_New_elements, + v8_Array_Length, + v8_Array_New_len, + v8_Array_New_fn, + v8_Array_Iterate, + v8_Array_CheckCast, + v8_Function_SetName, + v8_Function_Call, + v8_Function_NewInstance, + v8_Function_NewInstance_noargs, + v8_Object_GetAlignedPointerFromInternalField, + v8_Value_IsBoolean, + v8_Boolean_Value, + v8_Value_FullIsTrue, + v8_Value_FullIsFalse, + v8_EscapableHandleScope_dtor, + v8_EscapableHandleScope_ctor, + v8_Value_IsObject, + v8_Value_IsNumber, + v8_Value_IsUint32, + v8_Value_Uint32Value, + v8_Value_IsUndefined, + v8_Value_IsNull, + v8_Value_IsNullOrUndefined, + v8_Value_IsTrue, + v8_Value_IsFalse, + v8_Value_IsString, + v8_Value_StrictEquals, + v8_Boolean_New, + v8_Object_GetInternalField, + v8_Context_GetIsolate, + v8_String_NewFromOneByte, + v8_String_IsExternal, + v8_String_IsExternalOneByte, + v8_String_IsExternalTwoByte, + v8_String_IsOneByte, + v8_String_Utf8Length, + v8_String_ContainsOnlyOneByte, + v8_String_WriteV2, + v8_String_WriteOneByteV2, + v8_String_WriteUtf8V2, + v8_String_Utf8LengthV2, + v8_api_internal_GlobalizeReference, + v8_api_internal_DisposeGlobal, + v8_api_internal_MakeWeak, + v8_api_internal_ClearWeak, + v8_api_internal_MoveGlobalReference, + v8_api_internal_GetFunctionTemplateData, + v8_Function_GetName, + v8_Value_IsFunction, + v8_Value_IsMap, + v8_Value_IsArray, + v8_Value_IsInt32, + v8_Value_IsBigInt, + v8_api_internal_FromJustIsNothing, + v8_Integer_New, + v8_Integer_NewFromUnsigned, + v8_Integer_Value, + v8_BigInt_New, + v8_String_NewFromUtf8Literal, + v8_Value_IsUint8Array, + v8_Value_ToString, + v8_Value_ToInteger, + v8_Context_Global, + v8_Object_InternalFieldCount, + v8_Object_GetIdentityHash, + v8_Object_DefineOwnProperty, + v8_ToExternalPointerTag, + v8_internal_Internals_GetCurrentIsolate, + v8_HeapObjectStatistics_ctor, + v8_ArrayBuffer_New, + v8_ArrayBuffer_GetBackingStore, + v8_BackingStore_Data, + v8_ArrayBufferView_Buffer, + v8_ArrayBufferView_ByteLength, + v8_ArrayBufferView_ByteOffset, + v8_Uint8Array_New, + v8_Uint32Array_New, + v8_CpuProfiler_New, + v8_CpuProfiler_Dispose, + v8_CpuProfiler_SetSamplingInterval, + v8_CpuProfiler_Start, + v8_CpuProfiler_Stop, + v8_CpuProfiler_StartProfiling_mode, + v8_CpuProfiler_StartProfiling, + v8_CpuProfiler_StopProfiling, + v8_CpuProfiler_CollectSample, + v8_CpuProfile_Delete, + v8_CpuProfile_GetTitle, + v8_CpuProfile_GetEndTime, + v8_CpuProfile_GetStartTime, + v8_CpuProfile_GetTopDownRoot, + v8_CpuProfile_GetSamplesCount, + v8_CpuProfile_GetSampleTimestamp, + v8_CpuProfile_GetSample, + v8_CpuProfileNode_GetHitCount, + v8_CpuProfileNode_GetScriptId, + v8_CpuProfileNode_GetLineTicks, + v8_CpuProfileNode_GetLineNumber, + v8_CpuProfileNode_GetColumnNumber, + v8_CpuProfileNode_GetFunctionName, + v8_CpuProfileNode_GetHitLineCount, + v8_CpuProfileNode_GetChildrenCount, + v8_CpuProfileNode_GetFunctionNameStr, + v8_CpuProfileNode_GetScriptResourceName, + v8_CpuProfileNode_GetChild, + v8_Map_Set, + v8_Map_Delete, + ); + } + #[cfg(all(not(windows), target_os = "android"))] + keep_symbols!( + posix_platform_specific_v8_apis::_ZN2v85Array3NewENS_5LocalINS_7ContextEEEmNSt6__ndk18functionIFNS_10MaybeLocalINS_5ValueEEEvEEE, + posix_platform_specific_v8_apis::_ZN2v811CpuProfiler13CollectSampleEPNS_7IsolateENSt6__ndk18optionalImEE, + posix_platform_specific_v8_apis::_ZN2v86BigInt3NewEPNS_7IsolateEl, + posix_platform_specific_v8_apis::_ZN2v812HeapProfiler25StartSamplingHeapProfilerEmiNS0_13SamplingFlagsE, + ); + #[cfg(all(not(windows), target_os = "macos"))] + keep_symbols!( + posix_platform_specific_v8_apis::_ZN2v85Array3NewENS_5LocalINS_7ContextEEEmNSt3__18functionIFNS_10MaybeLocalINS_5ValueEEEvEEE, + posix_platform_specific_v8_apis::_ZN2v811CpuProfiler13CollectSampleEPNS_7IsolateENSt3__18optionalIyEE, + posix_platform_specific_v8_apis::_ZN2v86BigInt3NewEPNS_7IsolateEx, + posix_platform_specific_v8_apis::_ZN2v812HeapProfiler25StartSamplingHeapProfilerEyiNS0_13SamplingFlagsE, + ); + #[cfg(all(not(windows), target_os = "freebsd"))] + keep_symbols!( + posix_platform_specific_v8_apis::_ZN2v85Array3NewENS_5LocalINS_7ContextEEEmNSt3__18functionIFNS_10MaybeLocalINS_5ValueEEEvEEE, + posix_platform_specific_v8_apis::_ZN2v811CpuProfiler13CollectSampleEPNS_7IsolateENSt3__18optionalImEE, + posix_platform_specific_v8_apis::_ZN2v86BigInt3NewEPNS_7IsolateEl, + posix_platform_specific_v8_apis::_ZN2v812HeapProfiler25StartSamplingHeapProfilerEmiNS0_13SamplingFlagsE, + ); + #[cfg(all( + not(windows), + not(target_os = "android"), + not(target_os = "macos"), + not(target_os = "freebsd") + ))] + keep_symbols!( + posix_platform_specific_v8_apis::_ZN2v85Array3NewENS_5LocalINS_7ContextEEEmSt8functionIFNS_10MaybeLocalINS_5ValueEEEvEE, + posix_platform_specific_v8_apis::_ZN2v811CpuProfiler13CollectSampleEPNS_7IsolateESt8optionalImE, + posix_platform_specific_v8_apis::_ZN2v86BigInt3NewEPNS_7IsolateEl, + posix_platform_specific_v8_apis::_ZN2v812HeapProfiler25StartSamplingHeapProfilerEmiNS0_13SamplingFlagsE, + ); +} diff --git a/src/runtime/napi/mod.rs b/src/runtime/napi/mod.rs index 00ec7ae369e2..f445353eedd4 100644 --- a/src/runtime/napi/mod.rs +++ b/src/runtime/napi/mod.rs @@ -1,27 +1,15 @@ //! Node-API (N-API) implementation. //! -//! The full implementation lives in `napi_body.rs` and depends on -//! `bun_jsc::{ConcurrentTask, Debugger, EventLoop, Strong, Task, -//! VirtualMachine}` method surface, `bun_collections::LinearFifo`, -//! `bun_threading::{Condvar, Mutex, WorkPool}`, `bun_output` macros. +//! The implementation lives in `napi_body.rs`; the FFI glue for the C++ +//! `napi_env` / handle-scope objects is `bun_jsc::napi`. #[path = "napi_body.rs"] -pub(crate) mod napi_body; +pub mod napi_body; +pub(crate) use bun_jsc::napi::NapiEnv; pub use napi_body::NapiStatus; pub(crate) use napi_body::{ - NapiFinalizerTask, ThreadSafeFunction, fix_dead_code_elimination, napi_async_work, + AsyncWorkCompletion, NapiFinalizerTask, TsfnDispatch, TsfnFinalize, fix_dead_code_elimination, }; -pub(crate) mod libc_check; - -// ─── compiling free items ──────────────────────────────────────────────────── - -bun_opaque::opaque_ffi! { - /// This is `struct napi_env__` from napi.h - pub(crate) struct NapiEnv; -} - -// ─── opaque type surface ───────────────────────────────────────────────────── -// TODO(blocked): bun_jsc::EventLoop (method surface) -// TODO(blocked): bun_collections::LinearFifo -// TODO(blocked): bun_threading::Condvar +pub mod libc_check; +mod link_symbols; diff --git a/src/runtime/napi/napi_body.rs b/src/runtime/napi/napi_body.rs index b0717f39c6f2..778768244bd8 100644 --- a/src/runtime/napi/napi_body.rs +++ b/src/runtime/napi/napi_body.rs @@ -1,76 +1,36 @@ //! Node-API (N-API) implementation. - -use core::ffi::{c_char, c_int, c_uint, c_void}; -use core::ptr; +//! +//! Every `napi_*` entry point is exported through a generated `extern "C"` +//! thunk (`HOST_EXPORT`); the argument types spell the N-API contract for +//! the raw pointers an addon passes: a nullable `napi_env` is +//! `Option<&NapiEnv>`, an out-parameter is [`Out`], an owned handle given +//! back is a `Box`, a handle the addon keeps using is a [`ThisPtr`]. + +use core::cell::Cell; +use core::ffi::{c_char, c_uint, c_void}; +use core::mem::{ManuallyDrop, MaybeUninit}; +use core::ptr::{self, NonNull}; use core::sync::atomic::{AtomicBool, AtomicI64, AtomicU8, AtomicU32, AtomicUsize, Ordering}; use bun_collections::LinearFifo; use bun_collections::linear_fifo::DynamicBuffer; use bun_event_loop::ConcurrentTask::AutoDeinit; -use bun_event_loop::{TaskTag, Taskable, task_tag}; +use bun_event_loop::{BoxedTask, TaskHop}; use bun_io::KeepAlive; use bun_jsc::StringJsc; use bun_jsc::bun_string_jsc; use bun_jsc::event_loop::{ConcurrentTaskItem as ConcurrentTask, EventLoop}; +use bun_jsc::napi::{NapiEnv, NapiEnvRef, NapiHandleScope, UngatedScope}; +use bun_jsc::rare_data::OwnedCleanupHook; use bun_jsc::virtual_machine::VirtualMachine; use bun_jsc::{ - self as jsc, CallFrame, Debugger, GlobalRef, JSGlobalObject, JSPromiseStrong, JSValue, - JsResult, StrongOptional, Task, + self as jsc, CallFrame, Debugger, JSGlobalObject, JSPromiseStrong, JSValue, JsResult, LoopKind, + StrongOptional, VmHandle, }; +use bun_ptr::{JsCell, RefPtr, ThisPtr}; use bun_threading::Condition as Condvar; -use bun_threading::Mutex; -use bun_threading::work_pool::{IntrusiveWorkTask as _, Task as WorkPoolTask, WorkPool}; - -// ─── local shims for upstream-crate gaps (see PORTING.md §extension traits) ─── - -/// Local extension shims for `JSValue` methods not yet surfaced on the -/// `bun_jsc::JSValue` type. -trait JSValueNapiExt { - fn is_async_context_frame(self) -> bool; -} - -unsafe extern "C" { - fn Bun__JSValue__isAsyncContextFrame(value: JSValue) -> bool; -} - -impl JSValueNapiExt for JSValue { - #[inline] - fn is_async_context_frame(self) -> bool { - // SAFETY: trivial FFI. - unsafe { Bun__JSValue__isAsyncContextFrame(self) } - } -} - -// `Taskable` impls for the napi heap tasks dispatched through the JS event loop. -impl Taskable for napi_async_work { - const TAG: TaskTag = task_tag::NapiAsyncWork; - /// Work the pool handed back during teardown: its `complete` callback is - /// how the addon learns the outcome and frees the work (Node calls it from - /// environment cleanup too); script it tries to run is refused at the boundary. - unsafe fn release_unrun(this: *mut Self) { - let global = VirtualMachine::get().global(); - // `Err` is left pending for the release dispatcher's fold. - // SAFETY: fn contract — the addon's live work object the pool posted. - let _ = unsafe { (*this).run_from_js(global) }; - } -} -impl Taskable for ThreadSafeFunction { - const TAG: TaskTag = task_tag::ThreadSafeFunction; - /// `this` is the TSFN itself, which the env's cleanup hook (`env_teardown`, - /// run with the exit handlers before the queue is released) already - /// neutralised or freed. Nothing to do, and `this` must not be dereferenced. - unsafe fn release_unrun(_: *mut Self) {} -} -impl Taskable for NapiFinalizerTask { - const TAG: TaskTag = task_tag::NapiFinalizerTask; - /// A finalizer queued before the loop stopped: Node runs an addon's - /// finalizers during environment cleanup (script already forbidden), and - /// an addon counts on them (external buffers freed when a Worker exits). - unsafe fn release_unrun(this: *mut Self) { - // `Err` is left pending for the release dispatcher's fold. - let _ = NapiFinalizerTask::run_on_js_thread(this); - } -} +use bun_threading::Guarded; +use bun_threading::work_pool::{Task as WorkPoolTask, WorkPool}; bun_output::declare_scope!(napi, visible); @@ -78,94 +38,64 @@ bun_output::declare_scope!(napi, visible); // NapiEnv // ────────────────────────────────────────────────────────────────────────── -bun_opaque::opaque_ffi! { - /// This is `struct napi_env__` from napi.h - /// - /// Opaque C++ object. `!Freeze` so that `&NapiEnv` does not assert - /// immutability — C++ mutates the underlying object (e.g. - /// `napi_set_last_error`, handle-scope push/pop) through pointers derived - /// from `&self`. See [`Self::as_mut_ptr`]. - pub struct NapiEnv; -} - -#[allow(improper_ctypes)] // `vm_handle::Shared` is opaque to C++ (`BunVmHandleRef`) unsafe extern "C" { - fn NapiEnv__globalObject(env: *mut NapiEnv) -> *mut JSGlobalObject; - fn NapiEnv__getAndClearPendingException(env: *mut NapiEnv, out: *mut JSValue) -> bool; - fn NapiEnv__hasPendingException(env: *mut NapiEnv) -> bool; - fn NapiEnv__deref(env: *mut NapiEnv); - fn NapiEnv__ref(env: *mut NapiEnv); - /// The reference to its VM's handle the env holds (`BunVmHandleRef`). - fn NapiEnv__vmHandle(env: *mut NapiEnv) -> *const bun_jsc::vm_handle::Shared; - fn napi_set_last_error(env: napi_env, status: NapiStatus) -> napi_status; - fn NapiUngatedScope__construct(storage: *mut c_void, env: *mut NapiEnv); - fn NapiUngatedScope__destruct(storage: *mut c_void); + safe fn Bun__JSValue__isAsyncContextFrame(value: JSValue) -> bool; + safe fn napi_set_last_error(env: Option<&NapiEnv>, status: NapiStatus) -> napi_status; + safe fn napi_internal_cleanup_env_cpp(env: &NapiEnv); + safe fn napi_internal_check_gc(env: &NapiEnv); + /// Drops the env's bookkeeping entry for a finalizer that has run; the + /// arguments are compared, not dereferenced. + safe fn napi_internal_remove_finalizer( + env: &NapiEnv, + fun: napi_finalize, + hint: *mut c_void, + data: *mut c_void, + ); + /// Returns false if the env has already torn down its registry. The + /// registry holds the address only. + safe fn NapiEnv__registerThreadSafeFunction(env: &NapiEnv, tsfn: *mut c_void) -> bool; + safe fn NapiEnv__unregisterThreadSafeFunction(env: &NapiEnv, tsfn: *mut c_void); } -impl NapiEnv { - pub(crate) fn to_js(&self) -> &JSGlobalObject { - // SAFETY: NapiEnv__globalObject always returns a valid non-null pointer. - unsafe { &*NapiEnv__globalObject(self.as_mut_ptr()) } - } - - /// Any thread holding an env ref: the env's VM handle. - pub(crate) fn vm_handle(&self) -> bun_jsc::vm_handle::BorrowedRef { - // SAFETY: the env holds a reference for its whole lifetime. - unsafe { bun_jsc::VmHandle::borrow_ref(NapiEnv__vmHandle(self.as_mut_ptr())) } - } +fn is_async_context_frame(value: JSValue) -> bool { + Bun__JSValue__isAsyncContextFrame(value) +} - /// Convert err to an extern napi_status, and store the error code in env so that it can be - /// accessed by napi_get_last_error_info - pub(crate) fn set_last_error(self_: Option<&Self>, err: NapiStatus) -> napi_status { - // SAFETY: napi_set_last_error accepts null env. - unsafe { napi_set_last_error(self_.map(Self::as_mut_ptr).unwrap_or(ptr::null_mut()), err) } - } +/// The napi status helpers on an env (they set the env's last error too). +pub(crate) trait NapiEnvExt { + fn env(&self) -> &NapiEnv; /// Convenience wrapper for set_last_error(.ok) - pub(crate) fn ok(&self) -> napi_status { - Self::set_last_error(Some(self), NapiStatus::ok) + fn ok(&self) -> napi_status { + napi_set_last_error(Some(self.env()), NapiStatus::ok) } /// These wrappers exist for convenience and so we can set a breakpoint in lldb - pub(crate) fn invalid_arg(&self) -> napi_status { + fn invalid_arg(&self) -> napi_status { if cfg!(debug_assertions) { bun_output::scoped_log!(napi, "invalid arg"); } - Self::set_last_error(Some(self), NapiStatus::invalid_arg) + napi_set_last_error(Some(self.env()), NapiStatus::invalid_arg) } - pub(crate) fn generic_failure(&self) -> napi_status { + fn generic_failure(&self) -> napi_status { if cfg!(debug_assertions) { bun_output::scoped_log!(napi, "generic failure"); } - Self::set_last_error(Some(self), NapiStatus::generic_failure) + napi_set_last_error(Some(self.env()), NapiStatus::generic_failure) } - pub(crate) fn pending_exception(&self) -> napi_status { - Self::set_last_error(Some(self), NapiStatus::pending_exception) + fn pending_exception(&self) -> napi_status { + napi_set_last_error(Some(self.env()), NapiStatus::pending_exception) } - /// Checks both `env->m_pendingException` (set by `napi_throw*`) and the JSC - /// VM exception slot. This is the gate Node.js's `NAPI_PREAMBLE` enforces. - pub(crate) fn has_pending_exception(&self) -> bool { - // SAFETY: env is non-null; C++ side is read-only here. - unsafe { NapiEnv__hasPendingException(self.as_mut_ptr()) } + fn status(&self, status: NapiStatus) -> napi_status { + napi_set_last_error(Some(self.env()), status) } /// Assert that we're not currently performing garbage collection - pub(crate) fn check_gc(&self) { - // SAFETY: env is non-null; C++ side is read-only here. - unsafe { napi_internal_check_gc(self.as_mut_ptr()) }; - } - - pub(crate) fn get_and_clear_pending_exception(&self) -> Option { - let mut exception = JSValue::ZERO; - // SAFETY: out-param is a valid stack location; interior mutability via - // `as_mut_ptr` permits C++ to clear the pending exception. - if unsafe { NapiEnv__getAndClearPendingException(self.as_mut_ptr(), &raw mut exception) } { - return Some(exception); - } - None + fn check_gc(&self) { + napi_internal_check_gc(self.env()); } /// After a native addon callback (a `complete`, a finalizer, a `call_js`): @@ -173,8 +103,8 @@ impl NapiEnv { /// is that call's exception, surfaced as `Err` with it pending on the VM. /// If both exist the VM's own wins and the latched one is discarded (it /// cannot be reported without running JS over the pending one). - pub(crate) fn surface_exception(&self, global: &JSGlobalObject) -> JsResult<()> { - let latched = self.get_and_clear_pending_exception(); + fn surface_exception(&self, global: &JSGlobalObject) -> JsResult<()> { + let latched = self.env().get_and_clear_pending_exception(); if global.has_exception() { return Err(jsc::JsError::Thrown); } @@ -185,21 +115,13 @@ impl NapiEnv { } } -// SAFETY: NapiEnv refcount is managed externally by C++ via NapiEnv__ref/NapiEnv__deref; -// the pointee remains valid while the count is > 0. -unsafe impl bun_ptr::ExternalSharedDescriptor for NapiEnv { - unsafe fn ext_ref(this: *mut Self) { - // SAFETY: caller contract — `this` is a valid C++-owned napi_env. - unsafe { NapiEnv__ref(this) } - } - unsafe fn ext_deref(this: *mut Self) { - // SAFETY: caller contract — `this` is a valid C++-owned napi_env. - unsafe { NapiEnv__deref(this) } +impl NapiEnvExt for NapiEnv { + #[inline] + fn env(&self) -> &NapiEnv { + self } } -pub(super) type NapiEnvRef = bun_ptr::ExternalShared; - #[cold] fn env_is_null() -> napi_status { // in this case we don't actually have an environment to set the last error on, so it doesn't @@ -207,114 +129,17 @@ fn env_is_null() -> napi_status { NapiStatus::invalid_arg as napi_status } -/// This is nullable because native modules may pass null pointers for the NAPI environment, which -/// is an error that our NAPI functions need to handle (by returning napi_invalid_arg). To specify -/// a Rust API that uses a never-null napi_env, use `&NapiEnv`. -pub(super) type napi_env = *mut NapiEnv; - -bun_opaque::opaque_ffi! { - /// Contents are not used by any Rust code - pub struct Ref; -} - -type napi_ref = *mut Ref; - -// ────────────────────────────────────────────────────────────────────────── -// NapiHandleScope -// ────────────────────────────────────────────────────────────────────────── - -bun_opaque::opaque_ffi! { - /// Opaque C++ handle-scope object (see [`NapiEnv`] for rationale). - pub struct NapiHandleScope; -} - -// `crate::ffi::ffi_body` re-declares `NapiHandleScope__{open,close}` locally -// with `*mut c_void` (it only needs the symbol address for TCC injection and -// cannot name the private `NapiHandleScope` type). Both declarations are -// ABI-identical thin pointers; suppress the duplicate-signature lint here as -// well since which side it fires on depends on module traversal order. -#[allow(clashing_extern_declarations)] -unsafe extern "C" { - pub(super) fn NapiHandleScope__open(env: *mut NapiEnv, escapable: bool) - -> *mut NapiHandleScope; - pub(super) fn NapiHandleScope__close(env: *mut NapiEnv, current: *mut NapiHandleScope); - fn NapiHandleScope__append(env: *mut NapiEnv, value: usize); - fn NapiHandleScope__escape(handle_scope: *mut NapiHandleScope, value: usize) -> bool; -} - -#[derive(Debug, thiserror::Error, strum::IntoStaticStr)] -enum EscapeError { - #[error("escape called twice")] - EscapeCalledTwice, -} - -impl NapiHandleScope { - /// Create a new handle scope in the given environment, or return null if creating one now is - /// unsafe (i.e. inside a finalizer) - fn open(env: &NapiEnv, escapable: bool) -> *mut NapiHandleScope { - // SAFETY: env is valid; C++ mutates env's scope stack (interior mutability). - unsafe { NapiHandleScope__open(env.as_mut_ptr(), escapable) } - } - - /// Closes the given handle scope, releasing all values inside it, if it is safe to do so. - /// Asserts that self is the current handle scope in env. - fn close(self_: *mut NapiHandleScope, env: &NapiEnv) { - // SAFETY: NapiHandleScope__close handles null `current`. - unsafe { NapiHandleScope__close(env.as_mut_ptr(), self_) } - } - - /// Place a value in the handle scope. Must be done while returning any JS value into NAPI - /// callbacks, as the value must remain alive as long as the handle scope is active, even if the - /// native module doesn't keep it visible on the stack. - fn append(env: &NapiEnv, value: JSValue) { - // SAFETY: env is valid; C++ appends to the current scope (interior mutability). - unsafe { NapiHandleScope__append(env.as_mut_ptr(), value.encoded()) } - } - - /// Move a value from the current handle scope (which must be escapable) to the reserved escape - /// slot in the parent handle scope, allowing that value to outlive the current handle scope. - /// Returns an error if escape() has already been called on this handle scope. - fn escape(&self, value: JSValue) -> Result<(), EscapeError> { - // SAFETY: self is a valid handle scope; C++ writes the escape slot - // (interior mutability via `as_mut_ptr`). - if !unsafe { NapiHandleScope__escape(self.as_mut_ptr(), value.encoded()) } { - return Err(EscapeError::EscapeCalledTwice); - } - Ok(()) - } -} - -/// RAII guard for [`NapiHandleScope::open`] / [`NapiHandleScope::close`]. -pub(super) struct NapiHandleScopeGuard<'a> { - scope: *mut NapiHandleScope, - env: &'a NapiEnv, -} - -impl NapiHandleScope { - /// Open a non-escapable handle scope and return an RAII guard that closes - /// it on `Drop`. If opening returns null (inside a finalizer), the guard's - /// `Drop` is a no-op. - #[must_use] - fn open_scoped(env: &NapiEnv) -> NapiHandleScopeGuard<'_> { - NapiHandleScopeGuard { - scope: Self::open(env, false), - env, - } - } -} +/// The `napi_env` an addon's callbacks receive. Entry points take +/// `Option<&NapiEnv>` instead: native modules may pass null, which is an error +/// they must get `napi_invalid_arg` for. +pub(crate) type napi_env = *mut NapiEnv; -impl Drop for NapiHandleScopeGuard<'_> { - fn drop(&mut self) { - if !self.scope.is_null() { - NapiHandleScope::close(self.scope, self.env); - } - } -} +/// An out-parameter: null when the addon does not want the value. +pub(crate) type Out<'a, T> = Option<&'a mut MaybeUninit>; -type napi_handle_scope = *mut NapiHandleScope; -type napi_escapable_handle_scope = *mut NapiHandleScope; -pub(super) type napi_callback_info = *mut CallFrame; -type napi_deferred = *mut JSPromiseStrong; +pub(crate) type napi_handle_scope = *mut NapiHandleScope; +pub(crate) type napi_escapable_handle_scope = *mut NapiHandleScope; +pub(crate) type napi_deferred = *mut JSPromiseStrong; // ────────────────────────────────────────────────────────────────────────── // napi_value @@ -324,14 +149,9 @@ type napi_deferred = *mut JSPromiseStrong; /// you must use these functions rather than convert between napi_value and jsc::JSValue directly #[repr(transparent)] #[derive(Copy, Clone)] -pub(crate) struct napi_value(i64); +pub struct napi_value(i64); impl napi_value { - pub(crate) fn set(&mut self, env: &NapiEnv, val: JSValue) { - NapiHandleScope::append(env, val); - self.0 = val.encoded() as i64; - } - pub(crate) fn get(self) -> JSValue { JSValue::from_encoded(self.0 as usize) } @@ -342,16 +162,20 @@ impl napi_value { } } -type char16_t = u16; -pub(super) type napi_property_attributes = c_uint; +trait OutValue { + fn set(&mut self, env: &NapiEnv, val: JSValue); +} +impl OutValue for MaybeUninit { + fn set(&mut self, env: &NapiEnv, val: JSValue) { + self.write(napi_value::create(env, val)); + } +} -// Only used as `*mut napi_valuetype` out-param written by C++; Rust never -// constructs or matches variants. -type napi_valuetype = u32; +pub(crate) type char16_t = u16; #[repr(u32)] #[derive(Copy, Clone, PartialEq, Eq)] -pub(super) enum napi_typedarray_type { +pub enum napi_typedarray_type { int8_array = 0, uint8_array = 1, uint8_clamped_array = 2, @@ -420,52 +244,19 @@ pub enum NapiStatus { /// This is not an `enum` so that the enum values cannot be trivially returned from NAPI functions, /// as that would skip storing the last error code. You should wrap return values in a call to /// NapiEnv::set_last_error. -pub(super) type napi_status = c_uint; - -pub(super) type napi_callback = Option napi_value>; +pub(crate) type napi_status = c_uint; /// expects `napi_env`, `callback_data`, `context` -pub(super) type NapiFinalizeFunction = extern "C" fn(napi_env, *mut c_void, *mut c_void); -pub(super) type napi_finalize = Option; - -#[repr(C)] -pub(super) struct napi_property_descriptor { - pub utf8name: *const c_char, - pub name: napi_value, - pub method: napi_callback, - pub getter: napi_callback, - pub setter: napi_callback, - pub value: napi_value, - pub attributes: napi_property_attributes, - pub data: *mut c_void, -} - -#[repr(C)] -pub(super) struct napi_extended_error_info { - pub error_message: *const c_char, - pub engine_reserved: *mut c_void, - pub engine_error_code: u32, - pub error_code: napi_status, -} - -type napi_key_collection_mode = c_uint; -type napi_key_filter = c_uint; -type napi_key_conversion = c_uint; - -#[repr(C)] -pub(super) struct napi_type_tag { - lower: u64, - upper: u64, -} +pub(crate) type NapiFinalizeFunction = extern "C" fn(napi_env, *mut c_void, *mut c_void); +pub(crate) type napi_finalize = Option; // ────────────────────────────────────────────────────────────────────────── -// Helper macro: unwrap nullable env / nullable out-param +// Helper macros: unwrap nullable env / nullable out-param // ────────────────────────────────────────────────────────────────────────── macro_rules! get_env { ($env:expr) => { - // SAFETY: caller passes raw napi_env; we treat non-null as &NapiEnv borrow. - match unsafe { $env.as_ref() } { + match $env { Some(e) => e, None => return env_is_null(), } @@ -485,91 +276,82 @@ macro_rules! preamble { }}; } -/// napi.cpp's `NapiUngatedScope` (see the comment there), constructed in place in this storage. -#[repr(C, align(8))] -struct UngatedScope([core::mem::MaybeUninit; 80]); - -struct UngatedScopeGuard<'a>(&'a mut UngatedScope); - -impl UngatedScope { - #[inline] - fn enter<'a>( - storage: &'a mut core::mem::MaybeUninit, - env: &NapiEnv, - ) -> UngatedScopeGuard<'a> { - let this = storage.write(UngatedScope([core::mem::MaybeUninit::uninit(); 80])); - // SAFETY: storage is 80 bytes, 8-aligned, and stays put until the guard drops; napi.cpp - // static_asserts that NapiUngatedScope fits. - unsafe { NapiUngatedScope__construct(this.0.as_mut_ptr().cast(), env.as_mut_ptr()) }; - UngatedScopeGuard(this) - } -} - -impl Drop for UngatedScopeGuard<'_> { - #[inline] - fn drop(&mut self) { - // SAFETY: constructed by `enter`, destroyed exactly once here. - unsafe { NapiUngatedScope__destruct(self.0.0.as_mut_ptr().cast()) }; - } -} - /// `get_env!`, then the rest of the function runs under napi.cpp's `NapiUngatedScope` (which see): no JS or addon code. macro_rules! ungated { ($env:ident, $raw:expr) => { let $env = get_env!($raw); - let mut napi_ungated_storage = ::core::mem::MaybeUninit::::uninit(); + let mut napi_ungated_storage = MaybeUninit::::uninit(); let _napi_ungated_scope = UngatedScope::enter(&mut napi_ungated_storage, $env); }; } macro_rules! get_out { ($env:expr, $ptr:expr) => { - // SAFETY: caller passes raw out pointer; we treat non-null as &mut borrow. - match unsafe { $ptr.as_mut() } { + match $ptr { Some(r) => r, None => return $env.invalid_arg(), } }; } -/// Write `v` through an optional N-API out-param pointer. -/// -/// N-API "info" entry points take a family of nullable `*mut T` out-params where -/// `NULL` means "caller doesn't want this field". This helper centralizes the -/// `if let Some(r) = ptr.as_mut() { *r = v }` pattern so the per-site `unsafe` -/// blocks collapse into one audited location. +/// Write `v` through an optional N-API out-param (`NULL`: the caller doesn't +/// want this field). +#[inline] +fn write_out(p: Out<'_, T>, v: T) { + if let Some(p) = p { + p.write(v); + } +} + +const NAPI_AUTO_LENGTH: usize = usize::MAX; + +/// The code units an N-API `(const T* str, size_t length)` argument pair +/// denotes: `length` of them, or up to the NUL when `length` is +/// `NAPI_AUTO_LENGTH`. /// /// # Safety -/// The caller (the native addon) must pass either `NULL` or a pointer that is: -/// - valid for a single write of `T`, -/// - properly aligned for `T`, -/// - not aliased by any other live `&`/`&mut` borrow for the duration of the call. -/// -/// These are exactly the N-API ABI guarantees for out-params, so call sites in -/// `extern "C" fn napi_*` bodies need no additional justification. -#[inline] -fn write_out(p: *mut T, v: T) { - // SAFETY: see doc comment — `p` is either null (skipped) or a valid, - // exclusively-owned out-param per the N-API contract. - if let Some(r) = unsafe { p.as_mut() } { - *r = v; +/// The N-API contract for string arguments: `ptr` is NUL-terminated when +/// `len == NAPI_AUTO_LENGTH` and valid for `len` reads otherwise, for `'a`. +unsafe fn napi_units<'a, T: Copy + PartialEq + Default>(ptr: NonNull, len: usize) -> &'a [T] { + let ptr = ptr.as_ptr().cast_const(); + // SAFETY: fn contract. + unsafe { + let len = if len != NAPI_AUTO_LENGTH { + len + } else if core::mem::size_of::() == 1 { + bun_core::ffi::cstr(ptr.cast::()).to_bytes().len() + } else { + let mut n = 0; + while *ptr.add(n) != T::default() { + n += 1; + } + n + }; + bun_core::ffi::slice(ptr, len) + } +} + +/// `napi_create_string_*`'s reading of its `(str, length)` arguments: a null +/// `str` is the empty string if `length` is 0, and lengths over `INT_MAX` are +/// refused, as in Node. +fn string_argument<'a, T>( + ptr: *const T, + len: usize, + units: impl FnOnce(NonNull) -> &'a [T], +) -> Option<&'a [T]> { + match NonNull::new(ptr.cast_mut()) { + None => (len == 0).then_some(&[]), + Some(_) if len != NAPI_AUTO_LENGTH && len > i32::MAX as usize => None, + Some(ptr) => Some(units(ptr)), } } // ────────────────────────────────────────────────────────────────────────── -// Exported / extern NAPI functions +// Exported NAPI functions (the rest are C++, napi.cpp) // ────────────────────────────────────────────────────────────────────────── -// Implemented in C++ (napi.cpp); declared extern here for Rust-side callers. -unsafe extern "C" { - pub(super) fn napi_get_last_error_info( - env: napi_env, - result: *mut *const napi_extended_error_info, - ) -> napi_status; -} - -#[unsafe(no_mangle)] -extern "C" fn napi_get_undefined(env_: napi_env, result_: *mut napi_value) -> napi_status { +// HOST_EXPORT(napi_get_undefined, c) +pub fn napi_get_undefined(env_: Option<&NapiEnv>, result_: Out) -> napi_status { bun_output::scoped_log!(napi, "napi_get_undefined"); ungated!(env, env_); env.check_gc(); @@ -578,8 +360,8 @@ extern "C" fn napi_get_undefined(env_: napi_env, result_: *mut napi_value) -> na env.ok() } -#[unsafe(no_mangle)] -extern "C" fn napi_get_null(env_: napi_env, result_: *mut napi_value) -> napi_status { +// HOST_EXPORT(napi_get_null, c) +pub fn napi_get_null(env_: Option<&NapiEnv>, result_: Out) -> napi_status { bun_output::scoped_log!(napi, "napi_get_null"); ungated!(env, env_); env.check_gc(); @@ -588,15 +370,11 @@ extern "C" fn napi_get_null(env_: napi_env, result_: *mut napi_value) -> napi_st env.ok() } -unsafe extern "C" { - pub(super) fn napi_get_global(env: napi_env, result: *mut napi_value) -> napi_status; -} - -#[unsafe(no_mangle)] -extern "C" fn napi_get_boolean( - env_: napi_env, +// HOST_EXPORT(napi_get_boolean, c) +pub fn napi_get_boolean( + env_: Option<&NapiEnv>, value: bool, - result_: *mut napi_value, + result_: Out, ) -> napi_status { bun_output::scoped_log!(napi, "napi_get_boolean"); ungated!(env, env_); @@ -606,25 +384,25 @@ extern "C" fn napi_get_boolean( env.ok() } -#[unsafe(no_mangle)] -extern "C" fn napi_create_array(env_: napi_env, result_: *mut napi_value) -> napi_status { +// HOST_EXPORT(napi_create_array, c) +pub fn napi_create_array(env_: Option<&NapiEnv>, result_: Out) -> napi_status { bun_output::scoped_log!(napi, "napi_create_array"); ungated!(env, env_); env.check_gc(); let result = get_out!(env, result_); let arr = match JSValue::create_empty_array(env.to_js(), 0) { Ok(v) => v, - Err(_) => return NapiEnv::set_last_error(Some(env), NapiStatus::pending_exception), + Err(_) => return env.status(NapiStatus::pending_exception), }; result.set(env, arr); env.ok() } -#[unsafe(no_mangle)] -extern "C" fn napi_create_array_with_length( - env_: napi_env, +// HOST_EXPORT(napi_create_array_with_length, c) +pub fn napi_create_array_with_length( + env_: Option<&NapiEnv>, length: usize, - result_: *mut napi_value, + result_: Out, ) -> napi_status { bun_output::scoped_log!(napi, "napi_create_array_with_length"); ungated!(env, env_); @@ -640,26 +418,18 @@ extern "C" fn napi_create_array_with_length( let array = match JSValue::create_empty_array(env.to_js(), len as usize) { Ok(v) => v, - Err(_) => return NapiEnv::set_last_error(Some(env), NapiStatus::pending_exception), + Err(_) => return env.status(NapiStatus::pending_exception), }; array.ensure_still_alive(); result.set(env, array); env.ok() } -unsafe extern "C" { - pub(super) fn napi_create_double( - env: napi_env, - value: f64, - result: *mut napi_value, - ) -> napi_status; -} - -#[unsafe(no_mangle)] -extern "C" fn napi_create_int32( - env_: napi_env, +// HOST_EXPORT(napi_create_int32, c) +pub fn napi_create_int32( + env_: Option<&NapiEnv>, value: i32, - result_: *mut napi_value, + result_: Out, ) -> napi_status { bun_output::scoped_log!(napi, "napi_create_int32"); ungated!(env, env_); @@ -669,11 +439,11 @@ extern "C" fn napi_create_int32( env.ok() } -#[unsafe(no_mangle)] -extern "C" fn napi_create_uint32( - env_: napi_env, +// HOST_EXPORT(napi_create_uint32, c) +pub fn napi_create_uint32( + env_: Option<&NapiEnv>, value: u32, - result_: *mut napi_value, + result_: Out, ) -> napi_status { bun_output::scoped_log!(napi, "napi_create_uint32"); ungated!(env, env_); @@ -683,11 +453,11 @@ extern "C" fn napi_create_uint32( env.ok() } -#[unsafe(no_mangle)] -extern "C" fn napi_create_int64( - env_: napi_env, +// HOST_EXPORT(napi_create_int64, c) +pub fn napi_create_int64( + env_: Option<&NapiEnv>, value: i64, - result_: *mut napi_value, + result_: Out, ) -> napi_status { bun_output::scoped_log!(napi, "napi_create_int64"); ungated!(env, env_); @@ -697,34 +467,19 @@ extern "C" fn napi_create_int64( env.ok() } -#[unsafe(no_mangle)] -extern "C" fn napi_create_string_latin1( - env_: napi_env, +// HOST_EXPORT(napi_create_string_latin1, c) +pub fn napi_create_string_latin1( + env_: Option<&NapiEnv>, str_: *const u8, length: usize, - result_: *mut napi_value, + result_: Out, ) -> napi_status { ungated!(env, env_); let result = get_out!(env, result_); - let slice: &[u8] = 'brk: { - if !str_.is_null() { - if NAPI_AUTO_LENGTH == length { - // SAFETY: caller guarantees ptr is NUL-terminated when length == NAPI_AUTO_LENGTH. - break 'brk unsafe { bun_core::ffi::cstr(str_.cast::()) }.to_bytes(); - } else if length > i32::MAX as usize { - return env.invalid_arg(); - } else { - // SAFETY: caller guarantees [ptr, ptr+length) is valid. - break 'brk unsafe { bun_core::ffi::slice(str_, length) }; - } - } - - if length == 0 { - break 'brk &[]; - } else { - return env.invalid_arg(); - } + // SAFETY: the addon's string argument (N-API contract). + let Some(slice) = string_argument(str_, length, |p| unsafe { napi_units(p, length) }) else { + return env.invalid_arg(); }; bun_output::scoped_log!( @@ -743,40 +498,25 @@ extern "C" fn napi_create_string_latin1( let js = match string.into_js(env.to_js()) { Ok(v) => v, - Err(_) => return NapiEnv::set_last_error(Some(env), NapiStatus::generic_failure), + Err(_) => return env.status(NapiStatus::generic_failure), }; result.set(env, js); env.ok() } -#[unsafe(no_mangle)] -extern "C" fn napi_create_string_utf8( - env_: napi_env, +// HOST_EXPORT(napi_create_string_utf8, c) +pub fn napi_create_string_utf8( + env_: Option<&NapiEnv>, str_: *const u8, length: usize, - result_: *mut napi_value, + result_: Out, ) -> napi_status { ungated!(env, env_); let result = get_out!(env, result_); - let slice: &[u8] = 'brk: { - if !str_.is_null() { - if NAPI_AUTO_LENGTH == length { - // SAFETY: caller guarantees ptr is NUL-terminated when length == NAPI_AUTO_LENGTH. - break 'brk unsafe { bun_core::ffi::cstr(str_.cast::()) }.to_bytes(); - } else if length > i32::MAX as usize { - return env.invalid_arg(); - } else { - // SAFETY: caller guarantees [ptr, ptr+length) is valid. - break 'brk unsafe { bun_core::ffi::slice(str_, length) }; - } - } - - if length == 0 { - break 'brk &[]; - } else { - return env.invalid_arg(); - } + // SAFETY: the addon's string argument (N-API contract). + let Some(slice) = string_argument(str_, length, |p| unsafe { napi_units(p, length) }) else { + return env.invalid_arg(); }; bun_output::scoped_log!(napi, "napi_create_string_utf8: {}", bstr::BStr::new(slice)); @@ -790,35 +530,19 @@ extern "C" fn napi_create_string_utf8( env.ok() } -#[unsafe(no_mangle)] -extern "C" fn napi_create_string_utf16( - env_: napi_env, +// HOST_EXPORT(napi_create_string_utf16, c) +pub fn napi_create_string_utf16( + env_: Option<&NapiEnv>, str_: *const char16_t, length: usize, - result_: *mut napi_value, + result_: Out, ) -> napi_status { ungated!(env, env_); let result = get_out!(env, result_); - let slice: &[u16] = 'brk: { - if !str_.is_null() { - if NAPI_AUTO_LENGTH == length { - // SAFETY: caller guarantees ptr is NUL-terminated when length == NAPI_AUTO_LENGTH. - // Scan to the NUL u16 terminator. - break 'brk unsafe { bun_core::ffi::wstr_units(str_) }; - } else if length > i32::MAX as usize { - return env.invalid_arg(); - } else { - // SAFETY: caller guarantees [ptr, ptr+length) is valid. - break 'brk unsafe { bun_core::ffi::slice(str_, length) }; - } - } - - if length == 0 { - break 'brk &[]; - } else { - return env.invalid_arg(); - } + // SAFETY: the addon's string argument (N-API contract). + let Some(slice) = string_argument(str_, length, |p| unsafe { napi_units(p, length) }) else { + return env.invalid_arg(); }; if cfg!(debug_assertions) { @@ -840,118 +564,17 @@ extern "C" fn napi_create_string_utf16( let js = match string.into_js(env.to_js()) { Ok(v) => v, - Err(_) => return NapiEnv::set_last_error(Some(env), NapiStatus::generic_failure), + Err(_) => return env.status(NapiStatus::generic_failure), }; result.set(env, js); env.ok() } -// Implemented in C++ (napi.cpp); declared extern here for Rust-side callers. -unsafe extern "C" { - pub(super) fn napi_create_symbol( - env: napi_env, - description: napi_value, - result: *mut napi_value, - ) -> napi_status; - pub(super) fn napi_create_error( - env: napi_env, - code: napi_value, - msg: napi_value, - result: *mut napi_value, - ) -> napi_status; - pub(super) fn napi_create_type_error( - env: napi_env, - code: napi_value, - msg: napi_value, - result: *mut napi_value, - ) -> napi_status; - pub(super) fn napi_create_range_error( - env: napi_env, - code: napi_value, - msg: napi_value, - result: *mut napi_value, - ) -> napi_status; - pub(super) fn napi_typeof( - env: napi_env, - value: napi_value, - result: *mut napi_valuetype, - ) -> napi_status; - pub(super) fn napi_get_value_double( - env: napi_env, - value: napi_value, - result: *mut f64, - ) -> napi_status; - pub(super) fn napi_get_value_int32( - env: napi_env, - value: napi_value, - result: *mut i32, - ) -> napi_status; - pub(super) fn napi_get_value_uint32( - env: napi_env, - value: napi_value, - result: *mut u32, - ) -> napi_status; - pub(super) fn napi_get_value_int64( - env: napi_env, - value: napi_value, - result: *mut i64, - ) -> napi_status; - pub(super) fn napi_get_value_bool( - env: napi_env, - value: napi_value, - result: *mut bool, - ) -> napi_status; - pub(super) fn napi_get_value_string_latin1( - env: napi_env, - value: napi_value, - buf_ptr: *mut c_char, - bufsize: usize, - result_ptr: *mut usize, - ) -> napi_status; - /// Copies a JavaScript string into a UTF-8 string buffer. The result is the - /// number of bytes (excluding the null terminator) copied into buf. - /// A sufficient buffer size should be greater than the length of string, - /// reserving space for null terminator. - /// If bufsize is insufficient, the string will be truncated and null terminated. - /// If buf is NULL, this method returns the length of the string (in bytes) - /// via the result parameter. - /// The result argument is optional unless buf is NULL. - pub(super) fn napi_get_value_string_utf8( - env: napi_env, - value: napi_value, - buf_ptr: *mut u8, - bufsize: usize, - result_ptr: *mut usize, - ) -> napi_status; - pub(super) fn napi_get_value_string_utf16( - env: napi_env, - value: napi_value, - buf_ptr: *mut char16_t, - bufsize: usize, - result_ptr: *mut usize, - ) -> napi_status; - pub(super) fn napi_coerce_to_bool( - env: napi_env, - value: napi_value, - result: *mut napi_value, - ) -> napi_status; - pub(super) fn napi_coerce_to_number( - env: napi_env, - value: napi_value, - result: *mut napi_value, - ) -> napi_status; - pub(super) fn napi_coerce_to_object( - env: napi_env, - value: napi_value, - result: *mut napi_value, - ) -> napi_status; -} - -#[unsafe(no_mangle)] -extern "C" fn napi_get_prototype( - env_: napi_env, +// HOST_EXPORT(napi_get_prototype, c) +pub fn napi_get_prototype( + env_: Option<&NapiEnv>, object_: napi_value, - result_: *mut napi_value, + result_: Out, ) -> napi_status { bun_output::scoped_log!(napi, "napi_get_prototype"); let env = preamble!(env_); @@ -966,7 +589,7 @@ extern "C" fn napi_get_prototype( // non-object values) handles them without an allocation. if object.is_undefined_or_null() { let _ = object.to_object(env.to_js()); - return NapiEnv::set_last_error(Some(env), NapiStatus::object_expected); + return env.status(NapiStatus::object_expected); } // Like V8's Object::GetPrototype: a Proxy yields null and its trap never runs. @@ -982,50 +605,12 @@ extern "C" fn napi_get_prototype( env.ok() } -// TODO: bind JSC::ownKeys -// pub extern "C" fn napi_get_property_names(env: napi_env, object: napi_value, result: *mut napi_value) -> napi_status { -// log("napi_get_property_names"); -// if !object.is_object() { -// return .object_expected; -// } -// result.* = -// } - -unsafe extern "C" { - pub(super) fn napi_set_element( - env: napi_env, - object: napi_value, - index: c_uint, - value: napi_value, - ) -> napi_status; - pub(super) fn napi_has_element( - env: napi_env, - object: napi_value, - index: c_uint, - result: *mut bool, - ) -> napi_status; - pub(super) fn napi_get_element( - env: napi_env, - object: napi_value, - index: u32, - result: *mut napi_value, - ) -> napi_status; - pub(super) fn napi_delete_element( - env: napi_env, - object: napi_value, - index: u32, - result: *mut bool, - ) -> napi_status; - pub(super) fn napi_define_properties( - env: napi_env, - object: napi_value, - property_count: usize, - properties: *const napi_property_descriptor, - ) -> napi_status; -} - -#[unsafe(no_mangle)] -extern "C" fn napi_is_array(env_: napi_env, value_: napi_value, result_: *mut bool) -> napi_status { +// HOST_EXPORT(napi_is_array, c) +pub fn napi_is_array( + env_: Option<&NapiEnv>, + value_: napi_value, + result_: Out, +) -> napi_status { bun_output::scoped_log!(napi, "napi_is_array"); ungated!(env, env_); env.check_gc(); @@ -1034,15 +619,15 @@ extern "C" fn napi_is_array(env_: napi_env, value_: napi_value, result_: *mut bo if value.is_empty() { return env.invalid_arg(); } - *result = value.js_type().is_array(); + result.write(value.js_type().is_array()); env.ok() } -#[unsafe(no_mangle)] -extern "C" fn napi_get_array_length( - env_: napi_env, +// HOST_EXPORT(napi_get_array_length, c) +pub fn napi_get_array_length( + env_: Option<&NapiEnv>, value_: napi_value, - result_: *mut u32, + result_: Out, ) -> napi_status { bun_output::scoped_log!(napi, "napi_get_array_length"); let env = preamble!(env_); @@ -1053,22 +638,22 @@ extern "C" fn napi_get_array_length( } if !value.js_type().is_array() { - return NapiEnv::set_last_error(Some(env), NapiStatus::array_expected); + return env.status(NapiStatus::array_expected); } - *result = match value.get_length(env.to_js()) { + result.write(match value.get_length(env.to_js()) { Ok(len) => len as u32, // intentional truncation - Err(_) => return NapiEnv::set_last_error(Some(env), NapiStatus::pending_exception), - }; + Err(_) => return env.status(NapiStatus::pending_exception), + }); env.ok() } -#[unsafe(no_mangle)] -extern "C" fn napi_strict_equals( - env_: napi_env, +// HOST_EXPORT(napi_strict_equals, c) +pub fn napi_strict_equals( + env_: Option<&NapiEnv>, lhs_: napi_value, rhs_: napi_value, - result_: *mut bool, + result_: Out, ) -> napi_status { bun_output::scoped_log!(napi, "napi_strict_equals"); let env = preamble!(env_); @@ -1077,173 +662,73 @@ extern "C" fn napi_strict_equals( if lhs.is_empty() || rhs.is_empty() { return env.invalid_arg(); } - *result = match lhs.is_strict_equal(rhs, env.to_js()) { + result.write(match lhs.is_strict_equal(rhs, env.to_js()) { Ok(b) => b, - Err(_) => return NapiEnv::set_last_error(Some(env), NapiStatus::pending_exception), - }; + Err(_) => return env.status(NapiStatus::pending_exception), + }); env.ok() } -unsafe extern "C" { - pub(super) fn napi_call_function( - env: napi_env, - recv: napi_value, - func: napi_value, - argc: usize, - argv: *const napi_value, - result: *mut napi_value, - ) -> napi_status; - pub(super) fn napi_new_instance( - env: napi_env, - constructor: napi_value, - argc: usize, - argv: *const napi_value, - result: *mut napi_value, - ) -> napi_status; - pub(super) fn napi_instanceof( - env: napi_env, - object: napi_value, - constructor: napi_value, - result: *mut bool, - ) -> napi_status; - pub(super) fn napi_get_cb_info( - env: napi_env, - cbinfo: napi_callback_info, - argc: *mut usize, - argv: *mut napi_value, - this_arg: *mut napi_value, - data: *mut *mut c_void, - ) -> napi_status; - pub(super) fn napi_get_new_target( - env: napi_env, - cbinfo: napi_callback_info, - result: *mut napi_value, - ) -> napi_status; - pub(super) fn napi_define_class( - env: napi_env, - utf8name: *const c_char, - length: usize, - constructor: napi_callback, - data: *mut c_void, - property_count: usize, - properties: *const napi_property_descriptor, - result: *mut napi_value, - ) -> napi_status; - pub(super) fn napi_wrap( - env: napi_env, - js_object: napi_value, - native_object: *mut c_void, - finalize_cb: napi_finalize, - finalize_hint: *mut c_void, - result: *mut napi_ref, - ) -> napi_status; - pub(super) fn napi_unwrap( - env: napi_env, - js_object: napi_value, - result: *mut *mut c_void, - ) -> napi_status; - pub(super) fn napi_remove_wrap( - env: napi_env, - js_object: napi_value, - result: *mut *mut c_void, - ) -> napi_status; - pub(super) fn napi_create_object(env: napi_env, result: *mut napi_value) -> napi_status; - pub(super) fn napi_create_external( - env: napi_env, - data: *mut c_void, - finalize_cb: napi_finalize, - finalize_hint: *mut c_void, - result: *mut napi_value, - ) -> napi_status; - pub(super) fn napi_get_value_external( - env: napi_env, - value: napi_value, - result: *mut *mut c_void, - ) -> napi_status; - pub(super) fn napi_create_reference( - env: napi_env, - value: napi_value, - initial_refcount: u32, - result: *mut napi_ref, - ) -> napi_status; - pub(super) fn napi_delete_reference(env: napi_env, ref_: napi_ref) -> napi_status; - pub(super) fn napi_reference_ref( - env: napi_env, - ref_: napi_ref, - result: *mut u32, - ) -> napi_status; - pub(super) fn napi_reference_unref( - env: napi_env, - ref_: napi_ref, - result: *mut u32, - ) -> napi_status; - pub(super) fn napi_get_reference_value( - env: napi_env, - ref_: napi_ref, - result: *mut napi_value, - ) -> napi_status; -} - -#[unsafe(no_mangle)] -extern "C" fn napi_open_handle_scope( - env_: napi_env, - result_: *mut napi_handle_scope, +// HOST_EXPORT(napi_open_handle_scope, c) +pub fn napi_open_handle_scope( + env_: Option<&NapiEnv>, + result_: Out, ) -> napi_status { bun_output::scoped_log!(napi, "napi_open_handle_scope"); ungated!(env, env_); env.check_gc(); let result = get_out!(env, result_); - *result = NapiHandleScope::open(env, false); + result.write(NapiHandleScope::open(env, false)); env.ok() } -#[unsafe(no_mangle)] -extern "C" fn napi_close_handle_scope( - env_: napi_env, - handle_scope: napi_handle_scope, +// HOST_EXPORT(napi_close_handle_scope, c) +pub fn napi_close_handle_scope( + env_: Option<&NapiEnv>, + handle_scope: Option<&NapiHandleScope>, ) -> napi_status { bun_output::scoped_log!(napi, "napi_close_handle_scope"); ungated!(env, env_); env.check_gc(); - if !handle_scope.is_null() { - NapiHandleScope::close(handle_scope, env); + if let Some(handle_scope) = handle_scope { + NapiHandleScope::close(Some(handle_scope), env); } env.ok() } // we don't support async contexts -#[unsafe(no_mangle)] -extern "C" fn napi_async_init( - env_: napi_env, +// HOST_EXPORT(napi_async_init, c) +pub fn napi_async_init( + env_: Option<&NapiEnv>, _async_resource: napi_value, _async_resource_name: napi_value, - async_ctx_: *mut *mut c_void, + async_ctx_: Out<*mut c_void>, ) -> napi_status { bun_output::scoped_log!(napi, "napi_async_init"); let env = get_env!(env_); let async_ctx = get_out!(env, async_ctx_); - *async_ctx = env_.cast::(); + async_ctx.write(env.as_mut_ptr().cast::()); env.ok() } // we don't support async contexts -#[unsafe(no_mangle)] -extern "C" fn napi_async_destroy(env_: napi_env, _async_ctx: *mut c_void) -> napi_status { +// HOST_EXPORT(napi_async_destroy, c) +pub fn napi_async_destroy(env_: Option<&NapiEnv>, _async_ctx: *mut c_void) -> napi_status { bun_output::scoped_log!(napi, "napi_async_destroy"); let env = get_env!(env_); env.ok() } // this is just a regular function call -#[unsafe(no_mangle)] -extern "C" fn napi_make_callback( - env_: napi_env, +// HOST_EXPORT(napi_make_callback, c) +pub fn napi_make_callback( + env_: Option<&NapiEnv>, _async_ctx: *mut c_void, recv_: napi_value, func_: napi_value, arg_count: usize, args: *const napi_value, - maybe_result: *mut napi_value, + maybe_result: Out, ) -> napi_status { bun_output::scoped_log!(napi, "napi_make_callback"); let env = preamble!(env_); @@ -1255,7 +740,7 @@ extern "C" fn napi_make_callback( return env.invalid_arg(); } if func.is_empty_or_undefined_or_null() - || (!func.is_callable() && !func.is_async_context_frame()) + || (!func.is_callable() && !is_async_context_frame(func)) { return env.invalid_arg(); } @@ -1279,81 +764,65 @@ extern "C" fn napi_make_callback( Err(_) => return env.pending_exception(), }; - // SAFETY: `maybe_result` is null or a valid exclusive out-param per N-API contract. - if let Some(result) = unsafe { maybe_result.as_mut() } { + if let Some(result) = maybe_result { result.set(env, res); } env.ok() } -#[unsafe(no_mangle)] -extern "C" fn napi_open_escapable_handle_scope( - env_: napi_env, - result_: *mut napi_escapable_handle_scope, +// HOST_EXPORT(napi_open_escapable_handle_scope, c) +pub fn napi_open_escapable_handle_scope( + env_: Option<&NapiEnv>, + result_: Out, ) -> napi_status { bun_output::scoped_log!(napi, "napi_open_escapable_handle_scope"); ungated!(env, env_); env.check_gc(); let result = get_out!(env, result_); - *result = NapiHandleScope::open(env, true); + result.write(NapiHandleScope::open(env, true)); env.ok() } -#[unsafe(no_mangle)] -extern "C" fn napi_close_escapable_handle_scope( - env_: napi_env, - scope: napi_escapable_handle_scope, +// HOST_EXPORT(napi_close_escapable_handle_scope, c) +pub fn napi_close_escapable_handle_scope( + env_: Option<&NapiEnv>, + scope: Option<&NapiHandleScope>, ) -> napi_status { bun_output::scoped_log!(napi, "napi_close_escapable_handle_scope"); ungated!(env, env_); env.check_gc(); - if !scope.is_null() { - NapiHandleScope::close(scope, env); + if let Some(scope) = scope { + NapiHandleScope::close(Some(scope), env); } env.ok() } -#[unsafe(no_mangle)] -extern "C" fn napi_escape_handle( - env_: napi_env, - scope_: napi_escapable_handle_scope, +// HOST_EXPORT(napi_escape_handle, c) +pub fn napi_escape_handle( + env_: Option<&NapiEnv>, + scope_: Option<&NapiHandleScope>, escapee: napi_value, - result_: *mut napi_value, + result_: Out, ) -> napi_status { bun_output::scoped_log!(napi, "napi_escape_handle"); ungated!(env, env_); env.check_gc(); let result = get_out!(env, result_); - // SAFETY: scope_ is a raw NAPI handle; non-null is treated as &NapiHandleScope. - let Some(scope) = (unsafe { scope_.as_ref() }) else { + let Some(scope) = scope_ else { return env.invalid_arg(); }; if scope.escape(escapee.get()).is_err() { - return NapiEnv::set_last_error(Some(env), NapiStatus::escape_called_twice); + return env.status(NapiStatus::escape_called_twice); } - *result = escapee; + result.write(escapee); env.ok() } -unsafe extern "C" { - pub(super) fn napi_type_tag_object( - env: napi_env, - value: napi_value, - tag: *const napi_type_tag, - ) -> napi_status; - pub(super) fn napi_check_object_type_tag( - env: napi_env, - value: napi_value, - tag: *const napi_type_tag, - result: *mut bool, - ) -> napi_status; -} - // do nothing for both of these -#[unsafe(no_mangle)] -extern "C" fn napi_open_callback_scope( - _env: napi_env, +// HOST_EXPORT(napi_open_callback_scope, c) +pub fn napi_open_callback_scope( + _env: Option<&NapiEnv>, _resource: napi_value, _context: *mut c_void, _result: *mut c_void, @@ -1362,33 +831,18 @@ extern "C" fn napi_open_callback_scope( NapiStatus::ok as napi_status } -#[unsafe(no_mangle)] -extern "C" fn napi_close_callback_scope(_env: napi_env, _scope: *mut c_void) -> napi_status { +// HOST_EXPORT(napi_close_callback_scope, c) +pub fn napi_close_callback_scope(_env: Option<&NapiEnv>, _scope: *mut c_void) -> napi_status { bun_output::scoped_log!(napi, "napi_close_callback_scope"); NapiStatus::ok as napi_status } -unsafe extern "C" { - pub(super) fn napi_throw(env: napi_env, error: napi_value) -> napi_status; - pub(super) fn napi_throw_error( - env: napi_env, - code: *const c_char, - msg: *const c_char, - ) -> napi_status; - pub(super) fn napi_throw_type_error( - env: napi_env, - code: *const c_char, - msg: *const c_char, - ) -> napi_status; - pub(super) fn napi_throw_range_error( - env: napi_env, - code: *const c_char, - msg: *const c_char, - ) -> napi_status; -} - -#[unsafe(no_mangle)] -extern "C" fn napi_is_error(env_: napi_env, value_: napi_value, result_: *mut bool) -> napi_status { +// HOST_EXPORT(napi_is_error, c) +pub fn napi_is_error( + env_: Option<&NapiEnv>, + value_: napi_value, + result_: Out, +) -> napi_status { bun_output::scoped_log!(napi, "napi_is_error"); ungated!(env, env_); env.check_gc(); @@ -1397,23 +851,15 @@ extern "C" fn napi_is_error(env_: napi_env, value_: napi_value, result_: *mut bo return env.invalid_arg(); } let result = get_out!(env, result_); - *result = value.is_any_error(); + result.write(value.is_any_error()); env.ok() } -unsafe extern "C" { - pub(super) fn napi_is_exception_pending(env: napi_env, result: *mut bool) -> napi_status; - pub(super) fn napi_get_and_clear_last_exception( - env: napi_env, - result: *mut napi_value, - ) -> napi_status; -} - -#[unsafe(no_mangle)] -extern "C" fn napi_is_arraybuffer( - env_: napi_env, +// HOST_EXPORT(napi_is_arraybuffer, c) +pub fn napi_is_arraybuffer( + env_: Option<&NapiEnv>, value_: napi_value, - result_: *mut bool, + result_: Out, ) -> napi_status { bun_output::scoped_log!(napi, "napi_is_arraybuffer"); ungated!(env, env_); @@ -1427,48 +873,30 @@ extern "C" fn napi_is_arraybuffer( // ArrayBuffer in JSC, so `js_type` alone can't tell them apart. Node's // `napi_is_arraybuffer` maps to V8's `IsArrayBuffer()`, which is false for // SharedArrayBuffer, so exclude shared buffers here too. - *result = value - .as_array_buffer(env.to_js()) - .is_some_and(|ab| ab.typed_array_type == jsc::JSType::ArrayBuffer && !ab.shared); + result.write( + value + .as_array_buffer(env.to_js()) + .is_some_and(|ab| ab.typed_array_type == jsc::JSType::ArrayBuffer && !ab.shared), + ); env.ok() } -unsafe extern "C" { - // Verified against the C++ implementation (napi.cpp `napi_create_arraybuffer`): - // `data` is a `void**` out-param receiving the buffer's data pointer, - // matching the N-API spec. - pub(super) fn napi_create_arraybuffer( - env: napi_env, - byte_length: usize, - data: *mut *mut c_void, - result: *mut napi_value, - ) -> napi_status; - pub(super) fn napi_create_external_arraybuffer( - env: napi_env, - external_data: *mut c_void, - byte_length: usize, - finalize_cb: napi_finalize, - finalize_hint: *mut c_void, - result: *mut napi_value, - ) -> napi_status; -} - -#[unsafe(no_mangle)] -extern "C" fn napi_get_arraybuffer_info( - env_: napi_env, +// HOST_EXPORT(napi_get_arraybuffer_info, c) +pub fn napi_get_arraybuffer_info( + env_: Option<&NapiEnv>, arraybuffer_: napi_value, - data: *mut *mut u8, - byte_length: *mut usize, + data: Out<*mut u8>, + byte_length: Out, ) -> napi_status { bun_output::scoped_log!(napi, "napi_get_arraybuffer_info"); ungated!(env, env_); env.check_gc(); let arraybuffer = arraybuffer_.get(); let Some(array_buffer) = arraybuffer.as_array_buffer(env.to_js()) else { - return NapiEnv::set_last_error(Some(env), NapiStatus::invalid_arg); + return env.status(NapiStatus::invalid_arg); }; if array_buffer.typed_array_type != jsc::JSType::ArrayBuffer { - return NapiEnv::set_last_error(Some(env), NapiStatus::invalid_arg); + return env.status(NapiStatus::invalid_arg); } write_out(data, array_buffer.ptr); @@ -1476,23 +904,15 @@ extern "C" fn napi_get_arraybuffer_info( env.ok() } -unsafe extern "C" { - pub(super) fn napi_is_typedarray( - env: napi_env, - value: napi_value, - result: *mut bool, - ) -> napi_status; -} - -#[unsafe(no_mangle)] -extern "C" fn napi_get_typedarray_info( - env_: napi_env, +// HOST_EXPORT(napi_get_typedarray_info, c) +pub fn napi_get_typedarray_info( + env_: Option<&NapiEnv>, typedarray_: napi_value, - maybe_type: *mut napi_typedarray_type, - maybe_length: *mut usize, - maybe_data: *mut *mut u8, - maybe_arraybuffer: *mut napi_value, - maybe_byte_offset: *mut usize, + maybe_type: Out, + maybe_length: Out, + maybe_data: Out<*mut u8>, + maybe_arraybuffer: Out, + maybe_byte_offset: Out, ) -> napi_status { bun_output::scoped_log!(napi, "napi_get_typedarray_info"); ungated!(env, env_); @@ -1505,55 +925,42 @@ extern "C" fn napi_get_typedarray_info( // Keep the pointer valid for the view's lifetime, as in Node: the // arraybuffer out-param below would otherwise invalidate it. - if !maybe_data.is_null() && !typedarray.materialize_array_buffer_view_buffer() { + if maybe_data.is_some() && !typedarray.materialize_array_buffer_view_buffer() { return env.generic_failure(); } let Some(array_buffer) = typedarray.as_array_buffer(env.to_js()) else { return env.invalid_arg(); }; - // SAFETY: `maybe_type` is null or a valid exclusive out-param per N-API contract. - if let Some(ty) = unsafe { maybe_type.as_mut() } { + if let Some(ty) = maybe_type { // The `ArrayBuffer.typed_array_type` field is already a `JSType`, so map it // straight to `napi_typedarray_type`. let Some(napi_ty) = napi_typedarray_type::from_js_type(array_buffer.typed_array_type) else { return env.invalid_arg(); }; - *ty = napi_ty; + ty.write(napi_ty); } // TODO: handle detached write_out(maybe_data, array_buffer.ptr); write_out(maybe_length, array_buffer.len); - // SAFETY: `maybe_arraybuffer` is null or a valid exclusive out-param per N-API contract. - if let Some(arraybuffer) = unsafe { maybe_arraybuffer.as_mut() } { + if let Some(arraybuffer) = maybe_arraybuffer { arraybuffer.set(env, typedarray.get_array_buffer_view_buffer(env.to_js())); } - // SAFETY: `maybe_byte_offset` is null or a valid exclusive out-param per N-API contract. - if let Some(byte_offset) = unsafe { maybe_byte_offset.as_mut() } { - *byte_offset = typedarray.get_array_buffer_view_byte_offset(); + if let Some(byte_offset) = maybe_byte_offset { + byte_offset.write(typedarray.get_array_buffer_view_byte_offset()); } env.ok() } -unsafe extern "C" { - pub(super) fn napi_create_dataview( - env: napi_env, - length: usize, - arraybuffer: napi_value, - byte_offset: usize, - result: *mut napi_value, - ) -> napi_status; -} - -#[unsafe(no_mangle)] -extern "C" fn napi_is_dataview( - env_: napi_env, +// HOST_EXPORT(napi_is_dataview, c) +pub fn napi_is_dataview( + env_: Option<&NapiEnv>, value_: napi_value, - result_: *mut bool, + result_: Out, ) -> napi_status { bun_output::scoped_log!(napi, "napi_is_dataview"); ungated!(env, env_); @@ -1562,19 +969,20 @@ extern "C" fn napi_is_dataview( if value.is_empty() { return env.invalid_arg(); } - *result = - !value.is_empty_or_undefined_or_null() && value.js_type_loose() == jsc::JSType::DataView; + result.write( + !value.is_empty_or_undefined_or_null() && value.js_type_loose() == jsc::JSType::DataView, + ); env.ok() } -#[unsafe(no_mangle)] -extern "C" fn napi_get_dataview_info( - env_: napi_env, +// HOST_EXPORT(napi_get_dataview_info, c) +pub fn napi_get_dataview_info( + env_: Option<&NapiEnv>, dataview_: napi_value, - maybe_bytelength: *mut usize, - maybe_data: *mut *mut u8, - maybe_arraybuffer: *mut napi_value, - maybe_byte_offset: *mut usize, + maybe_bytelength: Out, + maybe_data: Out<*mut u8>, + maybe_arraybuffer: Out, + maybe_byte_offset: Out, ) -> napi_status { bun_output::scoped_log!(napi, "napi_get_dataview_info"); ungated!(env, env_); @@ -1584,94 +992,95 @@ extern "C" fn napi_get_dataview_info( return env.invalid_arg(); } let Some(array_buffer) = dataview.as_array_buffer(env.to_js()) else { - return NapiEnv::set_last_error(Some(env), NapiStatus::object_expected); + return env.status(NapiStatus::object_expected); }; write_out(maybe_bytelength, array_buffer.byte_len); write_out(maybe_data, array_buffer.ptr); - // SAFETY: `maybe_arraybuffer` is null or a valid exclusive out-param per N-API contract. - if let Some(arraybuffer) = unsafe { maybe_arraybuffer.as_mut() } { + if let Some(arraybuffer) = maybe_arraybuffer { arraybuffer.set(env, dataview.get_array_buffer_view_buffer(env.to_js())); } - // SAFETY: `maybe_byte_offset` is null or a valid exclusive out-param per N-API contract. - if let Some(byte_offset) = unsafe { maybe_byte_offset.as_mut() } { - *byte_offset = dataview.get_array_buffer_view_byte_offset(); + if let Some(byte_offset) = maybe_byte_offset { + byte_offset.write(dataview.get_array_buffer_view_byte_offset()); } env.ok() } -#[unsafe(no_mangle)] -extern "C" fn napi_get_version(env_: napi_env, result_: *mut u32) -> napi_status { +// HOST_EXPORT(napi_get_version, c) +pub fn napi_get_version(env_: Option<&NapiEnv>, result_: Out) -> napi_status { bun_output::scoped_log!(napi, "napi_get_version"); let env = get_env!(env_); let result = get_out!(env, result_); // The result is supposed to be the highest NAPI version Bun supports, rather than the version reported by a NAPI module. // Keep this in sync with process.versions.napi in BunProcess.cpp. - *result = 10; + result.write(10); env.ok() } -#[unsafe(no_mangle)] -extern "C" fn napi_create_promise( - env_: napi_env, - deferred_: *mut napi_deferred, - promise_: *mut napi_value, +// HOST_EXPORT(napi_create_promise, c) +pub fn napi_create_promise( + env_: Option<&NapiEnv>, + deferred_: Out, + promise_: Out, ) -> napi_status { bun_output::scoped_log!(napi, "napi_create_promise"); let env = preamble!(env_); let deferred = get_out!(env, deferred_); let promise = get_out!(env, promise_); let strong = Box::new(JSPromiseStrong::init(env.to_js())); - let strong_ptr = bun_core::heap::into_raw(strong); - *deferred = strong_ptr; - // SAFETY: strong_ptr was just created from heap::alloc and is non-null. - let prom_value = unsafe { (*strong_ptr).get() }.as_value(env.to_js()); + let prom_value = strong.get().as_value(env.to_js()); + // Owned by the addon until `napi_resolve_deferred` / `napi_reject_deferred`. + deferred.write(bun_core::heap::into_raw(strong)); promise.set(env, prom_value); env.ok() } -#[unsafe(no_mangle)] -extern "C" fn napi_resolve_deferred( - env_: napi_env, - deferred: napi_deferred, +// HOST_EXPORT(napi_resolve_deferred, c) +pub fn napi_resolve_deferred( + env_: Option<&NapiEnv>, + deferred: Option>>, resolution_: napi_value, ) -> napi_status { bun_output::scoped_log!(napi, "napi_resolve_deferred"); let env = preamble!(env_); - // SAFETY: deferred was created by heap::alloc in napi_create_promise. - let deferred_box = unsafe { bun_core::heap::take(deferred) }; - // `deferred_box` drops at scope exit (deinit + free). + let Some(deferred) = deferred else { + return env.invalid_arg(); + }; + // Ours again (allocated in `napi_create_promise`); freed at scope exit. + let deferred = ManuallyDrop::into_inner(deferred); let resolution = resolution_.get(); - let prom = deferred_box.get(); + let prom = deferred.get(); if prom.resolve(env.to_js(), resolution).is_err() { return env.generic_failure(); } env.ok() } -#[unsafe(no_mangle)] -extern "C" fn napi_reject_deferred( - env_: napi_env, - deferred: napi_deferred, +// HOST_EXPORT(napi_reject_deferred, c) +pub fn napi_reject_deferred( + env_: Option<&NapiEnv>, + deferred: Option>>, rejection_: napi_value, ) -> napi_status { bun_output::scoped_log!(napi, "napi_reject_deferred"); let env = preamble!(env_); - // SAFETY: deferred was created by heap::alloc in napi_create_promise. - let deferred_box = unsafe { bun_core::heap::take(deferred) }; + let Some(deferred) = deferred else { + return env.invalid_arg(); + }; + let deferred = ManuallyDrop::into_inner(deferred); let rejection = rejection_.get(); - let prom = deferred_box.get(); + let prom = deferred.get(); if prom.reject(env.to_js(), Ok(rejection)).is_err() { return env.generic_failure(); } env.ok() } -#[unsafe(no_mangle)] -extern "C" fn napi_is_promise( - env_: napi_env, +// HOST_EXPORT(napi_is_promise, c) +pub fn napi_is_promise( + env_: Option<&NapiEnv>, value_: napi_value, - is_promise_: *mut bool, + is_promise_: Out, ) -> napi_status { bun_output::scoped_log!(napi, "napi_is_promise"); ungated!(env, env_); @@ -1683,25 +1092,16 @@ extern "C" fn napi_is_promise( return env.invalid_arg(); } - *is_promise = value.as_any_promise().is_some(); + is_promise.write(value.as_any_promise().is_some()); env.ok() } -unsafe extern "C" { - pub(super) fn napi_run_script( - env: napi_env, - script: napi_value, - result: *mut napi_value, - ) -> napi_status; - pub(super) fn napi_adjust_external_memory( - env: napi_env, - change_in_bytes: i64, - adjusted_value: *mut i64, - ) -> napi_status; -} - -#[unsafe(no_mangle)] -extern "C" fn napi_create_date(env_: napi_env, time: f64, result_: *mut napi_value) -> napi_status { +// HOST_EXPORT(napi_create_date, c) +pub fn napi_create_date( + env_: Option<&NapiEnv>, + time: f64, + result_: Out, +) -> napi_status { bun_output::scoped_log!(napi, "napi_create_date"); let env = preamble!(env_); let result = get_out!(env, result_); @@ -1712,8 +1112,12 @@ extern "C" fn napi_create_date(env_: napi_env, time: f64, result_: *mut napi_val env.ok() } -#[unsafe(no_mangle)] -extern "C" fn napi_is_date(env_: napi_env, value_: napi_value, is_date_: *mut bool) -> napi_status { +// HOST_EXPORT(napi_is_date, c) +pub fn napi_is_date( + env_: Option<&NapiEnv>, + value_: napi_value, + is_date_: Out, +) -> napi_status { bun_output::scoped_log!(napi, "napi_is_date"); ungated!(env, env_); env.check_gc(); @@ -1722,116 +1126,62 @@ extern "C" fn napi_is_date(env_: napi_env, value_: napi_value, is_date_: *mut bo if value.is_empty() { return env.invalid_arg(); } - *is_date = value.js_type_loose() == jsc::JSType::JSDate; + is_date.write(value.js_type_loose() == jsc::JSType::JSDate); env.ok() } -unsafe extern "C" { - pub(super) fn napi_get_date_value( - env: napi_env, - value: napi_value, - result: *mut f64, - ) -> napi_status; - pub(super) fn napi_add_finalizer( - env: napi_env, - js_object: napi_value, - native_object: *mut c_void, - finalize_cb: napi_finalize, - finalize_hint: *mut c_void, - result: napi_ref, - ) -> napi_status; - pub(super) fn napi_create_bigint_int64( - env: napi_env, - value: i64, - result: *mut napi_value, - ) -> napi_status; - pub(super) fn napi_create_bigint_uint64( - env: napi_env, - value: u64, - result: *mut napi_value, - ) -> napi_status; - pub(super) fn napi_create_bigint_words( - env: napi_env, - sign_bit: c_int, - word_count: usize, - words: *const u64, - result: *mut napi_value, - ) -> napi_status; - pub(super) fn napi_get_value_bigint_int64( - env: napi_env, - value: napi_value, - result: *mut i64, - lossless: *mut bool, - ) -> napi_status; - pub(super) fn napi_get_value_bigint_uint64( - env: napi_env, - value: napi_value, - result: *mut u64, - lossless: *mut bool, - ) -> napi_status; - pub(super) fn napi_get_value_bigint_words( - env: napi_env, - value: napi_value, - sign_bit: *mut c_int, - word_count: *mut usize, - words: *mut u64, - ) -> napi_status; - pub(super) fn napi_get_all_property_names( - env: napi_env, - object: napi_value, - key_mode: napi_key_collection_mode, - key_filter: napi_key_filter, - key_conversion: napi_key_conversion, - result: *mut napi_value, - ) -> napi_status; - pub(super) fn napi_set_instance_data( - env: napi_env, - data: *mut c_void, - finalize_cb: napi_finalize, - finalize_hint: *mut c_void, - ) -> napi_status; - pub(super) fn napi_get_instance_data(env: napi_env, data: *mut *mut c_void) -> napi_status; - pub(super) fn napi_detach_arraybuffer(env: napi_env, arraybuffer: napi_value) -> napi_status; - pub(super) fn napi_is_detached_arraybuffer( - env: napi_env, - value: napi_value, - result: *mut bool, - ) -> napi_status; -} - // ────────────────────────────────────────────────────────────────────────── // napi_async_work // ────────────────────────────────────────────────────────────────────────── #[repr(u32)] #[derive(Copy, Clone, PartialEq, Eq)] -pub(super) enum AsyncWorkStatus { +pub enum AsyncWorkStatus { Pending = 0, Started = 1, Completed = 2, Cancelled = 3, } -/// must be globally allocated -pub(crate) struct napi_async_work { - pub task: WorkPoolTask, - pub(crate) concurrent_task: ConcurrentTask, +/// Owned by the addon from `napi_create_async_work` until +/// `napi_delete_async_work`: it keeps the work alive across +/// `napi_queue_async_work` → `execute` (pool) → `complete` (JS thread), as +/// Node requires, and every side reaches it shared. While it is out on the pool +/// (`schedule` → `run_work_task`), the pool side takes `ticket`, runs `execute` +/// with `env`/`data`, updates `status` (atomic; `cancel` races it from the JS +/// thread) and posts through `concurrent_task`; the JS thread leaves those be +/// until the completion arrives and owns `scheduled` / `poll_ref` throughout. +pub struct napi_async_work { + /// The pool's node while the work is out on it. + task: Cell, + /// The completion's node (pool → JS thread). + concurrent_task: Cell, /// Held while the work is out on the pool (`schedule` until it is posted /// back): how the pool thread delivers completion / cancellation, and what /// makes the VM wait for it. - pub(crate) ticket: Option, + ticket: Cell>, + env: NapiEnvRef, + execute: napi_async_execute_callback, + complete: Option, + data: *mut c_void, + status: AtomicU32, // AsyncWorkStatus /// JS thread only. - pub global: GlobalRef, - pub(crate) env: NapiEnvRef, - pub(crate) execute: napi_async_execute_callback, - pub(crate) complete: Option, - pub(crate) data: *mut c_void, - pub(crate) status: AtomicU32, // AsyncWorkStatus - pub(crate) scheduled: bool, - pub poll_ref: KeepAlive, + scheduled: Cell, + /// JS thread only. + poll_ref: Cell, } -bun_threading::intrusive_work_task!(napi_async_work, task); +// Pool side / JS side split as documented on the struct; the addon keeps the +// work allocated until `complete` has run (N-API contract). +bun_threading::shared_work_task!(napi_async_work, task); + +bun_event_loop::task_hop! { + /// `task_tag::NapiAsyncWork`: the pool is done with a queued work; run its + /// `complete` on the JS thread. The addon keeps the work alive until then. + pub(crate) AsyncWorkCompletion for napi_async_work => NapiAsyncWork; + run = napi_async_work::run_from_js; + release_unrun = napi_async_work::release_unrun; +} impl napi_async_work { pub(crate) fn new( @@ -1839,99 +1189,38 @@ impl napi_async_work { execute: napi_async_execute_callback, complete: Option, data: *mut c_void, - ) -> *mut napi_async_work { - let global = env.to_js(); - - bun_core::heap::into_raw(Box::new(napi_async_work { - task: WorkPoolTask { - node: bun_threading::thread_pool::Node::default(), - callback: Self::run_from_thread_pool, - }, - concurrent_task: ConcurrentTask::default(), - global: GlobalRef::from(global), - // SAFETY: env outlives the async work; clone bumps the C++ refcount. - env: unsafe { NapiEnvRef::clone_from_raw(env.as_mut_ptr()) }, + ) -> Box { + Box::new(napi_async_work { + task: bun_threading::shared_work_task_node::(), + concurrent_task: Cell::new(ConcurrentTask::default()), + env: env.to_ref(), execute, - ticket: None, + ticket: Cell::new(None), complete, data, status: AtomicU32::new(AsyncWorkStatus::Pending as u32), - scheduled: false, - poll_ref: KeepAlive::default(), - })) - } - - // Forwards `this` to `heap::take` without dereferencing it here; - // not_unsafe_ptr_arg_deref is a false positive on opaque-token forwarding. - #[allow(clippy::not_unsafe_ptr_arg_deref)] - pub(crate) fn destroy(this: *mut napi_async_work) { - // SAFETY: `this` was created by heap::alloc in `new`. - // env.deinit() runs via Drop on NapiEnvRef. - drop(unsafe { bun_core::heap::take(this) }); + scheduled: Cell::new(false), + poll_ref: Cell::new(KeepAlive::default()), + }) } - pub(crate) fn schedule(&mut self) { - if self.scheduled { + /// JS thread. + pub(crate) fn schedule(this: ThisPtr) { + if this.scheduled.get() { return; } - self.scheduled = true; - self.poll_ref.ref_(bun_io::js_vm_ctx()); + this.scheduled.set(true); + let mut poll_ref = this.poll_ref.take(); + poll_ref.ref_(bun_io::js_vm_ctx()); + this.poll_ref.set(poll_ref); // The work object belongs to the addon and `execute` receives this // env, so the VM waits for it (Node likewise settles its threadpool // requests before an environment is freed). - self.ticket = Some(self.global.bun_vm().ticket()); - WorkPool::schedule(&raw mut self.task); - } - - pub(crate) unsafe fn run_from_thread_pool(task: *mut WorkPoolTask) { - // SAFETY: `task` is the `task` field of a live heap `napi_async_work`, - // exclusively owned by the work pool for this callback's duration. - unsafe { (*napi_async_work::from_task_ptr(task)).run() }; - } - - fn run(&mut self) { - let self_ptr: *mut Self = self; - // Moved out: the JS thread may free `self` the moment it is posted back. - let ticket = self - .ticket - .take() - .expect("scheduled napi async work holds a ticket"); - // A VM that is already stopping cancels work it has not started, as - // Node's environment cleanup does (uv_cancel). - let started = ticket.script_allowed() - && match self.status.compare_exchange( - AsyncWorkStatus::Pending as u32, - AsyncWorkStatus::Started as u32, - Ordering::SeqCst, - Ordering::SeqCst, - ) { - Ok(_) => true, - Err(state) => state != AsyncWorkStatus::Cancelled as u32, - }; - if started { - (self.execute)(self.env.get(), self.data); - self.status - .store(AsyncWorkStatus::Completed as u32, Ordering::SeqCst); - } else { - let _ = self.cancel(); - } - self.post_to_js_thread(self_ptr, &ticket); + this.ticket.set(Some(this.env.to_js().bun_vm().ticket())); + WorkPool::schedule_shared(this); } - /// Pool thread → JS thread: run `complete` there. `concurrent_task` is the - /// live inline field of this heap work; the queue takes ownership of its - /// `next` link. A VM tearing down runs `complete` from its queue release - /// (status cancelled if `execute` never ran), as Node does at environment - /// cleanup. - fn post_to_js_thread(&mut self, self_ptr: *mut Self, ticket: &bun_jsc::Ticket) { - let ct = core::ptr::NonNull::from( - self.concurrent_task - .from(self_ptr, AutoDeinit::ManualDeinit), - ); - ticket.post(ct); - } - - pub(crate) fn cancel(&mut self) -> bool { + pub(crate) fn cancel(&self) -> bool { self.status .compare_exchange( AsyncWorkStatus::Pending as u32, @@ -1942,66 +1231,99 @@ impl napi_async_work { .is_ok() } - pub(crate) fn run_from_js(&mut self, global: &JSGlobalObject) -> JsResult<()> { - // Note: the "this" value here may already be freed by the user in `complete` - // Note: KeepAlive is not `Copy`, so move it out (the original slot may - // be freed under us by `complete`). - let mut poll_ref = core::mem::take(&mut self.poll_ref); + /// Work the pool handed back during teardown: its `complete` callback is + /// how the addon learns the outcome and frees the work (Node calls it from + /// environment cleanup too); script it tries to run is refused at the + /// boundary. `Err` is left pending for the release dispatcher's fold. + fn release_unrun(this: ThisPtr) { + let _ = Self::run_from_js(this); + } + + /// JS thread: run `complete`. The addon may free the work (this + /// allocation) from inside `complete`, so nothing of `this` is touched + /// after that call. + fn run_from_js(this: ThisPtr) -> JsResult<()> { + let mut poll_ref = this.poll_ref.take(); // KeepAlive::unref needs an event-loop ctx so it cannot impl Drop // generically; this is a genuine one-off cleanup. scopeguard::defer! { poll_ref.unref(bun_io::js_vm_ctx()); } // https://github.com/nodejs/node/blob/a2de5b9150da60c77144bb5333371eaca3fab936/src/node_api.cc#L1201 - let Some(complete) = self.complete else { + let Some(complete) = this.complete else { return Ok(()); }; - - let env = self.env.get(); - // SAFETY: env is held alive by NapiEnvRef for the duration of this call. - let env_ref = unsafe { &*env }; - let _hs = NapiHandleScope::open_scoped(env_ref); - + let env = this.env.clone(); + let data = this.data; let status: NapiStatus = - if self.status.load(Ordering::SeqCst) == AsyncWorkStatus::Cancelled as u32 { + if this.status.load(Ordering::SeqCst) == AsyncWorkStatus::Cancelled as u32 { NapiStatus::cancelled } else { NapiStatus::ok }; - complete(env, status as napi_status, self.data); + let _hs = NapiHandleScope::open_scoped(&env); + complete(env.get(), status as napi_status, data); + env.surface_exception(env.to_js()) + } - // SAFETY: env is valid for the duration of this call. - unsafe { &*env }.surface_exception(global) + /// Pool thread: run `execute` (unless the VM is already stopping, which + /// cancels work it has not started, as Node's environment cleanup does + /// with `uv_cancel`) and post the work back to the JS thread for `complete`. + fn run_work_task(this: ThisPtr) { + // Moved out: the JS thread may free the work the moment it is posted back. + let ticket = this + .ticket + .take() + .expect("scheduled napi async work holds a ticket"); + let started = ticket.script_allowed() + && match this.status.compare_exchange( + AsyncWorkStatus::Pending as u32, + AsyncWorkStatus::Started as u32, + Ordering::SeqCst, + Ordering::SeqCst, + ) { + Ok(_) => true, + Err(state) => state != AsyncWorkStatus::Cancelled as u32, + }; + if started { + (this.execute)(this.env.get(), this.data); + this.status + .store(AsyncWorkStatus::Completed as u32, Ordering::SeqCst); + } else { + let _ = this.cancel(); + } + // A VM tearing down runs `complete` from its queue release (status + // cancelled if `execute` never ran), as Node does at environment cleanup. + let mut node = ConcurrentTask::default(); + node.from_task(AsyncWorkCompletion::task(this), AutoDeinit::ManualDeinit); + this.concurrent_task.set(node); + ticket.post(NonNull::new(this.concurrent_task.as_ptr()).expect("field address")); } } -type napi_threadsafe_function = *mut ThreadSafeFunction; - #[repr(u32)] #[derive(Copy, Clone, PartialEq, Eq)] -pub(crate) enum napi_threadsafe_function_release_mode { +pub enum napi_threadsafe_function_release_mode { release = 0, abort = 1, } const NAPI_TSFN_BLOCKING: c_uint = 1; -type napi_threadsafe_function_call_mode = c_uint; -pub(super) type napi_async_execute_callback = extern "C" fn(napi_env, *mut c_void); -pub(super) type napi_async_complete_callback = extern "C" fn(napi_env, napi_status, *mut c_void); -pub(super) type napi_threadsafe_function_call_js = +pub(crate) type napi_threadsafe_function_call_mode = c_uint; +pub(crate) type napi_async_execute_callback = extern "C" fn(napi_env, *mut c_void); +pub(crate) type napi_async_complete_callback = extern "C" fn(napi_env, napi_status, *mut c_void); +pub(crate) type napi_threadsafe_function_call_js = extern "C" fn(napi_env, napi_value, *mut c_void, *mut c_void); #[repr(C)] -struct napi_node_version { +pub struct napi_node_version { pub major: u32, pub minor: u32, pub patch: u32, - pub release: *const c_char, + /// `const char*`, a static literal. + pub release: bun_core::SyncCStr, } -// SAFETY: napi_node_version is POD; the *const c_char points at a static literal. -unsafe impl Sync for napi_node_version {} - // Splits "MAJOR.MINOR.PATCH" into u32 components at compile time. const fn parse_semver_component(s: &str, idx: usize) -> u32 { let bytes = s.as_bytes(); @@ -2027,31 +1349,11 @@ static NAPI_NODE_VERSION_GLOBAL: napi_node_version = napi_node_version { major: parse_semver_component(bun_core::Environment::REPORTED_NODEJS_VERSION, 0), minor: parse_semver_component(bun_core::Environment::REPORTED_NODEJS_VERSION, 1), patch: parse_semver_component(bun_core::Environment::REPORTED_NODEJS_VERSION, 2), - release: c"node".as_ptr(), + release: bun_core::SyncCStr(c"node".as_ptr()), }; -bun_opaque::opaque_ffi! { pub struct struct_napi_async_cleanup_hook_handle__; } -type napi_async_cleanup_hook_handle = *mut struct_napi_async_cleanup_hook_handle__; -type napi_async_cleanup_hook = Option; - -fn napi_span(ptr: *const u8, len: usize) -> &'static [u8] { - // SAFETY: caller-supplied C string region; lifetime is the duration of the NAPI call. - // `'static` is used because the slice never outlives the FFI call. - if ptr.is_null() { - return &[]; - } - - if len == NAPI_AUTO_LENGTH { - // SAFETY: N-API contract — `ptr` is a NUL-terminated C string when `len == NAPI_AUTO_LENGTH`. - return unsafe { bun_core::ffi::cstr(ptr.cast::()) }.to_bytes(); - } - - // SAFETY: N-API contract — `[ptr, ptr+len)` is a valid readable region for the call. - unsafe { bun_core::ffi::slice(ptr, len) } -} - -#[unsafe(no_mangle)] -extern "C" fn napi_fatal_error( +// HOST_EXPORT(napi_fatal_error, c) +pub fn napi_fatal_error( location_ptr: *const u8, location_len: usize, message_ptr: *const u8, @@ -2059,12 +1361,18 @@ extern "C" fn napi_fatal_error( ) -> ! { bun_output::scoped_log!(napi, "napi_fatal_error"); napi_internal_suppress_crash_on_abort_if_desired(); - let mut message = napi_span(message_ptr, message_len_); - if message.is_empty() { - message = b"fatal error"; - } - - let location = napi_span(location_ptr, location_len); + // SAFETY: the addon's string arguments (N-API contract); null is absent. + let (location, message) = unsafe { + ( + NonNull::new(location_ptr.cast_mut()).map_or(&b""[..], |p| napi_units(p, location_len)), + NonNull::new(message_ptr.cast_mut()).map_or(&b""[..], |p| napi_units(p, message_len_)), + ) + }; + let message: &[u8] = if message.is_empty() { + b"fatal error" + } else { + message + }; if !location.is_empty() { bun_core::Output::panic(format_args!( "NAPI FATAL ERROR: {} {}", @@ -2076,54 +1384,26 @@ extern "C" fn napi_fatal_error( bun_core::Output::panic(format_args!("napi: {}", bstr::BStr::new(message))); } -unsafe extern "C" { - pub(super) fn napi_create_buffer( - env: napi_env, - length: usize, - data: *mut *mut c_void, - result: *mut napi_value, - ) -> napi_status; - pub(super) fn napi_create_external_buffer( - env: napi_env, - length: usize, - data: *mut c_void, - finalize_cb: napi_finalize, - finalize_hint: *mut c_void, - result: *mut napi_value, - ) -> napi_status; - pub(super) fn napi_create_buffer_copy( - env: napi_env, - length: usize, - data: *const c_void, - result_data: *mut *mut c_void, - result: *mut napi_value, - ) -> napi_status; -} - -unsafe extern "C" { - fn napi_is_buffer(env: napi_env, value: napi_value, result: *mut bool) -> napi_status; -} - -#[unsafe(no_mangle)] -extern "C" fn napi_get_buffer_info( - env_: napi_env, +// HOST_EXPORT(napi_get_buffer_info, c) +pub fn napi_get_buffer_info( + env_: Option<&NapiEnv>, value_: napi_value, - data: *mut *mut u8, - length: *mut usize, + data: Out<*mut u8>, + length: Out, ) -> napi_status { bun_output::scoped_log!(napi, "napi_get_buffer_info"); ungated!(env, env_); let value = value_.get(); // Keep the pointer valid for the buffer's lifetime, as in Node. - if !data.is_null() && !value.materialize_array_buffer_view_buffer() { + if data.is_some() && !value.materialize_array_buffer_view_buffer() { return env.generic_failure(); } let Some(array_buf) = value.as_array_buffer(env.to_js()) else { - return NapiEnv::set_last_error(Some(env), NapiStatus::invalid_arg); + return env.status(NapiStatus::invalid_arg); }; // node::Buffer::HasInstance is IsArrayBufferView: reject a bare ArrayBuffer. if array_buf.typed_array_type == jsc::JSType::ArrayBuffer { - return NapiEnv::set_last_error(Some(env), NapiStatus::invalid_arg); + return env.status(NapiStatus::invalid_arg); } write_out(data, array_buf.ptr); @@ -2132,81 +1412,15 @@ extern "C" fn napi_get_buffer_info( env.ok() } -unsafe extern "C" { - fn node_api_create_syntax_error( - env: napi_env, - code: napi_value, - msg: napi_value, - result: *mut napi_value, - ) -> napi_status; - fn node_api_symbol_for( - env: napi_env, - utf8: *const c_char, - length: usize, - result: *mut napi_value, - ) -> napi_status; - fn node_api_throw_syntax_error( - env: napi_env, - code: *const c_char, - msg: *const c_char, - ) -> napi_status; - fn node_api_create_external_string_latin1( - env: napi_env, - str_: *mut u8, - length: usize, - finalize_cb: napi_finalize, - finalize_hint: *mut c_void, - result: *mut JSValue, - copied: *mut bool, - ) -> napi_status; - fn node_api_create_external_string_utf16( - env: napi_env, - str_: *mut u16, - length: usize, - finalize_cb: napi_finalize, - finalize_hint: *mut c_void, - result: *mut JSValue, - copied: *mut bool, - ) -> napi_status; - fn node_api_set_prototype(env: napi_env, object: napi_value, value: napi_value) -> napi_status; - fn node_api_create_object_with_properties( - env: napi_env, - prototype_or_null: napi_value, - property_names: *const napi_value, - property_values: *const napi_value, - property_count: usize, - result: *mut napi_value, - ) -> napi_status; - fn node_api_create_sharedarraybuffer( - env: napi_env, - byte_length: usize, - data: *mut *mut c_void, - result: *mut napi_value, - ) -> napi_status; - fn node_api_create_external_sharedarraybuffer( - env: napi_env, - external_data: *mut c_void, - byte_length: usize, - finalize_cb: Option, - finalize_hint: *mut c_void, - result: *mut napi_value, - ) -> napi_status; - fn node_api_is_sharedarraybuffer( - env: napi_env, - value: napi_value, - result: *mut bool, - ) -> napi_status; -} - -#[unsafe(no_mangle)] -extern "C" fn napi_create_async_work( - env_: napi_env, +// HOST_EXPORT(napi_create_async_work, c) +pub fn napi_create_async_work( + env_: Option<&NapiEnv>, _async_resource: napi_value, _async_resource_name: *const c_char, execute_: Option, complete: Option, data: *mut c_void, - result_: *mut *mut napi_async_work, + result_: Out<*mut napi_async_work>, ) -> napi_status { bun_output::scoped_log!(napi, "napi_create_async_work"); let env = get_env!(env_); @@ -2215,45 +1429,51 @@ extern "C" fn napi_create_async_work( let Some(execute) = execute_ else { return env.invalid_arg(); }; - *result = napi_async_work::new(env, execute, complete, data); + // Owned by the addon until `napi_delete_async_work`. + result.write(bun_core::heap::into_raw(napi_async_work::new( + env, execute, complete, data, + ))); env.ok() } -#[unsafe(no_mangle)] -extern "C" fn napi_delete_async_work(env_: napi_env, work_: *mut napi_async_work) -> napi_status { +// HOST_EXPORT(napi_delete_async_work, c) +pub fn napi_delete_async_work( + env_: Option<&NapiEnv>, + work_: Option>>, +) -> napi_status { bun_output::scoped_log!(napi, "napi_delete_async_work"); let env = get_env!(env_); - // SAFETY: `work_` is null or the `napi_async_work` we allocated in `napi_create_async_work`. - let Some(work) = (unsafe { work_.as_mut() }) else { + let Some(work) = work_ else { return env.invalid_arg(); }; - debug_assert!(core::ptr::eq(env.to_js(), work.global.as_ptr())); - napi_async_work::destroy(work_); + drop(ManuallyDrop::into_inner(work)); env.ok() } -#[unsafe(no_mangle)] -extern "C" fn napi_queue_async_work(env_: napi_env, work_: *mut napi_async_work) -> napi_status { +// HOST_EXPORT(napi_queue_async_work, c) +pub fn napi_queue_async_work( + env_: Option<&NapiEnv>, + work_: Option>, +) -> napi_status { bun_output::scoped_log!(napi, "napi_queue_async_work"); let env = get_env!(env_); - // SAFETY: `work_` is null or the `napi_async_work` we allocated in `napi_create_async_work`. - let Some(work) = (unsafe { work_.as_mut() }) else { + let Some(work) = work_ else { return env.invalid_arg(); }; - debug_assert!(core::ptr::eq(env.to_js(), work.global.as_ptr())); - work.schedule(); + napi_async_work::schedule(work); env.ok() } -#[unsafe(no_mangle)] -extern "C" fn napi_cancel_async_work(env_: napi_env, work_: *mut napi_async_work) -> napi_status { +// HOST_EXPORT(napi_cancel_async_work, c) +pub fn napi_cancel_async_work( + env_: Option<&NapiEnv>, + work_: Option<&napi_async_work>, +) -> napi_status { bun_output::scoped_log!(napi, "napi_cancel_async_work"); let env = get_env!(env_); - // SAFETY: `work_` is null or the `napi_async_work` we allocated in `napi_create_async_work`. - let Some(work) = (unsafe { work_.as_mut() }) else { + let Some(work) = work_ else { return env.invalid_arg(); }; - debug_assert!(core::ptr::eq(env.to_js(), work.global.as_ptr())); if work.cancel() { return env.ok(); } @@ -2261,25 +1481,25 @@ extern "C" fn napi_cancel_async_work(env_: napi_env, work_: *mut napi_async_work env.generic_failure() } -#[unsafe(no_mangle)] -extern "C" fn napi_get_node_version( - env_: napi_env, - version_: *mut *const napi_node_version, +// HOST_EXPORT(napi_get_node_version, c) +pub fn napi_get_node_version( + env_: Option<&NapiEnv>, + version_: Out<&'static napi_node_version>, ) -> napi_status { bun_output::scoped_log!(napi, "napi_get_node_version"); let env = get_env!(env_); let version = get_out!(env, version_); - *version = &raw const NAPI_NODE_VERSION_GLOBAL; + version.write(&NAPI_NODE_VERSION_GLOBAL); env.ok() } #[cfg(windows)] -type napi_event_loop = *mut bun_sys::windows::libuv::Loop; +pub(crate) type napi_event_loop = *mut bun_sys::windows::libuv::Loop; #[cfg(not(windows))] -type napi_event_loop = *mut EventLoop; +pub(crate) type napi_event_loop = *mut EventLoop; -#[unsafe(no_mangle)] -extern "C" fn napi_get_uv_event_loop(env_: napi_env, loop_: *mut napi_event_loop) -> napi_status { +// HOST_EXPORT(napi_get_uv_event_loop, c) +pub fn napi_get_uv_event_loop(env_: Option<&NapiEnv>, loop_: Out) -> napi_status { bun_output::scoped_log!(napi, "napi_get_uv_event_loop"); let env = get_env!(env_); let loop_out = get_out!(env, loop_); @@ -2287,75 +1507,32 @@ extern "C" fn napi_get_uv_event_loop(env_: napi_env, loop_: *mut napi_event_loop { // A past alignment assertion here fired spuriously. // TODO(@190n) investigate - *loop_out = VirtualMachine::get().uv_loop(); + loop_out.write(VirtualMachine::get().uv_loop()); } #[cfg(not(windows))] { // there is no uv event loop on posix, we use our event loop handle. - // SAFETY: `VirtualMachine::event_loop` already yields `*mut EventLoop`; - // no const→mut cast needed. - // SAFETY: bun_vm() never null for a Bun-owned global. - *loop_out = env.to_js().bun_vm().event_loop(); + loop_out.write(env.to_js().bun_vm().event_loop()); } env.ok() } -unsafe extern "C" { - pub(super) fn napi_fatal_exception(env: napi_env, err: napi_value) -> napi_status; - pub(super) fn napi_add_async_cleanup_hook( - env: napi_env, - function: napi_async_cleanup_hook, - data: *mut c_void, - handle_out: *mut napi_async_cleanup_hook_handle, - ) -> napi_status; - pub(super) fn napi_add_env_cleanup_hook( - env: napi_env, - function: Option, - data: *mut c_void, - ) -> napi_status; - pub(super) fn napi_create_typedarray( - env: napi_env, - type_: napi_typedarray_type, - length: usize, - arraybuffer: napi_value, - byte_offset: usize, - result: *mut napi_value, - ) -> napi_status; - pub(super) fn napi_remove_async_cleanup_hook( - handle: napi_async_cleanup_hook_handle, - ) -> napi_status; - pub(super) fn napi_remove_env_cleanup_hook( - env: napi_env, - function: Option, - data: *mut c_void, - ) -> napi_status; - - fn napi_internal_cleanup_env_cpp(env: napi_env); - fn napi_internal_check_gc(env: napi_env); - - /// Returns false if the env has already torn down its registry. - fn NapiEnv__registerThreadSafeFunction(env: *mut NapiEnv, tsfn: *mut c_void) -> bool; - fn NapiEnv__unregisterThreadSafeFunction(env: *mut NapiEnv, tsfn: *mut c_void); -} - extern "C" fn napi_internal_register_cleanup_callback(data: *mut c_void) { - // SAFETY: data is the napi_env we registered below. - unsafe { napi_internal_cleanup_env_cpp(data as napi_env) }; + // `data` is the env `napi_internal_register_cleanup_zig` registered. + napi_internal_cleanup_env_cpp(NapiEnv::opaque_ref(data.cast())); } -#[unsafe(no_mangle)] -extern "C" fn napi_internal_register_cleanup_zig(env_: napi_env) { - // SAFETY: caller guarantees env_ is non-null. - let env = unsafe { &*env_ }; +// HOST_EXPORT(napi_internal_register_cleanup_zig, c) +pub fn napi_internal_register_cleanup_zig(env: &NapiEnv) { env.to_js().bun_vm().as_mut().rare_data().push_cleanup_hook( env.to_js(), - env_.cast::(), + env.as_mut_ptr().cast::(), napi_internal_register_cleanup_callback, ); } -#[unsafe(no_mangle)] -extern "C" fn napi_internal_suppress_crash_on_abort_if_desired() { +// HOST_EXPORT(napi_internal_suppress_crash_on_abort_if_desired, c) +pub fn napi_internal_suppress_crash_on_abort_if_desired() { if bun_core::env_var::feature_flag::BUN_INTERNAL_SUPPRESS_CRASH_ON_NAPI_ABORT .get() .unwrap_or(false) @@ -2364,15 +1541,6 @@ extern "C" fn napi_internal_suppress_crash_on_abort_if_desired() { } } -unsafe extern "C" { - fn napi_internal_remove_finalizer( - env: napi_env, - fun: napi_finalize, - hint: *mut c_void, - data: *mut c_void, - ); -} - // ────────────────────────────────────────────────────────────────────────── // Finalizer // ────────────────────────────────────────────────────────────────────────── @@ -2388,46 +1556,38 @@ impl Finalizer { /// Run the addon's finalizer. What it raised through napi (latched on the /// env) or left on the VM is the `Err`, for the caller's dispatcher to fold. pub(crate) fn run(&mut self) -> JsResult<()> { - let env = self.env.get(); - // SAFETY: env is valid for the duration of this call. - let env_ref = unsafe { &*env }; - let _hs = NapiHandleScope::open_scoped(env_ref); + let env: &NapiEnv = &self.env; + let _hs = NapiHandleScope::open_scoped(env); - (self.fun)(env, self.data, self.hint); - // SAFETY: env is valid; passes the C finalizer back for bookkeeping. - unsafe { napi_internal_remove_finalizer(env, Some(self.fun), self.hint, self.data) }; + (self.fun)(env.as_mut_ptr(), self.data, self.hint); + napi_internal_remove_finalizer(env, Some(self.fun), self.hint, self.data); - env_ref.surface_exception(env_ref.to_js()) + env.surface_exception(env.to_js()) } - // `deinit` is handled by Drop on NapiEnvRef. - /// Takes ownership of `this`. pub(crate) fn enqueue(self) { - NapiFinalizerTask::init(self).schedule(); + NapiFinalizerTask::schedule(Box::new(NapiFinalizerTask { finalizer: self })); } } /// For Node-API modules not built with NAPI_EXPERIMENTAL, finalizers should be deferred to the /// immediate task queue instead of run immediately. This lets finalizers perform allocations, /// which they couldn't if they ran immediately while the garbage collector is still running. -#[unsafe(no_mangle)] -extern "C" fn napi_internal_enqueue_finalizer( - env: napi_env, +// HOST_EXPORT(napi_internal_enqueue_finalizer, c) +pub fn napi_internal_enqueue_finalizer( + env: Option<&NapiEnv>, fun: napi_finalize, data: *mut c_void, hint: *mut c_void, ) { let Some(fun) = fun else { return }; - // SAFETY: env is either null or a valid pointer per the N-API contract; - // null returns early. - let Some(env_ref) = (unsafe { env.as_ref() }) else { + let Some(env) = env else { return; }; let this = Finalizer { fun, - // SAFETY: env_ref points to a live C++-owned napi_env. - env: unsafe { NapiEnvRef::clone_from_raw(env_ref.as_mut_ptr()) }, + env: env.to_ref(), data, hint, }; @@ -2438,9 +1598,60 @@ extern "C" fn napi_internal_enqueue_finalizer( // ThreadSafeFunction // ────────────────────────────────────────────────────────────────────────── -/// Ownership: the JS thread owns this allocation until `finalize` or `env_teardown` sets `resources_released`; then the remaining `thread_count` references own it and the last one dropped frees it. -// TODO: generate a compile-time version of this instead of runtime checking -pub(crate) struct ThreadSafeFunction { +/// Reference-counted; each reference belongs to one holder: the JS side's +/// (`TsfnJs::owner_ref`, from creation until the function is finalized or its +/// env torn down), the addon threads' (`TsfnShared::threads_ref`, held while +/// `thread_count > 0`), a queued dispatch task's (`TsfnShared::dispatch_ref`) +/// and the queued finalize task's (`TsfnJs::finalize_ref`). Whoever drops the +/// last one frees it, on whichever thread that is (see `TsfnJs` for why that +/// is only ever plain memory by then). +#[derive(bun_ptr::ThreadSafeRefCounted)] +pub struct ThreadSafeFunction { + ref_count: bun_ptr::ThreadSafeRefCount, + /// The addon threads' references (`napi_acquire/release_threadsafe_function`). + /// It reaching zero (with nothing queued) is what finalizes the function. + thread_count: AtomicI64, + /// The call queue, and the references that change hands under its lock. + shared: Guarded, + /// This value will never change after initialization. Zero means the size is unlimited. + max_queue_size: usize, + queue_count: AtomicU32, + dispatch_state: AtomicU8, // DispatchState + blocking_condvar: Condvar, + closing: AtomicU8, // ClosingState + /// Written under `shared`'s lock by `env_teardown` on the JS thread: the + /// loop is going away. Every path that would schedule onto it from another + /// thread reads it under the same lock, so teardown cannot land between + /// the check and the enqueue. + env_dead: AtomicBool, + + ctx: *mut c_void, + /// The addon's `call_js_cb`; `None`: `callback` is called directly. + call_js: Option, + /// How addon threads (`napi_call_threadsafe_function`) schedule a + /// dispatch on the VM. Weak: addon threads hold this function for as long + /// as they like (Node: calls after env cleanup get `napi_closing`), so it + /// cannot be something the VM waits for. + handle: VmHandle, + loop_kind: LoopKind, + + /// JS-thread state. + js: JsCell, +} + +struct TsfnShared { + queue: LinearFifo<*mut c_void, DynamicBuffer<*mut c_void>>, + /// Held on behalf of the addon threads while `thread_count > 0`. + threads_ref: Option>, + /// The queued dispatch task's (at most one is queued: `dispatch_state`). + dispatch_ref: Option>, +} + +/// Only the JS thread touches this. By the time the JS side's reference is +/// released (`finalize` / `env_teardown`) everything JS-affine here has been +/// released on the JS thread — `env` taken, `callback` emptied, `poll_ref` +/// unref'd — so whichever thread drops the last reference only frees memory. +struct TsfnJs { /// thread-safe functions can be "referenced" and "unreferenced". A /// "referenced" thread-safe function will cause the event loop on the thread /// on which it is created to remain alive until the thread-safe function is @@ -2451,55 +1662,17 @@ pub(crate) struct ThreadSafeFunction { /// Neither does napi_unref_threadsafe_function mark the thread-safe /// functions as able to be destroyed nor does napi_ref_threadsafe_function /// prevent it from being destroyed. - pub poll_ref: KeepAlive, - - // User implementation error can cause this number to go negative. - pub(crate) thread_count: AtomicI64, - // for std.condvar - pub(crate) lock: Mutex, - - // Note: BackRef — `enqueue_task`/`drain_microtasks` need `&mut - // EventLoop`; reborrowed at use sites (single JS thread). `None` once the - // owning env is torn down: the loop lives inside a VirtualMachine that a - // worker's shutdown frees, while addon threads outlive it. - /// JS-thread uses; `None` once the env has been torn down. - pub(crate) event_loop: Option>, - /// How addon threads (`napi_call_threadsafe_function`) schedule a - /// dispatch on the VM. Weak: addon threads hold this function for as long - /// as they like (Node: calls after env cleanup get `napi_closing`), so it - /// cannot be something the VM waits for. - pub(crate) handle: bun_jsc::VmHandle, - pub(crate) loop_kind: bun_jsc::LoopKind, - pub(crate) tracker: Debugger::AsyncTaskTracker, - - /// Dropped on the JS thread by `env_teardown`; `None` afterwards. - pub(crate) env: Option, - pub(crate) finalizer_fun: napi_finalize, - pub(crate) finalizer_data: *mut c_void, - - pub(crate) has_queued_finalizer: bool, - pub(crate) queue: TsfnQueue, - - pub ctx: *mut c_void, - - pub callback: TsfnCallback, - pub(crate) dispatch_state: AtomicU8, // DispatchState - pub(crate) blocking_condvar: Condvar, - pub(crate) closing: AtomicU8, // ClosingState - /// Written under `lock` by `env_teardown` on the JS thread. Every path - /// that would reach `event_loop` from another thread reads it under the - /// same lock, so teardown cannot land between the check and the enqueue. - pub(crate) env_dead: AtomicBool, - /// Also written under `lock`, once `finalize` or `env_teardown` has released every JS-thread-owned resource; until then the thread that drops the last `thread_count` reference must not free this (Node's `kClosed`). - pub(crate) resources_released: AtomicBool, -} - -pub(crate) enum TsfnCallback { - Js(StrongOptional), - C { - js: StrongOptional, - napi_threadsafe_function_call_js: napi_threadsafe_function_call_js, - }, + poll_ref: KeepAlive, + tracker: Debugger::AsyncTaskTracker, + /// Dropped by `env_teardown`; `None` afterwards. + env: Option, + callback: StrongOptional, + finalizer_fun: napi_finalize, + finalizer_data: *mut c_void, + /// The JS side's reference: from creation until `finalize` / `env_teardown`. + owner_ref: Option>, + /// The queued finalize task's reference. + finalize_ref: Option>, } #[repr(u8)] @@ -2512,35 +1685,29 @@ enum ClosingState { #[repr(u8)] #[derive(Copy, Clone, PartialEq, Eq)] -pub(super) enum DispatchState { +pub(crate) enum DispatchState { Idle, Running, Pending, } -pub(crate) struct TsfnQueue { - pub data: LinearFifo<*mut c_void, DynamicBuffer<*mut c_void>>, - /// This value will never change after initialization. Zero means the size is unlimited. - pub max_queue_size: usize, - pub count: AtomicU32, +bun_event_loop::task_hop! { + /// `task_tag::ThreadSafeFunction`: drain the queued calls on the JS thread. + /// The queued task holds `TsfnShared::dispatch_ref`. + pub(crate) TsfnDispatch for ThreadSafeFunction => ThreadSafeFunction; + run = ThreadSafeFunction::run_dispatch_task; + release_unrun = ThreadSafeFunction::release_dispatch_task; } -impl TsfnQueue { - pub(crate) fn init(max_queue_size: usize) -> TsfnQueue { - TsfnQueue { - data: LinearFifo::<*mut c_void, DynamicBuffer<*mut c_void>>::init(), - max_queue_size, - count: AtomicU32::new(0), - } - } - - pub(crate) fn is_blocked(&self) -> bool { - self.max_queue_size > 0 && self.count.load(Ordering::SeqCst) as usize >= self.max_queue_size - } +bun_event_loop::task_hop! { + /// `task_tag::ThreadSafeFunctionFinalize`: the last thread reference is gone + /// and the queue drained; run the addon's finalizer and let the JS side go. + /// The queued task holds `TsfnJs::finalize_ref`. + pub(crate) TsfnFinalize for ThreadSafeFunction => ThreadSafeFunctionFinalize; + run = ThreadSafeFunction::run_finalize_task; + release_unrun = ThreadSafeFunction::release_finalize_task; } -// Drop on TsfnQueue: LinearFifo drops itself. - /// Live `ThreadSafeFunction` allocations, process-wide. static THREADSAFE_FUNCTION_LIVE_COUNT: AtomicUsize = AtomicUsize::new(0); @@ -2563,59 +1730,77 @@ impl Drop for ThreadSafeFunction { } impl ThreadSafeFunction { - pub(crate) fn new(init: ThreadSafeFunction) -> *mut ThreadSafeFunction { + fn new(init: ThreadSafeFunction) -> RefPtr { let _ = THREADSAFE_FUNCTION_LIVE_COUNT.fetch_add(1, Ordering::SeqCst); - bun_core::heap::into_raw(Box::new(init)) + RefPtr::new(init) + } + + fn run_dispatch_task(this: ThisPtr) -> JsResult<()> { + let dispatched = this.shared.lock().dispatch_ref.take(); + Self::drain(this); + if let Some(dispatched) = dispatched { + dispatched.deref(); + } + Ok(()) + } + + /// The env's cleanup hook (`env_teardown`, run with the exit handlers + /// before the queue is released) already neutralised the function; only + /// the task's reference is left to drop. + fn release_dispatch_task(this: ThisPtr) { + let dispatched = this.shared.lock().dispatch_ref.take(); + if let Some(dispatched) = dispatched { + dispatched.deref(); + } + } + + fn run_finalize_task(this: ThisPtr) -> JsResult<()> { + let queued = this.js.with_mut(|js| js.finalize_ref.take()); + if !this.env_dead.load(Ordering::SeqCst) { + Self::finalize(this); + } + if let Some(queued) = queued { + queued.deref(); + } + Ok(()) + } + + /// The finalize task never ran: normally because the VM is tearing down, + /// in which case `env_teardown` (which the function is still registered + /// for) runs the addon's finalizer and drops the JS side's reference; only + /// the task's own reference is dropped here. + fn release_finalize_task(this: ThisPtr) { + let queued = this.js.with_mut(|js| js.finalize_ref.take()); + if let Some(queued) = queued { + queued.deref(); + } } - // This has two states: - // 1. We need to run potentially multiple tasks. - // 2. We need to finalize the ThreadSafeFunction. - // - // Dispatched via the event-loop task table (`dispatch.rs`), which hands us - // a `*mut ThreadSafeFunction`; the signature is fixed by that registry. /// The threadsafe function's queue drain is a dispatcher: each queued call /// is a JS entry of its own, so what one leaves pending is folded per call /// (`dispatch_one`) and the drain goes on; the VM's termination ends it. - #[allow(clippy::not_unsafe_ptr_arg_deref)] - pub(crate) fn on_dispatch(this: *mut ThreadSafeFunction) { - // SAFETY: `this` is a live heap allocation owned by the event loop - // dispatch; `env_dead` is atomic so a shared reborrow suffices. - if unsafe { (*this).env_dead.load(Ordering::SeqCst) } { - // `env_teardown` already released everything and owns the free - // decision. The loop this task came from is being destroyed. - return; - } - // SAFETY: as above. - if unsafe { (*this).closing.load(Ordering::SeqCst) } == ClosingState::Closed as u8 { - // SAFETY: `this` is the live heap allocation `maybe_queue_finalizer` - // queued this task for. - unsafe { ThreadSafeFunction::finalize(this) }; + fn drain(this: ThisPtr) { + if this.env_dead.load(Ordering::SeqCst) { + // `env_teardown` already released everything the JS side owned. The + // loop this task came from is being destroyed. return; } + // Finalization is its own task (`TsfnFinalize`), queued once nothing + // can schedule a dispatch any more. + debug_assert!(this.closing.load(Ordering::SeqCst) != ClosingState::Closed as u8); let mut is_first = true; // Run the tasks. loop { - // SAFETY: as above. - unsafe { - (*this) - .dispatch_state - .store(DispatchState::Running as u8, Ordering::SeqCst) - }; - // SAFETY: as above. `dispatch_one` runs JS that can re-enter other - // TSFN entry points, so the exclusive borrow is scoped to this call. + this.dispatch_state + .store(DispatchState::Running as u8, Ordering::SeqCst); // A stopping VM ends the drain like an empty queue does. - let more = unsafe { (*this).dispatch_one(is_first) }.unwrap_or(false); + let more = Self::dispatch_one(this, is_first).unwrap_or(false); if more { is_first = false; - // SAFETY: as above. - unsafe { - (*this) - .dispatch_state - .store(DispatchState::Pending as u8, Ordering::SeqCst) - }; + this.dispatch_state + .store(DispatchState::Pending as u8, Ordering::SeqCst); } else { // We're done running tasks, for now. Transition Running → Idle // via CAS instead of an unconditional store: between @@ -2627,16 +1812,15 @@ impl ThreadSafeFunction { // up. If we blindly stored Idle we'd overwrite that Pending // and the callback would be dropped (flaky lost-wakeup under // load). On CAS failure, loop and re-drain. - // SAFETY: as above. - if unsafe { - (*this).dispatch_state.compare_exchange( + if this + .dispatch_state + .compare_exchange( DispatchState::Running as u8, DispatchState::Idle as u8, Ordering::SeqCst, Ordering::SeqCst, ) - } - .is_ok() + .is_ok() { break; } @@ -2654,42 +1838,46 @@ impl ThreadSafeFunction { self.closing.load(Ordering::SeqCst) != ClosingState::NotClosing as u8 } - /// The creating VM's event loop, or `None` once its env has been torn down. - /// - /// JS-thread only. Its callers (`call`, `maybe_queue_finalizer`) run from - /// the loop's own dispatch, so no other `&mut EventLoop` is live. Paths - /// reachable from an addon thread must use the shared `&EventLoop` that - /// `BackRef` derefs to, never this. - #[inline] - fn loop_mut(&mut self) -> Option<&mut EventLoop> { - let back_ref = self.event_loop.as_mut()?; - // SAFETY: BackRef invariant while `Some`; JS thread, outside tick(). - Some(unsafe { back_ref.get_mut() }) + fn is_blocked(&self) -> bool { + self.max_queue_size > 0 + && self.queue_count.load(Ordering::SeqCst) as usize >= self.max_queue_size + } + + /// This function's env; `None` once it has been torn down. JS thread. + fn env(&self) -> Option<&NapiEnv> { + self.js.get().env.as_deref() + } + + /// The creating VM's event loop, or `None` once its env has been torn + /// down. JS thread; its callers run from the loop's own dispatch. + fn event_loop(&self) -> Option<&mut EventLoop> { + let env = self.env()?; + Some(env.to_js().bun_vm().event_loop_of(self.loop_kind)) } - fn maybe_queue_finalizer(&mut self) { - let prev = self + fn maybe_queue_finalizer(this: ThisPtr) { + let prev = this .closing .swap(ClosingState::Closed as u8, Ordering::SeqCst); - match prev { - x if x == ClosingState::Closing as u8 || x == ClosingState::NotClosing as u8 => { - // TODO: is this boolean necessary? Can we rely just on the closing value? - if !self.has_queued_finalizer { - // Note: replace callback with a no-op variant to drop Strong now. - self.callback = TsfnCallback::Js(StrongOptional::empty()); - self.poll_ref.disable(); - let self_ptr: *mut Self = self; - let Some(loop_) = self.loop_mut() else { - // env torn down: `env_teardown` owns the finalize + free. - return; - }; - loop_.enqueue_task(Task::init(self_ptr)); - self.has_queued_finalizer = true; - } + if prev == ClosingState::Closed as u8 { + // already scheduled. + return; + } + let queue = this.js.with_mut(|js| { + if js.finalize_ref.is_some() { + return false; } - _ => { - // already scheduled. + js.callback = StrongOptional::empty(); + js.poll_ref.disable(); + if this.env_dead.load(Ordering::SeqCst) || js.env.is_none() { + // env torn down: `env_teardown` owns the finalize. + return false; } + js.finalize_ref = Some(RefPtr::from_this(this)); + true + }); + if queue && let Some(event_loop) = this.event_loop() { + event_loop.enqueue_task(TsfnFinalize::task(this)); } } @@ -2699,80 +1887,84 @@ impl ThreadSafeFunction { /// This can run several times in one tick of the event loop, so the /// microtasks one call queued are drained before the next call /// (https://github.com/nodejs/node/pull/38506), but not before the first. - pub(crate) fn dispatch_one(&mut self, is_first: bool) -> Result { + pub(crate) fn dispatch_one( + this: ThisPtr, + is_first: bool, + ) -> Result { let mut queue_finalizer_after_call = false; let task = 'brk: { - // `MutexGuard` holds the lock by raw pointer, so it does not borrow - // `*self` across the `&mut self` calls below. - let _g = self.lock.lock_guard(); - if self.is_closing() { + let mut shared = this.shared.lock(); + if this.is_closing() { // Closing (napi_tsfn_abort, or the last call already ran): // nothing still queued runs any more, as in Node's DispatchOne. // An abort's leftovers go back to the addon, with no lock held - // since that re-enters it. Then it finalizes whatever thread_count is: after an abort the other threads may never release (Node's CloseHandlesAndMaybeDelete). - let leftovers = self.take_queue(); - drop(_g); - self.hand_back(leftovers); - let _g = self.lock.lock_guard(); - self.maybe_queue_finalizer(); + // since that re-enters it; the function finalizes once the last + // thread reference is gone. + let leftovers = this.take_queue(&mut shared); + drop(shared); + this.hand_back(leftovers); + let _shared = this.shared.lock(); + if this.thread_count.load(Ordering::SeqCst) == 0 { + Self::maybe_queue_finalizer(this); + } return Ok(false); } - let was_blocked = self.queue.is_blocked(); - let Some(t) = self.queue.data.read_item() else { + let Some(t) = shared.queue.read_item() else { // When there are no tasks and the number of threads that have // references reaches zero, we prepare to finalize the // ThreadSafeFunction. - if self.thread_count.load(Ordering::SeqCst) == 0 { - if self.queue.max_queue_size > 0 { - self.blocking_condvar.signal(); + if this.thread_count.load(Ordering::SeqCst) == 0 { + if this.max_queue_size > 0 { + this.blocking_condvar.signal(); } - self.maybe_queue_finalizer(); + Self::maybe_queue_finalizer(this); } return Ok(false); }; - if self.queue.count.fetch_sub(1, Ordering::SeqCst) == 1 - && self.thread_count.load(Ordering::SeqCst) == 0 + if this.queue_count.fetch_sub(1, Ordering::SeqCst) == 1 + && this.thread_count.load(Ordering::SeqCst) == 0 { - self.closing + this.closing .store(ClosingState::Closing as u8, Ordering::SeqCst); - if self.queue.max_queue_size > 0 { - self.blocking_condvar.signal(); + if this.max_queue_size > 0 { + this.blocking_condvar.signal(); } queue_finalizer_after_call = true; - } else if was_blocked && !self.queue.is_blocked() { - self.blocking_condvar.signal(); + } else if this.max_queue_size > 0 { + // A slot opened: one blocked producer may go. (Waking one only + // on the full → not-full edge strands the other waiters once + // the woken producer has nothing more to push.) + this.blocking_condvar.signal(); } break 'brk t; }; - let called = match self.loop_mut() { - Some(loop_) if !is_first => loop_.drain_microtasks(), + let called = match this.event_loop() { + Some(event_loop) if !is_first => event_loop.drain_microtasks(), _ => Ok(()), } - .and_then(|()| self.call(task)); + .and_then(|()| this.call(task)); // The last queued call finalizes even when the VM is stopping. if queue_finalizer_after_call { - self.maybe_queue_finalizer(); + Self::maybe_queue_finalizer(this); } called?; - // An item was dequeued: keep on_dispatch looping so remaining queued + // An item was dequeued: keep `drain` looping so remaining queued // items drain and the empty-queue thread_count==0 path can finalize. Ok(true) } /// One queued call from the drain, which is its landing frame: what it /// left pending is folded here. `Err`: the VM is stopping. - fn call(&mut self, task: *mut c_void) -> Result<(), bun_jsc::Stopped> { - let Some(env) = self.env.as_ref().map(NapiEnvRef::get) else { + fn call(&self, task: *mut c_void) -> Result<(), bun_jsc::Stopped> { + let Some(env) = self.env() else { // env torn down; nothing to call into. return Ok(()); }; - // SAFETY: env is valid while the TSF is live. - let env = unsafe { &*env }; match self.deliver(env, task) { Ok(()) => Ok(()), Err(err) => bun_jsc::task::report_error_or_terminate(env.to_js(), err), @@ -2781,44 +1973,45 @@ impl ThreadSafeFunction { /// One queued call: a JS entry of its own, so what it leaves pending is /// the `Err`, for the caller's landing frame to fold. `env` is this - /// function's own, which `self.env` still holds. - fn deliver(&mut self, env: &NapiEnv, task: *mut c_void) -> JsResult<()> { + /// function's own, which `js.env` still holds. + fn deliver(&self, env: &NapiEnv, task: *mut c_void) -> JsResult<()> { let global_object = env.to_js(); - let _dispatch = self.tracker.dispatch(global_object); + let (tracker, callback) = { + let js = self.js.get(); + (js.tracker, js.callback.get()) + }; + let _dispatch = tracker.dispatch(global_object); - match &self.callback { - TsfnCallback::Js(strong) => { - let js: JSValue = strong.get().unwrap_or(JSValue::UNDEFINED); + match self.call_js { + None => { + let js: JSValue = callback.unwrap_or(JSValue::UNDEFINED); if js.is_empty_or_undefined_or_null() { return Ok(()); } js.call(global_object, JSValue::UNDEFINED, &[]).map(drop) } - TsfnCallback::C { - js: cb_js, - napi_threadsafe_function_call_js, - } => { + Some(call_js) => { let _hs = NapiHandleScope::open_scoped(env); // No func at creation => null js_callback (Node), not encoded undefined. - let js = match cb_js.get() { + let js = match callback { Some(v) => napi_value::create(env, v), None => napi_value(0), }; - napi_threadsafe_function_call_js(env.as_mut_ptr(), js, self.ctx, task); + call_js(env.as_mut_ptr(), js, self.ctx, task); env.surface_exception(global_object) } } } - /// Caller holds `lock`. Empties the queue; the items are the caller's to - /// give back to the addon once the lock is dropped. - fn take_queue(&mut self) -> Vec<*mut c_void> { + /// Caller holds the lock (`shared`). Empties the queue; the items are the + /// caller's to give back to the addon once the lock is dropped. + fn take_queue(&self, shared: &mut TsfnShared) -> Vec<*mut c_void> { let mut items = Vec::new(); - while let Some(item) = self.queue.data.read_item() { + while let Some(item) = shared.queue.read_item() { items.push(item); } - self.queue.count.store(0, Ordering::SeqCst); + self.queue_count.store(0, Ordering::SeqCst); items } @@ -2828,101 +2021,85 @@ impl ThreadSafeFunction { /// JS is no longer reachable" (Node's ThreadSafeFunction::EmptyQueue). A /// function created without a call_js_cb has nothing to give back. fn hand_back(&self, items: Vec<*mut c_void>) { - let TsfnCallback::C { - napi_threadsafe_function_call_js, - .. - } = &self.callback - else { + let Some(call_js) = self.call_js else { return; }; - let call_js = *napi_threadsafe_function_call_js; for item in items { call_js(ptr::null_mut(), napi_value(0), self.ctx, item); } } /// Runs on an addon thread. A call that reports `napi_closing` consumes the - /// caller's thread reference, so like a release it can free the threadsafe - /// function -- hence `*mut Self`, not `&mut self` (Node's `Push`). - /// - /// SAFETY: `this` is a live threadsafe function and the caller holds no - /// reference into it. - pub(crate) unsafe fn push( - this: *mut ThreadSafeFunction, - ctx: *mut c_void, - block: bool, - ) -> napi_status { - // SAFETY: live allocation; the borrow is scoped to this call and ends - // before the free below. - let (status, orphaned) = unsafe { (*this).enqueue(ctx, block) }; - - if orphaned { - // SAFETY: the lock is dropped, this was the last thread reference, - // and the JS thread already released what only it may release. - unsafe { ThreadSafeFunction::free_orphaned(this) }; - } + /// caller's thread reference (Node's `Push`), which can be the last one. + pub(crate) fn push(this: ThisPtr, ctx: *mut c_void, block: bool) -> napi_status { + let mut released = Released::default(); + let status = Self::enqueue(this, ctx, block, &mut released); + released.release(); status } - /// Returns `(status, caller_must_free)`; the free must happen after the - /// lock guard here is dropped, which is why only `push` may call this. - fn enqueue(&mut self, ctx: *mut c_void, block: bool) -> (napi_status, bool) { - let _g = self.lock.lock_guard(); + fn enqueue( + this: ThisPtr, + ctx: *mut c_void, + block: bool, + released: &mut Released, + ) -> napi_status { + let mut shared = this.shared.lock(); if block { - while self.queue.is_blocked() && !self.is_closing() { - self.blocking_condvar.wait(&self.lock); + while this.is_blocked() && !this.is_closing() { + this.blocking_condvar.wait_guarded(&mut shared); } - } else if self.queue.is_blocked() && !self.is_closing() { + } else if this.is_blocked() && !this.is_closing() { // A closing threadsafe function reports napi_closing even with a full // queue (node's `Push` skips the queue-full check unless it is open), // so the caller's reference is still consumed and it can finalize. // don't set the error on the env as this is run from another thread - return (NapiStatus::queue_full as napi_status, false); + return NapiStatus::queue_full as napi_status; } - if self.is_closing() { + if this.is_closing() { // `env_teardown` sets `closing` under this same lock, so an env that // dies while we wait above lands here, never below. - if self.thread_count.load(Ordering::SeqCst) <= 0 { - return (NapiStatus::invalid_arg as napi_status, false); + if this.thread_count.load(Ordering::SeqCst) <= 0 { + return NapiStatus::invalid_arg as napi_status; } // Consumes this thread's reference, like Node's `Push`, so a thread - // that stops calling after napi_closing does not pin the loop. That - // can be the last reference: the caller frees if we say so. - let (_, caller_must_free) = - self.release_locked(napi_threadsafe_function_release_mode::release); - return (NapiStatus::closing as napi_status, caller_must_free); + // that stops calling after napi_closing does not pin the loop. + let _ = Self::release_locked( + this, + &mut shared, + napi_threadsafe_function_release_mode::release, + released, + ); + return NapiStatus::closing as napi_status; } - let _ = self.queue.count.fetch_add(1, Ordering::SeqCst); - let _ = self.queue.data.write_item(ctx); // OOM/capacity failures are fire-and-forget - self.schedule_dispatch(); - (NapiStatus::ok as napi_status, false) + let _ = this.queue_count.fetch_add(1, Ordering::SeqCst); + let _ = shared.queue.write_item(ctx); // OOM/capacity failures are fire-and-forget + Self::schedule_dispatch(this, &mut shared, released); + NapiStatus::ok as napi_status } - /// Caller must hold `lock`. Reached from addon threads (`enqueue`, + /// Caller holds the lock (`shared`). Reached from addon threads (`enqueue`, /// `release_locked`); the VM is reached only through its handle. - fn schedule_dispatch(&mut self) { - let prev = self + fn schedule_dispatch(this: ThisPtr, shared: &mut TsfnShared, released: &mut Released) { + let prev = this .dispatch_state .swap(DispatchState::Pending as u8, Ordering::SeqCst); match prev { x if x == DispatchState::Idle as u8 => { - let self_ptr: *mut Self = self; - if self.event_loop.is_none() { + if this.env_dead.load(Ordering::SeqCst) { // env torn down: the loop is gone, nothing to schedule onto. return; } - let ct = ConcurrentTask::create_from(self_ptr); - if let bun_jsc::vm_handle::Posted::Refused(ct) = - self.handle.post(self.loop_kind, ct) - { + debug_assert!(shared.dispatch_ref.is_none()); + shared.dispatch_ref = Some(RefPtr::from_this(this)); + if !this.handle.post_hop::(this.loop_kind, this) { // VM closed before the env cleanup hook ran here: no // dispatch will happen; the queued calls are released by the - // teardown path. Free the task and fall back to Idle. - // SAFETY: refused ⇒ we own the task box. - unsafe { drop(bun_core::heap::take(ct.as_ptr())) }; - self.dispatch_state + // teardown path. Fall back to Idle. + released.add(shared.dispatch_ref.take()); + this.dispatch_state .store(DispatchState::Idle as u8, Ordering::SeqCst); } } @@ -2935,94 +2112,60 @@ impl ThreadSafeFunction { } } - /// Runs on the JS thread once the function has closed. Runs the addon's - /// finalizer, releases what only this thread may release, and frees the - /// allocation unless another thread still holds a reference; then the last - /// release frees it (Node's Finalize + MaybeDelete). - /// - /// SAFETY: `this` is a live allocation from `new` that no other event-loop - /// task will reach again. - unsafe fn finalize(this: *mut ThreadSafeFunction) { - // SAFETY: caller contract. The borrow ends before the addon's finalizer - // runs; it may still use the handle (napi_get_threadsafe_function_context). - let finalizer = unsafe { - let self_ = &mut *this; - if let Some(env) = self_.env.as_ref() { - // SAFETY: env is live (we hold a ref). `this` is an opaque - // registry key here, never dereferenced. - NapiEnv__unregisterThreadSafeFunction(env.get(), this.cast()); - } - self_ + /// JS thread: the queue drained with no thread references left (Node's + /// Finalize). Queues the addon's finalizer, releases everything JS-affine + /// (see `TsfnJs`) and drops the JS side's reference. + fn finalize(this: ThisPtr) { + let (finalizer, env, owner) = this.js.with_mut(|js| { + js.poll_ref.unref(bun_io::js_vm_ctx()); + js.callback = StrongOptional::empty(); + let finalizer = js .finalizer_fun - .take() - .zip(self_.env.as_ref()) + .zip(js.env.as_ref()) .map(|(fun, env)| Finalizer { env: env.clone(), fun, - data: self_.finalizer_data, - hint: self_.ctx, - }) - }; - - // Before anything is released, as in Node and `env_teardown`. - if let Some(mut finalizer) = finalizer { - crate::dispatch::fold(finalizer.run()); + data: js.finalizer_data, + hint: this.ctx, + }); + (finalizer, js.env.take(), js.owner_ref.take()) + }); + + if let Some(env) = env { + // Drops our registry entry so teardown cannot hand this pointer + // out after it is freed. + NapiEnv__unregisterThreadSafeFunction(&env, this.as_ptr().cast()); } - - // SAFETY: caller contract; the finalizer has returned and the borrow - // ends before the free below. - let free = unsafe { - let self_ = &mut *this; - // The same critical section reads thread_count, so a thread that drops the last reference frees only if it sees this store. - let _g = self_.lock.lock_guard(); - self_.event_loop = None; - drop(self_.env.take()); - self_.resources_released.store(true, Ordering::SeqCst); - self_.thread_count.load(Ordering::SeqCst) <= 0 - }; - - if free { - // SAFETY: no thread reference is left, the lock is dropped, and - // nothing else can reach this allocation. - unsafe { ThreadSafeFunction::free_orphaned(this) }; + if let Some(finalizer) = finalizer { + finalizer.enqueue(); + } + if let Some(owner) = owner { + owner.deref(); } - } - - /// Frees the allocation and nothing else: no finalizer, no registry entry, - /// no event loop. Every JS-thread-owned resource must already be released - /// (`finalize`, `env_teardown`) or be safe to drop here (a creation that failed). - /// - /// SAFETY: `this` is a live allocation from `new`, the caller holds no - /// lock on it, and no other thread holds a reference. - unsafe fn free_orphaned(this: *mut ThreadSafeFunction) { - // SAFETY: per this function's contract, `this` is a live allocation from `new`. - drop(unsafe { bun_core::heap::take(this) }); } /// Runs on the JS thread from `NapiEnv::cleanup()` while JSC is still /// alive but the VirtualMachine (and the event loop this TSFN points at) /// is about to be destroyed. Mirrors Node's /// ThreadSafeFunction::Cleanup -> Finalize -> MaybeDelete. - /// - /// Returns true if the caller must free the allocation. - fn env_teardown(&mut self) -> bool { + fn env_teardown(this: ThisPtr) { // Phase 1: publish "the loop is going away". From here no other thread - // schedules onto it, but none may free us either -- the JS resources - // below are still live and only this thread may touch them. + // schedules onto it, but none may free us either -- the JS side's + // reference is held until phase 3. let (was_closing, queued) = { - let _g = self.lock.lock_guard(); - self.env_dead.store(true, Ordering::SeqCst); - let was_closing = self.is_closing(); + let mut shared = this.shared.lock(); + this.env_dead.store(true, Ordering::SeqCst); + let was_closing = this.is_closing(); if !was_closing { - self.closing + this.closing .store(ClosingState::Closing as u8, Ordering::SeqCst); } - if self.queue.max_queue_size > 0 { + if this.max_queue_size > 0 { // Wake producers blocked on the bounded queue; they observe // is_closing and release. - self.blocking_condvar.broadcast(); + this.blocking_condvar.broadcast(); } - (was_closing, self.take_queue()) + (was_closing, this.take_queue(&mut shared)) }; // Phase 2: addon callbacks, so no lock is held. @@ -3037,156 +2180,167 @@ impl ThreadSafeFunction { // live env and js_callback, with script refused if the worker was // stopped. A function already closing (napi_tsfn_abort) keeps the // abort contract. The finalizer runs either way. - // - // SAFETY: `env` is live; phase 3 below is what drops our reference. - let env = self.env.as_ref().map(|env| unsafe { &*env.get() }); - if let Some(env) = env + if let Some(env) = this.env() && env.to_js().bun_vm().worker_ref().is_some() { if was_closing { - self.hand_back(queued); - } else if matches!(self.callback, TsfnCallback::C { .. }) { + this.hand_back(queued); + } else if this.call_js.is_some() { for item in queued { // The env's cleanup hook is each delivery's landing frame, // as it is the finalizer's below. - crate::dispatch::fold(self.deliver(env, item)); + crate::dispatch::fold(this.deliver(env, item)); } } } - let finalizer = self - .finalizer_fun - .take() - .zip(self.env.as_ref()) - .map(|(fun, env)| Finalizer { - env: env.clone(), - fun, - data: self.finalizer_data, - hint: self.ctx, - }); + let finalizer = this.js.with_mut(|js| { + js.finalizer_fun + .take() + .zip(js.env.as_ref()) + .map(|(fun, env)| Finalizer { + env: env.clone(), + fun, + data: js.finalizer_data, + hint: this.ctx, + }) + }); if let Some(mut finalizer) = finalizer { // The env's cleanup hook is this finalizer's landing frame: what it // leaves is folded here so the next function's teardown starts clean. crate::dispatch::fold(finalizer.run()); } - // Phase 3: release what only the JS thread may release, then hand the - // allocation over. `resources_released` is published in the critical section that reads thread_count (Node's ReleaseResources + MaybeDelete). - let _g = self.lock.lock_guard(); - self.callback = TsfnCallback::Js(StrongOptional::empty()); - self.poll_ref.disable(); - self.event_loop = None; - drop(self.env.take()); - self.resources_released.store(true, Ordering::SeqCst); - // Cleanup hooks are the loop's last tick: a task still queued for this - // TSFN will never run (and its `release_unrun` does not dereference it). - // With no thread_count reference left, nobody else can reach this, so - // free it here. - self.thread_count.load(Ordering::SeqCst) <= 0 + // Phase 3: release what only the JS thread may release, then let the + // JS side's reference go: from here whoever drops the last reference + // (a thread's, a queued task's) frees the allocation (Node's + // ReleaseResources + MaybeDelete). + let owner = this.js.with_mut(|js| { + js.callback = StrongOptional::empty(); + js.poll_ref.disable(); + drop(js.env.take()); + js.owner_ref.take() + }); + if let Some(owner) = owner { + owner.deref(); + } } /// `napi_ref_threadsafe_function` — JS thread only (as in Node). - pub(crate) fn ref_(&mut self) { - self.poll_ref.ref_(bun_io::js_vm_ctx()); + pub(crate) fn ref_(&self) { + self.js.with_mut(|js| js.poll_ref.ref_(bun_io::js_vm_ctx())); } /// `napi_unref_threadsafe_function` — JS thread only (as in Node). - pub(crate) fn unref(&mut self) { - self.poll_ref.unref(bun_io::js_vm_ctx()); + pub(crate) fn unref(&self) { + self.js + .with_mut(|js| js.poll_ref.unref(bun_io::js_vm_ctx())); } - pub(crate) fn acquire(&mut self) -> napi_status { - let _g = self.lock.lock_guard(); - if self.is_closing() { + pub(crate) fn acquire(this: ThisPtr) -> napi_status { + let mut shared = this.shared.lock(); + if this.is_closing() { return NapiStatus::closing as napi_status; } - let _ = self.thread_count.fetch_add(1, Ordering::SeqCst); + if this.thread_count.fetch_add(1, Ordering::SeqCst) == 0 { + debug_assert!(shared.threads_ref.is_none()); + shared.threads_ref = Some(RefPtr::from_this(this)); + } NapiStatus::ok as napi_status } - /// Frees the threadsafe function when this drops the last thread reference - /// of an orphaned one, so it dispatches off `*mut Self`: freeing through a - /// pointer derived from a live `&mut self` is UB. - /// - /// SAFETY: `this` is a live threadsafe function and the caller holds no - /// reference into it. - pub(crate) unsafe fn release( - this: *mut ThreadSafeFunction, + /// Can drop the last reference, which frees the function. + pub(crate) fn release( + this: ThisPtr, mode: napi_threadsafe_function_release_mode, ) -> napi_status { - let (status, orphaned) = { - // SAFETY: live allocation. `MutexGuard` holds the lock by raw - // pointer, so it does not keep `*this` borrowed across the call - // below; both borrows are scoped and end before the free. - let _g = unsafe { (*this).lock.lock_guard() }; - // SAFETY: as above. - unsafe { (*this).release_locked(mode) } + let mut released = Released::default(); + let status = { + let mut shared = this.shared.lock(); + Self::release_locked(this, &mut shared, mode, &mut released) }; - - if orphaned { - // SAFETY: the lock is dropped, this was the last thread reference, - // and the JS thread already released what only it may release. - unsafe { ThreadSafeFunction::free_orphaned(this) }; - } + released.release(); status } - /// Caller must hold `lock`. Returns `(status, caller_must_free)`; the free - /// must happen after the lock is dropped. + /// Caller holds the lock (`shared`). The last thread reference takes the + /// addon threads' reference with it (into `released`). fn release_locked( - &mut self, + this: ThisPtr, + shared: &mut TsfnShared, mode: napi_threadsafe_function_release_mode, - ) -> (napi_status, bool) { - if self.thread_count.load(Ordering::SeqCst) <= 0 { - return (NapiStatus::invalid_arg as napi_status, false); + released: &mut Released, + ) -> napi_status { + if this.thread_count.load(Ordering::SeqCst) <= 0 { + return NapiStatus::invalid_arg as napi_status; } - let prev_remaining = self.thread_count.fetch_sub(1, Ordering::SeqCst); + let prev_remaining = this.thread_count.fetch_sub(1, Ordering::SeqCst); + if prev_remaining == 1 { + released.add(shared.threads_ref.take()); + } - if self.env_dead.load(Ordering::SeqCst) - || self.closing.load(Ordering::SeqCst) == ClosingState::Closed as u8 - { - // The JS thread owns the finalization (`finalize` queued or done, or `env_teardown` ran): never schedule onto the loop again. The last reference frees us once `resources_released` is set; before that the JS thread frees us itself. - let orphaned = prev_remaining == 1 && self.resources_released.load(Ordering::SeqCst); - return (NapiStatus::ok as napi_status, orphaned); + if this.env_dead.load(Ordering::SeqCst) { + // The event loop we were created on is gone (`env_teardown` set + // this under the lock we hold). Never schedule onto it. + return NapiStatus::ok as napi_status; } - // Already closing: the abort's dispatch is pending or running and finalizes whatever thread_count is by then. - if (mode == napi_threadsafe_function_release_mode::abort || prev_remaining == 1) - && !self.is_closing() - { - if mode == napi_threadsafe_function_release_mode::abort { - self.closing - .store(ClosingState::Closing as u8, Ordering::SeqCst); - if self.queue.max_queue_size > 0 { - // Wake all producers blocked in enqueue()'s bounded queue wait so they observe is_closing and release. - self.blocking_condvar.broadcast(); + if mode == napi_threadsafe_function_release_mode::abort || prev_remaining == 1 { + if !this.is_closing() { + if mode == napi_threadsafe_function_release_mode::abort { + this.closing + .store(ClosingState::Closing as u8, Ordering::SeqCst); + if this.max_queue_size > 0 { + // Wake all producers blocked in enqueue()'s bounded + // queue wait so they observe is_closing and release. + this.blocking_condvar.broadcast(); + } } + Self::schedule_dispatch(this, shared, released); + } else if prev_remaining == 1 { + // Already closing from an earlier abort. The last release must + // still reach dispatch_one's thread_count==0 path so the + // finalizer runs and the event-loop keepalive is dropped. + Self::schedule_dispatch(this, shared, released); } - self.schedule_dispatch(); } - (NapiStatus::ok as napi_status, false) + NapiStatus::ok as napi_status } } -/// Called from `NapiEnv::cleanup()` (JS thread) for every threadsafe function -/// still registered with the env that is being torn down. -#[unsafe(no_mangle)] -extern "C" fn napi_internal_threadsafe_function_env_teardown(tsfn: *mut c_void) { - let this = tsfn.cast::(); - // SAFETY: the registry only holds live TSFN pointers — `finalize` and - // `env_teardown` both remove the entry before freeing. Exclusive borrow - // scoped to this call. - if unsafe { (*this).env_teardown() } { - // SAFETY: no other thread holds a reference (thread_count == 0) and no - // event-loop task will run again. - unsafe { ThreadSafeFunction::free_orphaned(this) }; +/// References whose holders let go inside a `ThreadSafeFunction`'s critical +/// section, released once its lock is dropped: the last one frees the +/// function, lock included. +#[derive(Default)] +struct Released([Option>; 2]); + +impl Released { + fn add(&mut self, r: Option>) { + if let Some(r) = r { + let slot = self.0.iter_mut().find(|slot| slot.is_none()); + *slot.expect("at most two references change hands per call") = Some(r); + } + } + + fn release(self) { + for r in self.0.into_iter().flatten() { + r.deref(); + } } } -#[unsafe(no_mangle)] -extern "C" fn napi_create_threadsafe_function( - env_: napi_env, +/// Called from `NapiEnv::cleanup()` (JS thread) for every threadsafe function +/// still registered with the env that is being torn down. The registry only +/// holds live functions (`finalize` and this both remove the entry). +// HOST_EXPORT(napi_internal_threadsafe_function_env_teardown, c) +pub fn napi_internal_threadsafe_function_env_teardown(tsfn: ThisPtr) { + ThreadSafeFunction::env_teardown(tsfn); +} + +// HOST_EXPORT(napi_create_threadsafe_function, c) +pub fn napi_create_threadsafe_function( + env_: Option<&NapiEnv>, func_: napi_value, _async_resource: napi_value, _async_resource_name: napi_value, @@ -3196,7 +2350,7 @@ extern "C" fn napi_create_threadsafe_function( thread_finalize_cb: napi_finalize, context: *mut c_void, call_js_cb: Option, - result_: *mut napi_threadsafe_function, + result_: Out<*mut ThreadSafeFunction>, ) -> napi_status { bun_output::scoped_log!(napi, "napi_create_threadsafe_function"); let env = get_env!(env_); @@ -3205,2055 +2359,233 @@ extern "C" fn napi_create_threadsafe_function( if call_js_cb.is_none() && (func.is_empty_or_undefined_or_null() - || (!func.is_callable() && !func.is_async_context_frame())) + || (!func.is_callable() && !is_async_context_frame(func))) { - return NapiEnv::set_last_error(Some(env), NapiStatus::function_expected); + return env.status(NapiStatus::function_expected); } let vm = env.to_js().bun_vm().as_mut(); - let callback = if let Some(c) = call_js_cb { - TsfnCallback::C { - napi_threadsafe_function_call_js: c, - js: if func.is_empty() { - StrongOptional::empty() - } else { - StrongOptional::create(func.with_async_context_if_needed(env.to_js()), vm.global()) - }, - } + let callback = if func.is_empty() { + StrongOptional::empty() } else { - TsfnCallback::Js(if func.is_empty() { - StrongOptional::empty() - } else { - StrongOptional::create(func.with_async_context_if_needed(env.to_js()), vm.global()) - }) + StrongOptional::create(func.with_async_context_if_needed(env.to_js()), vm.global()) }; - let function = ThreadSafeFunction::new(ThreadSafeFunction { - // SAFETY: the loop is live now; `NapiEnv::cleanup()` clears this field - // (via `env_teardown`) before the VirtualMachine holding it is freed. - event_loop: Some(unsafe { bun_ptr::BackRef::from_raw_mut(vm.event_loop()) }), - handle: vm.handle(), - loop_kind: vm.current_loop_kind(), - // SAFETY: env is a live C++-owned napi_env. - env: Some(unsafe { NapiEnvRef::clone_from_raw(env.as_mut_ptr()) }), - callback, - ctx: context, - queue: TsfnQueue::init(max_queue_size), + let owner = ThreadSafeFunction::new(ThreadSafeFunction { + ref_count: bun_ptr::ThreadSafeRefCount::init(), thread_count: AtomicI64::new(i64::try_from(initial_thread_count).expect("int cast")), - poll_ref: KeepAlive::init(), - tracker: Debugger::AsyncTaskTracker::init(vm), - finalizer_fun: thread_finalize_cb, - finalizer_data: thread_finalize_data, - has_queued_finalizer: false, - lock: Mutex::new(), + shared: Guarded::new(TsfnShared { + queue: LinearFifo::<*mut c_void, DynamicBuffer<*mut c_void>>::init(), + threads_ref: None, + dispatch_ref: None, + }), + max_queue_size, + queue_count: AtomicU32::new(0), dispatch_state: AtomicU8::new(DispatchState::Idle as u8), blocking_condvar: Condvar::default(), closing: AtomicU8::new(ClosingState::NotClosing as u8), env_dead: AtomicBool::new(false), - resources_released: AtomicBool::new(false), + ctx: context, + call_js: call_js_cb, + handle: vm.handle(), + loop_kind: vm.current_loop_kind(), + js: JsCell::new(TsfnJs { + poll_ref: KeepAlive::init(), + tracker: Debugger::AsyncTaskTracker::init(vm), + env: Some(env.to_ref()), + callback, + finalizer_fun: thread_finalize_cb, + finalizer_data: thread_finalize_data, + owner_ref: None, + finalize_ref: None, + }), }); + let this = owner.this_ptr(); // Register with the env so that VM/worker teardown neutralizes this TSFN // before the event loop it points at is freed. `false` means the env has // already torn its threadsafe functions down -- we are running from a // finalizer, after the loop's last tick. - // SAFETY: env is live; `function` is a fresh heap allocation. - if !unsafe { NapiEnv__registerThreadSafeFunction(env.as_mut_ptr(), function.cast()) } { + if !NapiEnv__registerThreadSafeFunction(env, this.as_ptr().cast()) { // Born dead. Free only what we allocated and never run the addon's // finalizer: the handle was never published, so the addon still owns // what it passed in (node's `Init` failure path just deletes the // ThreadSafeFunction, whose destructor only releases its own resources). - // SAFETY: the allocation we just made; nothing else can reach it. - unsafe { ThreadSafeFunction::free_orphaned(function) }; + owner.deref(); return env.generic_failure(); } - // nodejs by default keeps the event loop alive until the thread-safe function is unref'd - // SAFETY: function is non-null (just allocated) and not yet handed out. - unsafe { (*function).ref_() }; - // SAFETY: as above. - unsafe { (*function).tracker.did_schedule(vm.global()) }; + if initial_thread_count > 0 { + this.shared.lock().threads_ref = Some(RefPtr::from_this(this)); + } + this.js.with_mut(|js| { + js.owner_ref = Some(owner); + // nodejs by default keeps the event loop alive until the thread-safe function is unref'd + js.poll_ref.ref_(bun_io::js_vm_ctx()); + js.tracker.did_schedule(vm.global()); + }); - *result = function; + result.write(this.as_ptr()); env.ok() } -#[unsafe(no_mangle)] -extern "C" fn napi_get_threadsafe_function_context( - func: napi_threadsafe_function, - result: *mut *mut c_void, +// HOST_EXPORT(napi_get_threadsafe_function_context, c) +pub fn napi_get_threadsafe_function_context( + func: Option<&ThreadSafeFunction>, + result: Out<*mut c_void>, ) -> napi_status { bun_output::scoped_log!(napi, "napi_get_threadsafe_function_context"); - // SAFETY: func and result are non-null per N-API contract. - unsafe { *result = (*func).ctx }; + let (Some(func), Some(result)) = (func, result) else { + return NapiStatus::invalid_arg as napi_status; + }; + result.write(func.ctx); NapiStatus::ok as napi_status } -#[unsafe(no_mangle)] -extern "C" fn napi_call_threadsafe_function( - func: napi_threadsafe_function, +// HOST_EXPORT(napi_call_threadsafe_function, c) +pub fn napi_call_threadsafe_function( + func: Option>, data: *mut c_void, is_blocking: napi_threadsafe_function_call_mode, ) -> napi_status { bun_output::scoped_log!(napi, "napi_call_threadsafe_function"); - // SAFETY: func is non-null per N-API contract, and the caller may not use it - // afterwards if this reports napi_closing — that consumes the caller's - // thread reference, which can free it. - unsafe { ThreadSafeFunction::push(func, data, is_blocking == NAPI_TSFN_BLOCKING) } + let Some(func) = func else { + return NapiStatus::invalid_arg as napi_status; + }; + // The caller may not use `func` afterwards if this reports napi_closing — + // that consumes the caller's thread reference, which can free it. + ThreadSafeFunction::push(func, data, is_blocking == NAPI_TSFN_BLOCKING) } -#[unsafe(no_mangle)] -extern "C" fn napi_acquire_threadsafe_function(func: napi_threadsafe_function) -> napi_status { +// HOST_EXPORT(napi_acquire_threadsafe_function, c) +pub fn napi_acquire_threadsafe_function(func: Option>) -> napi_status { bun_output::scoped_log!(napi, "napi_acquire_threadsafe_function"); - // SAFETY: func is non-null per N-API contract. - unsafe { &mut *func }.acquire() + let Some(func) = func else { + return NapiStatus::invalid_arg as napi_status; + }; + ThreadSafeFunction::acquire(func) } -#[unsafe(no_mangle)] -extern "C" fn napi_release_threadsafe_function( - func: napi_threadsafe_function, +// HOST_EXPORT(napi_release_threadsafe_function, c) +pub fn napi_release_threadsafe_function( + func: Option>, mode: napi_threadsafe_function_release_mode, ) -> napi_status { bun_output::scoped_log!(napi, "napi_release_threadsafe_function"); - // SAFETY: func is non-null per N-API contract, and the caller may not use - // it afterwards — this call can free it. - unsafe { ThreadSafeFunction::release(func, mode) } + let Some(func) = func else { + return NapiStatus::invalid_arg as napi_status; + }; + // The caller may not use `func` afterwards — this call can free it. + ThreadSafeFunction::release(func, mode) } -#[unsafe(no_mangle)] -extern "C" fn napi_unref_threadsafe_function( - env_: napi_env, - func: napi_threadsafe_function, +// HOST_EXPORT(napi_unref_threadsafe_function, c) +pub fn napi_unref_threadsafe_function( + env_: Option<&NapiEnv>, + func: Option<&ThreadSafeFunction>, ) -> napi_status { bun_output::scoped_log!(napi, "napi_unref_threadsafe_function"); - if func.is_null() { + let Some(func) = func else { return NapiStatus::invalid_arg as napi_status; - } + }; #[cfg(debug_assertions)] - { - // SAFETY: `func` was null-checked above; JS thread, shared read. - let loop_ = unsafe { (*func).event_loop.as_ref() }; - // SAFETY: `env_` is either null or a valid napi_env per N-API contract. - let env = unsafe { env_.as_ref() }; - if let (Some(loop_), Some(env)) = (loop_, env) { - debug_assert!(core::ptr::eq(loop_.global.unwrap().as_ptr(), env.to_js())); - } + if let (Some(own), Some(env)) = (func.env(), env_) { + debug_assert!(core::ptr::eq(own.to_js(), env.to_js())); } #[cfg(not(debug_assertions))] let _ = env_; - // SAFETY: `func` was null-checked above; exclusive borrow scoped to this call. - unsafe { (*func).unref() }; + func.unref(); NapiStatus::ok as napi_status } -#[unsafe(no_mangle)] -extern "C" fn napi_ref_threadsafe_function( - env_: napi_env, - func: napi_threadsafe_function, +// HOST_EXPORT(napi_ref_threadsafe_function, c) +pub fn napi_ref_threadsafe_function( + env_: Option<&NapiEnv>, + func: Option<&ThreadSafeFunction>, ) -> napi_status { bun_output::scoped_log!(napi, "napi_ref_threadsafe_function"); - if func.is_null() { + let Some(func) = func else { return NapiStatus::invalid_arg as napi_status; - } + }; #[cfg(debug_assertions)] - { - // SAFETY: `func` was null-checked above; JS thread, shared read. - let loop_ = unsafe { (*func).event_loop.as_ref() }; - // SAFETY: `env_` is either null or a valid napi_env per N-API contract. - let env = unsafe { env_.as_ref() }; - if let (Some(loop_), Some(env)) = (loop_, env) { - debug_assert!(core::ptr::eq(loop_.global.unwrap().as_ptr(), env.to_js())); - } + if let (Some(own), Some(env)) = (func.env(), env_) { + debug_assert!(core::ptr::eq(own.to_js(), env.to_js())); } #[cfg(not(debug_assertions))] let _ = env_; - // SAFETY: `func` was null-checked above; exclusive borrow scoped to this call. - unsafe { (*func).ref_() }; + func.ref_(); NapiStatus::ok as napi_status } -const NAPI_AUTO_LENGTH: usize = usize::MAX; - -// ────────────────────────────────────────────────────────────────────────── -// V8 API symbol references (DCE suppression) -// ────────────────────────────────────────────────────────────────────────── - -/// v8:: C++ symbols defined in v8.cpp -/// -/// Do not call these at runtime, as they do not contain type and callconv info. They are simply -/// used for DCE suppression and asserting that the symbols exist at link-time. -/// -// TODO: write a script to generate this struct. ideally it wouldn't even need to be committed to source. -#[cfg(not(windows))] -mod v8_api { - use core::ffi::c_void; - unsafe extern "C" { - pub(super) fn _ZN2v87Isolate10GetCurrentEv() -> *mut c_void; - pub(super) fn _ZN2v87Isolate13TryGetCurrentEv() -> *mut c_void; - pub(super) fn _ZN2v87Isolate17GetCurrentContextEv() -> *mut c_void; - pub(super) fn _ZN2v87Isolate28GetEnteredOrMicrotaskContextEv() -> *mut c_void; - pub(super) fn _ZN2v87Isolate36GetContinuationPreservedEmbedderDataEv() -> *mut c_void; - pub(super) fn _ZN2v87Isolate7IsInUseEv() -> *mut c_void; - pub(super) fn _ZN2v87Isolate21LowMemoryNotificationEv() -> *mut c_void; - pub(super) fn _ZN2v87Isolate36AutomaticallyRestoreInitialHeapLimitEd() -> *mut c_void; - pub(super) fn _ZN2v87Isolate30NumberOfTrackedHeapObjectTypesEv() -> *mut c_void; - pub(super) fn _ZN2v87Isolate31GetHeapObjectStatisticsAtLastGCEPNS_20HeapObjectStatisticsEm() - -> *mut c_void; - pub(super) fn _ZN2v87Isolate21AddGCPrologueCallbackEPFvPS0_NS_6GCTypeENS_15GCCallbackFlagsEPvES4_S2_() - -> *mut c_void; - pub(super) fn _ZN2v87Isolate24RemoveGCPrologueCallbackEPFvPS0_NS_6GCTypeENS_15GCCallbackFlagsEPvES4_() - -> *mut c_void; - pub(super) fn _ZN2v87Isolate21AddGCEpilogueCallbackEPFvPS0_NS_6GCTypeENS_15GCCallbackFlagsEPvES4_S2_() - -> *mut c_void; - pub(super) fn _ZN2v87Isolate24RemoveGCEpilogueCallbackEPFvPS0_NS_6GCTypeENS_15GCCallbackFlagsEPvES4_() - -> *mut c_void; - pub(super) fn _ZN2v87Isolate24AddNearHeapLimitCallbackEPFmPvmmES1_() -> *mut c_void; - pub(super) fn _ZN2v87Isolate27RemoveNearHeapLimitCallbackEPFmPvmmEm() -> *mut c_void; - pub(super) fn _ZN2v87Isolate16RequestInterruptEPFvPS0_PvES2_() -> *mut c_void; - pub(super) fn _ZN2v87Isolate14ThrowExceptionENS_5LocalINS_5ValueEEE() -> *mut c_void; - pub(super) fn _ZN2v87Isolate10ThrowErrorENS_5LocalINS_6StringEEE() -> *mut c_void; - pub(super) fn _ZN2v89Exception5ErrorENS_5LocalINS_6StringEEENS1_INS_5ValueEEE() - -> *mut c_void; - pub(super) fn _ZN2v89Exception9TypeErrorENS_5LocalINS_6StringEEENS1_INS_5ValueEEE() - -> *mut c_void; - pub(super) fn _ZN2v87Isolate15GetHeapProfilerEv() -> *mut c_void; - pub(super) fn _ZN2v812HeapProfiler24StopSamplingHeapProfilerEv() -> *mut c_void; - pub(super) fn _ZN2v812HeapProfiler20GetAllocationProfileEv() -> *mut c_void; - pub(super) fn _ZN4node25AddEnvironmentCleanupHookEPN2v87IsolateEPFvPvES3_() -> *mut c_void; - pub(super) fn _ZN4node28RemoveEnvironmentCleanupHookEPN2v87IsolateEPFvPvES3_() -> *mut c_void; - pub(super) fn _ZN4node19GetCurrentEventLoopEPN2v87IsolateE() -> *mut c_void; - pub(super) fn _ZN4node29AsyncHooksGetExecutionAsyncIdEN2v85LocalINS0_7ContextEEE() - -> *mut c_void; - pub(super) fn _ZN4node13EmitAsyncInitEPN2v87IsolateENS0_5LocalINS0_6ObjectEEENS3_INS0_6StringEEEd() - -> *mut c_void; - pub(super) fn _ZN4node16EmitAsyncDestroyEPN2v87IsolateENS_13async_contextE() -> *mut c_void; - pub(super) fn _ZN4node12MakeCallbackEPN2v87IsolateENS0_5LocalINS0_6ObjectEEENS3_INS0_8FunctionEEEiPNS3_INS0_5ValueEEENS_13async_contextE() - -> *mut c_void; - pub(super) fn _ZN2v84base9TimeTicks3NowEv() -> *mut c_void; - pub(super) fn _ZN2v86Number3NewEPNS_7IsolateEd() -> *mut c_void; - pub(super) fn _ZNK2v86Number5ValueEv() -> *mut c_void; - pub(super) fn _ZN2v86Number12NewFromInt32EPNS_7IsolateEi() -> *mut c_void; - pub(super) fn _ZN2v86Number13NewFromUint32EPNS_7IsolateEj() -> *mut c_void; - pub(super) fn _ZN2v86String11NewFromUtf8EPNS_7IsolateEPKcNS_13NewStringTypeEi() - -> *mut c_void; - pub(super) fn _ZNK2v86String9WriteUtf8EPNS_7IsolateEPciPii() -> *mut c_void; - pub(super) fn _ZN2v812api_internal12ToLocalEmptyEv() -> *mut c_void; - pub(super) fn _ZNK2v86String6LengthEv() -> *mut c_void; - pub(super) fn _ZN2v88External3NewEPNS_7IsolateEPv() -> *mut c_void; - pub(super) fn _ZNK2v88External5ValueEv() -> *mut c_void; - pub(super) fn _ZN2v88External3NewEPNS_7IsolateEPvt() -> *mut c_void; - pub(super) fn _ZNK2v88External5ValueEt() -> *mut c_void; - pub(super) fn _ZN2v86Object3NewEPNS_7IsolateE() -> *mut c_void; - pub(super) fn _ZN2v86Object3SetENS_5LocalINS_7ContextEEENS1_INS_5ValueEEES5_() -> *mut c_void; - pub(super) fn _ZN2v86Object3SetENS_5LocalINS_7ContextEEEjNS1_INS_5ValueEEE() -> *mut c_void; - pub(super) fn _ZN2v86Object16SetInternalFieldEiNS_5LocalINS_4DataEEE() -> *mut c_void; - pub(super) fn _ZN2v86Object20SlowGetInternalFieldEi() -> *mut c_void; - pub(super) fn _ZN2v86Object32SetAlignedPointerInInternalFieldEiPvt() -> *mut c_void; - pub(super) fn _ZN2v86Object38SlowGetAlignedPointerFromInternalFieldEit() -> *mut c_void; - pub(super) fn _ZN2v86Object3GetENS_5LocalINS_7ContextEEENS1_INS_5ValueEEE() -> *mut c_void; - pub(super) fn _ZN2v86Object3GetENS_5LocalINS_7ContextEEEj() -> *mut c_void; - pub(super) fn _ZN2v811HandleScope12CreateHandleEPNS_8internal7IsolateEm() -> *mut c_void; - pub(super) fn _ZN2v811HandleScope12CreateHandleEPNS_7IsolateEm() -> *mut c_void; - pub(super) fn _ZN2v811HandleScope10InitializeEPNS_7IsolateE() -> *mut c_void; - pub(super) fn _ZNK2v85Value16QuickIsUndefinedEv() -> *mut c_void; - pub(super) fn _ZNK2v85Value11QuickIsNullEv() -> *mut c_void; - pub(super) fn _ZNK2v85Value22QuickIsNullOrUndefinedEv() -> *mut c_void; - pub(super) fn _ZNK2v85Value13QuickIsStringEv() -> *mut c_void; - pub(super) fn _ZN2v811HandleScope6ExtendEPNS_7IsolateE() -> *mut c_void; - pub(super) fn _ZN2v811HandleScope16DeleteExtensionsEPNS_7IsolateE() -> *mut c_void; - pub(super) fn _ZN2v811HandleScopeC1EPNS_7IsolateE() -> *mut c_void; - pub(super) fn _ZN2v811HandleScopeD1Ev() -> *mut c_void; - pub(super) fn _ZN2v811HandleScopeD2Ev() -> *mut c_void; - pub(super) fn _ZN2v816FunctionTemplate11GetFunctionENS_5LocalINS_7ContextEEE() -> *mut c_void; - pub(super) fn _ZN2v816FunctionTemplate12SetClassNameENS_5LocalINS_6StringEEE() -> *mut c_void; - pub(super) fn _ZN2v816FunctionTemplate3NewEPNS_7IsolateEPFvRKNS_20FunctionCallbackInfoINS_5ValueEEEENS_5LocalIS4_EENSA_INS_9SignatureEEEiNS_19ConstructorBehaviorENS_14SideEffectTypeEPKNS_9CFunctionEttt() - -> *mut c_void; - pub(super) fn _ZN2v814ObjectTemplate11NewInstanceENS_5LocalINS_7ContextEEE() -> *mut c_void; - pub(super) fn _ZN2v814ObjectTemplate21SetInternalFieldCountEi() -> *mut c_void; - pub(super) fn _ZNK2v814ObjectTemplate18InternalFieldCountEv() -> *mut c_void; - pub(super) fn _ZN2v814ObjectTemplate3NewEPNS_7IsolateENS_5LocalINS_16FunctionTemplateEEE() - -> *mut c_void; - pub(super) fn _ZN2v816FunctionTemplate16InstanceTemplateEv() -> *mut c_void; - pub(super) fn _ZN2v816FunctionTemplate17PrototypeTemplateEv() -> *mut c_void; - pub(super) fn _ZN2v88Template3SetENS_5LocalINS_4NameEEENS1_INS_4DataEEENS_17PropertyAttributeE() - -> *mut c_void; - pub(super) fn _ZN2v88Template21SetNativeDataPropertyENS_5LocalINS_4NameEEEPFvS3_RKNS_20PropertyCallbackInfoINS_5ValueEEEEPFvS3_NS1_IS5_EERKNS4_IvEEESB_NS_17PropertyAttributeENS_14SideEffectTypeESI_() - -> *mut c_void; - pub(super) fn _ZN2v89Signature3NewEPNS_7IsolateENS_5LocalINS_16FunctionTemplateEEE() - -> *mut c_void; - pub(super) fn _ZN2v824EscapableHandleScopeBase10EscapeSlotEPm() -> *mut c_void; - pub(super) fn _ZN2v824EscapableHandleScopeBaseC2EPNS_7IsolateE() -> *mut c_void; - pub(super) fn _ZN2v88internal35IsolateFromNeverReadOnlySpaceObjectEm() -> *mut c_void; - pub(super) fn _ZN2v85Array3NewEPNS_7IsolateEPNS_5LocalINS_5ValueEEEm() -> *mut c_void; - pub(super) fn _ZNK2v85Array6LengthEv() -> *mut c_void; - pub(super) fn _ZN2v85Array3NewEPNS_7IsolateEi() -> *mut c_void; - pub(super) fn _ZN2v85Array7IterateENS_5LocalINS_7ContextEEEPFNS0_14CallbackResultEjNS1_INS_5ValueEEEPvES7_() - -> *mut c_void; - pub(super) fn _ZN2v85Array9CheckCastEPNS_5ValueE() -> *mut c_void; - pub(super) fn _ZN2v88Function7SetNameENS_5LocalINS_6StringEEE() -> *mut c_void; - pub(super) fn _ZN2v88Function4CallENS_5LocalINS_7ContextEEENS1_INS_5ValueEEEiPS5_() - -> *mut c_void; - pub(super) fn _ZNK2v88Function11NewInstanceENS_5LocalINS_7ContextEEEiPNS1_INS_5ValueEEE() - -> *mut c_void; - pub(super) fn _ZNK2v85Value9IsBooleanEv() -> *mut c_void; - pub(super) fn _ZNK2v87Boolean5ValueEv() -> *mut c_void; - pub(super) fn _ZNK2v85Value10FullIsTrueEv() -> *mut c_void; - pub(super) fn _ZNK2v85Value11FullIsFalseEv() -> *mut c_void; - pub(super) fn _ZN2v820EscapableHandleScopeC1EPNS_7IsolateE() -> *mut c_void; - pub(super) fn _ZN2v820EscapableHandleScopeC2EPNS_7IsolateE() -> *mut c_void; - pub(super) fn _ZN2v820EscapableHandleScopeD1Ev() -> *mut c_void; - pub(super) fn _ZN2v820EscapableHandleScopeD2Ev() -> *mut c_void; - pub(super) fn _ZNK2v85Value8IsObjectEv() -> *mut c_void; - pub(super) fn _ZNK2v85Value8IsNumberEv() -> *mut c_void; - pub(super) fn _ZNK2v85Value8IsUint32Ev() -> *mut c_void; - pub(super) fn _ZNK2v85Value11Uint32ValueENS_5LocalINS_7ContextEEE() -> *mut c_void; - pub(super) fn _ZNK2v85Value11IsUndefinedEv() -> *mut c_void; - pub(super) fn _ZNK2v85Value6IsNullEv() -> *mut c_void; - pub(super) fn _ZNK2v85Value17IsNullOrUndefinedEv() -> *mut c_void; - pub(super) fn _ZNK2v85Value6IsTrueEv() -> *mut c_void; - pub(super) fn _ZNK2v85Value7IsFalseEv() -> *mut c_void; - pub(super) fn _ZNK2v85Value8IsStringEv() -> *mut c_void; - pub(super) fn _ZNK2v85Value12StrictEqualsENS_5LocalIS0_EE() -> *mut c_void; - pub(super) fn _ZN2v87Boolean3NewEPNS_7IsolateEb() -> *mut c_void; - pub(super) fn _ZN2v811ArrayBuffer3NewEPNS_7IsolateEmNS_30BackingStoreInitializationModeE() - -> *mut c_void; - pub(super) fn _ZN2v811ArrayBuffer15GetBackingStoreEv() -> *mut c_void; - pub(super) fn _ZNK2v812BackingStore4DataEv() -> *mut c_void; - pub(super) fn _ZN2v815ArrayBufferView6BufferEv() -> *mut c_void; - pub(super) fn _ZN2v815ArrayBufferView10ByteLengthEv() -> *mut c_void; - pub(super) fn _ZN2v815ArrayBufferView10ByteOffsetEv() -> *mut c_void; - pub(super) fn _ZN2v810Uint8Array3NewENS_5LocalINS_11ArrayBufferEEEmm() -> *mut c_void; - pub(super) fn _ZN2v811Uint32Array3NewENS_5LocalINS_11ArrayBufferEEEmm() -> *mut c_void; - pub(super) fn _ZN2v86Object16GetInternalFieldEi() -> *mut c_void; - pub(super) fn _ZN2v87Context10GetIsolateEv() -> *mut c_void; - pub(super) fn _ZN2v86String14NewFromOneByteEPNS_7IsolateEPKhNS_13NewStringTypeEi() - -> *mut c_void; - pub(super) fn _ZNK2v86String10Utf8LengthEPNS_7IsolateE() -> *mut c_void; - pub(super) fn _ZNK2v86String10IsExternalEv() -> *mut c_void; - pub(super) fn _ZNK2v86String17IsExternalOneByteEv() -> *mut c_void; - pub(super) fn _ZNK2v86String17IsExternalTwoByteEv() -> *mut c_void; - pub(super) fn _ZNK2v86String9IsOneByteEv() -> *mut c_void; - pub(super) fn _ZNK2v86String19ContainsOnlyOneByteEv() -> *mut c_void; - pub(super) fn _ZNK2v86String7WriteV2EPNS_7IsolateEjjPti() -> *mut c_void; - pub(super) fn _ZNK2v86String14WriteOneByteV2EPNS_7IsolateEjjPhi() -> *mut c_void; - pub(super) fn _ZNK2v86String11WriteUtf8V2EPNS_7IsolateEPcmiPm() -> *mut c_void; - pub(super) fn _ZNK2v86String12Utf8LengthV2EPNS_7IsolateE() -> *mut c_void; - pub(super) fn _ZN2v812api_internal18GlobalizeReferenceEPNS_8internal7IsolateEm() - -> *mut c_void; - pub(super) fn _ZN2v812api_internal13DisposeGlobalEPm() -> *mut c_void; - pub(super) fn _ZN2v812api_internal8MakeWeakEPmPvPFvRKNS_16WeakCallbackInfoIvEEENS_16WeakCallbackTypeE() - -> *mut c_void; - pub(super) fn _ZN2v812api_internal9ClearWeakEPm() -> *mut c_void; - pub(super) fn _ZN2v812api_internal19MoveGlobalReferenceEPPmS2_() -> *mut c_void; - pub(super) fn _ZN2v812api_internal23GetFunctionTemplateDataEPNS_7IsolateENS_5LocalINS_4DataEEE() - -> *mut c_void; - pub(super) fn _ZNK2v88Function7GetNameEv() -> *mut c_void; - pub(super) fn _ZNK2v85Value10IsFunctionEv() -> *mut c_void; - pub(super) fn _ZNK2v85Value5IsMapEv() -> *mut c_void; - pub(super) fn _ZNK2v85Value7IsArrayEv() -> *mut c_void; - pub(super) fn _ZNK2v85Value7IsInt32Ev() -> *mut c_void; - pub(super) fn _ZNK2v85Value8IsBigIntEv() -> *mut c_void; - pub(super) fn _ZN2v812api_internal17FromJustIsNothingEv() -> *mut c_void; - pub(super) fn _ZN2v87Integer3NewEPNS_7IsolateEi() -> *mut c_void; - pub(super) fn _ZN2v87Integer15NewFromUnsignedEPNS_7IsolateEj() -> *mut c_void; - pub(super) fn _ZNK2v87Integer5ValueEv() -> *mut c_void; - pub(super) fn _ZN2v86String18NewFromUtf8LiteralEPNS_7IsolateEPKcNS_13NewStringTypeEi() - -> *mut c_void; - pub(super) fn _ZNK2v85Value12IsUint8ArrayEv() -> *mut c_void; - pub(super) fn _ZNK2v85Value8ToStringENS_5LocalINS_7ContextEEE() -> *mut c_void; - pub(super) fn _ZNK2v85Value9ToIntegerENS_5LocalINS_7ContextEEE() -> *mut c_void; - pub(super) fn _ZN2v87Context6GlobalEv() -> *mut c_void; - pub(super) fn _ZNK2v86Object18InternalFieldCountEv() -> *mut c_void; - pub(super) fn _ZN2v86Object15GetIdentityHashEv() -> *mut c_void; - pub(super) fn _ZN2v86Object17DefineOwnPropertyENS_5LocalINS_7ContextEEENS1_INS_4NameEEENS1_INS_5ValueEEENS_17PropertyAttributeE() - -> *mut c_void; - pub(super) fn _ZN2v820ToExternalPointerTagEt() -> *mut c_void; - pub(super) fn _ZN2v88internal9Internals17GetCurrentIsolateEv() -> *mut c_void; - pub(super) fn _ZN2v820HeapObjectStatisticsC1Ev() -> *mut c_void; - pub(super) fn _ZN2v811CpuProfiler3NewEPNS_7IsolateENS_22CpuProfilingNamingModeENS_23CpuProfilingLoggingModeE() - -> *mut c_void; - pub(super) fn _ZN2v811CpuProfiler7DisposeEv() -> *mut c_void; - pub(super) fn _ZN2v811CpuProfiler19SetSamplingIntervalEi() -> *mut c_void; - pub(super) fn _ZN2v811CpuProfiler5StartENS_5LocalINS_6StringEEENS_16CpuProfilingModeEbj() - -> *mut c_void; - pub(super) fn _ZN2v811CpuProfiler4StopEj() -> *mut c_void; - pub(super) fn _ZN2v811CpuProfiler14StartProfilingENS_5LocalINS_6StringEEENS_16CpuProfilingModeEbj() - -> *mut c_void; - pub(super) fn _ZN2v811CpuProfiler14StartProfilingENS_5LocalINS_6StringEEEb() -> *mut c_void; - pub(super) fn _ZN2v811CpuProfiler13StopProfilingENS_5LocalINS_6StringEEE() -> *mut c_void; - pub(super) fn _ZN2v810CpuProfile6DeleteEv() -> *mut c_void; - pub(super) fn _ZNK2v810CpuProfile8GetTitleEv() -> *mut c_void; - pub(super) fn _ZNK2v810CpuProfile10GetEndTimeEv() -> *mut c_void; - pub(super) fn _ZNK2v810CpuProfile12GetStartTimeEv() -> *mut c_void; - pub(super) fn _ZNK2v810CpuProfile14GetTopDownRootEv() -> *mut c_void; - pub(super) fn _ZNK2v810CpuProfile15GetSamplesCountEv() -> *mut c_void; - pub(super) fn _ZNK2v810CpuProfile18GetSampleTimestampEi() -> *mut c_void; - pub(super) fn _ZNK2v810CpuProfile9GetSampleEi() -> *mut c_void; - pub(super) fn _ZNK2v814CpuProfileNode11GetHitCountEv() -> *mut c_void; - pub(super) fn _ZNK2v814CpuProfileNode11GetScriptIdEv() -> *mut c_void; - pub(super) fn _ZNK2v814CpuProfileNode12GetLineTicksEPNS0_8LineTickEj() -> *mut c_void; - pub(super) fn _ZNK2v814CpuProfileNode13GetLineNumberEv() -> *mut c_void; - pub(super) fn _ZNK2v814CpuProfileNode15GetColumnNumberEv() -> *mut c_void; - pub(super) fn _ZNK2v814CpuProfileNode15GetFunctionNameEv() -> *mut c_void; - pub(super) fn _ZNK2v814CpuProfileNode15GetHitLineCountEv() -> *mut c_void; - pub(super) fn _ZNK2v814CpuProfileNode16GetChildrenCountEv() -> *mut c_void; - pub(super) fn _ZNK2v814CpuProfileNode18GetFunctionNameStrEv() -> *mut c_void; - pub(super) fn _ZNK2v814CpuProfileNode21GetScriptResourceNameEv() -> *mut c_void; - pub(super) fn _ZNK2v814CpuProfileNode8GetChildEi() -> *mut c_void; - pub(super) fn _ZN2v83Map3SetENS_5LocalINS_7ContextEEENS1_INS_5ValueEEES5_() -> *mut c_void; - pub(super) fn _ZN2v83Map6DeleteENS_5LocalINS_7ContextEEENS1_INS_5ValueEEE() -> *mut c_void; - // NOTE: return type omitted to match the `uv_functions_to_export` declarations - // below (avoids `clashing_extern_declarations`); only the symbol address is used. - pub(super) fn uv_os_getpid(); - pub(super) fn uv_os_getppid(); - } -} - -#[cfg(windows)] -mod v8_api { - use core::ffi::c_void; - // MSVC name mangling is different than it is on unix. - // To make this easier to deal with, this script generates the list of functions. - // - // dumpbin .\build\CMakeFiles\bun-debug.dir\src\bun.js\bindings\v8\*.cpp.obj /symbols | where-object { $_.Contains(' node::') -or $_.Contains(' v8::') } | foreach-object { (($_ -split "\|")[1] -split " ")[1] } | ForEach-Object { "extern fn @`"${_}`"() *anyopaque;" } - // - // MSVC-mangled symbol names contain `?@$` and are not valid Rust identifiers, so each entry - // is exposed under a Rust-safe alias via `#[link_name = "..."]`. The list is purely for DCE - // suppression / link-time existence checks and has no runtime callers — only the symbol - // *address* is taken (see `fix_dead_code_elimination`). - #[rustfmt::skip] - unsafe extern "C" { - #[link_name = "?TryGetCurrent@Isolate@v8@@SAPEAV12@XZ"] - pub(super) fn v8_Isolate_TryGetCurrent() -> *mut c_void; - #[link_name = "?GetCurrent@Isolate@v8@@SAPEAV12@XZ"] - pub(super) fn v8_Isolate_GetCurrent() -> *mut c_void; - #[link_name = "?GetCurrentContext@Isolate@v8@@QEAA?AV?$Local@VContext@v8@@@2@XZ"] - pub(super) fn v8_Isolate_GetCurrentContext() -> *mut c_void; - #[link_name = "?GetEnteredOrMicrotaskContext@Isolate@v8@@QEAA?AV?$Local@VContext@v8@@@2@XZ"] - pub(super) fn v8_Isolate_GetEnteredOrMicrotaskContext() -> *mut c_void; - #[link_name = "?GetContinuationPreservedEmbedderData@Isolate@v8@@QEAA?AV?$Local@VValue@v8@@@2@XZ"] - pub(super) fn v8_Isolate_GetContinuationPreservedEmbedderData() -> *mut c_void; - #[link_name = "?IsInUse@Isolate@v8@@QEAA_NXZ"] - pub(super) fn v8_Isolate_IsInUse() -> *mut c_void; - #[link_name = "?LowMemoryNotification@Isolate@v8@@QEAAXXZ"] - pub(super) fn v8_Isolate_LowMemoryNotification() -> *mut c_void; - #[link_name = "?AutomaticallyRestoreInitialHeapLimit@Isolate@v8@@QEAAXN@Z"] - pub(super) fn v8_Isolate_AutomaticallyRestoreInitialHeapLimit() -> *mut c_void; - #[link_name = "?NumberOfTrackedHeapObjectTypes@Isolate@v8@@QEAA_KXZ"] - pub(super) fn v8_Isolate_NumberOfTrackedHeapObjectTypes() -> *mut c_void; - #[link_name = "?GetHeapObjectStatisticsAtLastGC@Isolate@v8@@QEAA_NPEAVHeapObjectStatistics@2@_K@Z"] - pub(super) fn v8_Isolate_GetHeapObjectStatisticsAtLastGC() -> *mut c_void; - #[link_name = "?AddGCPrologueCallback@Isolate@v8@@QEAAXP6AXPEAV12@W4GCType@2@W4GCCallbackFlags@2@PEAX@Z31@Z"] - pub(super) fn v8_Isolate_AddGCPrologueCallback() -> *mut c_void; - #[link_name = "?RemoveGCPrologueCallback@Isolate@v8@@QEAAXP6AXPEAV12@W4GCType@2@W4GCCallbackFlags@2@PEAX@Z3@Z"] - pub(super) fn v8_Isolate_RemoveGCPrologueCallback() -> *mut c_void; - #[link_name = "?AddGCEpilogueCallback@Isolate@v8@@QEAAXP6AXPEAV12@W4GCType@2@W4GCCallbackFlags@2@PEAX@Z31@Z"] - pub(super) fn v8_Isolate_AddGCEpilogueCallback() -> *mut c_void; - #[link_name = "?RemoveGCEpilogueCallback@Isolate@v8@@QEAAXP6AXPEAV12@W4GCType@2@W4GCCallbackFlags@2@PEAX@Z3@Z"] - pub(super) fn v8_Isolate_RemoveGCEpilogueCallback() -> *mut c_void; - #[link_name = "?AddNearHeapLimitCallback@Isolate@v8@@QEAAXP6A_KPEAX_K1@Z0@Z"] - pub(super) fn v8_Isolate_AddNearHeapLimitCallback() -> *mut c_void; - #[link_name = "?RemoveNearHeapLimitCallback@Isolate@v8@@QEAAXP6A_KPEAX_K1@Z1@Z"] - pub(super) fn v8_Isolate_RemoveNearHeapLimitCallback() -> *mut c_void; - #[link_name = "?RequestInterrupt@Isolate@v8@@QEAAXP6AXPEAV12@PEAX@Z1@Z"] - pub(super) fn v8_Isolate_RequestInterrupt() -> *mut c_void; - #[link_name = "?ThrowException@Isolate@v8@@QEAA?AV?$Local@VValue@v8@@@2@V32@@Z"] - pub(super) fn v8_Isolate_ThrowException() -> *mut c_void; - #[link_name = "?ThrowError@Isolate@v8@@QEAA?AV?$Local@VValue@v8@@@2@V?$Local@VString@v8@@@2@@Z"] - pub(super) fn v8_Isolate_ThrowError() -> *mut c_void; - #[link_name = "?Error@Exception@v8@@SA?AV?$Local@VValue@v8@@@2@V?$Local@VString@v8@@@2@V32@@Z"] - pub(super) fn v8_Exception_Error() -> *mut c_void; - #[link_name = "?TypeError@Exception@v8@@SA?AV?$Local@VValue@v8@@@2@V?$Local@VString@v8@@@2@V32@@Z"] - pub(super) fn v8_Exception_TypeError() -> *mut c_void; - #[link_name = "?GetHeapProfiler@Isolate@v8@@QEAAPEAVHeapProfiler@2@XZ"] - pub(super) fn v8_Isolate_GetHeapProfiler() -> *mut c_void; - #[link_name = "?StartSamplingHeapProfiler@HeapProfiler@v8@@QEAA_N_KHW4SamplingFlags@12@@Z"] - pub(super) fn v8_HeapProfiler_StartSamplingHeapProfiler() -> *mut c_void; - #[link_name = "?StopSamplingHeapProfiler@HeapProfiler@v8@@QEAAXXZ"] - pub(super) fn v8_HeapProfiler_StopSamplingHeapProfiler() -> *mut c_void; - #[link_name = "?GetAllocationProfile@HeapProfiler@v8@@QEAAPEAVAllocationProfile@2@XZ"] - pub(super) fn v8_HeapProfiler_GetAllocationProfile() -> *mut c_void; - #[link_name = "?AddEnvironmentCleanupHook@node@@YAXPEAVIsolate@v8@@P6AXPEAX@Z1@Z"] - pub(super) fn node_AddEnvironmentCleanupHook() -> *mut c_void; - #[link_name = "?RemoveEnvironmentCleanupHook@node@@YAXPEAVIsolate@v8@@P6AXPEAX@Z1@Z"] - pub(super) fn node_RemoveEnvironmentCleanupHook() -> *mut c_void; - #[link_name = "?GetCurrentEventLoop@node@@YAPEAUuv_loop_s@@PEAVIsolate@v8@@@Z"] - pub(super) fn node_GetCurrentEventLoop() -> *mut c_void; - #[link_name = "?AsyncHooksGetExecutionAsyncId@node@@YANV?$Local@VContext@v8@@@v8@@@Z"] - pub(super) fn node_AsyncHooksGetExecutionAsyncId() -> *mut c_void; - #[link_name = "?EmitAsyncInit@node@@YA?AUasync_context@1@PEAVIsolate@v8@@V?$Local@VObject@v8@@@4@V?$Local@VString@v8@@@4@N@Z"] - pub(super) fn node_EmitAsyncInit() -> *mut c_void; - #[link_name = "?EmitAsyncDestroy@node@@YAXPEAVIsolate@v8@@Uasync_context@1@@Z"] - pub(super) fn node_EmitAsyncDestroy() -> *mut c_void; - #[link_name = "?MakeCallback@node@@YA?AV?$MaybeLocal@VValue@v8@@@v8@@PEAVIsolate@3@V?$Local@VObject@v8@@@3@V?$Local@VFunction@v8@@@3@HPEAV?$Local@VValue@v8@@@3@Uasync_context@1@@Z"] - pub(super) fn node_MakeCallback() -> *mut c_void; - #[link_name = "?Now@TimeTicks@base@v8@@SA?AV123@XZ"] - pub(super) fn v8_base_TimeTicks_Now() -> *mut c_void; - #[link_name = "?New@Number@v8@@SA?AV?$Local@VNumber@v8@@@2@PEAVIsolate@2@N@Z"] - pub(super) fn v8_Number_New() -> *mut c_void; - #[link_name = "?Value@Number@v8@@QEBANXZ"] - pub(super) fn v8_Number_Value() -> *mut c_void; - #[link_name = "?NewFromInt32@Number@v8@@CA?AV?$Local@VNumber@v8@@@2@PEAVIsolate@2@H@Z"] - pub(super) fn v8_Number_NewFromInt32() -> *mut c_void; - #[link_name = "?NewFromUint32@Number@v8@@CA?AV?$Local@VNumber@v8@@@2@PEAVIsolate@2@I@Z"] - pub(super) fn v8_Number_NewFromUint32() -> *mut c_void; - #[link_name = "?NewFromUtf8@String@v8@@SA?AV?$MaybeLocal@VString@v8@@@2@PEAVIsolate@2@PEBDW4NewStringType@2@H@Z"] - pub(super) fn v8_String_NewFromUtf8() -> *mut c_void; - #[link_name = "?WriteUtf8@String@v8@@QEBAHPEAVIsolate@2@PEADHPEAHH@Z"] - pub(super) fn v8_String_WriteUtf8() -> *mut c_void; - #[link_name = "?ToLocalEmpty@api_internal@v8@@YAXXZ"] - pub(super) fn v8_api_internal_ToLocalEmpty() -> *mut c_void; - #[link_name = "?Length@String@v8@@QEBAHXZ"] - pub(super) fn v8_String_Length() -> *mut c_void; - #[link_name = "?New@External@v8@@SA?AV?$Local@VExternal@v8@@@2@PEAVIsolate@2@PEAX@Z"] - pub(super) fn v8_External_New() -> *mut c_void; - #[link_name = "?Value@External@v8@@QEBAPEAXXZ"] - pub(super) fn v8_External_Value() -> *mut c_void; - #[link_name = "?New@External@v8@@SA?AV?$Local@VExternal@v8@@@2@PEAVIsolate@2@PEAXG@Z"] - pub(super) fn v8_External_New_tagged() -> *mut c_void; - #[link_name = "?Value@External@v8@@QEBAPEAXG@Z"] - pub(super) fn v8_External_Value_tagged() -> *mut c_void; - #[link_name = "?New@Object@v8@@SA?AV?$Local@VObject@v8@@@2@PEAVIsolate@2@@Z"] - pub(super) fn v8_Object_New() -> *mut c_void; - #[link_name = "?Set@Object@v8@@QEAA?AV?$Maybe@_N@2@V?$Local@VContext@v8@@@2@V?$Local@VValue@v8@@@2@1@Z"] - pub(super) fn v8_Object_Set_key() -> *mut c_void; - #[link_name = "?Set@Object@v8@@QEAA?AV?$Maybe@_N@2@V?$Local@VContext@v8@@@2@IV?$Local@VValue@v8@@@2@@Z"] - pub(super) fn v8_Object_Set_index() -> *mut c_void; - #[link_name = "?SetInternalField@Object@v8@@QEAAXHV?$Local@VData@v8@@@2@@Z"] - pub(super) fn v8_Object_SetInternalField() -> *mut c_void; - #[link_name = "?SlowGetInternalField@Object@v8@@AEAA?AV?$Local@VData@v8@@@2@H@Z"] - pub(super) fn v8_Object_SlowGetInternalField() -> *mut c_void; - #[link_name = "?SetAlignedPointerInInternalField@Object@v8@@QEAAXHPEAXG@Z"] - pub(super) fn v8_Object_SetAlignedPointerInInternalField() -> *mut c_void; - #[link_name = "?SlowGetAlignedPointerFromInternalField@Object@v8@@AEAAPEAXHG@Z"] - pub(super) fn v8_Object_SlowGetAlignedPointerFromInternalField() -> *mut c_void; - #[link_name = "?Get@Object@v8@@QEAA?AV?$MaybeLocal@VValue@v8@@@2@V?$Local@VContext@v8@@@2@I@Z"] - pub(super) fn v8_Object_Get_index() -> *mut c_void; - #[link_name = "?Get@Object@v8@@QEAA?AV?$MaybeLocal@VValue@v8@@@2@V?$Local@VContext@v8@@@2@V?$Local@VValue@v8@@@2@@Z"] - pub(super) fn v8_Object_Get_key() -> *mut c_void; - #[link_name = "?CreateHandle@HandleScope@v8@@KAPEA_KPEAVIsolate@internal@2@_K@Z"] - pub(super) fn v8_HandleScope_CreateHandle() -> *mut c_void; - #[link_name = "?Extend@HandleScope@v8@@CAPEA_KPEAVIsolate@2@@Z"] - pub(super) fn v8_HandleScope_Extend() -> *mut c_void; - #[link_name = "?DeleteExtensions@HandleScope@v8@@AEAAXPEAVIsolate@2@@Z"] - pub(super) fn v8_HandleScope_DeleteExtensions() -> *mut c_void; - #[link_name = "??0HandleScope@v8@@QEAA@PEAVIsolate@1@@Z"] - pub(super) fn v8_HandleScope_ctor() -> *mut c_void; - #[link_name = "??1HandleScope@v8@@QEAA@XZ"] - pub(super) fn v8_HandleScope_dtor() -> *mut c_void; - #[link_name = "?GetFunction@FunctionTemplate@v8@@QEAA?AV?$MaybeLocal@VFunction@v8@@@2@V?$Local@VContext@v8@@@2@@Z"] - pub(super) fn v8_FunctionTemplate_GetFunction() -> *mut c_void; - #[link_name = "?SetClassName@FunctionTemplate@v8@@QEAAXV?$Local@VString@v8@@@2@@Z"] - pub(super) fn v8_FunctionTemplate_SetClassName() -> *mut c_void; - #[link_name = "?New@FunctionTemplate@v8@@SA?AV?$Local@VFunctionTemplate@v8@@@2@PEAVIsolate@2@P6AXAEBV?$FunctionCallbackInfo@VValue@v8@@@2@@ZV?$Local@VValue@v8@@@2@V?$Local@VSignature@v8@@@2@HW4ConstructorBehavior@2@W4SideEffectType@2@PEBVCFunction@2@GGG@Z"] - pub(super) fn v8_FunctionTemplate_New() -> *mut c_void; - #[link_name = "?NewInstance@ObjectTemplate@v8@@QEAA?AV?$MaybeLocal@VObject@v8@@@2@V?$Local@VContext@v8@@@2@@Z"] - pub(super) fn v8_ObjectTemplate_NewInstance() -> *mut c_void; - #[link_name = "?SetInternalFieldCount@ObjectTemplate@v8@@QEAAXH@Z"] - pub(super) fn v8_ObjectTemplate_SetInternalFieldCount() -> *mut c_void; - #[link_name = "?InternalFieldCount@ObjectTemplate@v8@@QEBAHXZ"] - pub(super) fn v8_ObjectTemplate_InternalFieldCount() -> *mut c_void; - #[link_name = "?New@ObjectTemplate@v8@@SA?AV?$Local@VObjectTemplate@v8@@@2@PEAVIsolate@2@V?$Local@VFunctionTemplate@v8@@@2@@Z"] - pub(super) fn v8_ObjectTemplate_New() -> *mut c_void; - #[link_name = "?InstanceTemplate@FunctionTemplate@v8@@QEAA?AV?$Local@VObjectTemplate@v8@@@2@XZ"] - pub(super) fn v8_FunctionTemplate_InstanceTemplate() -> *mut c_void; - #[link_name = "?PrototypeTemplate@FunctionTemplate@v8@@QEAA?AV?$Local@VObjectTemplate@v8@@@2@XZ"] - pub(super) fn v8_FunctionTemplate_PrototypeTemplate() -> *mut c_void; - #[link_name = "?Set@Template@v8@@QEAAXV?$Local@VName@v8@@@2@V?$Local@VData@v8@@@2@W4PropertyAttribute@2@@Z"] - pub(super) fn v8_Template_Set() -> *mut c_void; - #[link_name = "?SetNativeDataProperty@Template@v8@@QEAAXV?$Local@VName@v8@@@2@P6AX0AEBV?$PropertyCallbackInfo@VValue@v8@@@2@@ZP6AX0V?$Local@VValue@v8@@@2@AEBV?$PropertyCallbackInfo@X@2@@Z3W4PropertyAttribute@2@W4SideEffectType@2@7@Z"] - pub(super) fn v8_Template_SetNativeDataProperty() -> *mut c_void; - #[link_name = "?New@Signature@v8@@SA?AV?$Local@VSignature@v8@@@2@PEAVIsolate@2@V?$Local@VFunctionTemplate@v8@@@2@@Z"] - pub(super) fn v8_Signature_New() -> *mut c_void; - #[link_name = "?EscapeSlot@EscapableHandleScopeBase@v8@@IEAAPEA_KPEA_K@Z"] - pub(super) fn v8_EscapableHandleScopeBase_EscapeSlot() -> *mut c_void; - #[link_name = "??0EscapableHandleScopeBase@v8@@QEAA@PEAVIsolate@1@@Z"] - pub(super) fn v8_EscapableHandleScopeBase_ctor() -> *mut c_void; - #[link_name = "?IsolateFromNeverReadOnlySpaceObject@internal@v8@@YAPEAVIsolate@12@_K@Z"] - pub(super) fn v8_internal_IsolateFromNeverReadOnlySpaceObject() -> *mut c_void; - #[link_name = "?New@Array@v8@@SA?AV?$Local@VArray@v8@@@2@PEAVIsolate@2@PEAV?$Local@VValue@v8@@@2@_K@Z"] - pub(super) fn v8_Array_New_elements() -> *mut c_void; - #[link_name = "?Length@Array@v8@@QEBAIXZ"] - pub(super) fn v8_Array_Length() -> *mut c_void; - #[link_name = "?New@Array@v8@@SA?AV?$Local@VArray@v8@@@2@PEAVIsolate@2@H@Z"] - pub(super) fn v8_Array_New_len() -> *mut c_void; - #[link_name = "?New@Array@v8@@SA?AV?$MaybeLocal@VArray@v8@@@2@V?$Local@VContext@v8@@@2@_KV?$function@$$A6A?AV?$MaybeLocal@VValue@v8@@@v8@@XZ@std@@@Z"] - pub(super) fn v8_Array_New_fn() -> *mut c_void; - #[link_name = "?Iterate@Array@v8@@QEAA?AV?$Maybe@X@2@V?$Local@VContext@v8@@@2@P6A?AW4CallbackResult@12@IV?$Local@VValue@v8@@@2@PEAX@Z2@Z"] - pub(super) fn v8_Array_Iterate() -> *mut c_void; - #[link_name = "?CheckCast@Array@v8@@CAXPEAVValue@2@@Z"] - pub(super) fn v8_Array_CheckCast() -> *mut c_void; - #[link_name = "?SetName@Function@v8@@QEAAXV?$Local@VString@v8@@@2@@Z"] - pub(super) fn v8_Function_SetName() -> *mut c_void; - #[link_name = "?Call@Function@v8@@QEAA?AV?$MaybeLocal@VValue@v8@@@2@V?$Local@VContext@v8@@@2@V?$Local@VValue@v8@@@2@HQEAV52@@Z"] - pub(super) fn v8_Function_Call() -> *mut c_void; - #[link_name = "?NewInstance@Function@v8@@QEBA?AV?$MaybeLocal@VObject@v8@@@2@V?$Local@VContext@v8@@@2@HQEAV?$Local@VValue@v8@@@2@@Z"] - pub(super) fn v8_Function_NewInstance() -> *mut c_void; - #[link_name = "?NewInstance@Function@v8@@QEBA?AV?$MaybeLocal@VObject@v8@@@2@V?$Local@VContext@v8@@@2@@Z"] - pub(super) fn v8_Function_NewInstance_noargs() -> *mut c_void; - #[link_name = "?GetAlignedPointerFromInternalField@Object@v8@@QEAAPEAXHG@Z"] - pub(super) fn v8_Object_GetAlignedPointerFromInternalField() -> *mut c_void; - #[link_name = "?IsBoolean@Value@v8@@QEBA_NXZ"] - pub(super) fn v8_Value_IsBoolean() -> *mut c_void; - #[link_name = "?Value@Boolean@v8@@QEBA_NXZ"] - pub(super) fn v8_Boolean_Value() -> *mut c_void; - #[link_name = "?FullIsTrue@Value@v8@@AEBA_NXZ"] - pub(super) fn v8_Value_FullIsTrue() -> *mut c_void; - #[link_name = "?FullIsFalse@Value@v8@@AEBA_NXZ"] - pub(super) fn v8_Value_FullIsFalse() -> *mut c_void; - #[link_name = "??1EscapableHandleScope@v8@@QEAA@XZ"] - pub(super) fn v8_EscapableHandleScope_dtor() -> *mut c_void; - #[link_name = "??0EscapableHandleScope@v8@@QEAA@PEAVIsolate@1@@Z"] - pub(super) fn v8_EscapableHandleScope_ctor() -> *mut c_void; - #[link_name = "?IsObject@Value@v8@@QEBA_NXZ"] - pub(super) fn v8_Value_IsObject() -> *mut c_void; - #[link_name = "?IsNumber@Value@v8@@QEBA_NXZ"] - pub(super) fn v8_Value_IsNumber() -> *mut c_void; - #[link_name = "?IsUint32@Value@v8@@QEBA_NXZ"] - pub(super) fn v8_Value_IsUint32() -> *mut c_void; - #[link_name = "?Uint32Value@Value@v8@@QEBA?AV?$Maybe@I@2@V?$Local@VContext@v8@@@2@@Z"] - pub(super) fn v8_Value_Uint32Value() -> *mut c_void; - #[link_name = "?IsUndefined@Value@v8@@QEBA_NXZ"] - pub(super) fn v8_Value_IsUndefined() -> *mut c_void; - #[link_name = "?IsNull@Value@v8@@QEBA_NXZ"] - pub(super) fn v8_Value_IsNull() -> *mut c_void; - #[link_name = "?IsNullOrUndefined@Value@v8@@QEBA_NXZ"] - pub(super) fn v8_Value_IsNullOrUndefined() -> *mut c_void; - #[link_name = "?IsTrue@Value@v8@@QEBA_NXZ"] - pub(super) fn v8_Value_IsTrue() -> *mut c_void; - #[link_name = "?IsFalse@Value@v8@@QEBA_NXZ"] - pub(super) fn v8_Value_IsFalse() -> *mut c_void; - #[link_name = "?IsString@Value@v8@@QEBA_NXZ"] - pub(super) fn v8_Value_IsString() -> *mut c_void; - #[link_name = "?StrictEquals@Value@v8@@QEBA_NV?$Local@VValue@v8@@@2@@Z"] - pub(super) fn v8_Value_StrictEquals() -> *mut c_void; - #[link_name = "?New@Boolean@v8@@SA?AV?$Local@VBoolean@v8@@@2@PEAVIsolate@2@_N@Z"] - pub(super) fn v8_Boolean_New() -> *mut c_void; - #[link_name = "?GetInternalField@Object@v8@@QEAA?AV?$Local@VData@v8@@@2@H@Z"] - pub(super) fn v8_Object_GetInternalField() -> *mut c_void; - #[link_name = "?GetIsolate@Context@v8@@QEAAPEAVIsolate@2@XZ"] - pub(super) fn v8_Context_GetIsolate() -> *mut c_void; - #[link_name = "?NewFromOneByte@String@v8@@SA?AV?$MaybeLocal@VString@v8@@@2@PEAVIsolate@2@PEBEW4NewStringType@2@H@Z"] - pub(super) fn v8_String_NewFromOneByte() -> *mut c_void; - #[link_name = "?IsExternal@String@v8@@QEBA_NXZ"] - pub(super) fn v8_String_IsExternal() -> *mut c_void; - #[link_name = "?IsExternalOneByte@String@v8@@QEBA_NXZ"] - pub(super) fn v8_String_IsExternalOneByte() -> *mut c_void; - #[link_name = "?IsExternalTwoByte@String@v8@@QEBA_NXZ"] - pub(super) fn v8_String_IsExternalTwoByte() -> *mut c_void; - #[link_name = "?IsOneByte@String@v8@@QEBA_NXZ"] - pub(super) fn v8_String_IsOneByte() -> *mut c_void; - #[link_name = "?Utf8Length@String@v8@@QEBAHPEAVIsolate@2@@Z"] - pub(super) fn v8_String_Utf8Length() -> *mut c_void; - #[link_name = "?ContainsOnlyOneByte@String@v8@@QEBA_NXZ"] - pub(super) fn v8_String_ContainsOnlyOneByte() -> *mut c_void; - #[link_name = "?WriteV2@String@v8@@QEBAXPEAVIsolate@2@IIPEAGH@Z"] - pub(super) fn v8_String_WriteV2() -> *mut c_void; - #[link_name = "?WriteOneByteV2@String@v8@@QEBAXPEAVIsolate@2@IIPEAEH@Z"] - pub(super) fn v8_String_WriteOneByteV2() -> *mut c_void; - #[link_name = "?WriteUtf8V2@String@v8@@QEBA_KPEAVIsolate@2@PEAD_KHPEA_K@Z"] - pub(super) fn v8_String_WriteUtf8V2() -> *mut c_void; - #[link_name = "?Utf8LengthV2@String@v8@@QEBA_KPEAVIsolate@2@@Z"] - pub(super) fn v8_String_Utf8LengthV2() -> *mut c_void; - #[link_name = "?GlobalizeReference@api_internal@v8@@YAPEA_KPEAVIsolate@internal@2@_K@Z"] - pub(super) fn v8_api_internal_GlobalizeReference() -> *mut c_void; - #[link_name = "?DisposeGlobal@api_internal@v8@@YAXPEA_K@Z"] - pub(super) fn v8_api_internal_DisposeGlobal() -> *mut c_void; - #[link_name = "?MakeWeak@api_internal@v8@@YAXPEA_KPEAXP6AXAEBV?$WeakCallbackInfo@X@2@@ZW4WeakCallbackType@2@@Z"] - pub(super) fn v8_api_internal_MakeWeak() -> *mut c_void; - #[link_name = "?ClearWeak@api_internal@v8@@YAPEAXPEA_K@Z"] - pub(super) fn v8_api_internal_ClearWeak() -> *mut c_void; - #[link_name = "?MoveGlobalReference@api_internal@v8@@YAXPEAPEA_K0@Z"] - pub(super) fn v8_api_internal_MoveGlobalReference() -> *mut c_void; - #[link_name = "?GetFunctionTemplateData@api_internal@v8@@YA?AV?$Local@VValue@v8@@@2@PEAVIsolate@2@V?$Local@VData@v8@@@2@@Z"] - pub(super) fn v8_api_internal_GetFunctionTemplateData() -> *mut c_void; - #[link_name = "?GetName@Function@v8@@QEBA?AV?$Local@VValue@v8@@@2@XZ"] - pub(super) fn v8_Function_GetName() -> *mut c_void; - #[link_name = "?IsFunction@Value@v8@@QEBA_NXZ"] - pub(super) fn v8_Value_IsFunction() -> *mut c_void; - #[link_name = "?IsMap@Value@v8@@QEBA_NXZ"] - pub(super) fn v8_Value_IsMap() -> *mut c_void; - #[link_name = "?IsArray@Value@v8@@QEBA_NXZ"] - pub(super) fn v8_Value_IsArray() -> *mut c_void; - #[link_name = "?IsInt32@Value@v8@@QEBA_NXZ"] - pub(super) fn v8_Value_IsInt32() -> *mut c_void; - #[link_name = "?IsBigInt@Value@v8@@QEBA_NXZ"] - pub(super) fn v8_Value_IsBigInt() -> *mut c_void; - #[link_name = "?FromJustIsNothing@api_internal@v8@@YAXXZ"] - pub(super) fn v8_api_internal_FromJustIsNothing() -> *mut c_void; - #[link_name = "?New@Integer@v8@@SA?AV?$Local@VInteger@v8@@@2@PEAVIsolate@2@H@Z"] - pub(super) fn v8_Integer_New() -> *mut c_void; - #[link_name = "?NewFromUnsigned@Integer@v8@@SA?AV?$Local@VInteger@v8@@@2@PEAVIsolate@2@I@Z"] - pub(super) fn v8_Integer_NewFromUnsigned() -> *mut c_void; - #[link_name = "?Value@Integer@v8@@QEBA_JXZ"] - pub(super) fn v8_Integer_Value() -> *mut c_void; - #[link_name = "?New@BigInt@v8@@SA?AV?$Local@VBigInt@v8@@@2@PEAVIsolate@2@_J@Z"] - pub(super) fn v8_BigInt_New() -> *mut c_void; - #[link_name = "?NewFromUtf8Literal@String@v8@@CA?AV?$Local@VString@v8@@@2@PEAVIsolate@2@PEBDW4NewStringType@2@H@Z"] - pub(super) fn v8_String_NewFromUtf8Literal() -> *mut c_void; - #[link_name = "?IsUint8Array@Value@v8@@QEBA_NXZ"] - pub(super) fn v8_Value_IsUint8Array() -> *mut c_void; - #[link_name = "?ToString@Value@v8@@QEBA?AV?$MaybeLocal@VString@v8@@@2@V?$Local@VContext@v8@@@2@@Z"] - pub(super) fn v8_Value_ToString() -> *mut c_void; - #[link_name = "?ToInteger@Value@v8@@QEBA?AV?$MaybeLocal@VInteger@v8@@@2@V?$Local@VContext@v8@@@2@@Z"] - pub(super) fn v8_Value_ToInteger() -> *mut c_void; - #[link_name = "?Global@Context@v8@@QEAA?AV?$Local@VObject@v8@@@2@XZ"] - pub(super) fn v8_Context_Global() -> *mut c_void; - #[link_name = "?InternalFieldCount@Object@v8@@QEBAHXZ"] - pub(super) fn v8_Object_InternalFieldCount() -> *mut c_void; - #[link_name = "?GetIdentityHash@Object@v8@@QEAAHXZ"] - pub(super) fn v8_Object_GetIdentityHash() -> *mut c_void; - #[link_name = "?DefineOwnProperty@Object@v8@@QEAA?AV?$Maybe@_N@2@V?$Local@VContext@v8@@@2@V?$Local@VName@v8@@@2@V?$Local@VValue@v8@@@2@W4PropertyAttribute@2@@Z"] - pub(super) fn v8_Object_DefineOwnProperty() -> *mut c_void; - #[link_name = "?ToExternalPointerTag@v8@@YA?AW4ExternalPointerTag@internal@1@G@Z"] - pub(super) fn v8_ToExternalPointerTag() -> *mut c_void; - #[link_name = "?GetCurrentIsolate@Internals@internal@v8@@SAPEAVIsolate@3@XZ"] - pub(super) fn v8_internal_Internals_GetCurrentIsolate() -> *mut c_void; - #[link_name = "??0HeapObjectStatistics@v8@@QEAA@XZ"] - pub(super) fn v8_HeapObjectStatistics_ctor() -> *mut c_void; - #[link_name = "?New@ArrayBuffer@v8@@SA?AV?$Local@VArrayBuffer@v8@@@2@PEAVIsolate@2@_KW4BackingStoreInitializationMode@2@@Z"] - pub(super) fn v8_ArrayBuffer_New() -> *mut c_void; - #[link_name = "?GetBackingStore@ArrayBuffer@v8@@QEAA?AV?$shared_ptr@VBackingStore@v8@@@std@@XZ"] - pub(super) fn v8_ArrayBuffer_GetBackingStore() -> *mut c_void; - #[link_name = "?Data@BackingStore@v8@@QEBAPEAXXZ"] - pub(super) fn v8_BackingStore_Data() -> *mut c_void; - #[link_name = "?Buffer@ArrayBufferView@v8@@QEAA?AV?$Local@VArrayBuffer@v8@@@2@XZ"] - pub(super) fn v8_ArrayBufferView_Buffer() -> *mut c_void; - #[link_name = "?ByteLength@ArrayBufferView@v8@@QEAA_KXZ"] - pub(super) fn v8_ArrayBufferView_ByteLength() -> *mut c_void; - #[link_name = "?ByteOffset@ArrayBufferView@v8@@QEAA_KXZ"] - pub(super) fn v8_ArrayBufferView_ByteOffset() -> *mut c_void; - #[link_name = "?New@Uint8Array@v8@@SA?AV?$Local@VUint8Array@v8@@@2@V?$Local@VArrayBuffer@v8@@@2@_K1@Z"] - pub(super) fn v8_Uint8Array_New() -> *mut c_void; - #[link_name = "?New@Uint32Array@v8@@SA?AV?$Local@VUint32Array@v8@@@2@V?$Local@VArrayBuffer@v8@@@2@_K1@Z"] - pub(super) fn v8_Uint32Array_New() -> *mut c_void; - #[link_name = "?New@CpuProfiler@v8@@SAPEAV12@PEAVIsolate@2@W4CpuProfilingNamingMode@2@W4CpuProfilingLoggingMode@2@@Z"] - pub(super) fn v8_CpuProfiler_New() -> *mut c_void; - #[link_name = "?Dispose@CpuProfiler@v8@@QEAAXXZ"] - pub(super) fn v8_CpuProfiler_Dispose() -> *mut c_void; - #[link_name = "?SetSamplingInterval@CpuProfiler@v8@@QEAAXH@Z"] - pub(super) fn v8_CpuProfiler_SetSamplingInterval() -> *mut c_void; - #[link_name = "?Start@CpuProfiler@v8@@QEAA?AUCpuProfilingResult@2@V?$Local@VString@v8@@@2@W4CpuProfilingMode@2@_NI@Z"] - pub(super) fn v8_CpuProfiler_Start() -> *mut c_void; - #[link_name = "?Stop@CpuProfiler@v8@@QEAAPEAVCpuProfile@2@I@Z"] - pub(super) fn v8_CpuProfiler_Stop() -> *mut c_void; - #[link_name = "?StartProfiling@CpuProfiler@v8@@QEAA?AW4CpuProfilingStatus@2@V?$Local@VString@v8@@@2@W4CpuProfilingMode@2@_NI@Z"] - pub(super) fn v8_CpuProfiler_StartProfiling_mode() -> *mut c_void; - #[link_name = "?StartProfiling@CpuProfiler@v8@@QEAA?AW4CpuProfilingStatus@2@V?$Local@VString@v8@@@2@_N@Z"] - pub(super) fn v8_CpuProfiler_StartProfiling() -> *mut c_void; - #[link_name = "?StopProfiling@CpuProfiler@v8@@QEAAPEAVCpuProfile@2@V?$Local@VString@v8@@@2@@Z"] - pub(super) fn v8_CpuProfiler_StopProfiling() -> *mut c_void; - #[link_name = "?CollectSample@CpuProfiler@v8@@SAXPEAVIsolate@2@V?$optional@_K@std@@@Z"] - pub(super) fn v8_CpuProfiler_CollectSample() -> *mut c_void; - #[link_name = "?Delete@CpuProfile@v8@@QEAAXXZ"] - pub(super) fn v8_CpuProfile_Delete() -> *mut c_void; - #[link_name = "?GetTitle@CpuProfile@v8@@QEBA?AV?$Local@VString@v8@@@2@XZ"] - pub(super) fn v8_CpuProfile_GetTitle() -> *mut c_void; - #[link_name = "?GetEndTime@CpuProfile@v8@@QEBA_JXZ"] - pub(super) fn v8_CpuProfile_GetEndTime() -> *mut c_void; - #[link_name = "?GetStartTime@CpuProfile@v8@@QEBA_JXZ"] - pub(super) fn v8_CpuProfile_GetStartTime() -> *mut c_void; - #[link_name = "?GetTopDownRoot@CpuProfile@v8@@QEBAPEBVCpuProfileNode@2@XZ"] - pub(super) fn v8_CpuProfile_GetTopDownRoot() -> *mut c_void; - #[link_name = "?GetSamplesCount@CpuProfile@v8@@QEBAHXZ"] - pub(super) fn v8_CpuProfile_GetSamplesCount() -> *mut c_void; - #[link_name = "?GetSampleTimestamp@CpuProfile@v8@@QEBA_JH@Z"] - pub(super) fn v8_CpuProfile_GetSampleTimestamp() -> *mut c_void; - #[link_name = "?GetSample@CpuProfile@v8@@QEBAPEBVCpuProfileNode@2@H@Z"] - pub(super) fn v8_CpuProfile_GetSample() -> *mut c_void; - #[link_name = "?GetHitCount@CpuProfileNode@v8@@QEBAIXZ"] - pub(super) fn v8_CpuProfileNode_GetHitCount() -> *mut c_void; - #[link_name = "?GetScriptId@CpuProfileNode@v8@@QEBAHXZ"] - pub(super) fn v8_CpuProfileNode_GetScriptId() -> *mut c_void; - #[link_name = "?GetLineTicks@CpuProfileNode@v8@@QEBA_NPEAULineTick@12@I@Z"] - pub(super) fn v8_CpuProfileNode_GetLineTicks() -> *mut c_void; - #[link_name = "?GetLineNumber@CpuProfileNode@v8@@QEBAHXZ"] - pub(super) fn v8_CpuProfileNode_GetLineNumber() -> *mut c_void; - #[link_name = "?GetColumnNumber@CpuProfileNode@v8@@QEBAHXZ"] - pub(super) fn v8_CpuProfileNode_GetColumnNumber() -> *mut c_void; - #[link_name = "?GetFunctionName@CpuProfileNode@v8@@QEBA?AV?$Local@VString@v8@@@2@XZ"] - pub(super) fn v8_CpuProfileNode_GetFunctionName() -> *mut c_void; - #[link_name = "?GetHitLineCount@CpuProfileNode@v8@@QEBAIXZ"] - pub(super) fn v8_CpuProfileNode_GetHitLineCount() -> *mut c_void; - #[link_name = "?GetChildrenCount@CpuProfileNode@v8@@QEBAHXZ"] - pub(super) fn v8_CpuProfileNode_GetChildrenCount() -> *mut c_void; - #[link_name = "?GetFunctionNameStr@CpuProfileNode@v8@@QEBAPEBDXZ"] - pub(super) fn v8_CpuProfileNode_GetFunctionNameStr() -> *mut c_void; - #[link_name = "?GetScriptResourceName@CpuProfileNode@v8@@QEBA?AV?$Local@VString@v8@@@2@XZ"] - pub(super) fn v8_CpuProfileNode_GetScriptResourceName() -> *mut c_void; - #[link_name = "?GetChild@CpuProfileNode@v8@@QEBAPEBV12@H@Z"] - pub(super) fn v8_CpuProfileNode_GetChild() -> *mut c_void; - #[link_name = "?Set@Map@v8@@QEAA?AV?$MaybeLocal@VMap@v8@@@2@V?$Local@VContext@v8@@@2@V?$Local@VValue@v8@@@2@1@Z"] - pub(super) fn v8_Map_Set() -> *mut c_void; - #[link_name = "?Delete@Map@v8@@QEAA?AV?$Maybe@_N@2@V?$Local@VContext@v8@@@2@V?$Local@VValue@v8@@@2@@Z"] - pub(super) fn v8_Map_Delete() -> *mut c_void; - } -} - -/// V8 API functions whose Itanium mangled name is platform-dependent: the C++ -/// stdlib inline namespace (std:: vs std::__1:: vs std::__ndk1::) and the -/// int64_t/uint64_t underlying type (long `l`/`m` vs long long `x`/`y`). -#[cfg(windows)] -mod posix_platform_specific_v8_apis {} -#[cfg(all(not(windows), target_os = "android"))] -mod posix_platform_specific_v8_apis { - use core::ffi::c_void; - unsafe extern "C" { - pub(super) fn _ZN2v85Array3NewENS_5LocalINS_7ContextEEEmNSt6__ndk18functionIFNS_10MaybeLocalINS_5ValueEEEvEEE() - -> *mut c_void; - pub(super) fn _ZN2v811CpuProfiler13CollectSampleEPNS_7IsolateENSt6__ndk18optionalImEE() - -> *mut c_void; - pub(super) fn _ZN2v86BigInt3NewEPNS_7IsolateEl() -> *mut c_void; - pub(super) fn _ZN2v812HeapProfiler25StartSamplingHeapProfilerEmiNS0_13SamplingFlagsE() - -> *mut c_void; - } -} -#[cfg(all(not(windows), target_os = "macos"))] -mod posix_platform_specific_v8_apis { - use core::ffi::c_void; - unsafe extern "C" { - pub(super) fn _ZN2v85Array3NewENS_5LocalINS_7ContextEEEmNSt3__18functionIFNS_10MaybeLocalINS_5ValueEEEvEEE() - -> *mut c_void; - pub(super) fn _ZN2v811CpuProfiler13CollectSampleEPNS_7IsolateENSt3__18optionalIyEE() - -> *mut c_void; - pub(super) fn _ZN2v86BigInt3NewEPNS_7IsolateEx() -> *mut c_void; - pub(super) fn _ZN2v812HeapProfiler25StartSamplingHeapProfilerEyiNS0_13SamplingFlagsE() - -> *mut c_void; - } -} -#[cfg(all(not(windows), target_os = "freebsd"))] -mod posix_platform_specific_v8_apis { - use core::ffi::c_void; - // FreeBSD's base libc++ uses the same `std::__1::` inline namespace as Apple's, - // but uint64_t/int64_t are `unsigned long`/`long` (m/l) like Linux, not `long long` (y/x). - unsafe extern "C" { - pub(super) fn _ZN2v85Array3NewENS_5LocalINS_7ContextEEEmNSt3__18functionIFNS_10MaybeLocalINS_5ValueEEEvEEE() - -> *mut c_void; - pub(super) fn _ZN2v811CpuProfiler13CollectSampleEPNS_7IsolateENSt3__18optionalImEE() - -> *mut c_void; - pub(super) fn _ZN2v86BigInt3NewEPNS_7IsolateEl() -> *mut c_void; - pub(super) fn _ZN2v812HeapProfiler25StartSamplingHeapProfilerEmiNS0_13SamplingFlagsE() - -> *mut c_void; - } -} -#[cfg(all( - not(windows), - not(target_os = "android"), - not(target_os = "macos"), - not(target_os = "freebsd") -))] -mod posix_platform_specific_v8_apis { - use core::ffi::c_void; - unsafe extern "C" { - pub(super) fn _ZN2v85Array3NewENS_5LocalINS_7ContextEEEmSt8functionIFNS_10MaybeLocalINS_5ValueEEEvEE() - -> *mut c_void; - pub(super) fn _ZN2v811CpuProfiler13CollectSampleEPNS_7IsolateESt8optionalImE() -> *mut c_void; - pub(super) fn _ZN2v86BigInt3NewEPNS_7IsolateEl() -> *mut c_void; - pub(super) fn _ZN2v812HeapProfiler25StartSamplingHeapProfilerEmiNS0_13SamplingFlagsE() - -> *mut c_void; - } -} - -// ────────────────────────────────────────────────────────────────────────── -// uv_* symbol references (posix DCE suppression) -// ────────────────────────────────────────────────────────────────────────── - -#[cfg(unix)] -mod uv_functions_to_export { - unsafe extern "C" { - pub(super) fn uv_accept(); - pub(super) fn uv_async_init(); - pub(super) fn uv_async_send(); - pub(super) fn uv_available_parallelism(); - pub(super) fn uv_backend_fd(); - pub(super) fn uv_backend_timeout(); - pub(super) fn uv_barrier_destroy(); - pub(super) fn uv_barrier_init(); - pub(super) fn uv_barrier_wait(); - pub(super) fn uv_buf_init(); - pub(super) fn uv_cancel(); - pub(super) fn uv_chdir(); - pub(super) fn uv_check_init(); - pub(super) fn uv_check_start(); - pub(super) fn uv_check_stop(); - pub(super) fn uv_clock_gettime(); - pub(super) fn uv_close(); - pub(super) fn uv_cond_broadcast(); - pub(super) fn uv_cond_destroy(); - pub(super) fn uv_cond_init(); - pub(super) fn uv_cond_signal(); - pub(super) fn uv_cond_timedwait(); - pub(super) fn uv_cond_wait(); - pub(super) fn uv_cpu_info(); - pub(super) fn uv_cpumask_size(); - pub(super) fn uv_cwd(); - pub(super) fn uv_default_loop(); - pub(super) fn uv_disable_stdio_inheritance(); - pub(super) fn uv_dlclose(); - pub(super) fn uv_dlerror(); - pub(super) fn uv_dlopen(); - pub(super) fn uv_dlsym(); - pub(super) fn uv_err_name(); - pub(super) fn uv_err_name_r(); - pub(super) fn uv_exepath(); - pub(super) fn uv_fileno(); - pub(super) fn uv_free_cpu_info(); - pub(super) fn uv_free_interface_addresses(); - pub(super) fn uv_freeaddrinfo(); - pub(super) fn uv_fs_access(); - pub(super) fn uv_fs_chmod(); - pub(super) fn uv_fs_chown(); - pub(super) fn uv_fs_close(); - pub(super) fn uv_fs_closedir(); - pub(super) fn uv_fs_copyfile(); - pub(super) fn uv_fs_event_getpath(); - pub(super) fn uv_fs_event_init(); - pub(super) fn uv_fs_event_start(); - pub(super) fn uv_fs_event_stop(); - pub(super) fn uv_fs_fchmod(); - pub(super) fn uv_fs_fchown(); - pub(super) fn uv_fs_fdatasync(); - pub(super) fn uv_fs_fstat(); - pub(super) fn uv_fs_fsync(); - pub(super) fn uv_fs_ftruncate(); - pub(super) fn uv_fs_futime(); - pub(super) fn uv_fs_get_path(); - pub(super) fn uv_fs_get_ptr(); - pub(super) fn uv_fs_get_result(); - pub(super) fn uv_fs_get_statbuf(); - pub(super) fn uv_fs_get_system_error(); - pub(super) fn uv_fs_get_type(); - pub(super) fn uv_fs_lchown(); - pub(super) fn uv_fs_link(); - pub(super) fn uv_fs_lstat(); - pub(super) fn uv_fs_lutime(); - pub(super) fn uv_fs_mkdir(); - pub(super) fn uv_fs_mkdtemp(); - pub(super) fn uv_fs_mkstemp(); - pub(super) fn uv_fs_open(); - pub(super) fn uv_fs_opendir(); - pub(super) fn uv_fs_poll_getpath(); - pub(super) fn uv_fs_poll_init(); - pub(super) fn uv_fs_poll_start(); - pub(super) fn uv_fs_poll_stop(); - pub(super) fn uv_fs_read(); - pub(super) fn uv_fs_readdir(); - pub(super) fn uv_fs_readlink(); - pub(super) fn uv_fs_realpath(); - pub(super) fn uv_fs_rename(); - pub(super) fn uv_fs_req_cleanup(); - pub(super) fn uv_fs_rmdir(); - pub(super) fn uv_fs_scandir(); - pub(super) fn uv_fs_scandir_next(); - pub(super) fn uv_fs_sendfile(); - pub(super) fn uv_fs_stat(); - pub(super) fn uv_fs_statfs(); - pub(super) fn uv_fs_symlink(); - pub(super) fn uv_fs_unlink(); - pub(super) fn uv_fs_utime(); - pub(super) fn uv_fs_write(); - pub(super) fn uv_get_available_memory(); - pub(super) fn uv_get_constrained_memory(); - pub(super) fn uv_get_free_memory(); - pub(super) fn uv_get_osfhandle(); - pub(super) fn uv_get_process_title(); - pub(super) fn uv_get_total_memory(); - pub(super) fn uv_getaddrinfo(); - pub(super) fn uv_getnameinfo(); - pub(super) fn uv_getrusage(); - pub(super) fn uv_getrusage_thread(); - pub(super) fn uv_gettimeofday(); - pub(super) fn uv_guess_handle(); - pub(super) fn uv_handle_get_data(); - pub(super) fn uv_handle_get_loop(); - pub(super) fn uv_handle_get_type(); - pub(super) fn uv_handle_set_data(); - pub(super) fn uv_handle_size(); - pub(super) fn uv_handle_type_name(); - pub(super) fn uv_has_ref(); - pub(super) fn uv_hrtime(); - pub(super) fn uv_idle_init(); - pub(super) fn uv_idle_start(); - pub(super) fn uv_idle_stop(); - pub(super) fn uv_if_indextoiid(); - pub(super) fn uv_if_indextoname(); - pub(super) fn uv_inet_ntop(); - pub(super) fn uv_inet_pton(); - pub(super) fn uv_interface_addresses(); - pub(super) fn uv_ip_name(); - pub(super) fn uv_ip4_addr(); - pub(super) fn uv_ip4_name(); - pub(super) fn uv_ip6_addr(); - pub(super) fn uv_ip6_name(); - pub(super) fn uv_is_active(); - pub(super) fn uv_is_closing(); - pub(super) fn uv_is_readable(); - pub(super) fn uv_is_writable(); - pub(super) fn uv_key_create(); - pub(super) fn uv_key_delete(); - pub(super) fn uv_key_get(); - pub(super) fn uv_key_set(); - pub(super) fn uv_kill(); - pub(super) fn uv_library_shutdown(); - pub(super) fn uv_listen(); - pub(super) fn uv_loadavg(); - pub(super) fn uv_loop_alive(); - pub(super) fn uv_loop_close(); - pub(super) fn uv_loop_configure(); - pub(super) fn uv_loop_delete(); - pub(super) fn uv_loop_fork(); - pub(super) fn uv_loop_get_data(); - pub(super) fn uv_loop_init(); - pub(super) fn uv_loop_new(); - pub(super) fn uv_loop_set_data(); - pub(super) fn uv_loop_size(); - pub(super) fn uv_metrics_idle_time(); - pub(super) fn uv_metrics_info(); - pub(super) fn uv_mutex_destroy(); - pub(super) fn uv_mutex_init(); - pub(super) fn uv_mutex_init_recursive(); - pub(super) fn uv_mutex_lock(); - pub(super) fn uv_mutex_trylock(); - pub(super) fn uv_mutex_unlock(); - pub(super) fn uv_now(); - pub(super) fn uv_once(); - pub(super) fn uv_open_osfhandle(); - pub(super) fn uv_os_environ(); - pub(super) fn uv_os_free_environ(); - pub(super) fn uv_os_free_group(); - pub(super) fn uv_os_free_passwd(); - pub(super) fn uv_os_get_group(); - pub(super) fn uv_os_get_passwd(); - pub(super) fn uv_os_get_passwd2(); - pub(super) fn uv_os_getenv(); - pub(super) fn uv_os_gethostname(); - pub(super) fn uv_os_getpid(); - pub(super) fn uv_os_getppid(); - pub(super) fn uv_os_getpriority(); - pub(super) fn uv_os_homedir(); - pub(super) fn uv_os_setenv(); - pub(super) fn uv_os_setpriority(); - pub(super) fn uv_os_tmpdir(); - pub(super) fn uv_os_uname(); - pub(super) fn uv_os_unsetenv(); - pub(super) fn uv_pipe(); - pub(super) fn uv_pipe_bind(); - pub(super) fn uv_pipe_bind2(); - pub(super) fn uv_pipe_chmod(); - pub(super) fn uv_pipe_connect(); - pub(super) fn uv_pipe_connect2(); - pub(super) fn uv_pipe_getpeername(); - pub(super) fn uv_pipe_getsockname(); - pub(super) fn uv_pipe_init(); - pub(super) fn uv_pipe_open(); - pub(super) fn uv_pipe_pending_count(); - pub(super) fn uv_pipe_pending_instances(); - pub(super) fn uv_pipe_pending_type(); - pub(super) fn uv_poll_init(); - pub(super) fn uv_poll_init_socket(); - pub(super) fn uv_poll_start(); - pub(super) fn uv_poll_stop(); - pub(super) fn uv_prepare_init(); - pub(super) fn uv_prepare_start(); - pub(super) fn uv_prepare_stop(); - pub(super) fn uv_print_active_handles(); - pub(super) fn uv_print_all_handles(); - pub(super) fn uv_process_get_pid(); - pub(super) fn uv_process_kill(); - pub(super) fn uv_queue_work(); - pub(super) fn uv_random(); - pub(super) fn uv_read_start(); - pub(super) fn uv_read_stop(); - pub(super) fn uv_recv_buffer_size(); - pub(super) fn uv_ref(); - pub(super) fn uv_replace_allocator(); - pub(super) fn uv_req_get_data(); - pub(super) fn uv_req_get_type(); - pub(super) fn uv_req_set_data(); - pub(super) fn uv_req_size(); - pub(super) fn uv_req_type_name(); - pub(super) fn uv_resident_set_memory(); - pub(super) fn uv_run(); - pub(super) fn uv_rwlock_destroy(); - pub(super) fn uv_rwlock_init(); - pub(super) fn uv_rwlock_rdlock(); - pub(super) fn uv_rwlock_rdunlock(); - pub(super) fn uv_rwlock_tryrdlock(); - pub(super) fn uv_rwlock_trywrlock(); - pub(super) fn uv_rwlock_wrlock(); - pub(super) fn uv_rwlock_wrunlock(); - pub(super) fn uv_sem_destroy(); - pub(super) fn uv_sem_init(); - pub(super) fn uv_sem_post(); - pub(super) fn uv_sem_trywait(); - pub(super) fn uv_sem_wait(); - pub(super) fn uv_send_buffer_size(); - pub(super) fn uv_set_process_title(); - pub(super) fn uv_setup_args(); - pub(super) fn uv_shutdown(); - pub(super) fn uv_signal_init(); - pub(super) fn uv_signal_start(); - pub(super) fn uv_signal_start_oneshot(); - pub(super) fn uv_signal_stop(); - pub(super) fn uv_sleep(); - pub(super) fn uv_socketpair(); - pub(super) fn uv_spawn(); - pub(super) fn uv_stop(); - pub(super) fn uv_stream_get_write_queue_size(); - pub(super) fn uv_stream_set_blocking(); - pub(super) fn uv_strerror(); - pub(super) fn uv_strerror_r(); - pub(super) fn uv_tcp_bind(); - pub(super) fn uv_tcp_close_reset(); - pub(super) fn uv_tcp_connect(); - pub(super) fn uv_tcp_getpeername(); - pub(super) fn uv_tcp_getsockname(); - pub(super) fn uv_tcp_init(); - pub(super) fn uv_tcp_init_ex(); - pub(super) fn uv_tcp_keepalive(); - pub(super) fn uv_tcp_nodelay(); - pub(super) fn uv_tcp_open(); - pub(super) fn uv_tcp_simultaneous_accepts(); - pub(super) fn uv_thread_create(); - pub(super) fn uv_thread_create_ex(); - pub(super) fn uv_thread_detach(); - pub(super) fn uv_thread_equal(); - pub(super) fn uv_thread_getaffinity(); - pub(super) fn uv_thread_getcpu(); - pub(super) fn uv_thread_getname(); - pub(super) fn uv_thread_getpriority(); - pub(super) fn uv_thread_join(); - pub(super) fn uv_thread_self(); - pub(super) fn uv_thread_setaffinity(); - pub(super) fn uv_thread_setname(); - pub(super) fn uv_thread_setpriority(); - pub(super) fn uv_timer_again(); - pub(super) fn uv_timer_get_due_in(); - pub(super) fn uv_timer_get_repeat(); - pub(super) fn uv_timer_init(); - pub(super) fn uv_timer_set_repeat(); - pub(super) fn uv_timer_start(); - pub(super) fn uv_timer_stop(); - pub(super) fn uv_translate_sys_error(); - pub(super) fn uv_try_write(); - pub(super) fn uv_try_write2(); - pub(super) fn uv_tty_get_vterm_state(); - pub(super) fn uv_tty_get_winsize(); - pub(super) fn uv_tty_init(); - pub(super) fn uv_tty_reset_mode(); - pub(super) fn uv_tty_set_mode(); - pub(super) fn uv_tty_set_vterm_state(); - pub(super) fn uv_udp_bind(); - pub(super) fn uv_udp_connect(); - pub(super) fn uv_udp_get_send_queue_count(); - pub(super) fn uv_udp_get_send_queue_size(); - pub(super) fn uv_udp_getpeername(); - pub(super) fn uv_udp_getsockname(); - pub(super) fn uv_udp_init(); - pub(super) fn uv_udp_init_ex(); - pub(super) fn uv_udp_open(); - pub(super) fn uv_udp_recv_start(); - pub(super) fn uv_udp_recv_stop(); - pub(super) fn uv_udp_send(); - pub(super) fn uv_udp_set_broadcast(); - pub(super) fn uv_udp_set_membership(); - pub(super) fn uv_udp_set_multicast_interface(); - pub(super) fn uv_udp_set_multicast_loop(); - pub(super) fn uv_udp_set_multicast_ttl(); - pub(super) fn uv_udp_set_source_membership(); - pub(super) fn uv_udp_set_ttl(); - pub(super) fn uv_udp_try_send(); - pub(super) fn uv_udp_try_send2(); - pub(super) fn uv_udp_using_recvmmsg(); - pub(super) fn uv_unref(); - pub(super) fn uv_update_time(); - pub(super) fn uv_uptime(); - pub(super) fn uv_utf16_length_as_wtf8(); - pub(super) fn uv_utf16_to_wtf8(); - pub(super) fn uv_version(); - pub(super) fn uv_version_string(); - pub(super) fn uv_walk(); - pub(super) fn uv_write(); - pub(super) fn uv_write2(); - pub(super) fn uv_wtf8_length_as_utf16(); - pub(super) fn uv_wtf8_to_utf16(); - } -} -#[cfg(not(unix))] -mod uv_functions_to_export {} - // ────────────────────────────────────────────────────────────────────────── // fix_dead_code_elimination // ────────────────────────────────────────────────────────────────────────── -/// To update this list, use find + multi-cursor in your editor. -/// - pub extern fn napi_ -/// - pub export fn napi_ use bun_core::keep_symbols; +/// Keeps every symbol a native addon links against: the `napi_*` entry points +/// implemented here (their `extern "C"` thunks are generated) and the C/C++ +/// ones (`link_symbols`). pub(crate) fn fix_dead_code_elimination() { jsc::mark_binding(); - // napi_functions_to_export + use crate::generated_host_exports as exports; keep_symbols!( - napi_acquire_threadsafe_function, - napi_add_async_cleanup_hook, - napi_add_env_cleanup_hook, - napi_add_finalizer, - napi_adjust_external_memory, - napi_async_destroy, - napi_async_init, - napi_call_function, - napi_call_threadsafe_function, - napi_cancel_async_work, - napi_check_object_type_tag, - napi_close_callback_scope, - napi_close_escapable_handle_scope, - napi_close_handle_scope, - napi_coerce_to_bool, - napi_coerce_to_number, - napi_coerce_to_object, - napi_create_array, - napi_create_array_with_length, - napi_create_arraybuffer, - napi_create_async_work, - napi_create_bigint_int64, - napi_create_bigint_uint64, - napi_create_bigint_words, - napi_create_buffer, - napi_create_buffer_copy, - napi_create_dataview, - napi_create_date, - napi_create_double, - napi_create_error, - napi_create_external, - napi_create_external_arraybuffer, - napi_create_external_buffer, - napi_create_int32, - napi_create_int64, - napi_create_object, - napi_create_promise, - napi_create_range_error, - napi_create_reference, - napi_create_string_latin1, - napi_create_string_utf16, - napi_create_string_utf8, - napi_create_symbol, - napi_create_threadsafe_function, - napi_create_type_error, - napi_create_typedarray, - napi_create_uint32, - napi_define_class, - napi_define_properties, - napi_delete_async_work, - napi_delete_element, - napi_delete_reference, - napi_detach_arraybuffer, - napi_escape_handle, - napi_fatal_error, - napi_fatal_exception, - napi_get_all_property_names, - napi_get_and_clear_last_exception, - napi_get_array_length, - napi_get_arraybuffer_info, - napi_get_boolean, - napi_get_buffer_info, - napi_get_cb_info, - napi_get_dataview_info, - napi_get_date_value, - napi_get_element, - napi_get_global, - napi_get_instance_data, - napi_get_last_error_info, - napi_get_new_target, - napi_get_node_version, - napi_get_null, - napi_get_prototype, - napi_get_reference_value, - napi_get_threadsafe_function_context, - napi_get_typedarray_info, - napi_get_undefined, - napi_get_uv_event_loop, - napi_get_value_bigint_int64, - napi_get_value_bigint_uint64, - napi_get_value_bigint_words, - napi_get_value_bool, - napi_get_value_double, - napi_get_value_external, - napi_get_value_int32, - napi_get_value_int64, - napi_get_value_string_latin1, - napi_get_value_string_utf16, - napi_get_value_string_utf8, - napi_get_value_uint32, - napi_get_version, - napi_has_element, - napi_instanceof, - napi_is_array, - napi_is_arraybuffer, - napi_is_buffer, - napi_is_dataview, - napi_is_date, - napi_is_detached_arraybuffer, - napi_is_error, - napi_is_exception_pending, - napi_is_promise, - napi_is_typedarray, - napi_make_callback, - napi_new_instance, - napi_open_callback_scope, - napi_open_escapable_handle_scope, - napi_open_handle_scope, - napi_queue_async_work, - napi_ref_threadsafe_function, - napi_reference_ref, - napi_reference_unref, - napi_reject_deferred, - napi_release_threadsafe_function, - napi_remove_async_cleanup_hook, - napi_remove_env_cleanup_hook, - napi_remove_wrap, - napi_resolve_deferred, - napi_run_script, - napi_set_element, - napi_set_instance_data, - napi_strict_equals, - napi_throw, - napi_throw_error, - napi_throw_range_error, - napi_throw_type_error, - napi_type_tag_object, - napi_typeof, - napi_unref_threadsafe_function, - napi_unwrap, - napi_wrap, - // -- node-api - node_api_create_syntax_error, - node_api_symbol_for, - node_api_throw_syntax_error, - node_api_create_external_string_latin1, - node_api_create_external_string_utf16, - node_api_set_prototype, - node_api_create_object_with_properties, - node_api_create_sharedarraybuffer, - node_api_create_external_sharedarraybuffer, - node_api_is_sharedarraybuffer, - ); - - // uv_functions_to_export - // This list is hand-maintained — keep it in sync with the - // `uv_functions_to_export` module above. - #[cfg(unix)] - { - use uv_functions_to_export::*; - keep_symbols!( - uv_accept, - uv_async_init, - uv_async_send, - uv_available_parallelism, - uv_backend_fd, - uv_backend_timeout, - uv_barrier_destroy, - uv_barrier_init, - uv_barrier_wait, - uv_buf_init, - uv_cancel, - uv_chdir, - uv_check_init, - uv_check_start, - uv_check_stop, - uv_clock_gettime, - uv_close, - uv_cond_broadcast, - uv_cond_destroy, - uv_cond_init, - uv_cond_signal, - uv_cond_timedwait, - uv_cond_wait, - uv_cpu_info, - uv_cpumask_size, - uv_cwd, - uv_default_loop, - uv_disable_stdio_inheritance, - uv_dlclose, - uv_dlerror, - uv_dlopen, - uv_dlsym, - uv_err_name, - uv_err_name_r, - uv_exepath, - uv_fileno, - uv_free_cpu_info, - uv_free_interface_addresses, - uv_freeaddrinfo, - uv_fs_access, - uv_fs_chmod, - uv_fs_chown, - uv_fs_close, - uv_fs_closedir, - uv_fs_copyfile, - uv_fs_event_getpath, - uv_fs_event_init, - uv_fs_event_start, - uv_fs_event_stop, - uv_fs_fchmod, - uv_fs_fchown, - uv_fs_fdatasync, - uv_fs_fstat, - uv_fs_fsync, - uv_fs_ftruncate, - uv_fs_futime, - uv_fs_get_path, - uv_fs_get_ptr, - uv_fs_get_result, - uv_fs_get_statbuf, - uv_fs_get_system_error, - uv_fs_get_type, - uv_fs_lchown, - uv_fs_link, - uv_fs_lstat, - uv_fs_lutime, - uv_fs_mkdir, - uv_fs_mkdtemp, - uv_fs_mkstemp, - uv_fs_open, - uv_fs_opendir, - uv_fs_poll_getpath, - uv_fs_poll_init, - uv_fs_poll_start, - uv_fs_poll_stop, - uv_fs_read, - uv_fs_readdir, - uv_fs_readlink, - uv_fs_realpath, - uv_fs_rename, - uv_fs_req_cleanup, - uv_fs_rmdir, - uv_fs_scandir, - uv_fs_scandir_next, - uv_fs_sendfile, - uv_fs_stat, - uv_fs_statfs, - uv_fs_symlink, - uv_fs_unlink, - uv_fs_utime, - uv_fs_write, - uv_get_available_memory, - uv_get_constrained_memory, - uv_get_free_memory, - uv_get_osfhandle, - uv_get_process_title, - uv_get_total_memory, - uv_getaddrinfo, - uv_getnameinfo, - uv_getrusage, - uv_getrusage_thread, - uv_gettimeofday, - uv_guess_handle, - uv_handle_get_data, - uv_handle_get_loop, - uv_handle_get_type, - uv_handle_set_data, - uv_handle_size, - uv_handle_type_name, - uv_has_ref, - uv_hrtime, - uv_idle_init, - uv_idle_start, - uv_idle_stop, - uv_if_indextoiid, - uv_if_indextoname, - uv_inet_ntop, - uv_inet_pton, - uv_interface_addresses, - uv_ip_name, - uv_ip4_addr, - uv_ip4_name, - uv_ip6_addr, - uv_ip6_name, - uv_is_active, - uv_is_closing, - uv_is_readable, - uv_is_writable, - uv_key_create, - uv_key_delete, - uv_key_get, - uv_key_set, - uv_kill, - uv_library_shutdown, - uv_listen, - uv_loadavg, - uv_loop_alive, - uv_loop_close, - uv_loop_configure, - uv_loop_delete, - uv_loop_fork, - uv_loop_get_data, - uv_loop_init, - uv_loop_new, - uv_loop_set_data, - uv_loop_size, - uv_metrics_idle_time, - uv_metrics_info, - uv_mutex_destroy, - uv_mutex_init, - uv_mutex_init_recursive, - uv_mutex_lock, - uv_mutex_trylock, - uv_mutex_unlock, - uv_now, - uv_once, - uv_open_osfhandle, - uv_os_environ, - uv_os_free_environ, - uv_os_free_group, - uv_os_free_passwd, - uv_os_get_group, - uv_os_get_passwd, - uv_os_get_passwd2, - uv_os_getenv, - uv_os_gethostname, - uv_os_getpid, - uv_os_getppid, - uv_os_getpriority, - uv_os_homedir, - uv_os_setenv, - uv_os_setpriority, - uv_os_tmpdir, - uv_os_uname, - uv_os_unsetenv, - uv_pipe, - uv_pipe_bind, - uv_pipe_bind2, - uv_pipe_chmod, - uv_pipe_connect, - uv_pipe_connect2, - uv_pipe_getpeername, - uv_pipe_getsockname, - uv_pipe_init, - uv_pipe_open, - uv_pipe_pending_count, - uv_pipe_pending_instances, - uv_pipe_pending_type, - uv_poll_init, - uv_poll_init_socket, - uv_poll_start, - uv_poll_stop, - uv_prepare_init, - uv_prepare_start, - uv_prepare_stop, - uv_print_active_handles, - uv_print_all_handles, - uv_process_get_pid, - uv_process_kill, - uv_queue_work, - uv_random, - uv_read_start, - uv_read_stop, - uv_recv_buffer_size, - uv_ref, - uv_replace_allocator, - uv_req_get_data, - uv_req_get_type, - uv_req_set_data, - uv_req_size, - uv_req_type_name, - uv_resident_set_memory, - uv_run, - uv_rwlock_destroy, - uv_rwlock_init, - uv_rwlock_rdlock, - uv_rwlock_rdunlock, - uv_rwlock_tryrdlock, - uv_rwlock_trywrlock, - uv_rwlock_wrlock, - uv_rwlock_wrunlock, - uv_sem_destroy, - uv_sem_init, - uv_sem_post, - uv_sem_trywait, - uv_sem_wait, - uv_send_buffer_size, - uv_set_process_title, - uv_setup_args, - uv_shutdown, - uv_signal_init, - uv_signal_start, - uv_signal_start_oneshot, - uv_signal_stop, - uv_sleep, - uv_socketpair, - uv_spawn, - uv_stop, - uv_stream_get_write_queue_size, - uv_stream_set_blocking, - uv_strerror, - uv_strerror_r, - uv_tcp_bind, - uv_tcp_close_reset, - uv_tcp_connect, - uv_tcp_getpeername, - uv_tcp_getsockname, - uv_tcp_init, - uv_tcp_init_ex, - uv_tcp_keepalive, - uv_tcp_nodelay, - uv_tcp_open, - uv_tcp_simultaneous_accepts, - uv_thread_create, - uv_thread_create_ex, - uv_thread_detach, - uv_thread_equal, - uv_thread_getaffinity, - uv_thread_getcpu, - uv_thread_getname, - uv_thread_getpriority, - uv_thread_join, - uv_thread_self, - uv_thread_setaffinity, - uv_thread_setname, - uv_thread_setpriority, - uv_timer_again, - uv_timer_get_due_in, - uv_timer_get_repeat, - uv_timer_init, - uv_timer_set_repeat, - uv_timer_start, - uv_timer_stop, - uv_translate_sys_error, - uv_try_write, - uv_try_write2, - uv_tty_get_vterm_state, - uv_tty_get_winsize, - uv_tty_init, - uv_tty_reset_mode, - uv_tty_set_mode, - uv_tty_set_vterm_state, - uv_udp_bind, - uv_udp_connect, - uv_udp_get_send_queue_count, - uv_udp_get_send_queue_size, - uv_udp_getpeername, - uv_udp_getsockname, - uv_udp_init, - uv_udp_init_ex, - uv_udp_open, - uv_udp_recv_start, - uv_udp_recv_stop, - uv_udp_send, - uv_udp_set_broadcast, - uv_udp_set_membership, - uv_udp_set_multicast_interface, - uv_udp_set_multicast_loop, - uv_udp_set_multicast_ttl, - uv_udp_set_source_membership, - uv_udp_set_ttl, - uv_udp_try_send, - uv_udp_try_send2, - uv_udp_using_recvmmsg, - uv_unref, - uv_update_time, - uv_uptime, - uv_utf16_length_as_wtf8, - uv_utf16_to_wtf8, - uv_version, - uv_version_string, - uv_walk, - uv_write, - uv_write2, - uv_wtf8_length_as_utf16, - uv_wtf8_to_utf16, - ); - } - - // V8API - // Hand-maintained for the same reason as the uv list above (no reflection - // over extern blocks) — keep in sync with the `v8_api` module. - #[cfg(not(windows))] - { - use v8_api::*; - keep_symbols!( - _ZN2v87Isolate10GetCurrentEv, _ZN2v87Isolate13TryGetCurrentEv, - _ZN2v87Isolate17GetCurrentContextEv, - _ZN2v87Isolate28GetEnteredOrMicrotaskContextEv, - _ZN2v87Isolate36GetContinuationPreservedEmbedderDataEv, - _ZN2v87Isolate7IsInUseEv, _ZN2v87Isolate21LowMemoryNotificationEv, - _ZN2v87Isolate36AutomaticallyRestoreInitialHeapLimitEd, - _ZN2v87Isolate30NumberOfTrackedHeapObjectTypesEv, - _ZN2v87Isolate31GetHeapObjectStatisticsAtLastGCEPNS_20HeapObjectStatisticsEm, - _ZN2v87Isolate21AddGCPrologueCallbackEPFvPS0_NS_6GCTypeENS_15GCCallbackFlagsEPvES4_S2_, - _ZN2v87Isolate24RemoveGCPrologueCallbackEPFvPS0_NS_6GCTypeENS_15GCCallbackFlagsEPvES4_, - _ZN2v87Isolate21AddGCEpilogueCallbackEPFvPS0_NS_6GCTypeENS_15GCCallbackFlagsEPvES4_S2_, - _ZN2v87Isolate24RemoveGCEpilogueCallbackEPFvPS0_NS_6GCTypeENS_15GCCallbackFlagsEPvES4_, - _ZN2v87Isolate24AddNearHeapLimitCallbackEPFmPvmmES1_, - _ZN2v87Isolate27RemoveNearHeapLimitCallbackEPFmPvmmEm, - _ZN2v87Isolate16RequestInterruptEPFvPS0_PvES2_, - _ZN2v87Isolate14ThrowExceptionENS_5LocalINS_5ValueEEE, - _ZN2v87Isolate10ThrowErrorENS_5LocalINS_6StringEEE, - _ZN2v89Exception5ErrorENS_5LocalINS_6StringEEENS1_INS_5ValueEEE, - _ZN2v89Exception9TypeErrorENS_5LocalINS_6StringEEENS1_INS_5ValueEEE, - _ZN2v87Isolate15GetHeapProfilerEv, - _ZN2v812HeapProfiler24StopSamplingHeapProfilerEv, - _ZN2v812HeapProfiler20GetAllocationProfileEv, - _ZN4node25AddEnvironmentCleanupHookEPN2v87IsolateEPFvPvES3_, - _ZN4node28RemoveEnvironmentCleanupHookEPN2v87IsolateEPFvPvES3_, - _ZN4node19GetCurrentEventLoopEPN2v87IsolateE, - _ZN4node29AsyncHooksGetExecutionAsyncIdEN2v85LocalINS0_7ContextEEE, - _ZN4node13EmitAsyncInitEPN2v87IsolateENS0_5LocalINS0_6ObjectEEENS3_INS0_6StringEEEd, - _ZN4node16EmitAsyncDestroyEPN2v87IsolateENS_13async_contextE, - _ZN4node12MakeCallbackEPN2v87IsolateENS0_5LocalINS0_6ObjectEEENS3_INS0_8FunctionEEEiPNS3_INS0_5ValueEEENS_13async_contextE, - _ZN2v84base9TimeTicks3NowEv, - _ZN2v86Number3NewEPNS_7IsolateEd, _ZNK2v86Number5ValueEv, - _ZN2v86Number12NewFromInt32EPNS_7IsolateEi, - _ZN2v86Number13NewFromUint32EPNS_7IsolateEj, - _ZN2v86String11NewFromUtf8EPNS_7IsolateEPKcNS_13NewStringTypeEi, - _ZNK2v86String9WriteUtf8EPNS_7IsolateEPciPii, _ZN2v812api_internal12ToLocalEmptyEv, - _ZNK2v86String6LengthEv, _ZN2v88External3NewEPNS_7IsolateEPv, - _ZNK2v88External5ValueEv, _ZN2v86Object3NewEPNS_7IsolateE, - _ZN2v88External3NewEPNS_7IsolateEPvt, _ZNK2v88External5ValueEt, - _ZN2v86Object3SetENS_5LocalINS_7ContextEEENS1_INS_5ValueEEES5_, - _ZN2v86Object3SetENS_5LocalINS_7ContextEEEjNS1_INS_5ValueEEE, - _ZN2v86Object16SetInternalFieldEiNS_5LocalINS_4DataEEE, - _ZN2v86Object20SlowGetInternalFieldEi, - _ZN2v86Object32SetAlignedPointerInInternalFieldEiPvt, - _ZN2v86Object38SlowGetAlignedPointerFromInternalFieldEit, - _ZN2v86Object3GetENS_5LocalINS_7ContextEEENS1_INS_5ValueEEE, - _ZN2v86Object3GetENS_5LocalINS_7ContextEEEj, - _ZN2v811HandleScope12CreateHandleEPNS_8internal7IsolateEm, - _ZN2v811HandleScope12CreateHandleEPNS_7IsolateEm, - _ZN2v811HandleScope10InitializeEPNS_7IsolateE, - _ZNK2v85Value16QuickIsUndefinedEv, - _ZNK2v85Value11QuickIsNullEv, - _ZNK2v85Value22QuickIsNullOrUndefinedEv, - _ZNK2v85Value13QuickIsStringEv, - _ZN2v811HandleScope6ExtendEPNS_7IsolateE, - _ZN2v811HandleScope16DeleteExtensionsEPNS_7IsolateE, - _ZN2v811HandleScopeC1EPNS_7IsolateE, _ZN2v811HandleScopeD1Ev, - _ZN2v811HandleScopeD2Ev, - _ZN2v816FunctionTemplate11GetFunctionENS_5LocalINS_7ContextEEE, - _ZN2v816FunctionTemplate12SetClassNameENS_5LocalINS_6StringEEE, - _ZN2v816FunctionTemplate3NewEPNS_7IsolateEPFvRKNS_20FunctionCallbackInfoINS_5ValueEEEENS_5LocalIS4_EENSA_INS_9SignatureEEEiNS_19ConstructorBehaviorENS_14SideEffectTypeEPKNS_9CFunctionEttt, - _ZN2v814ObjectTemplate11NewInstanceENS_5LocalINS_7ContextEEE, - _ZN2v814ObjectTemplate21SetInternalFieldCountEi, - _ZNK2v814ObjectTemplate18InternalFieldCountEv, - _ZN2v814ObjectTemplate3NewEPNS_7IsolateENS_5LocalINS_16FunctionTemplateEEE, - _ZN2v816FunctionTemplate16InstanceTemplateEv, - _ZN2v816FunctionTemplate17PrototypeTemplateEv, - _ZN2v88Template3SetENS_5LocalINS_4NameEEENS1_INS_4DataEEENS_17PropertyAttributeE, - _ZN2v88Template21SetNativeDataPropertyENS_5LocalINS_4NameEEEPFvS3_RKNS_20PropertyCallbackInfoINS_5ValueEEEEPFvS3_NS1_IS5_EERKNS4_IvEEESB_NS_17PropertyAttributeENS_14SideEffectTypeESI_, - _ZN2v89Signature3NewEPNS_7IsolateENS_5LocalINS_16FunctionTemplateEEE, - _ZN2v824EscapableHandleScopeBase10EscapeSlotEPm, - _ZN2v824EscapableHandleScopeBaseC2EPNS_7IsolateE, - _ZN2v88internal35IsolateFromNeverReadOnlySpaceObjectEm, - _ZN2v85Array3NewEPNS_7IsolateEPNS_5LocalINS_5ValueEEEm, _ZNK2v85Array6LengthEv, - _ZN2v85Array3NewEPNS_7IsolateEi, - _ZN2v85Array7IterateENS_5LocalINS_7ContextEEEPFNS0_14CallbackResultEjNS1_INS_5ValueEEEPvES7_, - _ZN2v85Array9CheckCastEPNS_5ValueE, - _ZN2v88Function7SetNameENS_5LocalINS_6StringEEE, - _ZN2v88Function4CallENS_5LocalINS_7ContextEEENS1_INS_5ValueEEEiPS5_, - _ZNK2v88Function11NewInstanceENS_5LocalINS_7ContextEEEiPNS1_INS_5ValueEEE, - _ZNK2v85Value9IsBooleanEv, - _ZNK2v87Boolean5ValueEv, _ZNK2v85Value10FullIsTrueEv, _ZNK2v85Value11FullIsFalseEv, - _ZN2v820EscapableHandleScopeC1EPNS_7IsolateE, - _ZN2v820EscapableHandleScopeC2EPNS_7IsolateE, _ZN2v820EscapableHandleScopeD1Ev, - _ZN2v820EscapableHandleScopeD2Ev, _ZNK2v85Value8IsObjectEv, - _ZNK2v85Value8IsNumberEv, _ZNK2v85Value8IsUint32Ev, - _ZNK2v85Value11Uint32ValueENS_5LocalINS_7ContextEEE, _ZNK2v85Value11IsUndefinedEv, - _ZNK2v85Value6IsNullEv, _ZNK2v85Value17IsNullOrUndefinedEv, _ZNK2v85Value6IsTrueEv, - _ZNK2v85Value7IsFalseEv, _ZNK2v85Value8IsStringEv, - _ZNK2v85Value12StrictEqualsENS_5LocalIS0_EE, _ZN2v87Boolean3NewEPNS_7IsolateEb, - _ZN2v811ArrayBuffer3NewEPNS_7IsolateEmNS_30BackingStoreInitializationModeE, - _ZN2v811ArrayBuffer15GetBackingStoreEv, _ZNK2v812BackingStore4DataEv, - _ZN2v815ArrayBufferView6BufferEv, _ZN2v815ArrayBufferView10ByteLengthEv, - _ZN2v815ArrayBufferView10ByteOffsetEv, - _ZN2v810Uint8Array3NewENS_5LocalINS_11ArrayBufferEEEmm, - _ZN2v811Uint32Array3NewENS_5LocalINS_11ArrayBufferEEEmm, - _ZN2v86Object16GetInternalFieldEi, _ZN2v87Context10GetIsolateEv, - _ZN2v86String14NewFromOneByteEPNS_7IsolateEPKhNS_13NewStringTypeEi, - _ZNK2v86String10Utf8LengthEPNS_7IsolateE, _ZNK2v86String10IsExternalEv, - _ZNK2v86String17IsExternalOneByteEv, _ZNK2v86String17IsExternalTwoByteEv, - _ZNK2v86String9IsOneByteEv, _ZNK2v86String19ContainsOnlyOneByteEv, - _ZNK2v86String7WriteV2EPNS_7IsolateEjjPti, - _ZNK2v86String14WriteOneByteV2EPNS_7IsolateEjjPhi, - _ZNK2v86String11WriteUtf8V2EPNS_7IsolateEPcmiPm, - _ZNK2v86String12Utf8LengthV2EPNS_7IsolateE, - _ZN2v812api_internal18GlobalizeReferenceEPNS_8internal7IsolateEm, - _ZN2v812api_internal13DisposeGlobalEPm, - _ZN2v812api_internal8MakeWeakEPmPvPFvRKNS_16WeakCallbackInfoIvEEENS_16WeakCallbackTypeE, - _ZN2v812api_internal9ClearWeakEPm, - _ZN2v812api_internal19MoveGlobalReferenceEPPmS2_, - _ZN2v812api_internal23GetFunctionTemplateDataEPNS_7IsolateENS_5LocalINS_4DataEEE, - _ZNK2v88Function7GetNameEv, _ZNK2v85Value10IsFunctionEv, _ZNK2v85Value5IsMapEv, - _ZNK2v85Value7IsArrayEv, _ZNK2v85Value7IsInt32Ev, _ZNK2v85Value8IsBigIntEv, - _ZN2v812api_internal17FromJustIsNothingEv, uv_os_getpid, uv_os_getppid, - _ZN2v87Integer3NewEPNS_7IsolateEi, - _ZN2v87Integer15NewFromUnsignedEPNS_7IsolateEj, - _ZNK2v87Integer5ValueEv, - _ZN2v86String18NewFromUtf8LiteralEPNS_7IsolateEPKcNS_13NewStringTypeEi, - _ZNK2v85Value12IsUint8ArrayEv, - _ZNK2v85Value8ToStringENS_5LocalINS_7ContextEEE, - _ZNK2v85Value9ToIntegerENS_5LocalINS_7ContextEEE, - _ZN2v87Context6GlobalEv, - _ZNK2v86Object18InternalFieldCountEv, - _ZN2v86Object15GetIdentityHashEv, - _ZN2v86Object17DefineOwnPropertyENS_5LocalINS_7ContextEEENS1_INS_4NameEEENS1_INS_5ValueEEENS_17PropertyAttributeE, - _ZN2v820ToExternalPointerTagEt, - _ZN2v88internal9Internals17GetCurrentIsolateEv, - _ZN2v820HeapObjectStatisticsC1Ev, - _ZN2v811CpuProfiler3NewEPNS_7IsolateENS_22CpuProfilingNamingModeENS_23CpuProfilingLoggingModeE, - _ZN2v811CpuProfiler7DisposeEv, - _ZN2v811CpuProfiler19SetSamplingIntervalEi, - _ZN2v811CpuProfiler5StartENS_5LocalINS_6StringEEENS_16CpuProfilingModeEbj, - _ZN2v811CpuProfiler4StopEj, - _ZN2v811CpuProfiler14StartProfilingENS_5LocalINS_6StringEEENS_16CpuProfilingModeEbj, - _ZN2v811CpuProfiler14StartProfilingENS_5LocalINS_6StringEEEb, - _ZN2v811CpuProfiler13StopProfilingENS_5LocalINS_6StringEEE, - _ZN2v810CpuProfile6DeleteEv, - _ZNK2v810CpuProfile8GetTitleEv, - _ZNK2v810CpuProfile10GetEndTimeEv, - _ZNK2v810CpuProfile12GetStartTimeEv, - _ZNK2v810CpuProfile14GetTopDownRootEv, - _ZNK2v810CpuProfile15GetSamplesCountEv, - _ZNK2v810CpuProfile18GetSampleTimestampEi, - _ZNK2v810CpuProfile9GetSampleEi, - _ZNK2v814CpuProfileNode11GetHitCountEv, - _ZNK2v814CpuProfileNode11GetScriptIdEv, - _ZNK2v814CpuProfileNode12GetLineTicksEPNS0_8LineTickEj, - _ZNK2v814CpuProfileNode13GetLineNumberEv, - _ZNK2v814CpuProfileNode15GetColumnNumberEv, - _ZNK2v814CpuProfileNode15GetFunctionNameEv, - _ZNK2v814CpuProfileNode15GetHitLineCountEv, - _ZNK2v814CpuProfileNode16GetChildrenCountEv, - _ZNK2v814CpuProfileNode18GetFunctionNameStrEv, - _ZNK2v814CpuProfileNode21GetScriptResourceNameEv, - _ZNK2v814CpuProfileNode8GetChildEi, - _ZN2v83Map3SetENS_5LocalINS_7ContextEEENS1_INS_5ValueEEES5_, - _ZN2v83Map6DeleteENS_5LocalINS_7ContextEEENS1_INS_5ValueEEE, - ); - } - #[cfg(windows)] - { - use v8_api::*; - keep_symbols!( - v8_Isolate_TryGetCurrent, - v8_Isolate_GetCurrent, - v8_Isolate_GetCurrentContext, - v8_Isolate_GetEnteredOrMicrotaskContext, - v8_Isolate_GetContinuationPreservedEmbedderData, - v8_Isolate_IsInUse, - v8_Isolate_LowMemoryNotification, - v8_Isolate_AutomaticallyRestoreInitialHeapLimit, - v8_Isolate_NumberOfTrackedHeapObjectTypes, - v8_Isolate_GetHeapObjectStatisticsAtLastGC, - v8_Isolate_AddGCPrologueCallback, - v8_Isolate_RemoveGCPrologueCallback, - v8_Isolate_AddGCEpilogueCallback, - v8_Isolate_RemoveGCEpilogueCallback, - v8_Isolate_AddNearHeapLimitCallback, - v8_Isolate_RemoveNearHeapLimitCallback, - v8_Isolate_RequestInterrupt, - v8_Isolate_ThrowException, - v8_Isolate_ThrowError, - v8_Exception_Error, - v8_Exception_TypeError, - v8_Isolate_GetHeapProfiler, - v8_HeapProfiler_StartSamplingHeapProfiler, - v8_HeapProfiler_StopSamplingHeapProfiler, - v8_HeapProfiler_GetAllocationProfile, - node_AddEnvironmentCleanupHook, - node_RemoveEnvironmentCleanupHook, - node_GetCurrentEventLoop, - node_AsyncHooksGetExecutionAsyncId, - node_EmitAsyncInit, - node_EmitAsyncDestroy, - node_MakeCallback, - v8_base_TimeTicks_Now, - v8_Number_New, - v8_Number_Value, - v8_Number_NewFromInt32, - v8_Number_NewFromUint32, - v8_String_NewFromUtf8, - v8_String_WriteUtf8, - v8_api_internal_ToLocalEmpty, - v8_String_Length, - v8_External_New, - v8_External_Value, - v8_External_New_tagged, - v8_External_Value_tagged, - v8_Object_New, - v8_Object_Set_key, - v8_Object_Set_index, - v8_Object_SetInternalField, - v8_Object_SlowGetInternalField, - v8_Object_SetAlignedPointerInInternalField, - v8_Object_SlowGetAlignedPointerFromInternalField, - v8_Object_Get_index, - v8_Object_Get_key, - v8_HandleScope_CreateHandle, - v8_HandleScope_Extend, - v8_HandleScope_DeleteExtensions, - v8_HandleScope_ctor, - v8_HandleScope_dtor, - v8_FunctionTemplate_GetFunction, - v8_FunctionTemplate_SetClassName, - v8_FunctionTemplate_New, - v8_ObjectTemplate_NewInstance, - v8_ObjectTemplate_SetInternalFieldCount, - v8_ObjectTemplate_InternalFieldCount, - v8_ObjectTemplate_New, - v8_FunctionTemplate_InstanceTemplate, - v8_FunctionTemplate_PrototypeTemplate, - v8_Template_Set, - v8_Template_SetNativeDataProperty, - v8_Signature_New, - v8_EscapableHandleScopeBase_EscapeSlot, - v8_EscapableHandleScopeBase_ctor, - v8_internal_IsolateFromNeverReadOnlySpaceObject, - v8_Array_New_elements, - v8_Array_Length, - v8_Array_New_len, - v8_Array_New_fn, - v8_Array_Iterate, - v8_Array_CheckCast, - v8_Function_SetName, - v8_Function_Call, - v8_Function_NewInstance, - v8_Function_NewInstance_noargs, - v8_Object_GetAlignedPointerFromInternalField, - v8_Value_IsBoolean, - v8_Boolean_Value, - v8_Value_FullIsTrue, - v8_Value_FullIsFalse, - v8_EscapableHandleScope_dtor, - v8_EscapableHandleScope_ctor, - v8_Value_IsObject, - v8_Value_IsNumber, - v8_Value_IsUint32, - v8_Value_Uint32Value, - v8_Value_IsUndefined, - v8_Value_IsNull, - v8_Value_IsNullOrUndefined, - v8_Value_IsTrue, - v8_Value_IsFalse, - v8_Value_IsString, - v8_Value_StrictEquals, - v8_Boolean_New, - v8_Object_GetInternalField, - v8_Context_GetIsolate, - v8_String_NewFromOneByte, - v8_String_IsExternal, - v8_String_IsExternalOneByte, - v8_String_IsExternalTwoByte, - v8_String_IsOneByte, - v8_String_Utf8Length, - v8_String_ContainsOnlyOneByte, - v8_String_WriteV2, - v8_String_WriteOneByteV2, - v8_String_WriteUtf8V2, - v8_String_Utf8LengthV2, - v8_api_internal_GlobalizeReference, - v8_api_internal_DisposeGlobal, - v8_api_internal_MakeWeak, - v8_api_internal_ClearWeak, - v8_api_internal_MoveGlobalReference, - v8_api_internal_GetFunctionTemplateData, - v8_Function_GetName, - v8_Value_IsFunction, - v8_Value_IsMap, - v8_Value_IsArray, - v8_Value_IsInt32, - v8_Value_IsBigInt, - v8_api_internal_FromJustIsNothing, - v8_Integer_New, - v8_Integer_NewFromUnsigned, - v8_Integer_Value, - v8_BigInt_New, - v8_String_NewFromUtf8Literal, - v8_Value_IsUint8Array, - v8_Value_ToString, - v8_Value_ToInteger, - v8_Context_Global, - v8_Object_InternalFieldCount, - v8_Object_GetIdentityHash, - v8_Object_DefineOwnProperty, - v8_ToExternalPointerTag, - v8_internal_Internals_GetCurrentIsolate, - v8_HeapObjectStatistics_ctor, - v8_ArrayBuffer_New, - v8_ArrayBuffer_GetBackingStore, - v8_BackingStore_Data, - v8_ArrayBufferView_Buffer, - v8_ArrayBufferView_ByteLength, - v8_ArrayBufferView_ByteOffset, - v8_Uint8Array_New, - v8_Uint32Array_New, - v8_CpuProfiler_New, - v8_CpuProfiler_Dispose, - v8_CpuProfiler_SetSamplingInterval, - v8_CpuProfiler_Start, - v8_CpuProfiler_Stop, - v8_CpuProfiler_StartProfiling_mode, - v8_CpuProfiler_StartProfiling, - v8_CpuProfiler_StopProfiling, - v8_CpuProfiler_CollectSample, - v8_CpuProfile_Delete, - v8_CpuProfile_GetTitle, - v8_CpuProfile_GetEndTime, - v8_CpuProfile_GetStartTime, - v8_CpuProfile_GetTopDownRoot, - v8_CpuProfile_GetSamplesCount, - v8_CpuProfile_GetSampleTimestamp, - v8_CpuProfile_GetSample, - v8_CpuProfileNode_GetHitCount, - v8_CpuProfileNode_GetScriptId, - v8_CpuProfileNode_GetLineTicks, - v8_CpuProfileNode_GetLineNumber, - v8_CpuProfileNode_GetColumnNumber, - v8_CpuProfileNode_GetFunctionName, - v8_CpuProfileNode_GetHitLineCount, - v8_CpuProfileNode_GetChildrenCount, - v8_CpuProfileNode_GetFunctionNameStr, - v8_CpuProfileNode_GetScriptResourceName, - v8_CpuProfileNode_GetChild, - v8_Map_Set, - v8_Map_Delete, - ); - } - - // posix_platform_specific_v8_apis - #[cfg(all(not(windows), target_os = "android"))] - keep_symbols!( - posix_platform_specific_v8_apis::_ZN2v85Array3NewENS_5LocalINS_7ContextEEEmNSt6__ndk18functionIFNS_10MaybeLocalINS_5ValueEEEvEEE, - posix_platform_specific_v8_apis::_ZN2v811CpuProfiler13CollectSampleEPNS_7IsolateENSt6__ndk18optionalImEE, - posix_platform_specific_v8_apis::_ZN2v86BigInt3NewEPNS_7IsolateEl, - posix_platform_specific_v8_apis::_ZN2v812HeapProfiler25StartSamplingHeapProfilerEmiNS0_13SamplingFlagsE, - ); - #[cfg(all(not(windows), target_os = "macos"))] - keep_symbols!( - posix_platform_specific_v8_apis::_ZN2v85Array3NewENS_5LocalINS_7ContextEEEmNSt3__18functionIFNS_10MaybeLocalINS_5ValueEEEvEEE, - posix_platform_specific_v8_apis::_ZN2v811CpuProfiler13CollectSampleEPNS_7IsolateENSt3__18optionalIyEE, - posix_platform_specific_v8_apis::_ZN2v86BigInt3NewEPNS_7IsolateEx, - posix_platform_specific_v8_apis::_ZN2v812HeapProfiler25StartSamplingHeapProfilerEyiNS0_13SamplingFlagsE, - ); - #[cfg(all(not(windows), target_os = "freebsd"))] - keep_symbols!( - posix_platform_specific_v8_apis::_ZN2v85Array3NewENS_5LocalINS_7ContextEEEmNSt3__18functionIFNS_10MaybeLocalINS_5ValueEEEvEEE, - posix_platform_specific_v8_apis::_ZN2v811CpuProfiler13CollectSampleEPNS_7IsolateENSt3__18optionalImEE, - posix_platform_specific_v8_apis::_ZN2v86BigInt3NewEPNS_7IsolateEl, - posix_platform_specific_v8_apis::_ZN2v812HeapProfiler25StartSamplingHeapProfilerEmiNS0_13SamplingFlagsE, - ); - #[cfg(all( - not(windows), - not(target_os = "android"), - not(target_os = "macos"), - not(target_os = "freebsd") - ))] - keep_symbols!( - posix_platform_specific_v8_apis::_ZN2v85Array3NewENS_5LocalINS_7ContextEEEmSt8functionIFNS_10MaybeLocalINS_5ValueEEEvEE, - posix_platform_specific_v8_apis::_ZN2v811CpuProfiler13CollectSampleEPNS_7IsolateESt8optionalImE, - posix_platform_specific_v8_apis::_ZN2v86BigInt3NewEPNS_7IsolateEl, - posix_platform_specific_v8_apis::_ZN2v812HeapProfiler25StartSamplingHeapProfilerEmiNS0_13SamplingFlagsE, + exports::napi_acquire_threadsafe_function, + exports::napi_async_destroy, + exports::napi_async_init, + exports::napi_call_threadsafe_function, + exports::napi_cancel_async_work, + exports::napi_close_callback_scope, + exports::napi_close_escapable_handle_scope, + exports::napi_close_handle_scope, + exports::napi_create_array, + exports::napi_create_array_with_length, + exports::napi_create_async_work, + exports::napi_create_date, + exports::napi_create_int32, + exports::napi_create_int64, + exports::napi_create_promise, + exports::napi_create_string_latin1, + exports::napi_create_string_utf16, + exports::napi_create_string_utf8, + exports::napi_create_threadsafe_function, + exports::napi_create_uint32, + exports::napi_delete_async_work, + exports::napi_escape_handle, + exports::napi_fatal_error, + exports::napi_get_array_length, + exports::napi_get_arraybuffer_info, + exports::napi_get_boolean, + exports::napi_get_buffer_info, + exports::napi_get_dataview_info, + exports::napi_get_node_version, + exports::napi_get_null, + exports::napi_get_prototype, + exports::napi_get_threadsafe_function_context, + exports::napi_get_typedarray_info, + exports::napi_get_undefined, + exports::napi_get_uv_event_loop, + exports::napi_get_version, + exports::napi_is_array, + exports::napi_is_arraybuffer, + exports::napi_is_dataview, + exports::napi_is_date, + exports::napi_is_error, + exports::napi_is_promise, + exports::napi_make_callback, + exports::napi_open_callback_scope, + exports::napi_open_escapable_handle_scope, + exports::napi_open_handle_scope, + exports::napi_queue_async_work, + exports::napi_ref_threadsafe_function, + exports::napi_reject_deferred, + exports::napi_release_threadsafe_function, + exports::napi_resolve_deferred, + exports::napi_strict_equals, + exports::napi_unref_threadsafe_function, ); + super::link_symbols::keep(); keep_symbols!(crate::node::buffer::BufferVectorized::fill); } @@ -5266,21 +2598,34 @@ pub(crate) struct NapiFinalizerTask { pub(crate) finalizer: Finalizer, } +// `task_tag::NapiFinalizerTask`: run one deferred addon finalizer. One released +// unrun (the loop stopped first) runs too: Node runs an addon's finalizers +// during environment cleanup (script already forbidden), and an addon counts +// on them (external buffers freed when a Worker exits). `Err` is left pending +// for the release dispatcher's fold. +bun_event_loop::boxed_task! { + NapiFinalizerTask => NapiFinalizerTask; + run = |task: Box| (*task).run_finalizer(); + release_unrun = |task: Box| { let _ = (*task).run_finalizer(); }; +} + +impl OwnedCleanupHook for NapiFinalizerTask { + /// A cleanup hook returns nothing: `Err` is left pending for the hook + /// runner's fold. + fn run(self: Box) { + let _ = (*self).run_finalizer(); + } +} + impl NapiFinalizerTask { - pub(crate) fn init(finalizer: Finalizer) -> Box { - Box::new(NapiFinalizerTask { finalizer }) + fn run_finalizer(mut self) -> JsResult<()> { + self.finalizer.run() } pub(crate) fn schedule(self: Box) { - // SAFETY: env is valid (held by NapiEnvRef). - let global_this = unsafe { &*self.finalizer.env.get() }.to_js(); - - // Inline of `JSGlobalObject::try_bun_vm` (the full impl lives in the - // gated `JSGlobalObject.rs`): the VM pointer is fetched unconditionally - // from C++; "main thread" is determined by whether the thread-local VM - // holder is populated. - // SAFETY: `bun_vm()` returns a valid `*mut VirtualMachine` for this global. - let vm: &VirtualMachine = global_this.bun_vm(); + // Inline of `JSGlobalObject::try_bun_vm`: the VM pointer is fetched + // unconditionally from C++; "main thread" is determined by whether the + // thread-local VM holder is populated. let is_main_thread = VirtualMachine::get_or_null().is_some(); if !is_main_thread { @@ -5289,30 +2634,24 @@ impl NapiFinalizerTask { // already torn down the finalizer can never run; free the task but // not the env ref — the env's count is not atomic and the env goes // with its VM — as the cleanup-hooks-already-ran case below does. - // SAFETY: env is valid (held by NapiEnvRef). - let handle = unsafe { &*self.finalizer.env.get() }.vm_handle().clone(); - let this = bun_core::heap::into_raw(self); - let ct = ConcurrentTask::create(Task::init(this)); - if let bun_jsc::vm_handle::Posted::Refused(ct) = - handle.post(bun_jsc::LoopKind::Regular, ct) - { - // SAFETY: refused ⇒ we own both boxes. - unsafe { - drop(bun_core::heap::take(ct.as_ptr())); - let task = bun_core::heap::take(this); - let _ = core::mem::ManuallyDrop::new(task.finalizer.env); - } + let handle: VmHandle = self.finalizer.env.vm_handle(); + if let Err(task) = handle.post_boxed(LoopKind::Regular, self) { + let NapiFinalizerTask { finalizer } = *task; + let Finalizer { env, .. } = finalizer; + let _ = ManuallyDrop::new(env); } return; } + let global_this = self.finalizer.env.to_js(); + let vm: &VirtualMachine = global_this.bun_vm(); if vm.is_shutting_down() { if vm.has_run_cleanup_hooks() { // `on_exit()` already drained cleanup hooks; we are inside the // final `collectNow()` (Heap::sweepArrayBuffers) and the JSC // VM is being torn down. The cleanup-hook list will never be // walked again, and running the user finalizer here (mid-GC, - // with the global about to be freed) is unsafe. Drop the task + // with the global about to be freed) is not sound. Drop the task // so the `Box` and its `NapiEnvRef` are // released; the addon's external data is reclaimed by the OS // at process exit. @@ -5320,33 +2659,11 @@ impl NapiFinalizerTask { return; } // Immediate tasks won't run, so we run this as a cleanup hook instead - let this = bun_core::heap::into_raw(self); - global_this.bun_vm().as_mut().rare_data().push_cleanup_hook( - vm.global(), - this.cast::(), - Self::run_as_cleanup_hook, - ); + vm.as_mut() + .rare_data() + .push_owned_cleanup_hook(vm.global(), self); } else { - let this = bun_core::heap::into_raw(self); - vm.event_loop_ref().enqueue_task(Task::init(this)); + vm.event_loop_ref().enqueue_task(self.into_task()); } } - - // Forwards `this` to `heap::take` without dereferencing it here; - // not_unsafe_ptr_arg_deref is a false positive on opaque-token forwarding. - #[allow(clippy::not_unsafe_ptr_arg_deref)] - pub(crate) fn run_on_js_thread(this: *mut NapiFinalizerTask) -> JsResult<()> { - // SAFETY: `this` was created by heap::alloc in `schedule`. - let mut this_box = unsafe { bun_core::heap::take(this) }; - this_box.finalizer.run() - // finalizer.deinit() runs via Drop on NapiEnvRef when this_box drops. - } - - extern "C" fn run_as_cleanup_hook(opaque_this: *mut c_void) { - // SAFETY: opaque_this is the *mut NapiFinalizerTask we registered above (non-null). - let this: *mut NapiFinalizerTask = opaque_this.cast(); - // A cleanup hook returns nothing: `Err` is left pending for the hook - // runner's fold. - let _ = Self::run_on_js_thread(this); - } } diff --git a/src/threading/lib.rs b/src/threading/lib.rs index b3af867af395..fe3c02bd76a4 100644 --- a/src/threading/lib.rs +++ b/src/threading/lib.rs @@ -40,7 +40,9 @@ pub use thread_pool::ThreadPool; pub use unbounded_queue::{Link, Linked, UnboundedQueue}; pub use wait_group::WaitGroup; pub use work_pool::Task as WorkPoolTask; -pub use work_pool::{IntrusiveWorkTask, OwnedTask, WorkPool}; +pub use work_pool::{ + IntrusiveWorkTask, OwnedTask, SharedWorkTask, WorkPool, shared_work_task_node, +}; /// Returns a non-zero OS thread id. /// Used by `Mutex` debug deadlock detection and `Condition` (Windows). diff --git a/src/threading/work_pool.rs b/src/threading/work_pool.rs index 60f4a0c98fe6..47ae0ae8a97c 100644 --- a/src/threading/work_pool.rs +++ b/src/threading/work_pool.rs @@ -38,6 +38,61 @@ pub unsafe trait IntrusiveWorkTask: bun_core::IntrusiveField { } } +/// A `T` that stays shared (`&T` / [`ThisPtr`](bun_ptr::ThisPtr)) while the +/// pool holds its embedded task node: the node sits in a [`Cell`](core::cell::Cell) +/// (built by [`shared_work_task_node`]) and the pool re-enters `T` through a +/// `ThisPtr`, on a pool thread, concurrently with whatever the scheduling +/// thread still does to `T`. Implement via [`shared_work_task!`], which +/// carries the contract; schedule with [`WorkPool::schedule_shared`]. +/// +/// # Safety +/// Whoever calls `schedule_shared` keeps `T` allocated, and its node +/// untouched, until `run_work_task` is done with it; and every field of `T` +/// is either confined to one side (the pool's `run_work_task`, or the +/// scheduling thread) for that span or synchronized — `T` need not be `Sync` +/// otherwise, so the type system does not check this. +pub unsafe trait SharedWorkTask: bun_core::IntrusiveField> { + /// Pool thread. + fn run_work_task(this: bun_ptr::ThisPtr); +} + +/// The task node for a [`SharedWorkTask`], to store in the field its +/// `IntrusiveField` impl names. +pub fn shared_work_task_node() -> core::cell::Cell { + /// # Safety + /// Only installed by [`shared_work_task_node`], so `task` is the node + /// embedded in a live `T` that [`WorkPool::schedule_shared`] handed to the pool. + unsafe fn run(task: *mut Task) { + // SAFETY: fn contract (`Cell` is `repr(transparent)` over `Task`). + let this = unsafe { T::from_field_ptr(task.cast::>()) }; + // SAFETY: fn contract — the scheduler keeps `T` live for this call. + T::run_work_task(unsafe { bun_ptr::ThisPtr::new(this) }); + } + core::cell::Cell::new(Task { + node: Default::default(), + callback: run::, + }) +} + +/// Implements [`SharedWorkTask`] for a struct that embeds a +/// `$field: Cell` node and has an inherent +/// `fn run_work_task(this: ThisPtr)` (pool thread). The invocation is +/// where the trait's contract is vouched for: say next to it which fields the +/// pool side touches and what keeps the value alive while it is scheduled. +#[macro_export] +macro_rules! shared_work_task { + ($ty:ty, $field:ident) => { + ::bun_core::intrusive_field!($ty, $field: ::core::cell::Cell<$crate::work_pool::Task>); + // SAFETY: see macro doc — the invoker states the confinement / liveness at the call site. + unsafe impl $crate::work_pool::SharedWorkTask for $ty { + #[inline] + fn run_work_task(this: ::bun_ptr::ThisPtr) { + <$ty>::run_work_task(this) + } + } + }; +} + /// An [`IntrusiveWorkTask`] that the [`WorkPool`] takes ownership of by value /// (`Box`). [`WorkPool::schedule_owned`] performs the `Box` → /// raw-pointer hand-off and [`__callback`](OwnedTask::__callback) recovers @@ -150,6 +205,14 @@ impl WorkPool { Self::get().schedule(Batch::from(task)); } + /// Hand `this`'s embedded [`SharedWorkTask`] node to the pool (see the + /// trait's contract). + pub fn schedule_shared(this: bun_ptr::ThisPtr) { + // SAFETY: `ThisPtr` invariant — `this` is a live `T`, so projecting to its + // node stays in bounds; `Cell` is `repr(transparent)` over `Task`. + Self::schedule(unsafe { T::field_of(this.as_ptr()) }.cast::()); + } + /// Schedule a heap-allocated task by value. The pool takes ownership of /// the `Box`; [`OwnedTask::run`] receives it back on a worker thread. /// Replaces the open-coded `Box::into_raw` + `&raw mut (*p).task` + diff --git a/test/internal/source-lints/vm-thread-door.inventory.json b/test/internal/source-lints/vm-thread-door.inventory.json index 170bc4087eca..389e2ea8182e 100644 --- a/test/internal/source-lints/vm-thread-door.inventory.json +++ b/test/internal/source-lints/vm-thread-door.inventory.json @@ -118,11 +118,8 @@ }, "src/runtime/napi/napi_body.rs": { "WorkPool::schedule*": 1, - "intrusive_work_task!": [ + "shared_work_task!": [ "napi_async_work" - ], - "unsafe impl Sync": [ - "napi_node_version" ] }, "src/runtime/node/fs_events.rs": { diff --git a/test/internal/source-lints/vm-thread-door.test.ts b/test/internal/source-lints/vm-thread-door.test.ts index 6bd0ac3428c8..0686b8997f3f 100644 --- a/test/internal/source-lints/vm-thread-door.test.ts +++ b/test/internal/source-lints/vm-thread-door.test.ts @@ -8,8 +8,8 @@ // `sql_jsc`, `http_jsc`), the two things that could open one: // // 1. `unsafe impl Send` / `unsafe impl Sync`, the `owned_task!` macro -// (which emits one) and `intrusive_work_task!` (which is what makes a -// type schedulable on the pool). `VirtualMachine`, +// (which emits one), and `intrusive_work_task!` / `shared_work_task!` +// (which are what makes a type schedulable on the pool). `VirtualMachine`, // `EventLoop` and `JSGlobalObject` are `!Send + !Sync`, so VM state can // only reach another thread inside a type someone declared `Send` by hand. // Every such type must either carry a `Ticket` for the VM whose state it @@ -45,7 +45,8 @@ const PATTERNS: [name: string, re: RegExp][] = [ ["unsafe impl Sync", /\bunsafe\s+impl(?:\s*<[^>]*>)?\s+Sync\s+for\s+([A-Za-z_][\w:<>, ']*)/g], ["owned_task!", /\b(?:bun_threading::)?owned_task!\s*\(\s*([A-Za-z_]\w*)/g], ["intrusive_work_task!", /\b(?:bun_threading::)?intrusive_work_task!\s*\(\s*([A-Za-z_]\w*)/g], - ["WorkPool::schedule*", /\bWorkPool::(?:schedule|schedule_new|schedule_owned|go)\b/g], + ["shared_work_task!", /\b(?:bun_threading::)?shared_work_task!\s*\(\s*([A-Za-z_]\w*)/g], + ["WorkPool::schedule*", /\bWorkPool::(?:schedule|schedule_new|schedule_owned|schedule_shared|go)\b/g], ["worker_pool.schedule(Batch)", /\)\s*\.schedule\(\s*(?:bun_threading::thread_pool::)?Batch::from/g], ["HTTPThread::schedule", /\bHTTPThread::schedule\s*\(/g], ["thread spawn", /\bthread::(?:Builder::new\s*\(|spawn\s*\()/g], From fcdf80f87772ce14d490f518213aab52f6a82a52 Mon Sep 17 00:00:00 2001 From: Jarred Sumner Date: Sun, 23 Aug 2026 22:33:45 +0000 Subject: [PATCH 02/11] VmHandle::post: read the task tag before the task can be queued --- src/jsc/VmHandle.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/jsc/VmHandle.rs b/src/jsc/VmHandle.rs index 37fd749c5818..5adc1955aa74 100644 --- a/src/jsc/VmHandle.rs +++ b/src/jsc/VmHandle.rs @@ -336,8 +336,8 @@ impl VmHandle { /// their own to free on refusal). pub fn post(&self, kind: LoopKind, task: NonNull) -> Posted { // SAFETY: handed over by the caller and not yet queued anywhere. - let tag = || unsafe { task.as_ref() }.task.tag; - if self.post_with(tag, |s| s.deliver(kind, task)) { + let tag = unsafe { task.as_ref() }.task.tag; + if self.post_with(|| tag, |s| s.deliver(kind, task)) { Posted::Queued } else { Posted::Refused(task) From 31e521ee92fd3291f30461c1db7717a29fea9524 Mon Sep 17 00:00:00 2001 From: Jarred Sumner Date: Thu, 27 Aug 2026 08:18:45 +0000 Subject: [PATCH 03/11] napi: release ThreadSafeFunction RefPtr slots by drop after the RefPtr Drop change --- src/runtime/napi/napi_body.rs | 38 +++++++++-------------------------- 1 file changed, 10 insertions(+), 28 deletions(-) diff --git a/src/runtime/napi/napi_body.rs b/src/runtime/napi/napi_body.rs index 778768244bd8..de2106fd02f4 100644 --- a/src/runtime/napi/napi_body.rs +++ b/src/runtime/napi/napi_body.rs @@ -1738,9 +1738,7 @@ impl ThreadSafeFunction { fn run_dispatch_task(this: ThisPtr) -> JsResult<()> { let dispatched = this.shared.lock().dispatch_ref.take(); Self::drain(this); - if let Some(dispatched) = dispatched { - dispatched.deref(); - } + drop(dispatched); Ok(()) } @@ -1749,9 +1747,7 @@ impl ThreadSafeFunction { /// the task's reference is left to drop. fn release_dispatch_task(this: ThisPtr) { let dispatched = this.shared.lock().dispatch_ref.take(); - if let Some(dispatched) = dispatched { - dispatched.deref(); - } + drop(dispatched); } fn run_finalize_task(this: ThisPtr) -> JsResult<()> { @@ -1759,9 +1755,7 @@ impl ThreadSafeFunction { if !this.env_dead.load(Ordering::SeqCst) { Self::finalize(this); } - if let Some(queued) = queued { - queued.deref(); - } + drop(queued); Ok(()) } @@ -1771,9 +1765,7 @@ impl ThreadSafeFunction { /// the task's own reference is dropped here. fn release_finalize_task(this: ThisPtr) { let queued = this.js.with_mut(|js| js.finalize_ref.take()); - if let Some(queued) = queued { - queued.deref(); - } + drop(queued); } /// The threadsafe function's queue drain is a dispatcher: each queued call @@ -2034,7 +2026,7 @@ impl ThreadSafeFunction { pub(crate) fn push(this: ThisPtr, ctx: *mut c_void, block: bool) -> napi_status { let mut released = Released::default(); let status = Self::enqueue(this, ctx, block, &mut released); - released.release(); + drop(released); status } @@ -2139,9 +2131,7 @@ impl ThreadSafeFunction { if let Some(finalizer) = finalizer { finalizer.enqueue(); } - if let Some(owner) = owner { - owner.deref(); - } + drop(owner); } /// Runs on the JS thread from `NapiEnv::cleanup()` while JSC is still @@ -2220,9 +2210,7 @@ impl ThreadSafeFunction { drop(js.env.take()); js.owner_ref.take() }); - if let Some(owner) = owner { - owner.deref(); - } + drop(owner); } /// `napi_ref_threadsafe_function` — JS thread only (as in Node). @@ -2258,7 +2246,7 @@ impl ThreadSafeFunction { let mut shared = this.shared.lock(); Self::release_locked(this, &mut shared, mode, &mut released) }; - released.release(); + drop(released); status } @@ -2310,7 +2298,7 @@ impl ThreadSafeFunction { } /// References whose holders let go inside a `ThreadSafeFunction`'s critical -/// section, released once its lock is dropped: the last one frees the +/// section, dropped once its lock is released: the last one frees the /// function, lock included. #[derive(Default)] struct Released([Option>; 2]); @@ -2322,12 +2310,6 @@ impl Released { *slot.expect("at most two references change hands per call") = Some(r); } } - - fn release(self) { - for r in self.0.into_iter().flatten() { - r.deref(); - } - } } /// Called from `NapiEnv::cleanup()` (JS thread) for every threadsafe function @@ -2411,7 +2393,7 @@ pub fn napi_create_threadsafe_function( // finalizer: the handle was never published, so the addon still owns // what it passed in (node's `Init` failure path just deletes the // ThreadSafeFunction, whose destructor only releases its own resources). - owner.deref(); + drop(owner); return env.generic_failure(); } From 9ef00534e43155b454773ba06b91a29552c34a45 Mon Sep 17 00:00:00 2001 From: Jarred Sumner Date: Thu, 27 Aug 2026 09:07:20 +0000 Subject: [PATCH 04/11] napi: pool owns a reference to queued async work; typed release for refused boxed tasks WorkPool::schedule_shared takes a RefPtr and the node's queued flag guards double scheduling; napi_async_work is ThreadSafeRefCounted, the pool's reference rides the completion back and is dropped on the JS thread. ConcurrentTask carriers record how to free an owned payload when a weak post is refused (BoxedTask::refused), replacing the ManagedTask tag check. Drop the duplicate uv_os_getpid/getppid retention entries. --- src/codegen/generate-host-exports.ts | 1 + src/event_loop/ConcurrentTask.rs | 166 ++++++++++++++++++++++----- src/jsc/VmHandle.rs | 22 ++-- src/jsc/hot_reloader.rs | 7 +- src/runtime/bake/dev_server/mod.rs | 8 +- src/runtime/napi/link_symbols.rs | 4 - src/runtime/napi/napi_body.rs | 92 ++++++++------- src/threading/lib.rs | 4 +- src/threading/work_pool.rs | 112 +++++++++++------- 9 files changed, 279 insertions(+), 137 deletions(-) diff --git a/src/codegen/generate-host-exports.ts b/src/codegen/generate-host-exports.ts index ab53343731db..d2d6a7f658b3 100644 --- a/src/codegen/generate-host-exports.ts +++ b/src/codegen/generate-host-exports.ts @@ -578,6 +578,7 @@ const importCandidates: Array<[string, string]> = [ ["core::mem", "ManuallyDrop"], ["core::mem", "MaybeUninit"], ["bun_ptr", "ThisPtr"], + ["bun_ptr", "RefPtr"], ["bun_jsc", "JSPromiseStrong"], ["bun_jsc", "NapiEnv"], ["bun_jsc", "NapiHandleScope"], diff --git a/src/event_loop/ConcurrentTask.rs b/src/event_loop/ConcurrentTask.rs index caa44b69fcc3..ec1ba1d049c5 100644 --- a/src/event_loop/ConcurrentTask.rs +++ b/src/event_loop/ConcurrentTask.rs @@ -5,8 +5,8 @@ //! //! The task is run on a thread pool and then the result is returned to the main JavaScript thread. //! -//! If `auto_delete` is true, the task is automatically deallocated when it's finished. -//! Otherwise, it's expected that the containing struct will deallocate the task. +//! A heap carrier (`create*`) is deallocated by the event loop once its task is +//! dispatched; an intrusive one is part of the struct that owns it. use crate::ManagedTask; use bun_threading::UnboundedQueue; @@ -230,7 +230,12 @@ pub unsafe trait BoxedTask: Sized { fn run(self: Box) -> crate::JsResult<()>; /// As [`Taskable::release_unrun`]. fn release_unrun(self: Box); + /// A weak post was refused: the VM this was for has closed (any thread; + /// its heap may be gone). Free the task without touching that VM. + fn refused(self: Box); + /// The JS thread's own enqueue (`EventLoop::enqueue_task`), which cannot + /// be refused; off-thread posts go through `ConcurrentTask::create_boxed`. #[inline] fn into_task(self: Box) -> Task { Task::new(Self::TAG, Box::into_raw(self).cast::<()>()) @@ -238,10 +243,10 @@ pub unsafe trait BoxedTask: Sized { } /// Implements [`BoxedTask`] for `$ty` as the task `task_tag::$tag` dispatches -/// to, forwarding to `$run` / `$release` (each `fn(Box<$ty>)`). +/// to, forwarding to `$run` / `$release` / `$refused` (each `fn(Box<$ty>)`). #[macro_export] macro_rules! boxed_task { - ($ty:ty => $tag:ident; run = $run:expr; release_unrun = $release:expr $(;)?) => { + ($ty:ty => $tag:ident; run = $run:expr; release_unrun = $release:expr; refused = $refused:expr $(;)?) => { // SAFETY: see macro doc — one boxed task type per tag. unsafe impl $crate::BoxedTask for $ty { const TAG: $crate::TaskTag = $crate::task_tag::$tag; @@ -253,6 +258,10 @@ macro_rules! boxed_task { fn release_unrun(self: ::std::boxed::Box) { ($release)(self) } + #[inline] + fn refused(self: ::std::boxed::Box) { + ($refused)(self) + } } }; } @@ -298,6 +307,10 @@ impl Taskable for crate::ManagedTask::ManagedTask { } // ──────────────────────────────────────────────────────────────────────────── +/// How a heap carrier (`ConcurrentTask::create*`) frees itself, and the +/// payload if the carrier owns it, when a weak post is refused. +type ReleaseRefused = unsafe fn(core::ptr::NonNull); + #[repr(C)] pub struct ConcurrentTask { pub task: Task, @@ -305,10 +318,13 @@ pub struct ConcurrentTask { /// path (`atomic_store_next`, called once per completed work-pool task via /// `enqueue_task_concurrent`) is a single release-store — no read-modify-write. pub next: Link, - /// If `true`, the task is heap-owned and freed by the event loop after - /// dispatch. Immutable after construction; read only on the consumer thread, - /// so it does not need to share a word with the contended `next` link. - pub auto_delete: bool, + /// `Some` on a heap carrier (`create*`): the event loop frees the carrier + /// after dispatching its task, and a refused weak post frees carrier and + /// owned payload through it ([`ConcurrentTask::release_refused`]). `None` + /// on an intrusive carrier, which belongs to its container. Immutable after + /// construction; read only on the consumer thread, so it does not need to + /// share a word with the contended `next` link. + release_refused: Option, } impl Default for ConcurrentTask { @@ -318,12 +334,12 @@ impl Default for ConcurrentTask { // byte + raw pointer); caller must set a real task before use. task: unsafe { bun_core::ffi::zeroed_unchecked() }, next: Link::new(), - auto_delete: false, + release_refused: None, } } } -// `auto_delete` is deliberately its own field rather than packed into bit 0 +// `release_refused` is deliberately its own field rather than packed into bit 0 // of `next`: `Task` is already two words here (tag is not packed into the // pointer), so the struct was never 16B, and profiling (build/create-next // benches) showed @@ -334,7 +350,7 @@ impl Default for ConcurrentTask { const _: () = assert!( core::mem::size_of::() == core::mem::size_of::() + 2 * core::mem::size_of::(), - "ConcurrentTask = Task + next ptr + auto_delete (padded)" + "ConcurrentTask = Task + next ptr + release_refused" ); // SAFETY: `link()` always projects to the same embedded `next: Link` @@ -365,11 +381,55 @@ impl ConcurrentTask { bun_core::heap::into_raw(Box::new(init)) } + /// A heap carrier for `task`, whose payload the carrier does not own + /// (intrusive, or freed by whoever posts it) — except a `ManagedTask`, + /// which it does. pub fn create(task: Task) -> core::ptr::NonNull { + /// # Safety + /// `this` is a refused heap carrier. + unsafe fn carrier_only(this: core::ptr::NonNull) { + // SAFETY: fn contract; `create*` boxed it. + drop(unsafe { bun_core::heap::take(this.as_ptr()) }); + } + /// # Safety + /// `this` is a refused heap carrier whose payload is a `ManagedTask`. + unsafe fn managed(this: core::ptr::NonNull) { + // SAFETY: fn contract; refused ⇒ both boxes are ours. + unsafe { + let task = bun_core::heap::take(this.as_ptr()).task; + crate::ManagedTask::ManagedTask::release(task.ptr.cast()); + } + } + let release: ReleaseRefused = if task.tag == task_tag::ManagedTask { + managed + } else { + carrier_only + }; + Self::create_with(task, release) + } + + /// A heap carrier owning the boxed `task`: a refused weak post hands it to + /// [`BoxedTask::refused`]. + pub fn create_boxed(task: Box) -> core::ptr::NonNull { + /// # Safety + /// `this` is a refused heap carrier built by `create_boxed::`. + unsafe fn boxed(this: core::ptr::NonNull) { + // SAFETY: fn contract; refused ⇒ both boxes are ours, and the + // payload is the `Box` `into_task` leaked. + let task = unsafe { + let task = bun_core::heap::take(this.as_ptr()).task; + Box::from_raw(task.ptr.cast::()) + }; + T::refused(task); + } + Self::create_with(task.into_task(), boxed::) + } + + fn create_with(task: Task, release: ReleaseRefused) -> core::ptr::NonNull { let raw = ConcurrentTask::new(ConcurrentTask { task, next: Link::new(), - auto_delete: true, + release_refused: Some(release), }); // SAFETY: `new` heap-allocates via `heap::into_raw` — never null. unsafe { core::ptr::NonNull::new_unchecked(raw) } @@ -395,17 +455,23 @@ impl ConcurrentTask { of: *mut T, auto_deinit: AutoDeinit, ) -> &mut ConcurrentTask { - self.from_task(Task::init(of), auto_deinit) + debug_assert!(auto_deinit == AutoDeinit::ManualDeinit); + self.from_task(Task::init(of)) } - /// Load this (intrusive) carrier with `task`, ready to post. - pub fn from_task(&mut self, task: Task, auto_deinit: AutoDeinit) -> &mut ConcurrentTask { - bun_core::mark_binding!(); - *self = ConcurrentTask { + /// An intrusive carrier loaded with `task`, ready to post. + pub const fn intrusive(task: Task) -> ConcurrentTask { + ConcurrentTask { task, next: Link::new(), - auto_delete: auto_deinit == AutoDeinit::AutoDeinit, - }; + release_refused: None, + } + } + + /// Load this intrusive carrier with `task`, ready to post. + pub fn from_task(&mut self, task: Task) -> &mut ConcurrentTask { + bun_core::mark_binding!(); + *self = Self::intrusive(task); self } @@ -426,25 +492,65 @@ impl ConcurrentTask { } /// A weak poster got `task` back because the target VM has closed: free - /// it if it is a heap task (`create*`); an intrusive one belongs to its - /// container. + /// it if it is a heap carrier (`create*`), with the payload if the carrier + /// owns it; an intrusive one belongs to its container. /// /// # Safety /// `task` was just refused and is not queued anywhere. pub unsafe fn release_refused(task: core::ptr::NonNull) { - // SAFETY: fn contract. - let inner = unsafe { Self::into_task(task) }; - // A callback task (`from_callback`, `ManagedTask::new*`) owns a heap - // `ManagedTask` behind `task.ptr` as well. - if inner.tag == crate::task_tag::ManagedTask { - // SAFETY: as above; refused ⇒ ours. - unsafe { crate::ManagedTask::ManagedTask::release(inner.ptr.cast()) }; + // SAFETY: fn contract; `release_refused` was installed by the + // constructor that knows the carrier's and payload's ownership. + unsafe { + if let Some(release) = task.as_ref().release_refused { + release(task); + } } } - /// Returns whether this task should be automatically deallocated after execution. + /// Whether this is a heap carrier (`create*`) the event loop frees after + /// dispatching its task. #[inline] pub fn auto_delete(&self) -> bool { - self.auto_delete + self.release_refused.is_some() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use core::sync::atomic::{AtomicUsize, Ordering}; + + static REFUSED: AtomicUsize = AtomicUsize::new(0); + static DROPPED: AtomicUsize = AtomicUsize::new(0); + + struct Payload(#[allow(dead_code)] Box<[u8; 64]>); + impl Drop for Payload { + fn drop(&mut self) { + DROPPED.fetch_add(1, Ordering::SeqCst); + } + } + crate::boxed_task! { + Payload => NapiFinalizerTask; + run = |_task: Box| Ok(()); + release_unrun = |_task: Box| {}; + refused = |_task: Box| { REFUSED.fetch_add(1, Ordering::SeqCst); }; + } + + #[test] + fn refused_boxed_carrier_releases_its_payload() { + let carrier = ConcurrentTask::create_boxed(Box::new(Payload(Box::new([7; 64])))); + // SAFETY: never queued; ours. + unsafe { ConcurrentTask::release_refused(carrier) }; + assert_eq!(REFUSED.load(Ordering::SeqCst), 1); + assert_eq!(DROPPED.load(Ordering::SeqCst), 1); + + let mut intrusive = + ConcurrentTask::intrusive(Box::new(Payload(Box::new([7; 64]))).into_task()); + // SAFETY: never queued; an intrusive carrier is left alone. + unsafe { ConcurrentTask::release_refused(core::ptr::NonNull::from(&mut intrusive)) }; + assert_eq!(DROPPED.load(Ordering::SeqCst), 1); + // SAFETY: the payload leaked into the intrusive carrier above. + drop(unsafe { Box::from_raw(intrusive.task.ptr.cast::()) }); + assert_eq!(DROPPED.load(Ordering::SeqCst), 2); } } diff --git a/src/jsc/VmHandle.rs b/src/jsc/VmHandle.rs index 5adc1955aa74..e8a88581610c 100644 --- a/src/jsc/VmHandle.rs +++ b/src/jsc/VmHandle.rs @@ -379,24 +379,22 @@ impl VmHandle { } /// Queue a [`BoxedTask`](bun_event_loop::BoxedTask) on the VM's `kind` - /// loop and wake it, or hand it back if the VM is closed. - pub fn post_boxed( - &self, - kind: LoopKind, - task: Box, - ) -> Result<(), Box> { + /// loop and wake it, or hand it to + /// [`BoxedTask::refused`](bun_event_loop::BoxedTask::refused) if the VM is + /// closed. Whether it was queued. + pub fn post_boxed(&self, kind: LoopKind, task: Box) -> bool { let mut task = Some(task); - self.post_with( + let queued = self.post_with( || T::TAG, |s| { - let task = task.take().expect("posted once").into_task(); - s.deliver(kind, ConcurrentTaskItem::create(task)); + let task = task.take().expect("posted once"); + s.deliver(kind, ConcurrentTaskItem::create_boxed(task)); }, ); - match task { - None => Ok(()), - Some(task) => Err(task), + if let Some(task) = task { + T::refused(task); } + queued } /// Queue a C++ `EventLoopTask` on the VM's `kind` loop from another diff --git a/src/jsc/hot_reloader.rs b/src/jsc/hot_reloader.rs index 3660c0526a98..013c684efb81 100644 --- a/src/jsc/hot_reloader.rs +++ b/src/jsc/hot_reloader.rs @@ -614,10 +614,9 @@ where })); // SAFETY: `that` was just allocated above and is exclusively owned here. unsafe { - let concurrent = (*that).concurrent_task.insert(ConcurrentTask { - task: JscTask::init(that), - ..Default::default() - }); + let concurrent = (*that) + .concurrent_task + .insert(ConcurrentTask::intrusive(JscTask::init(that))); // `&that.concurrent_task` is an interior pointer into the // Box-allocated Task. `RELOAD_IMMEDIATELY` already diverged above, so // a handle is always present here. diff --git a/src/runtime/bake/dev_server/mod.rs b/src/runtime/bake/dev_server/mod.rs index e8b18a04c1e0..a2fd9014146e 100644 --- a/src/runtime/bake/dev_server/mod.rs +++ b/src/runtime/bake/dev_server/mod.rs @@ -939,10 +939,10 @@ impl WatcherAtomics { // Not atomic because the dev server is not running events right now. (*this).dbg_server_event = Some(ev); } - (*ev).concurrent_task = bun_event_loop::ConcurrentTask::ConcurrentTask { - task: bun_event_loop::Task::init(ev), - ..Default::default() - }; + (*ev).concurrent_task = + bun_event_loop::ConcurrentTask::ConcurrentTask::intrusive( + bun_event_loop::Task::init(ev), + ); // The queued node pointer is derived from `ev` (allocation-root // provenance) so it stays valid across `Drop for DevServer`'s // writes. Refused ⇒ the VM is torn down; the event is one of diff --git a/src/runtime/napi/link_symbols.rs b/src/runtime/napi/link_symbols.rs index 923733836c23..639143451bce 100644 --- a/src/runtime/napi/link_symbols.rs +++ b/src/runtime/napi/link_symbols.rs @@ -301,8 +301,6 @@ mod v8_api { pub(super) fn _ZNK2v814CpuProfileNode8GetChildEi(); pub(super) fn _ZN2v83Map3SetENS_5LocalINS_7ContextEEENS1_INS_5ValueEEES5_(); pub(super) fn _ZN2v83Map6DeleteENS_5LocalINS_7ContextEEENS1_INS_5ValueEEE(); - pub(super) fn uv_os_getpid(); - pub(super) fn uv_os_getppid(); } } #[cfg(windows)] @@ -1654,8 +1652,6 @@ pub(super) fn keep() { _ZNK2v814CpuProfileNode8GetChildEi, _ZN2v83Map3SetENS_5LocalINS_7ContextEEENS1_INS_5ValueEEES5_, _ZN2v83Map6DeleteENS_5LocalINS_7ContextEEENS1_INS_5ValueEEE, - uv_os_getpid, - uv_os_getppid, ); } #[cfg(windows)] diff --git a/src/runtime/napi/napi_body.rs b/src/runtime/napi/napi_body.rs index de2106fd02f4..0f44479c7219 100644 --- a/src/runtime/napi/napi_body.rs +++ b/src/runtime/napi/napi_body.rs @@ -14,7 +14,6 @@ use core::sync::atomic::{AtomicBool, AtomicI64, AtomicU8, AtomicU32, AtomicUsize use bun_collections::LinearFifo; use bun_collections::linear_fifo::DynamicBuffer; -use bun_event_loop::ConcurrentTask::AutoDeinit; use bun_event_loop::{BoxedTask, TaskHop}; use bun_io::KeepAlive; use bun_jsc::StringJsc; @@ -30,7 +29,7 @@ use bun_jsc::{ use bun_ptr::{JsCell, RefPtr, ThisPtr}; use bun_threading::Condition as Condvar; use bun_threading::Guarded; -use bun_threading::work_pool::{Task as WorkPoolTask, WorkPool}; +use bun_threading::work_pool::WorkPool; bun_output::declare_scope!(napi, visible); @@ -1143,19 +1142,24 @@ pub enum AsyncWorkStatus { Cancelled = 3, } -/// Owned by the addon from `napi_create_async_work` until -/// `napi_delete_async_work`: it keeps the work alive across -/// `napi_queue_async_work` → `execute` (pool) → `complete` (JS thread), as -/// Node requires, and every side reaches it shared. While it is out on the pool -/// (`schedule` → `run_work_task`), the pool side takes `ticket`, runs `execute` -/// with `env`/`data`, updates `status` (atomic; `cancel` races it from the JS +/// The addon holds a reference from `napi_create_async_work` until +/// `napi_delete_async_work`; the pool holds one while the work is out on it +/// (`schedule` → `run_work_task`), which then rides the completion back to the +/// JS thread (`completion_ref`) so the work is only ever freed there. While it +/// is out on the pool, the pool side takes `ticket`, runs `execute` with +/// `env`/`data`, updates `status` (atomic; `cancel` races it from the JS /// thread) and posts through `concurrent_task`; the JS thread leaves those be /// until the completion arrives and owns `scheduled` / `poll_ref` throughout. +#[derive(bun_ptr::ThreadSafeRefCounted)] pub struct napi_async_work { + ref_count: bun_ptr::ThreadSafeRefCount, /// The pool's node while the work is out on it. - task: Cell, + task: bun_threading::SharedWorkNode, /// The completion's node (pool → JS thread). concurrent_task: Cell, + /// The queued completion's reference (the one the pool held), dropped on + /// the JS thread once `complete` has run. + completion_ref: Cell>>, /// Held while the work is out on the pool (`schedule` until it is posted /// back): how the pool thread delivers completion / cancellation, and what /// makes the VM wait for it. @@ -1171,13 +1175,13 @@ pub struct napi_async_work { poll_ref: Cell, } -// Pool side / JS side split as documented on the struct; the addon keeps the -// work allocated until `complete` has run (N-API contract). +// Pool side / JS side split as documented on the struct; the pool's reference +// is dropped on the JS thread (`run_from_js` / `release_unrun`). bun_threading::shared_work_task!(napi_async_work, task); bun_event_loop::task_hop! { /// `task_tag::NapiAsyncWork`: the pool is done with a queued work; run its - /// `complete` on the JS thread. The addon keeps the work alive until then. + /// `complete` on the JS thread. The queued task holds `completion_ref`. pub(crate) AsyncWorkCompletion for napi_async_work => NapiAsyncWork; run = napi_async_work::run_from_js; release_unrun = napi_async_work::release_unrun; @@ -1189,10 +1193,12 @@ impl napi_async_work { execute: napi_async_execute_callback, complete: Option, data: *mut c_void, - ) -> Box { - Box::new(napi_async_work { - task: bun_threading::shared_work_task_node::(), + ) -> RefPtr { + RefPtr::new(napi_async_work { + ref_count: bun_ptr::ThreadSafeRefCount::init(), + task: bun_threading::SharedWorkNode::new::(), concurrent_task: Cell::new(ConcurrentTask::default()), + completion_ref: Cell::new(None), env: env.to_ref(), execute, ticket: Cell::new(None), @@ -1213,11 +1219,10 @@ impl napi_async_work { let mut poll_ref = this.poll_ref.take(); poll_ref.ref_(bun_io::js_vm_ctx()); this.poll_ref.set(poll_ref); - // The work object belongs to the addon and `execute` receives this - // env, so the VM waits for it (Node likewise settles its threadpool - // requests before an environment is freed). + // `execute` receives this env, so the VM waits for it (Node likewise + // settles its threadpool requests before an environment is freed). this.ticket.set(Some(this.env.to_js().bun_vm().ticket())); - WorkPool::schedule_shared(this); + WorkPool::schedule_shared(RefPtr::from_this(this)); } pub(crate) fn cancel(&self) -> bool { @@ -1239,10 +1244,9 @@ impl napi_async_work { let _ = Self::run_from_js(this); } - /// JS thread: run `complete`. The addon may free the work (this - /// allocation) from inside `complete`, so nothing of `this` is touched - /// after that call. + /// JS thread: run `complete`, then drop the completion's reference. fn run_from_js(this: ThisPtr) -> JsResult<()> { + let _completion = this.completion_ref.take(); let mut poll_ref = this.poll_ref.take(); // KeepAlive::unref needs an event-loop ctx so it cannot impl Drop // generically; this is a genuine one-off cleanup. @@ -1268,9 +1272,11 @@ impl napi_async_work { /// Pool thread: run `execute` (unless the VM is already stopping, which /// cancels work it has not started, as Node's environment cleanup does - /// with `uv_cancel`) and post the work back to the JS thread for `complete`. - fn run_work_task(this: ThisPtr) { - // Moved out: the JS thread may free the work the moment it is posted back. + /// with `uv_cancel`) and post the work back to the JS thread for + /// `complete`, handing the pool's reference over to that completion. + fn run_work_task(this: RefPtr) { + // Moved out: the JS thread may consume the completion the moment it is + // posted. let ticket = this .ticket .take() @@ -1295,9 +1301,12 @@ impl napi_async_work { // A VM tearing down runs `complete` from its queue release (status // cancelled if `execute` never ran), as Node does at environment cleanup. let mut node = ConcurrentTask::default(); - node.from_task(AsyncWorkCompletion::task(this), AutoDeinit::ManualDeinit); + node.from_task(AsyncWorkCompletion::task(this.this_ptr())); this.concurrent_task.set(node); - ticket.post(NonNull::new(this.concurrent_task.as_ptr()).expect("field address")); + let work = this.this_ptr(); + let carrier = NonNull::new(work.concurrent_task.as_ptr()).expect("field address"); + work.completion_ref.set(Some(this)); + ticket.post(carrier); } } @@ -1429,8 +1438,8 @@ pub fn napi_create_async_work( let Some(execute) = execute_ else { return env.invalid_arg(); }; - // Owned by the addon until `napi_delete_async_work`. - result.write(bun_core::heap::into_raw(napi_async_work::new( + // The addon's reference, until `napi_delete_async_work`. + result.write(RefPtr::into_raw(napi_async_work::new( env, execute, complete, data, ))); env.ok() @@ -1439,7 +1448,7 @@ pub fn napi_create_async_work( // HOST_EXPORT(napi_delete_async_work, c) pub fn napi_delete_async_work( env_: Option<&NapiEnv>, - work_: Option>>, + work_: Option>>, ) -> napi_status { bun_output::scoped_log!(napi, "napi_delete_async_work"); let env = get_env!(env_); @@ -2589,6 +2598,7 @@ bun_event_loop::boxed_task! { NapiFinalizerTask => NapiFinalizerTask; run = |task: Box| (*task).run_finalizer(); release_unrun = |task: Box| { let _ = (*task).run_finalizer(); }; + refused = |task: Box| (*task).refused(); } impl OwnedCleanupHook for NapiFinalizerTask { @@ -2604,6 +2614,16 @@ impl NapiFinalizerTask { self.finalizer.run() } + /// The VM is already torn down, so the finalizer can never run: free the + /// task but not the env ref — the env's count is not atomic and the env + /// goes with its VM — as the cleanup-hooks-already-ran case in `schedule` + /// does. + fn refused(self) { + let NapiFinalizerTask { finalizer } = self; + let Finalizer { env, .. } = finalizer; + let _ = ManuallyDrop::new(env); + } + pub(crate) fn schedule(self: Box) { // Inline of `JSGlobalObject::try_bun_vm`: the VM pointer is fetched // unconditionally from C++; "main thread" is determined by whether the @@ -2612,16 +2632,10 @@ impl NapiFinalizerTask { if !is_main_thread { // Off the JS thread (e.g. an external buffer finalized from a GC - // helper thread): post through the env's VM handle. If the VM is - // already torn down the finalizer can never run; free the task but - // not the env ref — the env's count is not atomic and the env goes - // with its VM — as the cleanup-hooks-already-ran case below does. + // helper thread): post through the env's VM handle (`refused` if + // the VM is already torn down). let handle: VmHandle = self.finalizer.env.vm_handle(); - if let Err(task) = handle.post_boxed(LoopKind::Regular, self) { - let NapiFinalizerTask { finalizer } = *task; - let Finalizer { env, .. } = finalizer; - let _ = ManuallyDrop::new(env); - } + handle.post_boxed(LoopKind::Regular, self); return; } diff --git a/src/threading/lib.rs b/src/threading/lib.rs index fe3c02bd76a4..628f0d6c8dce 100644 --- a/src/threading/lib.rs +++ b/src/threading/lib.rs @@ -40,9 +40,7 @@ pub use thread_pool::ThreadPool; pub use unbounded_queue::{Link, Linked, UnboundedQueue}; pub use wait_group::WaitGroup; pub use work_pool::Task as WorkPoolTask; -pub use work_pool::{ - IntrusiveWorkTask, OwnedTask, SharedWorkTask, WorkPool, shared_work_task_node, -}; +pub use work_pool::{IntrusiveWorkTask, OwnedTask, SharedWorkNode, SharedWorkTask, WorkPool}; /// Returns a non-zero OS thread id. /// Used by `Mutex` debug deadlock detection and `Condition` (Windows). diff --git a/src/threading/work_pool.rs b/src/threading/work_pool.rs index 47ae0ae8a97c..8da30dacfdb8 100644 --- a/src/threading/work_pool.rs +++ b/src/threading/work_pool.rs @@ -38,55 +38,76 @@ pub unsafe trait IntrusiveWorkTask: bun_core::IntrusiveField { } } -/// A `T` that stays shared (`&T` / [`ThisPtr`](bun_ptr::ThisPtr)) while the -/// pool holds its embedded task node: the node sits in a [`Cell`](core::cell::Cell) -/// (built by [`shared_work_task_node`]) and the pool re-enters `T` through a -/// `ThisPtr`, on a pool thread, concurrently with whatever the scheduling -/// thread still does to `T`. Implement via [`shared_work_task!`], which -/// carries the contract; schedule with [`WorkPool::schedule_shared`]. +/// A refcounted `T` that stays shared (`&T`) while the pool holds its embedded +/// [`SharedWorkNode`]: [`WorkPool::schedule_shared`] moves one reference into +/// the pool, and the pool hands that reference to +/// [`run_work_task`](Self::run_work_task) on a pool thread, concurrently with +/// whatever other holders still do to `T`. Implement via [`shared_work_task!`], +/// which carries the contract. /// /// # Safety -/// Whoever calls `schedule_shared` keeps `T` allocated, and its node -/// untouched, until `run_work_task` is done with it; and every field of `T` -/// is either confined to one side (the pool's `run_work_task`, or the -/// scheduling thread) for that span or synchronized — `T` need not be `Sync` -/// otherwise, so the type system does not check this. -pub unsafe trait SharedWorkTask: bun_core::IntrusiveField> { - /// Pool thread. - fn run_work_task(this: bun_ptr::ThisPtr); +/// Every field of `T` is either confined to one side (the pool's +/// `run_work_task`, or the other holders) while the node is queued, or +/// synchronized — `T` need not be `Sync` otherwise, so the type system does not +/// check this; and wherever `run_work_task` lets its reference go must be a +/// thread `T` may be freed on. +pub unsafe trait SharedWorkTask: + bun_ptr::AnyRefCounted + bun_core::IntrusiveField +{ + /// Pool thread. `this` is the reference `schedule_shared` was given. + fn run_work_task(this: bun_ptr::RefPtr); } -/// The task node for a [`SharedWorkTask`], to store in the field its +/// The pool's node inside a [`SharedWorkTask`], stored in the field its /// `IntrusiveField` impl names. -pub fn shared_work_task_node() -> core::cell::Cell { - /// # Safety - /// Only installed by [`shared_work_task_node`], so `task` is the node - /// embedded in a live `T` that [`WorkPool::schedule_shared`] handed to the pool. - unsafe fn run(task: *mut Task) { - // SAFETY: fn contract (`Cell` is `repr(transparent)` over `Task`). - let this = unsafe { T::from_field_ptr(task.cast::>()) }; - // SAFETY: fn contract — the scheduler keeps `T` live for this call. - T::run_work_task(unsafe { bun_ptr::ThisPtr::new(this) }); +#[repr(C)] +pub struct SharedWorkNode { + task: core::cell::UnsafeCell, + /// Set from `schedule_shared` until the pool thread picks the node up. + queued: core::sync::atomic::AtomicBool, +} + +impl SharedWorkNode { + pub fn new() -> SharedWorkNode { + /// # Safety + /// Only installed by [`SharedWorkNode::new`], so `task` is the node + /// embedded in a live `T` that [`WorkPool::schedule_shared`] queued + /// together with one reference. + unsafe fn run(task: *mut Task) { + // SAFETY: fn contract (`UnsafeCell` is `repr(transparent)` + // over `Task`, and `task` is `SharedWorkNode`'s first field). + let (node, this) = unsafe { + let node = task.cast::(); + (&*node, T::from_field_ptr(node)) + }; + node.queued + .store(false, core::sync::atomic::Ordering::Release); + // SAFETY: fn contract — `schedule_shared` moved this reference into the pool. + T::run_work_task(unsafe { bun_ptr::RefPtr::from_raw(this) }); + } + SharedWorkNode { + task: core::cell::UnsafeCell::new(Task { + node: Default::default(), + callback: run::, + }), + queued: core::sync::atomic::AtomicBool::new(false), + } } - core::cell::Cell::new(Task { - node: Default::default(), - callback: run::, - }) } -/// Implements [`SharedWorkTask`] for a struct that embeds a -/// `$field: Cell` node and has an inherent -/// `fn run_work_task(this: ThisPtr)` (pool thread). The invocation is +/// Implements [`SharedWorkTask`] for a refcounted struct that embeds a +/// `$field: SharedWorkNode` and has an inherent +/// `fn run_work_task(this: RefPtr)` (pool thread). The invocation is /// where the trait's contract is vouched for: say next to it which fields the -/// pool side touches and what keeps the value alive while it is scheduled. +/// pool side touches and where the pool's reference is dropped. #[macro_export] macro_rules! shared_work_task { ($ty:ty, $field:ident) => { - ::bun_core::intrusive_field!($ty, $field: ::core::cell::Cell<$crate::work_pool::Task>); - // SAFETY: see macro doc — the invoker states the confinement / liveness at the call site. + ::bun_core::intrusive_field!($ty, $field: $crate::work_pool::SharedWorkNode); + // SAFETY: see macro doc — the invoker states the confinement at the call site. unsafe impl $crate::work_pool::SharedWorkTask for $ty { #[inline] - fn run_work_task(this: ::bun_ptr::ThisPtr) { + fn run_work_task(this: ::bun_ptr::RefPtr) { <$ty>::run_work_task(this) } } @@ -205,12 +226,21 @@ impl WorkPool { Self::get().schedule(Batch::from(task)); } - /// Hand `this`'s embedded [`SharedWorkTask`] node to the pool (see the - /// trait's contract). - pub fn schedule_shared(this: bun_ptr::ThisPtr) { - // SAFETY: `ThisPtr` invariant — `this` is a live `T`, so projecting to its - // node stays in bounds; `Cell` is `repr(transparent)` over `Task`. - Self::schedule(unsafe { T::field_of(this.as_ptr()) }.cast::()); + /// Queue `this`'s embedded [`SharedWorkNode`]; the pool owns `this` until + /// [`SharedWorkTask::run_work_task`] receives it. Scheduling a node that is + /// already queued is a bug: it asserts in debug and is otherwise a no-op. + pub fn schedule_shared(this: bun_ptr::RefPtr) { + let this = bun_ptr::RefPtr::into_raw(this); + // SAFETY: `this` is live (we hold the reference just unwrapped), so the + // projection is in bounds. + let node: &SharedWorkNode = unsafe { &*T::field_of(this) }; + if node.queued.swap(true, core::sync::atomic::Ordering::AcqRel) { + debug_assert!(false, "SharedWorkTask scheduled while already queued"); + // SAFETY: the reference unwrapped above, not handed to the pool. + drop(unsafe { bun_ptr::RefPtr::from_raw(this) }); + return; + } + Self::schedule(node.task.get()); } /// Schedule a heap-allocated task by value. The pool takes ownership of From 30aaf0ec5ba15602281af35dae88addcaaef1fcc Mon Sep 17 00:00:00 2001 From: Jarred Sumner Date: Thu, 27 Aug 2026 09:52:08 +0000 Subject: [PATCH 05/11] SharedWorkNode::arm keeps whole-allocation provenance; drop AutoDeinit; Miri test for SharedWorkTask --- src/codegen/generate-host-exports.ts | 2 +- src/event_loop/ConcurrentTask.rs | 14 +-- src/runtime/shell/builtin/rm.rs | 4 +- src/runtime/shell/interpreter.rs | 4 +- src/runtime/webcore/fetch/FetchTasklet.rs | 11 +- src/runtime/webcore/s3/download_stream.rs | 10 +- src/runtime/webcore/s3/simple_request.rs | 12 +-- src/threading/work_pool.rs | 116 ++++++++++++++++++---- 8 files changed, 113 insertions(+), 60 deletions(-) diff --git a/src/codegen/generate-host-exports.ts b/src/codegen/generate-host-exports.ts index d2d6a7f658b3..8f17d7a28a33 100644 --- a/src/codegen/generate-host-exports.ts +++ b/src/codegen/generate-host-exports.ts @@ -157,7 +157,7 @@ function ptrify(ty: string): { cTy: string; deref: (n: string) => string; extraL } // Other slice shapes (`&'a [T]`) and `&str` are NOT FFI-safe; reject. if (/^&[^\[]*\[/.test(ty) || /^&\s*str\b/.test(ty)) { - throw new Error(`slice/str param \`${ty}\` is not FFI-safe; use \`&[T]\` (const) or (ptr, len)`); + throw new Error(`slice/str param \`${ty}\` is not FFI-safe; use \`&[T]\` / \`&mut [T]\` or (ptr, len)`); } // `&mut T` / `&T` — keep as a reference in the thunk signature. `&T` and // `*const T` (resp. `&mut T`/`*mut T`) are ABI-identical for `extern "C"` diff --git a/src/event_loop/ConcurrentTask.rs b/src/event_loop/ConcurrentTask.rs index ec1ba1d049c5..b7cd861bb7a9 100644 --- a/src/event_loop/ConcurrentTask.rs +++ b/src/event_loop/ConcurrentTask.rs @@ -367,12 +367,6 @@ unsafe impl Linked for ConcurrentTask { } pub type Queue = UnboundedQueue; -#[derive(Copy, Clone, Eq, PartialEq)] -pub enum AutoDeinit { - ManualDeinit, - AutoDeinit, -} - impl ConcurrentTask { /// Heap-allocate a ConcurrentTask and return a raw pointer. /// The pointer is intrusive (linked into `Queue`), so we use `heap::alloc` rather than `Box`. @@ -450,12 +444,8 @@ impl ConcurrentTask { Self::create(ManagedTask::ManagedTask::new(ptr, callback)) } - pub fn from( - &mut self, - of: *mut T, - auto_deinit: AutoDeinit, - ) -> &mut ConcurrentTask { - debug_assert!(auto_deinit == AutoDeinit::ManualDeinit); + /// Load this intrusive carrier with `of`'s task, ready to post. + pub fn from(&mut self, of: *mut T) -> &mut ConcurrentTask { self.from_task(Task::init(of)) } diff --git a/src/runtime/shell/builtin/rm.rs b/src/runtime/shell/builtin/rm.rs index f3ca95379533..2094b62dd508 100644 --- a/src/runtime/shell/builtin/rm.rs +++ b/src/runtime/shell/builtin/rm.rs @@ -1495,7 +1495,7 @@ impl DirTask { /// `this` is a live DirTask; the pending-main-callback count on the /// owning ShellRmTask was bumped before calling. unsafe fn queue_for_write(this: *mut DirTask) { - use bun_event_loop::{ConcurrentTask::AutoDeinit, EventLoopTask}; + use bun_event_loop::EventLoopTask; // SAFETY: caller contract — `this` is live; `task_manager` is live // (pending count > 0). On the early-return path `deinit` reclaims a // non-root Box and `decr_pending_and_maybe_deinit` releases the @@ -1525,7 +1525,7 @@ impl DirTask { }; match &mut me.concurrent_task { EventLoopTask::Js(ct) => { - ct.from(this, AutoDeinit::ManualDeinit); + ct.from(this); poster.post_js(core::ptr::NonNull::from(ct)); } EventLoopTask::Mini(at) => { diff --git a/src/runtime/shell/interpreter.rs b/src/runtime/shell/interpreter.rs index 3cdf1eba50c1..8fa344dbe98d 100644 --- a/src/runtime/shell/interpreter.rs +++ b/src/runtime/shell/interpreter.rs @@ -2813,7 +2813,7 @@ impl ShellTask { /// [`schedule`](Self::schedule); not touched again on the worker thread /// after this returns. pub(crate) unsafe fn on_finish(ctx: *mut C) { - use bun_event_loop::{ConcurrentTask::AutoDeinit, EventLoopTask}; + use bun_event_loop::EventLoopTask; log!("ShellTask onFinish"); // SAFETY: caller contract — `ctx` embeds `ShellTask` at `TASK_OFFSET`. // Stay on raw pointers: once `enqueue_task_concurrent` returns, the @@ -2830,7 +2830,7 @@ impl ShellTask { match &mut (*this).concurrent_task { EventLoopTask::Js(ct) => { // Tag resolved via `C: Taskable`. - ct.from(ctx, AutoDeinit::ManualDeinit); + ct.from(ctx); poster.post_js(core::ptr::NonNull::from(ct)); } EventLoopTask::Mini(at) => { diff --git a/src/runtime/webcore/fetch/FetchTasklet.rs b/src/runtime/webcore/fetch/FetchTasklet.rs index fd72c2b4d30b..4dec639e3461 100644 --- a/src/runtime/webcore/fetch/FetchTasklet.rs +++ b/src/runtime/webcore/fetch/FetchTasklet.rs @@ -5,10 +5,7 @@ use core::sync::atomic::{AtomicBool, Ordering}; use bun_boringssl as boringssl; use bun_cares_sys::c_ares_draft as c_ares; use bun_core::{MutableString, String as BunString}; -use bun_event_loop::{ - ConcurrentTask::{AutoDeinit, ConcurrentTask}, - Task, Taskable, -}; +use bun_event_loop::{ConcurrentTask::ConcurrentTask, Task, Taskable}; use bun_http as http; use bun_http::Method; use bun_http::{ @@ -2459,11 +2456,7 @@ impl FetchTasklet { } } // will deinit when done with the http client (when is_done = true) - let ct = core::ptr::NonNull::from( - task_ref - .concurrent_task - .from(task, AutoDeinit::ManualDeinit), - ); + let ct = core::ptr::NonNull::from(task_ref.concurrent_task.from(task)); // `ct` is the inline `concurrent_task` field of the heap tasklet; the // queue takes ownership of its `next` link. This thread's ref keeps the // tasklet (and the ticket in it) alive across the post. diff --git a/src/runtime/webcore/s3/download_stream.rs b/src/runtime/webcore/s3/download_stream.rs index 1025d73b98c6..4ac7ac5e865c 100644 --- a/src/runtime/webcore/s3/download_stream.rs +++ b/src/runtime/webcore/s3/download_stream.rs @@ -3,7 +3,7 @@ use core::ptr::NonNull; use core::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use bun_core::MutableString; -use bun_event_loop::ConcurrentTask::{AutoDeinit, ConcurrentTask}; +use bun_event_loop::ConcurrentTask::ConcurrentTask; use bun_event_loop::{TaskTag, Taskable, task_tag}; use bun_http::{AsyncHTTP, HTTPClientResult, Headers, Signals}; use bun_io::KeepAlive; @@ -317,9 +317,7 @@ impl S3HttpDownloadStreamingTask { // this heap request and the queue takes ownership of its `next` link. Not done ⇒ // `this` (and the ticket in it) outlives the post. unsafe { - let task = core::ptr::NonNull::from( - (*this).concurrent_task.from(this, AutoDeinit::ManualDeinit), - ); + let task = core::ptr::NonNull::from((*this).concurrent_task.from(this)); done_ticket .as_ref() .unwrap_or_else(|| (*this).http_ticket.as_ref().expect(Self::HOLDS_TICKET)) @@ -355,9 +353,7 @@ impl S3HttpDownloadStreamingTask { .is_ok() }; if should_enqueue { - let task = core::ptr::NonNull::from( - (*this).concurrent_task.from(this, AutoDeinit::ManualDeinit), - ); + let task = core::ptr::NonNull::from((*this).concurrent_task.from(this)); ticket.post(task); } drop(ticket); diff --git a/src/runtime/webcore/s3/simple_request.rs b/src/runtime/webcore/s3/simple_request.rs index a05b3e529091..30effdca8dc1 100644 --- a/src/runtime/webcore/s3/simple_request.rs +++ b/src/runtime/webcore/s3/simple_request.rs @@ -2,7 +2,7 @@ use core::ffi::c_void; use core::sync::atomic::Ordering; use bun_core::MutableString; -use bun_event_loop::ConcurrentTask::{AutoDeinit, ConcurrentTask}; +use bun_event_loop::ConcurrentTask::ConcurrentTask; use bun_event_loop::{TaskTag, Taskable, task_tag}; use bun_http::async_http::Options as HttpOptions; use bun_http::{ @@ -288,7 +288,7 @@ impl S3HttpSimpleTask { crate::jsc_hooks::ActiveHandle::S3Request(core::ptr::NonNull::new(this).expect("task")) .unregister(); // SAFETY: `this` was produced by `S3HttpSimpleTask::new` (heap::alloc) and ownership is - // reclaimed here exactly once via the ConcurrentTask `AutoDeinit::ManualDeinit` contract; + // reclaimed here exactly once via the intrusive (container-owned) ConcurrentTask; // `this` is dropped at scope exit. let mut this = unsafe { bun_core::heap::take(this) }; @@ -434,9 +434,7 @@ impl S3HttpSimpleTask { // JS thread may free `this` the moment it is queued. unsafe { let ticket = (*this).http_ticket.take().expect(Self::HOLDS_TICKET); - let queued = core::ptr::NonNull::from( - (*this).concurrent_task.from(this, AutoDeinit::ManualDeinit), - ); + let queued = core::ptr::NonNull::from((*this).concurrent_task.from(this)); ticket.post(queued); } } @@ -455,9 +453,7 @@ impl S3HttpSimpleTask { (*this).result.fail = Some(bun_http::Error::Aborted); (*this).result.has_more = false; let ticket = (*this).http_ticket.take().expect(Self::HOLDS_TICKET); - let queued = core::ptr::NonNull::from( - (*this).concurrent_task.from(this, AutoDeinit::ManualDeinit), - ); + let queued = core::ptr::NonNull::from((*this).concurrent_task.from(this)); ticket.post(queued); } } diff --git a/src/threading/work_pool.rs b/src/threading/work_pool.rs index 8da30dacfdb8..64c6b59f6287 100644 --- a/src/threading/work_pool.rs +++ b/src/threading/work_pool.rs @@ -72,18 +72,19 @@ impl SharedWorkNode { /// # Safety /// Only installed by [`SharedWorkNode::new`], so `task` is the node /// embedded in a live `T` that [`WorkPool::schedule_shared`] queued - /// together with one reference. + /// together with one reference, reached through a pointer with the + /// whole `T`'s provenance. unsafe fn run(task: *mut Task) { - // SAFETY: fn contract (`UnsafeCell` is `repr(transparent)` - // over `Task`, and `task` is `SharedWorkNode`'s first field). - let (node, this) = unsafe { + // SAFETY: fn contract; `task` is `SharedWorkNode`'s first field + // (repr(C), `UnsafeCell` is transparent). Raw projections only, so + // the pointer keeps the allocation's provenance for `from_raw`. + let this = unsafe { let node = task.cast::(); - (&*node, T::from_field_ptr(node)) + (*core::ptr::addr_of!((*node).queued)) + .store(false, core::sync::atomic::Ordering::Release); + bun_ptr::RefPtr::from_raw(T::from_field_ptr(node)) }; - node.queued - .store(false, core::sync::atomic::Ordering::Release); - // SAFETY: fn contract — `schedule_shared` moved this reference into the pool. - T::run_work_task(unsafe { bun_ptr::RefPtr::from_raw(this) }); + T::run_work_task(this); } SharedWorkNode { task: core::cell::UnsafeCell::new(Task { @@ -93,6 +94,29 @@ impl SharedWorkNode { queued: core::sync::atomic::AtomicBool::new(false), } } + + /// Move `this` into its node for the pool: the node's `Task` to hand to + /// the pool (its callback takes the reference back out), or `None` if the + /// node is already queued (a bug: asserts in debug; the reference is dropped). + pub fn arm(this: bun_ptr::RefPtr) -> Option<*mut Task> { + let this = bun_ptr::RefPtr::into_raw(this); + // SAFETY: `this` is live (the reference just unwrapped). Raw + // projections only, so the `Task` pointer the pool gets keeps the + // whole allocation's provenance for the callback's container-of. + unsafe { + let node: *mut SharedWorkNode = T::field_of(this); + if (*core::ptr::addr_of!((*node).queued)) + .swap(true, core::sync::atomic::Ordering::AcqRel) + { + debug_assert!(false, "SharedWorkTask scheduled while already queued"); + drop(bun_ptr::RefPtr::from_raw(this)); + return None; + } + Some(core::cell::UnsafeCell::raw_get(core::ptr::addr_of!( + (*node).task + ))) + } + } } /// Implements [`SharedWorkTask`] for a refcounted struct that embeds a @@ -230,17 +254,9 @@ impl WorkPool { /// [`SharedWorkTask::run_work_task`] receives it. Scheduling a node that is /// already queued is a bug: it asserts in debug and is otherwise a no-op. pub fn schedule_shared(this: bun_ptr::RefPtr) { - let this = bun_ptr::RefPtr::into_raw(this); - // SAFETY: `this` is live (we hold the reference just unwrapped), so the - // projection is in bounds. - let node: &SharedWorkNode = unsafe { &*T::field_of(this) }; - if node.queued.swap(true, core::sync::atomic::Ordering::AcqRel) { - debug_assert!(false, "SharedWorkTask scheduled while already queued"); - // SAFETY: the reference unwrapped above, not handed to the pool. - drop(unsafe { bun_ptr::RefPtr::from_raw(this) }); - return; + if let Some(task) = SharedWorkNode::arm(this) { + Self::schedule(task); } - Self::schedule(node.task.get()); } /// Schedule a heap-allocated task by value. The pool takes ownership of @@ -301,3 +317,65 @@ impl WorkPool { Ok(()) } } + +#[cfg(test)] +mod tests { + use super::*; + use core::cell::Cell; + use core::sync::atomic::{AtomicUsize, Ordering}; + + static RUNS: AtomicUsize = AtomicUsize::new(0); + static DROPS: AtomicUsize = AtomicUsize::new(0); + + #[derive(bun_ptr::ThreadSafeRefCounted)] + struct Work { + ref_count: bun_ptr::ThreadSafeRefCount, + before: Cell, + task: SharedWorkNode, + after: Cell, + } + crate::shared_work_task!(Work, task); + impl Work { + fn run_work_task(this: bun_ptr::RefPtr) { + this.after.set(this.before.get() + this.after.get()); + RUNS.fetch_add(1, Ordering::SeqCst); + drop(this); + } + } + impl Drop for Work { + fn drop(&mut self) { + DROPS.fetch_add(1, Ordering::SeqCst); + } + } + + /// The pool's part: invoke the node's callback with the `Task` pointer. + fn fake_pool(task: *mut Task) { + // SAFETY: `task` came from `SharedWorkNode::arm`. + unsafe { ((*task).callback)(task) }; + } + + #[test] + fn shared_work_task_round_trip() { + let work = bun_ptr::RefPtr::new(Work { + ref_count: bun_ptr::ThreadSafeRefCount::init(), + before: Cell::new(7), + task: SharedWorkNode::new::(), + after: Cell::new(1), + }); + let task = SharedWorkNode::arm(work.clone()).expect("not queued"); + // Other holders keep using the value while it is queued. + work.before.set(41); + fake_pool(task); + assert_eq!(work.after.get(), 42); + assert_eq!(RUNS.load(Ordering::SeqCst), 1); + assert_eq!(DROPS.load(Ordering::SeqCst), 0); + + // Re-armed after the callback cleared `queued`; the pool's reference + // is the last one this time. + let task = SharedWorkNode::arm(work).expect("not queued"); + assert_eq!(DROPS.load(Ordering::SeqCst), 0); + fake_pool(task); + assert_eq!(RUNS.load(Ordering::SeqCst), 2); + assert_eq!(DROPS.load(Ordering::SeqCst), 1); + } +} From 1231a96fec1776d3045d4ac1bd35ff6d4f78477c Mon Sep 17 00:00:00 2001 From: Jarred Sumner Date: Sat, 29 Aug 2026 08:30:57 +0000 Subject: [PATCH 06/11] ConcurrentTask test: underscore field instead of allow(dead_code) --- src/event_loop/ConcurrentTask.rs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/event_loop/ConcurrentTask.rs b/src/event_loop/ConcurrentTask.rs index b7cd861bb7a9..c1390b76ffff 100644 --- a/src/event_loop/ConcurrentTask.rs +++ b/src/event_loop/ConcurrentTask.rs @@ -513,7 +513,9 @@ mod tests { static REFUSED: AtomicUsize = AtomicUsize::new(0); static DROPPED: AtomicUsize = AtomicUsize::new(0); - struct Payload(#[allow(dead_code)] Box<[u8; 64]>); + struct Payload { + _buf: Box<[u8; 64]>, + } impl Drop for Payload { fn drop(&mut self) { DROPPED.fetch_add(1, Ordering::SeqCst); @@ -528,14 +530,20 @@ mod tests { #[test] fn refused_boxed_carrier_releases_its_payload() { - let carrier = ConcurrentTask::create_boxed(Box::new(Payload(Box::new([7; 64])))); + let carrier = ConcurrentTask::create_boxed(Box::new(Payload { + _buf: Box::new([7; 64]), + })); // SAFETY: never queued; ours. unsafe { ConcurrentTask::release_refused(carrier) }; assert_eq!(REFUSED.load(Ordering::SeqCst), 1); assert_eq!(DROPPED.load(Ordering::SeqCst), 1); - let mut intrusive = - ConcurrentTask::intrusive(Box::new(Payload(Box::new([7; 64]))).into_task()); + let mut intrusive = ConcurrentTask::intrusive( + Box::new(Payload { + _buf: Box::new([7; 64]), + }) + .into_task(), + ); // SAFETY: never queued; an intrusive carrier is left alone. unsafe { ConcurrentTask::release_refused(core::ptr::NonNull::from(&mut intrusive)) }; assert_eq!(DROPPED.load(Ordering::SeqCst), 1); From 5db8efd6f28861ab4dc1a09d16f8e51868a50477 Mon Sep 17 00:00:00 2001 From: Jarred Sumner Date: Sat, 29 Aug 2026 09:09:22 +0000 Subject: [PATCH 07/11] SharedWorkTask/TaskHop/BoxedTask: implementors write their own unsafe impl; drop the macros that hid it --- src/event_loop/ConcurrentTask.rs | 70 +++----------- src/runtime/napi/napi_body.rs | 95 ++++++++++++------- src/threading/work_pool.rs | 30 ++---- .../vm-thread-door.inventory.json | 2 +- .../source-lints/vm-thread-door.test.ts | 4 +- 5 files changed, 86 insertions(+), 115 deletions(-) diff --git a/src/event_loop/ConcurrentTask.rs b/src/event_loop/ConcurrentTask.rs index c1390b76ffff..2e58b9a46186 100644 --- a/src/event_loop/ConcurrentTask.rs +++ b/src/event_loop/ConcurrentTask.rs @@ -167,8 +167,8 @@ pub trait Taskable { /// A task whose queued pointer is a [`ThisPtr`](bun_ptr::ThisPtr) to /// `Target`, which keeps itself alive for the task; the dispatcher runs it or -/// releases it through here. A zero-sized hop type per tag, declared with -/// [`task_hop!`] next to `Target` so the ref protocol lives there. +/// releases it through here. A zero-sized hop type per tag, declared next to +/// `Target` with its own `unsafe impl` stating the ref protocol. /// /// # Safety /// `TAG` is dispatched (in `bun_runtime::dispatch`) to this impl and no other @@ -190,34 +190,9 @@ pub unsafe trait TaskHop { } } -/// Declares `$hop`, the [`TaskHop`] that `task_tag::$tag` dispatches to for -/// `$target`, forwarding to `$run` / `$release`. The doc comment on the -/// invocation is where `$target`'s liveness protocol for the queued task is -/// stated. -#[macro_export] -macro_rules! task_hop { - ($(#[$m:meta])* $v:vis $hop:ident for $target:ty => $tag:ident; run = $run:expr; release_unrun = $release:expr $(;)?) => { - $(#[$m])* - $v struct $hop; - // SAFETY: see macro doc — one hop per tag; the invoker documents the liveness protocol. - unsafe impl $crate::TaskHop for $hop { - type Target = $target; - const TAG: $crate::TaskTag = $crate::task_tag::$tag; - #[inline] - fn run(this: ::bun_ptr::ThisPtr<$target>) -> $crate::JsResult<()> { - ($run)(this) - } - #[inline] - fn release_unrun(this: ::bun_ptr::ThisPtr<$target>) { - ($release)(this) - } - } - }; -} - /// A task that owns its payload: queued as the `Box` leaked into /// [`Task::ptr`], handed back as that box when the dispatcher runs or -/// releases it. Implement via [`boxed_task!`]. +/// releases it. /// /// # Safety /// `TAG` is dispatched (in `bun_runtime::dispatch`) to this impl and no other @@ -242,30 +217,6 @@ pub unsafe trait BoxedTask: Sized { } } -/// Implements [`BoxedTask`] for `$ty` as the task `task_tag::$tag` dispatches -/// to, forwarding to `$run` / `$release` / `$refused` (each `fn(Box<$ty>)`). -#[macro_export] -macro_rules! boxed_task { - ($ty:ty => $tag:ident; run = $run:expr; release_unrun = $release:expr; refused = $refused:expr $(;)?) => { - // SAFETY: see macro doc — one boxed task type per tag. - unsafe impl $crate::BoxedTask for $ty { - const TAG: $crate::TaskTag = $crate::task_tag::$tag; - #[inline] - fn run(self: ::std::boxed::Box) -> $crate::JsResult<()> { - ($run)(self) - } - #[inline] - fn release_unrun(self: ::std::boxed::Box) { - ($release)(self) - } - #[inline] - fn refused(self: ::std::boxed::Box) { - ($refused)(self) - } - } - }; -} - impl TaskTag { /// The tag's identifier, for diagnostics. pub fn name(self) -> &'static str { @@ -521,11 +472,16 @@ mod tests { DROPPED.fetch_add(1, Ordering::SeqCst); } } - crate::boxed_task! { - Payload => NapiFinalizerTask; - run = |_task: Box| Ok(()); - release_unrun = |_task: Box| {}; - refused = |_task: Box| { REFUSED.fetch_add(1, Ordering::SeqCst); }; + // SAFETY: test-only; never dispatched, so the borrowed tag cannot collide. + unsafe impl BoxedTask for Payload { + const TAG: TaskTag = task_tag::NapiFinalizerTask; + fn run(self: Box) -> crate::JsResult<()> { + Ok(()) + } + fn release_unrun(self: Box) {} + fn refused(self: Box) { + REFUSED.fetch_add(1, Ordering::SeqCst); + } } #[test] diff --git a/src/runtime/napi/napi_body.rs b/src/runtime/napi/napi_body.rs index 0f44479c7219..15d76fbafe1b 100644 --- a/src/runtime/napi/napi_body.rs +++ b/src/runtime/napi/napi_body.rs @@ -1175,16 +1175,21 @@ pub struct napi_async_work { poll_ref: Cell, } -// Pool side / JS side split as documented on the struct; the pool's reference -// is dropped on the JS thread (`run_from_js` / `release_unrun`). -bun_threading::shared_work_task!(napi_async_work, task); +bun_core::intrusive_field!(napi_async_work, task: bun_threading::SharedWorkNode); -bun_event_loop::task_hop! { - /// `task_tag::NapiAsyncWork`: the pool is done with a queued work; run its - /// `complete` on the JS thread. The queued task holds `completion_ref`. - pub(crate) AsyncWorkCompletion for napi_async_work => NapiAsyncWork; - run = napi_async_work::run_from_js; - release_unrun = napi_async_work::release_unrun; +/// `task_tag::NapiAsyncWork`: the pool is done with a queued work; run its +/// `complete` on the JS thread. +pub(crate) struct AsyncWorkCompletion; +// SAFETY: the only hop for `NapiAsyncWork`; the queued task holds `completion_ref`. +unsafe impl TaskHop for AsyncWorkCompletion { + type Target = napi_async_work; + const TAG: bun_event_loop::TaskTag = bun_event_loop::task_tag::NapiAsyncWork; + fn run(this: ThisPtr) -> JsResult<()> { + napi_async_work::run_from_js(this) + } + fn release_unrun(this: ThisPtr) { + napi_async_work::release_unrun(this) + } } impl napi_async_work { @@ -1269,7 +1274,14 @@ impl napi_async_work { complete(env.get(), status as napi_status, data); env.surface_exception(env.to_js()) } +} +// SAFETY: the pool/JS split documented on the struct: `run_work_task` takes +// `ticket`, races `status` atomically, reads `env`/`execute`/`data`, and sets +// `concurrent_task`/`completion_ref`, which the JS thread leaves alone until the +// completion arrives; the pool's reference rides that completion and is dropped +// on the JS thread (`run_from_js` / `release_unrun`). +unsafe impl bun_threading::SharedWorkTask for napi_async_work { /// Pool thread: run `execute` (unless the VM is already stopping, which /// cancels work it has not started, as Node's environment cleanup does /// with `uv_cancel`) and post the work back to the JS thread for @@ -1700,21 +1712,33 @@ pub(crate) enum DispatchState { Pending, } -bun_event_loop::task_hop! { - /// `task_tag::ThreadSafeFunction`: drain the queued calls on the JS thread. - /// The queued task holds `TsfnShared::dispatch_ref`. - pub(crate) TsfnDispatch for ThreadSafeFunction => ThreadSafeFunction; - run = ThreadSafeFunction::run_dispatch_task; - release_unrun = ThreadSafeFunction::release_dispatch_task; +/// `task_tag::ThreadSafeFunction`: drain the queued calls on the JS thread. +pub(crate) struct TsfnDispatch; +// SAFETY: the only hop for `ThreadSafeFunction`; the queued task holds `TsfnShared::dispatch_ref`. +unsafe impl TaskHop for TsfnDispatch { + type Target = ThreadSafeFunction; + const TAG: bun_event_loop::TaskTag = bun_event_loop::task_tag::ThreadSafeFunction; + fn run(this: ThisPtr) -> JsResult<()> { + ThreadSafeFunction::run_dispatch_task(this) + } + fn release_unrun(this: ThisPtr) { + ThreadSafeFunction::release_dispatch_task(this) + } } -bun_event_loop::task_hop! { - /// `task_tag::ThreadSafeFunctionFinalize`: the last thread reference is gone - /// and the queue drained; run the addon's finalizer and let the JS side go. - /// The queued task holds `TsfnJs::finalize_ref`. - pub(crate) TsfnFinalize for ThreadSafeFunction => ThreadSafeFunctionFinalize; - run = ThreadSafeFunction::run_finalize_task; - release_unrun = ThreadSafeFunction::release_finalize_task; +/// `task_tag::ThreadSafeFunctionFinalize`: the last thread reference is gone +/// and the queue drained; run the addon's finalizer and let the JS side go. +pub(crate) struct TsfnFinalize; +// SAFETY: the only hop for `ThreadSafeFunctionFinalize`; the queued task holds `TsfnJs::finalize_ref`. +unsafe impl TaskHop for TsfnFinalize { + type Target = ThreadSafeFunction; + const TAG: bun_event_loop::TaskTag = bun_event_loop::task_tag::ThreadSafeFunctionFinalize; + fn run(this: ThisPtr) -> JsResult<()> { + ThreadSafeFunction::run_finalize_task(this) + } + fn release_unrun(this: ThisPtr) { + ThreadSafeFunction::release_finalize_task(this) + } } /// Live `ThreadSafeFunction` allocations, process-wide. @@ -2589,16 +2613,23 @@ pub(crate) struct NapiFinalizerTask { pub(crate) finalizer: Finalizer, } -// `task_tag::NapiFinalizerTask`: run one deferred addon finalizer. One released -// unrun (the loop stopped first) runs too: Node runs an addon's finalizers -// during environment cleanup (script already forbidden), and an addon counts -// on them (external buffers freed when a Worker exits). `Err` is left pending -// for the release dispatcher's fold. -bun_event_loop::boxed_task! { - NapiFinalizerTask => NapiFinalizerTask; - run = |task: Box| (*task).run_finalizer(); - release_unrun = |task: Box| { let _ = (*task).run_finalizer(); }; - refused = |task: Box| (*task).refused(); +// SAFETY: the only task type for `task_tag::NapiFinalizerTask`. +unsafe impl BoxedTask for NapiFinalizerTask { + const TAG: bun_event_loop::TaskTag = bun_event_loop::task_tag::NapiFinalizerTask; + /// Run one deferred addon finalizer. + fn run(self: Box) -> JsResult<()> { + (*self).run_finalizer() + } + /// One released unrun (the loop stopped first) runs too: Node runs an + /// addon's finalizers during environment cleanup (script already + /// forbidden), and an addon counts on them (external buffers freed when a + /// Worker exits). `Err` is left pending for the release dispatcher's fold. + fn release_unrun(self: Box) { + let _ = (*self).run_finalizer(); + } + fn refused(self: Box) { + (*self).refused() + } } impl OwnedCleanupHook for NapiFinalizerTask { diff --git a/src/threading/work_pool.rs b/src/threading/work_pool.rs index 64c6b59f6287..8359a476d014 100644 --- a/src/threading/work_pool.rs +++ b/src/threading/work_pool.rs @@ -42,8 +42,9 @@ pub unsafe trait IntrusiveWorkTask: bun_core::IntrusiveField { /// [`SharedWorkNode`]: [`WorkPool::schedule_shared`] moves one reference into /// the pool, and the pool hands that reference to /// [`run_work_task`](Self::run_work_task) on a pool thread, concurrently with -/// whatever other holders still do to `T`. Implement via [`shared_work_task!`], -/// which carries the contract. +/// whatever other holders still do to `T`. Name the node's field with +/// `bun_core::intrusive_field!(T, field: SharedWorkNode)` and write the +/// `unsafe impl` yourself, stating the confinement below next to it. /// /// # Safety /// Every field of `T` is either confined to one side (the pool's @@ -119,25 +120,6 @@ impl SharedWorkNode { } } -/// Implements [`SharedWorkTask`] for a refcounted struct that embeds a -/// `$field: SharedWorkNode` and has an inherent -/// `fn run_work_task(this: RefPtr)` (pool thread). The invocation is -/// where the trait's contract is vouched for: say next to it which fields the -/// pool side touches and where the pool's reference is dropped. -#[macro_export] -macro_rules! shared_work_task { - ($ty:ty, $field:ident) => { - ::bun_core::intrusive_field!($ty, $field: $crate::work_pool::SharedWorkNode); - // SAFETY: see macro doc — the invoker states the confinement at the call site. - unsafe impl $crate::work_pool::SharedWorkTask for $ty { - #[inline] - fn run_work_task(this: ::bun_ptr::RefPtr) { - <$ty>::run_work_task(this) - } - } - }; -} - /// An [`IntrusiveWorkTask`] that the [`WorkPool`] takes ownership of by value /// (`Box`). [`WorkPool::schedule_owned`] performs the `Box` → /// raw-pointer hand-off and [`__callback`](OwnedTask::__callback) recovers @@ -334,8 +316,10 @@ mod tests { task: SharedWorkNode, after: Cell, } - crate::shared_work_task!(Work, task); - impl Work { + bun_core::intrusive_field!(Work, task: SharedWorkNode); + // SAFETY: single-threaded test; `run_work_task` touches only `Cell`s the + // holder is not touching at that moment, and `Work` may drop anywhere. + unsafe impl SharedWorkTask for Work { fn run_work_task(this: bun_ptr::RefPtr) { this.after.set(this.before.get() + this.after.get()); RUNS.fetch_add(1, Ordering::SeqCst); diff --git a/test/internal/source-lints/vm-thread-door.inventory.json b/test/internal/source-lints/vm-thread-door.inventory.json index 389e2ea8182e..0e3337d84215 100644 --- a/test/internal/source-lints/vm-thread-door.inventory.json +++ b/test/internal/source-lints/vm-thread-door.inventory.json @@ -118,7 +118,7 @@ }, "src/runtime/napi/napi_body.rs": { "WorkPool::schedule*": 1, - "shared_work_task!": [ + "unsafe impl SharedWorkTask": [ "napi_async_work" ] }, diff --git a/test/internal/source-lints/vm-thread-door.test.ts b/test/internal/source-lints/vm-thread-door.test.ts index 0686b8997f3f..81f776da1cf9 100644 --- a/test/internal/source-lints/vm-thread-door.test.ts +++ b/test/internal/source-lints/vm-thread-door.test.ts @@ -8,7 +8,7 @@ // `sql_jsc`, `http_jsc`), the two things that could open one: // // 1. `unsafe impl Send` / `unsafe impl Sync`, the `owned_task!` macro -// (which emits one), and `intrusive_work_task!` / `shared_work_task!` +// (which emits one), and `intrusive_work_task!` / `unsafe impl SharedWorkTask` // (which are what makes a type schedulable on the pool). `VirtualMachine`, // `EventLoop` and `JSGlobalObject` are `!Send + !Sync`, so VM state can // only reach another thread inside a type someone declared `Send` by hand. @@ -45,7 +45,7 @@ const PATTERNS: [name: string, re: RegExp][] = [ ["unsafe impl Sync", /\bunsafe\s+impl(?:\s*<[^>]*>)?\s+Sync\s+for\s+([A-Za-z_][\w:<>, ']*)/g], ["owned_task!", /\b(?:bun_threading::)?owned_task!\s*\(\s*([A-Za-z_]\w*)/g], ["intrusive_work_task!", /\b(?:bun_threading::)?intrusive_work_task!\s*\(\s*([A-Za-z_]\w*)/g], - ["shared_work_task!", /\b(?:bun_threading::)?shared_work_task!\s*\(\s*([A-Za-z_]\w*)/g], + ["unsafe impl SharedWorkTask", /\bunsafe\s+impl(?:\s*<[^>]*>)?\s+(?:bun_threading::(?:work_pool::)?)?SharedWorkTask\s+for\s+([A-Za-z_][\w:<>, ']*)/g], ["WorkPool::schedule*", /\bWorkPool::(?:schedule|schedule_new|schedule_owned|schedule_shared|go)\b/g], ["worker_pool.schedule(Batch)", /\)\s*\.schedule\(\s*(?:bun_threading::thread_pool::)?Batch::from/g], ["HTTPThread::schedule", /\bHTTPThread::schedule\s*\(/g], From 438125a7d75a87f1af291e34b852e9a65f684067 Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Sat, 29 Aug 2026 09:12:02 +0000 Subject: [PATCH 08/11] [autofix.ci] apply automated fixes --- test/internal/source-lints/vm-thread-door.test.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/test/internal/source-lints/vm-thread-door.test.ts b/test/internal/source-lints/vm-thread-door.test.ts index 81f776da1cf9..1991366a74cc 100644 --- a/test/internal/source-lints/vm-thread-door.test.ts +++ b/test/internal/source-lints/vm-thread-door.test.ts @@ -45,7 +45,10 @@ const PATTERNS: [name: string, re: RegExp][] = [ ["unsafe impl Sync", /\bunsafe\s+impl(?:\s*<[^>]*>)?\s+Sync\s+for\s+([A-Za-z_][\w:<>, ']*)/g], ["owned_task!", /\b(?:bun_threading::)?owned_task!\s*\(\s*([A-Za-z_]\w*)/g], ["intrusive_work_task!", /\b(?:bun_threading::)?intrusive_work_task!\s*\(\s*([A-Za-z_]\w*)/g], - ["unsafe impl SharedWorkTask", /\bunsafe\s+impl(?:\s*<[^>]*>)?\s+(?:bun_threading::(?:work_pool::)?)?SharedWorkTask\s+for\s+([A-Za-z_][\w:<>, ']*)/g], + [ + "unsafe impl SharedWorkTask", + /\bunsafe\s+impl(?:\s*<[^>]*>)?\s+(?:bun_threading::(?:work_pool::)?)?SharedWorkTask\s+for\s+([A-Za-z_][\w:<>, ']*)/g, + ], ["WorkPool::schedule*", /\bWorkPool::(?:schedule|schedule_new|schedule_owned|schedule_shared|go)\b/g], ["worker_pool.schedule(Batch)", /\)\s*\.schedule\(\s*(?:bun_threading::thread_pool::)?Batch::from/g], ["HTTPThread::schedule", /\bHTTPThread::schedule\s*\(/g], From bb47b0097b96c89ade8f2518708fa15935324ca1 Mon Sep 17 00:00:00 2001 From: Jarred Sumner Date: Sun, 6 Sep 2026 19:44:10 +0000 Subject: [PATCH 09/11] napi: adopt main's threadsafe-function finalize timing (#39848) and Bun__napi_* symbol names (#41330) on the RefCounted design: the closing dispatch finalizes whatever thread_count is, the finalizer runs before the JS side is released, a release after close never schedules --- src/runtime/napi/napi_body.rs | 130 ++++++++++++++++++---------------- 1 file changed, 69 insertions(+), 61 deletions(-) diff --git a/src/runtime/napi/napi_body.rs b/src/runtime/napi/napi_body.rs index 15d76fbafe1b..64da91f5a676 100644 --- a/src/runtime/napi/napi_body.rs +++ b/src/runtime/napi/napi_body.rs @@ -40,11 +40,11 @@ bun_output::declare_scope!(napi, visible); unsafe extern "C" { safe fn Bun__JSValue__isAsyncContextFrame(value: JSValue) -> bool; safe fn napi_set_last_error(env: Option<&NapiEnv>, status: NapiStatus) -> napi_status; - safe fn napi_internal_cleanup_env_cpp(env: &NapiEnv); - safe fn napi_internal_check_gc(env: &NapiEnv); + safe fn Bun__napi_cleanup_env_cpp(env: &NapiEnv); + safe fn Bun__napi_check_gc(env: &NapiEnv); /// Drops the env's bookkeeping entry for a finalizer that has run; the /// arguments are compared, not dereferenced. - safe fn napi_internal_remove_finalizer( + safe fn Bun__napi_remove_finalizer( env: &NapiEnv, fun: napi_finalize, hint: *mut c_void, @@ -94,7 +94,7 @@ pub(crate) trait NapiEnvExt { /// Assert that we're not currently performing garbage collection fn check_gc(&self) { - napi_internal_check_gc(self.env()); + Bun__napi_check_gc(self.env()); } /// After a native addon callback (a `complete`, a finalizer, a `call_js`): @@ -1381,7 +1381,7 @@ pub fn napi_fatal_error( message_len_: usize, ) -> ! { bun_output::scoped_log!(napi, "napi_fatal_error"); - napi_internal_suppress_crash_on_abort_if_desired(); + Bun__napi_suppress_crash_on_abort_if_desired(); // SAFETY: the addon's string arguments (N-API contract); null is absent. let (location, message) = unsafe { ( @@ -1538,22 +1538,22 @@ pub fn napi_get_uv_event_loop(env_: Option<&NapiEnv>, loop_: Out(), - napi_internal_register_cleanup_callback, + Bun__napi_register_cleanup_callback, ); } -// HOST_EXPORT(napi_internal_suppress_crash_on_abort_if_desired, c) -pub fn napi_internal_suppress_crash_on_abort_if_desired() { +// HOST_EXPORT(Bun__napi_suppress_crash_on_abort_if_desired, c) +pub fn Bun__napi_suppress_crash_on_abort_if_desired() { if bun_core::env_var::feature_flag::BUN_INTERNAL_SUPPRESS_CRASH_ON_NAPI_ABORT .get() .unwrap_or(false) @@ -1581,7 +1581,7 @@ impl Finalizer { let _hs = NapiHandleScope::open_scoped(env); (self.fun)(env.as_mut_ptr(), self.data, self.hint); - napi_internal_remove_finalizer(env, Some(self.fun), self.hint, self.data); + Bun__napi_remove_finalizer(env, Some(self.fun), self.hint, self.data); env.surface_exception(env.to_js()) } @@ -1595,8 +1595,8 @@ impl Finalizer { /// For Node-API modules not built with NAPI_EXPERIMENTAL, finalizers should be deferred to the /// immediate task queue instead of run immediately. This lets finalizers perform allocations, /// which they couldn't if they ran immediately while the garbage collector is still running. -// HOST_EXPORT(napi_internal_enqueue_finalizer, c) -pub fn napi_internal_enqueue_finalizer( +// HOST_EXPORT(Bun__napi_enqueue_finalizer, c) +pub fn Bun__napi_enqueue_finalizer( env: Option<&NapiEnv>, fun: napi_finalize, data: *mut c_void, @@ -1726,8 +1726,9 @@ unsafe impl TaskHop for TsfnDispatch { } } -/// `task_tag::ThreadSafeFunctionFinalize`: the last thread reference is gone -/// and the queue drained; run the addon's finalizer and let the JS side go. +/// `task_tag::ThreadSafeFunctionFinalize`: the function closed (queue drained +/// with no thread reference left, or aborted); run the addon's finalizer and +/// let the JS side go. pub(crate) struct TsfnFinalize; // SAFETY: the only hop for `ThreadSafeFunctionFinalize`; the queued task holds `TsfnJs::finalize_ref`. unsafe impl TaskHop for TsfnFinalize { @@ -1923,15 +1924,14 @@ impl ThreadSafeFunction { // Closing (napi_tsfn_abort, or the last call already ran): // nothing still queued runs any more, as in Node's DispatchOne. // An abort's leftovers go back to the addon, with no lock held - // since that re-enters it; the function finalizes once the last - // thread reference is gone. + // since that re-enters it. Then it finalizes whatever + // thread_count is: after an abort the other threads may never + // release (Node's CloseHandlesAndMaybeDelete). let leftovers = this.take_queue(&mut shared); drop(shared); this.hand_back(leftovers); let _shared = this.shared.lock(); - if this.thread_count.load(Ordering::SeqCst) == 0 { - Self::maybe_queue_finalizer(this); - } + Self::maybe_queue_finalizer(this); return Ok(false); } let Some(t) = shared.queue.read_item() else { @@ -2137,33 +2137,41 @@ impl ThreadSafeFunction { } } - /// JS thread: the queue drained with no thread references left (Node's - /// Finalize). Queues the addon's finalizer, releases everything JS-affine - /// (see `TsfnJs`) and drops the JS side's reference. + /// JS thread, once the function has closed (Node's Finalize + + /// MaybeDelete): runs the addon's finalizer, which may still use the + /// handle, then releases everything JS-affine (see `TsfnJs`) and drops the + /// JS side's reference. The addon threads' reference, if one is left, + /// keeps the allocation until their last release. fn finalize(this: ThisPtr) { - let (finalizer, env, owner) = this.js.with_mut(|js| { - js.poll_ref.unref(bun_io::js_vm_ctx()); - js.callback = StrongOptional::empty(); - let finalizer = js - .finalizer_fun + let finalizer = this.js.with_mut(|js| { + if let Some(env) = js.env.as_ref() { + // Drops our registry entry so teardown cannot hand this pointer + // out after it is freed. + NapiEnv__unregisterThreadSafeFunction(env, this.as_ptr().cast()); + } + js.finalizer_fun + .take() .zip(js.env.as_ref()) .map(|(fun, env)| Finalizer { env: env.clone(), fun, data: js.finalizer_data, hint: this.ctx, - }); - (finalizer, js.env.take(), js.owner_ref.take()) + }) }); - if let Some(env) = env { - // Drops our registry entry so teardown cannot hand this pointer - // out after it is freed. - NapiEnv__unregisterThreadSafeFunction(&env, this.as_ptr().cast()); - } - if let Some(finalizer) = finalizer { - finalizer.enqueue(); + // Before anything is released, as in Node and `env_teardown`; the + // finalize task is its landing frame. + if let Some(mut finalizer) = finalizer { + crate::dispatch::fold(finalizer.run()); } + + let owner = this.js.with_mut(|js| { + js.poll_ref.unref(bun_io::js_vm_ctx()); + js.callback = StrongOptional::empty(); + drop(js.env.take()); + js.owner_ref.take() + }); drop(owner); } @@ -2300,30 +2308,30 @@ impl ThreadSafeFunction { released.add(shared.threads_ref.take()); } - if this.env_dead.load(Ordering::SeqCst) { - // The event loop we were created on is gone (`env_teardown` set - // this under the lock we hold). Never schedule onto it. + if this.env_dead.load(Ordering::SeqCst) + || this.closing.load(Ordering::SeqCst) == ClosingState::Closed as u8 + { + // The JS thread owns the finalization (`finalize` queued or done, + // or `env_teardown` ran): never schedule onto the loop again. The + // last reference dropped frees the allocation. return NapiStatus::ok as napi_status; } - if mode == napi_threadsafe_function_release_mode::abort || prev_remaining == 1 { - if !this.is_closing() { - if mode == napi_threadsafe_function_release_mode::abort { - this.closing - .store(ClosingState::Closing as u8, Ordering::SeqCst); - if this.max_queue_size > 0 { - // Wake all producers blocked in enqueue()'s bounded - // queue wait so they observe is_closing and release. - this.blocking_condvar.broadcast(); - } + // Already closing: the abort's dispatch is pending or running and + // finalizes whatever thread_count is by then. + if (mode == napi_threadsafe_function_release_mode::abort || prev_remaining == 1) + && !this.is_closing() + { + if mode == napi_threadsafe_function_release_mode::abort { + this.closing + .store(ClosingState::Closing as u8, Ordering::SeqCst); + if this.max_queue_size > 0 { + // Wake all producers blocked in enqueue()'s bounded queue + // wait so they observe is_closing and release. + this.blocking_condvar.broadcast(); } - Self::schedule_dispatch(this, shared, released); - } else if prev_remaining == 1 { - // Already closing from an earlier abort. The last release must - // still reach dispatch_one's thread_count==0 path so the - // finalizer runs and the event-loop keepalive is dropped. - Self::schedule_dispatch(this, shared, released); } + Self::schedule_dispatch(this, shared, released); } NapiStatus::ok as napi_status @@ -2348,8 +2356,8 @@ impl Released { /// Called from `NapiEnv::cleanup()` (JS thread) for every threadsafe function /// still registered with the env that is being torn down. The registry only /// holds live functions (`finalize` and this both remove the entry). -// HOST_EXPORT(napi_internal_threadsafe_function_env_teardown, c) -pub fn napi_internal_threadsafe_function_env_teardown(tsfn: ThisPtr) { +// HOST_EXPORT(Bun__napi_threadsafe_function_env_teardown, c) +pub fn Bun__napi_threadsafe_function_env_teardown(tsfn: ThisPtr) { ThreadSafeFunction::env_teardown(tsfn); } From 21fe89cc195fbaa4fc242c6c863e9ea4002ec39b Mon Sep 17 00:00:00 2001 From: Jarred Sumner Date: Sun, 6 Sep 2026 20:21:04 +0000 Subject: [PATCH 10/11] SharedWorkTask: document that a re-schedule during a run yields an overlapping run --- src/threading/work_pool.rs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/src/threading/work_pool.rs b/src/threading/work_pool.rs index 8359a476d014..41a0f8227d46 100644 --- a/src/threading/work_pool.rs +++ b/src/threading/work_pool.rs @@ -46,12 +46,18 @@ pub unsafe trait IntrusiveWorkTask: bun_core::IntrusiveField { /// `bun_core::intrusive_field!(T, field: SharedWorkNode)` and write the /// `unsafe impl` yourself, stating the confinement below next to it. /// +/// The node is re-armable as soon as the pool picks it up (before +/// `run_work_task` runs), so a re-schedule that races a run is never lost; the +/// price is that a holder which re-schedules while a run is still in progress +/// gets a second, overlapping `run_work_task` on another pool thread. +/// /// # Safety /// Every field of `T` is either confined to one side (the pool's -/// `run_work_task`, or the other holders) while the node is queued, or -/// synchronized — `T` need not be `Sync` otherwise, so the type system does not -/// check this; and wherever `run_work_task` lets its reference go must be a -/// thread `T` may be freed on. +/// `run_work_task`, or the other holders) while the node is queued or running, +/// or synchronized — `T` need not be `Sync` otherwise, so the type system does +/// not check this; a `T` that can be re-scheduled before the previous run +/// returns must also tolerate overlapping runs; and wherever `run_work_task` +/// lets its reference go must be a thread `T` may be freed on. pub unsafe trait SharedWorkTask: bun_ptr::AnyRefCounted + bun_core::IntrusiveField { From f040c81ff2215ee322baf4d911eeb6e7a1b83f9a Mon Sep 17 00:00:00 2001 From: Jarred Sumner Date: Tue, 8 Sep 2026 13:07:32 +0000 Subject: [PATCH 11/11] napi: back to the napi_internal_* symbol names now that main reverted #41330 --- src/runtime/napi/napi_body.rs | 36 +++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/src/runtime/napi/napi_body.rs b/src/runtime/napi/napi_body.rs index 64da91f5a676..c561ecae5b2f 100644 --- a/src/runtime/napi/napi_body.rs +++ b/src/runtime/napi/napi_body.rs @@ -40,11 +40,11 @@ bun_output::declare_scope!(napi, visible); unsafe extern "C" { safe fn Bun__JSValue__isAsyncContextFrame(value: JSValue) -> bool; safe fn napi_set_last_error(env: Option<&NapiEnv>, status: NapiStatus) -> napi_status; - safe fn Bun__napi_cleanup_env_cpp(env: &NapiEnv); - safe fn Bun__napi_check_gc(env: &NapiEnv); + safe fn napi_internal_cleanup_env_cpp(env: &NapiEnv); + safe fn napi_internal_check_gc(env: &NapiEnv); /// Drops the env's bookkeeping entry for a finalizer that has run; the /// arguments are compared, not dereferenced. - safe fn Bun__napi_remove_finalizer( + safe fn napi_internal_remove_finalizer( env: &NapiEnv, fun: napi_finalize, hint: *mut c_void, @@ -94,7 +94,7 @@ pub(crate) trait NapiEnvExt { /// Assert that we're not currently performing garbage collection fn check_gc(&self) { - Bun__napi_check_gc(self.env()); + napi_internal_check_gc(self.env()); } /// After a native addon callback (a `complete`, a finalizer, a `call_js`): @@ -1381,7 +1381,7 @@ pub fn napi_fatal_error( message_len_: usize, ) -> ! { bun_output::scoped_log!(napi, "napi_fatal_error"); - Bun__napi_suppress_crash_on_abort_if_desired(); + napi_internal_suppress_crash_on_abort_if_desired(); // SAFETY: the addon's string arguments (N-API contract); null is absent. let (location, message) = unsafe { ( @@ -1538,22 +1538,22 @@ pub fn napi_get_uv_event_loop(env_: Option<&NapiEnv>, loop_: Out(), - Bun__napi_register_cleanup_callback, + napi_internal_register_cleanup_callback, ); } -// HOST_EXPORT(Bun__napi_suppress_crash_on_abort_if_desired, c) -pub fn Bun__napi_suppress_crash_on_abort_if_desired() { +// HOST_EXPORT(napi_internal_suppress_crash_on_abort_if_desired, c) +pub fn napi_internal_suppress_crash_on_abort_if_desired() { if bun_core::env_var::feature_flag::BUN_INTERNAL_SUPPRESS_CRASH_ON_NAPI_ABORT .get() .unwrap_or(false) @@ -1581,7 +1581,7 @@ impl Finalizer { let _hs = NapiHandleScope::open_scoped(env); (self.fun)(env.as_mut_ptr(), self.data, self.hint); - Bun__napi_remove_finalizer(env, Some(self.fun), self.hint, self.data); + napi_internal_remove_finalizer(env, Some(self.fun), self.hint, self.data); env.surface_exception(env.to_js()) } @@ -1595,8 +1595,8 @@ impl Finalizer { /// For Node-API modules not built with NAPI_EXPERIMENTAL, finalizers should be deferred to the /// immediate task queue instead of run immediately. This lets finalizers perform allocations, /// which they couldn't if they ran immediately while the garbage collector is still running. -// HOST_EXPORT(Bun__napi_enqueue_finalizer, c) -pub fn Bun__napi_enqueue_finalizer( +// HOST_EXPORT(napi_internal_enqueue_finalizer, c) +pub fn napi_internal_enqueue_finalizer( env: Option<&NapiEnv>, fun: napi_finalize, data: *mut c_void, @@ -2356,8 +2356,8 @@ impl Released { /// Called from `NapiEnv::cleanup()` (JS thread) for every threadsafe function /// still registered with the env that is being torn down. The registry only /// holds live functions (`finalize` and this both remove the entry). -// HOST_EXPORT(Bun__napi_threadsafe_function_env_teardown, c) -pub fn Bun__napi_threadsafe_function_env_teardown(tsfn: ThisPtr) { +// HOST_EXPORT(napi_internal_threadsafe_function_env_teardown, c) +pub fn napi_internal_threadsafe_function_env_teardown(tsfn: ThisPtr) { ThreadSafeFunction::env_teardown(tsfn); }