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

Merge feature/damAnalyzer to main - #2614

Merged
tlakollo merged 96 commits into
mainfrom
merge-damanalyzer
Feb 18, 2022
Merged

tlakollo merged 96 commits into
mainfrom
merge-damanalyzer

Conversation

@tlakollo

Copy link
Copy Markdown
Contributor

This PR merges the feature/damAnalyzer to linker main branch

mateoatr and others added 30 commits September 16, 2021 14:43
* Add DiagnosticId enum
Add GetDiagnosticDescriptor

* Check that the diagnostic id is in the range of the supported linker warnings

* Lint

* Share DiagnosticString

* Noisy whitespace

* Warnings go up to 6000 inclusive

* PR feedback

* Get diagnostic string
Update test

* Lint

* Tests

* Add warnings

* Display members using the linker's format

* Remove unused Xunit theory

* Check for PublicParameterlessCtor
Remove unused files

* Refactor analyzer

* Delete SemanticModelExtensions

* Update DiagnosticString

* Lint

* Rename methods
Use DiagnosticId names in for-loop
Remove unnecessary if-def
Add TryGetAttribute method
Add Annotations to shared code in preparation for sharing the logic to retrieve unmatched DAM annotations between linker and analyzer
Rename DiagnosticIds
Add license headers where missing

* Don't warn when the method is RUC annotated
Share code between linker and analyzer for retrieving the missing type annotations

* Add comments, add source/targetIsMethodReturnType parameters

* Match with NamedType for consistency

* Remove GetMembersTypesString
* Simplify DAM analyzer and add conversion test

* PR feedback
- Take Location in helper instead of originOperation
- Avoid optional parameters
- Add test with DAM on conversion return type

* Add success testcase
[feature/damAnalyzer] Merge from main
* Format parameters with spaces

* Fix field formatting an DAM tests

* Turn on a few linker DAM tests for analyzer

* Add missing using

* Fix formatting

* FIx typo and enable more tests

Also add a few testcases demonstrating an issue uncovered in some of the
tests from MethodReturnParameterDataFlow.

* PR feedback

- Skip failing tests
[feature/damAnalyzer] Merge changes from release/6.0.2xx
* fix for spurious warning issue 2308

* fb
Let the warnings be generated by Trimmer and Analyzer
Whenever discrepancies ocurred open an issue to track and let the test pass
- Add back dataflow tests as individual facts
- Fix test failures
- Lint and prevent code-fixing skipped facts
[DAM analyzer] Update from main
This adds basic dataflow analysis for the Roslyn analyzer. So far it only tracks DAM annotations (not known types, reflection intrinsics, and similar). It also doesn't handle exceptional control flow, but unlike the linker's analysis it does handle backwards branches.

The dataflow framework is set up to (hopefully) facilitate code sharing going forward - the core abstractions don't depend on Roslyn constructs, but there's more work that would need to be done to actually share this code with the linker.

As the analysis runs, it caches any trim analysis patterns it encounters, and warnings are reported after it converges. The caching is intended to be additive - it should ensure that we increase the set of possible analysis patterns as we go, but it should never lose track of a pattern encountered in a previous iteration of the analysis.

The core logic for creating and propagating the tracked values is in TrimAnalysisVisitor, similar to ReflectionMethodBodyScanner. There is a base class LocalDataFlowVisitor, similar to MethodBodyScanner, which knows how to propagate values across locals in Roslyn in a generic way.

The actual dataflow algorithm (ForwardDataFlowAnalysis) does the simplest possible thing in this change. The goal is to set it up in a way that the core abstractions don't need to change even when we go optimize the algorithm (and ideally for any optimizations to be generic, not tightly bound with our particular analysis). This should make it easier to reuse the code in the linker and possibly in other future analyses.

This also cleans up the representation of annotated values. We used to use a NamedTypeSymbol for annotated methods (to represent the 'this' parameter). Now this is hidden inside of SymbolValue, which tracks the method, and whether it represents the receiver, or the return parameter.
This fixes an ambiguity where AnnotatedSymbol needs to track type symbols that don't represent 'this' parameters.
The IOperation tree represents properties as
IPropertyReferenceOperation, so we need to handle
properties specially (whereas the linker sees calls
to the getter/setter directly).
…2397)

The idea is simple, store only a single object field.
If the field is null, the set is empty.
If the field is a HashSet, then it contains multiple values in that hashset.
If the field is TValue, then it set contains single value - that value.

I probably went a bit overboard on optimizations here, but I wanted to try what it takes to implement a good collection class. The result should not allocate at all when "Foreached" over if it contains no or single value (by far the most common case).

Co-authored-by: Sven Boemer <[email protected]>
See dotnet/core-eng#14783.

Also switch to latest macOS/Ubuntu/Windows vmImage.

Co-authored-by: Alexander Köplinger <[email protected]>
* DynamicallyAccessedMembersBinder port to Analyzer

* FB

* FB2

* better filtering
…ue (#2401)

Currently linker uses ValueNode to represent both single and multi-values. The multi-value is stored as a special value MergePoint. This means that basically every "Reader" should call UniqueValues which enumerates all values in the value. Otherwise it may only react to single-values and not function correctly for multi-values.

Also in order to share more code with the analyzer, we need to switch to the new model, where multi-values is stored in an explicit ValueSet.

This change replaces all the places where multiple values can be stored with MultiValue (=ValueSet<ValueNode>). Then it removes the MergePoint values and the entire infrastructure around it.
Other notable changes:
- Added implicit conversion from single TValue to ValueSet<TValue> to make it much easier to work with
- Changed how ArrayValue is created to use factory methods. Previously ArrayValue could store a multi-value as its size. This meant that it was necessary to enumerate UniqueValues on ArrayValue to get actual sizes (results in multiple ArrayValues). This change introduces a factory method which return a MultiValue which may contain multiple ArrayValues if there are multiple potential sizes. A bit more memory hungry in some cases, but makes the "reader" simpler and less error prone.
- Added IsEmpty on ValueSet - as it's relatively common to check for empty ValueSet
- This actually fixes a bug #2025 because it now correctly tracks empty MultiValue
- This change finally gets rid of all possible places where ValueNode could be null before - null was used as basically Unknown value, but it sometimes caused nullrefs in weird places. This can't happen anymore, since MultiValue is a struct and thus is always - non-null.
This is in preparation to merging the value type system with the analyzer and the `SingleValue` type.

Removes the Kind enum and uses type checks instead (there are not that many places actually since we already used type checks in lot of places).
Cleans up some of the value .ctors and properties.
Remove Equals/GetHashCode implementation where possible (leave it up to record).
The helpers to tanslate binding flags to annotation already handle unsupported/unknown binding flags, so there's no need for the intrinsics to handle that yet again. Just simplifies the code.

Also fixed places where we lookup method parameters. If the lookup is done on a MethodReference the parameters typically don't have names. So instead do it on the MethodDefinition where they do have names and thus produce much better diagnostic messages.
…2444)

Removes the `RecodnizedReflectionAccessPattern` and `UnrecognizedReflectionAccessPattern` attributes and all of the infrastructure for it.

In the tests this is replaced by:
* `ExpectedNoWarning` on the test level which makes sure we don't produce unexpected warnings (basically equivalent to `RecognizedReflecitonAccessPattern`.
* `ExpectedWarning` to mark the places where warning should be generated - direct replacement for `UnrecognizedReflectionAccessPattern`.

This change also removes some of the test-private helpers and replaces it with the `DataFlowTypeExtensions` helpers.

This is mostly a mechanical change.

This is part of the work to remove reflection access patterns from everywhere - in order to make the data flow logic sharable with the analyzer.
…inker (#2447)

Removes the `IReflectionPatternRecorder` and all related classes. This interface has been introduced at the very beginning of the data flow work in the linker. Back then the purpose of it was to separate the marking logic from diagnostic reporting logic. We thought we would be able to report nice virtual callstacks of warnings and so on. These ideas were superseded by the current design of forcing explicit annotations on method boundaries and thus avoiding the need to report warnings correlated across multiple methods.

As such the only consumer of this interface is a "logger" which directly outputs any unrecognized patterns as warnings. The product makes no use of the "Recognized pattern" event at all.

The only remaining logic is the ability to suppress diagnostic generation within the data flow logic (typically due to `RequiresUnreferencedCode` attribute on the method). For now I kept this by adding an `AnalysisContext` helper struct to pass around the message origin and diagnostics settings and logging warnings through it. We will likely need an abstraction for diagnostics to be able to share code with the analyzer anyway, so this is probably a step in the right direction.

This is almost entirely a mechanical change, in general simplifying the code.
tlakollo and others added 5 commits February 14, 2022 13:06
Produce warnings for annotations on invalid types using a symbol analyzer
Add code to not produce invalid types warnings on dataflow analysis, and reduce the scope to only interesting types
Add extension file to ask if a type is interesting for dataflow
The value of a property set expression is the value, not the return value of the set method (void).
This tracks null values and adjusts the handling of null values in a
few intrinsics which either take structs that can never be null, or
don't return when the input is null.

MethodBodyScanner needed a small adjustment to correctly deal with the
case where an intrinsic returns TopValue.
…2611)

With latest VS we get a 6.0.2 runtime but only 6.0.1 ref pack. The tests so far expected to use the exact same version, but there's no hard rule that it will be the case.

Change the algorithm to search for highest available major.minor.* ref pack if the matching one doesn't exist.

Co-authored-by: Vitek Karas <[email protected]>
dotnet-bot and others added 7 commits February 16, 2022 05:45
* Fix how test find the ref pack to compile test cases against (#2610)

With latest VS we get a 6.0.2 runtime but only 6.0.1 ref pack. The tests so far expected to use the exact same version, but there's no hard rule that it will be the case.

Change the algorithm to search for highest available major.minor.* ref pack if the matching one doesn't exist.

* Specify SDK version in global.json (#2592)

Co-authored-by: Vitek Karas <[email protected]>
Co-authored-by: Sven Boemer <[email protected]>
And fix invocations of GetValueUsageInfo
* suppressing analyzer for compiler generated methods

* FB

* fixing some tests
This adds support for exception filters in the analyzer. Now the exception state will flow from from try blocks to any catch blocks without filters, or to the filter regions of any catch blocks that do have filters. Additionally, the dataflow state flows from a filter region to the next filter or catch. We don't check whether the exception type of the filter regions match, but conservatively assume that control can flow out of any filter to the next filter or catch.

This also assumes that control leaves the filter region from its last block - I don't know if there are cases where a filter region can contain more than one basic block, so if this is possible the logic might need to be updated.

I added a few testcases with dataflow and side effects in filter regions. This fixes #2415 and allows enabling two more of the previously failing tests.
Analyzer intentionally "ignores" intrinsics which linker recognizes, but analyzer doesn't yet. Meaning it will not produce any warnings due to them.

Some tests didn't reflect this change correctly.
The tests use fake generated backing fields, which the linker recognizes as the real thing, but the analyzer is not fooled. So it's expected the analyzer would produce warnings here - and the developer who writes code like this (hard to imagine why) should fix those warnings anyway.

Co-authored-by: Tlakaelel Axayakatl Ceja <[email protected]>
@vitek-karas

Copy link
Copy Markdown
Member

I ran the runtime build with linker from the damAnalyzer branch. Some improvements to the data flow logic uncovered new warnings (all moot). So I prepared a runtime PR dotnet/runtime#65580 with the necessary fixes.

@agocke agocke closed this Feb 18, 2022
@agocke agocke reopened this Feb 18, 2022
agocke and others added 2 commits February 18, 2022 13:47
The damAnalyzer branch has actually fixed the array access bug in the linker.
The analyzer doesn't understand this pattern though, so it doesn't produce a warning.
@tlakollo
tlakollo merged commit 7079b34 into main Feb 18, 2022
@agocke
agocke deleted the merge-damanalyzer branch February 18, 2022 23:58
@agocke

agocke commented Feb 18, 2022

Copy link
Copy Markdown
Member

🎉🎉🎉

agocke pushed a commit to dotnet/runtime that referenced this pull request Nov 16, 2022
Merge feature/damAnalyzer branch to main

Commit migrated from dotnet/linker@7079b34
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.

8 participants