From 4771e006722766491e381293b5965d41f689029f Mon Sep 17 00:00:00 2001 From: Max schwenk Date: Thu, 12 Nov 2026 02:18:53 -0500 Subject: [PATCH 01/16] deps: add V8 hooks for forking a process with a live isolate Two things go wrong when a process with a live isolate calls fork(2): - With v8_enable_private_mapping_fork_optimization (the Linux default in Node.js) every mapping V8 makes is MADV_DONTFORK, so the child has no heap and crashes at once. V8 now remembers the ranges it marked (trimmed on unmap, so the record stays as small as the live mappings), and v8::MakeMappingsForkable() clears the mark on all of them and stops marking new ones. Processes that never call it keep the optimization. - The child produces the same Math.random() sequences as its parent and its siblings. v8::ReseedRandomNumberGeneratorsAfterFork() reseeds the isolate's generator from fresh entropy and resets the Math.random() state of every native context. It does nothing with --random-seed. Both are declared in a new include/v8-fork.h so that adding them does not change headers that most of V8 includes. --- deps/v8/include/v8-fork.h | 40 +++++++++++ deps/v8/src/api/api.cc | 34 +++++++++ deps/v8/src/base/platform/platform-posix.cc | 77 +++++++++++++++++++-- 3 files changed, 147 insertions(+), 4 deletions(-) create mode 100644 deps/v8/include/v8-fork.h diff --git a/deps/v8/include/v8-fork.h b/deps/v8/include/v8-fork.h new file mode 100644 index 00000000000..6c50b194829 --- /dev/null +++ b/deps/v8/include/v8-fork.h @@ -0,0 +1,40 @@ +// Copyright 2026 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef INCLUDE_V8_FORK_H_ +#define INCLUDE_V8_FORK_H_ + +#include "v8config.h" // NOLINT(build/include_directory) + +namespace v8 { + +class Isolate; + +/** + * Experimental, for embedders that fork(2) a process with a live isolate. + * + * Reseeds the isolate's random number generator from fresh entropy and resets + * the Math.random() state of every native context of the isolate, so that the + * next Math.random() call in each context starts a new sequence. Without this, + * a forked child produces the same Math.random() sequences as its parent and + * its siblings. Does nothing when --random-seed is set (the embedder asked for + * reproducible sequences). Must be called on the isolate's thread. + */ +V8_EXPORT void ReseedRandomNumberGeneratorsAfterFork(Isolate* isolate); + +/** + * Experimental, for embedders that fork(2) a process with a live isolate. + * + * Built with v8_enable_private_mapping_fork_optimization (the Linux default in + * Node.js), V8 marks the memory it maps MADV_DONTFORK, so that fork+exec does + * not copy the page tables of the heap; a forked child then has no heap. This + * clears that mark on every mapping made so far and stops marking new ones, + * for the rest of the process's life (and its forked children's). Cheap after + * the first call. Thread-safe. + */ +V8_EXPORT void MakeMappingsForkable(); + +} // namespace v8 + +#endif // INCLUDE_V8_FORK_H_ diff --git a/deps/v8/src/api/api.cc b/deps/v8/src/api/api.cc index eb3cd7dee28..38d1ece2034 100644 --- a/deps/v8/src/api/api.cc +++ b/deps/v8/src/api/api.cc @@ -22,6 +22,7 @@ #include "include/v8-extension.h" #include "include/v8-external-memory-accounter.h" #include "include/v8-fast-api-calls.h" +#include "include/v8-fork.h" #include "include/v8-function.h" #include "include/v8-json.h" #include "include/v8-locker.h" @@ -89,6 +90,7 @@ #include "src/objects/api-callbacks.h" #include "src/objects/backing-store.h" #include "src/objects/contexts.h" +#include "src/numbers/math-random.h" #include "src/objects/cpp-heap-object-wrapper-inl.h" #include "src/objects/embedder-data-array-inl.h" #include "src/objects/embedder-data-slot-inl.h" @@ -10725,6 +10727,38 @@ void Isolate::Freeze(bool is_frozen) { i_isolate->Freeze(is_frozen); } +#if V8_OS_POSIX +namespace base { +// Defined in src/base/platform/platform-posix.cc. +void MakeMappingsForkable(); +} // namespace base +#endif + +void MakeMappingsForkable() { +#if V8_OS_POSIX + base::MakeMappingsForkable(); +#endif +} + +void ReseedRandomNumberGeneratorsAfterFork(Isolate* isolate) { + i::Isolate* i_isolate = reinterpret_cast(isolate); + // With a fixed seed the embedder asked for reproducible sequences. + if (i::v8_flags.random_seed != 0) return; + // A default-constructed generator draws its seed from the embedder's + // entropy source (or the OS), not from state copied from the parent. + base::RandomNumberGenerator fresh; + i_isolate->random_number_generator()->SetSeed(fresh.NextInt64()); + // Math.random() reseeds a context from the generator above when it finds a + // zero state, see MathRandom::RefillCache(). + i::DisallowGarbageCollection no_gc; + i::Tagged context = i_isolate->heap()->native_contexts_list(); + while (!i::IsUndefined(context, i_isolate)) { + i::Tagged native_context = i::Cast(context); + i::MathRandom::ResetContext(native_context); + context = native_context->next_context_link(); + } +} + void Isolate::IncreaseHeapLimitForDebugging() { // No-op. } diff --git a/deps/v8/src/base/platform/platform-posix.cc b/deps/v8/src/base/platform/platform-posix.cc index 9363910367e..fef32577819 100644 --- a/deps/v8/src/base/platform/platform-posix.cc +++ b/deps/v8/src/base/platform/platform-posix.cc @@ -37,6 +37,8 @@ #include #include +#include +#include #include #include "src/base/lazy-instance.h" @@ -173,6 +175,53 @@ int GetFlagsForMemoryPermission(OS::MemoryPermission access, PageType page_type, return flags; } +#if V8_OS_LINUX && V8_ENABLE_PRIVATE_MAPPING_FORK_OPTIMIZATION +// The ranges this process marked MADV_DONTFORK, so that an embedder that +// forks a process with a live isolate (whose heap lives in them) can make them +// copyable again, see MakeMappingsForkable(). Unmapped ranges are trimmed off, +// so the set stays as small as the set of live mappings. +std::atomic g_mappings_forkable{false}; +LazyMutex g_dontfork_mutex = LAZY_MUTEX_INITIALIZER; +std::map* g_dontfork_ranges = nullptr; // start -> end + +void MarkDontFork(void* address, size_t size) { + if (g_mappings_forkable.load(std::memory_order_relaxed)) return; + MutexGuard guard(g_dontfork_mutex.Pointer()); + if (g_mappings_forkable.load(std::memory_order_relaxed)) return; + // This is advisory, so we ignore errors. + madvise(address, size, MADV_DONTFORK); + if (g_dontfork_ranges == nullptr) { + g_dontfork_ranges = new std::map(); + } + const uintptr_t start = reinterpret_cast(address); + (*g_dontfork_ranges)[start] = start + size; +} + +void ForgetDontFork(void* address, size_t size) { + if (g_mappings_forkable.load(std::memory_order_relaxed)) return; + MutexGuard guard(g_dontfork_mutex.Pointer()); + if (g_dontfork_ranges == nullptr) return; + const uintptr_t start = reinterpret_cast(address); + const uintptr_t end = start + size; + auto it = g_dontfork_ranges->upper_bound(start); + if (it != g_dontfork_ranges->begin()) --it; + while (it != g_dontfork_ranges->end() && it->first < end) { + const uintptr_t range_start = it->first; + const uintptr_t range_end = it->second; + if (range_end <= start) { + ++it; + continue; + } + it = g_dontfork_ranges->erase(it); + if (range_start < start) (*g_dontfork_ranges)[range_start] = start; + if (range_end > end) (*g_dontfork_ranges)[end] = range_end; + } +} +#else +void MarkDontFork(void* address, size_t size) {} +void ForgetDontFork(void* address, size_t size) {} +#endif // V8_OS_LINUX && V8_ENABLE_PRIVATE_MAPPING_FORK_OPTIMIZATION + void* Allocate(void* hint, size_t size, OS::MemoryPermission access, PageType page_type, std::optional handle = std::nullopt, @@ -190,10 +239,7 @@ void* Allocate(void* hint, size_t size, OS::MemoryPermission access, void* result = mmap(hint, size, prot, flags, fd, kMmapFdOffset); if (result == MAP_FAILED) return nullptr; -#if V8_OS_LINUX && V8_ENABLE_PRIVATE_MAPPING_FORK_OPTIMIZATION - // This is advisory, so we ignore errors. - madvise(result, size, MADV_DONTFORK); -#endif + MarkDontFork(result, size); #if ENABLE_HUGEPAGE if (result != nullptr && size >= kHugePageSize) { @@ -217,6 +263,26 @@ void* Allocate(void* hint, size_t size, OS::MemoryPermission access, } // namespace +// Experimental, see v8::MakeMappingsForkable() in include/v8-fork.h: clears +// MADV_DONTFORK on everything this process marked so far and stops marking +// new mappings. Irreversible. +void MakeMappingsForkable() { +#if V8_OS_LINUX && V8_ENABLE_PRIVATE_MAPPING_FORK_OPTIMIZATION + if (g_mappings_forkable.load(std::memory_order_acquire)) return; + MutexGuard guard(g_dontfork_mutex.Pointer()); + if (g_mappings_forkable.load(std::memory_order_relaxed)) return; + if (g_dontfork_ranges != nullptr) { + for (const auto& [start, end] : *g_dontfork_ranges) { + // Advisory; a range that was replaced by another mapping only fails. + madvise(reinterpret_cast(start), end - start, MADV_DOFORK); + } + delete g_dontfork_ranges; + g_dontfork_ranges = nullptr; + } + g_mappings_forkable.store(true, std::memory_order_release); +#endif // V8_OS_LINUX && V8_ENABLE_PRIVATE_MAPPING_FORK_OPTIMIZATION +} + // TODO(v8:10026): Add the right permission flag to make executable pages // guarded. int GetProtectionFromMemoryPermission(OS::MemoryPermission access) { @@ -531,6 +597,7 @@ void* OS::AllocateShared(size_t size, MemoryPermission access) { void OS::Free(void* address, size_t size) { DCHECK_EQ(0, reinterpret_cast(address) % AllocatePageSize()); DCHECK_EQ(0, size % AllocatePageSize()); + ForgetDontFork(address, size); CHECK_EQ(0, munmap(address, size)); } @@ -551,6 +618,7 @@ void* OS::AllocateShared(void* hint, size_t size, MemoryPermission access, // static void OS::FreeShared(void* address, size_t size) { DCHECK_EQ(0, size % AllocatePageSize()); + ForgetDontFork(address, size); CHECK_EQ(0, munmap(address, size)); } @@ -558,6 +626,7 @@ void OS::FreeShared(void* address, size_t size) { void OS::Release(void* address, size_t size) { DCHECK_EQ(0, reinterpret_cast(address) % CommitPageSize()); DCHECK_EQ(0, size % CommitPageSize()); + ForgetDontFork(address, size); CHECK_EQ(0, munmap(address, size)); } From 8dd694e68b39e33670d0b50aedd83eb659dd5678 Mon Sep 17 00:00:00 2001 From: Max schwenk Date: Thu, 12 Nov 2026 02:18:53 -0500 Subject: [PATCH 02/16] deps: fix libuv in children forked from a running loop Two problems for a process that forks while its loop runs and keeps using the loop in the child: - The threadpool's atfork child handler only reset its uv_once guard. nthreads and threads still described the parent's threads, so uv_library_shutdown() at the child's exit joined threads that do not exist in the child and hung. Forget them; the next uv__work_submit() starts new ones. - On Linux, fork() from a callback that uv__io_poll() is dispatching returns into that uv__io_poll() in the child, which keeps using the epoll fd number it read on entry and dispatches the rest of the parent's events. uv_loop_fork() created the new epoll instance under a new number, so the old number could by then name another loop's epoll instance (another thread's): the child removed that loop's wakeup eventfd from it with EPOLL_CTL_DEL. uv__io_fork() now gives the new epoll instance the old number and invalidates the rest of the in-flight events, which belong to the parent. --- deps/uv/src/threadpool.c | 9 +++++++++ deps/uv/src/unix/linux.c | 43 ++++++++++++++++++++++++++++++++++++++-- 2 files changed, 50 insertions(+), 2 deletions(-) diff --git a/deps/uv/src/threadpool.c b/deps/uv/src/threadpool.c index 2a129a5d4a5..b7e7a4007f4 100644 --- a/deps/uv/src/threadpool.c +++ b/deps/uv/src/threadpool.c @@ -256,6 +256,15 @@ static void init_threads(void) { static void reset_once(void) { uv_once_t child_once = UV_ONCE_INIT; memcpy(&once, &child_once, sizeof(child_once)); + /* The worker threads do not exist in the child. Forget them, or + * uv__threadpool_cleanup() (uv_library_shutdown()) would try to join them + * and wait forever. The next uv__work_submit() starts new ones. The array is + * leaked when it was allocated: it is not safe to call free() here. + */ + threads = NULL; + nthreads = 0; + idle_threads = 0; + slow_io_work_running = 0; } #endif diff --git a/deps/uv/src/unix/linux.c b/deps/uv/src/unix/linux.c index 110964884dd..0a081695246 100644 --- a/deps/uv/src/unix/linux.c +++ b/deps/uv/src/unix/linux.c @@ -654,21 +654,47 @@ int uv__platform_loop_init(uv_loop_t* loop) { } +struct uv__invalidate; +static void uv__io_fork_invalidate_events(uv_loop_t* loop); + int uv__io_fork(uv_loop_t* loop) { int err; + int old_fd; struct watcher_list* root; root = uv__inotify_watchers(loop)->rbh_root; - uv__close(loop->backend_fd); + /* fork() may have been called from a callback that uv__io_poll() is + * dispatching. The rest of the events that the parent's epoll_pwait() + * returned are the parent's: don't let the child dispatch them. + */ + uv__io_fork_invalidate_events(loop); + + old_fd = loop->backend_fd; loop->backend_fd = -1; /* TODO(bnoordhuis) Loses items from the submission and completion rings. */ uv__platform_loop_delete(loop); err = uv__platform_loop_init(loop); - if (err) + if (err) { + uv__close(old_fd); return err; + } + + /* Give the new epoll instance the old file descriptor number. A + * uv__io_poll() call that is still on the stack (fork() from a callback) + * keeps using the number it read on entry; with a new number, that could + * by then be another loop's epoll instance (another thread's), or any + * other file. + */ + if (dup3(loop->backend_fd, old_fd, O_CLOEXEC) == -1) { + err = UV__ERR(errno); + uv__close(old_fd); + return err; + } + uv__close(loop->backend_fd); + loop->backend_fd = old_fd; return uv__inotify_fork(loop, root); } @@ -696,6 +722,19 @@ struct uv__invalidate { }; +static void uv__io_fork_invalidate_events(uv_loop_t* loop) { + uv__loop_internal_fields_t* lfields; + struct uv__invalidate* inv; + int i; + + lfields = uv__get_internal_fields(loop); + inv = lfields->inv; + if (inv != NULL) + for (i = 0; i < inv->nfds; i++) + inv->events[i].data.fd = -1; +} + + void uv__platform_invalidate_fd(uv_loop_t* loop, int fd) { uv__loop_internal_fields_t* lfields; struct uv__invalidate* inv; From 74669973c15e2f788d5eb779c78e427482387fe0 Mon Sep 17 00:00:00 2001 From: Max schwenk Date: Thu, 12 Nov 2026 02:18:53 -0500 Subject: [PATCH 03/16] src: let the V8 platform's threads stop and restart around fork(2) WorkerThreadsTaskRunner::StopThreadsForFork() stops the delayed task scheduler thread (its pending timers are handed back with the time they had left) and puts the worker task queue in a paused state in which BlockingPop() returns nullptr without dropping anything, so that each worker finishes the task it is running and exits. Once all threads are joined, no thread runs a task or holds a lock, and the queued tasks are intact; RestartThreadsAfterFork() starts the threads again, in the parent and in the child, and each process runs its own copy of the queued tasks. If the workers do not stop within a timeout (a worker can wait for the main thread, for instance for a garbage collection it requested), everything is restarted and the caller can retry. NumberOfWorkerThreads() now returns a value fixed at construction. --- src/node_platform.cc | 255 ++++++++++++++++++++++++++++++++++++++++--- src/node_platform.h | 38 +++++++ 2 files changed, 276 insertions(+), 17 deletions(-) diff --git a/src/node_platform.cc b/src/node_platform.cc index ff4b139a72e..b8b432303d4 100644 --- a/src/node_platform.cc +++ b/src/node_platform.cc @@ -24,6 +24,7 @@ struct PlatformWorkerData { int* pending_platform_workers; int id; PlatformDebugLogLevel debug_log_level; + WorkerThreadsTaskRunner* runner; }; const char* GetTaskPriorityName(TaskPriority priority) { @@ -58,7 +59,7 @@ static void PlatformWorkerThread(void* data) { "PlatformWorkerThread"); // Notify the main thread that the platform worker is ready. - { + if (worker_data->platform_workers_mutex != nullptr) { Mutex::ScopedLock lock(*worker_data->platform_workers_mutex); (*worker_data->pending_platform_workers)--; worker_data->platform_workers_ready->Signal(lock); @@ -83,6 +84,9 @@ static void PlatformWorkerThread(void* data) { pending_worker_tasks->Lock().NotifyOfOutstandingCompletion(); } } + // BlockingPop() returned nullptr: the queue was stopped (shutdown) or paused + // (fork). Either way this thread runs no further task. + worker_data->runner->OnWorkerThreadExit(id); } static int GetActualThreadPoolSize(int thread_pool_size) { @@ -129,7 +133,9 @@ class WorkerThreadsTaskRunner::DelayedTaskScheduler { // schedules the timers into the local task queue that will be flushed // by the local event loop. locked.Push(std::move(delayed)); - uv_async_send(&flush_tasks_); + // While the thread is stopped for a fork, the task waits in tasks_ until + // RestartAfterFork() flushes it. + if (!stopped_for_fork_) uv_async_send(&flush_tasks_); } void Stop() { @@ -139,6 +145,40 @@ class WorkerThreadsTaskRunner::DelayedTaskScheduler { uv_async_send(&flush_tasks_); } + // fork(2) support, main thread. Asks the scheduler thread to hand its + // pending timers back (each task with the time it still had to wait) and to + // leave its loop. The caller joins the thread afterwards. + void StopForFork() { + auto locked = tasks_.Lock(); + CHECK(!has_shut_down_); + CHECK(!stopped_for_fork_); + stopped_for_fork_ = true; + locked.Push(std::make_unique(this)); + uv_async_send(&flush_tasks_); + } + + // After the thread was joined (and, in the child, after fork(2)): starts a + // new thread and re-arms the parked timers with the time they had left, + // minus the time spent stopped. + std::unique_ptr RestartAfterFork() { + std::unique_ptr t = Start(); + const uint64_t now = uv_hrtime(); + auto locked = tasks_.Lock(); + CHECK(stopped_for_fork_); + stopped_for_fork_ = false; + for (ParkedTask& parked : parked_tasks_) { + const uint64_t stopped_ms = (now - parked.parked_at) / 1000000; + const uint64_t delay_ms = parked.due_in_ms > stopped_ms + ? parked.due_in_ms - stopped_ms + : 0; + locked.Push(std::make_unique( + this, std::move(parked.entry), delay_ms / 1000.0)); + } + parked_tasks_.clear(); + uv_async_send(&flush_tasks_); + return t; + } + private: void Run() { TRACE_EVENT_METADATA1("__metadata", "thread_name", "name", @@ -147,6 +187,7 @@ class WorkerThreadsTaskRunner::DelayedTaskScheduler { CHECK_EQ(0, uv_loop_init(&loop_)); flush_tasks_.data = this; CHECK_EQ(0, uv_async_init(&loop_, &flush_tasks_, FlushTasks)); + leaving_for_fork_ = false; uv_sem_post(&ready_); uv_run(&loop_, UV_RUN_DEFAULT); @@ -161,8 +202,17 @@ class WorkerThreadsTaskRunner::DelayedTaskScheduler { // in posting order, then, once Stop() was called, the StopTask. std::vector> tasks = scheduler->tasks_.Lock().PopAll(); - for (std::unique_ptr& task : tasks) { - task->Run(); + for (size_t i = 0; i < tasks.size(); i++) { + tasks[i]->Run(); + if (scheduler->leaving_for_fork_) { + // A ForkStopTask ran: whatever was posted after it waits for the + // thread to be restarted. + auto locked = scheduler->tasks_.Lock(); + for (size_t j = i + 1; j < tasks.size(); j++) { + locked.Push(std::move(tasks[j])); + } + break; + } } } @@ -184,6 +234,30 @@ class WorkerThreadsTaskRunner::DelayedTaskScheduler { DelayedTaskScheduler* scheduler_; }; + // Like StopTask, but keeps the timers' tasks for RestartAfterFork(). + class ForkStopTask : public Task { + public: + explicit ForkStopTask(DelayedTaskScheduler* scheduler) + : scheduler_(scheduler) {} + + void Run() override { + const uint64_t now = uv_hrtime(); + std::vector timers(scheduler_->timers_.begin(), + scheduler_->timers_.end()); + for (uv_timer_t* timer : timers) { + const uint64_t due_in_ms = uv_timer_get_due_in(timer); + scheduler_->parked_tasks_.push_back( + ParkedTask{scheduler_->TakeTimerTask(timer), due_in_ms, now}); + } + scheduler_->leaving_for_fork_ = true; + uv_close(reinterpret_cast(&scheduler_->flush_tasks_), + [](uv_handle_t* handle) {}); + } + + private: + DelayedTaskScheduler* scheduler_; + }; + class ScheduleTask : public Task { public: ScheduleTask(DelayedTaskScheduler* scheduler, @@ -228,6 +302,12 @@ class WorkerThreadsTaskRunner::DelayedTaskScheduler { return task_entry; } + struct ParkedTask { + std::unique_ptr entry; + uint64_t due_in_ms; + uint64_t parked_at; // uv_hrtime() + }; + uv_sem_t ready_; // Task queue in the worker thread task runner, we push the delayed task back // to it when the timer expires. @@ -240,36 +320,66 @@ class WorkerThreadsTaskRunner::DelayedTaskScheduler { uv_async_t flush_tasks_; std::unordered_set timers_; bool has_shut_down_ = false; + // Guarded by tasks_'s lock: the thread is stopped (or stopping) for a fork. + bool stopped_for_fork_ = false; + // Scheduler thread only: a ForkStopTask ran in this loop. + bool leaving_for_fork_ = false; + // Timers handed back by ForkStopTask; read by the main thread after it + // joined the scheduler thread. + std::vector parked_tasks_; }; WorkerThreadsTaskRunner::WorkerThreadsTaskRunner( int thread_pool_size, PlatformDebugLogLevel debug_log_level) - : debug_log_level_(debug_log_level) { + : debug_log_level_(debug_log_level), thread_pool_size_(thread_pool_size) { + delayed_task_scheduler_ = std::make_unique( + &pending_worker_tasks_); + threads_.resize(thread_pool_size_ + 1); + threads_[0] = delayed_task_scheduler_->Start(); + StartWorkerThreads(); + number_of_threads_ = 0; + for (const auto& t : threads_) { + if (t) number_of_threads_++; + } +} + +void WorkerThreadsTaskRunner::StartWorkerThreads() { Mutex platform_workers_mutex; ConditionVariable platform_workers_ready; Mutex::ScopedLock lock(platform_workers_mutex); - int pending_platform_workers = thread_pool_size; - - delayed_task_scheduler_ = std::make_unique( - &pending_worker_tasks_); - threads_.push_back(delayed_task_scheduler_->Start()); + int pending_platform_workers = 0; + { + Mutex::ScopedLock workers_lock(workers_mutex_); + worker_exited_.assign(thread_pool_size_, false); + running_workers_ = 0; + } - for (int i = 0; i < thread_pool_size; i++) { + for (int i = 0; i < thread_pool_size_; i++) { auto worker_data = std::make_unique( PlatformWorkerData{&pending_worker_tasks_, &platform_workers_mutex, &platform_workers_ready, &pending_platform_workers, i, - debug_log_level_}); + debug_log_level_, + this}); std::unique_ptr t { new uv_thread_t() }; + { + Mutex::ScopedLock workers_lock(workers_mutex_); + running_workers_++; + } + pending_platform_workers++; if (uv_thread_create(t.get(), PlatformWorkerThread, worker_data.get()) != 0) { + pending_platform_workers--; + Mutex::ScopedLock workers_lock(workers_mutex_); + running_workers_--; + worker_exited_[i] = true; break; } worker_data.release(); - threads_.push_back(std::move(t)); + threads_[i + 1] = std::move(t); } // Wait for platform workers to initialize before continuing with the @@ -279,6 +389,13 @@ WorkerThreadsTaskRunner::WorkerThreadsTaskRunner( } } +void WorkerThreadsTaskRunner::OnWorkerThreadExit(int id) { + Mutex::ScopedLock lock(workers_mutex_); + running_workers_--; + worker_exited_[id] = true; + workers_exited_.Broadcast(lock); +} + void WorkerThreadsTaskRunner::PostTask(v8::TaskPriority priority, std::unique_ptr task, const v8::SourceLocation& location) { @@ -304,12 +421,96 @@ void WorkerThreadsTaskRunner::Shutdown() { pending_worker_tasks_.Lock().Stop(); delayed_task_scheduler_->Stop(); for (size_t i = 0; i < threads_.size(); i++) { - CHECK_EQ(0, uv_thread_join(threads_[i].get())); + if (threads_[i]) CHECK_EQ(0, uv_thread_join(threads_[i].get())); + } +} + +bool WorkerThreadsTaskRunner::StopThreadsForFork(uint64_t timeout_ms) { + // The scheduler thread only moves tasks into pending_worker_tasks_ when + // their timers fire, it never runs one, so it stops right away. + delayed_task_scheduler_->StopForFork(); + CHECK_EQ(0, uv_thread_join(threads_[0].get())); + threads_[0].reset(); + + // Each worker finishes the task it is running and leaves its loop instead + // of taking the next one. A running V8 job keeps its worker until the job + // runs out of work, which happens because nothing adds work while the main + // thread waits here. + pending_worker_tasks_.Lock().Pause(); + bool stopped; + { + Mutex::ScopedLock lock(workers_mutex_); + const uint64_t deadline = uv_hrtime() + timeout_ms * 1000000; + while (running_workers_ > 0) { + const uint64_t now = uv_hrtime(); + if (now >= deadline) break; + workers_exited_.TimedWait(lock, deadline - now); + } + stopped = running_workers_ == 0; + } + + if (stopped) { + for (size_t i = 1; i < threads_.size(); i++) { + if (!threads_[i]) continue; + CHECK_EQ(0, uv_thread_join(threads_[i].get())); + threads_[i].reset(); + } + return true; + } + + // A worker is still busy, for instance blocked until the main thread + // performs a garbage collection it asked for. Undo: let the busy workers + // continue, replace the ones that already left, restart the scheduler. + pending_worker_tasks_.Lock().Resume(); + std::vector exited; + { + Mutex::ScopedLock lock(workers_mutex_); + for (int i = 0; i < thread_pool_size_; i++) { + if (worker_exited_[i] && threads_[i + 1]) exited.push_back(i); + } + } + for (int i : exited) { + CHECK_EQ(0, uv_thread_join(threads_[i + 1].get())); + threads_[i + 1].reset(); + auto worker_data = std::make_unique( + PlatformWorkerData{&pending_worker_tasks_, + nullptr, + nullptr, + nullptr, + i, + debug_log_level_, + this}); + std::unique_ptr t{new uv_thread_t()}; + { + Mutex::ScopedLock lock(workers_mutex_); + running_workers_++; + worker_exited_[i] = false; + } + if (uv_thread_create(t.get(), PlatformWorkerThread, worker_data.get()) != + 0) { + Mutex::ScopedLock lock(workers_mutex_); + running_workers_--; + worker_exited_[i] = true; + continue; + } + worker_data.release(); + threads_[i + 1] = std::move(t); } + threads_[0] = delayed_task_scheduler_->RestartAfterFork(); + return false; +} + +void WorkerThreadsTaskRunner::RestartThreadsAfterFork() { + pending_worker_tasks_.Lock().Resume(); + // In the child, threads_ describes threads of the parent, all of which had + // been joined before fork(2). + for (auto& t : threads_) t.reset(); + threads_[0] = delayed_task_scheduler_->RestartAfterFork(); + StartWorkerThreads(); } int WorkerThreadsTaskRunner::NumberOfWorkerThreads() const { - return threads_.size(); + return number_of_threads_; } PerIsolatePlatformData::PerIsolatePlatformData( @@ -538,6 +739,14 @@ int NodePlatform::NumberOfWorkerThreads() { return worker_thread_task_runner_->NumberOfWorkerThreads(); } +bool NodePlatform::StopThreadsForFork(uint64_t timeout_ms) { + return worker_thread_task_runner_->StopThreadsForFork(timeout_ms); +} + +void NodePlatform::RestartThreadsAfterFork() { + worker_thread_task_runner_->RestartThreadsAfterFork(); +} + void PerIsolatePlatformData::RunForegroundTask(std::unique_ptr task) { if (isolate_->IsExecutionTerminating()) return; DebugSealHandleScope scope(isolate_); @@ -797,10 +1006,11 @@ std::unique_ptr TaskQueue::Locked::Pop() { template std::unique_ptr TaskQueue::Locked::BlockingPop() { - while (queue_->task_queue_.empty() && !queue_->stopped_) { + while (queue_->task_queue_.empty() && !queue_->stopped_ && + !queue_->paused_) { queue_->tasks_available_.Wait(lock_); } - if (queue_->stopped_) { + if (queue_->stopped_ || queue_->paused_) { return std::unique_ptr(nullptr); } return queue_->PopTask(); @@ -826,6 +1036,17 @@ void TaskQueue::Locked::Stop() { queue_->tasks_available_.Broadcast(lock_); } +template +void TaskQueue::Locked::Pause() { + queue_->paused_ = true; + queue_->tasks_available_.Broadcast(lock_); +} + +template +void TaskQueue::Locked::Resume() { + queue_->paused_ = false; +} + template std::vector> TaskQueue::Locked::PopAll() { std::vector> result; diff --git a/src/node_platform.h b/src/node_platform.h index 52e3e629bc0..d897a987169 100644 --- a/src/node_platform.h +++ b/src/node_platform.h @@ -35,6 +35,12 @@ class TaskQueue { void NotifyOfOutstandingCompletion(); void BlockingDrain(); void Stop(); + // Make BlockingPop() return nullptr to every consumer while paused, + // without dropping the queued tasks (unlike Stop()), so that consumer + // threads can exit and be joined before fork(2) and be started again + // afterwards. + void Pause(); + void Resume(); // All queued tasks, in the order Pop() would have returned them. Store the // result before iterating it: used directly as a range-for initializer, // `Lock().PopAll()` keeps the lock held for the whole loop from C++23 on. @@ -80,6 +86,7 @@ class TaskQueue { ConditionVariable outstanding_tasks_drained_; int outstanding_tasks_; bool stopped_; + bool paused_ = false; uint64_t next_sequence_ = 0; PriorityQueue task_queue_; }; @@ -206,7 +213,21 @@ class WorkerThreadsTaskRunner { int NumberOfWorkerThreads() const; + // fork(2) support. StopThreadsForFork() stops every thread of the runner at + // a point where none of them is running a task; queued tasks and delayed + // tasks are kept. It returns false, with every thread running again, if the + // worker threads did not finish their current tasks within |timeout_ms|. + // RestartThreadsAfterFork() starts them again, in the parent and in the + // child. Main thread only. + bool StopThreadsForFork(uint64_t timeout_ms); + void RestartThreadsAfterFork(); + + // Called by a worker thread right before it exits. + void OnWorkerThreadExit(int id); + private: + void StartWorkerThreads(); + // A queue shared by all threads. The consumers are the worker threads which // take tasks from it to run in PlatformWorkerThread(). The producers can be // any thread. Both the foreground thread and the worker threads can push @@ -222,6 +243,19 @@ class WorkerThreadsTaskRunner { std::vector> threads_; PlatformDebugLogLevel debug_log_level_ = PlatformDebugLogLevel::kNone; + + // Number of platform worker threads requested (threads_ also holds the + // delayed task scheduler thread). + int thread_pool_size_ = 0; + // threads_.size() as V8 sees it; constant for the life of the runner, also + // while the threads are stopped for a fork. + int number_of_threads_ = 0; + // Worker threads still inside PlatformWorkerThread(), and which ones have + // left it (indexed by worker id), guarded by workers_mutex_. + Mutex workers_mutex_; + ConditionVariable workers_exited_; + int running_workers_ = 0; + std::vector worker_exited_; }; class NodePlatform : public MultiIsolatePlatform { @@ -269,6 +303,10 @@ class NodePlatform : public MultiIsolatePlatform { Platform::StackTracePrinter GetStackTracePrinter() override; v8::PageAllocator* GetPageAllocator() override; + // fork(2) support, see WorkerThreadsTaskRunner. Main thread only. + bool StopThreadsForFork(uint64_t timeout_ms); + void RestartThreadsAfterFork(); + private: IsolatePlatformDelegate* ForIsolate(v8::Isolate* isolate); std::shared_ptr ForNodeIsolate(v8::Isolate* isolate); From 4e23b0eb41ed9a7c96a291f27d788cfb421537c2 Mon Sep 17 00:00:00 2001 From: Max schwenk Date: Thu, 12 Nov 2026 02:19:02 -0500 Subject: [PATCH 04/16] src,lib: add process.forkSelf() process.forkSelf() forks the running process: it returns the child's pid in the parent and 0 in the child, like fork(2), for processes that want to pay their startup cost once and copy themselves afterwards. It exists only on POSIX main threads. Before forking it stops V8's platform threads (and holds the inspector watchdog thread's lock); after it they are started again in both processes. It refuses (ERR_FORK_SELF_UNSAFE) while Worker threads, the inspector's I/O thread, the trace event writer thread or the SIGINT watchdog thread run, and (ERR_FORK_SELF_BUSY) while requests are in flight on the event loop, which would never complete in the child or complete in both processes. In the child, before any JavaScript or event loop turn runs: uv_loop_fork(); async handles that were pending before the fork are woken again (libuv clears the flag in the child); process.pid is updated; V8's random number generators and Node's own random caches (randomInt, randomUUID) are reseeded or dropped; stdio is left to the parent at exit (O_NONBLOCK and termios are shared with it); the IPC channel inherited from the parent is closed without 'disconnect', and messages read before the fork but not emitted yet are dropped. The parent reaps the children it forked (nothing else would: libuv only waits for processes it spawned) with waitpid() per pid on SIGCHLD, and an optional onExit(code, signal) callback reports the exit and keeps the parent's loop alive until then. --- lib/child_process.js | 19 +- .../switches/does_not_own_process_state.js | 2 + .../bootstrap/switches/is_main_thread.js | 5 + .../bootstrap/switches/is_not_main_thread.js | 3 + lib/internal/child_process.js | 35 ++ lib/internal/crypto/random.js | 31 +- lib/internal/errors.js | 2 + lib/internal/process/fork_self.js | 120 +++++++ lib/internal/util/debuglog.js | 4 +- node.gyp | 1 + src/env.h | 3 + src/inspector_agent.cc | 19 ++ src/inspector_agent.h | 8 + src/node.cc | 10 + src/node_errors.h | 2 + src/node_internals.h | 2 + src/node_process.h | 6 + src/node_process_fork.cc | 322 ++++++++++++++++++ src/node_process_methods.cc | 5 + src/node_watchdog.cc | 5 + src/node_watchdog.h | 3 + src/tracing/agent.h | 4 + src/tracing/agent_legacy.h | 1 + src/tracing/agent_perfetto.h | 1 + 24 files changed, 592 insertions(+), 21 deletions(-) create mode 100644 lib/internal/process/fork_self.js create mode 100644 src/node_process_fork.cc diff --git a/lib/child_process.js b/lib/child_process.js index ac7188048be..1e1442fd9d9 100644 --- a/lib/child_process.js +++ b/lib/child_process.js @@ -89,6 +89,7 @@ const { const child_process = require('internal/child_process'); const { getValidStdio, + kForkChildListeners, setupChannel, ChildProcess, stdioStringToArray, @@ -183,12 +184,18 @@ function _forkChild(fd, serializationMode) { p.open(fd); p.unref(); const control = setupChannel(process, p, serializationMode); - process.on('newListener', function onNewListener(name) { - if (name === 'message' || name === 'disconnect') control.refCounted(); - }); - process.on('removeListener', function onRemoveListener(name) { - if (name === 'message' || name === 'disconnect') control.unrefCounted(); - }); + const listeners = { + onNewListener(name) { + if (name === 'message' || name === 'disconnect') control.refCounted(); + }, + onRemoveListener(name) { + if (name === 'message' || name === 'disconnect') control.unrefCounted(); + }, + }; + // Removed again by detachChannelAfterFork(). + process[kForkChildListeners] = listeners; + process.on('newListener', listeners.onNewListener); + process.on('removeListener', listeners.onRemoveListener); } function normalizeExecArgs(command, options, callback) { diff --git a/lib/internal/bootstrap/switches/does_not_own_process_state.js b/lib/internal/bootstrap/switches/does_not_own_process_state.js index 8350a7c79d8..d25488b2cef 100644 --- a/lib/internal/bootstrap/switches/does_not_own_process_state.js +++ b/lib/internal/bootstrap/switches/does_not_own_process_state.js @@ -7,6 +7,8 @@ const { unavailable } = require('internal/process/worker_thread_only'); process.abort = unavailable('process.abort()'); process.chdir = unavailable('process.chdir()'); +// Forking needs a process this environment owns. +delete process.forkSelf; process.umask = wrappedUmask; process.cwd = rawMethods.cwd; diff --git a/lib/internal/bootstrap/switches/is_main_thread.js b/lib/internal/bootstrap/switches/is_main_thread.js index e9e37275b17..6cc2305ef23 100644 --- a/lib/internal/bootstrap/switches/is_main_thread.js +++ b/lib/internal/bootstrap/switches/is_main_thread.js @@ -21,6 +21,11 @@ process._debugEnd = rawMethods._debugEnd; process._startProfilerIdleNotifier = () => {}; process._stopProfilerIdleNotifier = () => {}; +// process.forkSelf() exists only where it can work: POSIX main threads. +if (typeof rawMethods.forkSelf === 'function') { + process.forkSelf = require('internal/process/fork_self').forkSelf; +} + function defineStream(name, getter) { ObjectDefineProperty(process, name, { __proto__: null, diff --git a/lib/internal/bootstrap/switches/is_not_main_thread.js b/lib/internal/bootstrap/switches/is_not_main_thread.js index 1716bea2014..f337c9587f5 100644 --- a/lib/internal/bootstrap/switches/is_not_main_thread.js +++ b/lib/internal/bootstrap/switches/is_not_main_thread.js @@ -12,6 +12,9 @@ delete process._debugEnd; delete process._debugPause; delete process._startProfilerIdleNotifier; delete process._stopProfilerIdleNotifier; +// process.forkSelf() can only fork the main thread; feature detection +// (typeof process.forkSelf === 'function') must say so. +delete process.forkSelf; function defineStream(name, getter) { ObjectDefineProperty(process, name, { diff --git a/lib/internal/child_process.js b/lib/internal/child_process.js index 06daf2183db..75dc18791e3 100644 --- a/lib/internal/child_process.js +++ b/lib/internal/child_process.js @@ -87,6 +87,8 @@ let HTTPParser; const MAX_HANDLE_RETRANSMISSIONS = 3; const kChannelHandle = Symbol('kChannelHandle'); +const kDetachedByFork = Symbol('kDetachedByFork'); +const kForkChildListeners = Symbol('kForkChildListeners'); const kIsUsedAsStdio = Symbol('kIsUsedAsStdio'); const kPendingMessages = Symbol('kPendingMessages'); @@ -1000,6 +1002,8 @@ function setupChannel(target, channel, serializationMode) { }; function emit(event, message, handle) { + // Read by the parent of a process.forkSelf() child; not this process's. + if (channel[kDetachedByFork]) return; if ('internalMessage' === event || target.listenerCount('message')) { target.emit(event, message, handle); return; @@ -1024,6 +1028,35 @@ function setupChannel(target, channel, serializationMode) { return control; } +// In a child created by process.forkSelf(): the IPC channel inherited from +// the parent belongs to the parent. Close this process's copy of the file +// descriptor right away (no event loop turn may read a message meant for the +// parent), without emitting 'disconnect', and drop messages that were read +// before the fork but not emitted yet. +function detachChannelAfterFork(target) { + const channel = target[kChannelHandle]; + if (channel) { + channel[kDetachedByFork] = true; + channel.onread = nop; + channel.close(); + } + const listeners = target[kForkChildListeners]; + if (listeners) { + target.removeListener('newListener', listeners.onNewListener); + target.removeListener('removeListener', listeners.onRemoveListener); + target[kForkChildListeners] = undefined; + } + target[kChannelHandle] = null; + target._handleQueue = null; + target._pendingMessage = null; + target.connected = false; + delete target.channel; + delete target.send; + delete target._send; + delete target.disconnect; + delete target._disconnect; +} + const INTERNAL_PREFIX = 'NODE_'; function isInternal(message) { return (message !== null && @@ -1182,7 +1215,9 @@ function spawnSync(options) { module.exports = { ChildProcess, + detachChannelAfterFork, kChannelHandle, + kForkChildListeners, setupChannel, getValidStdio, stdioStringToArray, diff --git a/lib/internal/crypto/random.js b/lib/internal/crypto/random.js index edf5b95f509..16b22cc3b74 100644 --- a/lib/internal/crypto/random.js +++ b/lib/internal/crypto/random.js @@ -388,20 +388,25 @@ let uuidData; let uuidNotBuffered; let uuidBatch = 0; +function resetRandomCaches() { + TypedArrayPrototypeFill(randomCache, 0); + randomCacheOffset = randomCache.length; + if (uuidData !== undefined) { + TypedArrayPrototypeFill(uuidData, 0); + uuidData = undefined; + } + if (uuidNotBuffered !== undefined) { + TypedArrayPrototypeFill(uuidNotBuffered, 0); + uuidNotBuffered = undefined; + } + uuidBatch = 0; +} + +// A child created by process.forkSelf() must not hand out the random bytes +// its parent (and its siblings) already hold. +require('internal/process/fork_self').addForkSelfChildHook(resetRandomCaches); + if (isBuildingSnapshot()) { - const resetRandomCaches = () => { - TypedArrayPrototypeFill(randomCache, 0); - randomCacheOffset = randomCache.length; - if (uuidData !== undefined) { - TypedArrayPrototypeFill(uuidData, 0); - uuidData = undefined; - } - if (uuidNotBuffered !== undefined) { - TypedArrayPrototypeFill(uuidNotBuffered, 0); - uuidNotBuffered = undefined; - } - uuidBatch = 0; - }; // Clear cached random data after user serialization callbacks. addAfterUserSerializeCallback(resetRandomCaches); // Microtasks and exit handlers can refill the caches after serialization diff --git a/lib/internal/errors.js b/lib/internal/errors.js index 2d8551302bd..e2bdbb2236c 100644 --- a/lib/internal/errors.js +++ b/lib/internal/errors.js @@ -1242,6 +1242,8 @@ E('ERR_FEATURE_UNAVAILABLE_ON_PLATFORM', ', which is being used to run Node.js', TypeError); E('ERR_FFI_LIBRARY_CLOSED', 'Library is closed', Error); +E('ERR_FORK_SELF_BUSY', '%s', Error); +E('ERR_FORK_SELF_UNSAFE', '%s', Error); E('ERR_FS_CP_DIR_TO_NON_DIR', 'Cannot overwrite non-directory with directory', SystemError); E('ERR_FS_CP_EEXIST', 'Target already exists', SystemError); diff --git a/lib/internal/process/fork_self.js b/lib/internal/process/fork_self.js new file mode 100644 index 00000000000..7b929efd16b --- /dev/null +++ b/lib/internal/process/fork_self.js @@ -0,0 +1,120 @@ +'use strict'; + +// process.forkSelf(): fork(2) the running process. The native part is +// src/node_process_fork.cc; doc/api/process.md describes what is handled. + +const { + ArrayPrototypePush, + FunctionPrototypeCall, + SafeMap, +} = primordials; + +const { + codes: { + ERR_FORK_SELF_BUSY, + }, +} = require('internal/errors'); +const { + validateFunction, + validateObject, +} = require('internal/validators'); + +// Returned by the binding when V8's worker threads did not finish their +// current tasks in time (see kForkSelfBusy in node_process_fork.cc). +const kBusy = -1; +// How long the binding waits for V8's worker threads to finish the tasks +// they are running, per attempt. A V8 job keeps a worker until it runs out of +// work, so this is normally a few milliseconds; it is long only when a worker +// waits for the main thread (for instance for a garbage collection it +// requested), which the next attempt resolves because returning to +// JavaScript lets V8 handle that request. +const kStopTimeoutsMs = [500, 2000, 8000]; + +// Functions run in the child, synchronously, before forkSelf() returns 0. +const childHooks = []; + +/** + * Registers a function to run in every child created by process.forkSelf(), + * before forkSelf() returns in the child. For internal state that must not + * be shared with the parent. + * @param {() => void} fn + */ +function addForkSelfChildHook(fn) { + ArrayPrototypePush(childHooks, fn); +} + +let warned = false; + +function forkSelf(options) { + if (options !== undefined) { + validateObject(options, 'options'); + if (options.onExit !== undefined) { + validateFunction(options.onExit, 'options.onExit'); + } + } + if (!warned) { + warned = true; + // Synchronously: a warning queued for a later tick would be inherited + // and printed by the child as well. + require('internal/process/warning').emitWarningSync( + 'process.forkSelf is an experimental feature and might change at any ' + + 'time', 'ExperimentalWarning'); + } + const { + forkSelf: rawForkSelf, + setForkSelfExitCallback, + } = internalBinding('process_methods'); + let pid = kBusy; + for (let i = 0; i < kStopTimeoutsMs.length && pid === kBusy; i++) { + // With onExit, the caller waits for the child: keep the loop alive. + pid = rawForkSelf(kStopTimeoutsMs[i], options?.onExit !== undefined); + } + if (pid === kBusy) { + throw new ERR_FORK_SELF_BUSY( + 'process.forkSelf() could not stop V8\'s worker threads: a background ' + + 'task did not finish'); + } + if (pid === 0) { + runChildHooks(); + return 0; + } + // The binding reaps every child it created (nothing else would); this + // reports the exit to the caller. + if (options?.onExit !== undefined) { + if (!exitCallbackSet) { + exitCallbackSet = true; + setForkSelfExitCallback(onChildExit); + } + exitCallbacks.set(pid, options.onExit); + } + return pid; +} + +// pid -> options.onExit of the children of this process. +const exitCallbacks = new SafeMap(); +let exitCallbackSet = false; + +function onChildExit(pid, code, signal) { + const onExit = exitCallbacks.get(pid); + if (onExit === undefined) return; + exitCallbacks.delete(pid); + onExit(code, signal); +} + +function runChildHooks() { + // The parent's children are not this process's. + exitCallbacks.clear(); + // The inherited IPC channel belongs to the parent: close it before any + // event loop turn could read a message meant for the parent. + if (process.channel) { + require('internal/child_process').detachChannelAfterFork(process); + } + for (let i = 0; i < childHooks.length; i++) { + FunctionPrototypeCall(childHooks[i], undefined); + } +} + +module.exports = { + addForkSelfChildHook, + forkSelf, +}; diff --git a/lib/internal/util/debuglog.js b/lib/internal/util/debuglog.js index 2eeab81dcff..e10ffda89a0 100644 --- a/lib/internal/util/debuglog.js +++ b/lib/internal/util/debuglog.js @@ -67,12 +67,12 @@ function lazyUtilColors() { function debuglogImpl(enabled, set) { if (debugImpls[set] === undefined) { if (enabled) { - const pid = process.pid; emitWarningIfNeeded(set); debugImpls[set] = function debug(...args) { const colors = lazyUtilColors().shouldColorize(process.stderr); const msg = formatWithOptions({ colors }, ...args); - const coloredPID = inspect(pid, { colors }); + // Read on every call: process.forkSelf() changes it. + const coloredPID = inspect(process.pid, { colors }); process.stderr.write(format('%s %s: %s\n', set, coloredPID, msg)); }; } else { diff --git a/node.gyp b/node.gyp index 5334b8a746d..ddc55030657 100644 --- a/node.gyp +++ b/node.gyp @@ -153,6 +153,7 @@ 'src/node_profiling.cc', 'src/node_postmortem_metadata.cc', 'src/node_process_events.cc', + 'src/node_process_fork.cc', 'src/node_process_methods.cc', 'src/node_process_object.cc', 'src/node_realm.cc', diff --git a/src/env.h b/src/env.h index 4aadd63536e..edf261c8795 100644 --- a/src/env.h +++ b/src/env.h @@ -943,6 +943,9 @@ class Environment final : public MemoryRetainer { inline void add_sub_worker_context(worker::Worker* context); inline void remove_sub_worker_context(worker::Worker* context); void stop_sub_worker_contexts(); + size_t sub_worker_context_count() const { + return sub_worker_contexts_.size(); + } template inline void ForEachWorker(Fn&& iterator); // Determine if the environment is stopping. This getter is thread-safe. diff --git a/src/inspector_agent.cc b/src/inspector_agent.cc index 22506e26b32..64b0607ff2e 100644 --- a/src/inspector_agent.cc +++ b/src/inspector_agent.cc @@ -518,6 +518,25 @@ void ThrowUninitializedInspectorError(Environment* env) { } // namespace +#ifdef __POSIX__ +// fork(2) support. The SignalInspector thread takes no lock other than +// start_io_thread_agents_mutex, held across the fork so that the child's copy +// is not locked by a thread it does not have. +void PrepareForFork() { + start_io_thread_agents_mutex.Lock(); +} + +void AfterFork(bool in_child) { + if (in_child && debug_signal_handler_started) { + // The SignalInspector thread did not survive the fork: start a new one + // (this reinitializes the semaphore it waits on, which may have had a + // waiter in the parent). + if (StartWatchdogThread() != 0) debug_signal_handler_started = false; + } + start_io_thread_agents_mutex.Unlock(); +} +#endif // __POSIX__ + class NodeInspectorClient : public V8InspectorClient { public: explicit NodeInspectorClient(node::Environment* env, bool is_main) diff --git a/src/inspector_agent.h b/src/inspector_agent.h index 5a1d1de2654..cc045e4fbb0 100644 --- a/src/inspector_agent.h +++ b/src/inspector_agent.h @@ -170,6 +170,14 @@ class Agent { std::shared_ptr network_resource_manager_; }; +#ifdef __POSIX__ +// fork(2) support for the per-process SIGUSR1 watchdog thread: call +// PrepareForFork() right before fork() and AfterFork() right after it, in +// both processes. The child gets a new watchdog thread. +void PrepareForFork(); +void AfterFork(bool in_child); +#endif // __POSIX__ + } // namespace inspector } // namespace node diff --git a/src/node.cc b/src/node.cc index 163070b501c..a45f61be29d 100644 --- a/src/node.cc +++ b/src/node.cc @@ -666,12 +666,22 @@ static void PlatformInit(ProcessInitializationFlags::Flags flags) { #endif // _WIN32 } +// Set in a process created by process.forkSelf(): the stdio state recorded by +// PlatformInit() belongs to the parent, which still uses the same open file +// descriptions (O_NONBLOCK is shared between processes) and terminal. +static std::atomic stdio_owned_by_parent = false; + +void DisownStdioAfterFork() { + stdio_owned_by_parent.store(true); +} + // Safe to call more than once and from signal handlers. void ResetStdio() { if (init_process_flags.load() & ProcessInitializationFlags::kNoStdioInitialization) { return; } + if (stdio_owned_by_parent.load()) return; uv_tty_reset_mode(); #ifdef __POSIX__ diff --git a/src/node_errors.h b/src/node_errors.h index 8fcea26f6b6..feb6a968822 100644 --- a/src/node_errors.h +++ b/src/node_errors.h @@ -93,6 +93,8 @@ void OOMErrorHandler(const char* location, const v8::OOMDetails& details); V(ERR_FS_CP_SOCKET, Error) \ V(ERR_FS_CP_FIFO_PIPE, Error) \ V(ERR_FS_CP_UNKNOWN, Error) \ + V(ERR_FORK_SELF_BUSY, Error) \ + V(ERR_FORK_SELF_UNSAFE, Error) \ V(ERR_HEAP_PROFILE_HAVE_BEEN_STARTED, Error) \ V(ERR_HEAP_PROFILE_NOT_STARTED, Error) \ V(ERR_ILLEGAL_CONSTRUCTOR, Error) \ diff --git a/src/node_internals.h b/src/node_internals.h index bb45d73e909..52430370880 100644 --- a/src/node_internals.h +++ b/src/node_internals.h @@ -109,6 +109,8 @@ std::string FormatErrorMessage(v8::Isolate* isolate, v8::Local message, bool add_source_line = true); void ResetStdio(); // Safe to call more than once and from signal handlers. +// In a child created by process.forkSelf(): make ResetStdio() a no-op. +void DisownStdioAfterFork(); #ifdef __POSIX__ void SignalExit(int signal, siginfo_t* info, void* ucontext); #endif diff --git a/src/node_process.h b/src/node_process.h index 64393302d2c..f4815ef76d3 100644 --- a/src/node_process.h +++ b/src/node_process.h @@ -106,6 +106,12 @@ class BindingData : public SnapshotableObject { static v8::CFunction fast_hrtime_bigint_; }; +#if defined(__POSIX__) && !defined(__PASE__) +// process.forkSelf(), see node_process_fork.cc. +void ForkSelf(const v8::FunctionCallbackInfo& args); +void SetForkSelfExitCallback(const v8::FunctionCallbackInfo& args); +#endif + } // namespace process } // namespace node #endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS diff --git a/src/node_process_fork.cc b/src/node_process_fork.cc new file mode 100644 index 00000000000..aba2aa317bb --- /dev/null +++ b/src/node_process_fork.cc @@ -0,0 +1,322 @@ +// process.forkSelf(): fork(2) a running Node.js process. The JavaScript side +// is lib/internal/process/fork_self.js; doc/api/process.md describes what is +// and is not handled. +// +// fork(2) copies only the calling thread. Everything else that runs threads +// in a Node.js process is brought to a state where no other thread runs or +// holds a lock at the instant of the fork, and restarted afterwards: +// - V8's platform worker threads and the delayed task scheduler thread are +// stopped between tasks and joined, then started again in both processes +// (NodePlatform::StopThreadsForFork()/RestartThreadsAfterFork()); +// - the libuv threadpool is idle (no request is in flight on the loop) and is +// recreated lazily in the child (libuv's atfork handler); +// - the SIGUSR1 watchdog thread takes no lock while waiting and is recreated +// in the child (inspector::AfterFork()); +// - threads that cannot be handled make forkSelf() throw: Worker threads, the +// inspector's I/O thread, the trace event writer thread and the SIGINT +// watchdog thread. + +#include "env-inl.h" +#include "inspector_agent.h" +#include "node_errors.h" +#include "node_internals.h" +#include "node_platform.h" +#include "node_process.h" +#include "node_v8_platform-inl.h" +#include "node_watchdog.h" +#include "tracing/agent.h" +#include "util-inl.h" +#include "uv.h" +#include "v8-fork.h" +#include "v8.h" + +#if defined(__POSIX__) && !defined(__PASE__) +#include +#include +#include +#include +#include +#include +#endif + +namespace node { +namespace process { + +using v8::Context; +using v8::FunctionCallbackInfo; +using v8::Integer; +using v8::Isolate; +using v8::Local; +using v8::Value; + +#if defined(__POSIX__) && !defined(__PASE__) + +namespace { + +// Returned instead of a pid when the platform threads did not stop in time; +// the JavaScript side lets V8 serve its interrupts and tries again. +constexpr int kForkSelfBusy = -1; + +constexpr uint64_t kDefaultStopTimeoutMs = 2000; + +void CollectPendingAsyncHandles(uv_handle_t* handle, void* arg) { + if (handle->type != UV_ASYNC || uv_is_closing(handle)) return; + uv_async_t* async = reinterpret_cast(handle); + if (async->pending == 0) return; + static_cast*>(arg)->push_back(async); +} + +// The children this process created with forkSelf() and has not reaped yet. +// Nothing else would reap them: libuv only waits for the processes it +// spawned. Each SIGCHLD is answered with waitpid(pid, WNOHANG) for every pid +// here, never waitpid(-1), so the children of child_process are left alone. +// Main thread only. +struct ForkedChildren { + struct Child { + pid_t pid; + // The caller waits for this child's exit: keep the event loop alive. + bool keep_alive; + }; + Environment* env; + uv_signal_t sigchld; + std::vector children; + // forkSelfExitCallback(pid, exitCode, signal), set from JavaScript. + v8::Global on_exit; + + void UpdateRef() { + uv_handle_t* handle = reinterpret_cast(&sigchld); + for (const Child& child : children) { + if (child.keep_alive) return uv_ref(handle); + } + uv_unref(handle); + } +}; +ForkedChildren* forked_children = nullptr; + +void ReapForkedChildren(uv_signal_t* handle, int signum) { + ForkedChildren* children = forked_children; + if (children == nullptr) return; + Environment* env = children->env; + struct Exit { + pid_t pid; + int exit_code; // -1 when killed by a signal + int signal; // 0 when it exited + }; + std::vector exits; + for (auto it = children->children.begin(); it != children->children.end();) { + int status = 0; + pid_t r; + do { + r = waitpid(it->pid, &status, WNOHANG); + } while (r == -1 && errno == EINTR); + if (r == 0) { + ++it; + continue; + } + if (r == it->pid) { + if (WIFEXITED(status)) { + exits.push_back({r, WEXITSTATUS(status), 0}); + } else if (WIFSIGNALED(status)) { + exits.push_back({r, -1, WTERMSIG(status)}); + } else { + ++it; // Stopped or continued: still alive. + continue; + } + } + // Reaped above, or (ECHILD) by someone else. + it = children->children.erase(it); + } + children->UpdateRef(); + if (exits.empty() || children->on_exit.IsEmpty() || !env->can_call_into_js()) + return; + Isolate* isolate = env->isolate(); + v8::HandleScope handle_scope(isolate); + Context::Scope context_scope(env->context()); + Local on_exit = children->on_exit.Get(isolate); + for (const Exit& exit : exits) { + Local argv[] = { + Integer::New(isolate, exit.pid), + exit.signal == 0 ? Integer::New(isolate, exit.exit_code).As() + : v8::Null(isolate).As(), + exit.signal != 0 + ? OneByteString(isolate, signo_string(exit.signal)).As() + : v8::Null(isolate).As(), + }; + if (MakeCallback(isolate, + env->process_object(), + on_exit, + arraysize(argv), + argv, + {0, 0}) + .IsEmpty()) { + return; // An exception is pending; the rest waits for the next SIGCHLD. + } + } +} + +ForkedChildren* GetForkedChildren(Environment* env) { + if (forked_children != nullptr) return forked_children; + ForkedChildren* children = new ForkedChildren(); + children->env = env; + CHECK_EQ(0, uv_signal_init(env->event_loop(), &children->sigchld)); + children->sigchld.data = children; + CHECK_EQ(0, + uv_signal_start(&children->sigchld, ReapForkedChildren, SIGCHLD)); + // Waiting for children is not a reason to keep the process alive. + uv_unref(reinterpret_cast(&children->sigchld)); + env->AddCleanupHook( + [](void* arg) { + ForkedChildren* children = static_cast(arg); + forked_children = nullptr; + children->on_exit.Reset(); + uv_close(reinterpret_cast(&children->sigchld), + [](uv_handle_t* handle) { + delete static_cast(handle->data); + }); + }, + children); + forked_children = children; + return children; +} + +} // namespace + +// setForkSelfExitCallback(fn): fn(pid, exitCode, signal) runs when a child +// created by forkSelf() was reaped. +void SetForkSelfExitCallback(const FunctionCallbackInfo& args) { + Environment* env = Environment::GetCurrent(args); + CHECK(env->is_main_thread()); + CHECK(args[0]->IsFunction()); + GetForkedChildren(env)->on_exit.Reset(env->isolate(), + args[0].As()); +} + +// forkSelf(stopTimeoutMs, keepAlive): pid in the parent, 0 in the child, +// kForkSelfBusy when V8's worker threads did not finish their tasks within +// stopTimeoutMs. With keepAlive, the parent's event loop stays alive until the +// child was reaped. Throws when forking is not safe. +void ForkSelf(const FunctionCallbackInfo& args) { + Environment* env = Environment::GetCurrent(args); + + if (!env->is_main_thread() || !env->owns_process_state()) { + return THROW_ERR_FORK_SELF_UNSAFE( + env, "process.forkSelf() is only available on the main thread"); + } + if (env->sub_worker_context_count() > 0) { + return THROW_ERR_FORK_SELF_UNSAFE( + env, + "process.forkSelf() cannot fork while Worker threads are running " + "(this includes the thread of off-thread module customization hooks)"); + } +#if HAVE_INSPECTOR + if (env->inspector_agent()->IsListening()) { + return THROW_ERR_FORK_SELF_UNSAFE( + env, + "process.forkSelf() cannot fork while the inspector is listening " + "(--inspect, inspector.open())"); + } +#endif + if (per_process::v8_platform.tracing_agent_ && + per_process::v8_platform.tracing_agent_->IsThreadRunning()) { + return THROW_ERR_FORK_SELF_UNSAFE( + env, + "process.forkSelf() cannot fork while trace events are recorded"); + } + if (SigintWatchdogHelper::GetInstance()->IsRunning()) { + return THROW_ERR_FORK_SELF_UNSAFE( + env, + "process.forkSelf() cannot fork while a SIGINT watchdog is running " + "(REPL, vm breakOnSigint)"); + } + // A request in flight would never complete in the child (threadpool work) + // or complete in both processes (a pending write would be written twice). + const unsigned int active_requests = env->event_loop()->active_reqs.count; + if (active_requests > 0) { + return THROW_ERR_FORK_SELF_BUSY( + env, + "process.forkSelf() cannot fork while %d requests are in flight on " + "the event loop (file system, DNS, crypto or zlib work, pending " + "writes, connects); call it again once they have completed", + static_cast(active_requests)); + } + + NodePlatform* platform = per_process::v8_platform.Platform(); + CHECK_NOT_NULL(platform); + uint64_t stop_timeout_ms = kDefaultStopTimeoutMs; + if (args[0]->IsNumber()) { + const double value = args[0].As()->Value(); + if (value >= 0) stop_timeout_ms = static_cast(value); + } + + // On Linux V8 marks its mappings MADV_DONTFORK (so that child_process + // spawns do not copy the heap's page tables): the child needs them. Once per + // process, a few milliseconds the first time. + v8::MakeMappingsForkable(); + + // Nothing buffered by C stdio may be written by both processes. + fflush(nullptr); + + if (!platform->StopThreadsForFork(stop_timeout_ms)) { + return args.GetReturnValue().Set(kForkSelfBusy); + } + + // libuv clears the pending flag of every async handle in the child (another + // thread could have been half way through uv_async_send()). No thread can + // send now, so this is the exact set the child has to wake up again. + std::vector pending_async_handles; + uv_walk(env->event_loop(), CollectPendingAsyncHandles, &pending_async_handles); + +#if HAVE_INSPECTOR + inspector::PrepareForFork(); +#endif + const pid_t pid = fork(); + const int fork_errno = errno; + + if (pid == 0) { + // In the child, before anything can use the loop or wake it up from + // another thread: new epoll/io_uring instances, a new async eventfd and a + // new signal pipe, all watchers re-armed. + const int err = uv_loop_fork(env->event_loop()); + if (err != 0) { + FPrintF(stderr, "process.forkSelf(): uv_loop_fork() failed: %s\n", + uv_strerror(err)); + ABORT(); + } + for (uv_async_t* async : pending_async_handles) uv_async_send(async); + // The parent's other children are not this process's to reap. + if (forked_children != nullptr) { + forked_children->children.clear(); + forked_children->UpdateRef(); + } + DisownStdioAfterFork(); + v8::ReseedRandomNumberGeneratorsAfterFork(env->isolate()); + // process.pid was computed once at startup. It is a configurable, + // read-only data property (see PatchProcessObject()). + Isolate* isolate = env->isolate(); + Local context = env->context(); + USE(env->process_object()->DefineOwnProperty( + context, + FIXED_ONE_BYTE_STRING(isolate, "pid"), + Integer::New(isolate, uv_os_getpid()), + v8::ReadOnly)); + } +#if HAVE_INSPECTOR + inspector::AfterFork(pid == 0); +#endif + platform->RestartThreadsAfterFork(); + + if (pid < 0) { + return env->ThrowErrnoException(fork_errno, "fork"); + } + if (pid > 0) { + ForkedChildren* children = GetForkedChildren(env); + children->children.push_back({pid, args[1]->IsTrue()}); + children->UpdateRef(); + } + args.GetReturnValue().Set(static_cast(pid)); +} + +#endif // defined(__POSIX__) && !defined(__PASE__) + +} // namespace process +} // namespace node diff --git a/src/node_process_methods.cc b/src/node_process_methods.cc index 6a35e5c5e4c..4cc28b5353c 100644 --- a/src/node_process_methods.cc +++ b/src/node_process_methods.cc @@ -812,6 +812,9 @@ static void CreatePerIsolateProperties(IsolateData* isolate_data, #if defined __POSIX__ && !defined(__PASE__) SetMethod(isolate, target, "execve", Execve); + SetMethod(isolate, target, "forkSelf", ForkSelf); + SetMethod( + isolate, target, "setForkSelfExitCallback", SetForkSelfExitCallback); #endif SetMethodNoSideEffect(isolate, target, "uptime", Uptime); SetMethod(isolate, target, "patchProcessObject", PatchProcessObject); @@ -860,6 +863,8 @@ void RegisterExternalReferences(ExternalReferenceRegistry* registry) { #if defined __POSIX__ && !defined(__PASE__) registry->Register(Execve); + registry->Register(ForkSelf); + registry->Register(SetForkSelfExitCallback); #endif registry->Register(Uptime); registry->Register(PatchProcessObject); diff --git a/src/node_watchdog.cc b/src/node_watchdog.cc index c403f8cb071..456c375dc7e 100644 --- a/src/node_watchdog.cc +++ b/src/node_watchdog.cc @@ -774,6 +774,11 @@ bool SigintWatchdogHelper::InformWatchdogsAboutSignal() { } +bool SigintWatchdogHelper::IsRunning() { + Mutex::ScopedLock lock(mutex_); + return start_stop_count_ > 0; +} + int SigintWatchdogHelper::Start() { Mutex::ScopedLock lock(mutex_); diff --git a/src/node_watchdog.h b/src/node_watchdog.h index f37831cbd01..6b113bfffa0 100644 --- a/src/node_watchdog.h +++ b/src/node_watchdog.h @@ -183,6 +183,9 @@ class SigintWatchdogHelper { int Start(); bool Stop(); + // Whether the helper thread (POSIX) runs: between the first Start() and + // the matching Stop(). process.forkSelf() refuses to fork then. + bool IsRunning(); private: SigintWatchdogHelper(); diff --git a/src/tracing/agent.h b/src/tracing/agent.h index 60ed6ebf5a8..d5377e05937 100644 --- a/src/tracing/agent.h +++ b/src/tracing/agent.h @@ -36,6 +36,10 @@ class Agent { // Returns a comma-separated list of enabled categories. virtual std::string GetEnabledCategories() const = 0; + // Whether the agent's writer thread runs (it does from the first enabled + // client until StopTracing()). process.forkSelf() refuses to fork then. + virtual bool IsThreadRunning() const { return false; } + // Called by V8Platform to start/stop file-based tracing. virtual void StartTracing(const std::string& categories) = 0; virtual void StopTracing() = 0; diff --git a/src/tracing/agent_legacy.h b/src/tracing/agent_legacy.h index cd992d1ee39..ca77df81723 100644 --- a/src/tracing/agent_legacy.h +++ b/src/tracing/agent_legacy.h @@ -85,6 +85,7 @@ class LegacyTracingAgent final : public Agent { std::unique_ptr writer, enum UseDefaultCategoryMode mode); std::string GetEnabledCategories() const override; + bool IsThreadRunning() const override { return started_; } void AppendTraceEvent(TraceObject* trace_event); void AddMetadataEvent(std::unique_ptr event); void Flush(bool blocking); diff --git a/src/tracing/agent_perfetto.h b/src/tracing/agent_perfetto.h index fc12b4d0f3f..b02b5e28516 100644 --- a/src/tracing/agent_perfetto.h +++ b/src/tracing/agent_perfetto.h @@ -102,6 +102,7 @@ class PerfettoTracingAgent final : public Agent { std::unique_ptr writer, enum UseDefaultCategoryMode mode); std::string GetEnabledCategories() const override; + bool IsThreadRunning() const override { return started_; } void StartTracing(const std::string& categories) override; void StopTracing() override; From 74afba081bca51fb298d32309fa240166884cbf6 Mon Sep 17 00:00:00 2001 From: Max schwenk Date: Thu, 12 Nov 2026 02:19:02 -0500 Subject: [PATCH 05/16] test: add process.forkSelf() tests --- test/common/fork-self.js | 64 +++++++++ test/parallel/test-process-fork-self-basic.js | 124 ++++++++++++++++++ .../test-process-fork-self-big-heap.js | 56 ++++++++ .../parallel/test-process-fork-self-errors.js | 61 +++++++++ test/parallel/test-process-fork-self-gc.js | 102 ++++++++++++++ test/parallel/test-process-fork-self-ipc.js | 100 ++++++++++++++ .../test-process-fork-self-jemalloc.js | 65 +++++++++ test/parallel/test-process-fork-self-many.js | 42 ++++++ .../parallel/test-process-fork-self-nested.js | 48 +++++++ .../parallel/test-process-fork-self-random.js | 62 +++++++++ 10 files changed, 724 insertions(+) create mode 100644 test/common/fork-self.js create mode 100644 test/parallel/test-process-fork-self-basic.js create mode 100644 test/parallel/test-process-fork-self-big-heap.js create mode 100644 test/parallel/test-process-fork-self-errors.js create mode 100644 test/parallel/test-process-fork-self-gc.js create mode 100644 test/parallel/test-process-fork-self-ipc.js create mode 100644 test/parallel/test-process-fork-self-jemalloc.js create mode 100644 test/parallel/test-process-fork-self-many.js create mode 100644 test/parallel/test-process-fork-self-nested.js create mode 100644 test/parallel/test-process-fork-self-random.js diff --git a/test/common/fork-self.js b/test/common/fork-self.js new file mode 100644 index 00000000000..23a25559303 --- /dev/null +++ b/test/common/fork-self.js @@ -0,0 +1,64 @@ +'use strict'; + +// Helpers for test-process-fork-self-*.js. +// +// Everything that exists before process.forkSelf() also exists in the child, +// including common.mustCall() wrappers, 'exit' listeners and the caller's +// pending code, so these tests make the child report through its exit code +// (an assertion that fails in the child exits it with code 1) and files, and +// the parent checks exit codes. + +const assert = require('assert'); + +// Forks and runs childFn in the child, then exits the child with the code it +// returns (or 0); childFn may be async. In the parent, returns a promise for +// { pid, code, signal }. In the child, returns null: the caller must return +// right away, the rest of its code is the parent's. +function forkChild(childFn) { + let resolveExit; + const exited = new Promise((resolve) => { resolveExit = resolve; }); + const pid = process.forkSelf({ + onExit(code, signal) { resolveExit({ pid, code, signal }); }, + }); + if (pid === 0) { + runInChild(childFn); + return null; + } + assert.ok(Number.isInteger(pid) && pid > 0, `pid ${pid}`); + return exited; +} + +function runInChild(childFn) { + // The parent's 'exit' listeners (common's mustCall() checks among them) + // are the parent's business; the child reports through its exit code. + process.removeAllListeners('exit'); + const self = process.pid; + // A grandchild inherits this continuation too: only the process that ran + // childFn exits when it settles. + const exit = (code) => { + // After the caller's own continuations (it returns when it gets null). + setImmediate(() => { + if (process.pid === self) process.exit(code); + }); + }; + let result; + try { + result = childFn(); + } catch (err) { + console.error(err); + exit(1); + return; + } + Promise.resolve(result).then((code) => exit(code ?? 0), (err) => { + console.error(err); + exit(1); + }); +} + +async function expectCleanExit(promise) { + const { pid, code, signal } = await promise; + assert.strictEqual(signal, null, `child ${pid} killed by ${signal}`); + assert.strictEqual(code, 0, `child ${pid} exited with ${code}`); +} + +module.exports = { forkChild, expectCleanExit }; diff --git a/test/parallel/test-process-fork-self-basic.js b/test/parallel/test-process-fork-self-basic.js new file mode 100644 index 00000000000..57f78f613b1 --- /dev/null +++ b/test/parallel/test-process-fork-self-basic.js @@ -0,0 +1,124 @@ +'use strict'; + +// process.forkSelf(): returns twice; pid and ppid; the event loop, timers, +// promises, setImmediate, fs (sync and async), dns and child_process work in +// the child; exit codes and signals reach the parent's onExit. + +const common = require('../common'); +if (typeof process.forkSelf !== 'function') { + common.skip('process.forkSelf() is not available on this platform'); +} + +const assert = require('assert'); +const fs = require('fs'); +const dns = require('dns'); +const net = require('net'); +const { spawnSync, execFile } = require('child_process'); +const { forkChild, expectCleanExit } = require('../common/fork-self'); + +const parentPid = process.pid; + +(async () => { + // Returns twice; pid/ppid. + let child = forkChild(() => { + assert.notStrictEqual(process.pid, parentPid); + assert.strictEqual(process.ppid, parentPid); + const desc = Object.getOwnPropertyDescriptor(process, 'pid'); + assert.strictEqual(desc.writable, false); + // The kernel's view: /proc/self is this process. + if (common.isLinux) { + assert.strictEqual(Number(fs.readlinkSync('/proc/self')), process.pid); + } + }); + if (!child) return; + await expectCleanExit(child); + assert.strictEqual(process.pid, parentPid); + + // Event loop: timers, setImmediate, nextTick, promises, async fs (the libuv + // threadpool is recreated in the child), fs.promises, dns, a TCP server. + child = forkChild(async () => { + const order = []; + await new Promise((resolve) => { + setTimeout(() => { order.push('timeout'); resolve(); }, 5); + setImmediate(() => order.push('immediate')); + process.nextTick(() => order.push('tick')); + queueMicrotask(() => order.push('microtask')); + }); + // (tick and microtask order depends on whether this runs in a microtask) + assert.deepStrictEqual(order.slice(2), ['immediate', 'timeout']); + assert.deepStrictEqual(order.slice(0, 2).sort(), ['microtask', 'tick']); + + const data = await fs.promises.readFile(__filename, 'utf8'); + assert.match(data, /process\.forkSelf\(\): returns twice/); + await new Promise((resolve, reject) => { + fs.stat(__filename, (err, st) => { + if (err) return reject(err); + assert.ok(st.size > 0); + resolve(); + }); + }); + // Many concurrent threadpool requests. + await Promise.all(Array.from({ length: 64 }, () => fs.promises.stat(__filename))); + + const { address } = await dns.promises.lookup('localhost'); + assert.ok(net.isIP(address)); + + await new Promise((resolve) => { + const server = net.createServer((sock) => sock.end('hi')).listen(0, () => { + net.connect(server.address().port, '127.0.0.1').on('data', (d) => { + assert.strictEqual(d.toString(), 'hi'); + server.close(resolve); + }); + }); + }); + }); + if (!child) return; + await expectCleanExit(child); + + // child_process in the child. + child = forkChild(async () => { + const r = spawnSync(process.execPath, ['-p', '6 * 7']); + assert.strictEqual(r.status, 0); + assert.strictEqual(r.stdout.toString().trim(), '42'); + const out = await new Promise((resolve, reject) => { + execFile(process.execPath, ['-p', 'process.ppid'], (err, stdout) => { + if (err) return reject(err); + resolve(stdout.trim()); + }); + }); + assert.strictEqual(Number(out), process.pid); + }); + if (!child) return; + await expectCleanExit(child); + + // Exit codes and signals. + child = forkChild(() => 7); + if (!child) return; + let r = await child; + assert.deepStrictEqual([r.code, r.signal], [7, null]); + child = forkChild(() => { + process.kill(process.pid, 'SIGTERM'); + return new Promise(() => {}); + }); + if (!child) return; + r = await child; + assert.deepStrictEqual([r.code, r.signal], [null, 'SIGTERM']); + child = forkChild(() => { throw new Error('thrown in the child (expected)'); }); + if (!child) return; + r = await child; + assert.deepStrictEqual([r.code, r.signal], [1, null]); + + // Without onExit the child is still reaped (no zombie left behind). + const pid = process.forkSelf(); + if (pid === 0) { + process.removeAllListeners('exit'); + process.exit(0); + } + if (common.isLinux) { + const deadline = Date.now() + 10_000; + while (fs.existsSync(`/proc/${pid}`) && Date.now() < deadline) { + await new Promise((resolve) => setTimeout(resolve, 10)); + } + assert.ok(!fs.existsSync(`/proc/${pid}`), `child ${pid} was not reaped`); + } +})().then(common.mustCall()); diff --git a/test/parallel/test-process-fork-self-big-heap.js b/test/parallel/test-process-fork-self-big-heap.js new file mode 100644 index 00000000000..5c6f721a72b --- /dev/null +++ b/test/parallel/test-process-fork-self-big-heap.js @@ -0,0 +1,56 @@ +// Flags: --max-old-space-size=3072 --expose-gc +'use strict'; + +// process.forkSelf() with a large heap (1 GiB by default, override with +// NODE_TEST_FORK_SELF_HEAP_MB): the child sees the parent's objects, can +// mutate them without the parent noticing, and can collect garbage over the +// whole heap. + +const common = require('../common'); +if (typeof process.forkSelf !== 'function') { + common.skip('process.forkSelf() is not available on this platform'); +} +if (common.isPi()) common.skip('Too slow for Raspberry Pi devices'); + +const assert = require('assert'); +const v8 = require('v8'); +const { forkChild, expectCleanExit } = require('../common/fork-self'); + +const targetMiB = Number(process.env.NODE_TEST_FORK_SELF_HEAP_MB || 1024); + +// ~1 KiB per entry: a string and a small object graph. +const chunks = []; +while (v8.getHeapStatistics().used_heap_size < targetMiB * 1024 * 1024) { + const chunk = []; + for (let i = 0; i < 1024; i++) { + chunk.push({ id: chunks.length * 1024 + i, s: `${i}`.padStart(900, 'x') + chunks.length, next: null }); + } + for (let i = 1; i < chunk.length; i++) chunk[i - 1].next = chunk[i]; + chunks.push(chunk); +} +const used = v8.getHeapStatistics().used_heap_size; +console.log(`parent heap: ${(used / 2 ** 20).toFixed(0)} MiB in ${chunks.length} chunks`); + +(async () => { + const t0 = process.hrtime.bigint(); + const child = forkChild(() => { + // Everything is there. + let n = 0; + for (const chunk of chunks) { + for (let node = chunk[0]; node !== null; node = node.next) n++; + } + assert.strictEqual(n, chunks.length * 1024); + // Mutate and collect over the whole heap. + for (let i = 0; i < chunks.length; i += 2) chunks[i] = null; + globalThis.gc(); + const after = v8.getHeapStatistics().used_heap_size; + assert.ok(after < used, `${after} >= ${used}`); + }); + if (!child) return; + const forkMs = Number(process.hrtime.bigint() - t0) / 1e6; + console.log(`forkSelf() with that heap: ${forkMs.toFixed(1)} ms in the parent`); + await expectCleanExit(child); + // The parent's objects are untouched. + assert.ok(chunks.every((c) => c !== null)); + assert.strictEqual(chunks[0][0].id, 0); +})().then(common.mustCall()); diff --git a/test/parallel/test-process-fork-self-errors.js b/test/parallel/test-process-fork-self-errors.js new file mode 100644 index 00000000000..dfb3f9a9749 --- /dev/null +++ b/test/parallel/test-process-fork-self-errors.js @@ -0,0 +1,61 @@ +'use strict'; + +// process.forkSelf() refuses to fork when it cannot be done safely, and +// leaves the process fully working after refusing. + +const common = require('../common'); +if (typeof process.forkSelf !== 'function') { + common.skip('process.forkSelf() is not available on this platform'); +} + +const assert = require('assert'); +const fs = require('fs'); +const { Worker } = require('worker_threads'); +const { forkChild, expectCleanExit } = require('../common/fork-self'); + +// Options are validated. +assert.throws(() => process.forkSelf(1), { code: 'ERR_INVALID_ARG_TYPE' }); +assert.throws(() => process.forkSelf({ onExit: 1 }), { code: 'ERR_INVALID_ARG_TYPE' }); + +// Not available on Worker threads. +const w = new Worker(` + require('worker_threads').parentPort.postMessage(typeof process.forkSelf); +`, { eval: true }); +w.on('message', common.mustCall((type) => { + assert.strictEqual(type, 'undefined'); +})); + +(async () => { + // While a Worker thread is alive. + assert.throws(() => process.forkSelf(), { + code: 'ERR_FORK_SELF_UNSAFE', + message: /Worker threads are running/, + }); + await new Promise((resolve) => w.on('exit', resolve)); + + // While a request is in flight on the event loop. + const pending = fs.promises.readFile(__filename); + assert.throws(() => process.forkSelf(), { + code: 'ERR_FORK_SELF_BUSY', + message: /requests are in flight/, + }); + await pending; + + // While the inspector is listening. + if (common.hasInspector) { + const inspector = require('inspector'); + inspector.open(0, '127.0.0.1', false); + assert.throws(() => process.forkSelf(), { + code: 'ERR_FORK_SELF_UNSAFE', + message: /inspector is listening/, + }); + inspector.close(); + } + + // Everything works again once the condition is gone, in both processes. + const child = forkChild(async () => { + await fs.promises.readFile(__filename); + }); + if (!child) return; + await expectCleanExit(child); +})().then(common.mustCall()); diff --git a/test/parallel/test-process-fork-self-gc.js b/test/parallel/test-process-fork-self-gc.js new file mode 100644 index 00000000000..20ad69b81f0 --- /dev/null +++ b/test/parallel/test-process-fork-self-gc.js @@ -0,0 +1,102 @@ +// Flags: --expose-gc +'use strict'; + +// V8's background threads work in a child of process.forkSelf(): garbage +// collection with concurrent marking and sweeping, and concurrent optimizing +// compilation, while the parent keeps doing the same. Forks while the parent +// is in the middle of an incremental marking cycle and has compile jobs +// queued. + +const common = require('../common'); +if (typeof process.forkSelf !== 'function') { + common.skip('process.forkSelf() is not available on this platform'); +} + +const assert = require('assert'); +const fs = require('fs'); +const v8 = require('v8'); +const { forkChild, expectCleanExit } = require('../common/fork-self'); + +function churn(rounds) { + let keep = []; + for (let r = 0; r < rounds; r++) { + const a = []; + for (let i = 0; i < 20_000; i++) a.push({ i, s: `s${i}`, arr: [i, i + 1] }); + keep.push(a); + if (keep.length > 8) keep = keep.slice(4); + } + return keep.length; +} + +// Many distinct hot functions, so that several optimizing compile jobs are +// queued for the background threads at once. +function makeHot(n) { + const fns = []; + for (let k = 0; k < n; k++) { + // eslint-disable-next-line no-new-func + fns.push(new Function('x', `let s = ${k}; for (let i = 0; i < 50; i++) s += (x * i) % ${k + 7}; return s;`)); + } + let total = 0; + for (let round = 0; round < 2000; round++) { + for (const f of fns) total += f(round); + } + return total; +} + +function threadNames() { + if (!common.isLinux) return null; + return fs.readdirSync('/proc/self/task').map((t) => { + try { + return fs.readFileSync(`/proc/self/task/${t}/comm`, 'utf8').trim(); + } catch { + return ''; + } + }); +} + +function childWork() { + const names = threadNames(); + if (names !== null) { + assert.ok(names.filter((n) => n === 'node-V8Worker').length >= 1, names.join()); + assert.ok(names.includes('DelayedTaskSche'), names.join()); + } + const before = v8.getHeapStatistics(); + churn(60); + globalThis.gc(); + makeHot(40); + churn(30); + globalThis.gc(); + const after = v8.getHeapStatistics(); + assert.ok(after.total_heap_size > 0 && before.total_heap_size > 0); +} + +(async () => { + // Plain. + let child = forkChild(childWork); + if (!child) return; + await expectCleanExit(child); + + // In the middle of allocation-heavy work (incremental marking and + // concurrent sweeping likely in progress) and with compile jobs queued. + for (let i = 0; i < 6; i++) { + churn(10 + i * 5); + makeHot(20); + child = forkChild(childWork); + if (!child) return; + // The parent keeps going too. + churn(20); + makeHot(10); + await expectCleanExit(child); + } + + // Several children working at the same time as the parent. + const children = []; + for (let i = 0; i < 4; i++) { + child = forkChild(childWork); + if (!child) return; + children.push(child); + } + churn(40); + for (const c of children) await expectCleanExit(c); + globalThis.gc(); +})().then(common.mustCall()); diff --git a/test/parallel/test-process-fork-self-ipc.js b/test/parallel/test-process-fork-self-ipc.js new file mode 100644 index 00000000000..f4be7b0ea30 --- /dev/null +++ b/test/parallel/test-process-fork-self-ipc.js @@ -0,0 +1,100 @@ +'use strict'; + +// A zygote started with child_process.fork() forks on request. The IPC +// channel it inherited belongs to it alone: each child closes its copy before +// any event loop turn (no message meant for the zygote may be consumed by a +// child), without emitting 'disconnect', and process.connected is false and +// process.send/process.channel are gone in the child. The zygote keeps +// receiving every message. + +const common = require('../common'); +if (typeof process.forkSelf !== 'function') { + common.skip('process.forkSelf() is not available on this platform'); +} + +const assert = require('assert'); +const { fork } = require('child_process'); +const fs = require('fs'); +const path = require('path'); +const tmpdir = require('../common/tmpdir'); + +const kChildren = 6; +const kNoise = 100; + +if (process.argv[2] === 'zygote') { + const dir = process.argv[3]; + let received = 0; + let exited = 0; + process.on('message', (m) => { + received++; + if (m.cmd === 'fork') { + const pid = process.forkSelf({ + onExit(code, signal) { + exited++; + process.send({ exited: pid, code, signal }); + }, + }); + if (pid === 0) { + let got = 0; + let disconnected = false; + process.on('message', () => got++); + process.on('disconnect', () => { disconnected = true; }); + // Several loop turns while the parent floods the channel. + setTimeout(() => { + fs.writeFileSync(path.join(dir, `child-${m.n}.json`), JSON.stringify({ + got, + disconnected, + connected: process.connected, + send: typeof process.send, + channel: typeof process.channel, + disconnect: typeof process.disconnect, + })); + process.exit(0); + }, 300); + return; + } + process.send({ forked: pid, n: m.n }); + } else if (m.cmd === 'count') { + process.send({ received, exitedCount: exited }); + } + }); + return; +} + +tmpdir.refresh(); +const zygote = fork(__filename, ['zygote', tmpdir.path]); +const exits = []; +let forked = 0; +zygote.on('message', common.mustCallAtLeast((m) => { + if (m.forked) { + forked++; + // Flood the channel right after the fork. + for (let i = 0; i < kNoise; i++) zygote.send({ cmd: 'noise', i }); + if (forked < kChildren) zygote.send({ cmd: 'fork', n: forked }); + } else if (m.exited) { + exits.push(m); + if (exits.length === kChildren) zygote.send({ cmd: 'count' }); + } else if (m.received !== undefined) { + for (const exit of exits) { + assert.strictEqual(exit.code, 0, JSON.stringify(exit)); + } + for (let n = 0; n < kChildren; n++) { + const child = JSON.parse( + fs.readFileSync(path.join(tmpdir.path, `child-${n}.json`))); + assert.deepStrictEqual(child, { + got: 0, + disconnected: false, + connected: false, + send: 'undefined', + channel: 'undefined', + disconnect: 'undefined', + }); + } + // Every fork request, every noise message and this count request. + assert.strictEqual(m.received, kChildren * (1 + kNoise) + 1); + assert.strictEqual(m.exitedCount, kChildren); + zygote.disconnect(); + } +})); +zygote.on('exit', common.mustCall((code) => assert.strictEqual(code, 0))); +zygote.send({ cmd: 'fork', n: 0 }); diff --git a/test/parallel/test-process-fork-self-jemalloc.js b/test/parallel/test-process-fork-self-jemalloc.js new file mode 100644 index 00000000000..e764470a9d0 --- /dev/null +++ b/test/parallel/test-process-fork-self-jemalloc.js @@ -0,0 +1,65 @@ +'use strict'; + +// process.forkSelf() in a process that runs with jemalloc preloaded +// (LD_PRELOAD=libjemalloc.so.2), with the libuv threadpool, zlib and crypto +// allocating from several threads before and after the fork. Skipped when +// jemalloc is not installed. + +const common = require('../common'); +if (typeof process.forkSelf !== 'function') { + common.skip('process.forkSelf() is not available on this platform'); +} +if (!common.isLinux) common.skip('LD_PRELOAD jemalloc test is Linux only'); + +const assert = require('assert'); +const fs = require('fs'); +const { spawnSync } = require('child_process'); + +if (process.argv[2] === 'child') { + const zlib = require('zlib'); + const crypto = require('crypto'); + const { forkChild, expectCleanExit } = require('../common/fork-self'); + const maps = fs.readFileSync('/proc/self/maps', 'utf8'); + assert.match(maps, /libjemalloc/); + + const busy = () => Promise.all([ + ...Array.from({ length: 16 }, () => new Promise((resolve, reject) => { + zlib.gzip(crypto.randomBytes(256 * 1024), (err, out) => (err ? reject(err) : resolve(out))); + })), + ...Array.from({ length: 16 }, () => new Promise((resolve, reject) => { + crypto.pbkdf2('secret', 'salt', 2000, 64, 'sha256', (err) => (err ? reject(err) : resolve())); + })), + ]); + + (async () => { + for (let i = 0; i < 20; i++) { + await busy(); + const child = forkChild(async () => { + await busy(); + const big = Array.from({ length: 2000 }, () => Buffer.alloc(4096, 1)); + assert.strictEqual(big.length, 2000); + }); + if (!child) return; + await busy(); + await expectCleanExit(child); + } + })().then(common.mustCall()); + return; +} + +const candidates = [ + '/usr/lib/aarch64-linux-gnu/libjemalloc.so.2', + '/usr/lib/x86_64-linux-gnu/libjemalloc.so.2', + '/usr/lib64/libjemalloc.so.2', + '/usr/lib/libjemalloc.so.2', +]; +const jemalloc = candidates.find((p) => fs.existsSync(p)); +if (!jemalloc) common.skip('libjemalloc.so.2 not found'); + +const r = spawnSync(process.execPath, [__filename, 'child'], { + env: { ...process.env, LD_PRELOAD: jemalloc }, + stdio: 'inherit', + timeout: 120_000, +}); +assert.strictEqual(r.signal, null); +assert.strictEqual(r.status, 0); diff --git a/test/parallel/test-process-fork-self-many.js b/test/parallel/test-process-fork-self-many.js new file mode 100644 index 00000000000..2315df4284d --- /dev/null +++ b/test/parallel/test-process-fork-self-many.js @@ -0,0 +1,42 @@ +'use strict'; + +// 1,000 sequential process.forkSelf() calls: the parent stays healthy (its V8 +// threads are stopped and restarted every time, its children are reaped), and +// every child runs JavaScript and its event loop. + +const common = require('../common'); +if (typeof process.forkSelf !== 'function') { + common.skip('process.forkSelf() is not available on this platform'); +} + +const assert = require('assert'); +const fs = require('fs'); +const { forkChild } = require('../common/fork-self'); + +const kForks = 1000; + +(async () => { + let objects = []; + const start = process.hrtime.bigint(); + for (let i = 0; i < kForks; i++) { + // Keep the parent's heap and JIT busy between forks. + objects.push({ i, s: `x${i}`.repeat(10) }); + if (objects.length > 500) objects = objects.slice(250); + const child = forkChild(() => new Promise((resolve) => { + setImmediate(() => resolve(i % 256 === 255 ? 0 : i % 256)); + })); + if (!child) return; + const { code, signal } = await child; + assert.strictEqual(signal, null); + assert.strictEqual(code, i % 256 === 255 ? 0 : i % 256); + } + const ms = Number(process.hrtime.bigint() - start) / 1e6; + console.log(`${kForks} sequential forks in ${ms.toFixed(0)} ms`); + if (common.isLinux) { + // No zombies left behind, and the parent has its usual set of threads. + const children = fs.readFileSync(`/proc/${process.pid}/task/${process.pid}/children`, 'utf8').trim(); + assert.strictEqual(children, ''); + const threads = fs.readdirSync('/proc/self/task').length; + assert.ok(threads < 32, `${threads} threads`); + } +})().then(common.mustCall()); diff --git a/test/parallel/test-process-fork-self-nested.js b/test/parallel/test-process-fork-self-nested.js new file mode 100644 index 00000000000..ca601ba5d1d --- /dev/null +++ b/test/parallel/test-process-fork-self-nested.js @@ -0,0 +1,48 @@ +'use strict'; + +// A child of process.forkSelf() can fork again (children of children), each +// level reaping its own children, with pids and randomness per process. + +const common = require('../common'); +if (typeof process.forkSelf !== 'function') { + common.skip('process.forkSelf() is not available on this platform'); +} + +const assert = require('assert'); +const fs = require('fs'); +const path = require('path'); +const tmpdir = require('../common/tmpdir'); +const { forkChild, expectCleanExit } = require('../common/fork-self'); + +tmpdir.refresh(); +const kDepth = 4; + +function level(depth) { + return async () => { + fs.writeFileSync(path.join(tmpdir.path, `level-${depth}.json`), + JSON.stringify({ pid: process.pid, ppid: process.ppid, r: Math.random() })); + if (depth < kDepth) { + let child = forkChild(level(depth + 1)); + if (!child) return; + await expectCleanExit(child); + // Fork twice at this level, the second one after the first was reaped. + child = forkChild(() => {}); + if (!child) return; + await expectCleanExit(child); + } + }; +} + +(async () => { + const child = forkChild(level(1)); + if (!child) return; + await expectCleanExit(child); + const levels = [{ pid: process.pid }]; + for (let d = 1; d <= kDepth; d++) { + levels.push(JSON.parse(fs.readFileSync(path.join(tmpdir.path, `level-${d}.json`)))); + } + for (let d = 1; d <= kDepth; d++) { + assert.strictEqual(levels[d].ppid, levels[d - 1].pid); + } + assert.strictEqual(new Set(levels.map((l) => l.r)).size, levels.length); +})().then(common.mustCall()); diff --git a/test/parallel/test-process-fork-self-random.js b/test/parallel/test-process-fork-self-random.js new file mode 100644 index 00000000000..05bb0af3bc9 --- /dev/null +++ b/test/parallel/test-process-fork-self-random.js @@ -0,0 +1,62 @@ +'use strict'; + +// Children of process.forkSelf() must not share randomness with the parent or +// with each other: crypto.randomBytes (OpenSSL's DRBG notices the pid change +// and reseeds), Node's randomUUID and randomInt caches, getRandomValues, and +// Math.random in the main context and in vm contexts (V8's per-context state +// and the isolate's generator are reseeded). + +const common = require('../common'); +if (typeof process.forkSelf !== 'function') { + common.skip('process.forkSelf() is not available on this platform'); +} +if (!common.hasCrypto) common.skip('missing crypto'); + +const assert = require('assert'); +const crypto = require('crypto'); +const fs = require('fs'); +const path = require('path'); +const vm = require('vm'); +const tmpdir = require('../common/tmpdir'); +const { forkChild, expectCleanExit } = require('../common/fork-self'); + +tmpdir.refresh(); + +const context = vm.createContext({}); + +function sample() { + return { + bytes: crypto.randomBytes(16).toString('hex'), + uuid: crypto.randomUUID(), + uuidUnbuffered: crypto.randomUUID({ disableEntropyCache: true }), + int: crypto.randomInt(2 ** 47), + values: Buffer.from(crypto.getRandomValues(new Uint8Array(16))).toString('hex'), + math: Math.random(), + vmMath: vm.runInContext('Math.random()', context), + }; +} + +// Fill every cache in the parent first, so that a child that kept them would +// hand out the same values as its siblings. +const parent = sample(); + +(async () => { + const kChildren = 4; + const exits = []; + for (let i = 0; i < kChildren; i++) { + const child = forkChild(() => { + fs.writeFileSync(path.join(tmpdir.path, `child-${i}.json`), + JSON.stringify(sample())); + }); + if (!child) return; + exits.push(child); + } + for (const exit of exits) await expectCleanExit(exit); + const samples = [parent, ...Array.from({ length: kChildren }, (_, i) => + JSON.parse(fs.readFileSync(path.join(tmpdir.path, `child-${i}.json`))))]; + for (const key of Object.keys(parent)) { + const values = new Set(samples.map((s) => s[key])); + assert.strictEqual(values.size, samples.length, + `${key} repeated across processes: ${[...values]}`); + } +})().then(common.mustCall()); From 264c1bb918347c3466acfbfcbdaa564de5e8b02a Mon Sep 17 00:00:00 2001 From: Max schwenk Date: Thu, 12 Nov 2026 02:27:43 -0500 Subject: [PATCH 06/16] src: handle the CA certificate threads and unknown threads in forkSelf() After the first TLS use, Node.js parses the CA certificates on one-shot threads and joins them at exit. A child of process.forkSelf() crashed at exit trying to join them (they are the parent's), and a fork while one was still running would have left the certificate caches half initialized in the child. forkSelf() now waits for them first and marks them joined. forkSelf() also lists the process's threads (Linux) once its own are stopped, and refuses to fork when any thread it does not know to survive fork(2) is still running, such as a native addon's. --- src/crypto/crypto_context.cc | 17 ++++++ src/crypto/crypto_util.h | 5 ++ src/node_process_fork.cc | 65 +++++++++++++++++++++ test/parallel/test-process-fork-self-tls.js | 54 +++++++++++++++++ 4 files changed, 141 insertions(+) create mode 100644 test/parallel/test-process-fork-self-tls.js diff --git a/src/crypto/crypto_context.cc b/src/crypto/crypto_context.cc index 64be71541fe..d3b58502b6f 100644 --- a/src/crypto/crypto_context.cc +++ b/src/crypto/crypto_context.cc @@ -1109,6 +1109,23 @@ X509_STORE* NewRootCertStore(Environment* env) { return store; } +void JoinCertificateLoadingThreads() { + { + Mutex::ScopedLock lock(start_cert_loading_thread_mutex); + if (cert_loading_thread_started.load()) { + uv_thread_join(&cert_loading_thread); + cert_loading_thread_started.store(false); + } + } + { + Mutex::ScopedLock lock(start_system_cert_loading_thread_mutex); + if (system_cert_loading_thread_started.load()) { + uv_thread_join(&system_cert_loading_thread); + system_cert_loading_thread_started.store(false); + } + } +} + void CleanupCachedRootCertificates() { // Serialize with starters to avoid the race window. { diff --git a/src/crypto/crypto_util.h b/src/crypto/crypto_util.h index 00ac9f6703a..da9b5d041e1 100644 --- a/src/crypto/crypto_util.h +++ b/src/crypto/crypto_util.h @@ -77,6 +77,11 @@ void InitCrypto(v8::Local target); extern void UseExtraCaCerts(std::string_view file); void CleanupCachedRootCertificates(); +// For process.forkSelf(): waits for the threads that load CA certificates off +// the main thread, if they were started, so that they neither run (half way +// through initializing the certificate caches) at the instant of fork(2) nor +// are joined again later, which the child could not do. +void JoinCertificateLoadingThreads(); int PasswordCallback(char* buf, int size, int rwflag, void* u); int NoPasswordCallback(char* buf, int size, int rwflag, void* u); diff --git a/src/node_process_fork.cc b/src/node_process_fork.cc index aba2aa317bb..d887cc416fb 100644 --- a/src/node_process_fork.cc +++ b/src/node_process_fork.cc @@ -29,6 +29,9 @@ #include "uv.h" #include "v8-fork.h" #include "v8.h" +#if HAVE_OPENSSL +#include "crypto/crypto_util.h" +#endif #if defined(__POSIX__) && !defined(__PASE__) #include @@ -36,6 +39,8 @@ #include #include #include +#include +#include #include #endif @@ -179,6 +184,42 @@ ForkedChildren* GetForkedChildren(Environment* env) { return children; } +// The threads of this process other than the calling one that fork(2) cannot +// leave behind safely, by name. Known to be fine: the SIGUSR1 watchdog +// (recreated in the child) and idle libuv threadpool workers (libuv's atfork +// handler recreates the pool; no request is in flight, checked above). +// Linux only; elsewhere the list is empty. +std::string UnknownThreads() { + std::string unknown; +#ifdef __linux__ + const pid_t self = getpid(); + uv_fs_t req; + if (uv_fs_scandir(nullptr, &req, "/proc/self/task", 0, nullptr) < 0) { + uv_fs_req_cleanup(&req); + return unknown; + } + uv_dirent_t ent; + while (uv_fs_scandir_next(&req, &ent) == 0) { + const pid_t tid = static_cast(strtol(ent.name, nullptr, 10)); + if (tid == self) continue; + std::string path = std::string("/proc/self/task/") + ent.name + "/comm"; + char name[64] = {0}; + FILE* f = fopen(path.c_str(), "re"); + if (f == nullptr) continue; // Exited meanwhile. + if (fgets(name, sizeof(name), f) == nullptr) name[0] = '\0'; + fclose(f); + std::string comm(name); + while (!comm.empty() && (comm.back() == '\n' || comm.back() == ' ')) + comm.pop_back(); + if (comm == "SignalInspector" || comm == "libuv-worker") continue; + if (!unknown.empty()) unknown += ", "; + unknown += comm + " (" + ent.name + ")"; + } + uv_fs_req_cleanup(&req); +#endif + return unknown; +} + } // namespace // setForkSelfExitCallback(fn): fn(pid, exitCode, signal) runs when a child @@ -256,10 +297,34 @@ void ForkSelf(const FunctionCallbackInfo& args) { // Nothing buffered by C stdio may be written by both processes. fflush(nullptr); +#if HAVE_OPENSSL + // One-shot threads that parse the CA certificates after the first TLS use. + crypto::JoinCertificateLoadingThreads(); +#endif + if (!platform->StopThreadsForFork(stop_timeout_ms)) { return args.GetReturnValue().Set(kForkSelfBusy); } + // Every thread that is still running now must be one that survives fork(2) + // as is. Anything else (a native addon's thread, a Node.js thread this + // code does not know about) would be missing in the child while its state + // says it runs, possibly holding a lock. + std::string unknown_threads = UnknownThreads(); + // A thread that was just joined can still be listed for a moment. + for (int i = 0; i < 20 && !unknown_threads.empty(); i++) { + uv_sleep(1); + unknown_threads = UnknownThreads(); + } + if (!unknown_threads.empty()) { + platform->RestartThreadsAfterFork(); + return THROW_ERR_FORK_SELF_UNSAFE( + env, + "process.forkSelf() cannot fork while threads it does not know how to " + "handle are running (native addons?): %s", + unknown_threads); + } + // libuv clears the pending flag of every async handle in the child (another // thread could have been half way through uv_async_send()). No thread can // send now, so this is the exact set the child has to wake up again. diff --git a/test/parallel/test-process-fork-self-tls.js b/test/parallel/test-process-fork-self-tls.js new file mode 100644 index 00000000000..40dc6cf05ca --- /dev/null +++ b/test/parallel/test-process-fork-self-tls.js @@ -0,0 +1,54 @@ +'use strict'; + +// After the first TLS use, Node.js parses the CA certificates on a one-shot +// background thread and joins it at exit. A child of process.forkSelf() must +// neither inherit that thread half way through (the certificate caches would +// stay half initialized) nor try to join it at exit (it is the parent's). + +const common = require('../common'); +if (typeof process.forkSelf !== 'function') { + common.skip('process.forkSelf() is not available on this platform'); +} +if (!common.hasCrypto) common.skip('missing crypto'); + +const assert = require('assert'); +const tls = require('tls'); +const fixtures = require('../common/fixtures'); +const { forkChild, expectCleanExit } = require('../common/fork-self'); + +// Starts the certificate loading thread; fork right away, while it may still +// be running. +tls.createSecureContext(); + +(async () => { + for (const how of ['exit', 'reallyExit']) { + const child = forkChild(async () => { + // The default CA store works in the child. + const ctx = tls.createSecureContext(); + assert.ok(ctx.context); + assert.ok(tls.rootCertificates.length > 0); + // And a TLS connection works end to end. + await new Promise((resolve, reject) => { + const server = tls.createServer({ + key: fixtures.readKey('agent1-key.pem'), + cert: fixtures.readKey('agent1-cert.pem'), + }, (socket) => socket.end('hello')).listen(0, () => { + const client = tls.connect({ + port: server.address().port, + rejectUnauthorized: false, + }, () => { + client.on('data', (d) => { + assert.strictEqual(d.toString(), 'hello'); + client.end(); + server.close(resolve); + }); + }); + client.on('error', reject); + }); + }); + if (how === 'reallyExit') process.reallyExit(0); + }); + if (!child) return; + await expectCleanExit(child); + } +})().then(common.mustCall()); From cc396e41188ba315116b4b8d2ddf9f44efeee777 Mon Sep 17 00:00:00 2001 From: Max schwenk Date: Thu, 12 Nov 2026 02:40:00 -0500 Subject: [PATCH 07/16] deps: make V8's fork optimization switchable, reopen perf maps MakeMappingsForkable() used to drop MADV_DONTFORK for good, which made every later fork+exec (child_process.spawn() is fork+exec in libuv) copy the page tables of the whole heap: spawnSync('/bin/true') from a process with a 1.5 GiB heap went from 6 ms to 57 ms. V8 now keeps the record of its ranges and MakeMappingsUnforkable() marks them all MADV_DONTFORK again; mappings made in between are recorded and marked then. ReopenPerfMapAfterFork(): with --perf-basic-prof, a forked child copies the parent's perf-.map (which describes the code it inherited) to its own perf-.map and writes new entries there, instead of appending to the parent's file. --- deps/v8/include/v8-fork.h | 22 +++++++++-- deps/v8/src/api/api.cc | 14 +++++++ deps/v8/src/base/platform/platform-posix.cc | 44 +++++++++++++-------- deps/v8/src/logging/log.cc | 44 +++++++++++++++++++++ 4 files changed, 104 insertions(+), 20 deletions(-) diff --git a/deps/v8/include/v8-fork.h b/deps/v8/include/v8-fork.h index 6c50b194829..6621027a641 100644 --- a/deps/v8/include/v8-fork.h +++ b/deps/v8/include/v8-fork.h @@ -28,12 +28,26 @@ V8_EXPORT void ReseedRandomNumberGeneratorsAfterFork(Isolate* isolate); * * Built with v8_enable_private_mapping_fork_optimization (the Linux default in * Node.js), V8 marks the memory it maps MADV_DONTFORK, so that fork+exec does - * not copy the page tables of the heap; a forked child then has no heap. This - * clears that mark on every mapping made so far and stops marking new ones, - * for the rest of the process's life (and its forked children's). Cheap after - * the first call. Thread-safe. + * not copy the page tables of the heap; a forked child then has no heap. + * MakeMappingsForkable() clears that mark on every mapping V8 holds, and new + * mappings are not marked until MakeMappingsUnforkable() marks them all + * again; call that before a fork that is followed by exec. Each call that + * changes the state costs one madvise() per mapping; calls that do not + * change it are cheap. The state is inherited by forked children. + * Thread-safe. Do nothing where the optimization is not built in. */ V8_EXPORT void MakeMappingsForkable(); +V8_EXPORT void MakeMappingsUnforkable(); + +/** + * Experimental, for embedders that fork(2) a process with a live isolate. + * + * With --perf-basic-prof (or --perf-basic-prof-only-functions), call this in + * the child: it copies the parent's perf-.map, which describes the code + * the child inherited, to the child's own perf-.map and writes new + * entries there. Does nothing otherwise. --perf-prof (jitdump) is not handled. + */ +V8_EXPORT void ReopenPerfMapAfterFork(); } // namespace v8 diff --git a/deps/v8/src/api/api.cc b/deps/v8/src/api/api.cc index 38d1ece2034..2cc25065b01 100644 --- a/deps/v8/src/api/api.cc +++ b/deps/v8/src/api/api.cc @@ -10731,6 +10731,7 @@ void Isolate::Freeze(bool is_frozen) { namespace base { // Defined in src/base/platform/platform-posix.cc. void MakeMappingsForkable(); +void MakeMappingsUnforkable(); } // namespace base #endif @@ -10740,6 +10741,19 @@ void MakeMappingsForkable() { #endif } +void MakeMappingsUnforkable() { +#if V8_OS_POSIX + base::MakeMappingsUnforkable(); +#endif +} + +namespace internal { +// Defined in src/logging/log.cc. +void ReopenPerfBasicLogAfterFork(); +} // namespace internal + +void ReopenPerfMapAfterFork() { i::ReopenPerfBasicLogAfterFork(); } + void ReseedRandomNumberGeneratorsAfterFork(Isolate* isolate) { i::Isolate* i_isolate = reinterpret_cast(isolate); // With a fixed seed the embedder asked for reproducible sequences. diff --git a/deps/v8/src/base/platform/platform-posix.cc b/deps/v8/src/base/platform/platform-posix.cc index fef32577819..56447c92816 100644 --- a/deps/v8/src/base/platform/platform-posix.cc +++ b/deps/v8/src/base/platform/platform-posix.cc @@ -185,11 +185,13 @@ LazyMutex g_dontfork_mutex = LAZY_MUTEX_INITIALIZER; std::map* g_dontfork_ranges = nullptr; // start -> end void MarkDontFork(void* address, size_t size) { - if (g_mappings_forkable.load(std::memory_order_relaxed)) return; MutexGuard guard(g_dontfork_mutex.Pointer()); - if (g_mappings_forkable.load(std::memory_order_relaxed)) return; - // This is advisory, so we ignore errors. - madvise(address, size, MADV_DONTFORK); + // While the mappings are forkable (see MakeMappingsForkable()), new ones + // are only recorded; MakeMappingsUnforkable() marks them later. + if (!g_mappings_forkable.load(std::memory_order_relaxed)) { + // This is advisory, so we ignore errors. + madvise(address, size, MADV_DONTFORK); + } if (g_dontfork_ranges == nullptr) { g_dontfork_ranges = new std::map(); } @@ -198,7 +200,6 @@ void MarkDontFork(void* address, size_t size) { } void ForgetDontFork(void* address, size_t size) { - if (g_mappings_forkable.load(std::memory_order_relaxed)) return; MutexGuard guard(g_dontfork_mutex.Pointer()); if (g_dontfork_ranges == nullptr) return; const uintptr_t start = reinterpret_cast(address); @@ -263,24 +264,35 @@ void* Allocate(void* hint, size_t size, OS::MemoryPermission access, } // namespace -// Experimental, see v8::MakeMappingsForkable() in include/v8-fork.h: clears -// MADV_DONTFORK on everything this process marked so far and stops marking -// new mappings. Irreversible. -void MakeMappingsForkable() { +// Experimental, see include/v8-fork.h. Switch V8's mappings between copied by +// fork(2) (needed by a forked child that keeps using the isolate) and +// MADV_DONTFORK (cheap fork+exec). #if V8_OS_LINUX && V8_ENABLE_PRIVATE_MAPPING_FORK_OPTIMIZATION - if (g_mappings_forkable.load(std::memory_order_acquire)) return; +static void SetMappingsForkable(bool forkable) { + if (g_mappings_forkable.load(std::memory_order_acquire) == forkable) return; MutexGuard guard(g_dontfork_mutex.Pointer()); - if (g_mappings_forkable.load(std::memory_order_relaxed)) return; + if (g_mappings_forkable.load(std::memory_order_relaxed) == forkable) return; if (g_dontfork_ranges != nullptr) { for (const auto& [start, end] : *g_dontfork_ranges) { - // Advisory; a range that was replaced by another mapping only fails. - madvise(reinterpret_cast(start), end - start, MADV_DOFORK); + // Advisory; a range that is not entirely mapped any more only fails. + madvise(reinterpret_cast(start), end - start, + forkable ? MADV_DOFORK : MADV_DONTFORK); } - delete g_dontfork_ranges; - g_dontfork_ranges = nullptr; } - g_mappings_forkable.store(true, std::memory_order_release); + g_mappings_forkable.store(forkable, std::memory_order_release); +} #endif // V8_OS_LINUX && V8_ENABLE_PRIVATE_MAPPING_FORK_OPTIMIZATION + +void MakeMappingsForkable() { +#if V8_OS_LINUX && V8_ENABLE_PRIVATE_MAPPING_FORK_OPTIMIZATION + SetMappingsForkable(true); +#endif +} + +void MakeMappingsUnforkable() { +#if V8_OS_LINUX && V8_ENABLE_PRIVATE_MAPPING_FORK_OPTIMIZATION + SetMappingsForkable(false); +#endif } // TODO(v8:10026): Add the right permission flag to make executable pages diff --git a/deps/v8/src/logging/log.cc b/deps/v8/src/logging/log.cc index 6de82a480d4..c6261831985 100644 --- a/deps/v8/src/logging/log.cc +++ b/deps/v8/src/logging/log.cc @@ -378,6 +378,13 @@ class PerfBasicLogger : public CodeEventLogger { static base::LazyRecursiveMutex& GetFileMutex(); + public: + // In a child created by fork(2): the open file is the parent's. Copy it + // (the code it describes so far is the child's too) to this process's own + // perf-.map and continue there. + static void ReopenAfterFork(); + + private: // Extension added to V8 log file name to get the low-level log name. static const char kFilenameFormatString[]; static const int kFilenameBufferPadding; @@ -386,6 +393,8 @@ class PerfBasicLogger : public CodeEventLogger { // to determine when it goes away, we keep the reference count. static FILE* perf_output_handle_; static uint64_t reference_count_; + // The pid in the name of the file perf_output_handle_ writes to. + static int perf_output_pid_; }; // Extra space for the "perf-%d.map" filename, including the PID. @@ -401,6 +410,40 @@ base::LazyRecursiveMutex& PerfBasicLogger::GetFileMutex() { // PerfBasicLogger::GetFileMutex(). uint64_t PerfBasicLogger::reference_count_ = 0; FILE* PerfBasicLogger::perf_output_handle_ = nullptr; +int PerfBasicLogger::perf_output_pid_ = 0; + +// static +void PerfBasicLogger::ReopenAfterFork() { + base::LockGuard guard_file(GetFileMutex().Pointer()); + if (perf_output_handle_ == nullptr) return; + const int pid = base::OS::GetCurrentProcessId(); + if (pid == perf_output_pid_) return; + const char* base_dir = v8_flags.perf_basic_prof_path; + base::ScopedVector old_name(strlen(base_dir) + kFilenameBufferPadding); + base::ScopedVector new_name(strlen(base_dir) + kFilenameBufferPadding); + CHECK_NE(SNPrintF(old_name, "%s/perf-%d.map", base_dir, perf_output_pid_), + -1); + CHECK_NE(SNPrintF(new_name, "%s/perf-%d.map", base_dir, pid), -1); + // Everything written before the fork is in the file (it is line buffered; + // flush the rest of a partial line, if any). + fflush(perf_output_handle_); + FILE* out = base::OS::FOpen(new_name.begin(), base::OS::LogFileOpenMode); + if (out == nullptr) return; // Keep writing to the parent's file. + if (FILE* in = base::OS::FOpen(old_name.begin(), "r")) { + char buffer[64 * 1024]; + size_t n; + while ((n = fread(buffer, 1, sizeof(buffer), in)) > 0) { + fwrite(buffer, 1, n, out); + } + fclose(in); + } + fclose(perf_output_handle_); + perf_output_handle_ = out; + perf_output_pid_ = pid; + setvbuf(perf_output_handle_, nullptr, _IOLBF, 0); +} + +void ReopenPerfBasicLogAfterFork() { PerfBasicLogger::ReopenAfterFork(); } PerfBasicLogger::PerfBasicLogger(Isolate* isolate) : CodeEventLogger(isolate) { base::LockGuard guard_file(GetFileMutex().Pointer()); @@ -420,6 +463,7 @@ PerfBasicLogger::PerfBasicLogger(Isolate* isolate) : CodeEventLogger(isolate) { perf_output_handle_ = base::OS::FOpen(perf_dump_name.begin(), base::OS::LogFileOpenMode); CHECK_NOT_NULL(perf_output_handle_); + perf_output_pid_ = process_id_; setvbuf(perf_output_handle_, nullptr, _IOLBF, 0); } } From 072d2f56dc80451ec8112e946384b77636d58c0d Mon Sep 17 00:00:00 2001 From: Max schwenk Date: Thu, 12 Nov 2026 02:40:01 -0500 Subject: [PATCH 08/16] src: restore fast spawns after forkSelf(), reopen perf maps in children Before uv_spawn(), mark V8's mappings MADV_DONTFORK again if process.forkSelf() made them copyable; a child of forkSelf() (which inherits the copyable state) pays for that once, at its first spawn. In the child, write --perf-basic-prof entries to the child's own map file. NODE_FORK_SELF_TIMING=1 prints where the parent's time goes in each forkSelf() call. --- src/node_process_fork.cc | 20 +++++++++ src/node_task_runner.cc | 4 ++ src/process_wrap.cc | 4 ++ src/spawn_sync.cc | 4 ++ .../test-process-fork-self-perf-map.js | 44 +++++++++++++++++++ 5 files changed, 76 insertions(+) create mode 100644 test/parallel/test-process-fork-self-perf-map.js diff --git a/src/node_process_fork.cc b/src/node_process_fork.cc index d887cc416fb..1372912fabf 100644 --- a/src/node_process_fork.cc +++ b/src/node_process_fork.cc @@ -289,10 +289,14 @@ void ForkSelf(const FunctionCallbackInfo& args) { if (value >= 0) stop_timeout_ms = static_cast(value); } + static const bool print_timing = getenv("NODE_FORK_SELF_TIMING") != nullptr; + const uint64_t t_start = uv_hrtime(); + // On Linux V8 marks its mappings MADV_DONTFORK (so that child_process // spawns do not copy the heap's page tables): the child needs them. Once per // process, a few milliseconds the first time. v8::MakeMappingsForkable(); + const uint64_t t_forkable = uv_hrtime(); // Nothing buffered by C stdio may be written by both processes. fflush(nullptr); @@ -302,9 +306,11 @@ void ForkSelf(const FunctionCallbackInfo& args) { crypto::JoinCertificateLoadingThreads(); #endif + const uint64_t t_certs = uv_hrtime(); if (!platform->StopThreadsForFork(stop_timeout_ms)) { return args.GetReturnValue().Set(kForkSelfBusy); } + const uint64_t t_stopped = uv_hrtime(); // Every thread that is still running now must be one that survives fork(2) // as is. Anything else (a native addon's thread, a Node.js thread this @@ -334,8 +340,10 @@ void ForkSelf(const FunctionCallbackInfo& args) { #if HAVE_INSPECTOR inspector::PrepareForFork(); #endif + const uint64_t t_fork = uv_hrtime(); const pid_t pid = fork(); const int fork_errno = errno; + const uint64_t t_forked = uv_hrtime(); if (pid == 0) { // In the child, before anything can use the loop or wake it up from @@ -355,6 +363,7 @@ void ForkSelf(const FunctionCallbackInfo& args) { } DisownStdioAfterFork(); v8::ReseedRandomNumberGeneratorsAfterFork(env->isolate()); + v8::ReopenPerfMapAfterFork(); // process.pid was computed once at startup. It is a configurable, // read-only data property (see PatchProcessObject()). Isolate* isolate = env->isolate(); @@ -370,6 +379,17 @@ void ForkSelf(const FunctionCallbackInfo& args) { #endif platform->RestartThreadsAfterFork(); + if (print_timing && pid != 0) { + const uint64_t t_end = uv_hrtime(); + auto ms = [](uint64_t a, uint64_t b) { return (b - a) / 1e6; }; + fprintf(stderr, + "forkSelf timing (ms): forkable %.3f certs %.3f stop %.3f " + "census %.3f fork %.3f restart %.3f total %.3f\n", + ms(t_start, t_forkable), ms(t_forkable, t_certs), + ms(t_certs, t_stopped), ms(t_stopped, t_fork), + ms(t_fork, t_forked), ms(t_forked, t_end), ms(t_start, t_end)); + } + if (pid < 0) { return env->ThrowErrnoException(fork_errno, "fork"); } diff --git a/src/node_task_runner.cc b/src/node_task_runner.cc index 136dec24fa0..4a67fafc982 100644 --- a/src/node_task_runner.cc +++ b/src/node_task_runner.cc @@ -1,6 +1,7 @@ #include "node_task_runner.h" #include "simdjson.h" #include "util-inl.h" +#include "v8-fork.h" #include // NOLINT(build/c++11) @@ -214,6 +215,9 @@ void ProcessRunner::Run() { // keeps the string alive until destructor cwd_ = ConvertPathToUTF8(package_json_path_.parent_path()); options_.cwd = cwd_.c_str(); + // A fork that is followed by exec: let it skip the heap again if + // process.forkSelf() made the heap copyable. + v8::MakeMappingsUnforkable(); if (int r = uv_spawn(loop_, &process_, &options_)) { fprintf(stderr, "Error: %s\n", uv_strerror(r)); } diff --git a/src/process_wrap.cc b/src/process_wrap.cc index 8ca42a784de..e45807c0078 100644 --- a/src/process_wrap.cc +++ b/src/process_wrap.cc @@ -26,6 +26,7 @@ #include "stream_base-inl.h" #include "stream_wrap.h" #include "util-inl.h" +#include "v8-fork.h" #include #include @@ -326,6 +327,9 @@ class ProcessWrap : public HandleWrap { } if (err == 0) { + // A fork that is followed by exec: let it skip the heap again if + // process.forkSelf() made the heap copyable. + v8::MakeMappingsUnforkable(); err = uv_spawn(env->event_loop(), &wrap->process_, &options); wrap->MarkAsInitialized(); } diff --git a/src/spawn_sync.cc b/src/spawn_sync.cc index 0358bb995fe..8e8c84e02f5 100644 --- a/src/spawn_sync.cc +++ b/src/spawn_sync.cc @@ -27,6 +27,7 @@ #include "node_internals.h" #include "string_bytes.h" #include "util-inl.h" +#include "v8-fork.h" #include #include "nbytes.h" @@ -514,6 +515,9 @@ Maybe SyncProcessRunner::TryInitializeAndRunLoop(Local options) { } uv_process_options_.exit_cb = ExitCallback; + // A fork that is followed by exec: let it skip the heap again if + // process.forkSelf() made the heap copyable. + v8::MakeMappingsUnforkable(); r = uv_spawn(uv_loop_, &uv_process_, &uv_process_options_); if (r < 0) { SetError(r); diff --git a/test/parallel/test-process-fork-self-perf-map.js b/test/parallel/test-process-fork-self-perf-map.js new file mode 100644 index 00000000000..779a53e3b43 --- /dev/null +++ b/test/parallel/test-process-fork-self-perf-map.js @@ -0,0 +1,44 @@ +// Flags: --perf-basic-prof +'use strict'; + +// With --perf-basic-prof, a child of process.forkSelf() writes its own +// perf-.map, which starts with everything the parent had written (the +// code the child inherited) and continues with the child's own code. + +const common = require('../common'); +if (typeof process.forkSelf !== 'function') { + common.skip('process.forkSelf() is not available on this platform'); +} +if (!common.isLinux) common.skip('--perf-basic-prof is Linux only'); + +const assert = require('assert'); +const fs = require('fs'); +const { forkChild, expectCleanExit } = require('../common/fork-self'); + +function hot(name) { + // eslint-disable-next-line no-new-func + const f = new Function('x', `return function ${name}(y) { return x + y; }`)(1); + for (let i = 0; i < 1e5; i++) f(i); + return f; +} + +hot('compiledInTheParent'); +const parentMap = `/tmp/perf-${process.pid}.map`; +assert.match(fs.readFileSync(parentMap, 'utf8'), /compiledInTheParent/); + +(async () => { + let childPid; + const child = forkChild(() => { + hot('compiledInTheChild'); + fs.writeFileSync(`/tmp/fork-self-perf-map-${process.ppid}`, String(process.pid)); + }); + if (!child) return; + ({ pid: childPid } = await expectCleanExit(child).then(() => child)); + const childMap = `/tmp/perf-${childPid}.map`; + const text = fs.readFileSync(childMap, 'utf8'); + assert.match(text, /compiledInTheParent/); + assert.match(text, /compiledInTheChild/); + assert.doesNotMatch(fs.readFileSync(parentMap, 'utf8'), /compiledInTheChild/); + fs.unlinkSync(childMap); + fs.unlinkSync(`/tmp/fork-self-perf-map-${process.pid}`); +})().then(common.mustCall()); From 38945eb1cec99e3defc39b7dce8182819f410307 Mon Sep 17 00:00:00 2001 From: Max schwenk Date: Thu, 12 Nov 2026 02:40:01 -0500 Subject: [PATCH 09/16] doc: document process.forkSelf() --- doc/api/errors.md | 28 +++++++++++ doc/api/process.md | 115 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 143 insertions(+) diff --git a/doc/api/errors.md b/doc/api/errors.md index 42d054bddb2..9a0d12a8554 100644 --- a/doc/api/errors.md +++ b/doc/api/errors.md @@ -1417,6 +1417,33 @@ An invalid pointer was passed to an FFI operation. An operation was attempted on an FFI dynamic library after it was closed. + + +### `ERR_FORK_SELF_BUSY` + + + +> Stability: 1 - Experimental + +[`process.forkSelf()`][] could not fork right now: requests were in flight on +the event loop, or V8's background threads did not become idle. Calling it +again once the event loop is idle can succeed. + + + +### `ERR_FORK_SELF_UNSAFE` + + + +> Stability: 1 - Experimental + +[`process.forkSelf()`][] cannot fork this process safely in its current state, +for example while Worker threads are running or the inspector is listening. + ### `ERR_FS_CP_DIR_TO_NON_DIR` @@ -4843,3 +4870,4 @@ An error occurred trying to allocate memory. This should never happen. [try-catch]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch [type-stripping]: typescript.md#type-stripping [vm]: vm.md +[`process.forkSelf()`]: process.md#processforkselfoptions diff --git a/doc/api/process.md b/doc/api/process.md index 33dfd847716..4878bbefe05 100644 --- a/doc/api/process.md +++ b/doc/api/process.md @@ -2282,6 +2282,114 @@ function setup() { setup(); ``` +## `process.forkSelf([options])` + + + +> Stability: 1 - Experimental + +* `options` {Object} + * `onExit` {Function} Called in the parent once the child has exited, with + the same arguments as the [`'exit'`][] event of a `ChildProcess`: + * `code` {integer|null} The exit code, or `null` if the child was killed + by a signal. + * `signal` {string|null} The name of the signal that killed the child, or + `null`. + + While a child forked with `onExit` is running, it keeps the parent's event + loop alive. +* Returns: {integer} The process id of the child in the parent, and `0` in the + child. + +Forks the running process with `fork(2)`: the child is a copy of the parent +with its JavaScript heap, loaded modules, compiled code, timers and other +handles, and both processes continue by returning from `process.forkSelf()`. +A process that spends a long time getting ready (loading and compiling many +modules) can do that once and then fork copies of itself, which share the +parent's memory until they write to it. + +```mjs +const pid = process.forkSelf({ + onExit(code, signal) { + console.log(`child ${pid} exited with ${code ?? signal}`); + }, +}); +if (pid === 0) { + // In the child. + console.log(`I am ${process.pid}, forked from ${process.ppid}`); + process.exit(0); +} +``` + +```cjs +const pid = process.forkSelf({ + onExit(code, signal) { + console.log(`child ${pid} exited with ${code ?? signal}`); + }, +}); +if (pid === 0) { + // In the child. + console.log(`I am ${process.pid}, forked from ${process.ppid}`); + process.exit(0); +} +``` + +Node.js makes the following safe in the child, before `process.forkSelf()` +returns `0` and before any event loop turn: + +* The event loop is reinitialized (`uv_loop_fork()`); timers, file system + operations, DNS, `child_process` and network handles work in the child. + V8's background threads (garbage collection, compilation) and the libuv + thread pool are started again in both processes. +* `process.pid` is the child's; `process.ppid` is the parent's. +* The IPC channel inherited from the parent (when the parent was started by + [`child_process.fork()`][] or is a [`cluster`][] worker) is closed in the + child without emitting `'disconnect'`: `process.connected` is `false` and + `process.send()`, `process.disconnect()` and `process.channel` are gone. + Messages that the parent had received but not yet emitted are not emitted in + the child. +* Randomness is not shared: `Math.random()` (in every context, unless + `--random-seed` is set), [`crypto.randomUUID()`][], [`crypto.randomInt()`][], + [`crypto.randomBytes()`][] and other users of OpenSSL's random number + generator produce sequences of their own in each child. +* The parent waits for (reaps) the children it forked, whether or not + `onExit` is given. + +Everything else is inherited as `fork(2)` inherits it, and is the caller's +responsibility: + +* Handles other than the IPC channel are open in both processes: a server + accepts connections in the child too, a socket or `process.stdin` can be + read by either process, and ending a shared socket ends it for both. Close + in the child what belongs to the parent. +* Callbacks that were already queued (for example by `process.nextTick()`, + promises, or timers) run in both processes. So do `process.on('exit')` + listeners; remove the parent's in the child if they must not run there. +* Values captured before the fork stay the parent's: modules that stored + `process.pid` at load time, and entropy pools kept in JavaScript (such as + the pool of the `nanoid` package) hand out the same values in every child. +* `performance.timeOrigin`, `process.uptime()` and `process.hrtime()` continue + the parent's clocks. +* Memory is shared copy-on-write: a child's garbage collections and + allocations turn shared pages into private ones over time. + +`process.forkSelf()` throws an error with the code +[`ERR_FORK_SELF_UNSAFE`][] if Worker threads (including the thread of +off-thread module customization hooks) are running, the inspector is +listening, trace events are being recorded, a SIGINT watchdog (the REPL, +`vm` with `breakOnSigint`) is running, or (on Linux) any thread that Node.js +does not know to be safe to fork is running, such as a native addon's thread. +It throws [`ERR_FORK_SELF_BUSY`][] if requests are in flight on the event +loop (file system, DNS, crypto or zlib work, pending writes, connects) or +if V8's background threads did not become idle; call it again once the event +loop is idle. + +This function is only available on the main thread of a process that owns its +process state, and not on Windows or IBM i. Test for it with +`typeof process.forkSelf === 'function'`. + ## `process.getActiveResourcesInfo()`