From b0bfb828e956221b8c56dea14cdc489ad63fda93 Mon Sep 17 00:00:00 2001 From: David Wrighton Date: Wed, 14 Oct 2026 00:12:27 +0000 Subject: [PATCH 01/21] Compact Wasm ReadyToRun GC and unwind metadata Specialize register-free codecs, use implicit frame-relative pointer-scaled slots, enable slim headers, encode flags-first offset runs, and normalize unwind frames to 16-byte units. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/coreclr/gcinfo/gcinfoencoder.cpp | 106 +++++++-- src/coreclr/inc/gcinfodecoder.h | 39 ++- src/coreclr/inc/gcinfotypes.h | 42 +++- src/coreclr/jit/unwindwasm.cpp | 8 +- .../GcInfoDecoderTests.cs | 224 ++++++++++++++++++ .../Amd64/GcInfo.cs | 7 +- .../Amd64/GcSlotTable.cs | 23 +- .../GCInfoTypes.cs | 7 +- .../Wasm32/UnwindInfo.cs | 4 +- src/coreclr/vm/gcinfodecoder.cpp | 135 ++++------- src/coreclr/vm/wasm/helpers.cpp | 2 +- 11 files changed, 463 insertions(+), 134 deletions(-) create mode 100644 src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/GcInfoDecoderTests.cs diff --git a/src/coreclr/gcinfo/gcinfoencoder.cpp b/src/coreclr/gcinfo/gcinfoencoder.cpp index f69eb1154a8780..2efd80626214fa 100644 --- a/src/coreclr/gcinfo/gcinfoencoder.cpp +++ b/src/coreclr/gcinfo/gcinfoencoder.cpp @@ -527,6 +527,7 @@ template void TGcInfoEncoder::DefineCa template GcSlotId TGcInfoEncoder::GetRegisterSlotId( UINT32 regNum, GcSlotFlags flags ) { + _ASSERTE(GcInfoEncoding::HAS_REGISTER_SLOTS); // We could lookup an existing identical slot in the slot table (via some hashtable mechanism). // We just create duplicates for now. @@ -552,6 +553,7 @@ template GcSlotId TGcInfoEncoder::GetR template GcSlotId TGcInfoEncoder::GetStackSlotId( INT32 spOffset, GcSlotFlags flags, GcStackSlotBase spBase ) { + _ASSERTE(GcInfoEncoding::HAS_STACK_SLOT_BASE || spBase == GC_FRAMEREG_REL); // We could lookup an existing identical slot in the slot table (via some hashtable mechanism). // We just create duplicates for now. @@ -1404,7 +1406,7 @@ template void TGcInfoEncoder::Build() { UINT32 numDeleted = 0; UINT32 i; - for(i = 0; i < m_NumSlots && m_SlotTable[i].IsRegister(); i++) + for(i = 0; GcInfoEncoding::HAS_REGISTER_SLOTS && i < m_NumSlots && m_SlotTable[i].IsRegister(); i++) { if(m_SlotTable[i].IsDeleted()) { @@ -1424,15 +1426,17 @@ template void TGcInfoEncoder::Build() } numUntrackedSlots = numUsedSlots - (numRegisters + numStackSlots); - // Common case: nothing, or a few registers - if (numRegisters) + if constexpr (GcInfoEncoding::HAS_REGISTER_SLOTS) { - GCINFO_WRITE(m_Info1, 1, 1, FlagsSize); - GCINFO_WRITE_VARL_U(m_Info1, numRegisters, GcInfoEncoding::NUM_REGISTERS_ENCBASE, NumRegsSize); - } - else - { - GCINFO_WRITE(m_Info1, 0, 1, FlagsSize); + if (numRegisters) + { + GCINFO_WRITE(m_Info1, 1, 1, FlagsSize); + GCINFO_WRITE_VARL_U(m_Info1, numRegisters, GcInfoEncoding::NUM_REGISTERS_ENCBASE, NumRegsSize); + } + else + { + GCINFO_WRITE(m_Info1, 0, 1, FlagsSize); + } } if (numStackSlots || numUntrackedSlots) { @@ -1450,7 +1454,7 @@ template void TGcInfoEncoder::Build() if(numUsedSlots == 0) goto lExitSuccess; - if(numRegisters > 0) + if(GcInfoEncoding::HAS_REGISTER_SLOTS && numRegisters > 0) { GcSlotDesc *pSlotDesc; do @@ -1508,11 +1512,21 @@ template void TGcInfoEncoder::Build() // Encode slot identification _ASSERTE((pSlotDesc->Slot.Stack.Base & ~3) == 0); - GCINFO_WRITE(m_Info1, pSlotDesc->Slot.Stack.Base, 2, StackSlotSize); + if constexpr (GcInfoEncoding::HAS_STACK_SLOT_BASE) + { + GCINFO_WRITE(m_Info1, pSlotDesc->Slot.Stack.Base, 2, StackSlotSize); + } INT32 currentNormStackSlot = GcInfoEncoding::NORMALIZE_STACK_SLOT(pSlotDesc->Slot.Stack.SpOffset); + if constexpr (GcInfoEncoding::STACK_SLOT_FLAGS_FIRST) + { + GCINFO_WRITE(m_Info1, pSlotDesc->Flags, 2, StackSlotSize); + } GCINFO_WRITE_VARL_S(m_Info1, currentNormStackSlot, GcInfoEncoding::STACK_SLOT_ENCBASE, StackSlotSize); - GCINFO_WRITE(m_Info1, pSlotDesc->Flags, 2, StackSlotSize); + if constexpr (!GcInfoEncoding::STACK_SLOT_FLAGS_FIRST) + { + GCINFO_WRITE(m_Info1, pSlotDesc->Flags, 2, StackSlotSize); + } for(UINT32 j = 1; j < numStackSlots; j++) { @@ -1531,9 +1545,32 @@ template void TGcInfoEncoder::Build() currentNormStackSlot = GcInfoEncoding::NORMALIZE_STACK_SLOT(pSlotDesc->Slot.Stack.SpOffset); _ASSERTE((pSlotDesc->Slot.Stack.Base & ~3) == 0); - GCINFO_WRITE(m_Info1, pSlotDesc->Slot.Stack.Base, 2, StackSlotSize); + if constexpr (GcInfoEncoding::HAS_STACK_SLOT_BASE) + { + GCINFO_WRITE(m_Info1, pSlotDesc->Slot.Stack.Base, 2, StackSlotSize); + } + + if constexpr (GcInfoEncoding::STACK_SLOT_FLAGS_FIRST) + { + if (lastFlags != GC_SLOT_BASE) + { + GCINFO_WRITE(m_Info1, pSlotDesc->Flags, 2, StackSlotSize); + } + else + { + _ASSERTE(pSlotDesc->Flags == GC_SLOT_BASE); + } - if(lastFlags != GC_SLOT_BASE) + if (pSlotDesc->Flags != lastFlags) + { + GCINFO_WRITE_VARL_S(m_Info1, currentNormStackSlot, GcInfoEncoding::STACK_SLOT_ENCBASE, StackSlotSize); + } + else + { + GCINFO_WRITE_VARL_U(m_Info1, currentNormStackSlot - lastNormStackSlot, GcInfoEncoding::STACK_SLOT_DELTA_ENCBASE, StackSlotSize); + } + } + else if(lastFlags != GC_SLOT_BASE) { GCINFO_WRITE_VARL_S(m_Info1, currentNormStackSlot, GcInfoEncoding::STACK_SLOT_ENCBASE, StackSlotSize); GCINFO_WRITE(m_Info1, pSlotDesc->Flags, 2, StackSlotSize); @@ -1560,11 +1597,21 @@ template void TGcInfoEncoder::Build() // Encode slot identification _ASSERTE((pSlotDesc->Slot.Stack.Base & ~3) == 0); - GCINFO_WRITE(m_Info1, pSlotDesc->Slot.Stack.Base, 2, UntrackedSlotSize); + if constexpr (GcInfoEncoding::HAS_STACK_SLOT_BASE) + { + GCINFO_WRITE(m_Info1, pSlotDesc->Slot.Stack.Base, 2, UntrackedSlotSize); + } INT32 currentNormStackSlot = GcInfoEncoding::NORMALIZE_STACK_SLOT(pSlotDesc->Slot.Stack.SpOffset); + if constexpr (GcInfoEncoding::STACK_SLOT_FLAGS_FIRST) + { + GCINFO_WRITE(m_Info1, pSlotDesc->Flags, 2, UntrackedSlotSize); + } GCINFO_WRITE_VARL_S(m_Info1, currentNormStackSlot, GcInfoEncoding::STACK_SLOT_ENCBASE, UntrackedSlotSize); - GCINFO_WRITE(m_Info1, pSlotDesc->Flags, 2, UntrackedSlotSize); + if constexpr (!GcInfoEncoding::STACK_SLOT_FLAGS_FIRST) + { + GCINFO_WRITE(m_Info1, pSlotDesc->Flags, 2, UntrackedSlotSize); + } for(UINT32 j = 1; j < numUntrackedSlots; j++) { @@ -1583,9 +1630,32 @@ template void TGcInfoEncoder::Build() currentNormStackSlot = GcInfoEncoding::NORMALIZE_STACK_SLOT(pSlotDesc->Slot.Stack.SpOffset); _ASSERTE((pSlotDesc->Slot.Stack.Base & ~3) == 0); - GCINFO_WRITE(m_Info1, pSlotDesc->Slot.Stack.Base, 2, UntrackedSlotSize); + if constexpr (GcInfoEncoding::HAS_STACK_SLOT_BASE) + { + GCINFO_WRITE(m_Info1, pSlotDesc->Slot.Stack.Base, 2, UntrackedSlotSize); + } + + if constexpr (GcInfoEncoding::STACK_SLOT_FLAGS_FIRST) + { + if (lastFlags != GC_SLOT_UNTRACKED) + { + GCINFO_WRITE(m_Info1, pSlotDesc->Flags, 2, UntrackedSlotSize); + } + else + { + _ASSERTE(pSlotDesc->Flags == GC_SLOT_UNTRACKED); + } - if(lastFlags != GC_SLOT_UNTRACKED) + if (pSlotDesc->Flags != lastFlags) + { + GCINFO_WRITE_VARL_S(m_Info1, currentNormStackSlot, GcInfoEncoding::STACK_SLOT_ENCBASE, UntrackedSlotSize); + } + else + { + GCINFO_WRITE_VARL_U(m_Info1, currentNormStackSlot - lastNormStackSlot, GcInfoEncoding::STACK_SLOT_DELTA_ENCBASE, UntrackedSlotSize); + } + } + else if(lastFlags != GC_SLOT_UNTRACKED) { GCINFO_WRITE_VARL_S(m_Info1, currentNormStackSlot, GcInfoEncoding::STACK_SLOT_ENCBASE, UntrackedSlotSize); GCINFO_WRITE(m_Info1, pSlotDesc->Flags, 2, UntrackedSlotSize); diff --git a/src/coreclr/inc/gcinfodecoder.h b/src/coreclr/inc/gcinfodecoder.h index 0836dfd0c54b68..cbb4ca3731aa0e 100644 --- a/src/coreclr/inc/gcinfodecoder.h +++ b/src/coreclr/inc/gcinfodecoder.h @@ -498,12 +498,46 @@ class GcSlotDecoder UINT32 GetNumRegisters() { - return m_NumRegisters; + return GcInfoEncoding::HAS_REGISTER_SLOTS ? m_NumRegisters : 0; } const GcSlotDesc* GetSlotDesc(UINT32 slotIndex); private: + static GcStackSlotBase ReadStackSlotBase(BitStreamReader& reader) + { + return GcInfoEncoding::HAS_STACK_SLOT_BASE ? (GcStackSlotBase)reader.Read(2) : GC_FRAMEREG_REL; + } + + static INT32 ReadStackSlotOffset(BitStreamReader& reader, GcSlotFlags& flags, INT32 previousOffset, bool first) + { + bool absolute; + if constexpr (GcInfoEncoding::STACK_SLOT_FLAGS_FIRST) + { + GcSlotFlags previousFlags = first ? static_cast(7) : flags; + flags = previousFlags == GC_SLOT_BASE ? GC_SLOT_BASE : static_cast(reader.Read(2)); + absolute = flags != previousFlags; + } + else + { + absolute = first || flags != GC_SLOT_BASE; + } + + INT32 offset = absolute + ? static_cast(reader.DecodeVarLengthSigned(GcInfoEncoding::STACK_SLOT_ENCBASE)) + : previousOffset + static_cast(reader.DecodeVarLengthUnsigned(GcInfoEncoding::STACK_SLOT_DELTA_ENCBASE)); + + if constexpr (!GcInfoEncoding::STACK_SLOT_FLAGS_FIRST) + { + if (absolute) + { + flags = static_cast(reader.Read(2)); + } + } + + return offset; + } + GcSlotDesc m_SlotArray[MAX_PREDECODED_SLOTS]; BitStreamReader m_SlotReader; UINT32 m_NumSlots; @@ -744,7 +778,7 @@ class TGcInfoDecoder const GcSlotDesc* pSlot = slotDecoder.GetSlotDesc(slotIndex); bool reportFpBasedSlotsOnly = (inputFlags & ReportFPBasedSlotsOnly); - if(slotIndex < slotDecoder.GetNumRegisters()) + if(GcInfoEncoding::HAS_REGISTER_SLOTS && slotIndex < slotDecoder.GetNumRegisters()) { UINT32 regNum = pSlot->Slot.RegisterNumber; if( ( reportScratchSlots || !IsScratchRegister( regNum, pRD ) ) && !reportFpBasedSlotsOnly ) @@ -798,4 +832,3 @@ typedef TGcInfoDecoder InterpreterGcInfoDecoder; #endif // _GC_INFO_DECODER_ - diff --git a/src/coreclr/inc/gcinfotypes.h b/src/coreclr/inc/gcinfotypes.h index 2ef36ca12051ef..877a8d1187c7c3 100644 --- a/src/coreclr/inc/gcinfotypes.h +++ b/src/coreclr/inc/gcinfotypes.h @@ -617,6 +617,9 @@ struct AMD64GcInfoEncoding { static const int POINTER_SIZE_ENCBASE = 3; static const int LIVESTATE_RLE_RUN_ENCBASE = 2; static const int LIVESTATE_RLE_SKIP_ENCBASE = 4; + static const bool HAS_REGISTER_SLOTS = true; + static const bool HAS_STACK_SLOT_BASE = true; + static const bool STACK_SLOT_FLAGS_FIRST = false; static const bool HAS_FIXED_STACK_PARAMETER_SCRATCH_AREA = true; static const bool HAS_INTERRUPTIBLE_RANGES = true; }; @@ -676,6 +679,9 @@ struct ARM32GcInfoEncoding { static const int POINTER_SIZE_ENCBASE = 3; static const int LIVESTATE_RLE_RUN_ENCBASE = 2; static const int LIVESTATE_RLE_SKIP_ENCBASE = 4; + static const bool HAS_REGISTER_SLOTS = true; + static const bool HAS_STACK_SLOT_BASE = true; + static const bool STACK_SLOT_FLAGS_FIRST = false; static const bool HAS_FIXED_STACK_PARAMETER_SCRATCH_AREA = true; static const bool HAS_INTERRUPTIBLE_RANGES = true; }; @@ -738,6 +744,9 @@ struct ARM64GcInfoEncoding { static const int POINTER_SIZE_ENCBASE = 3; static const int LIVESTATE_RLE_RUN_ENCBASE = 2; static const int LIVESTATE_RLE_SKIP_ENCBASE = 4; + static const bool HAS_REGISTER_SLOTS = true; + static const bool HAS_STACK_SLOT_BASE = true; + static const bool STACK_SLOT_FLAGS_FIRST = false; static const bool HAS_FIXED_STACK_PARAMETER_SCRATCH_AREA = true; static const bool HAS_INTERRUPTIBLE_RANGES = true; }; @@ -798,6 +807,9 @@ struct LoongArch64GcInfoEncoding { static const int POINTER_SIZE_ENCBASE = 3; static const int LIVESTATE_RLE_RUN_ENCBASE = 2; static const int LIVESTATE_RLE_SKIP_ENCBASE = 4; + static const bool HAS_REGISTER_SLOTS = true; + static const bool HAS_STACK_SLOT_BASE = true; + static const bool STACK_SLOT_FLAGS_FIRST = false; static const bool HAS_FIXED_STACK_PARAMETER_SCRATCH_AREA = true; static const bool HAS_INTERRUPTIBLE_RANGES = true; }; @@ -859,6 +871,9 @@ struct RISCV64GcInfoEncoding { static const int POINTER_SIZE_ENCBASE = 3; static const int LIVESTATE_RLE_RUN_ENCBASE = 2; static const int LIVESTATE_RLE_SKIP_ENCBASE = 4; + static const bool HAS_REGISTER_SLOTS = true; + static const bool HAS_STACK_SLOT_BASE = true; + static const bool STACK_SLOT_FLAGS_FIRST = false; static const bool HAS_FIXED_STACK_PARAMETER_SCRATCH_AREA = true; static const bool HAS_INTERRUPTIBLE_RANGES = true; }; @@ -915,6 +930,9 @@ struct X86GcInfoEncoding { static const int POINTER_SIZE_ENCBASE = 3; static const int LIVESTATE_RLE_RUN_ENCBASE = 2; static const int LIVESTATE_RLE_SKIP_ENCBASE = 4; + static const bool HAS_REGISTER_SLOTS = true; + static const bool HAS_STACK_SLOT_BASE = true; + static const bool STACK_SLOT_FLAGS_FIRST = false; static const bool HAS_FIXED_STACK_PARAMETER_SCRATCH_AREA = true; static const bool HAS_INTERRUPTIBLE_RANGES = true; }; @@ -927,17 +945,16 @@ struct X86GcInfoEncoding { #define TargetGcInfoEncoding Wasm32GcInfoEncoding -// TODO-WASM: Investigate normalizing stack slots to save space based on wasm stack alignment - struct Wasm32GcInfoEncoding { static const uint32_t NUM_NORM_CODE_OFFSETS_PER_CHUNK = (64); static const uint32_t NUM_NORM_CODE_OFFSETS_PER_CHUNK_LOG2 = (6); - static inline constexpr int32_t NORMALIZE_STACK_SLOT (int32_t x) { return (x); } - static inline constexpr int32_t DENORMALIZE_STACK_SLOT (int32_t x) { return (x); } + static inline constexpr int32_t NORMALIZE_STACK_SLOT (int32_t x) { return (x / TARGET_POINTER_SIZE); } + static inline constexpr int32_t DENORMALIZE_STACK_SLOT (int32_t x) { return (x * TARGET_POINTER_SIZE); } static inline constexpr uint32_t NORMALIZE_CODE_LENGTH (uint32_t x) { return (x); } static inline constexpr uint32_t DENORMALIZE_CODE_LENGTH (uint32_t x) { return (x); } - static inline constexpr uint32_t NORMALIZE_STACK_BASE_REGISTER (uint32_t x) { return (x); } - static inline constexpr uint32_t DENORMALIZE_STACK_BASE_REGISTER (uint32_t x) { return (x); } + // Slim headers identify the default frame register by normalized zero. + static inline constexpr uint32_t NORMALIZE_STACK_BASE_REGISTER (uint32_t x) { return (x ^ 2); } + static inline constexpr uint32_t DENORMALIZE_STACK_BASE_REGISTER (uint32_t x) { return (x ^ 2); } static inline constexpr uint32_t NORMALIZE_SIZE_OF_STACK_AREA (uint32_t x) { return (x); } static inline constexpr uint32_t DENORMALIZE_SIZE_OF_STACK_AREA (uint32_t x) { return (x); } static const bool CODE_OFFSETS_NEED_NORMALIZATION = false; @@ -965,14 +982,20 @@ struct Wasm32GcInfoEncoding { static const int INTERRUPTIBLE_RANGE_DELTA2_ENCBASE = 5; static const int REGISTER_ENCBASE = 3; static const int REGISTER_DELTA_ENCBASE = REGISTER_ENCBASE; - static const int STACK_SLOT_ENCBASE = 6; - static const int STACK_SLOT_DELTA_ENCBASE = 4; + static const int STACK_SLOT_ENCBASE = 3; + static const int STACK_SLOT_DELTA_ENCBASE = 3; static const int NUM_SAFE_POINTS_ENCBASE = 4; static const int NUM_INTERRUPTIBLE_RANGES_ENCBASE = 1; static const int NUM_EH_CLAUSES_ENCBASE = 2; static const int POINTER_SIZE_ENCBASE = 3; static const int LIVESTATE_RLE_RUN_ENCBASE = 2; static const int LIVESTATE_RLE_SKIP_ENCBASE = 4; + // Register-free encodings omit the register-presence bit from the slot table. + static const bool HAS_REGISTER_SLOTS = false; + // All slots are frame-relative, so no per-slot stack base is encoded. + static const bool HAS_STACK_SLOT_BASE = false; + // Equal flags use offset deltas; ordinary flags are implicit after their first slot. + static const bool STACK_SLOT_FLAGS_FIRST = true; static const bool HAS_FIXED_STACK_PARAMETER_SCRATCH_AREA = false; static const bool HAS_INTERRUPTIBLE_RANGES = false; }; @@ -1037,6 +1060,9 @@ struct InterpreterGcInfoEncoding { static const int POINTER_SIZE_ENCBASE = 3; static const int LIVESTATE_RLE_RUN_ENCBASE = 2; static const int LIVESTATE_RLE_SKIP_ENCBASE = 4; + static const bool HAS_REGISTER_SLOTS = false; + static const bool HAS_STACK_SLOT_BASE = true; + static const bool STACK_SLOT_FLAGS_FIRST = false; static const bool HAS_FIXED_STACK_PARAMETER_SCRATCH_AREA = false; static const bool HAS_INTERRUPTIBLE_RANGES = true; }; diff --git a/src/coreclr/jit/unwindwasm.cpp b/src/coreclr/jit/unwindwasm.cpp index 51b310b581068a..221f2fb2773766 100644 --- a/src/coreclr/jit/unwindwasm.cpp +++ b/src/coreclr/jit/unwindwasm.cpp @@ -61,7 +61,8 @@ void Compiler::unwindReserveFunc(FuncInfoDsc* func) bool isFunclet = func->IsFunclet(); bool isColdCode = false; assert(func->endVirtualIP > func->startVirtualIP); - ULONG encodedSize = emitter::SizeOfULEB128(func->funWasmFrameSize) + + assert((func->funWasmFrameSize % STACK_ALIGN) == 0); + ULONG encodedSize = emitter::SizeOfULEB128(func->funWasmFrameSize / STACK_ALIGN) + emitter::SizeOfULEB128(func->endVirtualIP - func->startVirtualIP); eeReserveUnwindInfo(isFunclet, isColdCode, encodedSize); @@ -107,13 +108,14 @@ void Compiler::unwindEmitFunc(FuncInfoDsc* func, void* pHotCode, void* pColdCode // pColdCode = nullptr; - // Unwind info is the frame size and the virtual IP length. + // Unwind info is the frame size in 16-byte units and the virtual IP length. // All values encoded via ULEB128. // uint8_t buffer[10]; size_t index = 0; assert(func->endVirtualIP > func->startVirtualIP); - index += GetEmitter()->emitOutputULEB128(buffer + index, func->funWasmFrameSize); + assert((func->funWasmFrameSize % STACK_ALIGN) == 0); + index += GetEmitter()->emitOutputULEB128(buffer + index, func->funWasmFrameSize / STACK_ALIGN); index += GetEmitter()->emitOutputULEB128(buffer + index, func->endVirtualIP - func->startVirtualIP); assert(index <= sizeof(buffer)); diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/GcInfoDecoderTests.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/GcInfoDecoderTests.cs new file mode 100644 index 00000000000000..9a8b7a20a991b7 --- /dev/null +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/GcInfoDecoderTests.cs @@ -0,0 +1,224 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.IO; +using System.Reflection.PortableExecutable; +using ILCompiler.Reflection.ReadyToRun; +using ILCompiler.Reflection.ReadyToRun.Amd64; +using Xunit; + +namespace ILCompiler.ReadyToRun.Tests; + +public class GcInfoDecoderTests +{ + [Theory] + [InlineData(0)] + [InlineData(1)] + [InlineData(2)] + [InlineData(3)] + public void Amd64SlotTableRetainsRegisterPresenceBit(int rootFlags) + { + byte[] encoded = [0x08, 0xC0, (byte)(rootFlags << 7), (byte)(rootFlags >> 1), 0x00, 0x00, 0x00, 0x00]; + using MemoryStream stream = new(encoded); + GcInfo info = new(new NativeReader(stream), 0, Machine.Amd64, 5); + + Assert.Equal(1u, info.SlotTable.NumRegisters); + Assert.Equal(0u, info.SlotTable.NumStackSlots); + Assert.Equal(0u, info.SlotTable.NumUntracked); + GcSlotTable.GcSlot slot = Assert.Single(info.SlotTable.GcSlots); + Assert.Equal(0, slot.RegisterNumber); + Assert.Null(slot.StackSlot); + Assert.Equal((GcSlotFlags)rootFlags, slot.Flags); + } + + [Theory] + [InlineData(-1, 8, false, 0x02)] + [InlineData(0, 8, false, 0x02)] + [InlineData(1, 8, false, 0x02)] + [InlineData(2, 8, false, 0x02)] + [InlineData(3, 8, false, 0x02)] + [InlineData(0, -8, false, 0x06)] + [InlineData(0, 124, false, 0x3F)] + [InlineData(0, -128, false, 0x48)] + [InlineData(-1, 8, true, 0x02)] + [InlineData(0, 8, true, 0x02)] + [InlineData(1, 8, true, 0x02)] + [InlineData(2, 8, true, 0x02)] + [InlineData(3, 8, true, 0x02)] + [InlineData(0, -8, true, 0x06)] + [InlineData(0, 124, true, 0x3F)] + [InlineData(0, -128, true, 0x48)] + public void WasmSlotTableUsesImplicitFrameBaseAndPointerUnits(int rootFlags, int offset, bool slimHeader, int encodedOffset) + { + int descriptor = rootFlags | (encodedOffset << 2); + byte[] encoded = (slimHeader, rootFlags < 0) switch + { + (true, true) => [0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], + (false, true) => [0x81, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], + (true, false) => [0x0A, 0x40, 0x20, (byte)(descriptor << 3), (byte)(descriptor >> 5), 0x00, 0x00, 0x00], + (false, false) => [0x81, 0x10, 0x00, 0x08, 0x04, (byte)descriptor, (byte)(descriptor >> 8), 0x00], + }; + using MemoryStream stream = new(encoded); + GcInfo info = new(new NativeReader(stream), 0, WasmMachine.Wasm32, 5); + + Assert.Equal(2, info.CodeLength); + Assert.Equal(2u, info.StackBaseRegister); + Assert.Equal(0u, info.SlotTable.NumRegisters); + Assert.Equal(0u, info.SlotTable.NumStackSlots); + Assert.Equal(rootFlags < 0 ? 0u : 1u, info.SlotTable.NumUntracked); + if (rootFlags < 0) + { + Assert.Empty(info.SlotTable.GcSlots); + Assert.Equal(slimHeader ? 2 : 4, info.Size); + } + else + { + GcSlotTable.GcSlot slot = Assert.Single(info.SlotTable.GcSlots); + Assert.Equal(offset, slot.StackSlot.SpOffset); + Assert.Equal(GcStackSlotBase.GC_FRAMEREG_REL, slot.StackSlot.Base); + Assert.Equal((GcSlotFlags)rootFlags | GcSlotFlags.GC_SLOT_UNTRACKED, slot.Flags); + Assert.Equal(slimHeader ? 5 : encodedOffset < 16 ? 6 : 7, info.Size); + } + } + + [Theory] + [InlineData(0, 0x08, 0x00)] + [InlineData(4, 0x08, 0x01)] + [InlineData(8, 0x08, 0x06)] + [InlineData(15, 0xC8, 0x07)] + [InlineData(16, 0x08, 0x0A)] + public void WasmSlotOffsetsUseUnsignedPointerUnitDeltas(int delta, byte firstByte, byte secondByte) + { + byte[] encoded = [0x81, 0x10, 0x00, 0x08, 0x08, firstByte, secondByte, 0x00]; + using MemoryStream stream = new(encoded); + GcInfo info = new(new NativeReader(stream), 0, WasmMachine.Wasm32, 5); + + Assert.Equal(0u, info.SlotTable.NumRegisters); + Assert.Equal(0u, info.SlotTable.NumStackSlots); + Assert.Equal(2u, info.SlotTable.NumUntracked); + Assert.Equal(2, info.SlotTable.GcSlots.Count); + Assert.Equal(7, info.Size); + for (int i = 0; i < info.SlotTable.GcSlots.Count; i++) + { + GcSlotTable.GcSlot slot = info.SlotTable.GcSlots[i]; + Assert.Equal(i == 0 ? 8 : 8 + delta * 4, slot.StackSlot.SpOffset); + Assert.Equal(GcStackSlotBase.GC_FRAMEREG_REL, slot.StackSlot.Base); + Assert.Equal(GcSlotFlags.GC_SLOT_UNTRACKED, slot.Flags); + } + } + + [Theory] + [InlineData(0)] + [InlineData(1)] + [InlineData(2)] + [InlineData(3)] + public void WasmSlotOffsetsUseDeltasForAllFlagTypes(int rootFlags) + { + byte[] encoded = [0x01, (byte)(0x01 | (rootFlags << 5)), (byte)(rootFlags == 0 ? 0x09 : 0x21 | (rootFlags << 3)), 0x00]; + GcInfo info = DecodeWasmSlotTable(encoded); + GcSlotTable table = info.SlotTable; + + Assert.Equal(2u, table.NumUntracked); + Assert.Equal(5, info.Size); + for (int i = 0; i < table.GcSlots.Count; i++) + { + Assert.Equal(8 + i * 4, table.GcSlots[i].StackSlot.SpOffset); + Assert.Equal((GcSlotFlags)rootFlags | GcSlotFlags.GC_SLOT_UNTRACKED, table.GcSlots[i].Flags); + } + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void WasmSlotOffsetsResetAtSectionAndFlagBoundaries(bool splitSections) + { + byte[] encoded = splitSections + ? [0x83, 0x80, 0x41, 0x00] + : [0x01, 0x64, 0x39, 0x34, 0x27, 0x64, 0x28, 0x40, 0x0A]; + int[] offsets = splitSections ? [12, 8] : [8, 12, -8, 4, 128, 132, -128, -124]; + int[] flags = splitSections ? [0, 0] : [3, 3, 2, 2, 1, 1, 0, 0]; + GcInfo info = DecodeWasmSlotTable(encoded); + GcSlotTable table = info.SlotTable; + + Assert.Equal(splitSections ? 1u : 0u, table.NumStackSlots); + Assert.Equal(splitSections ? 1u : 8u, table.NumUntracked); + Assert.Equal(splitSections ? 6 : 11, info.Size); + Assert.Equal(offsets.Length, table.GcSlots.Count); + for (int i = 0; i < offsets.Length; i++) + { + GcSlotFlags expectedFlags = (GcSlotFlags)flags[i]; + if (!splitSections || i != 0) + { + expectedFlags |= GcSlotFlags.GC_SLOT_UNTRACKED; + } + Assert.Equal(offsets[i], table.GcSlots[i].StackSlot.SpOffset); + Assert.Equal(expectedFlags, table.GcSlots[i].Flags); + } + } + + [Theory] + [InlineData(Machine.Amd64, true, 5u)] + [InlineData(Machine.Amd64, false, uint.MaxValue)] + [InlineData(WasmMachine.Wasm32, true, 2u)] + [InlineData(WasmMachine.Wasm32, false, uint.MaxValue)] + public void SlimHeaderUsesImplicitDefaultFrameRegister(Machine machine, bool hasFrameRegister, uint frameRegister) + { + byte[] encoded = [hasFrameRegister ? (byte)0x0A : (byte)0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; + using MemoryStream stream = new(encoded); + GcInfo info = new(new NativeReader(stream), 0, machine, 5); + + Assert.Equal(2, info.CodeLength); + Assert.Equal(frameRegister, info.StackBaseRegister); + Assert.Empty(info.SlotTable.GcSlots); + Assert.Equal(2, info.Size); + } + + [Theory] + [InlineData(0xA1)] + [InlineData(0xC1)] + public void WasmFatHeaderPreservesGenericContext(byte header) + { + byte[] encoded = [header, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00]; + using MemoryStream stream = new(encoded); + GcInfo info = new(new NativeReader(stream), 0, WasmMachine.Wasm32, 5); + + Assert.Equal(2, info.CodeLength); + Assert.Equal(2u, info.StackBaseRegister); + Assert.Equal(8, info.GenericsInstContextStackSlot); + Assert.Equal(1u, info.ValidRangeStart); + Assert.Empty(info.SlotTable.GcSlots); + Assert.Equal(5, info.Size); + } + + [Theory] + [InlineData(0x00, 0x00, 0u, 2)] + [InlineData(0x0E, 0x00, 224u, 2)] + [InlineData(0x7F, 0x00, 2032u, 2)] + [InlineData(0x80, 0x01, 2048u, 3)] + public void WasmUnwindFrameSizeUsesSixteenByteUnits(byte firstByte, byte secondByte, uint frameSize, int size) + { + byte[] encoded = size == 2 + ? [firstByte, 0x02] + : [firstByte, secondByte, 0x02]; + using MemoryStream stream = new(encoded); + ILCompiler.Reflection.ReadyToRun.Wasm32.UnwindInfo info = new(new NativeReader(stream), 0); + + Assert.Equal(frameSize, info.BytesUnwind); + Assert.Equal(4u, info.VirtualIPCount); + Assert.Equal(size, info.Size); + } + + private static GcInfo DecodeWasmSlotTable(byte[] slotTable) + { + byte[] encoded = new byte[slotTable.Length + 2]; + encoded[0] = 0x0A; + for (int i = 0; i < slotTable.Length; i++) + { + encoded[i + 1] |= (byte)(slotTable[i] << 6); + encoded[i + 2] |= (byte)(slotTable[i] >> 2); + } + using MemoryStream stream = new(encoded); + + return new GcInfo(new NativeReader(stream), 0, WasmMachine.Wasm32, 5); + } +} diff --git a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Amd64/GcInfo.cs b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Amd64/GcInfo.cs index b38be1644ff478..cc12f67eea0f67 100644 --- a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Amd64/GcInfo.cs +++ b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Amd64/GcInfo.cs @@ -151,9 +151,12 @@ public GcInfo(NativeReader imageReader, int offset, Machine machine, int version GenericsInstContextStackSlot = _gcInfoTypes.DenormalizeStackSlot(imageReader.DecodeVarLengthSigned(_gcInfoTypes.GENERICS_INST_CONTEXT_STACK_SLOT_ENCBASE, ref bitOffset)); } - if (_hasStackBaseRegister && !_slimHeader) + if (_hasStackBaseRegister) { - StackBaseRegister = _gcInfoTypes.DenormalizeStackBaseRegister(imageReader.DecodeVarLengthUnsigned(_gcInfoTypes.STACK_BASE_REGISTER_ENCBASE, ref bitOffset)); + uint normalizedRegister = _slimHeader + ? 0 + : imageReader.DecodeVarLengthUnsigned(_gcInfoTypes.STACK_BASE_REGISTER_ENCBASE, ref bitOffset); + StackBaseRegister = _gcInfoTypes.DenormalizeStackBaseRegister(normalizedRegister); } if (_hasSizeOfEditAndContinuePreservedArea) diff --git a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Amd64/GcSlotTable.cs b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Amd64/GcSlotTable.cs index 78e9c762b456ab..f29feaf5741910 100644 --- a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Amd64/GcSlotTable.cs +++ b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Amd64/GcSlotTable.cs @@ -110,7 +110,7 @@ public GcSlotTable(NativeReader imageReader, Machine machine, GcInfoTypes gcInfo { _machine = machine; - if (imageReader.ReadBits(1, ref bitOffset) != 0) + if (machine != WasmMachine.Wasm32 && imageReader.ReadBits(1, ref bitOffset) != 0) { NumRegisters = imageReader.DecodeVarLengthUnsigned(gcInfoTypes.NUM_REGISTERS_ENCBASE, ref bitOffset); } @@ -177,6 +177,25 @@ private void DecodeRegisters(NativeReader imageReader, GcInfoTypes gcInfoTypes, private void DecodeStackSlots(NativeReader imageReader, Machine machine, GcInfoTypes gcInfoTypes, uint nSlots, bool isUntracked, ref int bitOffset) { + if (machine == WasmMachine.Wasm32) + { + GcSlotFlags previousFlags = (GcSlotFlags)7; + int offset = 0; + for (int i = 0; i < nSlots; i++) + { + GcSlotFlags slotFlags = previousFlags == GcSlotFlags.GC_SLOT_BASE + ? GcSlotFlags.GC_SLOT_BASE + : (GcSlotFlags)imageReader.ReadBits(2, ref bitOffset); + offset = slotFlags != previousFlags + ? imageReader.DecodeVarLengthSigned(gcInfoTypes.STACK_SLOT_ENCBASE, ref bitOffset) + : offset + (int)imageReader.DecodeVarLengthUnsigned(gcInfoTypes.STACK_SLOT_DELTA_ENCBASE, ref bitOffset); + int byteOffset = gcInfoTypes.DenormalizeStackSlot(offset); + GcSlots.Add(new GcSlot(GcSlots.Count, -1, new GcStackSlot(byteOffset, GcStackSlotBase.GC_FRAMEREG_REL), slotFlags, isUntracked)); + previousFlags = slotFlags; + } + return; + } + // We have stack slots left and more room to predecode GcStackSlotBase spBase = (GcStackSlotBase)imageReader.ReadBits(2, ref bitOffset); int normSpOffset = imageReader.DecodeVarLengthSigned(gcInfoTypes.STACK_SLOT_ENCBASE, ref bitOffset); @@ -195,7 +214,7 @@ private void DecodeStackSlots(NativeReader imageReader, Machine machine, GcInfoT } else { - int normSpOffsetDelta = imageReader.DecodeVarLengthSigned(gcInfoTypes.STACK_SLOT_DELTA_ENCBASE, ref bitOffset); + int normSpOffsetDelta = (int)imageReader.DecodeVarLengthUnsigned(gcInfoTypes.STACK_SLOT_DELTA_ENCBASE, ref bitOffset); normSpOffset += normSpOffsetDelta; spOffset = gcInfoTypes.DenormalizeStackSlot(normSpOffset); } diff --git a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/GCInfoTypes.cs b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/GCInfoTypes.cs index 6dd5387285826f..2723eb7ab5f7c8 100644 --- a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/GCInfoTypes.cs +++ b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/GCInfoTypes.cs @@ -173,8 +173,8 @@ internal GcInfoTypes(Machine machine, bool denormalizeCodeOffsets) INTERRUPTIBLE_RANGE_DELTA2_ENCBASE = 5; REGISTER_ENCBASE = 3; REGISTER_DELTA_ENCBASE = REGISTER_ENCBASE; - STACK_SLOT_ENCBASE = 6; - STACK_SLOT_DELTA_ENCBASE = 4; + STACK_SLOT_ENCBASE = 3; + STACK_SLOT_DELTA_ENCBASE = 3; NUM_SAFE_POINTS_ENCBASE = 4; NUM_INTERRUPTIBLE_RANGES_ENCBASE = 1; POINTER_SIZE_ENCBASE = 3; @@ -259,6 +259,7 @@ internal int DenormalizeStackSlot(int x) case Machine.Amd64: return (x << 3); case Machine.ArmThumb2: + case WasmMachine.Wasm32: return (x << 2); case Machine.Arm64: case Machine.LoongArch64: @@ -282,6 +283,8 @@ internal uint DenormalizeStackBaseRegister(uint x) return ((x ^ 22) & 0x3); case Machine.RiscV64: return (x ^ 8); + case WasmMachine.Wasm32: + return (x ^ 2); } return x; } diff --git a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Wasm32/UnwindInfo.cs b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Wasm32/UnwindInfo.cs index 368d371d386f8f..f5f4ecf1066107 100644 --- a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Wasm32/UnwindInfo.cs +++ b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Wasm32/UnwindInfo.cs @@ -7,7 +7,7 @@ namespace ILCompiler.Reflection.ReadyToRun.Wasm32 { /// Parses the WASM unwind info blob used by ReadyToRun. /// The blob format is two unsigned LEB128 values in order: - /// BytesUnwind (frame size), followed by VirtualIPCount (virtual IP span / 2). + /// Frame size / 16, followed by virtual IP span / 2. /// is the number of bytes consumed while decoding those fields. public class UnwindInfo : BaseUnwindInfo { @@ -20,7 +20,7 @@ public UnwindInfo() { } public UnwindInfo(NativeReader imageReader, int offset) { uint startOffset = (uint)offset; - BytesUnwind = imageReader.ReadULEB128(ref offset); + BytesUnwind = checked(imageReader.ReadULEB128(ref offset) * 16); VirtualIPCount = imageReader.ReadULEB128(ref offset) * 2; Size = offset - (int)startOffset; } diff --git a/src/coreclr/vm/gcinfodecoder.cpp b/src/coreclr/vm/gcinfodecoder.cpp index 4777ef53ebe5c2..65cf9897bd4246 100644 --- a/src/coreclr/vm/gcinfodecoder.cpp +++ b/src/coreclr/vm/gcinfodecoder.cpp @@ -1159,9 +1159,16 @@ template void TGcInfoDecoder::ReportUn template void GcSlotDecoder::DecodeSlotTable(BitStreamReader& reader) { - if (reader.ReadOneFast()) + if constexpr (GcInfoEncoding::HAS_REGISTER_SLOTS) { - m_NumRegisters = (UINT32) reader.DecodeVarLengthUnsigned(GcInfoEncoding::NUM_REGISTERS_ENCBASE); + if (reader.ReadOneFast()) + { + m_NumRegisters = (UINT32) reader.DecodeVarLengthUnsigned(GcInfoEncoding::NUM_REGISTERS_ENCBASE); + } + else + { + m_NumRegisters = 0; + } } else { @@ -1178,11 +1185,11 @@ template void GcSlotDecoder::DecodeSlo numStackSlots = 0; m_NumUntracked = 0; } - m_NumSlots = m_NumRegisters + numStackSlots + m_NumUntracked; + m_NumSlots = GetNumRegisters() + numStackSlots + m_NumUntracked; UINT32 i = 0; - if(m_NumRegisters > 0) + if(GcInfoEncoding::HAS_REGISTER_SLOTS && m_NumRegisters > 0) { // We certainly predecode the first register @@ -1220,32 +1227,22 @@ template void GcSlotDecoder::DecodeSlo { // We have stack slots left and more room to predecode - GcStackSlotBase spBase = (GcStackSlotBase) reader.Read(2); - UINT32 normSpOffset = (INT32) reader.DecodeVarLengthSigned(GcInfoEncoding::STACK_SLOT_ENCBASE); + GcStackSlotBase spBase = ReadStackSlotBase(reader); + GcSlotFlags flags = GC_SLOT_BASE; + UINT32 normSpOffset = ReadStackSlotOffset(reader, flags, 0, true); INT32 spOffset = GcInfoEncoding::DENORMALIZE_STACK_SLOT(normSpOffset); - GcSlotFlags flags = (GcSlotFlags) reader.Read(2); m_SlotArray[i].Slot.Stack.SpOffset = spOffset; m_SlotArray[i].Slot.Stack.Base = spBase; m_SlotArray[i].Flags = flags; - UINT32 loopEnd = _min(m_NumRegisters + numStackSlots, MAX_PREDECODED_SLOTS); + UINT32 loopEnd = _min(GetNumRegisters() + numStackSlots, MAX_PREDECODED_SLOTS); for(i++; i < loopEnd; i++) { - spBase = (GcStackSlotBase) reader.Read(2); + spBase = ReadStackSlotBase(reader); - if(flags) - { - normSpOffset = (INT32) reader.DecodeVarLengthSigned(GcInfoEncoding::STACK_SLOT_ENCBASE); - spOffset = GcInfoEncoding::DENORMALIZE_STACK_SLOT(normSpOffset); - flags = (GcSlotFlags) reader.Read(2); - } - else - { - INT32 normSpOffsetDelta = (INT32) reader.DecodeVarLengthUnsigned(GcInfoEncoding::STACK_SLOT_DELTA_ENCBASE); - normSpOffset += normSpOffsetDelta; - spOffset = GcInfoEncoding::DENORMALIZE_STACK_SLOT(normSpOffset); - } + normSpOffset = ReadStackSlotOffset(reader, flags, normSpOffset, false); + spOffset = GcInfoEncoding::DENORMALIZE_STACK_SLOT(normSpOffset); m_SlotArray[i].Slot.Stack.SpOffset = spOffset; m_SlotArray[i].Slot.Stack.Base = spBase; @@ -1259,10 +1256,10 @@ template void GcSlotDecoder::DecodeSlo // Interpreter-TODO: Add a configurable way to skip encoding/decoding the base for the interpreter, because // all interpreter locals are at positive offsets relative to FP. - GcStackSlotBase spBase = (GcStackSlotBase) reader.Read(2); - UINT32 normSpOffset = (INT32) reader.DecodeVarLengthSigned(GcInfoEncoding::STACK_SLOT_ENCBASE); + GcStackSlotBase spBase = ReadStackSlotBase(reader); + GcSlotFlags flags = GC_SLOT_BASE; + UINT32 normSpOffset = ReadStackSlotOffset(reader, flags, 0, true); INT32 spOffset = GcInfoEncoding::DENORMALIZE_STACK_SLOT(normSpOffset); - GcSlotFlags flags = (GcSlotFlags) reader.Read(2); m_SlotArray[i].Slot.Stack.SpOffset = spOffset; m_SlotArray[i].Slot.Stack.Base = spBase; @@ -1271,20 +1268,10 @@ template void GcSlotDecoder::DecodeSlo UINT32 loopEnd = _min(m_NumSlots, MAX_PREDECODED_SLOTS); for(i++; i < loopEnd; i++) { - spBase = (GcStackSlotBase) reader.Read(2); + spBase = ReadStackSlotBase(reader); - if(flags) - { - normSpOffset = (INT32) reader.DecodeVarLengthSigned(GcInfoEncoding::STACK_SLOT_ENCBASE); - spOffset = GcInfoEncoding::DENORMALIZE_STACK_SLOT(normSpOffset); - flags = (GcSlotFlags) reader.Read(2); - } - else - { - INT32 normSpOffsetDelta = (INT32) reader.DecodeVarLengthUnsigned(GcInfoEncoding::STACK_SLOT_DELTA_ENCBASE); - normSpOffset += normSpOffsetDelta; - spOffset = GcInfoEncoding::DENORMALIZE_STACK_SLOT(normSpOffset); - } + normSpOffset = ReadStackSlotOffset(reader, flags, normSpOffset, false); + spOffset = GcInfoEncoding::DENORMALIZE_STACK_SLOT(normSpOffset); m_SlotArray[i].Slot.Stack.SpOffset = spOffset; m_SlotArray[i].Slot.Stack.Base = spBase; @@ -1310,7 +1297,7 @@ template void GcSlotDecoder::DecodeSlo // Skip any remaining registers - for(; i < m_NumRegisters; i++) + for(; GcInfoEncoding::HAS_REGISTER_SLOTS && i < m_NumRegisters; i++) { if(flags) { @@ -1325,44 +1312,34 @@ template void GcSlotDecoder::DecodeSlo if(numStackSlots > 0) { - if(i == m_NumRegisters) + if(i == GetNumRegisters()) { // Skip the first stack slot - reader.Read(2); - reader.DecodeVarLengthSigned(GcInfoEncoding::STACK_SLOT_ENCBASE); - flags = (GcSlotFlags) reader.Read(2); + ReadStackSlotBase(reader); + ReadStackSlotOffset(reader, flags, 0, true); i++; } // Skip any remaining stack slots - const UINT32 loopEnd = m_NumRegisters + numStackSlots; + const UINT32 loopEnd = GetNumRegisters() + numStackSlots; for(; i < loopEnd; i++) { - reader.Read(2); + ReadStackSlotBase(reader); - if(flags) - { - reader.DecodeVarLengthSigned(GcInfoEncoding::STACK_SLOT_ENCBASE); - flags = (GcSlotFlags) reader.Read(2); - } - else - { - reader.DecodeVarLengthUnsigned(GcInfoEncoding::STACK_SLOT_DELTA_ENCBASE); - } + ReadStackSlotOffset(reader, flags, 0, false); } } if(m_NumUntracked > 0) { - if(i == m_NumRegisters + numStackSlots) + if(i == GetNumRegisters() + numStackSlots) { // Skip the first untracked slot - reader.Read(2); - reader.DecodeVarLengthSigned(GcInfoEncoding::STACK_SLOT_ENCBASE); - flags = (GcSlotFlags) reader.Read(2); + ReadStackSlotBase(reader); + ReadStackSlotOffset(reader, flags, 0, true); i++; } @@ -1370,17 +1347,9 @@ template void GcSlotDecoder::DecodeSlo for(; i < m_NumSlots; i++) { - reader.Read(2); + ReadStackSlotBase(reader); - if(flags) - { - reader.DecodeVarLengthSigned(GcInfoEncoding::STACK_SLOT_ENCBASE); - flags = (GcSlotFlags) reader.Read(2); - } - else - { - reader.DecodeVarLengthUnsigned(GcInfoEncoding::STACK_SLOT_DELTA_ENCBASE); - } + ReadStackSlotOffset(reader, flags, 0, false); } } } @@ -1400,7 +1369,7 @@ template const GcSlotDesc* GcSlotDecoder const GcSlotDesc* GcSlotDecoderSlot.Stack.Base = (GcStackSlotBase) m_SlotReader.Read(2); - UINT32 normSpOffset = (INT32) m_SlotReader.DecodeVarLengthSigned(GcInfoEncoding::STACK_SLOT_ENCBASE); - m_pLastSlot->Slot.Stack.SpOffset = GcInfoEncoding::DENORMALIZE_STACK_SLOT(normSpOffset); - m_pLastSlot->Flags = (GcSlotFlags) m_SlotReader.Read(2); - } - else - { - m_pLastSlot->Slot.Stack.Base = (GcStackSlotBase) m_SlotReader.Read(2); - - if(m_pLastSlot->Flags) - { - INT32 normSpOffset = (INT32) m_SlotReader.DecodeVarLengthSigned(GcInfoEncoding::STACK_SLOT_ENCBASE); - m_pLastSlot->Slot.Stack.SpOffset = GcInfoEncoding::DENORMALIZE_STACK_SLOT(normSpOffset); - m_pLastSlot->Flags = (GcSlotFlags) m_SlotReader.Read(2); - } - else - { - INT32 normSpOffsetDelta = (INT32) m_SlotReader.DecodeVarLengthUnsigned(GcInfoEncoding::STACK_SLOT_DELTA_ENCBASE); - INT32 normSpOffset = normSpOffsetDelta + GcInfoEncoding::NORMALIZE_STACK_SLOT(m_pLastSlot->Slot.Stack.SpOffset); - m_pLastSlot->Slot.Stack.SpOffset = GcInfoEncoding::DENORMALIZE_STACK_SLOT(normSpOffset); - } - } + bool first = (m_NumDecodedSlots == GetNumRegisters()) || (m_NumDecodedSlots == GetNumTracked()); + m_pLastSlot->Slot.Stack.Base = ReadStackSlotBase(m_SlotReader); + INT32 previousOffset = first ? 0 : GcInfoEncoding::NORMALIZE_STACK_SLOT(m_pLastSlot->Slot.Stack.SpOffset); + INT32 normSpOffset = ReadStackSlotOffset(m_SlotReader, m_pLastSlot->Flags, previousOffset, first); + m_pLastSlot->Slot.Stack.SpOffset = GcInfoEncoding::DENORMALIZE_STACK_SLOT(normSpOffset); } m_NumDecodedSlots++; diff --git a/src/coreclr/vm/wasm/helpers.cpp b/src/coreclr/vm/wasm/helpers.cpp index 4311f5b61b87bd..a4ca2e289d9df8 100644 --- a/src/coreclr/vm/wasm/helpers.cpp +++ b/src/coreclr/vm/wasm/helpers.cpp @@ -1893,7 +1893,7 @@ static void WasmUnwindStackFrameCore(TADDR* pSP, TADDR* pIP, UINT_PTR ImageBase, else { PTR_BYTE pUnwindData = dac_cast(FunctionEntry->UnwindData + ImageBase); - *pSP = fp + DecodeULEB128AsU32(&pUnwindData); // Unwind the frame pointer to the callers stack pointer + *pSP = fp + DecodeULEB128AsU32(&pUnwindData) * 16; // Unwind the frame pointer to the callers stack pointer // A reverse-pinvoke frame's caller is native, not an R2R shadow frame; leave the IP unset so the walk // continues via the Frame chain instead of reading the native caller SP as a shadow frame. *pIP = callerIsNative ? 0 : GetWasmVirtualIPFromStackPointer(*pSP); From 7a25adfeeadce007fb6085714f9cb8c73250c472 Mon Sep 17 00:00:00 2001 From: David Wrighton Date: Wed, 14 Oct 2026 00:28:56 +0000 Subject: [PATCH 02/21] Exclude tracked-root decoding from Wasm ReadyToRun Retain and consume the zero tracked-slot and safepoint counts, while specializing away tracked descriptors and lifetime parsing. Keep interpreter and native-target tracked-root support. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/coreclr/gcinfo/gcinfoencoder.cpp | 1 + src/coreclr/inc/gcinfodecoder.h | 2 +- src/coreclr/inc/gcinfotypes.h | 9 +++++++++ src/coreclr/vm/gcinfodecoder.cpp | 21 ++++++++++++++------- 4 files changed, 25 insertions(+), 8 deletions(-) diff --git a/src/coreclr/gcinfo/gcinfoencoder.cpp b/src/coreclr/gcinfo/gcinfoencoder.cpp index 2efd80626214fa..5d897b438b1e50 100644 --- a/src/coreclr/gcinfo/gcinfoencoder.cpp +++ b/src/coreclr/gcinfo/gcinfoencoder.cpp @@ -1500,6 +1500,7 @@ template void TGcInfoEncoder::Build() if(numStackSlots > 0) { + _ASSERTE(GcInfoEncoding::HAS_TRACKED_SLOTS); GcSlotDesc *pSlotDesc; do { diff --git a/src/coreclr/inc/gcinfodecoder.h b/src/coreclr/inc/gcinfodecoder.h index cbb4ca3731aa0e..2ac0e75137d8d2 100644 --- a/src/coreclr/inc/gcinfodecoder.h +++ b/src/coreclr/inc/gcinfodecoder.h @@ -493,7 +493,7 @@ class GcSlotDecoder UINT32 GetNumTracked() { - return m_NumSlots - m_NumUntracked; + return GcInfoEncoding::HAS_TRACKED_SLOTS ? m_NumSlots - m_NumUntracked : 0; } UINT32 GetNumRegisters() diff --git a/src/coreclr/inc/gcinfotypes.h b/src/coreclr/inc/gcinfotypes.h index 877a8d1187c7c3..a21a0debab7b6b 100644 --- a/src/coreclr/inc/gcinfotypes.h +++ b/src/coreclr/inc/gcinfotypes.h @@ -618,6 +618,7 @@ struct AMD64GcInfoEncoding { static const int LIVESTATE_RLE_RUN_ENCBASE = 2; static const int LIVESTATE_RLE_SKIP_ENCBASE = 4; static const bool HAS_REGISTER_SLOTS = true; + static const bool HAS_TRACKED_SLOTS = true; static const bool HAS_STACK_SLOT_BASE = true; static const bool STACK_SLOT_FLAGS_FIRST = false; static const bool HAS_FIXED_STACK_PARAMETER_SCRATCH_AREA = true; @@ -680,6 +681,7 @@ struct ARM32GcInfoEncoding { static const int LIVESTATE_RLE_RUN_ENCBASE = 2; static const int LIVESTATE_RLE_SKIP_ENCBASE = 4; static const bool HAS_REGISTER_SLOTS = true; + static const bool HAS_TRACKED_SLOTS = true; static const bool HAS_STACK_SLOT_BASE = true; static const bool STACK_SLOT_FLAGS_FIRST = false; static const bool HAS_FIXED_STACK_PARAMETER_SCRATCH_AREA = true; @@ -745,6 +747,7 @@ struct ARM64GcInfoEncoding { static const int LIVESTATE_RLE_RUN_ENCBASE = 2; static const int LIVESTATE_RLE_SKIP_ENCBASE = 4; static const bool HAS_REGISTER_SLOTS = true; + static const bool HAS_TRACKED_SLOTS = true; static const bool HAS_STACK_SLOT_BASE = true; static const bool STACK_SLOT_FLAGS_FIRST = false; static const bool HAS_FIXED_STACK_PARAMETER_SCRATCH_AREA = true; @@ -808,6 +811,7 @@ struct LoongArch64GcInfoEncoding { static const int LIVESTATE_RLE_RUN_ENCBASE = 2; static const int LIVESTATE_RLE_SKIP_ENCBASE = 4; static const bool HAS_REGISTER_SLOTS = true; + static const bool HAS_TRACKED_SLOTS = true; static const bool HAS_STACK_SLOT_BASE = true; static const bool STACK_SLOT_FLAGS_FIRST = false; static const bool HAS_FIXED_STACK_PARAMETER_SCRATCH_AREA = true; @@ -872,6 +876,7 @@ struct RISCV64GcInfoEncoding { static const int LIVESTATE_RLE_RUN_ENCBASE = 2; static const int LIVESTATE_RLE_SKIP_ENCBASE = 4; static const bool HAS_REGISTER_SLOTS = true; + static const bool HAS_TRACKED_SLOTS = true; static const bool HAS_STACK_SLOT_BASE = true; static const bool STACK_SLOT_FLAGS_FIRST = false; static const bool HAS_FIXED_STACK_PARAMETER_SCRATCH_AREA = true; @@ -931,6 +936,7 @@ struct X86GcInfoEncoding { static const int LIVESTATE_RLE_RUN_ENCBASE = 2; static const int LIVESTATE_RLE_SKIP_ENCBASE = 4; static const bool HAS_REGISTER_SLOTS = true; + static const bool HAS_TRACKED_SLOTS = true; static const bool HAS_STACK_SLOT_BASE = true; static const bool STACK_SLOT_FLAGS_FIRST = false; static const bool HAS_FIXED_STACK_PARAMETER_SCRATCH_AREA = true; @@ -992,6 +998,8 @@ struct Wasm32GcInfoEncoding { static const int LIVESTATE_RLE_SKIP_ENCBASE = 4; // Register-free encodings omit the register-presence bit from the slot table. static const bool HAS_REGISTER_SLOTS = false; + // The wire format retains a zero tracked-slot count, but Wasm R2R only reports untracked roots. + static const bool HAS_TRACKED_SLOTS = false; // All slots are frame-relative, so no per-slot stack base is encoded. static const bool HAS_STACK_SLOT_BASE = false; // Equal flags use offset deltas; ordinary flags are implicit after their first slot. @@ -1061,6 +1069,7 @@ struct InterpreterGcInfoEncoding { static const int LIVESTATE_RLE_RUN_ENCBASE = 2; static const int LIVESTATE_RLE_SKIP_ENCBASE = 4; static const bool HAS_REGISTER_SLOTS = false; + static const bool HAS_TRACKED_SLOTS = true; static const bool HAS_STACK_SLOT_BASE = true; static const bool STACK_SLOT_FLAGS_FIRST = false; static const bool HAS_FIXED_STACK_PARAMETER_SCRATCH_AREA = false; diff --git a/src/coreclr/vm/gcinfodecoder.cpp b/src/coreclr/vm/gcinfodecoder.cpp index 65cf9897bd4246..5c4b9050e2a4f8 100644 --- a/src/coreclr/vm/gcinfodecoder.cpp +++ b/src/coreclr/vm/gcinfodecoder.cpp @@ -372,6 +372,7 @@ TGcInfoDecoder::TGcInfoDecoder( #ifdef PARTIALLY_INTERRUPTIBLE_GC_SUPPORTED m_NumSafePoints = (UINT32) m_Reader.DecodeVarLengthUnsigned(GcInfoEncoding::NUM_SAFE_POINTS_ENCBASE); m_SafePointIndex = m_NumSafePoints; + _ASSERTE(GcInfoEncoding::HAS_TRACKED_SLOTS || m_NumSafePoints == 0); #endif if (slimHeader || !GcInfoEncoding::HAS_INTERRUPTIBLE_RANGES) @@ -384,7 +385,7 @@ TGcInfoDecoder::TGcInfoDecoder( } #ifdef PARTIALLY_INTERRUPTIBLE_GC_SUPPORTED - if(flags & (DECODE_GC_LIFETIMES | DECODE_INTERRUPTIBILITY)) + if(GcInfoEncoding::HAS_TRACKED_SLOTS && (flags & (DECODE_GC_LIFETIMES | DECODE_INTERRUPTIBILITY))) { if(m_NumSafePoints) { @@ -401,7 +402,7 @@ TGcInfoDecoder::TGcInfoDecoder( m_SafePointIndex = FindSafePoint(offset); } } - else if(flags & DECODE_FOR_RANGES_CALLBACK) + else if(GcInfoEncoding::HAS_TRACKED_SLOTS && (flags & DECODE_FOR_RANGES_CALLBACK)) { // Note that normalization as a code offset can be different than // normalization as code length @@ -769,7 +770,11 @@ template bool TGcInfoDecoder::Enumerat #ifdef PARTIALLY_INTERRUPTIBLE_GC_SUPPORTED - if(m_SafePointIndex < m_NumSafePoints && !executionAborted) + if constexpr (!GcInfoEncoding::HAS_TRACKED_SLOTS) + { + _ASSERTE(m_NumSafePoints == 0 && m_NumInterruptibleRanges == 0); + } + else if(m_SafePointIndex < m_NumSafePoints && !executionAborted) { // Skip interruptibility information for(UINT32 i=0; i bool TGcInfoDecoder::Enumerat if (reportUntrackedOnly) goto ReportUntracked; + if constexpr (GcInfoEncoding::HAS_TRACKED_SLOTS) { UINT32 numSlots = slotDecoder.GetNumTracked(); @@ -1185,7 +1191,8 @@ template void GcSlotDecoder::DecodeSlo numStackSlots = 0; m_NumUntracked = 0; } - m_NumSlots = GetNumRegisters() + numStackSlots + m_NumUntracked; + _ASSERTE(GcInfoEncoding::HAS_TRACKED_SLOTS || numStackSlots == 0); + m_NumSlots = GetNumRegisters() + (GcInfoEncoding::HAS_TRACKED_SLOTS ? numStackSlots : 0) + m_NumUntracked; UINT32 i = 0; @@ -1223,7 +1230,7 @@ template void GcSlotDecoder::DecodeSlo } } - if((numStackSlots > 0) && (i < MAX_PREDECODED_SLOTS)) + if(GcInfoEncoding::HAS_TRACKED_SLOTS && (numStackSlots > 0) && (i < MAX_PREDECODED_SLOTS)) { // We have stack slots left and more room to predecode @@ -1310,7 +1317,7 @@ template void GcSlotDecoder::DecodeSlo } } - if(numStackSlots > 0) + if(GcInfoEncoding::HAS_TRACKED_SLOTS && numStackSlots > 0) { if(i == GetNumRegisters()) { @@ -1334,7 +1341,7 @@ template void GcSlotDecoder::DecodeSlo if(m_NumUntracked > 0) { - if(i == GetNumRegisters() + numStackSlots) + if(i == GetNumTracked()) { // Skip the first untracked slot From 6148d5d364311627292731b4fcca7ed84c8e14b9 Mon Sep 17 00:00:00 2001 From: David Wrighton Date: Wed, 14 Oct 2026 22:24:38 +0000 Subject: [PATCH 03/21] Version standalone Wasm GC and unwind metadata encoding Use ReadyToRun 33.0 to distinguish the compact codec from older images and the separate proposed 32.0 frame-identity format. Reject older Wasm images in single-file and composite loading and in the managed reader before decoding. Keep native minimum-version handling unchanged. Add cross-target header compatibility regressions and document the encoding. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/design/coreclr/botr/readytorun-format.md | 18 +++++++- src/coreclr/inc/readytorun.h | 7 ++- .../nativeaot/Runtime/inc/ModuleHeaders.h | 5 ++- .../Common/Internal/Runtime/ModuleHeaders.cs | 5 ++- .../TestCases/R2RTestSuites.cs | 43 +++++++++++++++++++ .../ReadyToRunReader.cs | 8 +++- src/coreclr/vm/nativeimage.cpp | 7 +++ src/coreclr/vm/readytoruninfo.cpp | 8 ++++ 8 files changed, 93 insertions(+), 8 deletions(-) diff --git a/docs/design/coreclr/botr/readytorun-format.md b/docs/design/coreclr/botr/readytorun-format.md index 91bbc3cfa5cc54..a76035355eb70c 100644 --- a/docs/design/coreclr/botr/readytorun-format.md +++ b/docs/design/coreclr/botr/readytorun-format.md @@ -455,14 +455,30 @@ two consecutive ULEB128 values: | Order | Encoding | Value |------:|:---------|:----- -| 1 | ULEB128 | Frame size in bytes (the number of bytes to unwind from the stack) +| 1 | ULEB128 | Frame size divided by 16 (the number of 16-byte units to unwind from the stack) | 2 | ULEB128 | Virtual IP count divided by 2 (the number of virtual IPs logically present in the function, halved) +ReadyToRun format 33.0 uses this scaled frame size and the compact Wasm GC encoding described +below. Earlier Wasm images use incompatible encodings and must be regenerated. The Wasm runtime +and managed reader reject them before interpreting their unwind or GC metadata; native targets +retain their existing minimum supported format version. + The virtual IP count (after multiplying by 2) gives the span of virtual IPs covered by this function or funclet. All virtual IPs are forced to even numbers so that the runtime can force all virtual ips to have odd numbers and fit into the address space in a manner which cannot conflict with either interpreter IPs or PortableEntryPoint structures. +### GC info (wasm) + +Wasm GC slot tables omit the register-presence bit and per-slot stack base: roots are implicitly +frame-relative, with offsets stored in 4-byte pointer units. Slim headers use normalized zero +for the default frame register. Slot flags precede offsets; equal-flag runs use unsigned offset +deltas, and ordinary object flags are implicit after their first slot in each section. + +Wasm ReadyToRun reports only untracked roots. The zero tracked-slot and safepoint counts remain +in the stream, but its runtime decoder omits tracked-slot descriptor and lifetime parsing. +The interpreter retains tracked-root support and its own register-free encoding. + ## ReadyToRunSectionType.MethodDefEntryPoints This section contains a native format sparse array (see 4 Native Format) that maps methoddef rows to diff --git a/src/coreclr/inc/readytorun.h b/src/coreclr/inc/readytorun.h index acd6516506ab41..a5267fa3adcd8d 100644 --- a/src/coreclr/inc/readytorun.h +++ b/src/coreclr/inc/readytorun.h @@ -19,10 +19,11 @@ // src/coreclr/nativeaot/Runtime/inc/ModuleHeaders.h // If you update this, ensure you run `git grep MINIMUM_READYTORUN_MAJOR_VERSION` // and handle pending work. -#define READYTORUN_MAJOR_VERSION 31 -#define READYTORUN_MINOR_VERSION 0x0001 +#define READYTORUN_MAJOR_VERSION 33 +#define READYTORUN_MINOR_VERSION 0x0000 #define MINIMUM_READYTORUN_MAJOR_VERSION 26 +#define MINIMUM_WASM_READYTORUN_MAJOR_VERSION 33 // R2R Version 2.1 adds the InliningInfo section // R2R Version 2.2 adds the ProfileDataInfo section @@ -82,6 +83,8 @@ // method's ReadyToRun entry point and fixups. // R2R Version 31.1 adds READYTORUN_FLAG_SINGLE_THREADED, which records that the image lays out [ThreadStatic] fields as regular statics // for a runtime built without FEATURE_MULTITHREADING. +// R2R Version 33 compacts Wasm GC slot tables and encodes unwind frame sizes in 16-byte units. +// Wasm images from earlier versions must be regenerated. struct READYTORUN_CORE_HEADER { diff --git a/src/coreclr/nativeaot/Runtime/inc/ModuleHeaders.h b/src/coreclr/nativeaot/Runtime/inc/ModuleHeaders.h index 5c0fc628ffd3e0..ce385687896f06 100644 --- a/src/coreclr/nativeaot/Runtime/inc/ModuleHeaders.h +++ b/src/coreclr/nativeaot/Runtime/inc/ModuleHeaders.h @@ -11,8 +11,9 @@ struct ReadyToRunHeaderConstants { static const uint32_t Signature = 0x00525452; // 'RTR' - static const uint32_t CurrentMajorVersion = 31; - static const uint32_t CurrentMinorVersion = 1; + static const uint32_t CurrentMajorVersion = 33; + static const uint32_t CurrentMinorVersion = 0; + static const uint32_t MinimumWasmMajorVersion = 33; }; struct ReadyToRunHeader diff --git a/src/coreclr/tools/Common/Internal/Runtime/ModuleHeaders.cs b/src/coreclr/tools/Common/Internal/Runtime/ModuleHeaders.cs index a67995d9889062..8283e7d70e7d65 100644 --- a/src/coreclr/tools/Common/Internal/Runtime/ModuleHeaders.cs +++ b/src/coreclr/tools/Common/Internal/Runtime/ModuleHeaders.cs @@ -15,8 +15,9 @@ internal struct ReadyToRunHeaderConstants { public const uint Signature = 0x00525452; // 'RTR' - public const ushort CurrentMajorVersion = 31; - public const ushort CurrentMinorVersion = 1; + public const ushort CurrentMajorVersion = 33; + public const ushort CurrentMinorVersion = 0; + public const ushort MinimumWasmMajorVersion = 33; } #if READYTORUN #pragma warning disable 0169 diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/TestCases/R2RTestSuites.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/TestCases/R2RTestSuites.cs index 55728597715585..b07dc9f89dcc29 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/TestCases/R2RTestSuites.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/TestCases/R2RTestSuites.cs @@ -30,6 +30,49 @@ public R2RTestSuites(ITestOutputHelper output) _output = output; } + [Theory] + [InlineData(false)] + [InlineData(true)] + public void WasmGcEncodingRejectsOlderReadyToRunHeaders(bool composite) + { + const ushort CompactWasmGcFormatVersion = 33; + CompiledAssembly input = new() + { + AssemblyName = nameof(WasmGcEncodingRejectsOlderReadyToRunHeaders), + SourceResourceNames = ["Webcil/WasmWebcilModule.cs"], + }; + + new R2RTestRunner(_output).Run(new R2RTestCase( + nameof(WasmGcEncodingRejectsOlderReadyToRunHeaders), + [ + new(nameof(WasmGcEncodingRejectsOlderReadyToRunHeaders), [new CrossgenAssembly(input)]) + { + Options = composite ? [Crossgen2Option.Composite] : [], + OutputFileExtension = TestPaths.IsWasmTarget ? ".wasm" : ".dll", + Validate = reader => + { + Assert.Equal(CompactWasmGcFormatVersion, reader.ReadyToRunHeader.MajorVersion); + int headerOffset = reader.GetOffset(reader.ReadyToRunHeader.RelativeVirtualAddress); + foreach (ushort majorVersion in new ushort[] { 31, 32, CompactWasmGcFormatVersion }) + { + byte[] image = (byte[])reader.Image.Clone(); + BinaryPrimitives.WriteUInt16LittleEndian(image.AsSpan(headerOffset + sizeof(uint)), majorVersion); + ReadyToRunReader patchedReader = new(null, reader.Filename, image); + if (TestPaths.IsWasmTarget && majorVersion < CompactWasmGcFormatVersion) + { + Assert.Throws(() => _ = patchedReader.ReadyToRunHeader); + Assert.Throws(() => _ = patchedReader.ReadyToRunHeader); + } + else + { + Assert.Equal(majorVersion, patchedReader.ReadyToRunHeader.MajorVersion); + } + } + }, + }, + ])); + } + [ConditionalTheory(typeof(TestPaths), nameof(TestPaths.IsXArchTarget))] [InlineData(1)] [InlineData(2)] diff --git a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/ReadyToRunReader.cs b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/ReadyToRunReader.cs index 7a57773a932dcb..3ae6615dfa301b 100644 --- a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/ReadyToRunReader.cs +++ b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/ReadyToRunReader.cs @@ -723,7 +723,13 @@ private unsafe void EnsureHeader() // Initialize R2RHeader Debug.Assert(_readyToRunHeaderRVA != 0); int r2rHeaderOffset = GetOffset(_readyToRunHeaderRVA); - _readyToRunHeader = new ReadyToRunHeader(ImageReader, _readyToRunHeaderRVA, r2rHeaderOffset); + ReadyToRunHeader header = new ReadyToRunHeader(ImageReader, _readyToRunHeaderRVA, r2rHeaderOffset); + if (_machine == WasmMachine.Wasm32 && header.MajorVersion < ReadyToRunHeaderConstants.MinimumWasmMajorVersion) + { + throw new BadImageFormatException( + $"Wasm ReadyToRun images before format {ReadyToRunHeaderConstants.MinimumWasmMajorVersion}.0 use an unsupported GC/unwind encoding. Recompile '{Filename}' with current crossgen2."); + } + _readyToRunHeader = header; FindOwnerCompositeExecutable(); diff --git a/src/coreclr/vm/nativeimage.cpp b/src/coreclr/vm/nativeimage.cpp index 5c197a2186bbe0..d01c209bbb381a 100644 --- a/src/coreclr/vm/nativeimage.cpp +++ b/src/coreclr/vm/nativeimage.cpp @@ -298,6 +298,13 @@ NativeImage *NativeImage::Open( COMPlusThrowHR(COR_E_BADIMAGEFORMAT); } +#ifdef TARGET_WASM + if (pHeader->MajorVersion < MINIMUM_WASM_READYTORUN_MAJOR_VERSION) + { + COMPlusThrowHR(COR_E_BADIMAGEFORMAT); + } +#endif // TARGET_WASM + NewHolder image = new NativeImage(pAssemblyBinder, loadedImageHolder.Extract(), nativeImageFileName); AllocMemTracker amTracker; image->Initialize(pHeader, pLoaderAllocator, &amTracker); diff --git a/src/coreclr/vm/readytoruninfo.cpp b/src/coreclr/vm/readytoruninfo.cpp index 1b6d1fea438995..82222a49a176ac 100644 --- a/src/coreclr/vm/readytoruninfo.cpp +++ b/src/coreclr/vm/readytoruninfo.cpp @@ -671,6 +671,14 @@ PTR_ReadyToRunInfo ReadyToRunInfo::Initialize(Module * pModule, AllocMemTracker return NULL; } +#ifdef TARGET_WASM + if (pHeader->MajorVersion < MINIMUM_WASM_READYTORUN_MAJOR_VERSION) + { + DoLog("Ready to Run disabled - unsupported Wasm GC/unwind encoding"); + return NULL; + } +#endif // TARGET_WASM + LoaderHeap *pHeap = pModule->GetLoaderAllocator()->GetHighFrequencyHeap(); NativeImage *nativeImage = NULL; From b89730723e664a0036765f59a77e44ab24a3ac68 Mon Sep 17 00:00:00 2001 From: David Wrighton Date: Wed, 21 Oct 2026 21:32:25 +0000 Subject: [PATCH 04/21] Compact shared GC slot encoding and tune Wasm metadata for Brotli Generalize shrinking slot flags and bounded register encoding, pack Wasm unwind data, and omit redundant Wasm header fields. Select the whole-image Brotli-winning integer bases while retaining version-aware readers and focused decoder coverage. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/design/coreclr/botr/readytorun-format.md | 89 ++- docs/design/datacontracts/GCInfo.md | 28 +- docs/design/datacontracts/StackWalk.md | 4 +- src/coreclr/gcinfo/gcinfoencoder.cpp | 280 ++++----- src/coreclr/inc/clrnt.h | 10 +- src/coreclr/inc/gcinfo.h | 7 +- src/coreclr/inc/gcinfodecoder.h | 84 ++- src/coreclr/inc/gcinfoencoder.h | 17 +- src/coreclr/inc/gcinfotypes.h | 35 +- src/coreclr/inc/readytorun.h | 3 +- src/coreclr/jit/gcencode.cpp | 2 +- src/coreclr/jit/unwindwasm.cpp | 25 +- .../GcInfoDecoderTests.cs | 574 ++++++++++++++---- .../ReadyToRun/RuntimeFunctionsTableNode.cs | 6 +- .../Amd64/GcInfo.cs | 31 +- .../Amd64/GcSlotTable.cs | 82 ++- .../GCInfoTypes.cs | 13 +- .../NativeReader.cs | 4 +- .../ReadyToRunMethod.cs | 3 +- .../Wasm32/UnwindInfo.cs | 10 +- src/coreclr/vm/codeman.cpp | 3 +- src/coreclr/vm/gcinfodecoder.cpp | 131 ++-- src/coreclr/vm/readytoruninfo.cpp | 31 +- src/coreclr/vm/wasm/helpers.cpp | 10 +- ...ecutionManagerCore.ReadyToRunJitManager.cs | 1 + .../Helpers/UnwindDataSize.cs | 19 +- .../Contracts/GCInfo/GCInfoDecoder.cs | 122 +++- .../GCInfo/PlatformTraits/ARMGCInfoTraits.cs | 1 + .../GCInfo/PlatformTraits/IGCInfoTraits.cs | 4 + .../PlatformTraits/InterpreterGCInfoTraits.cs | 1 + .../GCInfo/PlatformTraits/WasmGCInfoTraits.cs | 19 +- .../Contracts/GCInfo/X86/GCInfo.cs | 2 +- .../StackWalk/Context/Wasm/WasmUnwinder.cs | 25 +- .../ExecutionManager/ExecutionManagerTests.cs | 17 +- .../cdac/tests/UnitTests/GCInfoTests.cs | 198 ++++++ .../cdac/tests/UnitTests/StackWalkTests.cs | 24 +- .../cdac/tests/UnitTests/WasmUnwinderTests.cs | 41 +- 37 files changed, 1345 insertions(+), 611 deletions(-) create mode 100644 src/native/managed/cdac/tests/UnitTests/GCInfoTests.cs diff --git a/docs/design/coreclr/botr/readytorun-format.md b/docs/design/coreclr/botr/readytorun-format.md index f395ef8d43ac82..0e18adaa1c3dfc 100644 --- a/docs/design/coreclr/botr/readytorun-format.md +++ b/docs/design/coreclr/botr/readytorun-format.md @@ -460,15 +460,24 @@ value containing the minimum WebAssembly function table index for the image. ### UnwindInfo (wasm) -On WebAssembly, the unwind info blob associated with each `RUNTIME_FUNCTION` entry is encoded as -two consecutive ULEB128 values: - -| Order | Encoding | Value -|------:|:---------|:----- -| 1 | ULEB128 | Frame size divided by 16 (the number of 16-byte units to unwind from the stack) -| 2 | ULEB128 | Virtual IP count divided by 2 (the number of virtual IPs logically present in the function, halved) - -ReadyToRun format 33.0 uses this scaled frame size and the compact Wasm GC encoding described +On WebAssembly, the unwind info blob associated with each `RUNTIME_FUNCTION` entry is a single +ULEB128-encoded unsigned 64-bit integer. It interleaves the frame size divided by 16 and the +virtual IP count divided by 2: + +| Encoded bits | Value +|-------------:|:----- +| 3:0 | Frame size in 16-byte units, bits 3:0 +| 7:4 | Virtual IP count in 2-IP units, bits 3:0 +| 11:8 | Frame size in 16-byte units, bits 7:4 +| 15:12 | Virtual IP count in 2-IP units, bits 7:4 +| 31:16 | Frame size in 16-byte units, bits 23:8 +| 47:32 | Virtual IP count in 2-IP units, bits 23:8 + +The largest representable frame size is `2^28 - 16` bytes; the largest virtual IP count is +`2^25 - 2`. The encoded value requires at most seven bytes, and one byte when the frame size +is below 256 bytes and the virtual IP count is below 16. + +ReadyToRun format 33.0 uses this packed unwind data and the compact Wasm GC encoding described below. Earlier Wasm images use incompatible encodings and must be regenerated. The Wasm runtime and managed reader reject them before interpreting their unwind or GC metadata; native targets retain their existing minimum supported format version. @@ -478,15 +487,65 @@ function or funclet. All virtual IPs are forced to even numbers so that the runt ips to have odd numbers and fit into the address space in a manner which cannot conflict with either interpreter IPs or PortableEntryPoint structures. +### GC info + +ReadyToRun format 33.0 uses GCInfo v6. On every platform using the shared GCInfo encoding, +tracked and untracked stack slots are each sorted in descending flag order: +pinned interior pointers, pinned object references, interior pointers, then ordinary object +references. + +Register slots encode their interior/pinned flags before the register number. Slots are sorted +in descending flag order, so all pinned slots precede unpinned slots. The first register carries +both flag bits. Subsequent registers carry both bits while the preceding slot is pinned, only +the interior bit after an unpinned interior slot, and no flag bits after an ordinary reference. +Once an unpinned slot has been seen, the pinned bit is therefore implicitly zero. +The first register in each flag group uses an absolute register number; subsequent registers +with the same flags use the difference from the preceding register number minus one. + +Register numbers and deltas use at most two chunks. The first chunk contains `ENCBASE` low +payload bits followed by one continuation bit. If set, the second chunk contains all remaining +bits of the target register number, without another continuation bit: + +| Target | Register bits | Absolute ENCBASE / total bits | Delta ENCBASE / total bits | +| --- | --- | --- | --- | +| x64 (including APX R16-R31), Arm64, LoongArch64, RISC-V64 | 5 | 3 / 4 or 6 | 2 / 3 or 6 | +| Arm32 | 4 | 2 / 3 or 5 | 1 / 2 or 5 | +| Shared-format x86 | 3 | 3 / 4 | 3 / 4 | + +This reserves x64 encoding space for APX roots without changing register allocation or +runtime context support for them. Legacy x86 GCInfo uses its separate, unchanged format. +GCInfo versions before v6 retain the original flags-after-absolute, unbounded register encoding. + +Stack slots use the same shrinking flag bits as registers: two bits initially and after a +pinned slot, only the interior bit after an unpinned interior slot, and no flag bits after an +ordinary reference. Within each flag group, slots are sorted by base, SP before Frame, then +by ascending offset. Each non-Wasm slot has one base bit: `0` for SP-relative and `1` for +frame-relative. Caller-SP-relative slots are not represented in v6. + +The first slot of each flags/base combination has a signed absolute stack offset, followed +by unsigned offset deltas for the remaining slots in that group. Flags, base, and offset state +reset at the tracked/untracked boundary. Platform-specific offset normalization is unchanged. +Older non-Wasm ReadyToRun images retain their original GCInfo decoding. + ### GC info (wasm) Wasm GC slot tables omit the register-presence bit and per-slot stack base: roots are implicitly -frame-relative, with offsets stored in 4-byte pointer units. Slim headers use normalized zero -for the default frame register. Slot flags precede offsets; equal-flag runs use unsigned offset -deltas, and ordinary object flags are implicit after their first slot in each section. - -Wasm ReadyToRun reports only untracked roots. The zero tracked-slot and safepoint counts remain -in the stream, but its runtime decoder omits tracked-slot descriptor and lifetime parsing. +frame-relative, with offsets stored in 4-byte pointer units. Both header forms implicitly use +normalized zero for the default frame register: neither its presence bit nor its register +number is encoded. Fat headers therefore contain nine flag bits instead of ten. The prolog +size is also implicit at one virtual-IP unit; its encoded size-minus-one field is omitted. +Stack slot flags use the platform-independent shrinking bits described above. + +Wasm slim headers imply zero safe points and omit the count. Methods with nonzero safe-point +counts must use fat headers, which retain the count and safe-point data. Non-Wasm slim headers +retain their safe-point counts. + +Wasm v6 uses ENCBASE 5 for code lengths, 7 for untracked-slot counts, 3 for safe-point counts, +and 4 for reverse-P/Invoke frame offsets. These values favor whole-image Brotli compression +rather than the smallest uncompressed GC payload. + +Wasm ReadyToRun reports only untracked roots. The zero tracked-slot count remains in the +stream, but its runtime decoder omits tracked-slot descriptor and lifetime parsing. The interpreter retains tracked-root support and its own register-free encoding. ## ReadyToRunSectionType.MethodDefEntryPoints diff --git a/docs/design/datacontracts/GCInfo.md b/docs/design/datacontracts/GCInfo.md index a136cffdac2dbc..e330734a05ea18 100644 --- a/docs/design/datacontracts/GCInfo.md +++ b/docs/design/datacontracts/GCInfo.md @@ -5,10 +5,15 @@ This contract is for fetching information related to GCInfo associated with nati The GCInfo contract has platform specific implementations as GCInfo differs per architecture. With the exception of x86, all platforms have a common encoding scheme with different encoding lengths and normalization functions for data. x86 uses an entirely different scheme which is partially supported by this contract. WebAssembly uses the common decoder with `Wasm32GcInfoEncoding` traits from -`src/coreclr/inc/gcinfotypes.h`: code lengths/offsets and stack offsets are -unscaled, the code-length encoding base is 6, and there is no fixed stack +`src/coreclr/inc/gcinfotypes.h`: code lengths/offsets are unscaled, stack offsets +are in four-byte pointer units, the code-length encoding base is 6, and there is no fixed stack parameter scratch area. The platform encoding has no interruptible-range -count in its fat header (`HAS_INTERRUPTIBLE_RANGES` is false). +count in its fat header (`HAS_INTERRUPTIBLE_RANGES` is false). Starting with GCInfo +version 6, both header forms omit the frame-register presence bit and register value, +implicitly using normalized register zero (physical register 2). The prolog-size-minus-one +field is omitted and its normalized prolog size is implicitly one when needed for +GS-cookie or generic-context validity. Slim headers imply zero safe points and omit the +count; nonzero safe-point counts require fat headers and remain explicitly encoded. `DecodeInterpreterGCInfo` uses the separate interpreter traits even on WebAssembly, including its code-length encoding base of 8 and its interruptible-range count field. @@ -198,6 +203,23 @@ Constants: The GCInfo format consists of a header structure and following data types. The header is either 'slim' for simple methods that can use the compact encoding scheme or a 'fat' header containing more details. +The tables and decoding pseudocode below describe the common layout. Wasm platform GCInfo +version 6 omits `UsingStackBaseRegister`, `StackBaseRegister`, and `PrologSize` as described +above, and omits `NumSafePoints` only for slim headers. Its fat `HeaderFlags` occupy nine +bits: bit `0x40` is omitted from the stream, higher flag bits shift down one position, and +the decoder restores `GC_INFO_HAS_STACK_BASE_REGISTER` implicitly. Interpreter headers +retain the common layout on every architecture. + +Wasm version 6 uses the following tuned variable-length integer bases. Earlier Wasm +versions retain their original bases. + +| Constant | Wasm v6 ENCBASE | +| --- | --- | +| `CODE_LENGTH_ENCBASE` | 5 | +| `NUM_UNTRACKED_SLOTS_ENCBASE` | 7 | +| `NUM_SAFE_POINTS_ENCBASE` | 3 | +| `REVERSE_PINVOKE_FRAME_ENCBASE` | 4 | + #### GCInfo Header ##### Slim Header diff --git a/docs/design/datacontracts/StackWalk.md b/docs/design/datacontracts/StackWalk.md index e059d7a5b9039b..97ae6f3b1658cb 100644 --- a/docs/design/datacontracts/StackWalk.md +++ b/docs/design/datacontracts/StackWalk.md @@ -488,7 +488,7 @@ Root-method frame identities have three forms: A funclet instead stores its establishing-frame pointer plus two, giving the identity low bits `10`. These tags are followed until the root-method frame is reached. The physical funclet frame supplies the function-local virtual IP, while the root frame supplies the identity used to find the controlling method's base virtual IP. cDAC requires each establishing-frame link to move toward the caller and bounds the traversal so corrupt target memory cannot create an unbounded walk. -**WASM R2R unwinding.** The virtual IP is the identity-derived method base plus twice the physical frame's stored function-local value. `WasmContext.Unwind` passes its current virtual IP as the control PC to `IExecutionManager.TryGetUnwindInfo`, reads the fixed frame size as a uint32 ULEB128 value from `unwindInfoBaseAddress + RuntimeFunction.UnwindData`, and adds that size to the physical frame base. A zero frame size terminates the R2R walk because it would make no progress; malformed uint32 ULEB128 data is invalid. +**WASM R2R unwinding.** The virtual IP is the identity-derived method base plus twice the physical frame's stored function-local value. `WasmContext.Unwind` passes its current virtual IP as the control PC to `IExecutionManager.TryGetUnwindInfo` and reads one uint64 ULEB128 value from `unwindInfoBaseAddress + RuntimeFunction.UnwindData`. This value interleaves the frame size in 16-byte units and virtual IP count in 2-IP units, as specified in the [ReadyToRun format](../coreclr/botr/readytorun-format.md#unwindinfo-wasm). The decoded frame size is added to the physical frame base. A zero frame size terminates the R2R walk because it would make no progress; malformed uint64 ULEB128 data is invalid. For a managed caller, the resulting stack pointer identifies the caller's R2R frame record; its virtual IP and logical frame pointer are resolved as above. When the current frame has a positive odd reverse-P/Invoke identity, unwinding still preserves the advanced caller SP for the explicit `Frame` chain, but leaves IP and FP null because the caller is native. When the resulting stack pointer has no R2R frame record (a terminator, an interpreter transition or the stack top), the caller is not R2R code: the advanced SP is kept, IP and FP are null, and walking continues through the explicit `Frame` or interpreter frame chain. The R2R walk is cleared (SP, IP and FP all null) only when the current frame cannot be unwound at all: no R2R frame at SP, no unwind data, or a zero frame size. @@ -498,7 +498,7 @@ void Unwind() { TargetPointer frameBase = /* frame base of the R2R frame at SP */; uint identity = target.Read(frameBase + FrameIdentityOffset); - uint frameSize = /* ULEB128 in the unwind data of the function containing IP */; + uint frameSize = /* frame-size field of the packed uint64 ULEB128, multiplied by 16 */; if (/* no frame at SP, no unwind data, or frameSize == 0 */) { SP = IP = FP = null; diff --git a/src/coreclr/gcinfo/gcinfoencoder.cpp b/src/coreclr/gcinfo/gcinfoencoder.cpp index 5d897b438b1e50..535ddd38710f0d 100644 --- a/src/coreclr/gcinfo/gcinfoencoder.cpp +++ b/src/coreclr/gcinfo/gcinfoencoder.cpp @@ -553,6 +553,7 @@ template GcSlotId TGcInfoEncoder::GetR template GcSlotId TGcInfoEncoder::GetStackSlotId( INT32 spOffset, GcSlotFlags flags, GcStackSlotBase spBase ) { + _ASSERTE(spBase == GC_SP_REL || spBase == GC_FRAMEREG_REL); _ASSERTE(GcInfoEncoding::HAS_STACK_SLOT_BASE || spBase == GC_FRAMEREG_REL); // We could lookup an existing identical slot in the slot table (via some hashtable mechanism). // We just create duplicates for now. @@ -807,12 +808,11 @@ struct CompareSlotDescAndIdBySlotDesc else { _ASSERTE( !pSecond->IsRegister() ); - if( pFirst->Slot.Stack.SpOffset != pSecond->Slot.Stack.SpOffset ) - return pFirst->Slot.Stack.SpOffset < pSecond->Slot.Stack.SpOffset; - - // This is arbitrary, but we want to make sure they are considered separate slots if( pFirst->Slot.Stack.Base != pSecond->Slot.Stack.Base ) return pFirst->Slot.Stack.Base < pSecond->Slot.Stack.Base; + + if( pFirst->Slot.Stack.SpOffset != pSecond->Slot.Stack.SpOffset ) + return pFirst->Slot.Stack.SpOffset < pSecond->Slot.Stack.SpOffset; } // If we get here, the slots are identical @@ -943,7 +943,17 @@ template void TGcInfoEncoder::Build() UINT32 hasContextParamType = (m_GenericsInstContextStackSlot != NO_GENERICS_INST_CONTEXT); UINT32 hasReversePInvokeFrame = (m_ReversePInvokeFrameSlot != NO_REVERSE_PINVOKE_FRAME); - BOOL slimHeader = (!m_IsVarArg && !hasGSCookie && + if constexpr (GcInfoEncoding::USES_COMPACT_WASM_HEADER) + { + _ASSERTE(m_StackBaseRegister != NO_STACK_BASE_REGISTER); + _ASSERTE(GcInfoEncoding::NORMALIZE_STACK_BASE_REGISTER(m_StackBaseRegister) == 0); + } + + BOOL slimHeader = +#ifdef PARTIALLY_INTERRUPTIBLE_GC_SUPPORTED + (!GcInfoEncoding::USES_COMPACT_WASM_HEADER || (m_NumCallSites == 0)) && +#endif + (!m_IsVarArg && !hasGSCookie && !hasContextParamType && (m_InterruptibleRanges.Count() == 0) && !hasReversePInvokeFrame && ((m_StackBaseRegister == NO_STACK_BASE_REGISTER) || (GcInfoEncoding::NORMALIZE_STACK_BASE_REGISTER(m_StackBaseRegister) == 0))) && #ifdef TARGET_AMD64 @@ -959,7 +969,10 @@ template void TGcInfoEncoder::Build() { // Slim encoding means nothing special, partially interruptible, maybe a default frame register GCINFO_WRITE(m_Info1, 0, 1, FlagsSize); // Slim encoding - GCINFO_WRITE(m_Info1, (m_StackBaseRegister == NO_STACK_BASE_REGISTER) ? 0 : 1, 1, FlagsSize); + if constexpr (!GcInfoEncoding::USES_COMPACT_WASM_HEADER) + { + GCINFO_WRITE(m_Info1, (m_StackBaseRegister == NO_STACK_BASE_REGISTER) ? 0 : 1, 1, FlagsSize); + } } else { @@ -969,7 +982,10 @@ template void TGcInfoEncoder::Build() GCINFO_WRITE(m_Info1, (hasGSCookie ? 1 : 0), 1, FlagsSize); GCINFO_WRITE(m_Info1, 0 /* unused - was hasPSPSymStackSlot */, 1, FlagsSize); GCINFO_WRITE(m_Info1, m_contextParamType, 2, FlagsSize); - GCINFO_WRITE(m_Info1, ((m_StackBaseRegister != NO_STACK_BASE_REGISTER) ? 1 : 0), 1, FlagsSize); + if constexpr (!GcInfoEncoding::USES_COMPACT_WASM_HEADER) + { + GCINFO_WRITE(m_Info1, ((m_StackBaseRegister != NO_STACK_BASE_REGISTER) ? 1 : 0), 1, FlagsSize); + } #ifdef TARGET_AMD64 GCINFO_WRITE(m_Info1, (m_WantsReportOnlyLeaf ? 1 : 0), 1, FlagsSize); #elif defined(TARGET_ARM) || defined(TARGET_ARM64) || defined(TARGET_LOONGARCH64) || defined(TARGET_RISCV64) @@ -981,7 +997,7 @@ template void TGcInfoEncoder::Build() GCINFO_WRITE(m_Info1, (hasReversePInvokeFrame ? 1 : 0), 1, FlagsSize); // See definition of GC_INFO_FLAGS_BIT_SIZE - _ASSERTE(m_Info1.GetBitCount() == (10 + 1)); // +1 for the initial slim/fat encoding bit + _ASSERTE(m_Info1.GetBitCount() == (GcInfoEncoding::USES_COMPACT_WASM_HEADER ? 9 : 10) + 1); } _ASSERTE( m_CodeLength > 0 ); @@ -1005,7 +1021,14 @@ template void TGcInfoEncoder::Build() _ASSERTE(normPrologSize > 0 && normPrologSize < m_CodeLength); _ASSERTE(normEpilogSize < m_CodeLength); - GCINFO_WRITE_VARL_U(m_Info1, normPrologSize-1, GcInfoEncoding::NORM_PROLOG_SIZE_ENCBASE, ProEpilogSize); + if constexpr (GcInfoEncoding::USES_COMPACT_WASM_HEADER) + { + _ASSERTE(normPrologSize == 1); + } + else + { + GCINFO_WRITE_VARL_U(m_Info1, normPrologSize-1, GcInfoEncoding::NORM_PROLOG_SIZE_ENCBASE, ProEpilogSize); + } GCINFO_WRITE_VARL_U(m_Info1, normEpilogSize, GcInfoEncoding::NORM_EPILOG_SIZE_ENCBASE, ProEpilogSize); } else if (hasContextParamType) @@ -1017,7 +1040,14 @@ template void TGcInfoEncoder::Build() UINT32 normPrologSize = GcInfoEncoding::NORMALIZE_CODE_OFFSET(m_GSCookieValidRangeStart); _ASSERTE(normPrologSize > 0 && normPrologSize < m_CodeLength); - GCINFO_WRITE_VARL_U(m_Info1, normPrologSize-1, GcInfoEncoding::NORM_PROLOG_SIZE_ENCBASE, ProEpilogSize); + if constexpr (GcInfoEncoding::USES_COMPACT_WASM_HEADER) + { + _ASSERTE(normPrologSize == 1); + } + else + { + GCINFO_WRITE_VARL_U(m_Info1, normPrologSize-1, GcInfoEncoding::NORM_PROLOG_SIZE_ENCBASE, ProEpilogSize); + } } // Encode the offset to the GS cookie. @@ -1046,7 +1076,7 @@ template void TGcInfoEncoder::Build() GCINFO_WRITE_VARL_S(m_Info1, GcInfoEncoding::NORMALIZE_STACK_SLOT(m_GenericsInstContextStackSlot), GcInfoEncoding::GENERICS_INST_CONTEXT_STACK_SLOT_ENCBASE, GenericsCtxSize); } - if(!slimHeader && (m_StackBaseRegister != NO_STACK_BASE_REGISTER)) + if(!GcInfoEncoding::USES_COMPACT_WASM_HEADER && !slimHeader && (m_StackBaseRegister != NO_STACK_BASE_REGISTER)) { GCINFO_WRITE_VARL_U(m_Info1, GcInfoEncoding::NORMALIZE_STACK_BASE_REGISTER(m_StackBaseRegister), GcInfoEncoding::STACK_BASE_REGISTER_ENCBASE, StackBaseSize); } @@ -1108,7 +1138,10 @@ template void TGcInfoEncoder::Build() m_pCallSites[numCallSites++] = normOffset; } - GCINFO_WRITE_VARL_U(m_Info1, numCallSites, GcInfoEncoding::NUM_SAFE_POINTS_ENCBASE, NumCallSitesSize); + if (!GcInfoEncoding::USES_COMPACT_WASM_HEADER || !slimHeader) + { + GCINFO_WRITE_VARL_U(m_Info1, numCallSites, GcInfoEncoding::NUM_SAFE_POINTS_ENCBASE, NumCallSitesSize); + } m_NumCallSites = numCallSites; #endif // PARTIALLY_INTERRUPTIBLE_GC_SUPPORTED @@ -1456,6 +1489,9 @@ template void TGcInfoEncoder::Build() if(GcInfoEncoding::HAS_REGISTER_SLOTS && numRegisters > 0) { +#ifdef MEASURE_GCINFO + size_t startBitCount = m_Info1.GetBitCount(); +#endif GcSlotDesc *pSlotDesc; do { @@ -1467,8 +1503,8 @@ template void TGcInfoEncoder::Build() // Encode slot identification UINT32 currentNormRegNum = pSlotDesc->Slot.RegisterNumber; - GCINFO_WRITE_VARL_U(m_Info1, currentNormRegNum, GcInfoEncoding::REGISTER_ENCBASE, RegSlotSize); - GCINFO_WRITE(m_Info1, pSlotDesc->Flags, 2, RegSlotSize); + m_Info1.Write(pSlotDesc->Flags, 2); + m_Info1.EncodeRegister(currentNormRegNum, GcInfoEncoding::REGISTER_ENCBASE, GcInfoEncoding::REGISTER_BITS); for(UINT32 j = 1; j < numRegisters; j++) { @@ -1487,189 +1523,85 @@ template void TGcInfoEncoder::Build() if(lastFlags != GC_SLOT_IS_REGISTER) { - GCINFO_WRITE_VARL_U(m_Info1, currentNormRegNum, GcInfoEncoding::REGISTER_ENCBASE, RegSlotSize); - GCINFO_WRITE(m_Info1, pSlotDesc->Flags, 2, RegSlotSize); - } - else - { - _ASSERTE(pSlotDesc->Flags == GC_SLOT_IS_REGISTER); - GCINFO_WRITE_VARL_U(m_Info1, currentNormRegNum - lastNormRegNum - 1, GcInfoEncoding::REGISTER_DELTA_ENCBASE, RegSlotSize); - } - } - } - - if(numStackSlots > 0) - { - _ASSERTE(GcInfoEncoding::HAS_TRACKED_SLOTS); - GcSlotDesc *pSlotDesc; - do - { - _ASSERTE(currentSlot < m_NumSlots); - pSlotDesc = &m_SlotTable[currentSlot++]; - } - while(pSlotDesc->IsDeleted()); - _ASSERTE(!pSlotDesc->IsRegister()); - _ASSERTE(!pSlotDesc->IsUntracked()); - - // Encode slot identification - _ASSERTE((pSlotDesc->Slot.Stack.Base & ~3) == 0); - if constexpr (GcInfoEncoding::HAS_STACK_SLOT_BASE) - { - GCINFO_WRITE(m_Info1, pSlotDesc->Slot.Stack.Base, 2, StackSlotSize); - } - INT32 currentNormStackSlot = GcInfoEncoding::NORMALIZE_STACK_SLOT(pSlotDesc->Slot.Stack.SpOffset); - if constexpr (GcInfoEncoding::STACK_SLOT_FLAGS_FIRST) - { - GCINFO_WRITE(m_Info1, pSlotDesc->Flags, 2, StackSlotSize); - } - GCINFO_WRITE_VARL_S(m_Info1, currentNormStackSlot, GcInfoEncoding::STACK_SLOT_ENCBASE, StackSlotSize); - - if constexpr (!GcInfoEncoding::STACK_SLOT_FLAGS_FIRST) - { - GCINFO_WRITE(m_Info1, pSlotDesc->Flags, 2, StackSlotSize); - } - - for(UINT32 j = 1; j < numStackSlots; j++) - { - INT32 lastNormStackSlot = currentNormStackSlot; - GcSlotFlags lastFlags = pSlotDesc->Flags; - - do - { - _ASSERTE(currentSlot < m_NumSlots); - pSlotDesc = &m_SlotTable[currentSlot++]; + m_Info1.Write(pSlotDesc->Flags, (lastFlags & GC_SLOT_PINNED) != 0 ? 2 : 1); } - while(pSlotDesc->IsDeleted()); - _ASSERTE(!pSlotDesc->IsRegister()); - _ASSERTE(!pSlotDesc->IsUntracked()); - currentNormStackSlot = GcInfoEncoding::NORMALIZE_STACK_SLOT(pSlotDesc->Slot.Stack.SpOffset); - - _ASSERTE((pSlotDesc->Slot.Stack.Base & ~3) == 0); - if constexpr (GcInfoEncoding::HAS_STACK_SLOT_BASE) + if(pSlotDesc->Flags != lastFlags) { - GCINFO_WRITE(m_Info1, pSlotDesc->Slot.Stack.Base, 2, StackSlotSize); - } - - if constexpr (GcInfoEncoding::STACK_SLOT_FLAGS_FIRST) - { - if (lastFlags != GC_SLOT_BASE) - { - GCINFO_WRITE(m_Info1, pSlotDesc->Flags, 2, StackSlotSize); - } - else - { - _ASSERTE(pSlotDesc->Flags == GC_SLOT_BASE); - } - - if (pSlotDesc->Flags != lastFlags) - { - GCINFO_WRITE_VARL_S(m_Info1, currentNormStackSlot, GcInfoEncoding::STACK_SLOT_ENCBASE, StackSlotSize); - } - else - { - GCINFO_WRITE_VARL_U(m_Info1, currentNormStackSlot - lastNormStackSlot, GcInfoEncoding::STACK_SLOT_DELTA_ENCBASE, StackSlotSize); - } - } - else if(lastFlags != GC_SLOT_BASE) - { - GCINFO_WRITE_VARL_S(m_Info1, currentNormStackSlot, GcInfoEncoding::STACK_SLOT_ENCBASE, StackSlotSize); - GCINFO_WRITE(m_Info1, pSlotDesc->Flags, 2, StackSlotSize); + m_Info1.EncodeRegister(currentNormRegNum, GcInfoEncoding::REGISTER_ENCBASE, GcInfoEncoding::REGISTER_BITS); } else { - _ASSERTE(pSlotDesc->Flags == GC_SLOT_BASE); - GCINFO_WRITE_VARL_U(m_Info1, currentNormStackSlot - lastNormStackSlot, GcInfoEncoding::STACK_SLOT_DELTA_ENCBASE, StackSlotSize); + _ASSERTE(currentNormRegNum > lastNormRegNum); + m_Info1.EncodeRegister(currentNormRegNum - lastNormRegNum - 1, + GcInfoEncoding::REGISTER_DELTA_ENCBASE, GcInfoEncoding::REGISTER_BITS); } } +#ifdef MEASURE_GCINFO + size_t bitCount = m_Info1.GetBitCount() - startBitCount; + m_CurrentMethodSize.RegSlotSize += bitCount; + m_CurrentMethodSize.TotalSize += bitCount; +#endif } - if(numUntrackedSlots > 0) + for (UINT32 section = 0; section < 2; section++) { - GcSlotDesc *pSlotDesc; - do - { - _ASSERTE(currentSlot < m_NumSlots); - pSlotDesc = &m_SlotTable[currentSlot++]; - } - while(pSlotDesc->IsDeleted()); - _ASSERTE(!pSlotDesc->IsRegister()); - _ASSERTE(pSlotDesc->IsUntracked()); - - // Encode slot identification - _ASSERTE((pSlotDesc->Slot.Stack.Base & ~3) == 0); - if constexpr (GcInfoEncoding::HAS_STACK_SLOT_BASE) - { - GCINFO_WRITE(m_Info1, pSlotDesc->Slot.Stack.Base, 2, UntrackedSlotSize); - } - INT32 currentNormStackSlot = GcInfoEncoding::NORMALIZE_STACK_SLOT(pSlotDesc->Slot.Stack.SpOffset); - if constexpr (GcInfoEncoding::STACK_SLOT_FLAGS_FIRST) - { - GCINFO_WRITE(m_Info1, pSlotDesc->Flags, 2, UntrackedSlotSize); - } - GCINFO_WRITE_VARL_S(m_Info1, currentNormStackSlot, GcInfoEncoding::STACK_SLOT_ENCBASE, UntrackedSlotSize); - - if constexpr (!GcInfoEncoding::STACK_SLOT_FLAGS_FIRST) - { - GCINFO_WRITE(m_Info1, pSlotDesc->Flags, 2, UntrackedSlotSize); - } - - for(UINT32 j = 1; j < numUntrackedSlots; j++) + UINT32 numSectionSlots = section == 0 ? numStackSlots : numUntrackedSlots; + _ASSERTE(section != 0 || GcInfoEncoding::HAS_TRACKED_SLOTS || numSectionSlots == 0); +#ifdef MEASURE_GCINFO + size_t startBitCount = m_Info1.GetBitCount(); +#endif + GcSlotFlags previousFlags = GC_SLOT_BASE; + GcStackSlotBase previousBase = GC_SP_REL; + INT32 previousOffset = 0; + for (UINT32 i = 0; i < numSectionSlots; i++) { - INT32 lastNormStackSlot = currentNormStackSlot; - GcSlotFlags lastFlags = pSlotDesc->Flags; - - do + while (m_SlotTable[currentSlot].IsDeleted()) { + currentSlot++; _ASSERTE(currentSlot < m_NumSlots); - pSlotDesc = &m_SlotTable[currentSlot++]; } - while(pSlotDesc->IsDeleted()); - _ASSERTE(!pSlotDesc->IsRegister()); - _ASSERTE(pSlotDesc->IsUntracked()); - - currentNormStackSlot = GcInfoEncoding::NORMALIZE_STACK_SLOT(pSlotDesc->Slot.Stack.SpOffset); + const GcSlotDesc& slot = m_SlotTable[currentSlot++]; + _ASSERTE(!slot.IsRegister()); + _ASSERTE((slot.IsUntracked() != FALSE) == (section != 0)); - _ASSERTE((pSlotDesc->Slot.Stack.Base & ~3) == 0); - if constexpr (GcInfoEncoding::HAS_STACK_SLOT_BASE) + GcSlotFlags flags = static_cast(slot.Flags & (GC_SLOT_INTERIOR | GC_SLOT_PINNED)); + if (i == 0 || previousFlags != GC_SLOT_BASE) { - GCINFO_WRITE(m_Info1, pSlotDesc->Slot.Stack.Base, 2, UntrackedSlotSize); + m_Info1.Write(flags, i == 0 || (previousFlags & GC_SLOT_PINNED) != 0 ? 2 : 1); } - - if constexpr (GcInfoEncoding::STACK_SLOT_FLAGS_FIRST) + GcStackSlotBase base = slot.Slot.Stack.Base; + if constexpr (GcInfoEncoding::HAS_STACK_SLOT_BASE) { - if (lastFlags != GC_SLOT_UNTRACKED) - { - GCINFO_WRITE(m_Info1, pSlotDesc->Flags, 2, UntrackedSlotSize); - } - else - { - _ASSERTE(pSlotDesc->Flags == GC_SLOT_UNTRACKED); - } - - if (pSlotDesc->Flags != lastFlags) - { - GCINFO_WRITE_VARL_S(m_Info1, currentNormStackSlot, GcInfoEncoding::STACK_SLOT_ENCBASE, UntrackedSlotSize); - } - else - { - GCINFO_WRITE_VARL_U(m_Info1, currentNormStackSlot - lastNormStackSlot, GcInfoEncoding::STACK_SLOT_DELTA_ENCBASE, UntrackedSlotSize); - } + m_Info1.Write(base == GC_FRAMEREG_REL, 1); } - else if(lastFlags != GC_SLOT_UNTRACKED) + + INT32 offset = GcInfoEncoding::NORMALIZE_STACK_SLOT(slot.Slot.Stack.SpOffset); + if (i == 0 || flags != previousFlags || base != previousBase) { - GCINFO_WRITE_VARL_S(m_Info1, currentNormStackSlot, GcInfoEncoding::STACK_SLOT_ENCBASE, UntrackedSlotSize); - GCINFO_WRITE(m_Info1, pSlotDesc->Flags, 2, UntrackedSlotSize); + m_Info1.EncodeVarLengthSigned(offset, GcInfoEncoding::STACK_SLOT_ENCBASE); } else { - _ASSERTE(pSlotDesc->Flags == GC_SLOT_UNTRACKED); - GCINFO_WRITE_VARL_U(m_Info1, currentNormStackSlot - lastNormStackSlot, GcInfoEncoding::STACK_SLOT_DELTA_ENCBASE, UntrackedSlotSize); + _ASSERTE(offset >= previousOffset); + m_Info1.EncodeVarLengthUnsigned(offset - previousOffset, GcInfoEncoding::STACK_SLOT_DELTA_ENCBASE); } + previousFlags = flags; + previousBase = base; + previousOffset = offset; } +#ifdef MEASURE_GCINFO + size_t bitCount = m_Info1.GetBitCount() - startBitCount; + if (section == 0) + m_CurrentMethodSize.StackSlotSize += bitCount; + else + m_CurrentMethodSize.UntrackedSlotSize += bitCount; + m_CurrentMethodSize.TotalSize += bitCount; +#endif } + #ifdef PARTIALLY_INTERRUPTIBLE_GC_SUPPORTED //----------------------------------------------------------------- // Encode GC info at call sites @@ -2641,6 +2573,18 @@ int BitStreamWriter::SizeofVarLengthUnsigned( size_t n, UINT32 base) return bitsUsed; } +void BitStreamWriter::EncodeRegister(UINT32 value, UINT32 base, UINT32 registerBits) +{ + _ASSERTE(base <= registerBits && registerBits < 32); + _ASSERTE(value < (1u << registerBits)); + UINT32 extension = value >> base; + Write((value & ((1u << base) - 1)) | (extension != 0 ? 1u << base : 0), base + 1); + if (extension != 0) + { + Write(extension, registerBits - base); + } +} + int BitStreamWriter::EncodeVarLengthUnsigned( size_t n, UINT32 base) { // If a value gets so big we are probably doing something wrong diff --git a/src/coreclr/inc/clrnt.h b/src/coreclr/inc/clrnt.h index f0c72b682b465e..f26a1417e429d0 100644 --- a/src/coreclr/inc/clrnt.h +++ b/src/coreclr/inc/clrnt.h @@ -533,7 +533,15 @@ RtlVirtualUnwind ( __inout_opt PT_KNONVOLATILE_CONTEXT_POINTERS ContextPointers ); -UINT32 DecodeULEB128AsU32(PTR_BYTE* ppData); +UINT64 DecodeULEB128AsU64(PTR_BYTE* ppData); + +inline void DecodeWasmUnwindInfo(UINT64 encoded, UINT32& frameSize, UINT32& virtualIPCount) +{ + frameSize = static_cast((encoded & 0xF) | (((encoded >> 8) & 0xF) << 4) | + (((encoded >> 16) & 0xFFFF) << 8)) * 16; + virtualIPCount = static_cast(((encoded >> 4) & 0xF) | (((encoded >> 12) & 0xF) << 4) | + (((encoded >> 32) & 0xFFFF) << 8)) * 2; +} ULONG RtlpGetFunctionEndAddress ( diff --git a/src/coreclr/inc/gcinfo.h b/src/coreclr/inc/gcinfo.h index 70461bbbd5be7f..0fd1319e29d430 100644 --- a/src/coreclr/inc/gcinfo.h +++ b/src/coreclr/inc/gcinfo.h @@ -37,7 +37,7 @@ const unsigned this_OFFSET_FLAG = 0x2; // the offset is "this" // The current GCInfo Version //----------------------------------------------------------------------------- -#define GCINFO_VERSION 5 +#define GCINFO_VERSION 6 #ifdef SOS_INCLUDE extern bool IsRuntimeVersionAtLeast(DWORD major); @@ -47,7 +47,7 @@ inline int GCInfoVersion() // Since v2 and v3 had the same file format and v1 is no longer supported, // we can assume that everything before net10.0 uses GCInfo v3. if (IsRuntimeVersionAtLeast(11)) - return 5; + return 6; if (IsRuntimeVersionAtLeast(10)) return 4; return 3; @@ -84,6 +84,9 @@ struct GCInfoToken // Keep this in sync with GetR2RGCInfoVersion in cDac (ExecutionManagerCore.ReadyToRunJitManager.cs) static uint32_t ReadyToRunVersionToGcInfoVersion(uint32_t readyToRunMajorVersion, uint32_t readyToRunMinorVersion) { + if (readyToRunMajorVersion >= 33) + return 6; + if (readyToRunMajorVersion >= 21) return 5; diff --git a/src/coreclr/inc/gcinfodecoder.h b/src/coreclr/inc/gcinfodecoder.h index 2ac0e75137d8d2..bf2f17eaa71d82 100644 --- a/src/coreclr/inc/gcinfodecoder.h +++ b/src/coreclr/inc/gcinfodecoder.h @@ -479,7 +479,7 @@ class GcSlotDecoder GcSlotDecoder() {} - void DecodeSlotTable(BitStreamReader& reader); + void DecodeSlotTable(BitStreamReader& reader, UINT32 version); UINT32 GetNumSlots() { @@ -504,35 +504,82 @@ class GcSlotDecoder const GcSlotDesc* GetSlotDesc(UINT32 slotIndex); private: + static UINT32 ReadRegisterValue(BitStreamReader& reader, UINT32 base) + { + UINT32 chunk = static_cast(reader.Read(base + 1)); + UINT32 value = chunk & ((1u << base) - 1); + if ((chunk & (1u << base)) != 0) + { + _ASSERTE(base < GcInfoEncoding::REGISTER_BITS); + if (base < GcInfoEncoding::REGISTER_BITS) + { + value |= static_cast(reader.Read(GcInfoEncoding::REGISTER_BITS - base)) << base; + } + } + + return value; + } + + static GcSlotFlags ReadSlotFlags(BitStreamReader& reader, GcSlotFlags previousFlags, bool first) + { + return first || previousFlags != GC_SLOT_BASE + ? static_cast(reader.Read(first || (previousFlags & GC_SLOT_PINNED) != 0 ? 2 : 1)) + : GC_SLOT_BASE; + } + + UINT32 ReadRegisterSlot(BitStreamReader& reader, GcSlotFlags& flags, UINT32 previousRegister, bool first) + { + bool absolute = first || flags != GC_SLOT_BASE; + if (m_UseCompactSlotEncoding) + { + GcSlotFlags previousFlags = flags; + flags = ReadSlotFlags(reader, previousFlags, first); + absolute = first || flags != previousFlags; + UINT32 value = ReadRegisterValue(reader, absolute + ? GcInfoEncoding::REGISTER_ENCBASE : GcInfoEncoding::REGISTER_DELTA_ENCBASE); + + return absolute ? value : previousRegister + value + 1; + } + + UINT32 value = static_cast(reader.DecodeVarLengthUnsigned(absolute + ? GcInfoEncoding::REGISTER_ENCBASE : GcInfoEncoding::REGISTER_DELTA_ENCBASE)); + if (absolute) + { + flags = static_cast(reader.Read(2)); + } + + return absolute ? value : previousRegister + value + 1; + } + static GcStackSlotBase ReadStackSlotBase(BitStreamReader& reader) { return GcInfoEncoding::HAS_STACK_SLOT_BASE ? (GcStackSlotBase)reader.Read(2) : GC_FRAMEREG_REL; } - static INT32 ReadStackSlotOffset(BitStreamReader& reader, GcSlotFlags& flags, INT32 previousOffset, bool first) + INT32 ReadStackSlot(BitStreamReader& reader, GcSlotFlags& flags, GcStackSlotBase& base, + INT32 previousOffset, bool first) { - bool absolute; - if constexpr (GcInfoEncoding::STACK_SLOT_FLAGS_FIRST) + bool absolute = first || flags != GC_SLOT_BASE; + if (m_UseCompactSlotEncoding) { - GcSlotFlags previousFlags = first ? static_cast(7) : flags; - flags = previousFlags == GC_SLOT_BASE ? GC_SLOT_BASE : static_cast(reader.Read(2)); - absolute = flags != previousFlags; + GcSlotFlags previousFlags = flags; + GcStackSlotBase previousBase = first ? GC_SP_REL : base; + flags = ReadSlotFlags(reader, previousFlags, first); + base = GcInfoEncoding::HAS_STACK_SLOT_BASE && !reader.ReadOneFast() ? GC_SP_REL : GC_FRAMEREG_REL; + absolute = first || flags != previousFlags || base != previousBase; } else { - absolute = first || flags != GC_SLOT_BASE; + base = ReadStackSlotBase(reader); } INT32 offset = absolute ? static_cast(reader.DecodeVarLengthSigned(GcInfoEncoding::STACK_SLOT_ENCBASE)) : previousOffset + static_cast(reader.DecodeVarLengthUnsigned(GcInfoEncoding::STACK_SLOT_DELTA_ENCBASE)); - if constexpr (!GcInfoEncoding::STACK_SLOT_FLAGS_FIRST) + if (!m_UseCompactSlotEncoding && absolute) { - if (absolute) - { - flags = static_cast(reader.Read(2)); - } + flags = static_cast(reader.Read(2)); } return offset; @@ -543,6 +590,7 @@ class GcSlotDecoder UINT32 m_NumSlots; UINT32 m_NumRegisters; UINT32 m_NumUntracked; + bool m_UseCompactSlotEncoding; UINT32 m_NumDecodedSlots; GcSlotDesc* m_pLastSlot; @@ -642,6 +690,16 @@ class TGcInfoDecoder } private: + bool UsesCompactWasmHeader() + { + return GcInfoEncoding::USES_COMPACT_WASM_HEADER && Version() >= 6; + } + + bool UsesLegacyWasmEncoding() + { + return GcInfoEncoding::USES_COMPACT_WASM_HEADER && Version() < 6; + } + BitStreamReader m_Reader; UINT32 m_InstructionOffset; diff --git a/src/coreclr/inc/gcinfoencoder.h b/src/coreclr/inc/gcinfoencoder.h index 7e705bb8c516a7..3c6c4d0a9852da 100644 --- a/src/coreclr/inc/gcinfoencoder.h +++ b/src/coreclr/inc/gcinfoencoder.h @@ -45,9 +45,23 @@ - NumCallSites (#ifdef PARTIALLY_INTERRUPTIBLE_GC_SUPPORTED) - NumInterruptibleRanges (fat header only; omitted if !HAS_INTERRUPTIBLE_RANGES) + Wasm headers omit the stack-base presence bit and register value, and imply frame register zero + after normalization. Their prolog size is implicitly one. Wasm slim headers also omit NumCallSites + and imply zero; nonzero call-site counts require fat headers. + 2. Call sites offsets (#ifdef PARTIALLY_INTERRUPTIBLE_GC_SUPPORTED) 3. Fully-interruptible ranges 4. Slot table + Register flags precede the register number while the previous flags are non-normal. + After the first unpinned register, only the interior flag bit is present. + The first register of each flag group is absolute; later registers use gap-minus-one deltas. + Register integers have an ENCBASE-sized payload and continuation bit, optionally followed + by the remaining target register bits without another continuation bit. + Tracked and untracked stack slots use the same shrinking flag bits as registers. + Slots are sorted by descending flags, then SP before Frame, then ascending offset. + Each non-Wasm slot has one base bit: 0 for SP, 1 for Frame. Wasm is implicitly Frame-relative. + The first slot of each flags/base combination has a signed absolute offset; later offsets + in that group are unsigned deltas. State resets at the tracked/untracked boundary. 5. GC state at call sites (#ifdef PARTIALLY_INTERRUPTIBLE_GC_SUPPORTED) 6. GC state at try clauses (#ifdef PARTIALLY_INTERRUPTIBLE_GC_SUPPORTED) 7. Chunk pointers @@ -227,6 +241,7 @@ class BitStreamWriter // If it doesn't fit, set bit #base to 1 and use base+1 more bits //-------------------------------------------------------- int EncodeVarLengthUnsigned( size_t n, UINT32 base ); + void EncodeRegister(UINT32 value, UINT32 base, UINT32 registerBits); //-------------------------------------------------------- // Signed quantities are encoded the same as unsigned @@ -363,7 +378,7 @@ class TGcInfoEncoder // It's up to the JIT to do the right thing. We don't enforce this. GcSlotId GetRegisterSlotId( UINT32 regNum, GcSlotFlags flags ); - GcSlotId GetStackSlotId( INT32 spOffset, GcSlotFlags flags, GcStackSlotBase spBase = GC_CALLER_SP_REL ); + GcSlotId GetStackSlotId( INT32 spOffset, GcSlotFlags flags, GcStackSlotBase spBase ); // // After a FinalizeSlotIds is called, no more slot definitions can be made. diff --git a/src/coreclr/inc/gcinfotypes.h b/src/coreclr/inc/gcinfotypes.h index a21a0debab7b6b..9c246381f49f80 100644 --- a/src/coreclr/inc/gcinfotypes.h +++ b/src/coreclr/inc/gcinfotypes.h @@ -571,6 +571,8 @@ void FASTCALL decodeCallPattern(int pattern, #define TargetGcInfoEncoding AMD64GcInfoEncoding struct AMD64GcInfoEncoding { + static const bool USES_COMPACT_WASM_HEADER = false; + static const int REGISTER_BITS = 5; // Includes APX registers R16-R31. static const uint32_t NUM_NORM_CODE_OFFSETS_PER_CHUNK = (64); static const uint32_t NUM_NORM_CODE_OFFSETS_PER_CHUNK_LOG2 = (6); @@ -620,7 +622,6 @@ struct AMD64GcInfoEncoding { static const bool HAS_REGISTER_SLOTS = true; static const bool HAS_TRACKED_SLOTS = true; static const bool HAS_STACK_SLOT_BASE = true; - static const bool STACK_SLOT_FLAGS_FIRST = false; static const bool HAS_FIXED_STACK_PARAMETER_SCRATCH_AREA = true; static const bool HAS_INTERRUPTIBLE_RANGES = true; }; @@ -634,6 +635,8 @@ struct AMD64GcInfoEncoding { #define TargetGcInfoEncoding ARM32GcInfoEncoding struct ARM32GcInfoEncoding { + static const bool USES_COMPACT_WASM_HEADER = false; + static const int REGISTER_BITS = 4; static const uint32_t NUM_NORM_CODE_OFFSETS_PER_CHUNK = (64); static const uint32_t NUM_NORM_CODE_OFFSETS_PER_CHUNK_LOG2 = (6); static inline constexpr int32_t NORMALIZE_STACK_SLOT (int32_t x) { return ((x)>>2); } @@ -683,7 +686,6 @@ struct ARM32GcInfoEncoding { static const bool HAS_REGISTER_SLOTS = true; static const bool HAS_TRACKED_SLOTS = true; static const bool HAS_STACK_SLOT_BASE = true; - static const bool STACK_SLOT_FLAGS_FIRST = false; static const bool HAS_FIXED_STACK_PARAMETER_SCRATCH_AREA = true; static const bool HAS_INTERRUPTIBLE_RANGES = true; }; @@ -697,6 +699,8 @@ struct ARM32GcInfoEncoding { #define TargetGcInfoEncoding ARM64GcInfoEncoding struct ARM64GcInfoEncoding { + static const bool USES_COMPACT_WASM_HEADER = false; + static const int REGISTER_BITS = 5; static const uint32_t NUM_NORM_CODE_OFFSETS_PER_CHUNK = (64); static const uint32_t NUM_NORM_CODE_OFFSETS_PER_CHUNK_LOG2 = (6); // GC Pointers are 8-bytes aligned @@ -749,7 +753,6 @@ struct ARM64GcInfoEncoding { static const bool HAS_REGISTER_SLOTS = true; static const bool HAS_TRACKED_SLOTS = true; static const bool HAS_STACK_SLOT_BASE = true; - static const bool STACK_SLOT_FLAGS_FIRST = false; static const bool HAS_FIXED_STACK_PARAMETER_SCRATCH_AREA = true; static const bool HAS_INTERRUPTIBLE_RANGES = true; }; @@ -762,6 +765,8 @@ struct ARM64GcInfoEncoding { #define TargetGcInfoEncoding LoongArch64GcInfoEncoding struct LoongArch64GcInfoEncoding { + static const bool USES_COMPACT_WASM_HEADER = false; + static const int REGISTER_BITS = 5; static const uint32_t NUM_NORM_CODE_OFFSETS_PER_CHUNK = (64); static const uint32_t NUM_NORM_CODE_OFFSETS_PER_CHUNK_LOG2 = (6); // GC Pointers are 8-bytes aligned @@ -813,7 +818,6 @@ struct LoongArch64GcInfoEncoding { static const bool HAS_REGISTER_SLOTS = true; static const bool HAS_TRACKED_SLOTS = true; static const bool HAS_STACK_SLOT_BASE = true; - static const bool STACK_SLOT_FLAGS_FIRST = false; static const bool HAS_FIXED_STACK_PARAMETER_SCRATCH_AREA = true; static const bool HAS_INTERRUPTIBLE_RANGES = true; }; @@ -826,6 +830,8 @@ struct LoongArch64GcInfoEncoding { #define TargetGcInfoEncoding RISCV64GcInfoEncoding struct RISCV64GcInfoEncoding { + static const bool USES_COMPACT_WASM_HEADER = false; + static const int REGISTER_BITS = 5; static const uint32_t NUM_NORM_CODE_OFFSETS_PER_CHUNK = (64); static const uint32_t NUM_NORM_CODE_OFFSETS_PER_CHUNK_LOG2 = (6); // GC Pointers are 8-bytes aligned @@ -878,7 +884,6 @@ struct RISCV64GcInfoEncoding { static const bool HAS_REGISTER_SLOTS = true; static const bool HAS_TRACKED_SLOTS = true; static const bool HAS_STACK_SLOT_BASE = true; - static const bool STACK_SLOT_FLAGS_FIRST = false; static const bool HAS_FIXED_STACK_PARAMETER_SCRATCH_AREA = true; static const bool HAS_INTERRUPTIBLE_RANGES = true; }; @@ -892,6 +897,8 @@ struct RISCV64GcInfoEncoding { #define TargetGcInfoEncoding X86GcInfoEncoding struct X86GcInfoEncoding { + static const bool USES_COMPACT_WASM_HEADER = false; + static const int REGISTER_BITS = 3; static const uint32_t NUM_NORM_CODE_OFFSETS_PER_CHUNK = (64); static const uint32_t NUM_NORM_CODE_OFFSETS_PER_CHUNK_LOG2 = (6); static inline constexpr int32_t NORMALIZE_STACK_SLOT (int32_t x) { return (x); } @@ -938,7 +945,6 @@ struct X86GcInfoEncoding { static const bool HAS_REGISTER_SLOTS = true; static const bool HAS_TRACKED_SLOTS = true; static const bool HAS_STACK_SLOT_BASE = true; - static const bool STACK_SLOT_FLAGS_FIRST = false; static const bool HAS_FIXED_STACK_PARAMETER_SCRATCH_AREA = true; static const bool HAS_INTERRUPTIBLE_RANGES = true; }; @@ -952,13 +958,15 @@ struct X86GcInfoEncoding { #define TargetGcInfoEncoding Wasm32GcInfoEncoding struct Wasm32GcInfoEncoding { + static const bool USES_COMPACT_WASM_HEADER = true; + static const int REGISTER_BITS = 3; static const uint32_t NUM_NORM_CODE_OFFSETS_PER_CHUNK = (64); static const uint32_t NUM_NORM_CODE_OFFSETS_PER_CHUNK_LOG2 = (6); static inline constexpr int32_t NORMALIZE_STACK_SLOT (int32_t x) { return (x / TARGET_POINTER_SIZE); } static inline constexpr int32_t DENORMALIZE_STACK_SLOT (int32_t x) { return (x * TARGET_POINTER_SIZE); } static inline constexpr uint32_t NORMALIZE_CODE_LENGTH (uint32_t x) { return (x); } static inline constexpr uint32_t DENORMALIZE_CODE_LENGTH (uint32_t x) { return (x); } - // Slim headers identify the default frame register by normalized zero. + // The implicit default frame register normalizes to zero. static inline constexpr uint32_t NORMALIZE_STACK_BASE_REGISTER (uint32_t x) { return (x ^ 2); } static inline constexpr uint32_t DENORMALIZE_STACK_BASE_REGISTER (uint32_t x) { return (x ^ 2); } static inline constexpr uint32_t NORMALIZE_SIZE_OF_STACK_AREA (uint32_t x) { return (x); } @@ -971,16 +979,16 @@ struct Wasm32GcInfoEncoding { static const int GENERICS_INST_CONTEXT_STACK_SLOT_ENCBASE = 6; static const int SECURITY_OBJECT_STACK_SLOT_ENCBASE = 6; static const int GS_COOKIE_STACK_SLOT_ENCBASE = 6; - static const int CODE_LENGTH_ENCBASE = 6; + static const int CODE_LENGTH_ENCBASE = 5; static const int SIZE_OF_RETURN_KIND_IN_SLIM_HEADER = 2; static const int SIZE_OF_RETURN_KIND_IN_FAT_HEADER = 2; static const int STACK_BASE_REGISTER_ENCBASE = 3; static const int SIZE_OF_STACK_AREA_ENCBASE = 6; static const int SIZE_OF_EDIT_AND_CONTINUE_PRESERVED_AREA_ENCBASE = 3; - static const int REVERSE_PINVOKE_FRAME_ENCBASE = 6; + static const int REVERSE_PINVOKE_FRAME_ENCBASE = 4; static const int NUM_REGISTERS_ENCBASE = 3; static const int NUM_STACK_SLOTS_ENCBASE = 5; - static const int NUM_UNTRACKED_SLOTS_ENCBASE = 5; + static const int NUM_UNTRACKED_SLOTS_ENCBASE = 7; static const int NORM_PROLOG_SIZE_ENCBASE = 4; static const int NORM_EPILOG_SIZE_ENCBASE = 3; static const int NORM_CODE_OFFSET_DELTA_ENCBASE = 3; @@ -990,7 +998,7 @@ struct Wasm32GcInfoEncoding { static const int REGISTER_DELTA_ENCBASE = REGISTER_ENCBASE; static const int STACK_SLOT_ENCBASE = 3; static const int STACK_SLOT_DELTA_ENCBASE = 3; - static const int NUM_SAFE_POINTS_ENCBASE = 4; + static const int NUM_SAFE_POINTS_ENCBASE = 3; static const int NUM_INTERRUPTIBLE_RANGES_ENCBASE = 1; static const int NUM_EH_CLAUSES_ENCBASE = 2; static const int POINTER_SIZE_ENCBASE = 3; @@ -1002,8 +1010,6 @@ struct Wasm32GcInfoEncoding { static const bool HAS_TRACKED_SLOTS = false; // All slots are frame-relative, so no per-slot stack base is encoded. static const bool HAS_STACK_SLOT_BASE = false; - // Equal flags use offset deltas; ordinary flags are implicit after their first slot. - static const bool STACK_SLOT_FLAGS_FIRST = true; static const bool HAS_FIXED_STACK_PARAMETER_SCRATCH_AREA = false; static const bool HAS_INTERRUPTIBLE_RANGES = false; }; @@ -1019,6 +1025,8 @@ PORTABILITY_WARNING("Please specialize these definitions for your platform!") #ifdef FEATURE_INTERPRETER struct InterpreterGcInfoEncoding { + static const bool USES_COMPACT_WASM_HEADER = false; + static const int REGISTER_BITS = 3; static const uint32_t NUM_NORM_CODE_OFFSETS_PER_CHUNK = (64); static const uint32_t NUM_NORM_CODE_OFFSETS_PER_CHUNK_LOG2 = (6); @@ -1071,7 +1079,6 @@ struct InterpreterGcInfoEncoding { static const bool HAS_REGISTER_SLOTS = false; static const bool HAS_TRACKED_SLOTS = true; static const bool HAS_STACK_SLOT_BASE = true; - static const bool STACK_SLOT_FLAGS_FIRST = false; static const bool HAS_FIXED_STACK_PARAMETER_SCRATCH_AREA = false; static const bool HAS_INTERRUPTIBLE_RANGES = true; }; diff --git a/src/coreclr/inc/readytorun.h b/src/coreclr/inc/readytorun.h index a5267fa3adcd8d..da2f8174a6d09a 100644 --- a/src/coreclr/inc/readytorun.h +++ b/src/coreclr/inc/readytorun.h @@ -83,7 +83,8 @@ // method's ReadyToRun entry point and fixups. // R2R Version 31.1 adds READYTORUN_FLAG_SINGLE_THREADED, which records that the image lays out [ThreadStatic] fields as regular statics // for a runtime built without FEATURE_MULTITHREADING. -// R2R Version 33 compacts Wasm GC slot tables and encodes unwind frame sizes in 16-byte units. +// R2R Version 33 uses GCInfo v6, with shrinking slot flag bits and offsets relative within flags/base groups. +// Wasm also compacts stack slot offsets and packs scaled unwind frame sizes and virtual IP counts into one ULEB128. // Wasm images from earlier versions must be regenerated. struct READYTORUN_CORE_HEADER diff --git a/src/coreclr/jit/gcencode.cpp b/src/coreclr/jit/gcencode.cpp index 4630cd276227ad..7ffde2356b1dc4 100644 --- a/src/coreclr/jit/gcencode.cpp +++ b/src/coreclr/jit/gcencode.cpp @@ -3710,7 +3710,7 @@ class GcInfoEncoderWithLogging { } - GcSlotId GetStackSlotId(INT32 spOffset, GcSlotFlags flags, GcStackSlotBase spBase = GC_CALLER_SP_REL) + GcSlotId GetStackSlotId(INT32 spOffset, GcSlotFlags flags, GcStackSlotBase spBase) { GcSlotId newSlotId = m_gcInfoEncoder->GetStackSlotId(spOffset, flags, spBase); if (m_doLogging) diff --git a/src/coreclr/jit/unwindwasm.cpp b/src/coreclr/jit/unwindwasm.cpp index 221f2fb2773766..a03a65f7c17800 100644 --- a/src/coreclr/jit/unwindwasm.cpp +++ b/src/coreclr/jit/unwindwasm.cpp @@ -10,6 +10,19 @@ #error "This should be included only for Wasm" #endif // TARGET_WASM +static uint64_t EncodeWasmUnwindInfo(unsigned frameSizeInUnits, unsigned virtualIPCountInUnits) +{ + constexpr unsigned MaxUnwindFieldValue = 0xFFFFFF; + if ((frameSizeInUnits > MaxUnwindFieldValue) || (virtualIPCountInUnits > MaxUnwindFieldValue)) + { + IMPL_LIMITATION("Wasm unwind frame size or virtual IP count exceeds 24 bits"); + } + + return (frameSizeInUnits & 0xF) | ((virtualIPCountInUnits & 0xF) << 4) | ((frameSizeInUnits & 0xF0) << 4) | + ((virtualIPCountInUnits & 0xF0) << 8) | (static_cast(frameSizeInUnits >> 8) << 16) | + (static_cast(virtualIPCountInUnits >> 8) << 32); +} + void Compiler::unwindBegProlog() { } @@ -62,8 +75,8 @@ void Compiler::unwindReserveFunc(FuncInfoDsc* func) bool isColdCode = false; assert(func->endVirtualIP > func->startVirtualIP); assert((func->funWasmFrameSize % STACK_ALIGN) == 0); - ULONG encodedSize = emitter::SizeOfULEB128(func->funWasmFrameSize / STACK_ALIGN) + - emitter::SizeOfULEB128(func->endVirtualIP - func->startVirtualIP); + ULONG encodedSize = emitter::SizeOfULEB128( + EncodeWasmUnwindInfo(func->funWasmFrameSize / STACK_ALIGN, func->endVirtualIP - func->startVirtualIP)); eeReserveUnwindInfo(isFunclet, isColdCode, encodedSize); } @@ -108,15 +121,15 @@ void Compiler::unwindEmitFunc(FuncInfoDsc* func, void* pHotCode, void* pColdCode // pColdCode = nullptr; - // Unwind info is the frame size in 16-byte units and the virtual IP length. - // All values encoded via ULEB128. + // Interleave the frame size in 16-byte units and virtual IP count in 2-IP units into one ULEB128. // uint8_t buffer[10]; size_t index = 0; assert(func->endVirtualIP > func->startVirtualIP); assert((func->funWasmFrameSize % STACK_ALIGN) == 0); - index += GetEmitter()->emitOutputULEB128(buffer + index, func->funWasmFrameSize / STACK_ALIGN); - index += GetEmitter()->emitOutputULEB128(buffer + index, func->endVirtualIP - func->startVirtualIP); + index += GetEmitter()->emitOutputULEB128(buffer + index, + EncodeWasmUnwindInfo(func->funWasmFrameSize / STACK_ALIGN, + func->endVirtualIP - func->startVirtualIP)); assert(index <= sizeof(buffer)); JITDUMP("Unwind info for %s %u: VIP range [%u, %u); frame size %u\n", func->IsFunclet() ? "funclet" : "main", diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/GcInfoDecoderTests.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/GcInfoDecoderTests.cs index 9a8b7a20a991b7..6f16611d5a4dc3 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/GcInfoDecoderTests.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/GcInfoDecoderTests.cs @@ -1,6 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System; +using System.Collections.Generic; using System.IO; using System.Reflection.PortableExecutable; using ILCompiler.Reflection.ReadyToRun; @@ -12,15 +14,21 @@ namespace ILCompiler.ReadyToRun.Tests; public class GcInfoDecoderTests { [Theory] - [InlineData(0)] - [InlineData(1)] - [InlineData(2)] - [InlineData(3)] - public void Amd64SlotTableRetainsRegisterPresenceBit(int rootFlags) + [InlineData(0, 5)] + [InlineData(1, 5)] + [InlineData(2, 5)] + [InlineData(3, 5)] + [InlineData(0, 6)] + [InlineData(1, 6)] + [InlineData(2, 6)] + [InlineData(3, 6)] + public void Amd64SlotTableRetainsRegisterPresenceBit(int rootFlags, int version) { - byte[] encoded = [0x08, 0xC0, (byte)(rootFlags << 7), (byte)(rootFlags >> 1), 0x00, 0x00, 0x00, 0x00]; + byte[] encoded = version < 6 + ? [0x08, 0xC0, (byte)(rootFlags << 7), (byte)(rootFlags >> 1), 0x00, 0x00, 0x00, 0x00] + : [0x08, 0xC0, (byte)(rootFlags << 3), 0x00, 0x00, 0x00, 0x00, 0x00]; using MemoryStream stream = new(encoded); - GcInfo info = new(new NativeReader(stream), 0, Machine.Amd64, 5); + GcInfo info = new(new NativeReader(stream), 0, Machine.Amd64, version); Assert.Equal(1u, info.SlotTable.NumRegisters); Assert.Equal(0u, info.SlotTable.NumStackSlots); @@ -31,194 +39,496 @@ public void Amd64SlotTableRetainsRegisterPresenceBit(int rootFlags) Assert.Equal((GcSlotFlags)rootFlags, slot.Flags); } + public static IEnumerable RegisterSlotCases() + { + foreach (Machine machine in new[] { Machine.Amd64, Machine.ArmThumb2, Machine.Arm64, + Machine.I386, Machine.LoongArch64, Machine.RiscV64 }) + { + foreach (int version in new[] { 5, 6 }) + { + for (int flags = 0; flags < 4; flags++) + yield return [machine, version, flags]; + } + } + } + [Theory] - [InlineData(-1, 8, false, 0x02)] - [InlineData(0, 8, false, 0x02)] - [InlineData(1, 8, false, 0x02)] - [InlineData(2, 8, false, 0x02)] - [InlineData(3, 8, false, 0x02)] - [InlineData(0, -8, false, 0x06)] - [InlineData(0, 124, false, 0x3F)] - [InlineData(0, -128, false, 0x48)] - [InlineData(-1, 8, true, 0x02)] - [InlineData(0, 8, true, 0x02)] - [InlineData(1, 8, true, 0x02)] - [InlineData(2, 8, true, 0x02)] - [InlineData(3, 8, true, 0x02)] - [InlineData(0, -8, true, 0x06)] - [InlineData(0, 124, true, 0x3F)] - [InlineData(0, -128, true, 0x48)] - public void WasmSlotTableUsesImplicitFrameBaseAndPointerUnits(int rootFlags, int offset, bool slimHeader, int encodedOffset) + [MemberData(nameof(RegisterSlotCases))] + public void RegisterSlotsUseFlagsFirstAndBoundedIntegers(Machine machine, int version, int flags) { - int descriptor = rootFlags | (encodedOffset << 2); - byte[] encoded = (slimHeader, rootFlags < 0) switch + int maxRegister = machine switch { - (true, true) => [0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], - (false, true) => [0x81, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], - (true, false) => [0x0A, 0x40, 0x20, (byte)(descriptor << 3), (byte)(descriptor >> 5), 0x00, 0x00, 0x00], - (false, false) => [0x81, 0x10, 0x00, 0x08, 0x04, (byte)descriptor, (byte)(descriptor >> 8), 0x00], + Machine.I386 => 7, + Machine.ArmThumb2 => 15, + _ => 31, }; - using MemoryStream stream = new(encoded); - GcInfo info = new(new NativeReader(stream), 0, WasmMachine.Wasm32, 5); + for (int first = 0; first <= maxRegister; first++) + { + for (int last = first; last <= maxRegister; last++) + { + List<(int Register, int Flags)> registers = [(first, flags)]; + if (last != first) + registers.Add((last, flags)); + if (flags != 0) + { + registers.Add((0, flags - 1)); + registers.Add((maxRegister, flags - 1)); + } + AssertRegisterSlots(machine, version, registers); + } + } - Assert.Equal(2, info.CodeLength); - Assert.Equal(2u, info.StackBaseRegister); - Assert.Equal(0u, info.SlotTable.NumRegisters); - Assert.Equal(0u, info.SlotTable.NumStackSlots); - Assert.Equal(rootFlags < 0 ? 0u : 1u, info.SlotTable.NumUntracked); - if (rootFlags < 0) + List<(int Register, int Flags)> allRegisters = []; + for (int runFlags = 3; runFlags >= 0; runFlags--) + { + for (int register = 0; register <= maxRegister; register++) + allRegisters.Add((register, runFlags)); + } + AssertRegisterSlots(machine, version, allRegisters); + } + + private static void AssertRegisterSlots(Machine machine, int version, List<(int Register, int Flags)> registers) + { + SlotTableWriter writer = new(machine); + writer.WriteCounts(0, 0, registers.Count); + writer.WriteRegisters(registers, version); + writer.WriteUnsigned(0, 3); + using MemoryStream stream = new(writer.ToArray()); + GcInfo info = new(new NativeReader(stream), 0, machine, version); + Assert.Equal((uint)registers.Count, info.SlotTable.NumRegisters); + Assert.Equal(registers.Count, info.SlotTable.GcSlots.Count); + for (int i = 0; i < registers.Count; i++) { - Assert.Empty(info.SlotTable.GcSlots); - Assert.Equal(slimHeader ? 2 : 4, info.Size); + Assert.Equal(registers[i].Register, info.SlotTable.GcSlots[i].RegisterNumber); + Assert.Equal((GcSlotFlags)registers[i].Flags, info.SlotTable.GcSlots[i].Flags); + Assert.Null(info.SlotTable.GcSlots[i].StackSlot); } - else + Assert.Equal((writer.BitCount + 7) / 8, info.Size); + } + + public static IEnumerable StackSlotFlagCases() + { + Machine[] machines = [Machine.Amd64, Machine.ArmThumb2, Machine.Arm64, Machine.I386, + Machine.LoongArch64, Machine.RiscV64, WasmMachine.Wasm32]; + foreach (Machine machine in machines) { - GcSlotTable.GcSlot slot = Assert.Single(info.SlotTable.GcSlots); - Assert.Equal(offset, slot.StackSlot.SpOffset); - Assert.Equal(GcStackSlotBase.GC_FRAMEREG_REL, slot.StackSlot.Base); - Assert.Equal((GcSlotFlags)rootFlags | GcSlotFlags.GC_SLOT_UNTRACKED, slot.Flags); - Assert.Equal(slimHeader ? 5 : encodedOffset < 16 ? 6 : 7, info.Size); + foreach (bool tracked in new[] { false, true }) + { + foreach (int count in new[] { 1, 2, 3, 4, 31, 32, 33, 65 }) + { + for (int mask = 0; mask < 16; mask++) + { + yield return [machine, tracked, count, mask]; + } + } + } } } [Theory] - [InlineData(0, 0x08, 0x00)] - [InlineData(4, 0x08, 0x01)] - [InlineData(8, 0x08, 0x06)] - [InlineData(15, 0xC8, 0x07)] - [InlineData(16, 0x08, 0x0A)] - public void WasmSlotOffsetsUseUnsignedPointerUnitDeltas(int delta, byte firstByte, byte secondByte) + [MemberData(nameof(StackSlotFlagCases))] + public void StackSlotsUseFlagsThenBaseThenOffset(Machine machine, bool tracked, int count, int mask) { - byte[] encoded = [0x81, 0x10, 0x00, 0x08, 0x08, firstByte, secondByte, 0x00]; - using MemoryStream stream = new(encoded); - GcInfo info = new(new NativeReader(stream), 0, WasmMachine.Wasm32, 5); + SlotTableWriter writer = new(machine); + int[] counts = new int[4]; + int numSlots = 0; + for (int flags = 0; flags < counts.Length; flags++) + { + counts[flags] = (mask & (1 << flags)) != 0 ? count : 0; + numSlots += counts[flags]; + } + writer.WriteCounts(tracked ? numSlots : 0, tracked ? 0 : numSlots); + writer.WriteStackSlots(counts); + if (tracked && numSlots != 0) + writer.WriteUnsigned(0, 3); // No lifetime chunk pointers. + using MemoryStream stream = new(writer.ToArray()); + GcInfo info = new(new NativeReader(stream), 0, machine, 6); Assert.Equal(0u, info.SlotTable.NumRegisters); - Assert.Equal(0u, info.SlotTable.NumStackSlots); - Assert.Equal(2u, info.SlotTable.NumUntracked); - Assert.Equal(2, info.SlotTable.GcSlots.Count); - Assert.Equal(7, info.Size); - for (int i = 0; i < info.SlotTable.GcSlots.Count; i++) + Assert.Equal(tracked ? (uint)numSlots : 0u, info.SlotTable.NumStackSlots); + Assert.Equal(tracked ? 0u : (uint)numSlots, info.SlotTable.NumUntracked); + Assert.Equal(numSlots, info.SlotTable.GcSlots.Count); + Assert.Equal((writer.BitCount + 7) / 8, info.Size); + + int slotIndex = 0; + for (int flags = 3; flags >= 0; flags--) { - GcSlotTable.GcSlot slot = info.SlotTable.GcSlots[i]; - Assert.Equal(i == 0 ? 8 : 8 + delta * 4, slot.StackSlot.SpOffset); - Assert.Equal(GcStackSlotBase.GC_FRAMEREG_REL, slot.StackSlot.Base); - Assert.Equal(GcSlotFlags.GC_SLOT_UNTRACKED, slot.Flags); + for (int i = 0; i < counts[flags]; i++) + { + GcSlotTable.GcSlot slot = info.SlotTable.GcSlots[slotIndex++]; + Assert.Equal(writer.DenormalizeOffset(writer.GetStackOffset(i, count)), slot.StackSlot.SpOffset); + Assert.Equal(writer.GetStackBase(i, count), slot.StackSlot.Base); + Assert.Equal((GcSlotFlags)flags | (tracked ? 0 : GcSlotFlags.GC_SLOT_UNTRACKED), slot.Flags); + } } } [Theory] - [InlineData(0)] - [InlineData(1)] - [InlineData(2)] - [InlineData(3)] - public void WasmSlotOffsetsUseDeltasForAllFlagTypes(int rootFlags) + [InlineData(Machine.Amd64)] + [InlineData(Machine.ArmThumb2)] + [InlineData(Machine.Arm64)] + [InlineData(Machine.I386)] + [InlineData(Machine.LoongArch64)] + [InlineData(Machine.RiscV64)] + public void LegacyStackSlotFlagsRemainReadable(Machine machine) { - byte[] encoded = [0x01, (byte)(0x01 | (rootFlags << 5)), (byte)(rootFlags == 0 ? 0x09 : 0x21 | (rootFlags << 3)), 0x00]; - GcInfo info = DecodeWasmSlotTable(encoded); - GcSlotTable table = info.SlotTable; + SlotTableWriter writer = new(machine); + writer.WriteCounts(8, 8); + writer.WriteLegacySlots(); + writer.WriteLegacySlots(); + writer.WriteUnsigned(0, 3); - Assert.Equal(2u, table.NumUntracked); - Assert.Equal(5, info.Size); - for (int i = 0; i < table.GcSlots.Count; i++) + using MemoryStream stream = new(writer.ToArray()); + GcInfo info = new(new NativeReader(stream), 0, machine, 5); + Assert.Equal(8u, info.SlotTable.NumStackSlots); + Assert.Equal(8u, info.SlotTable.NumUntracked); + Assert.Equal(16, info.SlotTable.GcSlots.Count); + for (int i = 0; i < 16; i++) { - Assert.Equal(8 + i * 4, table.GcSlots[i].StackSlot.SpOffset); - Assert.Equal((GcSlotFlags)rootFlags | GcSlotFlags.GC_SLOT_UNTRACKED, table.GcSlots[i].Flags); + GcSlotTable.GcSlot slot = info.SlotTable.GcSlots[i]; + Assert.Equal(writer.DenormalizeOffset(-8 + i % 8), slot.StackSlot.SpOffset); + Assert.Equal((GcStackSlotBase)(i % 8 % 3), slot.StackSlot.Base); + Assert.Equal((GcSlotFlags)(3 - i % 8 / 2) | (i < 8 ? 0 : GcSlotFlags.GC_SLOT_UNTRACKED), slot.Flags); } + Assert.Equal((writer.BitCount + 7) / 8, info.Size); } [Theory] - [InlineData(false)] - [InlineData(true)] - public void WasmSlotOffsetsResetAtSectionAndFlagBoundaries(bool splitSections) + [InlineData(Machine.Amd64)] + [InlineData(WasmMachine.Wasm32)] + public void StackSlotFlagsAndBasesResetAtTrackedUntrackedBoundary(Machine machine) { - byte[] encoded = splitSections - ? [0x83, 0x80, 0x41, 0x00] - : [0x01, 0x64, 0x39, 0x34, 0x27, 0x64, 0x28, 0x40, 0x0A]; - int[] offsets = splitSections ? [12, 8] : [8, 12, -8, 4, 128, 132, -128, -124]; - int[] flags = splitSections ? [0, 0] : [3, 3, 2, 2, 1, 1, 0, 0]; - GcInfo info = DecodeWasmSlotTable(encoded); - GcSlotTable table = info.SlotTable; - - Assert.Equal(splitSections ? 1u : 0u, table.NumStackSlots); - Assert.Equal(splitSections ? 1u : 8u, table.NumUntracked); - Assert.Equal(splitSections ? 6 : 11, info.Size); - Assert.Equal(offsets.Length, table.GcSlots.Count); - for (int i = 0; i < offsets.Length; i++) + SlotTableWriter writer = new(machine); + writer.WriteCounts(2, 2); + writer.WriteStackSlots([0, 2, 0, 0]); + writer.WriteStackSlots([0, 2, 0, 0]); + writer.WriteUnsigned(0, 3); + + using MemoryStream stream = new(writer.ToArray()); + GcInfo info = new(new NativeReader(stream), 0, machine, 6); + Assert.Equal(4, info.SlotTable.GcSlots.Count); + for (int i = 0; i < 4; i++) { - GcSlotFlags expectedFlags = (GcSlotFlags)flags[i]; - if (!splitSections || i != 0) - { - expectedFlags |= GcSlotFlags.GC_SLOT_UNTRACKED; - } - Assert.Equal(offsets[i], table.GcSlots[i].StackSlot.SpOffset); - Assert.Equal(expectedFlags, table.GcSlots[i].Flags); + Assert.Equal(writer.DenormalizeOffset(writer.GetStackOffset(i % 2, 2)), info.SlotTable.GcSlots[i].StackSlot.SpOffset); + Assert.Equal(writer.GetStackBase(i % 2, 2), info.SlotTable.GcSlots[i].StackSlot.Base); + Assert.Equal(GcSlotFlags.GC_SLOT_INTERIOR | (i < 2 ? 0 : GcSlotFlags.GC_SLOT_UNTRACKED), info.SlotTable.GcSlots[i].Flags); } + Assert.Equal((writer.BitCount + 7) / 8, info.Size); + } + + [Theory] + [InlineData(Machine.Amd64, 0)] + [InlineData(Machine.Amd64, 1)] + [InlineData(Machine.Amd64, 2)] + [InlineData(Machine.Amd64, 3)] + [InlineData(WasmMachine.Wasm32, 0)] + [InlineData(WasmMachine.Wasm32, 1)] + [InlineData(WasmMachine.Wasm32, 2)] + [InlineData(WasmMachine.Wasm32, 3)] + public void StackSlotDeltasAllowZeroAndLargeGaps(Machine machine, int flags) + { + SlotTableWriter writer = new(machine); + writer.WriteCounts(0, 4); + int[] counts = new int[4]; + counts[flags] = 4; + writer.WriteStackSlots(counts, [0, 0, 15, 256]); + + using MemoryStream stream = new(writer.ToArray()); + GcInfo info = new(new NativeReader(stream), 0, machine, 6); + Assert.Equal(4, info.SlotTable.GcSlots.Count); + int[] offsets = [0, 0, 15, 256]; + for (int i = 0; i < offsets.Length; i++) + Assert.Equal(writer.DenormalizeOffset(offsets[i]), info.SlotTable.GcSlots[i].StackSlot.SpOffset); + Assert.Equal((writer.BitCount + 7) / 8, info.Size); } [Theory] - [InlineData(Machine.Amd64, true, 5u)] - [InlineData(Machine.Amd64, false, uint.MaxValue)] - [InlineData(WasmMachine.Wasm32, true, 2u)] - [InlineData(WasmMachine.Wasm32, false, uint.MaxValue)] - public void SlimHeaderUsesImplicitDefaultFrameRegister(Machine machine, bool hasFrameRegister, uint frameRegister) + [InlineData(Machine.Amd64, 6, 0x0A, 5u)] + [InlineData(Machine.Amd64, 6, 0x08, uint.MaxValue)] + [InlineData(WasmMachine.Wasm32, 5, 0x0A, 2u)] + [InlineData(WasmMachine.Wasm32, 5, 0x08, uint.MaxValue)] + [InlineData(WasmMachine.Wasm32, 6, 0x04, 2u)] + public void SlimHeaderUsesImplicitDefaultFrameRegister(Machine machine, int version, byte header, uint frameRegister) { - byte[] encoded = [hasFrameRegister ? (byte)0x0A : (byte)0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; + byte[] encoded = [header, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; using MemoryStream stream = new(encoded); - GcInfo info = new(new NativeReader(stream), 0, machine, 5); + GcInfo info = new(new NativeReader(stream), 0, machine, version); Assert.Equal(2, info.CodeLength); Assert.Equal(frameRegister, info.StackBaseRegister); Assert.Empty(info.SlotTable.GcSlots); - Assert.Equal(2, info.Size); + Assert.Equal(machine == WasmMachine.Wasm32 && version >= 6 ? 1 : 2, info.Size); } [Theory] - [InlineData(0xA1)] - [InlineData(0xC1)] - public void WasmFatHeaderPreservesGenericContext(byte header) + [InlineData(5, new byte[] { 0xA1, 0x10, 0x00, 0x01, 0x00 })] + [InlineData(5, new byte[] { 0xC1, 0x10, 0x00, 0x01, 0x00 })] + [InlineData(6, new byte[] { 0x21, 0x08, 0x02, 0x00 })] + [InlineData(6, new byte[] { 0x41, 0x08, 0x02, 0x00 })] + public void WasmFatHeaderPreservesGenericContext(int version, byte[] encoded) { - byte[] encoded = [header, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00]; using MemoryStream stream = new(encoded); - GcInfo info = new(new NativeReader(stream), 0, WasmMachine.Wasm32, 5); + GcInfo info = new(new NativeReader(stream), 0, WasmMachine.Wasm32, version); Assert.Equal(2, info.CodeLength); Assert.Equal(2u, info.StackBaseRegister); Assert.Equal(8, info.GenericsInstContextStackSlot); Assert.Equal(1u, info.ValidRangeStart); Assert.Empty(info.SlotTable.GcSlots); - Assert.Equal(5, info.Size); + Assert.Equal(encoded.Length, info.Size); + } + + [Theory] + [InlineData(new byte[] { 0x09, 0x08, 0x20, 0x00 }, 8, uint.MaxValue, -1, 0u)] + [InlineData(new byte[] { 0x01, 0x09, 0x01, 0x00 }, -1, 1u, -1, 0u)] + [InlineData(new byte[] { 0x01, 0x0A, 0x03, 0x00 }, -1, uint.MaxValue, 3, 0u)] + [InlineData(new byte[] { 0x01, 0x08, 0x01 }, -1, uint.MaxValue, -1, 1u)] + public void WasmFatHeaderPreservesOptionalFields(byte[] encoded, int cookieOffset, uint preservedArea, + int reversePInvokeOffset, uint safePoints) + { + using MemoryStream stream = new(encoded); + GcInfo info = new(new NativeReader(stream), 0, WasmMachine.Wasm32, 6); + + Assert.Equal(2, info.CodeLength); + Assert.Equal(2u, info.StackBaseRegister); + Assert.Equal(cookieOffset, info.GSCookieStackSlot); + Assert.Equal(preservedArea, info.SizeOfEditAndContinuePreservedArea); + Assert.Equal(reversePInvokeOffset, info.ReversePInvokeFrameStackSlot); + Assert.Equal(safePoints, info.NumSafePoints); + Assert.Equal((int)safePoints, info.SafePointOffsets.Count); + if (safePoints != 0) + Assert.Equal(0u, Assert.Single(info.SafePointOffsets).Value); + if (cookieOffset != -1) + { + Assert.Equal(1u, info.ValidRangeStart); + Assert.Equal(2u, info.ValidRangeEnd); + } + Assert.Empty(info.SlotTable.GcSlots); + Assert.Equal(encoded.Length, info.Size); } [Theory] - [InlineData(0x00, 0x00, 0u, 2)] - [InlineData(0x0E, 0x00, 224u, 2)] - [InlineData(0x7F, 0x00, 2032u, 2)] - [InlineData(0x80, 0x01, 2048u, 3)] - public void WasmUnwindFrameSizeUsesSixteenByteUnits(byte firstByte, byte secondByte, uint frameSize, int size) + [InlineData(new byte[] { 0x00 }, 0u, 0u)] + [InlineData(new byte[] { 0x11 }, 16u, 2u)] + [InlineData(new byte[] { 0x7F }, 240u, 14u)] + [InlineData(new byte[] { 0xF0, 0x02 }, 256u, 14u)] + [InlineData(new byte[] { 0x8F, 0x01 }, 240u, 16u)] + [InlineData(new byte[] { 0x80, 0x80, 0x84, 0x80, 0x10 }, 4096u, 512u)] + [InlineData(new byte[] { 0x81, 0x80, 0x80, 0x80, 0x10 }, 16u, 512u)] + [InlineData(new byte[] { 0x9F, 0x9E, 0xFC, 0x7F }, 0xFFFFF0u, 2u)] + [InlineData(new byte[] { 0x8F, 0xBE, 0xFC, 0xFF, 0x0F }, 0xFFFFFF0u, 32u)] + [InlineData(new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x3F }, 0xFFFFFF0u, 0x1FFFFFEu)] + [InlineData(new byte[] { 0xF0, 0xE1, 0x83, 0x80, 0xF0, 0xFF, 0x3F }, 0u, 0x1FFFFFEu)] + public void WasmUnwindInfoInterleavesFrameSizeAndVirtualIPCount(byte[] encoded, uint frameSize, uint virtualIPCount) { - byte[] encoded = size == 2 - ? [firstByte, 0x02] - : [firstByte, secondByte, 0x02]; using MemoryStream stream = new(encoded); ILCompiler.Reflection.ReadyToRun.Wasm32.UnwindInfo info = new(new NativeReader(stream), 0); Assert.Equal(frameSize, info.BytesUnwind); - Assert.Equal(4u, info.VirtualIPCount); - Assert.Equal(size, info.Size); + Assert.Equal(virtualIPCount, info.VirtualIPCount); + Assert.Equal(encoded.Length, info.Size); } - private static GcInfo DecodeWasmSlotTable(byte[] slotTable) + private sealed class SlotTableWriter { - byte[] encoded = new byte[slotTable.Length + 2]; - encoded[0] = 0x0A; - for (int i = 0; i < slotTable.Length; i++) + private readonly Machine _machine; + private readonly List _bytes = []; + public int BitCount { get; private set; } + + public SlotTableWriter(Machine machine) { - encoded[i + 1] |= (byte)(slotTable[i] << 6); - encoded[i + 2] |= (byte)(slotTable[i] >> 2); + _machine = machine; + Write(0, 1); + if (machine != WasmMachine.Wasm32) + Write(1, 1); + WriteUnsigned(2, machine switch + { + WasmMachine.Wasm32 => 5, + Machine.I386 => 6, + Machine.ArmThumb2 => 7, + _ => 8, + }); + if (machine != WasmMachine.Wasm32) + { + WriteUnsigned(0, machine switch + { + Machine.Amd64 => 2, + Machine.I386 => 4, + _ => 3, + }); + } + } + + public int DenormalizeOffset(int offset) => offset * (_machine switch + { + WasmMachine.Wasm32 or Machine.ArmThumb2 => 4, + Machine.I386 => 1, + _ => 8, + }); + + public void WriteCounts(int tracked, int untracked, int registers = 0) + { + if (_machine != WasmMachine.Wasm32) + { + Write(registers == 0 ? 0 : 1, 1); + if (registers != 0) + WriteUnsigned(registers, _machine is Machine.Amd64 or Machine.ArmThumb2 ? 2 : 3); + } + Write(tracked + untracked == 0 ? 0 : 1, 1); + if (tracked + untracked == 0) + return; + WriteUnsigned(tracked, _machine switch + { + WasmMachine.Wasm32 or Machine.I386 => 5, + Machine.ArmThumb2 => 3, + _ => 2, + }); + WriteUnsigned(untracked, _machine switch + { + WasmMachine.Wasm32 => 7, + Machine.I386 => 5, + Machine.ArmThumb2 => 3, + _ => 1, + }); + } + + public void WriteRegisters(List<(int Register, int Flags)> registers, int version) + { + int absoluteBase = _machine == Machine.ArmThumb2 ? 2 : 3; + int deltaBase = _machine switch + { + Machine.ArmThumb2 => 1, + Machine.I386 => 3, + _ => 2, + }; + int registerBits = _machine switch + { + Machine.I386 => 3, + Machine.ArmThumb2 => 4, + _ => 5, + }; + for (int i = 0; i < registers.Count; i++) + { + (int register, int flags) = registers[i]; + bool emitFlags = i == 0 || registers[i - 1].Flags != 0; + bool absolute = version < 6 ? emitFlags : i == 0 || flags != registers[i - 1].Flags; + int value = absolute ? register : register - registers[i - 1].Register - 1; + int encodingBase = absolute ? absoluteBase : deltaBase; + if (version >= 6) + { + if (emitFlags) + Write(flags, i == 0 || (registers[i - 1].Flags & 2) != 0 ? 2 : 1); + bool extended = value >= (1 << encodingBase); + Write((value & ((1 << encodingBase) - 1)) | (extended ? 1 << encodingBase : 0), encodingBase + 1); + if (extended) + Write(value >> encodingBase, registerBits - encodingBase); + } + else + { + WriteUnsigned(value, encodingBase); + if (emitFlags) + Write(flags, 2); + } + } + } + + public GcStackSlotBase GetStackBase(int index, int count) + { + return _machine != WasmMachine.Wasm32 && index < (count + 1) / 2 + ? GcStackSlotBase.GC_SP_REL : GcStackSlotBase.GC_FRAMEREG_REL; + } + + public int GetStackOffset(int index, int count) + { + return GetStackBase(index, count) == GcStackSlotBase.GC_FRAMEREG_REL + ? -8 + index - (_machine == WasmMachine.Wasm32 ? 0 : (count + 1) / 2) : 8 + index; + } + + public void WriteStackSlots(int[] counts, int[]? offsets = null) + { + int previousFlags = -1; + GcStackSlotBase previousBase = GcStackSlotBase.GC_FRAMEREG_REL; + int previousOffset = 0; + for (int flags = 3; flags >= 0; flags--) + { + int count = counts[flags]; + for (int i = 0; i < count; i++) + { + if (previousFlags != 0) + Write(flags, previousFlags < 0 || (previousFlags & 2) != 0 ? 2 : 1); + GcStackSlotBase slotBase = GetStackBase(i, count); + if (_machine != WasmMachine.Wasm32) + Write(slotBase == GcStackSlotBase.GC_FRAMEREG_REL ? 1 : 0, 1); + int offset = offsets is null ? GetStackOffset(i, count) : offsets[i]; + if (flags != previousFlags || slotBase != previousBase) + WriteSigned(offset, _machine == WasmMachine.Wasm32 ? 3 : 6); + else + WriteUnsigned(offset - previousOffset, _machine == WasmMachine.Wasm32 ? 3 : 4); + previousFlags = flags; + previousBase = slotBase; + previousOffset = offset; + } + } + } + + public void WriteLegacySlots() + { + for (int i = 0; i < 8; i++) + { + Write(i % 3, 2); + if (i < 7) + { + WriteSigned(-8 + i, 6); + Write(3 - i / 2, 2); + } + else + { + WriteUnsigned(1, 4); + } + } + } + + public void WriteUnsigned(int value, int encodingBase) + { + int mask = (1 << encodingBase) - 1; + do + { + int chunk = value & mask; + value >>>= encodingBase; + Write(chunk | (value == 0 ? 0 : 1 << encodingBase), encodingBase + 1); + } while (value != 0); + } + + private void WriteSigned(int value, int encodingBase) + { + while (true) + { + int chunk = value & ((1 << encodingBase) - 1); + value >>= encodingBase; + bool done = value == 0 && (chunk & (1 << (encodingBase - 1))) == 0 + || value == -1 && (chunk & (1 << (encodingBase - 1))) != 0; + Write(chunk | (done ? 0 : 1 << encodingBase), encodingBase + 1); + if (done) + return; + } + } + + private void Write(int value, int count) + { + for (int i = 0; i < count; i++, BitCount++) + { + if (BitCount % 8 == 0) + _bytes.Add(0); + _bytes[BitCount / 8] |= (byte)(((value >> i) & 1) << (BitCount % 8)); + } } - using MemoryStream stream = new(encoded); - return new GcInfo(new NativeReader(stream), 0, WasmMachine.Wasm32, 5); + public byte[] ToArray() + { + byte[] result = new byte[_bytes.Count + 8]; + _bytes.CopyTo(result); + + return result; + } } } diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/RuntimeFunctionsTableNode.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/RuntimeFunctionsTableNode.cs index f6967aad85279c..d6d9f2e1ce5875 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/RuntimeFunctionsTableNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/RuntimeFunctionsTableNode.cs @@ -107,12 +107,12 @@ public uint GetWasmVirtualIP(MethodWithGCInfo lookupMethod, int lookupFrameIndex /// /// Read the virtual IP count from a WASM unwind blob. - /// The blob format is: ULEB128(frameSize) followed by ULEB128(virtualIPCount). /// private static uint GetFunctionLocalVirtualIPCountFromUnwindBlob(byte[] blobData) { - DwarfHelper.ReadULEB128(blobData.AsSpan(), out int offset); // skip frame size - return (uint)DwarfHelper.ReadULEB128(blobData.AsSpan(offset), out _) * 2; // Multiply by 2 to force all virtual IPs to be an even number. + ulong encoded = DwarfHelper.ReadULEB128(blobData.AsSpan()); + return (uint)(((encoded >> 4) & 0xF) | (((encoded >> 12) & 0xF) << 4) | + (((encoded >> 32) & 0xFFFF) << 8)) * 2; } public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) diff --git a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Amd64/GcInfo.cs b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Amd64/GcInfo.cs index cc12f67eea0f67..af0fbdc635520b 100644 --- a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Amd64/GcInfo.cs +++ b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Amd64/GcInfo.cs @@ -64,6 +64,8 @@ public SafePointOffset(int index, uint value) private Machine _machine; private GcInfoTypes _gcInfoTypes; + private bool UsesCompactWasmHeader => _machine == WasmMachine.Wasm32 && Version >= 6; + public int Version { get; set; } public ReturnKinds ReturnKind { get; set; } public uint ValidRangeStart { get; set; } @@ -92,7 +94,7 @@ public GcInfo(NativeReader imageReader, int offset, Machine machine, int version Offset = offset; Version = version; bool denormalizeCodeOffsets = Version > MIN_GCINFO_VERSION_WITH_NORMALIZED_CODE_OFFSETS; - _gcInfoTypes = new GcInfoTypes(machine, denormalizeCodeOffsets); + _gcInfoTypes = new GcInfoTypes(machine, denormalizeCodeOffsets, version); _machine = machine; SecurityObjectStackSlot = -1; @@ -118,7 +120,8 @@ public GcInfo(NativeReader imageReader, int offset, Machine machine, int version if (_hasGSCookie) { - uint normPrologSize = imageReader.DecodeVarLengthUnsigned(_gcInfoTypes.NORM_PROLOG_SIZE_ENCBASE, ref bitOffset) + 1; + uint normPrologSize = UsesCompactWasmHeader ? 1 : + imageReader.DecodeVarLengthUnsigned(_gcInfoTypes.NORM_PROLOG_SIZE_ENCBASE, ref bitOffset) + 1; uint normEpilogSize = imageReader.DecodeVarLengthUnsigned(_gcInfoTypes.NORM_EPILOG_SIZE_ENCBASE, ref bitOffset); ValidRangeStart = _gcInfoTypes.DenormalizeCodeOffset(normPrologSize); @@ -126,7 +129,8 @@ public GcInfo(NativeReader imageReader, int offset, Machine machine, int version } else if (_hasSecurityObject || _hasGenericsInstContext) { - uint normValidRangeStart = imageReader.DecodeVarLengthUnsigned(_gcInfoTypes.NORM_PROLOG_SIZE_ENCBASE, ref bitOffset) + 1; + uint normValidRangeStart = UsesCompactWasmHeader ? 1 : + imageReader.DecodeVarLengthUnsigned(_gcInfoTypes.NORM_PROLOG_SIZE_ENCBASE, ref bitOffset) + 1; ValidRangeStart = _gcInfoTypes.DenormalizeCodeOffset(normValidRangeStart); ValidRangeEnd = ValidRangeStart + 1; } @@ -153,7 +157,7 @@ public GcInfo(NativeReader imageReader, int offset, Machine machine, int version if (_hasStackBaseRegister) { - uint normalizedRegister = _slimHeader + uint normalizedRegister = _slimHeader || UsesCompactWasmHeader ? 0 : imageReader.DecodeVarLengthUnsigned(_gcInfoTypes.STACK_BASE_REGISTER_ENCBASE, ref bitOffset); StackBaseRegister = _gcInfoTypes.DenormalizeStackBaseRegister(normalizedRegister); @@ -175,7 +179,8 @@ public GcInfo(NativeReader imageReader, int offset, Machine machine, int version } // PARTIALLY_INTERRUPTIBLE_GC_SUPPORTED (this macro is always defined in _gcInfoTypes.h) - NumSafePoints = imageReader.DecodeVarLengthUnsigned(_gcInfoTypes.NUM_SAFE_POINTS_ENCBASE, ref bitOffset); + NumSafePoints = UsesCompactWasmHeader && _slimHeader ? 0 : + imageReader.DecodeVarLengthUnsigned(_gcInfoTypes.NUM_SAFE_POINTS_ENCBASE, ref bitOffset); if (!_slimHeader && _gcInfoTypes.HAS_INTERRUPTIBLE_RANGES) { @@ -187,7 +192,7 @@ public GcInfo(NativeReader imageReader, int offset, Machine machine, int version InterruptibleRanges = EnumerateInterruptibleRanges(imageReader, _gcInfoTypes.INTERRUPTIBLE_RANGE_DELTA1_ENCBASE, _gcInfoTypes.INTERRUPTIBLE_RANGE_DELTA2_ENCBASE, ref bitOffset); - SlotTable = new GcSlotTable(imageReader, machine, _gcInfoTypes, ref bitOffset); + SlotTable = new GcSlotTable(imageReader, machine, _gcInfoTypes, ref bitOffset, Version); if (SlotTable.NumSlots > 0) { @@ -334,12 +339,22 @@ private void ParseHeaderFlags(NativeReader imageReader, ref int bitOffset) _slimHeader = (imageReader.ReadBits(1, ref bitOffset) == 0); if (_slimHeader) { - headerFlags = imageReader.ReadBits(1, ref bitOffset) == 1 ? GcInfoHeaderFlags.GC_INFO_HAS_STACK_BASE_REGISTER : 0; + headerFlags = UsesCompactWasmHeader || imageReader.ReadBits(1, ref bitOffset) == 1 + ? GcInfoHeaderFlags.GC_INFO_HAS_STACK_BASE_REGISTER : 0; } else { int numFlagBits = (int)((Version == 1) ? GcInfoHeaderFlags.GC_INFO_FLAGS_BIT_SIZE_VERSION_1 : GcInfoHeaderFlags.GC_INFO_FLAGS_BIT_SIZE); - headerFlags = (GcInfoHeaderFlags)imageReader.ReadBits(numFlagBits, ref bitOffset); + if (UsesCompactWasmHeader) + { + int flags = imageReader.ReadBits(numFlagBits - 1, ref bitOffset); + headerFlags = (GcInfoHeaderFlags)((flags & 0x3F) | ((flags & 0x1C0) << 1)) | + GcInfoHeaderFlags.GC_INFO_HAS_STACK_BASE_REGISTER; + } + else + { + headerFlags = (GcInfoHeaderFlags)imageReader.ReadBits(numFlagBits, ref bitOffset); + } } _hasSecurityObject = (headerFlags & GcInfoHeaderFlags.GC_INFO_HAS_SECURITY_OBJECT) != 0; diff --git a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Amd64/GcSlotTable.cs b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Amd64/GcSlotTable.cs index f29feaf5741910..2f212a651b8444 100644 --- a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Amd64/GcSlotTable.cs +++ b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Amd64/GcSlotTable.cs @@ -60,6 +60,8 @@ private static string GetRegisterName(int registerNumber, Machine machine) return ((x86.Registers)registerNumber).ToString(); case Machine.Amd64: + if (registerNumber is >= 16 and <= 31) + return $"R{registerNumber}"; return ((Amd64.Registers)registerNumber).ToString(); case Machine.ArmThumb2: @@ -106,7 +108,7 @@ public GcSlotTable() { } /// /// based on GcSlotDecoder::DecodeSlotTable /// - public GcSlotTable(NativeReader imageReader, Machine machine, GcInfoTypes gcInfoTypes, ref int bitOffset) + public GcSlotTable(NativeReader imageReader, Machine machine, GcInfoTypes gcInfoTypes, ref int bitOffset, int version) { _machine = machine; @@ -124,15 +126,15 @@ public GcSlotTable(NativeReader imageReader, Machine machine, GcInfoTypes gcInfo GcSlots = new List(); if (NumRegisters > 0) { - DecodeRegisters(imageReader, gcInfoTypes, ref bitOffset); + DecodeRegisters(imageReader, gcInfoTypes, ref bitOffset, version); } if (NumStackSlots > 0) { - DecodeStackSlots(imageReader, machine, gcInfoTypes, NumStackSlots, false, ref bitOffset); + DecodeStackSlots(imageReader, machine, gcInfoTypes, NumStackSlots, false, ref bitOffset, version); } if (NumUntracked > 0) { - DecodeStackSlots(imageReader, machine, gcInfoTypes, NumUntracked, true, ref bitOffset); + DecodeStackSlots(imageReader, machine, gcInfoTypes, NumUntracked, true, ref bitOffset, version); } } @@ -152,46 +154,70 @@ public override string ToString() return sb.ToString(); } - private void DecodeRegisters(NativeReader imageReader, GcInfoTypes gcInfoTypes, ref int bitOffset) + private static uint ReadRegisterValue(NativeReader imageReader, int encodingBase, int registerBits, ref int bitOffset) { - // We certainly predecode the first register - uint regNum = imageReader.DecodeVarLengthUnsigned(gcInfoTypes.REGISTER_ENCBASE, ref bitOffset); - GcSlotFlags flags = (GcSlotFlags)imageReader.ReadBits(2, ref bitOffset); - GcSlots.Add(new GcSlot(GcSlots.Count, (int)regNum, null, flags)); + uint chunk = (uint)imageReader.ReadBits(encodingBase + 1, ref bitOffset); + uint value = chunk & ((1u << encodingBase) - 1); + if ((chunk & (1u << encodingBase)) != 0) + { + if (registerBits <= encodingBase) + throw new BadImageFormatException("GC register encoding exceeds the target register width."); + value |= (uint)imageReader.ReadBits(registerBits - encodingBase, ref bitOffset) << encodingBase; + } + + return value; + } + + private static GcSlotFlags ReadSlotFlags(NativeReader imageReader, GcSlotFlags previousFlags, bool first, ref int bitOffset) + { + return first || previousFlags != 0 + ? (GcSlotFlags)imageReader.ReadBits(first || (previousFlags & GcSlotFlags.GC_SLOT_PINNED) != 0 ? 2 : 1, ref bitOffset) + : 0; + } - for (int i = 1; i < NumRegisters; i++) + private void DecodeRegisters(NativeReader imageReader, GcInfoTypes gcInfoTypes, ref int bitOffset, int version) + { + uint regNum = 0; + GcSlotFlags flags = 0; + for (int i = 0; i < NumRegisters; i++) { - if ((uint)flags != 0) + bool absolute = i == 0 || flags != 0; + if (version >= 6) { - regNum = imageReader.DecodeVarLengthUnsigned(gcInfoTypes.REGISTER_ENCBASE, ref bitOffset); - flags = (GcSlotFlags)imageReader.ReadBits(2, ref bitOffset); - } - else - { - uint regDelta = imageReader.DecodeVarLengthUnsigned(gcInfoTypes.REGISTER_DELTA_ENCBASE, ref bitOffset) + 1; - regNum += regDelta; + GcSlotFlags previousFlags = flags; + flags = ReadSlotFlags(imageReader, previousFlags, i == 0, ref bitOffset); + absolute = i == 0 || flags != previousFlags; } + int encodingBase = absolute ? gcInfoTypes.REGISTER_ENCBASE : gcInfoTypes.REGISTER_DELTA_ENCBASE; + uint value = version >= 6 + ? ReadRegisterValue(imageReader, encodingBase, gcInfoTypes.REGISTER_BITS, ref bitOffset) + : imageReader.DecodeVarLengthUnsigned(encodingBase, ref bitOffset); + regNum = absolute ? value : regNum + value + 1; + if (version < 6 && absolute) + flags = (GcSlotFlags)imageReader.ReadBits(2, ref bitOffset); GcSlots.Add(new GcSlot(GcSlots.Count, (int)regNum, null, flags)); } } - private void DecodeStackSlots(NativeReader imageReader, Machine machine, GcInfoTypes gcInfoTypes, uint nSlots, bool isUntracked, ref int bitOffset) + private void DecodeStackSlots(NativeReader imageReader, Machine machine, GcInfoTypes gcInfoTypes, uint nSlots, bool isUntracked, ref int bitOffset, int version) { - if (machine == WasmMachine.Wasm32) + if (version >= 6) { - GcSlotFlags previousFlags = (GcSlotFlags)7; + GcSlotFlags slotFlags = 0; + GcStackSlotBase previousBase = GcStackSlotBase.GC_SP_REL; int offset = 0; - for (int i = 0; i < nSlots; i++) + for (uint i = 0; i < nSlots; i++) { - GcSlotFlags slotFlags = previousFlags == GcSlotFlags.GC_SLOT_BASE - ? GcSlotFlags.GC_SLOT_BASE - : (GcSlotFlags)imageReader.ReadBits(2, ref bitOffset); - offset = slotFlags != previousFlags + GcSlotFlags previousFlags = slotFlags; + slotFlags = ReadSlotFlags(imageReader, previousFlags, i == 0, ref bitOffset); + GcStackSlotBase slotBase = machine != WasmMachine.Wasm32 && imageReader.ReadBits(1, ref bitOffset) == 0 + ? GcStackSlotBase.GC_SP_REL : GcStackSlotBase.GC_FRAMEREG_REL; + offset = i == 0 || slotFlags != previousFlags || slotBase != previousBase ? imageReader.DecodeVarLengthSigned(gcInfoTypes.STACK_SLOT_ENCBASE, ref bitOffset) : offset + (int)imageReader.DecodeVarLengthUnsigned(gcInfoTypes.STACK_SLOT_DELTA_ENCBASE, ref bitOffset); int byteOffset = gcInfoTypes.DenormalizeStackSlot(offset); - GcSlots.Add(new GcSlot(GcSlots.Count, -1, new GcStackSlot(byteOffset, GcStackSlotBase.GC_FRAMEREG_REL), slotFlags, isUntracked)); - previousFlags = slotFlags; + GcSlots.Add(new GcSlot(GcSlots.Count, -1, new GcStackSlot(byteOffset, slotBase), slotFlags, isUntracked)); + previousBase = slotBase; } return; } diff --git a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/GCInfoTypes.cs b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/GCInfoTypes.cs index 2723eb7ab5f7c8..7058647fcdc75f 100644 --- a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/GCInfoTypes.cs +++ b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/GCInfoTypes.cs @@ -112,6 +112,7 @@ public class GcInfoTypes internal int NUM_UNTRACKED_SLOTS_ENCBASE { get; } = 1; internal int REGISTER_ENCBASE { get; } = 3; internal int REGISTER_DELTA_ENCBASE { get; } = 2; + internal int REGISTER_BITS { get; } = 5; internal int STACK_SLOT_ENCBASE { get; } = 6; internal int STACK_SLOT_DELTA_ENCBASE { get; } = 4; internal int POINTER_SIZE_ENCBASE { get; } = 3; @@ -122,7 +123,7 @@ public class GcInfoTypes internal bool HAS_FIXED_STACK_PARAMETER_SCRATCH_AREA { get; } = true; internal bool HAS_INTERRUPTIBLE_RANGES { get; } = true; - internal GcInfoTypes(Machine machine, bool denormalizeCodeOffsets) + internal GcInfoTypes(Machine machine, bool denormalizeCodeOffsets, int version) { _target = machine; _denormalizeCodeOffsets = denormalizeCodeOffsets; @@ -134,6 +135,7 @@ internal GcInfoTypes(Machine machine, bool denormalizeCodeOffsets) NUM_SAFE_POINTS_ENCBASE = 2; break; case Machine.ArmThumb2: + REGISTER_BITS = 4; CODE_LENGTH_ENCBASE = 7; SECURITY_OBJECT_STACK_SLOT_ENCBASE = 5; GS_COOKIE_STACK_SLOT_ENCBASE = 5; @@ -159,14 +161,14 @@ internal GcInfoTypes(Machine machine, bool denormalizeCodeOffsets) GENERICS_INST_CONTEXT_STACK_SLOT_ENCBASE = 6; SECURITY_OBJECT_STACK_SLOT_ENCBASE = 6; GS_COOKIE_STACK_SLOT_ENCBASE = 6; - CODE_LENGTH_ENCBASE = 6; + CODE_LENGTH_ENCBASE = version >= 6 ? 5 : 6; STACK_BASE_REGISTER_ENCBASE = 3; SIZE_OF_STACK_AREA_ENCBASE = 6; SIZE_OF_EDIT_AND_CONTINUE_PRESERVED_AREA_ENCBASE = 3; - REVERSE_PINVOKE_FRAME_ENCBASE = 6; + REVERSE_PINVOKE_FRAME_ENCBASE = version >= 6 ? 4 : 6; NUM_REGISTERS_ENCBASE = 3; NUM_STACK_SLOTS_ENCBASE = 5; - NUM_UNTRACKED_SLOTS_ENCBASE = 5; + NUM_UNTRACKED_SLOTS_ENCBASE = version >= 6 ? 7 : 5; NORM_PROLOG_SIZE_ENCBASE = 4; NORM_EPILOG_SIZE_ENCBASE = 3; INTERRUPTIBLE_RANGE_DELTA1_ENCBASE = 5; @@ -175,7 +177,7 @@ internal GcInfoTypes(Machine machine, bool denormalizeCodeOffsets) REGISTER_DELTA_ENCBASE = REGISTER_ENCBASE; STACK_SLOT_ENCBASE = 3; STACK_SLOT_DELTA_ENCBASE = 3; - NUM_SAFE_POINTS_ENCBASE = 4; + NUM_SAFE_POINTS_ENCBASE = version >= 6 ? 3 : 4; NUM_INTERRUPTIBLE_RANGES_ENCBASE = 1; POINTER_SIZE_ENCBASE = 3; LIVESTATE_RLE_RUN_ENCBASE = 2; @@ -185,6 +187,7 @@ internal GcInfoTypes(Machine machine, bool denormalizeCodeOffsets) break; case Machine.I386: + REGISTER_BITS = 3; CODE_LENGTH_ENCBASE = 6; NORM_PROLOG_SIZE_ENCBASE = 4; SIZE_OF_EDIT_AND_CONTINUE_PRESERVED_AREA_ENCBASE = 3; diff --git a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/NativeReader.cs b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/NativeReader.cs index abd2ff09bc6783..0136347e6c34a1 100644 --- a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/NativeReader.cs +++ b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/NativeReader.cs @@ -388,7 +388,7 @@ public uint DecodeUDelta(ref int start, uint lastValue) /// Reads a standard unsigned LEB128 value starting at and advances /// past the encoded bytes. /// - public uint ReadULEB128(ref int start) + public ulong ReadULEB128(ref int start) { // 24 bytes is longer than the longest valid LEB128. int bytesToRead = Math.Min(24, (int)_backingStream.Length - start); @@ -398,7 +398,7 @@ public uint ReadULEB128(ref int start) Span buffer = stackalloc byte[24]; int readStart = start; ReadSpanAt(ref readStart, buffer.Slice(0, bytesToRead)); - uint result = checked((uint)DwarfHelper.ReadULEB128(buffer.Slice(0, bytesToRead), out int bytesRead)); + ulong result = DwarfHelper.ReadULEB128(buffer.Slice(0, bytesToRead), out int bytesRead); start += bytesRead; return result; } diff --git a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/ReadyToRunMethod.cs b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/ReadyToRunMethod.cs index 6a014fbeab897b..c58cb7bbc1d6ec 100644 --- a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/ReadyToRunMethod.cs +++ b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/ReadyToRunMethod.cs @@ -97,7 +97,8 @@ internal static int ReadyToRunVersionToGcInfoVersion(int readyToRunMajorVersion, if (readyToRunMajorVersion < 21) return 4; - return 5; + // R2R 33.0+ uses GCInfo v6. + return readyToRunMajorVersion >= 33 ? 6 : 5; } } diff --git a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Wasm32/UnwindInfo.cs b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Wasm32/UnwindInfo.cs index f5f4ecf1066107..a25eb45c79e137 100644 --- a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Wasm32/UnwindInfo.cs +++ b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Wasm32/UnwindInfo.cs @@ -6,8 +6,7 @@ namespace ILCompiler.Reflection.ReadyToRun.Wasm32 { /// Parses the WASM unwind info blob used by ReadyToRun. - /// The blob format is two unsigned LEB128 values in order: - /// Frame size / 16, followed by virtual IP span / 2. + /// The blob is one unsigned LEB128 value interleaving frame size / 16 and virtual IP span / 2. /// is the number of bytes consumed while decoding those fields. public class UnwindInfo : BaseUnwindInfo { @@ -20,8 +19,11 @@ public UnwindInfo() { } public UnwindInfo(NativeReader imageReader, int offset) { uint startOffset = (uint)offset; - BytesUnwind = checked(imageReader.ReadULEB128(ref offset) * 16); - VirtualIPCount = imageReader.ReadULEB128(ref offset) * 2; + ulong encoded = imageReader.ReadULEB128(ref offset); + BytesUnwind = (uint)((encoded & 0xF) | (((encoded >> 8) & 0xF) << 4) | + (((encoded >> 16) & 0xFFFF) << 8)) * 16; + VirtualIPCount = (uint)(((encoded >> 4) & 0xF) | (((encoded >> 12) & 0xF) << 4) | + (((encoded >> 32) & 0xFFFF) << 8)) * 2; Size = offset - (int)startOffset; } diff --git a/src/coreclr/vm/codeman.cpp b/src/coreclr/vm/codeman.cpp index a039d39815a26b..59dfdf990cca8d 100644 --- a/src/coreclr/vm/codeman.cpp +++ b/src/coreclr/vm/codeman.cpp @@ -1303,8 +1303,7 @@ PTR_VOID GetUnwindDataBlob(TADDR moduleBase, PTR_RUNTIME_FUNCTION pRuntimeFuncti #elif defined(TARGET_WASM) PTR_BYTE pUnwindInfo(dac_cast(moduleBase + pRuntimeFunction->UnwindData)); PTR_BYTE pUnwindData = pUnwindInfo; - DecodeULEB128AsU32(&pUnwindData); // Skip the count of bytes to unwind - DecodeULEB128AsU32(&pUnwindData); // Read the function length in virtual IP units + DecodeULEB128AsU64(&pUnwindData); *pSize = static_cast(pUnwindData - pUnwindInfo); return pUnwindInfo; #else diff --git a/src/coreclr/vm/gcinfodecoder.cpp b/src/coreclr/vm/gcinfodecoder.cpp index 5c4b9050e2a4f8..4f11918e14e779 100644 --- a/src/coreclr/vm/gcinfodecoder.cpp +++ b/src/coreclr/vm/gcinfodecoder.cpp @@ -95,7 +95,16 @@ template bool TGcInfoDecoder::SetIsInt // returns true if we decoded all that was asked; template bool TGcInfoDecoder::PredecodeFatHeader(int remainingFlags) { - m_headerFlags = (GcInfoHeaderFlags)m_Reader.Read(GC_INFO_FLAGS_BIT_SIZE); + if (UsesCompactWasmHeader()) + { + UINT32 flags = static_cast(m_Reader.Read(GC_INFO_FLAGS_BIT_SIZE - 1)); + m_headerFlags = static_cast((flags & 0x3F) | ((flags & 0x1C0) << 1) | + GC_INFO_HAS_STACK_BASE_REGISTER); + } + else + { + m_headerFlags = (GcInfoHeaderFlags)m_Reader.Read(GC_INFO_FLAGS_BIT_SIZE); + } #ifdef DECODE_OLD_FORMATS if (Version() < 4) @@ -113,7 +122,8 @@ template bool TGcInfoDecoder::Predecod return true; } - m_CodeLength = GcInfoEncoding::DENORMALIZE_CODE_LENGTH((UINT32)m_Reader.DecodeVarLengthUnsigned(GcInfoEncoding::CODE_LENGTH_ENCBASE)); + m_CodeLength = GcInfoEncoding::DENORMALIZE_CODE_LENGTH((UINT32)m_Reader.DecodeVarLengthUnsigned( + UsesLegacyWasmEncoding() ? 6 : GcInfoEncoding::CODE_LENGTH_ENCBASE)); remainingFlags &= ~DECODE_CODE_LENGTH; if (remainingFlags == 0) { @@ -128,7 +138,8 @@ template bool TGcInfoDecoder::Predecod UINT32 normCodeLength = NormalizeCodeOffset(m_CodeLength); // Decode prolog/epilog information - UINT32 normPrologSize = (UINT32)m_Reader.DecodeVarLengthUnsigned(GcInfoEncoding::NORM_PROLOG_SIZE_ENCBASE) + 1; + UINT32 normPrologSize = UsesCompactWasmHeader() ? 1 : + (UINT32)m_Reader.DecodeVarLengthUnsigned(GcInfoEncoding::NORM_PROLOG_SIZE_ENCBASE) + 1; UINT32 normEpilogSize = (UINT32)m_Reader.DecodeVarLengthUnsigned(GcInfoEncoding::NORM_EPILOG_SIZE_ENCBASE); m_ValidRangeStart = DenormalizeCodeOffset(normPrologSize); @@ -138,7 +149,8 @@ template bool TGcInfoDecoder::Predecod else if ((m_headerFlags & GC_INFO_HAS_GENERICS_INST_CONTEXT_MASK) != GC_INFO_HAS_GENERICS_INST_CONTEXT_NONE) { // Decode prolog information - UINT32 normPrologSize = (UINT32)m_Reader.DecodeVarLengthUnsigned(GcInfoEncoding::NORM_PROLOG_SIZE_ENCBASE) + 1; + UINT32 normPrologSize = UsesCompactWasmHeader() ? 1 : + (UINT32)m_Reader.DecodeVarLengthUnsigned(GcInfoEncoding::NORM_PROLOG_SIZE_ENCBASE) + 1; m_ValidRangeStart = DenormalizeCodeOffset(normPrologSize); // satisfy asserts that assume m_GSCookieValidRangeStart != 0 ==> m_GSCookieValidRangeStart < m_GSCookieValidRangeEnd m_ValidRangeEnd = m_ValidRangeStart + 1; @@ -211,7 +223,8 @@ template bool TGcInfoDecoder::Predecod if (m_headerFlags & GC_INFO_HAS_STACK_BASE_REGISTER) { - m_StackBaseRegister = GcInfoEncoding::DENORMALIZE_STACK_BASE_REGISTER((UINT32)m_Reader.DecodeVarLengthUnsigned(GcInfoEncoding::STACK_BASE_REGISTER_ENCBASE)); + m_StackBaseRegister = GcInfoEncoding::DENORMALIZE_STACK_BASE_REGISTER(UsesCompactWasmHeader() ? 0 : + (UINT32)m_Reader.DecodeVarLengthUnsigned(GcInfoEncoding::STACK_BASE_REGISTER_ENCBASE)); } else { @@ -242,7 +255,8 @@ template bool TGcInfoDecoder::Predecod if (m_headerFlags & GC_INFO_REVERSE_PINVOKE_FRAME) { - m_ReversePInvokeFrameStackSlot = GcInfoEncoding::DENORMALIZE_STACK_SLOT((INT32)m_Reader.DecodeVarLengthSigned(GcInfoEncoding::REVERSE_PINVOKE_FRAME_ENCBASE)); + m_ReversePInvokeFrameStackSlot = GcInfoEncoding::DENORMALIZE_STACK_SLOT((INT32)m_Reader.DecodeVarLengthSigned( + UsesLegacyWasmEncoding() ? 6 : GcInfoEncoding::REVERSE_PINVOKE_FRAME_ENCBASE)); } else { @@ -302,7 +316,7 @@ TGcInfoDecoder::TGcInfoDecoder( } else { - if (m_Reader.ReadOneFast()) + if (UsesCompactWasmHeader() || m_Reader.ReadOneFast()) { m_headerFlags = GC_INFO_HAS_STACK_BASE_REGISTER; m_StackBaseRegister = GcInfoEncoding::DENORMALIZE_STACK_BASE_REGISTER(0); @@ -330,7 +344,8 @@ TGcInfoDecoder::TGcInfoDecoder( return; } - m_CodeLength = GcInfoEncoding::DENORMALIZE_CODE_LENGTH((UINT32)m_Reader.DecodeVarLengthUnsigned(GcInfoEncoding::CODE_LENGTH_ENCBASE)); + m_CodeLength = GcInfoEncoding::DENORMALIZE_CODE_LENGTH((UINT32)m_Reader.DecodeVarLengthUnsigned( + UsesLegacyWasmEncoding() ? 6 : GcInfoEncoding::CODE_LENGTH_ENCBASE)); // // predecoding the rest of slim header does not require any reading. @@ -370,7 +385,8 @@ TGcInfoDecoder::TGcInfoDecoder( } #ifdef PARTIALLY_INTERRUPTIBLE_GC_SUPPORTED - m_NumSafePoints = (UINT32) m_Reader.DecodeVarLengthUnsigned(GcInfoEncoding::NUM_SAFE_POINTS_ENCBASE); + m_NumSafePoints = UsesCompactWasmHeader() && slimHeader ? 0 : + (UINT32)m_Reader.DecodeVarLengthUnsigned(UsesLegacyWasmEncoding() ? 4 : GcInfoEncoding::NUM_SAFE_POINTS_ENCBASE); m_SafePointIndex = m_NumSafePoints; _ASSERTE(GcInfoEncoding::HAS_TRACKED_SLOTS || m_NumSafePoints == 0); #endif @@ -839,7 +855,7 @@ template bool TGcInfoDecoder::Enumerat //------------------------------------------------------------------------------ - slotDecoder.DecodeSlotTable(m_Reader); + slotDecoder.DecodeSlotTable(m_Reader, Version()); if (reportUntrackedOnly) goto ReportUntracked; @@ -1134,7 +1150,7 @@ template void TGcInfoDecoder::Enumerat // Read the slot table //------------------------------------------------------------------------------ - slotDecoder.DecodeSlotTable(m_Reader); + slotDecoder.DecodeSlotTable(m_Reader, Version()); if (slotDecoder.GetNumUntracked()) { @@ -1163,8 +1179,9 @@ template void TGcInfoDecoder::ReportUn } } -template void GcSlotDecoder::DecodeSlotTable(BitStreamReader& reader) +template void GcSlotDecoder::DecodeSlotTable(BitStreamReader& reader, UINT32 version) { + m_UseCompactSlotEncoding = version >= 6; if constexpr (GcInfoEncoding::HAS_REGISTER_SLOTS) { if (reader.ReadOneFast()) @@ -1184,7 +1201,8 @@ template void GcSlotDecoder::DecodeSlo if (reader.ReadOneFast()) { numStackSlots = (UINT32) reader.DecodeVarLengthUnsigned(GcInfoEncoding::NUM_STACK_SLOTS_ENCBASE); - m_NumUntracked = (UINT32) reader.DecodeVarLengthUnsigned(GcInfoEncoding::NUM_UNTRACKED_SLOTS_ENCBASE); + m_NumUntracked = (UINT32) reader.DecodeVarLengthUnsigned( + GcInfoEncoding::USES_COMPACT_WASM_HEADER && version < 6 ? 5 : GcInfoEncoding::NUM_UNTRACKED_SLOTS_ENCBASE); } else { @@ -1202,9 +1220,8 @@ template void GcSlotDecoder::DecodeSlo _ASSERTE(i < MAX_PREDECODED_SLOTS); - UINT32 normRegNum = (UINT32) reader.DecodeVarLengthUnsigned(GcInfoEncoding::REGISTER_ENCBASE); - UINT32 regNum = normRegNum; - GcSlotFlags flags = (GcSlotFlags) reader.Read(2); + GcSlotFlags flags = GC_SLOT_BASE; + UINT32 regNum = ReadRegisterSlot(reader, flags, 0, true); m_SlotArray[0].Slot.RegisterNumber = regNum; m_SlotArray[0].Flags = flags; @@ -1212,18 +1229,7 @@ template void GcSlotDecoder::DecodeSlo UINT32 loopEnd = _min(m_NumRegisters, MAX_PREDECODED_SLOTS); for(i++; i < loopEnd; i++) { - if(flags) - { - normRegNum = (UINT32) reader.DecodeVarLengthUnsigned(GcInfoEncoding::REGISTER_ENCBASE); - regNum = normRegNum; - flags = (GcSlotFlags) reader.Read(2); - } - else - { - UINT32 normRegDelta = (UINT32) reader.DecodeVarLengthUnsigned(GcInfoEncoding::REGISTER_DELTA_ENCBASE) + 1; - normRegNum += normRegDelta; - regNum = normRegNum; - } + regNum = ReadRegisterSlot(reader, flags, regNum, false); m_SlotArray[i].Slot.RegisterNumber = regNum; m_SlotArray[i].Flags = flags; @@ -1234,9 +1240,9 @@ template void GcSlotDecoder::DecodeSlo { // We have stack slots left and more room to predecode - GcStackSlotBase spBase = ReadStackSlotBase(reader); + GcStackSlotBase spBase; GcSlotFlags flags = GC_SLOT_BASE; - UINT32 normSpOffset = ReadStackSlotOffset(reader, flags, 0, true); + UINT32 normSpOffset = ReadStackSlot(reader, flags, spBase, 0, true); INT32 spOffset = GcInfoEncoding::DENORMALIZE_STACK_SLOT(normSpOffset); m_SlotArray[i].Slot.Stack.SpOffset = spOffset; @@ -1246,9 +1252,7 @@ template void GcSlotDecoder::DecodeSlo UINT32 loopEnd = _min(GetNumRegisters() + numStackSlots, MAX_PREDECODED_SLOTS); for(i++; i < loopEnd; i++) { - spBase = ReadStackSlotBase(reader); - - normSpOffset = ReadStackSlotOffset(reader, flags, normSpOffset, false); + normSpOffset = ReadStackSlot(reader, flags, spBase, normSpOffset, false); spOffset = GcInfoEncoding::DENORMALIZE_STACK_SLOT(normSpOffset); m_SlotArray[i].Slot.Stack.SpOffset = spOffset; @@ -1263,9 +1267,9 @@ template void GcSlotDecoder::DecodeSlo // Interpreter-TODO: Add a configurable way to skip encoding/decoding the base for the interpreter, because // all interpreter locals are at positive offsets relative to FP. - GcStackSlotBase spBase = ReadStackSlotBase(reader); + GcStackSlotBase spBase; GcSlotFlags flags = GC_SLOT_BASE; - UINT32 normSpOffset = ReadStackSlotOffset(reader, flags, 0, true); + UINT32 normSpOffset = ReadStackSlot(reader, flags, spBase, 0, true); INT32 spOffset = GcInfoEncoding::DENORMALIZE_STACK_SLOT(normSpOffset); m_SlotArray[i].Slot.Stack.SpOffset = spOffset; @@ -1275,9 +1279,7 @@ template void GcSlotDecoder::DecodeSlo UINT32 loopEnd = _min(m_NumSlots, MAX_PREDECODED_SLOTS); for(i++; i < loopEnd; i++) { - spBase = ReadStackSlotBase(reader); - - normSpOffset = ReadStackSlotOffset(reader, flags, normSpOffset, false); + normSpOffset = ReadStackSlot(reader, flags, spBase, normSpOffset, false); spOffset = GcInfoEncoding::DENORMALIZE_STACK_SLOT(normSpOffset); m_SlotArray[i].Slot.Stack.SpOffset = spOffset; @@ -1301,20 +1303,13 @@ template void GcSlotDecoder::DecodeSlo // Move the argument reader past the end of the table GcSlotFlags flags = m_pLastSlot->Flags; + GcStackSlotBase spBase = i > m_NumRegisters ? m_pLastSlot->Slot.Stack.Base : GC_SP_REL; // Skip any remaining registers for(; GcInfoEncoding::HAS_REGISTER_SLOTS && i < m_NumRegisters; i++) { - if(flags) - { - reader.DecodeVarLengthUnsigned(GcInfoEncoding::REGISTER_ENCBASE); - flags = (GcSlotFlags) reader.Read(2); - } - else - { - reader.DecodeVarLengthUnsigned(GcInfoEncoding::REGISTER_DELTA_ENCBASE); - } + ReadRegisterSlot(reader, flags, 0, false); } if(GcInfoEncoding::HAS_TRACKED_SLOTS && numStackSlots > 0) @@ -1323,8 +1318,7 @@ template void GcSlotDecoder::DecodeSlo { // Skip the first stack slot - ReadStackSlotBase(reader); - ReadStackSlotOffset(reader, flags, 0, true); + ReadStackSlot(reader, flags, spBase, 0, true); i++; } @@ -1333,9 +1327,7 @@ template void GcSlotDecoder::DecodeSlo const UINT32 loopEnd = GetNumRegisters() + numStackSlots; for(; i < loopEnd; i++) { - ReadStackSlotBase(reader); - - ReadStackSlotOffset(reader, flags, 0, false); + ReadStackSlot(reader, flags, spBase, 0, false); } } @@ -1345,8 +1337,7 @@ template void GcSlotDecoder::DecodeSlo { // Skip the first untracked slot - ReadStackSlotBase(reader); - ReadStackSlotOffset(reader, flags, 0, true); + ReadStackSlot(reader, flags, spBase, 0, true); i++; } @@ -1354,9 +1345,7 @@ template void GcSlotDecoder::DecodeSlo for(; i < m_NumSlots; i++) { - ReadStackSlotBase(reader); - - ReadStackSlotOffset(reader, flags, 0, false); + ReadStackSlot(reader, flags, spBase, 0, false); } } } @@ -1382,28 +1371,8 @@ template const GcSlotDesc* GcSlotDecoderSlot.RegisterNumber = normRegNum; - m_pLastSlot->Flags = (GcSlotFlags) m_SlotReader.Read(2); - } - else - { - if(m_pLastSlot->Flags) - { - UINT32 normRegNum = (UINT32) m_SlotReader.DecodeVarLengthUnsigned(GcInfoEncoding::REGISTER_ENCBASE); - m_pLastSlot->Slot.RegisterNumber = normRegNum; - m_pLastSlot->Flags = (GcSlotFlags) m_SlotReader.Read(2); - } - else - { - UINT32 normRegDelta = (UINT32) m_SlotReader.DecodeVarLengthUnsigned(GcInfoEncoding::REGISTER_DELTA_ENCBASE) + 1; - UINT32 normRegNum = normRegDelta + m_pLastSlot->Slot.RegisterNumber; - m_pLastSlot->Slot.RegisterNumber = normRegNum; - } - } + m_pLastSlot->Slot.RegisterNumber = ReadRegisterSlot(m_SlotReader, m_pLastSlot->Flags, + m_pLastSlot->Slot.RegisterNumber, false); } else { @@ -1412,9 +1381,9 @@ template const GcSlotDesc* GcSlotDecoderSlot.Stack.Base = ReadStackSlotBase(m_SlotReader); INT32 previousOffset = first ? 0 : GcInfoEncoding::NORMALIZE_STACK_SLOT(m_pLastSlot->Slot.Stack.SpOffset); - INT32 normSpOffset = ReadStackSlotOffset(m_SlotReader, m_pLastSlot->Flags, previousOffset, first); + INT32 normSpOffset = ReadStackSlot(m_SlotReader, m_pLastSlot->Flags, m_pLastSlot->Slot.Stack.Base, + previousOffset, first); m_pLastSlot->Slot.Stack.SpOffset = GcInfoEncoding::DENORMALIZE_STACK_SLOT(normSpOffset); } diff --git a/src/coreclr/vm/readytoruninfo.cpp b/src/coreclr/vm/readytoruninfo.cpp index 82222a49a176ac..72a5c578be2c94 100644 --- a/src/coreclr/vm/readytoruninfo.cpp +++ b/src/coreclr/vm/readytoruninfo.cpp @@ -2845,21 +2845,19 @@ PCODE DynamicHelpers::CreateDictionaryLookupHelper(LoaderAllocator * pAllocator, #endif // FEATURE_STUBPRECODE_DYNAMIC_HELPERS #ifdef TARGET_WASM -// Decode a ULEB128-encoded value that must fit in a UINT32. -// Advances *ppData past the encoded bytes. Asserts if the value overflows 32 bits. -UINT32 DecodeULEB128AsU32(PTR_BYTE* ppData) +UINT64 DecodeULEB128AsU64(PTR_BYTE* ppData) { - UINT32 result = 0; - int shift = 0; - BYTE b; - do + UINT64 result = 0; + for (int shift = 0; shift < 64; shift += 7) { - b = *(*ppData)++; - _ASSERTE(shift < 35); // A valid u32 ULEB128 is at most 5 bytes - result |= (UINT32)(b & 0x7F) << shift; - shift += 7; - } while (b & 0x80); - return result; + BYTE b = *(*ppData)++; + if (shift == 63 && b > 1) + COMPlusThrowHR(COR_E_BADIMAGEFORMAT); + result |= static_cast(b & 0x7F) << shift; + if ((b & 0x80) == 0) + return result; + } + COMPlusThrowHR(COR_E_BADIMAGEFORMAT); } static bool TryDecodeULEB128AsU32(PTR_BYTE* ppData, PTR_BYTE pEnd, UINT32* pValue) @@ -2971,11 +2969,10 @@ void ReadyToRunInfo::RegisterVirtualIPRange(Module* pModule) T_RUNTIME_FUNCTION* pLastEntry = &m_pRuntimeFunctions[m_nRuntimeFunctions - 1]; UINT32 lastEntryVirtualIPIndex = RUNTIME_FUNCTION__BeginAddress(pLastEntry); - // Decode the virtual IP count from the last entry's unwind data. - // Unwind format: ULEB128(frameSize) ULEB128(virtualIPCount) PTR_BYTE pUnwindData = dac_cast(imageBase + pLastEntry->UnwindData); - DecodeULEB128AsU32(&pUnwindData); // skip frame size - UINT32 lastEntryVIPCount = DecodeULEB128AsU32(&pUnwindData) * 2; // Multiply by 2 to force all virtual IPs to be an even number. + UINT32 frameSize; + UINT32 lastEntryVIPCount; + DecodeWasmUnwindInfo(DecodeULEB128AsU64(&pUnwindData), frameSize, lastEntryVIPCount); UINT32 totalVirtualIPs = lastEntryVirtualIPIndex + lastEntryVIPCount; diff --git a/src/coreclr/vm/wasm/helpers.cpp b/src/coreclr/vm/wasm/helpers.cpp index bcdf150d60a57b..f2eca03a298035 100644 --- a/src/coreclr/vm/wasm/helpers.cpp +++ b/src/coreclr/vm/wasm/helpers.cpp @@ -631,8 +631,9 @@ RtlpGetFunctionEndAddress ( ) { PTR_BYTE pUnwindData = dac_cast(FunctionEntry->UnwindData + ImageBase); - DecodeULEB128AsU32(&pUnwindData); // Skip the count of bytes to unwind - uint32_t logicalVirtualIPLength = DecodeULEB128AsU32(&pUnwindData) * 2; // Read the function length in virtual IP units, then multiply by 2 to report them as even numbers. + UINT32 frameSize; + UINT32 logicalVirtualIPLength; + DecodeWasmUnwindInfo(DecodeULEB128AsU64(&pUnwindData), frameSize, logicalVirtualIPLength); return logicalVirtualIPLength + RUNTIME_FUNCTION__BeginAddress(FunctionEntry); } @@ -1886,7 +1887,10 @@ static void WasmUnwindStackFrameCore(TADDR* pSP, TADDR* pIP, UINT_PTR ImageBase, else { PTR_BYTE pUnwindData = dac_cast(FunctionEntry->UnwindData + ImageBase); - *pSP = fp + DecodeULEB128AsU32(&pUnwindData) * 16; // Unwind the frame pointer to the callers stack pointer + UINT32 frameSize; + UINT32 virtualIPCount; + DecodeWasmUnwindInfo(DecodeULEB128AsU64(&pUnwindData), frameSize, virtualIPCount); + *pSP = fp + frameSize; // A reverse-pinvoke frame's caller is native, not an R2R shadow frame; leave the IP unset so the walk // continues via the Frame chain instead of reading the native caller SP as a shadow frame. *pIP = callerIsNative ? 0 : GetWasmVirtualIPFromStackPointer(*pSP); diff --git a/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/ExecutionManager/ExecutionManagerCore.ReadyToRunJitManager.cs b/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/ExecutionManager/ExecutionManagerCore.ReadyToRunJitManager.cs index f73dd851d5c382..c077bcb850f94b 100644 --- a/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/ExecutionManager/ExecutionManagerCore.ReadyToRunJitManager.cs +++ b/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/ExecutionManager/ExecutionManagerCore.ReadyToRunJitManager.cs @@ -199,6 +199,7 @@ private uint GetR2RGCInfoVersion(Data.ReadyToRunInfo r2rInfo) // see readytorun.h for the versioning details return header.MajorVersion switch { + >= 33 => 6, >= 21 => 5, >= 11 => 4, < 11 => 3, diff --git a/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/ExecutionManager/Helpers/UnwindDataSize.cs b/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/ExecutionManager/Helpers/UnwindDataSize.cs index 426f72377f7cd5..c9aa1b0d519e93 100644 --- a/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/ExecutionManager/Helpers/UnwindDataSize.cs +++ b/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/ExecutionManager/Helpers/UnwindDataSize.cs @@ -100,8 +100,7 @@ public static uint GetUnwindDataSize(Target target, TargetPointer unwindInfo, Ru } case RuntimeInfoArchitecture.Wasm: { - uint size = GetULEB128Size(target, unwindInfo); - size += GetULEB128Size(target, unwindInfo + size); + ReadWasmUnwindData(target, unwindInfo, out uint size); return size; } default: @@ -109,14 +108,22 @@ public static uint GetUnwindDataSize(Target target, TargetPointer unwindInfo, Ru } } - private static uint GetULEB128Size(Target target, TargetPointer address) + internal static ulong ReadWasmUnwindData(Target target, TargetPointer address, out uint size) { - const int MaxBytes = 5; + const int MaxBytes = 10; + ulong result = 0; for (uint offset = 0; offset < MaxBytes; offset++) { - if ((target.Read(address + offset) & 0x80) == 0) - return offset + 1; + byte value = target.Read(address + offset); + if (offset == MaxBytes - 1 && value > 1) + break; + result |= (ulong)(value & 0x7F) << (int)(offset * 7); + if ((value & 0x80) == 0) + { + size = offset + 1; + return result; + } } throw new InvalidOperationException("Malformed ULEB128 value in WASM unwind data."); diff --git a/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/GCInfoDecoder.cs b/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/GCInfoDecoder.cs index b5ac9c24c5fa9b..d7f6bb03b532de 100644 --- a/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/GCInfoDecoder.cs +++ b/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/GCInfoDecoder.cs @@ -103,6 +103,8 @@ public static GcSlotDesc CreateStackSlot(int spOffset, GcStackSlotBase slotBase, private readonly NativeReader _reader; private readonly RuntimeInfoArchitecture _arch; private readonly bool PartiallyInterruptibleGCSupported = true; + private bool UsesCompactWasmHeader => TTraits.USES_COMPACT_WASM_HEADER && _gcVersion >= 6; + private bool UsesLegacyWasmEncoding => TTraits.USES_COMPACT_WASM_HEADER && _gcVersion < 6; /* Decode State */ private int _bitOffset; @@ -189,9 +191,30 @@ private IEnumerable DecodeBody() yield return DecodePoints.SlotTable; } + private uint ReadRegisterValue(int encodingBase) + { + uint chunk = (uint)_reader.ReadBits(encodingBase + 1, ref _bitOffset); + uint value = chunk & ((1u << encodingBase) - 1); + if ((chunk & (1u << encodingBase)) != 0) + { + if (TTraits.REGISTER_BITS <= encodingBase) + throw new InvalidOperationException("GC register encoding exceeds the target register width."); + value |= (uint)_reader.ReadBits(TTraits.REGISTER_BITS - encodingBase, ref _bitOffset) << encodingBase; + } + + return value; + } + + private GcSlotFlags ReadSlotFlags(GcSlotFlags previousFlags, bool first) + { + return first || previousFlags != 0 + ? (GcSlotFlags)_reader.ReadBits(first || (previousFlags & GcSlotFlags.GC_SLOT_PINNED) != 0 ? 2 : 1, ref _bitOffset) + : 0; + } + private IEnumerable DecodeSlotTable() { - if (_reader.ReadBits(1, ref _bitOffset) != 0) + if (TTraits.HAS_REGISTER_SLOTS && _reader.ReadBits(1, ref _bitOffset) != 0) { _numRegisters = _reader.DecodeVarLengthUnsigned(TTraits.NUM_REGISTERS_ENCBASE, ref _bitOffset); } @@ -200,7 +223,8 @@ private IEnumerable DecodeSlotTable() if (_reader.ReadBits(1, ref _bitOffset) != 0) { numStackSlots = _reader.DecodeVarLengthUnsigned(TTraits.NUM_STACK_SLOTS_ENCBASE, ref _bitOffset); - _numUntrackedSlots = _reader.DecodeVarLengthUnsigned(TTraits.NUM_UNTRACKED_SLOTS_ENCBASE, ref _bitOffset); + _numUntrackedSlots = _reader.DecodeVarLengthUnsigned( + UsesLegacyWasmEncoding ? 5 : TTraits.NUM_UNTRACKED_SLOTS_ENCBASE, ref _bitOffset); } _numSlots = _numRegisters + numStackSlots + _numUntrackedSlots; @@ -209,27 +233,36 @@ private IEnumerable DecodeSlotTable() // Decode register slots if (_numRegisters > 0) { - uint regNum = _reader.DecodeVarLengthUnsigned(TTraits.REGISTER_ENCBASE, ref _bitOffset); - GcSlotFlags flags = (GcSlotFlags)_reader.ReadBits(2, ref _bitOffset); - - _slots.Add(GcSlotDesc.CreateRegisterSlot(regNum, flags)); - - for (int i = 1; i < _numRegisters; i++) + uint regNum = 0; + GcSlotFlags flags = 0; + for (int i = 0; i < _numRegisters; i++) { - if (flags != 0) - { - regNum = _reader.DecodeVarLengthUnsigned(TTraits.REGISTER_ENCBASE, ref _bitOffset); - flags = (GcSlotFlags)_reader.ReadBits(2, ref _bitOffset); - } - else + bool absolute = i == 0 || flags != 0; + if (_gcVersion >= 6) { - regNum += _reader.DecodeVarLengthUnsigned(TTraits.REGISTER_DELTA_ENCBASE, ref _bitOffset) + 1; + GcSlotFlags previousFlags = flags; + flags = ReadSlotFlags(previousFlags, i == 0); + absolute = i == 0 || flags != previousFlags; } + int encodingBase = absolute ? TTraits.REGISTER_ENCBASE : TTraits.REGISTER_DELTA_ENCBASE; + uint value = _gcVersion >= 6 + ? ReadRegisterValue(encodingBase) + : _reader.DecodeVarLengthUnsigned(encodingBase, ref _bitOffset); + regNum = absolute ? value : regNum + value + 1; + if (_gcVersion < 6 && absolute) + flags = (GcSlotFlags)_reader.ReadBits(2, ref _bitOffset); _slots.Add(GcSlotDesc.CreateRegisterSlot(regNum, flags)); } } + if (_gcVersion >= 6) + { + DecodeStackSlots(numStackSlots, isUntracked: false); + DecodeStackSlots(_numUntrackedSlots, isUntracked: true); + yield break; + } + // Decode stack slots if (numStackSlots > 0) { @@ -297,6 +330,26 @@ private IEnumerable DecodeSlotTable() yield break; } + private void DecodeStackSlots(uint count, bool isUntracked) + { + GcSlotFlags flags = 0; + GcStackSlotBase previousBase = GcStackSlotBase.GC_SP_REL; + int offset = 0; + for (uint i = 0; i < count; i++) + { + GcSlotFlags previousFlags = flags; + flags = ReadSlotFlags(previousFlags, i == 0); + GcStackSlotBase slotBase = TTraits.HAS_STACK_SLOT_BASE && _reader.ReadBits(1, ref _bitOffset) == 0 + ? GcStackSlotBase.GC_SP_REL : GcStackSlotBase.GC_FRAMEREG_REL; + offset = i == 0 || flags != previousFlags || slotBase != previousBase + ? _reader.DecodeVarLengthSigned(TTraits.STACK_SLOT_ENCBASE, ref _bitOffset) + : offset + (int)_reader.DecodeVarLengthUnsigned(TTraits.STACK_SLOT_DELTA_ENCBASE, ref _bitOffset); + GcSlotFlags slotFlags = isUntracked ? flags | GcSlotFlags.GC_SLOT_UNTRACKED : flags; + _slots.Add(GcSlotDesc.CreateStackSlot(TTraits.DenormalizeStackSlot(offset), slotBase, slotFlags)); + previousBase = slotBase; + } + } + private IEnumerable DecodeInterruptibleRanges() { if (_numInterruptibleRanges == 0) @@ -360,7 +413,7 @@ private IEnumerable DecodeHeader() private IEnumerable DecodeSlimHeader() { - if (_reader.ReadBits(1, ref _bitOffset) != 0) + if (UsesCompactWasmHeader || _reader.ReadBits(1, ref _bitOffset) != 0) { _headerFlags = GcInfoHeaderFlags.GC_INFO_HAS_STACK_BASE_REGISTER; _stackBaseRegister = TTraits.DenormalizeStackBaseRegister(0); @@ -373,7 +426,8 @@ private IEnumerable DecodeSlimHeader() yield return DecodePoints.ReturnKind; yield return DecodePoints.VarArg; - _codeLength = TTraits.DenormalizeCodeLength(_reader.DecodeVarLengthUnsigned(TTraits.CODE_LENGTH_ENCBASE, ref _bitOffset)); + _codeLength = TTraits.DenormalizeCodeLength(_reader.DecodeVarLengthUnsigned( + UsesLegacyWasmEncoding ? 6 : TTraits.CODE_LENGTH_ENCBASE, ref _bitOffset)); // predecoding the rest of slim header does not require any reading. _validRangeStart = 0; @@ -396,9 +450,10 @@ private IEnumerable DecodeSlimHeader() yield return DecodePoints.EditAndContinue; yield return DecodePoints.ReversePInvoke; - if (PartiallyInterruptibleGCSupported) + if (PartiallyInterruptibleGCSupported && !UsesCompactWasmHeader) { - _numSafePoints = _reader.DecodeVarLengthUnsigned(TTraits.NUM_SAFE_POINTS_ENCBASE, ref _bitOffset); + _numSafePoints = _reader.DecodeVarLengthUnsigned( + UsesLegacyWasmEncoding ? 4 : TTraits.NUM_SAFE_POINTS_ENCBASE, ref _bitOffset); } _numInterruptibleRanges = 0; @@ -406,11 +461,21 @@ private IEnumerable DecodeSlimHeader() private IEnumerable DecodeFatHeader() { - _headerFlags = (GcInfoHeaderFlags)_reader.ReadBits((int)GcInfoHeaderFlags.GC_INFO_FLAGS_BIT_SIZE, ref _bitOffset); + if (UsesCompactWasmHeader) + { + uint flags = (uint)_reader.ReadBits((int)GcInfoHeaderFlags.GC_INFO_FLAGS_BIT_SIZE - 1, ref _bitOffset); + _headerFlags = (GcInfoHeaderFlags)((flags & 0x3F) | ((flags & 0x1C0) << 1)) | + GcInfoHeaderFlags.GC_INFO_HAS_STACK_BASE_REGISTER; + } + else + { + _headerFlags = (GcInfoHeaderFlags)_reader.ReadBits((int)GcInfoHeaderFlags.GC_INFO_FLAGS_BIT_SIZE, ref _bitOffset); + } yield return DecodePoints.ReturnKind; yield return DecodePoints.VarArg; - _codeLength = TTraits.DenormalizeCodeLength(_reader.DecodeVarLengthUnsigned(TTraits.CODE_LENGTH_ENCBASE, ref _bitOffset)); + _codeLength = TTraits.DenormalizeCodeLength(_reader.DecodeVarLengthUnsigned( + UsesLegacyWasmEncoding ? 6 : TTraits.CODE_LENGTH_ENCBASE, ref _bitOffset)); yield return DecodePoints.CodeLength; if (_headerFlags.HasFlag(GcInfoHeaderFlags.GC_INFO_HAS_GS_COOKIE)) @@ -420,7 +485,8 @@ private IEnumerable DecodeFatHeader() uint normCodeLength = TTraits.NormalizeCodeLength(_codeLength); // Decode prolog/epilog information - uint normPrologSize = _reader.DecodeVarLengthUnsigned(TTraits.NORM_PROLOG_SIZE_ENCBASE, ref _bitOffset) + 1; + uint normPrologSize = UsesCompactWasmHeader ? 1 : + _reader.DecodeVarLengthUnsigned(TTraits.NORM_PROLOG_SIZE_ENCBASE, ref _bitOffset) + 1; uint normEpilogSize = _reader.DecodeVarLengthUnsigned(TTraits.NORM_EPILOG_SIZE_ENCBASE, ref _bitOffset); _validRangeStart = TTraits.DenormalizeCodeOffset(normPrologSize); @@ -430,7 +496,8 @@ private IEnumerable DecodeFatHeader() else if ((_headerFlags & GcInfoHeaderFlags.GC_INFO_HAS_GENERICS_INST_CONTEXT_MASK) != GcInfoHeaderFlags.GC_INFO_HAS_GENERICS_INST_CONTEXT_NONE) { // Decode prolog information - uint normPrologSize = _reader.DecodeVarLengthUnsigned(TTraits.NORM_PROLOG_SIZE_ENCBASE, ref _bitOffset) + 1; + uint normPrologSize = UsesCompactWasmHeader ? 1 : + _reader.DecodeVarLengthUnsigned(TTraits.NORM_PROLOG_SIZE_ENCBASE, ref _bitOffset) + 1; _validRangeStart = TTraits.DenormalizeCodeOffset(normPrologSize); // satisfy asserts that assume m_GSCookieValidRangeStart != 0 ==> m_GSCookieValidRangeStart < m_GSCookieValidRangeEnd _validRangeEnd = _validRangeStart + 1; @@ -456,7 +523,8 @@ private IEnumerable DecodeFatHeader() yield return DecodePoints.GenericInstContext; _stackBaseRegister = _headerFlags.HasFlag(GcInfoHeaderFlags.GC_INFO_HAS_STACK_BASE_REGISTER) ? - TTraits.DenormalizeStackBaseRegister(_reader.DecodeVarLengthUnsigned(TTraits.STACK_BASE_REGISTER_ENCBASE, ref _bitOffset)) : + TTraits.DenormalizeStackBaseRegister(UsesCompactWasmHeader ? 0 : + _reader.DecodeVarLengthUnsigned(TTraits.STACK_BASE_REGISTER_ENCBASE, ref _bitOffset)) : TTraits.NO_STACK_BASE_REGISTER; if (_headerFlags.HasFlag(GcInfoHeaderFlags.GC_INFO_HAS_EDIT_AND_CONTINUE_INFO)) @@ -478,7 +546,8 @@ private IEnumerable DecodeFatHeader() yield return DecodePoints.EditAndContinue; _reversePInvokeFrameStackSlot = _headerFlags.HasFlag(GcInfoHeaderFlags.GC_INFO_REVERSE_PINVOKE_FRAME) ? - TTraits.DenormalizeStackSlot(_reader.DecodeVarLengthSigned(TTraits.REVERSE_PINVOKE_FRAME_ENCBASE, ref _bitOffset)) : + TTraits.DenormalizeStackSlot(_reader.DecodeVarLengthSigned( + UsesLegacyWasmEncoding ? 6 : TTraits.REVERSE_PINVOKE_FRAME_ENCBASE, ref _bitOffset)) : TTraits.NO_REVERSE_PINVOKE_FRAME; yield return DecodePoints.ReversePInvoke; @@ -490,7 +559,8 @@ private IEnumerable DecodeFatHeader() if (PartiallyInterruptibleGCSupported) { - _numSafePoints = _reader.DecodeVarLengthUnsigned(TTraits.NUM_SAFE_POINTS_ENCBASE, ref _bitOffset); + _numSafePoints = _reader.DecodeVarLengthUnsigned( + UsesLegacyWasmEncoding ? 4 : TTraits.NUM_SAFE_POINTS_ENCBASE, ref _bitOffset); } _numInterruptibleRanges = TTraits.HAS_INTERRUPTIBLE_RANGES diff --git a/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/PlatformTraits/ARMGCInfoTraits.cs b/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/PlatformTraits/ARMGCInfoTraits.cs index 16888a3c4cf6d7..101bb3595fd09e 100644 --- a/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/PlatformTraits/ARMGCInfoTraits.cs +++ b/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/PlatformTraits/ARMGCInfoTraits.cs @@ -36,6 +36,7 @@ internal class ARMGCInfoTraits : IGCInfoTraits public static int INTERRUPTIBLE_RANGE_DELTA2_ENCBASE => 6; public static int REGISTER_ENCBASE => 2; public static int REGISTER_DELTA_ENCBASE => 1; + public static int REGISTER_BITS => 4; public static int STACK_SLOT_ENCBASE => 6; public static int STACK_SLOT_DELTA_ENCBASE => 4; public static int NUM_SAFE_POINTS_ENCBASE => 3; diff --git a/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/PlatformTraits/IGCInfoTraits.cs b/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/PlatformTraits/IGCInfoTraits.cs index 4c6b0f75a8544a..b0546c4181ada5 100644 --- a/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/PlatformTraits/IGCInfoTraits.cs +++ b/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/PlatformTraits/IGCInfoTraits.cs @@ -8,6 +8,9 @@ namespace Microsoft.Diagnostics.DataContractReader.Contracts.GCInfoHelpers; internal interface IGCInfoTraits { static virtual bool IsInterpreter => false; + static virtual bool USES_COMPACT_WASM_HEADER => false; + static virtual bool HAS_REGISTER_SLOTS => true; + static virtual bool HAS_STACK_SLOT_BASE => true; static virtual bool UsesStackPointerAsAmbientSP => false; static virtual int NO_GS_COOKIE { get; } = -1; static virtual uint NO_STACK_BASE_REGISTER { get; } = 0xFFFFFFFF; @@ -43,6 +46,7 @@ internal interface IGCInfoTraits static abstract int INTERRUPTIBLE_RANGE_DELTA2_ENCBASE { get; } static abstract int REGISTER_ENCBASE { get; } static abstract int REGISTER_DELTA_ENCBASE { get; } + static virtual int REGISTER_BITS => 5; static abstract int STACK_SLOT_ENCBASE { get; } static abstract int STACK_SLOT_DELTA_ENCBASE { get; } static abstract int NUM_SAFE_POINTS_ENCBASE { get; } diff --git a/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/PlatformTraits/InterpreterGCInfoTraits.cs b/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/PlatformTraits/InterpreterGCInfoTraits.cs index 7e36658d6becaa..9e6f7b154f193e 100644 --- a/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/PlatformTraits/InterpreterGCInfoTraits.cs +++ b/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/PlatformTraits/InterpreterGCInfoTraits.cs @@ -8,6 +8,7 @@ namespace Microsoft.Diagnostics.DataContractReader.Contracts.GCInfoHelpers; internal class InterpreterGCInfoTraits : IGCInfoTraits { public static bool IsInterpreter => true; + public static bool HAS_REGISTER_SLOTS => false; public static uint DenormalizeStackBaseRegister(uint reg) => reg; public static uint DenormalizeCodeLength(uint len) => len; public static uint NormalizeCodeLength(uint len) => len; diff --git a/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/PlatformTraits/WasmGCInfoTraits.cs b/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/PlatformTraits/WasmGCInfoTraits.cs index 6097373872693b..758fb494dc140b 100644 --- a/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/PlatformTraits/WasmGCInfoTraits.cs +++ b/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/PlatformTraits/WasmGCInfoTraits.cs @@ -8,37 +8,40 @@ namespace Microsoft.Diagnostics.DataContractReader.Contracts.GCInfoHelpers; // Mirrors Wasm32GcInfoEncoding in src/coreclr/inc/gcinfotypes.h. internal sealed class WasmGCInfoTraits : IGCInfoTraits { - public static uint DenormalizeStackBaseRegister(uint reg) => reg; + public static bool USES_COMPACT_WASM_HEADER => true; + public static uint DenormalizeStackBaseRegister(uint reg) => reg ^ 2; public static uint DenormalizeCodeLength(uint len) => len; public static uint NormalizeCodeLength(uint len) => len; public static uint DenormalizeCodeOffset(uint offset) => offset; public static uint NormalizeCodeOffset(uint offset) => offset; - public static int DenormalizeStackSlot(int value) => value; + public static int DenormalizeStackSlot(int value) => value * 4; public static uint DenormalizeSizeOfStackArea(uint size) => size; public static int GENERICS_INST_CONTEXT_STACK_SLOT_ENCBASE => 6; public static int GS_COOKIE_STACK_SLOT_ENCBASE => 6; - public static int CODE_LENGTH_ENCBASE => 6; + public static int CODE_LENGTH_ENCBASE => 5; public static int STACK_BASE_REGISTER_ENCBASE => 3; public static int SIZE_OF_STACK_AREA_ENCBASE => 6; public static int SIZE_OF_EDIT_AND_CONTINUE_PRESERVED_AREA_ENCBASE => 3; public static int SIZE_OF_EDIT_AND_CONTINUE_FIXED_STACK_FRAME_ENCBASE => 0; - public static int REVERSE_PINVOKE_FRAME_ENCBASE => 6; + public static int REVERSE_PINVOKE_FRAME_ENCBASE => 4; public static int NUM_REGISTERS_ENCBASE => 3; public static int NUM_STACK_SLOTS_ENCBASE => 5; - public static int NUM_UNTRACKED_SLOTS_ENCBASE => 5; + public static int NUM_UNTRACKED_SLOTS_ENCBASE => 7; public static int NORM_PROLOG_SIZE_ENCBASE => 4; public static int NORM_EPILOG_SIZE_ENCBASE => 3; public static int INTERRUPTIBLE_RANGE_DELTA1_ENCBASE => 5; public static int INTERRUPTIBLE_RANGE_DELTA2_ENCBASE => 5; public static int REGISTER_ENCBASE => 3; public static int REGISTER_DELTA_ENCBASE => 3; - public static int STACK_SLOT_ENCBASE => 6; - public static int STACK_SLOT_DELTA_ENCBASE => 4; - public static int NUM_SAFE_POINTS_ENCBASE => 4; + public static int STACK_SLOT_ENCBASE => 3; + public static int STACK_SLOT_DELTA_ENCBASE => 3; + public static int NUM_SAFE_POINTS_ENCBASE => 3; public static int NUM_INTERRUPTIBLE_RANGES_ENCBASE => 1; public static bool HAS_FIXED_STACK_PARAMETER_SCRATCH_AREA => false; public static bool HAS_INTERRUPTIBLE_RANGES => false; + public static bool HAS_REGISTER_SLOTS => false; + public static bool HAS_STACK_SLOT_BASE => false; // Valid Wasm GC info has no register slots; RyuJIT never emits one. Mirror the // native fallback (gcinfodecoder.cpp PORTABILITY_ASSERT): flag the unexpected diff --git a/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/X86/GCInfo.cs b/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/X86/GCInfo.cs index cba61f303eab15..71b0847e2a2433 100644 --- a/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/X86/GCInfo.cs +++ b/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/X86/GCInfo.cs @@ -30,7 +30,7 @@ public enum RegMask public record X86GCInfo : IGCInfoDecoder { private const uint MINIMUM_SUPPORTED_GCINFO_VERSION = 4; - private const uint MAXIMUM_SUPPORTED_GCINFO_VERSION = 5; + private const uint MAXIMUM_SUPPORTED_GCINFO_VERSION = 6; private readonly Target _target; diff --git a/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/StackWalk/Context/Wasm/WasmUnwinder.cs b/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/StackWalk/Context/Wasm/WasmUnwinder.cs index 45333f1639046d..1c2518d8db31a6 100644 --- a/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/StackWalk/Context/Wasm/WasmUnwinder.cs +++ b/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/StackWalk/Context/Wasm/WasmUnwinder.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; +using Microsoft.Diagnostics.DataContractReader.ExecutionManagerHelpers; namespace Microsoft.Diagnostics.DataContractReader.Contracts.StackWalkHelpers.Wasm; @@ -21,7 +22,7 @@ internal interface IWasmR2RInfo /// /// Returns the address of the WASM unwind blob for the function containing - /// . The blob begins with a ULEB128 fixed frame size. + /// . The blob contains a ULEB128 interleaving the frame size and virtual IP count. /// bool TryGetUnwindData(TargetCodePointer controlPC, out TargetPointer unwindDataAddress); } @@ -177,7 +178,9 @@ public bool TryUnwindOneFrame(ref TargetPointer sp, TargetCodePointer controlPC, } uint frameIdentity = _target.Read(frameBase.Value + FrameIdentityOffset); - uint frameSize = DecodeULEB128(unwindData.Value); + ulong encoded = UnwindDataSize.ReadWasmUnwindData(_target, unwindData, out _); + uint frameSize = (uint)((encoded & 0xF) | (((encoded >> 8) & 0xF) << 4) | + (((encoded >> 16) & 0xFFFF) << 8)) * 16; if (frameSize == 0) { // A zero frame size makes no progress; terminate rather than risk an unbounded walk. @@ -218,22 +221,4 @@ public bool TryGetLogicalFramePointer(TargetPointer sp, out TargetPointer frameP && TryGetEstablishingFramePointer(frameBase, out framePointer); } - // Standard little-endian base-128 varint, matching the native DecodeULEB128AsU32. A ULEB128 - // uint32 is at most 5 bytes (5 * 7 = 35 >= 32 bits); a longer encoding is malformed. - private uint DecodeULEB128(ulong address) - { - const int MaxBytes = 5; - uint result = 0; - int shift = 0; - for (ulong offset = 0; offset < MaxBytes; offset++) - { - byte b = _target.Read(address + offset); - result |= (uint)(b & 0x7F) << shift; - if ((b & 0x80) == 0) - return result; - shift += 7; - } - - throw new InvalidOperationException("Malformed ULEB128 value in WASM unwind data."); - } } diff --git a/src/native/managed/cdac/tests/UnitTests/ExecutionManager/ExecutionManagerTests.cs b/src/native/managed/cdac/tests/UnitTests/ExecutionManager/ExecutionManagerTests.cs index 09559c004dd659..8870013e3fce69 100644 --- a/src/native/managed/cdac/tests/UnitTests/ExecutionManager/ExecutionManagerTests.cs +++ b/src/native/managed/cdac/tests/UnitTests/ExecutionManager/ExecutionManagerTests.cs @@ -534,8 +534,11 @@ public void ReadyToRunInfo_WasmMissingOptionalFields_EnsureAllFieldsRead() Assert.Null(data.DelayLoadMethodCallThunks); } - [Fact] - public void GetGCInfo_R2R_WasmVirtualIPUsesLoadedImageBase() + [Theory] + [InlineData(21, 5u)] + [InlineData(32, 5u)] + [InlineData(33, 6u)] + public void GetGCInfo_R2R_WasmVirtualIPUsesLoadedImageBase(ushort majorVersion, uint expectedGcVersion) { MockTarget.Architecture wasmArch = new() { IsLittleEndian = true, Is64Bit = false }; @@ -557,13 +560,13 @@ public void GetGCInfo_R2R_WasmVirtualIPUsesLoadedImageBase() MockReadyToRunInfo r2rInfo = emBuilder.AddReadyToRunInfo([FunctionBeginAddress], []); r2rInfo.MinVirtualIP = VirtualIPRangeStart; r2rInfo.LoadedImageBase = LoadedImageBase; - r2rInfo.ReadyToRunHeader = emBuilder.AddReadyToRunHeader(majorVersion: 21).Address; + r2rInfo.ReadyToRunHeader = emBuilder.AddReadyToRunHeader(majorVersion: majorVersion).Address; emBuilder.SetRuntimeFunctionUnwindData(r2rInfo, index: 0, UnwindDataRva); emBuilder.Builder.AddHeapFragment(new MockMemorySpace.HeapFragment { Address = LoadedImageBase + UnwindDataRva, // Frame size 128, function length 32, followed by the GC info. - Data = [0x80, 0x01, 0x20, ExpectedGCInfoByte], + Data = [0x88, 0x20, ExpectedGCInfoByte], Name = "WASM unwind and GC info", }); @@ -576,7 +579,7 @@ public void GetGCInfo_R2R_WasmVirtualIPUsesLoadedImageBase() IGCInfoHandle gcInfoHandle = Mock.Of(); Mock gcInfoContract = new(MockBehavior.Strict); - gcInfoContract.Setup(c => c.DecodePlatformSpecificGCInfo(new TargetPointer(LoadedImageBase + UnwindDataRva + 3), 5)) + gcInfoContract.Setup(c => c.DecodePlatformSpecificGCInfo(new TargetPointer(LoadedImageBase + UnwindDataRva + 2), expectedGcVersion)) .Returns(gcInfoHandle); gcInfoContract.Setup(c => c.GetCodeLength(gcInfoHandle)).Returns(32u); Target target = CreateTarget( @@ -590,8 +593,8 @@ public void GetGCInfo_R2R_WasmVirtualIPUsesLoadedImageBase() Assert.NotNull(handle); em.GetGCInfo(handle.Value, out TargetPointer gcInfo, out uint gcVersion); - Assert.Equal(new TargetPointer(LoadedImageBase + UnwindDataRva + 3), gcInfo); - Assert.Equal(5u, gcVersion); + Assert.Equal(new TargetPointer(LoadedImageBase + UnwindDataRva + 2), gcInfo); + Assert.Equal(expectedGcVersion, gcVersion); Assert.Equal(ExpectedGCInfoByte, target.Read(gcInfo)); em.GetMethodRegionInfo(handle.Value, out uint hotSize, out TargetPointer coldStart, out uint coldSize); Assert.Equal(32u, hotSize); diff --git a/src/native/managed/cdac/tests/UnitTests/GCInfoTests.cs b/src/native/managed/cdac/tests/UnitTests/GCInfoTests.cs new file mode 100644 index 00000000000000..8266f464ba7cd5 --- /dev/null +++ b/src/native/managed/cdac/tests/UnitTests/GCInfoTests.cs @@ -0,0 +1,198 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.Collections.Generic; +using Microsoft.Diagnostics.DataContractReader.Contracts; +using Microsoft.Diagnostics.DataContractReader.Contracts.GCInfoHelpers; +using Microsoft.Diagnostics.DataContractReader.TestInfrastructure; +using Moq; +using Xunit; + +namespace Microsoft.Diagnostics.DataContractReader.Tests; + +public class GCInfoTests +{ + [Theory] + [InlineData(RuntimeInfoArchitecture.X64, false, new byte[] { 0x0A, 0x80, 0x50, 0x1B, 0xE2, 0x38, 0x21, 0x8C, 0x0B, 0x62, 0x1C, 0x88, 0x38 })] + [InlineData(RuntimeInfoArchitecture.Arm, false, new byte[] { 0x0A, 0x80, 0x80, 0x31, 0xC4, 0x71, 0x42, 0x18, 0x17, 0xC4, 0x38, 0x10, 0x71 })] + [InlineData(RuntimeInfoArchitecture.Arm64, false, new byte[] { 0x0A, 0x00, 0xA1, 0x36, 0xC4, 0x71, 0x42, 0x18, 0x17, 0xC4, 0x38, 0x10, 0x71 })] + [InlineData(RuntimeInfoArchitecture.LoongArch64, false, new byte[] { 0x0A, 0x00, 0xA1, 0x36, 0xC4, 0x71, 0x42, 0x18, 0x17, 0xC4, 0x38, 0x10, 0x71 })] + [InlineData(RuntimeInfoArchitecture.RiscV64, false, new byte[] { 0x0A, 0x00, 0xA1, 0x36, 0xC4, 0x71, 0x42, 0x18, 0x17, 0xC4, 0x38, 0x10, 0x71 })] + [InlineData(RuntimeInfoArchitecture.Wasm, false, new byte[] { 0x84, 0x00, 0xC2, 0x78, 0x87, 0x78, 0x46, 0x78, 0x03, 0x5E, 0x00 })] + [InlineData(RuntimeInfoArchitecture.X64, true, new byte[] { 0x0A, 0x40, 0xA8, 0x0D, 0x71, 0x9C, 0x10, 0xC6, 0x05, 0x31, 0x0E, 0x44, 0x1C })] + public void StackSlotsUseFlagsThenBaseThenOffset(RuntimeInfoArchitecture architecture, bool interpreter, byte[] encoded) + { + IGCInfoDecoder decoder = CreateDecoder(architecture, interpreter, encoded, 6); + IReadOnlyList slots = decoder.GetSlotLifetimes(); + Assert.Equal(8, slots.Count); + int slotSize = interpreter ? 1 : architecture is RuntimeInfoArchitecture.Arm or RuntimeInfoArchitecture.Wasm ? 4 : 8; + for (int i = 0; i < slots.Count; i++) + { + Assert.False(slots[i].IsRegister); + int offset = architecture == RuntimeInfoArchitecture.Wasm ? -8 + i % 2 : i % 2 == 0 ? 8 : -8; + Assert.Equal(offset * slotSize, slots[i].SpOffset); + Assert.Equal(architecture == RuntimeInfoArchitecture.Wasm ? 2u : (uint)(1 + i % 2), slots[i].BaseRegister); + Assert.Equal((uint)(3 - i / 2) | 4u, slots[i].GcFlags); + Assert.Equal(0u, slots[i].BeginOffset); + Assert.Equal(decoder.GetCodeLength(), slots[i].EndOffset); + } + } + + [Theory] + [InlineData(RuntimeInfoArchitecture.X64, 5)] + [InlineData(RuntimeInfoArchitecture.X64, 6)] + [InlineData(RuntimeInfoArchitecture.Arm, 5)] + [InlineData(RuntimeInfoArchitecture.Arm, 6)] + [InlineData(RuntimeInfoArchitecture.Arm64, 5)] + [InlineData(RuntimeInfoArchitecture.Arm64, 6)] + [InlineData(RuntimeInfoArchitecture.LoongArch64, 5)] + [InlineData(RuntimeInfoArchitecture.LoongArch64, 6)] + [InlineData(RuntimeInfoArchitecture.RiscV64, 5)] + [InlineData(RuntimeInfoArchitecture.RiscV64, 6)] + public void RegisterSlotsUseFlagsFirstAndBoundedIntegers(RuntimeInfoArchitecture architecture, int version) + { + bool arm = architecture == RuntimeInfoArchitecture.Arm; + bool x64 = architecture == RuntimeInfoArchitecture.X64; + int registerBits = arm ? 4 : 5; + int absoluteBase = arm ? 2 : 3; + int deltaBase = arm ? 1 : 2; + List<(int Register, int Flags)> registers = []; + for (int flags = 3; flags >= 0; flags--) + { + foreach (int register in new[] { 0, 1, 3, 4, 7, 8, 15, 16, 23, 24, 30, 31 }) + { + if (register >= (1 << registerBits) || flags == 3 && register < 8) + continue; + registers.Add((register, flags)); + } + } + List bytes = []; + int bitCount = 0; + Write(0, 1); + Write(1, 1); + WriteUnsigned(2, arm ? 7 : 8); + WriteUnsigned(1, x64 ? 2 : 3); + Write(0, 1); // Safe point at normalized offset zero. + Write(1, 1); + WriteUnsigned(registers.Count, x64 || arm ? 2 : 3); + Write(0, 1); + for (int i = 0; i < registers.Count; i++) + { + (int register, int flags) = registers[i]; + bool emitFlags = i == 0 || registers[i - 1].Flags != 0; + bool absolute = version < 6 ? emitFlags : i == 0 || flags != registers[i - 1].Flags; + int value = absolute ? register : register - registers[i - 1].Register - 1; + int encodingBase = absolute ? absoluteBase : deltaBase; + if (version >= 6) + { + if (emitFlags) + Write(flags, i == 0 || (registers[i - 1].Flags & 2) != 0 ? 2 : 1); + bool extended = value >= (1 << encodingBase); + Write((value & ((1 << encodingBase) - 1)) | (extended ? 1 << encodingBase : 0), encodingBase + 1); + if (extended) + Write(value >> encodingBase, registerBits - encodingBase); + } + else + { + WriteUnsigned(value, encodingBase); + if (emitFlags) + Write(flags, 2); + } + } + Write(0, 1); // Direct live-state bitmap. + foreach ((int register, int flags) in registers) + Write(1, 1); + + IGCInfoDecoder decoder = CreateDecoder(architecture, false, bytes.ToArray(), (uint)version); + IReadOnlyList slots = decoder.GetSlotLifetimes(); + Assert.Equal(registers.Count, slots.Count); + for (int i = 0; i < registers.Count; i++) + { + Assert.True(slots[i].IsRegister); + Assert.Equal((uint)registers[i].Register, slots[i].RegisterNumber); + Assert.Equal((uint)registers[i].Flags, slots[i].GcFlags); + Assert.Equal(0u, slots[i].BeginOffset); + Assert.Equal(1u, slots[i].EndOffset); + } + + void Write(int value, int count) + { + for (int i = 0; i < count; i++, bitCount++) + { + if (bitCount % 8 == 0) + bytes.Add(0); + bytes[bitCount / 8] |= (byte)(((value >> i) & 1) << (bitCount % 8)); + } + } + + void WriteUnsigned(int value, int encodingBase) + { + do + { + int chunk = value & ((1 << encodingBase) - 1); + value >>>= encodingBase; + Write(chunk | (value == 0 ? 0 : 1 << encodingBase), encodingBase + 1); + } while (value != 0); + } + } + + [Theory] + [InlineData(5u, new byte[] { 0x0A, 0x00 }, 0, 0u, 0u)] + [InlineData(5u, new byte[] { 0xA1, 0x10, 0x00, 0x01, 0x00 }, 8, 1u, 0u)] + [InlineData(5u, new byte[] { 0xC1, 0x10, 0x00, 0x01, 0x00 }, 8, 1u, 0u)] + [InlineData(6u, new byte[] { 0x04 }, 0, 0u, 0u)] + [InlineData(6u, new byte[] { 0x21, 0x08, 0x02, 0x00 }, 8, 1u, 0u)] + [InlineData(6u, new byte[] { 0x41, 0x08, 0x02, 0x00 }, 8, 1u, 0u)] + [InlineData(6u, new byte[] { 0x01, 0x08, 0x01 }, 0, 0u, 1u)] + public void WasmHeadersDecodePrologAndFrameRegister(uint version, byte[] encoded, int genericContextOffset, + uint prologSize, uint safePoints) + { + IGCInfoDecoder decoder = CreateDecoder(RuntimeInfoArchitecture.Wasm, false, encoded, version); + GCInfoHeader header = decoder.GetHeader(); + + Assert.Equal(2u, header.CodeSize); + Assert.Equal(2u, header.StackBaseRegister); + Assert.Equal(prologSize, header.PrologSize); + Assert.Equal(genericContextOffset == 0 ? null : new SpecialSlot(genericContextOffset), header.GenericsInstContext); + Assert.Equal((int)safePoints, decoder.GetSafePoints().Count); + if (safePoints != 0) + Assert.Equal(0u, Assert.Single(decoder.GetSafePoints())); + Assert.Empty(decoder.GetSlotLifetimes()); + } + + private static IGCInfoDecoder CreateDecoder(RuntimeInfoArchitecture architecture, bool interpreter, byte[] encoded, uint version) + { + MockTarget.Architecture arch = new() + { + IsLittleEndian = true, + Is64Bit = architecture is not (RuntimeInfoArchitecture.Arm or RuntimeInfoArchitecture.Wasm), + }; + TestPlaceholderTarget.Builder builder = new(arch); + const ulong GcInfoAddress = 0x10000; + byte[] data = new byte[encoded.Length + 8]; + encoded.CopyTo(data, 0); + builder.MemoryBuilder.AddHeapFragment(new MockMemorySpace.HeapFragment + { + Address = GcInfoAddress, + Data = data, + Name = "GC slot flag runs", + }); + Mock runtimeInfo = new(); + runtimeInfo.Setup(c => c.GetTargetArchitecture()).Returns(architecture); + Target target = builder.AddMockContract(runtimeInfo).Build(); + TargetPointer address = new(GcInfoAddress); + return interpreter + ? new GcInfoDecoder(target, address, version) + : architecture switch + { + RuntimeInfoArchitecture.X64 => new GcInfoDecoder(target, address, version), + RuntimeInfoArchitecture.Arm => new GcInfoDecoder(target, address, version), + RuntimeInfoArchitecture.Arm64 => new GcInfoDecoder(target, address, version), + RuntimeInfoArchitecture.LoongArch64 => new GcInfoDecoder(target, address, version), + RuntimeInfoArchitecture.RiscV64 => new GcInfoDecoder(target, address, version), + RuntimeInfoArchitecture.Wasm => new GcInfoDecoder(target, address, version), + _ => throw new InvalidOperationException(), + }; + } +} diff --git a/src/native/managed/cdac/tests/UnitTests/StackWalkTests.cs b/src/native/managed/cdac/tests/UnitTests/StackWalkTests.cs index 20f505534f942c..ec0196219f5960 100644 --- a/src/native/managed/cdac/tests/UnitTests/StackWalkTests.cs +++ b/src/native/managed/cdac/tests/UnitTests/StackWalkTests.cs @@ -18,16 +18,16 @@ public unsafe class StackWalkTests private const uint X86TransitionBlockSize = 7 * sizeof(uint); [Theory] - [InlineData(false, new byte[] { 0x04, 0x05, 0x21, 0x02 }, uint.MaxValue)] - [InlineData(false, new byte[] { 0x81, 0x08, 0x0a, 0x30, 0x42, 0x04 }, 8u)] - [InlineData(true, new byte[] { 0x04, 0x4a, 0x04 }, uint.MaxValue)] - [InlineData(true, new byte[] { 0x81, 0x08, 0x84, 0x11, 0x22, 0x00 }, 8u)] + [InlineData(false, new byte[] { 0x42, 0x02 }, 2u, -1)] + [InlineData(false, new byte[] { 0x01, 0x84, 0x44, 0x44, 0x00 }, 2u, 17)] + [InlineData(true, new byte[] { 0x04, 0x4a, 0x04 }, uint.MaxValue, 17)] + [InlineData(true, new byte[] { 0x81, 0x08, 0x84, 0x11, 0x22, 0x00 }, 8u, 17)] public void GCInfo_Wasm_DecodesPlatformAndInterpreterFormats( - bool interpreter, byte[] encoded, uint stackBaseRegister) + bool interpreter, byte[] encoded, uint stackBaseRegister, int safePointOffset) { MockTarget.Architecture arch = new() { IsLittleEndian = true, Is64Bit = false }; TestPlaceholderTarget.Builder builder = new(arch); - // Length 129 and safe point 17 distinguish the platform's six-bit encoding + // Length 129 and safe point 17, when present, distinguish the platform's five-bit encoding // from the interpreter's eight-bit encoding and exercise header alignment. byte[] gcInfo = new byte[32]; encoded.CopyTo(gcInfo, 0); @@ -44,15 +44,16 @@ public void GCInfo_Wasm_DecodesPlatformAndInterpreterFormats( .AddContract(version: "c1") .Build().Contracts.GCInfo; IGCInfoHandle handle = interpreter - ? contract.DecodeInterpreterGCInfo(new TargetPointer(0x1000), 4) - : contract.DecodePlatformSpecificGCInfo(new TargetPointer(0x1000), 4); + ? contract.DecodeInterpreterGCInfo(new TargetPointer(0x1000), 6) + : contract.DecodePlatformSpecificGCInfo(new TargetPointer(0x1000), 6); GCInfoHeader header = contract.GetHeader(handle); Assert.Equal(129u, contract.GetCodeLength(handle)); Assert.Equal(129u, header.CodeSize); Assert.Equal(stackBaseRegister, header.StackBaseRegister); Assert.Equal(0u, header.SizeOfStackParameterArea); - Assert.Equal(new uint[] { 17 }, contract.GetSafePoints(handle)); + uint[] expectedSafePoints = safePointOffset < 0 ? [] : [(uint)safePointOffset]; + Assert.Equal(expectedSafePoints, contract.GetSafePoints(handle)); Assert.Empty(contract.GetInterruptibleRanges(handle)); Assert.Equal(interpreter, contract.TryGetGenericContextStorage( handle, GenericContextLoc.ThisPtr, 0, out GenericContextStorage storage)); @@ -1781,10 +1782,9 @@ private static TargetPointer AddWasmR2RFunctions( helpers.Write(entry.Slice(runtimeFunctionLayout.Fields[nameof(Data.RuntimeFunction.BeginAddress)].Offset, sizeof(uint)), functions[i].BeginAddress); if (functions[i].FrameSize != 0) { - // Unwind data is the ULEB128 frame size, addressed as LoadedImageBase (0 here) + UnwindData. - Assert.True(functions[i].FrameSize < 0x80); + Assert.Equal(0, functions[i].FrameSize % 16); MockMemorySpace.HeapFragment unwindData = allocator.Allocate(1, "UnwindData"); - unwindData.Data[0] = functions[i].FrameSize; + unwindData.Data[0] = (byte)(functions[i].FrameSize / 16); helpers.Write(entry.Slice(runtimeFunctionLayout.Fields[nameof(Data.RuntimeFunction.UnwindData)].Offset, sizeof(uint)), (uint)unwindData.Address); } } diff --git a/src/native/managed/cdac/tests/UnitTests/WasmUnwinderTests.cs b/src/native/managed/cdac/tests/UnitTests/WasmUnwinderTests.cs index c53fa9e4598a14..6fe030693777c4 100644 --- a/src/native/managed/cdac/tests/UnitTests/WasmUnwinderTests.cs +++ b/src/native/managed/cdac/tests/UnitTests/WasmUnwinderTests.cs @@ -217,7 +217,7 @@ public void TryUnwindOneFrame_AdvancesBySingleByteFrameSize_AndYieldsCallerVirtu [ Frame(FramesBase, FuncIndexLeaf, 3, "leaf"), Frame(callerBase, FuncIndexCaller, 7, "caller"), - Blob(BlobsBase, [(byte)leafFrameSize], "leafUnwind"), // ULEB128 0x20 == 32 + Blob(BlobsBase, [(byte)(leafFrameSize / 16)], "leafUnwind"), ]); WasmUnwinder unwinder = new(target, info); @@ -240,7 +240,7 @@ public void WasmContext_UnwindCallerWithoutVirtualIp_PreservesStackPointerAndCle [ Frame(FramesBase, FuncIndexLeaf, 3, "leaf"), Frame(callerBase, FuncIndexCaller, 7, "nonR2RCaller"), - Blob(BlobsBase, [(byte)leafFrameSize], "leafUnwind"), + Blob(BlobsBase, [(byte)(leafFrameSize / 16)], "leafUnwind"), ]); WasmUnwinder unwinder = new(target, info); WasmContext context = new() @@ -257,10 +257,13 @@ public void WasmContext_UnwindCallerWithoutVirtualIp_PreservesStackPointerAndCle Assert.Equal(TargetPointer.Null, context.FramePointer); } - [Fact] - public void TryUnwindOneFrame_DecodesMultiByteFrameSize() + [Theory] + [InlineData(new byte[] { 0x80, 0x02 }, 256u)] + [InlineData(new byte[] { 0x80, 0x80, 0x84, 0x80, 0x10 }, 4096u)] + [InlineData(new byte[] { 0x81, 0x80, 0x80, 0x80, 0x10 }, 16u)] + [InlineData(new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x3F }, 0xFFFFFF0u)] + public void TryUnwindOneFrame_DecodesInterleavedFrameSize(byte[] encoded, uint leafFrameSize) { - const uint leafFrameSize = 200; // ULEB128: 0xC8 0x01 ulong callerBase = FramesBase + leafFrameSize; FakeWasmR2RInfo info = new(); @@ -272,7 +275,7 @@ public void TryUnwindOneFrame_DecodesMultiByteFrameSize() [ Frame(FramesBase, FuncIndexLeaf, 0, "leaf"), Frame(callerBase, FuncIndexCaller, 1, "caller"), - Blob(BlobsBase, [0xC8, 0x01], "leafUnwind"), + Blob(BlobsBase, encoded, "leafUnwind"), ]); WasmUnwinder unwinder = new(target, info); @@ -294,7 +297,7 @@ public void TryUnwindOneFrame_ReversePInvokeRoot_PreservesNativeCallerStackPoint TestPlaceholderTarget target = CreateTarget( [ Frame(FramesBase, reversePInvokeIdentity, 3, "reversePInvoke"), - Blob(BlobsBase, [(byte)leafFrameSize], "leafUnwind"), + Blob(BlobsBase, [(byte)(leafFrameSize / 16)], "leafUnwind"), ]); WasmUnwinder unwinder = new(target, info); @@ -317,7 +320,7 @@ public void WasmContext_UnwindReversePInvokeRoot_PreservesStackPointerAndClearsI TestPlaceholderTarget target = CreateTarget( [ Frame(FramesBase, reversePInvokeIdentity, 3, "reversePInvoke"), - Blob(BlobsBase, [(byte)leafFrameSize], "leafUnwind"), + Blob(BlobsBase, [(byte)(leafFrameSize / 16)], "leafUnwind"), ]); WasmUnwinder unwinder = new(target, info); WasmContext context = new() @@ -363,8 +366,10 @@ public void TryGetFramePointer_LocallocToBelowFloor_ReturnsFalse() Assert.False(unwinder.TryGetFramePointer(new TargetPointer(indirectSp), out _)); } - [Fact] - public void TryUnwindOneFrame_ZeroFrameSize_TerminatesCleanly() + [Theory] + [InlineData(0x00)] + [InlineData(0x10)] + public void TryUnwindOneFrame_ZeroFrameSize_TerminatesCleanly(byte encoded) { FakeWasmR2RInfo info = new(); info.VirtualIpBases[FuncIndexLeaf] = VirtualIpBase; @@ -373,7 +378,7 @@ public void TryUnwindOneFrame_ZeroFrameSize_TerminatesCleanly() TestPlaceholderTarget target = CreateTarget( [ Frame(FramesBase, FuncIndexLeaf, 3, "leaf"), - Blob(BlobsBase, [0x00], "zeroFrameSize"), // ULEB128 0 -> no progress + Blob(BlobsBase, [encoded], "zeroFrameSize"), ]); WasmUnwinder unwinder = new(target, info); @@ -382,8 +387,10 @@ public void TryUnwindOneFrame_ZeroFrameSize_TerminatesCleanly() Assert.Equal(TargetPointer.Null, sp); } - [Fact] - public void TryUnwindOneFrame_MalformedUleb128_Throws() + [Theory] + [InlineData(0x80)] + [InlineData(0x02)] + public void TryUnwindOneFrame_MalformedUleb128_Throws(byte lastByte) { FakeWasmR2RInfo info = new(); info.UnwindData[LeafControlPc] = BlobsBase; @@ -391,8 +398,7 @@ public void TryUnwindOneFrame_MalformedUleb128_Throws() TestPlaceholderTarget target = CreateTarget( [ Frame(FramesBase, FuncIndexLeaf, 3, "leaf"), - // 5 continuation bytes with no terminator -> exceeds the 5-byte uint32 ULEB128 limit. - Blob(BlobsBase, [0x80, 0x80, 0x80, 0x80, 0x80], "malformed"), + Blob(BlobsBase, [0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, lastByte], "malformed"), ]); WasmUnwinder unwinder = new(target, info); @@ -529,10 +535,9 @@ private static TestPlaceholderTarget CreateProducerLayoutTarget(LinearStack stac FakeExecutionManager executionManager = new(); for (int i = 0; i < functions.Length; i++) { - // Unwind data is the ULEB128 fixed frame size, addressed as LoadedImageBase (0) + UnwindData. - Assert.True(functions[i].FrameSize < 0x80); + Assert.True(functions[i].FrameSize / 16 < 0x10); MockMemorySpace.HeapFragment unwindData = allocator.Allocate(1, "UnwindData"); - unwindData.Data[0] = (byte)functions[i].FrameSize; + unwindData.Data[0] = (byte)(functions[i].FrameSize / 16); Span entry = runtimeFunctions.Data.AsSpan(i * (int)runtimeFunctionLayout.Stride, (int)runtimeFunctionLayout.Stride); helpers.Write(entry.Slice(runtimeFunctionLayout.Fields[nameof(Data.RuntimeFunction.BeginAddress)].Offset, sizeof(uint)), functions[i].BeginAddress); From b7b45d8d1546e5adf751ff0000e21aa31f694f8d Mon Sep 17 00:00:00 2001 From: David Wrighton Date: Wed, 21 Oct 2026 22:16:31 +0000 Subject: [PATCH 05/21] Require current GCInfo in the runtime and remove legacy Wasm decoding Require ReadyToRun 33 and GCInfo v6 on every runtime target. Remove legacy Wasm header and slot decoding while preserving older native formats in cDAC, R2R inspection tools, and the SOS decoder. Add v5 native and interpreter fixtures and update the format documentation. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/design/coreclr/botr/readytorun-format.md | 8 +- docs/design/datacontracts/GCInfo.md | 13 +-- src/coreclr/inc/gcinfo.h | 24 +----- src/coreclr/inc/gcinfodecoder.h | 86 +++++++++---------- src/coreclr/inc/readytorun.h | 3 +- .../GcInfoDecoderTests.cs | 33 +++++-- .../Amd64/GcInfo.cs | 4 +- .../Amd64/GcSlotTable.cs | 2 +- .../GCInfoTypes.cs | 10 +-- src/coreclr/vm/codeman.cpp | 17 +--- src/coreclr/vm/codeman.h | 1 - src/coreclr/vm/gc_unwind_x86.inl | 2 +- src/coreclr/vm/gcinfodecoder.cpp | 34 ++++---- src/coreclr/vm/nativeimage.cpp | 7 -- src/coreclr/vm/proftoeeinterfaceimpl.cpp | 2 +- src/coreclr/vm/readytoruninfo.cpp | 8 -- ...ecutionManagerCore.ReadyToRunJitManager.cs | 1 + .../Contracts/GCInfo/GCInfoDecoder.cs | 34 +++----- .../cdac/tests/UnitTests/GCInfoTests.cs | 38 ++++++-- 19 files changed, 152 insertions(+), 175 deletions(-) diff --git a/docs/design/coreclr/botr/readytorun-format.md b/docs/design/coreclr/botr/readytorun-format.md index 0e18adaa1c3dfc..c9b41f77959c2c 100644 --- a/docs/design/coreclr/botr/readytorun-format.md +++ b/docs/design/coreclr/botr/readytorun-format.md @@ -478,9 +478,9 @@ The largest representable frame size is `2^28 - 16` bytes; the largest virtual I is below 256 bytes and the virtual IP count is below 16. ReadyToRun format 33.0 uses this packed unwind data and the compact Wasm GC encoding described -below. Earlier Wasm images use incompatible encodings and must be regenerated. The Wasm runtime -and managed reader reject them before interpreting their unwind or GC metadata; native targets -retain their existing minimum supported format version. +below. The runtime requires ReadyToRun format 33.0 or later on every architecture and only +decodes GCInfo v6. Earlier images must be regenerated. Inspection tools retain older non-Wasm +format support, but reject earlier Wasm images before interpreting their unwind or GC metadata. The virtual IP count (after multiplying by 2) gives the span of virtual IPs covered by this function or funclet. All virtual IPs are forced to even numbers so that the runtime can force all virtual @@ -514,7 +514,6 @@ bits of the target register number, without another continuation bit: This reserves x64 encoding space for APX roots without changing register allocation or runtime context support for them. Legacy x86 GCInfo uses its separate, unchanged format. -GCInfo versions before v6 retain the original flags-after-absolute, unbounded register encoding. Stack slots use the same shrinking flag bits as registers: two bits initially and after a pinned slot, only the interior bit after an unpinned interior slot, and no flag bits after an @@ -525,7 +524,6 @@ frame-relative. Caller-SP-relative slots are not represented in v6. The first slot of each flags/base combination has a signed absolute stack offset, followed by unsigned offset deltas for the remaining slots in that group. Flags, base, and offset state reset at the tracked/untracked boundary. Platform-specific offset normalization is unchanged. -Older non-Wasm ReadyToRun images retain their original GCInfo decoding. ### GC info (wasm) diff --git a/docs/design/datacontracts/GCInfo.md b/docs/design/datacontracts/GCInfo.md index e330734a05ea18..f8a36730998746 100644 --- a/docs/design/datacontracts/GCInfo.md +++ b/docs/design/datacontracts/GCInfo.md @@ -6,10 +6,10 @@ The GCInfo contract has platform specific implementations as GCInfo differs per WebAssembly uses the common decoder with `Wasm32GcInfoEncoding` traits from `src/coreclr/inc/gcinfotypes.h`: code lengths/offsets are unscaled, stack offsets -are in four-byte pointer units, the code-length encoding base is 6, and there is no fixed stack +are in four-byte pointer units, the code-length encoding base is 5, and there is no fixed stack parameter scratch area. The platform encoding has no interruptible-range -count in its fat header (`HAS_INTERRUPTIBLE_RANGES` is false). Starting with GCInfo -version 6, both header forms omit the frame-register presence bit and register value, +count in its fat header (`HAS_INTERRUPTIBLE_RANGES` is false). Both header forms omit the +frame-register presence bit and register value, implicitly using normalized register zero (physical register 2). The prolog-size-minus-one field is omitted and its normalized prolog size is implicitly one when needed for GS-cookie or generic-context validity. Slim headers imply zero safe points and omit the @@ -18,6 +18,10 @@ count; nonzero safe-point counts require fat headers and remain explicitly encod WebAssembly, including its code-length encoding base of 8 and its interruptible-range count field. +The runtime uses GCInfo v6 exclusively. This contract also retains non-Wasm GCInfo v5 +decoding to support older runtimes. WebAssembly has only the v6 platform encoding; +there is no legacy WebAssembly decoding path. + ## APIs of contract ```csharp @@ -210,8 +214,7 @@ bits: bit `0x40` is omitted from the stream, higher flag bits shift down one pos the decoder restores `GC_INFO_HAS_STACK_BASE_REGISTER` implicitly. Interpreter headers retain the common layout on every architecture. -Wasm version 6 uses the following tuned variable-length integer bases. Earlier Wasm -versions retain their original bases. +Wasm uses the following tuned variable-length integer bases. | Constant | Wasm v6 ENCBASE | | --- | --- | diff --git a/src/coreclr/inc/gcinfo.h b/src/coreclr/inc/gcinfo.h index 0fd1319e29d430..6161bab6023395 100644 --- a/src/coreclr/inc/gcinfo.h +++ b/src/coreclr/inc/gcinfo.h @@ -61,11 +61,8 @@ inline int GCInfoVersion() // wasteful to store the version once for every method. // Instead, the version# istracked per range-section of generated/loaded methods. // -// The GCInfo version is computed as : -// 1) The current GCINFO_VERSION for JITted and Ngened images -// 2) A function of the Ready - to - run major version stored in READYTORUN_HEADER -// for ready - to - run images.ReadyToRunJitManager::JitTokenToGCInfoVersion() -// provides the GcInfo version for any Method. +// The runtime uses the current GCINFO_VERSION for both JITted and ReadyToRun code. +// Diagnostic tools can supply an earlier version when inspecting older runtimes. //----------------------------------------------------------------------------- struct GCInfoToken @@ -80,23 +77,6 @@ struct GCInfoToken Version = GCINFO_VERSION; } #endif - - // Keep this in sync with GetR2RGCInfoVersion in cDac (ExecutionManagerCore.ReadyToRunJitManager.cs) - static uint32_t ReadyToRunVersionToGcInfoVersion(uint32_t readyToRunMajorVersion, uint32_t readyToRunMinorVersion) - { - if (readyToRunMajorVersion >= 33) - return 6; - - if (readyToRunMajorVersion >= 21) - return 5; - - if (readyToRunMajorVersion >= 11) - return 4; - - // Since v2 and v3 had the same file format and v1 is no longer supported, - // we can assume GCInfo v3. - return 3; - } }; /*****************************************************************************/ diff --git a/src/coreclr/inc/gcinfodecoder.h b/src/coreclr/inc/gcinfodecoder.h index bf2f17eaa71d82..78e71f97b0aa7d 100644 --- a/src/coreclr/inc/gcinfodecoder.h +++ b/src/coreclr/inc/gcinfodecoder.h @@ -529,59 +529,59 @@ class GcSlotDecoder UINT32 ReadRegisterSlot(BitStreamReader& reader, GcSlotFlags& flags, UINT32 previousRegister, bool first) { - bool absolute = first || flags != GC_SLOT_BASE; - if (m_UseCompactSlotEncoding) +#ifdef DECODE_OLD_FORMATS + if (!m_UseCompactSlotEncoding) { - GcSlotFlags previousFlags = flags; - flags = ReadSlotFlags(reader, previousFlags, first); - absolute = first || flags != previousFlags; - UINT32 value = ReadRegisterValue(reader, absolute - ? GcInfoEncoding::REGISTER_ENCBASE : GcInfoEncoding::REGISTER_DELTA_ENCBASE); + bool absolute = first || flags != GC_SLOT_BASE; + UINT32 value = static_cast(reader.DecodeVarLengthUnsigned(absolute + ? GcInfoEncoding::REGISTER_ENCBASE : GcInfoEncoding::REGISTER_DELTA_ENCBASE)); + if (absolute) + { + flags = static_cast(reader.Read(2)); + } return absolute ? value : previousRegister + value + 1; } +#endif // DECODE_OLD_FORMATS - UINT32 value = static_cast(reader.DecodeVarLengthUnsigned(absolute - ? GcInfoEncoding::REGISTER_ENCBASE : GcInfoEncoding::REGISTER_DELTA_ENCBASE)); - if (absolute) - { - flags = static_cast(reader.Read(2)); - } + GcSlotFlags previousFlags = flags; + flags = ReadSlotFlags(reader, previousFlags, first); + bool absolute = first || flags != previousFlags; + UINT32 value = ReadRegisterValue(reader, absolute + ? GcInfoEncoding::REGISTER_ENCBASE : GcInfoEncoding::REGISTER_DELTA_ENCBASE); return absolute ? value : previousRegister + value + 1; } - static GcStackSlotBase ReadStackSlotBase(BitStreamReader& reader) - { - return GcInfoEncoding::HAS_STACK_SLOT_BASE ? (GcStackSlotBase)reader.Read(2) : GC_FRAMEREG_REL; - } - INT32 ReadStackSlot(BitStreamReader& reader, GcSlotFlags& flags, GcStackSlotBase& base, INT32 previousOffset, bool first) { - bool absolute = first || flags != GC_SLOT_BASE; - if (m_UseCompactSlotEncoding) - { - GcSlotFlags previousFlags = flags; - GcStackSlotBase previousBase = first ? GC_SP_REL : base; - flags = ReadSlotFlags(reader, previousFlags, first); - base = GcInfoEncoding::HAS_STACK_SLOT_BASE && !reader.ReadOneFast() ? GC_SP_REL : GC_FRAMEREG_REL; - absolute = first || flags != previousFlags || base != previousBase; - } - else +#ifdef DECODE_OLD_FORMATS + if (!m_UseCompactSlotEncoding) { - base = ReadStackSlotBase(reader); + bool absolute = first || flags != GC_SLOT_BASE; + base = GcInfoEncoding::HAS_STACK_SLOT_BASE ? (GcStackSlotBase)reader.Read(2) : GC_FRAMEREG_REL; + INT32 offset = absolute + ? static_cast(reader.DecodeVarLengthSigned(GcInfoEncoding::STACK_SLOT_ENCBASE)) + : previousOffset + static_cast(reader.DecodeVarLengthUnsigned(GcInfoEncoding::STACK_SLOT_DELTA_ENCBASE)); + if (absolute) + { + flags = static_cast(reader.Read(2)); + } + + return offset; } +#endif // DECODE_OLD_FORMATS + GcSlotFlags previousFlags = flags; + GcStackSlotBase previousBase = first ? GC_SP_REL : base; + flags = ReadSlotFlags(reader, previousFlags, first); + base = GcInfoEncoding::HAS_STACK_SLOT_BASE && !reader.ReadOneFast() ? GC_SP_REL : GC_FRAMEREG_REL; + bool absolute = first || flags != previousFlags || base != previousBase; INT32 offset = absolute ? static_cast(reader.DecodeVarLengthSigned(GcInfoEncoding::STACK_SLOT_ENCBASE)) : previousOffset + static_cast(reader.DecodeVarLengthUnsigned(GcInfoEncoding::STACK_SLOT_DELTA_ENCBASE)); - if (!m_UseCompactSlotEncoding && absolute) - { - flags = static_cast(reader.Read(2)); - } - return offset; } @@ -590,7 +590,9 @@ class GcSlotDecoder UINT32 m_NumSlots; UINT32 m_NumRegisters; UINT32 m_NumUntracked; +#ifdef DECODE_OLD_FORMATS bool m_UseCompactSlotEncoding; +#endif // DECODE_OLD_FORMATS UINT32 m_NumDecodedSlots; GcSlotDesc* m_pLastSlot; @@ -686,20 +688,14 @@ class TGcInfoDecoder inline UINT32 Version() { +#ifdef DECODE_OLD_FORMATS return m_Version; +#else + return GCINFO_VERSION; +#endif // DECODE_OLD_FORMATS } private: - bool UsesCompactWasmHeader() - { - return GcInfoEncoding::USES_COMPACT_WASM_HEADER && Version() >= 6; - } - - bool UsesLegacyWasmEncoding() - { - return GcInfoEncoding::USES_COMPACT_WASM_HEADER && Version() < 6; - } - BitStreamReader m_Reader; UINT32 m_InstructionOffset; @@ -745,7 +741,9 @@ class TGcInfoDecoder GcInfoDecoderFlags m_Flags; PTR_CBYTE m_GcInfoAddress; #endif +#ifdef DECODE_OLD_FORMATS UINT32 m_Version; +#endif // DECODE_OLD_FORMATS inline UINT32 NormalizeCodeOffset(UINT32 offset) { diff --git a/src/coreclr/inc/readytorun.h b/src/coreclr/inc/readytorun.h index da2f8174a6d09a..2744c4e88e9daf 100644 --- a/src/coreclr/inc/readytorun.h +++ b/src/coreclr/inc/readytorun.h @@ -22,8 +22,7 @@ #define READYTORUN_MAJOR_VERSION 33 #define READYTORUN_MINOR_VERSION 0x0000 -#define MINIMUM_READYTORUN_MAJOR_VERSION 26 -#define MINIMUM_WASM_READYTORUN_MAJOR_VERSION 33 +#define MINIMUM_READYTORUN_MAJOR_VERSION 33 // R2R Version 2.1 adds the InliningInfo section // R2R Version 2.2 adds the ProfileDataInfo section diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/GcInfoDecoderTests.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/GcInfoDecoderTests.cs index 6f16611d5a4dc3..67085b070865f2 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/GcInfoDecoderTests.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/GcInfoDecoderTests.cs @@ -242,11 +242,28 @@ public void StackSlotDeltasAllowZeroAndLargeGaps(Machine machine, int flags) Assert.Equal((writer.BitCount + 7) / 8, info.Size); } + [Fact] + public void NonWasmVersion5StackSlotsRemainReadable() + { + byte[] encoded = [0x0A, 0x80, 0xB0, 0x10, 0x88, 0x00]; + using MemoryStream stream = new(encoded); + GcInfo info = new(new NativeReader(stream), 0, Machine.Amd64, 5); + + Assert.Equal(2, info.CodeLength); + Assert.Equal(2u, info.SlotTable.NumUntracked); + Assert.Equal(64, info.SlotTable.GcSlots[0].StackSlot.SpOffset); + Assert.Equal(GcStackSlotBase.GC_SP_REL, info.SlotTable.GcSlots[0].StackSlot.Base); + Assert.Equal(128, info.SlotTable.GcSlots[1].StackSlot.SpOffset); + Assert.Equal(GcStackSlotBase.GC_FRAMEREG_REL, info.SlotTable.GcSlots[1].StackSlot.Base); + Assert.All(info.SlotTable.GcSlots, slot => Assert.Equal(GcSlotFlags.GC_SLOT_UNTRACKED, slot.Flags)); + Assert.Equal(encoded.Length, info.Size); + } + [Theory] + [InlineData(Machine.Amd64, 5, 0x0A, 5u)] + [InlineData(Machine.Amd64, 5, 0x08, uint.MaxValue)] [InlineData(Machine.Amd64, 6, 0x0A, 5u)] [InlineData(Machine.Amd64, 6, 0x08, uint.MaxValue)] - [InlineData(WasmMachine.Wasm32, 5, 0x0A, 2u)] - [InlineData(WasmMachine.Wasm32, 5, 0x08, uint.MaxValue)] [InlineData(WasmMachine.Wasm32, 6, 0x04, 2u)] public void SlimHeaderUsesImplicitDefaultFrameRegister(Machine machine, int version, byte header, uint frameRegister) { @@ -257,18 +274,16 @@ public void SlimHeaderUsesImplicitDefaultFrameRegister(Machine machine, int vers Assert.Equal(2, info.CodeLength); Assert.Equal(frameRegister, info.StackBaseRegister); Assert.Empty(info.SlotTable.GcSlots); - Assert.Equal(machine == WasmMachine.Wasm32 && version >= 6 ? 1 : 2, info.Size); + Assert.Equal(machine == WasmMachine.Wasm32 ? 1 : 2, info.Size); } [Theory] - [InlineData(5, new byte[] { 0xA1, 0x10, 0x00, 0x01, 0x00 })] - [InlineData(5, new byte[] { 0xC1, 0x10, 0x00, 0x01, 0x00 })] - [InlineData(6, new byte[] { 0x21, 0x08, 0x02, 0x00 })] - [InlineData(6, new byte[] { 0x41, 0x08, 0x02, 0x00 })] - public void WasmFatHeaderPreservesGenericContext(int version, byte[] encoded) + [InlineData(new byte[] { 0x21, 0x08, 0x02, 0x00 })] + [InlineData(new byte[] { 0x41, 0x08, 0x02, 0x00 })] + public void WasmFatHeaderPreservesGenericContext(byte[] encoded) { using MemoryStream stream = new(encoded); - GcInfo info = new(new NativeReader(stream), 0, WasmMachine.Wasm32, version); + GcInfo info = new(new NativeReader(stream), 0, WasmMachine.Wasm32, 6); Assert.Equal(2, info.CodeLength); Assert.Equal(2u, info.StackBaseRegister); diff --git a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Amd64/GcInfo.cs b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Amd64/GcInfo.cs index af0fbdc635520b..51d9834bffd641 100644 --- a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Amd64/GcInfo.cs +++ b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Amd64/GcInfo.cs @@ -64,7 +64,7 @@ public SafePointOffset(int index, uint value) private Machine _machine; private GcInfoTypes _gcInfoTypes; - private bool UsesCompactWasmHeader => _machine == WasmMachine.Wasm32 && Version >= 6; + private bool UsesCompactWasmHeader => _machine == WasmMachine.Wasm32; public int Version { get; set; } public ReturnKinds ReturnKind { get; set; } @@ -94,7 +94,7 @@ public GcInfo(NativeReader imageReader, int offset, Machine machine, int version Offset = offset; Version = version; bool denormalizeCodeOffsets = Version > MIN_GCINFO_VERSION_WITH_NORMALIZED_CODE_OFFSETS; - _gcInfoTypes = new GcInfoTypes(machine, denormalizeCodeOffsets, version); + _gcInfoTypes = new GcInfoTypes(machine, denormalizeCodeOffsets); _machine = machine; SecurityObjectStackSlot = -1; diff --git a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Amd64/GcSlotTable.cs b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Amd64/GcSlotTable.cs index 2f212a651b8444..623ff375021b63 100644 --- a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Amd64/GcSlotTable.cs +++ b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Amd64/GcSlotTable.cs @@ -201,7 +201,7 @@ private void DecodeRegisters(NativeReader imageReader, GcInfoTypes gcInfoTypes, private void DecodeStackSlots(NativeReader imageReader, Machine machine, GcInfoTypes gcInfoTypes, uint nSlots, bool isUntracked, ref int bitOffset, int version) { - if (version >= 6) + if (machine == WasmMachine.Wasm32 || version >= 6) { GcSlotFlags slotFlags = 0; GcStackSlotBase previousBase = GcStackSlotBase.GC_SP_REL; diff --git a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/GCInfoTypes.cs b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/GCInfoTypes.cs index 7058647fcdc75f..baa9eef2d7ab67 100644 --- a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/GCInfoTypes.cs +++ b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/GCInfoTypes.cs @@ -123,7 +123,7 @@ public class GcInfoTypes internal bool HAS_FIXED_STACK_PARAMETER_SCRATCH_AREA { get; } = true; internal bool HAS_INTERRUPTIBLE_RANGES { get; } = true; - internal GcInfoTypes(Machine machine, bool denormalizeCodeOffsets, int version) + internal GcInfoTypes(Machine machine, bool denormalizeCodeOffsets) { _target = machine; _denormalizeCodeOffsets = denormalizeCodeOffsets; @@ -161,14 +161,14 @@ internal GcInfoTypes(Machine machine, bool denormalizeCodeOffsets, int version) GENERICS_INST_CONTEXT_STACK_SLOT_ENCBASE = 6; SECURITY_OBJECT_STACK_SLOT_ENCBASE = 6; GS_COOKIE_STACK_SLOT_ENCBASE = 6; - CODE_LENGTH_ENCBASE = version >= 6 ? 5 : 6; + CODE_LENGTH_ENCBASE = 5; STACK_BASE_REGISTER_ENCBASE = 3; SIZE_OF_STACK_AREA_ENCBASE = 6; SIZE_OF_EDIT_AND_CONTINUE_PRESERVED_AREA_ENCBASE = 3; - REVERSE_PINVOKE_FRAME_ENCBASE = version >= 6 ? 4 : 6; + REVERSE_PINVOKE_FRAME_ENCBASE = 4; NUM_REGISTERS_ENCBASE = 3; NUM_STACK_SLOTS_ENCBASE = 5; - NUM_UNTRACKED_SLOTS_ENCBASE = version >= 6 ? 7 : 5; + NUM_UNTRACKED_SLOTS_ENCBASE = 7; NORM_PROLOG_SIZE_ENCBASE = 4; NORM_EPILOG_SIZE_ENCBASE = 3; INTERRUPTIBLE_RANGE_DELTA1_ENCBASE = 5; @@ -177,7 +177,7 @@ internal GcInfoTypes(Machine machine, bool denormalizeCodeOffsets, int version) REGISTER_DELTA_ENCBASE = REGISTER_ENCBASE; STACK_SLOT_ENCBASE = 3; STACK_SLOT_DELTA_ENCBASE = 3; - NUM_SAFE_POINTS_ENCBASE = version >= 6 ? 3 : 4; + NUM_SAFE_POINTS_ENCBASE = 3; NUM_INTERRUPTIBLE_RANGES_ENCBASE = 1; POINTER_SIZE_ENCBASE = 3; LIVESTATE_RLE_RUN_ENCBASE = 2; diff --git a/src/coreclr/vm/codeman.cpp b/src/coreclr/vm/codeman.cpp index 59dfdf990cca8d..6432932d3ae1ac 100644 --- a/src/coreclr/vm/codeman.cpp +++ b/src/coreclr/vm/codeman.cpp @@ -6801,19 +6801,6 @@ PTR_ReadyToRunInfo ReadyToRunJitManager::JitTokenToReadyToRunInfo(const METHODTO return MethodToken.m_pRangeSection->_pR2RModule->GetReadyToRunInfo(); } -UINT32 ReadyToRunJitManager::JitTokenToGCInfoVersion(const METHODTOKEN& MethodToken) -{ - CONTRACTL{ - NOTHROW; - GC_NOTRIGGER; - SUPPORTS_DAC; - } CONTRACTL_END; - - READYTORUN_HEADER * header = JitTokenToReadyToRunInfo(MethodToken)->GetReadyToRunHeader(); - - return GCInfoToken::ReadyToRunVersionToGcInfoVersion(header->MajorVersion, header->MinorVersion); -} - PTR_RUNTIME_FUNCTION ReadyToRunJitManager::JitTokenToRuntimeFunction(const METHODTOKEN& MethodToken) { CONTRACTL { @@ -6853,9 +6840,7 @@ GCInfoToken ReadyToRunJitManager::GetGCInfoToken(const METHODTOKEN& MethodToken) // GCInfo immediately follows unwind data PTR_BYTE gcInfo = dac_cast(pUnwindData) + nUnwindDataSize; - UINT32 gcInfoVersion = JitTokenToGCInfoVersion(MethodToken); - - return{ gcInfo, gcInfoVersion }; + return{ gcInfo, GCINFO_VERSION }; } unsigned ReadyToRunJitManager::InitializeEHEnumeration(const METHODTOKEN& MethodToken, EH_CLAUSE_ENUMERATOR* pEnumState) diff --git a/src/coreclr/vm/codeman.h b/src/coreclr/vm/codeman.h index 4a4d294f12fa7a..ba44e053ec0ce6 100644 --- a/src/coreclr/vm/codeman.h +++ b/src/coreclr/vm/codeman.h @@ -2951,7 +2951,6 @@ class ReadyToRunJitManager final : public IJitManager virtual PCODE GetCodeAddressForRelOffset(const METHODTOKEN& MethodToken, DWORD relOffset); static PTR_ReadyToRunInfo JitTokenToReadyToRunInfo(const METHODTOKEN& MethodToken); - static UINT32 JitTokenToGCInfoVersion(const METHODTOKEN& MethodToken); static PTR_RUNTIME_FUNCTION JitTokenToRuntimeFunction(const METHODTOKEN& MethodToken); diff --git a/src/coreclr/vm/gc_unwind_x86.inl b/src/coreclr/vm/gc_unwind_x86.inl index ef5d6c5ca20947..374252fedf7c7f 100644 --- a/src/coreclr/vm/gc_unwind_x86.inl +++ b/src/coreclr/vm/gc_unwind_x86.inl @@ -152,7 +152,7 @@ size_t DecodeGCHdrInfo(GCInfoToken gcInfoToken, /* Decode the InfoHdr */ InfoHdr header; - table = decodeHeader(table, gcInfoToken.Version, &header); + table = decodeHeader(table, GCINFO_VERSION, &header); BOOL hasArgTabOffset = FALSE; if (header.untrackedCnt == HAS_UNTRACKED) diff --git a/src/coreclr/vm/gcinfodecoder.cpp b/src/coreclr/vm/gcinfodecoder.cpp index 4f11918e14e779..ef68fe144f589b 100644 --- a/src/coreclr/vm/gcinfodecoder.cpp +++ b/src/coreclr/vm/gcinfodecoder.cpp @@ -95,7 +95,7 @@ template bool TGcInfoDecoder::SetIsInt // returns true if we decoded all that was asked; template bool TGcInfoDecoder::PredecodeFatHeader(int remainingFlags) { - if (UsesCompactWasmHeader()) + if (GcInfoEncoding::USES_COMPACT_WASM_HEADER) { UINT32 flags = static_cast(m_Reader.Read(GC_INFO_FLAGS_BIT_SIZE - 1)); m_headerFlags = static_cast((flags & 0x3F) | ((flags & 0x1C0) << 1) | @@ -122,8 +122,7 @@ template bool TGcInfoDecoder::Predecod return true; } - m_CodeLength = GcInfoEncoding::DENORMALIZE_CODE_LENGTH((UINT32)m_Reader.DecodeVarLengthUnsigned( - UsesLegacyWasmEncoding() ? 6 : GcInfoEncoding::CODE_LENGTH_ENCBASE)); + m_CodeLength = GcInfoEncoding::DENORMALIZE_CODE_LENGTH((UINT32)m_Reader.DecodeVarLengthUnsigned(GcInfoEncoding::CODE_LENGTH_ENCBASE)); remainingFlags &= ~DECODE_CODE_LENGTH; if (remainingFlags == 0) { @@ -138,7 +137,7 @@ template bool TGcInfoDecoder::Predecod UINT32 normCodeLength = NormalizeCodeOffset(m_CodeLength); // Decode prolog/epilog information - UINT32 normPrologSize = UsesCompactWasmHeader() ? 1 : + UINT32 normPrologSize = GcInfoEncoding::USES_COMPACT_WASM_HEADER ? 1 : (UINT32)m_Reader.DecodeVarLengthUnsigned(GcInfoEncoding::NORM_PROLOG_SIZE_ENCBASE) + 1; UINT32 normEpilogSize = (UINT32)m_Reader.DecodeVarLengthUnsigned(GcInfoEncoding::NORM_EPILOG_SIZE_ENCBASE); @@ -149,7 +148,7 @@ template bool TGcInfoDecoder::Predecod else if ((m_headerFlags & GC_INFO_HAS_GENERICS_INST_CONTEXT_MASK) != GC_INFO_HAS_GENERICS_INST_CONTEXT_NONE) { // Decode prolog information - UINT32 normPrologSize = UsesCompactWasmHeader() ? 1 : + UINT32 normPrologSize = GcInfoEncoding::USES_COMPACT_WASM_HEADER ? 1 : (UINT32)m_Reader.DecodeVarLengthUnsigned(GcInfoEncoding::NORM_PROLOG_SIZE_ENCBASE) + 1; m_ValidRangeStart = DenormalizeCodeOffset(normPrologSize); // satisfy asserts that assume m_GSCookieValidRangeStart != 0 ==> m_GSCookieValidRangeStart < m_GSCookieValidRangeEnd @@ -223,7 +222,7 @@ template bool TGcInfoDecoder::Predecod if (m_headerFlags & GC_INFO_HAS_STACK_BASE_REGISTER) { - m_StackBaseRegister = GcInfoEncoding::DENORMALIZE_STACK_BASE_REGISTER(UsesCompactWasmHeader() ? 0 : + m_StackBaseRegister = GcInfoEncoding::DENORMALIZE_STACK_BASE_REGISTER(GcInfoEncoding::USES_COMPACT_WASM_HEADER ? 0 : (UINT32)m_Reader.DecodeVarLengthUnsigned(GcInfoEncoding::STACK_BASE_REGISTER_ENCBASE)); } else @@ -255,8 +254,7 @@ template bool TGcInfoDecoder::Predecod if (m_headerFlags & GC_INFO_REVERSE_PINVOKE_FRAME) { - m_ReversePInvokeFrameStackSlot = GcInfoEncoding::DENORMALIZE_STACK_SLOT((INT32)m_Reader.DecodeVarLengthSigned( - UsesLegacyWasmEncoding() ? 6 : GcInfoEncoding::REVERSE_PINVOKE_FRAME_ENCBASE)); + m_ReversePInvokeFrameStackSlot = GcInfoEncoding::DENORMALIZE_STACK_SLOT((INT32)m_Reader.DecodeVarLengthSigned(GcInfoEncoding::REVERSE_PINVOKE_FRAME_ENCBASE)); } else { @@ -292,7 +290,9 @@ TGcInfoDecoder::TGcInfoDecoder( , m_Flags( flags ) , m_GcInfoAddress(dac_cast(gcInfoToken.Info)) #endif +#ifdef DECODE_OLD_FORMATS , m_Version(gcInfoToken.Version) +#endif // DECODE_OLD_FORMATS { _ASSERTE( (flags & (DECODE_INTERRUPTIBILITY | DECODE_GC_LIFETIMES)) || (0 == breakOffset) ); @@ -316,7 +316,7 @@ TGcInfoDecoder::TGcInfoDecoder( } else { - if (UsesCompactWasmHeader() || m_Reader.ReadOneFast()) + if (GcInfoEncoding::USES_COMPACT_WASM_HEADER || m_Reader.ReadOneFast()) { m_headerFlags = GC_INFO_HAS_STACK_BASE_REGISTER; m_StackBaseRegister = GcInfoEncoding::DENORMALIZE_STACK_BASE_REGISTER(0); @@ -344,8 +344,7 @@ TGcInfoDecoder::TGcInfoDecoder( return; } - m_CodeLength = GcInfoEncoding::DENORMALIZE_CODE_LENGTH((UINT32)m_Reader.DecodeVarLengthUnsigned( - UsesLegacyWasmEncoding() ? 6 : GcInfoEncoding::CODE_LENGTH_ENCBASE)); + m_CodeLength = GcInfoEncoding::DENORMALIZE_CODE_LENGTH((UINT32)m_Reader.DecodeVarLengthUnsigned(GcInfoEncoding::CODE_LENGTH_ENCBASE)); // // predecoding the rest of slim header does not require any reading. @@ -385,8 +384,8 @@ TGcInfoDecoder::TGcInfoDecoder( } #ifdef PARTIALLY_INTERRUPTIBLE_GC_SUPPORTED - m_NumSafePoints = UsesCompactWasmHeader() && slimHeader ? 0 : - (UINT32)m_Reader.DecodeVarLengthUnsigned(UsesLegacyWasmEncoding() ? 4 : GcInfoEncoding::NUM_SAFE_POINTS_ENCBASE); + m_NumSafePoints = GcInfoEncoding::USES_COMPACT_WASM_HEADER && slimHeader ? 0 : + (UINT32)m_Reader.DecodeVarLengthUnsigned(GcInfoEncoding::NUM_SAFE_POINTS_ENCBASE); m_SafePointIndex = m_NumSafePoints; _ASSERTE(GcInfoEncoding::HAS_TRACKED_SLOTS || m_NumSafePoints == 0); #endif @@ -1181,7 +1180,11 @@ template void TGcInfoDecoder::ReportUn template void GcSlotDecoder::DecodeSlotTable(BitStreamReader& reader, UINT32 version) { - m_UseCompactSlotEncoding = version >= 6; +#ifdef DECODE_OLD_FORMATS + m_UseCompactSlotEncoding = GcInfoEncoding::USES_COMPACT_WASM_HEADER || version >= 6; +#else + _ASSERTE(version == GCINFO_VERSION); +#endif // DECODE_OLD_FORMATS if constexpr (GcInfoEncoding::HAS_REGISTER_SLOTS) { if (reader.ReadOneFast()) @@ -1201,8 +1204,7 @@ template void GcSlotDecoder::DecodeSlo if (reader.ReadOneFast()) { numStackSlots = (UINT32) reader.DecodeVarLengthUnsigned(GcInfoEncoding::NUM_STACK_SLOTS_ENCBASE); - m_NumUntracked = (UINT32) reader.DecodeVarLengthUnsigned( - GcInfoEncoding::USES_COMPACT_WASM_HEADER && version < 6 ? 5 : GcInfoEncoding::NUM_UNTRACKED_SLOTS_ENCBASE); + m_NumUntracked = (UINT32) reader.DecodeVarLengthUnsigned(GcInfoEncoding::NUM_UNTRACKED_SLOTS_ENCBASE); } else { diff --git a/src/coreclr/vm/nativeimage.cpp b/src/coreclr/vm/nativeimage.cpp index d01c209bbb381a..5c197a2186bbe0 100644 --- a/src/coreclr/vm/nativeimage.cpp +++ b/src/coreclr/vm/nativeimage.cpp @@ -298,13 +298,6 @@ NativeImage *NativeImage::Open( COMPlusThrowHR(COR_E_BADIMAGEFORMAT); } -#ifdef TARGET_WASM - if (pHeader->MajorVersion < MINIMUM_WASM_READYTORUN_MAJOR_VERSION) - { - COMPlusThrowHR(COR_E_BADIMAGEFORMAT); - } -#endif // TARGET_WASM - NewHolder image = new NativeImage(pAssemblyBinder, loadedImageHolder.Extract(), nativeImageFileName); AllocMemTracker amTracker; image->Initialize(pHeader, pLoaderAllocator, &amTracker); diff --git a/src/coreclr/vm/proftoeeinterfaceimpl.cpp b/src/coreclr/vm/proftoeeinterfaceimpl.cpp index 7ab62b094fc7a2..53cab64836cab1 100644 --- a/src/coreclr/vm/proftoeeinterfaceimpl.cpp +++ b/src/coreclr/vm/proftoeeinterfaceimpl.cpp @@ -8347,7 +8347,7 @@ HRESULT ProfToEEInterfaceImpl::ProfilerEbpWalker( unsigned uiMethodSizeDummy; PTR_CBYTE table = PTR_CBYTE(gcInfo); table += decodeUnsigned(table, &uiMethodSizeDummy); - table = decodeHeader(table, gcInfoToken.Version, &header); + table = decodeHeader(table, GCINFO_VERSION, &header); // Ok, GCInfo, can we do a simple EBP walk or what? diff --git a/src/coreclr/vm/readytoruninfo.cpp b/src/coreclr/vm/readytoruninfo.cpp index 72a5c578be2c94..01472ea4936fea 100644 --- a/src/coreclr/vm/readytoruninfo.cpp +++ b/src/coreclr/vm/readytoruninfo.cpp @@ -671,14 +671,6 @@ PTR_ReadyToRunInfo ReadyToRunInfo::Initialize(Module * pModule, AllocMemTracker return NULL; } -#ifdef TARGET_WASM - if (pHeader->MajorVersion < MINIMUM_WASM_READYTORUN_MAJOR_VERSION) - { - DoLog("Ready to Run disabled - unsupported Wasm GC/unwind encoding"); - return NULL; - } -#endif // TARGET_WASM - LoaderHeap *pHeap = pModule->GetLoaderAllocator()->GetHighFrequencyHeap(); NativeImage *nativeImage = NULL; diff --git a/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/ExecutionManager/ExecutionManagerCore.ReadyToRunJitManager.cs b/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/ExecutionManager/ExecutionManagerCore.ReadyToRunJitManager.cs index c077bcb850f94b..3c7e09907faf72 100644 --- a/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/ExecutionManager/ExecutionManagerCore.ReadyToRunJitManager.cs +++ b/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/ExecutionManager/ExecutionManagerCore.ReadyToRunJitManager.cs @@ -188,6 +188,7 @@ public override void GetGCInfo(RangeSection rangeSection, TargetCodePointer jitt gcVersion = GetR2RGCInfoVersion(r2rInfo); } + // Diagnostics retain the historical mapping even when the runtime raises its minimum R2R version. // This function must be kept up to date with R2R version changes. // When the R2R version is bumped, it must be mapped to the correct GCInfo version. // Adding "MINIMUM_READYTORUN_MAJOR_VERSION" to ensure this is updated according diff --git a/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/GCInfoDecoder.cs b/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/GCInfoDecoder.cs index d7f6bb03b532de..43aa6f2ffa18e5 100644 --- a/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/GCInfoDecoder.cs +++ b/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/GCInfoDecoder.cs @@ -103,8 +103,6 @@ public static GcSlotDesc CreateStackSlot(int spOffset, GcStackSlotBase slotBase, private readonly NativeReader _reader; private readonly RuntimeInfoArchitecture _arch; private readonly bool PartiallyInterruptibleGCSupported = true; - private bool UsesCompactWasmHeader => TTraits.USES_COMPACT_WASM_HEADER && _gcVersion >= 6; - private bool UsesLegacyWasmEncoding => TTraits.USES_COMPACT_WASM_HEADER && _gcVersion < 6; /* Decode State */ private int _bitOffset; @@ -223,8 +221,7 @@ private IEnumerable DecodeSlotTable() if (_reader.ReadBits(1, ref _bitOffset) != 0) { numStackSlots = _reader.DecodeVarLengthUnsigned(TTraits.NUM_STACK_SLOTS_ENCBASE, ref _bitOffset); - _numUntrackedSlots = _reader.DecodeVarLengthUnsigned( - UsesLegacyWasmEncoding ? 5 : TTraits.NUM_UNTRACKED_SLOTS_ENCBASE, ref _bitOffset); + _numUntrackedSlots = _reader.DecodeVarLengthUnsigned(TTraits.NUM_UNTRACKED_SLOTS_ENCBASE, ref _bitOffset); } _numSlots = _numRegisters + numStackSlots + _numUntrackedSlots; @@ -256,7 +253,7 @@ private IEnumerable DecodeSlotTable() } } - if (_gcVersion >= 6) + if (TTraits.USES_COMPACT_WASM_HEADER || _gcVersion >= 6) { DecodeStackSlots(numStackSlots, isUntracked: false); DecodeStackSlots(_numUntrackedSlots, isUntracked: true); @@ -413,7 +410,7 @@ private IEnumerable DecodeHeader() private IEnumerable DecodeSlimHeader() { - if (UsesCompactWasmHeader || _reader.ReadBits(1, ref _bitOffset) != 0) + if (TTraits.USES_COMPACT_WASM_HEADER || _reader.ReadBits(1, ref _bitOffset) != 0) { _headerFlags = GcInfoHeaderFlags.GC_INFO_HAS_STACK_BASE_REGISTER; _stackBaseRegister = TTraits.DenormalizeStackBaseRegister(0); @@ -426,8 +423,7 @@ private IEnumerable DecodeSlimHeader() yield return DecodePoints.ReturnKind; yield return DecodePoints.VarArg; - _codeLength = TTraits.DenormalizeCodeLength(_reader.DecodeVarLengthUnsigned( - UsesLegacyWasmEncoding ? 6 : TTraits.CODE_LENGTH_ENCBASE, ref _bitOffset)); + _codeLength = TTraits.DenormalizeCodeLength(_reader.DecodeVarLengthUnsigned(TTraits.CODE_LENGTH_ENCBASE, ref _bitOffset)); // predecoding the rest of slim header does not require any reading. _validRangeStart = 0; @@ -450,10 +446,9 @@ private IEnumerable DecodeSlimHeader() yield return DecodePoints.EditAndContinue; yield return DecodePoints.ReversePInvoke; - if (PartiallyInterruptibleGCSupported && !UsesCompactWasmHeader) + if (PartiallyInterruptibleGCSupported && !TTraits.USES_COMPACT_WASM_HEADER) { - _numSafePoints = _reader.DecodeVarLengthUnsigned( - UsesLegacyWasmEncoding ? 4 : TTraits.NUM_SAFE_POINTS_ENCBASE, ref _bitOffset); + _numSafePoints = _reader.DecodeVarLengthUnsigned(TTraits.NUM_SAFE_POINTS_ENCBASE, ref _bitOffset); } _numInterruptibleRanges = 0; @@ -461,7 +456,7 @@ private IEnumerable DecodeSlimHeader() private IEnumerable DecodeFatHeader() { - if (UsesCompactWasmHeader) + if (TTraits.USES_COMPACT_WASM_HEADER) { uint flags = (uint)_reader.ReadBits((int)GcInfoHeaderFlags.GC_INFO_FLAGS_BIT_SIZE - 1, ref _bitOffset); _headerFlags = (GcInfoHeaderFlags)((flags & 0x3F) | ((flags & 0x1C0) << 1)) | @@ -474,8 +469,7 @@ private IEnumerable DecodeFatHeader() yield return DecodePoints.ReturnKind; yield return DecodePoints.VarArg; - _codeLength = TTraits.DenormalizeCodeLength(_reader.DecodeVarLengthUnsigned( - UsesLegacyWasmEncoding ? 6 : TTraits.CODE_LENGTH_ENCBASE, ref _bitOffset)); + _codeLength = TTraits.DenormalizeCodeLength(_reader.DecodeVarLengthUnsigned(TTraits.CODE_LENGTH_ENCBASE, ref _bitOffset)); yield return DecodePoints.CodeLength; if (_headerFlags.HasFlag(GcInfoHeaderFlags.GC_INFO_HAS_GS_COOKIE)) @@ -485,7 +479,7 @@ private IEnumerable DecodeFatHeader() uint normCodeLength = TTraits.NormalizeCodeLength(_codeLength); // Decode prolog/epilog information - uint normPrologSize = UsesCompactWasmHeader ? 1 : + uint normPrologSize = TTraits.USES_COMPACT_WASM_HEADER ? 1 : _reader.DecodeVarLengthUnsigned(TTraits.NORM_PROLOG_SIZE_ENCBASE, ref _bitOffset) + 1; uint normEpilogSize = _reader.DecodeVarLengthUnsigned(TTraits.NORM_EPILOG_SIZE_ENCBASE, ref _bitOffset); @@ -496,7 +490,7 @@ private IEnumerable DecodeFatHeader() else if ((_headerFlags & GcInfoHeaderFlags.GC_INFO_HAS_GENERICS_INST_CONTEXT_MASK) != GcInfoHeaderFlags.GC_INFO_HAS_GENERICS_INST_CONTEXT_NONE) { // Decode prolog information - uint normPrologSize = UsesCompactWasmHeader ? 1 : + uint normPrologSize = TTraits.USES_COMPACT_WASM_HEADER ? 1 : _reader.DecodeVarLengthUnsigned(TTraits.NORM_PROLOG_SIZE_ENCBASE, ref _bitOffset) + 1; _validRangeStart = TTraits.DenormalizeCodeOffset(normPrologSize); // satisfy asserts that assume m_GSCookieValidRangeStart != 0 ==> m_GSCookieValidRangeStart < m_GSCookieValidRangeEnd @@ -523,7 +517,7 @@ private IEnumerable DecodeFatHeader() yield return DecodePoints.GenericInstContext; _stackBaseRegister = _headerFlags.HasFlag(GcInfoHeaderFlags.GC_INFO_HAS_STACK_BASE_REGISTER) ? - TTraits.DenormalizeStackBaseRegister(UsesCompactWasmHeader ? 0 : + TTraits.DenormalizeStackBaseRegister(TTraits.USES_COMPACT_WASM_HEADER ? 0 : _reader.DecodeVarLengthUnsigned(TTraits.STACK_BASE_REGISTER_ENCBASE, ref _bitOffset)) : TTraits.NO_STACK_BASE_REGISTER; @@ -546,8 +540,7 @@ private IEnumerable DecodeFatHeader() yield return DecodePoints.EditAndContinue; _reversePInvokeFrameStackSlot = _headerFlags.HasFlag(GcInfoHeaderFlags.GC_INFO_REVERSE_PINVOKE_FRAME) ? - TTraits.DenormalizeStackSlot(_reader.DecodeVarLengthSigned( - UsesLegacyWasmEncoding ? 6 : TTraits.REVERSE_PINVOKE_FRAME_ENCBASE, ref _bitOffset)) : + TTraits.DenormalizeStackSlot(_reader.DecodeVarLengthSigned(TTraits.REVERSE_PINVOKE_FRAME_ENCBASE, ref _bitOffset)) : TTraits.NO_REVERSE_PINVOKE_FRAME; yield return DecodePoints.ReversePInvoke; @@ -559,8 +552,7 @@ private IEnumerable DecodeFatHeader() if (PartiallyInterruptibleGCSupported) { - _numSafePoints = _reader.DecodeVarLengthUnsigned( - UsesLegacyWasmEncoding ? 4 : TTraits.NUM_SAFE_POINTS_ENCBASE, ref _bitOffset); + _numSafePoints = _reader.DecodeVarLengthUnsigned(TTraits.NUM_SAFE_POINTS_ENCBASE, ref _bitOffset); } _numInterruptibleRanges = TTraits.HAS_INTERRUPTIBLE_RANGES diff --git a/src/native/managed/cdac/tests/UnitTests/GCInfoTests.cs b/src/native/managed/cdac/tests/UnitTests/GCInfoTests.cs index 8266f464ba7cd5..b47f37c6979820 100644 --- a/src/native/managed/cdac/tests/UnitTests/GCInfoTests.cs +++ b/src/native/managed/cdac/tests/UnitTests/GCInfoTests.cs @@ -138,17 +138,37 @@ void WriteUnsigned(int value, int encodingBase) } [Theory] - [InlineData(5u, new byte[] { 0x0A, 0x00 }, 0, 0u, 0u)] - [InlineData(5u, new byte[] { 0xA1, 0x10, 0x00, 0x01, 0x00 }, 8, 1u, 0u)] - [InlineData(5u, new byte[] { 0xC1, 0x10, 0x00, 0x01, 0x00 }, 8, 1u, 0u)] - [InlineData(6u, new byte[] { 0x04 }, 0, 0u, 0u)] - [InlineData(6u, new byte[] { 0x21, 0x08, 0x02, 0x00 }, 8, 1u, 0u)] - [InlineData(6u, new byte[] { 0x41, 0x08, 0x02, 0x00 }, 8, 1u, 0u)] - [InlineData(6u, new byte[] { 0x01, 0x08, 0x01 }, 0, 0u, 1u)] - public void WasmHeadersDecodePrologAndFrameRegister(uint version, byte[] encoded, int genericContextOffset, + [InlineData(false, new byte[] { 0x0A, 0x80, 0xB0, 0x10, 0x88, 0x00 })] + [InlineData(true, new byte[] { 0x0A, 0x40, 0x58, 0x08, 0x44 })] + public void NonWasmVersion5StackSlotsRemainReadable(bool interpreter, byte[] encoded) + { + IGCInfoDecoder decoder = CreateDecoder(RuntimeInfoArchitecture.X64, interpreter, encoded, 5); + IReadOnlyList slots = decoder.GetSlotLifetimes(); + + Assert.Equal(2u, decoder.GetCodeLength()); + Assert.Equal(2, slots.Count); + Assert.Equal(interpreter ? 8 : 64, slots[0].SpOffset); + Assert.Equal(1u, slots[0].BaseRegister); + Assert.Equal(interpreter ? 16 : 128, slots[1].SpOffset); + Assert.Equal(2u, slots[1].BaseRegister); + Assert.All(slots, slot => + { + Assert.False(slot.IsRegister); + Assert.Equal(0u, slot.GcFlags); + Assert.Equal(0u, slot.BeginOffset); + Assert.Equal(2u, slot.EndOffset); + }); + } + + [Theory] + [InlineData(new byte[] { 0x04 }, 0, 0u, 0u)] + [InlineData(new byte[] { 0x21, 0x08, 0x02, 0x00 }, 8, 1u, 0u)] + [InlineData(new byte[] { 0x41, 0x08, 0x02, 0x00 }, 8, 1u, 0u)] + [InlineData(new byte[] { 0x01, 0x08, 0x01 }, 0, 0u, 1u)] + public void WasmHeadersDecodePrologAndFrameRegister(byte[] encoded, int genericContextOffset, uint prologSize, uint safePoints) { - IGCInfoDecoder decoder = CreateDecoder(RuntimeInfoArchitecture.Wasm, false, encoded, version); + IGCInfoDecoder decoder = CreateDecoder(RuntimeInfoArchitecture.Wasm, false, encoded, 6); GCInfoHeader header = decoder.GetHeader(); Assert.Equal(2u, header.CodeSize); From 0d5a38e2105ba43702dc974babe76f5fbf52163f Mon Sep 17 00:00:00 2001 From: David Wrighton Date: Thu, 22 Oct 2026 21:50:50 +0000 Subject: [PATCH 06/21] Optimize Wasm GC slot encoding for pinned object roots Invert the Wasm pinned bit for slot sorting and encoding so pinned object roots sort last and omit repeated flags. Update native, ReadyToRun, and cDAC readers, regression coverage, and format documentation while retaining non-Wasm and interpreter encoding. Fresh same-input retail CoreLib measurements: image 20,891,864 -> 20,890,520 bytes; GC/unwind table 25,802 -> 24,448 bytes; whole-image Brotli q11/window22 3,806,455 -> 3,804,636 bytes. Decoded GC metadata matches for 52,559 methods. These use current IL rather than the historical measurement inputs. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/design/coreclr/botr/readytorun-format.md | 10 +++- docs/design/datacontracts/GCInfo.md | 5 ++ src/coreclr/gcinfo/gcinfoencoder.cpp | 14 ++++- src/coreclr/inc/gcinfodecoder.h | 5 +- .../GcInfoDecoderTests.cs | 59 +++++++++++++++---- .../Amd64/GcSlotTable.cs | 8 ++- .../Contracts/GCInfo/GCInfoDecoder.cs | 6 +- .../cdac/tests/UnitTests/GCInfoTests.cs | 29 ++++++++- 8 files changed, 113 insertions(+), 23 deletions(-) diff --git a/docs/design/coreclr/botr/readytorun-format.md b/docs/design/coreclr/botr/readytorun-format.md index c9b41f77959c2c..02fa5da25852f1 100644 --- a/docs/design/coreclr/botr/readytorun-format.md +++ b/docs/design/coreclr/botr/readytorun-format.md @@ -489,7 +489,7 @@ IPs or PortableEntryPoint structures. ### GC info -ReadyToRun format 33.0 uses GCInfo v6. On every platform using the shared GCInfo encoding, +ReadyToRun format 33.0 uses GCInfo v6. On non-Wasm platforms using the shared GCInfo encoding, tracked and untracked stack slots are each sorted in descending flag order: pinned interior pointers, pinned object references, interior pointers, then ordinary object references. @@ -532,7 +532,13 @@ frame-relative, with offsets stored in 4-byte pointer units. Both header forms i normalized zero for the default frame register: neither its presence bit nor its register number is encoded. Fat headers therefore contain nine flag bits instead of ten. The prolog size is also implicit at one virtual-IP unit; its encoded size-minus-one field is omitted. -Stack slot flags use the platform-independent shrinking bits described above. +Wasm XORs the pinned flag (`0x2`) before sorting and encoding stack slot flags. The descending +encoded order is therefore interior pointers (`11`), ordinary object references (`10`), +pinned interior pointers (`01`), then pinned object references (`00`). Pinned object references +are the most common Wasm roots. The first slot carries two flag bits; subsequent slots carry +two bits after an unpinned slot, one bit after a pinned interior pointer, and no flag bits after +a pinned object reference. Decoders XOR `0x2` back to recover the semantic flags. +Offset grouping and tracked/untracked state resets are unchanged. Wasm slim headers imply zero safe points and omit the count. Methods with nonzero safe-point counts must use fat headers, which retain the count and safe-point data. Non-Wasm slim headers diff --git a/docs/design/datacontracts/GCInfo.md b/docs/design/datacontracts/GCInfo.md index f8a36730998746..3fb68b5bbe9b44 100644 --- a/docs/design/datacontracts/GCInfo.md +++ b/docs/design/datacontracts/GCInfo.md @@ -14,6 +14,11 @@ implicitly using normalized register zero (physical register 2). The prolog-size field is omitted and its normalized prolog size is implicitly one when needed for GS-cookie or generic-context validity. Slim headers imply zero safe points and omit the count; nonzero safe-point counts require fat headers and remain explicitly encoded. +Wasm stack-slot flags are sorted and encoded after XOR with the pinned bit (`0x2`): +interior, ordinary object, pinned interior, then pinned object. The first slot has two +flag bits; later slots have two after an unpinned root, one after a pinned interior root, +and none after a pinned object root. Decoding restores the semantic pinned bit with +the same XOR. Tracked and untracked sections reset their flag and offset state independently. `DecodeInterpreterGCInfo` uses the separate interpreter traits even on WebAssembly, including its code-length encoding base of 8 and its interruptible-range count field. diff --git a/src/coreclr/gcinfo/gcinfoencoder.cpp b/src/coreclr/gcinfo/gcinfoencoder.cpp index 535ddd38710f0d..66b95bc5ce391b 100644 --- a/src/coreclr/gcinfo/gcinfoencoder.cpp +++ b/src/coreclr/gcinfo/gcinfoencoder.cpp @@ -780,6 +780,7 @@ struct GcSlotDescAndId UINT32 m_SlotId; }; +template struct CompareSlotDescAndIdBySlotDesc { bool operator()(const GcSlotDescAndId& first, const GcSlotDescAndId& second) @@ -787,14 +788,17 @@ struct CompareSlotDescAndIdBySlotDesc const GcSlotDesc* pFirst = &first.m_SlotDesc; const GcSlotDesc* pSecond = &second.m_SlotDesc; - int firstFlags = pFirst->Flags ^ GC_SLOT_UNTRACKED; - int secondFlags = pSecond->Flags ^ GC_SLOT_UNTRACKED; + constexpr int flagsXor = GC_SLOT_UNTRACKED | + (GcInfoEncoding::USES_COMPACT_WASM_HEADER ? GC_SLOT_PINNED : GC_SLOT_BASE); + int firstFlags = pFirst->Flags ^ flagsXor; + int secondFlags = pSecond->Flags ^ flagsXor; // All registers come before all stack slots // All untracked come last // Then sort them by flags, ensuring that the least-frequent interior/pinned flag combinations are first // This is accomplished in the comparison of flags, since we encode IsRegister in the highest flag bit // And we XOR the UNTRACKED flag to place them last in the second highest flag bit + // Wasm also inverts PINNED so its common pinned object roots come last. if( firstFlags != secondFlags ) return firstFlags > secondFlags; @@ -1253,7 +1257,7 @@ template void TGcInfoEncoder::Build() sortedSlots[i].m_SlotId = i; } - jitstd::sort(sortedSlots, sortedSlots + m_NumSlots, CompareSlotDescAndIdBySlotDesc()); + jitstd::sort(sortedSlots, sortedSlots + m_NumSlots, CompareSlotDescAndIdBySlotDesc()); for(UINT32 i = 0; i < m_NumSlots; i++) { @@ -1566,6 +1570,10 @@ template void TGcInfoEncoder::Build() _ASSERTE((slot.IsUntracked() != FALSE) == (section != 0)); GcSlotFlags flags = static_cast(slot.Flags & (GC_SLOT_INTERIOR | GC_SLOT_PINNED)); + if constexpr (GcInfoEncoding::USES_COMPACT_WASM_HEADER) + { + flags = static_cast(flags ^ GC_SLOT_PINNED); + } if (i == 0 || previousFlags != GC_SLOT_BASE) { m_Info1.Write(flags, i == 0 || (previousFlags & GC_SLOT_PINNED) != 0 ? 2 : 1); diff --git a/src/coreclr/inc/gcinfodecoder.h b/src/coreclr/inc/gcinfodecoder.h index 78e71f97b0aa7d..b44d98c373c404 100644 --- a/src/coreclr/inc/gcinfodecoder.h +++ b/src/coreclr/inc/gcinfodecoder.h @@ -522,9 +522,12 @@ class GcSlotDecoder static GcSlotFlags ReadSlotFlags(BitStreamReader& reader, GcSlotFlags previousFlags, bool first) { - return first || previousFlags != GC_SLOT_BASE + constexpr int flagsXor = GcInfoEncoding::USES_COMPACT_WASM_HEADER ? GC_SLOT_PINNED : GC_SLOT_BASE; + previousFlags = static_cast(previousFlags ^ flagsXor); + GcSlotFlags flags = first || previousFlags != GC_SLOT_BASE ? static_cast(reader.Read(first || (previousFlags & GC_SLOT_PINNED) != 0 ? 2 : 1)) : GC_SLOT_BASE; + return static_cast(flags ^ flagsXor); } UINT32 ReadRegisterSlot(BitStreamReader& reader, GcSlotFlags& flags, UINT32 previousRegister, bool first) diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/GcInfoDecoderTests.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/GcInfoDecoderTests.cs index 67085b070865f2..ef412b4623a589 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/GcInfoDecoderTests.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/GcInfoDecoderTests.cs @@ -151,8 +151,9 @@ public void StackSlotsUseFlagsThenBaseThenOffset(Machine machine, bool tracked, Assert.Equal((writer.BitCount + 7) / 8, info.Size); int slotIndex = 0; - for (int flags = 3; flags >= 0; flags--) + for (int encodedFlags = 3; encodedFlags >= 0; encodedFlags--) { + int flags = encodedFlags ^ (machine == WasmMachine.Wasm32 ? 2 : 0); for (int i = 0; i < counts[flags]; i++) { GcSlotTable.GcSlot slot = info.SlotTable.GcSlots[slotIndex++]; @@ -163,6 +164,33 @@ public void StackSlotsUseFlagsThenBaseThenOffset(Machine machine, bool tracked, } } + [Theory] + [InlineData(1)] + [InlineData(2)] + [InlineData(3)] + [InlineData(32)] + [InlineData(65)] + public void WasmPinnedObjectRunsOmitRepeatedFlags(int count) + { + SlotTableWriter writer = new(WasmMachine.Wasm32); + writer.WriteCounts(0, count); + writer.WriteStackSlots([0, 0, count, 0]); + Assert.Equal(28 + 4 * count, writer.BitCount); + + using MemoryStream stream = new(writer.ToArray()); + GcInfo info = new(new NativeReader(stream), 0, WasmMachine.Wasm32, 6); + Assert.Equal((uint)count, info.SlotTable.NumUntracked); + Assert.Equal(count, info.SlotTable.GcSlots.Count); + for (int i = 0; i < count; i++) + { + GcSlotTable.GcSlot slot = info.SlotTable.GcSlots[i]; + Assert.Equal(GcSlotFlags.GC_SLOT_PINNED | GcSlotFlags.GC_SLOT_UNTRACKED, slot.Flags); + Assert.Equal(4 * (-8 + i), slot.StackSlot.SpOffset); + Assert.Equal(GcStackSlotBase.GC_FRAMEREG_REL, slot.StackSlot.Base); + } + Assert.Equal((writer.BitCount + 7) / 8, info.Size); + } + [Theory] [InlineData(Machine.Amd64)] [InlineData(Machine.ArmThumb2)] @@ -194,14 +222,22 @@ public void LegacyStackSlotFlagsRemainReadable(Machine machine) } [Theory] - [InlineData(Machine.Amd64)] - [InlineData(WasmMachine.Wasm32)] - public void StackSlotFlagsAndBasesResetAtTrackedUntrackedBoundary(Machine machine) + [InlineData(Machine.Amd64, 0)] + [InlineData(Machine.Amd64, 1)] + [InlineData(Machine.Amd64, 2)] + [InlineData(Machine.Amd64, 3)] + [InlineData(WasmMachine.Wasm32, 0)] + [InlineData(WasmMachine.Wasm32, 1)] + [InlineData(WasmMachine.Wasm32, 2)] + [InlineData(WasmMachine.Wasm32, 3)] + public void StackSlotFlagsAndBasesResetAtTrackedUntrackedBoundary(Machine machine, int flags) { SlotTableWriter writer = new(machine); writer.WriteCounts(2, 2); - writer.WriteStackSlots([0, 2, 0, 0]); - writer.WriteStackSlots([0, 2, 0, 0]); + int[] counts = new int[4]; + counts[flags] = 2; + writer.WriteStackSlots(counts); + writer.WriteStackSlots(counts); writer.WriteUnsigned(0, 3); using MemoryStream stream = new(writer.ToArray()); @@ -211,7 +247,7 @@ public void StackSlotFlagsAndBasesResetAtTrackedUntrackedBoundary(Machine machin { Assert.Equal(writer.DenormalizeOffset(writer.GetStackOffset(i % 2, 2)), info.SlotTable.GcSlots[i].StackSlot.SpOffset); Assert.Equal(writer.GetStackBase(i % 2, 2), info.SlotTable.GcSlots[i].StackSlot.Base); - Assert.Equal(GcSlotFlags.GC_SLOT_INTERIOR | (i < 2 ? 0 : GcSlotFlags.GC_SLOT_UNTRACKED), info.SlotTable.GcSlots[i].Flags); + Assert.Equal((GcSlotFlags)flags | (i < 2 ? 0 : GcSlotFlags.GC_SLOT_UNTRACKED), info.SlotTable.GcSlots[i].Flags); } Assert.Equal((writer.BitCount + 7) / 8, info.Size); } @@ -464,22 +500,23 @@ public void WriteStackSlots(int[] counts, int[]? offsets = null) int previousFlags = -1; GcStackSlotBase previousBase = GcStackSlotBase.GC_FRAMEREG_REL; int previousOffset = 0; - for (int flags = 3; flags >= 0; flags--) + for (int encodedFlags = 3; encodedFlags >= 0; encodedFlags--) { + int flags = encodedFlags ^ (_machine == WasmMachine.Wasm32 ? 2 : 0); int count = counts[flags]; for (int i = 0; i < count; i++) { if (previousFlags != 0) - Write(flags, previousFlags < 0 || (previousFlags & 2) != 0 ? 2 : 1); + Write(encodedFlags, previousFlags < 0 || (previousFlags & 2) != 0 ? 2 : 1); GcStackSlotBase slotBase = GetStackBase(i, count); if (_machine != WasmMachine.Wasm32) Write(slotBase == GcStackSlotBase.GC_FRAMEREG_REL ? 1 : 0, 1); int offset = offsets is null ? GetStackOffset(i, count) : offsets[i]; - if (flags != previousFlags || slotBase != previousBase) + if (encodedFlags != previousFlags || slotBase != previousBase) WriteSigned(offset, _machine == WasmMachine.Wasm32 ? 3 : 6); else WriteUnsigned(offset - previousOffset, _machine == WasmMachine.Wasm32 ? 3 : 4); - previousFlags = flags; + previousFlags = encodedFlags; previousBase = slotBase; previousOffset = offset; } diff --git a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Amd64/GcSlotTable.cs b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Amd64/GcSlotTable.cs index 623ff375021b63..a319953d091d3e 100644 --- a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Amd64/GcSlotTable.cs +++ b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Amd64/GcSlotTable.cs @@ -168,11 +168,15 @@ private static uint ReadRegisterValue(NativeReader imageReader, int encodingBase return value; } - private static GcSlotFlags ReadSlotFlags(NativeReader imageReader, GcSlotFlags previousFlags, bool first, ref int bitOffset) + private GcSlotFlags ReadSlotFlags(NativeReader imageReader, GcSlotFlags previousFlags, bool first, ref int bitOffset) { - return first || previousFlags != 0 + GcSlotFlags flagsXor = _machine == WasmMachine.Wasm32 ? GcSlotFlags.GC_SLOT_PINNED : 0; + previousFlags ^= flagsXor; + GcSlotFlags flags = first || previousFlags != 0 ? (GcSlotFlags)imageReader.ReadBits(first || (previousFlags & GcSlotFlags.GC_SLOT_PINNED) != 0 ? 2 : 1, ref bitOffset) : 0; + + return flags ^ flagsXor; } private void DecodeRegisters(NativeReader imageReader, GcInfoTypes gcInfoTypes, ref int bitOffset, int version) diff --git a/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/GCInfoDecoder.cs b/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/GCInfoDecoder.cs index 43aa6f2ffa18e5..8e0586dcf18afd 100644 --- a/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/GCInfoDecoder.cs +++ b/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/GCInfoDecoder.cs @@ -205,9 +205,13 @@ private uint ReadRegisterValue(int encodingBase) private GcSlotFlags ReadSlotFlags(GcSlotFlags previousFlags, bool first) { - return first || previousFlags != 0 + GcSlotFlags flagsXor = TTraits.USES_COMPACT_WASM_HEADER ? GcSlotFlags.GC_SLOT_PINNED : 0; + previousFlags ^= flagsXor; + GcSlotFlags flags = first || previousFlags != 0 ? (GcSlotFlags)_reader.ReadBits(first || (previousFlags & GcSlotFlags.GC_SLOT_PINNED) != 0 ? 2 : 1, ref _bitOffset) : 0; + + return flags ^ flagsXor; } private IEnumerable DecodeSlotTable() diff --git a/src/native/managed/cdac/tests/UnitTests/GCInfoTests.cs b/src/native/managed/cdac/tests/UnitTests/GCInfoTests.cs index b47f37c6979820..4aee352178eadc 100644 --- a/src/native/managed/cdac/tests/UnitTests/GCInfoTests.cs +++ b/src/native/managed/cdac/tests/UnitTests/GCInfoTests.cs @@ -21,24 +21,47 @@ public class GCInfoTests [InlineData(RuntimeInfoArchitecture.RiscV64, false, new byte[] { 0x0A, 0x00, 0xA1, 0x36, 0xC4, 0x71, 0x42, 0x18, 0x17, 0xC4, 0x38, 0x10, 0x71 })] [InlineData(RuntimeInfoArchitecture.Wasm, false, new byte[] { 0x84, 0x00, 0xC2, 0x78, 0x87, 0x78, 0x46, 0x78, 0x03, 0x5E, 0x00 })] [InlineData(RuntimeInfoArchitecture.X64, true, new byte[] { 0x0A, 0x40, 0xA8, 0x0D, 0x71, 0x9C, 0x10, 0xC6, 0x05, 0x31, 0x0E, 0x44, 0x1C })] + [InlineData(RuntimeInfoArchitecture.Wasm, true, new byte[] { 0x0A, 0x40, 0xA8, 0x0D, 0x71, 0x9C, 0x10, 0xC6, 0x05, 0x31, 0x0E, 0x44, 0x1C })] public void StackSlotsUseFlagsThenBaseThenOffset(RuntimeInfoArchitecture architecture, bool interpreter, byte[] encoded) { IGCInfoDecoder decoder = CreateDecoder(architecture, interpreter, encoded, 6); IReadOnlyList slots = decoder.GetSlotLifetimes(); Assert.Equal(8, slots.Count); + bool wasm = architecture == RuntimeInfoArchitecture.Wasm && !interpreter; int slotSize = interpreter ? 1 : architecture is RuntimeInfoArchitecture.Arm or RuntimeInfoArchitecture.Wasm ? 4 : 8; for (int i = 0; i < slots.Count; i++) { Assert.False(slots[i].IsRegister); - int offset = architecture == RuntimeInfoArchitecture.Wasm ? -8 + i % 2 : i % 2 == 0 ? 8 : -8; + int offset = wasm ? -8 + i % 2 : i % 2 == 0 ? 8 : -8; Assert.Equal(offset * slotSize, slots[i].SpOffset); - Assert.Equal(architecture == RuntimeInfoArchitecture.Wasm ? 2u : (uint)(1 + i % 2), slots[i].BaseRegister); - Assert.Equal((uint)(3 - i / 2) | 4u, slots[i].GcFlags); + Assert.Equal(wasm ? 2u : (uint)(1 + i % 2), slots[i].BaseRegister); + uint flags = (uint)(3 - i / 2) ^ (wasm ? 2u : 0u); + Assert.Equal(flags | 4u, slots[i].GcFlags); Assert.Equal(0u, slots[i].BeginOffset); Assert.Equal(decoder.GetCodeLength(), slots[i].EndOffset); } } + [Theory] + [InlineData(1, new byte[] { 0x84, 0x40, 0x00, 0x78 })] + [InlineData(2, new byte[] { 0x84, 0x80, 0x00, 0x78, 0x01 })] + [InlineData(3, new byte[] { 0x84, 0xC0, 0x00, 0x78, 0x11 })] + public void WasmPinnedObjectRunsOmitRepeatedFlags(int count, byte[] encoded) + { + IGCInfoDecoder decoder = CreateDecoder(RuntimeInfoArchitecture.Wasm, false, encoded, 6); + IReadOnlyList slots = decoder.GetSlotLifetimes(); + Assert.Equal(count, slots.Count); + for (int i = 0; i < slots.Count; i++) + { + Assert.False(slots[i].IsRegister); + Assert.Equal(6u, slots[i].GcFlags); + Assert.Equal(4 * (-8 + i), slots[i].SpOffset); + Assert.Equal(2u, slots[i].BaseRegister); + Assert.Equal(0u, slots[i].BeginOffset); + Assert.Equal(2u, slots[i].EndOffset); + } + } + [Theory] [InlineData(RuntimeInfoArchitecture.X64, 5)] [InlineData(RuntimeInfoArchitecture.X64, 6)] From 3b4daf97aeeeb018c7c51f39d97a4461383e4c50 Mon Sep 17 00:00:00 2001 From: David Wrighton Date: Tue, 27 Oct 2026 15:55:41 -0700 Subject: [PATCH 07/21] Use interpreter GC decoding when inspecting interpreted frames Select InterpreterGcInfoDecoder for reverse-P/Invoke detection, generic-context prolog checks, and interruptible-range enumeration on interpreter frames. Keep native frame decoding unchanged. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 798665fd-8e9d-46c8-b56c-843764cdb3d1 --- src/coreclr/vm/exceptionhandling.cpp | 14 +++++++++++-- src/coreclr/vm/gcenv.ee.common.cpp | 30 +++++++++++++++++++++++----- 2 files changed, 37 insertions(+), 7 deletions(-) diff --git a/src/coreclr/vm/exceptionhandling.cpp b/src/coreclr/vm/exceptionhandling.cpp index f43bfd24128688..86cbd9099884f7 100644 --- a/src/coreclr/vm/exceptionhandling.cpp +++ b/src/coreclr/vm/exceptionhandling.cpp @@ -3966,8 +3966,18 @@ CLR_BOOL SfiNextWorker(StackFrameIterator* pThis, uint* uExCollideClauseIdx, CLR if (!doingFuncletUnwind) { #ifdef USE_GC_INFO_DECODER - GcInfoDecoder gcInfoDecoder(codeInfo.GetGCInfoToken(), DECODE_REVERSE_PINVOKE_VAR); - isPropagatingToNativeCode = gcInfoDecoder.GetReversePInvokeFrameStackSlot() != NO_REVERSE_PINVOKE_FRAME; +#ifdef FEATURE_INTERPRETER + if (codeInfo.GetCodeManager() == ExecutionManager::GetInterpreterCodeManager()) + { + InterpreterGcInfoDecoder gcInfoDecoder(codeInfo.GetGCInfoToken(), DECODE_REVERSE_PINVOKE_VAR); + isPropagatingToNativeCode = gcInfoDecoder.GetReversePInvokeFrameStackSlot() != NO_REVERSE_PINVOKE_FRAME; + } + else +#endif // FEATURE_INTERPRETER + { + GcInfoDecoder gcInfoDecoder(codeInfo.GetGCInfoToken(), DECODE_REVERSE_PINVOKE_VAR); + isPropagatingToNativeCode = gcInfoDecoder.GetReversePInvokeFrameStackSlot() != NO_REVERSE_PINVOKE_FRAME; + } #else // USE_GC_INFO_DECODER hdrInfo *hdrInfoBody; codeInfo.DecodeGCHdrInfo(&hdrInfoBody); diff --git a/src/coreclr/vm/gcenv.ee.common.cpp b/src/coreclr/vm/gcenv.ee.common.cpp index fb2e6b52f493fa..57510abdd1ddec 100644 --- a/src/coreclr/vm/gcenv.ee.common.cpp +++ b/src/coreclr/vm/gcenv.ee.common.cpp @@ -59,14 +59,24 @@ bool FindFirstInterruptiblePointStateCB( unsigned FindFirstInterruptiblePoint(CrawlFrame* pCF, unsigned offs, unsigned endOffs) { GCInfoToken gcInfoToken = pCF->GetGCInfoToken(); - GcInfoDecoder gcInfoDecoder(gcInfoToken, DECODE_FOR_RANGES_CALLBACK); FindFirstInterruptiblePointState state; state.offs = offs; state.endOffs = endOffs; state.returnOffs = -1; - gcInfoDecoder.EnumerateInterruptibleRanges(&FindFirstInterruptiblePointStateCB, &state); +#ifdef FEATURE_INTERPRETER + if (pCF->GetCodeManager() == ExecutionManager::GetInterpreterCodeManager()) + { + InterpreterGcInfoDecoder gcInfoDecoder(gcInfoToken, DECODE_FOR_RANGES_CALLBACK); + gcInfoDecoder.EnumerateInterruptibleRanges(&FindFirstInterruptiblePointStateCB, &state); + } + else +#endif // FEATURE_INTERPRETER + { + GcInfoDecoder gcInfoDecoder(gcInfoToken, DECODE_FOR_RANGES_CALLBACK); + gcInfoDecoder.EnumerateInterruptibleRanges(&FindFirstInterruptiblePointStateCB, &state); + } return state.returnOffs; } @@ -132,9 +142,19 @@ bool SafeToReportGenericParamContext(CrawlFrame* pCF) #else // USE_GC_INFO_DECODER - GcInfoDecoder gcInfoDecoder(pCF->GetGCInfoToken(), - DECODE_PROLOG_LENGTH); - UINT32 prologLength = gcInfoDecoder.GetPrologSize(); + UINT32 prologLength; +#ifdef FEATURE_INTERPRETER + if (pCF->GetCodeManager() == ExecutionManager::GetInterpreterCodeManager()) + { + InterpreterGcInfoDecoder gcInfoDecoder(pCF->GetGCInfoToken(), DECODE_PROLOG_LENGTH); + prologLength = gcInfoDecoder.GetPrologSize(); + } + else +#endif // FEATURE_INTERPRETER + { + GcInfoDecoder gcInfoDecoder(pCF->GetGCInfoToken(), DECODE_PROLOG_LENGTH); + prologLength = gcInfoDecoder.GetPrologSize(); + } if (pCF->GetRelOffset() < prologLength) { return false; From d2c97288b7751874a0351d9409e5b79a31e8e1b4 Mon Sep 17 00:00:00 2001 From: David Wrighton Date: Tue, 27 Oct 2026 15:55:41 -0700 Subject: [PATCH 08/21] Initialize the implicit GC frame register for frameless Wasm methods Set the Wasm GC encoder's frame register even when optimization removes the linear-memory frame, preserving the compact header invariant. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 798665fd-8e9d-46c8-b56c-843764cdb3d1 --- src/coreclr/jit/codegenwasm.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/coreclr/jit/codegenwasm.cpp b/src/coreclr/jit/codegenwasm.cpp index c03032987e5ddd..e2b5f48de992ce 100644 --- a/src/coreclr/jit/codegenwasm.cpp +++ b/src/coreclr/jit/codegenwasm.cpp @@ -4666,6 +4666,9 @@ void CodeGen::genCreateAndStoreGCInfo(unsigned codeSize, unsigned prologSize, un codeSize = 2 * maxVirtualIP; prologSize = 1; + // Wasm GC info has an implicit frame register even when there is no linear-memory frame. + gcInfoEncoder->SetStackBaseRegister(REG_FPBASE); + // Follow the code pattern of the x86 gc info encoder (genCreateAndStoreGCInfoJIT32). gcInfo.gcInfoBlockHdrSave(gcInfoEncoder, codeSize, prologSize); From eec92718309807c0d89f4d8f27a95e549811260f Mon Sep 17 00:00:00 2001 From: David Wrighton Date: Wed, 4 Nov 2026 00:14:18 +0000 Subject: [PATCH 09/21] Implement cDAC ISOSDacInterface18 GCInfo inspection Expose the existing GCInfo inspection interface through the cDAC COM object. Forward header, interruptible-range, safe-point, and slot-lifetime queries to the appropriate platform or interpreter decoder, with sized-buffer and HRESULT handling. Add regression coverage for interface discovery, unmanaged vtable calls, field mappings, buffer sizing, and failure outputs. Validate the NativeAOT cDAC build and 626 focused tests. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../SOSDacImpl.cs | 176 ++++++++++- .../cdac/tests/UnitTests/GCInfoTests.cs | 280 +++++++++++++++++- 2 files changed, 454 insertions(+), 2 deletions(-) diff --git a/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Legacy/SOSDacImpl.cs b/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Legacy/SOSDacImpl.cs index d575b5ba4cdd89..94a91fa8a55421 100644 --- a/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Legacy/SOSDacImpl.cs +++ b/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Legacy/SOSDacImpl.cs @@ -34,7 +34,7 @@ public sealed unsafe partial class SOSDacImpl : ISOSDacInterface, ISOSDacInterface2, ISOSDacInterface3, ISOSDacInterface4, ISOSDacInterface5, ISOSDacInterface6, ISOSDacInterface7, ISOSDacInterface8, ISOSDacInterface9, ISOSDacInterface10, ISOSDacInterface11, ISOSDacInterface12, ISOSDacInterface13, ISOSDacInterface14, ISOSDacInterface15, - ISOSDacInterface16, ISOSDacInterface17 + ISOSDacInterface16, ISOSDacInterface17, ISOSDacInterface18 { private const uint DefaultAppDomainId = 1; @@ -7606,4 +7606,178 @@ int ISOSDacInterface17.GetStressLogMemoryRanges(DacComNullableByRefSizeOf < (uint)sizeof(SOSGCInfoHeader)) + return HResults.E_INVALIDARG; + + *header = new SOSGCInfoHeader { SizeOf = (uint)sizeof(SOSGCInfoHeader) }; + (IGCInfo gcInfo, IGCInfoHandle handle) = GetGCInfoForAddress(ip); + GCInfoHeader info = gcInfo.GetHeader(handle); + *header = new SOSGCInfoHeader + { + SizeOf = (uint)sizeof(SOSGCInfoHeader), + GcInfoVersion = info.Version, + CodeSize = info.CodeSize, + PrologSize = info.PrologSize, + StackBaseRegister = info.StackBaseRegister, + SizeOfStackParameterArea = info.SizeOfStackParameterArea, + IsVarArg = info.IsVarArg ? 1 : 0, + WantsReportOnlyLeaf = info.WantsReportOnlyLeaf ? 1 : 0, + HasTailCalls = info.HasTailCalls ? 1 : 0, + GSCookieIsPresent = info.GSCookie.HasValue ? 1 : 0, + GSCookieStackSlot = info.GSCookie?.SpOffset ?? 0, + GSCookieValidRangeStart = info.GSCookieValidRangeStart, + GSCookieValidRangeEnd = info.GSCookieValidRangeEnd, + PSPSymIsPresent = info.PSPSym.HasValue ? 1 : 0, + PSPSymStackSlot = info.PSPSym?.SpOffset ?? 0, + GenericsInstContextIsPresent = info.GenericsInstContext.HasValue ? 1 : 0, + GenericsInstContextStackSlot = info.GenericsInstContext?.SpOffset ?? 0, + GenericsInstContextKind = (uint)info.GenericsInstContextKind, + }; + } + catch (System.Exception ex) + { + hr = ex.HResult; + } + + return hr; + } + + int ISOSDacInterface18.GetGCInfoInterruptibleRanges( + ClrDataAddress ip, uint count, SOSCodeRange[]? ranges, uint* pNeeded) + { + using Lock.Scope scope = _apiLock.EnterScope(); + int hr = HResults.S_OK; + try + { + if (pNeeded is null) + return HResults.E_POINTER; + *pNeeded = 0; + if (count > (uint)(ranges?.Length ?? 0)) + return HResults.E_INVALIDARG; + + (IGCInfo gcInfo, IGCInfoHandle handle) = GetGCInfoForAddress(ip); + IReadOnlyList info = gcInfo.GetInterruptibleRanges(handle); + *pNeeded = (uint)info.Count; + if (count < *pNeeded) + return HResults.S_FALSE; + + Span output = ranges.AsSpan(); + for (int i = 0; i < info.Count; i++) + { + InterruptibleRange range = info[i]; + output[i] = new SOSCodeRange + { + BeginOffset = range.StartOffset, + EndOffset = range.EndOffset, + }; + } + } + catch (System.Exception ex) + { + hr = ex.HResult; + } + + return hr; + } + + int ISOSDacInterface18.GetGCInfoSafePoints( + ClrDataAddress ip, uint count, uint[]? offsets, uint* pNeeded) + { + using Lock.Scope scope = _apiLock.EnterScope(); + int hr = HResults.S_OK; + try + { + if (pNeeded is null) + return HResults.E_POINTER; + *pNeeded = 0; + if (count > (uint)(offsets?.Length ?? 0)) + return HResults.E_INVALIDARG; + + (IGCInfo gcInfo, IGCInfoHandle handle) = GetGCInfoForAddress(ip); + IReadOnlyList info = gcInfo.GetSafePoints(handle); + *pNeeded = (uint)info.Count; + if (count < *pNeeded) + return HResults.S_FALSE; + + Span output = offsets.AsSpan(); + for (int i = 0; i < info.Count; i++) + { + output[i] = info[i]; + } + } + catch (System.Exception ex) + { + hr = ex.HResult; + } + + return hr; + } + + int ISOSDacInterface18.GetGCInfoSlotLifetimes( + ClrDataAddress ip, uint count, SOSGCSlotLifetime[]? lifetimes, uint* pNeeded) + { + using Lock.Scope scope = _apiLock.EnterScope(); + int hr = HResults.S_OK; + try + { + if (pNeeded is null) + return HResults.E_POINTER; + *pNeeded = 0; + if (count > (uint)(lifetimes?.Length ?? 0)) + return HResults.E_INVALIDARG; + + (IGCInfo gcInfo, IGCInfoHandle handle) = GetGCInfoForAddress(ip); + IReadOnlyList info = gcInfo.GetSlotLifetimes(handle); + *pNeeded = (uint)info.Count; + if (count < *pNeeded) + return HResults.S_FALSE; + + Span output = lifetimes.AsSpan(); + for (int i = 0; i < info.Count; i++) + { + GCSlotLifetime slot = info[i]; + output[i] = new SOSGCSlotLifetime + { + BeginOffset = slot.BeginOffset, + EndOffset = slot.EndOffset, + IsRegister = slot.IsRegister ? 1 : 0, + RegisterNumber = slot.RegisterNumber, + SpOffset = slot.SpOffset, + BaseRegister = slot.BaseRegister, + GcFlags = slot.GcFlags, + }; + } + } + catch (System.Exception ex) + { + hr = ex.HResult; + } + + return hr; + } + + private (IGCInfo Contract, IGCInfoHandle Handle) GetGCInfoForAddress(ClrDataAddress ip) + { + IExecutionManager executionManager = _target.Contracts.ExecutionManager; + TargetCodePointer codePointer = ip.ToTargetCodePointer(_target); + if (ip == 0 || executionManager.GetCodeBlockHandle(codePointer) is not CodeBlockHandle codeBlock) + throw new ArgumentException("The instruction pointer must refer to managed code.", nameof(ip)); + + executionManager.GetGCInfo(codeBlock, out TargetPointer address, out uint version); + IGCInfo gcInfo = _target.Contracts.GCInfo; + IGCInfoHandle handle = executionManager.GetCodeKind(codePointer) == Contracts.CodeKind.Interpreter + ? gcInfo.DecodeInterpreterGCInfo(address, version) + : gcInfo.DecodePlatformSpecificGCInfo(address, version); + + return (gcInfo, handle); + } } diff --git a/src/native/managed/cdac/tests/UnitTests/GCInfoTests.cs b/src/native/managed/cdac/tests/UnitTests/GCInfoTests.cs index 4aee352178eadc..aaefa6920a24b0 100644 --- a/src/native/managed/cdac/tests/UnitTests/GCInfoTests.cs +++ b/src/native/managed/cdac/tests/UnitTests/GCInfoTests.cs @@ -3,16 +3,21 @@ using System; using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Runtime.InteropServices.Marshalling; using Microsoft.Diagnostics.DataContractReader.Contracts; using Microsoft.Diagnostics.DataContractReader.Contracts.GCInfoHelpers; +using Microsoft.Diagnostics.DataContractReader.Legacy; using Microsoft.Diagnostics.DataContractReader.TestInfrastructure; using Moq; using Xunit; namespace Microsoft.Diagnostics.DataContractReader.Tests; -public class GCInfoTests +public unsafe class GCInfoTests { + private const ulong MethodIP = 0x10000; + [Theory] [InlineData(RuntimeInfoArchitecture.X64, false, new byte[] { 0x0A, 0x80, 0x50, 0x1B, 0xE2, 0x38, 0x21, 0x8C, 0x0B, 0x62, 0x1C, 0x88, 0x38 })] [InlineData(RuntimeInfoArchitecture.Arm, false, new byte[] { 0x0A, 0x80, 0x80, 0x31, 0xC4, 0x71, 0x42, 0x18, 0x17, 0xC4, 0x38, 0x10, 0x71 })] @@ -204,6 +209,279 @@ public void WasmHeadersDecodePrologAndFrameRegister(byte[] encoded, int genericC Assert.Empty(decoder.GetSlotLifetimes()); } + [Theory] + [ClassData(typeof(MockTarget.StdArch))] + public void QueryInterfaceFromIXCLRDataProcess_ExposesGCInfo(MockTarget.Architecture arch) + { + ISOSDacInterface18 sos = CreateGCInfoInterface(arch, CodeKind.Jitted); + void* process = ComInterfaceMarshaller.ConvertToUnmanaged(Assert.IsAssignableFrom(sos)); + try + { + Guid iid = typeof(ISOSDacInterface18).GUID; + Assert.Equal(HResults.S_OK, Marshal.QueryInterface((nint)process, in iid, out nint gcInfo)); + try + { + void** vtable = *(void***)gcInfo; + SOSGCInfoHeader header = new() { SizeOf = (uint)sizeof(SOSGCInfoHeader) }; + int hr = ((delegate* unmanaged[MemberFunction])vtable[3])(gcInfo, MethodIP, &header); + Assert.Equal(HResults.S_OK, hr); + Assert.Equal(6u, header.GcInfoVersion); + Assert.Equal(128u, header.CodeSize); + + uint needed = uint.MaxValue; + SOSCodeRange* ranges = stackalloc SOSCodeRange[2]; + hr = ((delegate* unmanaged[MemberFunction])vtable[4])(gcInfo, MethodIP, 2, ranges, &needed); + Assert.Equal(HResults.S_OK, hr); + Assert.Equal(2u, needed); + Assert.Equal(4u, ranges[0].BeginOffset); + Assert.Equal(20u, ranges[1].EndOffset); + + uint* offsets = stackalloc uint[2]; + hr = ((delegate* unmanaged[MemberFunction])vtable[5])(gcInfo, MethodIP, 2, offsets, &needed); + Assert.Equal(HResults.S_OK, hr); + Assert.Equal(2u, needed); + Assert.Equal(8u, offsets[0]); + Assert.Equal(24u, offsets[1]); + + SOSGCSlotLifetime* lifetimes = stackalloc SOSGCSlotLifetime[3]; + hr = ((delegate* unmanaged[MemberFunction])vtable[6])(gcInfo, MethodIP, 3, lifetimes, &needed); + Assert.Equal(HResults.S_OK, hr); + Assert.Equal(3u, needed); + Assert.Equal(1, lifetimes[0].IsRegister); + Assert.Equal(-24, lifetimes[1].SpOffset); + Assert.Equal(1u, lifetimes[2].BaseRegister); + } + finally + { + Marshal.Release(gcInfo); + } + } + finally + { + ComInterfaceMarshaller.Free(process); + } + } + + [Theory] + [InlineData(CodeKind.Jitted, GenericsContextKind.None)] + [InlineData(CodeKind.ReadyToRun, GenericsContextKind.This)] + [InlineData(CodeKind.Interpreter, GenericsContextKind.MethodDesc)] + [InlineData(CodeKind.Interpreter, GenericsContextKind.MethodHandle)] + public void GetGCInfoHeader_MapsFieldsAndSelectsDecoder(CodeKind codeKind, GenericsContextKind contextKind) + { + bool hasSpecialSlots = contextKind != GenericsContextKind.None; + MockTarget.Architecture arch = new() { Is64Bit = true, IsLittleEndian = true }; + ISOSDacInterface18 sos = CreateGCInfoInterface(arch, codeKind, (_, gcInfo, handle) => + { + gcInfo.Setup(g => g.GetHeader(handle)).Returns(new GCInfoHeader( + Version: 6, CodeSize: 128, PrologSize: 3, StackBaseRegister: 5, SizeOfStackParameterArea: 32, + IsVarArg: hasSpecialSlots, WantsReportOnlyLeaf: !hasSpecialSlots, HasTailCalls: hasSpecialSlots, + GSCookie: hasSpecialSlots ? new SpecialSlot(-16) : null, + GSCookieValidRangeStart: hasSpecialSlots ? 3u : 0u, + GSCookieValidRangeEnd: hasSpecialSlots ? 120u : 0u, + PSPSym: hasSpecialSlots ? new SpecialSlot(0) : null, + GenericsInstContext: hasSpecialSlots ? new SpecialSlot(-32) : null, + GenericsInstContextKind: contextKind)); + }); + + SOSGCInfoHeader header = new() { SizeOf = (uint)sizeof(SOSGCInfoHeader) }; + Assert.Equal(HResults.S_OK, sos.GetGCInfoHeader(MethodIP, &header)); + Assert.Equal((uint)sizeof(SOSGCInfoHeader), header.SizeOf); + Assert.Equal(6u, header.GcInfoVersion); + Assert.Equal(128u, header.CodeSize); + Assert.Equal(3u, header.PrologSize); + Assert.Equal(5u, header.StackBaseRegister); + Assert.Equal(32u, header.SizeOfStackParameterArea); + Assert.Equal(hasSpecialSlots ? 1 : 0, header.IsVarArg); + Assert.Equal(hasSpecialSlots ? 0 : 1, header.WantsReportOnlyLeaf); + Assert.Equal(hasSpecialSlots ? 1 : 0, header.HasTailCalls); + Assert.Equal(hasSpecialSlots ? 1 : 0, header.GSCookieIsPresent); + Assert.Equal(hasSpecialSlots ? -16 : 0, header.GSCookieStackSlot); + Assert.Equal(hasSpecialSlots ? 3u : 0u, header.GSCookieValidRangeStart); + Assert.Equal(hasSpecialSlots ? 120u : 0u, header.GSCookieValidRangeEnd); + Assert.Equal(hasSpecialSlots ? 1 : 0, header.PSPSymIsPresent); + Assert.Equal(0, header.PSPSymStackSlot); + Assert.Equal(hasSpecialSlots ? 1 : 0, header.GenericsInstContextIsPresent); + Assert.Equal(hasSpecialSlots ? -32 : 0, header.GenericsInstContextStackSlot); + Assert.Equal((uint)contextKind, header.GenericsInstContextKind); + } + + [Theory] + [InlineData(0)] + [InlineData(1)] + [InlineData(2)] + [InlineData(3)] + [InlineData(4)] + public void GetGCInfoTables_RespectBufferSizes(int count) + { + MockTarget.Architecture arch = new() { Is64Bit = false, IsLittleEndian = false }; + ISOSDacInterface18 sos = CreateGCInfoInterface(arch, CodeKind.Interpreter); + SOSCodeRange[]? ranges = count == 0 ? null : new SOSCodeRange[count]; + uint[]? offsets = count == 0 ? null : new uint[count]; + SOSGCSlotLifetime[]? lifetimes = count == 0 ? null : new SOSGCSlotLifetime[count]; + uint needed = uint.MaxValue; + + Assert.Equal(count < 2 ? HResults.S_FALSE : HResults.S_OK, + sos.GetGCInfoInterruptibleRanges(MethodIP, (uint)count, ranges, &needed)); + Assert.Equal(2u, needed); + Assert.Equal(count < 2 ? HResults.S_FALSE : HResults.S_OK, + sos.GetGCInfoSafePoints(MethodIP, (uint)count, offsets, &needed)); + Assert.Equal(2u, needed); + Assert.Equal(count < 3 ? HResults.S_FALSE : HResults.S_OK, + sos.GetGCInfoSlotLifetimes(MethodIP, (uint)count, lifetimes, &needed)); + Assert.Equal(3u, needed); + + if (count >= 2) + { + Assert.NotNull(ranges); + Assert.NotNull(offsets); + Assert.Equal(new SOSCodeRange { BeginOffset = 4, EndOffset = 12 }, ranges[0]); + Assert.Equal(new SOSCodeRange { BeginOffset = 16, EndOffset = 20 }, ranges[1]); + Assert.Equal(8u, offsets[0]); + Assert.Equal(24u, offsets[1]); + } + if (count >= 3) + { + Assert.NotNull(lifetimes); + Assert.Equal(new SOSGCSlotLifetime { BeginOffset = 4, EndOffset = 8, IsRegister = 1, RegisterNumber = 3, GcFlags = 3 }, lifetimes[0]); + Assert.Equal(new SOSGCSlotLifetime { BeginOffset = 0, EndOffset = 128, SpOffset = -24, BaseRegister = 2, GcFlags = 6 }, lifetimes[1]); + Assert.Equal(new SOSGCSlotLifetime { BeginOffset = 16, EndOffset = 20, SpOffset = 40, BaseRegister = 1, GcFlags = 1 }, lifetimes[2]); + } + if (ranges is not null) + Assert.All(ranges.AsSpan(count >= 2 ? 2 : 0).ToArray(), value => Assert.Equal(default, value)); + if (offsets is not null) + Assert.All(offsets.AsSpan(count >= 2 ? 2 : 0).ToArray(), value => Assert.Equal(0u, value)); + if (lifetimes is not null) + Assert.All(lifetimes.AsSpan(count >= 3 ? 3 : 0).ToArray(), value => Assert.Equal(default, value)); + } + + [Theory] + [ClassData(typeof(MockTarget.StdArch))] + public void GetGCInfoTables_EmptyResults(MockTarget.Architecture arch) + { + ISOSDacInterface18 sos = CreateGCInfoInterface(arch, CodeKind.ReadyToRun, (_, gcInfo, handle) => + { + gcInfo.Setup(g => g.GetInterruptibleRanges(handle)).Returns(Array.Empty()); + gcInfo.Setup(g => g.GetSafePoints(handle)).Returns(Array.Empty()); + gcInfo.Setup(g => g.GetSlotLifetimes(handle)).Returns(Array.Empty()); + }); + uint needed = uint.MaxValue; + Assert.Equal(HResults.S_OK, sos.GetGCInfoInterruptibleRanges(MethodIP, 0, null, &needed)); + Assert.Equal(0u, needed); + needed = uint.MaxValue; + Assert.Equal(HResults.S_OK, sos.GetGCInfoSafePoints(MethodIP, 0, null, &needed)); + Assert.Equal(0u, needed); + needed = uint.MaxValue; + Assert.Equal(HResults.S_OK, sos.GetGCInfoSlotLifetimes(MethodIP, 0, null, &needed)); + Assert.Equal(0u, needed); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void GetGCInfoHeader_RejectsInvalidBuffers(bool almostLargeEnough) + { + MockTarget.Architecture arch = new() { Is64Bit = true, IsLittleEndian = true }; + ISOSDacInterface18 sos = CreateGCInfoInterface(arch, CodeKind.Jitted); + Assert.Equal(HResults.E_POINTER, sos.GetGCInfoHeader(MethodIP, null)); + uint size = almostLargeEnough ? (uint)sizeof(SOSGCInfoHeader) - 1 : 0; + SOSGCInfoHeader header = new() { SizeOf = size, CodeSize = uint.MaxValue }; + Assert.Equal(HResults.E_INVALIDARG, sos.GetGCInfoHeader(MethodIP, &header)); + Assert.Equal(size, header.SizeOf); + Assert.Equal(uint.MaxValue, header.CodeSize); + } + + [Theory] + [ClassData(typeof(MockTarget.StdArch))] + public void GetGCInfoTables_RejectInvalidBuffers(MockTarget.Architecture arch) + { + ISOSDacInterface18 sos = CreateGCInfoInterface(arch, CodeKind.Jitted); + Assert.Equal(HResults.E_POINTER, sos.GetGCInfoInterruptibleRanges(MethodIP, 0, null, null)); + Assert.Equal(HResults.E_POINTER, sos.GetGCInfoSafePoints(MethodIP, 0, null, null)); + Assert.Equal(HResults.E_POINTER, sos.GetGCInfoSlotLifetimes(MethodIP, 0, null, null)); + + uint needed = uint.MaxValue; + Assert.Equal(HResults.E_INVALIDARG, sos.GetGCInfoInterruptibleRanges(MethodIP, 1, null, &needed)); + Assert.Equal(0u, needed); + needed = uint.MaxValue; + Assert.Equal(HResults.E_INVALIDARG, sos.GetGCInfoSafePoints(MethodIP, 1, null, &needed)); + Assert.Equal(0u, needed); + needed = uint.MaxValue; + Assert.Equal(HResults.E_INVALIDARG, sos.GetGCInfoSlotLifetimes(MethodIP, 1, null, &needed)); + Assert.Equal(0u, needed); + + Assert.Equal(HResults.E_INVALIDARG, sos.GetGCInfoInterruptibleRanges(MethodIP, 2, new SOSCodeRange[1], &needed)); + Assert.Equal(HResults.E_INVALIDARG, sos.GetGCInfoSafePoints(MethodIP, 2, new uint[1], &needed)); + Assert.Equal(HResults.E_INVALIDARG, sos.GetGCInfoSlotLifetimes(MethodIP, 2, new SOSGCSlotLifetime[1], &needed)); + } + + [Theory] + [InlineData(0ul, HResults.E_INVALIDARG)] + [InlineData(MethodIP + 1, HResults.E_INVALIDARG)] + [InlineData(MethodIP, HResults.E_FAIL)] + public void GetGCInfo_InitializesOutputsOnFailure(ulong ip, int expectedHResult) + { + MockTarget.Architecture arch = new() { Is64Bit = true, IsLittleEndian = true }; + ISOSDacInterface18 sos = CreateGCInfoInterface(arch, CodeKind.Jitted, (executionManager, _, _) => + { + executionManager.Setup(e => e.GetCodeBlockHandle(new TargetCodePointer(MethodIP + 1))).Returns((CodeBlockHandle?)null); + executionManager.Setup(e => e.GetCodeBlockHandle(new TargetCodePointer(MethodIP))) + .Throws(new COMException("Cannot read the method's code block.", HResults.E_FAIL)); + }); + SOSGCInfoHeader header = new() { SizeOf = (uint)sizeof(SOSGCInfoHeader), CodeSize = uint.MaxValue }; + Assert.Equal(expectedHResult, sos.GetGCInfoHeader(ip, &header)); + Assert.Equal((uint)sizeof(SOSGCInfoHeader), header.SizeOf); + Assert.Equal(0u, header.CodeSize); + Assert.Equal(0u, header.GcInfoVersion); + + uint needed = uint.MaxValue; + Assert.Equal(expectedHResult, sos.GetGCInfoInterruptibleRanges(ip, 0, null, &needed)); + Assert.Equal(0u, needed); + needed = uint.MaxValue; + Assert.Equal(expectedHResult, sos.GetGCInfoSafePoints(ip, 0, null, &needed)); + Assert.Equal(0u, needed); + needed = uint.MaxValue; + Assert.Equal(expectedHResult, sos.GetGCInfoSlotLifetimes(ip, 0, null, &needed)); + Assert.Equal(0u, needed); + } + + private static ISOSDacInterface18 CreateGCInfoInterface( + MockTarget.Architecture arch, + CodeKind codeKind, + Action, Mock, IGCInfoHandle>? configure = null) + { + CodeBlockHandle codeBlock = new(new TargetPointer(0x30000)); + TargetPointer gcInfoAddress = new(0x20000); + uint version = 6; + Mock executionManager = new(MockBehavior.Strict); + executionManager.Setup(e => e.GetCodeBlockHandle(new TargetCodePointer(MethodIP))).Returns(codeBlock); + executionManager.Setup(e => e.GetCodeKind(new TargetCodePointer(MethodIP))).Returns(codeKind); + executionManager.Setup(e => e.GetGCInfo(codeBlock, out gcInfoAddress, out version)); + Mock gcInfo = new(MockBehavior.Strict); + IGCInfoHandle handle = Mock.Of(); + if (codeKind == CodeKind.Interpreter) + gcInfo.Setup(g => g.DecodeInterpreterGCInfo(gcInfoAddress, version)).Returns(handle); + else + gcInfo.Setup(g => g.DecodePlatformSpecificGCInfo(gcInfoAddress, version)).Returns(handle); + gcInfo.Setup(g => g.GetHeader(handle)).Returns(new GCInfoHeader( + 6, 128, 0, 5, 0, false, false, false, null, 0, 0, null, null, GenericsContextKind.None)); + gcInfo.Setup(g => g.GetInterruptibleRanges(handle)).Returns(new InterruptibleRange[] { new(4, 12), new(16, 20) }); + gcInfo.Setup(g => g.GetSafePoints(handle)).Returns(new uint[] { 8, 24 }); + gcInfo.Setup(g => g.GetSlotLifetimes(handle)).Returns(new GCSlotLifetime[] + { + new(true, 3, 0, 0, 3, 4, 8), + new(false, 0, -24, 2, 6, 0, 128), + new(false, 0, 40, 1, 1, 16, 20), + }); + configure?.Invoke(executionManager, gcInfo, handle); + Target target = new TestPlaceholderTarget.Builder(arch) + .AddMockContract(executionManager) + .AddMockContract(gcInfo) + .Build(); + + return Assert.IsAssignableFrom(new SOSDacImpl(target, legacyObj: null, new())); + } + private static IGCInfoDecoder CreateDecoder(RuntimeInfoArchitecture architecture, bool interpreter, byte[] encoded, uint version) { MockTarget.Architecture arch = new() From 51a58db462e46e6fab1f34e1d5dc9f0415cfd8b8 Mon Sep 17 00:00:00 2001 From: David Wrighton Date: Wed, 4 Nov 2026 00:25:02 +0000 Subject: [PATCH 10/21] Normalize cDAC GCInfo inspection stack bases Keep ISOSDacInterface18 stack-base semantics independent of decoder enums and GCInfo versions. Document the existing API values and cover v5/v6 decoding, native COM output, and unsupported bases. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/coreclr/inc/sospriv.idl | 1 + .../ISOSDacInterface.cs | 1 + .../SOSDacImpl.cs | 7 ++- .../cdac/tests/UnitTests/GCInfoTests.cs | 61 +++++++++++++++++-- 4 files changed, 63 insertions(+), 7 deletions(-) diff --git a/src/coreclr/inc/sospriv.idl b/src/coreclr/inc/sospriv.idl index dd32bf649ec868..5346fe38e9adb6 100644 --- a/src/coreclr/inc/sospriv.idl +++ b/src/coreclr/inc/sospriv.idl @@ -701,6 +701,7 @@ typedef struct _SOSGCSlotLifetime int IsRegister; unsigned int RegisterNumber; int SpOffset; + // 0 = SP-relative; 1 = relative to SOSGCInfoHeader.StackBaseRegister. Ignored for register slots. unsigned int BaseRegister; unsigned int GcFlags; } SOSGCSlotLifetime; diff --git a/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Legacy/ISOSDacInterface.cs b/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Legacy/ISOSDacInterface.cs index dd2ce0fbbacb3c..072cfc33c8fd5a 100644 --- a/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Legacy/ISOSDacInterface.cs +++ b/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Legacy/ISOSDacInterface.cs @@ -1312,6 +1312,7 @@ public struct SOSGCSlotLifetime public int IsRegister; public uint RegisterNumber; public int SpOffset; + // 0 = SP-relative; 1 = relative to SOSGCInfoHeader.StackBaseRegister. Ignored for register slots. public uint BaseRegister; public uint GcFlags; } diff --git a/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Legacy/SOSDacImpl.cs b/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Legacy/SOSDacImpl.cs index 94a91fa8a55421..704fc38da7d907 100644 --- a/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Legacy/SOSDacImpl.cs +++ b/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Legacy/SOSDacImpl.cs @@ -7752,7 +7752,12 @@ int ISOSDacInterface18.GetGCInfoSlotLifetimes( IsRegister = slot.IsRegister ? 1 : 0, RegisterNumber = slot.RegisterNumber, SpOffset = slot.SpOffset, - BaseRegister = slot.BaseRegister, + BaseRegister = slot.IsRegister ? 0u : slot.BaseRegister switch + { + 1 => 0u, + 2 => 1u, + _ => throw new InvalidOperationException($"Unexpected GC stack slot base {slot.BaseRegister}."), + }, GcFlags = slot.GcFlags, }; } diff --git a/src/native/managed/cdac/tests/UnitTests/GCInfoTests.cs b/src/native/managed/cdac/tests/UnitTests/GCInfoTests.cs index aaefa6920a24b0..2b6066f0848e79 100644 --- a/src/native/managed/cdac/tests/UnitTests/GCInfoTests.cs +++ b/src/native/managed/cdac/tests/UnitTests/GCInfoTests.cs @@ -45,6 +45,11 @@ public void StackSlotsUseFlagsThenBaseThenOffset(RuntimeInfoArchitecture archite Assert.Equal(0u, slots[i].BeginOffset); Assert.Equal(decoder.GetCodeLength(), slots[i].EndOffset); } + + SOSGCSlotLifetime[] inspected = InspectGCInfoSlots(architecture, interpreter, decoder, 6); + Assert.Equal(slots.Count, inspected.Length); + for (int i = 0; i < inspected.Length; i++) + Assert.Equal(wasm ? 1u : (uint)(i % 2), inspected[i].BaseRegister); } [Theory] @@ -186,6 +191,10 @@ public void NonWasmVersion5StackSlotsRemainReadable(bool interpreter, byte[] enc Assert.Equal(0u, slot.BeginOffset); Assert.Equal(2u, slot.EndOffset); }); + + SOSGCSlotLifetime[] inspected = InspectGCInfoSlots(RuntimeInfoArchitecture.X64, interpreter, decoder, 5); + Assert.Equal(0u, inspected[0].BaseRegister); + Assert.Equal(1u, inspected[1].BaseRegister); } [Theory] @@ -249,7 +258,8 @@ public void QueryInterfaceFromIXCLRDataProcess_ExposesGCInfo(MockTarget.Architec Assert.Equal(3u, needed); Assert.Equal(1, lifetimes[0].IsRegister); Assert.Equal(-24, lifetimes[1].SpOffset); - Assert.Equal(1u, lifetimes[2].BaseRegister); + Assert.Equal(1u, lifetimes[1].BaseRegister); + Assert.Equal(0u, lifetimes[2].BaseRegister); } finally { @@ -344,8 +354,8 @@ public void GetGCInfoTables_RespectBufferSizes(int count) { Assert.NotNull(lifetimes); Assert.Equal(new SOSGCSlotLifetime { BeginOffset = 4, EndOffset = 8, IsRegister = 1, RegisterNumber = 3, GcFlags = 3 }, lifetimes[0]); - Assert.Equal(new SOSGCSlotLifetime { BeginOffset = 0, EndOffset = 128, SpOffset = -24, BaseRegister = 2, GcFlags = 6 }, lifetimes[1]); - Assert.Equal(new SOSGCSlotLifetime { BeginOffset = 16, EndOffset = 20, SpOffset = 40, BaseRegister = 1, GcFlags = 1 }, lifetimes[2]); + Assert.Equal(new SOSGCSlotLifetime { BeginOffset = 0, EndOffset = 128, SpOffset = -24, BaseRegister = 1, GcFlags = 6 }, lifetimes[1]); + Assert.Equal(new SOSGCSlotLifetime { BeginOffset = 16, EndOffset = 20, SpOffset = 40, BaseRegister = 0, GcFlags = 1 }, lifetimes[2]); } if (ranges is not null) Assert.All(ranges.AsSpan(count >= 2 ? 2 : 0).ToArray(), value => Assert.Equal(default, value)); @@ -445,14 +455,33 @@ public void GetGCInfo_InitializesOutputsOnFailure(ulong ip, int expectedHResult) Assert.Equal(0u, needed); } + [Theory] + [InlineData(0u)] + [InlineData(3u)] + public void GetGCInfoSlotLifetimes_RejectsUnsupportedStackBases(uint slotBase) + { + MockTarget.Architecture arch = new() { Is64Bit = true, IsLittleEndian = true }; + ISOSDacInterface18 sos = CreateGCInfoInterface(arch, CodeKind.Jitted, (_, gcInfo, handle) => + { + gcInfo.Setup(g => g.GetSlotLifetimes(handle)).Returns(new GCSlotLifetime[] + { + new(false, 0, 8, slotBase, 0, 0, 128), + }); + }); + SOSGCSlotLifetime[] result = [new() { SpOffset = 123 }]; + uint needed = 0; + Assert.Equal(HResults.COR_E_INVALIDOPERATION, sos.GetGCInfoSlotLifetimes(MethodIP, 1, result, &needed)); + Assert.Equal(123, result[0].SpOffset); + } + private static ISOSDacInterface18 CreateGCInfoInterface( MockTarget.Architecture arch, CodeKind codeKind, - Action, Mock, IGCInfoHandle>? configure = null) + Action, Mock, IGCInfoHandle>? configure = null, + uint version = 6) { CodeBlockHandle codeBlock = new(new TargetPointer(0x30000)); TargetPointer gcInfoAddress = new(0x20000); - uint version = 6; Mock executionManager = new(MockBehavior.Strict); executionManager.Setup(e => e.GetCodeBlockHandle(new TargetCodePointer(MethodIP))).Returns(codeBlock); executionManager.Setup(e => e.GetCodeKind(new TargetCodePointer(MethodIP))).Returns(codeKind); @@ -464,7 +493,7 @@ private static ISOSDacInterface18 CreateGCInfoInterface( else gcInfo.Setup(g => g.DecodePlatformSpecificGCInfo(gcInfoAddress, version)).Returns(handle); gcInfo.Setup(g => g.GetHeader(handle)).Returns(new GCInfoHeader( - 6, 128, 0, 5, 0, false, false, false, null, 0, 0, null, null, GenericsContextKind.None)); + version, 128, 0, 5, 0, false, false, false, null, 0, 0, null, null, GenericsContextKind.None)); gcInfo.Setup(g => g.GetInterruptibleRanges(handle)).Returns(new InterruptibleRange[] { new(4, 12), new(16, 20) }); gcInfo.Setup(g => g.GetSafePoints(handle)).Returns(new uint[] { 8, 24 }); gcInfo.Setup(g => g.GetSlotLifetimes(handle)).Returns(new GCSlotLifetime[] @@ -482,6 +511,26 @@ private static ISOSDacInterface18 CreateGCInfoInterface( return Assert.IsAssignableFrom(new SOSDacImpl(target, legacyObj: null, new())); } + private static SOSGCSlotLifetime[] InspectGCInfoSlots( + RuntimeInfoArchitecture architecture, bool interpreter, IGCInfoDecoder decoder, uint version) + { + MockTarget.Architecture arch = new() + { + IsLittleEndian = true, + Is64Bit = architecture is not (RuntimeInfoArchitecture.Arm or RuntimeInfoArchitecture.Wasm), + }; + ISOSDacInterface18 sos = CreateGCInfoInterface( + arch, interpreter ? CodeKind.Interpreter : CodeKind.ReadyToRun, + (_, gcInfo, handle) => gcInfo.Setup(g => g.GetSlotLifetimes(handle)).Returns(decoder.GetSlotLifetimes()), + version); + uint needed = 0; + Assert.Equal(HResults.S_FALSE, sos.GetGCInfoSlotLifetimes(MethodIP, 0, null, &needed)); + SOSGCSlotLifetime[] result = new SOSGCSlotLifetime[needed]; + Assert.Equal(HResults.S_OK, sos.GetGCInfoSlotLifetimes(MethodIP, needed, result, &needed)); + + return result; + } + private static IGCInfoDecoder CreateDecoder(RuntimeInfoArchitecture architecture, bool interpreter, byte[] encoded, uint version) { MockTarget.Architecture arch = new() From 5b29fbfe256ff4bd8b4c86c9e3a64d018e314f0a Mon Sep 17 00:00:00 2001 From: David Wrighton Date: Wed, 4 Nov 2026 19:00:49 +0000 Subject: [PATCH 11/21] Fix packed Wasm unwind decoding in the NativeAOT object writer Decode the JIT's interleaved unwind fields before emitting NativeAOT xdata and pdata. This fixes the Checked WASI frame-size assertion exposed by NativeAOT test compilation. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../Compiler/ObjectWriter/WasmRelocatableObjectWriter.cs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmRelocatableObjectWriter.cs b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmRelocatableObjectWriter.cs index aabcce56b67d42..3c04dfddce83be 100644 --- a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmRelocatableObjectWriter.cs +++ b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmRelocatableObjectWriter.cs @@ -641,9 +641,13 @@ private protected override void EmitUnwindInfo( for (int i = 0; i < frames.Length; i++) { FrameInfo frame = frames[i]; - uint frameSize = checked((uint)DwarfHelper.ReadULEB128(frame.BlobData, out int bytesRead)); + // The JIT interleaves frame size / 16 and virtual IP span / 2 in one ULEB128. + ulong encoded = DwarfHelper.ReadULEB128(frame.BlobData); + uint frameSize = (uint)((encoded & 0xF) | (((encoded >> 8) & 0xF) << 4) | + (((encoded >> 16) & 0xFFFF) << 8)) * 16; Debug.Assert(frameSize % _nodeFactory.Target.PointerSize == 0); - uint virtualSize = checked((uint)DwarfHelper.ReadULEB128(frame.BlobData.AsSpan(bytesRead))); + uint virtualSize = (uint)(((encoded >> 4) & 0xF) | (((encoded >> 12) & 0xF) << 4) | + (((encoded >> 32) & 0xFFFF) << 8)) * 2; Debug.Assert(virtualSize != 0); uint virtualStart = _nextVirtualIP; _nextVirtualIP = checked(virtualStart + virtualSize); From 1b659567c49dfb71fd688367ef6b7acb8bf8ff29 Mon Sep 17 00:00:00 2001 From: David Wrighton Date: Wed, 4 Nov 2026 19:01:59 +0000 Subject: [PATCH 12/21] Preserve the register-presence bit in legacy interpreter GCInfo Consume the pre-v6 register-presence bit even when interpreter traits prohibit register slots. Correct the v5 interpreter fixture so it detects lost stack roots. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../Contracts/GCInfo/GCInfoDecoder.cs | 2 +- src/native/managed/cdac/tests/UnitTests/GCInfoTests.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/GCInfoDecoder.cs b/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/GCInfoDecoder.cs index 8e0586dcf18afd..81982c678cd207 100644 --- a/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/GCInfoDecoder.cs +++ b/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/GCInfoDecoder.cs @@ -216,7 +216,7 @@ private GcSlotFlags ReadSlotFlags(GcSlotFlags previousFlags, bool first) private IEnumerable DecodeSlotTable() { - if (TTraits.HAS_REGISTER_SLOTS && _reader.ReadBits(1, ref _bitOffset) != 0) + if ((_gcVersion < 6 || TTraits.HAS_REGISTER_SLOTS) && _reader.ReadBits(1, ref _bitOffset) != 0) { _numRegisters = _reader.DecodeVarLengthUnsigned(TTraits.NUM_REGISTERS_ENCBASE, ref _bitOffset); } diff --git a/src/native/managed/cdac/tests/UnitTests/GCInfoTests.cs b/src/native/managed/cdac/tests/UnitTests/GCInfoTests.cs index 2b6066f0848e79..5e68a7e2150504 100644 --- a/src/native/managed/cdac/tests/UnitTests/GCInfoTests.cs +++ b/src/native/managed/cdac/tests/UnitTests/GCInfoTests.cs @@ -172,7 +172,7 @@ void WriteUnsigned(int value, int encodingBase) [Theory] [InlineData(false, new byte[] { 0x0A, 0x80, 0xB0, 0x10, 0x88, 0x00 })] - [InlineData(true, new byte[] { 0x0A, 0x40, 0x58, 0x08, 0x44 })] + [InlineData(true, new byte[] { 0x0A, 0x80, 0xB0, 0x10, 0x88, 0x00 })] public void NonWasmVersion5StackSlotsRemainReadable(bool interpreter, byte[] encoded) { IGCInfoDecoder decoder = CreateDecoder(RuntimeInfoArchitecture.X64, interpreter, encoded, 5); From 31e4b5797e382c0c2c3b0fcbf9dd281de248b6e6 Mon Sep 17 00:00:00 2001 From: David Wrighton Date: Wed, 4 Nov 2026 19:01:59 +0000 Subject: [PATCH 13/21] Denormalize reverse-PInvoke frame offsets in the R2R GCInfo reader Report byte offsets consistently with other special stack slots and the native decoder. Cover both positive and negative Wasm offsets. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../aot/ILCompiler.ReadyToRun.Tests/GcInfoDecoderTests.cs | 3 ++- .../tools/aot/ILCompiler.Reflection.ReadyToRun/Amd64/GcInfo.cs | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/GcInfoDecoderTests.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/GcInfoDecoderTests.cs index ef412b4623a589..e86729b51a1778 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/GcInfoDecoderTests.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/GcInfoDecoderTests.cs @@ -332,7 +332,8 @@ public void WasmFatHeaderPreservesGenericContext(byte[] encoded) [Theory] [InlineData(new byte[] { 0x09, 0x08, 0x20, 0x00 }, 8, uint.MaxValue, -1, 0u)] [InlineData(new byte[] { 0x01, 0x09, 0x01, 0x00 }, -1, 1u, -1, 0u)] - [InlineData(new byte[] { 0x01, 0x0A, 0x03, 0x00 }, -1, uint.MaxValue, 3, 0u)] + [InlineData(new byte[] { 0x01, 0x0A, 0x03, 0x00 }, -1, uint.MaxValue, 12, 0u)] + [InlineData(new byte[] { 0x01, 0x0A, 0x0D, 0x00 }, -1, uint.MaxValue, -12, 0u)] [InlineData(new byte[] { 0x01, 0x08, 0x01 }, -1, uint.MaxValue, -1, 1u)] public void WasmFatHeaderPreservesOptionalFields(byte[] encoded, int cookieOffset, uint preservedArea, int reversePInvokeOffset, uint safePoints) diff --git a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Amd64/GcInfo.cs b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Amd64/GcInfo.cs index 51d9834bffd641..a37a5e45d8d883 100644 --- a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Amd64/GcInfo.cs +++ b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Amd64/GcInfo.cs @@ -170,7 +170,7 @@ public GcInfo(NativeReader imageReader, int offset, Machine machine, int version if (_hasReversePInvokeFrame) { - ReversePInvokeFrameStackSlot = imageReader.DecodeVarLengthSigned(_gcInfoTypes.REVERSE_PINVOKE_FRAME_ENCBASE, ref bitOffset); + ReversePInvokeFrameStackSlot = _gcInfoTypes.DenormalizeStackSlot(imageReader.DecodeVarLengthSigned(_gcInfoTypes.REVERSE_PINVOKE_FRAME_ENCBASE, ref bitOffset)); } if (_gcInfoTypes.HAS_FIXED_STACK_PARAMETER_SCRATCH_AREA && !_slimHeader) From ddee9c77b3bc882efd665fb7490440fe786a9889 Mon Sep 17 00:00:00 2001 From: David Wrighton Date: Wed, 4 Nov 2026 19:01:59 +0000 Subject: [PATCH 14/21] Document the GCInfo v6 slot-table encoding Describe shrinking flags-first descriptors, bounded register integers, compact stack bases, grouped offsets, and version-specific count bits. Keep the non-Wasm v5 algorithms explicitly labeled as legacy. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/design/datacontracts/GCInfo.md | 121 +++++++++++++++++++++++++--- 1 file changed, 109 insertions(+), 12 deletions(-) diff --git a/docs/design/datacontracts/GCInfo.md b/docs/design/datacontracts/GCInfo.md index 3fb68b5bbe9b44..7d862ee2c17d34 100644 --- a/docs/design/datacontracts/GCInfo.md +++ b/docs/design/datacontracts/GCInfo.md @@ -603,16 +603,121 @@ for each range: The slot table describes all GC-tracked locations used by the method. It has three sections decoded in order: register slots, tracked stack slots, and untracked stack slots. -**Slot counts** are encoded with presence bits: +**Slot counts** are encoded with presence bits. GCInfo v6 omits the +register-presence bit for the interpreter and Wasm platform encoding, which +cannot contain register slots. Non-Wasm v5 retains that bit, including the +always-zero bit in interpreter data. ``` -if ReadBits(1): // has register slots - numRegisters = DecodeVarLengthUnsigned(NUM_REGISTERS_ENCBASE) +numRegisters = 0 +numStackSlots = 0 +numUntrackedSlots = 0 +if gcVersion < 6 or HAS_REGISTER_SLOTS: + if ReadBits(1): // has register slots + numRegisters = DecodeVarLengthUnsigned(NUM_REGISTERS_ENCBASE) if ReadBits(1): // has stack/untracked slots numStackSlots = DecodeVarLengthUnsigned(NUM_STACK_SLOTS_ENCBASE) numUntrackedSlots = DecodeVarLengthUnsigned(NUM_UNTRACKED_SLOTS_ENCBASE) ``` +The semantic slot flags are: + +| Flag | Value | Meaning | +| --- | --- | --- | +| `GC_SLOT_BASE` | 0x0 | Normal object reference | +| `GC_SLOT_INTERIOR` | 0x1 | Interior pointer (points inside an object) | +| `GC_SLOT_PINNED` | 0x2 | Pinned object reference | + +###### GCInfo v6 slot descriptors + +Flags precede locations. Each section is ordered by descending encoded flags. +For Wasm platform slots only, the encoded flags are the semantic flags XOR +`GC_SLOT_PINNED`; decoding reverses that transformation. This makes pinned +object roots the implicit-zero group on Wasm. + +The first descriptor in each section has two flag bits. Subsequent descriptors +have two bits after encoded flags with the pinned bit set, one bit after encoded +interior-only flags, and no bits after encoded flags zero. Sorting guarantees +that a later descriptor cannot need a flag bit that has become implicit. + +``` +ReadSlotFlags(previousFlags, first): + flagsXor = USES_COMPACT_WASM_HEADER ? GC_SLOT_PINNED : 0 + previousEncodedFlags = previousFlags XOR flagsXor + if first or previousEncodedFlags != 0: + numBits = (first or (previousEncodedFlags & GC_SLOT_PINNED) != 0) ? 2 : 1 + encodedFlags = ReadBits(numBits) + else: + encodedFlags = 0 + return encodedFlags XOR flagsXor +``` + +**Register slots** use an absolute register number at the start of each flag +group, followed by gap-minus-one deltas within that group. Register integers +use a bounded encoding rather than the ordinary variable-length encoding: +read `base + 1` bits, then, if the high bit is set, read exactly +`REGISTER_BITS - base` more bits. `REGISTER_BITS` is four on ARM and five on +the other register-bearing platforms supported by this decoder. + +``` +ReadRegisterValue(base): + chunk = ReadBits(base + 1) + value = chunk & ((1 << base) - 1) + if (chunk & (1 << base)) != 0: + value |= ReadBits(REGISTER_BITS - base) << base + return value + +previousFlags = 0 +regNum = 0 +for i = 0; i < numRegisters; i++: + flags = ReadSlotFlags(previousFlags, i == 0) + absolute = i == 0 or flags != previousFlags + base = absolute ? REGISTER_ENCBASE : REGISTER_DELTA_ENCBASE + value = ReadRegisterValue(base) + regNum = absolute ? value : regNum + value + 1 + emit register slot(regNum, flags) + previousFlags = flags +``` + +**Stack slots** are ordered by flags, then base (SP before frame register), then +signed normalized offset. A single bit selects the base: zero for SP-relative +and one for frame-register-relative. Caller-SP-relative slots are not encoded. +Wasm platform slots omit this bit and are implicitly frame-relative. + +Offsets are signed absolute values at the first slot or any flag/base change; +within a flag/base group, offsets use unsigned deltas without a bias. +Decode the tracked and untracked sections separately, resetting flags, base, +and offset state at the beginning of each section. + +``` +DecodeStackSlots(count, isUntracked): + previousFlags = 0 + previousBase = SP_REL + normOffset = 0 + for i = 0; i < count; i++: + flags = ReadSlotFlags(previousFlags, i == 0) + slotBase = (HAS_STACK_SLOT_BASE and ReadBits(1) == 0) ? SP_REL : FRAMEREG_REL + if i == 0 or flags != previousFlags or slotBase != previousBase: + normOffset = DecodeVarLengthSigned(STACK_SLOT_ENCBASE) + else: + normOffset += DecodeVarLengthUnsigned(STACK_SLOT_DELTA_ENCBASE) + emit stack slot(DenormalizeStackSlot(normOffset), slotBase, flags, isUntracked) + previousFlags = flags + previousBase = slotBase + +DecodeStackSlots(numStackSlots, false) +DecodeStackSlots(numUntrackedSlots, true) +``` + +`HAS_STACK_SLOT_BASE` is false only for Wasm platform slots. Stack-slot +denormalization converts Wasm offsets from four-byte pointer units to bytes; +the interpreter retains byte offsets on every architecture. + +###### Legacy non-Wasm GCInfo v5 slot descriptors + +The following algorithms apply only to the retained non-Wasm v5 decoding path, +not to current v6 data. Locations precede flags and stack bases occupy two bits. + **Register slots** use delta encoding when consecutive slots share the same flags: ``` @@ -648,15 +753,7 @@ else: // flags inherited from previous ``` -Untracked slots use the same encoding as tracked stack slots. - -The 2-bit slot flags are: - -| Flag | Value | Meaning | -| --- | --- | --- | -| `GC_SLOT_BASE` | 0x0 | Normal object reference | -| `GC_SLOT_INTERIOR` | 0x1 | Interior pointer (points inside an object) | -| `GC_SLOT_PINNED` | 0x2 | Pinned object reference | +Untracked slots use the same legacy encoding as tracked stack slots. ##### 4. Live State Data From ac165a313dc00d33fb50cea9b43647893e02c65e Mon Sep 17 00:00:00 2001 From: David Wrighton Date: Wed, 4 Nov 2026 19:02:17 +0000 Subject: [PATCH 15/21] Identify the GCInfo v6 decoder helpers Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../Contracts/GCInfo/GCInfoDecoder.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/GCInfoDecoder.cs b/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/GCInfoDecoder.cs index 81982c678cd207..d94588f358558a 100644 --- a/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/GCInfoDecoder.cs +++ b/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/GCInfoDecoder.cs @@ -189,6 +189,7 @@ private IEnumerable DecodeBody() yield return DecodePoints.SlotTable; } + // GCInfo v6 bounded register decoding. private uint ReadRegisterValue(int encodingBase) { uint chunk = (uint)_reader.ReadBits(encodingBase + 1, ref _bitOffset); @@ -331,6 +332,7 @@ private IEnumerable DecodeSlotTable() yield break; } + // GCInfo v6 stack-slot decoding. private void DecodeStackSlots(uint count, bool isUntracked) { GcSlotFlags flags = 0; From 534f2f3ded456b280c3492a952a67e018406adc8 Mon Sep 17 00:00:00 2001 From: David Wrighton Date: Wed, 4 Nov 2026 19:03:47 +0000 Subject: [PATCH 16/21] Select compact stack-slot decoding by GCInfo version Wasm platform GCInfo supports only v6, so its traits need not override the version check used by the other platforms. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../Contracts/GCInfo/GCInfoDecoder.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/GCInfoDecoder.cs b/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/GCInfoDecoder.cs index d94588f358558a..49d35ba839592d 100644 --- a/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/GCInfoDecoder.cs +++ b/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/GCInfoDecoder.cs @@ -258,7 +258,7 @@ private IEnumerable DecodeSlotTable() } } - if (TTraits.USES_COMPACT_WASM_HEADER || _gcVersion >= 6) + if (_gcVersion >= 6) { DecodeStackSlots(numStackSlots, isUntracked: false); DecodeStackSlots(_numUntrackedSlots, isUntracked: true); From 367e29929759cca08fcc9883890a46bed0cd97b8 Mon Sep 17 00:00:00 2001 From: David Wrighton Date: Wed, 4 Nov 2026 19:03:48 +0000 Subject: [PATCH 17/21] Map .NET 12 to GCInfo v6 in SOS Preserve GCInfo v5 for .NET 11 and the existing mappings for earlier runtimes. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/coreclr/inc/gcinfo.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/coreclr/inc/gcinfo.h b/src/coreclr/inc/gcinfo.h index 6161bab6023395..4fdece65a26fa8 100644 --- a/src/coreclr/inc/gcinfo.h +++ b/src/coreclr/inc/gcinfo.h @@ -46,8 +46,10 @@ inline int GCInfoVersion() // In SOS we only care about ability to parse/dump the GC Info. // Since v2 and v3 had the same file format and v1 is no longer supported, // we can assume that everything before net10.0 uses GCInfo v3. - if (IsRuntimeVersionAtLeast(11)) + if (IsRuntimeVersionAtLeast(12)) return 6; + if (IsRuntimeVersionAtLeast(11)) + return 5; if (IsRuntimeVersionAtLeast(10)) return 4; return 3; From 76899d02441ba8eecc99e6323d71a5537db50113 Mon Sep 17 00:00:00 2001 From: David Wrighton Date: Wed, 4 Nov 2026 19:43:18 +0000 Subject: [PATCH 18/21] Fix pre-existing GCInfo decoder correctness issues Correct architecture-specific frame registers, transition scaling and range mapping, indirect live-state payload sizes, ARM64 EnC header parsing, and lazy cDAC outgoing-area decoding. Add regressions using the existing v5 format. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../GcInfoRegressionTests.cs | 231 ++++++++++++++++++ .../Amd64/GcInfo.cs | 42 ++-- .../GCInfoTypes.cs | 5 +- .../Contracts/GCInfo/GCInfoDecoder.cs | 2 +- .../cdac/tests/UnitTests/GCInfoHeaderTests.cs | 57 +++++ 5 files changed, 318 insertions(+), 19 deletions(-) create mode 100644 src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/GcInfoRegressionTests.cs create mode 100644 src/native/managed/cdac/tests/UnitTests/GCInfoHeaderTests.cs diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/GcInfoRegressionTests.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/GcInfoRegressionTests.cs new file mode 100644 index 00000000000000..1071cf23226d81 --- /dev/null +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/GcInfoRegressionTests.cs @@ -0,0 +1,231 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection.PortableExecutable; +using ILCompiler.Reflection.ReadyToRun; +using ILCompiler.Reflection.ReadyToRun.Amd64; +using Xunit; + +namespace ILCompiler.ReadyToRun.Tests; + +public class GcInfoRegressionTests +{ + [Theory] + [InlineData(Machine.LoongArch64, 0, 22u)] + [InlineData(Machine.LoongArch64, 1, 3u)] + [InlineData(Machine.RiscV64, 0, 8u)] + [InlineData(Machine.RiscV64, 1, 2u)] + [InlineData(Machine.RiscV64, 10, 2u)] + public void FatHeaderDenormalizesFrameRegister(Machine machine, int encodedRegister, uint expectedRegister) + { + BitWriter writer = new(); + WriteFatHeader(writer, machine, 0x41); + writer.WriteUnsigned(encodedRegister, 2); + writer.WriteUnsigned(0, 3); + writer.WriteUnsigned(0, 3); + writer.WriteUnsigned(0, 1); + writer.Write(0, 2); + + GcInfo info = Decode(writer, machine); + Assert.Equal(expectedRegister, info.StackBaseRegister); + Assert.Empty(info.SlotTable.GcSlots); + Assert.Equal(writer.ByteCount, info.Size); + } + + [Theory] + [InlineData(2)] + [InlineData(33)] + public void Arm64EnCHeaderConsumesFixedFrameSize(int fixedFrameSize) + { + BitWriter writer = new(); + WriteFatHeader(writer, Machine.Arm64, 0x101); + writer.WriteUnsigned(1, 4); + writer.WriteUnsigned(fixedFrameSize, 4); + writer.WriteUnsigned(3, 3); + writer.WriteUnsigned(0, 3); + writer.WriteUnsigned(0, 1); + writer.Write(0, 2); + + GcInfo info = Decode(writer, Machine.Arm64); + Assert.Equal(1u, info.SizeOfEditAndContinuePreservedArea); + Assert.Equal(24u, info.SizeOfStackOutgoingAndScratchArea); + Assert.Equal(0u, info.NumSafePoints); + Assert.Equal(0u, info.NumInterruptibleRanges); + Assert.Empty(info.SlotTable.GcSlots); + Assert.Equal(writer.ByteCount, info.Size); + } + + public static IEnumerable TransitionCases() + { + foreach ((Machine machine, int instructionSize) in new[] + { + (Machine.Amd64, 1), + (Machine.ArmThumb2, 2), + (Machine.Arm64, 4), + (Machine.LoongArch64, 4), + (Machine.RiscV64, 2), + }) + { + yield return [machine, instructionSize, Array.Empty<(int, int)>(), 4, 4]; + yield return [machine, instructionSize, new[] { (8, 16) }, 4, 12]; + foreach ((int transition, int expected) in new[] { (3, 3), (4, 20), (9, 41) }) + yield return [machine, instructionSize, new[] { (0, 4), (20, 24), (40, 44) }, transition, expected]; + } + } + + [Theory] + [MemberData(nameof(TransitionCases))] + public void TransitionsMapNormalizedOffsetsAcrossRanges( + Machine machine, int instructionSize, (int Start, int Stop)[] ranges, int transition, int expected) + { + BitWriter writer = new(); + WriteFatHeader(writer, machine, 0, codeLength: 64); + writer.WriteUnsigned(0, 3); + writer.WriteUnsigned(0, machine == Machine.Amd64 ? 2 : 3); + writer.WriteUnsigned(ranges.Length, machine == Machine.ArmThumb2 ? 2 : 1); + int previousStop = 0; + foreach ((int start, int stop) in ranges) + { + writer.WriteUnsigned(start - previousStop, machine == Machine.ArmThumb2 ? 4 : 6); + writer.WriteUnsigned(stop - start - 1, 6); + previousStop = stop; + } + writer.Write(1, 1); + writer.WriteUnsigned(1, machine is Machine.Amd64 or Machine.ArmThumb2 ? 2 : 3); + writer.Write(0, 1); + writer.WriteUnsigned(0, machine == Machine.ArmThumb2 ? 2 : 3); + writer.Write(0, 2); + writer.WriteUnsigned(1, 3); + writer.Write(1, 1); + writer.Align(); + writer.Write(0, 1); // Simple could-be-live bitmap. + writer.Write(1, 1); + writer.Write(1, 1); // Final state is live. + writer.Write(1, 1); + writer.Write(transition, 6); + writer.Write(0, 1); + + GcInfo info = Decode(writer, machine); + KeyValuePair> entry = Assert.Single(info.Transitions); + Assert.Equal(expected * instructionSize, entry.Key); + Assert.Equal(entry.Key, Assert.Single(entry.Value).CodeOffset); + Assert.Equal(writer.ByteCount, info.Size); + } + + [Theory] + [InlineData(false, false)] + [InlineData(false, true)] + [InlineData(true, false)] + [InlineData(true, true)] + public void IndirectSafePointSizeIncludesEveryReferencedState(bool runLengthEncoded, bool highestStateLast) + { + BitWriter writer = new(); + writer.Write(0, 1); + writer.Write(1, 1); + writer.WriteUnsigned(128, 8); + writer.WriteUnsigned(64, 2); + for (int i = 1; i <= 64; i++) + writer.Write(i, 7); + writer.Write(0, 1); + writer.Write(1, 1); + writer.WriteUnsigned(32, 2); + writer.WriteUnsigned(0, 1); + for (int slot = 0; slot < 32; slot++) + { + writer.Write(1, 2); // SP-relative stack slot. + writer.WriteUnsigned(slot == 0 ? 0 : 1, slot == 0 ? 6 : 4); + if (slot == 0) + writer.Write(0, 2); + } + writer.Write(1, 1); + writer.WriteUnsigned(5, 3); // Six-bit indirect state offsets. + int firstStateSize = runLengthEncoded ? 12 : 33; + for (int i = 0; i < 64; i++) + writer.Write(i == (highestStateLast ? 63 : 0) ? firstStateSize : 0, 6); + writer.Align(); + for (int state = 0; state < 2; state++) + { + writer.Write(runLengthEncoded ? 1 : 0, 1); + if (runLengthEncoded) + { + writer.Write(0, 1); + writer.WriteUnsigned(state == 0 ? 32 : 0, 4); + if (state != 0) + writer.WriteUnsigned(31, 2); + } + else + { + for (int slot = 0; slot < 32; slot++) + writer.Write((slot + state) % 2, 1); + } + } + + GcInfo info = Decode(writer, Machine.Amd64); + Assert.Equal(64, info.LiveSlotsAtSafepoints.Count); + if (runLengthEncoded) + { + Assert.Equal(highestStateLast ? 0 : 32, info.LiveSlotsAtSafepoints[0].Count); + Assert.Equal(highestStateLast ? 32 : 0, info.LiveSlotsAtSafepoints[63].Count); + } + else + { + Assert.Equal(16, info.LiveSlotsAtSafepoints[0].Count); + Assert.Equal(16, info.LiveSlotsAtSafepoints[63].Count); + Assert.Same(info.SlotTable.GcSlots[highestStateLast ? 1 : 0], info.LiveSlotsAtSafepoints[0][0]); + } + Assert.Equal(writer.ByteCount, info.Size); + } + + private static void WriteFatHeader(BitWriter writer, Machine machine, int flags, int codeLength = 8) + { + writer.Write(1, 1); + writer.Write(flags, 10); + writer.WriteUnsigned(codeLength, machine == Machine.ArmThumb2 ? 7 : 8); + } + + private static GcInfo Decode(BitWriter writer, Machine machine) + { + using MemoryStream stream = new(writer.ToArray()); + + return new GcInfo(new NativeReader(stream), 0, machine, 5); + } + + private sealed class BitWriter + { + private readonly List _bytes = []; + private int _bitCount; + + public int ByteCount => (_bitCount + 7) / 8; + + public void Write(int value, int count) + { + for (int i = 0; i < count; i++, _bitCount++) + { + if (_bitCount % 8 == 0) + _bytes.Add(0); + _bytes[^1] |= (byte)(((value >> i) & 1) << (_bitCount % 8)); + } + } + + public void WriteUnsigned(int value, int encodingBase) + { + do + { + int chunk = value & ((1 << encodingBase) - 1); + value >>>= encodingBase; + Write(chunk | (value == 0 ? 0 : 1 << encodingBase), encodingBase + 1); + } while (value != 0); + } + + public void Align() + { + while (_bitCount % 8 != 0) + Write(0, 1); + } + + public byte[] ToArray() => [.. _bytes, .. new byte[8]]; + } +} diff --git a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Amd64/GcInfo.cs b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Amd64/GcInfo.cs index a37a5e45d8d883..cdbf638119d10a 100644 --- a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Amd64/GcInfo.cs +++ b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Amd64/GcInfo.cs @@ -166,6 +166,10 @@ public GcInfo(NativeReader imageReader, int offset, Machine machine, int version if (_hasSizeOfEditAndContinuePreservedArea) { SizeOfEditAndContinuePreservedArea = imageReader.DecodeVarLengthUnsigned(_gcInfoTypes.SIZE_OF_EDIT_AND_CONTINUE_PRESERVED_AREA_ENCBASE, ref bitOffset); + if (_machine == Machine.Arm64) + { + imageReader.DecodeVarLengthUnsigned(_gcInfoTypes.SIZE_OF_EDIT_AND_CONTINUE_FIXED_STACK_FRAME_ENCBASE, ref bitOffset); + } } if (_hasReversePInvokeFrame) @@ -426,6 +430,7 @@ private List> GetLiveSlotsAtSafepoints(NativeReader imageReader } uint offsetTablePos = (uint)bitOffset; + int maxBitOffset = bitOffset; for (uint safePointIndex = 0; safePointIndex < NumSafePoints; safePointIndex++) { @@ -476,6 +481,7 @@ private List> GetLiveSlotsAtSafepoints(NativeReader imageReader report = !report; } Debug.Assert(readSlots == numSlots); + maxBitOffset = Math.Max(maxBitOffset, bitOffset); result.Add(liveSlots); continue; } @@ -507,9 +513,11 @@ private List> GetLiveSlotsAtSafepoints(NativeReader imageReader } } + maxBitOffset = Math.Max(maxBitOffset, bitOffset); result.Add(liveSlots); } + bitOffset = maxBitOffset; return result; } @@ -684,31 +692,33 @@ private Dictionary> UpdateTransitionCodeOffset(List< { Dictionary> updatedTransitions = new Dictionary>(); int cumInterruptibleLength = 0; // the sum of the lengths of all preceding interruptible ranges - using (IEnumerator interruptibleRangesIter = InterruptibleRanges.GetEnumerator()) + int rangeIndex = 0; + foreach (GcTransition transition in transitions) { - interruptibleRangesIter.MoveNext(); - InterruptibleRange currentRange = interruptibleRangesIter.Current; - int currentRangeLength = (int)(currentRange.StopOffset - currentRange.StartOffset); - foreach (GcTransition transition in transitions) + int codeOffset = (int)_gcInfoTypes.DenormalizeCodeOffset((uint)transition.CodeOffset); + if (InterruptibleRanges.Count != 0) { - int codeOffset = transition.CodeOffset + (int)currentRange.StartOffset - cumInterruptibleLength; - if (codeOffset > currentRange.StopOffset) + InterruptibleRange currentRange = InterruptibleRanges[rangeIndex]; + int currentRangeLength = (int)(currentRange.StopOffset - currentRange.StartOffset); + while (codeOffset >= cumInterruptibleLength + currentRangeLength) { cumInterruptibleLength += currentRangeLength; - interruptibleRangesIter.MoveNext(); - currentRange = interruptibleRangesIter.Current; + if (++rangeIndex >= InterruptibleRanges.Count) + throw new BadImageFormatException("GC transition lies outside the interruptible ranges."); + currentRange = InterruptibleRanges[rangeIndex]; currentRangeLength = (int)(currentRange.StopOffset - currentRange.StartOffset); - codeOffset = transition.CodeOffset + (int)currentRange.StartOffset - cumInterruptibleLength; } + codeOffset += (int)currentRange.StartOffset - cumInterruptibleLength; + } - transition.CodeOffset = codeOffset; - if (!updatedTransitions.ContainsKey(codeOffset)) - { - updatedTransitions[codeOffset] = new List(); - } - updatedTransitions[codeOffset].Add(transition); + transition.CodeOffset = codeOffset; + if (!updatedTransitions.ContainsKey(codeOffset)) + { + updatedTransitions[codeOffset] = new List(); } + updatedTransitions[codeOffset].Add(transition); } + return updatedTransitions; } } diff --git a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/GCInfoTypes.cs b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/GCInfoTypes.cs index baa9eef2d7ab67..4d521d80f0ffc0 100644 --- a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/GCInfoTypes.cs +++ b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/GCInfoTypes.cs @@ -100,6 +100,7 @@ public class GcInfoTypes internal int GENERICS_INST_CONTEXT_STACK_SLOT_ENCBASE { get; } = 6; internal int STACK_BASE_REGISTER_ENCBASE { get; } = 3; internal int SIZE_OF_EDIT_AND_CONTINUE_PRESERVED_AREA_ENCBASE { get; } = 4; + internal int SIZE_OF_EDIT_AND_CONTINUE_FIXED_STACK_FRAME_ENCBASE { get; } = 4; internal int REVERSE_PINVOKE_FRAME_ENCBASE { get; } = 6; internal int SIZE_OF_STACK_AREA_ENCBASE { get; } = 3; internal int NUM_SAFE_POINTS_ENCBASE { get; } = 3; @@ -283,9 +284,9 @@ internal uint DenormalizeStackBaseRegister(uint x) case Machine.Arm64: return (x ^ 29); case Machine.LoongArch64: - return ((x ^ 22) & 0x3); + return x == 0 ? 22u : 3u; case Machine.RiscV64: - return (x ^ 8); + return x == 0 ? 8u : 2u; case WasmMachine.Wasm32: return (x ^ 2); } diff --git a/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/GCInfoDecoder.cs b/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/GCInfoDecoder.cs index 49d35ba839592d..117b898c052f57 100644 --- a/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/GCInfoDecoder.cs +++ b/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/GCInfoDecoder.cs @@ -548,13 +548,13 @@ private IEnumerable DecodeFatHeader() _reversePInvokeFrameStackSlot = _headerFlags.HasFlag(GcInfoHeaderFlags.GC_INFO_REVERSE_PINVOKE_FRAME) ? TTraits.DenormalizeStackSlot(_reader.DecodeVarLengthSigned(TTraits.REVERSE_PINVOKE_FRAME_ENCBASE, ref _bitOffset)) : TTraits.NO_REVERSE_PINVOKE_FRAME; - yield return DecodePoints.ReversePInvoke; if (TTraits.HAS_FIXED_STACK_PARAMETER_SCRATCH_AREA) { _fixedStackParameterScratchArea = TTraits.DenormalizeSizeOfStackArea(_reader.DecodeVarLengthUnsigned(TTraits.SIZE_OF_STACK_AREA_ENCBASE, ref _bitOffset)); } + yield return DecodePoints.ReversePInvoke; if (PartiallyInterruptibleGCSupported) { diff --git a/src/native/managed/cdac/tests/UnitTests/GCInfoHeaderTests.cs b/src/native/managed/cdac/tests/UnitTests/GCInfoHeaderTests.cs new file mode 100644 index 00000000000000..8f50c9b1ebaaf3 --- /dev/null +++ b/src/native/managed/cdac/tests/UnitTests/GCInfoHeaderTests.cs @@ -0,0 +1,57 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Microsoft.Diagnostics.DataContractReader.Contracts; +using Microsoft.Diagnostics.DataContractReader.Contracts.GCInfoHelpers; +using Microsoft.Diagnostics.DataContractReader.TestInfrastructure; +using Moq; +using Xunit; + +namespace Microsoft.Diagnostics.DataContractReader.Tests; + +public class GCInfoHeaderTests +{ + [Theory] + [InlineData(RuntimeInfoArchitecture.X64, 24u)] + [InlineData(RuntimeInfoArchitecture.Arm, 12u)] + [InlineData(RuntimeInfoArchitecture.Arm64, 24u)] + [InlineData(RuntimeInfoArchitecture.LoongArch64, 24u)] + [InlineData(RuntimeInfoArchitecture.RiscV64, 24u)] + public void GetHeaderDecodesOutgoingAreaBeforeSlotLifetimes(RuntimeInfoArchitecture architecture, uint expectedSize) + { + MockTarget.Architecture arch = new() + { + IsLittleEndian = true, + Is64Bit = architecture != RuntimeInfoArchitecture.Arm, + }; + TestPlaceholderTarget.Builder builder = new(arch); + const ulong GCInfoAddress = 0x10000; + byte[] encoded = architecture == RuntimeInfoArchitecture.Arm + ? [0x03, 0x40, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00] + : [0x03, 0x40, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00]; + builder.MemoryBuilder.AddHeapFragment(new MockMemorySpace.HeapFragment + { + Address = GCInfoAddress, + Data = encoded, + Name = "Fat GCInfo header with three outgoing stack slots", + }); + Mock runtimeInfo = new(); + runtimeInfo.Setup(c => c.GetTargetArchitecture()).Returns(architecture); + Target target = builder.AddMockContract(runtimeInfo).Build(); + TargetPointer address = new(GCInfoAddress); + IGCInfoDecoder decoder = architecture switch + { + RuntimeInfoArchitecture.X64 => new GcInfoDecoder(target, address, 5), + RuntimeInfoArchitecture.Arm => new GcInfoDecoder(target, address, 5), + RuntimeInfoArchitecture.Arm64 => new GcInfoDecoder(target, address, 5), + RuntimeInfoArchitecture.LoongArch64 => new GcInfoDecoder(target, address, 5), + RuntimeInfoArchitecture.RiscV64 => new GcInfoDecoder(target, address, 5), + _ => throw new System.InvalidOperationException(), + }; + + GCInfoHeader header = decoder.GetHeader(); + Assert.Equal(expectedSize, header.SizeOfStackParameterArea); + Assert.Empty(decoder.GetSlotLifetimes()); + Assert.Equal(expectedSize, decoder.GetHeader().SizeOfStackParameterArea); + } +} From e496a2251f623afa626350e1e2639cc2069ab145 Mon Sep 17 00:00:00 2001 From: David Wrighton Date: Wed, 4 Nov 2026 21:10:09 +0000 Subject: [PATCH 19/21] Preserve the cDAC reverse-PInvoke decoding boundary Add a separate stack-parameter-area decode point for GetHeader while keeping ReversePInvoke aligned with the native decoder. Cover early stopping for generic-context lookups and slim headers. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../Contracts/GCInfo/GCInfoDecoder.cs | 7 ++- .../cdac/tests/UnitTests/GCInfoHeaderTests.cs | 46 +++++++++++++++---- 2 files changed, 41 insertions(+), 12 deletions(-) diff --git a/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/GCInfoDecoder.cs b/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/GCInfoDecoder.cs index 117b898c052f57..a26b2dd500bfb8 100644 --- a/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/GCInfoDecoder.cs +++ b/src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/GCInfoDecoder.cs @@ -22,6 +22,7 @@ private enum DecodePoints GenericInstContext, EditAndContinue, ReversePInvoke, + StackParameterArea, InterruptibleRanges, SlotTable, Complete, @@ -451,6 +452,7 @@ private IEnumerable DecodeSlimHeader() yield return DecodePoints.GenericInstContext; yield return DecodePoints.EditAndContinue; yield return DecodePoints.ReversePInvoke; + yield return DecodePoints.StackParameterArea; if (PartiallyInterruptibleGCSupported && !TTraits.USES_COMPACT_WASM_HEADER) { @@ -548,13 +550,14 @@ private IEnumerable DecodeFatHeader() _reversePInvokeFrameStackSlot = _headerFlags.HasFlag(GcInfoHeaderFlags.GC_INFO_REVERSE_PINVOKE_FRAME) ? TTraits.DenormalizeStackSlot(_reader.DecodeVarLengthSigned(TTraits.REVERSE_PINVOKE_FRAME_ENCBASE, ref _bitOffset)) : TTraits.NO_REVERSE_PINVOKE_FRAME; + yield return DecodePoints.ReversePInvoke; if (TTraits.HAS_FIXED_STACK_PARAMETER_SCRATCH_AREA) { _fixedStackParameterScratchArea = TTraits.DenormalizeSizeOfStackArea(_reader.DecodeVarLengthUnsigned(TTraits.SIZE_OF_STACK_AREA_ENCBASE, ref _bitOffset)); } - yield return DecodePoints.ReversePInvoke; + yield return DecodePoints.StackParameterArea; if (PartiallyInterruptibleGCSupported) { @@ -582,7 +585,7 @@ private void EnsureDecodedTo(DecodePoints point) public GCInfoHeader GetHeader() { - EnsureDecodedTo(DecodePoints.ReversePInvoke); + EnsureDecodedTo(DecodePoints.StackParameterArea); GcInfoHeaderFlags genericsInstContextFlags = _headerFlags & GcInfoHeaderFlags.GC_INFO_HAS_GENERICS_INST_CONTEXT_MASK; SpecialSlot? gsCookie = _gsCookieStackSlot != TTraits.NO_GS_COOKIE ? new SpecialSlot(_gsCookieStackSlot) : null; diff --git a/src/native/managed/cdac/tests/UnitTests/GCInfoHeaderTests.cs b/src/native/managed/cdac/tests/UnitTests/GCInfoHeaderTests.cs index 8f50c9b1ebaaf3..c55b6cdad1cd39 100644 --- a/src/native/managed/cdac/tests/UnitTests/GCInfoHeaderTests.cs +++ b/src/native/managed/cdac/tests/UnitTests/GCInfoHeaderTests.cs @@ -18,6 +18,40 @@ public class GCInfoHeaderTests [InlineData(RuntimeInfoArchitecture.LoongArch64, 24u)] [InlineData(RuntimeInfoArchitecture.RiscV64, 24u)] public void GetHeaderDecodesOutgoingAreaBeforeSlotLifetimes(RuntimeInfoArchitecture architecture, uint expectedSize) + { + byte[] encoded = architecture == RuntimeInfoArchitecture.Arm + ? [0x03, 0x40, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00] + : [0x03, 0x40, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00]; + IGCInfoDecoder decoder = CreateDecoder(architecture, encoded); + + GCInfoHeader header = decoder.GetHeader(); + Assert.Equal(expectedSize, header.SizeOfStackParameterArea); + Assert.Empty(decoder.GetSlotLifetimes()); + Assert.Equal(expectedSize, decoder.GetHeader().SizeOfStackParameterArea); + } + + [Fact] + public void GenericContextLookupStopsBeforeOutgoingArea() + { + // The outgoing-area encoding is deliberately unterminated. + IGCInfoDecoder decoder = CreateDecoder(RuntimeInfoArchitecture.X64, + [0x03, 0x40, 0x80, 0x88, 0x88, 0x88, 0x88, 0x88]); + + Assert.False(decoder.TryGetGenericContextStorage(GenericContextLoc.ThisPtr, 0, out _)); + } + + [Fact] + public void SlimHeaderStopsBeforeSafePointCount() + { + // The safe-point count is deliberately unterminated. + IGCInfoDecoder decoder = CreateDecoder(RuntimeInfoArchitecture.X64, [0x22, 0xF8]); + + GCInfoHeader header = decoder.GetHeader(); + Assert.Equal(8u, header.CodeSize); + Assert.Equal(0u, header.SizeOfStackParameterArea); + } + + private static IGCInfoDecoder CreateDecoder(RuntimeInfoArchitecture architecture, byte[] encoded) { MockTarget.Architecture arch = new() { @@ -26,20 +60,17 @@ public void GetHeaderDecodesOutgoingAreaBeforeSlotLifetimes(RuntimeInfoArchitect }; TestPlaceholderTarget.Builder builder = new(arch); const ulong GCInfoAddress = 0x10000; - byte[] encoded = architecture == RuntimeInfoArchitecture.Arm - ? [0x03, 0x40, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00] - : [0x03, 0x40, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00]; builder.MemoryBuilder.AddHeapFragment(new MockMemorySpace.HeapFragment { Address = GCInfoAddress, Data = encoded, - Name = "Fat GCInfo header with three outgoing stack slots", + Name = "GCInfo header", }); Mock runtimeInfo = new(); runtimeInfo.Setup(c => c.GetTargetArchitecture()).Returns(architecture); Target target = builder.AddMockContract(runtimeInfo).Build(); TargetPointer address = new(GCInfoAddress); - IGCInfoDecoder decoder = architecture switch + return architecture switch { RuntimeInfoArchitecture.X64 => new GcInfoDecoder(target, address, 5), RuntimeInfoArchitecture.Arm => new GcInfoDecoder(target, address, 5), @@ -48,10 +79,5 @@ public void GetHeaderDecodesOutgoingAreaBeforeSlotLifetimes(RuntimeInfoArchitect RuntimeInfoArchitecture.RiscV64 => new GcInfoDecoder(target, address, 5), _ => throw new System.InvalidOperationException(), }; - - GCInfoHeader header = decoder.GetHeader(); - Assert.Equal(expectedSize, header.SizeOfStackParameterArea); - Assert.Empty(decoder.GetSlotLifetimes()); - Assert.Equal(expectedSize, decoder.GetHeader().SizeOfStackParameterArea); } } From 81d7ae14a02616ac598906b0f973765a295c009c Mon Sep 17 00:00:00 2001 From: David Wrighton Date: Thu, 19 Nov 2026 19:43:15 +0000 Subject: [PATCH 20/21] Use CoreCLR virtual IP scaling for NativeAOT Wasm ILC now doubles the JIT's virtual-IP spans when building the runtime function table, matching CoreCLR. Make the rest of NativeAOT consistent: the JIT always emits a doubled GC info code length, and WasmCodeManager doubles the frame virtual IP and EH clause offsets. This fixes the funclet lookup assert in WasmCodeManager.cpp seen in WASI NativeAOT CI. Update clr-abi.md to describe the packed unwind ULEB and the scaling. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/design/coreclr/botr/clr-abi.md | 6 +++--- src/coreclr/jit/codegenwasm.cpp | 5 ++--- .../nativeaot/Runtime/wasm/WasmCodeManager.cpp | 16 +++++++++------- .../ObjectWriter/WasmRelocatableObjectWriter.cs | 1 + 4 files changed, 15 insertions(+), 13 deletions(-) diff --git a/docs/design/coreclr/botr/clr-abi.md b/docs/design/coreclr/botr/clr-abi.md index 268e4853f5e477..01bf487f0e85ae 100644 --- a/docs/design/coreclr/botr/clr-abi.md +++ b/docs/design/coreclr/botr/clr-abi.md @@ -774,12 +774,12 @@ So on exit from the prolog the stack pointer (`$sp`) will point to the bottom of ### R2R stack frame layout -R2R methods and funclets that can be interrupted by GC or EH have an unwindable frame. This includes methods and funclets that contain calls. The Wasm unwind blob for each R2R function or funclet contains two ULEB128 values: +R2R methods and funclets that can be interrupted by GC or EH have an unwindable frame. This includes methods and funclets that contain calls. The Wasm unwind blob for each R2R function or funclet is one ULEB128 value that interleaves two fields: -1. The fixed frame size in bytes. +1. The fixed frame size, in 16-byte units. 2. The virtual IP span for the function or funclet, encoded in units of 2. -The runtime recovers the current R2R virtual IP from the current managed `$sp`. The low bit of virtual IP values is reserved to distinguish virtual IPs from interpreter addresses and portable entrypoints, so function-local virtual IPs are stored divided by 2 in the frame and multiplied by 2 by the runtime. +The runtime recovers the current R2R virtual IP from the current managed `$sp`. The low bit of virtual IP values is reserved to distinguish virtual IPs from interpreter addresses and portable entrypoints, so function-local virtual IPs are stored divided by 2 in the frame and multiplied by 2 by the runtime. EH clause offsets are likewise stored divided by 2, while the GC info code length is in doubled units. NativeAOT uses the same scaling. For a main R2R method, the fixed frame begins at `$fp`. If the method does not use `localloc`, `$fp` and `$sp` are the same local after the prolog. If the method uses `localloc`, `$fp` remains at the bottom of the fixed frame and `$sp` can move below it. The first two pointer-sized slots are reserved for unwind lookup: diff --git a/src/coreclr/jit/codegenwasm.cpp b/src/coreclr/jit/codegenwasm.cpp index 432ffec9c9a295..9b90d91e1a8039 100644 --- a/src/coreclr/jit/codegenwasm.cpp +++ b/src/coreclr/jit/codegenwasm.cpp @@ -4740,11 +4740,10 @@ void CodeGen::genCreateAndStoreGCInfo(unsigned codeSize, unsigned prologSize, un maxVirtualIP = max(maxVirtualIP, func->endVirtualIP); } - // CoreCLR doubles virtual IPs to preserve the low-bit tag on virtual code addresses. - // NativeAOT uses unscaled virtual IPs. + // The runtimes double virtual IPs to preserve the low-bit tag on virtual code addresses. // Use 1 as the prolog size. // - codeSize = m_compiler->IsNativeAot() ? maxVirtualIP : 2 * maxVirtualIP; + codeSize = 2 * maxVirtualIP; prologSize = 1; // Wasm GC info has an implicit frame register even when there is no linear-memory frame. diff --git a/src/coreclr/nativeaot/Runtime/wasm/WasmCodeManager.cpp b/src/coreclr/nativeaot/Runtime/wasm/WasmCodeManager.cpp index 5558f31b308f9f..4da14e6fc77286 100644 --- a/src/coreclr/nativeaot/Runtime/wasm/WasmCodeManager.cpp +++ b/src/coreclr/nativeaot/Runtime/wasm/WasmCodeManager.cpp @@ -65,6 +65,7 @@ WasmCodeManager::WasmCodeManager(const WasmRuntimeFunction* pFunctions, uint32_t // RyuJIT's shadow frame begins with an identity and a virtual IP. With localloc, SP // instead points at an indirection to FP. Funclet identities point at the establishing // frame, tagged with 2; ordinary NativeAOT identities are (method start virtual IP << 1) | 1. +// As in CoreCLR, the frame's virtual IP and EH clause offsets hold half the method-relative virtual IP. uintptr_t ICodeManager::GetFramePointerFromSP(uintptr_t shadowSP) { uintptr_t fp = GetPhysicalFramePointer(shadowSP); @@ -89,7 +90,7 @@ uintptr_t ICodeManager::GetIPFromSP(uintptr_t shadowSP) uint32_t virtualIP = *reinterpret_cast(fp + sizeof(uintptr_t)); uintptr_t identity = *reinterpret_cast(GetFramePointerFromSP(shadowSP)); ASSERT((identity & 1) != 0 && identity != 1); - return (identity >> 1) + virtualIP; + return (identity >> 1) + virtualIP * 2; } void ICodeManager::UnwindEHHelperFrame(REGDISPLAY* pRegisterSet) @@ -291,11 +292,12 @@ bool WasmCodeManager::EHEnumNext(EHEnumState * pEHEnumState, EHClause * pEHClaus pEnumState->uClause++; - pEHClauseOut->m_tryStartOffset = NativePrimitiveDecoder::ReadUnsigned(pEnumState->pEHInfo); + // EH clause offsets hold half the method-relative virtual IP. + pEHClauseOut->m_tryStartOffset = NativePrimitiveDecoder::ReadUnsigned(pEnumState->pEHInfo) * 2; uint32_t tryEndDeltaAndClauseKind = NativePrimitiveDecoder::ReadUnsigned(pEnumState->pEHInfo); pEHClauseOut->m_clauseKind = (EHClauseKind)(tryEndDeltaAndClauseKind & 0x3); - pEHClauseOut->m_tryEndOffset = pEHClauseOut->m_tryStartOffset + (tryEndDeltaAndClauseKind >> 2); + pEHClauseOut->m_tryEndOffset = pEHClauseOut->m_tryStartOffset + (tryEndDeltaAndClauseKind >> 2) * 2; // For each clause, we have up to 4 integers: // 1) try start offset @@ -309,7 +311,7 @@ bool WasmCodeManager::EHEnumNext(EHEnumState * pEHEnumState, EHClause * pEHClaus switch (pEHClauseOut->m_clauseKind) { case EH_CLAUSE_TYPED: - pEHClauseOut->m_handlerAddress = dac_cast(PINSTRToPCODE(dac_cast(pEnumState->pMethodStartAddress))) + NativePrimitiveDecoder::ReadUnsigned(pEnumState->pEHInfo); + pEHClauseOut->m_handlerAddress = dac_cast(PINSTRToPCODE(dac_cast(pEnumState->pMethodStartAddress))) + NativePrimitiveDecoder::ReadUnsigned(pEnumState->pEHInfo) * 2; // Read target type { @@ -321,11 +323,11 @@ bool WasmCodeManager::EHEnumNext(EHEnumState * pEHEnumState, EHClause * pEHClaus } break; case EH_CLAUSE_FAULT: - pEHClauseOut->m_handlerAddress = dac_cast(PINSTRToPCODE(dac_cast(pEnumState->pMethodStartAddress))) + NativePrimitiveDecoder::ReadUnsigned(pEnumState->pEHInfo); + pEHClauseOut->m_handlerAddress = dac_cast(PINSTRToPCODE(dac_cast(pEnumState->pMethodStartAddress))) + NativePrimitiveDecoder::ReadUnsigned(pEnumState->pEHInfo) * 2; break; case EH_CLAUSE_FILTER: - pEHClauseOut->m_handlerAddress = dac_cast(PINSTRToPCODE(dac_cast(pEnumState->pMethodStartAddress))) + NativePrimitiveDecoder::ReadUnsigned(pEnumState->pEHInfo); - pEHClauseOut->m_filterAddress = dac_cast(PINSTRToPCODE(dac_cast(pEnumState->pMethodStartAddress))) + NativePrimitiveDecoder::ReadUnsigned(pEnumState->pEHInfo); + pEHClauseOut->m_handlerAddress = dac_cast(PINSTRToPCODE(dac_cast(pEnumState->pMethodStartAddress))) + NativePrimitiveDecoder::ReadUnsigned(pEnumState->pEHInfo) * 2; + pEHClauseOut->m_filterAddress = dac_cast(PINSTRToPCODE(dac_cast(pEnumState->pMethodStartAddress))) + NativePrimitiveDecoder::ReadUnsigned(pEnumState->pEHInfo) * 2; break; default: UNREACHABLE_MSG("unexpected EHClauseKind"); diff --git a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmRelocatableObjectWriter.cs b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmRelocatableObjectWriter.cs index 4a65123cc8f026..fc4a7276411b6b 100644 --- a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmRelocatableObjectWriter.cs +++ b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmRelocatableObjectWriter.cs @@ -654,6 +654,7 @@ private protected override void EmitUnwindInfo( { FrameInfo frame = frames[i]; // The JIT interleaves frame size / 16 and virtual IP span / 2 in one ULEB128. + // As in CoreCLR, the runtime doubles JIT virtual IPs, so method starts stay odd. ulong encoded = DwarfHelper.ReadULEB128(frame.BlobData); uint frameSize = (uint)((encoded & 0xF) | (((encoded >> 8) & 0xF) << 4) | (((encoded >> 16) & 0xFFFF) << 8)) * 16; From 2fb09362196492b256e636f26cd51733da99ac89 Mon Sep 17 00:00:00 2001 From: David Wrighton Date: Mon, 23 Nov 2026 22:27:57 +0000 Subject: [PATCH 21/21] Pin all Wasm untracked GC roots Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/coreclr/gcinfo/gcinfoencoder.cpp | 7 ++++++ src/coreclr/jit/gcencode.cpp | 12 ++++++++++ .../TestCases/R2RTestSuites.cs | 19 ++++++++++++++++ .../TestCases/Webcil/WasmWebcilModule.cs | 22 +++++++++++++++++++ 4 files changed, 60 insertions(+) diff --git a/src/coreclr/gcinfo/gcinfoencoder.cpp b/src/coreclr/gcinfo/gcinfoencoder.cpp index 008134489f5ad5..ad54e53bb7f791 100644 --- a/src/coreclr/gcinfo/gcinfoencoder.cpp +++ b/src/coreclr/gcinfo/gcinfoencoder.cpp @@ -577,6 +577,13 @@ template GcSlotId TGcInfoEncoder::GetS _ASSERTE( (flags & (GC_SLOT_IS_REGISTER | GC_SLOT_IS_DELETED)) == 0 ); + if constexpr (GcInfoEncoding::USES_COMPACT_WASM_HEADER) + { + // The Wasm ABI requires GC references on the linear stack to be reported pinned; see + // docs/design/coreclr/botr/clr-abi.md, "GC References at Call Sites". + _ASSERTE((flags & (GC_SLOT_UNTRACKED | GC_SLOT_PINNED)) == (GC_SLOT_UNTRACKED | GC_SLOT_PINNED)); + } + if (!(TargetOS::IsApplePlatform && TargetArchitecture::IsArm64)) { // the spOffset for the stack slot is required to be pointer size aligned diff --git a/src/coreclr/jit/gcencode.cpp b/src/coreclr/jit/gcencode.cpp index 7ffde2356b1dc4..f3552b96581b03 100644 --- a/src/coreclr/jit/gcencode.cpp +++ b/src/coreclr/jit/gcencode.cpp @@ -4278,6 +4278,10 @@ void GCInfo::gcMakeRegPtrTable( flags = (GcSlotFlags)(flags | GC_SLOT_INTERIOR); } +#ifdef TARGET_WASM + flags = static_cast(flags | GC_SLOT_PINNED); +#endif // TARGET_WASM + GcStackSlotBase stackSlotBase = GC_SP_REL; if (varDsc->lvFramePointerBased) { @@ -4315,6 +4319,10 @@ void GCInfo::gcMakeRegPtrTable( flags = (GcSlotFlags)(flags | GC_SLOT_INTERIOR); } +#ifdef TARGET_WASM + flags = static_cast(flags | GC_SLOT_PINNED); +#endif // TARGET_WASM + GcStackSlotBase stackSlotBase = GC_SP_REL; if (m_compiler->isFramePointerUsed()) { @@ -4343,6 +4351,10 @@ void GCInfo::gcMakeRegPtrTable( flags = (GcSlotFlags)(flags | GC_SLOT_INTERIOR); } +#ifdef TARGET_WASM + flags = static_cast(flags | GC_SLOT_PINNED); +#endif // TARGET_WASM + GcStackSlotBase stackSlotBase = m_compiler->isFramePointerUsed() ? GC_FRAMEREG_REL : GC_SP_REL; gcInfoEncoderWithLog->GetStackSlotId(m_compiler->lvaCachedGenericContextArgOffset(), flags, stackSlotBase); diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/TestCases/R2RTestSuites.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/TestCases/R2RTestSuites.cs index a3b12894d2511f..2c989af18ab7f1 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/TestCases/R2RTestSuites.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/TestCases/R2RTestSuites.cs @@ -1748,6 +1748,25 @@ static void ValidateDefault(ReadyToRunReader reader) } AssertSafepointCovered(gcSlotIdentity, gcSlotRoot, markers); + // GC fields of an on-frame struct are untracked roots too, so they must also be pinned. + ReadyToRunMethod gcStructFields = GetMethod(methods, "GcStructFieldsAcrossSafepoint"); + RuntimeFunction gcStructRoot = GetRoot(gcStructFields); + NativeVarInfo pair = AssertStackRecord(gcStructRoot, VariableType.Local, 0, VarLocType.VLT_STK); + AssertSafepointCovered(gcStructFields, gcStructRoot, pair); + ILCompiler.Reflection.ReadyToRun.Cdac.CdacGcInfo gcStructInfo = + Assert.IsType(gcStructFields.GcInfo); + ILCompiler.Reflection.ReadyToRun.Cdac.CdacGcSlot[] pairFieldSlots = gcStructInfo.Slots + .Where(slot => slot.StackSlot is { } stackSlot + && stackSlot.SpOffset >= pair.VariableLocation.Data2 + && stackSlot.SpOffset < pair.VariableLocation.Data2 + (3 * sizeof(int))) + .ToArray(); + Assert.Equal(2, pairFieldSlots.Length); + Assert.All(pairFieldSlots, slot => + { + Assert.Equal(GcStackSlotBase.GC_FRAMEREG_REL, slot.StackSlot.Base); + Assert.Equal(GcSlotFlags.GC_SLOT_PINNED | GcSlotFlags.GC_SLOT_UNTRACKED, slot.Flags); + }); + // Has a catch clause, so the JIT emits a try_table catch_ref that references the // imported restore-context exception tag. Assert.True(methods.Exists(method => diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/TestCases/Webcil/WasmWebcilModule.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/TestCases/Webcil/WasmWebcilModule.cs index ee012f52af9011..b9db7fdb83217c 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/TestCases/Webcil/WasmWebcilModule.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/TestCases/Webcil/WasmWebcilModule.cs @@ -509,6 +509,28 @@ public static int GcSlotIdentity() return result; } + private struct GcMarkerPair + { + public GcMarker? First; + public int Value; + public GcMarker? Second; + } + + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + public static int GcStructFieldsAcrossSafepoint(int value) + { + GcMarkerPair pair = default; + pair.First = new GcMarker(value); + pair.Value = value; + pair.Second = new GcMarker(value + 1); + + CollectAtGcSafepoint(); + int result = pair.First!.Value + pair.Second!.Value + pair.Value; + GC.KeepAlive(pair.First); + GC.KeepAlive(pair.Second); + return result; + } + [MethodImpl(MethodImplOptions.NoInlining)] private static void TouchMarkerSlot(ref GcMarker? marker) {