diff --git a/common.gypi b/common.gypi index 953a1448d4b..5e1d6d8b695 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.17', + 'v8_embedder_string': '-node.18', ##### V8 defaults for Node.js ##### diff --git a/deps/v8/BUILD.bazel b/deps/v8/BUILD.bazel index 85f31b7a31f..f28fea4e8aa 100644 --- a/deps/v8/BUILD.bazel +++ b/deps/v8/BUILD.bazel @@ -240,6 +240,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 = [ @@ -512,6 +517,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", "v8_enable_undefined_double": "V8_ENABLE_UNDEFINED_DOUBLE", @@ -2028,6 +2034,7 @@ filegroup( "src/numbers/conversions.h", "src/numbers/conversions-inl.h", "src/numbers/hash-seed.h", + "src/numbers/hash-seed.cc", "src/numbers/hash-seed-inl.h", "src/numbers/ieee754.cc", "src/numbers/ieee754.h", diff --git a/deps/v8/BUILD.gn b/deps/v8/BUILD.gn index bc242c00dcc..4ba6a015295 100644 --- a/deps/v8/BUILD.gn +++ b/deps/v8/BUILD.gn @@ -499,6 +499,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 + # add instrumentation for Dumpling differential fuzzing v8_dumpling = false @@ -1241,6 +1244,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" ] } @@ -5981,6 +5987,7 @@ v8_source_set("v8_base_without_compiler") { "src/logging/runtime-call-stats.cc", "src/logging/tracing-flags.cc", "src/numbers/conversions.cc", + "src/numbers/hash-seed.cc", "src/numbers/ieee754.cc", "src/numbers/math-random.cc", "src/objects/abstract-code.cc", diff --git a/deps/v8/src/DEPS b/deps/v8/src/DEPS index 5ba183818bb..f977b8d83e0 100644 --- a/deps/v8/src/DEPS +++ b/deps/v8/src/DEPS @@ -138,7 +138,7 @@ specific_include_rules = { "heap\.cc": [ "+third_party/rapidhash-v8/secret.h", ], - "hash-seed-inl\.h": [ + "hash-seed\.cc": [ "+third_party/rapidhash-v8/secret.h", ], } 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 bc00018ecb3..b68267a096b 100644 --- a/deps/v8/src/builtins/number.tq +++ b/deps/v8/src/builtins/number.tq @@ -300,7 +300,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. @@ -351,7 +351,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 40efab394f9..5e134d4b7b4 100644 --- a/deps/v8/src/builtins/wasm.tq +++ b/deps/v8/src/builtins/wasm.tq @@ -1611,8 +1611,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 a144defd185..5d666df3dce 100644 --- a/deps/v8/src/codegen/code-stub-assembler.cc +++ b/deps/v8/src/codegen/code-stub-assembler.cc @@ -2711,6 +2711,66 @@ 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, m2 and m3 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 m3 = Load( + hash_seed, IntPtrConstant(base_offset + HashSeed::kDerivedM3Offset)); + + TNode x = value; + // 3-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))); + x = Word32And(Uint32Mul(Unsigned(x), m3), + 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, m2_inv and m3_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 m3_inv = Load( + hash_seed, IntPtrConstant(base_offset + HashSeed::kDerivedM3InvOffset)); + + TNode x = value; + // 3-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), m3_inv), + Uint32Constant(Name::kArrayIndexValueMask)); + 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)); @@ -9404,8 +9464,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); @@ -10535,9 +10594,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 3d52ef5456f..0d73215183f 100644 --- a/deps/v8/src/codegen/code-stub-assembler.h +++ b/deps/v8/src/codegen/code-stub-assembler.h @@ -4835,6 +4835,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 71b1b6189e7..ae9fc5556ab 100644 --- a/deps/v8/src/heap/factory-base.cc +++ b/deps/v8/src/heap/factory-base.cc @@ -299,9 +299,9 @@ Handle FactoryBase::NewProtectedWeakFixedArray( } template -Handle FactoryBase::NewByteArray(int length, - AllocationType allocation) { - return ByteArray::New(isolate(), length, allocation); +Handle FactoryBase::NewByteArray( + int length, AllocationType allocation, AllocationAlignment alignment) { + return ByteArray::New(isolate(), length, allocation, alignment); } template @@ -1173,7 +1173,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); } } @@ -1333,9 +1334,9 @@ FactoryBase::AllocateRawTwoByteInternalizedString( template Tagged FactoryBase::AllocateRawArray( - int size, AllocationType allocation, AllocationHint hint) { - Tagged result = - AllocateRaw(size, allocation, AllocationAlignment::kTaggedAligned, hint); + int size, AllocationType allocation, AllocationHint hint, + AllocationAlignment alignment) { + Tagged result = AllocateRaw(size, allocation, alignment, hint); if ((size > isolate()->heap()->AsHeap()->MaxRegularHeapObjectSize(allocation)) && v8_flags.use_marking_progress_bar) { diff --git a/deps/v8/src/heap/factory-base.h b/deps/v8/src/heap/factory-base.h index fcc711580b3..169dda311f1 100644 --- a/deps/v8/src/heap/factory-base.h +++ b/deps/v8/src/heap/factory-base.h @@ -199,7 +199,8 @@ class FactoryBase : public TorqueGeneratedFactory { // The function returns a pre-allocated empty byte array for length = 0. Handle NewByteArray( - int length, AllocationType allocation = AllocationType::kYoung); + int length, AllocationType allocation = AllocationType::kYoung, + AllocationAlignment alignment = kTaggedAligned); // Allocates a trusted byte array in trusted space, initialized with zeros. Handle NewTrustedByteArray( @@ -417,8 +418,10 @@ class FactoryBase : public TorqueGeneratedFactory { static constexpr int kNumberToStringBufferSize = 32; // Allocate memory for an uninitialized array (e.g., a FixedArray or similar). - Tagged AllocateRawArray(int size, AllocationType allocation, - AllocationHint hint = AllocationHint()); + Tagged AllocateRawArray( + int size, AllocationType allocation, + AllocationHint hint = AllocationHint(), + AllocationAlignment alignment = kTaggedAligned); Tagged AllocateRawFixedArray(int length, AllocationType allocation); Tagged AllocateRawWeakArrayList(int length, diff --git a/deps/v8/src/heap/factory.cc b/deps/v8/src/heap/factory.cc index aa7a66e5c4d..32b47dee39f 100644 --- a/deps/v8/src/heap/factory.cc +++ b/deps/v8/src/heap/factory.cc @@ -4117,7 +4117,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/heap/heap.cc b/deps/v8/src/heap/heap.cc index 0e52b4f26c2..82682a78cd7 100644 --- a/deps/v8/src/heap/heap.cc +++ b/deps/v8/src/heap/heap.cc @@ -134,7 +134,6 @@ #include "src/tracing/trace-event.h" #include "src/utils/utils-inl.h" #include "src/utils/utils.h" -#include "third_party/rapidhash-v8/secret.h" #if V8_ENABLE_WEBASSEMBLY #include "src/wasm/wasm-engine.h" @@ -6207,31 +6206,6 @@ void Heap::SetUpSpaces() { } } -void Heap::InitializeHashSeed() { - DCHECK(!deserialization_complete_); - uint64_t new_hash_seed; - if (v8_flags.hash_seed == 0) { - int64_t rnd = isolate()->random_number_generator()->NextInt64(); - new_hash_seed = static_cast(rnd); - } else { - new_hash_seed = static_cast(v8_flags.hash_seed); - } - - Tagged hash_seed = ReadOnlyRoots(this).hash_seed(); - - MemCopy(hash_seed->begin(), reinterpret_cast(&new_hash_seed), - kInt64Size); - -#if V8_USE_DEFAULT_HASHER_SECRET - MemCopy(hash_seed->begin() + kInt64Size, - reinterpret_cast(RAPIDHASH_DEFAULT_SECRET), - kInt64Size * 3); -#else - rapidhash_make_secret(new_hash_seed, reinterpret_cast( - hash_seed->begin() + kInt64Size)); -#endif // V8_USE_DEFAULT_HASHER_SECRET -} - std::shared_ptr Heap::GetForegroundTaskRunner( TaskPriority priority) const { return V8::GetCurrentPlatform()->GetForegroundTaskRunner( diff --git a/deps/v8/src/heap/heap.h b/deps/v8/src/heap/heap.h index dead9fb6a9a..c51facdc2cf 100644 --- a/deps/v8/src/heap/heap.h +++ b/deps/v8/src/heap/heap.h @@ -716,9 +716,6 @@ class Heap final { // Prepares the heap, setting up for deserialization. void InitializeMainThreadLocalHeap(LocalHeap* main_thread_local_heap); - // (Re-)Initialize hash seed from flag or RNG. - void InitializeHashSeed(); - // Invoked once for the process from V8::Initialize. static void InitializeOncePerProcess(); diff --git a/deps/v8/src/heap/setup-heap-internal.cc b/deps/v8/src/heap/setup-heap-internal.cc index 35d4420dd28..a40192b001d 100644 --- a/deps/v8/src/heap/setup-heap-internal.cc +++ b/deps/v8/src/heap/setup-heap-internal.cc @@ -16,6 +16,7 @@ #include "src/init/heap-symbols.h" #include "src/init/setup-isolate.h" #include "src/interpreter/interpreter.h" +#include "src/numbers/hash-seed.h" #include "src/objects/arguments.h" #include "src/objects/call-site-info.h" #include "src/objects/cell-inl.h" @@ -929,9 +930,10 @@ bool Heap::CreateImportantReadOnlyObjects() { // Hash seed for strings Factory* factory = isolate()->factory(); - set_hash_seed( - *factory->NewByteArray(kInt64Size * 4, AllocationType::kReadOnly)); - InitializeHashSeed(); + set_hash_seed(*factory->NewByteArray(HashSeed::kTotalSize, + AllocationType::kReadOnly, + AllocationAlignment::kDoubleAligned)); + HashSeed::InitializeRoots(isolate()); // Important strings and symbols for (const ConstantStringInit& entry : kImportantConstantStringTable) { diff --git a/deps/v8/src/numbers/hash-seed-inl.h b/deps/v8/src/numbers/hash-seed-inl.h index fb539869226..8988cf8418f 100644 --- a/deps/v8/src/numbers/hash-seed-inl.h +++ b/deps/v8/src/numbers/hash-seed-inl.h @@ -8,7 +8,6 @@ #include "src/numbers/hash-seed.h" #include "src/objects/fixed-array-inl.h" #include "src/roots/roots-inl.h" -#include "third_party/rapidhash-v8/secret.h" namespace v8 { namespace internal { @@ -19,23 +18,22 @@ inline HashSeed::HashSeed(Isolate* isolate) inline HashSeed::HashSeed(LocalIsolate* isolate) : HashSeed(ReadOnlyRoots(isolate)) {} -inline HashSeed::HashSeed(ReadOnlyRoots roots) { - // roots.hash_seed is not aligned - MemCopy(&seed_, roots.hash_seed()->begin(), sizeof(seed_)); - MemCopy(secret_, roots.hash_seed()->begin() + sizeof(seed_), sizeof(secret_)); -} +inline HashSeed::HashSeed(ReadOnlyRoots roots) + : data_(reinterpret_cast(roots.hash_seed()->begin())) {} -inline HashSeed::HashSeed(uint64_t seed, const uint64_t secret[3]) - : seed_(seed), - secret_{ - secret[0], - secret[1], - secret[2], - } {} +inline HashSeed HashSeed::Default() { return HashSeed(kDefaultData); } -inline HashSeed HashSeed::Default() { - return HashSeed(0, RAPIDHASH_DEFAULT_SECRET); -} +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; } +inline uint32_t HashSeed::m3() const { return data_->m3; } +inline uint32_t HashSeed::m3_inv() const { return data_->m3_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 new file mode 100644 index 00000000000..4251cc3ef15 --- /dev/null +++ b/deps/v8/src/numbers/hash-seed.cc @@ -0,0 +1,114 @@ +// 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. + +#include "src/numbers/hash-seed.h" + +#include + +#include "src/execution/isolate.h" +#include "src/flags/flags.h" +#include "src/numbers/hash-seed-inl.h" +#include "src/objects/name.h" +#include "third_party/rapidhash-v8/secret.h" + +namespace v8 { +namespace internal { + +namespace { + +#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]); + data->m3 = derive_multiplier(data->secrets[2]); + data->m3_inv = derive_multiplier_inverse(data->secrets[2]); +} +#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)); +static_assert(is_modular_inverse(kDefaultSeed.m3, kDefaultSeed.m3_inv)); +#endif // V8_ENABLE_SEEDED_ARRAY_INDEX_HASH + +// static +void HashSeed::InitializeRoots(Isolate* isolate) { + DCHECK(!isolate->heap()->deserialization_complete()); + uint64_t seed; + if (v8_flags.hash_seed == 0) { + int64_t rnd = isolate->random_number_generator()->NextInt64(); + seed = static_cast(rnd); + } else { + seed = static_cast(v8_flags.hash_seed); + } + + // Write the seed and derived secrets into the read-only roots ByteArray. + Data* data = const_cast(HashSeed(isolate).data_); + +#if V8_USE_DEFAULT_HASHER_SECRET + // Copy from the default seed and just override the meta seed. + *data = kDefaultSeed; + data->seed = seed; +#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)); + DCHECK(is_modular_inverse(data->m3, data->m3_inv)); +#endif // V8_ENABLE_SEEDED_ARRAY_INDEX_HASH +#endif // V8_USE_DEFAULT_HASHER_SECRET +} + +} // namespace internal +} // namespace v8 diff --git a/deps/v8/src/numbers/hash-seed.h b/deps/v8/src/numbers/hash-seed.h index 48368a25120..7cabdf1223c 100644 --- a/deps/v8/src/numbers/hash-seed.h +++ b/deps/v8/src/numbers/hash-seed.h @@ -5,7 +5,11 @@ #ifndef V8_NUMBERS_HASH_SEED_H_ #define V8_NUMBERS_HASH_SEED_H_ -#include +#include +#include +#include + +#include "src/base/macros.h" namespace v8 { namespace internal { @@ -14,28 +18,84 @@ class Isolate; class LocalIsolate; class ReadOnlyRoots; -class HashSeed { +// A lightweight view over the hash_seed ByteArray in read-only roots. +class V8_EXPORT_PRIVATE HashSeed { public: inline explicit HashSeed(Isolate* isolate); inline explicit HashSeed(LocalIsolate* isolate); inline explicit HashSeed(ReadOnlyRoots roots); - inline explicit HashSeed(uint64_t seed, const uint64_t secret[3]); static inline HashSeed Default(); - uint64_t seed() const { return seed_; } - const uint64_t* secret() const { return secret_; } + inline uint64_t seed() const; + inline const uint64_t* secret() const; - constexpr bool operator==(const HashSeed& b) const { - return seed_ == b.seed_ && secret_[0] == b.secret_[0] && - secret_[1] == b.secret_[1] && secret_[2] == b.secret_[2]; - } + bool operator==(const HashSeed& b) const { return data_ == b.data_; } + + static constexpr int kSecretsCount = 3; + + // The ReadOnlyRoots::hash_seed() byte array can be interpreted + // as a HashSeed::Data struct. + // Since this maps over either the read-only roots or over a static byte + // array, and in both cases, must be allocated at 8-byte boundaries, + // we don't use V8_OBJECT here. + struct Data { + // meta seed from --hash-seed, 0 = generate at startup + uint64_t seed; + // When V8_USE_DEFAULT_HASHER_SECRET is enabled, these are just + // 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 + uint32_t m3; // lower kArrayIndexValueBits bits of secret[2], must be odd + uint32_t m3_inv; // modular inverse of m3 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); + static constexpr int kDerivedM3Offset = offsetof(Data, m3); + static constexpr int kDerivedM3InvOffset = offsetof(Data, m3_inv); + + inline uint32_t m1() const; + inline uint32_t m1_inv() const; + inline uint32_t m2() const; + inline uint32_t m2_inv() const; + inline uint32_t m3() const; + inline uint32_t m3_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. + static void InitializeRoots(Isolate* isolate); private: - uint64_t seed_; - uint64_t secret_[3]; + // Pointer into the Data overlaying the ByteArray data (either + // points to read-only roots or to kDefaultData). + const Data* data_; + explicit HashSeed(const Data* data) : data_(data) {} + + // Points to the static constexpr default seed. + static const Data* const kDefaultData; }; +static_assert(std::is_trivially_copyable_v); +static_assert(alignof(HashSeed::Data) == alignof(uint64_t)); + } // namespace internal } // namespace v8 diff --git a/deps/v8/src/objects/fixed-array-inl.h b/deps/v8/src/objects/fixed-array-inl.h index 0b743e427f6..a0092d2ca11 100644 --- a/deps/v8/src/objects/fixed-array-inl.h +++ b/deps/v8/src/objects/fixed-array-inl.h @@ -591,15 +591,15 @@ template Handle PrimitiveArrayBase::Allocate( IsolateT* isolate, int length, std::optional* no_gc_out, - AllocationType allocation) { + AllocationType allocation, AllocationAlignment alignment) { // Note 0-length is explicitly allowed since not all subtypes can be // assumed to have canonical 0-length instances. DCHECK_GE(length, 0); DCHECK_LE(length, kMaxLength); DCHECK(!no_gc_out->has_value()); - Tagged xs = UncheckedCast( - isolate->factory()->AllocateRawArray(SizeFor(length), allocation)); + Tagged xs = UncheckedCast(isolate->factory()->AllocateRawArray( + SizeFor(length), allocation, AllocationHint(), alignment)); ReadOnlyRoots roots{isolate}; if (DEBUG_BOOL) no_gc_out->emplace(); @@ -818,7 +818,8 @@ DirectHandle ArrayList::New(IsolateT* isolate, int capacity, // static template Handle ByteArray::New(IsolateT* isolate, int length, - AllocationType allocation) { + AllocationType allocation, + AllocationAlignment alignment) { if (V8_UNLIKELY(static_cast(length) > kMaxLength)) { base::FatalNoSecurityImpact("Fatal JavaScript invalid size error %d", length); @@ -828,7 +829,7 @@ Handle ByteArray::New(IsolateT* isolate, int length, std::optional no_gc; Handle result = - Cast(Allocate(isolate, length, &no_gc, allocation)); + Cast(Allocate(isolate, length, &no_gc, allocation, alignment)); int padding_size = SizeFor(length) - OffsetOfElementAt(length); memset(&result->values()[length], 0, padding_size); diff --git a/deps/v8/src/objects/fixed-array.h b/deps/v8/src/objects/fixed-array.h index 59fcd0a4b46..e634550ae8f 100644 --- a/deps/v8/src/objects/fixed-array.h +++ b/deps/v8/src/objects/fixed-array.h @@ -454,7 +454,8 @@ class PrimitiveArrayBase : public detail::ArrayHeaderBase { static Handle Allocate( IsolateT* isolate, int length, std::optional* no_gc_out, - AllocationType allocation = AllocationType::kYoung); + AllocationType allocation = AllocationType::kYoung, + AllocationAlignment alignment = kTaggedAligned); inline bool IsInBounds(int index) const; @@ -792,7 +793,8 @@ V8_OBJECT class ByteArray template static inline Handle New( IsolateT* isolate, int capacity, - AllocationType allocation = AllocationType::kYoung); + AllocationType allocation = AllocationType::kYoung, + AllocationAlignment alignment = kTaggedAligned); inline uint32_t get_int(int offset) const; inline void set_int(int offset, uint32_t value); diff --git a/deps/v8/src/objects/name.h b/deps/v8/src/objects/name.h index 71defb0c53c..0e7a3cdfed8 100644 --- a/deps/v8/src/objects/name.h +++ b/deps/v8/src/objects/name.h @@ -211,7 +211,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 1ef2574c498..8603eaba415 100644 --- a/deps/v8/src/objects/name.tq +++ b/deps/v8/src/objects/name.tq @@ -61,6 +61,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; @@ -78,8 +83,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)); @@ -93,3 +100,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 175fabb486a..1d414c3465e 100644 --- a/deps/v8/src/objects/string-inl.h +++ b/deps/v8/src/objects/string-inl.h @@ -1772,7 +1772,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)) { @@ -1784,7 +1785,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 4f4808a4b66..e67f707481e 100644 --- a/deps/v8/src/objects/string-table.cc +++ b/deps/v8/src/objects/string-table.cc @@ -623,7 +623,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 47a88ad08a3..522f47c9f04 100644 --- a/deps/v8/src/objects/string.cc +++ b/deps/v8/src/objects/string.cc @@ -1906,7 +1906,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; @@ -1920,7 +1921,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/snapshot/read-only-deserializer.cc b/deps/v8/src/snapshot/read-only-deserializer.cc index 47967b29b81..f058f067327 100644 --- a/deps/v8/src/snapshot/read-only-deserializer.cc +++ b/deps/v8/src/snapshot/read-only-deserializer.cc @@ -8,6 +8,7 @@ #include "src/heap/heap-inl.h" #include "src/heap/read-only-heap.h" #include "src/logging/counters-scopes.h" +#include "src/numbers/hash-seed.h" #include "src/objects/objects-inl.h" #include "src/objects/slots.h" #include "src/snapshot/embedded/embedded-data-inl.h" @@ -172,7 +173,7 @@ void ReadOnlyDeserializer::DeserializeIntoIsolate() { #endif if (should_rehash()) { - isolate()->heap()->InitializeHashSeed(); + HashSeed::InitializeRoots(isolate()); Rehash(); } diff --git a/deps/v8/src/snapshot/shared-heap-deserializer.cc b/deps/v8/src/snapshot/shared-heap-deserializer.cc index bfb4a8948d5..1c881843e4c 100644 --- a/deps/v8/src/snapshot/shared-heap-deserializer.cc +++ b/deps/v8/src/snapshot/shared-heap-deserializer.cc @@ -29,7 +29,7 @@ void SharedHeapDeserializer::DeserializeIntoIsolate() { if (should_rehash()) { // The hash seed has already been initialized in ReadOnlyDeserializer, thus - // there is no need to call `isolate()->heap()->InitializeHashSeed();`. + // there is no need to call `HashSeed::InitializeRoots(isolate());`. Rehash(); } } diff --git a/deps/v8/src/strings/string-hasher-inl.h b/deps/v8/src/strings/string-hasher-inl.h index 28d45716631..cbf6e500de4 100644 --- a/deps/v8/src/strings/string-hasher-inl.h +++ b/deps/v8/src/strings/string-hasher-inl.h @@ -8,16 +8,15 @@ #include "src/strings/string-hasher.h" // Include the non-inl header before the rest of the headers. -#include "src/common/globals.h" -#include "src/utils/utils.h" - // 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" #include "src/utils/utils-inl.h" +#include "src/utils/utils.h" #include "third_party/rapidhash-v8/rapidhash.h" namespace v8 { @@ -114,6 +113,70 @@ 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(); + uint32_t m3 = seed.m3(); + constexpr uint32_t kShift = Name::kArrayIndexHashShift; + constexpr uint32_t kMask = Name::kArrayIndexValueMask; + // 3-round xorshift-multiply. + uint32_t x = value; + x ^= x >> kShift; + x = (x * m1) & kMask; + x ^= x >> kShift; + x = (x * m2) & kMask; + x ^= x >> kShift; + x = (x * m3) & 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 m3_inv = seed.m3_inv(); + uint32_t x = value; + constexpr uint32_t kShift = Name::kArrayIndexHashShift; + constexpr uint32_t kMask = Name::kArrayIndexValueMask; + // 3-round xorshift-multiply (inverse). + // Xorshift is an involution when kShift is at least half of the value width. + x ^= x >> kShift; + x = (x * m3_inv) & kMask; + 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; +} + namespace detail { enum IndexParseResult { kSuccess, kNonIndex, kOverflow }; @@ -237,9 +300,11 @@ uint32_t StringHasher::HashSequentialString(const char_t* chars_raw, detail::ArrayIndexT index; uint32_t i; switch (detail::TryParseArrayIndex(chars, length, i, index)) { - case detail::kSuccess: + case detail::kSuccess: { DCHECK_LE(index, String::kMaxArrayIndex); - return MakeArrayIndexHash(static_cast(index), length); + return StringHasher::MakeArrayIndexHash(static_cast(index), + length, seed); + } case detail::kNonIndex: // A non-index result from TryParseArrayIndex means we don't need to // check for integer indices. diff --git a/deps/v8/src/strings/string-hasher.h b/deps/v8/src/strings/string-hasher.h index 80dd0c7aac1..980debe83dd 100644 --- a/deps/v8/src/strings/string-hasher.h +++ b/deps/v8/src/strings/string-hasher.h @@ -46,10 +46,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 @@ -57,6 +70,40 @@ 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 3 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; x = (x * m3) & kMask; // round 3 + // x ^= x >> kShift; // finalize + // + // To decode, apply the same steps with the modular inverses of m1, m2 + // and m3 in reverse order. + // + // x ^= x >> kShift; x = (x * m3_inv) & kMask; // round 1 + // x ^= x >> kShift; x = (x * m2_inv) & kMask; // round 2 + // x ^= x >> kShift; x = (x * m1_inv) & kMask; // round 3 + // x ^= x >> kShift; // finalize + // + // where kShift = kArrayIndexValueBits / 2, kMask = kArrayIndexValueMask, + // m1, m2, m3 (all odd) are derived from the Isolate's rapidhash secrets. + // m1_inv, m2_inv, m3_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 b7066869095..90181643fce 100644 --- a/deps/v8/src/torque/torque-parser.cc +++ b/deps/v8/src/torque/torque-parser.cc @@ -84,6 +84,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 8980fc68c97..93b6477ac2c 100644 --- a/deps/v8/test/cctest/test-strings.cc +++ b/deps/v8/test/cctest/test-strings.cc @@ -1855,38 +1855,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);