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/docs/design/coreclr/botr/readytorun-format.md b/docs/design/coreclr/botr/readytorun-format.md index cf69574f13e2f5..5c9e055dab11f2 100644 --- a/docs/design/coreclr/botr/readytorun-format.md +++ b/docs/design/coreclr/botr/readytorun-format.md @@ -507,19 +507,98 @@ 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 in bytes (the number of bytes to unwind from the stack) -| 2 | ULEB128 | Virtual IP count divided by 2 (the number of virtual IPs logically present in the function, halved) +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 35.0 uses this packed unwind data and the compact Wasm GC encoding described +below. The runtime requires ReadyToRun format 35.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 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 35.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. + +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. + +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. + +### 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. 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. +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 +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 This section contains a [native format sparse array](#sparse-array) that maps methoddef rows to diff --git a/docs/design/datacontracts/ExecutionManager.md b/docs/design/datacontracts/ExecutionManager.md index bda78e52a0efd1..7e64804fbb88ce 100644 --- a/docs/design/datacontracts/ExecutionManager.md +++ b/docs/design/datacontracts/ExecutionManager.md @@ -636,7 +636,10 @@ For R2R images, `hasFlagByte` is always `false`. * For R2R code (`ReadyToRunJitManager`), the `GCInfo` is stored directly after the `UnwindData`. This in turn is found by looking up the `UnwindInfo` (`RUNTIME_FUNCTION`) and reading the `UnwindData` offset. We find the `UnwindInfo` as described above in `IExecutionManager.GetUnwindInfo`. Once we have the relevant unwind data, we calculate the size of the unwind data and return a pointer to the following byte (first byte of the GCInfo). The size of the unwind data is a platform specific. See src/coreclr/vm/codeman.cpp GetUnwindDataBlob for more details. * The `GCInfoVersion` of R2R code is mapped from the R2R MajorVersion and MinorVersion which is read from the ReadyToRunHeader which itself is read from the ReadyToRunInfo (can be found as in GetMethodInfo). The current GCInfoVersion mapping is: - * MajorVersion >= 11 and MajorVersion < 15 => 4 + * MajorVersion < 11 => 3 + * MajorVersion >= 11 and MajorVersion < 21 => 4 + * MajorVersion >= 21 and MajorVersion < 35 => 5 + * MajorVersion >= 35 => 6 * For interpreted code (`InterpreterJitManager`), a pointer to the `GCInfo` is stored on the `InterpreterRealCodeHeader`, accessed via nibble map lookup as with the EE JitManager. The `GCInfoVersion` is defined by the runtime global `GCInfoVersion`. The GC info is decoded using interpreter-specific decoding (`DecodeInterpreterGCInfo`). diff --git a/docs/design/datacontracts/GCInfo.md b/docs/design/datacontracts/GCInfo.md index 212cbe8aaf726b..15b43ae3cfb72f 100644 --- a/docs/design/datacontracts/GCInfo.md +++ b/docs/design/datacontracts/GCInfo.md @@ -5,14 +5,28 @@ 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 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). +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 +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. +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 @@ -280,6 +294,22 @@ 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 uses the following tuned variable-length integer 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 @@ -655,16 +685,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: ``` @@ -700,15 +835,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 diff --git a/docs/design/datacontracts/StackWalk.md b/docs/design/datacontracts/StackWalk.md index e483bfb8a2d86b..f8424ca6336fed 100644 --- a/docs/design/datacontracts/StackWalk.md +++ b/docs/design/datacontracts/StackWalk.md @@ -514,7 +514,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 controlling method's unwind blob contains its fixed frame size followed by its virtual IP extent, both uint32 ULEB128 values. When the extent is 2, the only observable function-local IP is 1: the virtual IP is the identity-derived method base plus 2, without reading the physical frame's IP slot, which may be uninitialized. Otherwise the virtual IP is the method base plus twice the physical frame's stored function-local value. `WasmContext.Unwind` resolves its current virtual IP through `IExecutionManager.GetCodeBlockHandle`, then uses `GetUnwindInfo` and `GetUnwindInfoBaseAddress` to locate the unwind data. It 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 controlling method's unwind blob is one uint64 ULEB128 value that interleaves the frame size in 16-byte units and the virtual IP count in 2-IP units, as specified in the [ReadyToRun format](../coreclr/botr/readytorun-format.md#unwindinfo-wasm). When the decoded virtual IP count is 4, the only observable function-local IP is 1: the virtual IP is the identity-derived method base plus 2, without reading the physical frame's IP slot, which may be uninitialized. Otherwise the virtual IP is the method base plus twice the physical frame's stored function-local value. `WasmContext.Unwind` resolves its current virtual IP through `IExecutionManager.GetCodeBlockHandle`, then uses `GetUnwindInfo` and `GetUnwindInfoBaseAddress` to locate the unwind data at `unwindInfoBaseAddress + RuntimeFunction.UnwindData`. 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. @@ -524,7 +524,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; @@ -941,7 +941,7 @@ The receiver interpretation can be overridden by the frame: the method's owning type is a value type and the method is not an unboxing stub. All supported ReadyToRun instance import maps use `THIS_REF` or `THIS_BYREF`: the runtime's minimum supported -ReadyToRun major version is 33. No per-map receiver-format flag or receiver-token validation is needed. +ReadyToRun major version is 35. No per-map receiver-format flag or receiver-token validation is needed. Signature-synthesized maps may continue to use concrete `REF` and `INTERIOR` tokens; synthetic maps for explicit-context shared bodies are not eligible for declaration-map borrowing. Signature-synthesized blobs retain the target's cookie encoding and are decoded accordingly. diff --git a/docs/design/datacontracts/reader-version-history.md b/docs/design/datacontracts/reader-version-history.md index d914301f4b2196..f387b506bfc61a 100644 --- a/docs/design/datacontracts/reader-version-history.md +++ b/docs/design/datacontracts/reader-version-history.md @@ -38,7 +38,7 @@ Added support for cached and virtual ReadyToRun argument maps: - `StackWalk` version `c2` decodes `THIS_REF` and `THIS_BYREF`, which encode the call-site receiver kind without a separate bit. `VASIG_COOKIE` moves from 5 to 7; version `c1` targets retain the old value. -- Supported ReadyToRun images have major version 33 or newer, so all instance import maps +- Supported ReadyToRun images have major version 35 or newer, so all instance import maps use contextual receiver tokens. Declaration lookup checks method-instantiation and explicit-context eligibility from metadata, without decoding maps or maintaining per-map format flags. - Prestub, call-counting, and stub-dispatch frames can reuse same-slot declaration maps, diff --git a/src/coreclr/gcinfo/gcinfoencoder.cpp b/src/coreclr/gcinfo/gcinfoencoder.cpp index 8e82da037dcc66..ad54e53bb7f791 100644 --- a/src/coreclr/gcinfo/gcinfoencoder.cpp +++ b/src/coreclr/gcinfo/gcinfoencoder.cpp @@ -531,6 +531,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. @@ -556,6 +557,8 @@ 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. @@ -574,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 @@ -781,6 +791,7 @@ struct GcEncoderSlotDescAndId UINT32 m_SlotId; }; +template struct CompareSlotDescAndIdBySlotDesc { bool operator()(const GcEncoderSlotDescAndId& first, const GcEncoderSlotDescAndId& second) @@ -788,14 +799,17 @@ struct CompareSlotDescAndIdBySlotDesc const GcEncoderSlotDesc* pFirst = &first.m_SlotDesc; const GcEncoderSlotDesc* 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; @@ -809,12 +823,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 @@ -945,7 +958,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 @@ -961,7 +984,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 { @@ -971,7 +997,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) @@ -983,7 +1012,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 ); @@ -1007,7 +1036,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) @@ -1019,7 +1055,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. @@ -1048,7 +1091,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); } @@ -1110,7 +1153,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 @@ -1222,7 +1268,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++) { @@ -1408,7 +1454,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()) { @@ -1428,15 +1474,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) { @@ -1454,8 +1502,11 @@ template void TGcInfoEncoder::Build() if(numUsedSlots == 0) goto lExitSuccess; - if(numRegisters > 0) + if(GcInfoEncoding::HAS_REGISTER_SLOTS && numRegisters > 0) { +#ifdef MEASURE_GCINFO + size_t startBitCount = m_Info1.GetBitCount(); +#endif GcEncoderSlotDesc *pSlotDesc; do { @@ -1467,8 +1518,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,122 +1538,89 @@ 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); + m_Info1.Write(pSlotDesc->Flags, (lastFlags & GC_SLOT_PINNED) != 0 ? 2 : 1); + } + + if(pSlotDesc->Flags != lastFlags) + { + m_Info1.EncodeRegister(currentNormRegNum, GcInfoEncoding::REGISTER_ENCBASE, GcInfoEncoding::REGISTER_BITS); } else { - _ASSERTE(pSlotDesc->Flags == GC_SLOT_IS_REGISTER); - GCINFO_WRITE_VARL_U(m_Info1, currentNormRegNum - lastNormRegNum - 1, GcInfoEncoding::REGISTER_DELTA_ENCBASE, RegSlotSize); + _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(numStackSlots > 0) + for (UINT32 section = 0; section < 2; section++) { - GcEncoderSlotDesc *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); - GCINFO_WRITE(m_Info1, pSlotDesc->Slot.Stack.Base, 2, StackSlotSize); - INT32 currentNormStackSlot = GcInfoEncoding::NORMALIZE_STACK_SLOT(pSlotDesc->Slot.Stack.SpOffset); - GCINFO_WRITE_VARL_S(m_Info1, currentNormStackSlot, GcInfoEncoding::STACK_SLOT_ENCBASE, StackSlotSize); - - GCINFO_WRITE(m_Info1, pSlotDesc->Flags, 2, StackSlotSize); - - for(UINT32 j = 1; j < numStackSlots; 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); - - _ASSERTE((pSlotDesc->Slot.Stack.Base & ~3) == 0); - GCINFO_WRITE(m_Info1, pSlotDesc->Slot.Stack.Base, 2, StackSlotSize); + const GcEncoderSlotDesc& slot = m_SlotTable[currentSlot++]; + _ASSERTE(!slot.IsRegister()); + _ASSERTE((slot.IsUntracked() != FALSE) == (section != 0)); - if(lastFlags != GC_SLOT_BASE) + GcSlotFlags flags = static_cast(slot.Flags & (GC_SLOT_INTERIOR | GC_SLOT_PINNED)); + if constexpr (GcInfoEncoding::USES_COMPACT_WASM_HEADER) { - GCINFO_WRITE_VARL_S(m_Info1, currentNormStackSlot, GcInfoEncoding::STACK_SLOT_ENCBASE, StackSlotSize); - GCINFO_WRITE(m_Info1, pSlotDesc->Flags, 2, StackSlotSize); + flags = static_cast(flags ^ GC_SLOT_PINNED); } - else + if (i == 0 || previousFlags != GC_SLOT_BASE) { - _ASSERTE(pSlotDesc->Flags == GC_SLOT_BASE); - GCINFO_WRITE_VARL_U(m_Info1, currentNormStackSlot - lastNormStackSlot, GcInfoEncoding::STACK_SLOT_DELTA_ENCBASE, StackSlotSize); + m_Info1.Write(flags, i == 0 || (previousFlags & GC_SLOT_PINNED) != 0 ? 2 : 1); } - } - } - - if(numUntrackedSlots > 0) - { - GcEncoderSlotDesc *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); - GCINFO_WRITE(m_Info1, pSlotDesc->Slot.Stack.Base, 2, UntrackedSlotSize); - INT32 currentNormStackSlot = GcInfoEncoding::NORMALIZE_STACK_SLOT(pSlotDesc->Slot.Stack.SpOffset); - GCINFO_WRITE_VARL_S(m_Info1, currentNormStackSlot, GcInfoEncoding::STACK_SLOT_ENCBASE, UntrackedSlotSize); - - GCINFO_WRITE(m_Info1, pSlotDesc->Flags, 2, UntrackedSlotSize); - - for(UINT32 j = 1; j < numUntrackedSlots; j++) - { - INT32 lastNormStackSlot = currentNormStackSlot; - GcSlotFlags lastFlags = pSlotDesc->Flags; - - do + GcStackSlotBase base = slot.Slot.Stack.Base; + if constexpr (GcInfoEncoding::HAS_STACK_SLOT_BASE) { - _ASSERTE(currentSlot < m_NumSlots); - pSlotDesc = &m_SlotTable[currentSlot++]; + m_Info1.Write(base == GC_FRAMEREG_REL, 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); - GCINFO_WRITE(m_Info1, pSlotDesc->Slot.Stack.Base, 2, UntrackedSlotSize); - 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 @@ -2574,6 +2592,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 3982afe1a87700..260bb9ae286992 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..4fdece65a26fa8 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); @@ -46,6 +46,8 @@ 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(12)) + return 6; if (IsRuntimeVersionAtLeast(11)) return 5; if (IsRuntimeVersionAtLeast(10)) @@ -61,11 +63,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,20 +79,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 >= 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 77e46a6c42990d..9a77bce785fd62 100644 --- a/src/coreclr/inc/gcinfodecoder.h +++ b/src/coreclr/inc/gcinfodecoder.h @@ -551,7 +551,7 @@ class GcSlotDecoder GcSlotDecoder() {} - void DecodeSlotTable(BitStreamReader& reader); + void DecodeSlotTable(BitStreamReader& reader, UINT32 version); UINT32 GetNumSlots() { @@ -565,22 +565,109 @@ class GcSlotDecoder UINT32 GetNumTracked() { - return m_NumSlots - m_NumUntracked; + return GcInfoEncoding::HAS_TRACKED_SLOTS ? m_NumSlots - m_NumUntracked : 0; } UINT32 GetNumRegisters() { - return m_NumRegisters; + return GcInfoEncoding::HAS_REGISTER_SLOTS ? m_NumRegisters : 0; } 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) + { + 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) + { +#ifdef DECODE_OLD_FORMATS + if (!m_UseCompactSlotEncoding) + { + 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 + + 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; + } + + INT32 ReadStackSlot(BitStreamReader& reader, GcSlotFlags& flags, GcStackSlotBase& base, + INT32 previousOffset, bool first) + { +#ifdef DECODE_OLD_FORMATS + if (!m_UseCompactSlotEncoding) + { + 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)); + + return offset; + } + GcSlotDesc m_SlotArray[MAX_PREDECODED_SLOTS]; BitStreamReader m_SlotReader; 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; @@ -676,7 +763,11 @@ class TGcInfoDecoder inline UINT32 Version() { +#ifdef DECODE_OLD_FORMATS return m_Version; +#else + return GCINFO_VERSION; +#endif // DECODE_OLD_FORMATS } private: @@ -725,7 +816,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) { @@ -816,7 +909,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 ) @@ -870,4 +963,3 @@ typedef TGcInfoDecoder InterpreterGcInfoDecoder; #endif // _GC_INFO_DECODER_ - diff --git a/src/coreclr/inc/gcinfoencoder.h b/src/coreclr/inc/gcinfoencoder.h index 21e0fa5c9bc4c5..c335d4ed69e549 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 @@ -234,6 +248,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 @@ -370,7 +385,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 fbcc66593532ad..5d59a44f7ffa3b 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); @@ -617,6 +619,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_TRACKED_SLOTS = true; + static const bool HAS_STACK_SLOT_BASE = true; static const bool HAS_FIXED_STACK_PARAMETER_SCRATCH_AREA = true; static const bool HAS_INTERRUPTIBLE_RANGES = true; }; @@ -630,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); } @@ -676,6 +683,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_TRACKED_SLOTS = true; + static const bool HAS_STACK_SLOT_BASE = true; static const bool HAS_FIXED_STACK_PARAMETER_SCRATCH_AREA = true; static const bool HAS_INTERRUPTIBLE_RANGES = true; }; @@ -689,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 @@ -738,6 +750,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_TRACKED_SLOTS = true; + static const bool HAS_STACK_SLOT_BASE = true; static const bool HAS_FIXED_STACK_PARAMETER_SCRATCH_AREA = true; static const bool HAS_INTERRUPTIBLE_RANGES = true; }; @@ -750,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 @@ -798,6 +815,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_TRACKED_SLOTS = true; + static const bool HAS_STACK_SLOT_BASE = true; static const bool HAS_FIXED_STACK_PARAMETER_SCRATCH_AREA = true; static const bool HAS_INTERRUPTIBLE_RANGES = true; }; @@ -810,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 @@ -859,6 +881,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_TRACKED_SLOTS = true; + static const bool HAS_STACK_SLOT_BASE = true; static const bool HAS_FIXED_STACK_PARAMETER_SCRATCH_AREA = true; static const bool HAS_INTERRUPTIBLE_RANGES = true; }; @@ -872,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); } @@ -915,6 +942,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_TRACKED_SLOTS = true; + static const bool HAS_STACK_SLOT_BASE = true; static const bool HAS_FIXED_STACK_PARAMETER_SCRATCH_AREA = true; static const bool HAS_INTERRUPTIBLE_RANGES = true; }; @@ -927,17 +957,18 @@ struct X86GcInfoEncoding { #define TargetGcInfoEncoding Wasm32GcInfoEncoding -// TODO-WASM: Investigate normalizing stack slots to save space based on wasm stack alignment - 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); } - 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); } + // 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); } static inline constexpr uint32_t DENORMALIZE_SIZE_OF_STACK_AREA (uint32_t x) { return (x); } static const bool CODE_OFFSETS_NEED_NORMALIZATION = false; @@ -948,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; @@ -965,14 +996,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 NUM_SAFE_POINTS_ENCBASE = 4; + static const int STACK_SLOT_ENCBASE = 3; + static const int STACK_SLOT_DELTA_ENCBASE = 3; + 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; 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; + // 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; static const bool HAS_FIXED_STACK_PARAMETER_SCRATCH_AREA = false; static const bool HAS_INTERRUPTIBLE_RANGES = false; }; @@ -988,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); @@ -1037,6 +1076,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_TRACKED_SLOTS = true; + static const bool HAS_STACK_SLOT_BASE = true; 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 073ead514389e5..c01d7e8b48fb25 100644 --- a/src/coreclr/inc/readytorun.h +++ b/src/coreclr/inc/readytorun.h @@ -19,10 +19,10 @@ // 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 34 -#define READYTORUN_MINOR_VERSION 0x0001 +#define READYTORUN_MAJOR_VERSION 35 +#define READYTORUN_MINOR_VERSION 0x0000 -#define MINIMUM_READYTORUN_MAJOR_VERSION 34 +#define MINIMUM_READYTORUN_MAJOR_VERSION 35 // R2R Version 2.1 adds the InliningInfo section // R2R Version 2.2 adds the ProfileDataInfo section @@ -90,6 +90,9 @@ // only the return address, and the runtime preserves the callee-saved registers around the // funclets that it calls // R2R Version 34.1 adds AuxiliaryModuleMetadata sections +// R2R Version 35 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/codegenwasm.cpp b/src/coreclr/jit/codegenwasm.cpp index b553d91408eeef..71040e8b6dab0a 100644 --- a/src/coreclr/jit/codegenwasm.cpp +++ b/src/coreclr/jit/codegenwasm.cpp @@ -4751,13 +4751,15 @@ 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. + gcInfoEncoder->SetStackBaseRegister(REG_FPBASE); + // Follow the code pattern of the x86 gc info encoder (genCreateAndStoreGCInfoJIT32). gcInfo.gcInfoBlockHdrSave(gcInfoEncoder, codeSize, prologSize); diff --git a/src/coreclr/jit/gcencode.cpp b/src/coreclr/jit/gcencode.cpp index 631581a17be611..658d8be20d7657 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) @@ -4278,6 +4278,10 @@ void GCInfo::gcMakeRegPtrTable( flags = (GcSlotFlags)(flags | GC_SLOT_INTERIOR); } +#ifdef TARGET_WASMARCH + flags = static_cast(flags | GC_SLOT_PINNED); +#endif // TARGET_WASMARCH + GcStackSlotBase stackSlotBase = GC_SP_REL; if (varDsc->lvFramePointerBased) { @@ -4315,6 +4319,10 @@ void GCInfo::gcMakeRegPtrTable( flags = (GcSlotFlags)(flags | GC_SLOT_INTERIOR); } +#ifdef TARGET_WASMARCH + flags = static_cast(flags | GC_SLOT_PINNED); +#endif // TARGET_WASMARCH + GcStackSlotBase stackSlotBase = GC_SP_REL; if (m_compiler->isFramePointerUsed()) { @@ -4343,6 +4351,10 @@ void GCInfo::gcMakeRegPtrTable( flags = (GcSlotFlags)(flags | GC_SLOT_INTERIOR); } +#ifdef TARGET_WASMARCH + flags = static_cast(flags | GC_SLOT_PINNED); +#endif // TARGET_WASMARCH + GcStackSlotBase stackSlotBase = m_compiler->isFramePointerUsed() ? GC_FRAMEREG_REL : GC_SP_REL; gcInfoEncoderWithLog->GetStackSlotId(m_compiler->lvaCachedGenericContextArgOffset(), flags, stackSlotBase); diff --git a/src/coreclr/jit/unwindwasm.cpp b/src/coreclr/jit/unwindwasm.cpp index ef281478d81aea..6238fec21ca1d5 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_WASMARCH +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() { } @@ -61,8 +74,9 @@ void Compiler::unwindReserveFunc(FuncInfoDsc* func) bool isFunclet = func->IsFunclet(); bool isColdCode = false; assert(func->endVirtualIP > func->startVirtualIP); - ULONG encodedSize = emitter::SizeOfULEB128(func->funWasmFrameSize) + - emitter::SizeOfULEB128(func->endVirtualIP - func->startVirtualIP); + assert((func->funWasmFrameSize % STACK_ALIGN) == 0); + ULONG encodedSize = emitter::SizeOfULEB128( + EncodeWasmUnwindInfo(func->funWasmFrameSize / STACK_ALIGN, func->endVirtualIP - func->startVirtualIP)); eeReserveUnwindInfo(isFunclet, isColdCode, encodedSize); } @@ -107,14 +121,15 @@ void Compiler::unwindEmitFunc(FuncInfoDsc* func, void* pHotCode, void* pColdCode // pColdCode = nullptr; - // Unwind info is the frame size 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); - index += GetEmitter()->emitOutputULEB128(buffer + index, func->funWasmFrameSize); - index += GetEmitter()->emitOutputULEB128(buffer + index, func->endVirtualIP - func->startVirtualIP); + assert((func->funWasmFrameSize % STACK_ALIGN) == 0); + 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/nativeaot/Runtime/inc/ModuleHeaders.h b/src/coreclr/nativeaot/Runtime/inc/ModuleHeaders.h index d09fff9a7db1c8..ad5c1d84b0e750 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 = 34; - static const uint32_t CurrentMinorVersion = 1; + static const uint32_t CurrentMajorVersion = 35; + static const uint32_t CurrentMinorVersion = 0; + static const uint32_t MinimumWasmMajorVersion = 35; }; struct ReadyToRunHeader 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 3e546d0af88b73..25716a8cdc46be 100644 --- a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmRelocatableObjectWriter.cs +++ b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmRelocatableObjectWriter.cs @@ -682,9 +682,14 @@ 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. + // 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; 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); diff --git a/src/coreclr/tools/Common/Internal/Runtime/ModuleHeaders.cs b/src/coreclr/tools/Common/Internal/Runtime/ModuleHeaders.cs index 79183dc60ebdd4..723241698d9a87 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 = 34; - public const ushort CurrentMinorVersion = 1; + public const ushort CurrentMajorVersion = 35; + public const ushort CurrentMinorVersion = 0; + public const ushort MinimumWasmMajorVersion = 35; } #if READYTORUN #pragma warning disable 0169 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..19fcee8dd6aad1 --- /dev/null +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/GcInfoDecoderTests.cs @@ -0,0 +1,574 @@ +// 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.Cdac; +using Xunit; + +namespace ILCompiler.ReadyToRun.Tests; + +public class GcInfoDecoderTests +{ + [Theory] + [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 = 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); + CdacGcInfo info = Decode(stream, Machine.Amd64, version); + + Assert.Equal(1u, info.NumRegisters); + Assert.Equal(0u, info.NumStackSlots); + Assert.Equal(0u, info.NumUntrackedSlots); + CdacGcSlot slot = Assert.Single(info.Slots); + Assert.Equal(0u, slot.RegisterNumber); + Assert.Null(slot.StackSlot); + Assert.Equal((GcSlotFlags)rootFlags, slot.Flags); + } + + public static IEnumerable RegisterSlotCases() + { + foreach (Machine machine in new[] { Machine.Amd64, Machine.ArmThumb2, Machine.Arm64, + Machine.LoongArch64, Machine.RiscV64 }) + { + foreach (int version in new[] { 5, 6 }) + { + for (int flags = 0; flags < 4; flags++) + yield return [machine, version, flags]; + } + } + } + + [Theory] + [MemberData(nameof(RegisterSlotCases))] + public void RegisterSlotsUseFlagsFirstAndBoundedIntegers(Machine machine, int version, int flags) + { + int maxRegister = machine == Machine.ArmThumb2 ? 15 : 31; + 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); + } + } + + 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); + using MemoryStream stream = new(writer.ToArray()); + CdacGcInfo info = Decode(stream, machine, version); + Assert.Equal((uint)registers.Count, info.NumRegisters); + Assert.Equal(registers.Count, info.Slots.Count); + for (int i = 0; i < registers.Count; i++) + { + Assert.Equal((uint)registers[i].Register, info.Slots[i].RegisterNumber); + Assert.Equal((GcSlotFlags)registers[i].Flags, info.Slots[i].Flags); + Assert.Null(info.Slots[i].StackSlot); + } + Assert.Equal((writer.BitCount + 7) / 8, info.Size); + } + + public static IEnumerable StackSlotFlagCases() + { + Machine[] machines = [Machine.Amd64, Machine.ArmThumb2, Machine.Arm64, + Machine.LoongArch64, Machine.RiscV64, WasmMachine.Wasm32]; + foreach (Machine machine in machines) + { + 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] + [MemberData(nameof(StackSlotFlagCases))] + public void StackSlotsUseFlagsThenBaseThenOffset(Machine machine, bool tracked, int count, int mask) + { + 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); + + using MemoryStream stream = new(writer.ToArray()); + CdacGcInfo info = Decode(stream, machine, 6); + Assert.Equal(0u, info.NumRegisters); + Assert.Equal(tracked ? (uint)numSlots : 0u, info.NumStackSlots); + Assert.Equal(tracked ? 0u : (uint)numSlots, info.NumUntrackedSlots); + Assert.Equal(numSlots, info.Slots.Count); + Assert.Equal((writer.BitCount + 7) / 8, info.Size); + + int slotIndex = 0; + for (int encodedFlags = 3; encodedFlags >= 0; encodedFlags--) + { + int flags = encodedFlags ^ (machine == WasmMachine.Wasm32 ? 2 : 0); + for (int i = 0; i < counts[flags]; i++) + { + CdacGcSlot slot = info.Slots[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(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()); + CdacGcInfo info = Decode(stream, WasmMachine.Wasm32, 6); + Assert.Equal((uint)count, info.NumUntrackedSlots); + Assert.Equal(count, info.Slots.Count); + for (int i = 0; i < count; i++) + { + CdacGcSlot slot = info.Slots[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)] + [InlineData(Machine.Arm64)] + [InlineData(Machine.LoongArch64)] + [InlineData(Machine.RiscV64)] + public void LegacyStackSlotFlagsRemainReadable(Machine machine) + { + SlotTableWriter writer = new(machine); + writer.WriteCounts(8, 8); + writer.WriteLegacySlots(); + writer.WriteLegacySlots(); + + using MemoryStream stream = new(writer.ToArray()); + CdacGcInfo info = Decode(stream, machine, 5); + Assert.Equal(8u, info.NumStackSlots); + Assert.Equal(8u, info.NumUntrackedSlots); + Assert.Equal(16, info.Slots.Count); + for (int i = 0; i < 16; i++) + { + CdacGcSlot slot = info.Slots[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(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); + int[] counts = new int[4]; + counts[flags] = 2; + writer.WriteStackSlots(counts); + writer.WriteStackSlots(counts); + + using MemoryStream stream = new(writer.ToArray()); + CdacGcInfo info = Decode(stream, machine, 6); + Assert.Equal(4, info.Slots.Count); + for (int i = 0; i < 4; i++) + { + Assert.Equal(writer.DenormalizeOffset(writer.GetStackOffset(i % 2, 2)), info.Slots[i].StackSlot.SpOffset); + Assert.Equal(writer.GetStackBase(i % 2, 2), info.Slots[i].StackSlot.Base); + Assert.Equal((GcSlotFlags)flags | (i < 2 ? 0 : GcSlotFlags.GC_SLOT_UNTRACKED), info.Slots[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()); + CdacGcInfo info = Decode(stream, machine, 6); + Assert.Equal(4, info.Slots.Count); + int[] offsets = [0, 0, 15, 256]; + for (int i = 0; i < offsets.Length; i++) + Assert.Equal(writer.DenormalizeOffset(offsets[i]), info.Slots[i].StackSlot.SpOffset); + 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); + CdacGcInfo info = Decode(stream, Machine.Amd64, 5); + + Assert.Equal(2, info.CodeLength); + Assert.Equal(2u, info.NumUntrackedSlots); + Assert.Equal(64, info.Slots[0].StackSlot.SpOffset); + Assert.Equal(GcStackSlotBase.GC_SP_REL, info.Slots[0].StackSlot.Base); + Assert.Equal(128, info.Slots[1].StackSlot.SpOffset); + Assert.Equal(GcStackSlotBase.GC_FRAMEREG_REL, info.Slots[1].StackSlot.Base); + Assert.All(info.Slots, 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, null)] + [InlineData(Machine.Amd64, 6, 0x0A, 5u)] + [InlineData(Machine.Amd64, 6, 0x08, null)] + [InlineData(WasmMachine.Wasm32, 6, 0x04, 2u)] + public void SlimHeaderUsesImplicitDefaultFrameRegister(Machine machine, int version, byte header, uint? frameRegister) + { + byte[] encoded = [header, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; + using MemoryStream stream = new(encoded); + CdacGcInfo info = Decode(stream, machine, version); + + Assert.Equal(2, info.CodeLength); + Assert.Equal(frameRegister, info.StackBaseRegister); + Assert.Empty(info.Slots); + Assert.Equal(machine == WasmMachine.Wasm32 ? 1 : 2, info.Size); + } + + [Theory] + [InlineData(new byte[] { 0x21, 0x08, 0x02, 0x00 })] + [InlineData(new byte[] { 0x41, 0x08, 0x02, 0x00 })] + public void WasmFatHeaderPreservesGenericContext(byte[] encoded) + { + using MemoryStream stream = new(encoded); + CdacGcInfo info = Decode(stream, WasmMachine.Wasm32, 6); + + Assert.Equal(2, info.CodeLength); + Assert.Equal(2u, info.StackBaseRegister); + Assert.Equal(8, info.Header.GenericsInstContext?.SpOffset); + Assert.Equal(1u, info.ValidRangeStart); + Assert.Empty(info.Slots); + 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, 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) + { + using MemoryStream stream = new(encoded); + CdacGcInfo info = Decode(stream, WasmMachine.Wasm32, 6); + + Assert.Equal(2, info.CodeLength); + Assert.Equal(2u, info.StackBaseRegister); + Assert.Equal(cookieOffset == -1 ? null : (int?)cookieOffset, info.Header.GSCookie?.SpOffset); + Assert.Equal(preservedArea == uint.MaxValue ? null : (uint?)preservedArea, info.SizeOfEditAndContinuePreservedArea); + Assert.Equal(reversePInvokeOffset == -1 ? null : (int?)reversePInvokeOffset, info.ReversePInvokeFrameStackSlot); + Assert.Equal((int)safePoints, info.SafePoints.Count); + if (safePoints != 0) + Assert.Equal(0u, Assert.Single(info.SafePoints)); + if (cookieOffset != -1) + { + Assert.Equal(1u, info.ValidRangeStart); + Assert.Equal(2u, info.ValidRangeEnd); + } + Assert.Empty(info.Slots); + Assert.Equal(encoded.Length, info.Size); + } + + [Theory] + [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) + { + using MemoryStream stream = new(encoded); + ILCompiler.Reflection.ReadyToRun.Wasm32.UnwindInfo info = new(new NativeReader(stream), 0); + + Assert.Equal(frameSize, info.BytesUnwind); + Assert.Equal(virtualIPCount, info.VirtualIPCount); + Assert.Equal(encoded.Length, info.Size); + } + + private static CdacGcInfo Decode(Stream stream, Machine machine, int version) + { + return Assert.IsType(CdacGcInfo.Decode(new NativeReader(stream), 0, machine, version)); + } + + private sealed class SlotTableWriter + { + private readonly Machine _machine; + private readonly List _bytes = []; + public int BitCount { get; private set; } + + public SlotTableWriter(Machine machine) + { + _machine = machine; + Write(0, 1); + if (machine != WasmMachine.Wasm32) + Write(1, 1); + WriteUnsigned(2, machine switch + { + WasmMachine.Wasm32 => 5, + Machine.ArmThumb2 => 7, + _ => 8, + }); + if (machine != WasmMachine.Wasm32) + { + WriteUnsigned(0, machine switch + { + Machine.Amd64 => 2, + _ => 3, + }); + } + } + + public int DenormalizeOffset(int offset) => offset * (_machine switch + { + WasmMachine.Wasm32 or Machine.ArmThumb2 => 4, + _ => 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 => 5, + Machine.ArmThumb2 => 3, + _ => 2, + }); + WriteUnsigned(untracked, _machine switch + { + WasmMachine.Wasm32 => 7, + 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, + _ => 2, + }; + int registerBits = _machine switch + { + 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 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(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 (encodedFlags != previousFlags || slotBase != previousBase) + WriteSigned(offset, _machine == WasmMachine.Wasm32 ? 3 : 6); + else + WriteUnsigned(offset - previousOffset, _machine == WasmMachine.Wasm32 ? 3 : 4); + previousFlags = encodedFlags; + 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)); + } + } + + public byte[] ToArray() + { + byte[] result = new byte[_bytes.Count + 8]; + _bytes.CopyTo(result); + + return result; + } + } +} diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/GcInfoRegressionTests.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/GcInfoRegressionTests.cs index d08e424aad7980..bd4cf3ed542c6b 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/GcInfoRegressionTests.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/GcInfoRegressionTests.cs @@ -339,6 +339,7 @@ public void CdacX86ArgumentPushKeepsThisAndInteriorFlags() [InlineData(1)] [InlineData(3)] [InlineData(5)] + [InlineData(6)] public void CdacX86TrackedEbpSlotsUseSignedOffsets(int version) { // One VarPtr entry: EBP-8, live in [2, 6). @@ -393,6 +394,38 @@ public void CdacDecodesLegacyFatHeader(Machine machine, int version) Assert.Equal(writer.ByteCount, info.Size); } + [Theory] + [InlineData(Machine.Amd64, 1, 0x10)] + [InlineData(Machine.ArmThumb2, 2, 0x10)] + [InlineData(Machine.Arm64, 3, 0x10)] + [InlineData(Machine.ArmThumb2, 2, 0x02)] + [InlineData(Machine.Arm64, 3, 0x02)] + public void CdacLegacyFatHeaderWithoutGSCookieUsesUnnormalizedProlog(Machine machine, int version, int flags) + { + bool isArm = machine == Machine.ArmThumb2; + int stackOffset = isArm ? -8 : -16; + BitWriter writer = new(); + writer.Write(1, 1); + writer.Write(flags, version == 1 ? 9 : 10); + if (version >= 2) + writer.Write(1, isArm ? 2 : 4); + writer.WriteUnsigned(20, isArm ? 7 : 8); + writer.WriteUnsigned(3, 5); + writer.WriteSigned(-2, isArm ? 5 : 6); + writer.WriteUnsigned(0, 3); + writer.WriteUnsigned(0, machine == Machine.Amd64 ? 2 : 3); + writer.WriteUnsigned(0, isArm ? 2 : 1); + writer.Write(0, 2); + + CdacGcInfo info = Assert.IsType(DecodeCdac(writer, machine, version)); + Assert.Equal(4u, info.ValidRangeStart); + Assert.Equal(5u, info.ValidRangeEnd); + Assert.Null(info.Header.GSCookie); + Assert.Equal(flags == 0x02 ? stackOffset : null, info.SecurityObjectStackSlot); + Assert.Equal(flags == 0x10 ? stackOffset : null, info.Header.GenericsInstContext?.SpOffset); + Assert.Equal(writer.ByteCount, info.Size); + } + [Theory] [InlineData(Machine.Amd64, 3)] [InlineData(Machine.ArmThumb2, 2)] 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 5f7debb1024cb3..167a3b9c614ccf 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/TestCases/R2RTestSuites.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/TestCases/R2RTestSuites.cs @@ -410,6 +410,49 @@ static void Validate(ReadyToRunReader reader) } } + [Theory] + [InlineData(false)] + [InlineData(true)] + public void WasmGcEncodingRejectsOlderReadyToRunHeaders(bool composite) + { + const ushort CompactWasmGcFormatVersion = 35; + 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, 33, 34, 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); + } + } + }, + }, + ])); + } + [Theory] [InlineData(false, false)] [InlineData(false, true)] @@ -1705,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 => @@ -1876,11 +1938,13 @@ static void AssertFrameGcSlot(ReadyToRunMethod method, NativeVarInfo record) { ILCompiler.Reflection.ReadyToRun.Cdac.CdacGcInfo gcInfo = Assert.IsType(method.GcInfo); + Assert.Equal(6, gcInfo.Version); Assert.Equal(0u, gcInfo.NumRegisters); ILCompiler.Reflection.ReadyToRun.Cdac.CdacGcSlot slot = Assert.Single( gcInfo.Slots, candidate => candidate.StackSlot?.SpOffset == record.VariableLocation.Data2); Assert.Equal(GcStackSlotBase.GC_FRAMEREG_REL, slot.StackSlot.Base); + Assert.Equal(GcSlotFlags.GC_SLOT_PINNED | GcSlotFlags.GC_SLOT_UNTRACKED, slot.Flags); } static void AssertSafepointCovered(ReadyToRunMethod method, RuntimeFunction root, params NativeVarInfo[] records) 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) { 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/Cdac/CdacGcInfo.cs b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Cdac/CdacGcInfo.cs index b9e31796fc2724..16a1dd94ec3904 100644 --- a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Cdac/CdacGcInfo.cs +++ b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Cdac/CdacGcInfo.cs @@ -120,7 +120,7 @@ private static CdacGcInfo Create(GcInfoDecoder decoder, ImageT slot.RegisterNumber, slot.SpOffset, (GcStackSlotBase)slot.Base, - // The shared decoder does not record GC_SLOT_UNTRACKED on the untracked slots it decodes. + // The shared decoder does not mark untracked slots before version 6. i >= numTracked ? (GcSlotFlags)slot.Flags | GcSlotFlags.GC_SLOT_UNTRACKED : (GcSlotFlags)slot.Flags, result)); } diff --git a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/ILCompiler.Reflection.ReadyToRun.csproj b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/ILCompiler.Reflection.ReadyToRun.csproj index 49d56dea656c61..765aec56cf5435 100644 --- a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/ILCompiler.Reflection.ReadyToRun.csproj +++ b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/ILCompiler.Reflection.ReadyToRun.csproj @@ -32,7 +32,7 @@ - + $(RepoRoot)src\native\managed\cdac\Microsoft.Diagnostics.DataContractReader.Abstractions\ $(RepoRoot)src\native\managed\cdac\Microsoft.Diagnostics.DataContractReader.Contracts\ diff --git a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/NativeReader.cs b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/NativeReader.cs index 006f3ce1aafdb1..eb3695897f2602 100644 --- a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/NativeReader.cs +++ b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/NativeReader.cs @@ -393,7 +393,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); @@ -403,7 +403,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 761bc6c90db3cf..006450f62cebf6 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 35.0+ uses GCInfo v6. + return readyToRunMajorVersion >= 35 ? 6 : 5; } } diff --git a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/ReadyToRunReader.cs b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/ReadyToRunReader.cs index de991dc6ecd8bd..37161a09ca6bdb 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/tools/aot/ILCompiler.Reflection.ReadyToRun/Wasm32/UnwindInfo.cs b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/Wasm32/UnwindInfo.cs index 368d371d386f8f..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: - /// BytesUnwind (frame size), followed by VirtualIPCount (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 = imageReader.ReadULEB128(ref offset); - 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 8276e1c741447a..2f677e5fb9ad9f 100644 --- a/src/coreclr/vm/codeman.cpp +++ b/src/coreclr/vm/codeman.cpp @@ -1304,8 +1304,7 @@ PTR_VOID GetUnwindDataBlob(TADDR moduleBase, PTR_RUNTIME_FUNCTION pRuntimeFuncti #elif defined(TARGET_WASMARCH) 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 @@ -6823,19 +6822,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 { @@ -6875,9 +6861,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 0aaa216065e93e..f61f07283826b1 100644 --- a/src/coreclr/vm/codeman.h +++ b/src/coreclr/vm/codeman.h @@ -2960,7 +2960,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 517115a094c711..75d0827990dfa7 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 817f23366ba66b..50a472f27d2e17 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 (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) | + 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) @@ -128,7 +137,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 = 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); m_ValidRangeStart = DenormalizeCodeOffset(normPrologSize); @@ -138,7 +148,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 = 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 m_ValidRangeEnd = m_ValidRangeStart + 1; @@ -211,7 +222,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(GcInfoEncoding::USES_COMPACT_WASM_HEADER ? 0 : + (UINT32)m_Reader.DecodeVarLengthUnsigned(GcInfoEncoding::STACK_BASE_REGISTER_ENCBASE)); } else { @@ -278,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) ); @@ -302,7 +316,7 @@ TGcInfoDecoder::TGcInfoDecoder( } else { - if (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); @@ -370,8 +384,10 @@ TGcInfoDecoder::TGcInfoDecoder( } #ifdef PARTIALLY_INTERRUPTIBLE_GC_SUPPORTED - m_NumSafePoints = (UINT32) m_Reader.DecodeVarLengthUnsigned(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 if (slimHeader || !GcInfoEncoding::HAS_INTERRUPTIBLE_RANGES) @@ -384,7 +400,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 +417,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 +785,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 //------------------------------------------------------------------------------ - slotDecoder.DecodeSlotTable(m_Reader); + slotDecoder.DecodeSlotTable(m_Reader, Version()); if (reportUntrackedOnly) goto ReportUntracked; + if constexpr (GcInfoEncoding::HAS_TRACKED_SLOTS) { UINT32 numSlots = slotDecoder.GetNumTracked(); @@ -1140,7 +1161,7 @@ template void TGcInfoDecoder::Enumerat // Read the slot table //------------------------------------------------------------------------------ - slotDecoder.DecodeSlotTable(m_Reader); + slotDecoder.DecodeSlotTable(m_Reader, Version()); if (slotDecoder.GetNumUntracked()) { @@ -1169,11 +1190,23 @@ template void TGcInfoDecoder::ReportUn } } -template void GcSlotDecoder::DecodeSlotTable(BitStreamReader& reader) +template void GcSlotDecoder::DecodeSlotTable(BitStreamReader& reader, UINT32 version) { - if (reader.ReadOneFast()) +#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) { - 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 { @@ -1190,19 +1223,19 @@ template void GcSlotDecoder::DecodeSlo numStackSlots = 0; m_NumUntracked = 0; } - m_NumSlots = m_NumRegisters + numStackSlots + m_NumUntracked; + _ASSERTE(GcInfoEncoding::HAS_TRACKED_SLOTS || numStackSlots == 0); + m_NumSlots = GetNumRegisters() + (GcInfoEncoding::HAS_TRACKED_SLOTS ? numStackSlots : 0) + m_NumUntracked; UINT32 i = 0; - if(m_NumRegisters > 0) + if(GcInfoEncoding::HAS_REGISTER_SLOTS && m_NumRegisters > 0) { // We certainly predecode the first register _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; @@ -1210,54 +1243,31 @@ 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; } } - 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 - GcStackSlotBase spBase = (GcStackSlotBase) reader.Read(2); - UINT32 normSpOffset = (INT32) reader.DecodeVarLengthSigned(GcInfoEncoding::STACK_SLOT_ENCBASE); + GcStackSlotBase spBase; + GcSlotFlags flags = GC_SLOT_BASE; + UINT32 normSpOffset = ReadStackSlot(reader, flags, spBase, 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); - - 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 = ReadStackSlot(reader, flags, spBase, normSpOffset, false); + spOffset = GcInfoEncoding::DENORMALIZE_STACK_SLOT(normSpOffset); m_SlotArray[i].Slot.Stack.SpOffset = spOffset; m_SlotArray[i].Slot.Stack.Base = spBase; @@ -1271,10 +1281,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; + GcSlotFlags flags = GC_SLOT_BASE; + UINT32 normSpOffset = ReadStackSlot(reader, flags, spBase, 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; @@ -1283,20 +1293,8 @@ template void GcSlotDecoder::DecodeSlo UINT32 loopEnd = _min(m_NumSlots, MAX_PREDECODED_SLOTS); for(i++; i < loopEnd; i++) { - spBase = (GcStackSlotBase) reader.Read(2); - - 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 = ReadStackSlot(reader, flags, spBase, normSpOffset, false); + spOffset = GcInfoEncoding::DENORMALIZE_STACK_SLOT(normSpOffset); m_SlotArray[i].Slot.Stack.SpOffset = spOffset; m_SlotArray[i].Slot.Stack.Base = spBase; @@ -1319,62 +1317,41 @@ 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(; i < m_NumRegisters; i++) + 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(numStackSlots > 0) + if(GcInfoEncoding::HAS_TRACKED_SLOTS && 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); + ReadStackSlot(reader, flags, spBase, 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); - - if(flags) - { - reader.DecodeVarLengthSigned(GcInfoEncoding::STACK_SLOT_ENCBASE); - flags = (GcSlotFlags) reader.Read(2); - } - else - { - reader.DecodeVarLengthUnsigned(GcInfoEncoding::STACK_SLOT_DELTA_ENCBASE); - } + ReadStackSlot(reader, flags, spBase, 0, false); } } if(m_NumUntracked > 0) { - if(i == m_NumRegisters + numStackSlots) + if(i == GetNumTracked()) { // Skip the first untracked slot - reader.Read(2); - reader.DecodeVarLengthSigned(GcInfoEncoding::STACK_SLOT_ENCBASE); - flags = (GcSlotFlags) reader.Read(2); + ReadStackSlot(reader, flags, spBase, 0, true); i++; } @@ -1382,17 +1359,7 @@ template void GcSlotDecoder::DecodeSlo for(; i < m_NumSlots; i++) { - reader.Read(2); - - if(flags) - { - reader.DecodeVarLengthSigned(GcInfoEncoding::STACK_SLOT_ENCBASE); - flags = (GcSlotFlags) reader.Read(2); - } - else - { - reader.DecodeVarLengthUnsigned(GcInfoEncoding::STACK_SLOT_DELTA_ENCBASE); - } + ReadStackSlot(reader, flags, spBase, 0, false); } } } @@ -1412,34 +1379,14 @@ 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 { @@ -1447,31 +1394,11 @@ template 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()); + INT32 previousOffset = first ? 0 : GcInfoEncoding::NORMALIZE_STACK_SLOT(m_pLastSlot->Slot.Stack.SpOffset); + 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); } m_NumDecodedSlots++; diff --git a/src/coreclr/vm/proftoeeinterfaceimpl.cpp b/src/coreclr/vm/proftoeeinterfaceimpl.cpp index c40b4896d7e78e..05e5ace83e1b52 100644 --- a/src/coreclr/vm/proftoeeinterfaceimpl.cpp +++ b/src/coreclr/vm/proftoeeinterfaceimpl.cpp @@ -8358,7 +8358,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 ee05cad4ba0526..03990b58614143 100644 --- a/src/coreclr/vm/readytoruninfo.cpp +++ b/src/coreclr/vm/readytoruninfo.cpp @@ -2940,21 +2940,19 @@ PCODE DynamicHelpers::CreateDictionaryLookupHelper(LoaderAllocator * pAllocator, #endif // FEATURE_STUBPRECODE_DYNAMIC_HELPERS #ifdef TARGET_WASMARCH -// 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) @@ -3066,11 +3064,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 86f1392800cb3b..61fe772d12b158 100644 --- a/src/coreclr/vm/wasm/helpers.cpp +++ b/src/coreclr/vm/wasm/helpers.cpp @@ -704,8 +704,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); } @@ -1909,7 +1910,10 @@ 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 + 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 54a26e2e7c45c6..498a74cda3aba4 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 @@ -196,10 +197,10 @@ private uint GetR2RGCInfoVersion(Data.ReadyToRunInfo r2rInfo) { Data.ReadyToRunHeader header = Target.ProcessedData.GetOrAdd(r2rInfo.ReadyToRunHeader); - // R2R 33, the runtime's minimum supported major version, still uses GCInfo version 5. // Retain historical mappings for older target dumps; see readytorun.h for versioning details. return header.MajorVersion switch { + >= 35 => 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 dfa5694cc5d3f9..87f9227b04a202 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 @@ -193,9 +193,35 @@ 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); + 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) + { + 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() { - if (_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); } @@ -213,27 +239,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) + bool absolute = i == 0 || flags != 0; + if (_gcVersion >= 6) { - regNum = _reader.DecodeVarLengthUnsigned(TTraits.REGISTER_ENCBASE, ref _bitOffset); - flags = (GcSlotFlags)_reader.ReadBits(2, ref _bitOffset); - } - else - { - 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) { @@ -301,6 +336,27 @@ private IEnumerable DecodeSlotTable() yield break; } + // GCInfo v6 stack-slot decoding. + 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) @@ -373,7 +429,7 @@ private IEnumerable DecodeHeader() private IEnumerable DecodeSlimHeader() { - if (_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); @@ -414,7 +470,7 @@ private IEnumerable DecodeSlimHeader() yield return DecodePoints.ReversePInvoke; yield return DecodePoints.StackParameterArea; - if (PartiallyInterruptibleGCSupported) + if (PartiallyInterruptibleGCSupported && !TTraits.USES_COMPACT_WASM_HEADER) { _numSafePoints = _reader.DecodeVarLengthUnsigned(TTraits.NUM_SAFE_POINTS_ENCBASE, ref _bitOffset); } @@ -424,8 +480,17 @@ private IEnumerable DecodeSlimHeader() private IEnumerable DecodeFatHeader() { - int numFlagBits = _gcVersion == 1 ? (int)GcInfoHeaderFlags.GC_INFO_FLAGS_BIT_SIZE_VERSION_1 : (int)GcInfoHeaderFlags.GC_INFO_FLAGS_BIT_SIZE; - _headerFlags = (GcInfoHeaderFlags)_reader.ReadBits(numFlagBits, ref _bitOffset); + 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)) | + GcInfoHeaderFlags.GC_INFO_HAS_STACK_BASE_REGISTER; + } + else + { + int numFlagBits = _gcVersion == 1 ? (int)GcInfoHeaderFlags.GC_INFO_FLAGS_BIT_SIZE_VERSION_1 : (int)GcInfoHeaderFlags.GC_INFO_FLAGS_BIT_SIZE; + _headerFlags = (GcInfoHeaderFlags)_reader.ReadBits(numFlagBits, ref _bitOffset); + } if (HasReturnKind) _returnKind = (uint)_reader.ReadBits(TTraits.SIZE_OF_RETURN_KIND_IN_FAT_HEADER, ref _bitOffset); @@ -442,7 +507,8 @@ private IEnumerable DecodeFatHeader() uint normCodeLength = IsLegacyFormat ? NormalizeCodeOffset(_codeLength) : TTraits.NormalizeCodeLength(_codeLength); // Decode prolog/epilog information - uint normPrologSize = _reader.DecodeVarLengthUnsigned(TTraits.NORM_PROLOG_SIZE_ENCBASE, ref _bitOffset) + 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); _validRangeStart = DenormalizeCodeOffset(normPrologSize); @@ -453,7 +519,8 @@ private IEnumerable DecodeFatHeader() || HasLegacySecurityObject) { // Decode prolog information - uint normPrologSize = _reader.DecodeVarLengthUnsigned(TTraits.NORM_PROLOG_SIZE_ENCBASE, ref _bitOffset) + 1; + uint normPrologSize = TTraits.USES_COMPACT_WASM_HEADER ? 1 : + _reader.DecodeVarLengthUnsigned(TTraits.NORM_PROLOG_SIZE_ENCBASE, ref _bitOffset) + 1; _validRangeStart = DenormalizeCodeOffset(normPrologSize); // satisfy asserts that assume m_GSCookieValidRangeStart != 0 ==> m_GSCookieValidRangeStart < m_GSCookieValidRangeEnd _validRangeEnd = _validRangeStart + 1; @@ -485,7 +552,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(TTraits.USES_COMPACT_WASM_HEADER ? 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)) 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 7877e5fdbb7926..80733a242ee3be 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 11b7e00cb879d6..b5ed199acbf957 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 45399e3ac8c634..20811af08beaec 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 @@ -29,10 +29,11 @@ public enum RegMask public record X86GCInfo : IGCInfoDecoder { - // Versions 1 through 4 share the same x86 encoding. Versions before 4 only occur in ReadyToRun - // images, which the cDAC never decodes; ILCompiler.Reflection.ReadyToRun (R2RDump) shares this decoder. + // Versions 1 through 4 share the same x86 encoding. R2RDump can encounter versions before 4 + // in older ReadyToRun images. The cDAC also decodes ReadyToRun images, but only supports + // .NET 11 and later, so it does not encounter those older versions. private const uint MINIMUM_SUPPORTED_GCINFO_VERSION = 1; - private const uint MAXIMUM_SUPPORTED_GCINFO_VERSION = 5; + private const uint MAXIMUM_SUPPORTED_GCINFO_VERSION = 6; private readonly Target _target; @@ -336,8 +337,7 @@ private ImmutableArray DecodeUntrackedSlots() // stack offset. On EBP-frames the offset is EBP-relative; on ESP-frames it is // ESP-relative. Double-aligned frames use a hybrid encoding: offsets that lie // above the frame are EBP-relative even when the rest of the frame is ESP-based. - // Reference: gc_unwind_x86.inl (EnumGcRefsX86 untracked path) and - // ILCompiler.Reflection.ReadyToRun/x86/GcSlotTable.cs (DecodeUntracked). + // Reference: gc_unwind_x86.inl (EnumGcRefsX86 untracked path). uint calleeSavedRegsCount = 0; if (Header.DoubleAlign) { @@ -393,8 +393,7 @@ private ImmutableArray DecodeVarPtrLifetimes() // Each entry is three unsigned varints: (varOffs, begOffs, endOffs). // varOffs is absolute; begOffs is delta-from-previous-begOffs; endOffs is delta-from-begOffs. // Low 2 bits of varOffs are flags matching LiveSlot.GcFlags (0x1 = byref/interior, 0x2 = pinned). - // Reference: gc_unwind_x86.inl varPtrTable processing and - // ILCompiler.Reflection.ReadyToRun/x86/GcSlotTable.cs (DecodeFrameVariableLifetimeTable). + // Reference: gc_unwind_x86.inl varPtrTable processing. ImmutableArray.Builder builder = ImmutableArray.CreateBuilder((int)Header.VarPtrTableSize); uint curOffs = 0; for (uint i = 0; i < Header.VarPtrTableSize; i++) 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 a03c40959b0a70..45b49591521596 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); } @@ -182,10 +183,9 @@ public TargetCodePointer GetVirtualIP(TargetPointer sp) if (!_r2rInfo.TryGetVirtualIPBase(frameIdentity, out ulong baseVirtualIP, out TargetPointer unwindData) || baseVirtualIP == 0) return TargetCodePointer.Null; - ulong address = unwindData.Value; - DecodeULEB128(ref address); // Skip the fixed frame size. - uint virtualIPLength = DecodeULEB128(ref address); - uint functionLocalVirtualIP = virtualIPLength == 2 ? 2 : _target.Read(frameBase.Value + VirtualIpOffset) * 2; + DecodeUnwindData(unwindData, out _, out uint virtualIPCount); + // A count of 4 covers only the prolog and the sole observable IP, whose store is elided. + uint functionLocalVirtualIP = virtualIPCount == 4 ? 2 : _target.Read(frameBase.Value + VirtualIpOffset) * 2; return new TargetCodePointer(baseVirtualIP + functionLocalVirtualIP); } @@ -214,8 +214,7 @@ public bool TryUnwindOneFrame(ref TargetPointer sp, TargetCodePointer controlPC, } ulong frameIdentity = ReadFrameIdentity(frameBase.Value); - ulong address = unwindData.Value; - uint frameSize = DecodeULEB128(ref address); + DecodeUnwindData(unwindData, out uint frameSize, out _); if (frameSize == 0) { // A zero frame size makes no progress; terminate rather than risk an unbounded walk. @@ -256,22 +255,14 @@ 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(ref ulong address) + // Mirrors the native DecodeWasmUnwindInfo: the frame size (16-byte units) and virtual IP count + // (2-IP units) are interleaved in one uint64 ULEB128 value. + private void DecodeUnwindData(TargetPointer unwindData, out uint frameSize, out uint virtualIPCount) { - const int MaxBytes = 5; - uint result = 0; - int shift = 0; - for (ulong offset = 0; offset < MaxBytes; offset++) - { - byte b = _target.Read(address++); - result |= (uint)(b & 0x7F) << shift; - if ((b & 0x80) == 0) - return result; - shift += 7; - } - - throw new InvalidOperationException("Malformed ULEB128 value in WASM unwind data."); + ulong encoded = UnwindDataSize.ReadWasmUnwindData(_target, unwindData, out _); + frameSize = (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; } } diff --git a/src/native/managed/cdac/tests/UnitTests/ExecutionManager/ExecutionManagerTests.cs b/src/native/managed/cdac/tests/UnitTests/ExecutionManager/ExecutionManagerTests.cs index f02bc29965930b..2e3b1657105b93 100644 --- a/src/native/managed/cdac/tests/UnitTests/ExecutionManager/ExecutionManagerTests.cs +++ b/src/native/managed/cdac/tests/UnitTests/ExecutionManager/ExecutionManagerTests.cs @@ -540,6 +540,8 @@ public void ReadyToRunInfo_WasmMissingOptionalFields_TryReadAllFields() [InlineData(21, 5u)] [InlineData(32, 5u)] [InlineData(33, 5u)] + [InlineData(34, 5u)] + [InlineData(35, 6u)] public void GetGCInfo_R2R_WasmVirtualIPUsesLoadedImageBase(ushort majorVersion, uint expectedGCVersion) { MockTarget.Architecture wasmArch = new() { IsLittleEndian = true, Is64Bit = false }; @@ -562,13 +564,13 @@ public void GetGCInfo_R2R_WasmVirtualIPUsesLoadedImageBase(ushort majorVersion, MockReadyToRunInfo r2rInfo = emBuilder.AddReadyToRunInfo([FunctionBeginAddress], []); r2rInfo.MinVirtualIP = VirtualIPRangeStart; r2rInfo.LoadedImageBase = LoadedImageBase; - r2rInfo.ReadyToRunHeader = emBuilder.AddReadyToRunHeader(majorVersion).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", }); @@ -581,7 +583,7 @@ public void GetGCInfo_R2R_WasmVirtualIPUsesLoadedImageBase(ushort majorVersion, IGCInfoHandle gcInfoHandle = Mock.Of(); Mock gcInfoContract = new(MockBehavior.Strict); - gcInfoContract.Setup(c => c.DecodePlatformSpecificGCInfo(new TargetPointer(LoadedImageBase + UnwindDataRva + 3), expectedGCVersion)) + gcInfoContract.Setup(c => c.DecodePlatformSpecificGCInfo(new TargetPointer(LoadedImageBase + UnwindDataRva + 2), expectedGCVersion)) .Returns(gcInfoHandle); gcInfoContract.Setup(c => c.GetCodeLength(gcInfoHandle)).Returns(32u); Target target = CreateTarget( @@ -595,7 +597,7 @@ public void GetGCInfo_R2R_WasmVirtualIPUsesLoadedImageBase(ushort majorVersion, Assert.NotNull(handle); em.GetGCInfo(handle.Value, out TargetPointer gcInfo, out uint gcVersion); - Assert.Equal(new TargetPointer(LoadedImageBase + UnwindDataRva + 3), gcInfo); + 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); diff --git a/src/native/managed/cdac/tests/UnitTests/GCInfoTests.cs b/src/native/managed/cdac/tests/UnitTests/GCInfoTests.cs index 9dbfeac8063a02..1a1df7a5c1caed 100644 --- a/src/native/managed/cdac/tests/UnitTests/GCInfoTests.cs +++ b/src/native/managed/cdac/tests/UnitTests/GCInfoTests.cs @@ -6,6 +6,7 @@ using System.Runtime.InteropServices; using System.Runtime.InteropServices.Marshalling; using Microsoft.Diagnostics.DataContractReader.Contracts; +using Microsoft.Diagnostics.DataContractReader.Contracts.GCInfoHelpers; using Microsoft.Diagnostics.DataContractReader.Contracts.GCInfoHelpers.X86; using Microsoft.Diagnostics.DataContractReader.Legacy; using Microsoft.Diagnostics.DataContractReader.TestInfrastructure; @@ -18,6 +19,206 @@ 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 })] + [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 })] + [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 = wasm ? -8 + i % 2 : i % 2 == 0 ? 8 : -8; + Assert.Equal(offset * slotSize, slots[i].SpOffset); + 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); + } + + 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] + [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)] + [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(false, new byte[] { 0x0A, 0x80, 0xB0, 0x10, 0x88, 0x00 })] + [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); + 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); + }); + + SOSGCSlotLifetime[] inspected = InspectGCInfoSlots(RuntimeInfoArchitecture.X64, interpreter, decoder, 5); + Assert.Equal(0u, inspected[0].BaseRegister); + Assert.Equal(1u, inspected[1].BaseRegister); + } + + [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, 6); + 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()); + } + [Theory] [ClassData(typeof(MockTarget.StdArch))] public void QueryInterfaceFromIXCLRDataProcess_ExposesGCInfo(MockTarget.Architecture arch) @@ -334,6 +535,7 @@ public void X86RegisterLifetimesPreserveLiveInteriorFlags(uint version, bool sur [Theory] [InlineData(4u)] [InlineData(5u)] + [InlineData(6u)] public void X86PointerLocationsFollowPushPopAndKill(uint version) { (IGCInfo gcInfo, IGCInfoHandle handle, _) = CreateX86GCInfo( @@ -880,4 +1082,58 @@ 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() + { + 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 b70584fb8094bc..42e5bda091f449 100644 --- a/src/native/managed/cdac/tests/UnitTests/StackWalkTests.cs +++ b/src/native/managed/cdac/tests/UnitTests/StackWalkTests.cs @@ -927,16 +927,16 @@ public void TransitionFrame_ThisUsesFrameReceiverKind( } [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); @@ -953,15 +953,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)); @@ -3145,10 +3146,11 @@ private static TargetPointer AddWasmR2RFunctions( { 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); - Assert.True(functions[i].FrameSize < 0x80); - MockMemorySpace.HeapFragment unwindData = allocator.Allocate(2, "UnwindData"); - unwindData.Data[0] = functions[i].FrameSize; - unwindData.Data[1] = 3; + Assert.Equal(0, functions[i].FrameSize % 16); + Assert.True(functions[i].FrameSize / 16 < 0x10); + MockMemorySpace.HeapFragment unwindData = allocator.Allocate(1, "UnwindData"); + // Packed frame size (16-byte units) in bits 0-3 and a non-singleton virtual IP count (2-IP units) in bits 4-7. + unwindData.Data[0] = (byte)((functions[i].FrameSize / 16) | 0x30); 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 e972904a51a6e1..f12e00924270f9 100644 --- a/src/native/managed/cdac/tests/UnitTests/WasmUnwinderTests.cs +++ b/src/native/managed/cdac/tests/UnitTests/WasmUnwinderTests.cs @@ -72,7 +72,7 @@ private static TestPlaceholderTarget CreateTarget(MockMemorySpace.HeapFragment[] private static TestPlaceholderTarget CreateTarget(MockTarget.Architecture arch, MockMemorySpace.HeapFragment[] fragments) { TestPlaceholderTarget.Builder builder = new(arch); - builder.MemoryBuilder.AddHeapFragment(Blob(BlobsBase + 0x100, [0, 3], "defaultMultiIPUnwind")); + builder.MemoryBuilder.AddHeapFragment(Blob(BlobsBase + 0x100, [0x30], "defaultMultiIPUnwind")); foreach (MockMemorySpace.HeapFragment fragment in fragments) builder.MemoryBuilder.AddHeapFragment(fragment); return builder.Build(); @@ -253,13 +253,39 @@ public void GetVirtualIP_SingleVirtualIP_IgnoresUninitializedSlot(uint slotValue TestPlaceholderTarget target = CreateTarget( [ Frame(FramesBase, FuncIndexLeaf, slotValue, "leaf"), - Blob(BlobsBase, [0x80, 1, 2], "singleIPUnwind"), + Blob(BlobsBase, [0x28], "singleIPUnwind"), ]); WasmUnwinder unwinder = new(target, info); Assert.Equal(VirtualIpBase + 2, unwinder.GetVirtualIP(new TargetPointer(FramesBase)).Value); } + [Theory] + [InlineData(0xffff_ffff_ffff_fffdUL, false)] + [InlineData(0x0000_0001_8000_0001UL, true)] + public void TryUnwindOneFrame_Wasm64_DecodesPackedFrameAndPointerWidthIdentity(ulong frameIdentity, bool reversePInvokeRoot) + { + const ulong leafBase = 0x1_0001_0000; + const ulong callerBase = leafBase + 0x110; + + FakeWasmR2RInfo info = new(); + info.VirtualIpBases[FuncIndexCaller] = VirtualIpBase; + info.UnwindData[LeafControlPc] = BlobsBase; + + TestPlaceholderTarget target = CreateTarget(Wasm64Arch, + [ + Frame64(leafBase, frameIdentity, 3, "leaf"), + Frame64(callerBase, FuncIndexCaller, 7, "caller"), + Blob(BlobsBase, [0x81, 0x02], "leafUnwind"), + ]); + WasmUnwinder unwinder = new(target, info); + + TargetPointer sp = new(leafBase); + Assert.True(unwinder.TryUnwindOneFrame(ref sp, new TargetCodePointer(LeafControlPc), out TargetCodePointer ip)); + Assert.Equal(callerBase, sp.Value); + Assert.Equal(reversePInvokeRoot ? TargetCodePointer.Null : new TargetCodePointer(VirtualIpBase + 14), ip); + } + [Fact] public void TryUnwindOneFrame_AdvancesBySingleByteFrameSize_AndYieldsCallerVirtualIP() { @@ -275,7 +301,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); @@ -298,7 +324,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() @@ -315,10 +341,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(); @@ -330,7 +359,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); @@ -352,7 +381,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); @@ -375,7 +404,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() @@ -421,8 +450,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; @@ -431,7 +462,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); @@ -440,8 +471,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; @@ -449,8 +482,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); @@ -587,11 +619,10 @@ private static TestPlaceholderTarget CreateProducerLayoutTarget(LinearStack stac FakeExecutionManager executionManager = new(); for (int i = 0; i < functions.Length; i++) { - // Unwind data holds the frame size and virtual IP extent, both ULEB128. - Assert.True(functions[i].FrameSize < 0x80); - MockMemorySpace.HeapFragment unwindData = allocator.Allocate(2, "UnwindData"); - unwindData.Data[0] = (byte)functions[i].FrameSize; - unwindData.Data[1] = 0x60; + // Packed frame size (16-byte units) in bits 0-3 and a non-singleton virtual IP count (2-IP units) in bits 4-7. + Assert.True(functions[i].FrameSize / 16 < 0x10); + MockMemorySpace.HeapFragment unwindData = allocator.Allocate(1, "UnwindData"); + unwindData.Data[0] = (byte)((functions[i].FrameSize / 16) | 0x30); 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);