Skip to content

Detect safe/unsafe usage of GetCustomAttribute and similar methods #952

@vitek-karas

Description

@vitek-karas

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<T> 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<T> (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:

	[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
		{
		}
	}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions