Commit 5ef39884404 for nodejs
commit 5ef3988440476b1b320103ee964f79764a51d903
Author: Node.js GitHub Bot <github-bot@iojs.org>
Date: Mon Nov 23 19:44:46 2026 -0500
deps: patch V8 to 15.8.62.61
Refs: https://github.com/v8/v8/compare/15.8.62.44...15.8.62.61
PR-URL: https://github.com/nodejs/node/pull/67693
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
diff --git a/deps/v8/include/v8-version.h b/deps/v8/include/v8-version.h
index 83a261b3ad9..e2fefa97222 100644
--- a/deps/v8/include/v8-version.h
+++ b/deps/v8/include/v8-version.h
@@ -11,7 +11,7 @@
#define V8_MAJOR_VERSION 15
#define V8_MINOR_VERSION 8
#define V8_BUILD_NUMBER 62
-#define V8_PATCH_LEVEL 44
+#define V8_PATCH_LEVEL 61
// Use 1 for candidates and 0 otherwise.
// (Boolean macro values are not supported by all preprocessors.)
diff --git a/deps/v8/src/builtins/builtins-wasm-gen.cc b/deps/v8/src/builtins/builtins-wasm-gen.cc
index 584c1f14766..7cf2060bbc0 100644
--- a/deps/v8/src/builtins/builtins-wasm-gen.cc
+++ b/deps/v8/src/builtins/builtins-wasm-gen.cc
@@ -257,6 +257,19 @@ TNode<BoolT> WasmBuiltinsAssembler::InSharedSpace(TNode<HeapObject> object) {
return IsPageFlagSet(address, MemoryChunk::kInSharedHeap);
}
+TNode<Object> WasmBuiltinsAssembler::LoadWasmRefFromSlot(
+ TNode<Object> object, TNode<IntPtrT> offset) {
+ TNode<IntPtrT> untagged_offset =
+ IntPtrSub(offset, IntPtrConstant(kHeapObjectTag));
+#if V8_ENABLE_SANDBOX
+ return CAST(
+ LoadFromObject(MachineType::AnyTagged(), object, untagged_offset));
+#else
+ return BitcastWordToTagged(UncheckedCast<IntPtrT>(
+ LoadFromObject(MachineType::IntPtr(), object, untagged_offset)));
+#endif
+}
+
// Wasm uses private symbols (e.g. wasm_exception_tag_symbol) to stamp certain
// objects. This builtin checks for presence of such symbols; it is a
// specialization of "GetOwnProperty" behavior: if the object is not a plain
diff --git a/deps/v8/src/builtins/builtins-wasm-gen.h b/deps/v8/src/builtins/builtins-wasm-gen.h
index 66b56de5265..688a321b572 100644
--- a/deps/v8/src/builtins/builtins-wasm-gen.h
+++ b/deps/v8/src/builtins/builtins-wasm-gen.h
@@ -36,6 +36,9 @@ class WasmBuiltinsAssembler : public CodeStubAssembler {
TNode<Float64T> StringToFloat64(TNode<String>);
TNode<BoolT> InSharedSpace(TNode<HeapObject>);
+
+ TNode<Object> LoadWasmRefFromSlot(TNode<Object> object,
+ TNode<IntPtrT> offset);
};
} // namespace internal
diff --git a/deps/v8/src/builtins/js-to-wasm.tq b/deps/v8/src/builtins/js-to-wasm.tq
index e4bbfece672..8eaecc0c6f7 100644
--- a/deps/v8/src/builtins/js-to-wasm.tq
+++ b/deps/v8/src/builtins/js-to-wasm.tq
@@ -156,6 +156,10 @@ macro RefCast<To: type>(i: &intptr):
return torque_internal::unsafe::NewReference<To>(i.object, i.offset);
}
+macro LoadWasmRef(slot: &intptr): Object {
+ return LoadWasmRefFromSlot(slot.object, slot.offset);
+}
+
macro TruncateBigIntToI64(context: Context, input: JSAny): intptr {
// This is only safe to use on 64-bit platforms.
dcheck(Is64());
@@ -953,10 +957,9 @@ builtin JSToWasmHandleReturns(
}
} else {
check((retType & kValueTypeIsRefBit) != 0);
- const ptr = %RawDownCast<RawPtr<uintptr>>(
- wrapperBuffer + kWrapperBufferGPReturnRegister1);
- const rawRef = *GetRefAt<uintptr>(ptr, 0);
- const value = BitcastWordToTagged(rawRef);
+ const slot =
+ GetRefAt<intptr>(wrapperBuffer, kWrapperBufferGPReturnRegister1);
+ const value = LoadWasmRef(slot);
return WasmToJSObject(jsContext, value);
}
}
@@ -1006,8 +1009,7 @@ builtin JSToWasmHandleReturns(
const retType = *retTypes.UncheckedAtIndex(k);
if ((retType & kValueTypeIsRefBit) != 0) {
const slot = locationAllocator.GetGPSlot();
- const rawRef = *slot;
- const value: Object = BitcastWordToTagged(rawRef);
+ const value: Object = LoadWasmRef(slot);
// Store the wasm object in the JSArray to make it GC safe. The
// transformation will happen later in a second loop.
fixedArray.objects[k] = value;
diff --git a/deps/v8/src/builtins/wasm-to-js.tq b/deps/v8/src/builtins/wasm-to-js.tq
index d5e1dd0c421..339d7f7e6f7 100644
--- a/deps/v8/src/builtins/wasm-to-js.tq
+++ b/deps/v8/src/builtins/wasm-to-js.tq
@@ -178,8 +178,7 @@ transitioning macro WasmToJSWrapper(data: WasmImportData): WasmToJSResult {
const paramType = paramIt.NextNotEmpty();
if ((paramType & kValueTypeIsRefBit) != 0) {
const slot = locationAllocator.GetGPSlot();
- const rawRef = *slot;
- const value = BitcastWordToTagged(rawRef);
+ const value = LoadWasmRef(slot);
outParams.objects[nextIndex] =
WasmToJSObject(data.native_context, value);
}
diff --git a/deps/v8/src/builtins/wasm.tq b/deps/v8/src/builtins/wasm.tq
index 89ce0f31e8e..0d2f3b18814 100644
--- a/deps/v8/src/builtins/wasm.tq
+++ b/deps/v8/src/builtins/wasm.tq
@@ -163,6 +163,8 @@ extern macro WasmBuiltinsAssembler::LoadContextFromWasmOrJsFrame():
extern macro WasmBuiltinsAssembler::StringToFloat64(String): float64;
extern macro WasmBuiltinsAssembler::InSharedSpace(HeapObject): bool;
+extern macro WasmBuiltinsAssembler::LoadWasmRefFromSlot(
+ HeapObject|TaggedZeroPattern, intptr): Object;
extern macro SwitchToTheCentralStackIfNeeded(): RawPtr;
extern macro SwitchFromTheCentralStack(RawPtr): void;
diff --git a/deps/v8/src/common/code-memory-access.cc b/deps/v8/src/common/code-memory-access.cc
index 1ac339ae38c..135d38927be 100644
--- a/deps/v8/src/common/code-memory-access.cc
+++ b/deps/v8/src/common/code-memory-access.cc
@@ -472,14 +472,14 @@ void ThreadIsolation::JitPageReference::UnregisterAllocationsExcept(
std::optional<base::Address>
ThreadIsolation::JitPageReference::StartOfAllocationAt(
- base::Address inner_pointer) {
+ base::Address inner_pointer, JitAllocationType type) {
auto it = jit_page_->allocations_.upper_bound(inner_pointer);
if (it == jit_page_->allocations_.begin()) {
return {};
}
it--;
size_t offset = inner_pointer - it->first;
- if (it->second.Size() <= offset) {
+ if (it->second.Size() <= offset || it->second.Type() != type) {
return {};
}
return it->first;
@@ -617,9 +617,9 @@ void ThreadIsolation::RegisterJitAllocations(Address start,
}
}
-void ThreadIsolation::RegisterJitAllocationForTesting(Address obj,
- size_t size) {
- RegisterJitAllocation(obj, size, JitAllocationType::kInstructionStream);
+void ThreadIsolation::RegisterJitAllocationForTesting(Address obj, size_t size,
+ JitAllocationType type) {
+ RegisterJitAllocation(obj, size, type);
}
// static
@@ -685,13 +685,13 @@ ThreadIsolation::SplitJitPages(Address addr1, size_t size1, Address addr2,
// static
std::optional<Address> ThreadIsolation::StartOfJitAllocationAt(
- Address inner_pointer) {
+ Address inner_pointer, JitAllocationType type) {
CFIMetadataWriteScope write_scope("StartOfJitAllocationAt");
std::optional<JitPageReference> page = TryLookupJitPage(inner_pointer, 1);
if (!page) {
return {};
}
- return page->StartOfAllocationAt(inner_pointer);
+ return page->StartOfAllocationAt(inner_pointer, type);
}
// static
@@ -711,14 +711,14 @@ bool ThreadIsolation::WriteProtectMemory(
// static
std::optional<Address> ThreadIsolation::TryLookupStartOfJitAllocationAt(
- Address inner_pointer) {
+ Address inner_pointer, JitAllocationType type) {
CFIMetadataWriteScope write_scope("TryLookupStartOfJitAllocationAt");
std::optional<JitPageReference> page =
TryLookupJitPageWithoutBlocking(inner_pointer);
if (!page) {
return {};
}
- return page->StartOfAllocationAt(inner_pointer);
+ return page->StartOfAllocationAt(inner_pointer, type);
}
// static
diff --git a/deps/v8/src/common/code-memory-access.h b/deps/v8/src/common/code-memory-access.h
index ca042b66e78..7dbaa89748a 100644
--- a/deps/v8/src/common/code-memory-access.h
+++ b/deps/v8/src/common/code-memory-access.h
@@ -197,15 +197,17 @@ class V8_EXPORT ThreadIsolation {
// Try to lookup the start of a jit allocation from inside a signal handler,
// returning std::nullopt if a required lock is already held.
static std::optional<Address> TryLookupStartOfJitAllocationAt(
- Address inner_pointer);
- static std::optional<Address> StartOfJitAllocationAt(Address inner_pointer);
+ Address inner_pointer, JitAllocationType type);
+ static std::optional<Address> StartOfJitAllocationAt(Address inner_pointer,
+ JitAllocationType type);
// Write-protect a given range of memory. Address and size need to be page
// aligned.
V8_NODISCARD static bool WriteProtectMemory(
Address addr, size_t size, PageAllocator::Permission page_permissions);
- static void RegisterJitAllocationForTesting(Address obj, size_t size);
+ static void RegisterJitAllocationForTesting(Address obj, size_t size,
+ JitAllocationType type);
static void UnregisterJitAllocationForTesting(Address addr, size_t size);
#if V8_HAS_PKU_JIT_WRITE_PROTECT
@@ -285,7 +287,7 @@ class V8_EXPORT ThreadIsolation {
void UnregisterRange(base::Address addr, size_t size);
std::optional<base::Address> StartOfAllocationAt(
- base::Address inner_pointer);
+ base::Address inner_pointer, JitAllocationType type);
std::pair<base::Address, JitAllocation&> AllocationContaining(
base::Address addr);
base::Address EndOfLastAllocation();
diff --git a/deps/v8/src/compiler/access-info.cc b/deps/v8/src/compiler/access-info.cc
index 35025fbb80b..7845db57561 100644
--- a/deps/v8/src/compiler/access-info.cc
+++ b/deps/v8/src/compiler/access-info.cc
@@ -9,7 +9,6 @@
#include <ostream>
#include "src/base/logging.h"
-#include "src/builtins/accessors.h"
#include "src/common/globals.h"
#include "src/compiler/compilation-dependencies.h"
#include "src/compiler/heap-refs.h"
@@ -24,6 +23,7 @@
#include "src/objects/field-index-inl.h"
#include "src/objects/field-type.h"
#include "src/objects/instance-type-inl.h"
+#include "src/objects/js-array.h"
#include "src/objects/module-inl.h"
#include "src/objects/objects-inl.h"
#include "src/objects/property-details.h"
@@ -53,7 +53,7 @@ bool CanInlinePropertyAccess(MapRef map, AccessMode access_mode) {
static_assert(ODDBALL_TYPE == LAST_PRIMITIVE_HEAP_OBJECT_TYPE);
if (IsBooleanMap(*map.object())) return true;
if (map.instance_type() < LAST_PRIMITIVE_HEAP_OBJECT_TYPE) return true;
- if (IsJSObjectMap(*map.object())) {
+ if (map.IsJSObjectMap()) {
if (map.is_dictionary_map()) {
if (!V8_DICT_PROPERTY_CONST_TRACKING_BOOL) return false;
return access_mode == AccessMode::kLoad && map.is_prototype_map();
@@ -63,7 +63,7 @@ bool CanInlinePropertyAccess(MapRef map, AccessMode access_mode) {
!map.is_access_check_needed();
}
#if V8_ENABLE_WEBASSEMBLY
- if (IsAnyWasmObjectMap(*map.object())) {
+ if (map.IsAnyWasmObjectMap()) {
DCHECK(!map.has_named_interceptor());
DCHECK(!map.is_access_check_needed());
// Accesses to Wasm objects all go through the prototype chain, but
@@ -118,7 +118,7 @@ ElementAccessInfo::ElementAccessInfo(
ElementAccessInfo::ElementAccessInfo(MapRef map, ObjectRef accessor,
ObjectRef target, bool string_keys,
Zone* zone)
- : elements_kind_(map.elements_kind()),
+ : elements_kind_(NO_ELEMENTS),
string_keys_(string_keys),
lookup_start_object_maps_({map}, zone),
transition_sources_(zone),
@@ -1020,7 +1020,7 @@ PropertyAccessInfo TryComputeDictionaryDataFieldAccessInfo(
// Receiver map must be a standard JSObject without access checks or
// interceptors.
if (!map.is_dictionary_map() || !map.IsJSObjectMap() ||
- IsJSGlobalObjectMap(*map.object()) || map.is_access_check_needed() ||
+ map.IsJSGlobalObjectMap() || map.is_access_check_needed() ||
map.has_named_interceptor()) {
return PropertyAccessInfo::Invalid(zone);
}
@@ -1061,7 +1061,7 @@ PropertyAccessInfo AccessInfoFactory::ComputePropertyAccessInfo(
}
}
- if (access_mode == AccessMode::kHas && !IsJSReceiverMap(*map.object())) {
+ if (access_mode == AccessMode::kHas && !map.IsJSReceiverMap()) {
return Invalid();
}
@@ -1198,7 +1198,7 @@ PropertyAccessInfo AccessInfoFactory::ComputePropertyAccessInfo(
// Don't search on the prototype chain for special indices in case of
// integer indexed exotic objects (see ES6 section 9.4.5).
- if (IsJSTypedArrayMap(*map.object()) && name.IsString()) {
+ if (map.IsJSTypedArrayMap() && name.IsString()) {
StringRef name_str = name.AsString();
SharedStringAccessGuardIfNeeded access_guard(
*name_str.object(), broker()->local_isolate_or_isolate());
@@ -1240,11 +1240,11 @@ PropertyAccessInfo AccessInfoFactory::ComputePropertyAccessInfo(
HeapObjectRef prototype = map.prototype(broker());
MapRef map_prototype_map = prototype.map(broker());
- if (!IsJSObjectMap(*map_prototype_map.object())) {
+ if (!map_prototype_map.IsJSObjectMap()) {
// Don't allow proxies on the prototype chain.
if (!prototype.IsNull()) {
- DCHECK(IsJSProxy(*prototype.object()) ||
- IsWasmObject(*prototype.object()));
+ DCHECK(map_prototype_map.IsJSProxyMap() ||
+ map_prototype_map.IsAnyWasmObjectMap());
return Invalid();
}
@@ -1403,14 +1403,14 @@ std::optional<ElementAccessInfo> AccessInfoFactory::ConsolidateElementLoad(
PropertyAccessInfo AccessInfoFactory::LookupSpecialFieldAccessor(
MapRef map, NameRef name) const {
// Check for String::length field accessor.
- if (IsStringMap(*map.object())) {
+ if (map.IsStringMap()) {
if (Name::Equals(isolate(), name.object(),
isolate()->factory()->length_string())) {
return PropertyAccessInfo::StringLength(zone(), map);
}
return Invalid();
}
- if (IsJSPrimitiveWrapperMap(*map.object()) &&
+ if (map.IsJSPrimitiveWrapperMap() &&
(map.elements_kind() == FAST_STRING_WRAPPER_ELEMENTS ||
map.elements_kind() == SLOW_STRING_WRAPPER_ELEMENTS)) {
if (Name::Equals(isolate(), name.object(),
@@ -1418,29 +1418,29 @@ PropertyAccessInfo AccessInfoFactory::LookupSpecialFieldAccessor(
return PropertyAccessInfo::StringWrapperLength(zone(), map);
}
}
- // Check for special JSObject field accessors.
- FieldIndex field_index;
- if (Accessors::IsJSObjectFieldAccessor(isolate(), map.object(), name.object(),
- &field_index)) {
+ // Check for special JSObject field accessors. Mirrors
+ // Accessors::IsJSObjectFieldAccessor, inlined here to use the snapshotted
+ // MapRef instance type rather than reading the live Map.
+ if (map.IsJSArrayMap() && !map.is_dictionary_map() &&
+ Name::Equals(isolate(), name.object(),
+ isolate()->factory()->length_string())) {
+ FieldIndex field_index = FieldIndex::ForInObjectOffset(
+ offsetof(JSArray, length_), FieldIndex::kTagged);
Type field_type = Type::NonInternal();
Representation field_representation = Representation::Tagged();
- if (IsJSArrayMap(*map.object())) {
- DCHECK(Name::Equals(isolate(), isolate()->factory()->length_string(),
- name.object()));
- // The JSArray::length property is a smi in the range
- // [0, FixedDoubleArray::kMaxLength] in case of fast double
- // elements, a smi in the range [0, FixedArray::kMaxLength]
- // in case of other fast elements, and [0, kMaxUInt32] in
- // case of other arrays.
- if (IsDoubleElementsKind(map.elements_kind())) {
- field_type = type_cache_->kFixedDoubleArrayLengthType;
- field_representation = Representation::Smi();
- } else if (IsFastElementsKind(map.elements_kind())) {
- field_type = type_cache_->kFixedArrayLengthType;
- field_representation = Representation::Smi();
- } else {
- field_type = type_cache_->kJSArrayLengthType;
- }
+ // The JSArray::length property is a smi in the range
+ // [0, FixedDoubleArray::kMaxLength] in case of fast double
+ // elements, a smi in the range [0, FixedArray::kMaxLength]
+ // in case of other fast elements, and [0, kMaxUInt32] in
+ // case of other arrays.
+ if (IsDoubleElementsKind(map.elements_kind())) {
+ field_type = type_cache_->kFixedDoubleArrayLengthType;
+ field_representation = Representation::Smi();
+ } else if (IsFastElementsKind(map.elements_kind())) {
+ field_type = type_cache_->kFixedArrayLengthType;
+ field_representation = Representation::Smi();
+ } else {
+ field_type = type_cache_->kJSArrayLengthType;
}
// Special fields are always mutable.
return PropertyAccessInfo::DataField(broker(), zone(), map, {{}, zone()},
@@ -1455,9 +1455,8 @@ PropertyAccessInfo AccessInfoFactory::LookupSpecialFieldAccessorInHolder(
PropertyDetails details, InternalIndex index) const {
// Check whether we're accessing the `length` property in a TypedArray
// prototype.
- if (v8_flags.typed_array_length_loading &&
- IsJSTypedArrayMap(*receiver_map.object()) &&
- !IsJSDetachedTypedArrayMap(*receiver_map.object()) &&
+ if (v8_flags.typed_array_length_loading && receiver_map.IsJSTypedArrayMap() &&
+ !receiver_map.IsJSDetachedTypedArrayMap() &&
!IsRabGsabTypedArrayElementsKind(receiver_map.elements_kind()) &&
Name::Equals(isolate(), name.object(),
isolate()->factory()->length_string()) &&
diff --git a/deps/v8/src/compiler/access-info.h b/deps/v8/src/compiler/access-info.h
index 74029290fd7..7cf8383321b 100644
--- a/deps/v8/src/compiler/access-info.h
+++ b/deps/v8/src/compiler/access-info.h
@@ -48,6 +48,7 @@ class ElementAccessInfo final {
void AddTransitionSource(MapRef map) {
CHECK_EQ(lookup_start_object_maps_.size(), 1);
+ CHECK(!is_proxy_on_prototype());
transition_sources_.push_back(map);
}
diff --git a/deps/v8/src/compiler/backend/arm/instruction-selector-arm.cc b/deps/v8/src/compiler/backend/arm/instruction-selector-arm.cc
index 140c8905af3..71b9b337c7b 100644
--- a/deps/v8/src/compiler/backend/arm/instruction-selector-arm.cc
+++ b/deps/v8/src/compiler/backend/arm/instruction-selector-arm.cc
@@ -3644,6 +3644,11 @@ InstructionSelector::AlignmentRequirements() {
SomeUnalignedAccessUnsupported(req_aligned, req_aligned);
}
+void InstructionSelector::EmitDecompressTaggedParam(
+ OpIndex node, InstructionOperand temp_op) {
+ UNREACHABLE();
+}
+
} // namespace compiler
} // namespace internal
} // namespace v8
diff --git a/deps/v8/src/compiler/backend/arm64/code-generator-arm64.cc b/deps/v8/src/compiler/backend/arm64/code-generator-arm64.cc
index 0d60664e9d4..9dc90c630bf 100644
--- a/deps/v8/src/compiler/backend/arm64/code-generator-arm64.cc
+++ b/deps/v8/src/compiler/backend/arm64/code-generator-arm64.cc
@@ -1979,7 +1979,11 @@ CodeGenerator::CodeGenResult CodeGenerator::AssembleArchInstruction(
ASSEMBLE_SHIFT(Ror, 32);
break;
case kArm64Mov32:
- __ Mov(i.OutputRegister32(), i.InputRegister32(0));
+ if (instr->InputAt(0)->IsRegister()) {
+ __ Mov(i.OutputRegister32(), i.InputRegister32(0));
+ } else {
+ __ Ldr(i.OutputRegister32(), i.ToMemOperand(instr->InputAt(0), masm()));
+ }
break;
case kArm64Sxtb32:
__ Sxtb(i.OutputRegister32(), i.InputRegister32(0));
@@ -2566,8 +2570,15 @@ CodeGenerator::CodeGenResult CodeGenerator::AssembleArchInstruction(
__ DecompressTaggedSigned(i.OutputRegister(), i.MemoryOperand());
break;
case kArm64LdrDecompressTagged:
- RecordTrapInfoIfNeeded(zone(), this, opcode, instr, __ pc_offset());
- __ DecompressTagged(i.OutputRegister(), i.MemoryOperand());
+ if (AddressingModeField::decode(instr->opcode()) != kMode_None) {
+ RecordTrapInfoIfNeeded(zone(), this, opcode, instr, __ pc_offset());
+ __ DecompressTagged(i.OutputRegister(), i.MemoryOperand());
+ } else if (instr->InputAt(0)->IsRegister()) {
+ __ DecompressTagged(i.OutputRegister(), i.InputRegister(0));
+ } else {
+ __ DecompressTagged(i.OutputRegister(),
+ i.ToMemOperand(instr->InputAt(0), masm()));
+ }
break;
case kArm64LdrDecompressProtected:
RecordTrapInfoIfNeeded(zone(), this, opcode, instr, __ pc_offset());
diff --git a/deps/v8/src/compiler/backend/arm64/instruction-selector-arm64.cc b/deps/v8/src/compiler/backend/arm64/instruction-selector-arm64.cc
index ad354c3f146..547c282d757 100644
--- a/deps/v8/src/compiler/backend/arm64/instruction-selector-arm64.cc
+++ b/deps/v8/src/compiler/backend/arm64/instruction-selector-arm64.cc
@@ -3230,6 +3230,17 @@ void InstructionSelector::VisitFloat64Ieee754Unop(OpIndex node,
void InstructionSelector::EmitMoveParamToFPR(OpIndex node, int index) {}
+void InstructionSelector::EmitDecompressTaggedParam(
+ OpIndex node, InstructionOperand temp_op) {
+ Arm64OperandGenerator g(this);
+ InstructionOperand result_op = g.DefineAsRegister(node);
+ InstructionCode opcode =
+ Cast<ParameterOp>(node).rep == RegisterRepresentation::Compressed()
+ ? kArm64Mov32
+ : kArm64LdrDecompressTagged;
+ Emit(opcode, 1, &result_op, 1, &temp_op);
+}
+
void InstructionSelector::EmitMoveFPRToParam(InstructionOperand* op,
LinkageLocation location) {}
@@ -3297,7 +3308,21 @@ void InstructionSelector::EmitPrepareResults(
Arm64OperandGenerator g(this);
for (PushParameter output : *results) {
+#if V8_ENABLE_WEBASSEMBLY && V8_ENABLE_SANDBOX
+ if (!output.location.IsCallerFrameSlot()) {
+ if (!output.op.IsInvalid()) {
+ DCHECK(output.node.valid());
+ InstructionOperand result_op = g.DefineAsRegister(output.node);
+ InstructionCode opcode = output.needs_decompression
+ ? kArm64LdrDecompressTagged
+ : kArm64Mov32;
+ Emit(opcode, 1, &result_op, 1, &output.op);
+ }
+ continue;
+ }
+#else
if (!output.location.IsCallerFrameSlot()) continue;
+#endif // V8_ENABLE_WEBASSEMBLY && V8_ENABLE_SANDBOX
// Skip any alignment holes in nodes.
if (output.node.valid()) {
DCHECK(!call_descriptor->IsCFunctionCall());
@@ -3312,6 +3337,21 @@ void InstructionSelector::EmitPrepareResults(
int offset = call_descriptor->GetOffsetToReturns();
int reverse_slot = -output.location.GetLocation() - offset;
+#if V8_ENABLE_WEBASSEMBLY && V8_ENABLE_SANDBOX
+ if (call_descriptor->IsAnyWasmFunctionCall() &&
+ output.location.GetType() == MachineType::AnyTagged() &&
+ IsReallyUsed(output.node)) {
+ InstructionOperand temp = g.TempRegister();
+ MarkAsRepresentation(MachineRepresentation::kTagged, temp);
+ Emit(kArm64Peek, temp, g.UseImmediate(reverse_slot));
+ InstructionOperand result_op = g.DefineAsRegister(output.node);
+ InstructionCode opcode = output.needs_decompression
+ ? kArm64LdrDecompressTagged
+ : kArm64Mov32;
+ Emit(opcode, 1, &result_op, 1, &temp);
+ continue;
+ }
+#endif // V8_ENABLE_WEBASSEMBLY && V8_ENABLE_SANDBOX
Emit(kArm64Peek, g.DefineAsRegister(output.node),
g.UseImmediate(reverse_slot));
}
diff --git a/deps/v8/src/compiler/backend/ia32/instruction-selector-ia32.cc b/deps/v8/src/compiler/backend/ia32/instruction-selector-ia32.cc
index c7eae16fc9f..5a3f4000cb8 100644
--- a/deps/v8/src/compiler/backend/ia32/instruction-selector-ia32.cc
+++ b/deps/v8/src/compiler/backend/ia32/instruction-selector-ia32.cc
@@ -3899,6 +3899,11 @@ InstructionSelector::AlignmentRequirements() {
FullUnalignedAccessSupport();
}
+void InstructionSelector::EmitDecompressTaggedParam(
+ OpIndex node, InstructionOperand temp_op) {
+ UNREACHABLE();
+}
+
} // namespace compiler
} // namespace internal
} // namespace v8
diff --git a/deps/v8/src/compiler/backend/instruction-selector.cc b/deps/v8/src/compiler/backend/instruction-selector.cc
index 7487c94ef7f..31fd68ad75f 100644
--- a/deps/v8/src/compiler/backend/instruction-selector.cc
+++ b/deps/v8/src/compiler/backend/instruction-selector.cc
@@ -93,6 +93,10 @@ InstructionSelector::InstructionSelector(
node_count_(node_count),
phi_states_(zone)
#endif
+#if V8_ENABLE_WEBASSEMBLY && V8_ENABLE_SANDBOX
+ ,
+ params_to_decompress_(zone)
+#endif
#if V8_TARGET_ARCH_ARM64 || defined(V8_ENABLE_APX_F)
,
ccmp_cascade_info_(zone)
@@ -1150,6 +1154,37 @@ void InstructionSelector::InitializeCallBuffer(
MachineRepresentation rep = location.GetType().representation();
OpIndex output = buffer->output_nodes[i].node;
+#if V8_ENABLE_WEBASSEMBLY && V8_ENABLE_SANDBOX
+ bool is_wasm_tagged_return = false;
+ if (!is_tail_call && buffer->descriptor->IsAnyWasmFunctionCall() &&
+ location.GetType() == MachineType::AnyTagged() && output.valid()) {
+ RegisterRepresentation out_rep;
+ if (buffer->output_nodes.size() == 1) {
+ for (OpIndex call_use : turboshaft_uses(output)) {
+ if (const DidntThrowOp* didnt_throw =
+ this->Get(call_use).TryCast<DidntThrowOp>()) {
+ if (IsReallyUsed(call_use)) {
+ is_wasm_tagged_return = true;
+ out_rep = didnt_throw->outputs_rep()[0];
+ }
+ break;
+ }
+ }
+ } else if (IsReallyUsed(output)) {
+ is_wasm_tagged_return = true;
+ out_rep = Cast<ProjectionOp>(output).rep;
+ }
+ if (is_wasm_tagged_return) {
+ if (out_rep == RegisterRepresentation::Compressed()) {
+ rep = MachineRepresentation::kCompressed;
+ } else {
+ DCHECK_EQ(out_rep, RegisterRepresentation::Tagged());
+ buffer->output_nodes[i].needs_decompression = true;
+ }
+ }
+ }
+#endif // V8_ENABLE_WEBASSEMBLY && V8_ENABLE_SANDBOX
+
InstructionOperand op = !output.valid()
? g.TempLocation(location)
: g.DefineAsLocation(output, location);
@@ -1157,6 +1192,19 @@ void InstructionSelector::InitializeCallBuffer(
// Caller frame slots are defined later via Peek in VisitCall.
if (!UnallocatedOperand::cast(op).HasFixedSlotPolicy()) {
+#if V8_ENABLE_WEBASSEMBLY && V8_ENABLE_SANDBOX
+ if (is_wasm_tagged_return) {
+ InstructionOperand temp_op = g.TempLocation(location);
+ MarkAsRepresentation(location.GetType().representation(), temp_op);
+ buffer->outputs.push_back(temp_op);
+ buffer->output_nodes[i].op =
+ location.IsRegister()
+ ? g.UseRegisterForVreg(
+ UnallocatedOperand::cast(temp_op).virtual_register())
+ : temp_op;
+ continue;
+ }
+#endif // V8_ENABLE_WEBASSEMBLY && V8_ENABLE_SANDBOX
buffer->outputs.push_back(op);
buffer->output_nodes[i].node = {};
}
@@ -1533,6 +1581,40 @@ void InstructionSelector::VisitBlock(const Block* block) {
}
}
+#if V8_ENABLE_WEBASSEMBLY && V8_ENABLE_SANDBOX
+ if (!params_to_decompress_.empty()) {
+ DCHECK_NE(param_instructions_start_, -1);
+ OperandGenerator g(this);
+ ZoneVector<std::pair<OpIndex, InstructionOperand>> decompress_ops(zone());
+ decompress_ops.reserve(params_to_decompress_.size());
+ for (auto [node, index] : params_to_decompress_) {
+ LinkageLocation location = linkage()->GetParameterLocation(index);
+ InstructionOperand temp_op = g.TempLocation(location);
+ Emit(kArchNop, temp_op);
+ InstructionOperand use_op =
+ location.IsRegister()
+ ? g.UseRegisterForVreg(
+ UnallocatedOperand::cast(temp_op).virtual_register())
+ : temp_op;
+ decompress_ops.push_back({node, use_op});
+ }
+ int nop_instructions_end = current_num_instructions();
+ for (auto [node, use_op] : decompress_ops) {
+ EmitDecompressTaggedParam(node, use_op);
+ }
+ // `instructions_` is stored in reverse execution order (higher indices are
+ // executed earlier in the block). Rotate so that all `kArchNop` parameter
+ // definitions are at the highest indices (executed first on function
+ // entry), followed by all `EmitDecompressTaggedParam` instructions, before
+ // any physical parameter register can be reused as an output.
+ std::rotate(instructions_.begin() + param_instructions_start_,
+ instructions_.begin() + nop_instructions_end,
+ instructions_.end());
+ params_to_decompress_.clear();
+ }
+ param_instructions_start_ = -1;
+#endif // V8_ENABLE_WEBASSEMBLY && V8_ENABLE_SANDBOX
+
// We're done with the block.
InstructionBlock* instruction_block =
sequence()->InstructionBlockAt(this->rpo_number(block));
@@ -2027,9 +2109,31 @@ void InstructionSelector::VisitParameter(OpIndex node) {
const int index = parameter.parameter_index;
OperandGenerator g(this);
+#if V8_ENABLE_WEBASSEMBLY && V8_ENABLE_SANDBOX
+ if (param_instructions_start_ == -1) {
+ // ParameterOps are only present at the beginning of the entry block (and
+ // thus visited last during the reverse iteration in `VisitBlock`).
+ DCHECK_EQ(current_block_->index().id(), 0);
+ param_instructions_start_ = static_cast<int>(instructions_.size());
+ }
+#endif // V8_ENABLE_WEBASSEMBLY && V8_ENABLE_SANDBOX
+
if (linkage()->GetParameterLocation(index).IsNullRegister()) {
EmitMoveParamToFPR(node, index);
} else {
+#if V8_ENABLE_WEBASSEMBLY && V8_ENABLE_SANDBOX
+ // Parameter 0 is the Wasm instance data (or import data) in trusted space,
+ // which uses a different cage base and must not be decompressed.
+ const CallDescriptor* incoming = linkage()->GetIncomingDescriptor();
+ if ((incoming->IsAnyWasmFunctionCall() || incoming->IsWasmImportWrapper() ||
+ incoming->IsWasmCapiFunction()) &&
+ index > 0 &&
+ (parameter.rep == RegisterRepresentation::Tagged() ||
+ parameter.rep == RegisterRepresentation::Compressed())) {
+ params_to_decompress_.push_back({node, index});
+ return;
+ }
+#endif // V8_ENABLE_WEBASSEMBLY && V8_ENABLE_SANDBOX
InstructionOperand op =
linkage()->ParameterHasSecondaryLocation(index)
? g.DefineAsDualLocation(
@@ -2992,7 +3096,13 @@ void InstructionSelector::VisitNode(OpIndex node) {
DCHECK_EQ(this->rpo_number(this->block(schedule(), node)).ToInt(), 0);
MachineType type =
linkage()->GetParameterType(op.Cast<ParameterOp>().parameter_index);
- MarkAsRepresentation(type.representation(), node);
+ MachineRepresentation rep = type.representation();
+#if V8_ENABLE_WEBASSEMBLY && V8_ENABLE_SANDBOX
+ if (op.Cast<ParameterOp>().rep == RegisterRepresentation::Compressed()) {
+ rep = MachineRepresentation::kCompressed;
+ }
+#endif // V8_ENABLE_WEBASSEMBLY && V8_ENABLE_SANDBOX
+ MarkAsRepresentation(rep, node);
return VisitParameter(node);
}
case Opcode::kChange: {
diff --git a/deps/v8/src/compiler/backend/instruction-selector.h b/deps/v8/src/compiler/backend/instruction-selector.h
index b8af2591b81..403aeaccf7c 100644
--- a/deps/v8/src/compiler/backend/instruction-selector.h
+++ b/deps/v8/src/compiler/backend/instruction-selector.h
@@ -388,6 +388,13 @@ struct PushParameter {
turboshaft::OpIndex node;
LinkageLocation location;
+#if V8_ENABLE_WEBASSEMBLY && V8_ENABLE_SANDBOX
+ // For Wasm return values in registers that need pointer decompression, `op`
+ // holds the temporary operand at the return location so `EmitPrepareResults`
+ // can decompress it into `node`'s virtual register.
+ InstructionOperand op;
+ bool needs_decompression = false;
+#endif // V8_ENABLE_WEBASSEMBLY && V8_ENABLE_SANDBOX
};
enum class FrameStateInputKind { kAny, kStackSlot };
@@ -1112,6 +1119,9 @@ class V8_EXPORT_PRIVATE InstructionSelector final
void VisitFloat64Ieee754Binop(turboshaft::OpIndex, InstructionCode code);
void VisitFloat64Ieee754Unop(turboshaft::OpIndex, InstructionCode code);
+ void EmitDecompressTaggedParam(turboshaft::OpIndex node,
+ InstructionOperand temp_op);
+
#define DECLARE_GENERATOR_T(x) void Visit##x(turboshaft::OpIndex node);
DECLARE_GENERATOR_T(Word32And)
DECLARE_GENERATOR_T(Word32Xor)
@@ -1616,6 +1626,11 @@ class V8_EXPORT_PRIVATE InstructionSelector final
ZoneVector<Upper32BitsState> phi_states_;
#endif
+#if V8_ENABLE_WEBASSEMBLY && V8_ENABLE_SANDBOX
+ ZoneVector<std::pair<turboshaft::OpIndex, int>> params_to_decompress_;
+ int param_instructions_start_ = -1;
+#endif // V8_ENABLE_WEBASSEMBLY && V8_ENABLE_SANDBOX
+
// CCMP branch-cascade fusion is compiled only where a ccmp emission path
// exists: ARM64 (native) and x64 with APX (runtime-gated on APX availability).
#if V8_TARGET_ARCH_ARM64 || defined(V8_ENABLE_APX_F)
diff --git a/deps/v8/src/compiler/backend/jump-threading.cc b/deps/v8/src/compiler/backend/jump-threading.cc
index efd6328c6db..394b77b5516 100644
--- a/deps/v8/src/compiler/backend/jump-threading.cc
+++ b/deps/v8/src/compiler/backend/jump-threading.cc
@@ -125,8 +125,7 @@ struct GapJumpRecord {
bool JumpThreading::ComputeForwarding(Zone* local_zone,
ZoneVector<RpoNumber>* result,
- InstructionSequence* code,
- bool frame_at_start) {
+ InstructionSequence* code) {
ZoneStack<RpoNumber> stack(local_zone);
JumpThreadingState state = {false, *result, stack};
state.Clear(code->InstructionBlockCount());
@@ -156,9 +155,13 @@ bool JumpThreading::ComputeForwarding(Zone* local_zone,
// can forward to a block with identical gap-moves.
if (instr->arch_opcode() == kArchJmp) {
TRACE(" jmp");
+ // Never record or forward a block that constructs or deconstructs a
+ // frame: skipping it drops the frame transition, and forwarding
+ // another block into it (e.g. a loop backedge into B0) re-executes
+ // frame construction.
RpoNumber forward_to;
- if ((frame_at_start || !(block->must_deconstruct_frame() ||
- block->must_construct_frame())) &&
+ if (!(block->must_deconstruct_frame() ||
+ block->must_construct_frame()) &&
record.CanForwardGapJump(instr, block->rpo_number(),
code->InputRpo(instr, 0),
&forward_to)) {
@@ -179,13 +182,10 @@ bool JumpThreading::ComputeForwarding(Zone* local_zone,
} else if (instr->arch_opcode() == kArchJmp) {
// try to forward the jump instruction.
TRACE(" jmp\n");
- // if this block deconstructs the frame, we can't forward it.
- // TODO(mtrofin): we can still forward if we end up building
- // the frame at start. So we should move the decision of whether
- // to build a frame or not in the register allocator, and trickle it
- // here and to the code generator.
- if (frame_at_start || !(block->must_deconstruct_frame() ||
- block->must_construct_frame())) {
+ // If this block constructs or deconstructs the frame, we can't
+ // forward it.
+ if (!(block->must_deconstruct_frame() ||
+ block->must_construct_frame())) {
fw = code->InputRpo(instr, 0);
}
} else if (instr->IsRet()) {
diff --git a/deps/v8/src/compiler/backend/jump-threading.h b/deps/v8/src/compiler/backend/jump-threading.h
index ce9e3949249..755990cafc2 100644
--- a/deps/v8/src/compiler/backend/jump-threading.h
+++ b/deps/v8/src/compiler/backend/jump-threading.h
@@ -18,7 +18,7 @@ class V8_EXPORT_PRIVATE JumpThreading {
// Compute the forwarding map of basic blocks to their ultimate destination.
// Returns {true} if there is at least one block that is forwarded.
static bool ComputeForwarding(Zone* local_zone, ZoneVector<RpoNumber>* result,
- InstructionSequence* code, bool frame_at_start);
+ InstructionSequence* code);
// Rewrite the instructions to forward jumps and branches.
// May also negate some branches.
diff --git a/deps/v8/src/compiler/backend/loong64/instruction-selector-loong64.cc b/deps/v8/src/compiler/backend/loong64/instruction-selector-loong64.cc
index 889991a7e46..81cfcaacda2 100644
--- a/deps/v8/src/compiler/backend/loong64/instruction-selector-loong64.cc
+++ b/deps/v8/src/compiler/backend/loong64/instruction-selector-loong64.cc
@@ -4036,6 +4036,11 @@ InstructionSelector::AlignmentRequirements() {
FullUnalignedAccessSupport();
}
+void InstructionSelector::EmitDecompressTaggedParam(
+ OpIndex node, InstructionOperand temp_op) {
+ UNREACHABLE();
+}
+
#undef SIMD_BINOP_LIST
#undef SIMD_SHIFT_OP_LIST
#undef SIMD_UNOP_LIST
diff --git a/deps/v8/src/compiler/backend/mips64/instruction-selector-mips64.cc b/deps/v8/src/compiler/backend/mips64/instruction-selector-mips64.cc
index a65d5981816..2d3fa3069c0 100644
--- a/deps/v8/src/compiler/backend/mips64/instruction-selector-mips64.cc
+++ b/deps/v8/src/compiler/backend/mips64/instruction-selector-mips64.cc
@@ -2966,6 +2966,11 @@ InstructionSelector::AlignmentRequirements() {
}
}
+void InstructionSelector::EmitDecompressTaggedParam(
+ OpIndex node, InstructionOperand temp_op) {
+ UNREACHABLE();
+}
+
#undef SIMD_BINOP_LIST
#undef SIMD_SHIFT_OP_LIST
#undef SIMD_RELAXED_OP_LIST
diff --git a/deps/v8/src/compiler/backend/ppc/instruction-selector-ppc.cc b/deps/v8/src/compiler/backend/ppc/instruction-selector-ppc.cc
index ff7db2fec3b..198a23f0d2b 100644
--- a/deps/v8/src/compiler/backend/ppc/instruction-selector-ppc.cc
+++ b/deps/v8/src/compiler/backend/ppc/instruction-selector-ppc.cc
@@ -2925,6 +2925,11 @@ InstructionSelector::AlignmentRequirements() {
FullUnalignedAccessSupport();
}
+void InstructionSelector::EmitDecompressTaggedParam(
+ OpIndex node, InstructionOperand temp_op) {
+ UNREACHABLE();
+}
+
} // namespace compiler
} // namespace internal
} // namespace v8
diff --git a/deps/v8/src/compiler/backend/register-allocator.cc b/deps/v8/src/compiler/backend/register-allocator.cc
index 4de50ce1094..3e71083556d 100644
--- a/deps/v8/src/compiler/backend/register-allocator.cc
+++ b/deps/v8/src/compiler/backend/register-allocator.cc
@@ -389,8 +389,8 @@ void LiveRange::AdvanceLastProcessedMarker(
}
LiveRange* LiveRange::SplitAt(LifetimePosition position, Zone* zone) {
- DCHECK(Start() < position);
- DCHECK(End() > position);
+ CHECK_LT(Start(), position);
+ CHECK_GT(End(), position);
int new_id = TopLevel()->GetNextChildId();
LiveRange* result =
diff --git a/deps/v8/src/compiler/backend/riscv/instruction-selector-riscv.h b/deps/v8/src/compiler/backend/riscv/instruction-selector-riscv.h
index f8a310591e0..c09d7814609 100644
--- a/deps/v8/src/compiler/backend/riscv/instruction-selector-riscv.h
+++ b/deps/v8/src/compiler/backend/riscv/instruction-selector-riscv.h
@@ -1834,6 +1834,11 @@ void InstructionSelector::AddOutputToSelectContinuation(OperandGenerator* g,
continuation_outputs_.push_back(g->DefineAsRegister(node));
}
+void InstructionSelector::EmitDecompressTaggedParam(
+ OpIndex node, InstructionOperand temp_op) {
+ UNREACHABLE();
+}
+
#if V8_ENABLE_WEBASSEMBLY
void InstructionSelector::VisitSetStackPointer(OpIndex node) {
diff --git a/deps/v8/src/compiler/backend/s390/instruction-selector-s390.cc b/deps/v8/src/compiler/backend/s390/instruction-selector-s390.cc
index 3ddc155cbcb..c0a2c0564d1 100644
--- a/deps/v8/src/compiler/backend/s390/instruction-selector-s390.cc
+++ b/deps/v8/src/compiler/backend/s390/instruction-selector-s390.cc
@@ -3404,6 +3404,11 @@ InstructionSelector::AlignmentRequirements() {
FullUnalignedAccessSupport();
}
+void InstructionSelector::EmitDecompressTaggedParam(
+ OpIndex node, InstructionOperand temp_op) {
+ UNREACHABLE();
+}
+
} // namespace compiler
} // namespace internal
} // namespace v8
diff --git a/deps/v8/src/compiler/backend/x64/code-generator-x64.cc b/deps/v8/src/compiler/backend/x64/code-generator-x64.cc
index d81a7bbcf39..d69787f557b 100644
--- a/deps/v8/src/compiler/backend/x64/code-generator-x64.cc
+++ b/deps/v8/src/compiler/backend/x64/code-generator-x64.cc
@@ -3482,12 +3482,18 @@ CodeGenerator::CodeGenResult CodeGenerator::AssembleArchInstruction(
}
case kX64MovqDecompressTagged: {
CHECK(instr->HasOutput());
- RecordTrapInfoIfNeeded(zone(), this, opcode, instr, __ pc_offset());
- Operand address(i.MemoryOperand());
- __ DecompressTagged(i.OutputRegister(), address);
- EmitTSANRelaxedLoadOOLIfNeeded(zone(), this, masm(), address,
- MakeSharedBaseTsanArgument(instr, i), i,
- DetermineStubCallMode(), kTaggedSize);
+ if (HasAddressingMode(instr)) {
+ RecordTrapInfoIfNeeded(zone(), this, opcode, instr, __ pc_offset());
+ Operand address(i.MemoryOperand());
+ __ DecompressTagged(i.OutputRegister(), address);
+ EmitTSANRelaxedLoadOOLIfNeeded(zone(), this, masm(), address,
+ MakeSharedBaseTsanArgument(instr, i), i,
+ DetermineStubCallMode(), kTaggedSize);
+ } else if (instr->InputAt(0)->IsRegister()) {
+ __ DecompressTagged(i.OutputRegister(), i.InputRegister(0));
+ } else {
+ __ DecompressTagged(i.OutputRegister(), i.InputOperand(0));
+ }
break;
}
case kX64MovqCompressTagged: {
diff --git a/deps/v8/src/compiler/backend/x64/instruction-selector-x64.cc b/deps/v8/src/compiler/backend/x64/instruction-selector-x64.cc
index 97a66ee51e0..bc722a7c68c 100644
--- a/deps/v8/src/compiler/backend/x64/instruction-selector-x64.cc
+++ b/deps/v8/src/compiler/backend/x64/instruction-selector-x64.cc
@@ -3248,6 +3248,17 @@ void InstructionSelector::VisitFloat64Ieee754Unop(OpIndex node,
void InstructionSelector::EmitMoveParamToFPR(OpIndex node, int index) {}
+void InstructionSelector::EmitDecompressTaggedParam(
+ OpIndex node, InstructionOperand temp_op) {
+ X64OperandGenerator g(this);
+ InstructionOperand result_op = g.DefineAsRegister(node);
+ InstructionCode opcode =
+ Cast<ParameterOp>(node).rep == RegisterRepresentation::Compressed()
+ ? kX64Movl
+ : kX64MovqDecompressTagged;
+ Emit(opcode, 1, &result_op, 1, &temp_op);
+}
+
void InstructionSelector::EmitMoveFPRToParam(InstructionOperand* op,
LinkageLocation location) {}
@@ -3313,7 +3324,20 @@ void InstructionSelector::EmitPrepareResults(
OpIndex node) {
X64OperandGenerator g(this);
for (PushParameter output : *results) {
+#if V8_ENABLE_WEBASSEMBLY && V8_ENABLE_SANDBOX
+ if (!output.location.IsCallerFrameSlot()) {
+ if (!output.op.IsInvalid()) {
+ DCHECK(output.node.valid());
+ InstructionOperand result_op = g.DefineAsRegister(output.node);
+ InstructionCode opcode =
+ output.needs_decompression ? kX64MovqDecompressTagged : kX64Movl;
+ Emit(opcode, 1, &result_op, 1, &output.op);
+ }
+ continue;
+ }
+#else
if (!output.location.IsCallerFrameSlot()) continue;
+#endif // V8_ENABLE_WEBASSEMBLY && V8_ENABLE_SANDBOX
// Skip any alignment holes in nodes.
if (output.node.valid()) {
DCHECK(!call_descriptor->IsCFunctionCall());
@@ -3324,10 +3348,24 @@ void InstructionSelector::EmitPrepareResults(
} else if (output.location.GetType() == MachineType::Simd128()) {
MarkAsSimd128(output.node);
}
- InstructionOperand result = g.DefineAsRegister(output.node);
int offset = call_descriptor->GetOffsetToReturns();
int reverse_slot = -output.location.GetLocation() - offset;
InstructionOperand slot = g.UseImmediate(reverse_slot);
+#if V8_ENABLE_WEBASSEMBLY && V8_ENABLE_SANDBOX
+ if (call_descriptor->IsAnyWasmFunctionCall() &&
+ output.location.GetType() == MachineType::AnyTagged() &&
+ IsReallyUsed(output.node)) {
+ InstructionOperand temp = g.TempRegister();
+ MarkAsRepresentation(MachineRepresentation::kTagged, temp);
+ Emit(kX64Peek, 1, &temp, 1, &slot);
+ InstructionOperand result = g.DefineAsRegister(output.node);
+ InstructionCode opcode =
+ output.needs_decompression ? kX64MovqDecompressTagged : kX64Movl;
+ Emit(opcode, 1, &result, 1, &temp);
+ continue;
+ }
+#endif // V8_ENABLE_WEBASSEMBLY && V8_ENABLE_SANDBOX
+ InstructionOperand result = g.DefineAsRegister(output.node);
Emit(kX64Peek, 1, &result, 1, &slot);
}
}
diff --git a/deps/v8/src/compiler/bytecode-graph-builder.cc b/deps/v8/src/compiler/bytecode-graph-builder.cc
index 1b580b4ba31..457b5611ab5 100644
--- a/deps/v8/src/compiler/bytecode-graph-builder.cc
+++ b/deps/v8/src/compiler/bytecode-graph-builder.cc
@@ -1733,9 +1733,13 @@ void BytecodeGraphBuilder::VisitLdaContextSlot() {
}
void BytecodeGraphBuilder::VisitLdaImmutableContextSlot() {
+ // LdaImmutableContextSlot is emitted for kNotAssigned context slots, which
+ // the debugger may still mutate at runtime.
+ bool immutable =
+ !broker()->isolate()->is_context_slot_not_assigned_unreliable();
const Operator* op = javascript()->LoadContextNoCell(
bytecode_iterator().GetUnsignedImmediateOperand(2),
- bytecode_iterator().GetContextSlotOperand(1), true);
+ bytecode_iterator().GetContextSlotOperand(1), immutable);
Node* node = NewNode(op);
Node* context =
environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
@@ -1758,8 +1762,12 @@ void BytecodeGraphBuilder::VisitLdaCurrentContextSlot() {
}
void BytecodeGraphBuilder::VisitLdaImmutableCurrentContextSlot() {
+ // LdaImmutableCurrentContextSlot is emitted for kNotAssigned context slots,
+ // which the debugger may still mutate at runtime.
+ bool immutable =
+ !broker()->isolate()->is_context_slot_not_assigned_unreliable();
const Operator* op = javascript()->LoadContextNoCell(
- 0, bytecode_iterator().GetContextSlotOperand(0), true);
+ 0, bytecode_iterator().GetContextSlotOperand(0), immutable);
Node* node = NewNode(op);
environment()->BindAccumulator(node);
}
diff --git a/deps/v8/src/compiler/escape-analysis.cc b/deps/v8/src/compiler/escape-analysis.cc
index 87757ff5d47..0e2bc171a08 100644
--- a/deps/v8/src/compiler/escape-analysis.cc
+++ b/deps/v8/src/compiler/escape-analysis.cc
@@ -4,6 +4,7 @@
#include "src/compiler/escape-analysis.h"
+#include "src/base/numerics/checked_math.h"
#include "src/codegen/tick-counter.h"
#include "src/compiler/frame-states.h"
#include "src/compiler/node-matchers.h"
@@ -560,8 +561,12 @@ Maybe<int> OffsetOfElementAt(ElementAccess const& access, int index) {
DCHECK_GE(index, 0);
DCHECK_GE(ElementSizeLog2Of(representation), kTaggedSizeLog2);
- return Just(access.header_size +
- (index << ElementSizeLog2Of(representation)));
+ base::CheckedNumeric<int> byte_index = base::CheckedNumeric<int>(index)
+ << ElementSizeLog2Of(representation);
+ base::CheckedNumeric<int> offset = byte_index + access.header_size;
+ int result;
+ if (!offset.AssignIfValid(&result)) return Nothing<int>();
+ return Just(result);
}
Maybe<int> OffsetOfElementsAccess(const Operator* op, Node* index_node) {
@@ -571,8 +576,11 @@ Maybe<int> OffsetOfElementsAccess(const Operator* op, Node* index_node) {
if (!index_type.Is(Type::OrderedNumber())) return Nothing<int>();
double max = index_type.Max();
double min = index_type.Min();
+ if (min < 0 || min != max || !base::IsValueInRangeForNumericType<int>(min)) {
+ return Nothing<int>();
+ }
int index = static_cast<int>(min);
- if (index < 0 || index != min || index != max) return Nothing<int>();
+ if (index != min) return Nothing<int>();
return OffsetOfElementAt(ElementAccessOf(op), index);
}
diff --git a/deps/v8/src/compiler/escape-analysis.h b/deps/v8/src/compiler/escape-analysis.h
index c2650e75f77..d950e979c48 100644
--- a/deps/v8/src/compiler/escape-analysis.h
+++ b/deps/v8/src/compiler/escape-analysis.h
@@ -130,7 +130,7 @@ class VirtualObject : public Dependable {
Maybe<Variable> FieldAt(int offset) const {
CHECK(IsAligned(offset, kTaggedSize));
CHECK(!HasEscaped());
- if (offset >= size()) {
+ if (offset < 0 || offset >= size()) {
// TODO(turbofan): Reading out-of-bounds can only happen in unreachable
// code. In this case, we have to mark the object as escaping to avoid
// dead nodes in the graph. This is a workaround that should be removed
diff --git a/deps/v8/src/compiler/heap-refs.cc b/deps/v8/src/compiler/heap-refs.cc
index 1c14ba6fc60..c1405e447e4 100644
--- a/deps/v8/src/compiler/heap-refs.cc
+++ b/deps/v8/src/compiler/heap-refs.cc
@@ -664,6 +664,19 @@ class MapData : public HeapObjectData {
CHECK(InstanceTypeChecker::IsJSObject(instance_type()));
return in_object_properties_;
}
+ uint8_t GetInObjectPropertiesStartInWords() const {
+ DCHECK(InstanceTypeChecker::IsJSObject(instance_type()));
+ return inobject_properties_start_or_constructor_function_index_;
+ }
+ int GetConstructorFunctionIndex() const {
+#if V8_ENABLE_WEBASSEMBLY
+ DCHECK(instance_type() <= LAST_PRIMITIVE_HEAP_OBJECT_TYPE ||
+ instance_type() == WASM_NULL_TYPE);
+#else
+ DCHECK(instance_type() <= LAST_PRIMITIVE_HEAP_OBJECT_TYPE);
+#endif
+ return inobject_properties_start_or_constructor_function_index_;
+ }
int UnusedPropertyFields() const { return unused_property_fields_; }
bool is_abandoned_prototype_map() const {
return is_abandoned_prototype_map_;
@@ -676,6 +689,7 @@ class MapData : public HeapObjectData {
InstanceType instance_type_;
int instance_size_;
+ uint8_t inobject_properties_start_or_constructor_function_index_;
Map::Bits2 bit_field2_;
Map::Bits3 bit_field3_;
int unused_property_fields_;
@@ -1014,12 +1028,11 @@ MapData::MapData(JSHeapBroker* broker, ObjectData** storage,
JSHeapBroker::MapUpdaterGuardIfNeeded mumd_scope(broker);
// When background serializing the map, we can perform a lite serialization
- // since the MapRef will read some of the Map's fields can be read directly.
-
- // Even though MapRefs can read {instance_type} directly, other classes depend
- // on {instance_type} being serialized.
+ // since the MapRef will read some of the Map's fields directly.
instance_type_ = object->instance_type();
instance_size_ = object->instance_size();
+ inobject_properties_start_or_constructor_function_index_ =
+ object->inobject_properties_start_or_constructor_function_index();
bit_field2_ = object->bit_field2();
@@ -1033,9 +1046,11 @@ MapData::MapData(JSHeapBroker* broker, ObjectData** storage,
// lock in more places.
bit_field3_ = object->relaxed_bit_field3();
is_abandoned_prototype_map_ = object->is_abandoned_prototype_map();
- if (IsJSObjectMap(*object)) {
+ if (InstanceTypeChecker::IsJSObject(instance_type_)) {
unused_property_fields_ = object->UnusedPropertyFields();
- in_object_properties_ = object->GetInObjectProperties();
+ in_object_properties_ =
+ (instance_size_ >> kTaggedSizeLog2) -
+ inobject_properties_start_or_constructor_function_index_;
} else {
unused_property_fields_ = 0;
in_object_properties_ = 0;
@@ -1335,11 +1350,11 @@ bool MapRef::IsStringWrapperMap() const {
}
bool MapRef::IsOneByteStringMap() const {
- return InstanceTypeChecker::IsOneByteString(*object());
+ return InstanceTypeChecker::IsOneByteString(instance_type());
}
bool MapRef::IsTwoByteStringMap() const {
- return InstanceTypeChecker::IsTwoByteString(*object());
+ return InstanceTypeChecker::IsTwoByteString(instance_type());
}
bool MapRef::CanInlineElementAccess() const {
@@ -1532,7 +1547,7 @@ FieldIndex MapRef::GetFieldIndexFor(InternalIndex descriptor_index) const {
}
int MapRef::GetInObjectPropertyOffset(int i) const {
- return object()->GetInObjectPropertyOffset(i);
+ return (GetInObjectPropertiesStartInWords() + i) * kTaggedSize;
}
PropertyDetails MapRef::GetPropertyDetails(
@@ -2114,7 +2129,8 @@ bool MapRef::IsInobjectSlackTrackingInProgress() const {
}
int MapRef::constructor_function_index() const {
- return object()->GetConstructorFunctionIndex();
+ IF_ACCESS_FROM_HEAP_C(GetConstructorFunctionIndex);
+ return data()->AsMap()->GetConstructorFunctionIndex();
}
bool MapRef::is_stable() const {
@@ -2124,10 +2140,15 @@ bool MapRef::is_stable() const {
bool MapRef::CanBeDeprecated() const { return object()->CanBeDeprecated(); }
-bool MapRef::CanTransition() const { return object()->CanTransition(); }
+bool MapRef::CanTransition() const {
+ const InstanceType type = instance_type();
+ return InstanceTypeChecker::IsJSObject(type) &&
+ !InstanceTypeChecker::IsMaybeReadOnlyJSObject(type);
+}
uint8_t MapRef::GetInObjectPropertiesStartInWords() const {
- return object()->GetInObjectPropertiesStartInWords();
+ IF_ACCESS_FROM_HEAP_C(GetInObjectPropertiesStartInWords);
+ return data()->AsMap()->GetInObjectPropertiesStartInWords();
}
int MapRef::GetInObjectProperties() const {
diff --git a/deps/v8/src/compiler/js-call-reducer.cc b/deps/v8/src/compiler/js-call-reducer.cc
index 9c18c8c2362..080e06f79f3 100644
--- a/deps/v8/src/compiler/js-call-reducer.cc
+++ b/deps/v8/src/compiler/js-call-reducer.cc
@@ -3145,7 +3145,9 @@ void JSCallReducer::Finalize() {
Reduction const reduction = Reduce(node);
if (reduction.Changed()) {
Node* replacement = reduction.replacement();
- if (replacement != node) {
+ if (replacement == node) {
+ Revisit(node);
+ } else {
Replace(node, replacement, max_id);
}
}
diff --git a/deps/v8/src/compiler/js-heap-broker.cc b/deps/v8/src/compiler/js-heap-broker.cc
index 6e716415226..71efb88a4ab 100644
--- a/deps/v8/src/compiler/js-heap-broker.cc
+++ b/deps/v8/src/compiler/js-heap-broker.cc
@@ -676,9 +676,11 @@ ProcessedFeedback const& JSHeapBroker::ReadFeedbackForGlobalAccess(
OptionalObjectRef contents = context.get(broker, context_slot_index);
if (contents.has_value()) CHECK(!contents->IsTdzHole());
- return *zone()->New<GlobalAccessFeedback>(
- context, context_slot_index,
- FeedbackNexus::ImmutabilityBit::decode(number), nexus.kind());
+ // Lexical script-context const slots can be mutated via the debugger.
+ bool immutable = FeedbackNexus::ImmutabilityBit::decode(number) &&
+ !isolate()->is_context_slot_not_assigned_unreliable();
+ return *zone()->New<GlobalAccessFeedback>(context, context_slot_index,
+ immutable, nexus.kind());
}
CHECK(IsPropertyCell(*feedback_value));
diff --git a/deps/v8/src/compiler/js-native-context-specialization.cc b/deps/v8/src/compiler/js-native-context-specialization.cc
index f5380467163..98fdd7439f1 100644
--- a/deps/v8/src/compiler/js-native-context-specialization.cc
+++ b/deps/v8/src/compiler/js-native-context-specialization.cc
@@ -1247,7 +1247,7 @@ Reduction JSNativeContextSpecialization::ReduceJSLoadGlobal(Node* node) {
value = effect =
graph()->NewNode(javascript()->LoadContextNoCell(
0, feedback.slot_index(), feedback.immutable()),
- script_context, effect);
+ script_context, effect, control);
}
ReplaceWithValue(node, value, effect, control);
return Replace(value);
@@ -2348,10 +2348,7 @@ Reduction JSNativeContextSpecialization::ReduceElementAccess(
// need to guard against changes to that below).
if ((IsHoleyOrDictionaryElementsKind(receiver_map.elements_kind()) ||
StoreModeCanGrow(feedback.keyed_mode().store_mode())) &&
-#if V8_ENABLE_WEBASSEMBLY
- !(receiver_map.IsAnyWasmObjectMap() &&
- access_info.is_proxy_on_prototype()) &&
-#endif // V8_ENABLE_WEBASSEMBLY
+ !access_info.is_proxy_on_prototype() &&
!receiver_map.PrototypesElementsDoNotHaveAccessorsOrThrow(
broker(), &prototype_maps)) {
return NoChange();
@@ -3593,22 +3590,24 @@ JSNativeContextSpecialization::BuildElementAccess(
ZoneVector<MapRef> const& receiver_maps =
access_info.lookup_start_object_maps();
- if (IsTypedArrayElementsKind(elements_kind) ||
- IsRabGsabTypedArrayElementsKind(elements_kind)) {
- return BuildElementAccessForTypedArrayOrRabGsabTypedArray(
- receiver, index, value, effect, control, context, elements_kind,
- keyed_mode);
- }
-
#if V8_ENABLE_WEBASSEMBLY
- if (receiver_maps.size() == 1 && receiver_maps.front().IsAnyWasmObjectMap() &&
- access_info.is_proxy_on_prototype()) {
+ if (access_info.is_proxy_on_prototype()) {
+ DCHECK_EQ(receiver_maps.size(), 1);
+ DCHECK(receiver_maps.front().IsAnyWasmObjectMap());
return BuildPrototypeProxyElementAccess(
receiver, index, value, effect, control, context, access_info,
language_mode, keyed_mode, if_exceptions, frame_state);
}
#endif // V8_ENABLE_WEBASSEMBLY
+ DCHECK_NE(elements_kind, NO_ELEMENTS);
+ if (IsTypedArrayElementsKind(elements_kind) ||
+ IsRabGsabTypedArrayElementsKind(elements_kind)) {
+ return BuildElementAccessForTypedArrayOrRabGsabTypedArray(
+ receiver, index, value, effect, control, context, elements_kind,
+ keyed_mode);
+ }
+
// Load the elements for the {receiver}.
Node* elements = effect = graph()->NewNode(
simplified()->LoadField(AccessBuilder::ForJSObjectElements()), receiver,
diff --git a/deps/v8/src/compiler/js-operator.cc b/deps/v8/src/compiler/js-operator.cc
index 2193fa595e8..cee43a75838 100644
--- a/deps/v8/src/compiler/js-operator.cc
+++ b/deps/v8/src/compiler/js-operator.cc
@@ -1369,7 +1369,7 @@ const Operator* JSOperatorBuilder::HasContextExtension(size_t depth) {
IrOpcode::kJSHasContextExtension, // opcode
Operator::kNoWrite | Operator::kNoThrow, // flags
"JSHasContextExtension", // name
- 0, 1, 0, 1, 1, 0, // counts
+ 0, 1, 1, 1, 1, 0, // counts
depth); // parameter
}
@@ -1380,7 +1380,7 @@ const Operator* JSOperatorBuilder::LoadContextNoCell(size_t depth, size_t index,
IrOpcode::kJSLoadContextNoCell, // opcode
Operator::kNoWrite | Operator::kNoThrow, // flags
"JSLoadContextNoCell", // name
- 0, 1, 0, 1, 1, 0, // counts
+ 0, 1, 1, 1, 1, 0, // counts
access); // parameter
}
diff --git a/deps/v8/src/compiler/js-typed-lowering.cc b/deps/v8/src/compiler/js-typed-lowering.cc
index 3b0f85776c3..6d3251cba09 100644
--- a/deps/v8/src/compiler/js-typed-lowering.cc
+++ b/deps/v8/src/compiler/js-typed-lowering.cc
@@ -1591,7 +1591,7 @@ Reduction JSTypedLowering::ReduceJSHasContextExtension(Node* node) {
Node* effect = NodeProperties::GetEffectInput(node);
TNode<Context> context =
TNode<Context>::UncheckedCast(NodeProperties::GetContextInput(node));
- Node* control = graph()->start();
+ Node* control = NodeProperties::GetControlInput(node);
JSGraphAssembler gasm(broker(), jsgraph_, jsgraph_->zone(),
BranchSemantics::kJS);
@@ -1626,7 +1626,7 @@ Reduction JSTypedLowering::ReduceJSLoadContextNoCell(Node* node) {
ContextAccess const& access = ContextAccessOf(node->op());
Node* effect = NodeProperties::GetEffectInput(node);
Node* context = NodeProperties::GetContextInput(node);
- Node* control = graph()->start();
+ Node* control = NodeProperties::GetControlInput(node);
for (size_t i = 0; i < access.depth(); ++i) {
context = effect = graph()->NewNode(
simplified()->LoadField(
@@ -1635,7 +1635,6 @@ Reduction JSTypedLowering::ReduceJSLoadContextNoCell(Node* node) {
}
node->ReplaceInput(0, context);
node->ReplaceInput(1, effect);
- node->AppendInput(jsgraph()->zone(), control);
NodeProperties::ChangeOp(
node,
simplified()->LoadField(AccessBuilder::ForContextSlot(access.index())));
@@ -1716,7 +1715,7 @@ Reduction JSTypedLowering::ReduceJSStoreContextNoCell(Node* node) {
ContextAccess const& access = ContextAccessOf(node->op());
Node* effect = NodeProperties::GetEffectInput(node);
Node* context = NodeProperties::GetContextInput(node);
- Node* control = graph()->start();
+ Node* control = NodeProperties::GetControlInput(node);
Node* value = NodeProperties::GetValueInput(node, 0);
for (size_t i = 0; i < access.depth(); ++i) {
context = effect = graph()->NewNode(
diff --git a/deps/v8/src/compiler/property-access-builder.cc b/deps/v8/src/compiler/property-access-builder.cc
index a3d2a8b6c61..1199895a0b0 100644
--- a/deps/v8/src/compiler/property-access-builder.cc
+++ b/deps/v8/src/compiler/property-access-builder.cc
@@ -216,20 +216,17 @@ std::optional<Node*> PropertyAccessBuilder::FoldLoadDictPrototypeConstant(
if (!value) return {};
for (MapRef map : access_info.lookup_start_object_maps()) {
- DirectHandle<Map> map_handle = map.object();
// Non-JSReceivers that passed AccessInfoFactory::ComputePropertyAccessInfo
// must have different lookup start map.
- if (!IsJSReceiverMap(*map_handle)) {
+ if (!map.IsJSReceiverMap()) {
// Perform the implicit ToObject for primitives here.
// Implemented according to ES6 section 7.3.2 GetV (V, P).
- Tagged<JSFunction> constructor =
- Map::GetConstructorFunction(
- *map_handle, *broker()->target_native_context().object())
- .value();
- // {constructor.initial_map()} is loaded/stored with acquire-release
- // semantics for constructors.
- map = MakeRefAssumeMemoryFence(broker(), constructor->initial_map());
- DCHECK(IsJSObjectMap(*map.object()));
+ OptionalJSFunctionRef constructor =
+ broker()->target_native_context().GetConstructorFunction(broker(),
+ map);
+ if (!constructor.has_value()) return {};
+ map = constructor->initial_map(broker());
+ DCHECK(map.IsJSObjectMap());
}
dependencies()->DependOnConstantInDictionaryPrototypeChain(
map, access_info.name(), value.value(), PropertyKind::kData);
diff --git a/deps/v8/src/compiler/turboshaft/decompression-optimization-phase.cc b/deps/v8/src/compiler/turboshaft/decompression-optimization-phase.cc
index 975e0fbfafb..c8222565ace 100644
--- a/deps/v8/src/compiler/turboshaft/decompression-optimization-phase.cc
+++ b/deps/v8/src/compiler/turboshaft/decompression-optimization-phase.cc
@@ -4,13 +4,26 @@
#include "src/compiler/turboshaft/decompression-optimization-phase.h"
+#include "src/compiler/linkage.h"
#include "src/compiler/turboshaft/decompression-optimization.h"
namespace v8::internal::compiler::turboshaft {
void DecompressionOptimizationPhase::Run(PipelineData* data, Zone* temp_zone) {
if (!COMPRESS_POINTERS_BOOL) return;
- RunDecompressionOptimization(data->graph(), temp_zone);
+#if V8_ENABLE_WEBASSEMBLY
+ bool is_wasm =
+ data->linkage() != nullptr
+ ? (data->linkage()
+ ->GetIncomingDescriptor()
+ ->IsAnyWasmFunctionCall() ||
+ data->linkage()->GetIncomingDescriptor()->IsWasmImportWrapper() ||
+ data->linkage()->GetIncomingDescriptor()->IsWasmCapiFunction())
+ : data->pipeline_kind() == TurboshaftPipelineKind::kWasm;
+#else
+ bool is_wasm = false;
+#endif
+ RunDecompressionOptimization(data->graph(), temp_zone, is_wasm);
}
} // namespace v8::internal::compiler::turboshaft
diff --git a/deps/v8/src/compiler/turboshaft/decompression-optimization.cc b/deps/v8/src/compiler/turboshaft/decompression-optimization.cc
index fc90c911ef8..5bcd82e749a 100644
--- a/deps/v8/src/compiler/turboshaft/decompression-optimization.cc
+++ b/deps/v8/src/compiler/turboshaft/decompression-optimization.cc
@@ -23,14 +23,16 @@ namespace {
struct DecompressionAnalyzer {
const Graph& graph;
Zone* phase_zone;
+ bool is_wasm;
// We use `uint8_t` instead of `bool` here to avoid the bitvector optimization
// of std::vector.
FixedOpIndexSidetable<uint8_t> needs_decompression;
ZoneVector<OpIndex> candidates;
- DecompressionAnalyzer(const Graph& graph, Zone* phase_zone)
+ DecompressionAnalyzer(const Graph& graph, Zone* phase_zone, bool is_wasm)
: graph(graph),
phase_zone(phase_zone),
+ is_wasm(is_wasm),
needs_decompression(graph.op_id_count(), phase_zone, &graph),
candidates(phase_zone) {
candidates.reserve(graph.op_id_count() / 8);
@@ -73,6 +75,23 @@ struct DecompressionAnalyzer {
}
void ProcessOperation(const Operation& op);
void MarkAddressingBase(OpIndex base_idx);
+
+#ifdef V8_ENABLE_SANDBOX
+ const CallOp* TryGetWasmCall(OpIndex maybe_didnt_throw) const {
+#if V8_ENABLE_WEBASSEMBLY
+ if (const DidntThrowOp* didnt_throw =
+ graph.Get(maybe_didnt_throw).TryCast<DidntThrowOp>()) {
+ if (const CallOp* call =
+ graph.Get(didnt_throw->throwing_operation()).TryCast<CallOp>()) {
+ if (call->descriptor->descriptor->IsAnyWasmFunctionCall()) {
+ return call;
+ }
+ }
+ }
+#endif
+ return nullptr;
+ }
+#endif // V8_ENABLE_SANDBOX
};
void DecompressionAnalyzer::ProcessOperation(const Operation& op) {
@@ -91,6 +110,10 @@ void DecompressionAnalyzer::ProcessOperation(const Operation& op) {
case Opcode::kFrameState:
// The deopt code knows how to handle compressed inputs.
break;
+ case Opcode::kMakeTuple:
+ // MakeTupleOp is not a real user, so it shouldn't mark its inputs as
+ // needing decompression.
+ break;
case Opcode::kPhi: {
// Replicate the phi's state for its inputs.
auto& phi = op.Cast<PhiOp>();
@@ -168,6 +191,47 @@ void DecompressionAnalyzer::ProcessOperation(const Operation& op) {
}
break;
}
+#ifdef V8_ENABLE_SANDBOX
+ case Opcode::kParameter: {
+ if (!is_wasm) break;
+ const ParameterOp& param = op.Cast<ParameterOp>();
+ // Parameter 0 is the Wasm instance data in trusted space, which uses a
+ // different cage base and must not be decompressed.
+ if (param.rep == RegisterRepresentation::Tagged() &&
+ param.parameter_index > 0 && !NeedsDecompression(op)) {
+ candidates.push_back(graph.Index(op));
+ }
+ break;
+ }
+ case Opcode::kDidntThrow: {
+ if (TryGetWasmCall(graph.Index(op)) != nullptr) {
+ if (op.outputs_rep().size() == 1 &&
+ op.outputs_rep()[0] == RegisterRepresentation::Tagged() &&
+ !NeedsDecompression(op)) {
+ candidates.push_back(graph.Index(op));
+ }
+ break;
+ }
+ for (OpIndex input : op.inputs()) {
+ MarkAsNeedsDecompression(input);
+ }
+ break;
+ }
+ case Opcode::kProjection: {
+ const ProjectionOp& proj = op.Cast<ProjectionOp>();
+ if (TryGetWasmCall(proj.input()) != nullptr) {
+ if (proj.rep == RegisterRepresentation::Tagged() &&
+ !NeedsDecompression(op)) {
+ candidates.push_back(graph.Index(op));
+ }
+ break;
+ }
+ for (OpIndex input : op.inputs()) {
+ MarkAsNeedsDecompression(input);
+ }
+ break;
+ }
+#endif // V8_ENABLE_SANDBOX
default:
for (OpIndex input : op.inputs()) {
MarkAsNeedsDecompression(input);
@@ -208,8 +272,9 @@ void DecompressionAnalyzer::MarkAddressingBase(OpIndex base_idx) {
// Instead of using `CopyingPhase`, we directly mutate the operations after
// the analysis. Doing it in-place is possible because we only modify operation
// options.
-void RunDecompressionOptimization(Graph& graph, Zone* phase_zone) {
- DecompressionAnalyzer analyzer(graph, phase_zone);
+void RunDecompressionOptimization(Graph& graph, Zone* phase_zone,
+ bool is_wasm) {
+ DecompressionAnalyzer analyzer(graph, phase_zone, is_wasm);
analyzer.Run();
for (OpIndex op_idx : analyzer.candidates) {
Operation& op = graph.Get(op_idx);
@@ -249,6 +314,36 @@ void RunDecompressionOptimization(Graph& graph, Zone* phase_zone) {
}
break;
}
+#ifdef V8_ENABLE_SANDBOX
+ case Opcode::kParameter: {
+ DCHECK(is_wasm);
+ auto& param = op.Cast<ParameterOp>();
+ DCHECK_EQ(param.rep, any_of(RegisterRepresentation::Tagged(),
+ RegisterRepresentation::Compressed()));
+ param.rep = RegisterRepresentation::Compressed();
+ break;
+ }
+ case Opcode::kDidntThrow: {
+ auto& didnt_throw = op.Cast<DidntThrowOp>();
+ DCHECK_EQ(didnt_throw.outputs_rep().size(), 1);
+ DCHECK_EQ(didnt_throw.outputs_rep()[0],
+ any_of(RegisterRepresentation::Tagged(),
+ RegisterRepresentation::Compressed()));
+ static constexpr RegisterRepresentation kCompressedRep =
+ RegisterRepresentation::Compressed();
+ static constexpr base::Vector<const RegisterRepresentation>
+ kCompressedReps(&kCompressedRep, 1);
+ didnt_throw.results_rep = &kCompressedReps;
+ break;
+ }
+ case Opcode::kProjection: {
+ auto& proj = op.Cast<ProjectionOp>();
+ DCHECK_EQ(proj.rep, any_of(RegisterRepresentation::Tagged(),
+ RegisterRepresentation::Compressed()));
+ proj.rep = RegisterRepresentation::Compressed();
+ break;
+ }
+#endif // V8_ENABLE_SANDBOX
default:
break;
}
diff --git a/deps/v8/src/compiler/turboshaft/decompression-optimization.h b/deps/v8/src/compiler/turboshaft/decompression-optimization.h
index 2974b15f7d6..f36b852fbd7 100644
--- a/deps/v8/src/compiler/turboshaft/decompression-optimization.h
+++ b/deps/v8/src/compiler/turboshaft/decompression-optimization.h
@@ -18,7 +18,8 @@ class Graph;
// late in the pipeline, all the preceding phases can safely assume that
// everything is decompressed and do not need to worry about the distinction
// between compressed and uncompressed pointers.
-void RunDecompressionOptimization(Graph& graph, Zone* phase_zone);
+void RunDecompressionOptimization(Graph& graph, Zone* phase_zone,
+ bool is_wasm = false);
} // namespace v8::internal::compiler::turboshaft
diff --git a/deps/v8/src/compiler/turboshaft/pipelines.h b/deps/v8/src/compiler/turboshaft/pipelines.h
index 7e8f7995ca8..8fb09741a1c 100644
--- a/deps/v8/src/compiler/turboshaft/pipelines.h
+++ b/deps/v8/src/compiler/turboshaft/pipelines.h
@@ -406,12 +406,9 @@ class V8_EXPORT_PRIVATE Pipeline {
RUN_MAYBE_ABORT(FrameElisionPhase);
- // TODO(mtrofin): move this off to the register allocator.
- bool generate_frame_at_start =
- data_->sequence()->instruction_blocks().front()->must_construct_frame();
// Optimimize jumps.
if (v8_flags.turbo_jt) {
- RUN_MAYBE_ABORT(JumpThreadingPhase, generate_frame_at_start);
+ RUN_MAYBE_ABORT(JumpThreadingPhase);
}
EndPhaseKind();
diff --git a/deps/v8/src/compiler/turboshaft/register-allocation-phase.h b/deps/v8/src/compiler/turboshaft/register-allocation-phase.h
index 09c7283dd0d..7074bd1f3f6 100644
--- a/deps/v8/src/compiler/turboshaft/register-allocation-phase.h
+++ b/deps/v8/src/compiler/turboshaft/register-allocation-phase.h
@@ -5,6 +5,7 @@
#ifndef V8_COMPILER_TURBOSHAFT_REGISTER_ALLOCATION_PHASE_H_
#define V8_COMPILER_TURBOSHAFT_REGISTER_ALLOCATION_PHASE_H_
+#include "src/common/synchronization-point-support.h"
#ifdef BUILTIN_BLOCK_POSITION
#include "src/compiler/backend/block-position.h"
#endif
@@ -200,10 +201,10 @@ struct JumpThreadingPhase {
DECL_TURBOSHAFT_PHASE_CONSTANTS_WITH_LEGACY_NAME(JumpThreading)
static constexpr bool kOutputIsTraceableGraph = false;
- void Run(PipelineData* data, Zone* temp_zone, bool frame_at_start) {
+ void Run(PipelineData* data, Zone* temp_zone) {
ZoneVector<RpoNumber> result(temp_zone);
- if (JumpThreading::ComputeForwarding(temp_zone, &result, data->sequence(),
- frame_at_start)) {
+ if (JumpThreading::ComputeForwarding(temp_zone, &result,
+ data->sequence())) {
JumpThreading::ApplyForwarding(temp_zone, result, data->sequence());
}
}
@@ -220,6 +221,7 @@ struct AssembleCodePhase {
if (data->broker() != nullptr) {
code_generator->PrepareCodeOnBackground(data->broker()->local_isolate());
}
+ SYNCHRONIZATION_POINT_TEST_ONLY("TurboshaftAfterAssembleCode");
}
};
diff --git a/deps/v8/src/debug/debug-scopes.cc b/deps/v8/src/debug/debug-scopes.cc
index 2523dca7f4f..365073f1f27 100644
--- a/deps/v8/src/debug/debug-scopes.cc
+++ b/deps/v8/src/debug/debug-scopes.cc
@@ -1101,11 +1101,17 @@ bool ScopeIterator::SetLocalVariableValue(DirectHandle<String> variable_name,
// don't match (https://crbug.com/753338).
// Skip the write if the context's ScopeInfo doesn't know anything
// about this variable.
- if (context_->scope_info()->ContextSlotIndex(*variable_name) !=
- index) {
+ VariableLookupResult lookup_result;
+ if (context_->scope_info()->ContextSlotIndex(
+ *variable_name, &lookup_result) != index) {
return false;
}
Context::Set(context_, index, new_value, isolate_);
+ if (lookup_result.maybe_assigned_flag == kNotAssigned) {
+ // Mutating a kNotAssigned context slot via the debugger invalidates
+ // compiler assumptions that kNotAssigned slots are immutable.
+ isolate_->MarkContextSlotNotAssignedIsUnreliable();
+ }
return true;
case VariableLocation::MODULE:
@@ -1138,9 +1144,16 @@ bool ScopeIterator::SetContextExtensionValue(DirectHandle<String> variable_name,
bool ScopeIterator::SetContextVariableValue(DirectHandle<String> variable_name,
DirectHandle<Object> new_value) {
- int slot_index = context_->scope_info()->ContextSlotIndex(*variable_name);
+ VariableLookupResult lookup_result;
+ int slot_index =
+ context_->scope_info()->ContextSlotIndex(*variable_name, &lookup_result);
if (slot_index < 0) return false;
Context::Set(context_, slot_index, new_value, isolate_);
+ if (lookup_result.maybe_assigned_flag == kNotAssigned) {
+ // Mutating a kNotAssigned context slot via the debugger invalidates
+ // compiler assumptions that kNotAssigned slots are immutable.
+ isolate_->MarkContextSlotNotAssignedIsUnreliable();
+ }
return true;
}
@@ -1174,6 +1187,11 @@ bool ScopeIterator::SetScriptVariableValue(DirectHandle<String> variable_name,
DirectHandle<Context> script_context(
script_contexts->get(lookup_result.context_index), isolate_);
Context::Set(script_context, lookup_result.slot_index, new_value, isolate_);
+ if (lookup_result.maybe_assigned_flag == kNotAssigned) {
+ // Mutating a kNotAssigned context slot via the debugger invalidates
+ // compiler assumptions that kNotAssigned slots are immutable.
+ isolate_->MarkContextSlotNotAssignedIsUnreliable();
+ }
return true;
}
diff --git a/deps/v8/src/execution/frames.cc b/deps/v8/src/execution/frames.cc
index 6976158cf26..29a410eb63a 100644
--- a/deps/v8/src/execution/frames.cc
+++ b/deps/v8/src/execution/frames.cc
@@ -472,7 +472,8 @@ std::optional<bool> IsInterpreterFramePc(Isolate* isolate, Address pc,
return false;
}
std::optional<Address> istream_address =
- ThreadIsolation::TryLookupStartOfJitAllocationAt(pc);
+ ThreadIsolation::TryLookupStartOfJitAllocationAt(
+ pc, ThreadIsolation::JitAllocationType::kInstructionStream);
if (!istream_address.has_value()) {
return {};
}
@@ -1697,6 +1698,44 @@ void VisitSpillSlots(Isolate* isolate, RootVisitor* v,
}
}
+#ifdef V8_ENABLE_WEBASSEMBLY
+void VisitWasmParameterSlot(RootVisitor* v, FullObjectSlot param_slot) {
+ DisallowGarbageCollection no_gc;
+#if defined(V8_COMPRESS_POINTERS) && defined(V8_ENABLE_SANDBOX)
+ // Incoming Wasm parameter slots on the stack (or spilled by
+ // WasmLiftoffSetupFrame / GenericWasmToJSWrapper before parameter processing)
+ // may contain arbitrary upper 32 bits if an attacker redirected an indirect
+ // call or passed an untagged value. Unconditionally treat the lower 32 bits
+ // as a compressed tagged value and write back the sanitized 64-bit value.
+ Tagged_t compressed_value = static_cast<Tagged_t>(*param_slot.location());
+ if (HAS_SMI_TAG(compressed_value)) {
+ *param_slot.location() = static_cast<Address>(compressed_value);
+ return;
+ }
+ Address decompressed =
+ V8HeapCompressionScheme::DecompressTagged(compressed_value);
+ FullObjectSlot local_slot(&decompressed);
+ {
+ DisableGCMole no_gcmole;
+ v->VisitRootPointer(Root::kStackRoots, nullptr, local_slot);
+ }
+ *param_slot.location() = decompressed;
+#else
+ {
+ DisableGCMole no_gcmole;
+ v->VisitRootPointer(Root::kStackRoots, nullptr, param_slot);
+ }
+#endif
+}
+
+void VisitWasmParameterSlots(RootVisitor* v, FullObjectSlot start,
+ FullObjectSlot end) {
+ for (FullObjectSlot slot = start; slot < end; ++slot) {
+ VisitWasmParameterSlot(v, slot);
+ }
+}
+#endif // V8_ENABLE_WEBASSEMBLY
+
SafepointEntry& GetSafepointEntryFromCodeCache(
Isolate* isolate, Address inner_pointer,
InnerPointerToCodeCache::Entry* entry) {
@@ -1962,8 +2001,7 @@ void WasmFrame::Iterate(RootVisitor* v) const {
FullObjectSlot tagged_parameter_limit =
tagged_parameter_base + wasm_code->num_tagged_parameter_slots();
- v->VisitRootPointers(Root::kStackRoots, nullptr, tagged_parameter_base,
- tagged_parameter_limit);
+ VisitWasmParameterSlots(v, tagged_parameter_base, tagged_parameter_limit);
}
// Visit the instance object.
@@ -2044,7 +2082,7 @@ void TypedFrame::IterateParamsOfGenericWasmToJSWrapper(RootVisitor* v) const {
FullObjectSlot param_start(fp() +
param_start_offset * kSystemPointerSize);
FullObjectSlot tagged_slot = param_start + slot_offset;
- VisitSpillSlot(isolate(), v, tagged_slot);
+ VisitWasmParameterSlot(v, tagged_slot);
} else {
// Caller frame slots have negative indices and start at -1. Flip it
// back to a positive offset (to be added to the frame's FP to find the
@@ -2071,7 +2109,7 @@ void TypedFrame::IterateParamsOfGenericWasmToJSWrapper(RootVisitor* v) const {
FullObjectSlot param_start(fp() +
param_start_offset * kSystemPointerSize);
FullObjectSlot tagged_slot = param_start + slot_offset;
- VisitSpillSlot(isolate(), v, tagged_slot);
+ VisitWasmParameterSlot(v, tagged_slot);
}
}
}
@@ -4112,7 +4150,7 @@ void WasmLiftoffSetupFrame::Iterate(RootVisitor* v) const {
fp() + WasmLiftoffSetupFrameConstants::kParameterSpillsOffset
[num_int_params_in_registers + i]);
- v->VisitRootPointer(Root::kStackRoots, "register parameter", spill_slot);
+ VisitWasmParameterSlot(v, spill_slot);
}
// Next we scan the slots of stack parameters.
@@ -4131,8 +4169,7 @@ void WasmLiftoffSetupFrame::Iterate(RootVisitor* v) const {
FullObjectSlot tagged_parameter_limit =
tagged_parameter_base + num_tagged_stack_slots;
- v->VisitRootPointers(Root::kStackRoots, "stack parameter",
- tagged_parameter_base, tagged_parameter_limit);
+ VisitWasmParameterSlots(v, tagged_parameter_base, tagged_parameter_limit);
}
}
#endif // V8_ENABLE_WEBASSEMBLY
diff --git a/deps/v8/src/execution/isolate.cc b/deps/v8/src/execution/isolate.cc
index 536ba8a1d6a..5a497723603 100644
--- a/deps/v8/src/execution/isolate.cc
+++ b/deps/v8/src/execution/isolate.cc
@@ -8730,5 +8730,15 @@ void Isolate::PrintNumberStringCacheStats(const char* comment,
PrintF("\n");
}
+void Isolate::MarkContextSlotNotAssignedIsUnreliable() {
+ if (is_context_slot_not_assigned_unreliable()) return;
+ context_slot_not_assigned_is_unreliable_.store(true,
+ std::memory_order_relaxed);
+ // Abort any in-flight concurrent compilations that may have relied on
+ // kNotAssigned and deoptimize existing optimized code.
+ AbortConcurrentOptimization(BlockingBehavior::kBlock);
+ Deoptimizer::DeoptimizeAll(this);
+}
+
} // namespace internal
} // namespace v8
diff --git a/deps/v8/src/execution/isolate.h b/deps/v8/src/execution/isolate.h
index bb742ca905a..2c961c48c2f 100644
--- a/deps/v8/src/execution/isolate.h
+++ b/deps/v8/src/execution/isolate.h
@@ -2471,6 +2471,16 @@ class V8_EXPORT_PRIVATE Isolate final : private HiddenFactory {
memory_saver_mode_enabled_ = memory_saver_mode_enabled;
}
+ // Returns true if the debugger has mutated a context slot marked as
+ // kNotAssigned in ScopeInfo, making the kNotAssigned flag unreliable for
+ // constant-folding optimizations in this isolate.
+ bool is_context_slot_not_assigned_unreliable() const {
+ return context_slot_not_assigned_is_unreliable_.load(
+ std::memory_order_relaxed);
+ }
+
+ void MarkContextSlotNotAssignedIsUnreliable();
+
void ReportExceptionFunctionCallback(
DirectHandle<JSReceiver> receiver,
DirectHandle<FunctionTemplateInfo> function,
@@ -2695,6 +2705,7 @@ class V8_EXPORT_PRIVATE Isolate final : private HiddenFactory {
std::atomic<bool> battery_saver_mode_enabled_ = false;
std::atomic<bool> memory_saver_mode_enabled_ = false;
+ std::atomic<bool> context_slot_not_assigned_is_unreliable_ = false;
// Helper function for RunHostImportModuleDynamicallyCallback.
// Unpacks import attributes, if present, from the second argument to dynamic
diff --git a/deps/v8/src/flags/feature-flags.h b/deps/v8/src/flags/feature-flags.h
index 0f933cd05fb..c1e1affd328 100644
--- a/deps/v8/src/flags/feature-flags.h
+++ b/deps/v8/src/flags/feature-flags.h
@@ -124,11 +124,6 @@
INTERNAL_FEATURE(always_specialize_for_script_context, \
"always specialize for script contexts in optimized code") \
\
- /* V8 side owner: leszeks */ \
- INTERNAL_FEATURE( \
- code_cache_source_hash_sha256, \
- "hashing code cache source string with SHA256 instead of string length") \
- \
/* Reference-Typed Strings Proposal. */ \
/* https://github.com/WebAssembly/stringref */ \
/* V8 side owner: jkummerow */ \
@@ -238,6 +233,11 @@
\
INTERNAL_FEATURE(homomorphic_ic, \
"Homomorphic IC state for same-handler highly polymorphic " \
- "ICs")
+ "ICs") \
+ \
+ /* V8 side owner: leszeks */ \
+ INTERNAL_FEATURE( \
+ code_cache_source_hash_sha256, \
+ "hashing code cache source string with SHA256 instead of string length")
#endif // V8_FLAGS_FEATURE_FLAGS_H_
diff --git a/deps/v8/src/heap/heap.cc b/deps/v8/src/heap/heap.cc
index 541c4317fa8..5d4350a6dce 100644
--- a/deps/v8/src/heap/heap.cc
+++ b/deps/v8/src/heap/heap.cc
@@ -7417,8 +7417,8 @@ bool Heap::GcSafeInstructionStreamContains(
std::optional<Tagged<InstructionStream>>
Heap::GcSafeTryFindInstructionStreamForInnerPointer(Address inner_pointer) {
- std::optional<Address> start =
- ThreadIsolation::StartOfJitAllocationAt(inner_pointer);
+ std::optional<Address> start = ThreadIsolation::StartOfJitAllocationAt(
+ inner_pointer, ThreadIsolation::JitAllocationType::kInstructionStream);
if (start.has_value()) {
return UncheckedCast<InstructionStream>(HeapObject::FromAddress(*start));
}
diff --git a/deps/v8/src/maglev/maglev-graph-builder.cc b/deps/v8/src/maglev/maglev-graph-builder.cc
index 18149e37fa6..427ba013e31 100644
--- a/deps/v8/src/maglev/maglev-graph-builder.cc
+++ b/deps/v8/src/maglev/maglev-graph-builder.cc
@@ -4189,20 +4189,17 @@ MaglevGraphBuilder::TryFoldLoadDictPrototypeConstant(
if (!constant.has_value()) return {};
for (compiler::MapRef map : access_info.lookup_start_object_maps()) {
- DirectHandle<Map> map_handle = map.object();
// Non-JSReceivers that passed AccessInfoFactory::ComputePropertyAccessInfo
// must have different lookup start map.
- if (!IsJSReceiverMap(*map_handle)) {
+ if (!map.IsJSReceiverMap()) {
// Perform the implicit ToObject for primitives here.
// Implemented according to ES6 section 7.3.2 GetV (V, P).
- Tagged<JSFunction> constructor =
- Map::GetConstructorFunction(
- *map_handle, *broker()->target_native_context().object())
- .value();
- // {constructor.initial_map()} is loaded/stored with acquire-release
- // semantics for constructors.
- map = MakeRefAssumeMemoryFence(broker(), constructor->initial_map());
- DCHECK(IsJSObjectMap(*map.object()));
+ compiler::OptionalJSFunctionRef constructor =
+ broker()->target_native_context().GetConstructorFunction(broker(),
+ map);
+ if (!constructor.has_value()) return {};
+ map = constructor->initial_map(broker());
+ DCHECK(map.IsJSObjectMap());
}
broker()->dependencies()->DependOnConstantInDictionaryPrototypeChain(
map, access_info.name(), constant.value(), PropertyKind::kData);
@@ -5641,13 +5638,10 @@ MaybeReduceResult MaglevGraphBuilder::TryBuildElementAccessOnJSArrayOrJSObject(
ValueNode* object, ValueNode* index_object,
const compiler::ElementAccessInfo& access_info,
compiler::KeyedAccessMode const& keyed_mode) {
+ DCHECK(!access_info.is_proxy_on_prototype());
if (!IsFastElementsKind(access_info.elements_kind())) {
return {};
}
- if (access_info.is_proxy_on_prototype()) {
- // TODO(jkummerow): Implement support.
- return {};
- }
switch (keyed_mode.access_mode()) {
case compiler::AccessMode::kLoad:
return BuildElementLoadOnJSArrayOrJSObject(
@@ -5710,6 +5704,13 @@ MaybeReduceResult MaglevGraphBuilder::TryBuildElementAccess(
return {};
}
+ for (const compiler::ElementAccessInfo& access_info : access_infos) {
+ if (access_info.is_proxy_on_prototype()) {
+ // TODO(jkummerow): Implement support.
+ return {};
+ }
+ }
+
// TODO(leszeks): This is copied without changes from TurboFan's native
// context specialization. We should figure out a way to share this code.
//
diff --git a/deps/v8/src/maglev/maglev-reducer-inl.h b/deps/v8/src/maglev/maglev-reducer-inl.h
index 12d7cd19560..f8ba24fa2d9 100644
--- a/deps/v8/src/maglev/maglev-reducer-inl.h
+++ b/deps/v8/src/maglev/maglev-reducer-inl.h
@@ -740,6 +740,10 @@ MaybeAssignedFlag MaglevReducer<BaseT>::GetContextMaybeAssigned(
}
int var_index = index - header_length;
*mode = scope_info.ContextLocalMode(var_index);
+ // The debugger may have mutated a kNotAssigned context slot at runtime.
+ if (broker()->isolate()->is_context_slot_not_assigned_unreliable()) {
+ return kMaybeAssigned;
+ }
return scope_info.ContextLocalMaybeAssignedFlag(var_index);
}
diff --git a/deps/v8/src/maglev/maglev-truncation.h b/deps/v8/src/maglev/maglev-truncation.h
index a13adb725f8..47c7c01cdd7 100644
--- a/deps/v8/src/maglev/maglev-truncation.h
+++ b/deps/v8/src/maglev/maglev-truncation.h
@@ -548,9 +548,8 @@ class TruncationProcessor {
node->OverwriteWith<Int32Add>();
}
- template <typename NodeT>
-
- void ProcessFloat64BinaryOp(ValueNode* node) {
+ template <typename NodeT, typename InputNodeT>
+ void ProcessFloat64BinaryOp(InputNodeT* node) {
if (!node->can_truncate_to_int32()) return;
switch (NonInt32InputCount(node)) {
@@ -560,14 +559,20 @@ class TruncationProcessor {
TRACE_TRUNCATION("truncating "
<< PrintNodeBrief{node} << " to "
<< OpcodeToString(Node::opcode_of<NodeT>));
- node->OverwriteWith<NodeT>();
+ node->template OverwriteWith<NodeT>();
break;
case 1:
// Convert nodes back to float64 and don't truncate.
ConvertInputsToFloat64(node);
- break;
+ [[fallthrough]];
case 2:
- // Don't truncate.
+ // Don't truncate. Either a direct input (case 1) or a transitive
+ // descendant of a Float64 input that hit case 1 (case 2) may have been
+ // truncated to Int32, shifting its value by multiples of 2^32 and
+ // invalidating the pre-truncation range cached on this node during
+ // graph building. Since at least one input is not Int32, the new static
+ // range would be wider than Int32 anyway, so reset it.
+ node->set_range(Range::All());
break;
default:
UNREACHABLE();
diff --git a/deps/v8/src/objects/string.cc b/deps/v8/src/objects/string.cc
index 7302ac66e2e..18cd65ff2c5 100644
--- a/deps/v8/src/objects/string.cc
+++ b/deps/v8/src/objects/string.cc
@@ -29,6 +29,7 @@
#include "src/objects/string-comparator.h"
#include "src/objects/string-inl.h"
#include "src/objects/tagged.h"
+#include "src/sandbox/check.h"
#include "src/strings/char-predicates.h"
#include "src/strings/string-builder-inl.h"
#include "src/strings/string-hasher.h"
@@ -733,6 +734,7 @@ std::unique_ptr<char[]> String::ToCString(uint32_t offset, uint32_t length,
size_t* length_return) {
DCHECK_LE(length, this->length());
DCHECK_LE(offset, this->length() - length);
+ SBXCHECK_LE(length, String::kMaxLength);
StringCharacterStream stream(this, offset);
@@ -764,6 +766,7 @@ std::unique_ptr<char[]> String::ToCString(size_t* length_return) {
std::string String::ToStdString() {
uint32_t length = this->length();
+ SBXCHECK_LE(length, String::kMaxLength);
StringCharacterStream stream(this, 0);
size_t utf8_bytes = stream.CountUtf8Bytes(length);
diff --git a/deps/v8/src/runtime/runtime-regexp.cc b/deps/v8/src/runtime/runtime-regexp.cc
index ec17453cda4..41060a34fa9 100644
--- a/deps/v8/src/runtime/runtime-regexp.cc
+++ b/deps/v8/src/runtime/runtime-regexp.cc
@@ -832,6 +832,7 @@ StringReplaceGlobalRegExpWithEmptyString(
int delta = allocated_string_size - string_size;
answer->set_length(position);
+ answer->ClearPadding();
if (delta == 0) return *answer;
Address end_of_string = answer->address() + string_size;
diff --git a/deps/v8/src/runtime/runtime-scopes.cc b/deps/v8/src/runtime/runtime-scopes.cc
index 8327e0e7b64..1a3b14276b2 100644
--- a/deps/v8/src/runtime/runtime-scopes.cc
+++ b/deps/v8/src/runtime/runtime-scopes.cc
@@ -429,6 +429,14 @@ Tagged<Object> DeclareEvalHelper(Isolate* isolate, Handle<String> name,
if (index != Context::kNotFound) {
DCHECK(holder.is_identical_to(context));
Context::Set(context, index, value, isolate);
+ Tagged<ScopeInfo> scope_info = context->scope_info();
+ int var_index = index - scope_info->ContextHeaderLength();
+ if (scope_info->ContextLocalMaybeAssignedFlag(var_index) ==
+ kNotAssigned) {
+ // Debug-evaluate can overwrite a context slot that was statically
+ // marked kNotAssigned when the enclosing scope was parsed.
+ isolate->MarkContextSlotNotAssignedIsUnreliable();
+ }
return ReadOnlyRoots(isolate).undefined_value();
}
@@ -950,6 +958,14 @@ MaybeDirectHandle<Object> StoreLookupSlot(
}
if ((attributes & READ_ONLY) == 0) {
Context::Set(holder_context, index, value, isolate);
+ Tagged<ScopeInfo> scope_info = holder_context->scope_info();
+ int var_index = index - scope_info->ContextHeaderLength();
+ if (scope_info->ContextLocalMaybeAssignedFlag(var_index) ==
+ kNotAssigned) {
+ // Debug-evaluate can overwrite a context slot that was statically
+ // marked kNotAssigned when the enclosing scope was parsed.
+ isolate->MarkContextSlotNotAssignedIsUnreliable();
+ }
} else if (!is_sloppy_function_name || is_strict(language_mode)) {
THROW_NEW_ERROR(isolate, NewTypeError(MessageTemplate::kConstAssign));
}
diff --git a/deps/v8/src/runtime/runtime-wasm.cc b/deps/v8/src/runtime/runtime-wasm.cc
index bf7259eb88d..6b50c1e1f64 100644
--- a/deps/v8/src/runtime/runtime-wasm.cc
+++ b/deps/v8/src/runtime/runtime-wasm.cc
@@ -862,7 +862,8 @@ RUNTIME_FUNCTION(Runtime_WasmFunctionTableGet) {
Cast<WasmTableObject>(trusted_instance_data->tables()->get(table_index)),
isolate);
// We only use the runtime call for lazily initialized function references.
- DCHECK(table->unsafe_type().ref_type_kind() == wasm::RefTypeKind::kFunction);
+ DCHECK(trusted_instance_data->dispatch_table(table_index) !=
+ *isolate->factory()->empty_wasm_dispatch_table());
if (!table->is_in_bounds(entry_index)) {
return ThrowWasmError(isolate, MessageTemplate::kWasmTrapTableOutOfBounds);
@@ -884,7 +885,8 @@ RUNTIME_FUNCTION(Runtime_WasmFunctionTableSet) {
Cast<WasmTableObject>(trusted_instance_data->tables()->get(table_index)),
isolate);
// We only use the runtime call for lazily initialized function references.
- DCHECK(table->unsafe_type().ref_type_kind() == wasm::RefTypeKind::kFunction);
+ DCHECK(trusted_instance_data->dispatch_table(table_index) !=
+ *isolate->factory()->empty_wasm_dispatch_table());
if (!table->is_in_bounds(entry_index)) {
return ThrowWasmError(isolate, MessageTemplate::kWasmTrapTableOutOfBounds);
diff --git a/deps/v8/src/sandbox/js-dispatch-table-inl.h b/deps/v8/src/sandbox/js-dispatch-table-inl.h
index 00295fa38cb..8755de05faf 100644
--- a/deps/v8/src/sandbox/js-dispatch-table-inl.h
+++ b/deps/v8/src/sandbox/js-dispatch-table-inl.h
@@ -12,6 +12,7 @@
#include "src/builtins/builtins-inl.h"
#include "src/common/code-memory-access-inl.h"
+#include "src/common/synchronization-point-support.h"
#include "src/execution/isolate.h"
#include "src/objects/objects-inl.h"
#include "src/sandbox/external-entity-table-inl.h"
@@ -27,6 +28,7 @@ namespace internal {
void JSDispatchEntry::MakeJSDispatchEntry(Address object, Address entrypoint,
uint16_t parameter_count,
bool mark_as_alive) {
+ DCHECK(IsFreelistEntry());
DCHECK_NE(entrypoint, kNullAddress);
DCHECK_EQ(object & kHeapObjectTag, 0);
#if V8_TARGET_ARCH_X64 && V8_SUPPORT_LA57
@@ -46,29 +48,51 @@ void JSDispatchEntry::MakeJSDispatchEntry(Address object, Address entrypoint,
Address payload = ((object - kObjectPointerOffset) << kObjectPointerShift) |
(parameter_count & kParameterCountMask);
#endif // !(V8_TARGET_ARCH_X64 && V8_SUPPORT_LA57)
-#ifdef V8_TARGET_ARCH_32_BIT
- parameter_count_.store(parameter_count, std::memory_order_relaxed);
- next_free_entry_.store(0, std::memory_order_relaxed);
-#endif // V8_TARGET_ARCH_32_BIT
DCHECK(!(payload & kMarkingBit));
if (mark_as_alive) payload |= kMarkingBit;
- entrypoint_.store(entrypoint, std::memory_order_relaxed);
+ // Updates to code_object_/encoded_word_ must use release stores (paired with
+ // acquire loads in GetCodePointer()) so that background threads (such as
+ // concurrent marking) that read the Code pointer do not observe an
+ // uninitialized Code object on the heap.
+ //
+ // In addition, the parameter count (in encoded_word_ on 64-bit, or
+ // parameter_count_ on 32-bit) must be written before the release store to
+ // entrypoint_ (on 64-bit) / next_free_entry_ (on 32-bit) transitions the
+ // entry out of the freelist state. Because that final store uses release
+ // ordering (paired with the acquire load in
+ // IsFreelistOrUninitializedEntry()), preceding stores to the parameter count
+ // (even when relaxed) cannot be reordered past it, preventing concurrent
+ // readers in GetParameterCount() from observing a non-free entry with a stale
+ // parameter count.
#if V8_TARGET_ARCH_X64 && V8_SUPPORT_LA57
encoded_word_.store(payload, std::memory_order_relaxed);
code_object_.store(object | kHeapObjectTag, std::memory_order_release);
#else
encoded_word_.store(payload, std::memory_order_release);
#endif // V8_TARGET_ARCH_X64 && V8_SUPPORT_LA57
- DCHECK(!IsFreelistEntry());
+#ifdef V8_TARGET_ARCH_32_BIT
+ parameter_count_.store(parameter_count, std::memory_order_relaxed);
+#endif // V8_TARGET_ARCH_32_BIT
+ SYNCHRONIZATION_POINT_TEST_ONLY("JSDispatchEntryMake");
+#ifdef V8_TARGET_ARCH_32_BIT
+ entrypoint_.store(entrypoint, std::memory_order_relaxed);
+ next_free_entry_.store(0, std::memory_order_release);
+#else
+ entrypoint_.store(entrypoint, std::memory_order_release);
+#endif // V8_TARGET_ARCH_32_BIT
+ DCHECK(!IsFreelistOrUninitializedEntry());
}
Address JSDispatchEntry::GetEntrypoint() const {
- DCHECK(!IsFreelistEntry());
+ DCHECK(!IsFreelistOrUninitializedEntry());
return entrypoint_.load(std::memory_order_relaxed);
}
Address JSDispatchEntry::GetCodePointer() const {
- DCHECK(!IsFreelistEntry());
+ DCHECK(!IsFreelistOrUninitializedEntry());
+ // Use acquire loads (paired with release stores in MakeJSDispatchEntry() and
+ // SetCodeAndEntrypointPointer()) to ensure the target Code object's fields on
+ // the heap are visible before dereferencing the returned pointer.
#if V8_TARGET_ARCH_X64 && V8_SUPPORT_LA57
return code_object_.load(std::memory_order_acquire);
#else
@@ -95,11 +119,11 @@ Tagged<Code> JSDispatchEntry::GetCode() const {
}
uint16_t JSDispatchEntry::GetParameterCount() const {
- // Loading a pointer out of a freed entry will always result in an invalid
- // pointer (e.g. upper bits set or nullptr). However, here we're just loading
- // an integer (the parameter count), so we probably want to make sure that
- // we're not getting that from a freed entry.
- CHECK(!IsFreelistEntry());
+ // Loading a pointer out of a freed or uninitialized entry will always result
+ // in an invalid pointer (e.g. upper bits set or nullptr). However, here we're
+ // just loading an integer (the parameter count), so we must ensure that we're
+ // not getting that from a freed or uninitialized (zero-filled) entry.
+ CHECK(!IsFreelistOrUninitializedEntry());
#ifdef V8_TARGET_ARCH_32_BIT
return parameter_count_.load(std::memory_order_relaxed);
#else
@@ -247,6 +271,9 @@ void JSDispatchEntry::SetCodeAndEntrypointPointer(Address new_object,
Address new_entrypoint,
Isolate* isolate) {
DCHECK_NE(new_entrypoint, kNullAddress);
+ // Updates to code_object_/encoded_word_ must use release stores (paired with
+ // acquire loads in GetCodePointer()) so that background threads that read the
+ // new Code pointer do not observe an uninitialized Code object on the heap.
#if V8_TARGET_ARCH_X64 && V8_SUPPORT_LA57
DCHECK(Internals::HasHeapObjectTag(new_object));
entrypoint_.store(new_entrypoint, std::memory_order_relaxed);
@@ -277,7 +304,7 @@ void JSDispatchEntry::SetCodeAndEntrypointPointer(Address new_object,
}
}
#endif // !(V8_TARGET_ARCH_X64 && V8_SUPPORT_LA57)
- DCHECK(!IsFreelistEntry());
+ DCHECK(!IsFreelistOrUninitializedEntry());
}
void JSDispatchEntry::SetEntrypointPointer(Address new_entrypoint) {
@@ -288,16 +315,33 @@ void JSDispatchEntry::SetEntrypointPointer(Address new_entrypoint) {
void JSDispatchEntry::MakeFreelistEntry(uint32_t next_entry_index) {
#ifdef V8_TARGET_ARCH_64_BIT
Address payload = kFreeEntryTag | next_entry_index;
- entrypoint_.store(payload, std::memory_order_relaxed);
+ entrypoint_.store(payload, std::memory_order_release);
#else
// Store index + 1 such that we can use 0 for non-free entries.
- next_free_entry_.store(next_entry_index + 1, std::memory_order_relaxed);
+ next_free_entry_.store(next_entry_index + 1, std::memory_order_release);
entrypoint_.store(kNullAddress, std::memory_order_relaxed);
#endif
#if V8_TARGET_ARCH_X64 && V8_SUPPORT_LA57
code_object_.store(kNullAddress, std::memory_order_relaxed);
#endif // V8_TARGET_ARCH_X64 && V8_SUPPORT_LA57
- encoded_word_.store(kNullAddress, std::memory_order_relaxed);
+ // Set the parameter count to 0xffff (kMaxUInt16 / kParameterCountMask) rather
+ // than 0 (kDontAdaptArgumentsSentinel) while keeping the marking bit and code
+ // pointer bits zeroed. Since 0xffff exceeds Code::kMaxArguments, a freelist
+ // entry never holds a valid parameter count. This prevents two issues:
+ // 1. Concurrent sweeping in GetParameterCount(): if an entry is swept while a
+ // background compiler thread is between the
+ // IsFreelistOrUninitializedEntry() check and the parameter count load in
+ // GetParameterCount(), or if the relaxed store below is reordered before
+ // the entrypoint_ store on weak memory models, the reader observes 0xffff
+ // rather than 0.
+ // 2. Direct parameter count loads in generated code (such as
+ // LoadParameterCountFromJSDispatchTable), which load the 16-bit parameter
+ // count directly without checking IsFreelistEntry(), will never match an
+ // expected parameter count of 0 on a freed entry.
+#ifdef V8_TARGET_ARCH_32_BIT
+ parameter_count_.store(kMaxUInt16, std::memory_order_relaxed);
+#endif
+ encoded_word_.store(kParameterCountMask, std::memory_order_relaxed);
DCHECK(IsFreelistEntry());
}
@@ -314,10 +358,20 @@ bool JSDispatchEntry::IsFreelistEntry(Address entrypoint) const {
bool JSDispatchEntry::IsFreelistEntry() const {
#ifdef V8_TARGET_ARCH_64_BIT
- auto entrypoint = entrypoint_.load(std::memory_order_relaxed);
+ auto entrypoint = entrypoint_.load(std::memory_order_acquire);
return IsFreelistEntry(entrypoint);
#else
- return next_free_entry_.load(std::memory_order_relaxed) != 0;
+ return next_free_entry_.load(std::memory_order_acquire) != 0;
+#endif
+}
+
+bool JSDispatchEntry::IsFreelistOrUninitializedEntry() const {
+#ifdef V8_TARGET_ARCH_64_BIT
+ auto entrypoint = entrypoint_.load(std::memory_order_acquire);
+ return entrypoint == kNullAddress || IsFreelistEntry(entrypoint);
+#else
+ return next_free_entry_.load(std::memory_order_acquire) != 0 ||
+ entrypoint_.load(std::memory_order_acquire) == kNullAddress;
#endif
}
diff --git a/deps/v8/src/sandbox/js-dispatch-table.h b/deps/v8/src/sandbox/js-dispatch-table.h
index 270c2efa13e..2c7b91ae3be 100644
--- a/deps/v8/src/sandbox/js-dispatch-table.h
+++ b/deps/v8/src/sandbox/js-dispatch-table.h
@@ -54,6 +54,9 @@ struct JSDispatchEntry {
// Returns true if this entry is a freelist entry.
inline bool IsFreelistEntry() const;
+ // Returns true if this entry is a freelist entry or an uninitialized
+ // (zero-filled) entry.
+ inline bool IsFreelistOrUninitializedEntry() const;
#ifdef V8_TARGET_ARCH_64_BIT
// Helper to check if an entry is a freelist entry using an already-loaded
// entrypoint value.
diff --git a/deps/v8/src/wasm/baseline/liftoff-assembler.cc b/deps/v8/src/wasm/baseline/liftoff-assembler.cc
index f2a2210fbae..f317cc81187 100644
--- a/deps/v8/src/wasm/baseline/liftoff-assembler.cc
+++ b/deps/v8/src/wasm/baseline/liftoff-assembler.cc
@@ -896,6 +896,14 @@ void LiftoffAssembler::FinishCall(const ValueKindSig* sig,
}
}
if (num_lowered_params == 1) {
+#if V8_ENABLE_SANDBOX
+ // For sandbox hardening, treat tagged return values from Wasm calls as
+ // compressed values and re-apply the pointer compression cage base.
+ if (is_reference(return_kind) &&
+ call_descriptor->IsAnyWasmFunctionCall()) {
+ DecompressTagged(reg_pair[0].gp(), reg_pair[0].gp());
+ }
+#endif
PushRegister(return_kind, reg_pair[0]);
} else {
PushRegister(return_kind, LiftoffRegister::ForPair(reg_pair[0].gp(),
diff --git a/deps/v8/src/wasm/baseline/liftoff-compiler.cc b/deps/v8/src/wasm/baseline/liftoff-compiler.cc
index 81f43cd1f46..9f86396ef3f 100644
--- a/deps/v8/src/wasm/baseline/liftoff-compiler.cc
+++ b/deps/v8/src/wasm/baseline/liftoff-compiler.cc
@@ -1078,6 +1078,13 @@ class LiftoffCompiler {
if (kind_ == kI32 && location_.IsRegister()) {
compiler_->asm_.clear_i32_upper_half(reg.gp());
}
+#endif
+#if V8_ENABLE_SANDBOX
+ // For sandbox hardening, treat tagged parameters as compressed values
+ // and re-apply the pointer compression cage base on function entry.
+ if (is_reference(kind_)) {
+ compiler_->asm_.DecompressTagged(reg.gp(), reg.gp());
+ }
#endif
if (needs_gp_pair_) {
NextLocation();
diff --git a/deps/v8/src/wasm/module-compiler.cc b/deps/v8/src/wasm/module-compiler.cc
index 9f78bde9a9a..860a71e2a42 100644
--- a/deps/v8/src/wasm/module-compiler.cc
+++ b/deps/v8/src/wasm/module-compiler.cc
@@ -2833,6 +2833,26 @@ void AsyncCompileJob::DoSync(Args&&... args) {
StartForegroundTask();
}
+template <typename Step, typename... Args>
+void AsyncCompileJob::DoImmediatelyOrDefer(Args&&... args) {
+ NextStep<Step>(std::forward<Args>(args)...);
+ Isolate* isolate = isolate_specific_info_.isolate_;
+ DCHECK_EQ(isolate, Isolate::Current());
+ // We cannot unconditionally spawn a non-nestable foreground task here
+ // because Node.js relies on synchronous completion of
+ // WasmModuleCompilation::Finish (e.g. in DeserializeWasmModule). Only defer
+ // to a non-nestable foreground task when inside an API interrupt or when
+ // JavaScript execution is disallowed (such as Blink's ScriptForbiddenScope
+ // during BFCache freeze, see crbug.com/580857997).
+ if (!isolate->is_executing_api_interrupt() &&
+ isolate->is_javascript_execution_allowed()) {
+ std::unique_ptr<CompileStep> step = std::move(step_);
+ step->Run(this, true);
+ } else {
+ StartForegroundTask();
+ }
+}
+
template <typename Step, typename... Args>
void AsyncCompileJob::DoAsync(Args&&... args) {
NextStep<Step>(std::forward<Args>(args)...);
@@ -2975,21 +2995,38 @@ class AsyncCompileJob::PrepareNativeModule : public CompileStep {
//==========================================================================
class AsyncCompileJob::FinishCompilation : public CompileStep {
public:
- explicit FinishCompilation(std::shared_ptr<NativeModule> final_native_module)
- : final_native_module_(std::move(final_native_module)) {}
+ explicit FinishCompilation(
+ std::shared_ptr<NativeModule> final_native_module,
+ IndirectHandle<WasmModuleObject> deserialized_module_object = {})
+ : final_native_module_(std::move(final_native_module)),
+ deserialized_module_object_(deserialized_module_object) {}
+
+ ~FinishCompilation() override {
+ GlobalHandles::Destroy(deserialized_module_object_.location());
+ }
private:
void RunInForeground(AsyncCompileJob* job) override {
TRACE_COMPILE("(3) Compilation finished\n");
- DCHECK_EQ(job->isolate_specific_info_.isolate_, Isolate::Current());
+ Isolate* isolate = job->isolate_specific_info_.isolate_;
+ DCHECK_EQ(isolate, Isolate::Current());
+ DirectHandle<WasmModuleObject> deserialized_module_object;
+ if (!deserialized_module_object_.is_null()) {
+ deserialized_module_object =
+ direct_handle(*deserialized_module_object_, isolate);
+ GlobalHandles::Destroy(deserialized_module_object_.location());
+ deserialized_module_object_ = {};
+ }
// Then finalize and publish the generated module.
// This invalidates the {AsyncCompileJob}.
- bool cache_hit = final_native_module_ != job->new_native_module_;
- std::move(*job).FinishCompile(std::move(final_native_module_), {},
- cache_hit);
+ bool cache_hit = deserialized_module_object.is_null() &&
+ final_native_module_ != job->new_native_module_;
+ std::move(*job).FinishCompile(std::move(final_native_module_),
+ deserialized_module_object, cache_hit);
}
std::shared_ptr<NativeModule> final_native_module_;
+ IndirectHandle<WasmModuleObject> deserialized_module_object_;
};
//==========================================================================
@@ -3264,9 +3301,7 @@ void AsyncStreamingProcessor::OnFinishedStream(
job_->compile_imports_);
owns_cache_entry_ = false;
}
- // Calling {Failed} will invalidate the {AsyncCompileJob} and delete {this}.
- HandleScope handle_scope(isolate);
- std::move(*job_).Failed();
+ job_->DoImmediatelyOrDefer<AsyncCompileJob::Fail>();
return;
}
@@ -3299,13 +3334,6 @@ void AsyncStreamingProcessor::OnFinishedStream(
return;
}
- // We have to open a HandleScope and prepare the Context for
- // CreateNativeModule, PrepareRuntimeObjects and FinishCompile as this is a
- // callback from the embedder.
- HandleScope scope(isolate);
- SaveAndSwitchContext saved_context(
- isolate, *job_->isolate_specific_info_.native_context_);
-
// Record the size of the wire bytes and the number of functions. In
// synchronous and asynchronous (non-streaming) compilation, this happens in
// {DecodeWasmModule}.
@@ -3351,19 +3379,16 @@ void AsyncStreamingProcessor::OnFinishedStream(
final_native_module = GetWasmEngine()->UpdateNativeModuleCache(
failed, job_->new_native_module_, isolate);
owns_cache_entry_ = false;
- cache_hit = final_native_module != job_->new_native_module_;
- // We finally call {Failed} or {FinishCompile}, which will invalidate the
- // {AsyncCompileJob} and delete {this}.
if (failed) {
SetCrashKey("CompilationState failed");
- std::move(*job_).Failed();
+ job_->DoImmediatelyOrDefer<AsyncCompileJob::Fail>();
return;
}
}
if (needs_finish) {
- std::move(*job_).FinishCompile(std::move(final_native_module), {},
- cache_hit);
+ job_->DoImmediatelyOrDefer<AsyncCompileJob::FinishCompilation>(
+ std::move(final_native_module));
}
}
@@ -3388,8 +3413,8 @@ bool AsyncStreamingProcessor::Deserialize(
base::UniqueArray<const uint8_t>& wire_bytes) {
TRACE_EVENT("v8.wasm", "wasm.Deserialize");
Isolate* isolate = job_->isolate_specific_info_.isolate_;
- // DeserializeNativeModule and FinishCompile assume that they are executed in
- // a HandleScope, and that a context is set on the isolate.
+ // DeserializeNativeModule assumes that it is executed in a HandleScope, and
+ // that a context is set on the isolate.
HandleScope scope(isolate);
SaveAndSwitchContext saved_context(
isolate, *job_->isolate_specific_info_.native_context_);
@@ -3408,10 +3433,11 @@ bool AsyncStreamingProcessor::Deserialize(
CppGCManaged<NativeModule>::Ptr deserialized_native_module =
module_object->native_module();
job_->wire_bytes_ = ModuleWireBytes(deserialized_native_module->wire_bytes());
- // Calling {FinishCompile} deletes the {AsyncCompileJob} and {this}.
- std::move(*job_).FinishCompile(
- std::move(deserialized_native_module).as_shared_ptr(), module_object,
- false);
+ IndirectHandle<WasmModuleObject> global_module_object =
+ isolate->global_handles()->Create(*module_object);
+ job_->DoImmediatelyOrDefer<AsyncCompileJob::FinishCompilation>(
+ std::move(deserialized_native_module).as_shared_ptr(),
+ global_module_object);
return true;
}
diff --git a/deps/v8/src/wasm/module-compiler.h b/deps/v8/src/wasm/module-compiler.h
index 09435d02a77..468c0d4ed4d 100644
--- a/deps/v8/src/wasm/module-compiler.h
+++ b/deps/v8/src/wasm/module-compiler.h
@@ -213,6 +213,11 @@ class AsyncCompileJob {
typename... Args>
void DoSync(Args&&... args);
+ // Switches to the compilation step {Step} and executes it immediately if
+ // allowed on the current stack, or starts a foreground task otherwise.
+ template <typename Step, typename... Args>
+ void DoImmediatelyOrDefer(Args&&... args);
+
// Switches to the compilation step {Step} and starts a background task to
// execute it.
template <typename Step, typename... Args>
diff --git a/deps/v8/src/wasm/module-instantiate.cc b/deps/v8/src/wasm/module-instantiate.cc
index 904d1ed2fe4..89680c9f1f0 100644
--- a/deps/v8/src/wasm/module-instantiate.cc
+++ b/deps/v8/src/wasm/module-instantiate.cc
@@ -1855,10 +1855,6 @@ bool InstanceBuilder::ProcessImportedTable(int import_index, int table_index,
table_object->has_trusted_data()
? table_object->trusted_data(isolate_)->module()
: nullptr;
- // The security-relevant aspect of this DCHECK is covered by the SBXCHECK_EQ
- // below.
- DCHECK_IMPLIES(table_object->unsafe_type().has_index(),
- table_type_module != nullptr);
// We need to check type equivalence (rather than subtyping) because tables
// are mutable: we cannot allow the importing module to write supertyped
diff --git a/deps/v8/src/wasm/streaming-decoder.cc b/deps/v8/src/wasm/streaming-decoder.cc
index 2e3f7c703a1..ba307859e2e 100644
--- a/deps/v8/src/wasm/streaming-decoder.cc
+++ b/deps/v8/src/wasm/streaming-decoder.cc
@@ -411,14 +411,14 @@ void StreamingDecoder::Finish(
}
struct CachingInterface : public WasmStreaming::ModuleCachingInterface {
- StreamingProcessor* const processor;
+ StreamingDecoder* const decoder;
base::UniqueArray<const uint8_t>& wire_bytes;
bool did_try_deserialization = false;
bool did_deserialize = false;
- CachingInterface(StreamingProcessor* proc,
+ CachingInterface(StreamingDecoder* decoder,
base::UniqueArray<const uint8_t>& wire_bytes)
- : processor(proc), wire_bytes(wire_bytes) {}
+ : decoder(decoder), wire_bytes(wire_bytes) {}
// Public API:
std::span<const uint8_t> GetWireBytes() const override {
@@ -431,11 +431,27 @@ void StreamingDecoder::Finish(
FATAL("SetCachedCompiledModuleBytes can only be called once");
}
did_try_deserialization = true;
+ CHECK_EQ(StreamState::kReceivingBytes, decoder->stream_state_);
+ // Move {processor_} to a local variable and mark the stream as
+ // {kFinished} before calling {Deserialize}. {Deserialize} can
+ // synchronously finish compilation, invoke embedder/JS callbacks (which
+ // may destroy the embedder's {StreamingDecoder} reference), and destroy
+ // the {AsyncCompileJob} (dropping its {StreamingDecoder} reference).
+ decoder->stream_state_ = StreamState::kFinished;
+ std::unique_ptr<StreamingProcessor> processor =
+ std::move(decoder->processor_);
did_deserialize =
processor->Deserialize(base::VectorOf(module_bytes), wire_bytes);
+ if (!did_deserialize) {
+ // Deserialization failed; restore {processor_} and {stream_state_}
+ // so {Finish} can fall back to decoding and compiling the wire bytes.
+ CHECK_EQ(StreamState::kFinished, decoder->stream_state_);
+ decoder->processor_ = std::move(processor);
+ decoder->stream_state_ = StreamState::kReceivingBytes;
+ }
return did_deserialize;
}
- } caching_interface{processor_.get(), bytes_copy};
+ } caching_interface{this, bytes_copy};
// Call the embedder.
caching_callback(caching_interface);
diff --git a/deps/v8/src/wasm/wasm-code-pointer-table-inl.h b/deps/v8/src/wasm/wasm-code-pointer-table-inl.h
index d305c69ea0f..fcb3752c00f 100644
--- a/deps/v8/src/wasm/wasm-code-pointer-table-inl.h
+++ b/deps/v8/src/wasm/wasm-code-pointer-table-inl.h
@@ -123,6 +123,13 @@ WasmCodePointer WasmCodePointerTable::AllocateUninitializedEntry() {
// Freelist is (still) empty so extend this space by another segment.
auto [segment, freelist] = AllocateAndInitializeSegment();
+ // Do not allocate the last segment, as `kInvalidWasmCodePointer` (-1) masks
+ // to its last entry (`kIndexSpaceSize - 1`) and must remain unmapped so
+ // calls to invalid code pointers reliably crash.
+ if (segment.last_entry() == WasmCodePointer::kIndexSpaceSize - 1) {
+ V8::FatalProcessOutOfMemory(
+ nullptr, "WasmCodePointerTable::AllocateUninitializedEntry");
+ }
// Take out the first entry before we link it to the freelist_head.
allocated_entry = AllocateEntryFromFreelistNonAtomic(&freelist);
diff --git a/deps/v8/src/wasm/wasm-js.cc b/deps/v8/src/wasm/wasm-js.cc
index d19ad0a5186..e0e91fc78a7 100644
--- a/deps/v8/src/wasm/wasm-js.cc
+++ b/deps/v8/src/wasm/wasm-js.cc
@@ -81,7 +81,11 @@ class WasmStreaming::WasmStreamingImpl {
void Finish(const WasmStreaming::ModuleCachingCallback& caching_callback) {
// Finish can only be called on the main thread of the isolate.
CHECK_EQ(i_isolate_->thread_id(), i::ThreadId::Current());
- streaming_decoder_->Finish(caching_callback);
+ // Hold a local reference in case the embedder destroys `WasmStreaming`
+ // inside `caching_callback` or `OnCompilationSucceeded`.
+ std::shared_ptr<i::wasm::StreamingDecoder> streaming_decoder =
+ streaming_decoder_;
+ streaming_decoder->Finish(caching_callback);
}
void Abort(i::MaybeHandle<i::JSAny> exception) {
@@ -192,9 +196,14 @@ class WasmModuleCompilation::Impl {
DCHECK_NULL(resolver_->callback_);
resolver_->callback_ = resolution_callback;
- streaming_decoder_->InitializeIsolateSpecificInfo(
+ // Hold a local reference in case the embedder destroys
+ // `WasmModuleCompilation` inside `caching_callback` or
+ // `resolution_callback`.
+ std::shared_ptr<i::wasm::StreamingDecoder> streaming_decoder =
+ streaming_decoder_;
+ streaming_decoder->InitializeIsolateSpecificInfo(
reinterpret_cast<i::Isolate*>(isolate));
- streaming_decoder_->Finish(caching_callback);
+ streaming_decoder->Finish(caching_callback);
}
void Abort() { streaming_decoder_->Abort(); }
diff --git a/deps/v8/src/wasm/wasm-objects-inl.h b/deps/v8/src/wasm/wasm-objects-inl.h
index 1a727dbaac3..36280be13be 100644
--- a/deps/v8/src/wasm/wasm-objects-inl.h
+++ b/deps/v8/src/wasm/wasm-objects-inl.h
@@ -1175,7 +1175,8 @@ void WasmSuspenderObject::set_reject(Tagged<UnionOf<JSObject, Undefined>> value,
wasm::ValueType WasmTableObject::type(const wasm::WasmModule* module) {
wasm::ValueType type = unsafe_type();
- SBXCHECK(!type.has_index() || module->has_type(type.ref_index()));
+ SBXCHECK(!type.has_index() ||
+ (module != nullptr && module->has_type(type.ref_index())));
return type;
}
@@ -1195,7 +1196,7 @@ wasm::ValueType WasmTableObject::unsafe_type() {
// technically sandbox violations, we should still try to avoid them to keep
// fuzzers happy. This SBXCHECK accomplishes that.
wasm::ValueType type = wasm::ValueType::FromRawBitField(raw_type());
- SBXCHECK(type.is_valid());
+ SBXCHECK(type.is_valid() && type.is_ref());
return type;
}
diff --git a/deps/v8/src/wasm/wasm-objects.cc b/deps/v8/src/wasm/wasm-objects.cc
index 2548fa1ab54..721d17c41c8 100644
--- a/deps/v8/src/wasm/wasm-objects.cc
+++ b/deps/v8/src/wasm/wasm-objects.cc
@@ -303,7 +303,7 @@ int WasmTableObject::Grow(Isolate* isolate, DirectHandle<WasmTableObject> table,
uint64_t static_max_size = wasm::max_table_size();
uint32_t max_size = static_cast<uint32_t>(std::min(
static_max_size, table->maximum_length_u64().value_or(static_max_size)));
- DCHECK_LE(old_size, max_size);
+ SBXCHECK_LE(old_size, max_size);
if (count > max_size - old_size) return -1;
uint32_t new_size = old_size + count;
@@ -324,11 +324,8 @@ int WasmTableObject::Grow(Isolate* isolate, DirectHandle<WasmTableObject> table,
bool has_dispatch_table = !dispatch_table.is_identical_to(
isolate->factory()->empty_wasm_dispatch_table());
- DCHECK_EQ(
- table->unsafe_type().ref_type_kind() == wasm::RefTypeKind::kFunction,
- has_dispatch_table);
if (has_dispatch_table) {
- DCHECK_EQ(old_size, dispatch_table->length());
+ SBXCHECK_EQ(old_size, dispatch_table->length());
dispatch_table = WasmDispatchTable::Grow(isolate, dispatch_table, new_size);
table->set_trusted_dispatch_table(*dispatch_table);
DCHECK_EQ(new_size, table->trusted_dispatch_table(isolate)->length());
@@ -390,9 +387,9 @@ void WasmTableObject::SetFunctionTableEntry(
table->entries()->set(entry_index, ReadOnlyRoots(isolate).wasm_null());
return;
}
- DCHECK(IsWasmFuncRef(*entry));
- DirectHandle<Object> external = WasmInternalFunction::GetOrCreateExternal(
- direct_handle(Cast<WasmFuncRef>(*entry)->internal(isolate), isolate));
+ DirectHandle<Object> external =
+ WasmInternalFunction::GetOrCreateExternal(direct_handle(
+ CheckedCast<WasmFuncRef>(*entry)->internal(isolate), isolate));
UpdateDispatchTableMultiple(isolate, dispatch_table, entry_index, 1,
external);
@@ -406,53 +403,16 @@ void WasmTableObject::Set(Isolate* isolate, DirectHandle<WasmTableObject> table,
// Callers need to perform bounds checks, type check, and error handling.
DCHECK(table->is_in_bounds(index));
- DirectHandle<FixedArray> entries(table->entries(), isolate);
// The FixedArray is addressed with int's.
int entry_index = static_cast<int>(index);
- wasm::ValueType unsafe_type = table->unsafe_type();
- if (unsafe_type.has_index()) {
- DCHECK(table->has_trusted_data());
- const wasm::WasmModule* module = table->trusted_data(isolate)->module();
- if (module->has_signature(table->type(module).ref_index())) {
- SetFunctionTableEntry(isolate, table, dispatch_table, entry_index, entry);
- return;
- }
- entries->set(entry_index, *entry);
- return;
- }
- switch (unsafe_type.generic_kind()) {
- case wasm::GenericKind::kExtern:
- case wasm::GenericKind::kString:
- case wasm::GenericKind::kStringViewWtf8:
- case wasm::GenericKind::kStringViewWtf16:
- case wasm::GenericKind::kStringViewIter:
- case wasm::GenericKind::kEq:
- case wasm::GenericKind::kStruct:
- case wasm::GenericKind::kArray:
- case wasm::GenericKind::kAny:
- case wasm::GenericKind::kI31:
- case wasm::GenericKind::kNone:
- case wasm::GenericKind::kNoFunc:
- case wasm::GenericKind::kNoExtern:
- case wasm::GenericKind::kExn:
- case wasm::GenericKind::kNoExn:
- case wasm::GenericKind::kCont:
- case wasm::GenericKind::kNoCont:
- case wasm::GenericKind::kWaitqueue:
- case wasm::GenericKind::kNoWaitqueue:
- entries->set(entry_index, *entry);
- return;
- case wasm::GenericKind::kFunc:
- SetFunctionTableEntry(isolate, table, dispatch_table, entry_index, entry);
- return;
- case wasm::GenericKind::kBottom:
- case wasm::GenericKind::kTop:
- case wasm::GenericKind::kVoid:
- case wasm::GenericKind::kExternString:
- break;
+ bool has_dispatch_table = !dispatch_table.is_identical_to(
+ isolate->factory()->empty_wasm_dispatch_table());
+ if (has_dispatch_table) {
+ SetFunctionTableEntry(isolate, table, dispatch_table, entry_index, entry);
+ } else {
+ table->entries()->set(entry_index, *entry);
}
- UNREACHABLE(); // Safely catches corrupted values read from the sandbox.
}
DirectHandle<Object> WasmTableObject::Get(Isolate* isolate,
@@ -469,63 +429,14 @@ DirectHandle<Object> WasmTableObject::Get(Isolate* isolate,
if (IsWasmNull(*entry)) return entry;
if (IsWasmFuncRef(*entry)) return entry;
+ if (!IsTuple2(*entry)) return entry;
- wasm::ValueType unsafe_type = table->unsafe_type();
- if (unsafe_type.has_index()) {
- DCHECK(table->has_trusted_data());
- const WasmModule* module = table->trusted_data(isolate)->module();
- wasm::ModuleTypeIndex element_type = table->type(module).ref_index();
- if (module->has_array(element_type) || module->has_struct(element_type) ||
- module->has_cont_type(element_type)) {
- return entry;
- }
- DCHECK(module->has_signature(element_type));
- // Fall through.
- } else {
- bool is_func = false;
- switch (unsafe_type.generic_kind()) {
- case wasm::GenericKind::kStringViewWtf8:
- case wasm::GenericKind::kStringViewWtf16:
- case wasm::GenericKind::kStringViewIter:
- case wasm::GenericKind::kExtern:
- case wasm::GenericKind::kString:
- case wasm::GenericKind::kEq:
- case wasm::GenericKind::kI31:
- case wasm::GenericKind::kStruct:
- case wasm::GenericKind::kArray:
- case wasm::GenericKind::kAny:
- case wasm::GenericKind::kNone:
- case wasm::GenericKind::kNoFunc:
- case wasm::GenericKind::kNoExtern:
- case wasm::GenericKind::kExn:
- case wasm::GenericKind::kNoExn:
- case wasm::GenericKind::kCont:
- case wasm::GenericKind::kNoCont:
- case wasm::GenericKind::kWaitqueue:
- case wasm::GenericKind::kNoWaitqueue:
- return entry;
- case wasm::GenericKind::kFunc:
- // Placeholder; handled below.
- is_func = true;
- break;
- case wasm::GenericKind::kBottom:
- case wasm::GenericKind::kTop:
- case wasm::GenericKind::kVoid:
- case wasm::GenericKind::kExternString:
- break;
- }
- // The code below is sandbox-safe, but we can be more explicit about
- // rejecting corruption (invalid {unsafe_type}) here.
- if (!is_func) UNREACHABLE();
- }
-
- // {entry} is not a valid entry in the table. It has to be a placeholder
- // for lazy initialization.
+ // {entry} is a placeholder for lazy initialization.
DirectHandle<Tuple2> tuple = Cast<Tuple2>(entry);
- auto trusted_instance_data = direct_handle(
- Cast<WasmInstanceObject>(tuple->value1())->trusted_data(isolate),
+ DirectHandle<WasmTrustedInstanceData> trusted_instance_data(
+ CheckedCast<WasmInstanceObject>(tuple->value1())->trusted_data(isolate),
isolate);
- int function_index = Cast<Smi>(tuple->value2()).value();
+ int function_index = CheckedCast<Smi>(tuple->value2()).value();
// Create a WasmInternalFunction and WasmFuncRef for the function if it does
// not exist yet, and store it in the table.
@@ -561,9 +472,8 @@ bool FunctionSigMatchesTable(wasm::CanonicalTypeIndex sig_id,
// types before installing the dispatch table entry. There are three
// alternative success conditions:
// (1) Generic "funcref" tables can hold any function entry.
- if (!table_type.has_index() &&
- table_type.generic_kind() == wasm::GenericKind::kFunc) {
- return true;
+ if (!table_type.has_index()) {
+ return table_type.generic_kind() == wasm::GenericKind::kFunc;
}
// (2) Most function types are expected to be final, so they can be compared
// cheaply by canonicalized index equality.
@@ -2438,6 +2348,9 @@ void DispatchTableClear(Tagged<DispatchTable> dispatch_table, int index,
void WasmDispatchTable::Clear(
int index, WasmDispatchTable::NewOrExistingEntry new_or_existing) {
+ if (new_or_existing == WasmDispatchTable::kExistingEntry) {
+ SBXCHECK(table_type().is_nullable());
+ }
DispatchTableClear<WasmDispatchTable>(this, index, new_or_existing);
#if V8_ENABLE_DRUMBRAKE
if (v8_flags.wasm_jitless &&
@@ -3450,7 +3363,8 @@ MaybeDirectHandle<Object> JSToWasmObject(Isolate* isolate,
const char** error_message) {
CanonicalValueType canonical;
if (unsafe_expected_type.has_index()) {
- SBXCHECK(module->has_type(unsafe_expected_type.ref_index()));
+ SBXCHECK(module != nullptr &&
+ module->has_type(unsafe_expected_type.ref_index()));
canonical = module->canonical_type(unsafe_expected_type);
} else {
// Some code paths did check this before, but to be on the safe side we
diff --git a/deps/v8/test/cctest/compiler/test-js-context-specialization.cc b/deps/v8/test/cctest/compiler/test-js-context-specialization.cc
index 3478222b77f..c56830412fb 100644
--- a/deps/v8/test/cctest/compiler/test-js-context-specialization.cc
+++ b/deps/v8/test/cctest/compiler/test-js-context-specialization.cc
@@ -97,6 +97,7 @@ void ContextSpecializationTester::CheckContextInputAndDepthChanges(
Node* node, DirectHandle<Context> expected_new_context_object,
size_t expected_new_depth) {
ContextAccess access = ContextAccessOf(node->op());
+ Node* expected_control = NodeProperties::GetControlInput(node);
Reduction r = spec()->Reduce(node);
CHECK(r.Changed());
@@ -104,6 +105,7 @@ void ContextSpecializationTester::CheckContextInputAndDepthChanges(
CHECK_EQ(IrOpcode::kHeapConstant, new_context->opcode());
HeapObjectMatcher match(new_context);
CHECK_EQ(Cast<Context>(*match.ResolvedValue()), *expected_new_context_object);
+ CHECK_EQ(NodeProperties::GetControlInput(r.replacement()), expected_control);
ContextAccess new_access = ContextAccessOf(r.replacement()->op());
CHECK_EQ(new_access.depth(), expected_new_depth);
@@ -114,11 +116,13 @@ void ContextSpecializationTester::CheckContextInputAndDepthChanges(
void ContextSpecializationTester::CheckContextInputAndDepthChanges(
Node* node, Node* expected_new_context, size_t expected_new_depth) {
ContextAccess access = ContextAccessOf(node->op());
+ Node* expected_control = NodeProperties::GetControlInput(node);
Reduction r = spec()->Reduce(node);
CHECK(r.Changed());
Node* new_context = NodeProperties::GetContextInput(r.replacement());
CHECK_EQ(new_context, expected_new_context);
+ CHECK_EQ(NodeProperties::GetControlInput(r.replacement()), expected_control);
ContextAccess new_access = ContextAccessOf(r.replacement()->op());
CHECK_EQ(new_access.depth(), expected_new_depth);
@@ -171,19 +175,23 @@ TEST(ReduceJSLoadContextNoCell0) {
Node* deep_const_context =
t.jsgraph()->ConstantNoHole(MakeRef(t.broker(), subcontext2), t.broker());
Node* param_context = t.graph()->NewNode(t.common()->Parameter(0), start);
+ Node* branch = t.graph()->NewNode(t.common()->Branch(), param_context, start);
+ Node* control = t.graph()->NewNode(t.common()->IfTrue(), branch);
{
// Mutable slot, constant context, depth = 0 => do nothing.
- Node* load = t.graph()->NewNode(
- t.javascript()->LoadContextNoCell(0, 0, false), const_context, start);
+ Node* load =
+ t.graph()->NewNode(t.javascript()->LoadContextNoCell(0, 0, false),
+ const_context, start, control);
Reduction r = t.spec()->Reduce(load);
CHECK(!r.Changed());
}
{
// Mutable slot, non-constant context, depth = 0 => do nothing.
- Node* load = t.graph()->NewNode(
- t.javascript()->LoadContextNoCell(0, 0, false), param_context, start);
+ Node* load =
+ t.graph()->NewNode(t.javascript()->LoadContextNoCell(0, 0, false),
+ param_context, start, control);
Reduction r = t.spec()->Reduce(load);
CHECK(!r.Changed());
}
@@ -193,13 +201,14 @@ TEST(ReduceJSLoadContextNoCell0) {
Node* load =
t.graph()->NewNode(t.javascript()->LoadContextNoCell(
2, Context::GLOBAL_EVAL_FUN_INDEX, false),
- deep_const_context, start);
+ deep_const_context, start, control);
Reduction r = t.spec()->Reduce(load);
CHECK(r.Changed());
Node* new_context_input = NodeProperties::GetContextInput(r.replacement());
CHECK_EQ(IrOpcode::kHeapConstant, new_context_input->opcode());
HeapObjectMatcher match(new_context_input);
CHECK_EQ(*native, Cast<Context>(*match.ResolvedValue()));
+ CHECK_EQ(control, NodeProperties::GetControlInput(r.replacement()));
ContextAccess access = ContextAccessOf(r.replacement()->op());
CHECK_EQ(Context::GLOBAL_EVAL_FUN_INDEX, static_cast<int>(access.index()));
CHECK_EQ(0, static_cast<int>(access.depth()));
@@ -208,8 +217,9 @@ TEST(ReduceJSLoadContextNoCell0) {
{
// Immutable slot, constant context, depth = 0 => specialize.
- Node* load = t.graph()->NewNode(
- t.javascript()->LoadContextNoCell(0, slot, true), const_context, start);
+ Node* load =
+ t.graph()->NewNode(t.javascript()->LoadContextNoCell(0, slot, true),
+ const_context, start, control);
Reduction r = t.spec()->Reduce(load);
CHECK(r.Changed());
CHECK(r.replacement() != load);
@@ -241,60 +251,62 @@ TEST(ReduceJSLoadContextNoCell1) {
t.graph()->NewNode(create_function_context, context0, start, start);
Node* context2 =
t.graph()->NewNode(create_function_context, context1, start, start);
+ Node* branch = t.graph()->NewNode(t.common()->Branch(), context0, start);
+ Node* control = t.graph()->NewNode(t.common()->IfTrue(), branch);
{
Node* load = t.graph()->NewNode(
t.javascript()->LoadContextNoCell(0, slot_index, false), context2,
- start);
+ start, control);
CHECK(!t.spec()->Reduce(load).Changed());
}
{
Node* load = t.graph()->NewNode(
- t.javascript()->LoadContextNoCell(0, slot_index, true), context2,
- start);
+ t.javascript()->LoadContextNoCell(0, slot_index, true), context2, start,
+ control);
CHECK(!t.spec()->Reduce(load).Changed());
}
{
Node* load = t.graph()->NewNode(
t.javascript()->LoadContextNoCell(1, slot_index, false), context2,
- start);
+ start, control);
t.CheckContextInputAndDepthChanges(load, context1, 0);
}
{
Node* load = t.graph()->NewNode(
- t.javascript()->LoadContextNoCell(1, slot_index, true), context2,
- start);
+ t.javascript()->LoadContextNoCell(1, slot_index, true), context2, start,
+ control);
t.CheckContextInputAndDepthChanges(load, context1, 0);
}
{
Node* load = t.graph()->NewNode(
t.javascript()->LoadContextNoCell(2, slot_index, false), context2,
- start);
+ start, control);
t.CheckContextInputAndDepthChanges(load, context0, 0);
}
{
Node* load = t.graph()->NewNode(
- t.javascript()->LoadContextNoCell(2, slot_index, true), context2,
- start);
+ t.javascript()->LoadContextNoCell(2, slot_index, true), context2, start,
+ control);
t.CheckContextInputAndDepthChanges(load, context0, 0);
}
{
Node* load = t.graph()->NewNode(
t.javascript()->LoadContextNoCell(3, slot_index, false), context2,
- start);
+ start, control);
t.CheckContextInputAndDepthChanges(load, context0, 1);
}
{
Node* load = t.graph()->NewNode(
- t.javascript()->LoadContextNoCell(3, slot_index, true), context2,
- start);
+ t.javascript()->LoadContextNoCell(3, slot_index, true), context2, start,
+ control);
t.CheckContextInputAndDepthChanges(load, context0, 1);
}
}
@@ -333,60 +345,63 @@ TEST(ReduceJSLoadContextNoCell2) {
t.graph()->NewNode(create_function_context, context0, start, start);
Node* context2 =
t.graph()->NewNode(create_function_context, context1, start, start);
+ Node* param = t.graph()->NewNode(t.common()->Parameter(0), start);
+ Node* branch = t.graph()->NewNode(t.common()->Branch(), param, start);
+ Node* control = t.graph()->NewNode(t.common()->IfTrue(), branch);
{
Node* load = t.graph()->NewNode(
t.javascript()->LoadContextNoCell(0, slot_index, false), context2,
- start);
+ start, control);
CHECK(!t.spec()->Reduce(load).Changed());
}
{
Node* load = t.graph()->NewNode(
- t.javascript()->LoadContextNoCell(0, slot_index, true), context2,
- start);
+ t.javascript()->LoadContextNoCell(0, slot_index, true), context2, start,
+ control);
CHECK(!t.spec()->Reduce(load).Changed());
}
{
Node* load = t.graph()->NewNode(
t.javascript()->LoadContextNoCell(1, slot_index, false), context2,
- start);
+ start, control);
t.CheckContextInputAndDepthChanges(load, context1, 0);
}
{
Node* load = t.graph()->NewNode(
- t.javascript()->LoadContextNoCell(1, slot_index, true), context2,
- start);
+ t.javascript()->LoadContextNoCell(1, slot_index, true), context2, start,
+ control);
t.CheckContextInputAndDepthChanges(load, context1, 0);
}
{
Node* load = t.graph()->NewNode(
t.javascript()->LoadContextNoCell(2, slot_index, false), context2,
- start);
+ start, control);
t.CheckContextInputAndDepthChanges(load, context0, 0);
}
{
Node* load = t.graph()->NewNode(
t.javascript()->LoadContextNoCell(2, Context::EXTENSION_INDEX, true),
- context2, start);
+ context2, start, control);
t.CheckChangesToValue(load, slot_value1);
}
{
Node* load = t.graph()->NewNode(
t.javascript()->LoadContextNoCell(3, slot_index, false), context2,
- start);
+ start, control);
t.CheckContextInputAndDepthChanges(load, context_object0, 0);
}
{
Node* load = t.graph()->NewNode(
t.javascript()->LoadContextNoCell(3, Context::EXTENSION_INDEX, true),
- context2, start);
+ context2, start, control);
t.CheckChangesToValue(load, slot_value0);
}
}
@@ -428,60 +443,62 @@ TEST(ReduceJSLoadContextNoCell3) {
t.graph()->NewNode(create_function_context, context0, start, start);
Node* context2 =
t.graph()->NewNode(create_function_context, context1, start, start);
+ Node* branch = t.graph()->NewNode(t.common()->Branch(), context0, start);
+ Node* control = t.graph()->NewNode(t.common()->IfTrue(), branch);
{
Node* load = t.graph()->NewNode(
t.javascript()->LoadContextNoCell(0, slot_index, false), context2,
- start);
+ start, control);
CHECK(!t.spec()->Reduce(load).Changed());
}
{
Node* load = t.graph()->NewNode(
- t.javascript()->LoadContextNoCell(0, slot_index, true), context2,
- start);
+ t.javascript()->LoadContextNoCell(0, slot_index, true), context2, start,
+ control);
CHECK(!t.spec()->Reduce(load).Changed());
}
{
Node* load = t.graph()->NewNode(
t.javascript()->LoadContextNoCell(1, slot_index, false), context2,
- start);
+ start, control);
t.CheckContextInputAndDepthChanges(load, context1, 0);
}
{
Node* load = t.graph()->NewNode(
- t.javascript()->LoadContextNoCell(1, slot_index, true), context2,
- start);
+ t.javascript()->LoadContextNoCell(1, slot_index, true), context2, start,
+ control);
t.CheckContextInputAndDepthChanges(load, context1, 0);
}
{
Node* load = t.graph()->NewNode(
t.javascript()->LoadContextNoCell(2, slot_index, false), context2,
- start);
+ start, control);
t.CheckContextInputAndDepthChanges(load, context_object1, 0);
}
{
Node* load = t.graph()->NewNode(
t.javascript()->LoadContextNoCell(2, Context::EXTENSION_INDEX, true),
- context2, start);
+ context2, start, control);
t.CheckChangesToValue(load, slot_value1);
}
{
Node* load = t.graph()->NewNode(
t.javascript()->LoadContextNoCell(3, slot_index, false), context2,
- start);
+ start, control);
t.CheckContextInputAndDepthChanges(load, context_object0, 0);
}
{
Node* load = t.graph()->NewNode(
t.javascript()->LoadContextNoCell(3, Context::EXTENSION_INDEX, true),
- context2, start);
+ context2, start, control);
t.CheckChangesToValue(load, slot_value0);
}
}
diff --git a/deps/v8/test/cctest/compiler/test-jump-threading.cc b/deps/v8/test/cctest/compiler/test-jump-threading.cc
index bc0dc1c500a..3a22c7e7dc2 100644
--- a/deps/v8/test/cctest/compiler/test-jump-threading.cc
+++ b/deps/v8/test/cctest/compiler/test-jump-threading.cc
@@ -161,8 +161,7 @@ void VerifyForwarding(TestCode* code, int count, int* expected) {
v8::internal::AccountingAllocator allocator;
Zone local_zone(&allocator, ZONE_NAME);
ZoneVector<RpoNumber> result(&local_zone);
- JumpThreading::ComputeForwarding(&local_zone, &result, &code->sequence_,
- true);
+ JumpThreading::ComputeForwarding(&local_zone, &result, &code->sequence_);
CHECK(count == static_cast<int>(result.size()));
for (int i = 0; i < count; i++) {
diff --git a/deps/v8/test/inspector/debugger/context-set-unassigned-optimized-expected.txt b/deps/v8/test/inspector/debugger/context-set-unassigned-optimized-expected.txt
new file mode 100644
index 00000000000..06963e14710
--- /dev/null
+++ b/deps/v8/test/inspector/debugger/context-set-unassigned-optimized-expected.txt
@@ -0,0 +1,9 @@
+Tests that Debugger.evaluateOnCallFrame and Debugger.setVariableValue on kNotAssigned context slots deoptimize optimized closures.
+evalScope.read before: 1
+evalScope.read after evaluateOnCallFrame: 100
+evalScope.read re-optimized: 100
+evalScope.read after second evaluateOnCallFrame: 200
+setVarScope.read before: 2
+readScriptConst before: 10
+setVarScope.read after setVariableValue: 300
+readScriptConst after setVariableValue: 400
diff --git a/deps/v8/test/inspector/debugger/context-set-unassigned-optimized.js b/deps/v8/test/inspector/debugger/context-set-unassigned-optimized.js
new file mode 100644
index 00000000000..4d848a988f4
--- /dev/null
+++ b/deps/v8/test/inspector/debugger/context-set-unassigned-optimized.js
@@ -0,0 +1,136 @@
+// 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.
+
+// Flags: --allow-natives-syntax
+
+const {contextGroup, Protocol} = InspectorTest.start(
+ 'Tests that Debugger.evaluateOnCallFrame and Debugger.setVariableValue ' +
+ 'on kNotAssigned context slots deoptimize optimized closures.');
+
+contextGroup.addScript(
+ `
+const scriptConst = 10;
+function readScriptConst() {
+ return scriptConst;
+}
+
+function makeScope(initial) {
+ let x = initial;
+ function read() {
+ return x;
+ }
+ function pauseInScope() {
+ debugger;
+ }
+ return {read, pauseInScope};
+}
+
+const evalScope = makeScope(1);
+const setVarScope = makeScope(2);
+
+function optimize(fn) {
+ %PrepareFunctionForOptimization(fn);
+ fn();
+ fn();
+ %OptimizeFunctionOnNextCall(fn);
+ return fn();
+}
+`,
+ 0, 0, 'test.js');
+
+(async function test() {
+ await Protocol.Debugger.enable();
+
+ // 1. Debugger.evaluateOnCallFrame mutating a kNotAssigned closure variable.
+ let res = await Protocol.Runtime.evaluate(
+ {expression: 'optimize(evalScope.read)', returnByValue: true});
+ InspectorTest.log('evalScope.read before: ' + res.result.result.value);
+
+ let pausedPromise = Protocol.Debugger.oncePaused();
+ let runPromise =
+ Protocol.Runtime.evaluate({expression: 'evalScope.pauseInScope()'});
+ let {params: {callFrames: [topFrame]}} = await pausedPromise;
+
+ await Protocol.Debugger.evaluateOnCallFrame({
+ callFrameId: topFrame.callFrameId,
+ expression: 'x = 100',
+ });
+ await Protocol.Debugger.resume();
+ await runPromise;
+
+ res = await Protocol.Runtime.evaluate(
+ {expression: 'evalScope.read()', returnByValue: true});
+ InspectorTest.log(
+ 'evalScope.read after evaluateOnCallFrame: ' + res.result.result.value);
+
+ // Re-optimize after kNotAssigned was invalidated and mutate again.
+ res = await Protocol.Runtime.evaluate(
+ {expression: 'optimize(evalScope.read)', returnByValue: true});
+ InspectorTest.log('evalScope.read re-optimized: ' + res.result.result.value);
+
+ pausedPromise = Protocol.Debugger.oncePaused();
+ runPromise =
+ Protocol.Runtime.evaluate({expression: 'evalScope.pauseInScope()'});
+ ({params: {callFrames: [topFrame]}} = await pausedPromise);
+
+ await Protocol.Debugger.evaluateOnCallFrame({
+ callFrameId: topFrame.callFrameId,
+ expression: 'x = 200',
+ });
+ await Protocol.Debugger.resume();
+ await runPromise;
+
+ res = await Protocol.Runtime.evaluate(
+ {expression: 'evalScope.read()', returnByValue: true});
+ InspectorTest.log(
+ 'evalScope.read after second evaluateOnCallFrame: ' +
+ res.result.result.value);
+
+ // 2. Debugger.setVariableValue mutating kNotAssigned closure and script
+ // variables.
+ res = await Protocol.Runtime.evaluate(
+ {expression: 'optimize(setVarScope.read)', returnByValue: true});
+ InspectorTest.log('setVarScope.read before: ' + res.result.result.value);
+ res = await Protocol.Runtime.evaluate(
+ {expression: 'optimize(readScriptConst)', returnByValue: true});
+ InspectorTest.log('readScriptConst before: ' + res.result.result.value);
+
+ pausedPromise = Protocol.Debugger.oncePaused();
+ runPromise =
+ Protocol.Runtime.evaluate({expression: 'setVarScope.pauseInScope()'});
+ ({params: {callFrames: [topFrame]}} = await pausedPromise);
+
+ const closureScopeIndex =
+ topFrame.scopeChain.findIndex(s => s.type === 'closure');
+ await Protocol.Debugger.setVariableValue({
+ scopeNumber: closureScopeIndex,
+ variableName: 'x',
+ newValue: {value: 300},
+ callFrameId: topFrame.callFrameId,
+ });
+
+ const scriptScopeIndex =
+ topFrame.scopeChain.findIndex(s => s.type === 'script');
+ await Protocol.Debugger.setVariableValue({
+ scopeNumber: scriptScopeIndex,
+ variableName: 'scriptConst',
+ newValue: {value: 400},
+ callFrameId: topFrame.callFrameId,
+ });
+
+ await Protocol.Debugger.resume();
+ await runPromise;
+
+ res = await Protocol.Runtime.evaluate(
+ {expression: 'setVarScope.read()', returnByValue: true});
+ InspectorTest.log(
+ 'setVarScope.read after setVariableValue: ' + res.result.result.value);
+ res = await Protocol.Runtime.evaluate(
+ {expression: 'readScriptConst()', returnByValue: true});
+ InspectorTest.log(
+ 'readScriptConst after setVariableValue: ' + res.result.result.value);
+
+ await Protocol.Debugger.disable();
+ InspectorTest.completeTest();
+})();
diff --git a/deps/v8/test/mjsunit/compiler/regress-577323082.js b/deps/v8/test/mjsunit/compiler/regress-577323082.js
new file mode 100644
index 00000000000..d2a3c61d820
--- /dev/null
+++ b/deps/v8/test/mjsunit/compiler/regress-577323082.js
@@ -0,0 +1,70 @@
+// 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.
+
+// Flags: --allow-natives-syntax --turbofan
+// Flags: --no-optimize-on-next-call-optimizes-to-maglev --no-turbolev
+
+"use strict";
+
+function C() {}
+function nop() {}
+
+function alwaysThrows(x) {
+ if (x) throw 1;
+ throw x.a + x.b + x.c + x.d + x.e + x.f + x.g + x.h;
+}
+
+function inner(ctor, fn) {
+ fn(1);
+ while (ctor) {
+ new ctor(...arguments);
+ Reflect.construct(0, arguments);
+ }
+}
+
+function outer(ctor) {
+ inner(ctor, alwaysThrows);
+}
+
+%PrepareFunctionForOptimization(C);
+%PrepareFunctionForOptimization(nop);
+%PrepareFunctionForOptimization(alwaysThrows);
+%PrepareFunctionForOptimization(inner);
+%PrepareFunctionForOptimization(outer);
+
+assertThrows(() => inner(C, nop), TypeError);
+assertThrows(() => outer(C));
+
+%OptimizeFunctionOnNextCall(outer);
+assertThrows(() => outer(C));
+
+function ext() {}
+%NeverOptimizeFunction(ext);
+
+function cand1(a, b, c, d, e, f, o) {
+ if (a && b && c && d && e && f) return delete o[a];
+ return delete o[b];
+}
+
+function cand2() {
+ ext(); ext(); ext(); ext(); ext();
+ return %IsBeingInterpreted();
+}
+
+function caller(a, b, c, d, e, f, o) {
+ ext();
+ const r2 = cand2();
+ ext();
+ const r1 = cand1(a, b, c, d, e, f, o);
+ return r1 ? r2 : true;
+}
+
+const obj = {};
+%PrepareFunctionForOptimization(cand1);
+%PrepareFunctionForOptimization(cand2);
+%PrepareFunctionForOptimization(caller);
+assertTrue(caller(1, 2, true, true, true, true, obj));
+assertTrue(caller(0, 2, true, true, true, true, obj));
+%OptimizeFunctionOnNextCall(caller);
+assertFalse(caller(1, 2, true, true, true, true, obj));
diff --git a/deps/v8/test/mjsunit/compiler/regress-585625642.js b/deps/v8/test/mjsunit/compiler/regress-585625642.js
new file mode 100644
index 00000000000..7ab2fe7e786
--- /dev/null
+++ b/deps/v8/test/mjsunit/compiler/regress-585625642.js
@@ -0,0 +1,134 @@
+// 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.
+
+// Flags: --allow-natives-syntax
+
+// 1. JSLoadContextNoCell (depth = 0, 2, 3) and JSStoreContextNoCell (depth = 2)
+// inside resumable generator loops with a smaller inner BlockContext.
+function makeGenerator() {
+ {
+ let outer_mut = 0;
+ const outer_const = 100;
+ () => [outer_mut, outer_const];
+ {
+ let mid_block = 0;
+ () => mid_block;
+
+ return function* gen(opt, flag, val, k) {
+ const x0 = val, x1 = val, x2 = val, x3 = val, x4 = val,
+ x5 = val, x6 = val, x7 = val, x8 = val, x9 = val;
+ () => [x0, x1, x2, x3, x4, x5, x6, x7, x8, x9];
+ for (let i = 0; i < 2; i++) {
+ if (opt === 1) {
+ const a = x9;
+ const b = outer_const;
+ outer_mut = a;
+ return a + b;
+ }
+ do {
+ if (opt === 2) return x9 + mid_block;
+ if (!flag) {
+ if (val === null) return 0.1 + (k === null);
+ {
+ const s = val;
+ () => s;
+ const resumed = yield val;
+ if (val === undefined) return 0.1 + (k === null);
+ if (resumed !== undefined) return s + outer_mut;
+ }
+ }
+ if (opt === -1) continue;
+ break;
+ } while (true);
+ }
+ return x9;
+ };
+ }
+ }
+}
+
+const gen = makeGenerator();
+%PrepareFunctionForOptimization(gen);
+for (let i = 0; i < 10; i++) {
+ assertEquals({value: 142, done: true}, gen(1, false, 42, 1).next());
+ assertEquals({value: 42, done: true}, gen(2, false, 42, 1).next());
+ assertEquals({value: 1.1, done: true}, gen(0, false, null, null).next());
+
+ let g1 = gen(0, false, undefined, null);
+ assertEquals({value: undefined, done: false}, g1.next());
+ assertEquals({value: 1.1, done: true}, g1.next());
+
+ let g2 = gen(0, false, 7, 1);
+ assertEquals({value: 7, done: false}, g2.next());
+ assertEquals({value: 49, done: true}, g2.next('done'));
+
+ let g3 = gen(0, true, 9, 1);
+ assertEquals({value: 9, done: true}, g3.next());
+}
+
+%OptimizeFunctionOnNextCall(gen);
+
+assertEquals({value: 142, done: true}, gen(1, false, 42, 1).next());
+assertEquals({value: 42, done: true}, gen(2, false, 42, 1).next());
+assertEquals({value: 1.1, done: true}, gen(0, false, null, null).next());
+
+let g1 = gen(0, false, undefined, null);
+assertEquals({value: undefined, done: false}, g1.next());
+assertEquals({value: 1.1, done: true}, g1.next());
+
+let g2 = gen(0, false, 7, 1);
+assertEquals({value: 7, done: false}, g2.next());
+assertEquals({value: 49, done: true}, g2.next('done'));
+
+let g3 = gen(0, true, 9, 1);
+assertEquals({value: 9, done: true}, g3.next());
+
+let g = gen(0, false, 13, 1);
+assertEquals({value: 13, done: false}, g.next());
+assertEquals({value: 13, done: false}, g.next());
+assertEquals({value: 13, done: true}, g.next());
+
+// 2. JSHasContextExtension (depth = 0 and depth = 1 via
+// CheckContextExtensionsSlowPath when loop-header context is a Phi merging
+// FunctionContext and a smaller BlockContext).
+function makeSloppyLookupGenerator() {
+ {
+ let target = 55;
+ () => target;
+ {
+ let mid = 0;
+ () => mid;
+ return function* lookupGen(use_eval, opt, val) {
+ if (use_eval) eval('var shadowed = 1;');
+ for (let i = 0; i < 2; i++) {
+ if (opt) return target;
+ {
+ const s = val;
+ () => s;
+ yield s;
+ }
+ }
+ return target;
+ };
+ }
+ }
+}
+
+const lookupGen = makeSloppyLookupGenerator();
+%PrepareFunctionForOptimization(lookupGen);
+for (let i = 0; i < 10; i++) {
+ assertEquals({value: 55, done: true}, lookupGen(false, true, 3).next());
+ let lg = lookupGen(false, false, 3);
+ assertEquals({value: 3, done: false}, lg.next());
+ assertEquals({value: 3, done: false}, lg.next());
+ assertEquals({value: 55, done: true}, lg.next());
+}
+
+%OptimizeFunctionOnNextCall(lookupGen);
+
+assertEquals({value: 55, done: true}, lookupGen(false, true, 3).next());
+let lg = lookupGen(false, false, 8);
+assertEquals({value: 8, done: false}, lg.next());
+assertEquals({value: 8, done: false}, lg.next());
+assertEquals({value: 55, done: true}, lg.next());
diff --git a/deps/v8/test/mjsunit/mjsunit.status b/deps/v8/test/mjsunit/mjsunit.status
index 2993a48ee63..fe6529fcf5e 100644
--- a/deps/v8/test/mjsunit/mjsunit.status
+++ b/deps/v8/test/mjsunit/mjsunit.status
@@ -1292,6 +1292,7 @@
'regress/wasm/regress-325372946': [SKIP],
'regress/wasm/regress-326091470': [SKIP],
'regress/wasm/regress-326904344': [SKIP],
+ 'regress/wasm/regress-336507783': [SKIP],
'regress/wasm/regress-353582136': [SKIP],
'regress/wasm/regress-353913485': [SKIP],
'regress/wasm/regress-354324155*': [SKIP],
diff --git a/deps/v8/test/mjsunit/regress/regress-576957750.js b/deps/v8/test/mjsunit/regress/regress-576957750.js
new file mode 100644
index 00000000000..178c066aa7a
--- /dev/null
+++ b/deps/v8/test/mjsunit/regress/regress-576957750.js
@@ -0,0 +1,11 @@
+// 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.
+
+let re = /\d/g;
+const replacer = { toString() { re.lastIndex = 0; return ""; } };
+function foo(subject) {
+ re.lastIndex = -1;
+ return subject.replace(re, replacer);
+}
+assertEquals('abcdefg', foo('abcdefg1234567'));
diff --git a/deps/v8/test/mjsunit/regress/regress-577558169.js b/deps/v8/test/mjsunit/regress/regress-577558169.js
new file mode 100644
index 00000000000..e3c1928254f
--- /dev/null
+++ b/deps/v8/test/mjsunit/regress/regress-577558169.js
@@ -0,0 +1,89 @@
+// 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.
+
+// Flags: --allow-natives-syntax --turbolev
+
+(function TestDirectPartialTruncation() {
+ let escape;
+ const obj = { t: 2 };
+ const big_arr = new Array(0x100000).fill(1);
+ const small_arr = [1.1, 2.2];
+
+ function f(a, s, val) {
+ var x = a | 0;
+ if (x < 100 && small_arr.length > 1) {
+ var z2 = s.length * 8388608;
+ var small = x + (-4294967294);
+ var big = z2 + (-2147483647);
+ var sum1 = (small - big) | 0;
+ escape = big;
+ var dup_small = x + obj.t;
+ var dup = dup_small - big;
+ var v;
+ if ((x & 1) < 2) {
+ v = dup;
+ } else {
+ v = "str";
+ }
+ var r1 = big_arr[v];
+ small_arr[v] = val;
+ return (sum1 | 0) + r1;
+ }
+ return 0;
+ }
+
+ const warm_s = "a".repeat(256);
+ %PrepareFunctionForOptimization(f);
+ for (let i = 0; i < 100; i++) {
+ f(0.5, warm_s, 3.3);
+ }
+ %OptimizeFunctionOnNextCall(f);
+ f(-2147483648 + 100, "", 1.23456789e100);
+ assertEquals(102, small_arr.length);
+ assertEquals(1.23456789e100, small_arr[101]);
+})();
+
+(function TestTransitivePartialTruncation() {
+ let escape1, escape2;
+ const obj = { t: 2 };
+ const big_arr = new Array(0x100000).fill(1);
+ const small_arr = [1.1, 2.2];
+
+ function g(a, s1, s2, val) {
+ var x = a | 0;
+ if (x < 100 && small_arr.length > 1) {
+ var small = x + (-4294967294);
+ var big1 = s1.length * 4194304 + (-2147483646);
+ var big2 = s2.length * 4194304 + (-1);
+ var mid = small - big1;
+ var top = mid - big2;
+ var sum1 = top | 0;
+ escape1 = big1;
+ escape2 = big2;
+ var dup_small = x + obj.t;
+ var dup_mid = dup_small - big1;
+ var dup_top = dup_mid - big2;
+ var v;
+ if ((x & 1) < 2) {
+ v = dup_top;
+ } else {
+ v = "str";
+ }
+ var r1 = big_arr[v];
+ small_arr[v] = val;
+ return (sum1 | 0) + r1;
+ }
+ return 0;
+ }
+
+ const warm_s = "a".repeat(256);
+ %PrepareFunctionForOptimization(g);
+ for (let i = 0; i < 100; i++) {
+ g(0.5, warm_s, warm_s, 3.3);
+ }
+ %OptimizeFunctionOnNextCall(g);
+ g(-2147483648 + 100, "", "", 1.23456789e100);
+ assertEquals(102, small_arr.length);
+ assertEquals(1.23456789e100, small_arr[101]);
+})();
diff --git a/deps/v8/test/mjsunit/regress/regress-584005343.js b/deps/v8/test/mjsunit/regress/regress-584005343.js
index a4b3e3a025b..58647f9c2c8 100644
--- a/deps/v8/test/mjsunit/regress/regress-584005343.js
+++ b/deps/v8/test/mjsunit/regress/regress-584005343.js
@@ -78,13 +78,28 @@
}
}
+ // Under --gc-stress (--verify-heap --stress-compaction), every StackOverflow
+ // triggers a full-heap GC and stack walk. Use 64 dummy parameters (~568 bytes
+ // per frame) to keep max recursion depth low, and only attempt compilation
+ // every 32 unwinding frames (~18 KB) so we hit the window where Outer.run
+ // compiles (~42 KB) while the inner <instance_members_initializer> overflows
+ // (>120 KB) in a handful of StackOverflow calls instead of hundreds.
let compiled = false;
- function probe() {
+ function probe(
+ d,
+ a00, a01, a02, a03, a04, a05, a06, a07,
+ a08, a09, a10, a11, a12, a13, a14, a15,
+ a16, a17, a18, a19, a20, a21, a22, a23,
+ a24, a25, a26, a27, a28, a29, a30, a31,
+ a32, a33, a34, a35, a36, a37, a38, a39,
+ a40, a41, a42, a43, a44, a45, a46, a47,
+ a48, a49, a50, a51, a52, a53, a54, a55,
+ a56, a57, a58, a59, a60, a61, a62, a63) {
try {
- probe();
+ probe(d + 1);
} catch (e) {
}
- if (!compiled) {
+ if (!compiled && d % 32 === 0) {
try {
Outer.run(null);
compiled = true;
@@ -92,7 +107,7 @@
}
}
}
- probe();
+ probe(0);
assertEquals(42, Outer.run(new Outer()));
}
diff --git a/deps/v8/test/mjsunit/regress/wasm/regress-336507783.js b/deps/v8/test/mjsunit/regress/wasm/regress-336507783.js
new file mode 100644
index 00000000000..adf59856573
--- /dev/null
+++ b/deps/v8/test/mjsunit/regress/wasm/regress-336507783.js
@@ -0,0 +1,236 @@
+// 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.
+
+// Flags: --allow-natives-syntax --no-wasm-inlining --expose-gc
+
+d8.file.execute('test/mjsunit/wasm/wasm-module-builder.js');
+
+(function TestDecompressTaggedParamsAndReturns() {
+ const builder = new WasmModuleBuilder();
+ const struct = builder.addStruct([
+ makeField(kWasmI32, true),
+ makeField(kWasmAnyRef, true),
+ ]);
+ const structRef = wasmRefNullType(struct);
+
+ // Callee returning 1 tagged value (in register) and 4 tagged values (in
+ // registers + on the stack).
+ const sigSingleRet = builder.addType(makeSig([kWasmI32], [structRef]));
+ const sigMultiRet = builder.addType(
+ makeSig([kWasmI32], [structRef, structRef, structRef, structRef]));
+
+ // Callee taking 8 tagged parameters (covering both register and stack
+ // parameter locations) mixed with untagged parameters.
+ // - Some parameters are dereferenced via `struct.get` (requiring full
+ // 64-bit pointer decompression).
+ // - Other parameters are only stored into a tagged struct field via
+ // `struct.set` or compared via `ref.eq` (exercising the Turboshaft
+ // decompression optimization), including across a call that triggers GC.
+ const sigManyParams = builder.addType(makeSig(
+ [
+ structRef, kWasmI32, structRef, structRef, structRef, structRef,
+ structRef, structRef, structRef,
+ ],
+ [kWasmI32]));
+
+ const impGcAndCount = builder.addImport('m', 'gcAndCount', sigManyParams);
+
+ const makeStruct = builder.addFunction('makeStruct', sigSingleRet)
+ .addBody([
+ kExprLocalGet, 0,
+ kExprRefNull, struct,
+ kGCPrefix, kExprStructNew, struct,
+ ])
+ .exportFunc();
+
+ const makeStructs4 = builder.addFunction('makeStructs4', sigMultiRet)
+ .addBody([
+ kExprLocalGet, 0,
+ kExprRefNull, struct,
+ kGCPrefix, kExprStructNew, struct,
+ kExprLocalGet, 0,
+ kExprI32Const, 1,
+ kExprI32Add,
+ kExprRefNull, struct,
+ kGCPrefix, kExprStructNew, struct,
+ kExprLocalGet, 0,
+ kExprI32Const, 2,
+ kExprI32Add,
+ kExprRefNull, struct,
+ kGCPrefix, kExprStructNew, struct,
+ kExprLocalGet, 0,
+ kExprI32Const, 3,
+ kExprI32Add,
+ kExprRefNull, struct,
+ kGCPrefix, kExprStructNew, struct,
+ ])
+ .exportFunc();
+
+ const consumeParams = builder.addFunction('consumeParams', sigManyParams)
+ .addBody([
+ // Call imported JS function first (triggering GC while incoming stack
+ // parameters and spilled compressed/uncompressed parameters are live).
+ kExprLocalGet, 0,
+ kExprLocalGet, 1,
+ kExprLocalGet, 0,
+ kExprLocalGet, 0,
+ kExprLocalGet, 0,
+ kExprLocalGet, 0,
+ kExprLocalGet, 6,
+ kExprLocalGet, 0,
+ kExprLocalGet, 8,
+ kExprCallFunction, impGcAndCount,
+ kExprDrop,
+ // Store param 7 (stack param) and param 2 (register param) into param 0
+ // without dereferencing them (compressed uses only, live across the
+ // GC-triggering import call above).
+ kExprLocalGet, 0,
+ kExprLocalGet, 7,
+ kGCPrefix, kExprStructSet, struct, 1,
+ kExprLocalGet, 3,
+ kExprLocalGet, 2,
+ kGCPrefix, kExprStructSet, struct, 1,
+ // Compare param 4 and param 5 via ref.eq (compressed use only).
+ kExprLocalGet, 4,
+ kExprLocalGet, 5,
+ kExprRefEq,
+ // Dereference param 0, param 6 (stack), and param 8 (stack).
+ kExprLocalGet, 0,
+ kGCPrefix, kExprStructGet, struct, 0,
+ kExprI32Add,
+ kExprLocalGet, 1,
+ kExprI32Add,
+ kExprLocalGet, 6,
+ kGCPrefix, kExprStructGet, struct, 0,
+ kExprI32Add,
+ kExprLocalGet, 8,
+ kGCPrefix, kExprStructGet, struct, 0,
+ kExprI32Add,
+ ])
+ .exportFunc();
+
+ const tableSingle = builder.addTable(wasmRefNullType(sigSingleRet), 1, 1);
+ builder.addActiveElementSegment(
+ tableSingle.index, wasmI32Const(0),
+ [[kExprRefFunc, makeStruct.index]], wasmRefNullType(sigSingleRet));
+
+ const tableMulti = builder.addTable(wasmRefNullType(sigMultiRet), 1, 1);
+ builder.addActiveElementSegment(
+ tableMulti.index, wasmI32Const(0),
+ [[kExprRefFunc, makeStructs4.index]], wasmRefNullType(sigMultiRet));
+
+ // Indirect tail call (`kExprReturnCallIndirect`) returning a single tagged
+ // reference.
+ const testTailCallIndirect =
+ builder.addFunction('testTailCallIndirect', sigSingleRet)
+ .addBody([
+ kExprLocalGet, 0,
+ kExprI32Const, 0,
+ kExprReturnCallIndirect, sigSingleRet, tableSingle.index,
+ ])
+ .exportFunc();
+
+ // Caller testing direct calls (`kExprCallFunction`, including to a function
+ // that performs an indirect tail call) and indirect calls
+ // (`kExprCallIndirect`) with both dereferenced and compressed-only uses of
+ // single and multi-value tagged returns.
+ builder.addFunction('testCalls', makeSig([kWasmI32], [kWasmI32]))
+ .addLocals(structRef, 5)
+ .addBody([
+ // 1. Direct call (`kExprCallFunction`) to a function with an indirect
+ // tail call, single tagged return.
+ kExprLocalGet, 0,
+ kExprCallFunction, testTailCallIndirect.index,
+ kExprLocalTee, 1,
+ kGCPrefix, kExprStructGet, struct, 0,
+
+ // 2. Indirect call (`kExprCallIndirect`), single tagged return
+ // dereferenced.
+ kExprLocalGet, 0,
+ kExprI32Const, 0,
+ kExprCallIndirect, sigSingleRet, tableSingle.index,
+ kGCPrefix, kExprStructGet, struct, 0,
+ kExprI32Add,
+
+ // 3. Indirect call (`kExprCallIndirect`), single tagged return only
+ // stored into a struct field (compressed use optimization).
+ kExprLocalGet, 1,
+ kExprLocalGet, 0,
+ kExprI32Const, 0,
+ kExprCallIndirect, sigSingleRet, tableSingle.index,
+ kGCPrefix, kExprStructSet, struct, 1,
+
+ // 4. Indirect call (`kExprCallIndirect`), 4 tagged returns (register +
+ // stack return slots), mixing dereferenced and compressed-only uses.
+ kExprLocalGet, 0,
+ kExprI32Const, 0,
+ kExprCallIndirect, sigMultiRet, tableMulti.index,
+ kExprLocalSet, 5, // stack return: dereferenced below
+ kExprLocalSet, 4, // stack return: stored as compressed below
+ kExprLocalSet, 3, // reg return: stored as compressed below
+ kExprLocalSet, 2, // reg return: dereferenced below
+
+ kExprLocalGet, 1,
+ kExprLocalGet, 3,
+ kGCPrefix, kExprStructSet, struct, 1,
+ kExprLocalGet, 2,
+ kExprLocalGet, 4,
+ kGCPrefix, kExprStructSet, struct, 1,
+
+ kExprLocalGet, 2,
+ kGCPrefix, kExprStructGet, struct, 0,
+ kExprI32Add,
+ kExprLocalGet, 5,
+ kGCPrefix, kExprStructGet, struct, 0,
+ kExprI32Add,
+
+ // 5. Pass 8 tagged arguments to `consumeParams` (without using locals 3
+ // and 4, so locals 3 and 4 remain compressed-only uses).
+ kExprLocalGet, 1,
+ kExprLocalGet, 0,
+ kExprLocalGet, 2,
+ kExprLocalGet, 1,
+ kExprLocalGet, 2,
+ kExprLocalGet, 2,
+ kExprLocalGet, 5,
+ kExprLocalGet, 2,
+ kExprLocalGet, 5,
+ kExprCallFunction, consumeParams.index,
+ kExprI32Add,
+ ])
+ .exportFunc();
+
+ let gcCount = 0;
+ function gcAndCount(a0, i1, a2, a3, a4, a5, a6, a7, a8) {
+ if (gcCount++ < 4) gc();
+ assertSame(a0, a2);
+ assertNotNull(a8);
+ return i1;
+ }
+
+ const instance = builder.instantiate({m: {gcAndCount}});
+
+ // Run in Liftoff first, then tier up to Turboshaft.
+ assertEquals(90, instance.exports.testCalls(10));
+ const s1 = instance.exports.testTailCallIndirect(42);
+ const multi1 = instance.exports.makeStructs4(10);
+ assertEquals(4, multi1.length);
+ assertEquals(
+ 128,
+ instance.exports.consumeParams(s1, 1, s1, s1, s1, s1, s1, s1, s1));
+
+ %WasmTierUpFunction(instance.exports.consumeParams);
+ %WasmTierUpFunction(instance.exports.testCalls);
+ %WasmTierUpFunction(instance.exports.testTailCallIndirect);
+ %WasmTierUpFunction(instance.exports.makeStruct);
+ %WasmTierUpFunction(instance.exports.makeStructs4);
+
+ assertEquals(90, instance.exports.testCalls(10));
+ const s2 = instance.exports.testTailCallIndirect(42);
+ const multi2 = instance.exports.makeStructs4(20);
+ assertEquals(4, multi2.length);
+ assertEquals(
+ 128,
+ instance.exports.consumeParams(s2, 1, s2, s2, s2, s2, s2, s2, s2));
+})();
diff --git a/deps/v8/test/mjsunit/regress/wasm/regress-simd-581561827.js b/deps/v8/test/mjsunit/regress/wasm/regress-simd-581561827.js
new file mode 100644
index 00000000000..8ab2b26eb95
--- /dev/null
+++ b/deps/v8/test/mjsunit/regress/wasm/regress-simd-581561827.js
@@ -0,0 +1,98 @@
+// 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.
+
+// Flags: --allow-natives-syntax --no-debug-code
+
+// Regression test for b/581561827: JumpThreading must not forward a
+// gap-jump block to the function entry block (B0) when B0 constructs a frame,
+// as branching back to B0 re-executes AssembleConstructFrame() and corrupts
+// the stack frame.
+
+d8.file.execute('test/mjsunit/wasm/wasm-module-builder.js');
+
+const builder = new WasmModuleBuilder();
+const id_mask = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
+
+const g = builder.addGlobal(kWasmI32, true, false);
+const sig_index = builder.addType(makeSig([kWasmS128, kWasmS128], [kWasmI32]));
+
+const leaf = builder.addFunction('leaf', sig_index)
+ .addLocals(kWasmS128, 2) // local 2 = x, local 3 = tmp
+ .addBody([
+ // Entry block B0: leaf elides kFunctionEntry stack check, so B0 contains
+ // only a ParallelMove (vmovapd xmm0, xmm2) + kArchJmp to the loop header,
+ // while FrameElider sets B0->must_construct_frame() due to kLoop check.
+ kExprLocalGet, 1,
+ kExprLocalGet, 0,
+ ...SimdInstr(kExprI8x16Shuffle), ...id_mask,
+ kExprLocalSet, 2,
+
+ kExprBlock, kWasmI32,
+ kExprLoop, kWasmVoid,
+ kExprGlobalGet, g.index,
+ kExprI32Const, 0,
+ kExprI32LeS,
+ kExprIf, kWasmVoid,
+ kExprLocalGet, 2,
+ ...SimdInstr(kExprI32x4ExtractLane), 0,
+ kExprBr, 2,
+ kExprEnd,
+
+ // Ensure param 1 (b) interferes with loop phi x.
+ kExprLocalGet, 2,
+ kExprLocalGet, 1,
+ ...SimdInstr(kExprI32x4Add),
+ kExprLocalSet, 3,
+
+ kExprGlobalGet, g.index,
+ kExprI32Const, 1,
+ kExprI32Sub,
+ kExprGlobalSet, g.index,
+
+ // Two backedges converging at the loop-merge block allow
+ // MoveOptimizer::OptimizeMerge to bail out at the loop header and then
+ // hoist the shared gap move into the merge block, leaving B0 and the
+ // loop backedge with identical gap moves targeting the loop header.
+ kExprGlobalGet, g.index,
+ kExprI32Const, 1,
+ kExprI32And,
+ kExprIf, kWasmVoid,
+ kExprLocalGet, 1,
+ kExprLocalGet, 3,
+ ...SimdInstr(kExprI8x16Shuffle), ...id_mask,
+ kExprLocalSet, 2,
+ kExprBr, 1,
+ kExprElse,
+ kExprLocalGet, 1,
+ kExprLocalGet, 3,
+ kExprLocalGet, 0,
+ ...SimdInstr(kExprI32x4Add),
+ ...SimdInstr(kExprI8x16Shuffle), ...id_mask,
+ kExprLocalSet, 2,
+ kExprBr, 1,
+ kExprEnd,
+ kExprUnreachable,
+ kExprEnd,
+ kExprI32Const, 0,
+ kExprEnd,
+ ])
+ .exportFunc();
+
+const table = builder.addTable(kWasmAnyFunc, 1, 1);
+builder.addActiveElementSegment(table.index, wasmI32Const(0), [leaf.index]);
+
+builder.addFunction('main', makeSig([kWasmI32, kWasmI32], [kWasmI32]))
+ .addBody([
+ kExprLocalGet, 0,
+ kExprGlobalSet, g.index,
+ kExprI32Const, 7, ...SimdInstr(kExprI32x4Splat),
+ kExprI32Const, 11, ...SimdInstr(kExprI32x4Splat),
+ kExprLocalGet, 1,
+ kExprCallIndirect, sig_index, table.index,
+ ])
+ .exportFunc();
+
+const instance = builder.instantiate();
+%WasmTierUpFunction(instance.exports.leaf);
+assertEquals(11, instance.exports.main(100, 0));
diff --git a/deps/v8/test/mjsunit/sandbox/regress-581561328.js b/deps/v8/test/mjsunit/sandbox/regress-581561328.js
new file mode 100644
index 00000000000..903480aacd8
--- /dev/null
+++ b/deps/v8/test/mjsunit/sandbox/regress-581561328.js
@@ -0,0 +1,138 @@
+// 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.
+
+// Flags: --sandbox-testing --allow-natives-syntax
+// Flags: --turbofan --no-turbolev --no-optimize-on-next-call-optimizes-to-maglev
+
+const memory = new DataView(new Sandbox.MemoryView(0, 0x100000000));
+const field = (type, name) =>
+ Sandbox.getFieldOffset(Sandbox.getInstanceTypeIdFor(type), name);
+const dispatchOffset = field('JS_FUNCTION_TYPE', 'dispatch_handle');
+const sharedOffset = field('JS_FUNCTION_TYPE', 'shared_function_info');
+const formalCountOffset =
+ field('SHARED_FUNCTION_INFO_TYPE', 'formal_parameter_count');
+const cellOffset = field('JS_FUNCTION_TYPE', 'feedback_cell');
+const valueOffset = field('FEEDBACK_CELL_TYPE', 'value');
+
+function address(object) {
+ return Sandbox.getAddressOf(object) >>> 0;
+}
+function read32(location) {
+ return memory.getUint32(location, true);
+}
+function write32(location, value) {
+ memory.setUint32(location, value >>> 0, true);
+}
+function dispatch(fn) {
+ return read32(address(fn) + dispatchOffset);
+}
+function shared(fn) {
+ return (read32(address(fn) + sharedOffset) - 1) >>> 0;
+}
+function cell(fn) {
+ return (read32(address(fn) + cellOffset) - 1) >>> 0;
+}
+function setDispatch(fn, handle) {
+ write32(address(fn) + dispatchOffset, handle);
+}
+function setFormalCount(fn, value) {
+ memory.setUint16(shared(fn) + formalCountOffset, value, true);
+}
+
+const undefinedTagged = (address(undefined) + 1) >>> 0;
+const retained = [];
+
+function raceSourceTarget() {
+ return 7;
+}
+function reader() {
+ return raceSourceTarget();
+}
+function makeTarget(q0, q1, q2, q3, q4, q5, q6, q7) {
+ let target;
+ for (let i = 0; i < 2; ++i) {
+ target = function targetChild(q0, q1, q2, q3, q4, q5, q6, q7) {
+ q5 = q4;
+ return 0x4242;
+ };
+ }
+ const spare = function(q0, q1, q2, q3, q4, q5, q6, q7) {};
+ return [spare, target];
+}
+
+%NeverOptimizeFunction(raceSourceTarget);
+%EnsureFeedbackVectorForFunction(raceSourceTarget);
+%NeverOptimizeFunction(makeTarget);
+%PrepareFunctionForOptimization(reader);
+reader();
+reader();
+
+const initialPair = makeTarget();
+let donor = initialPair[0];
+const initialTarget = initialPair[1];
+%NeverOptimizeFunction(initialTarget);
+%CompileBaseline(initialTarget);
+initialTarget();
+retained.push(donor, initialTarget);
+
+function newTarget() {
+ write32(cell(makeTarget) + valueOffset, undefinedTagged);
+ setDispatch(makeTarget, dispatch(donor));
+ const pair = makeTarget();
+ donor = pair[0];
+ retained.push(pair[0], pair[1]);
+ return pair[1];
+}
+%NeverOptimizeFunction(newTarget);
+
+const sab = new SharedArrayBuffer(4);
+const sync = new Int32Array(sab);
+const worker = new Worker(function() {
+ onmessage = function(msg) {
+ const sync = new Int32Array(msg.data ?? msg);
+ Atomics.store(sync, 0, 1);
+ Atomics.notify(sync, 0);
+ Atomics.wait(sync, 0, 1);
+
+ %BlockAt("JSDispatchEntryMake", 10000);
+ %BlockAt("TurboshaftAfterAssembleCode", 10000);
+ Atomics.store(sync, 0, 3);
+ Atomics.notify(sync, 0);
+
+ %WaitUntilBlocked("JSDispatchEntryMake", 10000);
+ %Resume("TurboshaftAssembleCode");
+ %WaitUntilBlocked("TurboshaftAfterAssembleCode", 10000);
+ %Resume("TurboshaftAfterAssembleCode");
+ %Resume("JSDispatchEntryMake");
+ };
+}, {type: 'function'});
+
+worker.postMessage(sab);
+Atomics.wait(sync, 0, 0);
+
+newTarget();
+while (((dispatch(donor) >>> 8) & 2047) >= 2045) {
+ newTarget();
+}
+const wantedHandle = ((dispatch(donor) >>> 8) + 1) << 8;
+
+setFormalCount(raceSourceTarget, 0);
+setDispatch(raceSourceTarget, dispatch(Number));
+
+%BlockAt("TurboshaftAssembleCode", 10000);
+%OptimizeFunctionOnNextCall(reader, "concurrent");
+reader();
+%WaitUntilBlocked("TurboshaftAssembleCode", 10000);
+
+setDispatch(raceSourceTarget, wantedHandle);
+
+Atomics.store(sync, 0, 2);
+Atomics.notify(sync, 0);
+Atomics.wait(sync, 0, 2);
+
+newTarget();
+
+%WaitForBackgroundOptimization();
+memory.setInt32(cell(raceSourceTarget) + valueOffset + 8, 0x10000000, true);
+reader();
diff --git a/deps/v8/test/mjsunit/sandbox/regress/regress-579314138-1.js b/deps/v8/test/mjsunit/sandbox/regress/regress-579314138-1.js
new file mode 100644
index 00000000000..362f2b4bec9
--- /dev/null
+++ b/deps/v8/test/mjsunit/sandbox/regress/regress-579314138-1.js
@@ -0,0 +1,39 @@
+// 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.
+
+// Flags: --sandbox-testing
+
+if (typeof Intl !== 'undefined') {
+ // Build a ConsString DAG of 3-byte UTF-8 code units (U+0800) with >= 2^31
+ // virtual characters, keeping intermediate lengths small so JS string
+ // concatenation does not reject them.
+ let s = '\u0800'.repeat(16);
+ for (let i = 0; i < 27; i++) {
+ s = s + s;
+ Sandbox.corruptObjectField(s, 'length', 32);
+ }
+ // 0x55555555 * 3 == 0xFFFFFFFF UTF-8 bytes, which truncates to -1 in ICU's
+ // 32-bit signed StringPiece length.
+ Sandbox.corruptObjectField(s, 'length', 0x55555555);
+
+ const kHeapObjectTag = 1;
+ const taggedOf = obj => Sandbox.getAddressOf(obj) + kHeapObjectTag;
+
+ const fmt = new Intl.NumberFormat('en-US');
+ const expectedLocaleTagged = taggedOf(fmt.resolvedOptions().locale);
+ const fmtSize = Sandbox.getSizeOf(fmt);
+ let localeOffset = -1;
+ for (let offset = 0; offset < fmtSize; offset += 4) {
+ if (Sandbox.readObjectField(fmt, offset, 32) === expectedLocaleTagged) {
+ localeOffset = offset;
+ break;
+ }
+ }
+ assertTrue(localeOffset >= 0);
+
+ Sandbox.corruptObjectField(fmt, localeOffset, taggedOf(s));
+
+ fmt.formatRange(1, 2);
+ assertUnreachable('Corrupted String length should be caught by SBXCHECK');
+}
diff --git a/deps/v8/test/mjsunit/sandbox/regress/regress-579314138-2.js b/deps/v8/test/mjsunit/sandbox/regress/regress-579314138-2.js
new file mode 100644
index 00000000000..6a8b6fcbd0d
--- /dev/null
+++ b/deps/v8/test/mjsunit/sandbox/regress/regress-579314138-2.js
@@ -0,0 +1,19 @@
+// 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.
+
+// Flags: --sandbox-testing --allow-natives-syntax
+
+let s = '\u0800'.repeat(16);
+for (let i = 0; i < 27; i++) {
+ s = s + s;
+ Sandbox.corruptObjectField(s, 'length', 32);
+}
+Sandbox.corruptObjectField(s, 'length', 0x55555555);
+
+if (typeof Intl !== 'undefined') {
+ new Intl.DisplayNames('en', {type: 'language'}).of(s);
+} else {
+ %StringToCString(s);
+}
+assertUnreachable('Corrupted String length should be caught by SBXCHECK');
diff --git a/deps/v8/test/mjsunit/sandbox/regress/regress-582143775.js b/deps/v8/test/mjsunit/sandbox/regress/regress-582143775.js
new file mode 100644
index 00000000000..ebefc73f364
--- /dev/null
+++ b/deps/v8/test/mjsunit/sandbox/regress/regress-582143775.js
@@ -0,0 +1,44 @@
+// 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.
+
+// Flags: --sandbox-testing
+
+d8.file.execute('test/mjsunit/wasm/wasm-module-builder.js');
+
+const builder = new WasmModuleBuilder();
+const $sig = builder.addType(kSig_v_v);
+const $f0 = builder.addFunction('f0', $sig).addBody([]);
+
+builder.addTable(wasmRefType($sig), 1, 1, [kExprRefFunc, $f0.index])
+ .exportAs('table0');
+builder.addTable(wasmRefNullType($sig), 1, 1)
+ .exportAs('table1');
+
+const instance = builder.instantiate();
+const {table0, table1} = instance.exports;
+
+const kHeapObjectTag = 1;
+const kWasmTableType = Sandbox.getInstanceTypeIdFor('WASM_TABLE_OBJECT_TYPE');
+const kWasmTableRawTypeOffset =
+ Sandbox.getFieldOffset(kWasmTableType, 'raw_type');
+const memory = new DataView(new Sandbox.MemoryView(0, 0x100000000));
+
+function getPtr(obj) {
+ return Sandbox.getAddressOf(obj) + kHeapObjectTag;
+}
+function getField(obj, offset) {
+ return memory.getUint32(obj + offset - kHeapObjectTag, true);
+}
+function setField(obj, offset, value) {
+ memory.setUint32(obj + offset - kHeapObjectTag, value, true);
+}
+
+// Corrupt non-nullable table0's in-sandbox raw_type to be nullable.
+const nullable_raw_type = getField(getPtr(table1), kWasmTableRawTypeOffset);
+setField(getPtr(table0), kWasmTableRawTypeOffset, nullable_raw_type);
+
+// Clearing an entry in a non-nullable WasmDispatchTable must fail an SBXCHECK.
+table0.set(0, null);
+
+assertUnreachable('Process should have been killed.');
diff --git a/deps/v8/test/unittests/common/thread-isolation-unittest.cc b/deps/v8/test/unittests/common/thread-isolation-unittest.cc
index 64dd6a8eef4..3f48254a147 100644
--- a/deps/v8/test/unittests/common/thread-isolation-unittest.cc
+++ b/deps/v8/test/unittests/common/thread-isolation-unittest.cc
@@ -8,6 +8,8 @@
namespace v8 {
namespace internal {
+using JitAllocationType = ThreadIsolation::JitAllocationType;
+
void InitializeThreadIsolation() {
// We don't provide a pkey allocator for the tests in this file, so we need to
// disable the force_memory_protection_keys flag.
@@ -55,14 +57,18 @@ TEST(ThreadIsolation, JitAllocation) {
Address address2 = address1 + size;
ThreadIsolation::RegisterJitPage(address2, size);
- ThreadIsolation::RegisterJitAllocationForTesting(address2 + size - 1, 1);
- ThreadIsolation::RegisterJitAllocationForTesting(address1, 1);
+ ThreadIsolation::RegisterJitAllocationForTesting(
+ address2 + size - 1, 1, JitAllocationType::kInstructionStream);
+ ThreadIsolation::RegisterJitAllocationForTesting(
+ address1, 1, JitAllocationType::kInstructionStream);
// An allocation spanning two pages.
- ThreadIsolation::RegisterJitAllocationForTesting(address2 - 1, 2);
+ ThreadIsolation::RegisterJitAllocationForTesting(
+ address2 - 1, 2, JitAllocationType::kInstructionStream);
ThreadIsolation::UnregisterJitPage(address1, size);
// The spanning allocation should've been released, try to reuse the memory.
- ThreadIsolation::RegisterJitAllocationForTesting(address2, 1);
+ ThreadIsolation::RegisterJitAllocationForTesting(
+ address2, 1, JitAllocationType::kInstructionStream);
ThreadIsolation::UnregisterJitPage(address2, size);
}
@@ -73,7 +79,10 @@ TEST(ThreadIsolation, CatchOOBJitAllocation) {
size_t size = 0x1000;
ThreadIsolation::RegisterJitPage(address1, size);
EXPECT_DEATH_IF_SUPPORTED(
- { ThreadIsolation::RegisterJitAllocationForTesting(address1 + size, 1); },
+ {
+ ThreadIsolation::RegisterJitAllocationForTesting(
+ address1 + size, 1, JitAllocationType::kInstructionStream);
+ },
"");
ThreadIsolation::UnregisterJitPage(address1, size);
}
@@ -90,14 +99,16 @@ TEST(ThreadIsolation, MergeJitPages) {
ThreadIsolation::RegisterJitPage(address1, size);
ThreadIsolation::RegisterJitPage(address3, size);
- ThreadIsolation::RegisterJitAllocationForTesting(address1, 3 * size);
+ ThreadIsolation::RegisterJitAllocationForTesting(
+ address1, 3 * size, JitAllocationType::kInstructionStream);
ThreadIsolation::UnregisterJitAllocationForTesting(address1, 3 * size);
// Test merge in both directions
ThreadIsolation::UnregisterJitPage(address2, size);
ThreadIsolation::RegisterJitPage(address2, size);
- ThreadIsolation::RegisterJitAllocationForTesting(address1, 3 * size);
+ ThreadIsolation::RegisterJitAllocationForTesting(
+ address1, 3 * size, JitAllocationType::kInstructionStream);
ThreadIsolation::UnregisterJitAllocationForTesting(address1, 3 * size);
ThreadIsolation::UnregisterJitPage(address2, size);
@@ -116,11 +127,16 @@ TEST(ThreadIsolation, FreeRange) {
ThreadIsolation::RegisterJitPage(address2, size);
ThreadIsolation::RegisterJitPage(address3, size);
- ThreadIsolation::RegisterJitAllocationForTesting(address2 - 1, 1);
- ThreadIsolation::RegisterJitAllocationForTesting(address2, 1);
- ThreadIsolation::RegisterJitAllocationForTesting(address2 + 1, size - 2);
- ThreadIsolation::RegisterJitAllocationForTesting(address3 - 1, 1);
- ThreadIsolation::RegisterJitAllocationForTesting(address3, 1);
+ ThreadIsolation::RegisterJitAllocationForTesting(
+ address2 - 1, 1, JitAllocationType::kInstructionStream);
+ ThreadIsolation::RegisterJitAllocationForTesting(
+ address2, 1, JitAllocationType::kInstructionStream);
+ ThreadIsolation::RegisterJitAllocationForTesting(
+ address2 + 1, size - 2, JitAllocationType::kInstructionStream);
+ ThreadIsolation::RegisterJitAllocationForTesting(
+ address3 - 1, 1, JitAllocationType::kInstructionStream);
+ ThreadIsolation::RegisterJitAllocationForTesting(
+ address3, 1, JitAllocationType::kInstructionStream);
{
WritableJitPage jit_page(address2, size);
@@ -157,7 +173,8 @@ TEST(ThreadIsolation, InvalidFreeRange) {
size_t size = 0x1000;
ThreadIsolation::RegisterJitPage(address1, size);
- ThreadIsolation::RegisterJitAllocationForTesting(address1, 2);
+ ThreadIsolation::RegisterJitAllocationForTesting(
+ address1, 2, JitAllocationType::kInstructionStream);
{
WritableJitPage jit_page(address1, size);
@@ -181,46 +198,84 @@ TEST(ThreadIsolation, TryLookupStartOfJitAllocationAt) {
Address alloc1 = address1 + 0x100;
size_t alloc1_size = 0x80;
- ThreadIsolation::RegisterJitAllocationForTesting(alloc1, alloc1_size);
+ ThreadIsolation::RegisterJitAllocationForTesting(
+ alloc1, alloc1_size, JitAllocationType::kInstructionStream);
Address alloc2 = address2 + 0x200;
size_t alloc2_size = 0x40;
- ThreadIsolation::RegisterJitAllocationForTesting(alloc2, alloc2_size);
+ ThreadIsolation::RegisterJitAllocationForTesting(
+ alloc2, alloc2_size, JitAllocationType::kInstructionStream);
+
+ Address wasm_alloc = address1 + 0x300;
+ size_t wasm_alloc_size = 0x60;
+ ThreadIsolation::RegisterJitAllocationForTesting(
+ wasm_alloc, wasm_alloc_size, JitAllocationType::kWasmCode);
// Outside any JIT page.
- EXPECT_EQ(ThreadIsolation::TryLookupStartOfJitAllocationAt(address1 - 1),
+ EXPECT_EQ(ThreadIsolation::TryLookupStartOfJitAllocationAt(
+ address1 - 1, JitAllocationType::kInstructionStream),
std::nullopt);
- EXPECT_EQ(ThreadIsolation::TryLookupStartOfJitAllocationAt(address1 + size),
+ EXPECT_EQ(ThreadIsolation::TryLookupStartOfJitAllocationAt(
+ address1 + size, JitAllocationType::kInstructionStream),
std::nullopt);
// Inside JIT page 1, outside alloc1.
- EXPECT_EQ(ThreadIsolation::TryLookupStartOfJitAllocationAt(address1),
+ EXPECT_EQ(ThreadIsolation::TryLookupStartOfJitAllocationAt(
+ address1, JitAllocationType::kInstructionStream),
std::nullopt);
- EXPECT_EQ(ThreadIsolation::TryLookupStartOfJitAllocationAt(alloc1 - 1),
+ EXPECT_EQ(ThreadIsolation::TryLookupStartOfJitAllocationAt(
+ alloc1 - 1, JitAllocationType::kInstructionStream),
+ std::nullopt);
+ EXPECT_EQ(ThreadIsolation::TryLookupStartOfJitAllocationAt(
+ alloc1 + alloc1_size, JitAllocationType::kInstructionStream),
std::nullopt);
- EXPECT_EQ(
- ThreadIsolation::TryLookupStartOfJitAllocationAt(alloc1 + alloc1_size),
- std::nullopt);
// Inside alloc1.
- EXPECT_EQ(ThreadIsolation::TryLookupStartOfJitAllocationAt(alloc1), alloc1);
- EXPECT_EQ(ThreadIsolation::TryLookupStartOfJitAllocationAt(alloc1 + 1),
+ EXPECT_EQ(ThreadIsolation::TryLookupStartOfJitAllocationAt(
+ alloc1, JitAllocationType::kInstructionStream),
+ alloc1);
+ EXPECT_EQ(ThreadIsolation::TryLookupStartOfJitAllocationAt(
+ alloc1 + 1, JitAllocationType::kInstructionStream),
alloc1);
- EXPECT_EQ(ThreadIsolation::TryLookupStartOfJitAllocationAt(alloc1 +
- alloc1_size - 1),
+ EXPECT_EQ(
+ ThreadIsolation::TryLookupStartOfJitAllocationAt(
+ alloc1 + alloc1_size - 1, JitAllocationType::kInstructionStream),
+ alloc1);
+ EXPECT_EQ(ThreadIsolation::StartOfJitAllocationAt(
+ alloc1, JitAllocationType::kInstructionStream),
alloc1);
+ // Looking for kInstructionStream skips Wasm allocations.
+ EXPECT_EQ(ThreadIsolation::TryLookupStartOfJitAllocationAt(
+ wasm_alloc, JitAllocationType::kInstructionStream),
+ std::nullopt);
+ EXPECT_EQ(ThreadIsolation::StartOfJitAllocationAt(
+ wasm_alloc, JitAllocationType::kInstructionStream),
+ std::nullopt);
+
+ // Explicit type lookup succeeds for matching type.
+ EXPECT_EQ(ThreadIsolation::TryLookupStartOfJitAllocationAt(
+ wasm_alloc, JitAllocationType::kWasmCode),
+ wasm_alloc);
+ EXPECT_EQ(ThreadIsolation::StartOfJitAllocationAt(
+ wasm_alloc, JitAllocationType::kWasmCode),
+ wasm_alloc);
+
// While page 1 is locked (e.g., on the interrupted thread), looking up on
// page 1 returns std::nullopt instead of deadlocking, while looking up on
// page 2 still succeeds.
{
WritableJitPage locked_page1(address1, size);
- EXPECT_EQ(ThreadIsolation::TryLookupStartOfJitAllocationAt(alloc1),
+ EXPECT_EQ(ThreadIsolation::TryLookupStartOfJitAllocationAt(
+ alloc1, JitAllocationType::kInstructionStream),
std::nullopt);
- EXPECT_EQ(ThreadIsolation::TryLookupStartOfJitAllocationAt(alloc2 + 10),
+ EXPECT_EQ(ThreadIsolation::TryLookupStartOfJitAllocationAt(
+ alloc2 + 10, JitAllocationType::kInstructionStream),
alloc2);
}
+ ThreadIsolation::UnregisterJitAllocationForTesting(wasm_alloc,
+ wasm_alloc_size);
ThreadIsolation::UnregisterJitAllocationForTesting(alloc1, alloc1_size);
ThreadIsolation::UnregisterJitAllocationForTesting(alloc2, alloc2_size);
ThreadIsolation::UnregisterJitPage(address1, size);
diff --git a/deps/v8/test/unittests/compiler/js-typed-lowering-unittest.cc b/deps/v8/test/unittests/compiler/js-typed-lowering-unittest.cc
index cacceae2f8c..99eea3ebe98 100644
--- a/deps/v8/test/unittests/compiler/js-typed-lowering-unittest.cc
+++ b/deps/v8/test/unittests/compiler/js-typed-lowering-unittest.cc
@@ -311,34 +311,79 @@ TEST_F(JSTypedLoweringTest, JSShiftRightLogicalWithUnsigned32AndUnsigned32) {
EXPECT_THAT(r.replacement(), IsNumberShiftRightLogical(lhs, rhs));
}
+// -----------------------------------------------------------------------------
+// JSHasContextExtension
+
+TEST_F(JSTypedLoweringTest, JSHasContextExtension) {
+ Node* const context = Parameter(Type::Any(), 0);
+ Node* const effect = graph()->start();
+ Node* const branch = graph()->NewNode(
+ common()->Branch(), Parameter(Type::Boolean(), 1), graph()->start());
+ Node* const control = graph()->NewNode(common()->IfTrue(), branch);
+
+ Node* const has_ext0 = graph()->NewNode(javascript()->HasContextExtension(0),
+ context, effect, control);
+ Node* const sentinel0 =
+ graph()->NewNode(common()->EffectPhi(1), has_ext0, control);
+ Reduction const r0 = Reduce(has_ext0);
+ ASSERT_TRUE(r0.Changed());
+ EXPECT_THAT(
+ NodeProperties::GetEffectInput(sentinel0),
+ IsLoadField(
+ AccessBuilder::ForScopeInfoFlags(),
+ IsLoadField(AccessBuilder::ForContextSlot(Context::SCOPE_INFO_INDEX),
+ context, effect, control),
+ _, control));
+
+ Node* const has_ext1 = graph()->NewNode(javascript()->HasContextExtension(1),
+ context, effect, control);
+ Node* const sentinel1 =
+ graph()->NewNode(common()->EffectPhi(1), has_ext1, control);
+ Reduction const r1 = Reduce(has_ext1);
+ ASSERT_TRUE(r1.Changed());
+ EXPECT_THAT(
+ NodeProperties::GetEffectInput(sentinel1),
+ IsLoadField(
+ AccessBuilder::ForScopeInfoFlags(),
+ IsLoadField(AccessBuilder::ForContextSlot(Context::SCOPE_INFO_INDEX),
+ IsLoadField(AccessBuilder::ForContextSlotKnownPointer(
+ Context::PREVIOUS_INDEX),
+ context, effect, control),
+ _, control),
+ _, control));
+}
+
// -----------------------------------------------------------------------------
// JSLoadContextNoCell
TEST_F(JSTypedLoweringTest, JSLoadContextNoCell) {
- Node* const context = Parameter(Type::Any());
+ Node* const context = Parameter(Type::Any(), 0);
Node* const effect = graph()->start();
+ Node* const branch = graph()->NewNode(
+ common()->Branch(), Parameter(Type::Boolean(), 1), graph()->start());
+ Node* const control = graph()->NewNode(common()->IfTrue(), branch);
static bool kBooleans[] = {false, true};
TRACED_FOREACH(size_t, index, kIndices) {
TRACED_FOREACH(bool, immutable, kBooleans) {
Reduction const r1 = Reduce(
graph()->NewNode(javascript()->LoadContextNoCell(0, index, immutable),
- context, effect));
+ context, effect, control));
ASSERT_TRUE(r1.Changed());
EXPECT_THAT(r1.replacement(),
IsLoadField(AccessBuilder::ForContextSlot(index), context,
- effect, graph()->start()));
+ effect, control));
Reduction const r2 = Reduce(
graph()->NewNode(javascript()->LoadContextNoCell(1, index, immutable),
- context, effect));
+ context, effect, control));
ASSERT_TRUE(r2.Changed());
EXPECT_THAT(
r2.replacement(),
IsLoadField(AccessBuilder::ForContextSlot(index),
IsLoadField(AccessBuilder::ForContextSlotKnownPointer(
Context::PREVIOUS_INDEX),
- context, effect, graph()->start()),
- _, graph()->start()));
+ context, effect, control),
+ _, control));
}
}
}
@@ -347,9 +392,11 @@ TEST_F(JSTypedLoweringTest, JSLoadContextNoCell) {
// JSStoreContextNoCell
TEST_F(JSTypedLoweringTest, JSStoreContextNoCell) {
- Node* const context = Parameter(Type::Any());
+ Node* const context = Parameter(Type::Any(), 0);
Node* const effect = graph()->start();
- Node* const control = graph()->start();
+ Node* const branch = graph()->NewNode(
+ common()->Branch(), Parameter(Type::Boolean(), 1), graph()->start());
+ Node* const control = graph()->NewNode(common()->IfTrue(), branch);
TRACED_FOREACH(size_t, index, kIndices) {
TRACED_FOREACH(Type, type, kJSTypes) {
Node* const value = Parameter(type);
@@ -371,7 +418,7 @@ TEST_F(JSTypedLoweringTest, JSStoreContextNoCell) {
IsStoreField(AccessBuilder::ForContextSlot(index),
IsLoadField(AccessBuilder::ForContextSlotKnownPointer(
Context::PREVIOUS_INDEX),
- context, effect, graph()->start()),
+ context, effect, control),
value, _, control));
}
}
diff --git a/deps/v8/test/unittests/compiler/regalloc/live-range-unittest.cc b/deps/v8/test/unittests/compiler/regalloc/live-range-unittest.cc
index 4811187e79a..ba81728a0ad 100644
--- a/deps/v8/test/unittests/compiler/regalloc/live-range-unittest.cc
+++ b/deps/v8/test/unittests/compiler/regalloc/live-range-unittest.cc
@@ -129,7 +129,7 @@ TEST_F(LiveRangeUnitTest, InvalidConstruction) {
TEST_F(LiveRangeUnitTest, SplitInvalidStart) {
TopLevelLiveRange* range = TestRangeBuilder(zone()).Build(0, 1);
- V8_ASSERT_DEBUG_DEATH(Split(range, 0), ".*");
+ ASSERT_DEATH_IF_SUPPORTED(Split(range, 0), ".*");
}
TEST_F(LiveRangeUnitTest, DISABLE_IN_RELEASE(InvalidSplitEnd)) {
diff --git a/deps/v8/test/unittests/wasm/streaming-compilation-unittest.cc b/deps/v8/test/unittests/wasm/streaming-compilation-unittest.cc
index 753d1e7f6b9..bffa46daab6 100644
--- a/deps/v8/test/unittests/wasm/streaming-compilation-unittest.cc
+++ b/deps/v8/test/unittests/wasm/streaming-compilation-unittest.cc
@@ -104,6 +104,7 @@ class MockPlatform final : public v8::Platform {
}
void ExecuteTasks() { task_runner_->ExecuteTasks(); }
+ void ExecuteNestedTasks() { task_runner_->ExecuteNestedTasks(); }
private:
class MockTaskRunner final : public TaskRunner {
@@ -116,7 +117,8 @@ class MockPlatform final : public v8::Platform {
void PostNonNestableTaskImpl(std::unique_ptr<Task> task,
const SourceLocation& location) override {
- PostTask(std::move(task));
+ base::MutexGuard lock_scope(&tasks_lock_);
+ non_nestable_tasks_.push(std::move(task));
}
void PostDelayedTaskImpl(std::unique_ptr<Task> task,
@@ -145,12 +147,25 @@ class MockPlatform final : public v8::Platform {
// The test must call this repeatedly if delayed tasks were posted, until
// all such tasks have been executed.
- void ExecuteTasks() {
+ void ExecuteTasks() { ExecuteTasksImpl(/* include_non_nestable */ true); }
+
+ void ExecuteNestedTasks() {
+ ExecuteTasksImpl(/* include_non_nestable */ false);
+ }
+
+ private:
+ void ExecuteTasksImpl(bool include_non_nestable) {
std::queue<std::unique_ptr<v8::Task>> tasks;
while (true) {
{
base::MutexGuard lock_scope(&tasks_lock_);
tasks.swap(tasks_);
+ if (include_non_nestable) {
+ while (!non_nestable_tasks_.empty()) {
+ tasks.push(std::move(non_nestable_tasks_.front()));
+ non_nestable_tasks_.pop();
+ }
+ }
// Move all delayed tasks which are ready for execution to {tasks_}.
base::TimeTicks now = base::TimeTicks::Now();
for (auto it = delayed_tasks_.begin(), end = delayed_tasks_.end();
@@ -174,10 +189,10 @@ class MockPlatform final : public v8::Platform {
}
}
- private:
base::Mutex tasks_lock_;
// We do not execute tasks concurrently, so we only need one list of tasks.
std::queue<std::unique_ptr<v8::Task>> tasks_;
+ std::queue<std::unique_ptr<v8::Task>> non_nestable_tasks_;
std::list<std::pair<std::unique_ptr<v8::Task>, base::TimeTicks>>
delayed_tasks_;
};
@@ -2141,6 +2156,169 @@ STREAM_TEST(StreamingErrorCrashKeyReused) {
isolate->SetCrashKeyStringCallbacks(nullptr, nullptr);
}
+// Regression test for crbug.com/580857997: finishing a stream (success,
+// decoding/validation failure, baseline compilation failure, or
+// deserialization) must schedule a non-nestable foreground task rather than
+// completing synchronously inside an API interrupt.
+STREAM_TEST(FinishStreamInApiInterruptIsDeferred) {
+ FlagScope<bool> no_cache(&v8_flags.wasm_native_module_cache, false);
+ Zone zone(reinterpret_cast<i::Isolate*>(isolate)->allocator(), ZONE_NAME);
+ ZoneBuffer valid_bytes = GetValidModuleBytes(&zone);
+ ZoneBuffer cached_bytes =
+ GetValidCompiledModuleBytes(isolate, &zone, valid_bytes);
+ ZoneBuffer invalid_bytes = GetModuleWithInvalidSection(&zone);
+ ZoneBuffer invalid_code_bytes(&zone);
+ {
+ TestSignatures sigs;
+ WasmModuleBuilder builder(&zone);
+ builder.AddFunction(sigs.v_v())->EmitCode({kExprI32Add, kExprEnd});
+ builder.WriteTo(&invalid_code_bytes);
+ }
+
+ StreamTester success_tester(isolate);
+ // Pre-compile the functions so FinishStream() is the last finisher.
+ success_tester.OnBytesReceived(valid_bytes.begin(), valid_bytes.size());
+ success_tester.RunCompilerTasks();
+ CHECK(success_tester.IsPromisePending());
+
+ StreamTester compile_error_tester(isolate);
+ {
+ // Disable lazy compilation so the invalid function body fails in
+ // CompilationState rather than ValidateFunctionsStreamingJob.
+ FlagScope<bool> eager_compile(&v8_flags.wasm_lazy_compilation, false);
+ compile_error_tester.OnBytesReceived(invalid_code_bytes.begin(),
+ invalid_code_bytes.size());
+ compile_error_tester.RunCompilerTasks();
+ CHECK(compile_error_tester.IsPromisePending());
+ }
+
+ StreamTester error_tester(isolate);
+ StreamTester cached_tester(isolate);
+ cached_tester.SetHasCompiledModuleBytes();
+
+ struct InterruptData {
+ MockPlatform* platform;
+ ZoneBuffer* valid_bytes;
+ ZoneBuffer* cached_bytes;
+ ZoneBuffer* invalid_bytes;
+ StreamTester* success_tester;
+ StreamTester* compile_error_tester;
+ StreamTester* error_tester;
+ StreamTester* cached_tester;
+ bool interrupt_ran = false;
+ } data{platform, &valid_bytes, &cached_bytes, &invalid_bytes,
+ &success_tester, &compile_error_tester, &error_tester, &cached_tester};
+
+ isolate->RequestInterrupt(
+ [](v8::Isolate* isolate, void* raw_data) {
+ i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
+ CHECK(i_isolate->is_executing_api_interrupt());
+ auto* d = static_cast<InterruptData*>(raw_data);
+
+ d->success_tester->FinishStream();
+ CHECK(d->success_tester->IsPromisePending());
+
+ d->compile_error_tester->FinishStream();
+ CHECK(d->compile_error_tester->IsPromisePending());
+
+ d->error_tester->OnBytesReceived(d->invalid_bytes->begin(),
+ d->invalid_bytes->size());
+ d->error_tester->FinishStream();
+ CHECK(d->error_tester->IsPromisePending());
+
+ d->cached_tester->OnBytesReceived(d->valid_bytes->begin(),
+ d->valid_bytes->size());
+ d->cached_tester->FinishStreamWithCachedModuleBytes(
+ base::VectorOf(*d->cached_bytes));
+ // Aborting after FinishStreamWithCachedModuleBytes must be a no-op even
+ // while the FinishCompilation task is still pending.
+ d->cached_tester->stream()->Abort();
+ CHECK(d->cached_tester->IsPromisePending());
+
+ // Pumping nestable tasks inside the interrupt must not execute the
+ // non-nestable foreground completion tasks.
+ d->platform->ExecuteNestedTasks();
+ CHECK(d->success_tester->IsPromisePending());
+ CHECK(d->compile_error_tester->IsPromisePending());
+ CHECK(d->error_tester->IsPromisePending());
+ CHECK(d->cached_tester->IsPromisePending());
+
+ d->interrupt_ran = true;
+ },
+ &data);
+
+ reinterpret_cast<i::Isolate*>(isolate)->stack_guard()->HandleInterrupts();
+ CHECK(data.interrupt_ran);
+ CHECK(success_tester.IsPromisePending());
+ CHECK(compile_error_tester.IsPromisePending());
+ CHECK(error_tester.IsPromisePending());
+ CHECK(cached_tester.IsPromisePending());
+
+ success_tester.RunCompilerTasks();
+ CHECK(success_tester.IsPromiseFulfilled());
+ CHECK(compile_error_tester.IsPromiseRejected());
+ CHECK(error_tester.IsPromiseRejected());
+ CHECK(cached_tester.IsPromiseFulfilled());
+
+ // Also verify deferral when JavaScript execution is disallowed outside an API
+ // interrupt (e.g. Blink's ScriptForbiddenScope during BFCache freeze).
+ StreamTester no_js_success_tester(isolate);
+ no_js_success_tester.OnBytesReceived(valid_bytes.begin(), valid_bytes.size());
+ no_js_success_tester.RunCompilerTasks();
+ CHECK(no_js_success_tester.IsPromisePending());
+
+ StreamTester no_js_cached_tester(isolate);
+ no_js_cached_tester.SetHasCompiledModuleBytes();
+ no_js_cached_tester.OnBytesReceived(valid_bytes.begin(), valid_bytes.size());
+
+ {
+ v8::Isolate::DisallowJavascriptExecutionScope no_js(
+ isolate,
+ v8::Isolate::DisallowJavascriptExecutionScope::THROW_ON_FAILURE);
+ no_js_success_tester.FinishStream();
+ CHECK(no_js_success_tester.IsPromisePending());
+ no_js_cached_tester.FinishStreamWithCachedModuleBytes(
+ base::VectorOf(cached_bytes));
+ CHECK(no_js_cached_tester.IsPromisePending());
+ }
+
+ no_js_success_tester.RunCompilerTasks();
+ CHECK(no_js_success_tester.IsPromiseFulfilled());
+ CHECK(no_js_cached_tester.IsPromiseFulfilled());
+}
+
+STREAM_TEST(TestDestroyDuringDeserializationFinish) {
+ FlagScope<bool> no_cache(&v8_flags.wasm_native_module_cache, false);
+ Zone zone(reinterpret_cast<i::Isolate*>(isolate)->allocator(), ZONE_NAME);
+ ZoneBuffer wire_bytes = GetValidModuleBytes(&zone);
+ ZoneBuffer module_bytes =
+ GetValidCompiledModuleBytes(isolate, &zone, wire_bytes);
+
+ auto compilation = std::make_unique<v8::WasmModuleCompilation>();
+ compilation->SetHasCompiledModuleBytes();
+ compilation->OnBytesReceived(wire_bytes.begin(), wire_bytes.size());
+ bool resolved = false;
+ compilation->Finish(
+ isolate,
+ [&](WasmStreaming::ModuleCachingInterface& caching_interface) {
+ CHECK(caching_interface.SetCachedCompiledModuleBytes(
+ base::VectorOf(module_bytes)));
+ // Allocate and fill a buffer of sizeof(StreamingDecoder) after
+ // {FinishCompile} has dropped {AsyncCompileJob::stream_} and
+ // {resolution_callback} has destroyed {compilation}.
+ auto overwrite = std::make_unique<uint8_t[]>(sizeof(StreamingDecoder));
+ std::memset(overwrite.get(), 0xaa, sizeof(StreamingDecoder));
+ },
+ [&](std::variant<Local<v8::WasmModuleObject>, Local<v8::Value>>
+ module_or_error) {
+ CHECK(std::holds_alternative<Local<v8::WasmModuleObject>>(
+ module_or_error));
+ resolved = true;
+ compilation.reset();
+ });
+ CHECK(resolved);
+}
+
#undef STREAM_TEST
} // namespace v8::internal::wasm