Skip to content

Commit 716a871

Browse files
lewingCopilot
andauthored
[cDAC][wasm] Continue stack walks from a TransitionFrame into its R2R caller (#135140)
On WASM, a cDAC `IStackWalk` walk drops every R2R frame between an `InterpreterFrame` and the next explicit Frame when R2R code entered the interpreter through a transition helper, such as the portable-entry-point thunk `WasmR2RToInterpreterThunk` → `ExecuteInterpretedMethodWithArgs_PortableEntryPoint`. The walk covers the interpreted chain, reports `NativeMarker ip=0 sp=<end of TransitionBlock>`, and jumps to the next Frame. The walk still ends and every reported frame is named, so frames go missing without any error. ## Cause On WASM such a helper records the R2R caller's linear-stack pointer in `TransitionBlock.m_StackPointer`, and may leave `m_ReturnAddress` 0. Native handles that in `src/coreclr/vm/frames.h` and `src/coreclr/vm/wasm/helpers.cpp`: - `FramedMethodFrame::GetTransitionBlock_Impl` fills a 0 return address lazily with `GetWasmVirtualIPFromStackPointer(m_StackPointer)`. - `TransitionFrame::GetSP` returns `m_StackPointer` when both fields are set, and `UpdateRegDisplay_Impl` uses those values plus that frame's frame pointer. The cDAC didn't describe `m_StackPointer`, and `BaseFrameHandler.HandleTransitionFrame` used the raw return address (0) and the end of the TransitionBlock. ## Changes - `datadescriptor.inc`: describe `TransitionBlock.StackPointer` under `TARGET_WASM`; it's an optional field (`Data.TransitionBlock.StackPointer`). - `FrameHelpers.GetTransitionBlockReturnAddress`: if the return address is 0 and `StackPointer` is set, derive the R2R virtual IP from it (`WasmUnwinder.GetVirtualIP`). `GetReturnAddress` uses this for all TransitionFrame types. - `WasmFrameHandler.HandleTransitionFrame`: when `StackPointer` is set and a return address is known, the caller's SP is `StackPointer` and its FP is the WASM logical frame pointer there (see below). Otherwise the SP is the end of the TransitionBlock and the FP is null. The same path runs when the interpreted chain under an `InterpreterFrame` is exhausted (`InterpreterVirtualUnwind` → `ApplyInterpreterFrameTransition`). - `WasmContext.Unwind`: recompute the frame pointer from each caller's stack pointer, as native `WasmUnwindStackFrame` does. Before, every R2R caller after the first kept the previous frame's frame pointer. - Funclet-aware logical frame pointer, mirroring native `GetWasmFramePointerFromStackPointer`, adapted from #133890. `IWasmR2RInfo.TryIsFunclet` reads the `RUNTIME_FUNCTION` funclet bit. `WasmUnwinder.TryGetLogicalFramePointer` returns a method's own frame base. For a funclet, it unwinds out to the establishing frame: either the parent method or funclet, or the frame pointer stored beside the `TERMINATE_R2R_STACK_WALK` marker when the VM invoked the funclet through `CallFuncletWith[out]Throwable`. Each step must move toward the caller. `WasmContext.Unwind` and both R2R seeding paths (the `InlinedCallFrame` marker and `HandleTransitionFrame`) use it. - `StackWalk.md` TransitionFrame section updated, and the generated tables regenerated. #133890 carries an overlapping version of this fix and the logical frame pointer, and will drop its copy when it restacks. ## Validation - `./dotnet.sh test src/native/managed/cdac/tests/UnitTests/Microsoft.Diagnostics.DataContractReader.Tests.csproj`: **passed**, 3266/3266. - `pwsh src/native/managed/cdac/tools/CdacUsageGraph/generate-docs.ps1 -Check`: **passed**, docs up to date. - `./build.sh -os browser -c Debug -subset clr.runtime`: **passed**. The generated descriptor lays out `TransitionBlock` as `ReturnAddress`@0, `StackPointer`@4, size 8. - New tests: - `UpdateContextFromFrame_WasmTransitionFrame_MirrorsNativeTransitionBlock`: four cases, return address and stack pointer each set or 0. - `CreateStackWalk_WasmInterpreterFrameEnteredFromR2R_ContinuesIntoR2RCaller`: the walk continues from an exhausted interpreted chain into two R2R callers, checking each one's IP, SP and frame pointer. - `WasmUnwinderTests.Unwind_ProducerLayout_*` (six cases): funclet linear-stack layouts taken from the JIT and runtime producers. They cover a finally called by its parent (with and without localloc), a funclet invoked by the VM (catch, and filter with the throwing frames still live), and nested finallys. Each uses real R2R function-table data and checks SP, IP and FP for every frame through `WasmContext.Unwind`. - `UpdateContextFromFrame_WasmFuncletCaller_ReportsEstablishingFramePointer`: both R2R seeding paths report the establishing frame pointer for a VM-invoked funclet. Each new test fails with its fix removed: - TransitionFrame change reverted: the walk test and both stack-pointer cases fail; the other two cases pass, as expected. - Only the `WasmContext.Unwind` FP change reverted: the walk test fails on the outer caller's frame pointer. - Frame base instead of the logical frame pointer: both seeding cases fail (checked on this branch), and all six producer-layout cases fail (checked when they were written, on `main` @ `25c3eaec650`). - Live browser-wasm validation through Blazor-Playground/nesm, with nesm's workarounds and frame guard off: Release runtime packs built from `9977dd27dc2` (descriptor `TransitionBlock.StackPointer`@4), with the reader at `dd4ec1e0b6e` and again at `30047665a62` (funclet commits included; no reader-attributable differences; only interpreter bytecode addresses and async-pause depth vary between runs). - R2R paused at a breakpoint: **pass**. Seeded from the frame chain (13 frames) and from a leaf `$sp` (21 frames). The 8 R2R CoreLib frames the issue reported missing (`IntrinsicInvokeHelper.InvokeEmitted` … `<BindManagedFunction>b__0`) now appear between the interpreted wrapper and the next `InterpreterFrame`, in wasm-stack order. Their names match a separate static ReadyToRun lookup. The `NativeMarker ip=0 sp=<TransitionBlock end>` is gone. - R2R paused in a `[JSImport]` call (23 frames), and interpreter-only paused in a tight loop (18) and in a `[JSImport]` call (22): **pass**. Every walk completes with no errors. - Funclets, reader `30047665a62`: an R2R app breaking inside each funclet layout: finally called by its parent (with and without localloc), catch and finally invoked by the VM, a finally nested in a VM-invoked catch, and a filter. Both seeds complete in every scenario. Each unwound funclet frame reports its establishing frame's frame pointer, and the localloc parent reports FP ≠ SP from its indirect slot. Finallys called by their parent were marked `NoOptimization`, because otherwise the JIT clones them and no funclet runs. This checks consistency with the parent frame's frame pointer, not a direct comparison with native. Not covered: a leaf funclet that makes no calls has no frame record. Neither native nor the cDAC can walk it, so it's only visible at a debugger pause inside it. Open #134608 may change that layout. Starting a walk inside a funclet still takes the leaf frame pointer from the frame base, tracked in #135147. Resolves #135137 > [!NOTE] > This PR description was generated with assistance from GitHub Copilot. --------- Co-authored-by: Copilot App <[email protected]>
1 parent 4d1b425 commit 716a871

12 files changed

Lines changed: 769 additions & 34 deletions

File tree

‎docs/design/datacontracts/StackWalk.md‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,7 @@ Unwinding call frames on the stack usually requires an OS specific implementatio
196196
| `ResumableFrame` | `TargetContextPtr` | `pointer` | Pointer to the Frame's Target Context |
197197
| `RuntimeFunction` | *(type size)* | `uint32` | Size of a runtime function entry in bytes |
198198
| `RuntimeFunction` | `BeginAddress` | `uint32` | Begin address of the function. On ARM32, bit 0 is the Thumb bit; on WebAssembly, bit 31 marks a funclet and is excluded from address arithmetic. |
199+
| `RuntimeFunction` | `UnwindData` | `uint32` | Pointer to the unwind info for the function |
199200
| `SoftwareExceptionFrame` | `ReturnAddress` | `CodePointer` | Return address saved in Frame |
200201
| `SoftwareExceptionFrame` | `TargetContext` | `pointer` | Context object saved in Frame |
201202
| `String` | `m_StringLength` | `uint32` | Length of the string in UTF-16 characters |
@@ -212,6 +213,7 @@ Unwinding call frames on the stack usually requires an OS specific implementatio
212213
| `TransitionBlock` | `CalleeSavedRegisters` | `pointer` | Platform specific CalleeSavedRegisters struct associated with the TransitionBlock |
213214
| `TransitionBlock` | `FirstGCRefMapSlot` | `pointer` | Byte offset where GCRefMap slot enumeration begins. ARM64: RetBuffArgReg offset; others: ArgumentRegisters offset |
214215
| `TransitionBlock` | `ReturnAddress` | `CodePointer` | Return address associated with the TransitionBlock |
216+
| `TransitionBlock` | `StackPointer` | `pointer` | WASM only: R2R linear-stack pointer of the caller, saved by the transition helper |
215217
| `VASigCookie` | `SizeOfArgs` | `uint32` | Total size in bytes of the varargs argument area; used on x86 to locate the argument base |
216218

217219
### Global variables used
@@ -451,7 +453,7 @@ Most of the handlers are implemented in `BaseFrameHandler`. Platform specific co
451453
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.
452454

453455
* 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.
454-
* 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 that shadow frame's base. If no virtual IP can be recovered, IP is set to null.
456+
* 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.
455457

456458
An active InlinedCallFrame stays the current Frame after its context update so the skipped-Frame check can step past it once the walk reaches the managed caller. If the updated IP is not managed code (for example, no WASM R2R virtual IP could be recovered), the walk fails, matching native `StackFrameIterator::NextRaw`; otherwise it would never advance past the Frame.
457459

@@ -472,8 +474,11 @@ When updating the context from a TransitionFrame, the IP, SP, and all ABI specif
472474
* On ARM, the additional register values stored in `ArgumentRegisters` are copied over. The `TransitionBlock` holds a pointer to the `ArgumentRegister` struct containing these values.
473475
* On x86, the caller SP also skips callee-popped stack arguments. For `ExternalMethodFrame` and `StubDispatchFrame`, the argument size comes from the frame's GCRefMap, including when its MethodDesc is null. `ReadStackPop()` gives the number of pointer-sized slots to add to the SP. If no GCRefMap is available, MethodDesc-backed frames use the argument map computed from their signature. `PInvokeCalliFrame` instead uses `VASigCookie.SizeOfArgs`.
474476
* For an x86 `StubDispatchFrame` without a GCRefMap, resolve its method from the stored MethodDesc or its representative MethodTable and slot. If no method is available, the SP stays at the end of the transition block and the IP is adjusted to the call instruction by subtracting five bytes from the saved return address.
477+
* On WASM, a transition helper called from R2R code records the caller's R2R linear-stack pointer in `TransitionBlock.StackPointer`, and may leave `ReturnAddress` 0. When `ReturnAddress` is 0 and `StackPointer` is set, the return address is the R2R virtual IP of the frame at `StackPointer` (native `FramedMethodFrame::GetTransitionBlock_Impl`). When `StackPointer` is set and a return address is known, the caller's SP is `StackPointer` and its FP is the WASM logical frame pointer at `StackPointer` (native `TransitionFrame::GetSP`); otherwise the SP is the end of the TransitionBlock and the FP is null. This also applies when the interpreted chain under an `InterpreterFrame` is exhausted and the walker applies the `InterpreterFrame`'s transition.
475478

476-
**Return Address**: Read from `TransitionBlock.ReturnAddress`. For an x86 `StubDispatchFrame` with neither a method nor a GCRefMap, subtract five bytes to return the adjusted call address, matching the context update.
479+
**WASM logical frame pointer.** R2R frames on WASM keep a record on the linear stack: the function-table index, then the function-local virtual IP / 2. Unwinding one frame (`WasmContext.Unwind`) adds the function's frame size from its unwind data to the frame base, and sets the caller's FP as native `GetWasmFramePointerFromStackPointer` does. For a method, the FP is its own frame base. For a funclet (its `RUNTIME_FUNCTION.BeginAddress` has bit 31 set), the FP is the establishing method's frame. The walker unwinds out of the funclet: if the caller slot holds the `TERMINATE_R2R_STACK_WALK` marker, the funclet was invoked by the VM through `CallFuncletWith[out]Throwable`, and the establishing frame pointer is stored one pointer after the marker. Otherwise the funclet was called by its parent method or funclet, and the walker repeats from there. Each step must move toward the caller, or the frame pointer is unknown (null).
480+
481+
**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.
477482

478483
The following Frame types also use this mechanism:
479484
* FramedMethodFrame

‎docs/design/datacontracts/data-descriptor-meanings.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -696,6 +696,7 @@
696696
"TransitionBlock.FirstGCRefMapSlot": "Byte offset where GCRefMap slot enumeration begins. ARM64: RetBuffArgReg offset; others: ArgumentRegisters offset",
697697
"TransitionBlock.ReturnAddress": "Return address associated with the TransitionBlock",
698698
"TransitionBlock.Size": "Size in bytes of the transition block, used to restore the caller's stack pointer",
699+
"TransitionBlock.StackPointer": "WASM only: R2R linear-stack pointer of the caller, saved by the transition helper",
699700
"TypedByRef.Data": "Managed pointer (the byref) stored in a System.TypedReference value",
700701
"TypedByRef.Type": "Raw TypeHandle pointer of the referent type",
701702
"type.Size": "Size in bytes of each SHash table entry",

‎src/coreclr/vm/datadescriptor/datadescriptor.inc‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1311,6 +1311,9 @@ CDAC_TYPE_END(InterpreterFrame)
13111311
CDAC_TYPE_BEGIN(TransitionBlock)
13121312
CDAC_TYPE_SIZE(sizeof(TransitionBlock))
13131313
CDAC_TYPE_FIELD(TransitionBlock, TYPE(CodePointer), ReturnAddress, offsetof(TransitionBlock, m_ReturnAddress))
1314+
#ifdef TARGET_WASM
1315+
CDAC_TYPE_FIELD(TransitionBlock, T_POINTER, StackPointer, offsetof(TransitionBlock, m_StackPointer))
1316+
#endif // TARGET_WASM
13141317
CDAC_TYPE_FIELD(TransitionBlock, TYPE(CalleeSavedRegisters), CalleeSavedRegisters, offsetof(TransitionBlock, m_calleeSavedRegisters))
13151318
// Offset to argument registers and first GCRefMap slot (platform-specific)
13161319
#if (defined(TARGET_AMD64) && !defined(UNIX_AMD64_ABI)) || defined(TARGET_WASM)

‎src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/ExecutionManager/Helpers/WasmFunctionTableIndexLookup.cs‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,19 @@ public bool TryGetVirtualIPBase(uint functionTableIndex, out ulong baseVirtualIP
9393
}
9494
}
9595

96+
// Mirrors ExecutionManager::IsFuncletFunctionIndex.
97+
public bool TryIsFunclet(uint functionTableIndex, out bool isFunclet)
98+
{
99+
isFunclet = false;
100+
Data.FunctionTableIndexRangeSection? section = FindSection(functionTableIndex);
101+
if (section is null)
102+
return false;
103+
104+
Data.ReadyToRunInfo r2rInfo = GetReadyToRunInfo(section);
105+
isFunclet = _runtimeFunctions.IsFunclet(GetRuntimeFunction(r2rInfo, functionTableIndex - section.MinFunctionTableIndex));
106+
return true;
107+
}
108+
96109
public bool TryGetUnwindData(uint functionTableIndex, out TargetPointer unwindDataAddress)
97110
{
98111
unwindDataAddress = TargetPointer.Null;

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,4 +23,7 @@ public bool TryGetVirtualIPBase(uint functionTableIndex, out ulong baseVirtualIP
2323

2424
public bool TryGetUnwindData(uint functionTableIndex, out TargetPointer unwindDataAddress)
2525
=> _lookup.TryGetUnwindData(functionTableIndex, out unwindDataAddress);
26+
27+
public bool TryIsFunclet(uint functionTableIndex, out bool isFunclet)
28+
=> _lookup.TryIsFunclet(functionTableIndex, out isFunclet);
2629
}

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

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,13 @@ internal interface IWasmR2RInfo
2626
/// frame size. Returns false when the index does not map to a known R2R function.
2727
/// </summary>
2828
bool TryGetUnwindData(uint functionTableIndex, out TargetPointer unwindDataAddress);
29+
30+
/// <summary>
31+
/// Reports whether an R2R function table entry is a funclet rather than a method's root
32+
/// function (<c>ExecutionManager::IsFuncletFunctionIndex</c>). Returns false when the index
33+
/// does not map to a known R2R function.
34+
/// </summary>
35+
bool TryIsFunclet(uint functionTableIndex, out bool isFunclet);
2936
}
3037

3138
/// <summary>
@@ -174,6 +181,87 @@ public bool TryUnwindOneFrame(ref TargetPointer sp, out TargetCodePointer ip)
174181
return true;
175182
}
176183

184+
/// <summary>
185+
/// Advances <paramref name="sp"/> by one R2R frame and returns the caller's stack pointer,
186+
/// without requiring the caller to be R2R-generated code. This is the frame-size half of
187+
/// <c>WasmUnwindStackFrameCore</c>, which <see cref="TryGetLogicalFramePointer"/> needs in
188+
/// order to inspect a synthetic <see cref="TerminateR2RStackWalk"/> frame.
189+
/// </summary>
190+
private bool TryUnwindToCallerStackPointer(TargetPointer sp, out TargetPointer callerSp)
191+
{
192+
callerSp = TargetPointer.Null;
193+
if (!TryGetFramePointer(sp, out TargetPointer frameBase))
194+
return false;
195+
196+
uint functionIndex = _target.Read<uint>(frameBase.Value + FunctionIndexOffset);
197+
if (!_r2rInfo.TryGetUnwindData(functionIndex, out TargetPointer unwindData))
198+
return false;
199+
200+
uint frameSize = DecodeULEB128(unwindData.Value);
201+
if (frameSize == 0)
202+
return false;
203+
204+
callerSp = new TargetPointer(frameBase.Value + frameSize);
205+
return true;
206+
}
207+
208+
/// <summary>
209+
/// Returns the logical (establishing) frame pointer for the frame at <paramref name="sp"/>,
210+
/// mirroring <c>GetWasmFramePointerFromStackPointer</c> in
211+
/// <c>src/coreclr/vm/wasm/helpers.cpp</c>.
212+
/// </summary>
213+
/// <remarks>
214+
/// For a method's root function this is its own frame base. For a funclet it is the frame
215+
/// base of the establishing method: the funclet's FP local is the FP its caller passed in
216+
/// (<c>WasmRegAlloc::AllocateFramePointer</c>, <c>CodeGen::genCallFinally</c>), so reaching it
217+
/// means unwinding out of the funclet, either to its containing method or funclet, or to the
218+
/// synthetic <see cref="TerminateR2RStackWalk"/> frame that
219+
/// <c>CallFuncletWith[out]Throwable</c> pushes, which carries the establishing frame pointer
220+
/// beside the marker.
221+
/// </remarks>
222+
public bool TryGetLogicalFramePointer(TargetPointer sp, out TargetPointer framePointer)
223+
{
224+
framePointer = TargetPointer.Null;
225+
226+
// Native recurses until it reaches a non-funclet frame or a CallFunclet terminator. The
227+
// cDAC reads untrusted memory, so require each step to move toward the caller; the step
228+
// count is only a backstop.
229+
const int MaxUnwindSteps = 4096;
230+
TargetPointer current = sp;
231+
232+
for (int i = 0; i < MaxUnwindSteps; i++)
233+
{
234+
if (!TryGetFramePointer(current, out TargetPointer frameBase))
235+
return false;
236+
237+
uint functionIndex = _target.Read<uint>(frameBase.Value + FunctionIndexOffset);
238+
// Native treats an unknown index as a root function; report no frame pointer instead.
239+
if (!_r2rInfo.TryIsFunclet(functionIndex, out bool isFunclet))
240+
return false;
241+
242+
if (!isFunclet)
243+
{
244+
framePointer = frameBase;
245+
return true;
246+
}
247+
248+
if (!TryUnwindToCallerStackPointer(current, out TargetPointer callerSp) || callerSp.Value <= current.Value)
249+
return false;
250+
251+
if (_target.Read<uint>(callerSp.Value + FunctionIndexOffset) == TerminateR2RStackWalk)
252+
{
253+
// Invoked by the VM through CallFuncletWith[out]Throwable.
254+
framePointer = GetEstablishingFramePointerFromTerminator(callerSp);
255+
return true;
256+
}
257+
258+
// Called by its containing method or funclet; keep walking out.
259+
current = callerSp;
260+
}
261+
262+
return false;
263+
}
264+
177265
// Standard little-endian base-128 varint, matching the native DecodeULEB128AsU32. A ULEB128
178266
// uint32 is at most 5 bytes (5 * 7 = 35 >= 32 bits); a longer encoding is malformed.
179267
private uint DecodeULEB128(ulong address)

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,11 +88,15 @@ public void Unwind(Target target)
8888
{
8989
StackPointer = sp;
9090
InstructionPointer = ip;
91+
// Native WasmUnwindStackFrame recomputes the caller's frame pointer from its stack pointer;
92+
// funclets report the establishing method's frame base (GetWasmFramePointerFromStackPointer).
93+
FramePointer = unwinder.TryGetLogicalFramePointer(sp, out TargetPointer fp) ? fp : TargetPointer.Null;
9194
}
9295
else
9396
{
9497
StackPointer = TargetPointer.Null;
9598
InstructionPointer = TargetCodePointer.Null;
99+
FramePointer = TargetPointer.Null;
96100
}
97101
}
98102

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

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -286,6 +286,25 @@ public void UpdateContextFromFrame(Data.Frame frame, IPlatformAgnosticContext co
286286
}
287287
}
288288

289+
/// <summary>
290+
/// Returns the return address recorded in <paramref name="transitionBlock"/>. On WASM, a
291+
/// transition helper called from R2R code may store only the caller's linear-stack pointer;
292+
/// the return address is then that frame's R2R virtual IP, matching the lazy computation in
293+
/// native <c>FramedMethodFrame::GetTransitionBlock_Impl</c>.
294+
/// </summary>
295+
public TargetCodePointer GetTransitionBlockReturnAddress(Data.TransitionBlock transitionBlock)
296+
{
297+
if (transitionBlock.ReturnAddress == TargetCodePointer.Null
298+
&& transitionBlock.StackPointer is TargetPointer stackPointer
299+
&& stackPointer != TargetPointer.Null)
300+
{
301+
Wasm.WasmUnwinder unwinder = new(_target, new Wasm.WasmR2RInfo(_target));
302+
return unwinder.GetVirtualIP(stackPointer);
303+
}
304+
305+
return transitionBlock.ReturnAddress;
306+
}
307+
289308
/// <summary>
290309
/// Returns the return address for <paramref name="frame"/>, matching native Frame::GetReturnAddress().
291310
/// Returns TargetCodePointer.Null if the Frame has no return address (e.g., non-active ICF,
@@ -319,7 +338,7 @@ public TargetCodePointer GetReturnAddress(Data.Frame frame)
319338
if (FindGCRefMap(dispatchFrame.Indirection) == TargetPointer.Null)
320339
return new TargetCodePointer((uint)tb.ReturnAddress - X86FrameHandler.CallInstructionSize);
321340
}
322-
return tb.ReturnAddress;
341+
return GetTransitionBlockReturnAddress(tb);
323342

324343
// SoftwareExceptionFrame: stored m_ReturnAddress
325344
case FrameType.SoftwareExceptionFrame:

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

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,8 @@ public override void HandleInlinedCallFrame(InlinedCallFrame inlinedCallFrame)
4141
Wasm.WasmUnwinder unwinder = new(_target, new Wasm.WasmR2RInfo(_target));
4242
_holder.Context.StackPointer = inlinedCallFrame.CallSiteSP;
4343
_holder.Context.InstructionPointer = unwinder.GetVirtualIP(inlinedCallFrame.CallSiteSP);
44-
// Root-function frame base; the funclet-aware logical frame pointer is not modeled yet.
45-
_holder.Context.FramePointer = unwinder.TryGetFramePointer(inlinedCallFrame.CallSiteSP, out TargetPointer framePointer)
44+
// Native GetWasmFramePointerFromStackPointer: a funclet reports its establishing method's frame.
45+
_holder.Context.FramePointer = unwinder.TryGetLogicalFramePointer(inlinedCallFrame.CallSiteSP, out TargetPointer framePointer)
4646
? framePointer
4747
: TargetPointer.Null;
4848
}
@@ -64,6 +64,32 @@ public override void HandleInlinedCallFrame(InlinedCallFrame inlinedCallFrame)
6464
}
6565
}
6666

67+
// Mirrors TransitionFrame::UpdateRegDisplay_Impl in src/coreclr/vm/wasm/helpers.cpp. With a recorded
68+
// R2R stack pointer and a known return address, the caller is the R2R frame at that stack pointer
69+
// (TransitionFrame::GetSP); otherwise the caller's stack pointer is the end of the TransitionBlock.
70+
public override void HandleTransitionFrame(FramedMethodFrame framedMethodFrame)
71+
{
72+
Data.TransitionBlock transitionBlock = _target.ProcessedData.GetOrAdd<Data.TransitionBlock>(framedMethodFrame.TransitionBlockPtr);
73+
TargetCodePointer instructionPointer = _frameHelpers.GetTransitionBlockReturnAddress(transitionBlock);
74+
TargetPointer stackPointer = transitionBlock.StackPointer ?? TargetPointer.Null;
75+
76+
_holder.Context.InstructionPointer = instructionPointer;
77+
if (stackPointer != TargetPointer.Null && instructionPointer != TargetCodePointer.Null)
78+
{
79+
_holder.Context.StackPointer = stackPointer;
80+
// Native GetWasmFramePointerFromStackPointer: a funclet reports its establishing method's frame.
81+
Wasm.WasmUnwinder unwinder = new(_target, new Wasm.WasmR2RInfo(_target));
82+
_holder.Context.FramePointer = unwinder.TryGetLogicalFramePointer(stackPointer, out TargetPointer framePointer)
83+
? framePointer
84+
: TargetPointer.Null;
85+
}
86+
else
87+
{
88+
_holder.Context.StackPointer = framedMethodFrame.TransitionBlockPtr + Data.TransitionBlock.GetSize(_target);
89+
_holder.Context.FramePointer = TargetPointer.Null;
90+
}
91+
}
92+
6793
public void HandleHijackFrame(HijackFrame frame)
6894
=> throw new PlatformNotSupportedException("HijackFrame handling is not supported on WASM.");
6995
}

‎src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Data/Frames/TransitionBlock.cs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@ internal partial class TransitionBlock : IData<TransitionBlock>
88
{
99
[Field] public partial TargetCodePointer ReturnAddress { get; }
1010

11+
// WASM only: the R2R linear-stack pointer of the caller, saved by transition helpers.
12+
[Field] public partial TargetPointer? StackPointer { get; }
13+
1114
[FieldAddress]
1215
public partial TargetPointer CalleeSavedRegisters { get; }
1316

0 commit comments

Comments
 (0)