Skip to content

[mono][reflection] ArgumentNullException calling GetCustomAttributes on user-defined subtype of ParameterInfo #94488

Closed

Description

@lambdageek

The following code works with .NET 8.0 CoreCLR, but throws with Mono:

Program.cs:

using System.Reflection;

public class P {
    public static void Main()
    {
        var propi =typeof(P).GetProperty("Foo");
        var pi = new Retrofit.PropertyAsParameterInfo(propi!);
        IEnumerable<Attribute> cattrs = pi.GetCustomAttributes();
        Console.WriteLine($"Got {cattrs.Count()} attributes");
        foreach (var cattr in cattrs) {
            Console.WriteLine (cattr);
        }
    }

    [Flarg]
    [Blarg]
    public int Foo {get; set;}

    // public static void Foo([Flarg][Blarg]int i) {}
}

[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property)]
public class FlargAttribute : Attribute {}

[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property)]
public class BlargAttribute : Attribute {}

PropertyAsParameterInfo.cs:

using System.Reflection;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;

namespace Retrofit;

internal sealed class PropertyAsParameterInfo : ParameterInfo
{
    private readonly PropertyInfo _underlyingProperty;
    private readonly ParameterInfo? _constructionParameterInfo;

    public PropertyAsParameterInfo(PropertyInfo propertyInfo)
    {
        Debug.Assert(propertyInfo != null, "PropertyInfo must be provided.");

        AttrsImpl = (ParameterAttributes)propertyInfo.Attributes;
        NameImpl = propertyInfo.Name;
        MemberImpl = propertyInfo;
        ClassImpl = propertyInfo.PropertyType;

        // It is not a real parameter in the delegate, so,
        // not defining a real position.
        PositionImpl = -1;

        _underlyingProperty = propertyInfo;
    }
    public override bool HasDefaultValue
        => _constructionParameterInfo is not null && _constructionParameterInfo.HasDefaultValue;
    public override object? DefaultValue
        => _constructionParameterInfo?.DefaultValue;
    public override int MetadataToken => _underlyingProperty.MetadataToken;
    public override object? RawDefaultValue
        => _constructionParameterInfo?.RawDefaultValue;

    public override object[] GetCustomAttributes(Type attributeType, bool inherit)
    {
        var constructorAttributes = _constructionParameterInfo?.GetCustomAttributes(attributeType, inherit);

        if (constructorAttributes == null || constructorAttributes is { Length: 0 })
        {
            return _underlyingProperty.GetCustomAttributes(attributeType, inherit);
        }

        var propertyAttributes = _underlyingProperty.GetCustomAttributes(attributeType, inherit);

        var mergedAttributes = new Attribute[constructorAttributes.Length + propertyAttributes.Length];
        Array.Copy(constructorAttributes, mergedAttributes, constructorAttributes.Length);
        Array.Copy(propertyAttributes, 0, mergedAttributes, constructorAttributes.Length, propertyAttributes.Length);

        return mergedAttributes;
    }

    public override object[] GetCustomAttributes(bool inherit)
    {
        var constructorAttributes = _constructionParameterInfo?.GetCustomAttributes(inherit);

        if (constructorAttributes == null || constructorAttributes is { Length: 0 })
        {
            return _underlyingProperty.GetCustomAttributes(inherit);
        }

        var propertyAttributes = _underlyingProperty.GetCustomAttributes(inherit);

        // Since the constructors attributes should take priority we will add them first,
        // as we usually call it as First() or FirstOrDefault() in the argument creation
        var mergedAttributes = new object[constructorAttributes.Length + propertyAttributes.Length];
        Array.Copy(constructorAttributes, mergedAttributes, constructorAttributes.Length);
        Array.Copy(propertyAttributes, 0, mergedAttributes, constructorAttributes.Length, propertyAttributes.Length);

        return mergedAttributes;
    }

    public override IList<CustomAttributeData> GetCustomAttributesData()
    {
        var attributes = new List<CustomAttributeData>(
            _constructionParameterInfo?.GetCustomAttributesData() ?? Array.Empty<CustomAttributeData>());
        attributes.AddRange(_underlyingProperty.GetCustomAttributesData());

        return attributes.AsReadOnly();
    }

    public override Type[] GetOptionalCustomModifiers()
        => _underlyingProperty.GetOptionalCustomModifiers();

    public override Type[] GetRequiredCustomModifiers()
        => _underlyingProperty.GetRequiredCustomModifiers();

    public override bool IsDefined(Type attributeType, bool inherit)
    {
        return (_constructionParameterInfo is not null && _constructionParameterInfo.IsDefined(attributeType, inherit)) ||
            _underlyingProperty.IsDefined(attributeType, inherit);
    }
}

repro.csproj:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
  <PropertyGroup Condition="false">
      <UseMonoRuntime>true</UseMonoRuntime>
      <SelfContained>true</SelfContained>
  </PropertyGroup>
</Project>

Expected output:

$ dotnet run
Got 2 attributes
FlargAttribute
BlargAttribute

Actual output

$ dotnet run
Unhandled Exception:
System.ArgumentNullException: Value cannot be null. (Parameter 'attributeType')
   at System.Reflection.CustomAttribute.GetCustomAttributes(ICustomAttributeProvider obj, Type attributeType, Boolean inherit)
   at System.Reflection.RuntimePropertyInfo.GetCustomAttributes(Type attributeType, Boolean inherit)
   at Retrofit.PropertyAsParameterInfo.GetCustomAttributes(Type attributeType, Boolean inherit) in /private/tmp/parma/PropertyAsParameterInfo.cs:line 42
   at System.Reflection.CustomAttribute.GetCustomAttributesBase(ICustomAttributeProvider obj, Type attributeType, Boolean inheritedOnly)
   at System.Reflection.CustomAttribute.GetCustomAttributes(ICustomAttributeProvider obj, Type attributeType, Boolean inherit)
   at System.Reflection.CustomAttribute.GetCustomAttributes(ICustomAttributeProvider obj, Boolean inherit)
   at System.Attribute.GetCustomAttributes(ParameterInfo element)
   at System.Reflection.CustomAttributeExtensions.GetCustomAttributes(ParameterInfo element)
   at P.Main() in /private/tmp/parma/Program.cs:line 9
[ERROR] FATAL UNHANDLED EXCEPTION: System.ArgumentNullException: Value cannot be null. (Parameter 'attributeType')
   at System.Reflection.CustomAttribute.GetCustomAttributes(ICustomAttributeProvider obj, Type attributeType, Boolean inherit)
   at System.Reflection.RuntimePropertyInfo.GetCustomAttributes(Type attributeType, Boolean inherit)
   at Retrofit.PropertyAsParameterInfo.GetCustomAttributes(Type attributeType, Boolean inherit) in /private/tmp/parma/PropertyAsParameterInfo.cs:line 42
   at System.Reflection.CustomAttribute.GetCustomAttributesBase(ICustomAttributeProvider obj, Type attributeType, Boolean inheritedOnly)
   at System.Reflection.CustomAttribute.GetCustomAttributes(ICustomAttributeProvider obj, Type attributeType, Boolean inherit)
   at System.Reflection.CustomAttribute.GetCustomAttributes(ICustomAttributeProvider obj, Boolean inherit)
   at System.Attribute.GetCustomAttributes(ParameterInfo element)
   at System.Reflection.CustomAttributeExtensions.GetCustomAttributes(ParameterInfo element)
   at P.Main() in /private/tmp/parma/Program.cs:line 9

Activity

  1. added
    area-VM-reflection-mono
    on Nov 7, 2023
  2. added this to the 8.0.x milestone on Nov 7, 2023
  3. lambdageek commented on Nov 7, 2023

    @lambdageek
    MemberAuthor

    Related to #94437 (comment). this is making aspnetcore tests fail when Mono is used as the runtime.

    Also see #94437 (comment)

    And in particular:

    // FIXME: GetCustomAttributesBase doesn't like being passed a null attributeType
    if (attributeType == typeof(CustomAttribute))
    attributeType = null!;
    if (attributeType == typeof(Attribute))
    attributeType = null!;
    if (attributeType == typeof(object))
    attributeType = null!;

  4. lambdageek commented on Nov 7, 2023

    @lambdageek
    MemberAuthor

    I think probably we shouldn't set attributeType = null as some kind of sentinel value that means "do a lookup without filtering the results". Just use a boolean

  5. lambdageek commented on Nov 7, 2023

    @lambdageek
    MemberAuthor
  6. tmds commented on Nov 8, 2023

    @tmds
    Member
  7. ghost added
    in-pr
    on Nov 10, 2023
  8. ghost removed
    in-pr
    on Nov 13, 2023
  9. janani66 commented on Nov 13, 2023

    @janani66

    Can this be ported back to .NET 8 and .NET 7?

  10. ivanpovazan commented on Nov 22, 2023

    @ivanpovazan
    Member

    @janani66 the fix did not get the necessary approval for merging in the backports and will be instead available only in the upcoming .net9 releases. For this reason I am closing the issue.

    Please feel free to reopen it if it blocks you and you find it essential to be backported to previous releases you rely on.

  11. janani66 commented on Dec 13, 2023

    @janani66

    We would like to have a clean aspnetcore test execution -- so the request is to have it back ported to .NET 8 . In this cycle, the aspnetcore failures were caught at the end.

    Adding reference to Tom's comment: #94707 (comment)

    @leecow

  12. ivanpovazan commented on Dec 14, 2023

    @ivanpovazan
    Member

    @janani66 please see my comment: #94707 (comment)

  13. locked and limited conversation to collaborators on Jan 14, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area-VM-reflection-mono

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions