build,test: test array index hash collision

This enables v8_enable_seeded_array_index_hash and add a test for it.

deps: V8: backport 0a8b1cdcc8b2

Original commit message:

    implement rapidhash secret generation

    Bug: 409717082
    Change-Id: I471f33d66de32002f744aeba534c1d34f71e27d2
    Reviewed-on: https://chromium-review.googlesource.com/c/v8/v8/+/6733490
    Reviewed-by: Leszek Swirski <leszeks@chromium.org>
    Commit-Queue: snek <snek@chromium.org>
    Cr-Commit-Position: refs/heads/main@{#101499}

deps: V8: backport 185f0fe09b72

Original commit message:

    [numbers] Refactor HashSeed as a lightweight view over ByteArray

    Instead of copying the seed and secrets into a struct with value
    fields, HashSeed now stores a pointer pointing either into the
    read-only ByteArray, or the static default seed for off-heap
    HashSeed::Default() calls. The underlying storage is always
    8-byte aligned so we can cast it directly into a struct.

    Change-Id: I5896a7f2ae24296eb4c80b757a5d90ac70a34866
    Reviewed-on: https://chromium-review.googlesource.com/c/v8/v8/+/7609720
    Reviewed-by: Leszek Swirski <leszeks@chromium.org>
    Commit-Queue: Joyee Cheung <joyee@igalia.com>
    Cr-Commit-Position: refs/heads/main@{#105531}

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 <leszeks@chromium.org>
    Commit-Queue: Joyee Cheung <joyee@igalia.com>
    Cr-Commit-Position: refs/heads/main@{#105596}

deps: V8: cherry-pick aac14dd95e5b

Original commit message:

    [string] add 3rd round to seeded array index hash

    Since we already have 3 derived secrets, and arithmetics are
    relatively cheap, add a 3rd round to the xorshift-multiply
    seeding scheme. This brings the bias from ~3.4 to ~0.4.

    Bug: 477515021
    Change-Id: I1ef48954bcee8768d8c90db06ac8adb02f06cebf
    Reviewed-on: https://chromium-review.googlesource.com/c/v8/v8/+/7655117
    Reviewed-by: Chengzhong Wu <cwu631@bloomberg.net>
    Commit-Queue: Joyee Cheung <joyee@igalia.com>
    Reviewed-by: Leszek Swirski <leszeks@chromium.org>
    Cr-Commit-Position: refs/heads/main@{#105824}

PR-URL: https://github.com/nodejs-private/node-private/pull/834
CVE-ID: CVE-2026-21717

deps: V8: backport 185f0fe09b72

Original commit message:

    [numbers] Refactor HashSeed as a lightweight view over ByteArray

    Instead of copying the seed and secrets into a struct with value
    fields, HashSeed now stores a pointer pointing either into the
    read-only ByteArray, or the static default seed for off-heap
    HashSeed::Default() calls. The underlying storage is always
    8-byte aligned so we can cast it directly into a struct.

    Change-Id: I5896a7f2ae24296eb4c80b757a5d90ac70a34866
    Reviewed-on: https://chromium-review.googlesource.com/c/v8/v8/+/7609720
    Reviewed-by: Leszek Swirski <leszeks@chromium.org>
    Commit-Queue: Joyee Cheung <joyee@igalia.com>
    Cr-Commit-Position: refs/heads/main@{#105531}

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 <leszeks@chromium.org>
    Commit-Queue: Joyee Cheung <joyee@igalia.com>
    Cr-Commit-Position: refs/heads/main@{#105596}

deps: V8: cherry-pick aac14dd95e5b

Original commit message:

    [string] add 3rd round to seeded array index hash

    Since we already have 3 derived secrets, and arithmetics are
    relatively cheap, add a 3rd round to the xorshift-multiply
    seeding scheme. This brings the bias from ~3.4 to ~0.4.

    Bug: 477515021
    Change-Id: I1ef48954bcee8768d8c90db06ac8adb02f06cebf
    Reviewed-on: https://chromium-review.googlesource.com/c/v8/v8/+/7655117
    Reviewed-by: Chengzhong Wu <cwu631@bloomberg.net>
    Commit-Queue: Joyee Cheung <joyee@igalia.com>
    Reviewed-by: Leszek Swirski <leszeks@chromium.org>
    Cr-Commit-Position: refs/heads/main@{#105824}

Co-authored-by: Joyee Cheung <joyeec9h3@gmail.com>
Refs: https://hackerone.com/reports/3511792
Refs: https://github.com/v8/v8/commit/aac14dd95e5be0d487eba6bcdaf9cef4f8bd806c
PR-URL: https://github.com/nodejs/node/pull/61898
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
Reviewed-By: Rafael Gonzaga <rafael.nunu@hotmail.com>
Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
(cherry picked from commit fff9a8aa03)
This commit is contained in:
Joyee Cheung authored and RafaelGSS committed 2026-04-27 07:58:02 -03:00
1 parent 15d406c1b1
commit 089d6c77e7
31 files changed
+561 -126

No files matched your search

+1 -1
View File
@@ -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 #####
+7
View File
@@ -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",
+7
View File
@@ -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",
+1 -1
View File
@@ -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",
],
}
+2 -1
View File
@@ -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
+2 -2
View File
@@ -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.
+2 -2
View File
@@ -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<float64>(arrayIndex);
const arrayIndex: uint32 = DecodeArrayIndexFromHashField(hash);
return Convert<float64>(Signed(arrayIndex));
}
return StringToFloat64(Flatten(s));
}
+63 -5
View File
@@ -2711,6 +2711,66 @@ TNode<Uint32T> CodeStubAssembler::LoadJSReceiverIdentityHash(
return var_hash.value();
}
#ifdef V8_ENABLE_SEEDED_ARRAY_INDEX_HASH
// Mirror C++ StringHasher::SeedArrayIndexValue.
TNode<Uint32T> CodeStubAssembler::SeedArrayIndexValue(TNode<Uint32T> 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<ByteArray> hash_seed = CAST(LoadRoot(RootIndex::kHashSeed));
intptr_t base_offset = OFFSET_OF_DATA_START(ByteArray) - kHeapObjectTag;
TNode<Uint32T> m1 = Load<Uint32T>(
hash_seed, IntPtrConstant(base_offset + HashSeed::kDerivedM1Offset));
TNode<Uint32T> m2 = Load<Uint32T>(
hash_seed, IntPtrConstant(base_offset + HashSeed::kDerivedM2Offset));
TNode<Uint32T> m3 = Load<Uint32T>(
hash_seed, IntPtrConstant(base_offset + HashSeed::kDerivedM3Offset));
TNode<Word32T> 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<Uint32T> CodeStubAssembler::UnseedArrayIndexValue(TNode<Uint32T> 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<ByteArray> hash_seed = CAST(LoadRoot(RootIndex::kHashSeed));
intptr_t base_offset = OFFSET_OF_DATA_START(ByteArray) - kHeapObjectTag;
TNode<Uint32T> m1_inv = Load<Uint32T>(
hash_seed, IntPtrConstant(base_offset + HashSeed::kDerivedM1InvOffset));
TNode<Uint32T> m2_inv = Load<Uint32T>(
hash_seed, IntPtrConstant(base_offset + HashSeed::kDerivedM2InvOffset));
TNode<Uint32T> m3_inv = Load<Uint32T>(
hash_seed, IntPtrConstant(base_offset + HashSeed::kDerivedM3InvOffset));
TNode<Word32T> 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<Uint32T> CodeStubAssembler::LoadNameHashAssumeComputed(TNode<Name> name) {
TNode<Uint32T> hash_field = LoadNameRawHash(name);
CSA_DCHECK(this, IsClearWord32(hash_field, Name::kHashNotComputedMask));
@@ -9404,8 +9464,7 @@ TNode<Number> CodeStubAssembler::StringToNumber(TNode<String> input) {
GotoIf(IsSetWord32(raw_hash_field, Name::kDoesNotContainCachedArrayIndexMask),
&runtime);
var_result = SmiTag(Signed(
DecodeWordFromWord32<String::ArrayIndexValueBits>(raw_hash_field)));
var_result = SmiFromUint32(DecodeArrayIndexFromHashField(raw_hash_field));
Goto(&end);
BIND(&runtime);
@@ -10535,9 +10594,8 @@ void CodeStubAssembler::TryToName(TNode<Object> key, Label* if_keyisindex,
BIND(&if_has_cached_index);
{
TNode<IntPtrT> index =
Signed(DecodeWordFromWord32<String::ArrayIndexValueBits>(
raw_hash_field));
TNode<IntPtrT> index = Signed(ChangeUint32ToWord(
DecodeArrayIndexFromHashField(raw_hash_field)));
CSA_DCHECK(this, IntPtrLessThan(index, IntPtrConstant(INT_MAX)));
*var_index = index;
Goto(if_keyisindex);
+6
View File
@@ -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<Uint32T> SeedArrayIndexValue(TNode<Uint32T> value);
TNode<Uint32T> UnseedArrayIndexValue(TNode<Uint32T> value);
#endif // V8_ENABLE_SEEDED_ARRAY_INDEX_HASH
private:
friend class CodeStubArguments;
+8 -7
View File
@@ -299,9 +299,9 @@ Handle<ProtectedWeakFixedArray> FactoryBase<Impl>::NewProtectedWeakFixedArray(
}
template <typename Impl>
Handle<ByteArray> FactoryBase<Impl>::NewByteArray(int length,
AllocationType allocation) {
return ByteArray::New(isolate(), length, allocation);
Handle<ByteArray> FactoryBase<Impl>::NewByteArray(
int length, AllocationType allocation, AllocationAlignment alignment) {
return ByteArray::New(isolate(), length, allocation, alignment);
}
template <typename Impl>
@@ -1173,7 +1173,8 @@ inline Handle<String> FactoryBase<Impl>::SmiToString(Tagged<Smi> number,
if (raw->raw_hash_field() == String::kEmptyHashField &&
number.value() >= 0) {
uint32_t raw_hash_field = StringHasher::MakeArrayIndexHash(
static_cast<uint32_t>(number.value()), raw->length());
static_cast<uint32_t>(number.value()), raw->length(),
HashSeed(read_only_roots()));
raw->set_raw_hash_field(raw_hash_field);
}
}
@@ -1333,9 +1334,9 @@ FactoryBase<Impl>::AllocateRawTwoByteInternalizedString(
template <typename Impl>
Tagged<HeapObject> FactoryBase<Impl>::AllocateRawArray(
int size, AllocationType allocation, AllocationHint hint) {
Tagged<HeapObject> result =
AllocateRaw(size, allocation, AllocationAlignment::kTaggedAligned, hint);
int size, AllocationType allocation, AllocationHint hint,
AllocationAlignment alignment) {
Tagged<HeapObject> result = AllocateRaw(size, allocation, alignment, hint);
if ((size >
isolate()->heap()->AsHeap()->MaxRegularHeapObjectSize(allocation)) &&
v8_flags.use_marking_progress_bar) {
+6 -3
View File
@@ -199,7 +199,8 @@ class FactoryBase : public TorqueGeneratedFactory<Impl> {
// The function returns a pre-allocated empty byte array for length = 0.
Handle<ByteArray> 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<TrustedByteArray> NewTrustedByteArray(
@@ -417,8 +418,10 @@ class FactoryBase : public TorqueGeneratedFactory<Impl> {
static constexpr int kNumberToStringBufferSize = 32;
// Allocate memory for an uninitialized array (e.g., a FixedArray or similar).
Tagged<HeapObject> AllocateRawArray(int size, AllocationType allocation,
AllocationHint hint = AllocationHint());
Tagged<HeapObject> AllocateRawArray(
int size, AllocationType allocation,
AllocationHint hint = AllocationHint(),
AllocationAlignment alignment = kTaggedAligned);
Tagged<HeapObject> AllocateRawFixedArray(int length,
AllocationType allocation);
Tagged<HeapObject> AllocateRawWeakArrayList(int length,
+2 -1
View File
@@ -4117,7 +4117,8 @@ Handle<String> 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<uint32_t>(value), raw->length());
static_cast<uint32_t>(value), raw->length(),
HashSeed(read_only_roots()));
raw->set_raw_hash_field(raw_hash_field);
}
}
-26
View File
@@ -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<uint64_t>(rnd);
} else {
new_hash_seed = static_cast<uint64_t>(v8_flags.hash_seed);
}
Tagged<ByteArray> hash_seed = ReadOnlyRoots(this).hash_seed();
MemCopy(hash_seed->begin(), reinterpret_cast<uint8_t*>(&new_hash_seed),
kInt64Size);
#if V8_USE_DEFAULT_HASHER_SECRET
MemCopy(hash_seed->begin() + kInt64Size,
reinterpret_cast<const uint8_t*>(RAPIDHASH_DEFAULT_SECRET),
kInt64Size * 3);
#else
rapidhash_make_secret(new_hash_seed, reinterpret_cast<uint64_t*>(
hash_seed->begin() + kInt64Size));
#endif // V8_USE_DEFAULT_HASHER_SECRET
}
std::shared_ptr<v8::TaskRunner> Heap::GetForegroundTaskRunner(
TaskPriority priority) const {
return V8::GetCurrentPlatform()->GetForegroundTaskRunner(
-3
View File
@@ -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();
+5 -3
View File
@@ -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) {
+14 -16
View File
@@ -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<const Data*>(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
+114
View File
@@ -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 <cstddef>
#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<uint32_t>(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<uint64_t>(rnd);
} else {
seed = static_cast<uint64_t>(v8_flags.hash_seed);
}
// Write the seed and derived secrets into the read-only roots ByteArray.
Data* data = const_cast<Data*>(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
+71 -11
View File
@@ -5,7 +5,11 @@
#ifndef V8_NUMBERS_HASH_SEED_H_
#define V8_NUMBERS_HASH_SEED_H_
#include <stdint.h>
#include <cstddef>
#include <cstdint>
#include <type_traits>
#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<HashSeed>);
static_assert(alignof(HashSeed::Data) == alignof(uint64_t));
} // namespace internal
} // namespace v8
+6 -5
View File
@@ -591,15 +591,15 @@ template <class IsolateT>
Handle<D> PrimitiveArrayBase<D, S, P>::Allocate(
IsolateT* isolate, int length,
std::optional<DisallowGarbageCollection>* 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<D> xs = UncheckedCast<D>(
isolate->factory()->AllocateRawArray(SizeFor(length), allocation));
Tagged<D> xs = UncheckedCast<D>(isolate->factory()->AllocateRawArray(
SizeFor(length), allocation, AllocationHint(), alignment));
ReadOnlyRoots roots{isolate};
if (DEBUG_BOOL) no_gc_out->emplace();
@@ -818,7 +818,8 @@ DirectHandle<ArrayList> ArrayList::New(IsolateT* isolate, int capacity,
// static
template <class IsolateT>
Handle<ByteArray> ByteArray::New(IsolateT* isolate, int length,
AllocationType allocation) {
AllocationType allocation,
AllocationAlignment alignment) {
if (V8_UNLIKELY(static_cast<unsigned>(length) > kMaxLength)) {
base::FatalNoSecurityImpact("Fatal JavaScript invalid size error %d",
length);
@@ -828,7 +829,7 @@ Handle<ByteArray> ByteArray::New(IsolateT* isolate, int length,
std::optional<DisallowGarbageCollection> no_gc;
Handle<ByteArray> result =
Cast<ByteArray>(Allocate(isolate, length, &no_gc, allocation));
Cast<ByteArray>(Allocate(isolate, length, &no_gc, allocation, alignment));
int padding_size = SizeFor(length) - OffsetOfElementAt(length);
memset(&result->values()[length], 0, padding_size);
+4 -2
View File
@@ -454,7 +454,8 @@ class PrimitiveArrayBase : public detail::ArrayHeaderBase<Super, true> {
static Handle<Derived> Allocate(
IsolateT* isolate, int length,
std::optional<DisallowGarbageCollection>* 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 <class IsolateT>
static inline Handle<ByteArray> 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);
+13 -1
View File
@@ -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;
+41 -2
View File
@@ -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<NameHash>(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;
}
}
+4 -2
View File
@@ -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)) {
+2 -1
View File
@@ -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();
}
+4 -2
View File
@@ -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;
+2 -1
View File
@@ -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();
}
+1 -1
View File
@@ -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();
}
}
+70 -5
View File
@@ -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 <type_traits>
#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<uint32_t>(index), length);
return StringHasher::MakeArrayIndexHash(static_cast<uint32_t>(index),
length, seed);
}
case detail::kNonIndex:
// A non-index result from TryParseArrayIndex means we don't need to
// check for integer indices.
+50 -3
View File
@@ -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.
+5
View File
@@ -84,6 +84,11 @@ class BuildFlags : public base::ContextualClass<BuildFlags> {
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) {
+48 -19
View File
@@ -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<uint32_t>(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);