Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions src/jsc/VirtualMachine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1732,11 +1732,23 @@ impl VirtualMachine {
|| self.should_destruct_main_thread_on_exit()
}

/// Whether an env's cleanup may turn the event loop to wait for the addon's
/// async cleanup hooks (`NapiEnv::drain`). Of the exits that tear the envs
/// down, only a requested main-thread exit under `BUN_DESTRUCT_VM_ON_EXIT`
/// may not: Node runs no cleanup hooks there at all, so nothing can depend
/// on the wait, and the exit stays immediate.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub fn exit_waits_for_cleanup(&self) -> bool {
!self.is_main_thread() || !self.exit_handler.requested
}

/// Drains `RareData::cleanup_hooks`, repeating while the hooks push more (an env's
/// cleanup defers finalizers onto this list once shutdown has begun). The `Vec` is
/// taken out of `rare_data` before the hooks run: they re-enter the VM.
fn run_cleanup_hooks(&mut self) {
/// taken out of `rare_data` before the hooks run: they re-enter the VM. Also called
/// on each loop turn an env's cleanup makes while it waits for the addon's async
/// cleanup hooks (`napi_internal_tick_event_loop`).
Comment thread
robobun marked this conversation as resolved.
Resolved
pub fn run_cleanup_hooks(&mut self) {
loop {
// The hooks re-enter the VM, so no borrow of `rare_data` is held while they run.
let hooks = match self.rare_data.as_deref_mut() {
Some(rare) if !rare.cleanup_hooks.is_empty() => {
core::mem::take(&mut rare.cleanup_hooks)
Expand Down
8 changes: 8 additions & 0 deletions src/jsc/bindings/napi.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3372,6 +3372,14 @@ extern "C" JS_EXPORT napi_status napi_remove_async_cleanup_hook(napi_async_clean
}

napi_env env = handle->env;

if (handle->started.load(std::memory_order_acquire)) {
// The hook's completion, possibly from another thread: no preamble and no
// last-error write (Node's version touches no env state either).
Comment thread
robobun marked this conversation as resolved.
Resolved
env->asyncCleanupHookCompleted(handle);
return napi_ok;
}

NAPI_PREAMBLE_NO_PENDING_CHECK(env);

// Always attempt removal like Node.js (no VM terminating check)
Expand Down
68 changes: 64 additions & 4 deletions src/jsc/bindings/napi.h
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,14 @@
#include <wtf/ListHashSet.h>
#include <wtf/Lock.h>

#include <atomic>
#include <optional>
#include <unordered_set>
#include <variant>

extern "C" void napi_internal_register_cleanup_zig(napi_env env);
extern "C" bool napi_internal_exit_waits_for_cleanup_hooks(napi_env env);
extern "C" void napi_internal_tick_event_loop(napi_env env);
extern "C" void napi_internal_threadsafe_function_env_teardown(void* tsfn);
extern "C" void napi_internal_suppress_crash_on_abort_if_desired();
extern "C" void Bun__crashHandler(const char* message, size_t message_len);
Expand Down Expand Up @@ -124,6 +127,9 @@ napi_status defineProperty(napi_env env, JSC::JSObject* to, const napi_property_
// itself has already run (that call is how it signals completion).
struct napi_async_cleanup_hook_handle__ {
napi_env env;
// Set by NapiEnv::drain() before it calls the hook: from then on, removing the
// handle is the completion drain() waits for (Node: AsyncCleanupHookInfo::started).
Comment thread
robobun marked this conversation as resolved.
Resolved
std::atomic<bool> started { false };

explicit napi_async_cleanup_hook_handle__(napi_env env)
: env(env)
Expand Down Expand Up @@ -365,9 +371,11 @@ struct NapiEnv : public WTF::RefCounted<NapiEnv> {
return handle.release();
}

// napi_remove_async_cleanup_hook on a hook drain() has not called: unregister it.
// The caller has already rejected null handles (napi_invalid_arg).
void removeAsyncCleanupHook(napi_async_cleanup_hook_handle handle)
{
ASSERT(!handle->started.load(std::memory_order_relaxed));
for (auto iter = m_cleanupHooks.begin(), end = m_cleanupHooks.end(); iter != end; ++iter) {
if (auto* async = std::get_if<Napi::AsyncCleanupHook>(&*iter)) {
if (async->handle == handle) {
Expand All @@ -377,11 +385,25 @@ struct NapiEnv : public WTF::RefCounted<NapiEnv> {
}
}

// Freed unconditionally, matching Node: for an already-drained hook
// this call is the addon's completion signal.
// Freed unconditionally, matching Node (a handle is removed at most once).
delete handle;
}

// napi_remove_async_cleanup_hook on a hook drain() has called, from any thread
// (Node: FinishAsyncCleanupHook). The decrement lets drain() go on and, in a
// worker, free this env: nothing of `this` is used after it.
Comment thread
robobun marked this conversation as resolved.
Resolved
void asyncCleanupHookCompleted(napi_async_cleanup_hook_handle handle)
{
ASSERT(handle->started.load(std::memory_order_relaxed));
delete handle;
const ::BunVmHandleRef* vmHandle = Bun__VmHandle__retainRef(m_vmHandle);
size_t previous = m_asyncCleanupHooksInFlight.fetch_sub(1, std::memory_order_acq_rel);
ASSERT_UNUSED(previous, previous > 0);
// Gives back the keep-alive drain() took for this hook, which also wakes the loop.
Bun__VmHandle__refKeepAlive(vmHandle, BunLoopKind::Regular, -1);
Bun__VmHandle__release(vmHandle);
}

bool inGC() const
{
return this->vm().isCollectorBusyOnCurrentThread();
Expand Down Expand Up @@ -581,6 +603,8 @@ struct NapiEnv : public WTF::RefCounted<NapiEnv> {
Napi::HookSet m_cleanupHooks;
JSC::Strong<JSC::Unknown> m_pendingException;
size_t m_cleanupHookCounter = 0;
// Async cleanup hooks called and not yet completed (Node: request_waiting_).
std::atomic<size_t> m_asyncCleanupHooksInFlight { 0 };

WTF::Lock m_threadSafeFunctionsLock;
WTF::HashSet<void*> m_threadSafeFunctions WTF_GUARDED_BY_LOCK(m_threadSafeFunctionsLock);
Expand All @@ -606,6 +630,7 @@ struct NapiEnv : public WTF::RefCounted<NapiEnv> {
void drain()
{
std::vector<Napi::EitherCleanupHook> hooks = getHooks();
size_t started = 0;

for (const Napi::EitherCleanupHook& hook : hooks) {
if (auto set_iter = m_cleanupHooks.find(hook); set_iter != m_cleanupHooks.end()) {
Expand All @@ -621,14 +646,49 @@ struct NapiEnv : public WTF::RefCounted<NapiEnv> {
} else {
auto& async = std::get<Napi::AsyncCleanupHook>(hook);
ASSERT(async.function != nullptr);
// The addon owns the handle and frees it via
// napi_remove_async_cleanup_hook, possibly after this returns (#37201).
// Counted, and keeping the loop alive (so that the wait below parks
// in its poll), before the call: the hook may complete inside it.
Comment thread
robobun marked this conversation as resolved.
Resolved
m_asyncCleanupHooksInFlight.fetch_add(1, std::memory_order_acq_rel);
// Env teardown runs on the regular loop, never inside a macro.
Bun__VmHandle__refKeepAlive(m_vmHandle, BunLoopKind::Regular, 1);
// A started handle keeps this env allocated (Node: the handle holds a
// reference to the env) for the completion that may still come.
Comment thread
robobun marked this conversation as resolved.
Resolved
ref();
started++;
async.handle->started.store(true, std::memory_order_release);
async.function(async.handle, async.data);
}
// Same invariant as the finalizer loop in cleanup(): a hook
// that leaked an exception must not poison the next hook.
clearExceptionsBetweenFinalizers();
}

if (waitForAsyncCleanupHooks()) {
// The global object's reference keeps `this` alive through cleanup().
while (started--) {
deref();
}
}
}

// After Node's Environment::CleanupHandles(), per env: the batch has been called,
// now the async hooks in it get to finish. Their completions arrive through the
// env's event loop. Unbounded, as in Node: a hook that never completes keeps the
// env alive. False if it returns with hooks still in flight: an exit that does not
// wait for them (see the Rust side of napi_internal_exit_waits_for_cleanup_hooks).
Comment thread
robobun marked this conversation as resolved.
Resolved
bool waitForAsyncCleanupHooks()
{
if (m_asyncCleanupHooksInFlight.load(std::memory_order_acquire) == 0) {
return true;
}
if (!napi_internal_exit_waits_for_cleanup_hooks(this)) {
return false;
}
do {
napi_internal_tick_event_loop(this);
} while (m_asyncCleanupHooksInFlight.load(std::memory_order_acquire) > 0);
clearExceptionsBetweenFinalizers();
return true;
}
Comment thread
robobun marked this conversation as resolved.
Resolved
};

Expand Down
1 change: 1 addition & 0 deletions src/runtime/bake/production.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,7 @@ pub fn build_command(ctx: Context) -> crate::Result<()> {
if vm.exit_handler.exit_code == 0 {
vm.exit_handler.exit_code = 1;
}
vm.exit_handler.requested = true;
vm.on_exit();
vm.global_exit();
}
Expand Down
1 change: 1 addition & 0 deletions src/runtime/cli/repl_command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,7 @@ impl<'a, 'r> ReplRunner<'a, 'r> {
vm.print_error_like_object_to_console(exception);
}
vm.exit_handler.exit_code = 1;
vm.exit_handler.requested = true;
vm.on_exit();
vm.global_exit();
}
Expand Down
Loading
Loading