From 87521e99d16171c01f23d4c4e246f37d2b0018fa Mon Sep 17 00:00:00 2001 From: Joyee Cheung Date: Wed, 4 Mar 2026 17:58:27 +0100 Subject: [PATCH] deps: V8: backport 1361b2a49d02 Original commit message: [strings] improve array index hash distribution Previously, the hashes stored in a Name's raw_hash_field for decimal numeric strings (potential array indices) consist of the literal integer value along with the length of the string. This means consecutive numeric strings can have consecutive hash values, which can lead to O(n^2) probing for insertion in the worst case when e.g. a non-numeric string happen to land in the these buckets. This patch adds a build-time flag v8_enable_seeded_array_index_hash that scrambles the 24-bit array-index value stored in a Name's raw_hash_field to improve the distribution. x ^= x >> kShift; x = (x * m1) & kMask; // round 1 x ^= x >> kShift; x = (x * m2) & kMask; // round 2 x ^= x >> kShift; // finalize To decode, apply the same steps with the modular inverses of m1 and m2 in reverse order. x ^= x >> kShift; x = (x * m2_inv) & kMask; // round 1 x ^= x >> kShift; x = (x * m1_inv) & kMask; // round 2 x ^= x >> kShift; // finalize where kShift = kArrayIndexValueBits / 2, kMask = kArrayIndexValueMask, m1, m2 (both odd) are the lower bits of the rapidhash secrets, m1_inv, m2_inv (modular inverses) are precomputed modular inverse of m1 and m2. The pre-computed values are appended to the hash_seed ByteArray in ReadOnlyRoots and accessed in generated code to reduce overhead. In call sites that don't already have access to the seeds, we read them from the current isolate group/isolate's read only roots. To consolidate the code that encode/decode these hashes, this patch adds MakeArrayIndexHash/DecodeArrayIndexFromHashField in C++ and CSA that perform seeding/unseeding if enabled, and updates places where encoding/decoding of array index is needed to use them. Bug: 477515021 Change-Id: I350afe511951a54c4378396538152cc56565fd55 Reviewed-on: https://chromium-review.googlesource.com/c/v8/v8/+/7564330 Reviewed-by: Leszek Swirski Commit-Queue: Joyee Cheung Cr-Commit-Position: refs/heads/main@{#105596} Refs: https://github.com/v8/v8/commit/1361b2a49d020a718dc5495713eae0fa67d697b9 Co-authored-by: Joyee Cheung PR-URL: https://github.com/nodejs-private/node-private/pull/828 --- common.gypi | 2 +- deps/v8/BUILD.bazel | 6 ++ deps/v8/BUILD.gn | 6 ++ deps/v8/src/ast/ast-value-factory.cc | 3 +- deps/v8/src/builtins/number.tq | 4 +- deps/v8/src/builtins/wasm.tq | 4 +- deps/v8/src/codegen/code-stub-assembler.cc | 58 +++++++++++++++++-- deps/v8/src/codegen/code-stub-assembler.h | 6 ++ deps/v8/src/heap/factory-base.cc | 3 +- deps/v8/src/heap/factory.cc | 3 +- deps/v8/src/numbers/hash-seed-inl.h | 7 +++ deps/v8/src/numbers/hash-seed.cc | 63 ++++++++++++++++++-- deps/v8/src/numbers/hash-seed.h | 24 +++++++- deps/v8/src/objects/name.h | 14 ++++- deps/v8/src/objects/name.tq | 43 +++++++++++++- deps/v8/src/objects/string-inl.h | 6 +- deps/v8/src/objects/string-table.cc | 3 +- deps/v8/src/objects/string.cc | 6 +- deps/v8/src/strings/string-hasher-inl.h | 63 +++++++++++++++++++- deps/v8/src/strings/string-hasher.h | 51 +++++++++++++++- deps/v8/src/torque/torque-parser.cc | 5 ++ deps/v8/test/cctest/test-strings.cc | 67 ++++++++++++++++------ 22 files changed, 397 insertions(+), 50 deletions(-) diff --git a/common.gypi b/common.gypi index 011355970f7..283c60eab35 100644 --- a/common.gypi +++ b/common.gypi @@ -38,7 +38,7 @@ # Reset this number to 0 on major V8 upgrades. # Increment by one for each non-official patch applied to deps/v8. - 'v8_embedder_string': '-node.43', + 'v8_embedder_string': '-node.44', ##### V8 defaults for Node.js ##### diff --git a/deps/v8/BUILD.bazel b/deps/v8/BUILD.bazel index 9f1f501d070..fe4011299d3 100644 --- a/deps/v8/BUILD.bazel +++ b/deps/v8/BUILD.bazel @@ -230,6 +230,11 @@ v8_flag( default = False, ) +v8_flag( + name = "v8_enable_seeded_array_index_hash", + default = False, +) + selects.config_setting_group( name = "enable_drumbrake_x64", match_all = [ @@ -485,6 +490,7 @@ v8_config( "v8_enable_webassembly": "V8_ENABLE_WEBASSEMBLY", "v8_enable_drumbrake": "V8_ENABLE_DRUMBRAKE", "v8_enable_drumbrake_tracing": "V8_ENABLE_DRUMBRAKE_TRACING", + "v8_enable_seeded_array_index_hash": "V8_ENABLE_SEEDED_ARRAY_INDEX_HASH", "v8_jitless": "V8_JITLESS", "v8_enable_vtunejit": "ENABLE_VTUNE_JIT_INTERFACE", }, diff --git a/deps/v8/BUILD.gn b/deps/v8/BUILD.gn index 3a354c523a0..fee8aedf6a2 100644 --- a/deps/v8/BUILD.gn +++ b/deps/v8/BUILD.gn @@ -518,6 +518,9 @@ declare_args() { # Use a hard-coded secret value when hashing. v8_use_default_hasher_secret = true + + # Enable seeded array index hash. + v8_enable_seeded_array_index_hash = false } # Derived defaults. @@ -1209,6 +1212,9 @@ config("features") { if (v8_enable_lite_mode) { defines += [ "V8_LITE_MODE" ] } + if (v8_enable_seeded_array_index_hash) { + defines += [ "V8_ENABLE_SEEDED_ARRAY_INDEX_HASH" ] + } if (v8_enable_gdbjit) { defines += [ "ENABLE_GDB_JIT_INTERFACE" ] } diff --git a/deps/v8/src/ast/ast-value-factory.cc b/deps/v8/src/ast/ast-value-factory.cc index 2de885e9eb4..277d21029a8 100644 --- a/deps/v8/src/ast/ast-value-factory.cc +++ b/deps/v8/src/ast/ast-value-factory.cc @@ -83,7 +83,8 @@ bool AstRawString::AsArrayIndex(uint32_t* index) const { // can't be convertible to an array index. if (!IsIntegerIndex()) return false; if (length() <= Name::kMaxCachedArrayIndexLength) { - *index = Name::ArrayIndexValueBits::decode(raw_hash_field_); + *index = StringHasher::DecodeArrayIndexFromHashField( + raw_hash_field_, HashSeed(GetReadOnlyRoots())); return true; } // Might be an index, but too big to cache it. Do the slow conversion. This diff --git a/deps/v8/src/builtins/number.tq b/deps/v8/src/builtins/number.tq index 76a27fad544..37185ee43a3 100644 --- a/deps/v8/src/builtins/number.tq +++ b/deps/v8/src/builtins/number.tq @@ -299,7 +299,7 @@ transitioning javascript builtin NumberParseFloat( const hash: NameHash = s.raw_hash_field; if (IsIntegerIndex(hash) && hash.array_index_length < kMaxCachedArrayIndexLength) { - const arrayIndex: uint32 = hash.array_index_value; + const arrayIndex: uint32 = DecodeArrayIndexFromHashField(hash); return SmiFromUint32(arrayIndex); } // Fall back to the runtime to convert string to a number. @@ -350,7 +350,7 @@ transitioning builtin ParseInt( const hash: NameHash = s.raw_hash_field; if (IsIntegerIndex(hash) && hash.array_index_length < kMaxCachedArrayIndexLength) { - const arrayIndex: uint32 = hash.array_index_value; + const arrayIndex: uint32 = DecodeArrayIndexFromHashField(hash); return SmiFromUint32(arrayIndex); } // Fall back to the runtime. diff --git a/deps/v8/src/builtins/wasm.tq b/deps/v8/src/builtins/wasm.tq index 900d7d98867..32408cfcd80 100644 --- a/deps/v8/src/builtins/wasm.tq +++ b/deps/v8/src/builtins/wasm.tq @@ -1517,8 +1517,8 @@ builtin WasmStringToDouble(s: String): float64 { const hash: NameHash = s.raw_hash_field; if (IsIntegerIndex(hash) && hash.array_index_length < kMaxCachedArrayIndexLength) { - const arrayIndex: int32 = Signed(hash.array_index_value); - return Convert(arrayIndex); + const arrayIndex: uint32 = DecodeArrayIndexFromHashField(hash); + return Convert(Signed(arrayIndex)); } return StringToFloat64(Flatten(s)); } diff --git a/deps/v8/src/codegen/code-stub-assembler.cc b/deps/v8/src/codegen/code-stub-assembler.cc index 9071cb487d7..8d71465f065 100644 --- a/deps/v8/src/codegen/code-stub-assembler.cc +++ b/deps/v8/src/codegen/code-stub-assembler.cc @@ -2546,6 +2546,56 @@ TNode CodeStubAssembler::LoadJSReceiverIdentityHash( return var_hash.value(); } +#ifdef V8_ENABLE_SEEDED_ARRAY_INDEX_HASH +// Mirror C++ StringHasher::SeedArrayIndexValue. +TNode CodeStubAssembler::SeedArrayIndexValue(TNode value) { + // Load m1 and m2 from the hash seed byte array. In the compiled code + // these will always come from the read-only roots. + TNode hash_seed = CAST(LoadRoot(RootIndex::kHashSeed)); + intptr_t base_offset = OFFSET_OF_DATA_START(ByteArray) - kHeapObjectTag; + TNode m1 = Load( + hash_seed, IntPtrConstant(base_offset + HashSeed::kDerivedM1Offset)); + TNode m2 = Load( + hash_seed, IntPtrConstant(base_offset + HashSeed::kDerivedM2Offset)); + + TNode x = value; + // 2-round xorshift-multiply. + x = Word32Xor(x, Word32Shr(x, Uint32Constant(Name::kArrayIndexHashShift))); + x = Word32And(Uint32Mul(Unsigned(x), m1), + Uint32Constant(Name::kArrayIndexValueMask)); + x = Word32Xor(x, Word32Shr(x, Uint32Constant(Name::kArrayIndexHashShift))); + x = Word32And(Uint32Mul(Unsigned(x), m2), + Uint32Constant(Name::kArrayIndexValueMask)); + x = Word32Xor(x, Word32Shr(x, Uint32Constant(Name::kArrayIndexHashShift))); + + return Unsigned(x); +} + +// Mirror C++ StringHasher::UnseedArrayIndexValue. +TNode CodeStubAssembler::UnseedArrayIndexValue(TNode value) { + // Load m1_inv and m2_inv from the hash seed byte array. In the compiled code + // these will always come from the read-only roots. + TNode hash_seed = CAST(LoadRoot(RootIndex::kHashSeed)); + intptr_t base_offset = OFFSET_OF_DATA_START(ByteArray) - kHeapObjectTag; + TNode m1_inv = Load( + hash_seed, IntPtrConstant(base_offset + HashSeed::kDerivedM1InvOffset)); + TNode m2_inv = Load( + hash_seed, IntPtrConstant(base_offset + HashSeed::kDerivedM2InvOffset)); + + TNode x = value; + // 2-round xorshift-multiply (inverse). + // Xorshift is an involution when kShift is at least half of the value width. + x = Word32Xor(x, Word32Shr(x, Uint32Constant(Name::kArrayIndexHashShift))); + x = Word32And(Uint32Mul(Unsigned(x), m2_inv), + Uint32Constant(Name::kArrayIndexValueMask)); + x = Word32Xor(x, Word32Shr(x, Uint32Constant(Name::kArrayIndexHashShift))); + x = Word32And(Uint32Mul(Unsigned(x), m1_inv), + Uint32Constant(Name::kArrayIndexValueMask)); + x = Word32Xor(x, Word32Shr(x, Uint32Constant(Name::kArrayIndexHashShift))); + return Unsigned(x); +} +#endif // V8_ENABLE_SEEDED_ARRAY_INDEX_HASH + TNode CodeStubAssembler::LoadNameHashAssumeComputed(TNode name) { TNode hash_field = LoadNameRawHash(name); CSA_DCHECK(this, IsClearWord32(hash_field, Name::kHashNotComputedMask)); @@ -8983,8 +9033,7 @@ TNode CodeStubAssembler::StringToNumber(TNode input) { GotoIf(IsSetWord32(raw_hash_field, Name::kDoesNotContainCachedArrayIndexMask), &runtime); - var_result = SmiTag(Signed( - DecodeWordFromWord32(raw_hash_field))); + var_result = SmiFromUint32(DecodeArrayIndexFromHashField(raw_hash_field)); Goto(&end); BIND(&runtime); @@ -9902,9 +9951,8 @@ void CodeStubAssembler::TryToName(TNode key, Label* if_keyisindex, BIND(&if_has_cached_index); { - TNode index = - Signed(DecodeWordFromWord32( - raw_hash_field)); + TNode index = Signed(ChangeUint32ToWord( + DecodeArrayIndexFromHashField(raw_hash_field))); CSA_DCHECK(this, IntPtrLessThan(index, IntPtrConstant(INT_MAX))); *var_index = index; Goto(if_keyisindex); diff --git a/deps/v8/src/codegen/code-stub-assembler.h b/deps/v8/src/codegen/code-stub-assembler.h index 6f9846af5ab..850411461ed 100644 --- a/deps/v8/src/codegen/code-stub-assembler.h +++ b/deps/v8/src/codegen/code-stub-assembler.h @@ -4614,6 +4614,12 @@ class V8_EXPORT_PRIVATE CodeStubAssembler return WordEqual(WordAnd(flags, IntPtrConstant(mask)), IntPtrConstant(0)); } +#ifdef V8_ENABLE_SEEDED_ARRAY_INDEX_HASH + // Mirror C++ StringHasher::SeedArrayIndexValue and UnseedArrayIndexValue. + TNode SeedArrayIndexValue(TNode value); + TNode UnseedArrayIndexValue(TNode value); +#endif // V8_ENABLE_SEEDED_ARRAY_INDEX_HASH + private: friend class CodeStubArguments; diff --git a/deps/v8/src/heap/factory-base.cc b/deps/v8/src/heap/factory-base.cc index 5a17db0c98d..98857460ca0 100644 --- a/deps/v8/src/heap/factory-base.cc +++ b/deps/v8/src/heap/factory-base.cc @@ -1094,7 +1094,8 @@ inline Handle FactoryBase::SmiToString(Tagged number, if (raw->raw_hash_field() == String::kEmptyHashField && number.value() >= 0) { uint32_t raw_hash_field = StringHasher::MakeArrayIndexHash( - static_cast(number.value()), raw->length()); + static_cast(number.value()), raw->length(), + HashSeed(read_only_roots())); raw->set_raw_hash_field(raw_hash_field); } } diff --git a/deps/v8/src/heap/factory.cc b/deps/v8/src/heap/factory.cc index 64580597d6b..0c258d0290d 100644 --- a/deps/v8/src/heap/factory.cc +++ b/deps/v8/src/heap/factory.cc @@ -3949,7 +3949,8 @@ Handle Factory::SizeToString(size_t value, bool check_cache) { if (value <= JSArray::kMaxArrayIndex && raw->raw_hash_field() == String::kEmptyHashField) { uint32_t raw_hash_field = StringHasher::MakeArrayIndexHash( - static_cast(value), raw->length()); + static_cast(value), raw->length(), + HashSeed(read_only_roots())); raw->set_raw_hash_field(raw_hash_field); } } diff --git a/deps/v8/src/numbers/hash-seed-inl.h b/deps/v8/src/numbers/hash-seed-inl.h index 7ba3fbffb8d..26a1fe22037 100644 --- a/deps/v8/src/numbers/hash-seed-inl.h +++ b/deps/v8/src/numbers/hash-seed-inl.h @@ -26,6 +26,13 @@ inline HashSeed HashSeed::Default() { return HashSeed(kDefaultData); } inline uint64_t HashSeed::seed() const { return data_->seed; } inline const uint64_t* HashSeed::secret() const { return data_->secrets; } +#ifdef V8_ENABLE_SEEDED_ARRAY_INDEX_HASH +inline uint32_t HashSeed::m1() const { return data_->m1; } +inline uint32_t HashSeed::m1_inv() const { return data_->m1_inv; } +inline uint32_t HashSeed::m2() const { return data_->m2; } +inline uint32_t HashSeed::m2_inv() const { return data_->m2_inv; } +#endif // V8_ENABLE_SEEDED_ARRAY_INDEX_HASH + } // namespace internal } // namespace v8 diff --git a/deps/v8/src/numbers/hash-seed.cc b/deps/v8/src/numbers/hash-seed.cc index e22f981f2e9..b455c2fb1a0 100644 --- a/deps/v8/src/numbers/hash-seed.cc +++ b/deps/v8/src/numbers/hash-seed.cc @@ -17,16 +17,66 @@ namespace internal { namespace { -static constexpr HashSeed::Data kDefaultSeed = { - 0, - {RAPIDHASH_DEFAULT_SECRET[0], RAPIDHASH_DEFAULT_SECRET[1], - RAPIDHASH_DEFAULT_SECRET[2]}}; +#ifdef V8_ENABLE_SEEDED_ARRAY_INDEX_HASH +// Calculate the modular inverse using Newton's method. +constexpr uint32_t modular_inverse(uint32_t m) { + uint32_t x = (3 * m) ^ 2; // 5 correct bits + x = x * (2 - m * x); // 10 correct bits + x = x * (2 - m * x); // 20 correct bits + x = x * (2 - m * x); // 40 correct bits + return x; +} + +constexpr uint32_t truncate_for_derived_secrets(uint64_t s) { + return static_cast(s) & Name::kArrayIndexValueMask; +} + +// Derive a multiplier from a rapidhash secret and ensure it's odd. +constexpr uint32_t derive_multiplier(uint64_t secret) { + return truncate_for_derived_secrets(secret) | 1; +} + +// Compute the modular inverse of the derived multiplier. +constexpr uint32_t derive_multiplier_inverse(uint64_t secret) { + return truncate_for_derived_secrets( + modular_inverse(derive_multiplier(secret))); +} + +constexpr bool is_modular_inverse(uint32_t m, uint32_t m_inv) { + return ((m * m_inv) & Name::kArrayIndexValueMask) == 1; +} + +constexpr void DeriveSecretsForArrayIndexHash(HashSeed::Data* data) { + data->m1 = derive_multiplier(data->secrets[0]); + data->m1_inv = derive_multiplier_inverse(data->secrets[0]); + data->m2 = derive_multiplier(data->secrets[1]); + data->m2_inv = derive_multiplier_inverse(data->secrets[1]); +} +#endif // V8_ENABLE_SEEDED_ARRAY_INDEX_HASH + +static constexpr HashSeed::Data kDefaultSeed = [] { + HashSeed::Data d{}; + d.seed = 0; + d.secrets[0] = RAPIDHASH_DEFAULT_SECRET[0]; + d.secrets[1] = RAPIDHASH_DEFAULT_SECRET[1]; + d.secrets[2] = RAPIDHASH_DEFAULT_SECRET[2]; +#ifdef V8_ENABLE_SEEDED_ARRAY_INDEX_HASH + DeriveSecretsForArrayIndexHash(&d); +#endif // V8_ENABLE_SEEDED_ARRAY_INDEX_HASH + return d; +}(); } // anonymous namespace static_assert(HashSeed::kSecretsCount == arraysize(RAPIDHASH_DEFAULT_SECRET)); const HashSeed::Data* const HashSeed::kDefaultData = &kDefaultSeed; +#ifdef V8_ENABLE_SEEDED_ARRAY_INDEX_HASH +// Compile-time verification that m * m_inv === 1 for the derived secrets. +static_assert(is_modular_inverse(kDefaultSeed.m1, kDefaultSeed.m1_inv)); +static_assert(is_modular_inverse(kDefaultSeed.m2, kDefaultSeed.m2_inv)); +#endif // V8_ENABLE_SEEDED_ARRAY_INDEX_HASH + // static void HashSeed::InitializeRoots(Isolate* isolate) { DCHECK(!isolate->heap()->deserialization_complete()); @@ -48,6 +98,11 @@ void HashSeed::InitializeRoots(Isolate* isolate) { #else data->seed = seed; rapidhash_make_secret(seed, data->secrets); +#ifdef V8_ENABLE_SEEDED_ARRAY_INDEX_HASH + DeriveSecretsForArrayIndexHash(data); + DCHECK(is_modular_inverse(data->m1, data->m1_inv)); + DCHECK(is_modular_inverse(data->m2, data->m2_inv)); +#endif // V8_ENABLE_SEEDED_ARRAY_INDEX_HASH #endif // V8_USE_DEFAULT_HASHER_SECRET } diff --git a/deps/v8/src/numbers/hash-seed.h b/deps/v8/src/numbers/hash-seed.h index 87b61c50320..b1dca8ef3e1 100644 --- a/deps/v8/src/numbers/hash-seed.h +++ b/deps/v8/src/numbers/hash-seed.h @@ -46,10 +46,32 @@ class V8_EXPORT_PRIVATE HashSeed { // RAPIDHASH_DEFAULT_SECRET. Otherwise they are derived from the seed // using rapidhash_make_secret(). uint64_t secrets[kSecretsCount]; + +#ifdef V8_ENABLE_SEEDED_ARRAY_INDEX_HASH + // Additional precomputed secrets for seeding the array index value hashes. + uint32_t m1; // lower kArrayIndexValueBits bits of secret[0], must be odd + uint32_t m1_inv; // modular inverse of m1 mod 2^kArrayIndexValueBits + uint32_t m2; // lower kArrayIndexValueBits bits of secret[1], must be odd + uint32_t m2_inv; // modular inverse of m2 mod 2^kArrayIndexValueBits +#endif // V8_ENABLE_SEEDED_ARRAY_INDEX_HASH }; static constexpr int kTotalSize = sizeof(Data); +#ifdef V8_ENABLE_SEEDED_ARRAY_INDEX_HASH + // Byte offsets from the data start, for CSA that loads fields at raw + // offsets from the ByteArray data start. + static constexpr int kDerivedM1Offset = offsetof(Data, m1); + static constexpr int kDerivedM1InvOffset = offsetof(Data, m1_inv); + static constexpr int kDerivedM2Offset = offsetof(Data, m2); + static constexpr int kDerivedM2InvOffset = offsetof(Data, m2_inv); + + inline uint32_t m1() const; + inline uint32_t m1_inv() const; + inline uint32_t m2() const; + inline uint32_t m2_inv() const; +#endif // V8_ENABLE_SEEDED_ARRAY_INDEX_HASH + // Generates a hash seed (from --hash-seed or the RNG) and writes it // together with derived secrets into the isolate's hash_seed in // its read-only roots. @@ -59,7 +81,7 @@ class V8_EXPORT_PRIVATE HashSeed { // Pointer into the Data overlaying the ByteArray data (either // points to read-only roots or to kDefaultData). const Data* data_; - HashSeed(const Data* data) : data_(data) {} + explicit HashSeed(const Data* data) : data_(data) {} // Points to the static constexpr default seed. static const Data* const kDefaultData; diff --git a/deps/v8/src/objects/name.h b/deps/v8/src/objects/name.h index 77ced2a0a10..a98d5b2fb49 100644 --- a/deps/v8/src/objects/name.h +++ b/deps/v8/src/objects/name.h @@ -161,7 +161,19 @@ V8_OBJECT class Name : public PrimitiveHeapObject { // For strings which are array indexes the hash value has the string length // mixed into the hash, mainly to avoid a hash value of zero which would be // the case for the string '0'. 24 bits are used for the array index value. - static const int kArrayIndexValueBits = 24; + static constexpr int kArrayIndexValueBits = 24; + // Mask for extracting the lower kArrayIndexValueBits of a value. + static constexpr uint32_t kArrayIndexValueMask = + (1u << kArrayIndexValueBits) - 1; +#ifdef V8_ENABLE_SEEDED_ARRAY_INDEX_HASH + // Half-width shift used by the seeded xorshift-multiply mixing. + static constexpr int kArrayIndexHashShift = kArrayIndexValueBits / 2; + // The shift must be at least the half width for the xorshift to be an + // involution. + static_assert(kArrayIndexHashShift * 2 >= kArrayIndexValueBits, + "kArrayIndexHashShift must be at least half of " + "kArrayIndexValueBits"); +#endif // V8_ENABLE_SEEDED_ARRAY_INDEX_HASH static const int kArrayIndexLengthBits = kBitsPerInt - kArrayIndexValueBits - HashFieldTypeBits::kSize; diff --git a/deps/v8/src/objects/name.tq b/deps/v8/src/objects/name.tq index 5c4259afbc4..331a1557f69 100644 --- a/deps/v8/src/objects/name.tq +++ b/deps/v8/src/objects/name.tq @@ -56,6 +56,11 @@ macro ContainsCachedArrayIndex(hash: uint32): bool { return (hash & kDoesNotContainCachedArrayIndexMask) == 0; } +@if(V8_ENABLE_SEEDED_ARRAY_INDEX_HASH) + extern macro SeedArrayIndexValue(uint32): uint32; +@if(V8_ENABLE_SEEDED_ARRAY_INDEX_HASH) + extern macro UnseedArrayIndexValue(uint32): uint32; + const kArrayIndexValueBitsShift: uint32 = kNofHashBitFields; const kArrayIndexLengthBitsShift: uint32 = kNofHashBitFields + kArrayIndexValueBits; @@ -73,8 +78,10 @@ macro IsIntegerIndex(hash: NameHash): bool { return hash.hash_field_type == HashFieldType::kIntegerIndex; } -macro MakeArrayIndexHash(value: uint32, length: uint32): NameHash { - // This is in sync with StringHasher::MakeArrayIndexHash. +// This is in sync with the private StringHasher::MakeArrayIndexHash without +// seeding. Do not call directly, use the @export MakeArrayIndexHash wrapper +// below. +macro MakeArrayIndexHashRaw(value: uint32, length: uint32): NameHash { dcheck(length <= kMaxArrayIndexSize); const one: uint32 = 1; dcheck(TenToThe(kMaxCachedArrayIndexLength) < (one << kArrayIndexValueBits)); @@ -88,3 +95,35 @@ macro MakeArrayIndexHash(value: uint32, length: uint32): NameHash { dcheck(IsIntegerIndex(hash)); return hash; } + +// This is in sync with the private StringHasher::DecodeArrayIndexFromHashField +// without seeding. Do not call directly, use the @export +// DecodeArrayIndexFromHashField wrapper below. +macro DecodeArrayIndexFromHashFieldRaw(rawHashField: uint32): uint32 { + const hash: NameHash = %RawDownCast(rawHashField); + dcheck(ContainsCachedArrayIndex(rawHashField) || IsIntegerIndex(hash)); + return hash.array_index_value; +} + +// Mirror C++ public StringHasher::MakeArrayIndexHash. +@export +macro MakeArrayIndexHash(value: uint32, length: uint32): NameHash { + @if(V8_ENABLE_SEEDED_ARRAY_INDEX_HASH) { + return MakeArrayIndexHashRaw(SeedArrayIndexValue(value), length); + } + @ifnot(V8_ENABLE_SEEDED_ARRAY_INDEX_HASH) { + return MakeArrayIndexHashRaw(value, length); + } +} + +// Mirror C++ public StringHasher::DecodeArrayIndexFromHashField. +@export +macro DecodeArrayIndexFromHashField(rawHashField: uint32): uint32 { + const value: uint32 = DecodeArrayIndexFromHashFieldRaw(rawHashField); + @if(V8_ENABLE_SEEDED_ARRAY_INDEX_HASH) { + return UnseedArrayIndexValue(value); + } + @ifnot(V8_ENABLE_SEEDED_ARRAY_INDEX_HASH) { + return value; + } +} diff --git a/deps/v8/src/objects/string-inl.h b/deps/v8/src/objects/string-inl.h index 71a6450886c..47334212e03 100644 --- a/deps/v8/src/objects/string-inl.h +++ b/deps/v8/src/objects/string-inl.h @@ -1596,7 +1596,8 @@ bool String::AsArrayIndex(uint32_t* index) { DisallowGarbageCollection no_gc; uint32_t field = raw_hash_field(); if (ContainsCachedArrayIndex(field)) { - *index = ArrayIndexValueBits::decode(field); + *index = StringHasher::DecodeArrayIndexFromHashField( + field, HashSeed(EarlyGetReadOnlyRoots())); return true; } if (IsHashFieldComputed(field) && !IsIntegerIndex(field)) { @@ -1608,7 +1609,8 @@ bool String::AsArrayIndex(uint32_t* index) { bool String::AsIntegerIndex(size_t* index) { uint32_t field = raw_hash_field(); if (ContainsCachedArrayIndex(field)) { - *index = ArrayIndexValueBits::decode(field); + *index = StringHasher::DecodeArrayIndexFromHashField( + field, HashSeed(EarlyGetReadOnlyRoots())); return true; } if (IsHashFieldComputed(field) && !IsIntegerIndex(field)) { diff --git a/deps/v8/src/objects/string-table.cc b/deps/v8/src/objects/string-table.cc index b233739b740..88ba27a785e 100644 --- a/deps/v8/src/objects/string-table.cc +++ b/deps/v8/src/objects/string-table.cc @@ -598,7 +598,8 @@ Address StringTable::Data::TryStringToIndexOrLookupExisting( // String could be an array index. if (Name::ContainsCachedArrayIndex(raw_hash_field)) { - return Smi::FromInt(String::ArrayIndexValueBits::decode(raw_hash_field)) + return Smi::FromInt(StringHasher::DecodeArrayIndexFromHashField( + raw_hash_field, seed)) .ptr(); } diff --git a/deps/v8/src/objects/string.cc b/deps/v8/src/objects/string.cc index efedc785025..615b05c5e0c 100644 --- a/deps/v8/src/objects/string.cc +++ b/deps/v8/src/objects/string.cc @@ -1884,7 +1884,8 @@ bool String::SlowAsArrayIndex(uint32_t* index) { if (length <= kMaxCachedArrayIndexLength) { uint32_t field = EnsureRawHash(); // Force computation of hash code. if (!IsIntegerIndex(field)) return false; - *index = ArrayIndexValueBits::decode(field); + *index = StringHasher::DecodeArrayIndexFromHashField( + field, HashSeed(EarlyGetReadOnlyRoots())); return true; } if (length == 0 || length > kMaxArrayIndexSize) return false; @@ -1898,7 +1899,8 @@ bool String::SlowAsIntegerIndex(size_t* index) { if (length <= kMaxCachedArrayIndexLength) { uint32_t field = EnsureRawHash(); // Force computation of hash code. if (!IsIntegerIndex(field)) return false; - *index = ArrayIndexValueBits::decode(field); + *index = StringHasher::DecodeArrayIndexFromHashField( + field, HashSeed(EarlyGetReadOnlyRoots())); return true; } if (length == 0 || length > kMaxIntegerIndexSize) return false; diff --git a/deps/v8/src/strings/string-hasher-inl.h b/deps/v8/src/strings/string-hasher-inl.h index d90f582a1a2..90ab93e0820 100644 --- a/deps/v8/src/strings/string-hasher-inl.h +++ b/deps/v8/src/strings/string-hasher-inl.h @@ -10,6 +10,7 @@ // Comment inserted to prevent header reordering. #include +#include "src/common/globals.h" #include "src/objects/name-inl.h" #include "src/objects/string-inl.h" #include "src/strings/char-predicates-inl.h" @@ -67,6 +68,64 @@ uint32_t StringHasher::MakeArrayIndexHash(uint32_t value, uint32_t length) { return value; } +uint32_t StringHasher::DecodeArrayIndexFromHashField(uint32_t raw_hash_field) { + DCHECK(String::ContainsCachedArrayIndex(raw_hash_field) || + String::IsIntegerIndex(raw_hash_field)); + return String::ArrayIndexValueBits::decode(raw_hash_field); +} + +#ifdef V8_ENABLE_SEEDED_ARRAY_INDEX_HASH +uint32_t StringHasher::SeedArrayIndexValue(uint32_t value, + const HashSeed seed) { + uint32_t m1 = seed.m1(); + uint32_t m2 = seed.m2(); + constexpr uint32_t kShift = Name::kArrayIndexHashShift; + constexpr uint32_t kMask = Name::kArrayIndexValueMask; + // 2-round xorshift-multiply. + uint32_t x = value; + x ^= x >> kShift; + x = (x * m1) & kMask; + x ^= x >> kShift; + x = (x * m2) & kMask; + x ^= x >> kShift; + return x; +} + +uint32_t StringHasher::UnseedArrayIndexValue(uint32_t value, + const HashSeed seed) { + uint32_t m1_inv = seed.m1_inv(); + uint32_t m2_inv = seed.m2_inv(); + uint32_t x = value; + constexpr uint32_t kShift = Name::kArrayIndexHashShift; + constexpr uint32_t kMask = Name::kArrayIndexValueMask; + // 2-round xorshift-multiply. + // Xorshift is an involution when kShift is at least half of the value width. + x ^= x >> kShift; + x = (x * m2_inv) & kMask; + x ^= x >> kShift; + x = (x * m1_inv) & kMask; + x ^= x >> kShift; + return x; +} +#endif // V8_ENABLE_SEEDED_ARRAY_INDEX_HASH + +uint32_t StringHasher::MakeArrayIndexHash( + uint32_t value, uint32_t length, [[maybe_unused]] const HashSeed seed) { +#ifdef V8_ENABLE_SEEDED_ARRAY_INDEX_HASH + value = SeedArrayIndexValue(value, seed); +#endif + return MakeArrayIndexHash(value, length); +} + +uint32_t StringHasher::DecodeArrayIndexFromHashField( + uint32_t raw_hash_field, [[maybe_unused]] const HashSeed seed) { + uint32_t value = DecodeArrayIndexFromHashField(raw_hash_field); +#ifdef V8_ENABLE_SEEDED_ARRAY_INDEX_HASH + value = UnseedArrayIndexValue(value, seed); +#endif + return value; +} + template uint32_t StringHasher::HashSequentialString(const char_t* chars_raw, uint32_t length, @@ -106,7 +165,7 @@ uint32_t StringHasher::HashSequentialString(const char_t* chars_raw, // done. if (!needs_overflow_check) { DCHECK_EQ(i, length); - return MakeArrayIndexHash(index, length); + return MakeArrayIndexHash(index, length, seed); } // Otherwise, the last character needs to be checked for both being // digit, and the result being in bounds of the maximum array index. @@ -118,7 +177,7 @@ uint32_t StringHasher::HashSequentialString(const char_t* chars_raw, goto non_index_hash; } if (TryAddArrayIndexChar(&index, c)) { - return MakeArrayIndexHash(index, length); + return MakeArrayIndexHash(index, length, seed); } // If the range check fails, this falls through into the integer index // check. diff --git a/deps/v8/src/strings/string-hasher.h b/deps/v8/src/strings/string-hasher.h index fe824d9bed4..2c204c24067 100644 --- a/deps/v8/src/strings/string-hasher.h +++ b/deps/v8/src/strings/string-hasher.h @@ -40,10 +40,23 @@ class V8_EXPORT_PRIVATE StringHasher final { uint32_t length, const HashSeed seed); - // Calculated hash value for a string consisting of 1 to + // Calculate the hash value for a string consisting of 1 to // String::kMaxArrayIndexSize digits with no leading zeros (except "0"). - // value is represented decimal value. - static V8_INLINE uint32_t MakeArrayIndexHash(uint32_t value, uint32_t length); + // + // The entire hash field consists of (from least significant bit to most): + // - HashFieldType::kIntegerIndex + // - kArrayIndexValueBits::kSize bits containing the hash value + // - The length of the decimal string + // + // When V8_ENABLE_SEEDED_ARRAY_INDEX_HASH is enabled, the numeric value + // is scrambled using secrets derived from the hash seed. When it's disabled + // the public overloads ignore the seed, whose retrieval should be optimized + // away in common configurations. + static V8_INLINE uint32_t MakeArrayIndexHash(uint32_t value, uint32_t length, + const HashSeed seed); + // Decode array index value from raw hash field and reverse seeding, if any. + static V8_INLINE uint32_t + DecodeArrayIndexFromHashField(uint32_t raw_hash_field, const HashSeed seed); // No string is allowed to have a hash of zero. That value is reserved // for internal properties. If the hash calculation yields zero then we @@ -51,6 +64,38 @@ class V8_EXPORT_PRIVATE StringHasher final { static const int kZeroHash = 27; static V8_INLINE uint32_t GetTrivialHash(uint32_t length); + + private: + // Raw encode/decode without seeding. Use the public overloads above. + static V8_INLINE uint32_t MakeArrayIndexHash(uint32_t value, uint32_t length); + static V8_INLINE uint32_t + DecodeArrayIndexFromHashField(uint32_t raw_hash_field); + +#ifdef V8_ENABLE_SEEDED_ARRAY_INDEX_HASH + // When V8_ENABLE_SEEDED_ARRAY_INDEX_HASH is enabled, the numeric value + // will be scrambled with 2 rounds of xorshift-multiply. + // + // x ^= x >> kShift; x = (x * m1) & kMask; // round 1 + // x ^= x >> kShift; x = (x * m2) & kMask; // round 2 + // x ^= x >> kShift; // finalize + // + // To decode, apply the same steps with the modular inverses of m1 and m2 in + // reverse order. + // + // x ^= x >> kShift; x = (x * m2_inv) & kMask; // round 1 + // x ^= x >> kShift; x = (x * m1_inv) & kMask; // round 2 + // x ^= x >> kShift; // finalize + // + // where kShift = kArrayIndexValueBits / 2, kMask = kArrayIndexValueMask, + // m1, m2 (both odd) are derived from the Isolate's rapidhash secrets. + // m1_inv, m2_inv (modular inverses) are precomputed so that + // UnseedArrayIndexValue can quickly recover the original value. + static V8_INLINE uint32_t SeedArrayIndexValue(uint32_t value, + const HashSeed seed); + // Decode array index value from seeded raw hash field. + static V8_INLINE uint32_t UnseedArrayIndexValue(uint32_t value, + const HashSeed seed); +#endif // V8_ENABLE_SEEDED_ARRAY_INDEX_HASH }; // Useful for std containers that require something ()'able. diff --git a/deps/v8/src/torque/torque-parser.cc b/deps/v8/src/torque/torque-parser.cc index 2bfa0cab8d3..06a235d96e9 100644 --- a/deps/v8/src/torque/torque-parser.cc +++ b/deps/v8/src/torque/torque-parser.cc @@ -90,6 +90,11 @@ class BuildFlags : public base::ContextualClass { build_flags_["V8_ENABLE_DRUMBRAKE"] = true; #else build_flags_["V8_ENABLE_DRUMBRAKE"] = false; +#endif +#ifdef V8_ENABLE_SEEDED_ARRAY_INDEX_HASH + build_flags_["V8_ENABLE_SEEDED_ARRAY_INDEX_HASH"] = true; +#else + build_flags_["V8_ENABLE_SEEDED_ARRAY_INDEX_HASH"] = false; #endif } static bool GetFlag(const std::string& name, const char* production) { diff --git a/deps/v8/test/cctest/test-strings.cc b/deps/v8/test/cctest/test-strings.cc index 1858cb0c40b..20e6568bdc1 100644 --- a/deps/v8/test/cctest/test-strings.cc +++ b/deps/v8/test/cctest/test-strings.cc @@ -1854,38 +1854,67 @@ TEST(HashArrayIndexStrings) { v8::HandleScope scope(CcTest::isolate()); i::Isolate* isolate = CcTest::i_isolate(); - CHECK_EQ(Name::HashBits::decode( - StringHasher::MakeArrayIndexHash(0 /* value */, 1 /* length */)), + i::HashSeed seed(isolate); + CHECK_EQ(Name::HashBits::decode(StringHasher::MakeArrayIndexHash( + 0 /* value */, 1 /* length */, seed)), isolate->factory()->zero_string()->hash()); - CHECK_EQ(Name::HashBits::decode( - StringHasher::MakeArrayIndexHash(1 /* value */, 1 /* length */)), + CHECK_EQ(Name::HashBits::decode(StringHasher::MakeArrayIndexHash( + 1 /* value */, 1 /* length */, seed)), isolate->factory()->one_string()->hash()); + CHECK_EQ(0u, StringHasher::DecodeArrayIndexFromHashField( + isolate->factory()->zero_string()->raw_hash_field(), seed)); + CHECK_EQ(1u, StringHasher::DecodeArrayIndexFromHashField( + isolate->factory()->one_string()->raw_hash_field(), seed)); + IndexData tests[] = { - {"", false, 0, false, 0}, - {"123no", false, 0, false, 0}, - {"12345", true, 12345, true, 12345}, - {"12345678", true, 12345678, true, 12345678}, - {"4294967294", true, 4294967294u, true, 4294967294u}, + {"", false, 0, false, 0}, + {"123no", false, 0, false, 0}, + {"12345", true, 12345, true, 12345}, + {"12345678", true, 12345678, true, 12345678}, + {"1000000", true, 1000000, true, 1000000}, + {"9999999", true, 9999999, true, 9999999}, + {"10000000", true, 10000000, true, 10000000}, + {"16777215", true, 16777215, true, 16777215}, // max cached index + {"99999999", true, 99999999, true, 99999999}, + {"4294967294", true, 4294967294u, true, 4294967294u}, #if V8_TARGET_ARCH_32_BIT - {"4294967295", false, 0, false, 0}, // Valid length but not index. - {"4294967296", false, 0, false, 0}, - {"9007199254740991", false, 0, false, 0}, + {"4294967295", false, 0, false, 0}, // Valid length but not index. + {"4294967296", false, 0, false, 0}, + {"9007199254740991", false, 0, false, 0}, #else - {"4294967295", false, 0, true, 4294967295u}, - {"4294967296", false, 0, true, 4294967296ull}, - {"9007199254740991", false, 0, true, 9007199254740991ull}, + {"4294967295", false, 0, true, 4294967295u}, + {"4294967296", false, 0, true, 4294967296ull}, + {"9007199254740991", false, 0, true, 9007199254740991ull}, #endif - {"9007199254740992", false, 0, false, 0}, - {"18446744073709551615", false, 0, false, 0}, - {"18446744073709551616", false, 0, false, 0} - }; + {"9007199254740992", false, 0, false, 0}, + {"18446744073709551615", false, 0, false, 0}, + {"18446744073709551616", false, 0, false, 0}}; for (int i = 0, n = arraysize(tests); i < n; i++) { TestString(isolate, tests[i]); } } +TEST(ArrayIndexHashRoundTrip) { + CcTest::InitializeVM(); + LocalContext context; + v8::HandleScope scope(CcTest::isolate()); + i::Isolate* isolate = CcTest::i_isolate(); + i::HashSeed seed(isolate); + + constexpr uint32_t max_value = (1u << Name::kArrayIndexValueBits) - 1; + for (uint32_t value = 0; value <= max_value; value++) { + uint32_t length = + value == 0 ? 1 : static_cast(std::log10(value)) + 1; + uint32_t raw_hash_field = + StringHasher::MakeArrayIndexHash(value, length, seed); + uint32_t decoded = + StringHasher::DecodeArrayIndexFromHashField(raw_hash_field, seed); + CHECK_EQ(value, decoded); + } +} + TEST(StringEquals) { v8::Isolate* isolate = CcTest::isolate(); v8::HandleScope scope(isolate);