Skip to content

Enhanced Stack Frames with Native AOT #3323

@jamescrosswell

Description

@jamescrosswell

Continuing on from #3322 we need to implement Michal's other suggetions:

In the end, someone will need to do the work to enable the AOT/trim/single file safety analyzers and address all the warnings, but this is enough to have a golden path that makes sample/StackTrace project produce the same results under native AOT as under JIT.

Necessary fixes:

  • GetMethodBody under AOT throws. This will not return anything useful under Mono with ILStrip either. The code simply needs to deal with it.
  • Runtime reflection stack doesn't guarantee referential equality of MemberInfos (except for TypeInfo). This is also true on JIT-based runtimes, but there's even less caching on native AOT. Use operator ==.
  • The reflection to read TupleElementNamesAttribute is trim-unfriendly and cannot be analyzed. Replace with no-reflection.
  • Some fallout from the previous point because the nullable annotations on the thing returned by reflection were wrong.

Finally we should be able to simplify this:

var frames = (!AotHelper.IsNativeAot && _options.StackTraceMode == StackTraceMode.Enhanced)
? EnhancedStackTrace.GetFrames(stackTrace).Select(p => new RealStackFrame(p))
: stackTrace.GetFrames().Select(p => new RealStackFrame(p));

Also note Vitek Karas' guidance from Discord:

As noted in the PR, the code in that package will have problems in other cases which are not NativeAOT related - for example the GetMethodBody() will not work in some cases even on mono (since it may strip the IL if it precompiled the method).

Specifically for the "stack trace" scenario, we introduced https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.diagnosticmethodinfo?view=net-9.0 which should work even on NativeAOT - it provides the simple info for a frame (assembly name, type name and member name as strings, not as reflection objects), but it is declared as possibly returning nulls if the runtime simply doesn't have that information.

Metadata

Metadata

Assignees

No one assigned

    Projects

    Status

    No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions