Skip to content

Commit def2794

Browse files
lewingCopilot
andauthored
[cDAC][wasm] Keep caller SP for non-R2R callers and restore SoftwareExceptionFrame FP (#135494)
Aligns the wasm cDAC R2R unwinder with native `WasmUnwindStackFrameCore` and `UpdateRegDisplay_Impl`: - **Non-R2R caller:** keep the caller SP with a null IP and FP instead of clearing SP. Otherwise an R2R method whose active `InlinedCallFrame` lives in its own frame is reported repeatedly, because the walker never gets past that frame. - **`SoftwareExceptionFrame`:** restore FP along with IP and SP. FP (`InterpreterFP`) is wasm's only callee-saved register, but the `CalleeSavedRegisters` descriptor is empty on wasm, so FP was left over from the previous frame. - **Inactive `InlinedCallFrame`:** return before writing the interpreter-frame stash, as native does. `StackWalk.md` is updated. The earlier reverse P/Invoke check was dropped after #135440 identified those roots from the tagged frame identity. <details><summary>Not included</summary> - `IStackWalk.GetRuntimeFramePointer` on wasm: native `GetRegdisplayStackMark` has no `TARGET_WASM` implementation to mirror. - Leaf FP when a walk starts inside a funclet (#135147), which depends on #134608. </details> > [!NOTE] > This PR description was generated with GitHub Copilot. --------- Co-authored-by: Copilot App <[email protected]> Copilot-Session: cf17d923-d419-4c13-bcb4-094d592f8243
1 parent dd28b74 commit def2794

6 files changed

Lines changed: 249 additions & 16 deletions

File tree

‎docs/design/datacontracts/StackWalk.md‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -450,7 +450,7 @@ Most of the handlers are implemented in `BaseFrameHandler`. Platform specific co
450450

451451
#### InlinedCallFrame
452452

453-
InlinedCallFrames store and update only the IP, SP, and FP of a given context. If the stored IP (CallerReturnAddress) is 0 then the InlinedCallFrame does not have an active call and should not update the context.
453+
InlinedCallFrames store and update only the IP, SP, and FP of a given context. If the stored IP (CallerReturnAddress) is 0 then the InlinedCallFrame does not have an active call and should not update the context. On WASM this includes recording the following `InterpreterFrame` for the interpreter unwind.
454454

455455
* On ARM, the InlinedCallFrame stores the value of the SP after the prolog (`SPAfterProlog`) to allow unwinding for functions with stackalloc. When a function uses stackalloc, the CallSiteSP can already have been adjusted. This value should be placed in R9.
456456
* On WASM, a `CallerReturnAddress` of `INLINED_PINVOKE_FROM_R2R` (`1`) marks an active inlined P/Invoke from ReadyToRun code rather than an address. SP is taken from `CallSiteSP`, IP is the R2R virtual IP of the shadow frame at `CallSiteSP`, and FP is the WASM logical frame pointer at `CallSiteSP` (see below). If no virtual IP can be recovered, IP is set to null.
@@ -463,6 +463,8 @@ An active InlinedCallFrame stays the current Frame after its context update so t
463463

464464
SoftwareExceptionFrames store a copy of the context struct. The IP, SP, and all ABI specified (platform specific) callee-saved registers are copied from the stored context to the working context.
465465

466+
On WASM the only callee-saved register is the frame pointer (`InterpreterFP`), and the `CalleeSavedRegisters` data descriptor is empty, so the IP, SP and FP are copied explicitly from the stored context (native `SoftwareExceptionFrame::UpdateRegDisplay_Impl`).
467+
466468
**Return Address**: Read from the `ReturnAddress` field on the frame.
467469

468470
#### TransitionFrame
@@ -488,7 +490,27 @@ A funclet instead stores its establishing-frame pointer plus two, giving the ide
488490

489491
**WASM R2R unwinding.** The virtual IP is the identity-derived method base plus twice the physical frame's stored function-local value. `WasmContext.Unwind` passes its current virtual IP as the control PC to `IExecutionManager.TryGetUnwindInfo`, reads the fixed frame size as a uint32 ULEB128 value from `unwindInfoBaseAddress + RuntimeFunction.UnwindData`, and adds that size to the physical frame base. A zero frame size terminates the R2R walk because it would make no progress; malformed uint32 ULEB128 data is invalid.
490492

491-
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. At a terminator or another non-R2R caller, the R2R context is cleared and walking continues through the explicit `Frame` or interpreter frame chain.
493+
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.
494+
495+
```csharp
496+
// WasmContext.Unwind: one R2R frame, mirroring native RtlVirtualUnwind / WasmUnwindStackFrameCore.
497+
void Unwind()
498+
{
499+
TargetPointer frameBase = /* frame base of the R2R frame at SP */;
500+
uint identity = target.Read<uint>(frameBase + FrameIdentityOffset);
501+
uint frameSize = /* ULEB128 in the unwind data of the function containing IP */;
502+
if (/* no frame at SP, no unwind data, or frameSize == 0 */)
503+
{
504+
SP = IP = FP = null;
505+
return;
506+
}
507+
508+
SP = frameBase + frameSize;
509+
bool callerIsNative = identity is odd && (int)identity > 0; // reverse P/Invoke root
510+
IP = callerIsNative ? null : /* R2R virtual IP at SP, or null when SP has no R2R frame record */;
511+
FP = IP != null ? /* WASM logical frame pointer at SP */ : null;
512+
}
513+
```
492514

493515
**Return Address**: Read from `TransitionBlock.ReturnAddress`. On WASM, it is derived from `TransitionBlock.StackPointer` when it is 0, as above. For an x86 `StubDispatchFrame` with neither a method nor a GCRefMap, subtract five bytes to return the adjusted call address, matching the context update.
494516

‎src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/StackWalk/Context/Wasm/WasmUnwinder.cs‎

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -155,9 +155,11 @@ public TargetCodePointer GetVirtualIP(TargetPointer sp)
155155

156156
/// <summary>
157157
/// Advances <paramref name="sp"/> by one R2R frame and produces the caller's virtual IP,
158-
/// mirroring <c>WasmUnwindStackFrameCore</c>. Returns false when the R2R walk terminates
159-
/// (no R2R frame at <paramref name="sp"/>), in which case <paramref name="sp"/> is set to
160-
/// <see cref="TargetPointer.Null"/>.
158+
/// mirroring <c>WasmUnwindStackFrameCore</c>. Returns false when the R2R walk cannot advance
159+
/// (no R2R frame at <paramref name="sp"/>, missing unwind data, or a zero frame size), in
160+
/// which case <paramref name="sp"/> is set to <see cref="TargetPointer.Null"/>. Otherwise
161+
/// <paramref name="sp"/> is the caller's stack pointer, and <paramref name="ip"/> is null when
162+
/// the caller is not ReadyToRun code.
161163
/// </summary>
162164
public bool TryUnwindOneFrame(ref TargetPointer sp, TargetCodePointer controlPC, out TargetCodePointer ip)
163165
{
@@ -192,14 +194,9 @@ public bool TryUnwindOneFrame(ref TargetPointer sp, TargetCodePointer controlPC,
192194
return true;
193195
}
194196

197+
// A null IP means the caller is not R2R code (an interpreter transition or the stack top).
198+
// Like native, keep the caller's SP so the walk continues through the Frame chain.
195199
ip = GetVirtualIP(sp);
196-
if (ip == TargetCodePointer.Null)
197-
{
198-
// The caller is not R2R-generated code (an interpreter transition or the stack top);
199-
// the R2R walk is exhausted.
200-
sp = TargetPointer.Null;
201-
return false;
202-
}
203200

204201
return true;
205202
}

‎src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/StackWalk/Context/WasmContext.cs‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -85,9 +85,10 @@ public void Unwind(Target target)
8585

8686
internal void Unwind(Wasm.WasmUnwinder unwinder)
8787
{
88-
// Advance one ReadyToRun frame over the managed linear stack. When the R2R walk
89-
// terminates (an interpreter transition or the stack top), StackPointer becomes null and
90-
// the caller falls back to the explicit Frame chain / interpreter frame chain.
88+
// Advance one ReadyToRun frame over the managed linear stack. When the caller is not R2R
89+
// code (an interpreter transition, native code above a reverse P/Invoke, or the stack top),
90+
// StackPointer is the caller's SP and the IP and FP are null; the walker continues through
91+
// the explicit Frame chain / interpreter frame chain.
9192
TargetPointer sp = StackPointer;
9293
if (unwinder.TryUnwindOneFrame(ref sp, InstructionPointer, out TargetCodePointer ip))
9394
{

‎src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/StackWalk/FrameHandling/WasmFrameHandler.cs‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,8 @@ namespace Microsoft.Diagnostics.DataContractReader.Contracts.StackWalkHelpers;
1818
/// pointer) into the three synthetic <see cref="WasmContext"/> slots, which is the common
1919
/// P/Invoke-boundary seeding path; an inlined P/Invoke from R2R code instead stores a marker and is
2020
/// resolved from its R2R shadow frame. The software/faulting exception frame handlers likewise read a
21-
/// serialized <see cref="WasmContext"/> blob from the frame's <c>TargetContext</c>.
21+
/// serialized <see cref="WasmContext"/> blob from the frame's <c>TargetContext</c>, restoring
22+
/// IP, SP and the frame pointer.
2223
///
2324
/// Hijack frames are a debugger / GC-suspension concept that is not yet supported on WASM.
2425
/// </remarks>
@@ -33,6 +34,11 @@ internal sealed class WasmFrameHandler(Target target, ContextHolder<WasmContext>
3334

3435
public override void HandleInlinedCallFrame(InlinedCallFrame inlinedCallFrame)
3536
{
37+
// Native InlinedCallFrame::UpdateRegDisplay_Impl returns before any update, including the
38+
// interpreter-frame stash below, when the frame has no active call.
39+
if (inlinedCallFrame.CallerReturnAddress == TargetCodePointer.Null)
40+
return;
41+
3642
if (inlinedCallFrame.CallerReturnAddress.Value == InlinedPInvokeFromR2R)
3743
{
3844
// Mirrors InlinedCallFrame::UpdateRegDisplay_Impl in src/coreclr/vm/wasm/helpers.cpp.
@@ -64,6 +70,18 @@ public override void HandleInlinedCallFrame(InlinedCallFrame inlinedCallFrame)
6470
}
6571
}
6672

73+
// Native restores FP with IP and SP, but the CalleeSavedRegisters descriptor is empty on WASM,
74+
// so the base handler would leave FP stale.
75+
public override void HandleSoftwareExceptionFrame(SoftwareExceptionFrame softwareExceptionFrame)
76+
{
77+
ContextHolder<WasmContext> saved = new();
78+
saved.ReadFromAddress(_target, softwareExceptionFrame.TargetContext);
79+
80+
_holder.Context.InstructionPointer = saved.Context.InstructionPointer;
81+
_holder.Context.StackPointer = saved.Context.StackPointer;
82+
_holder.Context.FramePointer = saved.Context.FramePointer;
83+
}
84+
6785
// Mirrors TransitionFrame::UpdateRegDisplay_Impl in src/coreclr/vm/wasm/helpers.cpp. With a recorded
6886
// R2R stack pointer and a known return address, the caller is the R2R frame at that stack pointer
6987
// (TransitionFrame::GetSP); otherwise the caller's stack pointer is the end of the TransitionBlock.

‎src/native/managed/cdac/tests/UnitTests/StackWalkTests.cs‎

Lines changed: 165 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1546,6 +1546,80 @@ public void CreateStackWalk_WasmInterpreterFrameEnteredFromR2R_ContinuesIntoR2RC
15461546
Assert.True(walked.Length <= 7, $"Walk did not terminate: {walked.Length} frames");
15471547
}
15481548

1549+
// Unwinding keeps the caller's SP when the caller is not R2R, so the walk passes the
1550+
// InlinedCallFrame in the method's own frame and reports the method once.
1551+
[Fact]
1552+
public void CreateStackWalk_WasmR2RMethodWithNonR2RCaller_PassesInlinedCallFrameInItsFrame()
1553+
{
1554+
MockTarget.Architecture wasmArch = new() { IsLittleEndian = true, Is64Bit = false };
1555+
const uint FunctionTableIndex = 5;
1556+
const ulong MinVirtualIP = 0x8001_0000;
1557+
const uint FunctionBeginAddress = 0x100;
1558+
const uint LocalVirtualIPHalf = 3;
1559+
const byte R2RFrameSize = 0x70;
1560+
const ulong R2RIp = MinVirtualIP + FunctionBeginAddress + LocalVirtualIPHalf * 2;
1561+
const ulong InlinedPInvokeFromR2R = 1;
1562+
const uint TerminateR2RStackWalk = 1;
1563+
1564+
MockThread? thread = null;
1565+
MockInlinedCallFrame? icf = null;
1566+
int icfSize = 0;
1567+
ulong r2rFrame = 0;
1568+
TargetPointer runtimeFunctionAddress = TargetPointer.Null;
1569+
TestPlaceholderTarget target = CreateTarget(
1570+
wasmArch,
1571+
threadBuilder => thread = threadBuilder.AddThread(1, 1234),
1572+
frameBuilder =>
1573+
{
1574+
icf = frameBuilder.AddInlinedCallFrame(InlinedPInvokeFromR2R, datum: 0);
1575+
icfSize = frameBuilder.InlinedCallFrameLayout.Size;
1576+
},
1577+
runtimeArchitecture: RuntimeInfoArchitecture.Wasm,
1578+
configureTarget: targetBuilder =>
1579+
{
1580+
TargetTestHelpers helpers = targetBuilder.MemoryBuilder.TargetTestHelpers;
1581+
MockMemorySpace.BumpAllocator allocator = targetBuilder.MemoryBuilder.CreateAllocator(0x0020_0000, 0x0020_4000);
1582+
runtimeFunctionAddress = AddWasmR2RFunction(targetBuilder, allocator, FunctionTableIndex, MinVirtualIP, FunctionBeginAddress, R2RFrameSize);
1583+
uint frameIdentity = AddWasmPortableEntryPoint(targetBuilder, allocator, FunctionTableIndex);
1584+
AddWasmNullDebugger(targetBuilder, allocator);
1585+
1586+
// The method's frame record sits just below the InlinedCallFrame, and its caller's
1587+
// stack pointer is above it. The caller slot holds TERMINATE_R2R_STACK_WALK, so the
1588+
// caller has no R2R virtual IP.
1589+
r2rFrame = icf!.Address - 0x10;
1590+
ulong callerSp = r2rFrame + R2RFrameSize;
1591+
Assert.True(icf.Address + (ulong)icfSize <= callerSp);
1592+
1593+
byte[] record = new byte[8];
1594+
helpers.Write(record.AsSpan(0, sizeof(uint)), frameIdentity);
1595+
helpers.Write(record.AsSpan(4, sizeof(uint)), LocalVirtualIPHalf);
1596+
targetBuilder.MemoryBuilder.AddHeapFragment(new MockMemorySpace.HeapFragment { Address = r2rFrame, Data = record, Name = "R2RFrame" });
1597+
1598+
byte[] callerRecord = new byte[8];
1599+
helpers.Write(callerRecord.AsSpan(0, sizeof(uint)), TerminateR2RStackWalk);
1600+
targetBuilder.MemoryBuilder.AddHeapFragment(new MockMemorySpace.HeapFragment { Address = callerSp, Data = callerRecord, Name = "NonR2RCaller" });
1601+
1602+
icf.CallSiteSP = r2rFrame;
1603+
thread!.Frame = icf.Address;
1604+
},
1605+
executionManager: CreateInterpreterExecutionManager(
1606+
[],
1607+
managedIps: [R2RIp],
1608+
unwindInfo: () => (runtimeFunctionAddress, TargetPointer.Null)));
1609+
1610+
IStackWalk stackWalk = target.Contracts.StackWalk;
1611+
ThreadData threadData = target.Contracts.Thread.GetThreadData(new TargetPointer(thread!.Address));
1612+
IStackDataFrameHandle[] walked = stackWalk.CreateStackWalk(threadData).Take(16).ToArray();
1613+
1614+
(ulong Ip, ulong Sp)[] frameless = walked
1615+
.Where(f => f.State == StackWalkState.Frameless)
1616+
.Select(f => (stackWalk.GetInstructionPointer(f).Value, stackWalk.GetStackPointer(f).Value))
1617+
.ToArray();
1618+
1619+
Assert.Equal([(R2RIp, r2rFrame)], frameless);
1620+
Assert.True(walked.Length <= 3, $"Walk did not terminate: {walked.Length} frames");
1621+
}
1622+
15491623
private sealed class InterpreterExecutionManager : IExecutionManager
15501624
{
15511625
private readonly ulong[] _interpreterIps;
@@ -1745,6 +1819,97 @@ private static TargetPointer AddWasmR2RFunctions(
17451819
return runtimeFunctions.Address;
17461820
}
17471821

1822+
/// <summary>
1823+
/// Native InlinedCallFrame::UpdateRegDisplay_Impl returns before recording the owning
1824+
/// InterpreterFrame when the frame has no active call.
1825+
/// </summary>
1826+
[Fact]
1827+
public void UpdateContextFromFrame_WasmInactiveInlinedCallFrameOverInterpreterFrame_LeavesContextUnchanged()
1828+
{
1829+
MockTarget.Architecture wasmArch = new() { IsLittleEndian = true, Is64Bit = false };
1830+
1831+
ulong icfAddr = 0;
1832+
TestPlaceholderTarget target = CreateTarget(
1833+
wasmArch,
1834+
threadBuilder => threadBuilder.AddThread(1, 1234),
1835+
frameBuilder =>
1836+
{
1837+
ulong interpAddr = frameBuilder.AddFrame(MockFrameBuilder.InterpreterFrameIdentifierValue, "InterpreterFrame").Address;
1838+
MockInlinedCallFrame icf = frameBuilder.AddInlinedCallFrame(callerReturnAddress: 0, datum: 0, callSiteSP: 0x0004_1000);
1839+
icf.Next = interpAddr;
1840+
icfAddr = icf.Address;
1841+
});
1842+
1843+
ContextHolder<WasmContext> context = new();
1844+
context.Context.StackPointer = new TargetPointer(0x0005_0000);
1845+
context.Context.InstructionPointer = new TargetCodePointer(0x0005_1000);
1846+
context.Context.FramePointer = new TargetPointer(0x0005_2000);
1847+
FrameHelpers frameHelpers = new(target);
1848+
Data.Frame frame = target.ProcessedData.GetOrAdd<Data.Frame>(icfAddr);
1849+
frameHelpers.UpdateContextFromFrame(frame, context);
1850+
1851+
Assert.True(context.TryReadRegister(WasmContext.InterpreterWalkFramePointerRegister, out TargetNUInt stashed));
1852+
Assert.Equal(0ul, stashed.Value);
1853+
Assert.Equal(0x0005_0000ul, context.StackPointer.Value);
1854+
Assert.Equal(0x0005_1000ul, context.InstructionPointer.Value);
1855+
Assert.Equal(0x0005_2000ul, context.FramePointer.Value);
1856+
}
1857+
1858+
/// <summary>
1859+
/// On WASM the callee-saved register set is InterpreterFP, so a SoftwareExceptionFrame restores
1860+
/// the frame pointer from its saved context along with IP and SP (native
1861+
/// SoftwareExceptionFrame::UpdateRegDisplay_Impl). WASM's CalleeSavedRegisters descriptor is
1862+
/// empty, so the frame pointer must not be left from the previous frame.
1863+
/// </summary>
1864+
[Fact]
1865+
public void UpdateContextFromFrame_WasmSoftwareExceptionFrame_RestoresFramePointer()
1866+
{
1867+
MockTarget.Architecture wasmArch = new() { IsLittleEndian = true, Is64Bit = false };
1868+
TargetTestHelpers helpers = new(wasmArch);
1869+
const ulong FrameAddress = 0x0006_0000;
1870+
const int ReturnAddressOffset = 8;
1871+
const int TargetContextOffset = 12;
1872+
1873+
// WasmContext layout: ContextFlags, InterpreterWalkFramePointer, InterpreterSP, InterpreterFP, InterpreterIP.
1874+
byte[] data = new byte[TargetContextOffset + 5 * sizeof(uint)];
1875+
helpers.Write(data.AsSpan(0, sizeof(uint)), (uint)MockFrameBuilder.SoftwareExceptionFrameIdentifierValue);
1876+
helpers.Write(data.AsSpan(TargetContextOffset + 8, sizeof(uint)), 0x0004_1000u);
1877+
helpers.Write(data.AsSpan(TargetContextOffset + 12, sizeof(uint)), 0x0004_1040u);
1878+
helpers.Write(data.AsSpan(TargetContextOffset + 16, sizeof(uint)), 0x8001_0106u);
1879+
1880+
TestPlaceholderTarget target = CreateTarget(
1881+
wasmArch,
1882+
threadBuilder => threadBuilder.AddThread(1, 1234),
1883+
frameBuilder => { },
1884+
runtimeArchitecture: RuntimeInfoArchitecture.Wasm,
1885+
configureTarget: builder =>
1886+
{
1887+
builder.MemoryBuilder.AddHeapFragment(new MockMemorySpace.HeapFragment { Address = FrameAddress, Data = data, Name = "SoftwareExceptionFrame" });
1888+
builder.AddTypes(new Dictionary<DataType, Target.TypeInfo>
1889+
{
1890+
[DataType.SoftwareExceptionFrame] = new()
1891+
{
1892+
Fields = new Dictionary<string, Target.FieldInfo>
1893+
{
1894+
[nameof(Data.SoftwareExceptionFrame.ReturnAddress)] = new() { Offset = ReturnAddressOffset, TypeName = "CodePointer" },
1895+
[nameof(Data.SoftwareExceptionFrame.TargetContext)] = new() { Offset = TargetContextOffset },
1896+
},
1897+
},
1898+
[DataType.CalleeSavedRegisters] = new() { Fields = new Dictionary<string, Target.FieldInfo>() },
1899+
});
1900+
});
1901+
1902+
ContextHolder<WasmContext> context = new();
1903+
context.Context.FramePointer = new TargetPointer(0x0007_0000);
1904+
FrameHelpers frameHelpers = new(target);
1905+
Data.Frame frame = target.ProcessedData.GetOrAdd<Data.Frame>(new TargetPointer(FrameAddress));
1906+
frameHelpers.UpdateContextFromFrame(frame, context);
1907+
1908+
Assert.Equal(0x0004_1000ul, context.StackPointer.Value);
1909+
Assert.Equal(0x8001_0106ul, context.InstructionPointer.Value);
1910+
Assert.Equal(0x0004_1040ul, context.FramePointer.Value);
1911+
}
1912+
17481913
// When an active InlinedCallFrame is directly followed by an InterpreterFrame, WasmFrameHandler
17491914
// stashes the InterpreterFrame address into the synthetic first-argument register
17501915
// (InterpreterWalkFramePointer) so the subsequent interpreter virtual unwind can recover the

0 commit comments

Comments
 (0)