Skip to content
This repository was archived by the owner on Sep 25, 2026. It is now read-only.

Scan compiler-generated methods as a group - #2792

Merged
sbomer merged 24 commits into
dotnet:mainfrom
sbomer:scanMethodGroup
Jun 7, 2022
Merged

sbomer merged 24 commits into
dotnet:mainfrom
sbomer:scanMethodGroup

Conversation

@sbomer

@sbomer sbomer commented May 12, 2022 •

Copy link
Copy Markdown
Member

Still a WIP. Needs more tests, optimization, and cleanup, but functionally is mostly working. Don't look too closely at the code yet, but I wanted to get feedback on the design which I've tried to describe here @vitek-karas @agocke:

This scans compiler-generated methods together as a group when marking the corresponding user code.

There are two scans that we do:

  1. An initial scan to determine whether we need to run the dataflow scanner. It is also what marks static dependencies of the method IL.
  2. The full dataflow scan (only if the initial scan says we need to). This produces warnings and marks reflection dependencies.

Both scans are now done for the group of compiler-generated methods when marking the user code. For now, we only do the dataflow scan once per method, but in a later change, we will need to allow re-scanning compiler-generated callees (as part of the full scan for the corresponding user code) to properly track captured state.

When compiler-generated code is accessed via reflection, we now don't do a dataflow scan because we don't have the context that might be captured from user code. This also means that reflection-dependencies of the compiler-generated code aren't kept, and dataflow warnings aren't produced, unless the code is reached through the corresponding user method. To guard against this, there are new warnings on reflection access to compiler-generated code. (edit: The reflection access warnings are now only for compiler-generated code which would normally require the reflection method body scanner. This is a heuristic meant to conservatively approximate "this compiler-generated code would produce dataflow warnings if invoked by reflection with an unknown context".)

Currently, the initial scan (1.) may be done multiple times for a compiler-generated method, once when marking the corresponding user code, and again when marking the compiler-generated code. It only produces warnings when marking for the user code. We can't just fold the compiler-generated code marking into the user code marking, because the compiler-generated code might independently be accessed via reflection, and we still want to keep IL dependencies in that case. I initially hesitated to introduce another cache since I assumed the initial scan was supposed to be inexpensive, but now I am thinking it would make sense to cache even if only to simplify the code. Curious if you have an opinion @vitek-karas.

edit: I added a cache to ensure that the initial scan 1. is still only done once per method (including for compiler-generated methods). Warnings produced as a result of this initial scan will be produced whether the code is accessed by reflection or via a call from user code.

sbomer added 2 commits May 12, 2022 10:13
Instead, warn on reflection access to the compiler-generated members.
Comment thread src/linker/Linker.Steps/MarkStep.cs Resolved
@vitek-karas

Copy link
Copy Markdown
Member

I initially hesitated to introduce another cache since I assumed the initial scan was supposed to be inexpensive, but now I am thinking it would make sense to cache even if only to simplify the code.

I'm probably slow today - can you please expand what kind of cache you're talking about and what would it simplify?

Re reflection access to compiler generated methods:
I'm sort of split on this.
On one hand, if we generate a warning then it sort of doesn't matter what we do with the rest, so it would be OK to not mark the method in that case.
On the other hand, this would go against how linker operates today (we mark even though we're not sure about it in all other cases, basically we overmark members, we don't overmark types). But more importantly this would make it effectively impossible to handle some cases, see example below.

I think with this we're going to potentially have a problem:

class TestType
{
    public void MethodWithLocalFunction() { Local(); void Local() {} }
    private void InitMethod() {}
}

void InitializeEverything([DAM(All)] Type type)
{
    // Get all private methods which have a name starting with `Init`
    // Call them
    ....

    // There will be no warnings in this method as it's perfectly correct.
}

void Test()
{
    // This will produce a warning since we're accessing compiler generated code (the local function) potentially via reflection
    DoMyPrivateReflectionStuff(typeof(TestType));
}

The InitializeEverything method knows that it actually won't do anything bad with compiler generated code (since those methods have unspeakable names and it won't match them), but there's no way to tell that to the caller. And the caller is the one being blamed for this.

One potential "fix" for this could be:
If a compiler generate method is marked via reflection - play dumb and simply mark it the way we do today. It may produce warnings which would not happen when it's accessed normally from the user code, but so be it.
The idea behind this is:

  • I fear it's going to be relatively common to apply All or similar "bad" annotations to "random" types. It's already a problem with RUC methods, but there's nothing we can do about that.
  • Compiler generated code is relatively common and will probably expand in the future - so the new warning would happen more frequently.
  • It's pretty rare for compiler generated code to do something with reflection - most such code will NOT do that. So if we would detect that case - we would not need to warn.
  • Even today without cross-method analysis, we need to guarantee that dangerous code produces warnings - so if a compiler generated code does something weird, we should warn already. So the above should not break the basic "0 warnings => works" premise, but should be able to avoid new warnings in lot of cases.

@sbomer

sbomer commented May 13, 2022

Copy link
Copy Markdown
Member Author

I agree with your points about potential unnecessary warnings. The main reason I didn't want to mark compiler-generated code the way we do today is what you pointed out:

It may produce warnings which would not happen when it's accessed normally from the user code

In particular, this would make it so that a library which has been correctly annotated for trimming could get warnings when someone else introduces reflection access to the library:

// With this reflection access, you'd get a warning from `LocalFunction`.
Require.All(typeof(AnnotatedLibrary));

public class AnnotatedLibrary {
    public void M() {
        Type t = All();
        void LocalFunction() => Require.All(t);
        LocalFunction();
    }

    [return: DAM(DAMT.All)]
    public Type All() => null;
}

public class Require
{
    public static void All([DAM(DAMT.All)] Type t) {}
}

Maybe another way we could reduce the noise from unnecessary warnings is to only warn on reflection-access to compiler-generated code that might violate the dataflow annotations if called with an unknown context. Or, perhaps it's an option to leave this one as an analysis hole, under the assumption that if you're using reflection to invoke compiler-generated code that does something with captured state, you must know what you're doing already.

@vitek-karas

Copy link
Copy Markdown
Member

I agree that the warnings could be wrong - as in more than should be there, but that's only for the case where it's actually using some reflection, which I think is rare. I think we should prioritize the experience for the much more common case where there's no reflection inside the compiler generated code.

@sbomer

sbomer commented May 13, 2022

Copy link
Copy Markdown
Member Author

I initially hesitated to introduce another cache since I assumed the initial scan was supposed to be inexpensive, but now I am thinking it would make sense to cache even if only to simplify the code.

can you please expand what kind of cache you're talking about and what would it simplify?

I was thinking that we could have a cache to avoid doing the initial scan (1.) twice for compiler-generated code. Because the common case will be that it's reached from user code, and will always be scanned twice. It would require getting rid of the behavior where it only produces warnings when marking for the user code. I haven't thought carefully enough about it yet, but I was thinking it might avoid having to pass another bit through much of the marking logic to disable warnings.

@sbomer

sbomer commented May 13, 2022

Copy link
Copy Markdown
Member Author

but that's only for the case where it's actually using some reflection, which I think is rare. I think we should prioritize the experience for the much more common case where there's no reflection inside the compiler generated code.

Yes, I agree we should prioritize not warning in this case. Would either of these suggestions address this?

only warn on reflection-access to compiler-generated code that might violate the dataflow annotations if called with an unknown context. Or, perhaps it's an option to leave this one as an analysis hole, under the assumption that if you're using reflection to invoke compiler-generated code that does something with captured state, you must know what you're doing already.

If we can find a way to warn at the reflection callsite instead of inside correctly annotated code, I would prefer that.

@vitek-karas

Copy link
Copy Markdown
Member

Technically possible (but probably a bit complex): If we detect reflection access to compiler generated code, run the analysis on the compiler generated code but "suppress" warnings, only capture a single boolean if there is a warning or not. And if there's none -> no warning at all. If there is something, issue a warning similar to what you added here - on the callsite.

Didn't look into the implementation if this is reasonable. It might be - the reflection access is granular -> we will be accessing things one item at a time (one field, one method, ...). We can re-run the body scanner for each method in this case with a custom diagnostic context. It will not be perfect, but should be good enough - there will likely still be cases where marking the method in question will eventually produce warnings somewhere deeper. We can always try to improve, even though it's somewhat of a breaking change (we would be moving the place where a warning comes from, and also changing the warning code).

@sbomer

sbomer commented May 25, 2022

Copy link
Copy Markdown
Member Author

Just to summarize, we've looked at a few alternatives on a sliding scale. At the extremes:

  1. Warn on reflection access to any compiler-generated code. This was deemed too noisy since people are likely to use state machines and nested functions on types that they pass to All-annotated APIs.
  2. Don't warn for these cases at all. Technically an analysis hole, but will this really be a problem in practice? People shouldn't be invoking compiler-generated code via reflection in the first place. @MichalStrehovsky it sounds like you were in favor of this option.

In-between those extremes, we had some more options:

  • Run dataflow analysis on the compiler-generated code with an unknown context if accessed via reflection. Warn if it has potential issues at the reflection callsite. This is the most precise, but also the most complex approach.
    • Another idea was to produce the warning inside the compiler-generated code. I argued against this because it means the caller can introduce warnings into correctly-annotated code.
  • The latest idea @vitek-karas and I discussed was to produce warnings on reflection-access to compiler-generated code only when the compiler-generated code would require the reflection scanner. This is simpler than the more precise approach suggested above but still avoids producing warnings for cases where the compiler-generated code doesn't do anything with reflection or dataflow annotations. This is the path I've been going down for now and I've written a fair number of tests to validate these warnings.

What are people's thought on option 2? @MichalStrehovsky @vitek-karas @agocke

(Independently of the above, I'm discovering some edge cases around the compiler-generated code together with RUC-on-type: #2806.)

@sbomer
sbomer marked this pull request as ready for review May 25, 2022 23:21
@sbomer
sbomer requested a review from marek-safar as a code owner May 25, 2022 23:21
@MichalStrehovsky

Copy link
Copy Markdown
Member

I'm wondering whether the following ways to keep an entire type should be treated equivalently in analysis:

  1. void Foo([DAM(DAMK.All) Type x) called with typeof(SomeTypeThatHasClosureThatDoesReflection)
  2. [DynamicDependency(DAMK.All, typeof(SomeTypeThatHasClosureThatDoesReflection))]
  3. ILLinkTrim.Descriptors.xml saying to keep the type in entirety
  4. Command line argument to illink saying to keep the entire assembly that contains the type

All of the above tell analysis that someone is going to access potentially everything on this type without analysis seeing it. They may use reflection invoke. They may use hosting APIs. But the analysis has no visibility into the values set/passed. It keeps the members so that someone can do arbitrary things with them at runtime.

If we want to treat it that way, we would need to warn anytime a closure with crossmethod reflection is included in any of the above categories (e.g. it was in an assembly that we kept in full).

My theory is that people generally don't do reflection invocations with closures. They may introspect them to e.g. fix async stack traces, but they don't actually do stuff with closures. It may be okay if we don't warn and keep it as a hole, assuming the compiler generated code is never a real target of reflection.

@sbomer

sbomer commented May 26, 2022

Copy link
Copy Markdown
Member Author

I like the idea to treat descriptors/arguments as keeping things for reflection. If someone is going out of their way to preserve things we should assume the worst. This would also encourage people to turn on more aggressive trimming (since they might otherwise get more warnings from unused parts of the rooted assemblies).

If we want to treat it that way, we would need to warn anytime a closure with crossmethod reflection is included in any of the above categories (e.g. it was in an assembly that we kept in full).

Was this an argument against producing these warnings or a general observation? I think the same would be true of DAM-annotated methods (we would need to warn on any methods in a fully-kept assembly that have DAM annotations). I'm not sure how big of a problem that is, but it seems like the compiler-generated code warnings are no worse off.

My theory is that people generally don't do reflection invocations with closures.

I agree with your theory - at least I hope it's true. :) I definitely don't know of cases where leaving it as a hole would be problematic. Generally though, I prefer to produce the warning for correctness, to catch cases where that expectation might be violated.

@MichalStrehovsky

Copy link
Copy Markdown
Member

Was this an argument against producing these warnings or a general observation? I think the same would be true of DAM-annotated methods (we would need to warn on any methods in a fully-kept assembly that have DAM annotations). I'm not sure how big of a problem that is, but it seems like the compiler-generated code warnings are no worse off.

Just a general observation. You're right that it affects user code as well.

I like the idea to treat descriptors/arguments as keeping things for reflection. If someone is going out of their way to preserve things we should assume the worst. This would also encourage people to turn on more aggressive trimming (since they might otherwise get more warnings from unused parts of the rooted assemblies).

We should guide people towards:

  • If you [DAM] anything in the assembly, you should also set IsTrimmable=true
  • Never set TrimMode to anything but link

Then it should be less of a nuisance.

@sbomer sbomer changed the title [WIP] Scan compiler-generated methods as a group Scan compiler-generated methods as a group May 27, 2022
@vitek-karas

Copy link
Copy Markdown
Member

I do agree with descriptors and similar to trigger reflection dependency. We should fix that currently. That said I know that there were some cases in the past where we decided we should NOT warn on RUC if the reference is coming from a descriptor. Maybe we should revisit that again.

As for "copy" assemblies, maybe those should not warn, but it's not a big deal I think. We should have single-warn on by default and so typically one should get a single warning from the entire assembly.

While I absolutely agree that probably no one will actually invoke compiler generated code through reflection, I would like to avoid analysis holes if we can. Technically we're already warning on compiler generated code which is accessed via reflection - those which do have annotations or will have warnings from their bodies (since we don't special case them currently). And I haven't really seen issues where this would cause problems. This tells me that there are not that many cases where compiler generated code would trigger warnings (annotated or with reflection) in this situation. So the relatively simple filter of "does it need data flow", should be good enough.

@vitek-karas vitek-karas 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 cosmetic comments - looks good, great work.

Comment thread src/linker/Linker.Steps/MarkStep.cs Resolved
Comment thread src/linker/Linker.Steps/MarkStep.cs Resolved
Comment thread src/linker/Linker.Steps/MarkStep.cs Resolved
Comment thread src/linker/Linker.Steps/MarkStep.cs Resolved
DynamicallyAccessedMembersOnTypeReferencesMemberOnBaseWithDynamicallyAccessedMembers = 2115,
RequiresUnreferencedCodeOnStaticConstructor = 2116,
MethodsAreAssociatedWithUserMethod = 2117,
CompilerGeneratedMemberAccessedViaReflection = 2118,

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.

Once this is merged, could you add these error codes in dotnet/docs?

Comment thread src/linker/Linker.Steps/MarkStep.cs Resolved
sbomer added 2 commits May 31, 2022 11:25
- Add and clarify comments
- Naming suggestions
- Clean up switch statement slightly
- Add comments to warnings that should be
  fixed with compiler-generated dataflow support
@sbomer
sbomer merged commit 42eddb3 into dotnet:main Jun 7, 2022
agocke pushed a commit to dotnet/runtime that referenced this pull request Nov 16, 2022
This scans compiler-generated methods together as a group when marking
the corresponding user code.

There are two scans that we do:

1. An initial scan to determine whether we need to run the dataflow
scanner. It is also what marks static dependencies of the method IL.
2. The full dataflow scan (only if the initial scan says we need
to). This produces warnings and marks reflection dependencies.

Both scans are now done for the group of compiler-generated methods
when marking the user code. For now, we only do the dataflow scan once
per method, but in a later change, we will need to allow re-scanning
compiler-generated callees (as part of the full scan for the
corresponding user code) to properly track captured state.

When compiler-generated code is accessed via reflection, we now don't
do a dataflow scan because we don't have the context that might be
captured from user code. This also means that reflection-dependencies
of the compiler-generated code aren't kept, and dataflow warnings
aren't produced, unless the code is reached through the corresponding
user method. To guard against this, there are new warnings on
reflection access to compiler-generated code. The reflection access
warnings are only for compiler-generated code which would normally
require the reflection method body scanner. This is a heuristic meant
to conservatively approximate "this compiler-generated code would
produce dataflow warnings if invoked by reflection with an unknown
context".

Commit migrated from dotnet/linker@42eddb3
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants