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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions deps/uv/src/threadpool.c
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
43 changes: 41 additions & 2 deletions deps/uv/src/unix/linux.c
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down Expand Up @@ -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;
Expand Down
54 changes: 54 additions & 0 deletions deps/v8/include/v8-fork.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// 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.
* 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-<pid>.map, which describes the code
* the child inherited, to the child's own perf-<pid>.map and writes new
* entries there. Does nothing otherwise. --perf-prof (jitdump) is not handled.
*/
V8_EXPORT void ReopenPerfMapAfterFork();

} // namespace v8

#endif // INCLUDE_V8_FORK_H_
48 changes: 48 additions & 0 deletions deps/v8/src/api/api.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -10725,6 +10727,52 @@ 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();
void MakeMappingsUnforkable();
} // namespace base
#endif

void MakeMappingsForkable() {
#if V8_OS_POSIX
base::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<i::Isolate*>(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<i::Object> context = i_isolate->heap()->native_contexts_list();
while (!i::IsUndefined(context, i_isolate)) {
i::Tagged<i::Context> native_context = i::Cast<i::Context>(context);
i::MathRandom::ResetContext(native_context);
context = native_context->next_context_link();
}
}

void Isolate::IncreaseHeapLimitForDebugging() {
// No-op.
}
Expand Down
89 changes: 85 additions & 4 deletions deps/v8/src/base/platform/platform-posix.cc
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@

#include <cmath>
#include <cstdlib>
#include <atomic>
#include <map>
#include <optional>

#include "src/base/lazy-instance.h"
Expand Down Expand Up @@ -173,6 +175,54 @@ 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<bool> g_mappings_forkable{false};
LazyMutex g_dontfork_mutex = LAZY_MUTEX_INITIALIZER;
std::map<uintptr_t, uintptr_t>* g_dontfork_ranges = nullptr; // start -> end

void MarkDontFork(void* address, size_t size) {
MutexGuard guard(g_dontfork_mutex.Pointer());
// 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<uintptr_t, uintptr_t>();
}
const uintptr_t start = reinterpret_cast<uintptr_t>(address);
(*g_dontfork_ranges)[start] = start + size;
}

void ForgetDontFork(void* address, size_t size) {
MutexGuard guard(g_dontfork_mutex.Pointer());
if (g_dontfork_ranges == nullptr) return;
const uintptr_t start = reinterpret_cast<uintptr_t>(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<SharedMemoryHandle> handle = std::nullopt,
Expand All @@ -190,10 +240,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) {
Expand All @@ -217,6 +264,37 @@ void* Allocate(void* hint, size_t size, OS::MemoryPermission access,

} // namespace

// 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
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) == forkable) return;
if (g_dontfork_ranges != nullptr) {
for (const auto& [start, end] : *g_dontfork_ranges) {
// Advisory; a range that is not entirely mapped any more only fails.
madvise(reinterpret_cast<void*>(start), end - start,
forkable ? MADV_DOFORK : MADV_DONTFORK);
}
}
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
// guarded.
int GetProtectionFromMemoryPermission(OS::MemoryPermission access) {
Expand Down Expand Up @@ -531,6 +609,7 @@ void* OS::AllocateShared(size_t size, MemoryPermission access) {
void OS::Free(void* address, size_t size) {
DCHECK_EQ(0, reinterpret_cast<uintptr_t>(address) % AllocatePageSize());
DCHECK_EQ(0, size % AllocatePageSize());
ForgetDontFork(address, size);
CHECK_EQ(0, munmap(address, size));
}

Expand All @@ -551,13 +630,15 @@ 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));
}

// static
void OS::Release(void* address, size_t size) {
DCHECK_EQ(0, reinterpret_cast<uintptr_t>(address) % CommitPageSize());
DCHECK_EQ(0, size % CommitPageSize());
ForgetDontFork(address, size);
CHECK_EQ(0, munmap(address, size));
}

Expand Down
Loading