Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add reflection introspection support for function pointers #71516

Closed
wants to merge 10 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<EnableDefaultItems>false</EnableDefaultItems>
Expand Down Expand Up @@ -179,6 +179,7 @@
<Compile Include="$(BclSourcesRoot)\System\Reflection\Emit\TypeBuilderInstantiation.cs" />
<Compile Include="$(BclSourcesRoot)\System\Reflection\Emit\XXXOnTypeBuilderInstantiation.cs" />
<Compile Include="$(BclSourcesRoot)\System\Reflection\FieldInfo.CoreCLR.cs" />
<Compile Include="$(BclSourcesRoot)\System\Reflection\FunctionPointerInfo.CoreCLR.cs" />
<Compile Include="$(BclSourcesRoot)\System\Reflection\LoaderAllocator.cs" />
<Compile Include="$(BclSourcesRoot)\System\Reflection\MdConstant.cs" />
<Compile Include="$(BclSourcesRoot)\System\Reflection\MdFieldInfo.cs" />
Expand All @@ -195,6 +196,7 @@
<Compile Include="$(BclSourcesRoot)\System\Reflection\RuntimeEventInfo.cs" />
<Compile Include="$(BclSourcesRoot)\System\Reflection\RuntimeExceptionHandlingClause.cs" />
<Compile Include="$(BclSourcesRoot)\System\Reflection\RuntimeFieldInfo.cs" />
<Compile Include="$(BclSourcesRoot)\System\Reflection\RuntimeFunctionPointerParameterInfo.CoreCLR.cs" />
<Compile Include="$(BclSourcesRoot)\System\Reflection\RuntimeLocalVariableInfo.cs" />
<Compile Include="$(BclSourcesRoot)\System\Reflection\RuntimeMethodBody.cs" />
<Compile Include="$(BclSourcesRoot)\System\Reflection\RuntimeMethodInfo.CoreCLR.cs" />
Expand Down Expand Up @@ -245,6 +247,9 @@
<Compile Include="$(BclSourcesRoot)\System\ValueType.cs" />
<Compile Include="$(BclSourcesRoot)\System\WeakReference.CoreCLR.cs" />
<Compile Include="$(BclSourcesRoot)\System\WeakReference.T.CoreCLR.cs" />
<Compile Include="$(CommonPath)System\Collections\Generic\ArrayBuilder.cs">
<Link>Common\System\Collections\Generic\ArrayBuilder.cs</Link>
</Compile>
</ItemGroup>
<ItemGroup Condition="'$(FeatureComWrappers)' == 'true'">
<Compile Include="$(BclSourcesRoot)\System\Runtime\InteropServices\ComWrappers.cs" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Diagnostics;

namespace System.Reflection
{
internal partial class FunctionPointerInfo
{
private readonly RuntimeType _type;

internal FunctionPointerInfo(RuntimeType type)
{
_type = type;
Type[] arguments = RuntimeTypeHandle.GetArgumentTypesFromFunctionPointer(type);
Debug.Assert(arguments.Length >= 1);

_returnInfo = new RuntimeFunctionPointerParameterInfo(this, arguments[0], 0);
int count = arguments.Length;
if (count == 1)
{
_parameterInfos = Array.Empty<RuntimeFunctionPointerParameterInfo>();
}
else
{
RuntimeFunctionPointerParameterInfo[] parameterInfos = new RuntimeFunctionPointerParameterInfo[count - 1];
for (int i = 0; i < count - 1; i++)
{
parameterInfos[i] = new RuntimeFunctionPointerParameterInfo(this, arguments[i + 1], i + 1);
}
_parameterInfos = parameterInfos;
}
}

internal RuntimeType FunctionPointerType => _type;
internal unsafe MdSigCallingConvention CallingConvention => (MdSigCallingConvention)RuntimeTypeHandle.GetRawCallingConventionsFromFunctionPointer(_type);
internal Type[]? GetCustomModifiersFromFunctionPointer(int position, bool required) =>
RuntimeTypeHandle.GetCustomModifiersFromFunctionPointer(_type, 0, required: false);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,28 +8,6 @@

namespace System.Reflection
{
[Flags]
internal enum MdSigCallingConvention : byte
{
CallConvMask = 0x0f, // Calling convention is bottom 4 bits

Default = 0x00,
C = 0x01,
StdCall = 0x02,
ThisCall = 0x03,
FastCall = 0x04,
Vararg = 0x05,
Field = 0x06,
LocalSig = 0x07,
Property = 0x08,
Unmanaged = 0x09,
GenericInst = 0x0a, // generic method instantiation

Generic = 0x10, // Generic method sig with explicit number of type arguments (precedes ordinary parameter count)
HasThis = 0x20, // Top bit indicates a 'this' parameter
ExplicitThis = 0x40, // This parameter is explicitly in the signature
}

[Flags]
internal enum PInvokeAttributes
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Diagnostics;

namespace System.Reflection
{
internal partial class RuntimeFunctionPointerParameterInfo
{
private readonly FunctionPointerInfo _functionPointer;
private readonly int _position;
private Type[]? _optionalModifiers;

public RuntimeFunctionPointerParameterInfo(FunctionPointerInfo functionPointer, Type parameterType, int position)
{
_functionPointer = functionPointer;
_parameterType = parameterType;
_position = position; // 0 = return value; 1 = first parameter
}

public override Type[] GetOptionalCustomModifiers()
{
if (_optionalModifiers == null)
{
if (_position == 0)
{
// Return value should be normalized. This will call SetCustomModifiersForReturnType.
_functionPointer.ComputeCallingConventions();
Debug.Assert(_optionalModifiers != null);
}
else
{
Type[]? mods = RuntimeTypeHandle.GetCustomModifiersFromFunctionPointer(_functionPointer.FunctionPointerType, _position, required: false);
if (mods == null)
{
_optionalModifiers = Type.EmptyTypes;
}
}
}

Debug.Assert(_optionalModifiers != null);
return _optionalModifiers;
}

internal void SetCustomModifiersForReturnType(Type[] modifiers)
{
Debug.Assert(_position == 0);
_optionalModifiers = modifiers;
}

public override Type[] GetRequiredCustomModifiers()
{
Type[]? value = RuntimeTypeHandle.GetCustomModifiersFromFunctionPointer(_functionPointer.FunctionPointerType, _position, required: true);
return value ??= Type.EmptyTypes;
}
}
}
37 changes: 15 additions & 22 deletions src/coreclr/System.Private.CoreLib/src/System/RuntimeHandles.cs
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,12 @@ internal static bool IsSZArray(RuntimeType type)
return corElemType == CorElementType.ELEMENT_TYPE_SZARRAY;
}

internal static bool IsFunctionPointer(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
return corElemType == CorElementType.ELEMENT_TYPE_FNPTR;
}

internal static bool HasElementType(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
Expand Down Expand Up @@ -383,6 +389,15 @@ public ModuleHandle GetModuleHandle()
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern RuntimeMethodHandleInternal GetMethodAt(RuntimeType type, int slot);

[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern Type[]? GetCustomModifiersFromFunctionPointer(RuntimeType functionPointerType, int position, bool required);

[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern byte GetRawCallingConventionsFromFunctionPointer(RuntimeType type);

[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern Type[] GetArgumentTypesFromFunctionPointer(RuntimeType type);

// This is managed wrapper for MethodTable::IntroducedMethodIterator
internal struct IntroducedMethodEnumerator
{
Expand Down Expand Up @@ -1600,28 +1615,6 @@ internal static MetadataImport GetMetadataImport(RuntimeModule module)

internal sealed unsafe class Signature
{
#region Definitions
internal enum MdSigCallingConvention : byte
{
Generics = 0x10,
HasThis = 0x20,
ExplicitThis = 0x40,
CallConvMask = 0x0F,
Default = 0x00,
C = 0x01,
StdCall = 0x02,
ThisCall = 0x03,
FastCall = 0x04,
Vararg = 0x05,
Field = 0x06,
LocalSig = 0x07,
Property = 0x08,
Unmanaged = 0x09,
GenericInst = 0x0A,
Max = 0x0B,
}
#endregion

#region FCalls
[MemberNotNull(nameof(m_arguments))]
[MemberNotNull(nameof(m_returnTypeORfieldType))]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1489,7 +1489,7 @@ internal T[] GetMemberList(MemberListType listType, string? name, CacheType cach
private static CerHashtable<RuntimeMethodInfo, RuntimeMethodInfo> s_methodInstantiations;
private static object? s_methodInstantiationsLock;
private string? m_defaultMemberName;
private object? m_genericCache; // Generic cache for rare scenario specific data. It is used to cache Enum names and values.
private object? m_genericCache;
private object[]? _emptyArray; // Object array cache for Attribute.GetCustomAttributes() pathological no-result case.
#endregion

Expand Down Expand Up @@ -1532,6 +1532,10 @@ private MemberInfoCache<T> GetMemberCache<T>(ref MemberInfoCache<T>? m_cache)

#region Internal Members


/// <summary>
/// Generic cache for rare scenario specific data. It is used to cache either Enum names, Enum values, the Activator cache or a function pointer.
/// </summary>
internal object? GenericCache
{
get => m_genericCache;
Expand Down Expand Up @@ -1561,6 +1565,11 @@ internal bool DomainInitialized
if (!m_runtimeType.GetRootElementType().IsGenericTypeDefinition && m_runtimeType.ContainsGenericParameters)
return null;

// Exclude function pointer; it requires a grammar update (see https://docs.microsoft.com/dotnet/framework/reflection-and-codedom/specifying-fully-qualified-type-names)
// and parsing support for Type.GetType(...) and related GetType() methods.
if (m_runtimeType.IsFunctionPointer)
return null;

// No assembly.
return ConstructName(ref m_fullname, TypeNameFormatFlags.FormatNamespace | TypeNameFormatFlags.FormatFullInst);

Expand All @@ -1573,12 +1582,16 @@ internal bool DomainInitialized
}
}

internal string GetNameSpace()
internal string? GetNameSpace()
{
// @Optimization - Use ConstructName to populate m_namespace
if (m_namespace == null)
{
Type type = m_runtimeType;

if (type.IsFunctionPointer)
return null;

type = type.GetRootElementType();

while (type.IsNested)
Expand Down Expand Up @@ -1757,6 +1770,12 @@ internal FieldInfo GetField(RuntimeFieldHandleInternal field)
return m_fieldInfoCache!.AddField(field);
}

internal FunctionPointerInfo? FunctionPointerInfo
{
get => GenericCache as FunctionPointerInfo;
set => GenericCache = value;
}

#endregion
}
#endregion
Expand Down Expand Up @@ -3321,7 +3340,8 @@ public override string? AssemblyQualifiedName
{
string? fullname = FullName;

// FullName is null if this type contains generic parameters but is not a generic type definition.
// FullName is null if this type contains generic parameters but is not a generic type definition
// or if it is a function pointer.
if (fullname == null)
return null;

Expand All @@ -3333,7 +3353,7 @@ public override string? Namespace
{
get
{
string ns = Cache.GetNameSpace();
string? ns = Cache.GetNameSpace();
if (string.IsNullOrEmpty(ns))
{
return null;
Expand Down Expand Up @@ -3766,6 +3786,49 @@ internal static CorElementType GetUnderlyingType(RuntimeType type)

#endregion

#region Function Pointer
public override bool IsFunctionPointer => RuntimeTypeHandle.IsFunctionPointer(this);
public override bool IsUnmanagedFunctionPointer
{
get
{
switch (GetFunctionPointerInfo().CallingConvention)
{
case MdSigCallingConvention.C:
case MdSigCallingConvention.StdCall:
case MdSigCallingConvention.ThisCall:
case MdSigCallingConvention.FastCall:
case MdSigCallingConvention.Unmanaged:
return true;
default:
return false;
}
}
}

public override FunctionPointerParameterInfo[] GetFunctionPointerParameterInfos() => GetFunctionPointerInfo().ParameterInfos;
public override FunctionPointerParameterInfo GetFunctionPointerReturnParameter() => GetFunctionPointerInfo().ReturnParameter;
public override Type[] GetFunctionPointerCallingConventions() => GetFunctionPointerInfo().GetCallingConventions();

internal FunctionPointerInfo GetFunctionPointerInfo()
{
FunctionPointerInfo? fnPtr = Cache.FunctionPointerInfo;

if (fnPtr == null)
{
if (!IsFunctionPointer)
{
throw new InvalidOperationException(SR.InvalidOperation_NotFunctionPointer);
}

fnPtr = new FunctionPointerInfo(this);
Cache.FunctionPointerInfo = fnPtr;
}

return fnPtr;
}
#endregion

#endregion

public override string ToString() => GetCachedName(TypeNameKind.ToString)!;
Expand Down
4 changes: 3 additions & 1 deletion src/coreclr/debug/daccess/dacdbiimpl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2370,9 +2370,11 @@ TypeHandle DacDbiInterfaceImpl::FindLoadedFnptrType(DWORD numTypeArgs, TypeHandl
// @dbgtodo : Do we need to worry about calling convention here?
// LoadFnptrTypeThrowing expects the count of arguments, not
// including return value, so we subtract 1 from numTypeArgs.
return ClassLoader::LoadFnptrTypeThrowing(0,
return ClassLoader::LoadFnptrTypeThrowing(0, // callConv
numTypeArgs - 1,
pInst,
0, // numCustomMods
NULL, // customMods
ClassLoader::DontLoadTypes);
} // DacDbiInterfaceImpl::FindLoadedFnptrType

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
</PropertyGroup>
Expand Down Expand Up @@ -159,6 +159,7 @@
<Compile Include="System\Reflection\MethodBase.NativeAot.cs" />
<Compile Include="System\Reflection\Metadata\AssemblyExtensions.cs" />
<Compile Include="System\Reflection\Metadata\MetadataUpdater.cs" />
<Compile Include="System\Reflection\RuntimeFunctionPointerParameterInfo.NativeAot.cs" />
<Compile Include="System\Runtime\InteropServices\CriticalHandle.NativeAot.cs" />
<Compile Include="System\Activator.NativeAot.cs" />
<Compile Include="System\AppContext.NativeAot.cs" />
Expand Down Expand Up @@ -509,7 +510,7 @@
<Compile Include="System\Reflection\Runtime\TypeInfos\NativeFormat\NativeFormatRuntimeTypeInfo.CoreGetDeclared.cs" />
<Compile Include="System\Reflection\Runtime\TypeInfos\RuntimeArrayTypeInfo.cs" />
<Compile Include="System\Reflection\Runtime\TypeInfos\RuntimeByRefTypeInfo.cs" />
<Compile Include="System\Reflection\Runtime\TypeInfos\RuntimeClsIdTypeInfo.cs" Condition="'$(FeatureComInterop)' == 'true'"/>
<Compile Include="System\Reflection\Runtime\TypeInfos\RuntimeClsIdTypeInfo.cs" Condition="'$(FeatureComInterop)' == 'true'" />
<Compile Include="System\Reflection\Runtime\TypeInfos\RuntimeClsIdTypeInfo.UnificationKey.cs" Condition="'$(FeatureComInterop)' == 'true'" />
<Compile Include="System\Reflection\Runtime\TypeInfos\RuntimeConstructedGenericTypeInfo.cs" />
<Compile Include="System\Reflection\Runtime\TypeInfos\RuntimeConstructedGenericTypeInfo.UnificationKey.cs" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace System.Reflection
{
internal partial class RuntimeFunctionPointerParameterInfo
{
public override Type[] GetOptionalCustomModifiers() => throw new NotSupportedException();
public override Type[] GetRequiredCustomModifiers() => throw new NotSupportedException();
}
}
Loading