From 5e768789c34d87f63db20b0655046e6231c89ee0 Mon Sep 17 00:00:00 2001 From: Atsushi Kanamori Date: Thu, 16 Mar 2017 12:27:56 -0700 Subject: [PATCH] Fixing more file-class correspondence violations. (dotnet/coreclr#10231) * Cloned files. * Reduce each file to its namesake class. * Cleanup * Fix build break. Commit migrated from https://github.com/dotnet/coreclr/commit/a3cd6bc2cde83c5e9a87253cd5fe7ed8aaafbde3 --- .../src/mscorlib/System.Private.CoreLib.csproj | 15 + .../src/mscorlib/src/System/Reflection/Assembly.cs | 956 +-------------------- .../System/Reflection/ConstructorInfo.CoreCLR.cs | 11 + .../src/System/Reflection/ConstructorInfo.cs | 499 +---------- .../mscorlib/src/System/Reflection/EventInfo.cs | 224 +---- .../src/System/Reflection/FieldInfo.CoreCLR.cs | 35 + .../mscorlib/src/System/Reflection/FieldInfo.cs | 680 +-------------- .../src/System/Reflection/ImageFileMachine.cs | 15 + .../mscorlib/src/System/Reflection/MdFieldInfo.cs | 141 +++ .../mscorlib/src/System/Reflection/MethodInfo.cs | 812 ----------------- .../src/mscorlib/src/System/Reflection/Module.cs | 638 +------------- .../System/Reflection/ModuleResolveEventHandler.cs | 9 + .../src/System/Reflection/ParameterInfo.cs | 517 +---------- .../System/Reflection/PortableExecutableKinds.cs | 18 + .../mscorlib/src/System/Reflection/PropertyInfo.cs | 475 +--------- .../mscorlib/src/System/Reflection/RtFieldInfo.cs | 390 +++++++++ .../src/System/Reflection/RuntimeAssembly.cs | 931 ++++++++++++++++++++ .../System/Reflection/RuntimeConstructorInfo.cs | 488 +++++++++++ .../src/System/Reflection/RuntimeEventInfo.cs | 224 +++++ .../src/System/Reflection/RuntimeFieldInfo.cs | 140 +++ .../src/System/Reflection/RuntimeMethodInfo.cs | 810 +++++++++++++++++ .../src/System/Reflection/RuntimeModule.cs | 603 +++++++++++++ .../src/System/Reflection/RuntimeParameterInfo.cs | 515 +++++++++++ .../src/System/Reflection/RuntimePropertyInfo.cs | 474 ++++++++++ 24 files changed, 4844 insertions(+), 4776 deletions(-) create mode 100644 src/coreclr/src/mscorlib/src/System/Reflection/ConstructorInfo.CoreCLR.cs create mode 100644 src/coreclr/src/mscorlib/src/System/Reflection/FieldInfo.CoreCLR.cs create mode 100644 src/coreclr/src/mscorlib/src/System/Reflection/ImageFileMachine.cs create mode 100644 src/coreclr/src/mscorlib/src/System/Reflection/MdFieldInfo.cs create mode 100644 src/coreclr/src/mscorlib/src/System/Reflection/ModuleResolveEventHandler.cs create mode 100644 src/coreclr/src/mscorlib/src/System/Reflection/PortableExecutableKinds.cs create mode 100644 src/coreclr/src/mscorlib/src/System/Reflection/RtFieldInfo.cs create mode 100644 src/coreclr/src/mscorlib/src/System/Reflection/RuntimeAssembly.cs create mode 100644 src/coreclr/src/mscorlib/src/System/Reflection/RuntimeConstructorInfo.cs create mode 100644 src/coreclr/src/mscorlib/src/System/Reflection/RuntimeEventInfo.cs create mode 100644 src/coreclr/src/mscorlib/src/System/Reflection/RuntimeFieldInfo.cs create mode 100644 src/coreclr/src/mscorlib/src/System/Reflection/RuntimeMethodInfo.cs create mode 100644 src/coreclr/src/mscorlib/src/System/Reflection/RuntimeModule.cs create mode 100644 src/coreclr/src/mscorlib/src/System/Reflection/RuntimeParameterInfo.cs create mode 100644 src/coreclr/src/mscorlib/src/System/Reflection/RuntimePropertyInfo.cs diff --git a/src/coreclr/src/mscorlib/System.Private.CoreLib.csproj b/src/coreclr/src/mscorlib/System.Private.CoreLib.csproj index a71c15b..e86f9a3 100644 --- a/src/coreclr/src/mscorlib/System.Private.CoreLib.csproj +++ b/src/coreclr/src/mscorlib/System.Private.CoreLib.csproj @@ -453,16 +453,19 @@ + + + @@ -470,6 +473,7 @@ + @@ -481,16 +485,27 @@ + + + + + + + + + + + diff --git a/src/coreclr/src/mscorlib/src/System/Reflection/Assembly.cs b/src/coreclr/src/mscorlib/src/System/Reflection/Assembly.cs index 57ea5ca..86aa373 100644 --- a/src/coreclr/src/mscorlib/src/System/Reflection/Assembly.cs +++ b/src/coreclr/src/mscorlib/src/System/Reflection/Assembly.cs @@ -2,44 +2,19 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================================= -** -** -** -** -** -** -** Purpose: For Assembly-related stuff. -** -** -=============================================================================*/ +using System.Collections.Generic; +using CultureInfo = System.Globalization.CultureInfo; +using System.Security; +using System.Security.Policy; +using System.IO; +using System.Configuration.Assemblies; +using StackCrawlMark = System.Threading.StackCrawlMark; +using System.Runtime.Serialization; +using System.Diagnostics.Contracts; +using System.Runtime.Loader; namespace System.Reflection { - using System; - using System.Collections; - using System.Collections.Generic; - using CultureInfo = System.Globalization.CultureInfo; - using System.Security; - using System.Security.Policy; - using System.IO; - using StringBuilder = System.Text.StringBuilder; - using System.Configuration.Assemblies; - using StackCrawlMark = System.Threading.StackCrawlMark; - using System.Runtime.InteropServices; - using System.Runtime.CompilerServices; - using System.Runtime.Serialization; - using Microsoft.Win32; - using System.Threading; - using __HResults = System.__HResults; - using System.Runtime.Versioning; - using System.Diagnostics.Contracts; - using System.Runtime.Loader; - - [Serializable] - public delegate Module ModuleResolveEventHandler(Object sender, ResolveEventArgs e); - - [Serializable] public abstract class Assembly : ICustomAttributeProvider, ISerializable { @@ -760,915 +735,4 @@ namespace System.Reflection #endregion // public methods } - - [Serializable] - internal class RuntimeAssembly : Assembly - { -#if FEATURE_APPX - // The highest byte is the flags and the lowest 3 bytes are - // the cached ctor token of [DynamicallyInvocableAttribute]. - private enum ASSEMBLY_FLAGS : uint - { - ASSEMBLY_FLAGS_UNKNOWN = 0x00000000, - ASSEMBLY_FLAGS_INITIALIZED = 0x01000000, - ASSEMBLY_FLAGS_FRAMEWORK = 0x02000000, - ASSEMBLY_FLAGS_TOKEN_MASK = 0x00FFFFFF, - } -#endif // FEATURE_APPX - - private const uint COR_E_LOADING_REFERENCE_ASSEMBLY = 0x80131058U; - - internal RuntimeAssembly() { throw new NotSupportedException(); } - - #region private data members - private event ModuleResolveEventHandler _ModuleResolve; - private string m_fullname; - private object m_syncRoot; // Used to keep collectible types alive and as the syncroot for reflection.emit - private IntPtr m_assembly; // slack for ptr datum on unmanaged side - -#if FEATURE_APPX - private ASSEMBLY_FLAGS m_flags; -#endif - #endregion - -#if FEATURE_APPX - private ASSEMBLY_FLAGS Flags - { - get - { - if ((m_flags & ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_INITIALIZED) == 0) - { - ASSEMBLY_FLAGS flags = ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_UNKNOWN - | ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_FRAMEWORK; - - m_flags = flags | ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_INITIALIZED; - } - - return m_flags; - } - } -#endif // FEATURE_APPX - - internal object SyncRoot - { - get - { - if (m_syncRoot == null) - { - Interlocked.CompareExchange(ref m_syncRoot, new object(), null); - } - return m_syncRoot; - } - } - - public override event ModuleResolveEventHandler ModuleResolve - { - add - { - _ModuleResolve += value; - } - remove - { - _ModuleResolve -= value; - } - } - - private const String s_localFilePrefix = "file:"; - - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - private static extern void GetCodeBase(RuntimeAssembly assembly, - bool copiedName, - StringHandleOnStack retString); - - internal String GetCodeBase(bool copiedName) - { - String codeBase = null; - GetCodeBase(GetNativeHandle(), copiedName, JitHelpers.GetStringHandleOnStack(ref codeBase)); - return codeBase; - } - - public override String CodeBase - { - get - { - String codeBase = GetCodeBase(false); - return codeBase; - } - } - - internal RuntimeAssembly GetNativeHandle() - { - return this; - } - - // If the assembly is copied before it is loaded, the codebase will be set to the - // actual file loaded if copiedName is true. If it is false, then the original code base - // is returned. - public override AssemblyName GetName(bool copiedName) - { - AssemblyName an = new AssemblyName(); - - String codeBase = GetCodeBase(copiedName); - - an.Init(GetSimpleName(), - GetPublicKey(), - null, // public key token - GetVersion(), - GetLocale(), - GetHashAlgorithm(), - AssemblyVersionCompatibility.SameMachine, - codeBase, - GetFlags() | AssemblyNameFlags.PublicKey, - null); // strong name key pair - - PortableExecutableKinds pek; - ImageFileMachine ifm; - - Module manifestModule = ManifestModule; - if (manifestModule != null) - { - if (manifestModule.MDStreamVersion > 0x10000) - { - ManifestModule.GetPEKind(out pek, out ifm); - an.SetProcArchIndex(pek, ifm); - } - } - return an; - } - - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - private extern static void GetFullName(RuntimeAssembly assembly, StringHandleOnStack retString); - - public override String FullName - { - get - { - // If called by Object.ToString(), return val may be NULL. - if (m_fullname == null) - { - string s = null; - GetFullName(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref s)); - Interlocked.CompareExchange(ref m_fullname, s, null); - } - - return m_fullname; - } - } - - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - private static extern void GetEntryPoint(RuntimeAssembly assembly, ObjectHandleOnStack retMethod); - - public override MethodInfo EntryPoint - { - get - { - IRuntimeMethodInfo methodHandle = null; - GetEntryPoint(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref methodHandle)); - - if (methodHandle == null) - return null; - - return (MethodInfo)RuntimeType.GetMethodBase(methodHandle); - } - } - - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - private static extern void GetType(RuntimeAssembly assembly, - String name, - bool throwOnError, - bool ignoreCase, - ObjectHandleOnStack type, - ObjectHandleOnStack keepAlive); - - public override Type GetType(String name, bool throwOnError, bool ignoreCase) - { - // throw on null strings regardless of the value of "throwOnError" - if (name == null) - throw new ArgumentNullException(nameof(name)); - - RuntimeType type = null; - Object keepAlive = null; - GetType(GetNativeHandle(), name, throwOnError, ignoreCase, JitHelpers.GetObjectHandleOnStack(ref type), JitHelpers.GetObjectHandleOnStack(ref keepAlive)); - GC.KeepAlive(keepAlive); - - return type; - } - - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - private extern static void GetExportedTypes(RuntimeAssembly assembly, ObjectHandleOnStack retTypes); - - public override Type[] GetExportedTypes() - { - Type[] types = null; - GetExportedTypes(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref types)); - return types; - } - - public override IEnumerable DefinedTypes - { - get - { - List rtTypes = new List(); - - RuntimeModule[] modules = GetModulesInternal(true, false); - - for (int i = 0; i < modules.Length; i++) - { - rtTypes.AddRange(modules[i].GetDefinedTypes()); - } - - return rtTypes.ToArray(); - } - } - - // Load a resource based on the NameSpace of the type. - [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod - public override Stream GetManifestResourceStream(Type type, String name) - { - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - return GetManifestResourceStream(type, name, false, ref stackMark); - } - - [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod - public override Stream GetManifestResourceStream(String name) - { - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - return GetManifestResourceStream(name, ref stackMark, false); - } - - // ISerializable implementation - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - throw new ArgumentNullException(nameof(info)); - - Contract.EndContractBlock(); - - UnitySerializationHolder.GetUnitySerializationInfo(info, - UnitySerializationHolder.AssemblyUnity, - this.FullName, - this); - } - - public override Module ManifestModule - { - get - { - // We don't need to return the "external" ModuleBuilder because - // it is meant to be read-only - return RuntimeAssembly.GetManifestModule(GetNativeHandle()); - } - } - - public override Object[] GetCustomAttributes(bool inherit) - { - return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); - } - - public override Object[] GetCustomAttributes(Type attributeType, bool inherit) - { - if (attributeType == null) - throw new ArgumentNullException(nameof(attributeType)); - Contract.EndContractBlock(); - - RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; - - if (attributeRuntimeType == null) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType)); - - return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType); - } - - public override bool IsDefined(Type attributeType, bool inherit) - { - if (attributeType == null) - throw new ArgumentNullException(nameof(attributeType)); - Contract.EndContractBlock(); - - RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; - - if (attributeRuntimeType == null) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType)); - - return CustomAttribute.IsDefined(this, attributeRuntimeType); - } - - public override IList GetCustomAttributesData() - { - return CustomAttributeData.GetCustomAttributesInternal(this); - } - - [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod - internal static RuntimeAssembly InternalLoadFrom(String assemblyFile, - Evidence securityEvidence, - byte[] hashValue, - AssemblyHashAlgorithm hashAlgorithm, - bool forIntrospection, - ref StackCrawlMark stackMark) - { - if (assemblyFile == null) - throw new ArgumentNullException(nameof(assemblyFile)); - - Contract.EndContractBlock(); - - AssemblyName an = new AssemblyName(); - an.CodeBase = assemblyFile; - an.SetHashControl(hashValue, hashAlgorithm); - // The stack mark is used for MDA filtering - return InternalLoadAssemblyName(an, securityEvidence, null, ref stackMark, true /*thrownOnFileNotFound*/, forIntrospection); - } - - // Wrapper function to wrap the typical use of InternalLoad. - internal static RuntimeAssembly InternalLoad(String assemblyString, - Evidence assemblySecurity, - ref StackCrawlMark stackMark, - bool forIntrospection) - { - return InternalLoad(assemblyString, assemblySecurity, ref stackMark, IntPtr.Zero, forIntrospection); - } - - [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod - internal static RuntimeAssembly InternalLoad(String assemblyString, - Evidence assemblySecurity, - ref StackCrawlMark stackMark, - IntPtr pPrivHostBinder, - bool forIntrospection) - { - RuntimeAssembly assembly; - AssemblyName an = CreateAssemblyName(assemblyString, forIntrospection, out assembly); - - if (assembly != null) - { - // The assembly was returned from ResolveAssemblyEvent - return assembly; - } - - return InternalLoadAssemblyName(an, assemblySecurity, null, ref stackMark, - pPrivHostBinder, - true /*thrownOnFileNotFound*/, forIntrospection); - } - - // Creates AssemblyName. Fills assembly if AssemblyResolve event has been raised. - internal static AssemblyName CreateAssemblyName( - String assemblyString, - bool forIntrospection, - out RuntimeAssembly assemblyFromResolveEvent) - { - if (assemblyString == null) - throw new ArgumentNullException(nameof(assemblyString)); - Contract.EndContractBlock(); - - if ((assemblyString.Length == 0) || - (assemblyString[0] == '\0')) - throw new ArgumentException(Environment.GetResourceString("Format_StringZeroLength")); - - if (forIntrospection) - AppDomain.CheckReflectionOnlyLoadSupported(); - - AssemblyName an = new AssemblyName(); - - an.Name = assemblyString; - an.nInit(out assemblyFromResolveEvent, forIntrospection, true); - - return an; - } - - // Wrapper function to wrap the typical use of InternalLoadAssemblyName. - internal static RuntimeAssembly InternalLoadAssemblyName( - AssemblyName assemblyRef, - Evidence assemblySecurity, - RuntimeAssembly reqAssembly, - ref StackCrawlMark stackMark, - bool throwOnFileNotFound, - bool forIntrospection, - IntPtr ptrLoadContextBinder = default(IntPtr)) - { - return InternalLoadAssemblyName(assemblyRef, assemblySecurity, reqAssembly, ref stackMark, IntPtr.Zero, true /*throwOnError*/, forIntrospection, ptrLoadContextBinder); - } - - internal static RuntimeAssembly InternalLoadAssemblyName( - AssemblyName assemblyRef, - Evidence assemblySecurity, - RuntimeAssembly reqAssembly, - ref StackCrawlMark stackMark, - IntPtr pPrivHostBinder, - bool throwOnFileNotFound, - bool forIntrospection, - IntPtr ptrLoadContextBinder = default(IntPtr)) - { - if (assemblyRef == null) - throw new ArgumentNullException(nameof(assemblyRef)); - Contract.EndContractBlock(); - - if (assemblyRef.CodeBase != null) - { - AppDomain.CheckLoadFromSupported(); - } - - assemblyRef = (AssemblyName)assemblyRef.Clone(); - if (!forIntrospection && - (assemblyRef.ProcessorArchitecture != ProcessorArchitecture.None)) - { - // PA does not have a semantics for by-name binds for execution - assemblyRef.ProcessorArchitecture = ProcessorArchitecture.None; - } - - String codeBase = VerifyCodeBase(assemblyRef.CodeBase); - - return nLoad(assemblyRef, codeBase, assemblySecurity, reqAssembly, ref stackMark, - pPrivHostBinder, - throwOnFileNotFound, forIntrospection, ptrLoadContextBinder); - } - - // These are the framework assemblies that does reflection invocation - // on behalf of user code. We allow framework code to invoke non-W8P - // framework APIs but don't want user code to gain that privilege - // through these assemblies. So we blaklist them. - private static string[] s_unsafeFrameworkAssemblyNames = new string[] { - "System.Reflection.Context", - "Microsoft.VisualBasic" - }; - -#if FEATURE_APPX - internal bool IsFrameworkAssembly() - { - ASSEMBLY_FLAGS flags = Flags; - return (flags & ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_FRAMEWORK) != 0; - } -#endif - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern RuntimeAssembly _nLoad(AssemblyName fileName, - String codeBase, - Evidence assemblySecurity, - RuntimeAssembly locationHint, - ref StackCrawlMark stackMark, - IntPtr pPrivHostBinder, - bool throwOnFileNotFound, - bool forIntrospection, - bool suppressSecurityChecks, - IntPtr ptrLoadContextBinder); - - private static RuntimeAssembly nLoad(AssemblyName fileName, - String codeBase, - Evidence assemblySecurity, - RuntimeAssembly locationHint, - ref StackCrawlMark stackMark, - IntPtr pPrivHostBinder, - bool throwOnFileNotFound, - bool forIntrospection, - IntPtr ptrLoadContextBinder = default(IntPtr)) - { - return _nLoad(fileName, codeBase, assemblySecurity, locationHint, ref stackMark, - pPrivHostBinder, - throwOnFileNotFound, forIntrospection, true /* suppressSecurityChecks */, ptrLoadContextBinder); - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern bool IsReflectionOnly(RuntimeAssembly assembly); - - public override bool ReflectionOnly - { - get - { - return IsReflectionOnly(GetNativeHandle()); - } - } - - // Returns the module in this assembly with name 'name' - - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - private static extern void GetModule(RuntimeAssembly assembly, String name, ObjectHandleOnStack retModule); - - public override Module GetModule(String name) - { - Module retModule = null; - GetModule(GetNativeHandle(), name, JitHelpers.GetObjectHandleOnStack(ref retModule)); - return retModule; - } - - // Returns the file in the File table of the manifest that matches the - // given name. (Name should not include path.) - public override FileStream GetFile(String name) - { - RuntimeModule m = (RuntimeModule)GetModule(name); - if (m == null) - return null; - - return new FileStream(m.GetFullyQualifiedName(), - FileMode.Open, - FileAccess.Read, FileShare.Read, FileStream.DefaultBufferSize, false); - } - - public override FileStream[] GetFiles(bool getResourceModules) - { - Module[] m = GetModules(getResourceModules); - FileStream[] fs = new FileStream[m.Length]; - - for (int i = 0; i < fs.Length; i++) - { - fs[i] = new FileStream(((RuntimeModule)m[i]).GetFullyQualifiedName(), - FileMode.Open, - FileAccess.Read, FileShare.Read, FileStream.DefaultBufferSize, false); - } - - return fs; - } - - // Returns the names of all the resources - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern String[] GetManifestResourceNames(RuntimeAssembly assembly); - - // Returns the names of all the resources - public override String[] GetManifestResourceNames() - { - return GetManifestResourceNames(GetNativeHandle()); - } - - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - private extern static void GetExecutingAssembly(StackCrawlMarkHandle stackMark, ObjectHandleOnStack retAssembly); - - internal static RuntimeAssembly GetExecutingAssembly(ref StackCrawlMark stackMark) - { - RuntimeAssembly retAssembly = null; - GetExecutingAssembly(JitHelpers.GetStackCrawlMarkHandle(ref stackMark), JitHelpers.GetObjectHandleOnStack(ref retAssembly)); - return retAssembly; - } - - // Returns the names of all the resources - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern AssemblyName[] GetReferencedAssemblies(RuntimeAssembly assembly); - - public override AssemblyName[] GetReferencedAssemblies() - { - return GetReferencedAssemblies(GetNativeHandle()); - } - - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - private static extern int GetManifestResourceInfo(RuntimeAssembly assembly, - String resourceName, - ObjectHandleOnStack assemblyRef, - StringHandleOnStack retFileName, - StackCrawlMarkHandle stackMark); - - [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod - public override ManifestResourceInfo GetManifestResourceInfo(String resourceName) - { - RuntimeAssembly retAssembly = null; - String fileName = null; - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - int location = GetManifestResourceInfo(GetNativeHandle(), resourceName, - JitHelpers.GetObjectHandleOnStack(ref retAssembly), - JitHelpers.GetStringHandleOnStack(ref fileName), - JitHelpers.GetStackCrawlMarkHandle(ref stackMark)); - - if (location == -1) - return null; - - return new ManifestResourceInfo(retAssembly, fileName, - (ResourceLocation)location); - } - - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - private static extern void GetLocation(RuntimeAssembly assembly, StringHandleOnStack retString); - - public override String Location - { - get - { - String location = null; - - GetLocation(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref location)); - - return location; - } - } - - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - private extern static void GetImageRuntimeVersion(RuntimeAssembly assembly, StringHandleOnStack retString); - - public override String ImageRuntimeVersion - { - get - { - String s = null; - GetImageRuntimeVersion(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref s)); - return s; - } - } - - public override bool GlobalAssemblyCache - { - get - { - return false; - } - } - - public override Int64 HostContext - { - get - { - return 0; - } - } - - private static String VerifyCodeBase(String codebase) - { - if (codebase == null) - return null; - - int len = codebase.Length; - if (len == 0) - return null; - - - int j = codebase.IndexOf(':'); - // Check to see if the url has a prefix - if ((j != -1) && - (j + 2 < len) && - ((codebase[j + 1] == '/') || (codebase[j + 1] == '\\')) && - ((codebase[j + 2] == '/') || (codebase[j + 2] == '\\'))) - return codebase; -#if !PLATFORM_UNIX - else if ((len > 2) && (codebase[0] == '\\') && (codebase[1] == '\\')) - return "file://" + codebase; - else - return "file:///" + Path.GetFullPath(codebase); -#else - else - return "file://" + Path.GetFullPath(codebase); -#endif // !PLATFORM_UNIX - } - - internal Stream GetManifestResourceStream( - Type type, - String name, - bool skipSecurityCheck, - ref StackCrawlMark stackMark) - { - StringBuilder sb = new StringBuilder(); - if (type == null) - { - if (name == null) - throw new ArgumentNullException(nameof(type)); - } - else - { - String nameSpace = type.Namespace; - if (nameSpace != null) - { - sb.Append(nameSpace); - if (name != null) - sb.Append(Type.Delimiter); - } - } - - if (name != null) - sb.Append(name); - - return GetManifestResourceStream(sb.ToString(), ref stackMark, skipSecurityCheck); - } - - // GetResource will return a pointer to the resources in memory. - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - private static unsafe extern byte* GetResource(RuntimeAssembly assembly, - String resourceName, - out ulong length, - StackCrawlMarkHandle stackMark, - bool skipSecurityCheck); - - internal unsafe Stream GetManifestResourceStream(String name, ref StackCrawlMark stackMark, bool skipSecurityCheck) - { - ulong length = 0; - byte* pbInMemoryResource = GetResource(GetNativeHandle(), name, out length, JitHelpers.GetStackCrawlMarkHandle(ref stackMark), skipSecurityCheck); - - if (pbInMemoryResource != null) - { - //Console.WriteLine("Creating an unmanaged memory stream of length "+length); - if (length > Int64.MaxValue) - throw new NotImplementedException(Environment.GetResourceString("NotImplemented_ResourcesLongerThan2^63")); - - return new UnmanagedMemoryStream(pbInMemoryResource, (long)length, (long)length, FileAccess.Read); - } - - //Console.WriteLine("GetManifestResourceStream: Blob "+name+" not found..."); - return null; - } - - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - private static extern void GetVersion(RuntimeAssembly assembly, - out int majVer, - out int minVer, - out int buildNum, - out int revNum); - - internal Version GetVersion() - { - int majorVer, minorVer, build, revision; - GetVersion(GetNativeHandle(), out majorVer, out minorVer, out build, out revision); - return new Version(majorVer, minorVer, build, revision); - } - - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - private static extern void GetLocale(RuntimeAssembly assembly, StringHandleOnStack retString); - - internal CultureInfo GetLocale() - { - String locale = null; - - GetLocale(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref locale)); - - if (locale == null) - return CultureInfo.InvariantCulture; - - return new CultureInfo(locale); - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern bool FCallIsDynamic(RuntimeAssembly assembly); - - public override bool IsDynamic - { - get - { - return FCallIsDynamic(GetNativeHandle()); - } - } - - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - private static extern void GetSimpleName(RuntimeAssembly assembly, StringHandleOnStack retSimpleName); - - internal String GetSimpleName() - { - string name = null; - GetSimpleName(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref name)); - return name; - } - - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - private extern static AssemblyHashAlgorithm GetHashAlgorithm(RuntimeAssembly assembly); - - private AssemblyHashAlgorithm GetHashAlgorithm() - { - return GetHashAlgorithm(GetNativeHandle()); - } - - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - private extern static AssemblyNameFlags GetFlags(RuntimeAssembly assembly); - - private AssemblyNameFlags GetFlags() - { - return GetFlags(GetNativeHandle()); - } - - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - private static extern void GetPublicKey(RuntimeAssembly assembly, ObjectHandleOnStack retPublicKey); - - internal byte[] GetPublicKey() - { - byte[] publicKey = null; - GetPublicKey(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref publicKey)); - return publicKey; - } - - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - [return: MarshalAs(UnmanagedType.Bool)] - private extern static bool IsAllSecurityTransparent(RuntimeAssembly assembly); - - // Is everything introduced by this assembly transparent - internal bool IsAllSecurityTransparent() - { - return IsAllSecurityTransparent(GetNativeHandle()); - } - - // This method is called by the VM. - private RuntimeModule OnModuleResolveEvent(String moduleName) - { - ModuleResolveEventHandler moduleResolve = _ModuleResolve; - if (moduleResolve == null) - return null; - - Delegate[] ds = moduleResolve.GetInvocationList(); - int len = ds.Length; - for (int i = 0; i < len; i++) - { - RuntimeModule ret = (RuntimeModule)((ModuleResolveEventHandler)ds[i])(this, new ResolveEventArgs(moduleName, this)); - if (ret != null) - return ret; - } - - return null; - } - - [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod - public override Assembly GetSatelliteAssembly(CultureInfo culture) - { - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - return InternalGetSatelliteAssembly(culture, null, ref stackMark); - } - - // Useful for binding to a very specific version of a satellite assembly - [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod - public override Assembly GetSatelliteAssembly(CultureInfo culture, Version version) - { - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - return InternalGetSatelliteAssembly(culture, version, ref stackMark); - } - - [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod - internal Assembly InternalGetSatelliteAssembly(CultureInfo culture, - Version version, - ref StackCrawlMark stackMark) - { - if (culture == null) - throw new ArgumentNullException(nameof(culture)); - Contract.EndContractBlock(); - - - String name = GetSimpleName() + ".resources"; - return InternalGetSatelliteAssembly(name, culture, version, true, ref stackMark); - } - - [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod - internal RuntimeAssembly InternalGetSatelliteAssembly(String name, - CultureInfo culture, - Version version, - bool throwOnFileNotFound, - ref StackCrawlMark stackMark) - { - AssemblyName an = new AssemblyName(); - - an.SetPublicKey(GetPublicKey()); - an.Flags = GetFlags() | AssemblyNameFlags.PublicKey; - - if (version == null) - an.Version = GetVersion(); - else - an.Version = version; - - an.CultureInfo = culture; - an.Name = name; - - RuntimeAssembly retAssembly = nLoad(an, null, null, this, ref stackMark, - IntPtr.Zero, - throwOnFileNotFound, false); - - if (retAssembly == this || (retAssembly == null && throwOnFileNotFound)) - { - throw new FileNotFoundException(String.Format(culture, Environment.GetResourceString("IO.FileNotFound_FileName"), an.Name)); - } - - return retAssembly; - } - - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - private extern static void GetModules(RuntimeAssembly assembly, - bool loadIfNotFound, - bool getResourceModules, - ObjectHandleOnStack retModuleHandles); - - private RuntimeModule[] GetModulesInternal(bool loadIfNotFound, - bool getResourceModules) - { - RuntimeModule[] modules = null; - GetModules(GetNativeHandle(), loadIfNotFound, getResourceModules, JitHelpers.GetObjectHandleOnStack(ref modules)); - return modules; - } - - public override Module[] GetModules(bool getResourceModules) - { - return GetModulesInternal(true, getResourceModules); - } - - public override Module[] GetLoadedModules(bool getResourceModules) - { - return GetModulesInternal(false, getResourceModules); - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal static extern RuntimeModule GetManifestModule(RuntimeAssembly assembly); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal static extern int GetToken(RuntimeAssembly assembly); - } } diff --git a/src/coreclr/src/mscorlib/src/System/Reflection/ConstructorInfo.CoreCLR.cs b/src/coreclr/src/mscorlib/src/System/Reflection/ConstructorInfo.CoreCLR.cs new file mode 100644 index 0000000..c96bfb5 --- /dev/null +++ b/src/coreclr/src/mscorlib/src/System/Reflection/ConstructorInfo.CoreCLR.cs @@ -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. +// See the LICENSE file in the project root for more information. + +namespace System.Reflection +{ + public abstract partial class ConstructorInfo : MethodBase + { + internal virtual Type GetReturnType() { throw new NotImplementedException(); } + } +} diff --git a/src/coreclr/src/mscorlib/src/System/Reflection/ConstructorInfo.cs b/src/coreclr/src/mscorlib/src/System/Reflection/ConstructorInfo.cs index 284134a..df76ac5 100644 --- a/src/coreclr/src/mscorlib/src/System/Reflection/ConstructorInfo.cs +++ b/src/coreclr/src/mscorlib/src/System/Reflection/ConstructorInfo.cs @@ -2,27 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// +using System.Diagnostics; +using System.Globalization; namespace System.Reflection { - using System; - using System.Collections.Generic; - using System.Diagnostics; - using System.Diagnostics.Contracts; - using System.Globalization; - using System.Runtime; - using System.Runtime.ConstrainedExecution; - using System.Runtime.InteropServices; - using System.Runtime.Serialization; - using System.Security; - using System.Threading; - using MemberListType = System.RuntimeType.MemberListType; - using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; - using System.Runtime.CompilerServices; - [Serializable] - public abstract class ConstructorInfo : MethodBase + public abstract partial class ConstructorInfo : MethodBase { #region Static Members public readonly static String ConstructorName = ".ctor"; @@ -62,10 +48,6 @@ namespace System.Reflection return base.GetHashCode(); } - #region Internal Members - internal virtual Type GetReturnType() { throw new NotImplementedException(); } - #endregion - #region MemberInfo Overrides public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Constructor; } } #endregion @@ -89,479 +71,4 @@ namespace System.Reflection } #endregion } - - [Serializable] - internal sealed class RuntimeConstructorInfo : ConstructorInfo, ISerializable, IRuntimeMethodInfo - { - #region Private Data Members - private volatile RuntimeType m_declaringType; - private RuntimeTypeCache m_reflectedTypeCache; - private string m_toString; - private ParameterInfo[] m_parameters = null; // Created lazily when GetParameters() is called. -#pragma warning disable 169 - private object _empty1; // These empties are used to ensure that RuntimeConstructorInfo and RuntimeMethodInfo are have a layout which is sufficiently similar - private object _empty2; - private object _empty3; -#pragma warning restore 169 - private IntPtr m_handle; - private MethodAttributes m_methodAttributes; - private BindingFlags m_bindingFlags; - private volatile Signature m_signature; - private INVOCATION_FLAGS m_invocationFlags; - - internal INVOCATION_FLAGS InvocationFlags - { - get - { - if ((m_invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0) - { - INVOCATION_FLAGS invocationFlags = INVOCATION_FLAGS.INVOCATION_FLAGS_IS_CTOR; // this is a given - - Type declaringType = DeclaringType; - - // - // first take care of all the NO_INVOKE cases. - if (declaringType == typeof(void) || - (declaringType != null && declaringType.ContainsGenericParameters) || - ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) || - ((Attributes & MethodAttributes.RequireSecObject) == MethodAttributes.RequireSecObject)) - { - // We don't need other flags if this method cannot be invoked - invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE; - } - else if (IsStatic || declaringType != null && declaringType.IsAbstract) - { - invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NO_CTOR_INVOKE; - } - else - { - // this should be an invocable method, determine the other flags that participate in invocation - invocationFlags |= RuntimeMethodHandle.GetSecurityFlags(this); - - if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) == 0 && - ((Attributes & MethodAttributes.MemberAccessMask) != MethodAttributes.Public || - (declaringType != null && declaringType.NeedsReflectionSecurityCheck))) - { - // If method is non-public, or declaring type is not visible - invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY; - } - - // Check for attempt to create a delegate class, we demand unmanaged - // code permission for this since it's hard to validate the target address. - if (typeof(Delegate).IsAssignableFrom(DeclaringType)) - invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_IS_DELEGATE_CTOR; - } - - m_invocationFlags = invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED; - } - - return m_invocationFlags; - } - } - #endregion - - #region Constructor - internal RuntimeConstructorInfo( - RuntimeMethodHandleInternal handle, RuntimeType declaringType, RuntimeTypeCache reflectedTypeCache, - MethodAttributes methodAttributes, BindingFlags bindingFlags) - { - Contract.Ensures(methodAttributes == RuntimeMethodHandle.GetAttributes(handle)); - - m_bindingFlags = bindingFlags; - m_reflectedTypeCache = reflectedTypeCache; - m_declaringType = declaringType; - m_handle = handle.Value; - m_methodAttributes = methodAttributes; - } - #endregion - - #region NonPublic Methods - RuntimeMethodHandleInternal IRuntimeMethodInfo.Value - { - get - { - return new RuntimeMethodHandleInternal(m_handle); - } - } - - internal override bool CacheEquals(object o) - { - RuntimeConstructorInfo m = o as RuntimeConstructorInfo; - - if ((object)m == null) - return false; - - return m.m_handle == m_handle; - } - - private Signature Signature - { - get - { - if (m_signature == null) - m_signature = new Signature(this, m_declaringType); - - return m_signature; - } - } - - private RuntimeType ReflectedTypeInternal - { - get - { - return m_reflectedTypeCache.GetRuntimeType(); - } - } - - private void CheckConsistency(Object target) - { - if (target == null && IsStatic) - return; - - if (!m_declaringType.IsInstanceOfType(target)) - { - if (target == null) - throw new TargetException(Environment.GetResourceString("RFLCT.Targ_StatMethReqTarg")); - - throw new TargetException(Environment.GetResourceString("RFLCT.Targ_ITargMismatch")); - } - } - - internal BindingFlags BindingFlags { get { return m_bindingFlags; } } - #endregion - - #region Object Overrides - public override String ToString() - { - // "Void" really doesn't make sense here. But we'll keep it for compat reasons. - if (m_toString == null) - m_toString = "Void " + FormatNameAndSig(); - - return m_toString; - } - #endregion - - #region ICustomAttributeProvider - public override Object[] GetCustomAttributes(bool inherit) - { - return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); - } - - public override Object[] GetCustomAttributes(Type attributeType, bool inherit) - { - if (attributeType == null) - throw new ArgumentNullException(nameof(attributeType)); - Contract.EndContractBlock(); - - RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; - - if (attributeRuntimeType == null) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType)); - - return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType); - } - - public override bool IsDefined(Type attributeType, bool inherit) - { - if (attributeType == null) - throw new ArgumentNullException(nameof(attributeType)); - Contract.EndContractBlock(); - - RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; - - if (attributeRuntimeType == null) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType)); - - return CustomAttribute.IsDefined(this, attributeRuntimeType); - } - - public override IList GetCustomAttributesData() - { - return CustomAttributeData.GetCustomAttributesInternal(this); - } - #endregion - - - #region MemberInfo Overrides - public override String Name - { - get { return RuntimeMethodHandle.GetName(this); } - } - public override MemberTypes MemberType { get { return MemberTypes.Constructor; } } - - public override Type DeclaringType - { - get - { - return m_reflectedTypeCache.IsGlobal ? null : m_declaringType; - } - } - - public override Type ReflectedType - { - get - { - return m_reflectedTypeCache.IsGlobal ? null : ReflectedTypeInternal; - } - } - - public override int MetadataToken - { - get { return RuntimeMethodHandle.GetMethodDef(this); } - } - public override Module Module - { - get { return GetRuntimeModule(); } - } - - internal RuntimeType GetRuntimeType() { return m_declaringType; } - internal RuntimeModule GetRuntimeModule() { return RuntimeTypeHandle.GetModule(m_declaringType); } - internal RuntimeAssembly GetRuntimeAssembly() { return GetRuntimeModule().GetRuntimeAssembly(); } - #endregion - - #region MethodBase Overrides - - // This seems to always returns System.Void. - internal override Type GetReturnType() { return Signature.ReturnType; } - - internal override ParameterInfo[] GetParametersNoCopy() - { - if (m_parameters == null) - m_parameters = RuntimeParameterInfo.GetParameters(this, this, Signature); - - return m_parameters; - } - - [Pure] - public override ParameterInfo[] GetParameters() - { - ParameterInfo[] parameters = GetParametersNoCopy(); - - if (parameters.Length == 0) - return parameters; - - ParameterInfo[] ret = new ParameterInfo[parameters.Length]; - Array.Copy(parameters, ret, parameters.Length); - return ret; - } - - public override MethodImplAttributes GetMethodImplementationFlags() - { - return RuntimeMethodHandle.GetImplAttributes(this); - } - - public override RuntimeMethodHandle MethodHandle - { - get - { - Type declaringType = DeclaringType; - if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType) - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAllowedInReflectionOnly")); - return new RuntimeMethodHandle(this); - } - } - - public override MethodAttributes Attributes - { - get - { - return m_methodAttributes; - } - } - - public override CallingConventions CallingConvention - { - get - { - return Signature.CallingConvention; - } - } - - internal static void CheckCanCreateInstance(Type declaringType, bool isVarArg) - { - if (declaringType == null) - throw new ArgumentNullException(nameof(declaringType)); - Contract.EndContractBlock(); - - // ctor is ReflectOnly - if (declaringType is ReflectionOnlyType) - throw new InvalidOperationException(Environment.GetResourceString("Arg_ReflectionOnlyInvoke")); - - // ctor is declared on interface class - else if (declaringType.IsInterface) - throw new MemberAccessException( - String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Acc_CreateInterfaceEx"), declaringType)); - - // ctor is on an abstract class - else if (declaringType.IsAbstract) - throw new MemberAccessException( - String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Acc_CreateAbstEx"), declaringType)); - - // ctor is on a class that contains stack pointers - else if (declaringType.GetRootElementType() == typeof(ArgIterator)) - throw new NotSupportedException(); - - // ctor is vararg - else if (isVarArg) - throw new NotSupportedException(); - - // ctor is generic or on a generic class - else if (declaringType.ContainsGenericParameters) - { - throw new MemberAccessException( - String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Acc_CreateGenericEx"), declaringType)); - } - - // ctor is declared on System.Void - else if (declaringType == typeof(void)) - throw new MemberAccessException(Environment.GetResourceString("Access_Void")); - } - - internal void ThrowNoInvokeException() - { - CheckCanCreateInstance(DeclaringType, (CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs); - - // ctor is .cctor - if ((Attributes & MethodAttributes.Static) == MethodAttributes.Static) - throw new MemberAccessException(Environment.GetResourceString("Acc_NotClassInit")); - - throw new TargetException(); - } - - [DebuggerStepThroughAttribute] - [Diagnostics.DebuggerHidden] - [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod - public override Object Invoke( - Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) - { - INVOCATION_FLAGS invocationFlags = InvocationFlags; - - if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE) != 0) - ThrowNoInvokeException(); - - // check basic method consistency. This call will throw if there are problems in the target/method relationship - CheckConsistency(obj); - - if (obj != null) - { - // For unverifiable code, we require the caller to be critical. - // Adding the INVOCATION_FLAGS_NEED_SECURITY flag makes that check happen - invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY; - } - - Signature sig = Signature; - - // get the signature - int formalCount = sig.Arguments.Length; - int actualCount = (parameters != null) ? parameters.Length : 0; - if (formalCount != actualCount) - throw new TargetParameterCountException(Environment.GetResourceString("Arg_ParmCnt")); - - // if we are here we passed all the previous checks. Time to look at the arguments - if (actualCount > 0) - { - Object[] arguments = CheckArguments(parameters, binder, invokeAttr, culture, sig); - Object retValue = RuntimeMethodHandle.InvokeMethod(obj, arguments, sig, false); - // copy out. This should be made only if ByRef are present. - for (int index = 0; index < arguments.Length; index++) - parameters[index] = arguments[index]; - return retValue; - } - return RuntimeMethodHandle.InvokeMethod(obj, null, sig, false); - } - - public override MethodBody GetMethodBody() - { - MethodBody mb = RuntimeMethodHandle.GetMethodBody(this, ReflectedTypeInternal); - if (mb != null) - mb.m_methodBase = this; - return mb; - } - - public override bool IsSecurityCritical - { - get { return true; } - } - - public override bool IsSecuritySafeCritical - { - get { return false; } - } - - public override bool IsSecurityTransparent - { - get { return false; } - } - - public override bool ContainsGenericParameters - { - get - { - return (DeclaringType != null && DeclaringType.ContainsGenericParameters); - } - } - #endregion - - #region ConstructorInfo Overrides - [DebuggerStepThroughAttribute] - [Diagnostics.DebuggerHidden] - [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod - public override Object Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) - { - INVOCATION_FLAGS invocationFlags = InvocationFlags; - - // get the declaring TypeHandle early for consistent exceptions in IntrospectionOnly context - RuntimeTypeHandle declaringTypeHandle = m_declaringType.TypeHandle; - - if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE | INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS | INVOCATION_FLAGS.INVOCATION_FLAGS_NO_CTOR_INVOKE)) != 0) - ThrowNoInvokeException(); - - // get the signature - Signature sig = Signature; - - int formalCount = sig.Arguments.Length; - int actualCount = (parameters != null) ? parameters.Length : 0; - if (formalCount != actualCount) - throw new TargetParameterCountException(Environment.GetResourceString("Arg_ParmCnt")); - - // We don't need to explicitly invoke the class constructor here, - // JIT/NGen will insert the call to .cctor in the instance ctor. - - // if we are here we passed all the previous checks. Time to look at the arguments - if (actualCount > 0) - { - Object[] arguments = CheckArguments(parameters, binder, invokeAttr, culture, sig); - Object retValue = RuntimeMethodHandle.InvokeMethod(null, arguments, sig, true); - // copy out. This should be made only if ByRef are present. - for (int index = 0; index < arguments.Length; index++) - parameters[index] = arguments[index]; - return retValue; - } - return RuntimeMethodHandle.InvokeMethod(null, null, sig, true); - } - #endregion - - #region ISerializable Implementation - public void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - throw new ArgumentNullException(nameof(info)); - Contract.EndContractBlock(); - MemberInfoSerializationHolder.GetSerializationInfo( - info, - Name, - ReflectedTypeInternal, - ToString(), - SerializationToString(), - MemberTypes.Constructor, - null); - } - - internal string SerializationToString() - { - // We don't need the return type for constructors. - return FormatNameAndSig(true); - } - #endregion - } } diff --git a/src/coreclr/src/mscorlib/src/System/Reflection/EventInfo.cs b/src/coreclr/src/mscorlib/src/System/Reflection/EventInfo.cs index 1e2691a..0ec89da 100644 --- a/src/coreclr/src/mscorlib/src/System/Reflection/EventInfo.cs +++ b/src/coreclr/src/mscorlib/src/System/Reflection/EventInfo.cs @@ -2,19 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// +using System.Diagnostics; namespace System.Reflection { - using System; - using System.Collections.Generic; - using System.Diagnostics; - using System.Diagnostics.Contracts; - using System.Runtime.InteropServices; - using System.Runtime.Serialization; - using System.Runtime.ConstrainedExecution; - using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; - [Serializable] public abstract class EventInfo : MemberInfo { @@ -184,217 +175,4 @@ namespace System.Reflection } #endregion } - - [Serializable] - internal unsafe sealed class RuntimeEventInfo : EventInfo, ISerializable - { - #region Private Data Members - private int m_token; - private EventAttributes m_flags; - private string m_name; - private void* m_utf8name; - private RuntimeTypeCache m_reflectedTypeCache; - private RuntimeMethodInfo m_addMethod; - private RuntimeMethodInfo m_removeMethod; - private RuntimeMethodInfo m_raiseMethod; - private MethodInfo[] m_otherMethod; - private RuntimeType m_declaringType; - private BindingFlags m_bindingFlags; - #endregion - - #region Constructor - internal RuntimeEventInfo() - { - // Used for dummy head node during population - } - internal RuntimeEventInfo(int tkEvent, RuntimeType declaredType, RuntimeTypeCache reflectedTypeCache, out bool isPrivate) - { - Contract.Requires(declaredType != null); - Contract.Requires(reflectedTypeCache != null); - Debug.Assert(!reflectedTypeCache.IsGlobal); - - MetadataImport scope = declaredType.GetRuntimeModule().MetadataImport; - - m_token = tkEvent; - m_reflectedTypeCache = reflectedTypeCache; - m_declaringType = declaredType; - - - RuntimeType reflectedType = reflectedTypeCache.GetRuntimeType(); - - scope.GetEventProps(tkEvent, out m_utf8name, out m_flags); - - RuntimeMethodInfo dummy; - Associates.AssignAssociates(scope, tkEvent, declaredType, reflectedType, - out m_addMethod, out m_removeMethod, out m_raiseMethod, - out dummy, out dummy, out m_otherMethod, out isPrivate, out m_bindingFlags); - } - #endregion - - #region Internal Members - internal override bool CacheEquals(object o) - { - RuntimeEventInfo m = o as RuntimeEventInfo; - - if ((object)m == null) - return false; - - return m.m_token == m_token && - RuntimeTypeHandle.GetModule(m_declaringType).Equals( - RuntimeTypeHandle.GetModule(m.m_declaringType)); - } - - internal BindingFlags BindingFlags { get { return m_bindingFlags; } } - #endregion - - #region Object Overrides - public override String ToString() - { - if (m_addMethod == null || m_addMethod.GetParametersNoCopy().Length == 0) - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NoPublicAddMethod")); - - return m_addMethod.GetParametersNoCopy()[0].ParameterType.FormatTypeName() + " " + Name; - } - #endregion - - #region ICustomAttributeProvider - public override Object[] GetCustomAttributes(bool inherit) - { - return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); - } - - public override Object[] GetCustomAttributes(Type attributeType, bool inherit) - { - if (attributeType == null) - throw new ArgumentNullException(nameof(attributeType)); - Contract.EndContractBlock(); - - RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; - - if (attributeRuntimeType == null) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType)); - - return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType); - } - - public override bool IsDefined(Type attributeType, bool inherit) - { - if (attributeType == null) - throw new ArgumentNullException(nameof(attributeType)); - Contract.EndContractBlock(); - - RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; - - if (attributeRuntimeType == null) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType)); - - return CustomAttribute.IsDefined(this, attributeRuntimeType); - } - - public override IList GetCustomAttributesData() - { - return CustomAttributeData.GetCustomAttributesInternal(this); - } - #endregion - - #region MemberInfo Overrides - public override MemberTypes MemberType { get { return MemberTypes.Event; } } - public override String Name - { - get - { - if (m_name == null) - m_name = new Utf8String(m_utf8name).ToString(); - - return m_name; - } - } - public override Type DeclaringType { get { return m_declaringType; } } - public override Type ReflectedType - { - get - { - return ReflectedTypeInternal; - } - } - - private RuntimeType ReflectedTypeInternal - { - get - { - return m_reflectedTypeCache.GetRuntimeType(); - } - } - - public override int MetadataToken { get { return m_token; } } - public override Module Module { get { return GetRuntimeModule(); } } - internal RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); } - #endregion - - #region ISerializable - public void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - throw new ArgumentNullException(nameof(info)); - Contract.EndContractBlock(); - - MemberInfoSerializationHolder.GetSerializationInfo( - info, - Name, - ReflectedTypeInternal, - null, - MemberTypes.Event); - } - #endregion - - #region EventInfo Overrides - public override MethodInfo[] GetOtherMethods(bool nonPublic) - { - List ret = new List(); - - if ((object)m_otherMethod == null) - return new MethodInfo[0]; - - for (int i = 0; i < m_otherMethod.Length; i++) - { - if (Associates.IncludeAccessor((MethodInfo)m_otherMethod[i], nonPublic)) - ret.Add(m_otherMethod[i]); - } - - return ret.ToArray(); - } - - public override MethodInfo GetAddMethod(bool nonPublic) - { - if (!Associates.IncludeAccessor(m_addMethod, nonPublic)) - return null; - - return m_addMethod; - } - - public override MethodInfo GetRemoveMethod(bool nonPublic) - { - if (!Associates.IncludeAccessor(m_removeMethod, nonPublic)) - return null; - - return m_removeMethod; - } - - public override MethodInfo GetRaiseMethod(bool nonPublic) - { - if (!Associates.IncludeAccessor(m_raiseMethod, nonPublic)) - return null; - - return m_raiseMethod; - } - - public override EventAttributes Attributes - { - get - { - return m_flags; - } - } - #endregion - } } diff --git a/src/coreclr/src/mscorlib/src/System/Reflection/FieldInfo.CoreCLR.cs b/src/coreclr/src/mscorlib/src/System/Reflection/FieldInfo.CoreCLR.cs new file mode 100644 index 0000000..e9515b1 --- /dev/null +++ b/src/coreclr/src/mscorlib/src/System/Reflection/FieldInfo.CoreCLR.cs @@ -0,0 +1,35 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Globalization; + +namespace System.Reflection +{ + public abstract partial class FieldInfo : MemberInfo + { + public static FieldInfo GetFieldFromHandle(RuntimeFieldHandle handle) + { + if (handle.IsNullHandle()) + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHandle"), nameof(handle)); + + FieldInfo f = RuntimeType.GetFieldInfo(handle.GetRuntimeFieldInfo()); + + Type declaringType = f.DeclaringType; + if (declaringType != null && declaringType.IsGenericType) + throw new ArgumentException(String.Format( + CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_FieldDeclaringTypeGeneric"), + f.Name, declaringType.GetGenericTypeDefinition())); + + return f; + } + + public static FieldInfo GetFieldFromHandle(RuntimeFieldHandle handle, RuntimeTypeHandle declaringType) + { + if (handle.IsNullHandle()) + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHandle")); + + return RuntimeType.GetFieldInfo(declaringType.GetRuntimeType(), handle.GetRuntimeFieldInfo()); + } + } +} diff --git a/src/coreclr/src/mscorlib/src/System/Reflection/FieldInfo.cs b/src/coreclr/src/mscorlib/src/System/Reflection/FieldInfo.cs index 511fef5..c16df73 100644 --- a/src/coreclr/src/mscorlib/src/System/Reflection/FieldInfo.cs +++ b/src/coreclr/src/mscorlib/src/System/Reflection/FieldInfo.cs @@ -2,52 +2,14 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// +using System.Diagnostics; +using System.Globalization; namespace System.Reflection { - using System; - using System.Collections.Generic; - using System.Diagnostics; - using System.Diagnostics.Contracts; - using System.Globalization; - using System.Runtime; - using System.Runtime.CompilerServices; - using System.Runtime.ConstrainedExecution; - using System.Runtime.InteropServices; - using System.Runtime.Serialization; - using System.Threading; - using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; - [Serializable] - public abstract class FieldInfo : MemberInfo + public abstract partial class FieldInfo : MemberInfo { - #region Static Members - public static FieldInfo GetFieldFromHandle(RuntimeFieldHandle handle) - { - if (handle.IsNullHandle()) - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHandle"), nameof(handle)); - - FieldInfo f = RuntimeType.GetFieldInfo(handle.GetRuntimeFieldInfo()); - - Type declaringType = f.DeclaringType; - if (declaringType != null && declaringType.IsGenericType) - throw new ArgumentException(String.Format( - CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_FieldDeclaringTypeGeneric"), - f.Name, declaringType.GetGenericTypeDefinition())); - - return f; - } - - public static FieldInfo GetFieldFromHandle(RuntimeFieldHandle handle, RuntimeTypeHandle declaringType) - { - if (handle.IsNullHandle()) - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHandle")); - - return RuntimeType.GetFieldInfo(declaringType.GetRuntimeType(), handle.GetRuntimeFieldInfo()); - } - #endregion - #region Constructor protected FieldInfo() { } #endregion @@ -176,640 +138,4 @@ namespace System.Reflection #endregion } - - [Serializable] - internal abstract class RuntimeFieldInfo : FieldInfo, ISerializable - { - #region Private Data Members - private BindingFlags m_bindingFlags; - protected RuntimeTypeCache m_reflectedTypeCache; - protected RuntimeType m_declaringType; - #endregion - - #region Constructor - protected RuntimeFieldInfo() - { - // Used for dummy head node during population - } - protected RuntimeFieldInfo(RuntimeTypeCache reflectedTypeCache, RuntimeType declaringType, BindingFlags bindingFlags) - { - m_bindingFlags = bindingFlags; - m_declaringType = declaringType; - m_reflectedTypeCache = reflectedTypeCache; - } - #endregion - - #region NonPublic Members - internal BindingFlags BindingFlags { get { return m_bindingFlags; } } - private RuntimeType ReflectedTypeInternal - { - get - { - return m_reflectedTypeCache.GetRuntimeType(); - } - } - - internal RuntimeType GetDeclaringTypeInternal() - { - return m_declaringType; - } - - internal RuntimeType GetRuntimeType() { return m_declaringType; } - internal abstract RuntimeModule GetRuntimeModule(); - #endregion - - #region MemberInfo Overrides - public override MemberTypes MemberType { get { return MemberTypes.Field; } } - public override Type ReflectedType - { - get - { - return m_reflectedTypeCache.IsGlobal ? null : ReflectedTypeInternal; - } - } - - public override Type DeclaringType - { - get - { - return m_reflectedTypeCache.IsGlobal ? null : m_declaringType; - } - } - - public override Module Module { get { return GetRuntimeModule(); } } - #endregion - - #region Object Overrides - public unsafe override String ToString() - { - return FieldType.FormatTypeName() + " " + Name; - } - #endregion - - #region ICustomAttributeProvider - public override Object[] GetCustomAttributes(bool inherit) - { - return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); - } - - public override Object[] GetCustomAttributes(Type attributeType, bool inherit) - { - if (attributeType == null) - throw new ArgumentNullException(nameof(attributeType)); - Contract.EndContractBlock(); - - RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; - - if (attributeRuntimeType == null) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType)); - - return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType); - } - - public override bool IsDefined(Type attributeType, bool inherit) - { - if (attributeType == null) - throw new ArgumentNullException(nameof(attributeType)); - Contract.EndContractBlock(); - - RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; - - if (attributeRuntimeType == null) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType)); - - return CustomAttribute.IsDefined(this, attributeRuntimeType); - } - - public override IList GetCustomAttributesData() - { - return CustomAttributeData.GetCustomAttributesInternal(this); - } - #endregion - - #region FieldInfo Overrides - // All implemented on derived classes - #endregion - - #region ISerializable Implementation - public void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - throw new ArgumentNullException(nameof(info)); - Contract.EndContractBlock(); - MemberInfoSerializationHolder.GetSerializationInfo( - info, - Name, - ReflectedTypeInternal, - ToString(), - MemberTypes.Field); - } - #endregion - } - - [Serializable] - internal unsafe sealed class RtFieldInfo : RuntimeFieldInfo, IRuntimeFieldInfo - { - #region FCalls - [MethodImplAttribute(MethodImplOptions.InternalCall)] - static private extern void PerformVisibilityCheckOnField(IntPtr field, Object target, RuntimeType declaringType, FieldAttributes attr, uint invocationFlags); - #endregion - - #region Private Data Members - // agressive caching - private IntPtr m_fieldHandle; - private FieldAttributes m_fieldAttributes; - // lazy caching - private string m_name; - private RuntimeType m_fieldType; - private INVOCATION_FLAGS m_invocationFlags; - - internal INVOCATION_FLAGS InvocationFlags - { - get - { - if ((m_invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0) - { - Type declaringType = DeclaringType; - bool fIsReflectionOnlyType = (declaringType is ReflectionOnlyType); - - INVOCATION_FLAGS invocationFlags = 0; - - // first take care of all the NO_INVOKE cases - if ( - (declaringType != null && declaringType.ContainsGenericParameters) || - (declaringType == null && Module.Assembly.ReflectionOnly) || - (fIsReflectionOnlyType) - ) - { - invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE; - } - - // If the invocationFlags are still 0, then - // this should be an usable field, determine the other flags - if (invocationFlags == 0) - { - if ((m_fieldAttributes & FieldAttributes.InitOnly) != (FieldAttributes)0) - invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD; - - if ((m_fieldAttributes & FieldAttributes.HasFieldRVA) != (FieldAttributes)0) - invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD; - - // A public field is inaccesible to Transparent code if the field is Critical. - bool needsTransparencySecurityCheck = IsSecurityCritical && !IsSecuritySafeCritical; - bool needsVisibilitySecurityCheck = ((m_fieldAttributes & FieldAttributes.FieldAccessMask) != FieldAttributes.Public) || - (declaringType != null && declaringType.NeedsReflectionSecurityCheck); - if (needsTransparencySecurityCheck || needsVisibilitySecurityCheck) - invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY; - - // find out if the field type is one of the following: Primitive, Enum or Pointer - Type fieldType = FieldType; - if (fieldType.IsPointer || fieldType.IsEnum || fieldType.IsPrimitive) - invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_FIELD_SPECIAL_CAST; - } - - // must be last to avoid threading problems - m_invocationFlags = invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED; - } - - return m_invocationFlags; - } - } - #endregion - - private RuntimeAssembly GetRuntimeAssembly() { return m_declaringType.GetRuntimeAssembly(); } - - #region Constructor - internal RtFieldInfo( - RuntimeFieldHandleInternal handle, RuntimeType declaringType, RuntimeTypeCache reflectedTypeCache, BindingFlags bindingFlags) - : base(reflectedTypeCache, declaringType, bindingFlags) - { - m_fieldHandle = handle.Value; - m_fieldAttributes = RuntimeFieldHandle.GetAttributes(handle); - } - #endregion - - #region Private Members - RuntimeFieldHandleInternal IRuntimeFieldInfo.Value - { - get - { - return new RuntimeFieldHandleInternal(m_fieldHandle); - } - } - - #endregion - - #region Internal Members - internal void CheckConsistency(Object target) - { - // only test instance fields - if ((m_fieldAttributes & FieldAttributes.Static) != FieldAttributes.Static) - { - if (!m_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, m_declaringType, target.GetType())); - } - } - } - } - - internal override bool CacheEquals(object o) - { - RtFieldInfo m = o as RtFieldInfo; - - if ((object)m == null) - return false; - - return m.m_fieldHandle == m_fieldHandle; - } - - [DebuggerStepThroughAttribute] - [Diagnostics.DebuggerHidden] - internal void InternalSetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture, ref StackCrawlMark stackMark) - { - INVOCATION_FLAGS invocationFlags = InvocationFlags; - RuntimeType declaringType = DeclaringType as RuntimeType; - - if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE) != 0) - { - if (declaringType != null && declaringType.ContainsGenericParameters) - throw new InvalidOperationException(Environment.GetResourceString("Arg_UnboundGenField")); - - if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType) - throw new InvalidOperationException(Environment.GetResourceString("Arg_ReflectionOnlyField")); - - throw new FieldAccessException(); - } - - CheckConsistency(obj); - - RuntimeType fieldType = (RuntimeType)FieldType; - value = fieldType.CheckValue(value, binder, culture, invokeAttr); - - #region Security Check - if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD | INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY)) != 0) - PerformVisibilityCheckOnField(m_fieldHandle, obj, m_declaringType, m_fieldAttributes, (uint)m_invocationFlags); - #endregion - - bool domainInitialized = false; - if (declaringType == null) - { - RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, null, ref domainInitialized); - } - else - { - domainInitialized = declaringType.DomainInitialized; - RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, declaringType, ref domainInitialized); - declaringType.DomainInitialized = domainInitialized; - } - } - - // UnsafeSetValue doesn't perform any consistency or visibility check. - // It is the caller's responsibility to ensure the operation is safe. - // When the caller needs to perform visibility checks they should call - // InternalSetValue() instead. When the caller needs to perform - // consistency checks they should call CheckConsistency() before - // calling this method. - [DebuggerStepThroughAttribute] - [Diagnostics.DebuggerHidden] - internal void UnsafeSetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) - { - RuntimeType declaringType = DeclaringType as RuntimeType; - RuntimeType fieldType = (RuntimeType)FieldType; - value = fieldType.CheckValue(value, binder, culture, invokeAttr); - - bool domainInitialized = false; - if (declaringType == null) - { - RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, null, ref domainInitialized); - } - else - { - domainInitialized = declaringType.DomainInitialized; - RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, declaringType, ref domainInitialized); - declaringType.DomainInitialized = domainInitialized; - } - } - - [DebuggerStepThroughAttribute] - [Diagnostics.DebuggerHidden] - internal Object InternalGetValue(Object obj, ref StackCrawlMark stackMark) - { - INVOCATION_FLAGS invocationFlags = InvocationFlags; - RuntimeType declaringType = DeclaringType as RuntimeType; - - if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE) != 0) - { - if (declaringType != null && DeclaringType.ContainsGenericParameters) - throw new InvalidOperationException(Environment.GetResourceString("Arg_UnboundGenField")); - - if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType) - throw new InvalidOperationException(Environment.GetResourceString("Arg_ReflectionOnlyField")); - - throw new FieldAccessException(); - } - - CheckConsistency(obj); - - RuntimeType fieldType = (RuntimeType)FieldType; - if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) != 0) - PerformVisibilityCheckOnField(m_fieldHandle, obj, m_declaringType, m_fieldAttributes, (uint)(m_invocationFlags & ~INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD)); - - return UnsafeGetValue(obj); - } - - // UnsafeGetValue doesn't perform any consistency or visibility check. - // It is the caller's responsibility to ensure the operation is safe. - // When the caller needs to perform visibility checks they should call - // InternalGetValue() instead. When the caller needs to perform - // consistency checks they should call CheckConsistency() before - // calling this method. - [DebuggerStepThroughAttribute] - [Diagnostics.DebuggerHidden] - internal Object UnsafeGetValue(Object obj) - { - RuntimeType declaringType = DeclaringType as RuntimeType; - - RuntimeType fieldType = (RuntimeType)FieldType; - - bool domainInitialized = false; - if (declaringType == null) - { - return RuntimeFieldHandle.GetValue(this, obj, fieldType, null, ref domainInitialized); - } - else - { - domainInitialized = declaringType.DomainInitialized; - object retVal = RuntimeFieldHandle.GetValue(this, obj, fieldType, declaringType, ref domainInitialized); - declaringType.DomainInitialized = domainInitialized; - return retVal; - } - } - - #endregion - - #region MemberInfo Overrides - public override String Name - { - get - { - if (m_name == null) - m_name = RuntimeFieldHandle.GetName(this); - - return m_name; - } - } - - internal String FullName - { - get - { - return String.Format("{0}.{1}", DeclaringType.FullName, Name); - } - } - - public override int MetadataToken - { - get { return RuntimeFieldHandle.GetToken(this); } - } - - internal override RuntimeModule GetRuntimeModule() - { - return RuntimeTypeHandle.GetModule(RuntimeFieldHandle.GetApproxDeclaringType(this)); - } - - #endregion - - #region FieldInfo Overrides - public override Object GetValue(Object obj) - { - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - return InternalGetValue(obj, ref stackMark); - } - - public override object GetRawConstantValue() { throw new InvalidOperationException(); } - - [DebuggerStepThroughAttribute] - [Diagnostics.DebuggerHidden] - public override Object GetValueDirect(TypedReference obj) - { - if (obj.IsNull) - throw new ArgumentException(Environment.GetResourceString("Arg_TypedReference_Null")); - Contract.EndContractBlock(); - - unsafe - { - // Passing TypedReference by reference is easier to make correct in native code - return RuntimeFieldHandle.GetValueDirect(this, (RuntimeType)FieldType, &obj, (RuntimeType)DeclaringType); - } - } - - [DebuggerStepThroughAttribute] - [Diagnostics.DebuggerHidden] - public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) - { - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - InternalSetValue(obj, value, invokeAttr, binder, culture, ref stackMark); - } - - [DebuggerStepThroughAttribute] - [Diagnostics.DebuggerHidden] - public override void SetValueDirect(TypedReference obj, Object value) - { - if (obj.IsNull) - throw new ArgumentException(Environment.GetResourceString("Arg_TypedReference_Null")); - Contract.EndContractBlock(); - - unsafe - { - // Passing TypedReference by reference is easier to make correct in native code - RuntimeFieldHandle.SetValueDirect(this, (RuntimeType)FieldType, &obj, value, (RuntimeType)DeclaringType); - } - } - - public override RuntimeFieldHandle FieldHandle - { - get - { - Type declaringType = DeclaringType; - if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType) - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAllowedInReflectionOnly")); - return new RuntimeFieldHandle(this); - } - } - - internal IntPtr GetFieldHandle() - { - return m_fieldHandle; - } - - public override FieldAttributes Attributes - { - get - { - return m_fieldAttributes; - } - } - - public override Type FieldType - { - get - { - if (m_fieldType == null) - m_fieldType = new Signature(this, m_declaringType).FieldType; - - return m_fieldType; - } - } - - public override Type[] GetRequiredCustomModifiers() - { - return new Signature(this, m_declaringType).GetCustomModifiers(1, true); - } - - public override Type[] GetOptionalCustomModifiers() - { - return new Signature(this, m_declaringType).GetCustomModifiers(1, false); - } - - #endregion - } - - [Serializable] - internal sealed unsafe class MdFieldInfo : RuntimeFieldInfo, ISerializable - { - #region Private Data Members - private int m_tkField; - private string m_name; - private RuntimeType m_fieldType; - private FieldAttributes m_fieldAttributes; - #endregion - - #region Constructor - internal MdFieldInfo( - int tkField, FieldAttributes fieldAttributes, RuntimeTypeHandle declaringTypeHandle, RuntimeTypeCache reflectedTypeCache, BindingFlags bindingFlags) - : base(reflectedTypeCache, declaringTypeHandle.GetRuntimeType(), bindingFlags) - { - m_tkField = tkField; - m_name = null; - m_fieldAttributes = fieldAttributes; - } - #endregion - - #region Internal Members - internal override bool CacheEquals(object o) - { - MdFieldInfo m = o as MdFieldInfo; - - if ((object)m == null) - return false; - - return m.m_tkField == m_tkField && - m_declaringType.GetTypeHandleInternal().GetModuleHandle().Equals( - m.m_declaringType.GetTypeHandleInternal().GetModuleHandle()); - } - #endregion - - #region MemberInfo Overrides - public override String Name - { - get - { - if (m_name == null) - m_name = GetRuntimeModule().MetadataImport.GetName(m_tkField).ToString(); - - return m_name; - } - } - - public override int MetadataToken { get { return m_tkField; } } - internal override RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); } - #endregion - - #region FieldInfo Overrides - public override RuntimeFieldHandle FieldHandle { get { throw new NotSupportedException(); } } - public override FieldAttributes Attributes { get { return m_fieldAttributes; } } - - public override bool IsSecurityCritical { get { return DeclaringType.IsSecurityCritical; } } - public override bool IsSecuritySafeCritical { get { return DeclaringType.IsSecuritySafeCritical; } } - public override bool IsSecurityTransparent { get { return DeclaringType.IsSecurityTransparent; } } - - [DebuggerStepThroughAttribute] - [Diagnostics.DebuggerHidden] - public override Object GetValueDirect(TypedReference obj) - { - return GetValue(null); - } - - [DebuggerStepThroughAttribute] - [Diagnostics.DebuggerHidden] - public override void SetValueDirect(TypedReference obj, Object value) - { - throw new FieldAccessException(Environment.GetResourceString("Acc_ReadOnly")); - } - - [DebuggerStepThroughAttribute] - [Diagnostics.DebuggerHidden] - public unsafe override Object GetValue(Object obj) - { - return GetValue(false); - } - - public unsafe override Object GetRawConstantValue() { return GetValue(true); } - - private unsafe Object GetValue(bool raw) - { - // Cannot cache these because they could be user defined non-agile enumerations - - Object value = MdConstant.GetValue(GetRuntimeModule().MetadataImport, m_tkField, FieldType.GetTypeHandleInternal(), raw); - - if (value == DBNull.Value) - throw new NotSupportedException(Environment.GetResourceString("Arg_EnumLitValueNotFound")); - - return value; - } - - [DebuggerStepThroughAttribute] - [Diagnostics.DebuggerHidden] - public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) - { - throw new FieldAccessException(Environment.GetResourceString("Acc_ReadOnly")); - } - - public override Type FieldType - { - get - { - if (m_fieldType == null) - { - ConstArray fieldMarshal = GetRuntimeModule().MetadataImport.GetSigOfFieldDef(m_tkField); - - m_fieldType = new Signature(fieldMarshal.Signature.ToPointer(), - (int)fieldMarshal.Length, m_declaringType).FieldType; - } - - return m_fieldType; - } - } - - public override Type[] GetRequiredCustomModifiers() - { - return EmptyArray.Value; - } - - public override Type[] GetOptionalCustomModifiers() - { - return EmptyArray.Value; - } - - #endregion - } } diff --git a/src/coreclr/src/mscorlib/src/System/Reflection/ImageFileMachine.cs b/src/coreclr/src/mscorlib/src/System/Reflection/ImageFileMachine.cs new file mode 100644 index 0000000..5e3deac --- /dev/null +++ b/src/coreclr/src/mscorlib/src/System/Reflection/ImageFileMachine.cs @@ -0,0 +1,15 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace System.Reflection +{ + [Serializable] + public enum ImageFileMachine + { + I386 = 0x014c, + IA64 = 0x0200, + AMD64 = 0x8664, + ARM = 0x01c4, + } +} diff --git a/src/coreclr/src/mscorlib/src/System/Reflection/MdFieldInfo.cs b/src/coreclr/src/mscorlib/src/System/Reflection/MdFieldInfo.cs new file mode 100644 index 0000000..994cdc6 --- /dev/null +++ b/src/coreclr/src/mscorlib/src/System/Reflection/MdFieldInfo.cs @@ -0,0 +1,141 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Diagnostics; +using System.Globalization; +using System.Runtime.Serialization; +using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; + +namespace System.Reflection +{ + [Serializable] + internal sealed unsafe class MdFieldInfo : RuntimeFieldInfo, ISerializable + { + #region Private Data Members + private int m_tkField; + private string m_name; + private RuntimeType m_fieldType; + private FieldAttributes m_fieldAttributes; + #endregion + + #region Constructor + internal MdFieldInfo( + int tkField, FieldAttributes fieldAttributes, RuntimeTypeHandle declaringTypeHandle, RuntimeTypeCache reflectedTypeCache, BindingFlags bindingFlags) + : base(reflectedTypeCache, declaringTypeHandle.GetRuntimeType(), bindingFlags) + { + m_tkField = tkField; + m_name = null; + m_fieldAttributes = fieldAttributes; + } + #endregion + + #region Internal Members + internal override bool CacheEquals(object o) + { + MdFieldInfo m = o as MdFieldInfo; + + if ((object)m == null) + return false; + + return m.m_tkField == m_tkField && + m_declaringType.GetTypeHandleInternal().GetModuleHandle().Equals( + m.m_declaringType.GetTypeHandleInternal().GetModuleHandle()); + } + #endregion + + #region MemberInfo Overrides + public override String Name + { + get + { + if (m_name == null) + m_name = GetRuntimeModule().MetadataImport.GetName(m_tkField).ToString(); + + return m_name; + } + } + + public override int MetadataToken { get { return m_tkField; } } + internal override RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); } + #endregion + + #region FieldInfo Overrides + public override RuntimeFieldHandle FieldHandle { get { throw new NotSupportedException(); } } + public override FieldAttributes Attributes { get { return m_fieldAttributes; } } + + public override bool IsSecurityCritical { get { return DeclaringType.IsSecurityCritical; } } + public override bool IsSecuritySafeCritical { get { return DeclaringType.IsSecuritySafeCritical; } } + public override bool IsSecurityTransparent { get { return DeclaringType.IsSecurityTransparent; } } + + [DebuggerStepThroughAttribute] + [Diagnostics.DebuggerHidden] + public override Object GetValueDirect(TypedReference obj) + { + return GetValue(null); + } + + [DebuggerStepThroughAttribute] + [Diagnostics.DebuggerHidden] + public override void SetValueDirect(TypedReference obj, Object value) + { + throw new FieldAccessException(Environment.GetResourceString("Acc_ReadOnly")); + } + + [DebuggerStepThroughAttribute] + [Diagnostics.DebuggerHidden] + public unsafe override Object GetValue(Object obj) + { + return GetValue(false); + } + + public unsafe override Object GetRawConstantValue() { return GetValue(true); } + + private unsafe Object GetValue(bool raw) + { + // Cannot cache these because they could be user defined non-agile enumerations + + Object value = MdConstant.GetValue(GetRuntimeModule().MetadataImport, m_tkField, FieldType.GetTypeHandleInternal(), raw); + + if (value == DBNull.Value) + throw new NotSupportedException(Environment.GetResourceString("Arg_EnumLitValueNotFound")); + + return value; + } + + [DebuggerStepThroughAttribute] + [Diagnostics.DebuggerHidden] + public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) + { + throw new FieldAccessException(Environment.GetResourceString("Acc_ReadOnly")); + } + + public override Type FieldType + { + get + { + if (m_fieldType == null) + { + ConstArray fieldMarshal = GetRuntimeModule().MetadataImport.GetSigOfFieldDef(m_tkField); + + m_fieldType = new Signature(fieldMarshal.Signature.ToPointer(), + (int)fieldMarshal.Length, m_declaringType).FieldType; + } + + return m_fieldType; + } + } + + public override Type[] GetRequiredCustomModifiers() + { + return EmptyArray.Value; + } + + public override Type[] GetOptionalCustomModifiers() + { + return EmptyArray.Value; + } + + #endregion + } +} diff --git a/src/coreclr/src/mscorlib/src/System/Reflection/MethodInfo.cs b/src/coreclr/src/mscorlib/src/System/Reflection/MethodInfo.cs index 2205dda..807be0f 100644 --- a/src/coreclr/src/mscorlib/src/System/Reflection/MethodInfo.cs +++ b/src/coreclr/src/mscorlib/src/System/Reflection/MethodInfo.cs @@ -2,26 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - namespace System.Reflection { - using System; - using System.Collections.Generic; - using System.Diagnostics; - using System.Diagnostics.Contracts; - using System.Globalization; - using System.Runtime; - using System.Runtime.InteropServices; - using System.Runtime.ConstrainedExecution; - using System.Runtime.Serialization; - using System.Security; - using System.Text; - using System.Threading; - using MemberListType = System.RuntimeType.MemberListType; - using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; - using System.Runtime.CompilerServices; - [Serializable] public abstract class MethodInfo : MethodBase { @@ -80,798 +62,4 @@ namespace System.Reflection public virtual Delegate CreateDelegate(Type delegateType, Object target) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); } #endregion } - - [Serializable] - internal sealed class RuntimeMethodInfo : MethodInfo, ISerializable, IRuntimeMethodInfo - { - #region Private Data Members - private IntPtr m_handle; - private RuntimeTypeCache m_reflectedTypeCache; - private string m_name; - private string m_toString; - private ParameterInfo[] m_parameters; - private ParameterInfo m_returnParameter; - private BindingFlags m_bindingFlags; - private MethodAttributes m_methodAttributes; - private Signature m_signature; - private RuntimeType m_declaringType; - private object m_keepalive; - private INVOCATION_FLAGS m_invocationFlags; - - internal INVOCATION_FLAGS InvocationFlags - { - get - { - if ((m_invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0) - { - INVOCATION_FLAGS invocationFlags = INVOCATION_FLAGS.INVOCATION_FLAGS_UNKNOWN; - - Type declaringType = DeclaringType; - - // - // first take care of all the NO_INVOKE cases. - if (ContainsGenericParameters || - ReturnType.IsByRef || - (declaringType != null && declaringType.ContainsGenericParameters) || - ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) || - ((Attributes & MethodAttributes.RequireSecObject) == MethodAttributes.RequireSecObject)) - { - // We don't need other flags if this method cannot be invoked - invocationFlags = INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE; - } - else - { - // this should be an invocable method, determine the other flags that participate in invocation - invocationFlags = RuntimeMethodHandle.GetSecurityFlags(this); - - if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) == 0) - { - if ((Attributes & MethodAttributes.MemberAccessMask) != MethodAttributes.Public || - (declaringType != null && declaringType.NeedsReflectionSecurityCheck)) - { - // If method is non-public, or declaring type is not visible - invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY; - } - else if (IsGenericMethod) - { - Type[] genericArguments = GetGenericArguments(); - - for (int i = 0; i < genericArguments.Length; i++) - { - if (genericArguments[i].NeedsReflectionSecurityCheck) - { - invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY; - break; - } - } - } - } - } - - m_invocationFlags = invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED; - } - - return m_invocationFlags; - } - } - #endregion - - #region Constructor - internal RuntimeMethodInfo( - RuntimeMethodHandleInternal handle, RuntimeType declaringType, - RuntimeTypeCache reflectedTypeCache, MethodAttributes methodAttributes, BindingFlags bindingFlags, object keepalive) - { - Contract.Ensures(!m_handle.IsNull()); - - Debug.Assert(!handle.IsNullHandle()); - Debug.Assert(methodAttributes == RuntimeMethodHandle.GetAttributes(handle)); - - m_bindingFlags = bindingFlags; - m_declaringType = declaringType; - m_keepalive = keepalive; - m_handle = handle.Value; - m_reflectedTypeCache = reflectedTypeCache; - m_methodAttributes = methodAttributes; - } - #endregion - - #region Private Methods - RuntimeMethodHandleInternal IRuntimeMethodInfo.Value - { - get - { - return new RuntimeMethodHandleInternal(m_handle); - } - } - - private RuntimeType ReflectedTypeInternal - { - get - { - return m_reflectedTypeCache.GetRuntimeType(); - } - } - - private ParameterInfo[] FetchNonReturnParameters() - { - if (m_parameters == null) - m_parameters = RuntimeParameterInfo.GetParameters(this, this, Signature); - - return m_parameters; - } - - private ParameterInfo FetchReturnParameter() - { - if (m_returnParameter == null) - m_returnParameter = RuntimeParameterInfo.GetReturnParameter(this, this, Signature); - - return m_returnParameter; - } - #endregion - - #region Internal Members - internal override string FormatNameAndSig(bool serialization) - { - // Serialization uses ToString to resolve MethodInfo overloads. - StringBuilder sbName = new StringBuilder(Name); - - // serialization == true: use unambiguous (except for assembly name) type names to distinguish between overloads. - // serialization == false: use basic format to maintain backward compatibility of MethodInfo.ToString(). - TypeNameFormatFlags format = serialization ? TypeNameFormatFlags.FormatSerialization : TypeNameFormatFlags.FormatBasic; - - if (IsGenericMethod) - sbName.Append(RuntimeMethodHandle.ConstructInstantiation(this, format)); - - sbName.Append("("); - sbName.Append(ConstructParameters(GetParameterTypes(), CallingConvention, serialization)); - sbName.Append(")"); - - return sbName.ToString(); - } - - internal override bool CacheEquals(object o) - { - RuntimeMethodInfo m = o as RuntimeMethodInfo; - - if ((object)m == null) - return false; - - return m.m_handle == m_handle; - } - - internal Signature Signature - { - get - { - if (m_signature == null) - m_signature = new Signature(this, m_declaringType); - - return m_signature; - } - } - - internal BindingFlags BindingFlags { get { return m_bindingFlags; } } - - internal RuntimeMethodInfo GetParentDefinition() - { - if (!IsVirtual || m_declaringType.IsInterface) - return null; - - RuntimeType parent = (RuntimeType)m_declaringType.BaseType; - - if (parent == null) - return null; - - int slot = RuntimeMethodHandle.GetSlot(this); - - if (RuntimeTypeHandle.GetNumVirtuals(parent) <= slot) - return null; - - return (RuntimeMethodInfo)RuntimeType.GetMethodBase(parent, RuntimeTypeHandle.GetMethodAt(parent, slot)); - } - - // Unlike DeclaringType, this will return a valid type even for global methods - internal RuntimeType GetDeclaringTypeInternal() - { - return m_declaringType; - } - - #endregion - - #region Object Overrides - public override String ToString() - { - if (m_toString == null) - m_toString = ReturnType.FormatTypeName() + " " + FormatNameAndSig(); - - return m_toString; - } - - public override int GetHashCode() - { - // See RuntimeMethodInfo.Equals() below. - if (IsGenericMethod) - return ValueType.GetHashCodeOfPtr(m_handle); - else - return base.GetHashCode(); - } - - public override bool Equals(object obj) - { - if (!IsGenericMethod) - return obj == (object)this; - - // We cannot do simple object identity comparisons for generic methods. - // Equals will be called in CerHashTable when RuntimeType+RuntimeTypeCache.GetGenericMethodInfo() - // retrieve items from and insert items into s_methodInstantiations which is a CerHashtable. - - RuntimeMethodInfo mi = obj as RuntimeMethodInfo; - - if (mi == null || !mi.IsGenericMethod) - return false; - - // now we know that both operands are generic methods - - IRuntimeMethodInfo handle1 = RuntimeMethodHandle.StripMethodInstantiation(this); - IRuntimeMethodInfo handle2 = RuntimeMethodHandle.StripMethodInstantiation(mi); - if (handle1.Value.Value != handle2.Value.Value) - return false; - - Type[] lhs = GetGenericArguments(); - Type[] rhs = mi.GetGenericArguments(); - - if (lhs.Length != rhs.Length) - return false; - - for (int i = 0; i < lhs.Length; i++) - { - if (lhs[i] != rhs[i]) - return false; - } - - if (DeclaringType != mi.DeclaringType) - return false; - - if (ReflectedType != mi.ReflectedType) - return false; - - return true; - } - #endregion - - #region ICustomAttributeProvider - public override Object[] GetCustomAttributes(bool inherit) - { - return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType as RuntimeType, inherit); - } - - public override Object[] GetCustomAttributes(Type attributeType, bool inherit) - { - if (attributeType == null) - throw new ArgumentNullException(nameof(attributeType)); - Contract.EndContractBlock(); - - RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; - - if (attributeRuntimeType == null) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType)); - - return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType, inherit); - } - - public override bool IsDefined(Type attributeType, bool inherit) - { - if (attributeType == null) - throw new ArgumentNullException(nameof(attributeType)); - Contract.EndContractBlock(); - - RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; - - if (attributeRuntimeType == null) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType)); - - return CustomAttribute.IsDefined(this, attributeRuntimeType, inherit); - } - - public override IList GetCustomAttributesData() - { - return CustomAttributeData.GetCustomAttributesInternal(this); - } - #endregion - - #region MemberInfo Overrides - public override String Name - { - get - { - if (m_name == null) - m_name = RuntimeMethodHandle.GetName(this); - - return m_name; - } - } - - public override Type DeclaringType - { - get - { - if (m_reflectedTypeCache.IsGlobal) - return null; - - return m_declaringType; - } - } - - public override Type ReflectedType - { - get - { - if (m_reflectedTypeCache.IsGlobal) - return null; - - return m_reflectedTypeCache.GetRuntimeType(); - } - } - - public override MemberTypes MemberType { get { return MemberTypes.Method; } } - public override int MetadataToken - { - get { return RuntimeMethodHandle.GetMethodDef(this); } - } - public override Module Module { get { return GetRuntimeModule(); } } - internal RuntimeType GetRuntimeType() { return m_declaringType; } - internal RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); } - internal RuntimeAssembly GetRuntimeAssembly() { return GetRuntimeModule().GetRuntimeAssembly(); } - - public override bool IsSecurityCritical - { - get { return true; } - } - public override bool IsSecuritySafeCritical - { - get { return false; } - } - public override bool IsSecurityTransparent - { - get { return false; } - } - #endregion - - #region MethodBase Overrides - internal override ParameterInfo[] GetParametersNoCopy() - { - FetchNonReturnParameters(); - - return m_parameters; - } - - [System.Diagnostics.Contracts.Pure] - public override ParameterInfo[] GetParameters() - { - FetchNonReturnParameters(); - - if (m_parameters.Length == 0) - return m_parameters; - - ParameterInfo[] ret = new ParameterInfo[m_parameters.Length]; - - Array.Copy(m_parameters, ret, m_parameters.Length); - - return ret; - } - - public override MethodImplAttributes GetMethodImplementationFlags() - { - return RuntimeMethodHandle.GetImplAttributes(this); - } - - public override RuntimeMethodHandle MethodHandle - { - get - { - Type declaringType = DeclaringType; - if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType) - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAllowedInReflectionOnly")); - return new RuntimeMethodHandle(this); - } - } - - public override MethodAttributes Attributes { get { return m_methodAttributes; } } - - public override CallingConventions CallingConvention - { - get - { - return Signature.CallingConvention; - } - } - - public override MethodBody GetMethodBody() - { - MethodBody mb = RuntimeMethodHandle.GetMethodBody(this, ReflectedTypeInternal); - if (mb != null) - mb.m_methodBase = this; - return mb; - } - #endregion - - #region Invocation Logic(On MemberBase) - private void CheckConsistency(Object target) - { - // only test instance methods - if ((m_methodAttributes & MethodAttributes.Static) != MethodAttributes.Static) - { - if (!m_declaringType.IsInstanceOfType(target)) - { - if (target == null) - throw new TargetException(Environment.GetResourceString("RFLCT.Targ_StatMethReqTarg")); - else - throw new TargetException(Environment.GetResourceString("RFLCT.Targ_ITargMismatch")); - } - } - } - - private void ThrowNoInvokeException() - { - // method is ReflectionOnly - Type declaringType = DeclaringType; - if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType) - { - throw new InvalidOperationException(Environment.GetResourceString("Arg_ReflectionOnlyInvoke")); - } - // method is on a class that contains stack pointers - else if ((InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS) != 0) - { - throw new NotSupportedException(); - } - // method is vararg - else if ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) - { - throw new NotSupportedException(); - } - // method is generic or on a generic class - else if (DeclaringType.ContainsGenericParameters || ContainsGenericParameters) - { - throw new InvalidOperationException(Environment.GetResourceString("Arg_UnboundGenParam")); - } - // method is abstract class - else if (IsAbstract) - { - throw new MemberAccessException(); - } - // ByRef return are not allowed in reflection - else if (ReturnType.IsByRef) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_ByRefReturn")); - } - - throw new TargetException(); - } - - [DebuggerStepThroughAttribute] - [Diagnostics.DebuggerHidden] - [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod - public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) - { - object[] arguments = InvokeArgumentsCheck(obj, invokeAttr, binder, parameters, culture); - - return UnsafeInvokeInternal(obj, parameters, arguments); - } - - [DebuggerStepThroughAttribute] - [Diagnostics.DebuggerHidden] - internal object UnsafeInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) - { - object[] arguments = InvokeArgumentsCheck(obj, invokeAttr, binder, parameters, culture); - - return UnsafeInvokeInternal(obj, parameters, arguments); - } - - [DebuggerStepThroughAttribute] - [Diagnostics.DebuggerHidden] - private object UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) - { - if (arguments == null || arguments.Length == 0) - return RuntimeMethodHandle.InvokeMethod(obj, null, Signature, false); - else - { - Object retValue = RuntimeMethodHandle.InvokeMethod(obj, arguments, Signature, false); - - // copy out. This should be made only if ByRef are present. - for (int index = 0; index < arguments.Length; index++) - parameters[index] = arguments[index]; - - return retValue; - } - } - - [DebuggerStepThroughAttribute] - [Diagnostics.DebuggerHidden] - private object[] InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) - { - Signature sig = Signature; - - // get the signature - int formalCount = sig.Arguments.Length; - int actualCount = (parameters != null) ? parameters.Length : 0; - - INVOCATION_FLAGS invocationFlags = InvocationFlags; - - // INVOCATION_FLAGS_CONTAINS_STACK_POINTERS means that the struct (either the declaring type or the return type) - // contains pointers that point to the stack. This is either a ByRef or a TypedReference. These structs cannot - // be boxed and thus cannot be invoked through reflection which only deals with boxed value type objects. - if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE | INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS)) != 0) - ThrowNoInvokeException(); - - // check basic method consistency. This call will throw if there are problems in the target/method relationship - CheckConsistency(obj); - - if (formalCount != actualCount) - throw new TargetParameterCountException(Environment.GetResourceString("Arg_ParmCnt")); - - if (actualCount != 0) - return CheckArguments(parameters, binder, invokeAttr, culture, sig); - else - return null; - } - - #endregion - - #region MethodInfo Overrides - public override Type ReturnType - { - get { return Signature.ReturnType; } - } - - public override ICustomAttributeProvider ReturnTypeCustomAttributes - { - get { return ReturnParameter; } - } - - public override ParameterInfo ReturnParameter - { - get - { - Contract.Ensures(m_returnParameter != null); - - FetchReturnParameter(); - return m_returnParameter as ParameterInfo; - } - } - - public override MethodInfo GetBaseDefinition() - { - if (!IsVirtual || IsStatic || m_declaringType == null || m_declaringType.IsInterface) - return this; - - int slot = RuntimeMethodHandle.GetSlot(this); - RuntimeType declaringType = (RuntimeType)DeclaringType; - RuntimeType baseDeclaringType = declaringType; - RuntimeMethodHandleInternal baseMethodHandle = new RuntimeMethodHandleInternal(); - - do - { - int cVtblSlots = RuntimeTypeHandle.GetNumVirtuals(declaringType); - - if (cVtblSlots <= slot) - break; - - baseMethodHandle = RuntimeTypeHandle.GetMethodAt(declaringType, slot); - baseDeclaringType = declaringType; - - declaringType = (RuntimeType)declaringType.BaseType; - } while (declaringType != null); - - return (MethodInfo)RuntimeType.GetMethodBase(baseDeclaringType, baseMethodHandle); - } - - public override Delegate CreateDelegate(Type delegateType) - { - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - - // This API existed in v1/v1.1 and only expected to create closed - // instance delegates. Constrain the call to BindToMethodInfo to - // open delegates only for backwards compatibility. But we'll allow - // relaxed signature checking and open static delegates because - // there's no ambiguity there (the caller would have to explicitly - // pass us a static method or a method with a non-exact signature - // and the only change in behavior from v1.1 there is that we won't - // fail the call). - return CreateDelegateInternal( - delegateType, - null, - DelegateBindingFlags.OpenDelegateOnly | DelegateBindingFlags.RelaxedSignature, - ref stackMark); - } - - public override Delegate CreateDelegate(Type delegateType, Object target) - { - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - - // This API is new in Whidbey and allows the full range of delegate - // flexability (open or closed delegates binding to static or - // instance methods with relaxed signature checking). The delegate - // can also be closed over null. There's no ambiguity with all these - // options since the caller is providing us a specific MethodInfo. - return CreateDelegateInternal( - delegateType, - target, - DelegateBindingFlags.RelaxedSignature, - ref stackMark); - } - - private Delegate CreateDelegateInternal(Type delegateType, Object firstArgument, DelegateBindingFlags bindingFlags, ref StackCrawlMark stackMark) - { - // Validate the parameters. - if (delegateType == null) - throw new ArgumentNullException(nameof(delegateType)); - Contract.EndContractBlock(); - - RuntimeType rtType = delegateType as RuntimeType; - if (rtType == null) - throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(delegateType)); - - if (!rtType.IsDelegate()) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), nameof(delegateType)); - - Delegate d = Delegate.CreateDelegateInternal(rtType, this, firstArgument, bindingFlags, ref stackMark); - if (d == null) - { - throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTargMeth")); - } - - return d; - } - - #endregion - - #region Generics - public override MethodInfo MakeGenericMethod(params Type[] methodInstantiation) - { - if (methodInstantiation == null) - throw new ArgumentNullException(nameof(methodInstantiation)); - Contract.EndContractBlock(); - - RuntimeType[] methodInstantionRuntimeType = new RuntimeType[methodInstantiation.Length]; - - if (!IsGenericMethodDefinition) - throw new InvalidOperationException( - Environment.GetResourceString("Arg_NotGenericMethodDefinition", this)); - - for (int i = 0; i < methodInstantiation.Length; i++) - { - Type methodInstantiationElem = methodInstantiation[i]; - - if (methodInstantiationElem == null) - throw new ArgumentNullException(); - - RuntimeType rtMethodInstantiationElem = methodInstantiationElem as RuntimeType; - - if (rtMethodInstantiationElem == null) - { - Type[] methodInstantiationCopy = new Type[methodInstantiation.Length]; - for (int iCopy = 0; iCopy < methodInstantiation.Length; iCopy++) - methodInstantiationCopy[iCopy] = methodInstantiation[iCopy]; - methodInstantiation = methodInstantiationCopy; - return System.Reflection.Emit.MethodBuilderInstantiation.MakeGenericMethod(this, methodInstantiation); - } - - methodInstantionRuntimeType[i] = rtMethodInstantiationElem; - } - - RuntimeType[] genericParameters = GetGenericArgumentsInternal(); - - RuntimeType.SanityCheckGenericArguments(methodInstantionRuntimeType, genericParameters); - - MethodInfo ret = null; - - try - { - ret = RuntimeType.GetMethodBase(ReflectedTypeInternal, - RuntimeMethodHandle.GetStubIfNeeded(new RuntimeMethodHandleInternal(m_handle), m_declaringType, methodInstantionRuntimeType)) as MethodInfo; - } - catch (VerificationException e) - { - RuntimeType.ValidateGenericArguments(this, methodInstantionRuntimeType, e); - throw; - } - - return ret; - } - - internal RuntimeType[] GetGenericArgumentsInternal() - { - return RuntimeMethodHandle.GetMethodInstantiationInternal(this); - } - - public override Type[] GetGenericArguments() - { - Type[] types = RuntimeMethodHandle.GetMethodInstantiationPublic(this); - - if (types == null) - { - types = EmptyArray.Value; - } - return types; - } - - public override MethodInfo GetGenericMethodDefinition() - { - if (!IsGenericMethod) - throw new InvalidOperationException(); - Contract.EndContractBlock(); - - return RuntimeType.GetMethodBase(m_declaringType, RuntimeMethodHandle.StripMethodInstantiation(this)) as MethodInfo; - } - - public override bool IsGenericMethod - { - get { return RuntimeMethodHandle.HasMethodInstantiation(this); } - } - - public override bool IsGenericMethodDefinition - { - get { return RuntimeMethodHandle.IsGenericMethodDefinition(this); } - } - - public override bool ContainsGenericParameters - { - get - { - if (DeclaringType != null && DeclaringType.ContainsGenericParameters) - return true; - - if (!IsGenericMethod) - return false; - - Type[] pis = GetGenericArguments(); - for (int i = 0; i < pis.Length; i++) - { - if (pis[i].ContainsGenericParameters) - return true; - } - - return false; - } - } - #endregion - - #region ISerializable Implementation - public void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - throw new ArgumentNullException(nameof(info)); - Contract.EndContractBlock(); - - if (m_reflectedTypeCache.IsGlobal) - throw new NotSupportedException(Environment.GetResourceString("NotSupported_GlobalMethodSerialization")); - - MemberInfoSerializationHolder.GetSerializationInfo( - info, - Name, - ReflectedTypeInternal, - ToString(), - SerializationToString(), - MemberTypes.Method, - IsGenericMethod & !IsGenericMethodDefinition ? GetGenericArguments() : null); - } - - internal string SerializationToString() - { - return ReturnType.FormatTypeName(true) + " " + FormatNameAndSig(true); - } - #endregion - - #region Legacy Internal - internal static MethodBase InternalGetCurrentMethod(ref StackCrawlMark stackMark) - { - IRuntimeMethodInfo method = RuntimeMethodHandle.GetCurrentMethod(ref stackMark); - - if (method == null) - return null; - - return RuntimeType.GetMethodBase(method); - } - #endregion - } } diff --git a/src/coreclr/src/mscorlib/src/System/Reflection/Module.cs b/src/coreclr/src/mscorlib/src/System/Reflection/Module.cs index 79ab705..b38fb25 100644 --- a/src/coreclr/src/mscorlib/src/System/Reflection/Module.cs +++ b/src/coreclr/src/mscorlib/src/System/Reflection/Module.cs @@ -2,55 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -//////////////////////////////////////////////////////////////////////////////// -// +using System.Runtime.Serialization; +using System.Collections.Generic; +using System.Diagnostics.Contracts; namespace System.Reflection { - using System; - using System.Diagnostics.SymbolStore; - using System.Runtime.Remoting; - using System.Runtime.InteropServices; - using System.Runtime.Serialization; - using System.Collections; - using System.Collections.Generic; - using System.Threading; - using System.Runtime.CompilerServices; - using System.Security; - using System.IO; - using System.Globalization; - using System.Runtime.Versioning; - using System.Diagnostics.Contracts; - - [Serializable] - [Flags] - public enum PortableExecutableKinds - { - NotAPortableExecutableImage = 0x0, - - ILOnly = 0x1, - - Required32Bit = 0x2, - - PE32Plus = 0x4, - - Unmanaged32Bit = 0x8, - - Preferred32Bit = 0x10, - } - - [Serializable] - public enum ImageFileMachine - { - I386 = 0x014c, - - IA64 = 0x0200, - - AMD64 = 0x8664, - - ARM = 0x01c4, - } - [Serializable] public abstract class Module : ISerializable, ICustomAttributeProvider { @@ -531,593 +488,4 @@ namespace System.Reflection } #endregion } - - [Serializable] - internal class RuntimeModule : Module - { - internal RuntimeModule() { throw new NotSupportedException(); } - - #region FCalls - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - private extern static void GetType(RuntimeModule module, String className, bool ignoreCase, bool throwOnError, ObjectHandleOnStack type, ObjectHandleOnStack keepAlive); - - [DllImport(JitHelpers.QCall)] - [SuppressUnmanagedCodeSecurity] - private static extern bool nIsTransientInternal(RuntimeModule module); - - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - private extern static void GetScopeName(RuntimeModule module, StringHandleOnStack retString); - - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - private extern static void GetFullyQualifiedName(RuntimeModule module, StringHandleOnStack retString); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private extern static RuntimeType[] GetTypes(RuntimeModule module); - - internal RuntimeType[] GetDefinedTypes() - { - return GetTypes(GetNativeHandle()); - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private extern static bool IsResource(RuntimeModule module); - #endregion - - #region Module overrides - private static RuntimeTypeHandle[] ConvertToTypeHandleArray(Type[] genericArguments) - { - if (genericArguments == null) - return null; - - int size = genericArguments.Length; - RuntimeTypeHandle[] typeHandleArgs = new RuntimeTypeHandle[size]; - for (int i = 0; i < size; i++) - { - Type typeArg = genericArguments[i]; - if (typeArg == null) - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidGenericInstArray")); - typeArg = typeArg.UnderlyingSystemType; - if (typeArg == null) - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidGenericInstArray")); - if (!(typeArg is RuntimeType)) - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidGenericInstArray")); - typeHandleArgs[i] = typeArg.GetTypeHandleInternal(); - } - return typeHandleArgs; - } - - public override byte[] ResolveSignature(int metadataToken) - { - MetadataToken tk = new MetadataToken(metadataToken); - - if (!MetadataImport.IsValidToken(tk)) - throw new ArgumentOutOfRangeException(nameof(metadataToken), - Environment.GetResourceString("Argument_InvalidToken", tk, this)); - - if (!tk.IsMemberRef && !tk.IsMethodDef && !tk.IsTypeSpec && !tk.IsSignature && !tk.IsFieldDef) - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidToken", tk, this), - nameof(metadataToken)); - - ConstArray signature; - if (tk.IsMemberRef) - signature = MetadataImport.GetMemberRefProps(metadataToken); - else - signature = MetadataImport.GetSignatureFromToken(metadataToken); - - byte[] sig = new byte[signature.Length]; - - for (int i = 0; i < signature.Length; i++) - sig[i] = signature[i]; - - return sig; - } - - public override MethodBase ResolveMethod(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) - { - MetadataToken tk = new MetadataToken(metadataToken); - - if (!MetadataImport.IsValidToken(tk)) - throw new ArgumentOutOfRangeException(nameof(metadataToken), - Environment.GetResourceString("Argument_InvalidToken", tk, this)); - - RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments); - RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments); - - try - { - if (!tk.IsMethodDef && !tk.IsMethodSpec) - { - if (!tk.IsMemberRef) - throw new ArgumentException(Environment.GetResourceString("Argument_ResolveMethod", tk, this), - nameof(metadataToken)); - - unsafe - { - ConstArray sig = MetadataImport.GetMemberRefProps(tk); - - if (*(MdSigCallingConvention*)sig.Signature.ToPointer() == MdSigCallingConvention.Field) - throw new ArgumentException(Environment.GetResourceString("Argument_ResolveMethod", tk, this), - nameof(metadataToken)); - } - } - - IRuntimeMethodInfo methodHandle = ModuleHandle.ResolveMethodHandleInternal(GetNativeHandle(), tk, typeArgs, methodArgs); - Type declaringType = RuntimeMethodHandle.GetDeclaringType(methodHandle); - - if (declaringType.IsGenericType || declaringType.IsArray) - { - MetadataToken tkDeclaringType = new MetadataToken(MetadataImport.GetParentToken(tk)); - - if (tk.IsMethodSpec) - tkDeclaringType = new MetadataToken(MetadataImport.GetParentToken(tkDeclaringType)); - - declaringType = ResolveType(tkDeclaringType, genericTypeArguments, genericMethodArguments); - } - - return System.RuntimeType.GetMethodBase(declaringType as RuntimeType, methodHandle); - } - catch (BadImageFormatException e) - { - throw new ArgumentException(Environment.GetResourceString("Argument_BadImageFormatExceptionResolve"), e); - } - } - - private FieldInfo ResolveLiteralField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) - { - MetadataToken tk = new MetadataToken(metadataToken); - - if (!MetadataImport.IsValidToken(tk) || !tk.IsFieldDef) - throw new ArgumentOutOfRangeException(nameof(metadataToken), - String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_InvalidToken", tk, this))); - - int tkDeclaringType; - string fieldName; - - fieldName = MetadataImport.GetName(tk).ToString(); - tkDeclaringType = MetadataImport.GetParentToken(tk); - - Type declaringType = ResolveType(tkDeclaringType, genericTypeArguments, genericMethodArguments); - - declaringType.GetFields(); - - try - { - return declaringType.GetField(fieldName, - BindingFlags.Static | BindingFlags.Instance | - BindingFlags.Public | BindingFlags.NonPublic | - BindingFlags.DeclaredOnly); - } - catch - { - throw new ArgumentException(Environment.GetResourceString("Argument_ResolveField", tk, this), nameof(metadataToken)); - } - } - - public override FieldInfo ResolveField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) - { - MetadataToken tk = new MetadataToken(metadataToken); - - if (!MetadataImport.IsValidToken(tk)) - throw new ArgumentOutOfRangeException(nameof(metadataToken), - Environment.GetResourceString("Argument_InvalidToken", tk, this)); - - RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments); - RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments); - - try - { - IRuntimeFieldInfo fieldHandle = null; - - if (!tk.IsFieldDef) - { - if (!tk.IsMemberRef) - throw new ArgumentException(Environment.GetResourceString("Argument_ResolveField", tk, this), - nameof(metadataToken)); - - unsafe - { - ConstArray sig = MetadataImport.GetMemberRefProps(tk); - - if (*(MdSigCallingConvention*)sig.Signature.ToPointer() != MdSigCallingConvention.Field) - throw new ArgumentException(Environment.GetResourceString("Argument_ResolveField", tk, this), - nameof(metadataToken)); - } - - fieldHandle = ModuleHandle.ResolveFieldHandleInternal(GetNativeHandle(), tk, typeArgs, methodArgs); - } - - fieldHandle = ModuleHandle.ResolveFieldHandleInternal(GetNativeHandle(), metadataToken, typeArgs, methodArgs); - RuntimeType declaringType = RuntimeFieldHandle.GetApproxDeclaringType(fieldHandle.Value); - - if (declaringType.IsGenericType || declaringType.IsArray) - { - int tkDeclaringType = ModuleHandle.GetMetadataImport(GetNativeHandle()).GetParentToken(metadataToken); - declaringType = (RuntimeType)ResolveType(tkDeclaringType, genericTypeArguments, genericMethodArguments); - } - - return System.RuntimeType.GetFieldInfo(declaringType, fieldHandle); - } - catch (MissingFieldException) - { - return ResolveLiteralField(tk, genericTypeArguments, genericMethodArguments); - } - catch (BadImageFormatException e) - { - throw new ArgumentException(Environment.GetResourceString("Argument_BadImageFormatExceptionResolve"), e); - } - } - - public override Type ResolveType(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) - { - MetadataToken tk = new MetadataToken(metadataToken); - - if (tk.IsGlobalTypeDefToken) - throw new ArgumentException(Environment.GetResourceString("Argument_ResolveModuleType", tk), nameof(metadataToken)); - - if (!MetadataImport.IsValidToken(tk)) - throw new ArgumentOutOfRangeException(nameof(metadataToken), - Environment.GetResourceString("Argument_InvalidToken", tk, this)); - - if (!tk.IsTypeDef && !tk.IsTypeSpec && !tk.IsTypeRef) - throw new ArgumentException(Environment.GetResourceString("Argument_ResolveType", tk, this), nameof(metadataToken)); - - RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments); - RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments); - - try - { - Type t = GetModuleHandle().ResolveTypeHandle(metadataToken, typeArgs, methodArgs).GetRuntimeType(); - - if (t == null) - throw new ArgumentException(Environment.GetResourceString("Argument_ResolveType", tk, this), nameof(metadataToken)); - - return t; - } - catch (BadImageFormatException e) - { - throw new ArgumentException(Environment.GetResourceString("Argument_BadImageFormatExceptionResolve"), e); - } - } - - public override MemberInfo ResolveMember(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) - { - MetadataToken tk = new MetadataToken(metadataToken); - - if (tk.IsProperty) - throw new ArgumentException(Environment.GetResourceString("InvalidOperation_PropertyInfoNotAvailable")); - - if (tk.IsEvent) - throw new ArgumentException(Environment.GetResourceString("InvalidOperation_EventInfoNotAvailable")); - - if (tk.IsMethodSpec || tk.IsMethodDef) - return ResolveMethod(metadataToken, genericTypeArguments, genericMethodArguments); - - if (tk.IsFieldDef) - return ResolveField(metadataToken, genericTypeArguments, genericMethodArguments); - - if (tk.IsTypeRef || tk.IsTypeDef || tk.IsTypeSpec) - return ResolveType(metadataToken, genericTypeArguments, genericMethodArguments); - - if (tk.IsMemberRef) - { - if (!MetadataImport.IsValidToken(tk)) - throw new ArgumentOutOfRangeException(nameof(metadataToken), - Environment.GetResourceString("Argument_InvalidToken", tk, this)); - - ConstArray sig = MetadataImport.GetMemberRefProps(tk); - - unsafe - { - if (*(MdSigCallingConvention*)sig.Signature.ToPointer() == MdSigCallingConvention.Field) - { - return ResolveField(tk, genericTypeArguments, genericMethodArguments); - } - else - { - return ResolveMethod(tk, genericTypeArguments, genericMethodArguments); - } - } - } - - throw new ArgumentException(Environment.GetResourceString("Argument_ResolveMember", tk, this), - nameof(metadataToken)); - } - - public override string ResolveString(int metadataToken) - { - MetadataToken tk = new MetadataToken(metadataToken); - if (!tk.IsString) - throw new ArgumentException( - String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_ResolveString"), metadataToken, ToString())); - - if (!MetadataImport.IsValidToken(tk)) - throw new ArgumentOutOfRangeException(nameof(metadataToken), - String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_InvalidToken", tk, this))); - - string str = MetadataImport.GetUserString(metadataToken); - - if (str == null) - throw new ArgumentException( - String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_ResolveString"), metadataToken, ToString())); - - return str; - } - - public override void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine) - { - ModuleHandle.GetPEKind(GetNativeHandle(), out peKind, out machine); - } - - public override int MDStreamVersion - { - get - { - return ModuleHandle.GetMDStreamVersion(GetNativeHandle()); - } - } - #endregion - - #region Data Members -#pragma warning disable 169 - // If you add any data members, you need to update the native declaration ReflectModuleBaseObject. - private RuntimeType m_runtimeType; - private RuntimeAssembly m_runtimeAssembly; - private IntPtr m_pRefClass; - private IntPtr m_pData; - private IntPtr m_pGlobals; - private IntPtr m_pFields; -#pragma warning restore 169 - #endregion - - #region Protected Virtuals - protected override MethodInfo GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder, - CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) - { - return GetMethodInternal(name, bindingAttr, binder, callConvention, types, modifiers); - } - - internal MethodInfo GetMethodInternal(String name, BindingFlags bindingAttr, Binder binder, - CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) - { - if (RuntimeType == null) - return null; - - if (types == null) - { - return RuntimeType.GetMethod(name, bindingAttr); - } - else - { - return RuntimeType.GetMethod(name, bindingAttr, binder, callConvention, types, modifiers); - } - } - #endregion - - #region Internal Members - internal RuntimeType RuntimeType - { - get - { - if (m_runtimeType == null) - m_runtimeType = ModuleHandle.GetModuleType(GetNativeHandle()); - - return m_runtimeType; - } - } - - internal bool IsTransientInternal() - { - return RuntimeModule.nIsTransientInternal(this.GetNativeHandle()); - } - - internal MetadataImport MetadataImport - { - get - { - unsafe - { - return ModuleHandle.GetMetadataImport(GetNativeHandle()); - } - } - } - #endregion - - #region ICustomAttributeProvider Members - public override Object[] GetCustomAttributes(bool inherit) - { - return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); - } - - public override Object[] GetCustomAttributes(Type attributeType, bool inherit) - { - if (attributeType == null) - throw new ArgumentNullException(nameof(attributeType)); - Contract.EndContractBlock(); - - RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; - - if (attributeRuntimeType == null) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType)); - - return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType); - } - - public override bool IsDefined(Type attributeType, bool inherit) - { - if (attributeType == null) - throw new ArgumentNullException(nameof(attributeType)); - Contract.EndContractBlock(); - - RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; - - if (attributeRuntimeType == null) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType)); - - return CustomAttribute.IsDefined(this, attributeRuntimeType); - } - - public override IList GetCustomAttributesData() - { - return CustomAttributeData.GetCustomAttributesInternal(this); - } - #endregion - - #region Public Virtuals - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new ArgumentNullException(nameof(info)); - } - Contract.EndContractBlock(); - UnitySerializationHolder.GetUnitySerializationInfo(info, UnitySerializationHolder.ModuleUnity, this.ScopeName, this.GetRuntimeAssembly()); - } - - public override Type GetType(String className, bool throwOnError, bool ignoreCase) - { - // throw on null strings regardless of the value of "throwOnError" - if (className == null) - throw new ArgumentNullException(nameof(className)); - - RuntimeType retType = null; - Object keepAlive = null; - GetType(GetNativeHandle(), className, throwOnError, ignoreCase, JitHelpers.GetObjectHandleOnStack(ref retType), JitHelpers.GetObjectHandleOnStack(ref keepAlive)); - GC.KeepAlive(keepAlive); - return retType; - } - - internal string GetFullyQualifiedName() - { - String fullyQualifiedName = null; - GetFullyQualifiedName(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref fullyQualifiedName)); - return fullyQualifiedName; - } - - public override String FullyQualifiedName - { - get - { - return GetFullyQualifiedName(); - } - } - - public override Type[] GetTypes() - { - return GetTypes(GetNativeHandle()); - } - - #endregion - - #region Public Members - - public override Guid ModuleVersionId - { - get - { - unsafe - { - Guid mvid; - MetadataImport.GetScopeProps(out mvid); - return mvid; - } - } - } - - public override int MetadataToken - { - get - { - return ModuleHandle.GetToken(GetNativeHandle()); - } - } - - public override bool IsResource() - { - return IsResource(GetNativeHandle()); - } - - public override FieldInfo[] GetFields(BindingFlags bindingFlags) - { - if (RuntimeType == null) - return new FieldInfo[0]; - - return RuntimeType.GetFields(bindingFlags); - } - - public override FieldInfo GetField(String name, BindingFlags bindingAttr) - { - if (name == null) - throw new ArgumentNullException(nameof(name)); - - if (RuntimeType == null) - return null; - - return RuntimeType.GetField(name, bindingAttr); - } - - public override MethodInfo[] GetMethods(BindingFlags bindingFlags) - { - if (RuntimeType == null) - return new MethodInfo[0]; - - return RuntimeType.GetMethods(bindingFlags); - } - - public override String ScopeName - { - get - { - string scopeName = null; - GetScopeName(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref scopeName)); - return scopeName; - } - } - - public override String Name - { - get - { - String s = GetFullyQualifiedName(); - -#if !FEATURE_PAL - int i = s.LastIndexOf('\\'); -#else - int i = s.LastIndexOf(System.IO.Path.DirectorySeparatorChar); -#endif - if (i == -1) - return s; - - return s.Substring(i + 1); - } - } - - public override Assembly Assembly - { - [Pure] - get - { - return GetRuntimeAssembly(); - } - } - - internal RuntimeAssembly GetRuntimeAssembly() - { - return m_runtimeAssembly; - } - - - internal override ModuleHandle GetModuleHandle() - { - return new ModuleHandle(this); - } - - internal RuntimeModule GetNativeHandle() - { - return this; - } - #endregion - } } diff --git a/src/coreclr/src/mscorlib/src/System/Reflection/ModuleResolveEventHandler.cs b/src/coreclr/src/mscorlib/src/System/Reflection/ModuleResolveEventHandler.cs new file mode 100644 index 0000000..31cc799 --- /dev/null +++ b/src/coreclr/src/mscorlib/src/System/Reflection/ModuleResolveEventHandler.cs @@ -0,0 +1,9 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace System.Reflection +{ + [Serializable] + public delegate Module ModuleResolveEventHandler(Object sender, ResolveEventArgs e); +} diff --git a/src/coreclr/src/mscorlib/src/System/Reflection/ParameterInfo.cs b/src/coreclr/src/mscorlib/src/System/Reflection/ParameterInfo.cs index 373201f..01fe2e0 100644 --- a/src/coreclr/src/mscorlib/src/System/Reflection/ParameterInfo.cs +++ b/src/coreclr/src/mscorlib/src/System/Reflection/ParameterInfo.cs @@ -2,20 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// +using System.Collections.Generic; +using System.Diagnostics.Contracts; +using System.Runtime.Serialization; namespace System.Reflection { - using System; - using System.Collections.Generic; - using System.Diagnostics; - using System.Diagnostics.Contracts; - using System.Runtime.InteropServices; - using System.Runtime.Serialization; - using System.Runtime.CompilerServices; - using System.Threading; - using MdToken = System.Reflection.MetadataToken; - [Serializable] public class ParameterInfo : ICustomAttributeProvider, IObjectReference { @@ -229,507 +221,4 @@ namespace System.Reflection } #endregion } - - [Serializable] - internal unsafe sealed class RuntimeParameterInfo : ParameterInfo, ISerializable - { - #region Static Members - internal unsafe static ParameterInfo[] GetParameters(IRuntimeMethodInfo method, MemberInfo member, Signature sig) - { - Debug.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo); - - ParameterInfo dummy; - return GetParameters(method, member, sig, out dummy, false); - } - - internal unsafe static ParameterInfo GetReturnParameter(IRuntimeMethodInfo method, MemberInfo member, Signature sig) - { - Debug.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo); - - ParameterInfo returnParameter; - GetParameters(method, member, sig, out returnParameter, true); - return returnParameter; - } - - internal unsafe static ParameterInfo[] GetParameters( - IRuntimeMethodInfo methodHandle, MemberInfo member, Signature sig, out ParameterInfo returnParameter, bool fetchReturnParameter) - { - returnParameter = null; - int sigArgCount = sig.Arguments.Length; - ParameterInfo[] args = fetchReturnParameter ? null : new ParameterInfo[sigArgCount]; - - int tkMethodDef = RuntimeMethodHandle.GetMethodDef(methodHandle); - int cParamDefs = 0; - - // Not all methods have tokens. Arrays, pointers and byRef types do not have tokens as they - // are generated on the fly by the runtime. - if (!MdToken.IsNullToken(tkMethodDef)) - { - MetadataImport scope = RuntimeTypeHandle.GetMetadataImport(RuntimeMethodHandle.GetDeclaringType(methodHandle)); - - MetadataEnumResult tkParamDefs; - scope.EnumParams(tkMethodDef, out tkParamDefs); - - cParamDefs = tkParamDefs.Length; - - // Not all parameters have tokens. Parameters may have no token - // if they have no name and no attributes. - if (cParamDefs > sigArgCount + 1 /* return type */) - throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ParameterSignatureMismatch")); - - for (int i = 0; i < cParamDefs; i++) - { - #region Populate ParameterInfos - ParameterAttributes attr; - int position, tkParamDef = tkParamDefs[i]; - - scope.GetParamDefProps(tkParamDef, out position, out attr); - - position--; - - if (fetchReturnParameter == true && position == -1) - { - // more than one return parameter? - if (returnParameter != null) - throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ParameterSignatureMismatch")); - - returnParameter = new RuntimeParameterInfo(sig, scope, tkParamDef, position, attr, member); - } - else if (fetchReturnParameter == false && position >= 0) - { - // position beyong sigArgCount? - if (position >= sigArgCount) - throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ParameterSignatureMismatch")); - - args[position] = new RuntimeParameterInfo(sig, scope, tkParamDef, position, attr, member); - } - #endregion - } - } - - // Fill in empty ParameterInfos for those without tokens - if (fetchReturnParameter) - { - if (returnParameter == null) - { - returnParameter = new RuntimeParameterInfo(sig, MetadataImport.EmptyImport, 0, -1, (ParameterAttributes)0, member); - } - } - else - { - if (cParamDefs < args.Length + 1) - { - for (int i = 0; i < args.Length; i++) - { - if (args[i] != null) - continue; - - args[i] = new RuntimeParameterInfo(sig, MetadataImport.EmptyImport, 0, i, (ParameterAttributes)0, member); - } - } - } - - return args; - } - #endregion - - #region Private Statics - private static readonly Type s_DecimalConstantAttributeType = typeof(DecimalConstantAttribute); - private static readonly Type s_CustomConstantAttributeType = typeof(CustomConstantAttribute); - #endregion - - #region Private Data Members - // These are new in Whidbey, so we cannot serialize them directly or we break backwards compatibility. - [NonSerialized] - private int m_tkParamDef; - [NonSerialized] - private MetadataImport m_scope; - [NonSerialized] - private Signature m_signature; - [NonSerialized] - private volatile bool m_nameIsCached = false; - [NonSerialized] - private readonly bool m_noMetadata = false; - [NonSerialized] - private bool m_noDefaultValue = false; - [NonSerialized] - private MethodBase m_originalMember = null; - #endregion - - #region Internal Properties - internal MethodBase DefiningMethod - { - get - { - MethodBase result = m_originalMember != null ? m_originalMember : MemberImpl as MethodBase; - Debug.Assert(result != null); - return result; - } - } - #endregion - - #region VTS magic to serialize/deserialized to/from pre-Whidbey endpoints. - public void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - throw new ArgumentNullException(nameof(info)); - Contract.EndContractBlock(); - - // We could be serializing for consumption by a pre-Whidbey - // endpoint. Therefore we set up all the serialized fields to look - // just like a v1.0/v1.1 instance. - - // Need to set the type to ParameterInfo so that pre-Whidbey and Whidbey code - // can deserialize this. This is also why we cannot simply use [OnSerializing]. - info.SetType(typeof(ParameterInfo)); - - // Use the properties intead of the fields in case the fields haven't been et - // _importer, bExtraConstChecked, and m_cachedData don't need to be set - - // Now set the legacy fields that the current implementation doesn't - // use any more. Note that _importer is a raw pointer that should - // never have been serialized in V1. We set it to zero here; if the - // deserializer uses it (by calling GetCustomAttributes() on this - // instance) they'll AV, but at least it will be a well defined - // exception and not a random AV. - - info.AddValue("AttrsImpl", Attributes); - info.AddValue("ClassImpl", ParameterType); - info.AddValue("DefaultValueImpl", DefaultValue); - info.AddValue("MemberImpl", Member); - info.AddValue("NameImpl", Name); - info.AddValue("PositionImpl", Position); - info.AddValue("_token", m_tkParamDef); - } - #endregion - - #region Constructor - // used by RuntimePropertyInfo - internal RuntimeParameterInfo(RuntimeParameterInfo accessor, RuntimePropertyInfo property) - : this(accessor, (MemberInfo)property) - { - m_signature = property.Signature; - } - - private RuntimeParameterInfo(RuntimeParameterInfo accessor, MemberInfo member) - { - // Change ownership - MemberImpl = member; - - // The original owner should always be a method, because this method is only used to - // change the owner from a method to a property. - m_originalMember = accessor.MemberImpl as MethodBase; - Debug.Assert(m_originalMember != null); - - // Populate all the caches -- we inherit this behavior from RTM - NameImpl = accessor.Name; - m_nameIsCached = true; - ClassImpl = accessor.ParameterType; - PositionImpl = accessor.Position; - AttrsImpl = accessor.Attributes; - - // Strictly speeking, property's don't contain paramter tokens - // However we need this to make ca's work... oh well... - m_tkParamDef = MdToken.IsNullToken(accessor.MetadataToken) ? (int)MetadataTokenType.ParamDef : accessor.MetadataToken; - m_scope = accessor.m_scope; - } - - private RuntimeParameterInfo( - Signature signature, MetadataImport scope, int tkParamDef, - int position, ParameterAttributes attributes, MemberInfo member) - { - Contract.Requires(member != null); - Debug.Assert(MdToken.IsNullToken(tkParamDef) == scope.Equals(MetadataImport.EmptyImport)); - Debug.Assert(MdToken.IsNullToken(tkParamDef) || MdToken.IsTokenOfType(tkParamDef, MetadataTokenType.ParamDef)); - - PositionImpl = position; - MemberImpl = member; - m_signature = signature; - m_tkParamDef = MdToken.IsNullToken(tkParamDef) ? (int)MetadataTokenType.ParamDef : tkParamDef; - m_scope = scope; - AttrsImpl = attributes; - - ClassImpl = null; - NameImpl = null; - } - - // ctor for no metadata MethodInfo in the DynamicMethod and RuntimeMethodInfo cases - internal RuntimeParameterInfo(MethodInfo owner, String name, Type parameterType, int position) - { - MemberImpl = owner; - NameImpl = name; - m_nameIsCached = true; - m_noMetadata = true; - ClassImpl = parameterType; - PositionImpl = position; - AttrsImpl = ParameterAttributes.None; - m_tkParamDef = (int)MetadataTokenType.ParamDef; - m_scope = MetadataImport.EmptyImport; - } - #endregion - - #region Public Methods - public override Type ParameterType - { - get - { - // only instance of ParameterInfo has ClassImpl, all its subclasses don't - if (ClassImpl == null) - { - RuntimeType parameterType; - if (PositionImpl == -1) - parameterType = m_signature.ReturnType; - else - parameterType = m_signature.Arguments[PositionImpl]; - - Debug.Assert(parameterType != null); - // different thread could only write ClassImpl to the same value, so a race condition is not a problem here - ClassImpl = parameterType; - } - - return ClassImpl; - } - } - - public override String Name - { - get - { - if (!m_nameIsCached) - { - if (!MdToken.IsNullToken(m_tkParamDef)) - { - string name; - name = m_scope.GetName(m_tkParamDef).ToString(); - NameImpl = name; - } - - // other threads could only write it to true, so a race condition is OK - // this field is volatile, so the write ordering is guaranteed - m_nameIsCached = true; - } - - // name may be null - return NameImpl; - } - } - - public override bool HasDefaultValue - { - get - { - if (m_noMetadata || m_noDefaultValue) - return false; - - object defaultValue = GetDefaultValueInternal(false); - - return (defaultValue != DBNull.Value); - } - } - - public override Object DefaultValue { get { return GetDefaultValue(false); } } - public override Object RawDefaultValue { get { return GetDefaultValue(true); } } - - private Object GetDefaultValue(bool raw) - { - // OLD COMMENT (Is this even true?) - // Cannot cache because default value could be non-agile user defined enumeration. - // OLD COMMENT ends - if (m_noMetadata) - return null; - - // for dynamic method we pretend to have cached the value so we do not go to metadata - object defaultValue = GetDefaultValueInternal(raw); - - if (defaultValue == DBNull.Value) - { - #region Handle case if no default value was found - if (IsOptional) - { - // If the argument is marked as optional then the default value is Missing.Value. - defaultValue = Type.Missing; - } - #endregion - } - - return defaultValue; - } - - // returns DBNull.Value if the parameter doesn't have a default value - private Object GetDefaultValueInternal(bool raw) - { - Debug.Assert(!m_noMetadata); - - if (m_noDefaultValue) - return DBNull.Value; - - object defaultValue = null; - - // Why check the parameter type only for DateTime and only for the ctor arguments? - // No check on the parameter type is done for named args and for Decimal. - - // We should move this after MdToken.IsNullToken(m_tkParamDef) and combine it - // with the other custom attribute logic. But will that be a breaking change? - // For a DateTime parameter on which both an md constant and a ca constant are set, - // which one should win? - if (ParameterType == typeof(DateTime)) - { - if (raw) - { - CustomAttributeTypedArgument value = - CustomAttributeData.Filter( - CustomAttributeData.GetCustomAttributes(this), typeof(DateTimeConstantAttribute), 0); - - if (value.ArgumentType != null) - return new DateTime((long)value.Value); - } - else - { - object[] dt = GetCustomAttributes(typeof(DateTimeConstantAttribute), false); - if (dt != null && dt.Length != 0) - return ((DateTimeConstantAttribute)dt[0]).Value; - } - } - - #region Look for a default value in metadata - if (!MdToken.IsNullToken(m_tkParamDef)) - { - // This will return DBNull.Value if no constant value is defined on m_tkParamDef in the metadata. - defaultValue = MdConstant.GetValue(m_scope, m_tkParamDef, ParameterType.GetTypeHandleInternal(), raw); - } - #endregion - - if (defaultValue == DBNull.Value) - { - #region Look for a default value in the custom attributes - if (raw) - { - foreach (CustomAttributeData attr in CustomAttributeData.GetCustomAttributes(this)) - { - Type attrType = attr.Constructor.DeclaringType; - - if (attrType == typeof(DateTimeConstantAttribute)) - { - defaultValue = DateTimeConstantAttribute.GetRawDateTimeConstant(attr); - } - else if (attrType == typeof(DecimalConstantAttribute)) - { - defaultValue = DecimalConstantAttribute.GetRawDecimalConstant(attr); - } - else if (attrType.IsSubclassOf(s_CustomConstantAttributeType)) - { - defaultValue = CustomConstantAttribute.GetRawConstant(attr); - } - } - } - else - { - Object[] CustomAttrs = GetCustomAttributes(s_CustomConstantAttributeType, false); - if (CustomAttrs.Length != 0) - { - defaultValue = ((CustomConstantAttribute)CustomAttrs[0]).Value; - } - else - { - CustomAttrs = GetCustomAttributes(s_DecimalConstantAttributeType, false); - if (CustomAttrs.Length != 0) - { - defaultValue = ((DecimalConstantAttribute)CustomAttrs[0]).Value; - } - } - } - #endregion - } - - if (defaultValue == DBNull.Value) - m_noDefaultValue = true; - - return defaultValue; - } - - internal RuntimeModule GetRuntimeModule() - { - RuntimeMethodInfo method = Member as RuntimeMethodInfo; - RuntimeConstructorInfo constructor = Member as RuntimeConstructorInfo; - RuntimePropertyInfo property = Member as RuntimePropertyInfo; - - if (method != null) - return method.GetRuntimeModule(); - else if (constructor != null) - return constructor.GetRuntimeModule(); - else if (property != null) - return property.GetRuntimeModule(); - else - return null; - } - - public override int MetadataToken - { - get - { - return m_tkParamDef; - } - } - - public override Type[] GetRequiredCustomModifiers() - { - return m_signature.GetCustomModifiers(PositionImpl + 1, true); - } - - public override Type[] GetOptionalCustomModifiers() - { - return m_signature.GetCustomModifiers(PositionImpl + 1, false); - } - - #endregion - - #region ICustomAttributeProvider - public override Object[] GetCustomAttributes(bool inherit) - { - if (MdToken.IsNullToken(m_tkParamDef)) - return EmptyArray.Value; - - return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); - } - - public override Object[] GetCustomAttributes(Type attributeType, bool inherit) - { - if (attributeType == null) - throw new ArgumentNullException(nameof(attributeType)); - Contract.EndContractBlock(); - - if (MdToken.IsNullToken(m_tkParamDef)) - return EmptyArray.Value; - - RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; - - if (attributeRuntimeType == null) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType)); - - return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType); - } - - public override bool IsDefined(Type attributeType, bool inherit) - { - if (attributeType == null) - throw new ArgumentNullException(nameof(attributeType)); - Contract.EndContractBlock(); - - if (MdToken.IsNullToken(m_tkParamDef)) - return false; - - RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; - - if (attributeRuntimeType == null) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType)); - - return CustomAttribute.IsDefined(this, attributeRuntimeType); - } - - public override IList GetCustomAttributesData() - { - return CustomAttributeData.GetCustomAttributesInternal(this); - } - #endregion - } } diff --git a/src/coreclr/src/mscorlib/src/System/Reflection/PortableExecutableKinds.cs b/src/coreclr/src/mscorlib/src/System/Reflection/PortableExecutableKinds.cs new file mode 100644 index 0000000..4c38c02 --- /dev/null +++ b/src/coreclr/src/mscorlib/src/System/Reflection/PortableExecutableKinds.cs @@ -0,0 +1,18 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace System.Reflection +{ + [Flags] + [Serializable] + public enum PortableExecutableKinds + { + NotAPortableExecutableImage = 0x0, + ILOnly = 0x1, + Required32Bit = 0x2, + PE32Plus = 0x4, + Unmanaged32Bit = 0x8, + Preferred32Bit = 0x10, + } +} diff --git a/src/coreclr/src/mscorlib/src/System/Reflection/PropertyInfo.cs b/src/coreclr/src/mscorlib/src/System/Reflection/PropertyInfo.cs index 3438b96..68811f8 100644 --- a/src/coreclr/src/mscorlib/src/System/Reflection/PropertyInfo.cs +++ b/src/coreclr/src/mscorlib/src/System/Reflection/PropertyInfo.cs @@ -2,22 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// +using System.Diagnostics; +using System.Globalization; namespace System.Reflection { - using System; - using System.Collections.Generic; - using System.Diagnostics; - using System.Diagnostics.Contracts; - using System.Globalization; - using System.Runtime; - using System.Runtime.ConstrainedExecution; - using System.Runtime.InteropServices; - using System.Runtime.Serialization; - using System.Text; - using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; - [Serializable] public abstract class PropertyInfo : MemberInfo { @@ -147,464 +136,4 @@ namespace System.Reflection public bool IsSpecialName { get { return (Attributes & PropertyAttributes.SpecialName) != 0; } } #endregion } - - [Serializable] - internal unsafe sealed class RuntimePropertyInfo : PropertyInfo, ISerializable - { - #region Private Data Members - private int m_token; - private string m_name; - private void* m_utf8name; - private PropertyAttributes m_flags; - private RuntimeTypeCache m_reflectedTypeCache; - private RuntimeMethodInfo m_getterMethod; - private RuntimeMethodInfo m_setterMethod; - private MethodInfo[] m_otherMethod; - private RuntimeType m_declaringType; - private BindingFlags m_bindingFlags; - private Signature m_signature; - private ParameterInfo[] m_parameters; - #endregion - - #region Constructor - internal RuntimePropertyInfo( - int tkProperty, RuntimeType declaredType, RuntimeTypeCache reflectedTypeCache, out bool isPrivate) - { - Contract.Requires(declaredType != null); - Contract.Requires(reflectedTypeCache != null); - Debug.Assert(!reflectedTypeCache.IsGlobal); - - MetadataImport scope = declaredType.GetRuntimeModule().MetadataImport; - - m_token = tkProperty; - m_reflectedTypeCache = reflectedTypeCache; - m_declaringType = declaredType; - - ConstArray sig; - scope.GetPropertyProps(tkProperty, out m_utf8name, out m_flags, out sig); - - RuntimeMethodInfo dummy; - Associates.AssignAssociates(scope, tkProperty, declaredType, reflectedTypeCache.GetRuntimeType(), - out dummy, out dummy, out dummy, - out m_getterMethod, out m_setterMethod, out m_otherMethod, - out isPrivate, out m_bindingFlags); - } - #endregion - - #region Internal Members - internal override bool CacheEquals(object o) - { - RuntimePropertyInfo m = o as RuntimePropertyInfo; - - if ((object)m == null) - return false; - - return m.m_token == m_token && - RuntimeTypeHandle.GetModule(m_declaringType).Equals( - RuntimeTypeHandle.GetModule(m.m_declaringType)); - } - - internal Signature Signature - { - get - { - if (m_signature == null) - { - PropertyAttributes flags; - ConstArray sig; - - void* name; - GetRuntimeModule().MetadataImport.GetPropertyProps( - m_token, out name, out flags, out sig); - - m_signature = new Signature(sig.Signature.ToPointer(), (int)sig.Length, m_declaringType); - } - - return m_signature; - } - } - internal bool EqualsSig(RuntimePropertyInfo target) - { - //@Asymmetry - Legacy policy is to remove duplicate properties, including hidden properties. - // The comparison is done by name and by sig. The EqualsSig comparison is expensive - // but forutnetly it is only called when an inherited property is hidden by name or - // when an interfaces declare properies with the same signature. - // Note that we intentionally don't resolve generic arguments so that we don't treat - // signatures that only match in certain instantiations as duplicates. This has the - // down side of treating overriding and overriden properties as different properties - // in some cases. But PopulateProperties in rttype.cs should have taken care of that - // by comparing VTable slots. - // - // Class C1(Of T, Y) - // Property Prop1(ByVal t1 As T) As Integer - // Get - // ... ... - // End Get - // End Property - // Property Prop1(ByVal y1 As Y) As Integer - // Get - // ... ... - // End Get - // End Property - // End Class - // - - Contract.Requires(Name.Equals(target.Name)); - Contract.Requires(this != target); - Contract.Requires(this.ReflectedType == target.ReflectedType); - - return Signature.CompareSig(this.Signature, target.Signature); - } - internal BindingFlags BindingFlags { get { return m_bindingFlags; } } - #endregion - - #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); - - RuntimeType[] arguments = Signature.Arguments; - if (arguments.Length > 0) - { - sbName.Append(" ["); - sbName.Append(MethodBase.ConstructParameters(arguments, Signature.CallingConvention, serialization)); - sbName.Append("]"); - } - - return sbName.ToString(); - } - #endregion - - #region ICustomAttributeProvider - public override Object[] GetCustomAttributes(bool inherit) - { - return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); - } - - public override Object[] GetCustomAttributes(Type attributeType, bool inherit) - { - if (attributeType == null) - throw new ArgumentNullException(nameof(attributeType)); - Contract.EndContractBlock(); - - RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; - - if (attributeRuntimeType == null) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType)); - - return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType); - } - - public override bool IsDefined(Type attributeType, bool inherit) - { - if (attributeType == null) - throw new ArgumentNullException(nameof(attributeType)); - Contract.EndContractBlock(); - - RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; - - if (attributeRuntimeType == null) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType)); - - return CustomAttribute.IsDefined(this, attributeRuntimeType); - } - - public override IList GetCustomAttributesData() - { - return CustomAttributeData.GetCustomAttributesInternal(this); - } - #endregion - - #region MemberInfo Overrides - public override MemberTypes MemberType { get { return MemberTypes.Property; } } - public override String Name - { - get - { - if (m_name == null) - m_name = new Utf8String(m_utf8name).ToString(); - - return m_name; - } - } - public override Type DeclaringType - { - get - { - return m_declaringType; - } - } - - public override Type ReflectedType - { - get - { - return ReflectedTypeInternal; - } - } - - private RuntimeType ReflectedTypeInternal - { - get - { - return m_reflectedTypeCache.GetRuntimeType(); - } - } - - public override int MetadataToken { get { return m_token; } } - - public override Module Module { get { return GetRuntimeModule(); } } - internal RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); } - #endregion - - #region PropertyInfo Overrides - - #region Non Dynamic - - public override Type[] GetRequiredCustomModifiers() - { - return Signature.GetCustomModifiers(0, true); - } - - public override Type[] GetOptionalCustomModifiers() - { - return Signature.GetCustomModifiers(0, false); - } - - internal object GetConstantValue(bool raw) - { - Object defaultValue = MdConstant.GetValue(GetRuntimeModule().MetadataImport, m_token, PropertyType.GetTypeHandleInternal(), raw); - - if (defaultValue == DBNull.Value) - // Arg_EnumLitValueNotFound -> "Literal value was not found." - throw new InvalidOperationException(Environment.GetResourceString("Arg_EnumLitValueNotFound")); - - return defaultValue; - } - - public override object GetConstantValue() { return GetConstantValue(false); } - - public override object GetRawConstantValue() { return GetConstantValue(true); } - - public override MethodInfo[] GetAccessors(bool nonPublic) - { - List accessorList = new List(); - - if (Associates.IncludeAccessor(m_getterMethod, nonPublic)) - accessorList.Add(m_getterMethod); - - if (Associates.IncludeAccessor(m_setterMethod, nonPublic)) - accessorList.Add(m_setterMethod); - - if ((object)m_otherMethod != null) - { - for (int i = 0; i < m_otherMethod.Length; i++) - { - if (Associates.IncludeAccessor(m_otherMethod[i] as MethodInfo, nonPublic)) - accessorList.Add(m_otherMethod[i]); - } - } - return accessorList.ToArray(); - } - - public override Type PropertyType - { - get { return Signature.ReturnType; } - } - - public override MethodInfo GetGetMethod(bool nonPublic) - { - if (!Associates.IncludeAccessor(m_getterMethod, nonPublic)) - return null; - - return m_getterMethod; - } - - public override MethodInfo GetSetMethod(bool nonPublic) - { - if (!Associates.IncludeAccessor(m_setterMethod, nonPublic)) - return null; - - return m_setterMethod; - } - - public override ParameterInfo[] GetIndexParameters() - { - ParameterInfo[] indexParams = GetIndexParametersNoCopy(); - - int numParams = indexParams.Length; - - if (numParams == 0) - return indexParams; - - ParameterInfo[] ret = new ParameterInfo[numParams]; - - Array.Copy(indexParams, ret, numParams); - - return ret; - } - - internal ParameterInfo[] GetIndexParametersNoCopy() - { - // @History - Logic ported from RTM - - // No need to lock because we don't guarantee the uniqueness of ParameterInfo objects - if (m_parameters == null) - { - int numParams = 0; - ParameterInfo[] methParams = null; - - // First try to get the Get method. - MethodInfo m = GetGetMethod(true); - if (m != null) - { - // There is a Get method so use it. - methParams = m.GetParametersNoCopy(); - numParams = methParams.Length; - } - else - { - // If there is no Get method then use the Set method. - m = GetSetMethod(true); - - if (m != null) - { - methParams = m.GetParametersNoCopy(); - numParams = methParams.Length - 1; - } - } - - // Now copy over the parameter info's and change their - // owning member info to the current property info. - - ParameterInfo[] propParams = new ParameterInfo[numParams]; - - for (int i = 0; i < numParams; i++) - propParams[i] = new RuntimeParameterInfo((RuntimeParameterInfo)methParams[i], this); - - m_parameters = propParams; - } - - return m_parameters; - } - - public override PropertyAttributes Attributes - { - get - { - return m_flags; - } - } - - public override bool CanRead - { - get - { - return m_getterMethod != null; - } - } - - public override bool CanWrite - { - get - { - return m_setterMethod != null; - } - } - #endregion - - #region Dynamic - [DebuggerStepThroughAttribute] - [Diagnostics.DebuggerHidden] - public override Object GetValue(Object obj, Object[] index) - { - return GetValue(obj, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static, - null, index, null); - } - - [DebuggerStepThroughAttribute] - [Diagnostics.DebuggerHidden] - public override Object GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture) - { - MethodInfo m = GetGetMethod(true); - if (m == null) - throw new ArgumentException(System.Environment.GetResourceString("Arg_GetMethNotFnd")); - return m.Invoke(obj, invokeAttr, binder, index, null); - } - - [DebuggerStepThroughAttribute] - [Diagnostics.DebuggerHidden] - public override void SetValue(Object obj, Object value, Object[] index) - { - SetValue(obj, - value, - BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static, - null, - index, - null); - } - - [DebuggerStepThroughAttribute] - [Diagnostics.DebuggerHidden] - public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture) - { - MethodInfo m = GetSetMethod(true); - - if (m == null) - throw new ArgumentException(System.Environment.GetResourceString("Arg_SetMethNotFnd")); - - Object[] args = null; - - if (index != null) - { - args = new Object[index.Length + 1]; - - for (int i = 0; i < index.Length; i++) - args[i] = index[i]; - - args[index.Length] = value; - } - else - { - args = new Object[1]; - args[0] = value; - } - - m.Invoke(obj, invokeAttr, binder, args, culture); - } - #endregion - - #endregion - - #region ISerializable Implementation - public void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - throw new ArgumentNullException(nameof(info)); - Contract.EndContractBlock(); - - MemberInfoSerializationHolder.GetSerializationInfo( - info, - Name, - ReflectedTypeInternal, - ToString(), - SerializationToString(), - MemberTypes.Property, - null); - } - - internal string SerializationToString() - { - return FormatNameAndSig(true); - } - #endregion - } } diff --git a/src/coreclr/src/mscorlib/src/System/Reflection/RtFieldInfo.cs b/src/coreclr/src/mscorlib/src/System/Reflection/RtFieldInfo.cs new file mode 100644 index 0000000..856e952 --- /dev/null +++ b/src/coreclr/src/mscorlib/src/System/Reflection/RtFieldInfo.cs @@ -0,0 +1,390 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Diagnostics; +using System.Diagnostics.Contracts; +using System.Globalization; +using System.Runtime.CompilerServices; +using System.Threading; +using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; + +namespace System.Reflection +{ + [Serializable] + internal unsafe sealed class RtFieldInfo : RuntimeFieldInfo, IRuntimeFieldInfo + { + #region FCalls + [MethodImplAttribute(MethodImplOptions.InternalCall)] + static private extern void PerformVisibilityCheckOnField(IntPtr field, Object target, RuntimeType declaringType, FieldAttributes attr, uint invocationFlags); + #endregion + + #region Private Data Members + // agressive caching + private IntPtr m_fieldHandle; + private FieldAttributes m_fieldAttributes; + // lazy caching + private string m_name; + private RuntimeType m_fieldType; + private INVOCATION_FLAGS m_invocationFlags; + + internal INVOCATION_FLAGS InvocationFlags + { + get + { + if ((m_invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0) + { + Type declaringType = DeclaringType; + bool fIsReflectionOnlyType = (declaringType is ReflectionOnlyType); + + INVOCATION_FLAGS invocationFlags = 0; + + // first take care of all the NO_INVOKE cases + if ( + (declaringType != null && declaringType.ContainsGenericParameters) || + (declaringType == null && Module.Assembly.ReflectionOnly) || + (fIsReflectionOnlyType) + ) + { + invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE; + } + + // If the invocationFlags are still 0, then + // this should be an usable field, determine the other flags + if (invocationFlags == 0) + { + if ((m_fieldAttributes & FieldAttributes.InitOnly) != (FieldAttributes)0) + invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD; + + if ((m_fieldAttributes & FieldAttributes.HasFieldRVA) != (FieldAttributes)0) + invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD; + + // A public field is inaccesible to Transparent code if the field is Critical. + bool needsTransparencySecurityCheck = IsSecurityCritical && !IsSecuritySafeCritical; + bool needsVisibilitySecurityCheck = ((m_fieldAttributes & FieldAttributes.FieldAccessMask) != FieldAttributes.Public) || + (declaringType != null && declaringType.NeedsReflectionSecurityCheck); + if (needsTransparencySecurityCheck || needsVisibilitySecurityCheck) + invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY; + + // find out if the field type is one of the following: Primitive, Enum or Pointer + Type fieldType = FieldType; + if (fieldType.IsPointer || fieldType.IsEnum || fieldType.IsPrimitive) + invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_FIELD_SPECIAL_CAST; + } + + // must be last to avoid threading problems + m_invocationFlags = invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED; + } + + return m_invocationFlags; + } + } + #endregion + + private RuntimeAssembly GetRuntimeAssembly() { return m_declaringType.GetRuntimeAssembly(); } + + #region Constructor + internal RtFieldInfo( + RuntimeFieldHandleInternal handle, RuntimeType declaringType, RuntimeTypeCache reflectedTypeCache, BindingFlags bindingFlags) + : base(reflectedTypeCache, declaringType, bindingFlags) + { + m_fieldHandle = handle.Value; + m_fieldAttributes = RuntimeFieldHandle.GetAttributes(handle); + } + #endregion + + #region Private Members + RuntimeFieldHandleInternal IRuntimeFieldInfo.Value + { + get + { + return new RuntimeFieldHandleInternal(m_fieldHandle); + } + } + + #endregion + + #region Internal Members + internal void CheckConsistency(Object target) + { + // only test instance fields + if ((m_fieldAttributes & FieldAttributes.Static) != FieldAttributes.Static) + { + if (!m_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, m_declaringType, target.GetType())); + } + } + } + } + + internal override bool CacheEquals(object o) + { + RtFieldInfo m = o as RtFieldInfo; + + if ((object)m == null) + return false; + + return m.m_fieldHandle == m_fieldHandle; + } + + [DebuggerStepThroughAttribute] + [Diagnostics.DebuggerHidden] + internal void InternalSetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture, ref StackCrawlMark stackMark) + { + INVOCATION_FLAGS invocationFlags = InvocationFlags; + RuntimeType declaringType = DeclaringType as RuntimeType; + + if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE) != 0) + { + if (declaringType != null && declaringType.ContainsGenericParameters) + throw new InvalidOperationException(Environment.GetResourceString("Arg_UnboundGenField")); + + if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType) + throw new InvalidOperationException(Environment.GetResourceString("Arg_ReflectionOnlyField")); + + throw new FieldAccessException(); + } + + CheckConsistency(obj); + + RuntimeType fieldType = (RuntimeType)FieldType; + value = fieldType.CheckValue(value, binder, culture, invokeAttr); + + #region Security Check + if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD | INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY)) != 0) + PerformVisibilityCheckOnField(m_fieldHandle, obj, m_declaringType, m_fieldAttributes, (uint)m_invocationFlags); + #endregion + + bool domainInitialized = false; + if (declaringType == null) + { + RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, null, ref domainInitialized); + } + else + { + domainInitialized = declaringType.DomainInitialized; + RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, declaringType, ref domainInitialized); + declaringType.DomainInitialized = domainInitialized; + } + } + + // UnsafeSetValue doesn't perform any consistency or visibility check. + // It is the caller's responsibility to ensure the operation is safe. + // When the caller needs to perform visibility checks they should call + // InternalSetValue() instead. When the caller needs to perform + // consistency checks they should call CheckConsistency() before + // calling this method. + [DebuggerStepThroughAttribute] + [Diagnostics.DebuggerHidden] + internal void UnsafeSetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) + { + RuntimeType declaringType = DeclaringType as RuntimeType; + RuntimeType fieldType = (RuntimeType)FieldType; + value = fieldType.CheckValue(value, binder, culture, invokeAttr); + + bool domainInitialized = false; + if (declaringType == null) + { + RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, null, ref domainInitialized); + } + else + { + domainInitialized = declaringType.DomainInitialized; + RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, declaringType, ref domainInitialized); + declaringType.DomainInitialized = domainInitialized; + } + } + + [DebuggerStepThroughAttribute] + [Diagnostics.DebuggerHidden] + internal Object InternalGetValue(Object obj, ref StackCrawlMark stackMark) + { + INVOCATION_FLAGS invocationFlags = InvocationFlags; + RuntimeType declaringType = DeclaringType as RuntimeType; + + if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE) != 0) + { + if (declaringType != null && DeclaringType.ContainsGenericParameters) + throw new InvalidOperationException(Environment.GetResourceString("Arg_UnboundGenField")); + + if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType) + throw new InvalidOperationException(Environment.GetResourceString("Arg_ReflectionOnlyField")); + + throw new FieldAccessException(); + } + + CheckConsistency(obj); + + RuntimeType fieldType = (RuntimeType)FieldType; + if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) != 0) + PerformVisibilityCheckOnField(m_fieldHandle, obj, m_declaringType, m_fieldAttributes, (uint)(m_invocationFlags & ~INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD)); + + return UnsafeGetValue(obj); + } + + // UnsafeGetValue doesn't perform any consistency or visibility check. + // It is the caller's responsibility to ensure the operation is safe. + // When the caller needs to perform visibility checks they should call + // InternalGetValue() instead. When the caller needs to perform + // consistency checks they should call CheckConsistency() before + // calling this method. + [DebuggerStepThroughAttribute] + [Diagnostics.DebuggerHidden] + internal Object UnsafeGetValue(Object obj) + { + RuntimeType declaringType = DeclaringType as RuntimeType; + + RuntimeType fieldType = (RuntimeType)FieldType; + + bool domainInitialized = false; + if (declaringType == null) + { + return RuntimeFieldHandle.GetValue(this, obj, fieldType, null, ref domainInitialized); + } + else + { + domainInitialized = declaringType.DomainInitialized; + object retVal = RuntimeFieldHandle.GetValue(this, obj, fieldType, declaringType, ref domainInitialized); + declaringType.DomainInitialized = domainInitialized; + return retVal; + } + } + + #endregion + + #region MemberInfo Overrides + public override String Name + { + get + { + if (m_name == null) + m_name = RuntimeFieldHandle.GetName(this); + + return m_name; + } + } + + internal String FullName + { + get + { + return String.Format("{0}.{1}", DeclaringType.FullName, Name); + } + } + + public override int MetadataToken + { + get { return RuntimeFieldHandle.GetToken(this); } + } + + internal override RuntimeModule GetRuntimeModule() + { + return RuntimeTypeHandle.GetModule(RuntimeFieldHandle.GetApproxDeclaringType(this)); + } + + #endregion + + #region FieldInfo Overrides + public override Object GetValue(Object obj) + { + StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; + return InternalGetValue(obj, ref stackMark); + } + + public override object GetRawConstantValue() { throw new InvalidOperationException(); } + + [DebuggerStepThroughAttribute] + [Diagnostics.DebuggerHidden] + public override Object GetValueDirect(TypedReference obj) + { + if (obj.IsNull) + throw new ArgumentException(Environment.GetResourceString("Arg_TypedReference_Null")); + Contract.EndContractBlock(); + + unsafe + { + // Passing TypedReference by reference is easier to make correct in native code + return RuntimeFieldHandle.GetValueDirect(this, (RuntimeType)FieldType, &obj, (RuntimeType)DeclaringType); + } + } + + [DebuggerStepThroughAttribute] + [Diagnostics.DebuggerHidden] + public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) + { + StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; + InternalSetValue(obj, value, invokeAttr, binder, culture, ref stackMark); + } + + [DebuggerStepThroughAttribute] + [Diagnostics.DebuggerHidden] + public override void SetValueDirect(TypedReference obj, Object value) + { + if (obj.IsNull) + throw new ArgumentException(Environment.GetResourceString("Arg_TypedReference_Null")); + Contract.EndContractBlock(); + + unsafe + { + // Passing TypedReference by reference is easier to make correct in native code + RuntimeFieldHandle.SetValueDirect(this, (RuntimeType)FieldType, &obj, value, (RuntimeType)DeclaringType); + } + } + + public override RuntimeFieldHandle FieldHandle + { + get + { + Type declaringType = DeclaringType; + if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType) + throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAllowedInReflectionOnly")); + return new RuntimeFieldHandle(this); + } + } + + internal IntPtr GetFieldHandle() + { + return m_fieldHandle; + } + + public override FieldAttributes Attributes + { + get + { + return m_fieldAttributes; + } + } + + public override Type FieldType + { + get + { + if (m_fieldType == null) + m_fieldType = new Signature(this, m_declaringType).FieldType; + + return m_fieldType; + } + } + + public override Type[] GetRequiredCustomModifiers() + { + return new Signature(this, m_declaringType).GetCustomModifiers(1, true); + } + + public override Type[] GetOptionalCustomModifiers() + { + return new Signature(this, m_declaringType).GetCustomModifiers(1, false); + } + + #endregion + } +} diff --git a/src/coreclr/src/mscorlib/src/System/Reflection/RuntimeAssembly.cs b/src/coreclr/src/mscorlib/src/System/Reflection/RuntimeAssembly.cs new file mode 100644 index 0000000..5322047 --- /dev/null +++ b/src/coreclr/src/mscorlib/src/System/Reflection/RuntimeAssembly.cs @@ -0,0 +1,931 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Collections.Generic; +using CultureInfo = System.Globalization.CultureInfo; +using System.Security; +using System.Security.Policy; +using System.IO; +using StringBuilder = System.Text.StringBuilder; +using System.Configuration.Assemblies; +using StackCrawlMark = System.Threading.StackCrawlMark; +using System.Runtime.InteropServices; +using System.Runtime.CompilerServices; +using System.Runtime.Serialization; +using System.Threading; +using System.Diagnostics.Contracts; + +namespace System.Reflection +{ + [Serializable] + internal class RuntimeAssembly : Assembly + { +#if FEATURE_APPX + // The highest byte is the flags and the lowest 3 bytes are + // the cached ctor token of [DynamicallyInvocableAttribute]. + private enum ASSEMBLY_FLAGS : uint + { + ASSEMBLY_FLAGS_UNKNOWN = 0x00000000, + ASSEMBLY_FLAGS_INITIALIZED = 0x01000000, + ASSEMBLY_FLAGS_FRAMEWORK = 0x02000000, + ASSEMBLY_FLAGS_TOKEN_MASK = 0x00FFFFFF, + } +#endif // FEATURE_APPX + + private const uint COR_E_LOADING_REFERENCE_ASSEMBLY = 0x80131058U; + + internal RuntimeAssembly() { throw new NotSupportedException(); } + + #region private data members + private event ModuleResolveEventHandler _ModuleResolve; + private string m_fullname; + private object m_syncRoot; // Used to keep collectible types alive and as the syncroot for reflection.emit + private IntPtr m_assembly; // slack for ptr datum on unmanaged side + +#if FEATURE_APPX + private ASSEMBLY_FLAGS m_flags; +#endif + #endregion + +#if FEATURE_APPX + private ASSEMBLY_FLAGS Flags + { + get + { + if ((m_flags & ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_INITIALIZED) == 0) + { + ASSEMBLY_FLAGS flags = ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_UNKNOWN + | ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_FRAMEWORK; + + m_flags = flags | ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_INITIALIZED; + } + + return m_flags; + } + } +#endif // FEATURE_APPX + + internal object SyncRoot + { + get + { + if (m_syncRoot == null) + { + Interlocked.CompareExchange(ref m_syncRoot, new object(), null); + } + return m_syncRoot; + } + } + + public override event ModuleResolveEventHandler ModuleResolve + { + add + { + _ModuleResolve += value; + } + remove + { + _ModuleResolve -= value; + } + } + + private const String s_localFilePrefix = "file:"; + + [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] + [SuppressUnmanagedCodeSecurity] + private static extern void GetCodeBase(RuntimeAssembly assembly, + bool copiedName, + StringHandleOnStack retString); + + internal String GetCodeBase(bool copiedName) + { + String codeBase = null; + GetCodeBase(GetNativeHandle(), copiedName, JitHelpers.GetStringHandleOnStack(ref codeBase)); + return codeBase; + } + + public override String CodeBase + { + get + { + String codeBase = GetCodeBase(false); + return codeBase; + } + } + + internal RuntimeAssembly GetNativeHandle() + { + return this; + } + + // If the assembly is copied before it is loaded, the codebase will be set to the + // actual file loaded if copiedName is true. If it is false, then the original code base + // is returned. + public override AssemblyName GetName(bool copiedName) + { + AssemblyName an = new AssemblyName(); + + String codeBase = GetCodeBase(copiedName); + + an.Init(GetSimpleName(), + GetPublicKey(), + null, // public key token + GetVersion(), + GetLocale(), + GetHashAlgorithm(), + AssemblyVersionCompatibility.SameMachine, + codeBase, + GetFlags() | AssemblyNameFlags.PublicKey, + null); // strong name key pair + + PortableExecutableKinds pek; + ImageFileMachine ifm; + + Module manifestModule = ManifestModule; + if (manifestModule != null) + { + if (manifestModule.MDStreamVersion > 0x10000) + { + ManifestModule.GetPEKind(out pek, out ifm); + an.SetProcArchIndex(pek, ifm); + } + } + return an; + } + + [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] + [SuppressUnmanagedCodeSecurity] + private extern static void GetFullName(RuntimeAssembly assembly, StringHandleOnStack retString); + + public override String FullName + { + get + { + // If called by Object.ToString(), return val may be NULL. + if (m_fullname == null) + { + string s = null; + GetFullName(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref s)); + Interlocked.CompareExchange(ref m_fullname, s, null); + } + + return m_fullname; + } + } + + [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] + [SuppressUnmanagedCodeSecurity] + private static extern void GetEntryPoint(RuntimeAssembly assembly, ObjectHandleOnStack retMethod); + + public override MethodInfo EntryPoint + { + get + { + IRuntimeMethodInfo methodHandle = null; + GetEntryPoint(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref methodHandle)); + + if (methodHandle == null) + return null; + + return (MethodInfo)RuntimeType.GetMethodBase(methodHandle); + } + } + + [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] + [SuppressUnmanagedCodeSecurity] + private static extern void GetType(RuntimeAssembly assembly, + String name, + bool throwOnError, + bool ignoreCase, + ObjectHandleOnStack type, + ObjectHandleOnStack keepAlive); + + public override Type GetType(String name, bool throwOnError, bool ignoreCase) + { + // throw on null strings regardless of the value of "throwOnError" + if (name == null) + throw new ArgumentNullException(nameof(name)); + + RuntimeType type = null; + Object keepAlive = null; + GetType(GetNativeHandle(), name, throwOnError, ignoreCase, JitHelpers.GetObjectHandleOnStack(ref type), JitHelpers.GetObjectHandleOnStack(ref keepAlive)); + GC.KeepAlive(keepAlive); + + return type; + } + + [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] + [SuppressUnmanagedCodeSecurity] + private extern static void GetExportedTypes(RuntimeAssembly assembly, ObjectHandleOnStack retTypes); + + public override Type[] GetExportedTypes() + { + Type[] types = null; + GetExportedTypes(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref types)); + return types; + } + + public override IEnumerable DefinedTypes + { + get + { + List rtTypes = new List(); + + RuntimeModule[] modules = GetModulesInternal(true, false); + + for (int i = 0; i < modules.Length; i++) + { + rtTypes.AddRange(modules[i].GetDefinedTypes()); + } + + return rtTypes.ToArray(); + } + } + + // Load a resource based on the NameSpace of the type. + [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod + public override Stream GetManifestResourceStream(Type type, String name) + { + StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; + return GetManifestResourceStream(type, name, false, ref stackMark); + } + + [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod + public override Stream GetManifestResourceStream(String name) + { + StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; + return GetManifestResourceStream(name, ref stackMark, false); + } + + // ISerializable implementation + public override void GetObjectData(SerializationInfo info, StreamingContext context) + { + if (info == null) + throw new ArgumentNullException(nameof(info)); + + Contract.EndContractBlock(); + + UnitySerializationHolder.GetUnitySerializationInfo(info, + UnitySerializationHolder.AssemblyUnity, + this.FullName, + this); + } + + public override Module ManifestModule + { + get + { + // We don't need to return the "external" ModuleBuilder because + // it is meant to be read-only + return RuntimeAssembly.GetManifestModule(GetNativeHandle()); + } + } + + public override Object[] GetCustomAttributes(bool inherit) + { + return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); + } + + public override Object[] GetCustomAttributes(Type attributeType, bool inherit) + { + if (attributeType == null) + throw new ArgumentNullException(nameof(attributeType)); + Contract.EndContractBlock(); + + RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; + + if (attributeRuntimeType == null) + throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType)); + + return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType); + } + + public override bool IsDefined(Type attributeType, bool inherit) + { + if (attributeType == null) + throw new ArgumentNullException(nameof(attributeType)); + Contract.EndContractBlock(); + + RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; + + if (attributeRuntimeType == null) + throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType)); + + return CustomAttribute.IsDefined(this, attributeRuntimeType); + } + + public override IList GetCustomAttributesData() + { + return CustomAttributeData.GetCustomAttributesInternal(this); + } + + [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod + internal static RuntimeAssembly InternalLoadFrom(String assemblyFile, + Evidence securityEvidence, + byte[] hashValue, + AssemblyHashAlgorithm hashAlgorithm, + bool forIntrospection, + ref StackCrawlMark stackMark) + { + if (assemblyFile == null) + throw new ArgumentNullException(nameof(assemblyFile)); + + Contract.EndContractBlock(); + + AssemblyName an = new AssemblyName(); + an.CodeBase = assemblyFile; + an.SetHashControl(hashValue, hashAlgorithm); + // The stack mark is used for MDA filtering + return InternalLoadAssemblyName(an, securityEvidence, null, ref stackMark, true /*thrownOnFileNotFound*/, forIntrospection); + } + + // Wrapper function to wrap the typical use of InternalLoad. + internal static RuntimeAssembly InternalLoad(String assemblyString, + Evidence assemblySecurity, + ref StackCrawlMark stackMark, + bool forIntrospection) + { + return InternalLoad(assemblyString, assemblySecurity, ref stackMark, IntPtr.Zero, forIntrospection); + } + + [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod + internal static RuntimeAssembly InternalLoad(String assemblyString, + Evidence assemblySecurity, + ref StackCrawlMark stackMark, + IntPtr pPrivHostBinder, + bool forIntrospection) + { + RuntimeAssembly assembly; + AssemblyName an = CreateAssemblyName(assemblyString, forIntrospection, out assembly); + + if (assembly != null) + { + // The assembly was returned from ResolveAssemblyEvent + return assembly; + } + + return InternalLoadAssemblyName(an, assemblySecurity, null, ref stackMark, + pPrivHostBinder, + true /*thrownOnFileNotFound*/, forIntrospection); + } + + // Creates AssemblyName. Fills assembly if AssemblyResolve event has been raised. + internal static AssemblyName CreateAssemblyName( + String assemblyString, + bool forIntrospection, + out RuntimeAssembly assemblyFromResolveEvent) + { + if (assemblyString == null) + throw new ArgumentNullException(nameof(assemblyString)); + Contract.EndContractBlock(); + + if ((assemblyString.Length == 0) || + (assemblyString[0] == '\0')) + throw new ArgumentException(Environment.GetResourceString("Format_StringZeroLength")); + + if (forIntrospection) + AppDomain.CheckReflectionOnlyLoadSupported(); + + AssemblyName an = new AssemblyName(); + + an.Name = assemblyString; + an.nInit(out assemblyFromResolveEvent, forIntrospection, true); + + return an; + } + + // Wrapper function to wrap the typical use of InternalLoadAssemblyName. + internal static RuntimeAssembly InternalLoadAssemblyName( + AssemblyName assemblyRef, + Evidence assemblySecurity, + RuntimeAssembly reqAssembly, + ref StackCrawlMark stackMark, + bool throwOnFileNotFound, + bool forIntrospection, + IntPtr ptrLoadContextBinder = default(IntPtr)) + { + return InternalLoadAssemblyName(assemblyRef, assemblySecurity, reqAssembly, ref stackMark, IntPtr.Zero, true /*throwOnError*/, forIntrospection, ptrLoadContextBinder); + } + + internal static RuntimeAssembly InternalLoadAssemblyName( + AssemblyName assemblyRef, + Evidence assemblySecurity, + RuntimeAssembly reqAssembly, + ref StackCrawlMark stackMark, + IntPtr pPrivHostBinder, + bool throwOnFileNotFound, + bool forIntrospection, + IntPtr ptrLoadContextBinder = default(IntPtr)) + { + if (assemblyRef == null) + throw new ArgumentNullException(nameof(assemblyRef)); + Contract.EndContractBlock(); + + if (assemblyRef.CodeBase != null) + { + AppDomain.CheckLoadFromSupported(); + } + + assemblyRef = (AssemblyName)assemblyRef.Clone(); + if (!forIntrospection && + (assemblyRef.ProcessorArchitecture != ProcessorArchitecture.None)) + { + // PA does not have a semantics for by-name binds for execution + assemblyRef.ProcessorArchitecture = ProcessorArchitecture.None; + } + + String codeBase = VerifyCodeBase(assemblyRef.CodeBase); + + return nLoad(assemblyRef, codeBase, assemblySecurity, reqAssembly, ref stackMark, + pPrivHostBinder, + throwOnFileNotFound, forIntrospection, ptrLoadContextBinder); + } + + // These are the framework assemblies that does reflection invocation + // on behalf of user code. We allow framework code to invoke non-W8P + // framework APIs but don't want user code to gain that privilege + // through these assemblies. So we blaklist them. + private static string[] s_unsafeFrameworkAssemblyNames = new string[] { + "System.Reflection.Context", + "Microsoft.VisualBasic" + }; + +#if FEATURE_APPX + internal bool IsFrameworkAssembly() + { + ASSEMBLY_FLAGS flags = Flags; + return (flags & ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_FRAMEWORK) != 0; + } +#endif + + [MethodImplAttribute(MethodImplOptions.InternalCall)] + private static extern RuntimeAssembly _nLoad(AssemblyName fileName, + String codeBase, + Evidence assemblySecurity, + RuntimeAssembly locationHint, + ref StackCrawlMark stackMark, + IntPtr pPrivHostBinder, + bool throwOnFileNotFound, + bool forIntrospection, + bool suppressSecurityChecks, + IntPtr ptrLoadContextBinder); + + private static RuntimeAssembly nLoad(AssemblyName fileName, + String codeBase, + Evidence assemblySecurity, + RuntimeAssembly locationHint, + ref StackCrawlMark stackMark, + IntPtr pPrivHostBinder, + bool throwOnFileNotFound, + bool forIntrospection, + IntPtr ptrLoadContextBinder = default(IntPtr)) + { + return _nLoad(fileName, codeBase, assemblySecurity, locationHint, ref stackMark, + pPrivHostBinder, + throwOnFileNotFound, forIntrospection, true /* suppressSecurityChecks */, ptrLoadContextBinder); + } + + [MethodImplAttribute(MethodImplOptions.InternalCall)] + private static extern bool IsReflectionOnly(RuntimeAssembly assembly); + + public override bool ReflectionOnly + { + get + { + return IsReflectionOnly(GetNativeHandle()); + } + } + + // Returns the module in this assembly with name 'name' + + [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] + [SuppressUnmanagedCodeSecurity] + private static extern void GetModule(RuntimeAssembly assembly, String name, ObjectHandleOnStack retModule); + + public override Module GetModule(String name) + { + Module retModule = null; + GetModule(GetNativeHandle(), name, JitHelpers.GetObjectHandleOnStack(ref retModule)); + return retModule; + } + + // Returns the file in the File table of the manifest that matches the + // given name. (Name should not include path.) + public override FileStream GetFile(String name) + { + RuntimeModule m = (RuntimeModule)GetModule(name); + if (m == null) + return null; + + return new FileStream(m.GetFullyQualifiedName(), + FileMode.Open, + FileAccess.Read, FileShare.Read, FileStream.DefaultBufferSize, false); + } + + public override FileStream[] GetFiles(bool getResourceModules) + { + Module[] m = GetModules(getResourceModules); + FileStream[] fs = new FileStream[m.Length]; + + for (int i = 0; i < fs.Length; i++) + { + fs[i] = new FileStream(((RuntimeModule)m[i]).GetFullyQualifiedName(), + FileMode.Open, + FileAccess.Read, FileShare.Read, FileStream.DefaultBufferSize, false); + } + + return fs; + } + + // Returns the names of all the resources + [MethodImplAttribute(MethodImplOptions.InternalCall)] + private static extern String[] GetManifestResourceNames(RuntimeAssembly assembly); + + // Returns the names of all the resources + public override String[] GetManifestResourceNames() + { + return GetManifestResourceNames(GetNativeHandle()); + } + + [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] + [SuppressUnmanagedCodeSecurity] + private extern static void GetExecutingAssembly(StackCrawlMarkHandle stackMark, ObjectHandleOnStack retAssembly); + + internal static RuntimeAssembly GetExecutingAssembly(ref StackCrawlMark stackMark) + { + RuntimeAssembly retAssembly = null; + GetExecutingAssembly(JitHelpers.GetStackCrawlMarkHandle(ref stackMark), JitHelpers.GetObjectHandleOnStack(ref retAssembly)); + return retAssembly; + } + + // Returns the names of all the resources + [MethodImplAttribute(MethodImplOptions.InternalCall)] + private static extern AssemblyName[] GetReferencedAssemblies(RuntimeAssembly assembly); + + public override AssemblyName[] GetReferencedAssemblies() + { + return GetReferencedAssemblies(GetNativeHandle()); + } + + [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] + [SuppressUnmanagedCodeSecurity] + private static extern int GetManifestResourceInfo(RuntimeAssembly assembly, + String resourceName, + ObjectHandleOnStack assemblyRef, + StringHandleOnStack retFileName, + StackCrawlMarkHandle stackMark); + + [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod + public override ManifestResourceInfo GetManifestResourceInfo(String resourceName) + { + RuntimeAssembly retAssembly = null; + String fileName = null; + StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; + int location = GetManifestResourceInfo(GetNativeHandle(), resourceName, + JitHelpers.GetObjectHandleOnStack(ref retAssembly), + JitHelpers.GetStringHandleOnStack(ref fileName), + JitHelpers.GetStackCrawlMarkHandle(ref stackMark)); + + if (location == -1) + return null; + + return new ManifestResourceInfo(retAssembly, fileName, + (ResourceLocation)location); + } + + [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] + [SuppressUnmanagedCodeSecurity] + private static extern void GetLocation(RuntimeAssembly assembly, StringHandleOnStack retString); + + public override String Location + { + get + { + String location = null; + + GetLocation(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref location)); + + return location; + } + } + + [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] + [SuppressUnmanagedCodeSecurity] + private extern static void GetImageRuntimeVersion(RuntimeAssembly assembly, StringHandleOnStack retString); + + public override String ImageRuntimeVersion + { + get + { + String s = null; + GetImageRuntimeVersion(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref s)); + return s; + } + } + + public override bool GlobalAssemblyCache + { + get + { + return false; + } + } + + public override Int64 HostContext + { + get + { + return 0; + } + } + + private static String VerifyCodeBase(String codebase) + { + if (codebase == null) + return null; + + int len = codebase.Length; + if (len == 0) + return null; + + + int j = codebase.IndexOf(':'); + // Check to see if the url has a prefix + if ((j != -1) && + (j + 2 < len) && + ((codebase[j + 1] == '/') || (codebase[j + 1] == '\\')) && + ((codebase[j + 2] == '/') || (codebase[j + 2] == '\\'))) + return codebase; +#if !PLATFORM_UNIX + else if ((len > 2) && (codebase[0] == '\\') && (codebase[1] == '\\')) + return "file://" + codebase; + else + return "file:///" + Path.GetFullPath(codebase); +#else + else + return "file://" + Path.GetFullPath(codebase); +#endif // !PLATFORM_UNIX + } + + internal Stream GetManifestResourceStream( + Type type, + String name, + bool skipSecurityCheck, + ref StackCrawlMark stackMark) + { + StringBuilder sb = new StringBuilder(); + if (type == null) + { + if (name == null) + throw new ArgumentNullException(nameof(type)); + } + else + { + String nameSpace = type.Namespace; + if (nameSpace != null) + { + sb.Append(nameSpace); + if (name != null) + sb.Append(Type.Delimiter); + } + } + + if (name != null) + sb.Append(name); + + return GetManifestResourceStream(sb.ToString(), ref stackMark, skipSecurityCheck); + } + + // GetResource will return a pointer to the resources in memory. + [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] + [SuppressUnmanagedCodeSecurity] + private static unsafe extern byte* GetResource(RuntimeAssembly assembly, + String resourceName, + out ulong length, + StackCrawlMarkHandle stackMark, + bool skipSecurityCheck); + + internal unsafe Stream GetManifestResourceStream(String name, ref StackCrawlMark stackMark, bool skipSecurityCheck) + { + ulong length = 0; + byte* pbInMemoryResource = GetResource(GetNativeHandle(), name, out length, JitHelpers.GetStackCrawlMarkHandle(ref stackMark), skipSecurityCheck); + + if (pbInMemoryResource != null) + { + //Console.WriteLine("Creating an unmanaged memory stream of length "+length); + if (length > Int64.MaxValue) + throw new NotImplementedException(Environment.GetResourceString("NotImplemented_ResourcesLongerThan2^63")); + + return new UnmanagedMemoryStream(pbInMemoryResource, (long)length, (long)length, FileAccess.Read); + } + + //Console.WriteLine("GetManifestResourceStream: Blob "+name+" not found..."); + return null; + } + + [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] + [SuppressUnmanagedCodeSecurity] + private static extern void GetVersion(RuntimeAssembly assembly, + out int majVer, + out int minVer, + out int buildNum, + out int revNum); + + internal Version GetVersion() + { + int majorVer, minorVer, build, revision; + GetVersion(GetNativeHandle(), out majorVer, out minorVer, out build, out revision); + return new Version(majorVer, minorVer, build, revision); + } + + [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] + [SuppressUnmanagedCodeSecurity] + private static extern void GetLocale(RuntimeAssembly assembly, StringHandleOnStack retString); + + internal CultureInfo GetLocale() + { + String locale = null; + + GetLocale(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref locale)); + + if (locale == null) + return CultureInfo.InvariantCulture; + + return new CultureInfo(locale); + } + + [MethodImplAttribute(MethodImplOptions.InternalCall)] + private static extern bool FCallIsDynamic(RuntimeAssembly assembly); + + public override bool IsDynamic + { + get + { + return FCallIsDynamic(GetNativeHandle()); + } + } + + [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] + [SuppressUnmanagedCodeSecurity] + private static extern void GetSimpleName(RuntimeAssembly assembly, StringHandleOnStack retSimpleName); + + internal String GetSimpleName() + { + string name = null; + GetSimpleName(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref name)); + return name; + } + + [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] + [SuppressUnmanagedCodeSecurity] + private extern static AssemblyHashAlgorithm GetHashAlgorithm(RuntimeAssembly assembly); + + private AssemblyHashAlgorithm GetHashAlgorithm() + { + return GetHashAlgorithm(GetNativeHandle()); + } + + [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] + [SuppressUnmanagedCodeSecurity] + private extern static AssemblyNameFlags GetFlags(RuntimeAssembly assembly); + + private AssemblyNameFlags GetFlags() + { + return GetFlags(GetNativeHandle()); + } + + [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] + [SuppressUnmanagedCodeSecurity] + private static extern void GetPublicKey(RuntimeAssembly assembly, ObjectHandleOnStack retPublicKey); + + internal byte[] GetPublicKey() + { + byte[] publicKey = null; + GetPublicKey(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref publicKey)); + return publicKey; + } + + [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] + [SuppressUnmanagedCodeSecurity] + [return: MarshalAs(UnmanagedType.Bool)] + private extern static bool IsAllSecurityTransparent(RuntimeAssembly assembly); + + // Is everything introduced by this assembly transparent + internal bool IsAllSecurityTransparent() + { + return IsAllSecurityTransparent(GetNativeHandle()); + } + + // This method is called by the VM. + private RuntimeModule OnModuleResolveEvent(String moduleName) + { + ModuleResolveEventHandler moduleResolve = _ModuleResolve; + if (moduleResolve == null) + return null; + + Delegate[] ds = moduleResolve.GetInvocationList(); + int len = ds.Length; + for (int i = 0; i < len; i++) + { + RuntimeModule ret = (RuntimeModule)((ModuleResolveEventHandler)ds[i])(this, new ResolveEventArgs(moduleName, this)); + if (ret != null) + return ret; + } + + return null; + } + + [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod + public override Assembly GetSatelliteAssembly(CultureInfo culture) + { + StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; + return InternalGetSatelliteAssembly(culture, null, ref stackMark); + } + + // Useful for binding to a very specific version of a satellite assembly + [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod + public override Assembly GetSatelliteAssembly(CultureInfo culture, Version version) + { + StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; + return InternalGetSatelliteAssembly(culture, version, ref stackMark); + } + + [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod + internal Assembly InternalGetSatelliteAssembly(CultureInfo culture, + Version version, + ref StackCrawlMark stackMark) + { + if (culture == null) + throw new ArgumentNullException(nameof(culture)); + Contract.EndContractBlock(); + + + String name = GetSimpleName() + ".resources"; + return InternalGetSatelliteAssembly(name, culture, version, true, ref stackMark); + } + + [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod + internal RuntimeAssembly InternalGetSatelliteAssembly(String name, + CultureInfo culture, + Version version, + bool throwOnFileNotFound, + ref StackCrawlMark stackMark) + { + AssemblyName an = new AssemblyName(); + + an.SetPublicKey(GetPublicKey()); + an.Flags = GetFlags() | AssemblyNameFlags.PublicKey; + + if (version == null) + an.Version = GetVersion(); + else + an.Version = version; + + an.CultureInfo = culture; + an.Name = name; + + RuntimeAssembly retAssembly = nLoad(an, null, null, this, ref stackMark, + IntPtr.Zero, + throwOnFileNotFound, false); + + if (retAssembly == this || (retAssembly == null && throwOnFileNotFound)) + { + throw new FileNotFoundException(String.Format(culture, Environment.GetResourceString("IO.FileNotFound_FileName"), an.Name)); + } + + return retAssembly; + } + + [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] + [SuppressUnmanagedCodeSecurity] + private extern static void GetModules(RuntimeAssembly assembly, + bool loadIfNotFound, + bool getResourceModules, + ObjectHandleOnStack retModuleHandles); + + private RuntimeModule[] GetModulesInternal(bool loadIfNotFound, + bool getResourceModules) + { + RuntimeModule[] modules = null; + GetModules(GetNativeHandle(), loadIfNotFound, getResourceModules, JitHelpers.GetObjectHandleOnStack(ref modules)); + return modules; + } + + public override Module[] GetModules(bool getResourceModules) + { + return GetModulesInternal(true, getResourceModules); + } + + public override Module[] GetLoadedModules(bool getResourceModules) + { + return GetModulesInternal(false, getResourceModules); + } + + [MethodImplAttribute(MethodImplOptions.InternalCall)] + internal static extern RuntimeModule GetManifestModule(RuntimeAssembly assembly); + + [MethodImplAttribute(MethodImplOptions.InternalCall)] + internal static extern int GetToken(RuntimeAssembly assembly); + } +} diff --git a/src/coreclr/src/mscorlib/src/System/Reflection/RuntimeConstructorInfo.cs b/src/coreclr/src/mscorlib/src/System/Reflection/RuntimeConstructorInfo.cs new file mode 100644 index 0000000..069927e --- /dev/null +++ b/src/coreclr/src/mscorlib/src/System/Reflection/RuntimeConstructorInfo.cs @@ -0,0 +1,488 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.Contracts; +using System.Globalization; +using System.Runtime.Serialization; +using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; + +namespace System.Reflection +{ + [Serializable] + internal sealed class RuntimeConstructorInfo : ConstructorInfo, ISerializable, IRuntimeMethodInfo + { + #region Private Data Members + private volatile RuntimeType m_declaringType; + private RuntimeTypeCache m_reflectedTypeCache; + private string m_toString; + private ParameterInfo[] m_parameters = null; // Created lazily when GetParameters() is called. +#pragma warning disable 169 + private object _empty1; // These empties are used to ensure that RuntimeConstructorInfo and RuntimeMethodInfo are have a layout which is sufficiently similar + private object _empty2; + private object _empty3; +#pragma warning restore 169 + private IntPtr m_handle; + private MethodAttributes m_methodAttributes; + private BindingFlags m_bindingFlags; + private volatile Signature m_signature; + private INVOCATION_FLAGS m_invocationFlags; + + internal INVOCATION_FLAGS InvocationFlags + { + get + { + if ((m_invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0) + { + INVOCATION_FLAGS invocationFlags = INVOCATION_FLAGS.INVOCATION_FLAGS_IS_CTOR; // this is a given + + Type declaringType = DeclaringType; + + // + // first take care of all the NO_INVOKE cases. + if (declaringType == typeof(void) || + (declaringType != null && declaringType.ContainsGenericParameters) || + ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) || + ((Attributes & MethodAttributes.RequireSecObject) == MethodAttributes.RequireSecObject)) + { + // We don't need other flags if this method cannot be invoked + invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE; + } + else if (IsStatic || declaringType != null && declaringType.IsAbstract) + { + invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NO_CTOR_INVOKE; + } + else + { + // this should be an invocable method, determine the other flags that participate in invocation + invocationFlags |= RuntimeMethodHandle.GetSecurityFlags(this); + + if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) == 0 && + ((Attributes & MethodAttributes.MemberAccessMask) != MethodAttributes.Public || + (declaringType != null && declaringType.NeedsReflectionSecurityCheck))) + { + // If method is non-public, or declaring type is not visible + invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY; + } + + // Check for attempt to create a delegate class, we demand unmanaged + // code permission for this since it's hard to validate the target address. + if (typeof(Delegate).IsAssignableFrom(DeclaringType)) + invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_IS_DELEGATE_CTOR; + } + + m_invocationFlags = invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED; + } + + return m_invocationFlags; + } + } + #endregion + + #region Constructor + internal RuntimeConstructorInfo( + RuntimeMethodHandleInternal handle, RuntimeType declaringType, RuntimeTypeCache reflectedTypeCache, + MethodAttributes methodAttributes, BindingFlags bindingFlags) + { + Contract.Ensures(methodAttributes == RuntimeMethodHandle.GetAttributes(handle)); + + m_bindingFlags = bindingFlags; + m_reflectedTypeCache = reflectedTypeCache; + m_declaringType = declaringType; + m_handle = handle.Value; + m_methodAttributes = methodAttributes; + } + #endregion + + #region NonPublic Methods + RuntimeMethodHandleInternal IRuntimeMethodInfo.Value + { + get + { + return new RuntimeMethodHandleInternal(m_handle); + } + } + + internal override bool CacheEquals(object o) + { + RuntimeConstructorInfo m = o as RuntimeConstructorInfo; + + if ((object)m == null) + return false; + + return m.m_handle == m_handle; + } + + private Signature Signature + { + get + { + if (m_signature == null) + m_signature = new Signature(this, m_declaringType); + + return m_signature; + } + } + + private RuntimeType ReflectedTypeInternal + { + get + { + return m_reflectedTypeCache.GetRuntimeType(); + } + } + + private void CheckConsistency(Object target) + { + if (target == null && IsStatic) + return; + + if (!m_declaringType.IsInstanceOfType(target)) + { + if (target == null) + throw new TargetException(Environment.GetResourceString("RFLCT.Targ_StatMethReqTarg")); + + throw new TargetException(Environment.GetResourceString("RFLCT.Targ_ITargMismatch")); + } + } + + internal BindingFlags BindingFlags { get { return m_bindingFlags; } } + #endregion + + #region Object Overrides + public override String ToString() + { + // "Void" really doesn't make sense here. But we'll keep it for compat reasons. + if (m_toString == null) + m_toString = "Void " + FormatNameAndSig(); + + return m_toString; + } + #endregion + + #region ICustomAttributeProvider + public override Object[] GetCustomAttributes(bool inherit) + { + return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); + } + + public override Object[] GetCustomAttributes(Type attributeType, bool inherit) + { + if (attributeType == null) + throw new ArgumentNullException(nameof(attributeType)); + Contract.EndContractBlock(); + + RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; + + if (attributeRuntimeType == null) + throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType)); + + return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType); + } + + public override bool IsDefined(Type attributeType, bool inherit) + { + if (attributeType == null) + throw new ArgumentNullException(nameof(attributeType)); + Contract.EndContractBlock(); + + RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; + + if (attributeRuntimeType == null) + throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType)); + + return CustomAttribute.IsDefined(this, attributeRuntimeType); + } + + public override IList GetCustomAttributesData() + { + return CustomAttributeData.GetCustomAttributesInternal(this); + } + #endregion + + + #region MemberInfo Overrides + public override String Name + { + get { return RuntimeMethodHandle.GetName(this); } + } + public override MemberTypes MemberType { get { return MemberTypes.Constructor; } } + + public override Type DeclaringType + { + get + { + return m_reflectedTypeCache.IsGlobal ? null : m_declaringType; + } + } + + public override Type ReflectedType + { + get + { + return m_reflectedTypeCache.IsGlobal ? null : ReflectedTypeInternal; + } + } + + public override int MetadataToken + { + get { return RuntimeMethodHandle.GetMethodDef(this); } + } + public override Module Module + { + get { return GetRuntimeModule(); } + } + + internal RuntimeType GetRuntimeType() { return m_declaringType; } + internal RuntimeModule GetRuntimeModule() { return RuntimeTypeHandle.GetModule(m_declaringType); } + internal RuntimeAssembly GetRuntimeAssembly() { return GetRuntimeModule().GetRuntimeAssembly(); } + #endregion + + #region MethodBase Overrides + + // This seems to always returns System.Void. + internal override Type GetReturnType() { return Signature.ReturnType; } + + internal override ParameterInfo[] GetParametersNoCopy() + { + if (m_parameters == null) + m_parameters = RuntimeParameterInfo.GetParameters(this, this, Signature); + + return m_parameters; + } + + [Pure] + public override ParameterInfo[] GetParameters() + { + ParameterInfo[] parameters = GetParametersNoCopy(); + + if (parameters.Length == 0) + return parameters; + + ParameterInfo[] ret = new ParameterInfo[parameters.Length]; + Array.Copy(parameters, ret, parameters.Length); + return ret; + } + + public override MethodImplAttributes GetMethodImplementationFlags() + { + return RuntimeMethodHandle.GetImplAttributes(this); + } + + public override RuntimeMethodHandle MethodHandle + { + get + { + Type declaringType = DeclaringType; + if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType) + throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAllowedInReflectionOnly")); + return new RuntimeMethodHandle(this); + } + } + + public override MethodAttributes Attributes + { + get + { + return m_methodAttributes; + } + } + + public override CallingConventions CallingConvention + { + get + { + return Signature.CallingConvention; + } + } + + internal static void CheckCanCreateInstance(Type declaringType, bool isVarArg) + { + if (declaringType == null) + throw new ArgumentNullException(nameof(declaringType)); + Contract.EndContractBlock(); + + // ctor is ReflectOnly + if (declaringType is ReflectionOnlyType) + throw new InvalidOperationException(Environment.GetResourceString("Arg_ReflectionOnlyInvoke")); + + // ctor is declared on interface class + else if (declaringType.IsInterface) + throw new MemberAccessException( + String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Acc_CreateInterfaceEx"), declaringType)); + + // ctor is on an abstract class + else if (declaringType.IsAbstract) + throw new MemberAccessException( + String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Acc_CreateAbstEx"), declaringType)); + + // ctor is on a class that contains stack pointers + else if (declaringType.GetRootElementType() == typeof(ArgIterator)) + throw new NotSupportedException(); + + // ctor is vararg + else if (isVarArg) + throw new NotSupportedException(); + + // ctor is generic or on a generic class + else if (declaringType.ContainsGenericParameters) + { + throw new MemberAccessException( + String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Acc_CreateGenericEx"), declaringType)); + } + + // ctor is declared on System.Void + else if (declaringType == typeof(void)) + throw new MemberAccessException(Environment.GetResourceString("Access_Void")); + } + + internal void ThrowNoInvokeException() + { + CheckCanCreateInstance(DeclaringType, (CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs); + + // ctor is .cctor + if ((Attributes & MethodAttributes.Static) == MethodAttributes.Static) + throw new MemberAccessException(Environment.GetResourceString("Acc_NotClassInit")); + + throw new TargetException(); + } + + [DebuggerStepThroughAttribute] + [Diagnostics.DebuggerHidden] + [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod + public override Object Invoke( + Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) + { + INVOCATION_FLAGS invocationFlags = InvocationFlags; + + if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE) != 0) + ThrowNoInvokeException(); + + // check basic method consistency. This call will throw if there are problems in the target/method relationship + CheckConsistency(obj); + + if (obj != null) + { + // For unverifiable code, we require the caller to be critical. + // Adding the INVOCATION_FLAGS_NEED_SECURITY flag makes that check happen + invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY; + } + + Signature sig = Signature; + + // get the signature + int formalCount = sig.Arguments.Length; + int actualCount = (parameters != null) ? parameters.Length : 0; + if (formalCount != actualCount) + throw new TargetParameterCountException(Environment.GetResourceString("Arg_ParmCnt")); + + // if we are here we passed all the previous checks. Time to look at the arguments + if (actualCount > 0) + { + Object[] arguments = CheckArguments(parameters, binder, invokeAttr, culture, sig); + Object retValue = RuntimeMethodHandle.InvokeMethod(obj, arguments, sig, false); + // copy out. This should be made only if ByRef are present. + for (int index = 0; index < arguments.Length; index++) + parameters[index] = arguments[index]; + return retValue; + } + return RuntimeMethodHandle.InvokeMethod(obj, null, sig, false); + } + + public override MethodBody GetMethodBody() + { + MethodBody mb = RuntimeMethodHandle.GetMethodBody(this, ReflectedTypeInternal); + if (mb != null) + mb.m_methodBase = this; + return mb; + } + + public override bool IsSecurityCritical + { + get { return true; } + } + + public override bool IsSecuritySafeCritical + { + get { return false; } + } + + public override bool IsSecurityTransparent + { + get { return false; } + } + + public override bool ContainsGenericParameters + { + get + { + return (DeclaringType != null && DeclaringType.ContainsGenericParameters); + } + } + #endregion + + #region ConstructorInfo Overrides + [DebuggerStepThroughAttribute] + [Diagnostics.DebuggerHidden] + [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod + public override Object Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) + { + INVOCATION_FLAGS invocationFlags = InvocationFlags; + + // get the declaring TypeHandle early for consistent exceptions in IntrospectionOnly context + RuntimeTypeHandle declaringTypeHandle = m_declaringType.TypeHandle; + + if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE | INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS | INVOCATION_FLAGS.INVOCATION_FLAGS_NO_CTOR_INVOKE)) != 0) + ThrowNoInvokeException(); + + // get the signature + Signature sig = Signature; + + int formalCount = sig.Arguments.Length; + int actualCount = (parameters != null) ? parameters.Length : 0; + if (formalCount != actualCount) + throw new TargetParameterCountException(Environment.GetResourceString("Arg_ParmCnt")); + + // We don't need to explicitly invoke the class constructor here, + // JIT/NGen will insert the call to .cctor in the instance ctor. + + // if we are here we passed all the previous checks. Time to look at the arguments + if (actualCount > 0) + { + Object[] arguments = CheckArguments(parameters, binder, invokeAttr, culture, sig); + Object retValue = RuntimeMethodHandle.InvokeMethod(null, arguments, sig, true); + // copy out. This should be made only if ByRef are present. + for (int index = 0; index < arguments.Length; index++) + parameters[index] = arguments[index]; + return retValue; + } + return RuntimeMethodHandle.InvokeMethod(null, null, sig, true); + } + #endregion + + #region ISerializable Implementation + public void GetObjectData(SerializationInfo info, StreamingContext context) + { + if (info == null) + throw new ArgumentNullException(nameof(info)); + Contract.EndContractBlock(); + MemberInfoSerializationHolder.GetSerializationInfo( + info, + Name, + ReflectedTypeInternal, + ToString(), + SerializationToString(), + MemberTypes.Constructor, + null); + } + + internal string SerializationToString() + { + // We don't need the return type for constructors. + return FormatNameAndSig(true); + } + #endregion + } +} diff --git a/src/coreclr/src/mscorlib/src/System/Reflection/RuntimeEventInfo.cs b/src/coreclr/src/mscorlib/src/System/Reflection/RuntimeEventInfo.cs new file mode 100644 index 0000000..8d82e26 --- /dev/null +++ b/src/coreclr/src/mscorlib/src/System/Reflection/RuntimeEventInfo.cs @@ -0,0 +1,224 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Collections.Generic; +using System.Diagnostics.Contracts; +using System.Runtime.Serialization; +using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; + +namespace System.Reflection +{ + [Serializable] + internal unsafe sealed class RuntimeEventInfo : EventInfo, ISerializable + { + #region Private Data Members + private int m_token; + private EventAttributes m_flags; + private string m_name; + private void* m_utf8name; + private RuntimeTypeCache m_reflectedTypeCache; + private RuntimeMethodInfo m_addMethod; + private RuntimeMethodInfo m_removeMethod; + private RuntimeMethodInfo m_raiseMethod; + private MethodInfo[] m_otherMethod; + private RuntimeType m_declaringType; + private BindingFlags m_bindingFlags; + #endregion + + #region Constructor + internal RuntimeEventInfo() + { + // Used for dummy head node during population + } + internal RuntimeEventInfo(int tkEvent, RuntimeType declaredType, RuntimeTypeCache reflectedTypeCache, out bool isPrivate) + { + Contract.Requires(declaredType != null); + Contract.Requires(reflectedTypeCache != null); + Debug.Assert(!reflectedTypeCache.IsGlobal); + + MetadataImport scope = declaredType.GetRuntimeModule().MetadataImport; + + m_token = tkEvent; + m_reflectedTypeCache = reflectedTypeCache; + m_declaringType = declaredType; + + + RuntimeType reflectedType = reflectedTypeCache.GetRuntimeType(); + + scope.GetEventProps(tkEvent, out m_utf8name, out m_flags); + + RuntimeMethodInfo dummy; + Associates.AssignAssociates(scope, tkEvent, declaredType, reflectedType, + out m_addMethod, out m_removeMethod, out m_raiseMethod, + out dummy, out dummy, out m_otherMethod, out isPrivate, out m_bindingFlags); + } + #endregion + + #region Internal Members + internal override bool CacheEquals(object o) + { + RuntimeEventInfo m = o as RuntimeEventInfo; + + if ((object)m == null) + return false; + + return m.m_token == m_token && + RuntimeTypeHandle.GetModule(m_declaringType).Equals( + RuntimeTypeHandle.GetModule(m.m_declaringType)); + } + + internal BindingFlags BindingFlags { get { return m_bindingFlags; } } + #endregion + + #region Object Overrides + public override String ToString() + { + if (m_addMethod == null || m_addMethod.GetParametersNoCopy().Length == 0) + throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NoPublicAddMethod")); + + return m_addMethod.GetParametersNoCopy()[0].ParameterType.FormatTypeName() + " " + Name; + } + #endregion + + #region ICustomAttributeProvider + public override Object[] GetCustomAttributes(bool inherit) + { + return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); + } + + public override Object[] GetCustomAttributes(Type attributeType, bool inherit) + { + if (attributeType == null) + throw new ArgumentNullException(nameof(attributeType)); + Contract.EndContractBlock(); + + RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; + + if (attributeRuntimeType == null) + throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType)); + + return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType); + } + + public override bool IsDefined(Type attributeType, bool inherit) + { + if (attributeType == null) + throw new ArgumentNullException(nameof(attributeType)); + Contract.EndContractBlock(); + + RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; + + if (attributeRuntimeType == null) + throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType)); + + return CustomAttribute.IsDefined(this, attributeRuntimeType); + } + + public override IList GetCustomAttributesData() + { + return CustomAttributeData.GetCustomAttributesInternal(this); + } + #endregion + + #region MemberInfo Overrides + public override MemberTypes MemberType { get { return MemberTypes.Event; } } + public override String Name + { + get + { + if (m_name == null) + m_name = new Utf8String(m_utf8name).ToString(); + + return m_name; + } + } + public override Type DeclaringType { get { return m_declaringType; } } + public override Type ReflectedType + { + get + { + return ReflectedTypeInternal; + } + } + + private RuntimeType ReflectedTypeInternal + { + get + { + return m_reflectedTypeCache.GetRuntimeType(); + } + } + + public override int MetadataToken { get { return m_token; } } + public override Module Module { get { return GetRuntimeModule(); } } + internal RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); } + #endregion + + #region ISerializable + public void GetObjectData(SerializationInfo info, StreamingContext context) + { + if (info == null) + throw new ArgumentNullException(nameof(info)); + Contract.EndContractBlock(); + + MemberInfoSerializationHolder.GetSerializationInfo( + info, + Name, + ReflectedTypeInternal, + null, + MemberTypes.Event); + } + #endregion + + #region EventInfo Overrides + public override MethodInfo[] GetOtherMethods(bool nonPublic) + { + List ret = new List(); + + if ((object)m_otherMethod == null) + return new MethodInfo[0]; + + for (int i = 0; i < m_otherMethod.Length; i++) + { + if (Associates.IncludeAccessor((MethodInfo)m_otherMethod[i], nonPublic)) + ret.Add(m_otherMethod[i]); + } + + return ret.ToArray(); + } + + public override MethodInfo GetAddMethod(bool nonPublic) + { + if (!Associates.IncludeAccessor(m_addMethod, nonPublic)) + return null; + + return m_addMethod; + } + + public override MethodInfo GetRemoveMethod(bool nonPublic) + { + if (!Associates.IncludeAccessor(m_removeMethod, nonPublic)) + return null; + + return m_removeMethod; + } + + public override MethodInfo GetRaiseMethod(bool nonPublic) + { + if (!Associates.IncludeAccessor(m_raiseMethod, nonPublic)) + return null; + + return m_raiseMethod; + } + + public override EventAttributes Attributes + { + get + { + return m_flags; + } + } + #endregion + } +} diff --git a/src/coreclr/src/mscorlib/src/System/Reflection/RuntimeFieldInfo.cs b/src/coreclr/src/mscorlib/src/System/Reflection/RuntimeFieldInfo.cs new file mode 100644 index 0000000..cc1beb7 --- /dev/null +++ b/src/coreclr/src/mscorlib/src/System/Reflection/RuntimeFieldInfo.cs @@ -0,0 +1,140 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Collections.Generic; +using System.Diagnostics.Contracts; +using System.Runtime.Serialization; +using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; + +namespace System.Reflection +{ + [Serializable] + internal abstract class RuntimeFieldInfo : FieldInfo, ISerializable + { + #region Private Data Members + private BindingFlags m_bindingFlags; + protected RuntimeTypeCache m_reflectedTypeCache; + protected RuntimeType m_declaringType; + #endregion + + #region Constructor + protected RuntimeFieldInfo() + { + // Used for dummy head node during population + } + protected RuntimeFieldInfo(RuntimeTypeCache reflectedTypeCache, RuntimeType declaringType, BindingFlags bindingFlags) + { + m_bindingFlags = bindingFlags; + m_declaringType = declaringType; + m_reflectedTypeCache = reflectedTypeCache; + } + #endregion + + #region NonPublic Members + internal BindingFlags BindingFlags { get { return m_bindingFlags; } } + private RuntimeType ReflectedTypeInternal + { + get + { + return m_reflectedTypeCache.GetRuntimeType(); + } + } + + internal RuntimeType GetDeclaringTypeInternal() + { + return m_declaringType; + } + + internal RuntimeType GetRuntimeType() { return m_declaringType; } + internal abstract RuntimeModule GetRuntimeModule(); + #endregion + + #region MemberInfo Overrides + public override MemberTypes MemberType { get { return MemberTypes.Field; } } + public override Type ReflectedType + { + get + { + return m_reflectedTypeCache.IsGlobal ? null : ReflectedTypeInternal; + } + } + + public override Type DeclaringType + { + get + { + return m_reflectedTypeCache.IsGlobal ? null : m_declaringType; + } + } + + public override Module Module { get { return GetRuntimeModule(); } } + #endregion + + #region Object Overrides + public unsafe override String ToString() + { + return FieldType.FormatTypeName() + " " + Name; + } + #endregion + + #region ICustomAttributeProvider + public override Object[] GetCustomAttributes(bool inherit) + { + return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); + } + + public override Object[] GetCustomAttributes(Type attributeType, bool inherit) + { + if (attributeType == null) + throw new ArgumentNullException(nameof(attributeType)); + Contract.EndContractBlock(); + + RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; + + if (attributeRuntimeType == null) + throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType)); + + return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType); + } + + public override bool IsDefined(Type attributeType, bool inherit) + { + if (attributeType == null) + throw new ArgumentNullException(nameof(attributeType)); + Contract.EndContractBlock(); + + RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; + + if (attributeRuntimeType == null) + throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType)); + + return CustomAttribute.IsDefined(this, attributeRuntimeType); + } + + public override IList GetCustomAttributesData() + { + return CustomAttributeData.GetCustomAttributesInternal(this); + } + #endregion + + #region FieldInfo Overrides + // All implemented on derived classes + #endregion + + #region ISerializable Implementation + public void GetObjectData(SerializationInfo info, StreamingContext context) + { + if (info == null) + throw new ArgumentNullException(nameof(info)); + Contract.EndContractBlock(); + MemberInfoSerializationHolder.GetSerializationInfo( + info, + Name, + ReflectedTypeInternal, + ToString(), + MemberTypes.Field); + } + #endregion + } +} diff --git a/src/coreclr/src/mscorlib/src/System/Reflection/RuntimeMethodInfo.cs b/src/coreclr/src/mscorlib/src/System/Reflection/RuntimeMethodInfo.cs new file mode 100644 index 0000000..a2530e2 --- /dev/null +++ b/src/coreclr/src/mscorlib/src/System/Reflection/RuntimeMethodInfo.cs @@ -0,0 +1,810 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.Contracts; +using System.Globalization; +using System.Runtime.Serialization; +using System.Security; +using System.Text; +using System.Threading; +using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; + +namespace System.Reflection +{ + [Serializable] + internal sealed class RuntimeMethodInfo : MethodInfo, ISerializable, IRuntimeMethodInfo + { + #region Private Data Members + private IntPtr m_handle; + private RuntimeTypeCache m_reflectedTypeCache; + private string m_name; + private string m_toString; + private ParameterInfo[] m_parameters; + private ParameterInfo m_returnParameter; + private BindingFlags m_bindingFlags; + private MethodAttributes m_methodAttributes; + private Signature m_signature; + private RuntimeType m_declaringType; + private object m_keepalive; + private INVOCATION_FLAGS m_invocationFlags; + + internal INVOCATION_FLAGS InvocationFlags + { + get + { + if ((m_invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0) + { + INVOCATION_FLAGS invocationFlags = INVOCATION_FLAGS.INVOCATION_FLAGS_UNKNOWN; + + Type declaringType = DeclaringType; + + // + // first take care of all the NO_INVOKE cases. + if (ContainsGenericParameters || + ReturnType.IsByRef || + (declaringType != null && declaringType.ContainsGenericParameters) || + ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) || + ((Attributes & MethodAttributes.RequireSecObject) == MethodAttributes.RequireSecObject)) + { + // We don't need other flags if this method cannot be invoked + invocationFlags = INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE; + } + else + { + // this should be an invocable method, determine the other flags that participate in invocation + invocationFlags = RuntimeMethodHandle.GetSecurityFlags(this); + + if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) == 0) + { + if ((Attributes & MethodAttributes.MemberAccessMask) != MethodAttributes.Public || + (declaringType != null && declaringType.NeedsReflectionSecurityCheck)) + { + // If method is non-public, or declaring type is not visible + invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY; + } + else if (IsGenericMethod) + { + Type[] genericArguments = GetGenericArguments(); + + for (int i = 0; i < genericArguments.Length; i++) + { + if (genericArguments[i].NeedsReflectionSecurityCheck) + { + invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY; + break; + } + } + } + } + } + + m_invocationFlags = invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED; + } + + return m_invocationFlags; + } + } + #endregion + + #region Constructor + internal RuntimeMethodInfo( + RuntimeMethodHandleInternal handle, RuntimeType declaringType, + RuntimeTypeCache reflectedTypeCache, MethodAttributes methodAttributes, BindingFlags bindingFlags, object keepalive) + { + Contract.Ensures(!m_handle.IsNull()); + + Debug.Assert(!handle.IsNullHandle()); + Debug.Assert(methodAttributes == RuntimeMethodHandle.GetAttributes(handle)); + + m_bindingFlags = bindingFlags; + m_declaringType = declaringType; + m_keepalive = keepalive; + m_handle = handle.Value; + m_reflectedTypeCache = reflectedTypeCache; + m_methodAttributes = methodAttributes; + } + #endregion + + #region Private Methods + RuntimeMethodHandleInternal IRuntimeMethodInfo.Value + { + get + { + return new RuntimeMethodHandleInternal(m_handle); + } + } + + private RuntimeType ReflectedTypeInternal + { + get + { + return m_reflectedTypeCache.GetRuntimeType(); + } + } + + private ParameterInfo[] FetchNonReturnParameters() + { + if (m_parameters == null) + m_parameters = RuntimeParameterInfo.GetParameters(this, this, Signature); + + return m_parameters; + } + + private ParameterInfo FetchReturnParameter() + { + if (m_returnParameter == null) + m_returnParameter = RuntimeParameterInfo.GetReturnParameter(this, this, Signature); + + return m_returnParameter; + } + #endregion + + #region Internal Members + internal override string FormatNameAndSig(bool serialization) + { + // Serialization uses ToString to resolve MethodInfo overloads. + StringBuilder sbName = new StringBuilder(Name); + + // serialization == true: use unambiguous (except for assembly name) type names to distinguish between overloads. + // serialization == false: use basic format to maintain backward compatibility of MethodInfo.ToString(). + TypeNameFormatFlags format = serialization ? TypeNameFormatFlags.FormatSerialization : TypeNameFormatFlags.FormatBasic; + + if (IsGenericMethod) + sbName.Append(RuntimeMethodHandle.ConstructInstantiation(this, format)); + + sbName.Append("("); + sbName.Append(ConstructParameters(GetParameterTypes(), CallingConvention, serialization)); + sbName.Append(")"); + + return sbName.ToString(); + } + + internal override bool CacheEquals(object o) + { + RuntimeMethodInfo m = o as RuntimeMethodInfo; + + if ((object)m == null) + return false; + + return m.m_handle == m_handle; + } + + internal Signature Signature + { + get + { + if (m_signature == null) + m_signature = new Signature(this, m_declaringType); + + return m_signature; + } + } + + internal BindingFlags BindingFlags { get { return m_bindingFlags; } } + + internal RuntimeMethodInfo GetParentDefinition() + { + if (!IsVirtual || m_declaringType.IsInterface) + return null; + + RuntimeType parent = (RuntimeType)m_declaringType.BaseType; + + if (parent == null) + return null; + + int slot = RuntimeMethodHandle.GetSlot(this); + + if (RuntimeTypeHandle.GetNumVirtuals(parent) <= slot) + return null; + + return (RuntimeMethodInfo)RuntimeType.GetMethodBase(parent, RuntimeTypeHandle.GetMethodAt(parent, slot)); + } + + // Unlike DeclaringType, this will return a valid type even for global methods + internal RuntimeType GetDeclaringTypeInternal() + { + return m_declaringType; + } + + #endregion + + #region Object Overrides + public override String ToString() + { + if (m_toString == null) + m_toString = ReturnType.FormatTypeName() + " " + FormatNameAndSig(); + + return m_toString; + } + + public override int GetHashCode() + { + // See RuntimeMethodInfo.Equals() below. + if (IsGenericMethod) + return ValueType.GetHashCodeOfPtr(m_handle); + else + return base.GetHashCode(); + } + + public override bool Equals(object obj) + { + if (!IsGenericMethod) + return obj == (object)this; + + // We cannot do simple object identity comparisons for generic methods. + // Equals will be called in CerHashTable when RuntimeType+RuntimeTypeCache.GetGenericMethodInfo() + // retrieve items from and insert items into s_methodInstantiations which is a CerHashtable. + + RuntimeMethodInfo mi = obj as RuntimeMethodInfo; + + if (mi == null || !mi.IsGenericMethod) + return false; + + // now we know that both operands are generic methods + + IRuntimeMethodInfo handle1 = RuntimeMethodHandle.StripMethodInstantiation(this); + IRuntimeMethodInfo handle2 = RuntimeMethodHandle.StripMethodInstantiation(mi); + if (handle1.Value.Value != handle2.Value.Value) + return false; + + Type[] lhs = GetGenericArguments(); + Type[] rhs = mi.GetGenericArguments(); + + if (lhs.Length != rhs.Length) + return false; + + for (int i = 0; i < lhs.Length; i++) + { + if (lhs[i] != rhs[i]) + return false; + } + + if (DeclaringType != mi.DeclaringType) + return false; + + if (ReflectedType != mi.ReflectedType) + return false; + + return true; + } + #endregion + + #region ICustomAttributeProvider + public override Object[] GetCustomAttributes(bool inherit) + { + return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType as RuntimeType, inherit); + } + + public override Object[] GetCustomAttributes(Type attributeType, bool inherit) + { + if (attributeType == null) + throw new ArgumentNullException(nameof(attributeType)); + Contract.EndContractBlock(); + + RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; + + if (attributeRuntimeType == null) + throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType)); + + return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType, inherit); + } + + public override bool IsDefined(Type attributeType, bool inherit) + { + if (attributeType == null) + throw new ArgumentNullException(nameof(attributeType)); + Contract.EndContractBlock(); + + RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; + + if (attributeRuntimeType == null) + throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType)); + + return CustomAttribute.IsDefined(this, attributeRuntimeType, inherit); + } + + public override IList GetCustomAttributesData() + { + return CustomAttributeData.GetCustomAttributesInternal(this); + } + #endregion + + #region MemberInfo Overrides + public override String Name + { + get + { + if (m_name == null) + m_name = RuntimeMethodHandle.GetName(this); + + return m_name; + } + } + + public override Type DeclaringType + { + get + { + if (m_reflectedTypeCache.IsGlobal) + return null; + + return m_declaringType; + } + } + + public override Type ReflectedType + { + get + { + if (m_reflectedTypeCache.IsGlobal) + return null; + + return m_reflectedTypeCache.GetRuntimeType(); + } + } + + public override MemberTypes MemberType { get { return MemberTypes.Method; } } + public override int MetadataToken + { + get { return RuntimeMethodHandle.GetMethodDef(this); } + } + public override Module Module { get { return GetRuntimeModule(); } } + internal RuntimeType GetRuntimeType() { return m_declaringType; } + internal RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); } + internal RuntimeAssembly GetRuntimeAssembly() { return GetRuntimeModule().GetRuntimeAssembly(); } + + public override bool IsSecurityCritical + { + get { return true; } + } + public override bool IsSecuritySafeCritical + { + get { return false; } + } + public override bool IsSecurityTransparent + { + get { return false; } + } + #endregion + + #region MethodBase Overrides + internal override ParameterInfo[] GetParametersNoCopy() + { + FetchNonReturnParameters(); + + return m_parameters; + } + + [System.Diagnostics.Contracts.Pure] + public override ParameterInfo[] GetParameters() + { + FetchNonReturnParameters(); + + if (m_parameters.Length == 0) + return m_parameters; + + ParameterInfo[] ret = new ParameterInfo[m_parameters.Length]; + + Array.Copy(m_parameters, ret, m_parameters.Length); + + return ret; + } + + public override MethodImplAttributes GetMethodImplementationFlags() + { + return RuntimeMethodHandle.GetImplAttributes(this); + } + + public override RuntimeMethodHandle MethodHandle + { + get + { + Type declaringType = DeclaringType; + if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType) + throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAllowedInReflectionOnly")); + return new RuntimeMethodHandle(this); + } + } + + public override MethodAttributes Attributes { get { return m_methodAttributes; } } + + public override CallingConventions CallingConvention + { + get + { + return Signature.CallingConvention; + } + } + + public override MethodBody GetMethodBody() + { + MethodBody mb = RuntimeMethodHandle.GetMethodBody(this, ReflectedTypeInternal); + if (mb != null) + mb.m_methodBase = this; + return mb; + } + #endregion + + #region Invocation Logic(On MemberBase) + private void CheckConsistency(Object target) + { + // only test instance methods + if ((m_methodAttributes & MethodAttributes.Static) != MethodAttributes.Static) + { + if (!m_declaringType.IsInstanceOfType(target)) + { + if (target == null) + throw new TargetException(Environment.GetResourceString("RFLCT.Targ_StatMethReqTarg")); + else + throw new TargetException(Environment.GetResourceString("RFLCT.Targ_ITargMismatch")); + } + } + } + + private void ThrowNoInvokeException() + { + // method is ReflectionOnly + Type declaringType = DeclaringType; + if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType) + { + throw new InvalidOperationException(Environment.GetResourceString("Arg_ReflectionOnlyInvoke")); + } + // method is on a class that contains stack pointers + else if ((InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS) != 0) + { + throw new NotSupportedException(); + } + // method is vararg + else if ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) + { + throw new NotSupportedException(); + } + // method is generic or on a generic class + else if (DeclaringType.ContainsGenericParameters || ContainsGenericParameters) + { + throw new InvalidOperationException(Environment.GetResourceString("Arg_UnboundGenParam")); + } + // method is abstract class + else if (IsAbstract) + { + throw new MemberAccessException(); + } + // ByRef return are not allowed in reflection + else if (ReturnType.IsByRef) + { + throw new NotSupportedException(Environment.GetResourceString("NotSupported_ByRefReturn")); + } + + throw new TargetException(); + } + + [DebuggerStepThroughAttribute] + [Diagnostics.DebuggerHidden] + [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod + public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) + { + object[] arguments = InvokeArgumentsCheck(obj, invokeAttr, binder, parameters, culture); + + return UnsafeInvokeInternal(obj, parameters, arguments); + } + + [DebuggerStepThroughAttribute] + [Diagnostics.DebuggerHidden] + internal object UnsafeInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) + { + object[] arguments = InvokeArgumentsCheck(obj, invokeAttr, binder, parameters, culture); + + return UnsafeInvokeInternal(obj, parameters, arguments); + } + + [DebuggerStepThroughAttribute] + [Diagnostics.DebuggerHidden] + private object UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) + { + if (arguments == null || arguments.Length == 0) + return RuntimeMethodHandle.InvokeMethod(obj, null, Signature, false); + else + { + Object retValue = RuntimeMethodHandle.InvokeMethod(obj, arguments, Signature, false); + + // copy out. This should be made only if ByRef are present. + for (int index = 0; index < arguments.Length; index++) + parameters[index] = arguments[index]; + + return retValue; + } + } + + [DebuggerStepThroughAttribute] + [Diagnostics.DebuggerHidden] + private object[] InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) + { + Signature sig = Signature; + + // get the signature + int formalCount = sig.Arguments.Length; + int actualCount = (parameters != null) ? parameters.Length : 0; + + INVOCATION_FLAGS invocationFlags = InvocationFlags; + + // INVOCATION_FLAGS_CONTAINS_STACK_POINTERS means that the struct (either the declaring type or the return type) + // contains pointers that point to the stack. This is either a ByRef or a TypedReference. These structs cannot + // be boxed and thus cannot be invoked through reflection which only deals with boxed value type objects. + if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE | INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS)) != 0) + ThrowNoInvokeException(); + + // check basic method consistency. This call will throw if there are problems in the target/method relationship + CheckConsistency(obj); + + if (formalCount != actualCount) + throw new TargetParameterCountException(Environment.GetResourceString("Arg_ParmCnt")); + + if (actualCount != 0) + return CheckArguments(parameters, binder, invokeAttr, culture, sig); + else + return null; + } + + #endregion + + #region MethodInfo Overrides + public override Type ReturnType + { + get { return Signature.ReturnType; } + } + + public override ICustomAttributeProvider ReturnTypeCustomAttributes + { + get { return ReturnParameter; } + } + + public override ParameterInfo ReturnParameter + { + get + { + Contract.Ensures(m_returnParameter != null); + + FetchReturnParameter(); + return m_returnParameter as ParameterInfo; + } + } + + public override MethodInfo GetBaseDefinition() + { + if (!IsVirtual || IsStatic || m_declaringType == null || m_declaringType.IsInterface) + return this; + + int slot = RuntimeMethodHandle.GetSlot(this); + RuntimeType declaringType = (RuntimeType)DeclaringType; + RuntimeType baseDeclaringType = declaringType; + RuntimeMethodHandleInternal baseMethodHandle = new RuntimeMethodHandleInternal(); + + do + { + int cVtblSlots = RuntimeTypeHandle.GetNumVirtuals(declaringType); + + if (cVtblSlots <= slot) + break; + + baseMethodHandle = RuntimeTypeHandle.GetMethodAt(declaringType, slot); + baseDeclaringType = declaringType; + + declaringType = (RuntimeType)declaringType.BaseType; + } while (declaringType != null); + + return (MethodInfo)RuntimeType.GetMethodBase(baseDeclaringType, baseMethodHandle); + } + + public override Delegate CreateDelegate(Type delegateType) + { + StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; + + // This API existed in v1/v1.1 and only expected to create closed + // instance delegates. Constrain the call to BindToMethodInfo to + // open delegates only for backwards compatibility. But we'll allow + // relaxed signature checking and open static delegates because + // there's no ambiguity there (the caller would have to explicitly + // pass us a static method or a method with a non-exact signature + // and the only change in behavior from v1.1 there is that we won't + // fail the call). + return CreateDelegateInternal( + delegateType, + null, + DelegateBindingFlags.OpenDelegateOnly | DelegateBindingFlags.RelaxedSignature, + ref stackMark); + } + + public override Delegate CreateDelegate(Type delegateType, Object target) + { + StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; + + // This API is new in Whidbey and allows the full range of delegate + // flexability (open or closed delegates binding to static or + // instance methods with relaxed signature checking). The delegate + // can also be closed over null. There's no ambiguity with all these + // options since the caller is providing us a specific MethodInfo. + return CreateDelegateInternal( + delegateType, + target, + DelegateBindingFlags.RelaxedSignature, + ref stackMark); + } + + private Delegate CreateDelegateInternal(Type delegateType, Object firstArgument, DelegateBindingFlags bindingFlags, ref StackCrawlMark stackMark) + { + // Validate the parameters. + if (delegateType == null) + throw new ArgumentNullException(nameof(delegateType)); + Contract.EndContractBlock(); + + RuntimeType rtType = delegateType as RuntimeType; + if (rtType == null) + throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(delegateType)); + + if (!rtType.IsDelegate()) + throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), nameof(delegateType)); + + Delegate d = Delegate.CreateDelegateInternal(rtType, this, firstArgument, bindingFlags, ref stackMark); + if (d == null) + { + throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTargMeth")); + } + + return d; + } + + #endregion + + #region Generics + public override MethodInfo MakeGenericMethod(params Type[] methodInstantiation) + { + if (methodInstantiation == null) + throw new ArgumentNullException(nameof(methodInstantiation)); + Contract.EndContractBlock(); + + RuntimeType[] methodInstantionRuntimeType = new RuntimeType[methodInstantiation.Length]; + + if (!IsGenericMethodDefinition) + throw new InvalidOperationException( + Environment.GetResourceString("Arg_NotGenericMethodDefinition", this)); + + for (int i = 0; i < methodInstantiation.Length; i++) + { + Type methodInstantiationElem = methodInstantiation[i]; + + if (methodInstantiationElem == null) + throw new ArgumentNullException(); + + RuntimeType rtMethodInstantiationElem = methodInstantiationElem as RuntimeType; + + if (rtMethodInstantiationElem == null) + { + Type[] methodInstantiationCopy = new Type[methodInstantiation.Length]; + for (int iCopy = 0; iCopy < methodInstantiation.Length; iCopy++) + methodInstantiationCopy[iCopy] = methodInstantiation[iCopy]; + methodInstantiation = methodInstantiationCopy; + return System.Reflection.Emit.MethodBuilderInstantiation.MakeGenericMethod(this, methodInstantiation); + } + + methodInstantionRuntimeType[i] = rtMethodInstantiationElem; + } + + RuntimeType[] genericParameters = GetGenericArgumentsInternal(); + + RuntimeType.SanityCheckGenericArguments(methodInstantionRuntimeType, genericParameters); + + MethodInfo ret = null; + + try + { + ret = RuntimeType.GetMethodBase(ReflectedTypeInternal, + RuntimeMethodHandle.GetStubIfNeeded(new RuntimeMethodHandleInternal(m_handle), m_declaringType, methodInstantionRuntimeType)) as MethodInfo; + } + catch (VerificationException e) + { + RuntimeType.ValidateGenericArguments(this, methodInstantionRuntimeType, e); + throw; + } + + return ret; + } + + internal RuntimeType[] GetGenericArgumentsInternal() + { + return RuntimeMethodHandle.GetMethodInstantiationInternal(this); + } + + public override Type[] GetGenericArguments() + { + Type[] types = RuntimeMethodHandle.GetMethodInstantiationPublic(this); + + if (types == null) + { + types = EmptyArray.Value; + } + return types; + } + + public override MethodInfo GetGenericMethodDefinition() + { + if (!IsGenericMethod) + throw new InvalidOperationException(); + Contract.EndContractBlock(); + + return RuntimeType.GetMethodBase(m_declaringType, RuntimeMethodHandle.StripMethodInstantiation(this)) as MethodInfo; + } + + public override bool IsGenericMethod + { + get { return RuntimeMethodHandle.HasMethodInstantiation(this); } + } + + public override bool IsGenericMethodDefinition + { + get { return RuntimeMethodHandle.IsGenericMethodDefinition(this); } + } + + public override bool ContainsGenericParameters + { + get + { + if (DeclaringType != null && DeclaringType.ContainsGenericParameters) + return true; + + if (!IsGenericMethod) + return false; + + Type[] pis = GetGenericArguments(); + for (int i = 0; i < pis.Length; i++) + { + if (pis[i].ContainsGenericParameters) + return true; + } + + return false; + } + } + #endregion + + #region ISerializable Implementation + public void GetObjectData(SerializationInfo info, StreamingContext context) + { + if (info == null) + throw new ArgumentNullException(nameof(info)); + Contract.EndContractBlock(); + + if (m_reflectedTypeCache.IsGlobal) + throw new NotSupportedException(Environment.GetResourceString("NotSupported_GlobalMethodSerialization")); + + MemberInfoSerializationHolder.GetSerializationInfo( + info, + Name, + ReflectedTypeInternal, + ToString(), + SerializationToString(), + MemberTypes.Method, + IsGenericMethod & !IsGenericMethodDefinition ? GetGenericArguments() : null); + } + + internal string SerializationToString() + { + return ReturnType.FormatTypeName(true) + " " + FormatNameAndSig(true); + } + #endregion + + #region Legacy Internal + internal static MethodBase InternalGetCurrentMethod(ref StackCrawlMark stackMark) + { + IRuntimeMethodInfo method = RuntimeMethodHandle.GetCurrentMethod(ref stackMark); + + if (method == null) + return null; + + return RuntimeType.GetMethodBase(method); + } + #endregion + } +} diff --git a/src/coreclr/src/mscorlib/src/System/Reflection/RuntimeModule.cs b/src/coreclr/src/mscorlib/src/System/Reflection/RuntimeModule.cs new file mode 100644 index 0000000..703aaff --- /dev/null +++ b/src/coreclr/src/mscorlib/src/System/Reflection/RuntimeModule.cs @@ -0,0 +1,603 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Runtime.InteropServices; +using System.Runtime.Serialization; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using System.Security; +using System.Globalization; +using System.Diagnostics.Contracts; + +namespace System.Reflection +{ + [Serializable] + internal class RuntimeModule : Module + { + internal RuntimeModule() { throw new NotSupportedException(); } + + #region FCalls + [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] + [SuppressUnmanagedCodeSecurity] + private extern static void GetType(RuntimeModule module, String className, bool ignoreCase, bool throwOnError, ObjectHandleOnStack type, ObjectHandleOnStack keepAlive); + + [DllImport(JitHelpers.QCall)] + [SuppressUnmanagedCodeSecurity] + private static extern bool nIsTransientInternal(RuntimeModule module); + + [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] + [SuppressUnmanagedCodeSecurity] + private extern static void GetScopeName(RuntimeModule module, StringHandleOnStack retString); + + [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] + [SuppressUnmanagedCodeSecurity] + private extern static void GetFullyQualifiedName(RuntimeModule module, StringHandleOnStack retString); + + [MethodImplAttribute(MethodImplOptions.InternalCall)] + private extern static RuntimeType[] GetTypes(RuntimeModule module); + + internal RuntimeType[] GetDefinedTypes() + { + return GetTypes(GetNativeHandle()); + } + + [MethodImplAttribute(MethodImplOptions.InternalCall)] + private extern static bool IsResource(RuntimeModule module); + #endregion + + #region Module overrides + private static RuntimeTypeHandle[] ConvertToTypeHandleArray(Type[] genericArguments) + { + if (genericArguments == null) + return null; + + int size = genericArguments.Length; + RuntimeTypeHandle[] typeHandleArgs = new RuntimeTypeHandle[size]; + for (int i = 0; i < size; i++) + { + Type typeArg = genericArguments[i]; + if (typeArg == null) + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidGenericInstArray")); + typeArg = typeArg.UnderlyingSystemType; + if (typeArg == null) + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidGenericInstArray")); + if (!(typeArg is RuntimeType)) + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidGenericInstArray")); + typeHandleArgs[i] = typeArg.GetTypeHandleInternal(); + } + return typeHandleArgs; + } + + public override byte[] ResolveSignature(int metadataToken) + { + MetadataToken tk = new MetadataToken(metadataToken); + + if (!MetadataImport.IsValidToken(tk)) + throw new ArgumentOutOfRangeException(nameof(metadataToken), + Environment.GetResourceString("Argument_InvalidToken", tk, this)); + + if (!tk.IsMemberRef && !tk.IsMethodDef && !tk.IsTypeSpec && !tk.IsSignature && !tk.IsFieldDef) + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidToken", tk, this), + nameof(metadataToken)); + + ConstArray signature; + if (tk.IsMemberRef) + signature = MetadataImport.GetMemberRefProps(metadataToken); + else + signature = MetadataImport.GetSignatureFromToken(metadataToken); + + byte[] sig = new byte[signature.Length]; + + for (int i = 0; i < signature.Length; i++) + sig[i] = signature[i]; + + return sig; + } + + public override MethodBase ResolveMethod(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) + { + MetadataToken tk = new MetadataToken(metadataToken); + + if (!MetadataImport.IsValidToken(tk)) + throw new ArgumentOutOfRangeException(nameof(metadataToken), + Environment.GetResourceString("Argument_InvalidToken", tk, this)); + + RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments); + RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments); + + try + { + if (!tk.IsMethodDef && !tk.IsMethodSpec) + { + if (!tk.IsMemberRef) + throw new ArgumentException(Environment.GetResourceString("Argument_ResolveMethod", tk, this), + nameof(metadataToken)); + + unsafe + { + ConstArray sig = MetadataImport.GetMemberRefProps(tk); + + if (*(MdSigCallingConvention*)sig.Signature.ToPointer() == MdSigCallingConvention.Field) + throw new ArgumentException(Environment.GetResourceString("Argument_ResolveMethod", tk, this), + nameof(metadataToken)); + } + } + + IRuntimeMethodInfo methodHandle = ModuleHandle.ResolveMethodHandleInternal(GetNativeHandle(), tk, typeArgs, methodArgs); + Type declaringType = RuntimeMethodHandle.GetDeclaringType(methodHandle); + + if (declaringType.IsGenericType || declaringType.IsArray) + { + MetadataToken tkDeclaringType = new MetadataToken(MetadataImport.GetParentToken(tk)); + + if (tk.IsMethodSpec) + tkDeclaringType = new MetadataToken(MetadataImport.GetParentToken(tkDeclaringType)); + + declaringType = ResolveType(tkDeclaringType, genericTypeArguments, genericMethodArguments); + } + + return System.RuntimeType.GetMethodBase(declaringType as RuntimeType, methodHandle); + } + catch (BadImageFormatException e) + { + throw new ArgumentException(Environment.GetResourceString("Argument_BadImageFormatExceptionResolve"), e); + } + } + + private FieldInfo ResolveLiteralField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) + { + MetadataToken tk = new MetadataToken(metadataToken); + + if (!MetadataImport.IsValidToken(tk) || !tk.IsFieldDef) + throw new ArgumentOutOfRangeException(nameof(metadataToken), + String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_InvalidToken", tk, this))); + + int tkDeclaringType; + string fieldName; + + fieldName = MetadataImport.GetName(tk).ToString(); + tkDeclaringType = MetadataImport.GetParentToken(tk); + + Type declaringType = ResolveType(tkDeclaringType, genericTypeArguments, genericMethodArguments); + + declaringType.GetFields(); + + try + { + return declaringType.GetField(fieldName, + BindingFlags.Static | BindingFlags.Instance | + BindingFlags.Public | BindingFlags.NonPublic | + BindingFlags.DeclaredOnly); + } + catch + { + throw new ArgumentException(Environment.GetResourceString("Argument_ResolveField", tk, this), nameof(metadataToken)); + } + } + + public override FieldInfo ResolveField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) + { + MetadataToken tk = new MetadataToken(metadataToken); + + if (!MetadataImport.IsValidToken(tk)) + throw new ArgumentOutOfRangeException(nameof(metadataToken), + Environment.GetResourceString("Argument_InvalidToken", tk, this)); + + RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments); + RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments); + + try + { + IRuntimeFieldInfo fieldHandle = null; + + if (!tk.IsFieldDef) + { + if (!tk.IsMemberRef) + throw new ArgumentException(Environment.GetResourceString("Argument_ResolveField", tk, this), + nameof(metadataToken)); + + unsafe + { + ConstArray sig = MetadataImport.GetMemberRefProps(tk); + + if (*(MdSigCallingConvention*)sig.Signature.ToPointer() != MdSigCallingConvention.Field) + throw new ArgumentException(Environment.GetResourceString("Argument_ResolveField", tk, this), + nameof(metadataToken)); + } + + fieldHandle = ModuleHandle.ResolveFieldHandleInternal(GetNativeHandle(), tk, typeArgs, methodArgs); + } + + fieldHandle = ModuleHandle.ResolveFieldHandleInternal(GetNativeHandle(), metadataToken, typeArgs, methodArgs); + RuntimeType declaringType = RuntimeFieldHandle.GetApproxDeclaringType(fieldHandle.Value); + + if (declaringType.IsGenericType || declaringType.IsArray) + { + int tkDeclaringType = ModuleHandle.GetMetadataImport(GetNativeHandle()).GetParentToken(metadataToken); + declaringType = (RuntimeType)ResolveType(tkDeclaringType, genericTypeArguments, genericMethodArguments); + } + + return System.RuntimeType.GetFieldInfo(declaringType, fieldHandle); + } + catch (MissingFieldException) + { + return ResolveLiteralField(tk, genericTypeArguments, genericMethodArguments); + } + catch (BadImageFormatException e) + { + throw new ArgumentException(Environment.GetResourceString("Argument_BadImageFormatExceptionResolve"), e); + } + } + + public override Type ResolveType(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) + { + MetadataToken tk = new MetadataToken(metadataToken); + + if (tk.IsGlobalTypeDefToken) + throw new ArgumentException(Environment.GetResourceString("Argument_ResolveModuleType", tk), nameof(metadataToken)); + + if (!MetadataImport.IsValidToken(tk)) + throw new ArgumentOutOfRangeException(nameof(metadataToken), + Environment.GetResourceString("Argument_InvalidToken", tk, this)); + + if (!tk.IsTypeDef && !tk.IsTypeSpec && !tk.IsTypeRef) + throw new ArgumentException(Environment.GetResourceString("Argument_ResolveType", tk, this), nameof(metadataToken)); + + RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments); + RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments); + + try + { + Type t = GetModuleHandle().ResolveTypeHandle(metadataToken, typeArgs, methodArgs).GetRuntimeType(); + + if (t == null) + throw new ArgumentException(Environment.GetResourceString("Argument_ResolveType", tk, this), nameof(metadataToken)); + + return t; + } + catch (BadImageFormatException e) + { + throw new ArgumentException(Environment.GetResourceString("Argument_BadImageFormatExceptionResolve"), e); + } + } + + public override MemberInfo ResolveMember(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) + { + MetadataToken tk = new MetadataToken(metadataToken); + + if (tk.IsProperty) + throw new ArgumentException(Environment.GetResourceString("InvalidOperation_PropertyInfoNotAvailable")); + + if (tk.IsEvent) + throw new ArgumentException(Environment.GetResourceString("InvalidOperation_EventInfoNotAvailable")); + + if (tk.IsMethodSpec || tk.IsMethodDef) + return ResolveMethod(metadataToken, genericTypeArguments, genericMethodArguments); + + if (tk.IsFieldDef) + return ResolveField(metadataToken, genericTypeArguments, genericMethodArguments); + + if (tk.IsTypeRef || tk.IsTypeDef || tk.IsTypeSpec) + return ResolveType(metadataToken, genericTypeArguments, genericMethodArguments); + + if (tk.IsMemberRef) + { + if (!MetadataImport.IsValidToken(tk)) + throw new ArgumentOutOfRangeException(nameof(metadataToken), + Environment.GetResourceString("Argument_InvalidToken", tk, this)); + + ConstArray sig = MetadataImport.GetMemberRefProps(tk); + + unsafe + { + if (*(MdSigCallingConvention*)sig.Signature.ToPointer() == MdSigCallingConvention.Field) + { + return ResolveField(tk, genericTypeArguments, genericMethodArguments); + } + else + { + return ResolveMethod(tk, genericTypeArguments, genericMethodArguments); + } + } + } + + throw new ArgumentException(Environment.GetResourceString("Argument_ResolveMember", tk, this), + nameof(metadataToken)); + } + + public override string ResolveString(int metadataToken) + { + MetadataToken tk = new MetadataToken(metadataToken); + if (!tk.IsString) + throw new ArgumentException( + String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_ResolveString"), metadataToken, ToString())); + + if (!MetadataImport.IsValidToken(tk)) + throw new ArgumentOutOfRangeException(nameof(metadataToken), + String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_InvalidToken", tk, this))); + + string str = MetadataImport.GetUserString(metadataToken); + + if (str == null) + throw new ArgumentException( + String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_ResolveString"), metadataToken, ToString())); + + return str; + } + + public override void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine) + { + ModuleHandle.GetPEKind(GetNativeHandle(), out peKind, out machine); + } + + public override int MDStreamVersion + { + get + { + return ModuleHandle.GetMDStreamVersion(GetNativeHandle()); + } + } + #endregion + + #region Data Members +#pragma warning disable 169 + // If you add any data members, you need to update the native declaration ReflectModuleBaseObject. + private RuntimeType m_runtimeType; + private RuntimeAssembly m_runtimeAssembly; + private IntPtr m_pRefClass; + private IntPtr m_pData; + private IntPtr m_pGlobals; + private IntPtr m_pFields; +#pragma warning restore 169 + #endregion + + #region Protected Virtuals + protected override MethodInfo GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder, + CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) + { + return GetMethodInternal(name, bindingAttr, binder, callConvention, types, modifiers); + } + + internal MethodInfo GetMethodInternal(String name, BindingFlags bindingAttr, Binder binder, + CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) + { + if (RuntimeType == null) + return null; + + if (types == null) + { + return RuntimeType.GetMethod(name, bindingAttr); + } + else + { + return RuntimeType.GetMethod(name, bindingAttr, binder, callConvention, types, modifiers); + } + } + #endregion + + #region Internal Members + internal RuntimeType RuntimeType + { + get + { + if (m_runtimeType == null) + m_runtimeType = ModuleHandle.GetModuleType(GetNativeHandle()); + + return m_runtimeType; + } + } + + internal bool IsTransientInternal() + { + return RuntimeModule.nIsTransientInternal(this.GetNativeHandle()); + } + + internal MetadataImport MetadataImport + { + get + { + unsafe + { + return ModuleHandle.GetMetadataImport(GetNativeHandle()); + } + } + } + #endregion + + #region ICustomAttributeProvider Members + public override Object[] GetCustomAttributes(bool inherit) + { + return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); + } + + public override Object[] GetCustomAttributes(Type attributeType, bool inherit) + { + if (attributeType == null) + throw new ArgumentNullException(nameof(attributeType)); + Contract.EndContractBlock(); + + RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; + + if (attributeRuntimeType == null) + throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType)); + + return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType); + } + + public override bool IsDefined(Type attributeType, bool inherit) + { + if (attributeType == null) + throw new ArgumentNullException(nameof(attributeType)); + Contract.EndContractBlock(); + + RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; + + if (attributeRuntimeType == null) + throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType)); + + return CustomAttribute.IsDefined(this, attributeRuntimeType); + } + + public override IList GetCustomAttributesData() + { + return CustomAttributeData.GetCustomAttributesInternal(this); + } + #endregion + + #region Public Virtuals + public override void GetObjectData(SerializationInfo info, StreamingContext context) + { + if (info == null) + { + throw new ArgumentNullException(nameof(info)); + } + Contract.EndContractBlock(); + UnitySerializationHolder.GetUnitySerializationInfo(info, UnitySerializationHolder.ModuleUnity, this.ScopeName, this.GetRuntimeAssembly()); + } + + public override Type GetType(String className, bool throwOnError, bool ignoreCase) + { + // throw on null strings regardless of the value of "throwOnError" + if (className == null) + throw new ArgumentNullException(nameof(className)); + + RuntimeType retType = null; + Object keepAlive = null; + GetType(GetNativeHandle(), className, throwOnError, ignoreCase, JitHelpers.GetObjectHandleOnStack(ref retType), JitHelpers.GetObjectHandleOnStack(ref keepAlive)); + GC.KeepAlive(keepAlive); + return retType; + } + + internal string GetFullyQualifiedName() + { + String fullyQualifiedName = null; + GetFullyQualifiedName(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref fullyQualifiedName)); + return fullyQualifiedName; + } + + public override String FullyQualifiedName + { + get + { + return GetFullyQualifiedName(); + } + } + + public override Type[] GetTypes() + { + return GetTypes(GetNativeHandle()); + } + + #endregion + + #region Public Members + + public override Guid ModuleVersionId + { + get + { + unsafe + { + Guid mvid; + MetadataImport.GetScopeProps(out mvid); + return mvid; + } + } + } + + public override int MetadataToken + { + get + { + return ModuleHandle.GetToken(GetNativeHandle()); + } + } + + public override bool IsResource() + { + return IsResource(GetNativeHandle()); + } + + public override FieldInfo[] GetFields(BindingFlags bindingFlags) + { + if (RuntimeType == null) + return new FieldInfo[0]; + + return RuntimeType.GetFields(bindingFlags); + } + + public override FieldInfo GetField(String name, BindingFlags bindingAttr) + { + if (name == null) + throw new ArgumentNullException(nameof(name)); + + if (RuntimeType == null) + return null; + + return RuntimeType.GetField(name, bindingAttr); + } + + public override MethodInfo[] GetMethods(BindingFlags bindingFlags) + { + if (RuntimeType == null) + return new MethodInfo[0]; + + return RuntimeType.GetMethods(bindingFlags); + } + + public override String ScopeName + { + get + { + string scopeName = null; + GetScopeName(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref scopeName)); + return scopeName; + } + } + + public override String Name + { + get + { + String s = GetFullyQualifiedName(); + +#if !FEATURE_PAL + int i = s.LastIndexOf('\\'); +#else + int i = s.LastIndexOf(System.IO.Path.DirectorySeparatorChar); +#endif + if (i == -1) + return s; + + return s.Substring(i + 1); + } + } + + public override Assembly Assembly + { + [Pure] + get + { + return GetRuntimeAssembly(); + } + } + + internal RuntimeAssembly GetRuntimeAssembly() + { + return m_runtimeAssembly; + } + + + internal override ModuleHandle GetModuleHandle() + { + return new ModuleHandle(this); + } + + internal RuntimeModule GetNativeHandle() + { + return this; + } + #endregion + } +} diff --git a/src/coreclr/src/mscorlib/src/System/Reflection/RuntimeParameterInfo.cs b/src/coreclr/src/mscorlib/src/System/Reflection/RuntimeParameterInfo.cs new file mode 100644 index 0000000..516df6c --- /dev/null +++ b/src/coreclr/src/mscorlib/src/System/Reflection/RuntimeParameterInfo.cs @@ -0,0 +1,515 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Collections.Generic; +using System.Diagnostics.Contracts; +using System.Runtime.Serialization; +using System.Runtime.CompilerServices; +using MdToken = System.Reflection.MetadataToken; + +namespace System.Reflection +{ + [Serializable] + internal unsafe sealed class RuntimeParameterInfo : ParameterInfo, ISerializable + { + #region Static Members + internal unsafe static ParameterInfo[] GetParameters(IRuntimeMethodInfo method, MemberInfo member, Signature sig) + { + Debug.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo); + + ParameterInfo dummy; + return GetParameters(method, member, sig, out dummy, false); + } + + internal unsafe static ParameterInfo GetReturnParameter(IRuntimeMethodInfo method, MemberInfo member, Signature sig) + { + Debug.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo); + + ParameterInfo returnParameter; + GetParameters(method, member, sig, out returnParameter, true); + return returnParameter; + } + + internal unsafe static ParameterInfo[] GetParameters( + IRuntimeMethodInfo methodHandle, MemberInfo member, Signature sig, out ParameterInfo returnParameter, bool fetchReturnParameter) + { + returnParameter = null; + int sigArgCount = sig.Arguments.Length; + ParameterInfo[] args = fetchReturnParameter ? null : new ParameterInfo[sigArgCount]; + + int tkMethodDef = RuntimeMethodHandle.GetMethodDef(methodHandle); + int cParamDefs = 0; + + // Not all methods have tokens. Arrays, pointers and byRef types do not have tokens as they + // are generated on the fly by the runtime. + if (!MdToken.IsNullToken(tkMethodDef)) + { + MetadataImport scope = RuntimeTypeHandle.GetMetadataImport(RuntimeMethodHandle.GetDeclaringType(methodHandle)); + + MetadataEnumResult tkParamDefs; + scope.EnumParams(tkMethodDef, out tkParamDefs); + + cParamDefs = tkParamDefs.Length; + + // Not all parameters have tokens. Parameters may have no token + // if they have no name and no attributes. + if (cParamDefs > sigArgCount + 1 /* return type */) + throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ParameterSignatureMismatch")); + + for (int i = 0; i < cParamDefs; i++) + { + #region Populate ParameterInfos + ParameterAttributes attr; + int position, tkParamDef = tkParamDefs[i]; + + scope.GetParamDefProps(tkParamDef, out position, out attr); + + position--; + + if (fetchReturnParameter == true && position == -1) + { + // more than one return parameter? + if (returnParameter != null) + throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ParameterSignatureMismatch")); + + returnParameter = new RuntimeParameterInfo(sig, scope, tkParamDef, position, attr, member); + } + else if (fetchReturnParameter == false && position >= 0) + { + // position beyong sigArgCount? + if (position >= sigArgCount) + throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ParameterSignatureMismatch")); + + args[position] = new RuntimeParameterInfo(sig, scope, tkParamDef, position, attr, member); + } + #endregion + } + } + + // Fill in empty ParameterInfos for those without tokens + if (fetchReturnParameter) + { + if (returnParameter == null) + { + returnParameter = new RuntimeParameterInfo(sig, MetadataImport.EmptyImport, 0, -1, (ParameterAttributes)0, member); + } + } + else + { + if (cParamDefs < args.Length + 1) + { + for (int i = 0; i < args.Length; i++) + { + if (args[i] != null) + continue; + + args[i] = new RuntimeParameterInfo(sig, MetadataImport.EmptyImport, 0, i, (ParameterAttributes)0, member); + } + } + } + + return args; + } + #endregion + + #region Private Statics + private static readonly Type s_DecimalConstantAttributeType = typeof(DecimalConstantAttribute); + private static readonly Type s_CustomConstantAttributeType = typeof(CustomConstantAttribute); + #endregion + + #region Private Data Members + // These are new in Whidbey, so we cannot serialize them directly or we break backwards compatibility. + [NonSerialized] + private int m_tkParamDef; + [NonSerialized] + private MetadataImport m_scope; + [NonSerialized] + private Signature m_signature; + [NonSerialized] + private volatile bool m_nameIsCached = false; + [NonSerialized] + private readonly bool m_noMetadata = false; + [NonSerialized] + private bool m_noDefaultValue = false; + [NonSerialized] + private MethodBase m_originalMember = null; + #endregion + + #region Internal Properties + internal MethodBase DefiningMethod + { + get + { + MethodBase result = m_originalMember != null ? m_originalMember : MemberImpl as MethodBase; + Debug.Assert(result != null); + return result; + } + } + #endregion + + #region VTS magic to serialize/deserialized to/from pre-Whidbey endpoints. + public void GetObjectData(SerializationInfo info, StreamingContext context) + { + if (info == null) + throw new ArgumentNullException(nameof(info)); + Contract.EndContractBlock(); + + // We could be serializing for consumption by a pre-Whidbey + // endpoint. Therefore we set up all the serialized fields to look + // just like a v1.0/v1.1 instance. + + // Need to set the type to ParameterInfo so that pre-Whidbey and Whidbey code + // can deserialize this. This is also why we cannot simply use [OnSerializing]. + info.SetType(typeof(ParameterInfo)); + + // Use the properties intead of the fields in case the fields haven't been et + // _importer, bExtraConstChecked, and m_cachedData don't need to be set + + // Now set the legacy fields that the current implementation doesn't + // use any more. Note that _importer is a raw pointer that should + // never have been serialized in V1. We set it to zero here; if the + // deserializer uses it (by calling GetCustomAttributes() on this + // instance) they'll AV, but at least it will be a well defined + // exception and not a random AV. + + info.AddValue("AttrsImpl", Attributes); + info.AddValue("ClassImpl", ParameterType); + info.AddValue("DefaultValueImpl", DefaultValue); + info.AddValue("MemberImpl", Member); + info.AddValue("NameImpl", Name); + info.AddValue("PositionImpl", Position); + info.AddValue("_token", m_tkParamDef); + } + #endregion + + #region Constructor + // used by RuntimePropertyInfo + internal RuntimeParameterInfo(RuntimeParameterInfo accessor, RuntimePropertyInfo property) + : this(accessor, (MemberInfo)property) + { + m_signature = property.Signature; + } + + private RuntimeParameterInfo(RuntimeParameterInfo accessor, MemberInfo member) + { + // Change ownership + MemberImpl = member; + + // The original owner should always be a method, because this method is only used to + // change the owner from a method to a property. + m_originalMember = accessor.MemberImpl as MethodBase; + Debug.Assert(m_originalMember != null); + + // Populate all the caches -- we inherit this behavior from RTM + NameImpl = accessor.Name; + m_nameIsCached = true; + ClassImpl = accessor.ParameterType; + PositionImpl = accessor.Position; + AttrsImpl = accessor.Attributes; + + // Strictly speeking, property's don't contain paramter tokens + // However we need this to make ca's work... oh well... + m_tkParamDef = MdToken.IsNullToken(accessor.MetadataToken) ? (int)MetadataTokenType.ParamDef : accessor.MetadataToken; + m_scope = accessor.m_scope; + } + + private RuntimeParameterInfo( + Signature signature, MetadataImport scope, int tkParamDef, + int position, ParameterAttributes attributes, MemberInfo member) + { + Contract.Requires(member != null); + Debug.Assert(MdToken.IsNullToken(tkParamDef) == scope.Equals(MetadataImport.EmptyImport)); + Debug.Assert(MdToken.IsNullToken(tkParamDef) || MdToken.IsTokenOfType(tkParamDef, MetadataTokenType.ParamDef)); + + PositionImpl = position; + MemberImpl = member; + m_signature = signature; + m_tkParamDef = MdToken.IsNullToken(tkParamDef) ? (int)MetadataTokenType.ParamDef : tkParamDef; + m_scope = scope; + AttrsImpl = attributes; + + ClassImpl = null; + NameImpl = null; + } + + // ctor for no metadata MethodInfo in the DynamicMethod and RuntimeMethodInfo cases + internal RuntimeParameterInfo(MethodInfo owner, String name, Type parameterType, int position) + { + MemberImpl = owner; + NameImpl = name; + m_nameIsCached = true; + m_noMetadata = true; + ClassImpl = parameterType; + PositionImpl = position; + AttrsImpl = ParameterAttributes.None; + m_tkParamDef = (int)MetadataTokenType.ParamDef; + m_scope = MetadataImport.EmptyImport; + } + #endregion + + #region Public Methods + public override Type ParameterType + { + get + { + // only instance of ParameterInfo has ClassImpl, all its subclasses don't + if (ClassImpl == null) + { + RuntimeType parameterType; + if (PositionImpl == -1) + parameterType = m_signature.ReturnType; + else + parameterType = m_signature.Arguments[PositionImpl]; + + Debug.Assert(parameterType != null); + // different thread could only write ClassImpl to the same value, so a race condition is not a problem here + ClassImpl = parameterType; + } + + return ClassImpl; + } + } + + public override String Name + { + get + { + if (!m_nameIsCached) + { + if (!MdToken.IsNullToken(m_tkParamDef)) + { + string name; + name = m_scope.GetName(m_tkParamDef).ToString(); + NameImpl = name; + } + + // other threads could only write it to true, so a race condition is OK + // this field is volatile, so the write ordering is guaranteed + m_nameIsCached = true; + } + + // name may be null + return NameImpl; + } + } + + public override bool HasDefaultValue + { + get + { + if (m_noMetadata || m_noDefaultValue) + return false; + + object defaultValue = GetDefaultValueInternal(false); + + return (defaultValue != DBNull.Value); + } + } + + public override Object DefaultValue { get { return GetDefaultValue(false); } } + public override Object RawDefaultValue { get { return GetDefaultValue(true); } } + + private Object GetDefaultValue(bool raw) + { + // OLD COMMENT (Is this even true?) + // Cannot cache because default value could be non-agile user defined enumeration. + // OLD COMMENT ends + if (m_noMetadata) + return null; + + // for dynamic method we pretend to have cached the value so we do not go to metadata + object defaultValue = GetDefaultValueInternal(raw); + + if (defaultValue == DBNull.Value) + { + #region Handle case if no default value was found + if (IsOptional) + { + // If the argument is marked as optional then the default value is Missing.Value. + defaultValue = Type.Missing; + } + #endregion + } + + return defaultValue; + } + + // returns DBNull.Value if the parameter doesn't have a default value + private Object GetDefaultValueInternal(bool raw) + { + Debug.Assert(!m_noMetadata); + + if (m_noDefaultValue) + return DBNull.Value; + + object defaultValue = null; + + // Why check the parameter type only for DateTime and only for the ctor arguments? + // No check on the parameter type is done for named args and for Decimal. + + // We should move this after MdToken.IsNullToken(m_tkParamDef) and combine it + // with the other custom attribute logic. But will that be a breaking change? + // For a DateTime parameter on which both an md constant and a ca constant are set, + // which one should win? + if (ParameterType == typeof(DateTime)) + { + if (raw) + { + CustomAttributeTypedArgument value = + CustomAttributeData.Filter( + CustomAttributeData.GetCustomAttributes(this), typeof(DateTimeConstantAttribute), 0); + + if (value.ArgumentType != null) + return new DateTime((long)value.Value); + } + else + { + object[] dt = GetCustomAttributes(typeof(DateTimeConstantAttribute), false); + if (dt != null && dt.Length != 0) + return ((DateTimeConstantAttribute)dt[0]).Value; + } + } + + #region Look for a default value in metadata + if (!MdToken.IsNullToken(m_tkParamDef)) + { + // This will return DBNull.Value if no constant value is defined on m_tkParamDef in the metadata. + defaultValue = MdConstant.GetValue(m_scope, m_tkParamDef, ParameterType.GetTypeHandleInternal(), raw); + } + #endregion + + if (defaultValue == DBNull.Value) + { + #region Look for a default value in the custom attributes + if (raw) + { + foreach (CustomAttributeData attr in CustomAttributeData.GetCustomAttributes(this)) + { + Type attrType = attr.Constructor.DeclaringType; + + if (attrType == typeof(DateTimeConstantAttribute)) + { + defaultValue = DateTimeConstantAttribute.GetRawDateTimeConstant(attr); + } + else if (attrType == typeof(DecimalConstantAttribute)) + { + defaultValue = DecimalConstantAttribute.GetRawDecimalConstant(attr); + } + else if (attrType.IsSubclassOf(s_CustomConstantAttributeType)) + { + defaultValue = CustomConstantAttribute.GetRawConstant(attr); + } + } + } + else + { + Object[] CustomAttrs = GetCustomAttributes(s_CustomConstantAttributeType, false); + if (CustomAttrs.Length != 0) + { + defaultValue = ((CustomConstantAttribute)CustomAttrs[0]).Value; + } + else + { + CustomAttrs = GetCustomAttributes(s_DecimalConstantAttributeType, false); + if (CustomAttrs.Length != 0) + { + defaultValue = ((DecimalConstantAttribute)CustomAttrs[0]).Value; + } + } + } + #endregion + } + + if (defaultValue == DBNull.Value) + m_noDefaultValue = true; + + return defaultValue; + } + + internal RuntimeModule GetRuntimeModule() + { + RuntimeMethodInfo method = Member as RuntimeMethodInfo; + RuntimeConstructorInfo constructor = Member as RuntimeConstructorInfo; + RuntimePropertyInfo property = Member as RuntimePropertyInfo; + + if (method != null) + return method.GetRuntimeModule(); + else if (constructor != null) + return constructor.GetRuntimeModule(); + else if (property != null) + return property.GetRuntimeModule(); + else + return null; + } + + public override int MetadataToken + { + get + { + return m_tkParamDef; + } + } + + public override Type[] GetRequiredCustomModifiers() + { + return m_signature.GetCustomModifiers(PositionImpl + 1, true); + } + + public override Type[] GetOptionalCustomModifiers() + { + return m_signature.GetCustomModifiers(PositionImpl + 1, false); + } + + #endregion + + #region ICustomAttributeProvider + public override Object[] GetCustomAttributes(bool inherit) + { + if (MdToken.IsNullToken(m_tkParamDef)) + return EmptyArray.Value; + + return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); + } + + public override Object[] GetCustomAttributes(Type attributeType, bool inherit) + { + if (attributeType == null) + throw new ArgumentNullException(nameof(attributeType)); + Contract.EndContractBlock(); + + if (MdToken.IsNullToken(m_tkParamDef)) + return EmptyArray.Value; + + RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; + + if (attributeRuntimeType == null) + throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType)); + + return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType); + } + + public override bool IsDefined(Type attributeType, bool inherit) + { + if (attributeType == null) + throw new ArgumentNullException(nameof(attributeType)); + Contract.EndContractBlock(); + + if (MdToken.IsNullToken(m_tkParamDef)) + return false; + + RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; + + if (attributeRuntimeType == null) + throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType)); + + return CustomAttribute.IsDefined(this, attributeRuntimeType); + } + + public override IList GetCustomAttributesData() + { + return CustomAttributeData.GetCustomAttributesInternal(this); + } + #endregion + } +} diff --git a/src/coreclr/src/mscorlib/src/System/Reflection/RuntimePropertyInfo.cs b/src/coreclr/src/mscorlib/src/System/Reflection/RuntimePropertyInfo.cs new file mode 100644 index 0000000..5726081 --- /dev/null +++ b/src/coreclr/src/mscorlib/src/System/Reflection/RuntimePropertyInfo.cs @@ -0,0 +1,474 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.Contracts; +using System.Globalization; +using System.Runtime.Serialization; +using System.Text; +using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; + +namespace System.Reflection +{ + [Serializable] + internal unsafe sealed class RuntimePropertyInfo : PropertyInfo, ISerializable + { + #region Private Data Members + private int m_token; + private string m_name; + private void* m_utf8name; + private PropertyAttributes m_flags; + private RuntimeTypeCache m_reflectedTypeCache; + private RuntimeMethodInfo m_getterMethod; + private RuntimeMethodInfo m_setterMethod; + private MethodInfo[] m_otherMethod; + private RuntimeType m_declaringType; + private BindingFlags m_bindingFlags; + private Signature m_signature; + private ParameterInfo[] m_parameters; + #endregion + + #region Constructor + internal RuntimePropertyInfo( + int tkProperty, RuntimeType declaredType, RuntimeTypeCache reflectedTypeCache, out bool isPrivate) + { + Contract.Requires(declaredType != null); + Contract.Requires(reflectedTypeCache != null); + Debug.Assert(!reflectedTypeCache.IsGlobal); + + MetadataImport scope = declaredType.GetRuntimeModule().MetadataImport; + + m_token = tkProperty; + m_reflectedTypeCache = reflectedTypeCache; + m_declaringType = declaredType; + + ConstArray sig; + scope.GetPropertyProps(tkProperty, out m_utf8name, out m_flags, out sig); + + RuntimeMethodInfo dummy; + Associates.AssignAssociates(scope, tkProperty, declaredType, reflectedTypeCache.GetRuntimeType(), + out dummy, out dummy, out dummy, + out m_getterMethod, out m_setterMethod, out m_otherMethod, + out isPrivate, out m_bindingFlags); + } + #endregion + + #region Internal Members + internal override bool CacheEquals(object o) + { + RuntimePropertyInfo m = o as RuntimePropertyInfo; + + if ((object)m == null) + return false; + + return m.m_token == m_token && + RuntimeTypeHandle.GetModule(m_declaringType).Equals( + RuntimeTypeHandle.GetModule(m.m_declaringType)); + } + + internal Signature Signature + { + get + { + if (m_signature == null) + { + PropertyAttributes flags; + ConstArray sig; + + void* name; + GetRuntimeModule().MetadataImport.GetPropertyProps( + m_token, out name, out flags, out sig); + + m_signature = new Signature(sig.Signature.ToPointer(), (int)sig.Length, m_declaringType); + } + + return m_signature; + } + } + internal bool EqualsSig(RuntimePropertyInfo target) + { + //@Asymmetry - Legacy policy is to remove duplicate properties, including hidden properties. + // The comparison is done by name and by sig. The EqualsSig comparison is expensive + // but forutnetly it is only called when an inherited property is hidden by name or + // when an interfaces declare properies with the same signature. + // Note that we intentionally don't resolve generic arguments so that we don't treat + // signatures that only match in certain instantiations as duplicates. This has the + // down side of treating overriding and overriden properties as different properties + // in some cases. But PopulateProperties in rttype.cs should have taken care of that + // by comparing VTable slots. + // + // Class C1(Of T, Y) + // Property Prop1(ByVal t1 As T) As Integer + // Get + // ... ... + // End Get + // End Property + // Property Prop1(ByVal y1 As Y) As Integer + // Get + // ... ... + // End Get + // End Property + // End Class + // + + Contract.Requires(Name.Equals(target.Name)); + Contract.Requires(this != target); + Contract.Requires(this.ReflectedType == target.ReflectedType); + + return Signature.CompareSig(this.Signature, target.Signature); + } + internal BindingFlags BindingFlags { get { return m_bindingFlags; } } + #endregion + + #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); + + RuntimeType[] arguments = Signature.Arguments; + if (arguments.Length > 0) + { + sbName.Append(" ["); + sbName.Append(MethodBase.ConstructParameters(arguments, Signature.CallingConvention, serialization)); + sbName.Append("]"); + } + + return sbName.ToString(); + } + #endregion + + #region ICustomAttributeProvider + public override Object[] GetCustomAttributes(bool inherit) + { + return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); + } + + public override Object[] GetCustomAttributes(Type attributeType, bool inherit) + { + if (attributeType == null) + throw new ArgumentNullException(nameof(attributeType)); + Contract.EndContractBlock(); + + RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; + + if (attributeRuntimeType == null) + throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType)); + + return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType); + } + + public override bool IsDefined(Type attributeType, bool inherit) + { + if (attributeType == null) + throw new ArgumentNullException(nameof(attributeType)); + Contract.EndContractBlock(); + + RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; + + if (attributeRuntimeType == null) + throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType)); + + return CustomAttribute.IsDefined(this, attributeRuntimeType); + } + + public override IList GetCustomAttributesData() + { + return CustomAttributeData.GetCustomAttributesInternal(this); + } + #endregion + + #region MemberInfo Overrides + public override MemberTypes MemberType { get { return MemberTypes.Property; } } + public override String Name + { + get + { + if (m_name == null) + m_name = new Utf8String(m_utf8name).ToString(); + + return m_name; + } + } + public override Type DeclaringType + { + get + { + return m_declaringType; + } + } + + public override Type ReflectedType + { + get + { + return ReflectedTypeInternal; + } + } + + private RuntimeType ReflectedTypeInternal + { + get + { + return m_reflectedTypeCache.GetRuntimeType(); + } + } + + public override int MetadataToken { get { return m_token; } } + + public override Module Module { get { return GetRuntimeModule(); } } + internal RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); } + #endregion + + #region PropertyInfo Overrides + + #region Non Dynamic + + public override Type[] GetRequiredCustomModifiers() + { + return Signature.GetCustomModifiers(0, true); + } + + public override Type[] GetOptionalCustomModifiers() + { + return Signature.GetCustomModifiers(0, false); + } + + internal object GetConstantValue(bool raw) + { + Object defaultValue = MdConstant.GetValue(GetRuntimeModule().MetadataImport, m_token, PropertyType.GetTypeHandleInternal(), raw); + + if (defaultValue == DBNull.Value) + // Arg_EnumLitValueNotFound -> "Literal value was not found." + throw new InvalidOperationException(Environment.GetResourceString("Arg_EnumLitValueNotFound")); + + return defaultValue; + } + + public override object GetConstantValue() { return GetConstantValue(false); } + + public override object GetRawConstantValue() { return GetConstantValue(true); } + + public override MethodInfo[] GetAccessors(bool nonPublic) + { + List accessorList = new List(); + + if (Associates.IncludeAccessor(m_getterMethod, nonPublic)) + accessorList.Add(m_getterMethod); + + if (Associates.IncludeAccessor(m_setterMethod, nonPublic)) + accessorList.Add(m_setterMethod); + + if ((object)m_otherMethod != null) + { + for (int i = 0; i < m_otherMethod.Length; i++) + { + if (Associates.IncludeAccessor(m_otherMethod[i] as MethodInfo, nonPublic)) + accessorList.Add(m_otherMethod[i]); + } + } + return accessorList.ToArray(); + } + + public override Type PropertyType + { + get { return Signature.ReturnType; } + } + + public override MethodInfo GetGetMethod(bool nonPublic) + { + if (!Associates.IncludeAccessor(m_getterMethod, nonPublic)) + return null; + + return m_getterMethod; + } + + public override MethodInfo GetSetMethod(bool nonPublic) + { + if (!Associates.IncludeAccessor(m_setterMethod, nonPublic)) + return null; + + return m_setterMethod; + } + + public override ParameterInfo[] GetIndexParameters() + { + ParameterInfo[] indexParams = GetIndexParametersNoCopy(); + + int numParams = indexParams.Length; + + if (numParams == 0) + return indexParams; + + ParameterInfo[] ret = new ParameterInfo[numParams]; + + Array.Copy(indexParams, ret, numParams); + + return ret; + } + + internal ParameterInfo[] GetIndexParametersNoCopy() + { + // @History - Logic ported from RTM + + // No need to lock because we don't guarantee the uniqueness of ParameterInfo objects + if (m_parameters == null) + { + int numParams = 0; + ParameterInfo[] methParams = null; + + // First try to get the Get method. + MethodInfo m = GetGetMethod(true); + if (m != null) + { + // There is a Get method so use it. + methParams = m.GetParametersNoCopy(); + numParams = methParams.Length; + } + else + { + // If there is no Get method then use the Set method. + m = GetSetMethod(true); + + if (m != null) + { + methParams = m.GetParametersNoCopy(); + numParams = methParams.Length - 1; + } + } + + // Now copy over the parameter info's and change their + // owning member info to the current property info. + + ParameterInfo[] propParams = new ParameterInfo[numParams]; + + for (int i = 0; i < numParams; i++) + propParams[i] = new RuntimeParameterInfo((RuntimeParameterInfo)methParams[i], this); + + m_parameters = propParams; + } + + return m_parameters; + } + + public override PropertyAttributes Attributes + { + get + { + return m_flags; + } + } + + public override bool CanRead + { + get + { + return m_getterMethod != null; + } + } + + public override bool CanWrite + { + get + { + return m_setterMethod != null; + } + } + #endregion + + #region Dynamic + [DebuggerStepThroughAttribute] + [Diagnostics.DebuggerHidden] + public override Object GetValue(Object obj, Object[] index) + { + return GetValue(obj, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static, + null, index, null); + } + + [DebuggerStepThroughAttribute] + [Diagnostics.DebuggerHidden] + public override Object GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture) + { + MethodInfo m = GetGetMethod(true); + if (m == null) + throw new ArgumentException(System.Environment.GetResourceString("Arg_GetMethNotFnd")); + return m.Invoke(obj, invokeAttr, binder, index, null); + } + + [DebuggerStepThroughAttribute] + [Diagnostics.DebuggerHidden] + public override void SetValue(Object obj, Object value, Object[] index) + { + SetValue(obj, + value, + BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static, + null, + index, + null); + } + + [DebuggerStepThroughAttribute] + [Diagnostics.DebuggerHidden] + public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture) + { + MethodInfo m = GetSetMethod(true); + + if (m == null) + throw new ArgumentException(System.Environment.GetResourceString("Arg_SetMethNotFnd")); + + Object[] args = null; + + if (index != null) + { + args = new Object[index.Length + 1]; + + for (int i = 0; i < index.Length; i++) + args[i] = index[i]; + + args[index.Length] = value; + } + else + { + args = new Object[1]; + args[0] = value; + } + + m.Invoke(obj, invokeAttr, binder, args, culture); + } + #endregion + + #endregion + + #region ISerializable Implementation + public void GetObjectData(SerializationInfo info, StreamingContext context) + { + if (info == null) + throw new ArgumentNullException(nameof(info)); + Contract.EndContractBlock(); + + MemberInfoSerializationHolder.GetSerializationInfo( + info, + Name, + ReflectedTypeInternal, + ToString(), + SerializationToString(), + MemberTypes.Property, + null); + } + + internal string SerializationToString() + { + return FormatNameAndSig(true); + } + #endregion + } +} -- 2.7.4