Skip to content

[cDAC] Implement DacDbi GetStackWalkCurrentFrameInfo - #130646

Merged
rcj1 merged 24 commits into
mainfrom
copilot/implement-getstackwalkcurrentframeinfo
Jul 25, 2026
Merged

rcj1 merged 24 commits into
mainfrom
copilot/implement-getstackwalkcurrentframeinfo

Conversation

@rcj1

@rcj1 rcj1 commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor
  • Add IsVarArg on RuntimeTypeSystem
  • Add
   TargetPointer GetExactGenericArgsToken(IStackDataFrameHandle stackDataFrameHandle) => throw new NotImplementedException();

and supporting APIs on GC info contract
Implement GetStackWalkCurrentFrameInfo DacDbi API

Copilot AI review requested due to automatic review settings July 13, 2026 20:40
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @steveisok, @tommcdon, @dotnet/dotnet-diag
See info in area-owners.md if you want to be subscribed.

@rcj1
rcj1 temporarily deployed to copilot-pat-pool July 13, 2026 20:43 — with GitHub Actions Inactive
@rcj1
rcj1 temporarily deployed to copilot-pat-pool July 13, 2026 20:43 — with GitHub Actions Inactive
@rcj1
rcj1 had a problem deploying to copilot-pat-pool July 13, 2026 20:44 — with GitHub Actions Failure
@rcj1
rcj1 temporarily deployed to copilot-pat-pool July 13, 2026 20:45 — with GitHub Actions Inactive
@rcj1
rcj1 temporarily deployed to copilot-pat-pool July 13, 2026 20:45 — with GitHub Actions Inactive
@rcj1
rcj1 temporarily deployed to copilot-pat-pool July 13, 2026 20:46 — with GitHub Actions Inactive

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR extends the cDAC stack-walking and runtime type system contracts to support richer per-frame debugger data (frame classification, funclet/interrupt state, ambient SP, exact generic args token) and wires that through the legacy DacDbi implementation for GetStackWalkCurrentFrameInfo.

Changes:

  • Implements DacDbiImpl.GetStackWalkCurrentFrameInfo using new StackWalk/GCInfo contract APIs and expands frame classification logic (managed EH helpers, runtime entry point, native runtime-unwindable markers).
  • Extends cDAC contracts/abstractions: async method flags API, varargs detection, well-known MethodTables/MethodDescs, StackWalkFrameInfo, and GCInfo helpers (ambient SP + generic instantiation context slot).
  • Updates unit tests and contract docs to reflect the new async flags behavior and new StackWalk/RuntimeTypeSystem/GCInfo surface.
Show a summary per file
File Description
src/native/managed/cdac/tests/UnitTests/MethodDescTests.cs Updates async-thunk classification test coverage to validate the new GetAsyncMethodFlags semantics (variant/return-dropping flags).
src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Legacy/Dbi/IDacDbiInterface.cs Adds missing legacy enums/constants needed by the new frame-info shaping (FrameType, MAX_ILNUM, mapping result).
src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Legacy/Dbi/DacDbiImpl.cs Implements GetStackWalkCurrentFrameInfo and integrates new async flag checks + vararg + exact generic args token + ambient SP plumbing.
src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/StackWalk/StackWalk_1.ExceptionHandling.cs Adds secondary-walk logic to locate funclet parent method frame info.
src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/StackWalk/StackWalk_1.cs Extends stackwalk handle state (interrupt/fault), and implements GetCurrentFrameInfo + GetExactGenericArgsToken and helpers.
src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/RuntimeTypeSystem_1.cs Adds well-known MT/MD globals accessors, exposes raw async flags, and implements IsVarArg.
src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/IGCInfoDecoder.cs Extends decoder interface with generic-inst-context slot discovery + ambient SP query.
src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/X86/GCInfo.cs Implements ambient SP computation for x86 GC info and reports no generic-inst-context slot for the x86 format.
src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/GCInfoX86_1.cs Plumbs new ambient SP / generic-inst-context APIs through the x86 GCInfo contract.
src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/GCInfoDecoder.cs Implements generic-inst-context stack-slot discovery for the non-x86 decoder; ambient SP returns null for non-x86.
src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/GCInfo/GCInfo_1.cs Plumbs new APIs through the general GCInfo contract surface.
src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Constants.cs Adds new global names for the additional well-known MT/MD pointers.
src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Abstractions/Contracts/IStackWalk.cs Adds StackWalkFrameInfo and new StackWalk APIs needed by DacDbi frame info shaping.
src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Abstractions/Contracts/IRuntimeTypeSystem.cs Adds async flag enum/API, new well-known method desc API, and IsVarArg.
src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Abstractions/Contracts/IGCInfo.cs Adds ambient SP and generic-inst-context slot APIs.
src/coreclr/vm/datadescriptor/datadescriptor.inc Exposes additional well-known MT/MD globals to cDAC.
src/coreclr/inc/gcinfotypes.h Annotates INVALID_SYNC_OFFSET as a cDAC contract dependency.
src/coreclr/inc/eetwain.h Annotates SHADOW_SP_BITS as a cDAC contract dependency.
docs/design/datacontracts/StackWalk.md Documents new StackWalk APIs and frame-info semantics.
docs/design/datacontracts/RuntimeTypeSystem.md Documents new well-known MT/MD and async-flag/vararg APIs.
docs/design/datacontracts/GCInfo.md Documents new GCInfo APIs and the constants they depend on.

Copilot's findings

Comments suppressed due to low confidence (3)

src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Legacy/Dbi/DacDbiImpl.cs:1698

  • GetStackWalkCurrentFrameInfo only writes *pRetVal at the end of the try block. If any exception is thrown before that point, the out-pointer remains uninitialized, which can lead to reading undefined data on the caller side even though an HRESULT failure is returned.
                hr = HResults.S_FALSE;
            }
        }
        catch (System.Exception ex)
        {

src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Legacy/Dbi/DacDbiImpl.cs:5738

  • Avoid Enum.HasFlag here to prevent boxing on a potentially hot path (async locals enumeration).
            Contracts.ModuleHandle handle = loader.GetModuleHandleFromModulePtr(new TargetPointer(pModule));

src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Legacy/Dbi/DacDbiImpl.cs:1833

  • ClassifyManagedFrame calls GetWellKnownMethodTable/GetWellKnownMethodDesc repeatedly. Each call can trigger target reads; caching these values once per classification reduces repeated reads and also avoids accidentally matching TargetPointer.Null if any well-known global isn't initialized.
        catch (System.Exception ex)
        {
            hr = ex.HResult;
        }
#if DEBUG
        if (_legacy is not null)
  • Files reviewed: 21/21 changed files
  • Comments generated: 4

Copilot AI review requested due to automatic review settings July 13, 2026 20:47

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot's findings

  • Files reviewed: 21/21 changed files
  • Comments generated: 6

Copilot AI review requested due to automatic review settings July 13, 2026 22:44
@rcj1
rcj1 temporarily deployed to copilot-pat-pool July 13, 2026 22:44 — with GitHub Actions Inactive
@rcj1
rcj1 temporarily deployed to copilot-pat-pool July 13, 2026 22:45 — with GitHub Actions Inactive
@rcj1
rcj1 had a problem deploying to copilot-pat-pool July 13, 2026 22:46 — with GitHub Actions Failure
@rcj1
rcj1 temporarily deployed to copilot-pat-pool July 13, 2026 22:47 — with GitHub Actions Inactive
@rcj1
rcj1 temporarily deployed to copilot-pat-pool July 13, 2026 22:47 — with GitHub Actions Inactive
@rcj1
rcj1 temporarily deployed to copilot-pat-pool July 13, 2026 22:47 — with GitHub Actions Inactive

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot's findings

  • Files reviewed: 21/21 changed files
  • Comments generated: 4

Copilot AI commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

@copilot please fix the unit tests: https://dev.azure.com/dnceng-public/public/_build/results?buildId=1513742&view=logs&jobId=10cc3096-25b3-5ff2-0b7b-c72bfa82da9b

Fixed in 0a237a2. The cDAC test subset now builds and passes, including all four architecture cases for GetStackWalkCurrentFrameInfo_MissingOptionalMemory_PreservesAvailableData.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot's findings

Comments suppressed due to low confidence (3)

src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Legacy/Dbi/DacDbiImpl.cs:1849

  • GetStackWalkCurrentFrameInfo dereferences pRetVal unconditionally (*pRetVal = ...) but doesn’t validate it for null. This can AV the debugger/DAC process if a null out-pointer is ever passed. Please mirror the E_POINTER checks used by other IDacDbiInterface methods before the first write through pRetVal.
    public int GetStackWalkCurrentFrameInfo(nuint pSFIHandle, nint pFrameData, FrameType* pRetVal)
    {
        if (pSFIHandle == 0)
            return HResults.E_INVALIDARG;

        int hr = HResults.S_OK;

src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Abstractions/Contracts/IRuntimeTypeSystem.cs:105

  • AsyncMethodFlags values don’t match the runtime’s AsyncMethodFlags bit layout (see src/coreclr/vm/method.hpp). The contract is explicitly value-dependent, so these should use the native flag values (e.g., IsAsyncVariant=0x4, Thunk=0x10, ReturnDroppingThunk=0x20). As written, any consumer treating these as native flags will misinterpret them.
[Flags]
public enum AsyncMethodFlags : uint
{
    None = 0,
    AsyncCall = 0x1,
    IsAsyncVariant = 0x2,
    Thunk = 0x4,
    ReturnDroppingThunk = 0x8,
}

src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Abstractions/Contracts/IStackWalk.cs:107

  • This PR adds new public contract surface (new IStackDataFrameHandle properties and new IStackWalk members). Per the repo API rules, new public APIs typically require a linked api-approved issue/proposal, or the new surface should be internal until approval. The PR description doesn’t reference an approved issue.
public interface IStackWalk : IContract
{
    static string IContract.Name => nameof(StackWalk);
    IEnumerable<IStackDataFrameHandle> CreateStackWalk(ThreadData threadData) => throw new NotImplementedException();
    IEnumerable<IStackDataFrameHandle> CreateStackWalk(ThreadData threadData, byte[] contextBuffer, bool isFirst = true) => throw new NotImplementedException();
    IReadOnlyList<StackReferenceData> WalkStackReferences(ThreadData threadData, bool resolveInteriorPointers) => throw new NotImplementedException();
    byte[] GetRawContext(IStackDataFrameHandle stackDataFrameHandle) => throw new NotImplementedException();
    TargetPointer GetFrameAddress(IStackDataFrameHandle stackDataFrameHandle) => throw new NotImplementedException();
    TargetPointer GetFramePointer(IStackDataFrameHandle stackDataFrameHandle) => throw new NotImplementedException();
    TargetPointer GetBasePointer(IStackDataFrameHandle stackDataFrameHandle) => throw new NotImplementedException();
    TargetPointer GetStackPointer(IStackDataFrameHandle stackDataFrameHandle) => throw new NotImplementedException();
    string GetFrameName(TargetPointer frameIdentifier) => throw new NotImplementedException();
    TargetPointer GetMethodDescPtr(TargetPointer framePtr) => throw new NotImplementedException();
    TargetPointer GetMethodDescPtr(IStackDataFrameHandle stackDataFrameHandle) => throw new NotImplementedException();
    TargetCodePointer GetInstructionPointer(IStackDataFrameHandle stackDataFrameHandle) => throw new NotImplementedException();
    IEnumerable<StackFrameData> GetFrames(TargetPointer threadPointer) => throw new NotImplementedException();
    bool IsExceptionHandlingHelperInlinedCallFrame(TargetPointer frameAddress) => throw new NotImplementedException();
    DebuggerEvalData GetDebuggerEvalData(TargetPointer funcEvalFrameAddress) => throw new NotImplementedException();
    TargetPointer GetRedirectedContextPointer(ThreadData threadData) => throw new NotImplementedException();
    byte[] GetContext(ThreadData threadData, ThreadContextSource contextSource, uint contextFlags) => throw new NotImplementedException();
    TargetPointer GetParentOrSelfFrameMarker(IStackDataFrameHandle stackDataFrameHandle, out uint parentNativeOffset) => throw new NotImplementedException();
    TargetPointer GetExactGenericArgsToken(IStackDataFrameHandle stackDataFrameHandle) => throw new NotImplementedException();
}
  • Files reviewed: 30/30 changed files
  • Comments generated: 1

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot's findings

Comments suppressed due to low confidence (4)

src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Legacy/Dbi/DacDbiImpl.cs:1848

  • GetStackWalkCurrentFrameInfo dereferences pRetVal unconditionally ("*pRetVal = ...") but never validates it. Other DacDbiImpl entrypoints (e.g. GetStackWalkCurrentContext) return E_POINTER for null output pointers; this should do the same to avoid an AV when callers pass a null pRetVal.
    {
        if (pSFIHandle == 0)
            return HResults.E_INVALIDARG;

        int hr = HResults.S_OK;

src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Legacy/Dbi/DacDbiImpl.cs:2126

  • IsDiagnosticsHidden uses Enum.HasFlag, which allocates/boxes and is noticeably slower than bit tests. This helper is used on stack-walk paths (IsDiagnosticsHiddenOrLCGMethod, EnumerateAsyncLocals), so switching to bitwise checks avoids unnecessary overhead.
    private static bool IsDiagnosticsHidden(AsyncMethodFlags flags)
        => flags.HasFlag(AsyncMethodFlags.Thunk)
            && (flags.HasFlag(AsyncMethodFlags.ReturnDroppingThunk) || !flags.HasFlag(AsyncMethodFlags.IsAsyncVariant));

src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/StackWalk/StackWalk_1.cs:1149

  • GetExactGenericArgsToken is documented to return TargetPointer.Null when the token can't be recovered, but the ctxLoc==ThisPtr path can still throw (e.g. invalid object reference / unreadable memory) via Object.GetMethodTableAddress. Consider catching VirtualReadException here and returning Null to preserve the contract semantics.
        // For the "this"-derived context the slot holds the object reference; the exact generics
        // token is its MethodTable. For an explicit context arg the slot value is the token itself.
        return ctxLoc == GenericContextLoc.ThisPtr
            ? _target.Contracts.Object.GetMethodTableAddress(contextValue)
            : contextValue;

src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/StackWalk/StackWalk_1.cs:1177

  • ReadGenericContextStorage uses _target.ReadPointer for stack/register-relative loads; if the target memory isn't readable this will throw and escape GetExactGenericArgsToken, even though the API is intended to return TargetPointer.Null when recovery isn't possible. Using TryReadPointer here would make the behavior robust against missing optional memory.
        TargetPointer ReadPointerRelativeTo(TargetPointer baseAddress, int offset)
            => _target.ReadPointer(new TargetPointer(unchecked(baseAddress.Value + (ulong)(long)offset)));
  • Files reviewed: 30/30 changed files
  • Comments generated: 1

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot's findings

Comments suppressed due to low confidence (4)

src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Legacy/Dbi/DacDbiImpl.cs:1858

  • GetStackWalkCurrentFrameInfo writes through pRetVal unconditionally (*pRetVal = ...) but does not validate that the pointer is non-null. Other DacDbiImpl entrypoints (e.g. GetStackWalkCurrentContext, UnwindStackWalkFrame) return E_POINTER for null output pointers; this one would AV instead of returning an HRESULT.
    public int GetStackWalkCurrentFrameInfo(nuint pSFIHandle, nint pFrameData, FrameType* pRetVal)
    {
        if (pSFIHandle == 0)
            return HResults.E_INVALIDARG;

        int hr = HResults.S_OK;
        nuint legacyHandle = 0;
        FrameType ftResult = FrameType.kInvalid;
#if DEBUG
        bool haveFrameInfo = false;
        bool isInterrupted = false;
#endif
        try
        {
            *pRetVal = FrameType.kInvalid;
            GCHandle gcHandle = GCHandle.FromIntPtr((nint)pSFIHandle);

src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Abstractions/Contracts/IStackWalk.cs:106

  • This change adds/removes members on Microsoft.Diagnostics.DataContractReader.Contracts public abstractions (IStackDataFrameHandle new properties; IStackWalk new methods; GetRawContext signature change/removal of StackwalkFlag). If this assembly is shipped/validated, this is new + breaking public API surface and should have an api-approved issue linked from the PR description (or the new members should be internal/behind a different surface).
public interface IStackDataFrameHandle
{
    StackWalkState State { get; }
    bool IsInterrupted { get; }
    bool HasFaulted { get; }
}

public enum StackWalkState
{
    Complete,
    Error,

    // The current Context represents a managed method.
    Frameless,

    // The current Context is the seed native context from init (the
    // thread's saved CONTEXT). FrameIter may or may not be on a Frame.
    InitialNativeContext,

    // The current Context is native, produced by unwinding a managed
    // frame down to an M2U boundary. FrameIter is on the explicit Frame.
    NativeMarker,

    // FrameAddress is valid and identifies the explicit Frame at FrameIter.
    // The current Context has not yet been bridged through that Frame; the
    // next step uses it to update the Context, after which Frameless is yielded.
    Frame,
    SkippedFrame,
}

// Classifies the origin of a reported stack reference.
//   InstructionPointer - a managed (frameless) JIT frame; Source is the native PC.
//   Frame              - an explicit capital-F Frame; Source is the Frame address.
//   Other              - a root which is not any of the other enums
public enum StackSourceType
{
    InstructionPointer = 0,
    Frame = 1,
    Other = 2,
}

public class StackReferenceData
{
    public bool HasRegisterInformation { get; init; }
    public bool IsInteriorPointer { get; init; }
    public int Register { get; init; }
    public int Offset { get; init; }
    public TargetPointer Address { get; init; }
    public TargetPointer Object { get; init; }
    public uint Flags { get; init; }
    public StackSourceType SourceType { get; init; }
    public TargetPointer Source { get; init; }
    public TargetPointer StackPointer { get; init; }
}

public enum InternalFrameType
{
    None,
    M2U,
    U2M,
    FuncEval,
    InternalCall,
    ClassInit,
    Exception,
    JitCompilation,
}

public record struct StackFrameData(
    TargetPointer FrameAddress,
    TargetPointer FrameIdentifier,
    InternalFrameType InternalFrameType);

public record struct DebuggerEvalData(
    uint MethodToken,
    TargetPointer AssemblyPtr);

public interface IStackWalk : IContract
{
    static string IContract.Name => nameof(StackWalk);
    IEnumerable<IStackDataFrameHandle> CreateStackWalk(ThreadData threadData) => throw new NotImplementedException();
    IEnumerable<IStackDataFrameHandle> CreateStackWalk(ThreadData threadData, byte[] contextBuffer, bool isFirst = true) => throw new NotImplementedException();
    IReadOnlyList<StackReferenceData> WalkStackReferences(ThreadData threadData, bool resolveInteriorPointers) => throw new NotImplementedException();
    byte[] GetRawContext(IStackDataFrameHandle stackDataFrameHandle) => throw new NotImplementedException();
    TargetPointer GetFrameAddress(IStackDataFrameHandle stackDataFrameHandle) => throw new NotImplementedException();
    TargetPointer GetFramePointer(IStackDataFrameHandle stackDataFrameHandle) => throw new NotImplementedException();
    TargetPointer GetBasePointer(IStackDataFrameHandle stackDataFrameHandle) => throw new NotImplementedException();
    TargetPointer GetStackPointer(IStackDataFrameHandle stackDataFrameHandle) => throw new NotImplementedException();
    string GetFrameName(TargetPointer frameIdentifier) => throw new NotImplementedException();
    TargetPointer GetMethodDescPtr(TargetPointer framePtr) => throw new NotImplementedException();
    TargetPointer GetMethodDescPtr(IStackDataFrameHandle stackDataFrameHandle) => throw new NotImplementedException();
    TargetCodePointer GetInstructionPointer(IStackDataFrameHandle stackDataFrameHandle) => throw new NotImplementedException();
    IEnumerable<StackFrameData> GetFrames(TargetPointer threadPointer) => throw new NotImplementedException();
    bool IsExceptionHandlingHelperInlinedCallFrame(TargetPointer frameAddress) => throw new NotImplementedException();
    DebuggerEvalData GetDebuggerEvalData(TargetPointer funcEvalFrameAddress) => throw new NotImplementedException();
    TargetPointer GetRedirectedContextPointer(ThreadData threadData) => throw new NotImplementedException();
    byte[] GetContext(ThreadData threadData, ThreadContextSource contextSource, uint contextFlags) => throw new NotImplementedException();
    TargetPointer GetParentOrSelfFrameMarker(IStackDataFrameHandle stackDataFrameHandle, out uint parentNativeOffset) => throw new NotImplementedException();
    TargetPointer GetExactGenericArgsToken(IStackDataFrameHandle stackDataFrameHandle) => throw new NotImplementedException();

docs/design/datacontracts/RuntimeTypeSystem.md:1508

  • The AsyncMethodData.Flags enum values documented here don't match the runtime flag bits that RuntimeTypeSystem_1 reads (see AsyncMethodFlags_1 in RuntimeTypeSystem_1.cs, where IsAsyncVariant=0x4, Thunk=0x10, ReturnDroppingThunk=0x20). If the docs are meant to describe the raw target-process layout, the numeric values should be updated to match so contract consumers don't reimplement the bit tests incorrectly.
    [Flags]
    internal enum AsyncMethodFlags : uint
    {
        None = 0,
        AsyncCall = 0x1,
        IsAsyncVariant = 0x2,
        Thunk = 0x4,
        ReturnDroppingThunk = 0x8,
    }

src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/StackWalk/StackWalk_1.cs:1150

  • IStackWalk.GetExactGenericArgsToken is documented as returning TargetPointer.Null when the token can't be recovered, but the implementation can throw VirtualReadException (e.g., via _target.ReadPointer(...) inside ReadGenericContextStorage, or Object.GetMethodTableAddress). That makes the API harder to consume in dump scenarios where missing memory is expected.
    TargetPointer IStackWalk.GetExactGenericArgsToken(IStackDataFrameHandle stackDataFrameHandle)
    {
        StackDataFrameHandle handle = AssertCorrectHandle(stackDataFrameHandle);

        if (handle.State != StackWalkState.Frameless)
            return TargetPointer.Null;

        TargetPointer mdPtr = ((IStackWalk)this).GetMethodDescPtr(handle);
        if (mdPtr == TargetPointer.Null)
            return TargetPointer.Null;

        IRuntimeTypeSystem rts = _target.Contracts.RuntimeTypeSystem;
        MethodDescHandle md = rts.GetMethodDescHandle(mdPtr);

        // Only shared generic code has an exact generics context to recover.
        GenericContextLoc ctxLoc = rts.GetGenericContextLoc(md);
        if (ctxLoc == GenericContextLoc.None)
            return TargetPointer.Null;

        if (!IsManaged(handle.Context.InstructionPointer, out CodeBlockHandle? cbh))
            return TargetPointer.Null;

        uint instructionOffset = (uint)_eman.GetRelativeOffset(cbh.Value).Value;
        _eman.GetGCInfo(cbh.Value, out TargetPointer gcInfoAddr, out uint gcVersion);
        IGCInfo gcInfo = _target.Contracts.GCInfo;
        IGCInfoHandle gcHandle = IsInterpreterCode(handle.Context.InstructionPointer)
            ? gcInfo.DecodeInterpreterGCInfo(gcInfoAddr, gcVersion)
            : gcInfo.DecodePlatformSpecificGCInfo(gcInfoAddr, gcVersion);

        if (!gcInfo.TryGetGenericContextStorage(gcHandle, ctxLoc, instructionOffset, out GenericContextStorage storage))
            return TargetPointer.Null;

        TargetPointer contextValue = ReadGenericContextStorage(handle.Context, storage);
        if (contextValue == TargetPointer.Null)
            return TargetPointer.Null;

        // For the "this"-derived context the slot holds the object reference; the exact generics
        // token is its MethodTable. For an explicit context arg the slot value is the token itself.
        return ctxLoc == GenericContextLoc.ThisPtr
            ? _target.Contracts.Object.GetMethodTableAddress(contextValue)
            : contextValue;
    }
  • Files reviewed: 30/30 changed files
  • Comments generated: 0 new

@noahfalk noahfalk left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mostly looked good to me - a few comments inline

fyi @davidwrighton - more type system and GCInfo stuff getting exposed via contract

Comment thread docs/design/datacontracts/StackWalk.md Resolved
Comment thread docs/design/datacontracts/StackWalk.md Resolved
Comment thread docs/design/datacontracts/StackWalk.md Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot's findings

Comments suppressed due to low confidence (3)

src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Legacy/Dbi/DacDbiImpl.cs:1847

  • GetStackWalkCurrentFrameInfo dereferences pRetVal unconditionally (*pRetVal = ...). If the COM caller passes a null out-pointer, this will AV rather than returning E_INVALIDARG like other DacDbi APIs.
    docs/design/datacontracts/StackWalk.md:634
  • Doc typo: this paragraph describes GetContextFramePointer(...), but the text says GetBasePointer (which is not the API name).
`GetBasePointer` returns the base pointer register from the current frame's context: EBP on x86, RBP on x64, and the platform frame-pointer register on other architectures.

docs/design/datacontracts/RuntimeTypeSystem.md:316

  • The doc comment says the returned flags are the runtime's "native AsyncMethodFlags", but the contract enum values shown later in this doc (and in IRuntimeTypeSystem) are normalized and do not match CoreCLR's native bit values (e.g., Thunk is 0x10 in CoreCLR). Either align the contract enum values to native, or adjust this comment to not claim native bit-compatibility.
    // Returns the Runtime Async flags recorded for the method (native AsyncMethodFlags),
    // or AsyncMethodFlags.None if the method has no async method data.
  • Files reviewed: 38/38 changed files
  • Comments generated: 1

Comment thread docs/design/datacontracts/StackWalk.md Resolved
rcj1 and others added 2 commits July 23, 2026 15:32

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot's findings

Comments suppressed due to low confidence (3)

src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Legacy/Dbi/DacDbiImpl.cs:1858

  • pRetVal is dereferenced unconditionally (*pRetVal = ...). Unlike GetStackWalkCurrentContext, this method doesn't guard against pRetVal == null, which can cause an AV/corrupted-state exception instead of returning E_POINTER. Add a null check before the first dereference.
    src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Abstractions/Contracts/IStackWalk.cs:92
  • GetRawContext(IStackDataFrameHandle, StackwalkFlag flags = ...) was removed. Even though StackwalkFlag currently only has Default, this is still a source/binary breaking change for downstream consumers. Consider reintroducing the old overload (and StackwalkFlag enum) forwarding to the new single-parameter API to preserve compatibility.
public interface IStackWalk : IContract
{
    static string IContract.Name => nameof(StackWalk);
    IEnumerable<IStackDataFrameHandle> CreateStackWalk(ThreadData threadData) => throw new NotImplementedException();
    IEnumerable<IStackDataFrameHandle> CreateStackWalk(ThreadData threadData, byte[] contextBuffer, bool isFirst = true) => throw new NotImplementedException();
    IReadOnlyList<StackReferenceData> WalkStackReferences(ThreadData threadData, bool resolveInteriorPointers) => throw new NotImplementedException();
    byte[] GetRawContext(IStackDataFrameHandle stackDataFrameHandle) => throw new NotImplementedException();
    TargetPointer GetFrameAddress(IStackDataFrameHandle stackDataFrameHandle) => throw new NotImplementedException();

docs/design/datacontracts/StackWalk.md:622

  • The docs refer to GetFramePointer, but the contract API is named GetRuntimeFramePointer. Update the text to match the actual API name so the spec stays 1:1 with IStackWalk.
`GetFramePointer` returns the debugger frame pointer that uniquely identifies the current frame. On x64 it is the current stack pointer. On ARM, ARM64, RISCV64, and LoongArch64 it is the caller stack pointer. On x86, frameless managed methods use the unwound stack pointer minus the callee-popped argument size and one pointer, while runtime-unwindable native markers use the return-address slot from the recovered hijacked context.
  • Files reviewed: 38/38 changed files
  • Comments generated: 5

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot's findings

Comments suppressed due to low confidence (4)

src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Legacy/Dbi/DacDbiImpl.cs:1857

  • GetStackWalkCurrentFrameInfo dereferences pRetVal without checking for null. Other DacDbiImpl methods (e.g. UnwindStackWalkFrame) return E_POINTER for null output pointers; this one should do the same to avoid an AV in the DAC process if the caller passes a null out-param.
    docs/design/datacontracts/StackWalk.md:634
  • This doc section describes GetBasePointer, but the actual API name is GetContextFramePointer (and there is no GetBasePointer method). This is likely a leftover name and will confuse contract consumers.
`GetBasePointer` returns the base pointer register from the current frame's context: EBP on x86, RBP on x64, and the platform frame-pointer register on other architectures.

src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Abstractions/Contracts/IStackWalk.cs:14

  • This PR adds/changes multiple public contract APIs (e.g. new members on IStackDataFrameHandle/IStackWalk and new methods like GetExactGenericArgsToken, GetFuncletRootId, etc.). The PR metadata doesn't reference an api-approved issue; if this surface is intended to be public/stable, it needs an approved API proposal linked from the PR, otherwise these new APIs should be internal/non-public to avoid taking on a compatibility contract unintentionally.
public interface IStackDataFrameHandle
{
    StackWalkState State { get; }
    bool IsInterrupted { get; }
    bool HasFaulted { get; }
}

src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/StackWalk/StackWalk_1.cs:1149

  • GetExactGenericArgsToken adds a fairly complex new code path (GC-info decoder selection, storage decoding, register vs stack reads, and MethodTable resolution for ThisPtr) but there are no contract-level tests exercising the real implementation (only a mock in DacDbiImplTests). Please add at least one DumpTest or UnitTest that validates a non-null token is recovered for a known shared-generic frame, and one negative case that returns TargetPointer.Null when the context can't be recovered.
  • Files reviewed: 38/38 changed files
  • Comments generated: 0 new

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot's findings

Comments suppressed due to low confidence (3)

src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Legacy/Dbi/DacDbiImpl.cs:1899

  • GetStackWalkCurrentFrameInfo dereferences pRetVal unconditionally (*pRetVal = ...) but does not validate that the caller provided a non-null pointer. This can AV if the COM caller passes null; other methods in this file return E_POINTER for null out-params.
    src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Contracts/Contracts/StackWalk/StackWalk_1.cs:1187
  • ReadGenericContextStorage uses _target.ReadPointer(...), which throws on an unreadable address. Since GetExactGenericArgsToken is documented to return TargetPointer.Null when the context can't be recovered, this path should be resilient to failed reads (e.g., use TryReadPointer and return Null).
    docs/design/datacontracts/RuntimeTypeSystem.md:307
  • The doc comment says GetAsyncMethodFlags returns "native AsyncMethodFlags", but the contract surface AsyncMethodFlags in IRuntimeTypeSystem uses different bit values than the runtime's AsyncMethodFlags (see src/coreclr/vm/method.hpp: AsyncCall=1, IsAsyncVariant=4, Thunk=16, ReturnDroppingThunk=32). This should be clarified to avoid consumers assuming they can treat these as the raw runtime flags.
    // Returns the Runtime Async flags recorded for the method (native AsyncMethodFlags),
    // or AsyncMethodFlags.None if the method has no async method data.
    public virtual AsyncMethodFlags GetAsyncMethodFlags(MethodDescHandle methodDesc);
  • Files reviewed: 40/40 changed files
  • Comments generated: 1

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot's findings

Comments suppressed due to low confidence (2)

src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Legacy/Dbi/DacDbiImpl.cs:1899

  • GetStackWalkCurrentFrameInfo dereferences pRetVal without validating it. Other DacDbiImpl entry points validate output pointer arguments inside the try/catch (so null maps to E_INVALIDARG via the exception -> HRESULT conversion).
    src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Abstractions/Contracts/IRuntimeTypeSystem.cs:104
  • AsyncMethodFlags values here don't match the runtime's AsyncMethodFlags bit layout (e.g., Thunk is 0x10 and ReturnDroppingThunk is 0x20 in src/coreclr/vm/method.hpp). Since RuntimeTypeSystem_1.AsyncMethodFlags_1 already uses the runtime bit values, either this public enum should use the same constants (and GetAsyncMethodFlags can return the raw flags), or the contract docs should clearly state that GetAsyncMethodFlags returns a remapped/normalized set of flags.
    AsyncCall = 0x1,
    IsAsyncVariant = 0x2,
    Thunk = 0x4,
    ReturnDroppingThunk = 0x8,
  • Files reviewed: 40/40 changed files
  • Comments generated: 0 new

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot's findings

Comments suppressed due to low confidence (2)

src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Legacy/Dbi/DacDbiImpl.cs:1888

  • GetStackWalkCurrentFrameInfo dereferences pRetVal unconditionally ("*pRetVal = …") but doesn’t validate it for null, unlike other DacDbiImpl APIs (e.g., GetStackWalkCurrentContext / UnwindStackWalkFrame). If a caller passes null this will AV instead of returning E_POINTER.
    src/native/managed/cdac/Microsoft.Diagnostics.DataContractReader.Abstractions/Contracts/IRuntimeTypeSystem.cs:106
  • This PR adds new public API surface in the cDAC Abstractions contract (e.g., new public AsyncMethodFlags, new IRuntimeTypeSystem.GetAsyncMethodFlags / IsVarArg). Per the repo’s API policy, new public APIs should be linked to an approved API proposal/issue (api-approved), or alternatively be made internal until approved.
    ThisPtr,
}

[Flags]
public enum AsyncMethodFlags : uint
{
    None = 0,
    AsyncCall = 0x1,
    IsAsyncVariant = 0x2,
    Thunk = 0x4,
    ReturnDroppingThunk = 0x8,
}

  • Files reviewed: 40/40 changed files
  • Comments generated: 0 new

@noahfalk noahfalk left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

@rcj1

rcj1 commented Jul 25, 2026

Copy link
Copy Markdown
Contributor Author

/ba-g ci green

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants