Detect safe/unsafe usage of GetCustomAttribute and similar methods
- Dominant language
- C#
- Stars
- 392
- Forks
- 128
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 2
Description
If `--used-attrs-only` is specified linker will remove any attribute type (and usage) which is not referenced from some method body. This creates potentially problematic code patterns mainly because reflection APIs like `GetCustomAttribute` will by default return any attributes of the specified type `T` and any derived type of `T`. In this case linker will correctly keep the `T`, but it will remove all of the derived attributes, which is potentially not what the calling code expects to happen.
We should implement pattern recognition for the calls to `GetCustomAttribute` (and similar APIs as there are multiple APIs like this in the reflection) and detect cases where:
* The T is determined and it's a sealed type -> Safe
* Anything else -> Unsafe
The unsafe reporting should be done only if `--used-attrs-only` is specified. Without this, linker will by default keep all attribute types which are used anywhere, so the potentially problematic callsites are guaranteed to work correctly.
Sample test case showing how linker removes derived attributes:
``` C#
[SetupLinkerArgument ("--used-attrs-only", "true")]
class UnusedDerivedAttributeType
{
static void Main ()
{
var tmp = new Bar ();
var str = typeof (BaseAttribute).ToString ();
}
[Kept]
[KeptMember (".ctor()")]
[Derived]
class Bar
{
}
[Kept]
[KeptBaseType (typeof (Attribute))]
class BaseAttribute : Attribute
{
}
class DerivedAttribute : BaseAttribute
{
}
}
```
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.