Imported Upstream version 6.4.0.137

Former-commit-id: 943baa9f16a098c33e129777827f3a9d20da00d6
This commit is contained in:
Xamarin Public Jenkins (auto-signing)
2019-07-26 19:53:28 +00:00
parent e9207cf623
commit ef583813eb
2712 changed files with 74169 additions and 40587 deletions

View File

@@ -0,0 +1,96 @@
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Loader;
using System.Threading;
namespace System.Reflection
{
[StructLayout (LayoutKind.Sequential)]
partial class Assembly
{
internal bool IsRuntimeImplemented () => this is RuntimeAssembly;
internal virtual IntPtr MonoAssembly {
get {
throw new NotImplementedException ();
}
}
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public static Assembly? LoadWithPartialName (string partialName)
{
if (partialName == null)
throw new ArgumentNullException (nameof (partialName));
if (partialName.Length == 0 || partialName [0] == '\0')
throw new ArgumentException (SR.Format_StringZeroLength, nameof (partialName));
try {
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return RuntimeAssembly.InternalLoad (partialName, ref stackMark, IntPtr.Zero);
} catch (FileNotFoundException) {
return null;
}
}
[System.Security.DynamicSecurityMethod]
[MethodImplAttribute (MethodImplOptions.NoInlining)]
public static Assembly GetExecutingAssembly()
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return GetExecutingAssembly(ref stackMark);
}
[MethodImplAttribute (MethodImplOptions.InternalCall)]
internal static extern RuntimeAssembly GetExecutingAssembly (ref StackCrawlMark stackMark);
[MethodImplAttribute (MethodImplOptions.InternalCall)]
public static extern Assembly GetCallingAssembly ();
[MethodImplAttribute (MethodImplOptions.InternalCall)]
public static extern Assembly GetEntryAssembly ();
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public static Assembly Load (string assemblyString)
{
if (assemblyString == null)
throw new ArgumentNullException (nameof (assemblyString));
var name = new AssemblyName (assemblyString);
// TODO: trigger assemblyFromResolveEvent
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return Load (name, ref stackMark, AssemblyLoadContext.CurrentContextualReflectionContext);
}
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public static Assembly Load (AssemblyName assemblyRef)
{
if (assemblyRef == null)
throw new ArgumentNullException (nameof (assemblyRef));
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return Load (assemblyRef, ref stackMark, AssemblyLoadContext.CurrentContextualReflectionContext);
}
internal static Assembly Load (AssemblyName assemblyRef, ref StackCrawlMark stackMark, AssemblyLoadContext assemblyLoadContext)
{
// TODO: pass AssemblyName
// TODO: pass assemblyLoadContext
var assembly = InternalLoad (assemblyRef.FullName, ref stackMark, IntPtr.Zero);
if (assembly == null)
throw new FileNotFoundException (null, assemblyRef.Name);
return assembly;
}
[MethodImplAttribute (MethodImplOptions.InternalCall)]
internal static extern Assembly InternalLoad (string assemblyName, ref StackCrawlMark stackMark, IntPtr ptrLoadContextBinder);
[MethodImplAttribute (MethodImplOptions.InternalCall)]
internal extern Type InternalGetType (Module module, string name, bool throwOnError, bool ignoreCase);
[MethodImplAttribute (MethodImplOptions.InternalCall)]
internal extern static void InternalGetAssemblyName (string assemblyFile, out Mono.MonoAssemblyName aname, out string codebase);
}
}

View File

@@ -0,0 +1,129 @@
using Mono;
using System.Configuration.Assemblies;
using System.Globalization;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Reflection
{
[StructLayout (LayoutKind.Sequential)]
partial class AssemblyName
{
public AssemblyName (string assemblyName)
{
if (assemblyName == null)
throw new ArgumentNullException (nameof (assemblyName));
if (assemblyName.Length == 0 || assemblyName [0] == '\0')
throw new ArgumentException (SR.Format_StringZeroLength);
using (var name = RuntimeMarshal.MarshalString (assemblyName)) {
// TODO: Should use CoreRT AssemblyNameParser
if (!ParseAssemblyName (name.Value, out var nativeName, out var isVersionDefined, out var isTokenDefined))
throw new FileLoadException ("The assembly name is invalid.");
try {
unsafe {
FillName (&nativeName, null, isVersionDefined, false, isTokenDefined);
}
} finally {
RuntimeMarshal.FreeAssemblyName (ref nativeName, false);
}
}
}
unsafe byte [] ComputePublicKeyToken ()
{
if (_publicKey == null || _publicKey.Length == 0)
return Array.Empty<byte>();
var token = new byte [8];
fixed (byte* pkt = token)
fixed (byte *pk = _publicKey)
get_public_token (pkt, pk, _publicKey.Length);
return token;
}
internal static AssemblyName Create (Assembly assembly, bool fillCodebase)
{
AssemblyName aname = new AssemblyName ();
unsafe {
MonoAssemblyName *native = GetNativeName (assembly.MonoAssembly);
aname.FillName (native, fillCodebase ? assembly.CodeBase : null, true, true, true);
}
return aname;
}
internal unsafe void FillName (MonoAssemblyName *native, string codeBase, bool addVersion, bool addPublickey, bool defaultToken)
{
_name = RuntimeMarshal.PtrToUtf8String (native->name);
_flags = (AssemblyNameFlags) native->flags;
_hashAlgorithm = (AssemblyHashAlgorithm) native->hash_alg;
_versionCompatibility = AssemblyVersionCompatibility.SameMachine;
if (addVersion) {
var build = native->build == 65535 ? -1 : native->build;
var revision = native->revision == 65535 ? -1 : native->revision;
if (build == -1)
_version = new Version (native->major, native->minor);
else if (revision == -1)
_version = new Version (native->major, native->minor, build);
else
_version = new Version (native->major, native->minor, build, revision);
}
_codeBase = codeBase;
if (native->culture != IntPtr.Zero)
_cultureInfo = CultureInfo.GetCultureInfo (RuntimeMarshal.PtrToUtf8String (native->culture));
if (native->public_key != IntPtr.Zero) {
_publicKey = RuntimeMarshal.DecodeBlobArray (native->public_key);
_flags |= AssemblyNameFlags.PublicKey;
} else if (addPublickey) {
_publicKey = Array.Empty<byte> ();
_flags |= AssemblyNameFlags.PublicKey;
}
// MonoAssemblyName keeps the public key token as an hexadecimal string
if (native->public_key_token [0] != 0) {
var keyToken = new byte [8];
for (int i = 0, j = 0; i < 8; ++i) {
keyToken [i] = (byte) (RuntimeMarshal.AsciHexDigitValue (native->public_key_token [j++]) << 4);
keyToken [i] |= (byte) RuntimeMarshal.AsciHexDigitValue (native->public_key_token [j++]);
}
_publicKeyToken = keyToken;
} else if (defaultToken) {
_publicKeyToken = Array.Empty<byte> ();
}
}
static AssemblyName GetFileInformationCore (string assemblyFile)
{
unsafe {
Assembly.InternalGetAssemblyName (Path.GetFullPath (assemblyFile), out var nativeName, out var codebase);
var aname = new AssemblyName ();
try {
aname.FillName (&nativeName, codebase, true, false, true);
return aname;
} finally {
RuntimeMarshal.FreeAssemblyName (ref nativeName, false);
}
}
}
[MethodImplAttribute (MethodImplOptions.InternalCall)]
static extern unsafe void get_public_token (byte* token, byte* pubkey, int len);
[MethodImplAttribute (MethodImplOptions.InternalCall)]
static extern unsafe MonoAssemblyName* GetNativeName (IntPtr assemblyPtr);
[MethodImpl (MethodImplOptions.InternalCall)]
static extern bool ParseAssemblyName (IntPtr name, out MonoAssemblyName aname, out bool is_version_definited, out bool is_token_defined);
}
}

View File

@@ -0,0 +1,160 @@
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace System.Reflection
{
public class CustomAttributeData
{
class LazyCAttrData {
internal Assembly assembly;
internal IntPtr data;
internal uint data_length;
}
ConstructorInfo ctorInfo;
IList<CustomAttributeTypedArgument> ctorArgs;
IList<CustomAttributeNamedArgument> namedArgs;
LazyCAttrData lazyData;
protected CustomAttributeData ()
{
}
// custom-attrs.c:create_custom_attr_data ()
internal CustomAttributeData (ConstructorInfo ctorInfo, Assembly assembly, IntPtr data, uint data_length)
{
this.ctorInfo = ctorInfo;
this.lazyData = new LazyCAttrData ();
this.lazyData.assembly = assembly;
this.lazyData.data = data;
this.lazyData.data_length = data_length;
}
internal CustomAttributeData (ConstructorInfo ctorInfo)
: this (ctorInfo, Array.Empty<CustomAttributeTypedArgument> (), Array.Empty<CustomAttributeNamedArgument> ())
{
}
internal CustomAttributeData (ConstructorInfo ctorInfo, IList<CustomAttributeTypedArgument> ctorArgs, IList<CustomAttributeNamedArgument> namedArgs)
{
this.ctorInfo = ctorInfo;
this.ctorArgs = ctorArgs;
this.namedArgs = namedArgs;
}
[MethodImplAttribute (MethodImplOptions.InternalCall)]
static extern void ResolveArgumentsInternal (ConstructorInfo ctor, Assembly assembly, IntPtr data, uint data_length, out object[] ctorArgs, out object[] namedArgs);
void ResolveArguments ()
{
object[] ctor_args, named_args;
if (lazyData == null)
return;
ResolveArgumentsInternal (ctorInfo, lazyData.assembly, lazyData.data, lazyData.data_length, out ctor_args, out named_args);
this.ctorArgs = Array.AsReadOnly<CustomAttributeTypedArgument>
(ctor_args != null ? UnboxValues<CustomAttributeTypedArgument> (ctor_args) : Array.Empty<CustomAttributeTypedArgument>());
this.namedArgs = Array.AsReadOnly<CustomAttributeNamedArgument>
(named_args != null ? UnboxValues<CustomAttributeNamedArgument> (named_args) : Array.Empty<CustomAttributeNamedArgument>());
lazyData = null;
}
public
virtual
ConstructorInfo Constructor {
get {
return ctorInfo;
}
}
public
virtual
IList<CustomAttributeTypedArgument> ConstructorArguments {
get {
ResolveArguments ();
return ctorArgs;
}
}
public
virtual
IList<CustomAttributeNamedArgument> NamedArguments {
get {
ResolveArguments ();
return namedArgs;
}
}
public static IList<CustomAttributeData> GetCustomAttributes (Assembly target) {
return MonoCustomAttrs.GetCustomAttributesData (target);
}
public static IList<CustomAttributeData> GetCustomAttributes (MemberInfo target) {
return MonoCustomAttrs.GetCustomAttributesData (target);
}
internal static IList<CustomAttributeData> GetCustomAttributesInternal (RuntimeType target) {
return MonoCustomAttrs.GetCustomAttributesData (target);
}
public static IList<CustomAttributeData> GetCustomAttributes (Module target) {
return MonoCustomAttrs.GetCustomAttributesData (target);
}
public static IList<CustomAttributeData> GetCustomAttributes (ParameterInfo target) {
return MonoCustomAttrs.GetCustomAttributesData (target);
}
virtual public Type AttributeType {
get { return ctorInfo.DeclaringType; }
}
public override string ToString ()
{
ResolveArguments ();
StringBuilder sb = new StringBuilder ();
sb.Append ("[" + ctorInfo.DeclaringType.FullName + "(");
for (int i = 0; i < ctorArgs.Count; i++) {
sb.Append (ctorArgs [i].ToString ());
if (i + 1 < ctorArgs.Count)
sb.Append (", ");
}
if (namedArgs.Count > 0)
sb.Append (", ");
for (int j = 0; j < namedArgs.Count; j++) {
sb.Append (namedArgs [j].ToString ());
if (j + 1 < namedArgs.Count)
sb.Append (", ");
}
sb.AppendFormat (")]");
return sb.ToString ();
}
static T [] UnboxValues<T> (object [] values)
{
T [] retval = new T [values.Length];
for (int i = 0; i < values.Length; i++)
retval [i] = (T) values [i];
return retval;
}
public override int GetHashCode () => base.GetHashCode ();
public override bool Equals (object? obj)
{
return obj == (object)this;
}
}
}

View File

@@ -0,0 +1,13 @@
namespace System.Reflection
{
partial struct CustomAttributeTypedArgument
{
static object CanonicalizeValue (object value)
{
if (value.GetType ().IsEnum)
return ((Enum) value).GetValue ();
return value;
}
}
}

View File

@@ -0,0 +1,105 @@
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Reflection
{
partial class FieldInfo
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern FieldInfo internal_from_handle_type (IntPtr field_handle, IntPtr type_handle);
public static FieldInfo GetFieldFromHandle (RuntimeFieldHandle handle)
{
if (handle.IsNullHandle ())
throw new ArgumentException (SR.Argument_InvalidHandle);
return internal_from_handle_type (handle.Value, IntPtr.Zero);
}
public static FieldInfo GetFieldFromHandle (RuntimeFieldHandle handle, RuntimeTypeHandle declaringType)
{
if (handle.IsNullHandle ())
throw new ArgumentException (SR.Argument_InvalidHandle);
FieldInfo fi = internal_from_handle_type (handle.Value, declaringType.Value);
if (fi == null)
throw new ArgumentException ("The field handle and the type handle are incompatible.");
return fi;
}
internal virtual int GetFieldOffset ()
{
throw NotImplemented.ByDesign;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern MarshalAsAttribute get_marshal_info ();
internal object[] GetPseudoCustomAttributes ()
{
int count = 0;
if (IsNotSerialized)
count ++;
if (DeclaringType.IsExplicitLayout)
count ++;
MarshalAsAttribute marshalAs = get_marshal_info ();
if (marshalAs != null)
count ++;
if (count == 0)
return null;
object[] attrs = new object [count];
count = 0;
if (IsNotSerialized)
attrs [count ++] = new NonSerializedAttribute ();
if (DeclaringType.IsExplicitLayout)
attrs [count ++] = new FieldOffsetAttribute (GetFieldOffset ());
if (marshalAs != null)
attrs [count ++] = marshalAs;
return attrs;
}
internal CustomAttributeData[] GetPseudoCustomAttributesData ()
{
int count = 0;
if (IsNotSerialized)
count++;
if (DeclaringType.IsExplicitLayout)
count++;
MarshalAsAttribute marshalAs = get_marshal_info ();
if (marshalAs != null)
count++;
if (count == 0)
return null;
CustomAttributeData[] attrsData = new CustomAttributeData [count];
count = 0;
if (IsNotSerialized)
attrsData [count++] = new CustomAttributeData ((typeof (NonSerializedAttribute)).GetConstructor (Type.EmptyTypes));
if (DeclaringType.IsExplicitLayout) {
var ctorArgs = new CustomAttributeTypedArgument[] { new CustomAttributeTypedArgument (typeof (int), GetFieldOffset ()) };
attrsData [count++] = new CustomAttributeData (
(typeof (FieldOffsetAttribute)).GetConstructor (new[] { typeof (int) }),
ctorArgs,
Array.Empty<CustomAttributeNamedArgument> ());
}
if (marshalAs != null) {
var ctorArgs = new CustomAttributeTypedArgument[] { new CustomAttributeTypedArgument (typeof (UnmanagedType), marshalAs.Value) };
attrsData [count++] = new CustomAttributeData (
(typeof (MarshalAsAttribute)).GetConstructor (new[] { typeof (UnmanagedType) }),
ctorArgs,
Array.Empty<CustomAttributeNamedArgument> ());//FIXME Get named params
}
return attrsData;
}
}
}

View File

@@ -0,0 +1,24 @@
namespace System.Reflection
{
public abstract partial class MemberInfo
{
internal bool HasSameMetadataDefinitionAsCore<TOther>(MemberInfo other) where TOther : MemberInfo
{
if (other == null)
throw new ArgumentNullException(nameof(other));
// Ensure that "other" is a runtime-implemented MemberInfo. Do this check before calling any methods on it!
if (!(other is TOther))
return false;
if (MetadataToken != other.MetadataToken)
return false;
if (!(Module.Equals(other.Module)))
return false;
return true;
}
}
}

View File

@@ -0,0 +1,74 @@
using System.Runtime.CompilerServices;
using System.Reflection.Emit;
namespace System.Reflection
{
partial class MethodBase
{
public static MethodBase GetMethodFromHandle (RuntimeMethodHandle handle)
{
if (handle.IsNullHandle ())
throw new ArgumentException (SR.Argument_InvalidHandle);
MethodBase m = RuntimeMethodInfo.GetMethodFromHandleInternalType (handle.Value, IntPtr.Zero);
if (m == null)
throw new ArgumentException (SR.Argument_InvalidHandle);
Type declaringType = m.DeclaringType;
if (declaringType != null && declaringType.IsGenericType)
throw new ArgumentException (String.Format (SR.Argument_MethodDeclaringTypeGeneric,
m, declaringType.GetGenericTypeDefinition ()));
return m;
}
public static MethodBase GetMethodFromHandle (RuntimeMethodHandle handle, RuntimeTypeHandle declaringType)
{
if (handle.IsNullHandle ())
throw new ArgumentException (SR.Argument_InvalidHandle);
MethodBase m = RuntimeMethodInfo.GetMethodFromHandleInternalType (handle.Value, declaringType.Value);
if (m == null)
throw new ArgumentException (SR.Argument_InvalidHandle);
return m;
}
[MethodImplAttribute (MethodImplOptions.InternalCall)]
public extern static MethodBase GetCurrentMethod ();
internal virtual ParameterInfo[] GetParametersNoCopy ()
{
return GetParametersInternal ();
}
internal virtual ParameterInfo[] GetParametersInternal ()
{
throw new NotImplementedException ();
}
internal virtual int GetParametersCount ()
{
throw new NotImplementedException ();
}
internal virtual Type GetParameterType (int pos)
{
throw new NotImplementedException ();
}
internal virtual Type[] GetParameterTypes ()
{
ParameterInfo[] paramInfo = GetParametersNoCopy ();
Type[] parameterTypes = new Type [paramInfo.Length];
for (int i = 0; i < paramInfo.Length; i++)
parameterTypes [i] = paramInfo [i].ParameterType;
return parameterTypes;
}
internal virtual int get_next_table_index (object obj, int table, int count)
{
throw new NotImplementedException ();
}
}
}

View File

@@ -0,0 +1,397 @@
#nullable disable
using System.IO;
using System.Globalization;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Loader;
using System.Threading;
namespace System.Reflection
{
[StructLayout (LayoutKind.Sequential)]
sealed class RuntimeAssembly : Assembly
{
private sealed class ResolveEventHolder
{
public event ModuleResolveEventHandler ModuleResolve;
}
private sealed class UnmanagedMemoryStreamForModule : UnmanagedMemoryStream
{
Module module;
public unsafe UnmanagedMemoryStreamForModule (byte* pointer, long length, Module module)
: base (pointer, length)
{
this.module = module;
}
}
//
// KEEP IN SYNC WITH mcs/class/corlib/System.Reflection/RuntimeAssembly.cs
//
#region VM dependency
IntPtr _mono_assembly;
object _evidence; // Unused, kept for layout compatibility
#endregion
ResolveEventHolder resolve_event_holder;
public override extern MethodInfo? EntryPoint {
[MethodImplAttribute (MethodImplOptions.InternalCall)]
get;
}
public override bool ReflectionOnly => false;
public override string? CodeBase {
get {
return get_code_base (this, false);
}
}
public override string? FullName {
get {
return get_fullname (this);
}
}
//
// We can't store the event directly in this class, since the
// compiler would silently insert the fields before _mono_assembly
//
public override event ModuleResolveEventHandler ModuleResolve {
add {
resolve_event_holder.ModuleResolve += value;
}
remove {
resolve_event_holder.ModuleResolve -= value;
}
}
public override Module? ManifestModule => GetManifestModuleInternal ();
public override bool GlobalAssemblyCache => false;
public override long HostContext => 0;
public override string ImageRuntimeVersion => InternalImageRuntimeVersion (this);
public override string Location {
get {
return get_location ();
}
}
// TODO:
public override bool IsCollectible => false;
internal static AssemblyName CreateAssemblyName (string assemblyString, out RuntimeAssembly assemblyFromResolveEvent)
{
if (assemblyString == null)
throw new ArgumentNullException (nameof (assemblyString));
if ((assemblyString.Length == 0) ||
(assemblyString[0] == '\0'))
throw new ArgumentException (SR.Format_StringZeroLength);
assemblyFromResolveEvent = null;
try {
return new AssemblyName (assemblyString);
} catch (Exception) {
assemblyFromResolveEvent = (RuntimeAssembly)AssemblyLoadContext.DoAssemblyResolve (assemblyString);
if (assemblyFromResolveEvent == null)
throw new FileLoadException (assemblyString);
return null;
}
}
[MethodImplAttribute (MethodImplOptions.InternalCall)]
public override extern String[] GetManifestResourceNames ();
[MethodImplAttribute (MethodImplOptions.InternalCall)]
public override extern Type[] GetExportedTypes ();
[MethodImplAttribute (MethodImplOptions.InternalCall)]
public override extern Type[] GetForwardedTypes ();
public override ManifestResourceInfo GetManifestResourceInfo (string resourceName)
{
if (resourceName == null)
throw new ArgumentNullException ("resourceName");
if (resourceName.Length == 0)
throw new ArgumentException ("String cannot have zero length.");
ManifestResourceInfo result = new ManifestResourceInfo (null, null, 0);
bool found = GetManifestResourceInfoInternal (resourceName, result);
if (found)
return result;
else
return null;
}
public override Stream GetManifestResourceStream (string name)
{
if (name == null)
throw new ArgumentNullException (nameof (name));
if (name.Length == 0)
throw new ArgumentException ("String cannot have zero length.",
"name");
unsafe {
byte* data = (byte*) GetManifestResourceInternal (name, out int length, out Module resourceModule);
if (data == null)
return null;
// It cannot use SafeBuffer mode because not all methods are supported in this
// mode (e.g. UnmanagedMemoryStream.get_PositionPointer)
return new UnmanagedMemoryStreamForModule (data, length, resourceModule);
}
}
public override Stream GetManifestResourceStream (Type type, string name)
{
if (type == null && name == null)
throw new ArgumentNullException (nameof (type));
string nameSpace = type?.Namespace;
string resourceName = nameSpace != null && name != null ?
nameSpace + Type.Delimiter + name :
nameSpace + name;
return GetManifestResourceStream (resourceName);
}
public override AssemblyName GetName(bool copiedName)
{
return AssemblyName.Create (this, true);
}
public override Type GetType (string name, bool throwOnError, bool ignoreCase)
{
if (name == null)
throw new ArgumentNullException (nameof (name));
if (name.Length == 0)
throw new ArgumentException ("name", "Name cannot be empty");
return InternalGetType (null, name, throwOnError, ignoreCase);
}
public override bool IsDefined (Type attributeType, bool inherit)
{
return MonoCustomAttrs.IsDefined (this, attributeType, inherit);
}
public override IList<CustomAttributeData> GetCustomAttributesData ()
{
return CustomAttributeData.GetCustomAttributes (this);
}
public override object[] GetCustomAttributes (bool inherit)
{
return MonoCustomAttrs.GetCustomAttributes (this, inherit);
}
public override object[] GetCustomAttributes (Type attributeType, bool inherit)
{
return MonoCustomAttrs.GetCustomAttributes (this, attributeType, inherit);
}
public override Module GetModule (string name)
{
if (name == null)
throw new ArgumentNullException ("name");
if (name.Length == 0)
throw new ArgumentException ("Name can't be empty");
Module[] modules = GetModules (true);
foreach (Module module in modules) {
if (module.ScopeName == name)
return module;
}
return null;
}
public override Module[] GetModules (bool getResourceModules)
{
Module[] modules = GetModulesInternal ();
if (!getResourceModules) {
var result = new List<Module> (modules.Length);
foreach (Module m in modules)
if (!m.IsResource ())
result.Add (m);
return result.ToArray ();
}
else
return modules;
}
public override Module[] GetLoadedModules (bool getResourceModules)
{
return GetModules (getResourceModules);
}
public override AssemblyName[] GetReferencedAssemblies ()
{
using (var nativeNames = new Mono.SafeGPtrArrayHandle (InternalGetReferencedAssemblies (this))) {
var numAssemblies = nativeNames.Length;
try {
AssemblyName [] result = new AssemblyName[numAssemblies];
const bool addVersion = true;
const bool addPublicKey = false;
const bool defaultToken = true;
for (int i = 0; i < numAssemblies; i++) {
AssemblyName name = new AssemblyName ();
unsafe {
Mono.MonoAssemblyName *nativeName = (Mono.MonoAssemblyName*) nativeNames[i];
name.FillName (nativeName, null, addVersion, addPublicKey, defaultToken);
result[i] = name;
}
}
return result;
} finally {
for (int i = 0; i < numAssemblies; i++) {
unsafe {
Mono.MonoAssemblyName* nativeName = (Mono.MonoAssemblyName*) nativeNames[i];
Mono.RuntimeMarshal.FreeAssemblyName (ref *nativeName, true);
}
}
}
}
}
public override Assembly GetSatelliteAssembly (CultureInfo culture)
{
return GetSatelliteAssembly (culture, null);
}
public override Assembly GetSatelliteAssembly (CultureInfo culture, Version version)
{
if (culture == null)
throw new ArgumentNullException (nameof (culture));
return InternalGetSatelliteAssembly (culture, version, true);
}
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
internal Assembly InternalGetSatelliteAssembly (CultureInfo culture, Version version, bool throwOnFileNotFound)
{
var aname = GetName ();
var an = new AssemblyName ();
if (version == null)
an.Version = aname.Version;
else
an.Version = version;
an.CultureInfo = culture;
an.Name = aname.Name + ".resources";
Assembly res = null;
try {
StackCrawlMark unused = default;
res = Assembly.Load (an, ref unused, null);
} catch {
}
if (res == this)
res = null;
if (res == null && throwOnFileNotFound)
throw new FileNotFoundException (String.Format (culture, SR.IO_FileNotFound_FileName, an.Name));
return res;
}
public override FileStream GetFile (string name)
{
if (name == null)
throw new ArgumentNullException (nameof (name), SR.ArgumentNull_FileName);
if (name.Length == 0)
throw new ArgumentException (SR.Argument_EmptyFileName);
string location = Location;
if (location != null && Path.GetFileName (location) == name)
return new FileStream (location, FileMode.Open, FileAccess.Read);
string filename = (string)GetFilesInternal (name, true);
if (filename != null)
return new FileStream (filename, FileMode.Open, FileAccess.Read);
else
return null;
}
public override FileStream[] GetFiles (bool getResourceModules)
{
string[] names = (string[]) GetFilesInternal (null, getResourceModules);
if (names == null)
return Array.Empty<FileStream> ();
string location = Location;
FileStream[] res;
if (location != String.Empty) {
res = new FileStream [names.Length + 1];
res [0] = new FileStream (location, FileMode.Open, FileAccess.Read);
for (int i = 0; i < names.Length; ++i)
res [i + 1] = new FileStream (names [i], FileMode.Open, FileAccess.Read);
} else {
res = new FileStream [names.Length];
for (int i = 0; i < names.Length; ++i)
res [i] = new FileStream (names [i], FileMode.Open, FileAccess.Read);
}
return res;
}
internal static RuntimeAssembly InternalLoadAssemblyName (AssemblyName assemblyRef, ref StackCrawlMark stackMark, AssemblyLoadContext assemblyLoadContext)
{
// TODO: Use assemblyLoadContext
return (RuntimeAssembly) InternalLoad (assemblyRef.FullName, ref stackMark, IntPtr.Zero);
}
public override Module LoadModule (string moduleName, byte[] rawModule, byte[] rawSymbolStore)
{
throw new NotImplementedException ();
}
internal override IntPtr MonoAssembly {
get {
return _mono_assembly;
}
}
// FIXME: Merge some of these
[MethodImplAttribute (MethodImplOptions.InternalCall)]
extern string get_location ();
[MethodImplAttribute (MethodImplOptions.InternalCall)]
extern static string get_code_base (Assembly a, bool escaped);
[MethodImplAttribute (MethodImplOptions.InternalCall)]
extern static string get_fullname (Assembly a);
[MethodImplAttribute (MethodImplOptions.InternalCall)]
extern static string InternalImageRuntimeVersion (Assembly a);
[MethodImplAttribute (MethodImplOptions.InternalCall)]
extern bool GetManifestResourceInfoInternal (string name, ManifestResourceInfo info);
[MethodImplAttribute (MethodImplOptions.InternalCall)]
extern IntPtr /* byte* */ GetManifestResourceInternal (string name, out int size, out Module module);
[MethodImplAttribute (MethodImplOptions.InternalCall)]
extern Module GetManifestModuleInternal ();
[MethodImplAttribute (MethodImplOptions.InternalCall)]
extern Module[] GetModulesInternal ();
[MethodImplAttribute (MethodImplOptions.InternalCall)]
static extern IntPtr InternalGetReferencedAssemblies (Assembly module);
[MethodImplAttribute (MethodImplOptions.InternalCall)]
private extern object GetFilesInternal (String name, bool getResourceModules);
}
}

View File

@@ -0,0 +1,196 @@
#nullable disable
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Reflection
{
internal struct MonoEventInfo
{
public Type declaring_type;
public Type reflected_type;
public String name;
public MethodInfo add_method;
public MethodInfo remove_method;
public MethodInfo raise_method;
public EventAttributes attrs;
public MethodInfo[] other_methods;
}
[StructLayout (LayoutKind.Sequential)]
internal sealed class RuntimeEventInfo : EventInfo
{
#pragma warning disable 169
IntPtr klass;
IntPtr handle;
#pragma warning restore 169
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static extern void get_event_info (RuntimeEventInfo ev, out MonoEventInfo info);
internal static MonoEventInfo GetEventInfo (RuntimeEventInfo ev)
{
MonoEventInfo mei;
get_event_info (ev, out mei);
return mei;
}
public override Module Module {
get {
return GetRuntimeModule ();
}
}
internal BindingFlags BindingFlags {
get {
return GetBindingFlags ();
}
}
internal RuntimeType GetDeclaringTypeInternal ()
{
return (RuntimeType) DeclaringType;
}
RuntimeType ReflectedTypeInternal {
get {
return (RuntimeType) ReflectedType;
}
}
internal RuntimeModule GetRuntimeModule ()
{
return GetDeclaringTypeInternal ().GetRuntimeModule ();
}
internal BindingFlags GetBindingFlags ()
{
MonoEventInfo info = GetEventInfo (this);
MethodInfo method = info.add_method;
if (method == null)
method = info.remove_method;
if (method == null)
method = info.raise_method;
return RuntimeType.FilterPreCalculate (method != null && method.IsPublic, GetDeclaringTypeInternal () != ReflectedType , method != null && method.IsStatic);
}
public override EventAttributes Attributes {
get {
return GetEventInfo (this).attrs;
}
}
public override MethodInfo GetAddMethod (bool nonPublic)
{
MonoEventInfo info = GetEventInfo (this);
if (nonPublic || (info.add_method != null && info.add_method.IsPublic))
return info.add_method;
return null;
}
public override MethodInfo GetRaiseMethod (bool nonPublic)
{
MonoEventInfo info = GetEventInfo (this);
if (nonPublic || (info.raise_method != null && info.raise_method.IsPublic))
return info.raise_method;
return null;
}
public override MethodInfo GetRemoveMethod (bool nonPublic)
{
MonoEventInfo info = GetEventInfo (this);
if (nonPublic || (info.remove_method != null && info.remove_method.IsPublic))
return info.remove_method;
return null;
}
public override MethodInfo[] GetOtherMethods (bool nonPublic)
{
MonoEventInfo info = GetEventInfo (this);
if (nonPublic)
return info.other_methods;
int num_public = 0;
foreach (MethodInfo m in info.other_methods) {
if (m.IsPublic)
num_public++;
}
if (num_public == info.other_methods.Length)
return info.other_methods;
MethodInfo[] res = new MethodInfo [num_public];
num_public = 0;
foreach (MethodInfo m in info.other_methods) {
if (m.IsPublic)
res [num_public++] = m;
}
return res;
}
public override Type DeclaringType {
get {
return GetEventInfo (this).declaring_type;
}
}
public override Type ReflectedType {
get {
return GetEventInfo (this).reflected_type;
}
}
public override string Name {
get {
return GetEventInfo (this).name;
}
}
public override string ToString ()
{
return EventHandlerType + " " + Name;
}
public override bool IsDefined (Type attributeType, bool inherit)
{
return MonoCustomAttrs.IsDefined (this, attributeType, inherit);
}
public override object[] GetCustomAttributes( bool inherit)
{
return MonoCustomAttrs.GetCustomAttributes (this, inherit);
}
public override object[] GetCustomAttributes( Type attributeType, bool inherit)
{
return MonoCustomAttrs.GetCustomAttributes (this, attributeType, inherit);
}
public override IList<CustomAttributeData> GetCustomAttributesData () {
return CustomAttributeData.GetCustomAttributes (this);
}
public override int MetadataToken {
get {
return get_metadata_token (this);
}
}
public sealed override bool HasSameMetadataDefinitionAs (MemberInfo other) => HasSameMetadataDefinitionAsCore<RuntimeEventInfo> (other);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int get_metadata_token (RuntimeEventInfo monoEvent);
[MethodImplAttribute (MethodImplOptions.InternalCall)]
static extern EventInfo internal_from_handle_type (IntPtr event_handle, IntPtr type_handle);
internal static EventInfo GetEventFromHandle (Mono.RuntimeEventHandle handle, RuntimeTypeHandle reflectedType)
{
if (handle.Value == IntPtr.Zero)
throw new ArgumentException ("The handle is invalid.");
EventInfo ei = internal_from_handle_type (handle.Value, reflectedType.Value);
if (ei == null)
throw new ArgumentException ("The event handle and the type handle are incompatible.");
return ei;
}
}
}

View File

@@ -0,0 +1,27 @@
using System.Runtime.InteropServices;
namespace System.Reflection
{
[StructLayout (LayoutKind.Sequential)]
internal sealed class RuntimeExceptionHandlingClause : ExceptionHandlingClause
{
#region Keep in sync with MonoReflectionExceptionHandlingClause in object-internals.h
internal Type catch_type;
internal int filter_offset;
internal ExceptionHandlingClauseOptions flags;
internal int try_offset;
internal int try_length;
internal int handler_offset;
internal int handler_length;
#endregion
public override ExceptionHandlingClauseOptions Flags => flags;
public override int TryOffset => try_offset;
public override int TryLength => try_length;
public override int HandlerOffset => handler_offset;
public override int HandlerLength => handler_length;
public override int FilterOffset => filter_offset;
public override Type? CatchType => catch_type;
}
}

View File

@@ -0,0 +1,264 @@
#nullable disable
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace System.Reflection
{
abstract class RtFieldInfo : FieldInfo
{
internal abstract object UnsafeGetValue (object obj);
internal abstract void UnsafeSetValue (Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture);
internal abstract void CheckConsistency(Object target);
}
[StructLayout (LayoutKind.Sequential)]
class RuntimeFieldInfo : RtFieldInfo
{
#pragma warning disable 649
internal IntPtr klass;
internal RuntimeFieldHandle fhandle;
string name;
Type type;
FieldAttributes attrs;
#pragma warning restore 649
internal BindingFlags BindingFlags {
get {
return 0;
}
}
public override Module Module {
get {
return GetRuntimeModule ();
}
}
internal RuntimeType GetDeclaringTypeInternal ()
{
return (RuntimeType) DeclaringType;
}
RuntimeType ReflectedTypeInternal {
get {
return (RuntimeType) ReflectedType;
}
}
internal RuntimeModule GetRuntimeModule ()
{
return GetDeclaringTypeInternal ().GetRuntimeModule ();
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal override extern object UnsafeGetValue (object obj);
internal override void CheckConsistency(Object target)
{
// only test instance fields
if ((Attributes & FieldAttributes.Static) != FieldAttributes.Static)
{
if (!DeclaringType.IsInstanceOfType(target))
{
if (target == null)
{
throw new TargetException(Environment.GetResourceString("RFLCT.Targ_StatFldReqTarg"));
}
else
{
throw new ArgumentException(
String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Arg_FieldDeclTarget"),
Name, DeclaringType, target.GetType()));
}
}
}
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
internal override void UnsafeSetValue (Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture)
{
bool domainInitialized = false;
RuntimeFieldHandle.SetValue (this, obj, value, null, Attributes, null, ref domainInitialized);
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override void SetValueDirect(TypedReference obj, Object value)
{
if (obj.IsNull)
throw new ArgumentException(Environment.GetResourceString("Arg_TypedReference_Null"));
unsafe
{
// Passing TypedReference by reference is easier to make correct in native code
RuntimeFieldHandle.SetValueDirect(this, (RuntimeType)FieldType, &obj, value, (RuntimeType)DeclaringType);
}
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override Object GetValueDirect(TypedReference obj)
{
if (obj.IsNull)
throw new ArgumentException(Environment.GetResourceString("Arg_TypedReference_Null"));
unsafe
{
// Passing TypedReference by reference is easier to make correct in native code
return RuntimeFieldHandle.GetValueDirect(this, (RuntimeType)FieldType, &obj, (RuntimeType)DeclaringType);
}
}
public override FieldAttributes Attributes {
get {
return attrs;
}
}
public override RuntimeFieldHandle FieldHandle {
get {
return fhandle;
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern Type ResolveType ();
public override Type FieldType {
get {
if (type == null)
type = ResolveType ();
return type;
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern Type GetParentType (bool declaring);
public override Type ReflectedType {
get {
return GetParentType (false);
}
}
public override Type DeclaringType {
get {
return GetParentType (true);
}
}
public override string Name {
get {
return name;
}
}
public override bool IsDefined (Type attributeType, bool inherit) {
return MonoCustomAttrs.IsDefined (this, attributeType, inherit);
}
public override object[] GetCustomAttributes( bool inherit) {
return MonoCustomAttrs.GetCustomAttributes (this, inherit);
}
public override object[] GetCustomAttributes( Type attributeType, bool inherit) {
return MonoCustomAttrs.GetCustomAttributes (this, attributeType, inherit);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal override extern int GetFieldOffset ();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern object GetValueInternal (object obj);
public override object GetValue (object obj)
{
if (!IsStatic) {
if (obj == null)
throw new TargetException ("Non-static field requires a target");
if (!DeclaringType.IsAssignableFrom (obj.GetType ()))
throw new ArgumentException (string.Format (
"Field {0} defined on type {1} is not a field on the target object which is of type {2}.",
Name, DeclaringType, obj.GetType ()),
"obj");
}
if (!IsLiteral)
CheckGeneric ();
return GetValueInternal (obj);
}
public override string ToString () {
return String.Format ("{0} {1}", FieldType, name);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void SetValueInternal (FieldInfo fi, object obj, object value);
public override void SetValue (object obj, object val, BindingFlags invokeAttr, Binder binder, CultureInfo culture)
{
if (!IsStatic) {
if (obj == null)
throw new TargetException ("Non-static field requires a target");
if (!DeclaringType.IsAssignableFrom (obj.GetType ()))
throw new ArgumentException (string.Format (
"Field {0} defined on type {1} is not a field on the target object which is of type {2}.",
Name, DeclaringType, obj.GetType ()),
"obj");
}
if (IsLiteral)
throw new FieldAccessException ("Cannot set a constant field");
if (binder == null)
binder = Type.DefaultBinder;
CheckGeneric ();
if (val != null) {
RuntimeType fieldType = (RuntimeType) FieldType;
val = fieldType.CheckValue (val, binder, culture, invokeAttr);
}
SetValueInternal (this, obj, val);
}
internal RuntimeFieldInfo Clone (string newName)
{
RuntimeFieldInfo field = new RuntimeFieldInfo ();
field.name = newName;
field.type = type;
field.attrs = attrs;
field.klass = klass;
field.fhandle = fhandle;
return field;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public override extern object GetRawConstantValue ();
public override IList<CustomAttributeData> GetCustomAttributesData () {
return CustomAttributeData.GetCustomAttributes (this);
}
void CheckGeneric () {
if (DeclaringType.ContainsGenericParameters)
throw new InvalidOperationException ("Late bound operations cannot be performed on fields with types for which Type.ContainsGenericParameters is true.");
}
public sealed override bool HasSameMetadataDefinitionAs (MemberInfo other) => HasSameMetadataDefinitionAsCore<RuntimeFieldInfo> (other);
public override int MetadataToken {
get {
return get_metadata_token (this);
}
}
[MethodImplAttribute (MethodImplOptions.InternalCall)]
internal static extern int get_metadata_token (RuntimeFieldInfo monoField);
[MethodImplAttribute (MethodImplOptions.InternalCall)]
extern Type[] GetTypeModifiers (bool optional);
public override Type[] GetOptionalCustomModifiers () => GetCustomModifiers (true);
public override Type[] GetRequiredCustomModifiers () => GetCustomModifiers (false);
private Type[] GetCustomModifiers (bool optional) => GetTypeModifiers (optional) ?? Type.EmptyTypes;
}
}

View File

@@ -0,0 +1,22 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Reflection {
[StructLayout (LayoutKind.Sequential)]
internal sealed class RuntimeLocalVariableInfo : LocalVariableInfo {
#region Keep in sync with MonoReflectionLocalVariableInfo in object-internals.h
internal Type type;
internal bool is_pinned;
internal ushort position;
#endregion
public override bool IsPinned => is_pinned;
public override int LocalIndex => position;
public override Type LocalType => type;
}
}

View File

@@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Reflection {
internal sealed class RuntimeMethodBody : MethodBody
{
ExceptionHandlingClause[] clauses;
LocalVariableInfo[] locals;
byte[] il;
bool init_locals;
int sig_token;
int max_stack;
// Called by the runtime
internal RuntimeMethodBody (ExceptionHandlingClause[] clauses, LocalVariableInfo[] locals,
byte[] il, bool init_locals, int sig_token, int max_stack)
{
this.clauses = clauses;
this.locals = locals;
this.il = il;
this.init_locals = init_locals;
this.sig_token = sig_token;
this.max_stack = max_stack;
}
public override int LocalSignatureMetadataToken => sig_token;
public override IList<LocalVariableInfo> LocalVariables => Array.AsReadOnly (locals);
public override int MaxStackSize => max_stack;
public override bool InitLocals => init_locals;
public override byte[] GetILAsByteArray() => il;
public override IList<ExceptionHandlingClause> ExceptionHandlingClauses => Array.AsReadOnly (clauses);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,368 @@
#nullable disable
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
namespace System.Reflection {
[StructLayout (LayoutKind.Sequential)]
class RuntimeModule : Module
{
#pragma warning disable 649
#region Sync with object-internals.h
#region Sync with ModuleBuilder
internal IntPtr _impl; /* a pointer to a MonoImage */
internal Assembly assembly;
internal string fqname;
internal string name;
internal string scopename;
internal bool is_resource;
internal int token;
#endregion
#endregion
#pragma warning restore 649
public
override
Assembly Assembly {
get { return assembly; }
}
public
override
// Note: we do not ask for PathDiscovery because no path is returned here.
// However MS Fx requires it (see FDBK23572 for details).
string Name {
get { return name; }
}
public
override
string ScopeName {
get { return scopename; }
}
public
override
int MDStreamVersion {
get {
if (_impl == IntPtr.Zero)
throw new NotSupportedException ();
return GetMDStreamVersion (_impl);
}
}
public
override
Guid ModuleVersionId {
get {
return GetModuleVersionId ();
}
}
public override
string FullyQualifiedName {
get {
return fqname;
}
}
public
override
bool IsResource()
{
return is_resource;
}
public override
Type[] FindTypes(TypeFilter filter, object filterCriteria)
{
var filtered = new List<Type> ();
Type[] types = GetTypes ();
foreach (Type t in types)
if (filter (t, filterCriteria))
filtered.Add (t);
return filtered.ToArray ();
}
public override
object[] GetCustomAttributes(bool inherit)
{
return MonoCustomAttrs.GetCustomAttributes (this, inherit);
}
public override
object[] GetCustomAttributes(Type attributeType, bool inherit)
{
return MonoCustomAttrs.GetCustomAttributes (this, attributeType, inherit);
}
public override
FieldInfo GetField (string name, BindingFlags bindingAttr)
{
if (name == null)
throw new ArgumentNullException("name");
if (IsResource ())
return null;
Type globalType = GetGlobalType (_impl);
return (globalType != null) ? globalType.GetField (name, bindingAttr) : null;
}
public override
FieldInfo[] GetFields (BindingFlags bindingFlags)
{
if (IsResource ())
return new FieldInfo [0];
Type globalType = GetGlobalType (_impl);
return (globalType != null) ? globalType.GetFields (bindingFlags) : new FieldInfo [0];
}
public override
int MetadataToken {
get {
return get_MetadataToken (this);
}
}
protected
override
MethodInfo GetMethodImpl (string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
{
if (IsResource ())
return null;
Type globalType = GetGlobalType (_impl);
if (globalType == null)
return null;
if (types == null)
return globalType.GetMethod (name);
return globalType.GetMethod (name, bindingAttr, binder, callConvention, types, modifiers);
}
public
override
MethodInfo[] GetMethods (BindingFlags bindingFlags) {
if (IsResource ())
return new MethodInfo [0];
Type globalType = GetGlobalType (_impl);
return (globalType != null) ? globalType.GetMethods (bindingFlags) : new MethodInfo [0];
}
public override
void GetPEKind (out PortableExecutableKinds peKind, out ImageFileMachine machine) {
RuntimeModule.GetPEKind (_impl, out peKind, out machine);
}
public override
Type GetType(string className, bool throwOnError, bool ignoreCase)
{
if (className == null)
throw new ArgumentNullException ("className");
if (className == String.Empty)
throw new ArgumentException ("Type name can't be empty");
return assembly.InternalGetType (this, className, throwOnError, ignoreCase);
}
public override
bool IsDefined (Type attributeType, bool inherit)
{
return MonoCustomAttrs.IsDefined (this, attributeType, inherit);
}
public
override
FieldInfo ResolveField (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
return ResolveField (this, _impl, metadataToken, genericTypeArguments, genericMethodArguments);
}
internal static FieldInfo ResolveField (Module module, IntPtr monoModule, int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
ResolveTokenError error;
IntPtr handle = ResolveFieldToken (monoModule, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
if (handle == IntPtr.Zero)
throw resolve_token_exception (module.Name, metadataToken, error, "Field");
else
return FieldInfo.GetFieldFromHandle (new RuntimeFieldHandle (handle));
}
public
override
MemberInfo ResolveMember (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
return ResolveMember (this, _impl, metadataToken, genericTypeArguments, genericMethodArguments);
}
internal static MemberInfo ResolveMember (Module module, IntPtr monoModule, int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
ResolveTokenError error;
MemberInfo m = ResolveMemberToken (monoModule, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
if (m == null)
throw resolve_token_exception (module.Name, metadataToken, error, "MemberInfo");
else
return m;
}
public
override
MethodBase ResolveMethod (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
return ResolveMethod (this, _impl, metadataToken, genericTypeArguments, genericMethodArguments);
}
internal static MethodBase ResolveMethod (Module module, IntPtr monoModule, int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
ResolveTokenError error;
IntPtr handle = ResolveMethodToken (monoModule, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
if (handle == IntPtr.Zero)
throw resolve_token_exception (module.Name, metadataToken, error, "MethodBase");
else
return RuntimeMethodInfo.GetMethodFromHandleNoGenericCheck (new RuntimeMethodHandle (handle));
}
public
override
string ResolveString (int metadataToken) {
return ResolveString (this, _impl, metadataToken);
}
internal static string ResolveString (Module module, IntPtr monoModule, int metadataToken) {
ResolveTokenError error;
string s = ResolveStringToken (monoModule, metadataToken, out error);
if (s == null)
throw resolve_token_exception (module.Name, metadataToken, error, "string");
else
return s;
}
public
override
Type ResolveType (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
return ResolveType (this, _impl, metadataToken, genericTypeArguments, genericMethodArguments);
}
internal static Type ResolveType (Module module, IntPtr monoModule, int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
ResolveTokenError error;
IntPtr handle = ResolveTypeToken (monoModule, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
if (handle == IntPtr.Zero)
throw resolve_token_exception (module.Name, metadataToken, error, "Type");
else
return Type.GetTypeFromHandle (new RuntimeTypeHandle (handle));
}
public
override
byte[] ResolveSignature (int metadataToken) {
return ResolveSignature (this, _impl, metadataToken);
}
internal static byte[] ResolveSignature (Module module, IntPtr monoModule, int metadataToken) {
ResolveTokenError error;
byte[] res = ResolveSignature (monoModule, metadataToken, out error);
if (res == null)
throw resolve_token_exception (module.Name, metadataToken, error, "signature");
else
return res;
}
public override
Type[] GetTypes()
{
return InternalGetTypes (_impl);
}
public override IList<CustomAttributeData> GetCustomAttributesData () {
return CustomAttributeData.GetCustomAttributes (this);
}
internal RuntimeAssembly GetRuntimeAssembly ()
{
return (RuntimeAssembly)assembly;
}
internal IntPtr MonoModule {
get {
return _impl;
}
}
internal Guid GetModuleVersionId ()
{
var guid = new byte [16];
GetGuidInternal (_impl, guid);
return new Guid (guid);
}
internal static Exception resolve_token_exception (string name, int metadataToken, ResolveTokenError error, string tokenType) {
if (error == ResolveTokenError.OutOfRange)
return new ArgumentOutOfRangeException ("metadataToken", String.Format ("Token 0x{0:x} is not valid in the scope of module {1}", metadataToken, name));
else
return new ArgumentException (String.Format ("Token 0x{0:x} is not a valid {1} token in the scope of module {2}", metadataToken, tokenType, name), "metadataToken");
}
internal static IntPtr[] ptrs_from_types (Type[] types) {
if (types == null)
return null;
else {
IntPtr[] res = new IntPtr [types.Length];
for (int i = 0; i < types.Length; ++i) {
if (types [i] == null)
throw new ArgumentException ();
res [i] = types [i].TypeHandle.Value;
}
return res;
}
}
// This calls ves_icall_reflection_get_token, so needs a Module argument
[MethodImplAttribute (MethodImplOptions.InternalCall)]
internal static extern int get_MetadataToken (Module module);
[MethodImplAttribute (MethodImplOptions.InternalCall)]
internal static extern int GetMDStreamVersion (IntPtr module);
[MethodImplAttribute (MethodImplOptions.InternalCall)]
internal static extern Type[] InternalGetTypes (IntPtr module);
[MethodImplAttribute (MethodImplOptions.InternalCall)]
internal static extern IntPtr GetHINSTANCE (IntPtr module);
[MethodImplAttribute (MethodImplOptions.InternalCall)]
private static extern void GetGuidInternal (IntPtr module, byte[] guid);
[MethodImplAttribute (MethodImplOptions.InternalCall)]
internal static extern Type GetGlobalType (IntPtr module);
[MethodImplAttribute (MethodImplOptions.InternalCall)]
internal static extern IntPtr ResolveTypeToken (IntPtr module, int token, IntPtr[] type_args, IntPtr[] method_args, out ResolveTokenError error);
[MethodImplAttribute (MethodImplOptions.InternalCall)]
internal static extern IntPtr ResolveMethodToken (IntPtr module, int token, IntPtr[] type_args, IntPtr[] method_args, out ResolveTokenError error);
[MethodImplAttribute (MethodImplOptions.InternalCall)]
internal static extern IntPtr ResolveFieldToken (IntPtr module, int token, IntPtr[] type_args, IntPtr[] method_args, out ResolveTokenError error);
[MethodImplAttribute (MethodImplOptions.InternalCall)]
internal static extern string ResolveStringToken (IntPtr module, int token, out ResolveTokenError error);
[MethodImplAttribute (MethodImplOptions.InternalCall)]
internal static extern MemberInfo ResolveMemberToken (IntPtr module, int token, IntPtr[] type_args, IntPtr[] method_args, out ResolveTokenError error);
[MethodImplAttribute (MethodImplOptions.InternalCall)]
internal static extern byte[] ResolveSignature (IntPtr module, int metadataToken, out ResolveTokenError error);
[MethodImplAttribute (MethodImplOptions.InternalCall)]
internal static extern void GetPEKind (IntPtr module, out PortableExecutableKinds peKind, out ImageFileMachine machine);
}
internal enum ResolveTokenError {
OutOfRange,
BadTable,
Other
}
}

View File

@@ -0,0 +1,290 @@
#nullable disable
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Text;
namespace System.Reflection
{
class RuntimeParameterInfo : ParameterInfo
{
internal MarshalAsAttribute marshalAs;
// Called by the runtime
internal RuntimeParameterInfo (string name, Type type, int position, int attrs, object defaultValue, MemberInfo member, MarshalAsAttribute marshalAs) {
NameImpl = name;
ClassImpl = type;
PositionImpl = position;
AttrsImpl = (ParameterAttributes)attrs;
DefaultValueImpl = defaultValue;
MemberImpl = member;
this.marshalAs = marshalAs;
}
internal static void FormatParameters (StringBuilder sb, ParameterInfo[] p, CallingConventions callingConvention, bool serialization)
{
for (int i = 0; i < p.Length; ++i) {
if (i > 0)
sb.Append (", ");
Type t = p[i].ParameterType;
string typeName = t.FormatTypeName (serialization);
// Legacy: Why use "ByRef" for by ref parameters? What language is this?
// VB uses "ByRef" but it should precede (not follow) the parameter name.
// Why don't we just use "&"?
if (t.IsByRef && !serialization) {
sb.Append (typeName.TrimEnd (new char[] { '&' }));
sb.Append (" ByRef");
} else {
sb.Append (typeName);
}
}
if ((callingConvention & CallingConventions.VarArgs) != 0) {
if (p.Length > 0)
sb.Append (", ");
sb.Append ("...");
}
}
internal RuntimeParameterInfo (ParameterBuilder pb, Type type, MemberInfo member, int position) {
this.ClassImpl = type;
this.MemberImpl = member;
if (pb != null) {
this.NameImpl = pb.Name;
this.PositionImpl = pb.Position - 1; // ParameterInfo.Position is zero-based
this.AttrsImpl = (ParameterAttributes) pb.Attributes;
} else {
this.NameImpl = null;
this.PositionImpl = position - 1;
this.AttrsImpl = ParameterAttributes.None;
}
}
internal static ParameterInfo New (ParameterBuilder pb, Type type, MemberInfo member, int position)
{
return new RuntimeParameterInfo (pb, type, member, position);
}
/*FIXME this constructor looks very broken in the position parameter*/
internal RuntimeParameterInfo (ParameterInfo pinfo, Type type, MemberInfo member, int position) {
this.ClassImpl = type;
this.MemberImpl = member;
if (pinfo != null) {
this.NameImpl = pinfo.Name;
this.PositionImpl = pinfo.Position - 1; // ParameterInfo.Position is zero-based
this.AttrsImpl = (ParameterAttributes) pinfo.Attributes;
} else {
this.NameImpl = null;
this.PositionImpl = position - 1;
this.AttrsImpl = ParameterAttributes.None;
}
}
internal RuntimeParameterInfo (ParameterInfo pinfo, MemberInfo member) {
this.ClassImpl = pinfo.ParameterType;
this.MemberImpl = member;
this.NameImpl = pinfo.Name;
this.PositionImpl = pinfo.Position;
this.AttrsImpl = pinfo.Attributes;
this.DefaultValueImpl = GetDefaultValueImpl (pinfo);
}
/* to build a ParameterInfo for the return type of a method */
internal RuntimeParameterInfo (Type type, MemberInfo member, MarshalAsAttribute marshalAs) {
this.ClassImpl = type;
this.MemberImpl = member;
this.NameImpl = null;
this.PositionImpl = -1; // since parameter positions are zero-based, return type pos is -1
this.AttrsImpl = ParameterAttributes.Retval;
this.marshalAs = marshalAs;
}
public override
object DefaultValue {
get {
if (ClassImpl == typeof (Decimal) || ClassImpl == typeof (Decimal?)) {
/* default values for decimals are encoded using a custom attribute */
DecimalConstantAttribute[] attrs = (DecimalConstantAttribute[])GetCustomAttributes (typeof (DecimalConstantAttribute), false);
if (attrs.Length > 0)
return attrs [0].Value;
} else if (ClassImpl == typeof (DateTime) || ClassImpl == typeof (DateTime?)) {
/* default values for DateTime are encoded using a custom attribute */
DateTimeConstantAttribute[] attrs = (DateTimeConstantAttribute[])GetCustomAttributes (typeof (DateTimeConstantAttribute), false);
if (attrs.Length > 0)
return attrs [0].Value;
}
return DefaultValueImpl;
}
}
public override
object RawDefaultValue {
get {
if (DefaultValue != null && DefaultValue.GetType ().IsEnum)
return ((Enum)DefaultValue).GetValue ();
/*FIXME right now DefaultValue doesn't throw for reflection-only assemblies. Change this once the former is fixed.*/
return DefaultValue;
}
}
public
override
int MetadataToken {
get {
if (MemberImpl is PropertyInfo) {
PropertyInfo prop = (PropertyInfo)MemberImpl;
MethodInfo mi = prop.GetGetMethod (true);
if (mi == null)
mi = prop.GetSetMethod (true);
return mi.GetParametersInternal () [PositionImpl].MetadataToken;
} else if (MemberImpl is MethodBase) {
return GetMetadataToken ();
}
throw new ArgumentException ("Can't produce MetadataToken for member of type " + MemberImpl.GetType ());
}
}
public
override
object[] GetCustomAttributes (bool inherit)
{
return MonoCustomAttrs.GetCustomAttributes (this, inherit);
}
public
override
object[] GetCustomAttributes (Type attributeType, bool inherit)
{
return MonoCustomAttrs.GetCustomAttributes (this, attributeType, inherit);
}
internal object GetDefaultValueImpl (ParameterInfo pinfo)
{
FieldInfo field = typeof (ParameterInfo).GetField ("DefaultValueImpl", BindingFlags.Instance | BindingFlags.NonPublic);
return field.GetValue (pinfo);
}
public
override
bool IsDefined( Type attributeType, bool inherit) {
return MonoCustomAttrs.IsDefined (this, attributeType, inherit);
}
public override IList<CustomAttributeData> GetCustomAttributesData () {
return CustomAttributeData.GetCustomAttributes (this);
}
[MethodImplAttribute (MethodImplOptions.InternalCall)]
internal extern int GetMetadataToken ();
public override Type[] GetOptionalCustomModifiers () => GetCustomModifiers (true);
internal object[] GetPseudoCustomAttributes ()
{
int count = 0;
if (IsIn)
count ++;
if (IsOut)
count ++;
if (IsOptional)
count ++;
if (marshalAs != null)
count ++;
if (count == 0)
return null;
object[] attrs = new object [count];
count = 0;
if (IsIn)
attrs [count ++] = new InAttribute ();
if (IsOut)
attrs [count ++] = new OutAttribute ();
if (IsOptional)
attrs [count ++] = new OptionalAttribute ();
if (marshalAs != null) {
attrs [count ++] = (MarshalAsAttribute)marshalAs.CloneInternal ();
}
return attrs;
}
internal CustomAttributeData[] GetPseudoCustomAttributesData ()
{
int count = 0;
if (IsIn)
count++;
if (IsOut)
count++;
if (IsOptional)
count++;
if (marshalAs != null)
count++;
if (count == 0)
return null;
CustomAttributeData[] attrsData = new CustomAttributeData [count];
count = 0;
if (IsIn)
attrsData [count++] = new CustomAttributeData ((typeof (InAttribute)).GetConstructor (Type.EmptyTypes));
if (IsOut)
attrsData [count++] = new CustomAttributeData ((typeof (OutAttribute)).GetConstructor (Type.EmptyTypes));
if (IsOptional)
attrsData [count++] = new CustomAttributeData ((typeof (OptionalAttribute)).GetConstructor (Type.EmptyTypes));
if (marshalAs != null) {
var ctorArgs = new CustomAttributeTypedArgument[] { new CustomAttributeTypedArgument (typeof (UnmanagedType), marshalAs.Value) };
attrsData [count++] = new CustomAttributeData (
(typeof (MarshalAsAttribute)).GetConstructor (new[] { typeof (UnmanagedType) }),
ctorArgs,
Array.Empty<CustomAttributeNamedArgument> ());//FIXME Get named params
}
return attrsData;
}
public override Type[] GetRequiredCustomModifiers () => GetCustomModifiers (false);
public override bool HasDefaultValue {
get {
object defaultValue = DefaultValue;
if (defaultValue == null)
return true;
if (defaultValue.GetType () == typeof(DBNull) || defaultValue.GetType () == typeof(Missing))
return false;
return true;
}
}
[MethodImplAttribute (MethodImplOptions.InternalCall)]
internal static extern Type[] GetTypeModifiers (Type type, MemberInfo member, int position, bool optional);
internal static ParameterInfo New (ParameterInfo pinfo, Type type, MemberInfo member, int position)
{
return new RuntimeParameterInfo (pinfo, type, member, position);
}
internal static ParameterInfo New (ParameterInfo pinfo, MemberInfo member)
{
return new RuntimeParameterInfo (pinfo, member);
}
internal static ParameterInfo New (Type type, MemberInfo member, MarshalAsAttribute marshalAs)
{
return new RuntimeParameterInfo (type, member, marshalAs);
}
private Type[] GetCustomModifiers (bool optional) => GetTypeModifiers (ParameterType, Member, Position, optional) ?? Type.EmptyTypes;
}
}

View File

@@ -0,0 +1,434 @@
#nullable disable
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using Mono;
namespace System.Reflection
{
internal struct MonoPropertyInfo {
public Type parent;
public Type declaring_type;
public String name;
public MethodInfo get_method;
public MethodInfo set_method;
public PropertyAttributes attrs;
}
[Flags]
internal enum PInfo {
Attributes = 1,
GetMethod = 1 << 1,
SetMethod = 1 << 2,
ReflectedType = 1 << 3,
DeclaringType = 1 << 4,
Name = 1 << 5
}
internal delegate object GetterAdapter (object _this);
internal delegate R Getter<T,R> (T _this);
[StructLayout (LayoutKind.Sequential)]
internal class RuntimePropertyInfo : PropertyInfo
{
#pragma warning disable 649
internal IntPtr klass;
internal IntPtr prop;
MonoPropertyInfo info;
PInfo cached;
GetterAdapter cached_getter;
#pragma warning restore 649
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void get_property_info (RuntimePropertyInfo prop, ref MonoPropertyInfo info,
PInfo req_info);
[MethodImplAttribute (MethodImplOptions.InternalCall)]
internal static extern Type[] GetTypeModifiers (RuntimePropertyInfo prop, bool optional);
[MethodImplAttribute (MethodImplOptions.InternalCall)]
internal static extern object get_default_value (RuntimePropertyInfo prop);
internal BindingFlags BindingFlags {
get {
CachePropertyInfo (PInfo.GetMethod | PInfo.SetMethod);
bool isPublic = info.set_method?.IsPublic == true || info.get_method?.IsPublic == true;
bool isStatic = info.set_method?.IsStatic == true || info.get_method?.IsStatic == true;
bool isInherited = DeclaringType != ReflectedType;
return FilterPreCalculate (isPublic, isInherited, isStatic);
}
}
// Copied from https://github.com/dotnet/coreclr/blob/7a24a538cd265993e5864179f51781398c28ecdf/src/System.Private.CoreLib/src/System/RtType.cs#L2022
static BindingFlags FilterPreCalculate (bool isPublic, bool isInherited, bool isStatic)
{
BindingFlags bindingFlags = isPublic ? BindingFlags.Public : BindingFlags.NonPublic;
if (isInherited) {
// We arrange things so the DeclaredOnly flag means "include inherited members"
bindingFlags |= BindingFlags.DeclaredOnly;
if (isStatic)
bindingFlags |= BindingFlags.Static | BindingFlags.FlattenHierarchy;
else
bindingFlags |= BindingFlags.Instance;
}
else {
if (isStatic)
bindingFlags |= BindingFlags.Static;
else
bindingFlags |= BindingFlags.Instance;
}
return bindingFlags;
}
public override Module Module {
get {
return GetRuntimeModule ();
}
}
internal RuntimeType GetDeclaringTypeInternal ()
{
return (RuntimeType) DeclaringType;
}
RuntimeType ReflectedTypeInternal {
get {
return (RuntimeType) ReflectedType;
}
}
internal RuntimeModule GetRuntimeModule ()
{
return GetDeclaringTypeInternal ().GetRuntimeModule ();
}
#region Object Overrides
public override String ToString()
{
return FormatNameAndSig(false);
}
private string FormatNameAndSig(bool serialization)
{
StringBuilder sbName = new StringBuilder(PropertyType.FormatTypeName(serialization));
sbName.Append(" ");
sbName.Append(Name);
var pi = GetIndexParameters ();
if (pi.Length > 0) {
sbName.Append (" [");
RuntimeParameterInfo.FormatParameters (sbName, pi, 0, serialization);
sbName.Append ("]");
}
return sbName.ToString();
}
#endregion
void CachePropertyInfo (PInfo flags)
{
if ((cached & flags) != flags) {
get_property_info (this, ref info, flags);
cached |= flags;
}
}
public override PropertyAttributes Attributes {
get {
CachePropertyInfo (PInfo.Attributes);
return info.attrs;
}
}
public override bool CanRead {
get {
CachePropertyInfo (PInfo.GetMethod);
return (info.get_method != null);
}
}
public override bool CanWrite {
get {
CachePropertyInfo (PInfo.SetMethod);
return (info.set_method != null);
}
}
public override Type PropertyType {
get {
CachePropertyInfo (PInfo.GetMethod | PInfo.SetMethod);
if (info.get_method != null) {
return info.get_method.ReturnType;
} else {
ParameterInfo[] parameters = info.set_method.GetParametersInternal ();
return parameters [parameters.Length - 1].ParameterType;
}
}
}
public override Type ReflectedType {
get {
CachePropertyInfo (PInfo.ReflectedType);
return info.parent;
}
}
public override Type DeclaringType {
get {
CachePropertyInfo (PInfo.DeclaringType);
return info.declaring_type;
}
}
public override string Name {
get {
CachePropertyInfo (PInfo.Name);
return info.name;
}
}
public override MethodInfo[] GetAccessors (bool nonPublic)
{
int nget = 0;
int nset = 0;
CachePropertyInfo (PInfo.GetMethod | PInfo.SetMethod);
if (info.set_method != null && (nonPublic || info.set_method.IsPublic))
nset = 1;
if (info.get_method != null && (nonPublic || info.get_method.IsPublic))
nget = 1;
MethodInfo[] res = new MethodInfo [nget + nset];
int n = 0;
if (nset != 0)
res [n++] = info.set_method;
if (nget != 0)
res [n++] = info.get_method;
return res;
}
public override MethodInfo GetGetMethod (bool nonPublic)
{
CachePropertyInfo (PInfo.GetMethod);
if (info.get_method != null && (nonPublic || info.get_method.IsPublic))
return info.get_method;
else
return null;
}
public override ParameterInfo[] GetIndexParameters ()
{
CachePropertyInfo (PInfo.GetMethod | PInfo.SetMethod);
ParameterInfo[] src;
int length;
if (info.get_method != null) {
src = info.get_method.GetParametersInternal ();
length = src.Length;
} else if (info.set_method != null) {
src = info.set_method.GetParametersInternal ();
length = src.Length - 1;
} else
return Array.Empty<ParameterInfo> ();
var dest = new ParameterInfo [length];
for (int i = 0; i < length; ++i) {
dest [i] = RuntimeParameterInfo.New (src [i], this);
}
return dest;
}
public override MethodInfo GetSetMethod (bool nonPublic)
{
CachePropertyInfo (PInfo.SetMethod);
if (info.set_method != null && (nonPublic || info.set_method.IsPublic))
return info.set_method;
else
return null;
}
/*TODO verify for attribute based default values, just like ParameterInfo*/
public override object GetConstantValue ()
{
return get_default_value (this);
}
public override object GetRawConstantValue() {
return get_default_value (this);
}
// According to MSDN the inherit parameter is ignored here and
// the behavior always defaults to inherit = false
//
public override bool IsDefined (Type attributeType, bool inherit)
{
return MonoCustomAttrs.IsDefined (this, attributeType, false);
}
public override object[] GetCustomAttributes (bool inherit)
{
return MonoCustomAttrs.GetCustomAttributes (this, false);
}
public override object[] GetCustomAttributes (Type attributeType, bool inherit)
{
return MonoCustomAttrs.GetCustomAttributes (this, attributeType, false);
}
delegate object GetterAdapter (object _this);
delegate R Getter<T,R> (T _this);
delegate R StaticGetter<R> ();
#pragma warning disable 169
// Used via reflection
static object GetterAdapterFrame<T,R> (Getter<T,R> getter, object obj)
{
return getter ((T)obj);
}
static object StaticGetterAdapterFrame<R> (StaticGetter<R> getter, object obj)
{
return getter ();
}
#pragma warning restore 169
/*
* The idea behing this optimization is to use a pair of delegates to simulate the same effect of doing a reflection call.
* The first delegate cast the this argument to the right type and the second does points to the target method.
*/
static GetterAdapter CreateGetterDelegate (MethodInfo method)
{
Type[] typeVector;
Type getterType;
object getterDelegate;
MethodInfo adapterFrame;
Type getterDelegateType;
string frameName;
if (method.IsStatic) {
typeVector = new Type[] { method.ReturnType };
getterDelegateType = typeof (StaticGetter<>);
frameName = "StaticGetterAdapterFrame";
} else {
typeVector = new Type[] { method.DeclaringType, method.ReturnType };
getterDelegateType = typeof (Getter<,>);
frameName = "GetterAdapterFrame";
}
getterType = getterDelegateType.MakeGenericType (typeVector);
getterDelegate = Delegate.CreateDelegate (getterType, method);
adapterFrame = typeof (RuntimePropertyInfo).GetMethod (frameName, BindingFlags.Static | BindingFlags.NonPublic);
adapterFrame = adapterFrame.MakeGenericMethod (typeVector);
return (GetterAdapter)Delegate.CreateDelegate (typeof (GetterAdapter), getterDelegate, adapterFrame, true);
}
public override object GetValue (object obj, object[] index)
{
if (index == null || index.Length == 0) {
/*FIXME we should check if the number of arguments matches the expected one, otherwise the error message will be pretty criptic.*/
#if !FULL_AOT_RUNTIME
if (cached_getter == null) {
MethodInfo method = GetGetMethod (true);
if (method == null)
throw new ArgumentException ($"Get Method not found for '{Name}'");
if (!DeclaringType.IsValueType && !PropertyType.IsByRef && !method.ContainsGenericParameters) { //FIXME find a way to build an invoke delegate for value types.
cached_getter = CreateGetterDelegate (method);
// The try-catch preserves the .Invoke () behaviour
try {
return cached_getter (obj);
} catch (Exception ex) {
throw new TargetInvocationException (ex);
}
}
} else {
try {
return cached_getter (obj);
} catch (Exception ex) {
throw new TargetInvocationException (ex);
}
}
#endif
}
return GetValue (obj, BindingFlags.Default, null, index, null);
}
public override object GetValue (object obj, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture)
{
object ret = null;
MethodInfo method = GetGetMethod (true);
if (method == null)
throw new ArgumentException ($"Get Method not found for '{Name}'");
if (index == null || index.Length == 0)
ret = method.Invoke (obj, invokeAttr, binder, null, culture);
else
ret = method.Invoke (obj, invokeAttr, binder, index, culture);
return ret;
}
public override void SetValue (object obj, object value, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture)
{
MethodInfo method = GetSetMethod (true);
if (method == null)
throw new ArgumentException ("Set Method not found for '" + Name + "'");
object [] parms;
if (index == null || index.Length == 0)
parms = new object [] {value};
else {
int ilen = index.Length;
parms = new object [ilen+ 1];
index.CopyTo (parms, 0);
parms [ilen] = value;
}
method.Invoke (obj, invokeAttr, binder, parms, culture);
}
public override Type[] GetOptionalCustomModifiers () => GetCustomModifiers (true);
public override Type[] GetRequiredCustomModifiers () => GetCustomModifiers (false);
private Type[] GetCustomModifiers (bool optional) => GetTypeModifiers (this, optional) ?? Type.EmptyTypes;
public override IList<CustomAttributeData> GetCustomAttributesData () {
return CustomAttributeData.GetCustomAttributes (this);
}
public sealed override bool HasSameMetadataDefinitionAs (MemberInfo other) => HasSameMetadataDefinitionAsCore<RuntimePropertyInfo> (other);
public override int MetadataToken {
get {
return get_metadata_token (this);
}
}
[MethodImplAttribute (MethodImplOptions.InternalCall)]
internal static extern int get_metadata_token (RuntimePropertyInfo monoProperty);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern PropertyInfo internal_from_handle_type (IntPtr event_handle, IntPtr type_handle);
internal static PropertyInfo GetPropertyFromHandle (RuntimePropertyHandle handle, RuntimeTypeHandle reflectedType)
{
if (handle.Value == IntPtr.Zero)
throw new ArgumentException ("The handle is invalid.");
PropertyInfo pi = internal_from_handle_type (handle.Value, reflectedType.Value);
if (pi == null)
throw new ArgumentException ("The property handle and the type handle are incompatible.");
return pi;
}
}
}