dotnet / dotnet/linker

ILLinker doesn't warn on BaseType usage allowing for broken apps without warning

Open
#1,755 2 comments 0 reactions 0 assignees View on GitHub
area-Linker: Diagnostic
Dominant language
C#
Stars
392
Forks
128
Avg merge
2d 10h
Merged PRs (30d)
2

Description

Fully trim and execute the following app with ILLink warnings turned on:

```C#
using System;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;

class Program
{
static void Main()
{
var mi = GetMethod(typeof(Derived), "Method1");

if (mi == null)
{
Console.WriteLine("Couldn't find method!");
}
else
{
mi.Invoke(null, null);
}
}

static MethodInfo GetMethod(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] Type target,
string method)
{
for (Type targetType = target; targetType != null; targetType = targetType.BaseType)
{
MethodInfo mi = targetType.GetMethod(method, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null);

if (mi != null)
{
return mi;
}
}

return null;
}
}

class Base
{
private static void Method1() => Console.WriteLine("Method1");
}

class Derived : Base
{
}
```

### Actual results

When the app is not trimmed, it prints

`Method1`

When the app is trimmed, it prints

`Couldn't find method!`

However, I wasn't shown a warning that the above code was not safe.

### Expected results

We should either get an ILLink warning in the above code saying it is unsafe Reflection usage. Or the app should continue to work as it does untrimmed.

### Notes

This was found with the following code, which wasn't raising warnings, but it should be:

https://github.com/dotnet/runtime/blob/2c1cb0820128ed7d07d98abd004679e433ccb1de/src/mono/netcore/System.Private.CoreLib/src/System/Delegate.Mono.cs#L217-L251

cc @vitek-karas @MichalStrehovsky

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.