diff --git a/configure.py b/configure.py index a3769ff2d879..35e4be0495a9 100755 --- a/configure.py +++ b/configure.py @@ -1259,6 +1259,22 @@ default=None, help=f"Disable V8's Maglev compiler. {maglev_enabled_by_default_help}") +parser.add_argument('--v8-enable-builtins-profiling', + action='store_true', + dest='v8_enable_builtins_profiling', + default=None, + help='Instrument the embedded builtins with basic block counters. Run the ' + 'resulting binary with --turbo-profiling-output= to collect them, ' + 'then turn them into branch hints with ' + 'deps/v8/tools/builtins-pgo/get_hints.py.') + +parser.add_argument('--v8-builtins-profiling-log-file', + action='store', + dest='v8_builtins_profiling_log_file', + default=None, + help='Branch hints file for the embedded builtins (builtins PGO), as made by ' + 'deps/v8/tools/builtins-pgo/get_hints.py from a profiling build.') + parser.add_argument('--v8-enable-short-builtin-calls', action='store_true', dest='v8_enable_short_builtin_calls', @@ -2292,6 +2308,15 @@ def configure_v8(o, configs): if flavor != 'linux' and options.v8_enable_hugepage: raise Exception('--v8-enable-hugepage is supported only on linux.') o['variables']['v8_enable_hugepage'] = 1 if options.v8_enable_hugepage else 0 + if options.v8_enable_builtins_profiling and options.v8_builtins_profiling_log_file: + raise Exception('--v8-enable-builtins-profiling and ' + '--v8-builtins-profiling-log-file are mutually exclusive.') + o['variables']['v8_enable_builtins_profiling'] = 1 if options.v8_enable_builtins_profiling else 0 + if options.v8_builtins_profiling_log_file: + log_file = os.path.abspath(options.v8_builtins_profiling_log_file) + if not os.path.isfile(log_file): + raise Exception(f'Builtins profile not found: {log_file}') + o['variables']['v8_builtins_profiling_log_file'] = log_file if options.v8_enable_short_builtin_calls or o['variables']['target_arch'] == 'x64': o['variables']['v8_enable_short_builtin_calls'] = 1 if options.v8_enable_snapshot_compression: diff --git a/deps/uv/src/threadpool.c b/deps/uv/src/threadpool.c index 2a129a5d4a58..b7e7a4007f43 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 110964884ddc..0a0816952462 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; diff --git a/deps/v8/include/v8-fork.h b/deps/v8/include/v8-fork.h new file mode 100644 index 000000000000..6621027a6410 --- /dev/null +++ b/deps/v8/include/v8-fork.h @@ -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-.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 + +#endif // INCLUDE_V8_FORK_H_ diff --git a/deps/v8/src/api/api.cc b/deps/v8/src/api/api.cc index eb3cd7dee28f..2cc25065b011 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,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(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/bounded-page-allocator.cc b/deps/v8/src/base/bounded-page-allocator.cc index de53e0d4bdb3..92b5459df2ef 100644 --- a/deps/v8/src/base/bounded-page-allocator.cc +++ b/deps/v8/src/base/bounded-page-allocator.cc @@ -97,6 +97,36 @@ void* BoundedPageAllocator::AllocatePages(size_t size, size_t alignment, return nullptr; } +void* BoundedPageAllocator::AllocatePagesFromTop( + size_t size, PageAllocator::Permission access) { + MutexGuard guard(&mutex_); + DCHECK(IsAligned(size, allocate_page_size_)); + + Address address = region_allocator_.AllocateRegionFromTop(size); + if (address == RegionAllocator::kAllocationFailure) { + allocation_status_ = AllocationStatus::kRanOutOfReservation; + return nullptr; + } + + void* ptr = reinterpret_cast(address); + if (access == PageAllocator::kNoAccess || + access == PageAllocator::kNoAccessWillJitLater) { + allocation_status_ = AllocationStatus::kSuccess; + return ptr; + } + bool committed = + page_initialization_mode_ == PageInitializationMode::kRecommitOnly + ? page_allocator_->RecommitPages(ptr, size, access) + : page_allocator_->SetPermissions(ptr, size, access); + if (committed) { + allocation_status_ = AllocationStatus::kSuccess; + return ptr; + } + CHECK_EQ(region_allocator_.FreeRegion(address), size); + allocation_status_ = AllocationStatus::kFailedToCommit; + return nullptr; +} + bool BoundedPageAllocator::AllocatePagesAt(Address address, size_t size, PageAllocator::Permission access) { MutexGuard guard(&mutex_); diff --git a/deps/v8/src/base/bounded-page-allocator.h b/deps/v8/src/base/bounded-page-allocator.h index 13633daf6136..1927e62c736b 100644 --- a/deps/v8/src/base/bounded-page-allocator.h +++ b/deps/v8/src/base/bounded-page-allocator.h @@ -116,6 +116,10 @@ class V8_BASE_EXPORT BoundedPageAllocator : public v8::PageAllocator { // Allocates pages at given address, returns true on success. bool AllocatePagesAt(Address address, size_t size, Permission access); + // Allocates pages at the highest address where they fit, keeping them + // apart from the allocations that fill the range from the bottom. + void* AllocatePagesFromTop(size_t size, Permission access); + bool ResizeAllocationAt(void* address, size_t old_size, size_t new_size, Permission access) override; diff --git a/deps/v8/src/base/platform/platform-posix.cc b/deps/v8/src/base/platform/platform-posix.cc index 9363910367eb..56447c928168 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,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 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) { + 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(); + } + const uintptr_t start = reinterpret_cast(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(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 +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) { @@ -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(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) { @@ -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(address) % AllocatePageSize()); DCHECK_EQ(0, size % AllocatePageSize()); + ForgetDontFork(address, size); CHECK_EQ(0, munmap(address, size)); } @@ -551,6 +630,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 +638,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)); } diff --git a/deps/v8/src/base/region-allocator.cc b/deps/v8/src/base/region-allocator.cc index 82642f6ab8c3..605a31dbf28d 100644 --- a/deps/v8/src/base/region-allocator.cc +++ b/deps/v8/src/base/region-allocator.cc @@ -175,6 +175,19 @@ RegionAllocator::Address RegionAllocator::AllocateRegion( return region->begin(); } +RegionAllocator::Address RegionAllocator::AllocateRegionFromTop(size_t size) { + DCHECK_NE(size, 0); + DCHECK(IsAligned(size, page_size_)); + for (auto it = all_regions_.rbegin(); it != all_regions_.rend(); ++it) { + Region* region = *it; + if (!region->is_free() || region->size() < size) continue; + Address address = region->end() - size; + if (!AllocateRegionAt(address, size)) return kAllocationFailure; + return address; + } + return kAllocationFailure; +} + RegionAllocator::Address RegionAllocator::AllocateRegion( RandomNumberGenerator* rng, size_t size) { if (free_size() >= max_load_for_randomization_) { diff --git a/deps/v8/src/base/region-allocator.h b/deps/v8/src/base/region-allocator.h index 09431254ed0b..c942b8d0bcf6 100644 --- a/deps/v8/src/base/region-allocator.h +++ b/deps/v8/src/base/region-allocator.h @@ -81,6 +81,11 @@ class V8_BASE_EXPORT RegionAllocator final { // Same as above but tries to randomize the region displacement. Address AllocateRegion(RandomNumberGenerator* rng, size_t size); + // Allocates region of |size| (must be |page_size|-aligned) at the highest + // address where it fits. Returns the address of the region on success or + // kAllocationFailure. + Address AllocateRegionFromTop(size_t size); + // Allocates region of |size| at |requested_address| if it's free. Both the // address and the size must be |page_size|-aligned. On success returns // true. diff --git a/deps/v8/src/flags/flag-definitions.h b/deps/v8/src/flags/flag-definitions.h index 15d4341ff84b..2c1c3de7b447 100644 --- a/deps/v8/src/flags/flag-definitions.h +++ b/deps/v8/src/flags/flag-definitions.h @@ -2655,6 +2655,10 @@ DEFINE_BOOL(stress_per_context_marking_worklist, false, DEFINE_BOOL(stress_incremental_marking, false, "force incremental marking for small heaps and run it more often") +DEFINE_BOOL(large_objects_at_cage_top, false, + "allocate large object pages from the top of the pointer " + "compression cage, apart from regular pages, which fill it from " + "the bottom") DEFINE_BOOL(memory_pool, true, "Pool memory globally before returning it to the operating system") DEFINE_BOOL( diff --git a/deps/v8/src/flags/flags.cc b/deps/v8/src/flags/flags.cc index ac051cb784b6..c4b887f8c6d9 100644 --- a/deps/v8/src/flags/flags.cc +++ b/deps/v8/src/flags/flags.cc @@ -515,7 +515,8 @@ uint32_t ComputeFlagListHash() { if (flag.PointsTo(&v8_flags.max_old_space_size) || flag.PointsTo(&v8_flags.min_semi_space_size) || flag.PointsTo(&v8_flags.max_semi_space_size) || - flag.PointsTo(&v8_flags.max_heap_size)) { + flag.PointsTo(&v8_flags.max_heap_size) || + flag.PointsTo(&v8_flags.large_objects_at_cage_top)) { continue; } diff --git a/deps/v8/src/heap/memory-allocator.cc b/deps/v8/src/heap/memory-allocator.cc index 3343696c80b8..e891ec4c2aa2 100644 --- a/deps/v8/src/heap/memory-allocator.cc +++ b/deps/v8/src/heap/memory-allocator.cc @@ -20,6 +20,7 @@ #include "src/heap/mutable-page.h" #include "src/heap/read-only-spaces.h" #include "src/heap/zapping.h" +#include "src/init/isolate-group.h" #include "src/logging/log.h" #include "src/sandbox/hardware-support.h" #include "src/utils/allocation.h" @@ -119,6 +120,31 @@ Address MemoryAllocator::AllocateAlignedMemory( executable == EXECUTABLE ? MutablePage::GetCodeModificationPermission() : PageAllocator::kReadWrite; +#ifdef V8_COMPRESS_POINTERS + // Large objects from the top of the cage, so they do not share memory + // ranges with regular pages (lets an embedder's page allocator treat the + // two kinds of memory differently, e.g. back only pages with huge pages). + if (v8_flags.large_objects_at_cage_top && page_size == PageSize::kLarge && + executable == NOT_EXECUTABLE && !hint.MayGrow() && + address_hint == nullptr) { + VirtualMemoryCage* cage = isolate_->isolate_group()->GetPtrComprCage(); + if (cage != nullptr && page_allocator == cage->page_allocator() && + alignment <= cage->page_allocator()->AllocatePageSize()) { + base::BoundedPageAllocator* bounded = cage->page_allocator(); + size_t size = RoundUp(chunk_size, bounded->AllocatePageSize()); + void* ptr = bounded->AllocatePagesFromTop(size, permissions); + if (ptr != nullptr) { + VirtualMemory top(page_allocator, reinterpret_cast
(ptr), + size); + Address base = top.address(); + UpdateAllocatedSpaceLimits(base, base + chunk_size, executable); + *controller = std::move(top); + return base; + } + } + } +#endif // V8_COMPRESS_POINTERS + v8::PageAllocator::AllocationHint page_allocation_hint = v8::PageAllocator::AllocationHint().WithAddress(address_hint); if (hint.MayGrow()) { diff --git a/deps/v8/src/logging/log.cc b/deps/v8/src/logging/log.cc index 6de82a480d40..c62618319855 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); } } diff --git a/deps/v8/src/parsing/literal-buffer.cc b/deps/v8/src/parsing/literal-buffer.cc index c7e5560b9601..eba74ce332f7 100644 --- a/deps/v8/src/parsing/literal-buffer.cc +++ b/deps/v8/src/parsing/literal-buffer.cc @@ -4,10 +4,13 @@ #include "src/parsing/literal-buffer.h" +#include + #include "src/base/strings.h" #include "src/execution/isolate.h" #include "src/execution/local-isolate.h" #include "src/heap/factory.h" +#include "src/objects/string-inl.h" #include "src/utils/memcopy.h" namespace v8 { @@ -26,6 +29,54 @@ template DirectHandle LiteralBuffer::Internalize( template DirectHandle LiteralBuffer::Internalize( LocalIsolate* isolate) const; +template +DirectHandle LiteralBuffer::NewString(IsolateT* isolate) const { + // Old space, since a LocalIsolate cannot allocate anywhere else. + if (is_one_byte()) { + return isolate->factory() + ->NewStringFromOneByte(one_byte_literal(), AllocationType::kOld) + .ToHandleChecked(); + } + base::Vector chars = two_byte_literal(); + Handle result = + isolate->factory() + ->NewRawTwoByteString(chars.length(), AllocationType::kOld) + .ToHandleChecked(); + DisallowGarbageCollection no_gc; + // {result} is freshly allocated, so it can't be accessed concurrently. + CopyChars( + result->GetChars(no_gc, SharedStringAccessGuardIfNeeded::NotNeeded()), + chars.begin(), chars.length()); + return result; +} + +template DirectHandle LiteralBuffer::NewString(Isolate* isolate) const; +template DirectHandle LiteralBuffer::NewString( + LocalIsolate* isolate) const; + +void LiteralBuffer::AddChars(base::Vector code_units) { + const uint16_t* begin = code_units.begin(); + const uint16_t* end = code_units.end(); + if (is_one_byte()) { + const uint16_t* first_two_byte = std::find_if(begin, end, [](uint16_t c) { + return c > unibrow::Latin1::kMaxChar; + }); + int count = static_cast(first_two_byte - begin); + if (count > 0) { + EnsureCapacity(position_ + count); + CopyChars(backing_store_.begin() + position_, begin, count); + position_ += count; + } + if (first_two_byte == end) return; + ConvertToTwoByte(); + begin = first_two_byte; + } + int size = static_cast(end - begin) * base::kUC16Size; + EnsureCapacity(position_ + size); + MemCopy(backing_store_.begin() + position_, begin, size); + position_ += size; +} + int LiteralBuffer::NewCapacity(int min_capacity) { return min_capacity < (kMaxGrowth / (kGrowthFactor - 1)) ? min_capacity * kGrowthFactor @@ -34,8 +85,18 @@ int LiteralBuffer::NewCapacity(int min_capacity) { void LiteralBuffer::ExpandBuffer() { int min_capacity = std::max({kInitialCapacity, backing_store_.length()}); - base::Vector new_store = - base::Vector::New(NewCapacity(min_capacity)); + ResizeBuffer(NewCapacity(min_capacity)); +} + +void LiteralBuffer::EnsureCapacity(int min_capacity) { + if (min_capacity > backing_store_.length()) { + ResizeBuffer(NewCapacity(std::max(kInitialCapacity, min_capacity))); + } +} + +void LiteralBuffer::ResizeBuffer(int capacity) { + DCHECK_GE(capacity, position_); + base::Vector new_store = base::Vector::New(capacity); if (position_ > 0) { MemCopy(new_store.begin(), backing_store_.begin(), position_); } diff --git a/deps/v8/src/parsing/literal-buffer.h b/deps/v8/src/parsing/literal-buffer.h index 92ed94bfbcad..0790c8ba98c7 100644 --- a/deps/v8/src/parsing/literal-buffer.h +++ b/deps/v8/src/parsing/literal-buffer.h @@ -38,6 +38,9 @@ class LiteralBuffer final { AddTwoByteChar(code_unit); } + // Same as calling AddChar() for each code unit. + void AddChars(base::Vector code_units); + bool is_one_byte() const { return is_one_byte_; } bool Equals(base::Vector keyword) const { @@ -72,6 +75,10 @@ class LiteralBuffer final { template DirectHandle Internalize(IsolateT* isolate) const; + // Returns the literal as a new string that is not internalized. + template + DirectHandle NewString(IsolateT* isolate) const; + private: static constexpr int kInitialCapacity = 256; static constexpr int kGrowthFactor = 4; @@ -95,6 +102,8 @@ class LiteralBuffer final { void AddTwoByteChar(base::uc32 code_unit); int NewCapacity(int min_capacity); V8_NOINLINE V8_PRESERVE_MOST void ExpandBuffer(); + void EnsureCapacity(int min_capacity); + void ResizeBuffer(int capacity); void ConvertToTwoByte(); base::Vector backing_store_; diff --git a/deps/v8/src/parsing/parser.cc b/deps/v8/src/parsing/parser.cc index 509ca9322666..39a687307815 100644 --- a/deps/v8/src/parsing/parser.cc +++ b/deps/v8/src/parsing/parser.cc @@ -7,6 +7,7 @@ #include #include #include +#include #include "src/ast/ast-function-literal-id-reindexer.h" #include "src/ast/ast-traversal-visitor.h" @@ -719,6 +720,8 @@ void Parser::ParseProgram(Isolate* isolate, DirectHandle