From 4e0fad362cbac945427d3a94b922a614bddecb53 Mon Sep 17 00:00:00 2001 From: Max schwenk Date: Thu, 12 Nov 2026 06:23:11 +0000 Subject: [PATCH 01/33] src: read extra V8 flags from NODE_V8_FLAGS NODE_OPTIONS accepts only a short list of V8 flags. A pool of forked workers gets its flags from the environment, so flags outside that list cannot be tried without changing how the pool spawns its workers. NODE_V8_FLAGS is a space-separated list of V8 flags applied before V8 is initialized, in every process that inherits the variable. It exists to run experiments; it is not meant for upstream as is. --- src/node.cc | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/node.cc b/src/node.cc index 163070b501c5..b46c0aa78737 100644 --- a/src/node.cc +++ b/src/node.cc @@ -824,6 +824,22 @@ static ExitCode ProcessGlobalArgsInternal(std::vector* args, v8_args.emplace_back("--external-memory-max-reasonable-size=0"); } + // NODE_V8_FLAGS: V8 flags applied before V8 is initialized, for flags that + // NODE_OPTIONS does not accept. Every process that inherits the environment + // gets them, which is what a pool of forked workers needs. + if (settings == kDisallowedInEnvvar) { + std::string env_v8_flags; + if (credentials::SafeGetenv("NODE_V8_FLAGS", &env_v8_flags)) { + size_t start = 0; + while (start < env_v8_flags.size()) { + size_t end = env_v8_flags.find(' ', start); + if (end == std::string::npos) end = env_v8_flags.size(); + if (end > start) v8_args.emplace_back(env_v8_flags, start, end - start); + start = end + 1; + } + } + } + #ifdef __POSIX__ // Block SIGPROF signals when sleeping in epoll_wait/kevent/etc. Avoids the // performance penalty of frequent EINTR wakeups when the profiler is running. From ae046d7c070010abd158f8f3679328ea29f47b3a Mon Sep 17 00:00:00 2001 From: Max schwenk Date: Thu, 12 Nov 2026 01:06:58 -0500 Subject: [PATCH 02/33] deps: V8: scan magic comment values in bulk, don't internalize long ones Tools that evaluate transformed code (dev servers, test runners, TypeScript loaders and require hooks) append an inline source map to it: `//# sourceMappingURL=data:application/json;base64,...`, often tens of kilobytes to megabytes long and often most of the bytes of the script. The scanner copied magic comment values one code unit at a time through the character stream into a LiteralBuffer, which grows by at most 1 MB per reallocation, and then internalized sourceMappingURL values: a second copy of the source map in old space for as long as the script lives, plus a string table entry nothing else will ever match. Find the end of a value a buffer at a time, skipping blocks of printable ASCII (which never ends a value) with a loop the compiler vectorizes, and copy the value into the LiteralBuffer in bulk. Don't internalize sourceMappingURL values longer than 1024 characters: they are unique to their script, so the string table gains nothing from them. Short values such as `foo.js.map` are still internalized. Compiling a script with 64 KB of code and a 5 MB inline source map (new vm.Script, arm64): 15.0 ms -> 5.0 ms. --- deps/v8/src/parsing/literal-buffer.cc | 65 ++++++++++++++++++++++++++- deps/v8/src/parsing/literal-buffer.h | 9 ++++ deps/v8/src/parsing/scanner.cc | 42 ++++++++++++++--- deps/v8/src/parsing/scanner.h | 30 +++++++++++-- 4 files changed, 135 insertions(+), 11 deletions(-) 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/scanner.cc b/deps/v8/src/parsing/scanner.cc index 81f617730a31..8e55d9953c9f 100644 --- a/deps/v8/src/parsing/scanner.cc +++ b/deps/v8/src/parsing/scanner.cc @@ -274,6 +274,31 @@ void ProcessPerFunctionCompileHints(const base::Vector& data, positions.shrink_to_fit(); } +// Returns the first code unit in [begin, end) that ends a magic comment value, +// that is whitespace or a line terminator, or end if there is none. +const uint16_t* FindEndOfMagicCommentValue(const uint16_t* begin, + const uint16_t* end) { + auto ends_value = [](uint16_t c) { return IsWhiteSpaceOrLineTerminator(c); }; + // Values can be megabytes of base64 (inline source maps), and printable + // ASCII other than space never ends a value: skip blocks of it with a loop + // the compiler can vectorize, and only look closer at blocks with other + // code units. + constexpr int kBlockSize = 16; + while (end - begin >= kBlockSize) { + bool maybe_ends_value = false; + for (int i = 0; i < kBlockSize; i++) { + maybe_ends_value |= static_cast(begin[i] - 0x21) > 0x7E - 0x21; + } + if (V8_UNLIKELY(maybe_ends_value)) { + const uint16_t* block_end = begin + kBlockSize; + const uint16_t* result = std::find_if(begin, block_end, ends_value); + if (result != block_end) return result; + } + begin += kBlockSize; + } + return std::find_if(begin, end, ends_value); +} + } // namespace void Scanner::TryToParseMagicComment(base::uc32 hash_or_at_sign) { @@ -322,12 +347,15 @@ void Scanner::TryToParseMagicComment(base::uc32 hash_or_at_sign) { while (IsWhiteSpace(c0_)) { Advance(); } - while (c0_ != kEndOfInput && !unibrow::IsLineTerminator(c0_)) { - if (IsWhiteSpace(c0_)) { - break; - } + // The value ends at whitespace or a line terminator. Copy it a buffer at a + // time rather than a character at a time, since it can be long. + if (c0_ != kEndOfInput && !IsWhiteSpaceOrLineTerminator(c0_)) { value->AddChar(c0_); - Advance(); + AdvanceUntil(FindEndOfMagicCommentValue, + [value](const uint16_t* begin, const uint16_t* end) { + value->AddChars(base::Vector( + begin, static_cast(end - begin))); + }); } // Allow whitespace at the end. while (c0_ != kEndOfInput && !unibrow::IsLineTerminator(c0_)) { @@ -703,7 +731,9 @@ template DirectHandle Scanner::SourceUrl(LocalIsolate* isolate) const; template DirectHandle Scanner::SourceMappingUrl(IsolateT* isolate) const { DirectHandle tmp; - if (source_mapping_url_.length() > 0) { + if (source_mapping_url_.length() > kMaxInternalizedSourceMappingUrlLength) { + tmp = source_mapping_url_.NewString(isolate); + } else if (source_mapping_url_.length() > 0) { tmp = source_mapping_url_.Internalize(isolate); } return tmp; diff --git a/deps/v8/src/parsing/scanner.h b/deps/v8/src/parsing/scanner.h index ee69652633e6..6f616fb5f73b 100644 --- a/deps/v8/src/parsing/scanner.h +++ b/deps/v8/src/parsing/scanner.h @@ -75,12 +75,26 @@ class Utf16CharacterStream { // returns kEndOfInput. template V8_INLINE base::uc32 AdvanceUntil(FunctionType check) { - while (true) { - auto next_cursor_pos = - std::find_if(buffer_cursor_, buffer_end_, [&check](uint16_t raw_c0_) { + return AdvanceUntil( + [&check](const uint16_t* begin, const uint16_t* end) { + return std::find_if(begin, end, [&check](uint16_t raw_c0_) { base::uc32 c0_ = static_cast(raw_c0_); return check(c0_); }); + }, + [](const uint16_t*, const uint16_t*) {}); + } + + // Like AdvanceUntil(check), but a buffer at a time: |find(begin, end)| + // returns the first code unit in [begin, end) that meets the requirement, + // or end, and |skipped(begin, end)| is called with every run of code units + // that is advanced past. + template + V8_INLINE base::uc32 AdvanceUntil(FindFunction find, + SkippedFunction skipped) { + while (true) { + const uint16_t* next_cursor_pos = find(buffer_cursor_, buffer_end_); + skipped(buffer_cursor_, next_cursor_pos); if (next_cursor_pos == buffer_end_) { buffer_cursor_ = buffer_end_; @@ -425,6 +439,11 @@ class V8_EXPORT_PRIVATE Scanner { return ScanTemplateSpan(); } + // sourceMappingURL values longer than this are not internalized. They are + // typically inline source maps (data: URLs), which are unique to a script + // and can be megabytes long, so the string table gains nothing from them. + static constexpr int kMaxInternalizedSourceMappingUrlLength = 1024; + template DirectHandle SourceUrl(IsolateT* isolate) const; template @@ -563,6 +582,11 @@ class V8_EXPORT_PRIVATE Scanner { c0_ = source_->AdvanceUntil(check); } + template + V8_INLINE void AdvanceUntil(FindFunction find, SkippedFunction skipped) { + c0_ = source_->AdvanceUntil(find, skipped); + } + bool CombineSurrogatePair() { DCHECK(!unibrow::Utf16::IsLeadSurrogate(kEndOfInput)); if (unibrow::Utf16::IsLeadSurrogate(c0_)) { From 9a8cd716c3606de2f7054aff9f76f56ab9176f93 Mon Sep 17 00:00:00 2001 From: Max schwenk Date: Thu, 12 Nov 2026 01:09:42 -0500 Subject: [PATCH 03/33] deps: V8: slice long sourceMappingURL values out of the source The value of a sourceMappingURL magic comment is part of the source, which the Script keeps alive anyway. On the main thread the parser has the source string, so for a long value only record where it is, and make the Script's source_mapping_url a slice of the source instead of a copy. That saves the copy while scanning and the memory it takes for as long as the script lives. Only slice when the value is at least half of the source, so that a slice that outlives its script (an embedder may hold on to the URL) keeps at most twice its own size alive; otherwise copy the value out of the source. Background parses keep copying it. The code cache does not contain the source: deserialization attaches the source string the embedder passes, or a placeholder when it runs off the main thread. So the code serializer serializes a flat copy of a sliced URL, as it serialized the internalized copy before. Compiling a script with 64 KB of code and a 5 MB inline source map (new vm.Script, arm64): 5.0 ms -> 1.7 ms, and the heap retained per script goes from 5,193 KB to 73 KB, the same as without the comment. --- deps/v8/src/parsing/parser.cc | 11 +++++- deps/v8/src/parsing/scanner.cc | 47 +++++++++++++++++++++++-- deps/v8/src/parsing/scanner.h | 14 ++++++++ deps/v8/src/snapshot/code-serializer.cc | 14 ++++++++ 4 files changed, 83 insertions(+), 3 deletions(-) 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