diff options
Diffstat (limited to 'src/mscorlib/src/System/Reflection')
65 files changed, 852 insertions, 5898 deletions
diff --git a/src/mscorlib/src/System/Reflection/Assembly.cs b/src/mscorlib/src/System/Reflection/Assembly.cs index 479d6ca3a6..677e4aa964 100644 --- a/src/mscorlib/src/System/Reflection/Assembly.cs +++ b/src/mscorlib/src/System/Reflection/Assembly.cs @@ -37,7 +37,7 @@ namespace System.Reflection using __HResults = System.__HResults; using System.Runtime.Versioning; using System.Diagnostics.Contracts; - + using System.Runtime.Loader; [Serializable] [System.Runtime.InteropServices.ComVisible(true)] @@ -48,14 +48,9 @@ namespace System.Reflection [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_Assembly))] [System.Runtime.InteropServices.ComVisible(true)] -#pragma warning disable 618 - [PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted = true)] -#pragma warning restore 618 public abstract class Assembly : _Assembly, IEvidenceFactory, ICustomAttributeProvider, ISerializable { -#region constructors protected Assembly() {} -#endregion #region public static methods @@ -67,7 +62,7 @@ namespace System.Reflection public static Assembly GetAssembly(Type type) { if (type == null) - throw new ArgumentNullException("type"); + throw new ArgumentNullException(nameof(type)); Contract.EndContractBlock(); Module m = type.Module; @@ -105,36 +100,15 @@ namespace System.Reflection return base.GetHashCode(); } - // Locate an assembly by the name of the file containing the manifest. -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#else - [System.Security.SecuritySafeCritical] -#endif - [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public static Assembly LoadFrom(String assemblyFile) { - Contract.Ensures(Contract.Result<Assembly>() != null); - Contract.Ensures(!Contract.Result<Assembly>().ReflectionOnly); - -#if FEATURE_WINDOWSPHONE - throw new NotSupportedException(Environment.GetResourceString("NotSupported_WindowsPhone", "Assembly.LoadFrom")); -#else - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - - return RuntimeAssembly.InternalLoadFrom( - assemblyFile, - null, // securityEvidence - null, // hashValue - AssemblyHashAlgorithm.None, - false,// forIntrospection - false,// suppressSecurityChecks - ref stackMark); -#endif // FEATURE_WINDOWSPHONE + if(assemblyFile == null) + throw new ArgumentNullException(nameof(assemblyFile)); + string fullPath = Path.GetFullPath(assemblyFile); + return AssemblyLoadContext.Default.LoadFromAssemblyPath(fullPath); } // Locate an assembly for reflection by the name of the file containing the manifest. - [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public static Assembly ReflectionOnlyLoadFrom(String assemblyFile) { @@ -153,7 +127,6 @@ namespace System.Reflection } // Evidence is protected in Assembly.Load() - [System.Security.SecuritySafeCritical] // auto-generated [Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. Please use an overload of LoadFrom which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public static Assembly LoadFrom(String assemblyFile, @@ -174,7 +147,6 @@ namespace System.Reflection } // Evidence is protected in Assembly.Load() - [System.Security.SecuritySafeCritical] // auto-generated [Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. Please use an overload of LoadFrom which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public static Assembly LoadFrom(String assemblyFile, @@ -196,49 +168,21 @@ namespace System.Reflection ref stackMark); } - [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public static Assembly LoadFrom(String assemblyFile, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm) { - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - - return RuntimeAssembly.InternalLoadFrom( - assemblyFile, - null, - hashValue, - hashAlgorithm, - false, - false, - ref stackMark); + throw new NotSupportedException(Environment.GetResourceString("NotSupported_AssemblyLoadFromHash")); } -#if FEATURE_CAS_POLICY - // Load an assembly into the LoadFrom context bypassing some security checks - [SecurityCritical] - [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public static Assembly UnsafeLoadFrom(string assemblyFile) { - - Contract.Ensures(Contract.Result<Assembly>() != null); - Contract.Ensures(!Contract.Result<Assembly>().ReflectionOnly); - - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - - return RuntimeAssembly.InternalLoadFrom(assemblyFile, - null, // securityEvidence - null, // hashValue - AssemblyHashAlgorithm.None, - false, // forIntrospection - true, // suppressSecurityChecks - ref stackMark); + return LoadFrom(assemblyFile); } -#endif // FEATURE_CAS_POLICY // Locate an assembly by the long form of the assembly name. // eg. "Toolbox.dll, version=1.1.10.1220, locale=en, publickey=1234567890123456789012345678901234567890" - [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public static Assembly Load(String assemblyString) { @@ -253,7 +197,6 @@ namespace System.Reflection // Calls Type.GetType for WinRT types. // Note: Type.GetType fails for assembly names that start with weird characters like '['. By calling it for managed types we would // break AppCompat. - [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable internal static Type GetType_Compat(String assemblyString, String typeName) { @@ -283,7 +226,6 @@ namespace System.Reflection // Locate an assembly for reflection by the long form of the assembly name. // eg. "Toolbox.dll, version=1.1.10.1220, locale=en, publickey=1234567890123456789012345678901234567890" // - [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public static Assembly ReflectionOnlyLoad(String assemblyString) { @@ -293,7 +235,6 @@ namespace System.Reflection return RuntimeAssembly.InternalLoad(assemblyString, null, ref stackMark, true /*forIntrospection*/); } - [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable [Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. Please use an overload of Load which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")] public static Assembly Load(String assemblyString, Evidence assemblySecurity) @@ -307,11 +248,6 @@ namespace System.Reflection // Locate an assembly by its name. The name can be strong or // weak. The assembly is loaded into the domain of the caller. -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#else - [System.Security.SecuritySafeCritical] -#endif [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public static Assembly Load(AssemblyName assemblyRef) { @@ -331,11 +267,6 @@ namespace System.Reflection // Locate an assembly by its name. The name can be strong or // weak. The assembly is loaded into the domain of the caller. -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#else - [System.Security.SecuritySafeCritical] -#endif [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable internal static Assembly Load(AssemblyName assemblyRef, IntPtr ptrLoadContextBinder) { @@ -353,7 +284,6 @@ namespace System.Reflection return RuntimeAssembly.InternalLoadAssemblyName(assemblyRef, null, null, ref stackMark, true /*thrownOnFileNotFound*/, false /*forIntrospection*/, false /*suppressSecurityChecks*/, ptrLoadContextBinder); } - [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable [Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. Please use an overload of Load which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")] public static Assembly Load(AssemblyName assemblyRef, Evidence assemblySecurity) @@ -365,34 +295,17 @@ namespace System.Reflection return RuntimeAssembly.InternalLoadAssemblyName(assemblyRef, assemblySecurity, null, ref stackMark, true /*thrownOnFileNotFound*/, false /*forIntrospection*/, false /*suppressSecurityChecks*/); } -#if FEATURE_FUSION - [System.Security.SecuritySafeCritical] // auto-generated [Obsolete("This method has been deprecated. Please use Assembly.Load() instead. http://go.microsoft.com/fwlink/?linkid=14202")] - [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public static Assembly LoadWithPartialName(String partialName) { - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - return RuntimeAssembly.LoadWithPartialNameInternal(partialName, null, ref stackMark); - } - - [System.Security.SecuritySafeCritical] // auto-generated - [Obsolete("This method has been deprecated. Please use Assembly.Load() instead. http://go.microsoft.com/fwlink/?linkid=14202")] - [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable - public static Assembly LoadWithPartialName(String partialName, Evidence securityEvidence) - { - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - return RuntimeAssembly.LoadWithPartialNameInternal(partialName, securityEvidence, ref stackMark); + if(partialName == null) + throw new ArgumentNullException(nameof(partialName)); + return Load(partialName); } -#endif // FEATURE_FUSION // Loads the assembly with a COFF based IMAGE containing // an emitted assembly. The assembly is loaded into the domain // of the caller. -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#else - [System.Security.SecuritySafeCritical] -#endif [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public static Assembly Load(byte[] rawAssembly) { @@ -401,20 +314,12 @@ namespace System.Reflection AppDomain.CheckLoadByteArraySupported(); - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - return RuntimeAssembly.nLoadImage( - rawAssembly, - null, // symbol store - null, // evidence - ref stackMark, - false, // fIntrospection - SecurityContextSource.CurrentAssembly); + return Load(rawAssembly, null); } // Loads the assembly for reflection with a COFF based IMAGE containing // an emitted assembly. The assembly is loaded into the domain // of the caller. - [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public static Assembly ReflectionOnlyLoad(byte[] rawAssembly) { @@ -436,40 +341,30 @@ namespace System.Reflection // an emitted assembly. The assembly is loaded into the domain // of the caller. The second parameter is the raw bytes // representing the symbol store that matches the assembly. -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#else - [System.Security.SecuritySafeCritical] -#endif [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public static Assembly Load(byte[] rawAssembly, byte[] rawSymbolStore) { - Contract.Ensures(Contract.Result<Assembly>() != null); Contract.Ensures(!Contract.Result<Assembly>().ReflectionOnly); AppDomain.CheckLoadByteArraySupported(); - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - return RuntimeAssembly.nLoadImage( - rawAssembly, - rawSymbolStore, - null, // evidence - ref stackMark, - false, // fIntrospection - SecurityContextSource.CurrentAssembly); + if(rawAssembly == null) + throw new ArgumentNullException(nameof(rawAssembly)); + AssemblyLoadContext alc = new IndividualAssemblyLoadContext(); + MemoryStream assemblyStream = new MemoryStream(rawAssembly); + MemoryStream symbolStream = (rawSymbolStore!=null)?new MemoryStream(rawSymbolStore):null; + return alc.LoadFromStream(assemblyStream, symbolStream); } // Load an assembly from a byte array, controlling where the grant set of this assembly is // propigated from. - [SecuritySafeCritical] [MethodImpl(MethodImplOptions.NoInlining)] // Due to the stack crawl mark public static Assembly Load(byte[] rawAssembly, byte[] rawSymbolStore, SecurityContextSource securityContextSource) { - Contract.Ensures(Contract.Result<Assembly>() != null); Contract.Ensures(!Contract.Result<Assembly>().ReflectionOnly); @@ -478,7 +373,7 @@ namespace System.Reflection if (securityContextSource < SecurityContextSource.CurrentAppDomain || securityContextSource > SecurityContextSource.CurrentAssembly) { - throw new ArgumentOutOfRangeException("securityContextSource"); + throw new ArgumentOutOfRangeException(nameof(securityContextSource)); } StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; @@ -490,79 +385,37 @@ namespace System.Reflection securityContextSource); } -#if FEATURE_CAS_POLICY - [System.Security.SecuritySafeCritical] // auto-generated - [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.ControlEvidence)] - [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable - [Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. Please use an overload of Load which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")] - public static Assembly Load(byte[] rawAssembly, - byte[] rawSymbolStore, - Evidence securityEvidence) - { - - Contract.Ensures(Contract.Result<Assembly>() != null); - Contract.Ensures(!Contract.Result<Assembly>().ReflectionOnly); - - AppDomain.CheckLoadByteArraySupported(); + private static Dictionary<string, Assembly> s_loadfile = new Dictionary<string, Assembly>(); - if (securityEvidence != null && !AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled) - { - // A zone of MyComputer could not have been used to sandbox, so for compatibility we do not - // throw an exception when we see it. - Zone zone = securityEvidence.GetHostEvidence<Zone>(); - if (zone == null || zone.SecurityZone != SecurityZone.MyComputer) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit")); - } - } - - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - return RuntimeAssembly.nLoadImage( - rawAssembly, - rawSymbolStore, - securityEvidence, - ref stackMark, - false, // fIntrospection - SecurityContextSource.CurrentAssembly); - } -#endif // FEATURE_CAS_POLICY - - [System.Security.SecuritySafeCritical] // auto-generated public static Assembly LoadFile(String path) { - Contract.Ensures(Contract.Result<Assembly>() != null); Contract.Ensures(!Contract.Result<Assembly>().ReflectionOnly); AppDomain.CheckLoadFileSupported(); - new FileIOPermission(FileIOPermissionAccess.PathDiscovery | FileIOPermissionAccess.Read, path).Demand(); - return RuntimeAssembly.nLoadFile(path, null); - } - -#if FEATURE_CAS_POLICY - [System.Security.SecuritySafeCritical] // auto-generated - [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.ControlEvidence)] - [Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. Please use an overload of LoadFile which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")] - public static Assembly LoadFile(String path, - Evidence securityEvidence) - { - - Contract.Ensures(Contract.Result<Assembly>() != null); - Contract.Ensures(!Contract.Result<Assembly>().ReflectionOnly); + Assembly result = null; + if(path == null) + throw new ArgumentNullException(nameof(path)); - AppDomain.CheckLoadFileSupported(); + if (PathInternal.IsPartiallyQualified(path)) + { + throw new ArgumentException(Environment.GetResourceString("Argument_AbsolutePathRequired"), nameof(path)); + } - if (securityEvidence != null && !AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled) - throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit")); + string normalizedPath = Path.GetFullPath(path); - new FileIOPermission(FileIOPermissionAccess.PathDiscovery | FileIOPermissionAccess.Read, path).Demand(); - return RuntimeAssembly.nLoadFile(path, securityEvidence); + lock(s_loadfile) + { + if(s_loadfile.TryGetValue(normalizedPath, out result)) + return result; + AssemblyLoadContext alc = new IndividualAssemblyLoadContext(); + result = alc.LoadFromAssemblyPath(normalizedPath); + s_loadfile.Add(normalizedPath, result); + } + return result; } -#endif // FEATURE_CAS_POLICY -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public static Assembly Load(Stream assemblyStream, Stream pdbStream) { @@ -572,8 +425,6 @@ namespace System.Reflection StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return RuntimeAssembly.InternalLoadFromStream(assemblyStream, pdbStream, ref stackMark); } - - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public static Assembly Load(Stream assemblyStream) { @@ -583,12 +434,10 @@ namespace System.Reflection StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return RuntimeAssembly.InternalLoadFromStream(assemblyStream, null, ref stackMark); } -#endif //FEATURE_CORECLR /* * Get the assembly that the current code is running from. */ - [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public static Assembly GetExecutingAssembly() { @@ -596,7 +445,6 @@ namespace System.Reflection return RuntimeAssembly.GetExecutingAssembly(ref stackMark); } - [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public static Assembly GetCallingAssembly() { @@ -607,25 +455,22 @@ namespace System.Reflection return RuntimeAssembly.GetExecutingAssembly(ref stackMark); } - [System.Security.SecuritySafeCritical] // auto-generated public static Assembly GetEntryAssembly() { AppDomainManager domainManager = AppDomain.CurrentDomain.DomainManager; if (domainManager == null) domainManager = new AppDomainManager(); return domainManager.EntryAssembly; } - + #endregion // public static methods #region public methods public virtual event ModuleResolveEventHandler ModuleResolve { - [System.Security.SecurityCritical] // auto-generated_required add { throw new NotImplementedException(); } - [System.Security.SecurityCritical] // auto-generated_required remove { throw new NotImplementedException(); @@ -634,9 +479,6 @@ namespace System.Reflection public virtual String CodeBase { -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#endif get { throw new NotImplementedException(); @@ -645,24 +487,17 @@ namespace System.Reflection public virtual String EscapedCodeBase { - [System.Security.SecuritySafeCritical] // auto-generated get { return AssemblyName.EscapeCodeBase(CodeBase); } } -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#endif public virtual AssemblyName GetName() { return GetName(false); } -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#endif public virtual AssemblyName GetName(bool copiedName) { throw new NotImplementedException(); @@ -684,13 +519,6 @@ namespace System.Reflection } } -#if !FEATURE_CORECLR - Type _Assembly.GetType() - { - return base.GetType(); - } -#endif - public virtual Type GetType(String name) { return GetType(name, false, false); @@ -789,31 +617,11 @@ namespace System.Reflection throw new NotImplementedException(); } -#if FEATURE_CAS_POLICY - public virtual Evidence Evidence - { - get - { - throw new NotImplementedException(); - } - } - - public virtual PermissionSet PermissionSet - { - // SecurityCritical because permissions can contain sensitive information such as paths - [SecurityCritical] - get - { - throw new NotImplementedException(); - } - } - public bool IsFullyTrusted { - [SecuritySafeCritical] get { - return PermissionSet.IsUnrestricted(); + return true; } } @@ -821,14 +629,11 @@ namespace System.Reflection { get { - throw new NotImplementedException(); + return SecurityRuleSet.None; } } -#endif // FEATURE_CAS_POLICY - // ISerializable implementation - [System.Security.SecurityCritical] // auto-generated_required public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { throw new NotImplementedException(); @@ -890,8 +695,6 @@ namespace System.Reflection } } -#if FEATURE_MULTIMODULE_ASSEMBLIES - public Module LoadModule(String moduleName, byte[] rawModule) { @@ -904,7 +707,6 @@ namespace System.Reflection { throw new NotImplementedException(); } -#endif //FEATURE_MULTIMODULE_ASSEMBLIES // // Locates a type from this assembly and creates an instance of it using @@ -986,9 +788,6 @@ namespace System.Reflection // Returns the file in the File table of the manifest that matches the // given name. (Name should not include path.) -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#endif public virtual FileStream GetFile(String name) { throw new NotImplementedException(); @@ -999,9 +798,6 @@ namespace System.Reflection return GetFiles(false); } -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#endif public virtual FileStream[] GetFiles(bool getResourceModules) { throw new NotImplementedException(); @@ -1034,9 +830,6 @@ namespace System.Reflection public virtual String Location { -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#endif get { throw new NotImplementedException(); @@ -1103,27 +896,7 @@ namespace System.Reflection [Serializable] internal class RuntimeAssembly : Assembly -#if !FEATURE_CORECLR - , ICustomQueryInterface -#endif { -#if !FEATURE_CORECLR -#region ICustomQueryInterface - [System.Security.SecurityCritical] - CustomQueryInterfaceResult ICustomQueryInterface.GetInterface([In]ref Guid iid, out IntPtr ppv) - { - if (iid == typeof(NativeMethods.IDispatch).GUID) - { - ppv = Marshal.GetComInterfaceForObject(this, typeof(_Assembly)); - return CustomQueryInterfaceResult.Handled; - } - - ppv = IntPtr.Zero; - return CustomQueryInterfaceResult.NotHandled; - } -#endregion -#endif // !FEATURE_CORECLR - #if FEATURE_APPX // The highest byte is the flags and the lowest 3 bytes are // the cached ctor token of [DynamicallyInvocableAttribute]. @@ -1166,54 +939,12 @@ namespace System.Reflection private ASSEMBLY_FLAGS Flags { - [SecuritySafeCritical] get { if ((m_flags & ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_INITIALIZED) == 0) { - ASSEMBLY_FLAGS flags = ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_UNKNOWN; - -#if FEATURE_CORECLR - flags |= ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_FRAMEWORK | ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_SAFE_REFLECTION; -#else - if (RuntimeAssembly.IsFrameworkAssembly(GetName())) - { - flags |= ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_FRAMEWORK | ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_SAFE_REFLECTION; - - foreach (string name in s_unsafeFrameworkAssemblyNames) - { - if (String.Compare(GetSimpleName(), name, StringComparison.OrdinalIgnoreCase) == 0) - { - flags &= ~ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_SAFE_REFLECTION; - break; - } - } - - // Each blessed API will be annotated with a "__DynamicallyInvokableAttribute". - // This "__DynamicallyInvokableAttribute" is a type defined in its own assembly. - // So the ctor is always a MethodDef and the type a TypeDef. - // We cache this ctor MethodDef token for faster custom attribute lookup. - // If this attribute type doesn't exist in the assembly, it means the assembly - // doesn't contain any blessed APIs. - Type invocableAttribute = GetType("__DynamicallyInvokableAttribute", false); - if (invocableAttribute != null) - { - Contract.Assert(((MetadataToken)invocableAttribute.MetadataToken).IsTypeDef); - - ConstructorInfo ctor = invocableAttribute.GetConstructor(Type.EmptyTypes); - Contract.Assert(ctor != null); - - int token = ctor.MetadataToken; - Contract.Assert(((MetadataToken)token).IsMethodDef); - - flags |= (ASSEMBLY_FLAGS)token & ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_TOKEN_MASK; - } - } - else if (IsDesignerBindingContext()) - { - flags = ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_SAFE_REFLECTION; - } -#endif + ASSEMBLY_FLAGS flags = ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_UNKNOWN + | ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_FRAMEWORK | ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_SAFE_REFLECTION; m_flags = flags | ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_INITIALIZED; } @@ -1221,7 +952,7 @@ namespace System.Reflection return m_flags; } } -#endif // FEATURE_CORECLR +#endif // FEATURE_APPX internal object SyncRoot { @@ -1237,12 +968,10 @@ namespace System.Reflection public override event ModuleResolveEventHandler ModuleResolve { - [System.Security.SecurityCritical] // auto-generated_required add { _ModuleResolve += value; } - [System.Security.SecurityCritical] // auto-generated_required remove { _ModuleResolve -= value; @@ -1251,14 +980,12 @@ namespace System.Reflection private const String s_localFilePrefix = "file:"; - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void GetCodeBase(RuntimeAssembly assembly, bool copiedName, StringHandleOnStack retString); - [System.Security.SecurityCritical] // auto-generated internal String GetCodeBase(bool copiedName) { String codeBase = null; @@ -1268,11 +995,6 @@ namespace System.Reflection public override String CodeBase { -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#else - [System.Security.SecuritySafeCritical] -#endif get { String codeBase = GetCodeBase(false); VerifyCodeBaseDiscovery(codeBase); @@ -1288,11 +1010,6 @@ namespace System.Reflection // 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. -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#else - [System.Security.SecuritySafeCritical] -#endif public override AssemblyName GetName(bool copiedName) { AssemblyName an = new AssemblyName(); @@ -1326,27 +1043,12 @@ namespace System.Reflection return an; } -#if FEATURE_APTCA - // This method is called from the VM when creating conditional APTCA exceptions, in order to include - // the text which must be added to the partial trust visible assembly list - [SecurityCritical] - [PermissionSet(SecurityAction.Assert, Unrestricted = true)] - private string GetNameForConditionalAptca() - { - AssemblyName assemblyName = GetName(); - return assemblyName.GetNameWithPublicKey(); - - } -#endif // FEATURE_APTCA - - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void GetFullName(RuntimeAssembly assembly, StringHandleOnStack retString); public override String FullName { - [System.Security.SecuritySafeCritical] // auto-generated get { // If called by Object.ToString(), return val may be NULL. if (m_fullname == null) @@ -1360,14 +1062,12 @@ namespace System.Reflection } } - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void GetEntryPoint(RuntimeAssembly assembly, ObjectHandleOnStack retMethod); public override MethodInfo EntryPoint { - [System.Security.SecuritySafeCritical] // auto-generated get { IRuntimeMethodInfo methodHandle = null; GetEntryPoint(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref methodHandle)); @@ -1379,7 +1079,6 @@ namespace System.Reflection } } - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void GetType(RuntimeAssembly assembly, @@ -1389,12 +1088,11 @@ namespace System.Reflection ObjectHandleOnStack type, ObjectHandleOnStack keepAlive); - [System.Security.SecuritySafeCritical] 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("name"); + throw new ArgumentNullException(nameof(name)); RuntimeType type = null; Object keepAlive = null; @@ -1404,17 +1102,14 @@ namespace System.Reflection return type; } - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] internal extern static void GetForwardedTypes(RuntimeAssembly assembly, ObjectHandleOnStack retTypes); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void GetExportedTypes(RuntimeAssembly assembly, ObjectHandleOnStack retTypes); - [System.Security.SecuritySafeCritical] // auto-generated public override Type[] GetExportedTypes() { Type[] types = null; @@ -1424,7 +1119,6 @@ namespace System.Reflection public override IEnumerable<TypeInfo> DefinedTypes { - [System.Security.SecuritySafeCritical] get { List<RuntimeType> rtTypes = new List<RuntimeType>(); @@ -1441,7 +1135,6 @@ namespace System.Reflection } // Load a resource based on the NameSpace of the type. - [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public override Stream GetManifestResourceStream(Type type, String name) { @@ -1449,7 +1142,6 @@ namespace System.Reflection return GetManifestResourceStream(type, name, false, ref stackMark); } - [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public override Stream GetManifestResourceStream(String name) { @@ -1457,76 +1149,11 @@ namespace System.Reflection return GetManifestResourceStream(name, ref stackMark, false); } -#if FEATURE_CAS_POLICY - [System.Security.SecurityCritical] // auto-generated - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - private extern static void GetEvidence(RuntimeAssembly assembly, ObjectHandleOnStack retEvidence); - - [SecurityCritical] - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - private extern static SecurityRuleSet GetSecurityRuleSet(RuntimeAssembly assembly); - - public override Evidence Evidence - { - [SecuritySafeCritical] - [SecurityPermissionAttribute( SecurityAction.Demand, ControlEvidence = true )] - get - { - Evidence evidence = EvidenceNoDemand; - return evidence.Clone(); - } - } - - internal Evidence EvidenceNoDemand - { - [SecurityCritical] - get - { - Evidence evidence = null; - GetEvidence(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref evidence)); - return evidence; - } - } - - public override PermissionSet PermissionSet - { - [SecurityCritical] - get - { - PermissionSet grantSet = null; - PermissionSet deniedSet = null; - - GetGrantSet(out grantSet, out deniedSet); - - if (grantSet != null) - { - return grantSet.Copy(); - } - else - { - return new PermissionSet(PermissionState.Unrestricted); - } - } - } - - public override SecurityRuleSet SecurityRuleSet - { - [SecuritySafeCritical] - get - { - return GetSecurityRuleSet(GetNativeHandle()); - } - } -#endif // FEATURE_CAS_POLICY - // ISerializable implementation - [System.Security.SecurityCritical] // auto-generated_required public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info==null) - throw new ArgumentNullException("info"); + throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); @@ -1550,17 +1177,17 @@ namespace System.Reflection { return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); } - + public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) - throw new ArgumentNullException("attributeType"); + throw new ArgumentNullException(nameof(attributeType)); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType"); + throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType)); return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType); } @@ -1568,13 +1195,13 @@ namespace System.Reflection public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) - throw new ArgumentNullException("attributeType"); + throw new ArgumentNullException(nameof(attributeType)); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"caType"); + throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType)); return CustomAttribute.IsDefined(this, attributeRuntimeType); } @@ -1583,8 +1210,7 @@ namespace System.Reflection { return CustomAttributeData.GetCustomAttributesInternal(this); } - - [System.Security.SecurityCritical] // auto-generated + [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable internal static RuntimeAssembly InternalLoadFrom(String assemblyFile, Evidence securityEvidence, @@ -1595,16 +1221,10 @@ namespace System.Reflection ref StackCrawlMark stackMark) { if (assemblyFile == null) - throw new ArgumentNullException("assemblyFile"); + throw new ArgumentNullException(nameof(assemblyFile)); Contract.EndContractBlock(); -#if FEATURE_CAS_POLICY - if (securityEvidence != null && !AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit")); - } -#endif // FEATURE_CAS_POLICY AssemblyName an = new AssemblyName(); an.CodeBase = assemblyFile; an.SetHashControl(hashValue, hashAlgorithm); @@ -1613,7 +1233,6 @@ namespace System.Reflection } // Wrapper function to wrap the typical use of InternalLoad. - [System.Security.SecurityCritical] // auto-generated internal static RuntimeAssembly InternalLoad(String assemblyString, Evidence assemblySecurity, ref StackCrawlMark stackMark, @@ -1622,7 +1241,6 @@ namespace System.Reflection return InternalLoad(assemblyString, assemblySecurity, ref stackMark, IntPtr.Zero, forIntrospection); } - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable internal static RuntimeAssembly InternalLoad(String assemblyString, Evidence assemblySecurity, @@ -1644,14 +1262,13 @@ namespace System.Reflection } // Creates AssemblyName. Fills assembly if AssemblyResolve event has been raised. - [System.Security.SecurityCritical] // auto-generated internal static AssemblyName CreateAssemblyName( String assemblyString, bool forIntrospection, out RuntimeAssembly assemblyFromResolveEvent) { if (assemblyString == null) - throw new ArgumentNullException("assemblyString"); + throw new ArgumentNullException(nameof(assemblyString)); Contract.EndContractBlock(); if ((assemblyString.Length == 0) || @@ -1670,7 +1287,6 @@ namespace System.Reflection } // Wrapper function to wrap the typical use of InternalLoadAssemblyName. - [System.Security.SecurityCritical] // auto-generated internal static RuntimeAssembly InternalLoadAssemblyName( AssemblyName assemblyRef, Evidence assemblySecurity, @@ -1684,7 +1300,6 @@ namespace System.Reflection return InternalLoadAssemblyName(assemblyRef, assemblySecurity, reqAssembly, ref stackMark, IntPtr.Zero, true /*throwOnError*/, forIntrospection, suppressSecurityChecks, ptrLoadContextBinder); } - [System.Security.SecurityCritical] // auto-generated internal static RuntimeAssembly InternalLoadAssemblyName( AssemblyName assemblyRef, Evidence assemblySecurity, @@ -1698,7 +1313,7 @@ namespace System.Reflection { if (assemblyRef == null) - throw new ArgumentNullException("assemblyRef"); + throw new ArgumentNullException(nameof(assemblyRef)); Contract.EndContractBlock(); if (assemblyRef.CodeBase != null) @@ -1717,13 +1332,6 @@ namespace System.Reflection if (assemblySecurity != null) { -#if FEATURE_CAS_POLICY - if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit")); - } -#endif // FEATURE_CAS_POLICY - if (!suppressSecurityChecks) { #pragma warning disable 618 @@ -1732,22 +1340,19 @@ namespace System.Reflection } } - String codeBase = VerifyCodeBase(assemblyRef.CodeBase); - if (codeBase != null && !suppressSecurityChecks) { - - if (String.Compare( codeBase, 0, s_localFilePrefix, 0, 5, StringComparison.OrdinalIgnoreCase) != 0) { -#if FEATURE_FUSION // Of all the binders, Fusion is the only one that understands Web locations - IPermission perm = CreateWebPermission( assemblyRef.EscapedCodeBase ); - perm.Demand(); -#else + if (codeBase != null && !suppressSecurityChecks) + { + if (String.Compare( codeBase, 0, s_localFilePrefix, 0, 5, StringComparison.OrdinalIgnoreCase) != 0) + { + // Of all the binders, Fusion is the only one that understands Web locations throw new ArgumentException(Environment.GetResourceString("Arg_InvalidFileName"), "assemblyRef.CodeBase"); -#endif } - else { + else + { System.Security.Util.URLString urlString = new System.Security.Util.URLString( codeBase, true ); new FileIOPermission( FileIOPermissionAccess.PathDiscovery | FileIOPermissionAccess.Read , urlString.GetFileName() ).Demand(); - } + } } return nLoad(assemblyRef, codeBase, assemblySecurity, reqAssembly, ref stackMark, @@ -1765,7 +1370,6 @@ namespace System.Reflection }; #if FEATURE_APPX - [System.Security.SecuritySafeCritical] internal bool IsFrameworkAssembly() { ASSEMBLY_FLAGS flags = Flags; @@ -1780,43 +1384,28 @@ namespace System.Reflection return (flags & ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_SAFE_REFLECTION) != 0; } - [System.Security.SecuritySafeCritical] private bool IsDesignerBindingContext() { return RuntimeAssembly.nIsDesignerBindingContext(this); } - [System.Security.SecurityCritical] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static bool nIsDesignerBindingContext(RuntimeAssembly assembly); #endif - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern RuntimeAssembly _nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, - ref StackCrawlMark stackMark, + ref StackCrawlMark stackMark, IntPtr pPrivHostBinder, - bool throwOnFileNotFound, + bool throwOnFileNotFound, bool forIntrospection, bool suppressSecurityChecks, IntPtr ptrLoadContextBinder); -#if !FEATURE_CORECLR - // The NGEN task uses this method, so please do not modify its signature - [System.Security.SecurityCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern bool IsFrameworkAssembly(AssemblyName assemblyName); - - [System.Security.SecurityCritical] - [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal static extern bool IsNewPortableAssembly(AssemblyName assemblyName); -#endif - - [System.Security.SecurityCritical] // auto-generated private static RuntimeAssembly nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, @@ -1832,177 +1421,6 @@ namespace System.Reflection throwOnFileNotFound, forIntrospection, suppressSecurityChecks, ptrLoadContextBinder); } -#if FEATURE_FUSION - // used by vm - [System.Security.SecurityCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable - private static unsafe RuntimeAssembly LoadWithPartialNameHack(String partialName, bool cropPublicKey) - { - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - - AssemblyName an = new AssemblyName(partialName); - - if (!IsSimplyNamed(an)) - { - if (cropPublicKey) - { - an.SetPublicKey(null); - an.SetPublicKeyToken(null); - } - - if(IsFrameworkAssembly(an) || !AppDomain.IsAppXModel()) - { - AssemblyName GACAssembly = EnumerateCache(an); - if(GACAssembly != null) - return InternalLoadAssemblyName(GACAssembly, null, null,ref stackMark, true /*thrownOnFileNotFound*/, false, false); - else - return null; - } - } - - if (AppDomain.IsAppXModel()) - { - // also try versionless bind from the package - an.Version = null; - return nLoad(an, null, null, null, ref stackMark, - IntPtr.Zero, - false, false, false); - } - return null; - - } - -#if !FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - internal static RuntimeAssembly LoadWithPartialNameInternal(String partialName, Evidence securityEvidence, ref StackCrawlMark stackMark) - { - AssemblyName an = new AssemblyName(partialName); - return LoadWithPartialNameInternal(an, securityEvidence, ref stackMark); - } - - [System.Security.SecurityCritical] // auto-generated - internal static RuntimeAssembly LoadWithPartialNameInternal(AssemblyName an, Evidence securityEvidence, ref StackCrawlMark stackMark) - { - if (securityEvidence != null) - { -#if FEATURE_CAS_POLICY - if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit")); - } -#endif // FEATURE_CAS_POLICY - new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand(); - } - - AppDomain.CheckLoadWithPartialNameSupported(stackMark); - - RuntimeAssembly result = null; - try { - result = nLoad(an, null, securityEvidence, null, ref stackMark, - IntPtr.Zero, - true, false, false); - } - catch(Exception e) { - if (e.IsTransient) - throw e; - - if (IsUserError(e)) - throw; - - - if(IsFrameworkAssembly(an) || !AppDomain.IsAppXModel()) - { - if (IsSimplyNamed(an)) - return null; - - AssemblyName GACAssembly = EnumerateCache(an); - if(GACAssembly != null) - result = InternalLoadAssemblyName(GACAssembly, securityEvidence, null, ref stackMark, true /*thrownOnFileNotFound*/, false, false); - } - else - { - an.Version = null; - result = nLoad(an, null, securityEvidence, null, ref stackMark, - IntPtr.Zero, - false, false, false); - } - } - - - return result; - } -#endif // !FEATURE_CORECLR - - [SecuritySafeCritical] - private static bool IsUserError(Exception e) - { - return (uint)e.HResult == COR_E_LOADING_REFERENCE_ASSEMBLY; - } - - private static bool IsSimplyNamed(AssemblyName partialName) - { - byte[] pk = partialName.GetPublicKeyToken(); - if ((pk != null) && - (pk.Length == 0)) - return true; - - pk = partialName.GetPublicKey(); - if ((pk != null) && - (pk.Length == 0)) - return true; - - return false; - } - - [System.Security.SecurityCritical] // auto-generated - private static AssemblyName EnumerateCache(AssemblyName partialName) - { - new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert(); - - partialName.Version = null; - - ArrayList a = new ArrayList(); - Fusion.ReadCache(a, partialName.FullName, ASM_CACHE.GAC); - - IEnumerator myEnum = a.GetEnumerator(); - AssemblyName ainfoBest = null; - CultureInfo refCI = partialName.CultureInfo; - - while (myEnum.MoveNext()) { - AssemblyName ainfo = new AssemblyName((String)myEnum.Current); - - if (CulturesEqual(refCI, ainfo.CultureInfo)) { - if (ainfoBest == null) - ainfoBest = ainfo; - else { - // Choose highest version - if (ainfo.Version > ainfoBest.Version) - ainfoBest = ainfo; - } - } - } - - return ainfoBest; - } - - private static bool CulturesEqual(CultureInfo refCI, CultureInfo defCI) - { - bool defNoCulture = defCI.Equals(CultureInfo.InvariantCulture); - - // cultured asms aren't allowed to be bound to if - // the ref doesn't ask for them specifically - if ((refCI == null) || refCI.Equals(CultureInfo.InvariantCulture)) - return defNoCulture; - - if (defNoCulture || - ( !defCI.Equals(refCI) )) - return false; - - return true; - } -#endif // FEATURE_FUSION - - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool IsReflectionOnly(RuntimeAssembly assembly); @@ -2011,23 +1429,20 @@ namespace System.Reflection [ComVisible(false)] public override bool ReflectionOnly { - [System.Security.SecuritySafeCritical] // auto-generated get { return IsReflectionOnly(GetNativeHandle()); } } -#if FEATURE_CORECLR // Loads the assembly with a COFF based IMAGE containing // an emitted assembly. The assembly is loaded into the domain // of the caller. Currently is implemented only for UnmanagedMemoryStream // (no derived classes since we are not calling Read()) - [System.Security.SecurityCritical] // auto-generated internal static RuntimeAssembly InternalLoadFromStream(Stream assemblyStream, Stream pdbStream, ref StackCrawlMark stackMark) { if (assemblyStream == null) - throw new ArgumentNullException("assemblyStream"); + throw new ArgumentNullException(nameof(assemblyStream)); if (assemblyStream.GetType()!=typeof(UnmanagedMemoryStream)) throw new NotSupportedException(); @@ -2070,44 +1485,13 @@ namespace System.Reflection return assembly; } } -#endif //FEATURE_CORECLR - -#if FEATURE_MULTIMODULE_ASSEMBLIES - [System.Security.SecurityCritical] // auto-generated - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - private extern static void LoadModule(RuntimeAssembly assembly, - String moduleName, - byte[] rawModule, int cbModule, - byte[] rawSymbolStore, int cbSymbolStore, - ObjectHandleOnStack retModule); - - [SecurityPermissionAttribute(SecurityAction.Demand, ControlEvidence = true)] - [System.Security.SecuritySafeCritical] // auto-generated - public override Module LoadModule(String moduleName, byte[] rawModule, byte[] rawSymbolStore) - { - RuntimeModule retModule = null; - LoadModule( - GetNativeHandle(), - moduleName, - rawModule, - (rawModule != null) ? rawModule.Length : 0, - rawSymbolStore, - (rawSymbolStore != null) ? rawSymbolStore.Length : 0, - JitHelpers.GetObjectHandleOnStack(ref retModule)); - - return retModule; - } -#endif //FEATURE_MULTIMODULE_ASSEMBLIES // Returns the module in this assembly with name 'name' - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void GetModule(RuntimeAssembly assembly, String name, ObjectHandleOnStack retModule); - [System.Security.SecuritySafeCritical] // auto-generated public override Module GetModule(String name) { Module retModule = null; @@ -2117,11 +1501,6 @@ namespace System.Reflection // Returns the file in the File table of the manifest that matches the // given name. (Name should not include path.) -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#else - [System.Security.SecuritySafeCritical] -#endif public override FileStream GetFile(String name) { RuntimeModule m = (RuntimeModule)GetModule(name); @@ -2133,11 +1512,6 @@ namespace System.Reflection FileAccess.Read, FileShare.Read, FileStream.DefaultBufferSize, false); } -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#else - [System.Security.SecuritySafeCritical] -#endif public override FileStream[] GetFiles(bool getResourceModules) { Module[] m = GetModules(getResourceModules); @@ -2152,26 +1526,20 @@ namespace System.Reflection return fs; } - // Returns the names of all the resources - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern String[] GetManifestResourceNames(RuntimeAssembly assembly); // Returns the names of all the resources - [System.Security.SecuritySafeCritical] // auto-generated public override String[] GetManifestResourceNames() { return GetManifestResourceNames(GetNativeHandle()); } - - - [System.Security.SecurityCritical] // auto-generated + [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void GetExecutingAssembly(StackCrawlMarkHandle stackMark, ObjectHandleOnStack retAssembly); - [System.Security.SecurityCritical] // auto-generated internal static RuntimeAssembly GetExecutingAssembly(ref StackCrawlMark stackMark) { RuntimeAssembly retAssembly = null; @@ -2180,17 +1548,14 @@ namespace System.Reflection } // Returns the names of all the resources - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern AssemblyName[] GetReferencedAssemblies(RuntimeAssembly assembly); - [System.Security.SecuritySafeCritical] // auto-generated public override AssemblyName[] GetReferencedAssemblies() { return GetReferencedAssemblies(GetNativeHandle()); } - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern int GetManifestResourceInfo(RuntimeAssembly assembly, @@ -2199,7 +1564,6 @@ namespace System.Reflection StringHandleOnStack retFileName, StackCrawlMarkHandle stackMark); - [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public override ManifestResourceInfo GetManifestResourceInfo(String resourceName) { @@ -2218,18 +1582,12 @@ namespace System.Reflection (ResourceLocation) location); } - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void GetLocation(RuntimeAssembly assembly, StringHandleOnStack retString); public override String Location { -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#else - [System.Security.SecuritySafeCritical] -#endif get { String location = null; @@ -2242,7 +1600,6 @@ namespace System.Reflection } } - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void GetImageRuntimeVersion(RuntimeAssembly assembly, StringHandleOnStack retString); @@ -2252,7 +1609,6 @@ namespace System.Reflection [ComVisible(false)] public override String ImageRuntimeVersion { - [System.Security.SecuritySafeCritical] // auto-generated get{ String s = null; GetImageRuntimeVersion(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref s)); @@ -2261,30 +1617,26 @@ namespace System.Reflection } - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern static bool IsGlobalAssemblyCache(RuntimeAssembly assembly); public override bool GlobalAssemblyCache { - [System.Security.SecuritySafeCritical] // auto-generated get { - return IsGlobalAssemblyCache(GetNativeHandle()); + return false; } } - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static Int64 GetHostContext(RuntimeAssembly assembly); public override Int64 HostContext { - [System.Security.SecuritySafeCritical] // auto-generated get { - return GetHostContext(GetNativeHandle()); + return 0; } } @@ -2309,14 +1661,13 @@ namespace System.Reflection else if ((len > 2) && (codebase[0] == '\\') && (codebase[1] == '\\')) return "file://" + codebase; else - return "file:///" + Path.GetFullPathInternal( codebase ); + return "file:///" + Path.GetFullPath(codebase); #else else - return "file://" + Path.GetFullPathInternal( codebase ); + return "file://" + Path.GetFullPath(codebase); #endif // !PLATFORM_UNIX } - [System.Security.SecurityCritical] // auto-generated internal Stream GetManifestResourceStream( Type type, String name, @@ -2326,7 +1677,7 @@ namespace System.Reflection StringBuilder sb = new StringBuilder(); if(type == null) { if (name == null) - throw new ArgumentNullException("type"); + throw new ArgumentNullException(nameof(type)); } else { String nameSpace = type.Namespace; @@ -2339,25 +1690,11 @@ namespace System.Reflection if(name != null) sb.Append(name); - - return GetManifestResourceStream(sb.ToString(), ref stackMark, skipSecurityCheck); - } -#if FEATURE_CAS_POLICY - internal bool IsStrongNameVerified - { - [System.Security.SecurityCritical] // auto-generated - get { return GetIsStrongNameVerified(GetNativeHandle()); } + return GetManifestResourceStream(sb.ToString(), ref stackMark, skipSecurityCheck); } - [System.Security.SecurityCritical] // auto-generated - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - private static extern bool GetIsStrongNameVerified(RuntimeAssembly assembly); -#endif // FEATURE_CAS_POLICY - // GetResource will return a pointer to the resources in memory. - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static unsafe extern byte* GetResource(RuntimeAssembly assembly, @@ -2366,7 +1703,6 @@ namespace System.Reflection StackCrawlMarkHandle stackMark, bool skipSecurityCheck); - [System.Security.SecurityCritical] // auto-generated internal unsafe Stream GetManifestResourceStream(String name, ref StackCrawlMark stackMark, bool skipSecurityCheck) { ulong length = 0; @@ -2384,7 +1720,6 @@ namespace System.Reflection return null; } - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void GetVersion(RuntimeAssembly assembly, @@ -2393,7 +1728,6 @@ namespace System.Reflection out int buildNum, out int revNum); - [System.Security.SecurityCritical] // auto-generated internal Version GetVersion() { int majorVer, minorVer, build, revision; @@ -2401,12 +1735,10 @@ namespace System.Reflection return new Version (majorVer, minorVer, build, revision); } - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void GetLocale(RuntimeAssembly assembly, StringHandleOnStack retString); - [System.Security.SecurityCritical] // auto-generated internal CultureInfo GetLocale() { String locale = null; @@ -2419,27 +1751,18 @@ namespace System.Reflection return new CultureInfo(locale); } - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool FCallIsDynamic(RuntimeAssembly assembly); public override bool IsDynamic { - [SecuritySafeCritical] get { return FCallIsDynamic(GetNativeHandle()); } } - [System.Security.SecurityCritical] // auto-generated private void VerifyCodeBaseDiscovery(String codeBase) { -#if FEATURE_CAS_POLICY - if (CodeAccessSecurityEngine.QuickCheckForAllDemands()) { - return; - } -#endif // FEATURE_CAS_POLICY - if ((codeBase != null) && (String.Compare( codeBase, 0, s_localFilePrefix, 0, 5, StringComparison.OrdinalIgnoreCase) == 0)) { System.Security.Util.URLString urlString = new System.Security.Util.URLString( codeBase, true ); @@ -2447,12 +1770,10 @@ namespace System.Reflection } } - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void GetSimpleName(RuntimeAssembly assembly, StringHandleOnStack retSimpleName); - [SecuritySafeCritical] internal String GetSimpleName() { string name = null; @@ -2460,35 +1781,29 @@ namespace System.Reflection return name; } - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static AssemblyHashAlgorithm GetHashAlgorithm(RuntimeAssembly assembly); - [System.Security.SecurityCritical] // auto-generated private AssemblyHashAlgorithm GetHashAlgorithm() { return GetHashAlgorithm(GetNativeHandle()); } - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static AssemblyNameFlags GetFlags(RuntimeAssembly assembly); - [System.Security.SecurityCritical] // auto-generated private AssemblyNameFlags GetFlags() { return GetFlags(GetNativeHandle()); } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SecurityCritical] [SuppressUnmanagedCodeSecurity] private static extern void GetRawBytes(RuntimeAssembly assembly, ObjectHandleOnStack retRawBytes); // Get the raw bytes of the assembly - [SecuritySafeCritical] internal byte[] GetRawBytes() { byte[] rawBytes = null; @@ -2497,12 +1812,10 @@ namespace System.Reflection return rawBytes; } - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void GetPublicKey(RuntimeAssembly assembly, ObjectHandleOnStack retPublicKey); - [System.Security.SecurityCritical] // auto-generated internal byte[] GetPublicKey() { byte[] publicKey = null; @@ -2510,12 +1823,10 @@ namespace System.Reflection return publicKey; } - [SecurityCritical] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void GetGrantSet(RuntimeAssembly assembly, ObjectHandleOnStack granted, ObjectHandleOnStack denied); - [SecurityCritical] internal void GetGrantSet(out PermissionSet newGrant, out PermissionSet newDenied) { PermissionSet granted = null, denied = null; @@ -2523,134 +1834,51 @@ namespace System.Reflection newGrant = granted; newDenied = denied; } - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] private extern static bool IsAllSecurityCritical(RuntimeAssembly assembly); // Is everything introduced by this assembly critical - [System.Security.SecuritySafeCritical] // auto-generated internal bool IsAllSecurityCritical() { return IsAllSecurityCritical(GetNativeHandle()); } - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] private extern static bool IsAllSecuritySafeCritical(RuntimeAssembly assembly); // Is everything introduced by this assembly safe critical - [System.Security.SecuritySafeCritical] // auto-generated internal bool IsAllSecuritySafeCritical() { return IsAllSecuritySafeCritical(GetNativeHandle()); } - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] private extern static bool IsAllPublicAreaSecuritySafeCritical(RuntimeAssembly assembly); // Is everything introduced by this assembly safe critical - [System.Security.SecuritySafeCritical] // auto-generated internal bool IsAllPublicAreaSecuritySafeCritical() { return IsAllPublicAreaSecuritySafeCritical(GetNativeHandle()); } - [System.Security.SecurityCritical] // auto-generated [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 - [System.Security.SecuritySafeCritical] // auto-generated internal bool IsAllSecurityTransparent() { return IsAllSecurityTransparent(GetNativeHandle()); } -#if FEATURE_FUSION - // demandFlag: - // 0 demand PathDiscovery permission only - // 1 demand Read permission only - // 2 demand both Read and PathDiscovery - // 3 demand Web permission only - [System.Security.SecurityCritical] // auto-generated - private static void DemandPermission(String codeBase, bool havePath, - int demandFlag) - { - FileIOPermissionAccess access = FileIOPermissionAccess.PathDiscovery; - switch(demandFlag) { - - case 0: // default - break; - case 1: - access = FileIOPermissionAccess.Read; - break; - case 2: - access = FileIOPermissionAccess.PathDiscovery | FileIOPermissionAccess.Read; - break; - - case 3: - IPermission perm = CreateWebPermission(AssemblyName.EscapeCodeBase(codeBase)); - perm.Demand(); - return; - } - - if (!havePath) { - System.Security.Util.URLString urlString = new System.Security.Util.URLString( codeBase, true ); - codeBase = urlString.GetFileName(); - } - - codeBase = Path.GetFullPathInternal(codeBase); // canonicalize - - new FileIOPermission(access, codeBase).Demand(); - } -#endif - -#if FEATURE_FUSION - private static IPermission CreateWebPermission( String codeBase ) - { - Contract.Assert( codeBase != null, "Must pass in a valid CodeBase" ); - Assembly sys = Assembly.Load("System, Version=" + ThisAssembly.Version + ", Culture=neutral, PublicKeyToken=" + AssemblyRef.EcmaPublicKeyToken); - - Type type = sys.GetType("System.Net.NetworkAccess", true); - - IPermission retval = null; - if (!type.IsEnum || !type.IsVisible) - goto Exit; - - Object[] webArgs = new Object[2]; - webArgs[0] = (Enum) Enum.Parse(type, "Connect", true); - if (webArgs[0] == null) - goto Exit; - - webArgs[1] = codeBase; - - type = sys.GetType("System.Net.WebPermission", true); - - if (!type.IsVisible) - goto Exit; - - retval = (IPermission) Activator.CreateInstance(type, webArgs); - - Exit: - if (retval == null) { - Contract.Assert( false, "Unable to create WebPermission" ); - throw new InvalidOperationException(); - } - - return retval; - } -#endif // This method is called by the VM. - [System.Security.SecurityCritical] private RuntimeModule OnModuleResolveEvent(String moduleName) { ModuleResolveEventHandler moduleResolve = _ModuleResolve; @@ -2683,14 +1911,13 @@ namespace System.Reflection return InternalGetSatelliteAssembly(culture, version, ref stackMark); } - [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable internal Assembly InternalGetSatelliteAssembly(CultureInfo culture, Version version, ref StackCrawlMark stackMark) { if (culture == null) - throw new ArgumentNullException("culture"); + throw new ArgumentNullException(nameof(culture)); Contract.EndContractBlock(); @@ -2698,15 +1925,6 @@ namespace System.Reflection return InternalGetSatelliteAssembly(name, culture, version, true, ref stackMark); } -#if !FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool UseRelativeBindForSatellites(); -#endif - - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable internal RuntimeAssembly InternalGetSatelliteAssembly(String name, CultureInfo culture, @@ -2728,104 +1946,9 @@ namespace System.Reflection an.CultureInfo = culture; an.Name = name; - RuntimeAssembly retAssembly = null; - -#if !FEATURE_CORECLR - bool bIsAppXDevMode = AppDomain.IsAppXDesignMode(); - - bool useRelativeBind = false; - if (CodeAccessSecurityEngine.QuickCheckForAllDemands()) - { - if (IsFrameworkAssembly()) - useRelativeBind = true; - else - useRelativeBind = UseRelativeBindForSatellites(); - } - - - if (bIsAppXDevMode || useRelativeBind) - { - if (GlobalAssemblyCache) - { - // lookup in GAC - ArrayList a = new ArrayList(); - bool bTryLoadAnyway = false; - try - { - Fusion.ReadCache(a, an.FullName, ASM_CACHE.GAC); - } - catch(Exception e) - { - if (e.IsTransient) - throw; - - // We also catch any other exception types we haven't come across yet, - // not just UnauthorizedAccessException. - - // We do not want this by itself to cause us to fail to load resources. - - // On Classic, try the old unoptimized way, for full compatibility with 4.0. - // i.e. fall back to using nLoad. - if (!AppDomain.IsAppXModel()) - bTryLoadAnyway = true; - - // On AppX: - // Do not try nLoad since that would effectively allow Framework - // resource satellite assemblies to be placed in AppX packages. - // Instead, leave retAssembly == null. If we were called by the - // ResourceManager, this will usually result in falling back to - // the next culture in the resource fallback chain, possibly the - // neutral culture. - - // Note: if throwOnFileNotFound is true, arbitrary - // exceptions will be absorbed here and - // FileNotFoundException will be thrown in their place. - // (See below: "throw new FileNotFoundException"). - } - if (a.Count > 0 || bTryLoadAnyway) - { - // present in the GAC, load it from there - retAssembly = nLoad(an, null, null, this, ref stackMark, - IntPtr.Zero, - throwOnFileNotFound, false, false); - } - } - else - { - String codeBase = CodeBase; - - if ((codeBase != null) && - (String.Compare(codeBase, 0, s_localFilePrefix, 0, 5, StringComparison.OrdinalIgnoreCase) == 0)) - { - retAssembly = InternalProbeForSatelliteAssemblyNextToParentAssembly(an, - name, - codeBase, - culture, - throwOnFileNotFound, - bIsAppXDevMode /* useLoadFile */, // if bIsAppXDevMode is false, then useRelativeBind is true. - ref stackMark); - if (retAssembly != null && !IsSimplyNamed(an)) - { - AssemblyName defName = retAssembly.GetName(); - if (!AssemblyName.ReferenceMatchesDefinitionInternal(an,defName,false)) - retAssembly = null; - } - } - else if (!bIsAppXDevMode) - { - retAssembly = nLoad(an, null, null, this, ref stackMark, - IntPtr.Zero, - throwOnFileNotFound, false, false); - } - } - } - else -#endif // !FEATURE_CORECLR - { - retAssembly = nLoad(an, null, null, this, ref stackMark, - IntPtr.Zero, - throwOnFileNotFound, false, false); - } + RuntimeAssembly retAssembly = nLoad(an, null, null, this, ref stackMark, + IntPtr.Zero, + throwOnFileNotFound, false, false); if (retAssembly == this || (retAssembly == null && throwOnFileNotFound)) { @@ -2836,7 +1959,6 @@ namespace System.Reflection } // Helper method used by InternalGetSatelliteAssembly only. Not abstracted for use elsewhere. - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable private RuntimeAssembly InternalProbeForSatelliteAssemblyNextToParentAssembly(AssemblyName an, String name, @@ -2930,7 +2052,7 @@ namespace System.Reflection // the .DLL and .EXE load attempts if the user is interested in digging deeper. if (retAssembly == null && throwOnFileNotFound) - throw dllNotFoundException; + throw dllNotFoundException; } } catch (DirectoryNotFoundException) @@ -2944,11 +2066,9 @@ namespace System.Reflection return retAssembly; } - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] static internal extern RuntimeAssembly nLoadFile(String path, Evidence evidence); - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] static internal extern RuntimeAssembly nLoadImage(byte[] rawAssembly, byte[] rawSymbolStore, @@ -2956,8 +2076,7 @@ namespace System.Reflection ref StackCrawlMark stackMark, bool fIntrospection, SecurityContextSource securityContextSource); -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated + [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] static internal extern unsafe void nLoadFromUnmanagedArray(bool fIntrospection, @@ -2967,9 +2086,7 @@ namespace System.Reflection ulong pdbSize, StackCrawlMarkHandle stackMark, ObjectHandleOnStack retAssembly); -#endif - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void GetModules(RuntimeAssembly assembly, @@ -2977,7 +2094,6 @@ namespace System.Reflection bool getResourceModules, ObjectHandleOnStack retModuleHandles); - [System.Security.SecuritySafeCritical] // auto-generated private RuntimeModule[] GetModulesInternal(bool loadIfNotFound, bool getResourceModules) { @@ -2996,17 +2112,9 @@ namespace System.Reflection return GetModulesInternal(false, getResourceModules); } - [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern RuntimeModule GetManifestModule(RuntimeAssembly assembly); -#if FEATURE_APTCA - [System.Security.SecuritySafeCritical] - [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal static extern bool AptcaCheck(RuntimeAssembly targetAssembly, RuntimeAssembly sourceAssembly); -#endif // FEATURE_APTCA - - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern int GetToken(RuntimeAssembly assembly); } diff --git a/src/mscorlib/src/System/Reflection/AssemblyAttributes.cs b/src/mscorlib/src/System/Reflection/AssemblyAttributes.cs index 955255572b..b2e44b0034 100644 --- a/src/mscorlib/src/System/Reflection/AssemblyAttributes.cs +++ b/src/mscorlib/src/System/Reflection/AssemblyAttributes.cs @@ -190,7 +190,7 @@ namespace System.Reflection { public AssemblyFileVersionAttribute(String version) { if (version == null) - throw new ArgumentNullException("version"); + throw new ArgumentNullException(nameof(version)); Contract.EndContractBlock(); _version = version; } diff --git a/src/mscorlib/src/System/Reflection/AssemblyName.cs b/src/mscorlib/src/System/Reflection/AssemblyName.cs index 051f3b5f0e..48eab33ee5 100644 --- a/src/mscorlib/src/System/Reflection/AssemblyName.cs +++ b/src/mscorlib/src/System/Reflection/AssemblyName.cs @@ -24,6 +24,7 @@ namespace System.Reflection { using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Diagnostics.Contracts; + using System.Text; [Serializable] [ClassInterface(ClassInterfaceType.None)] @@ -103,19 +104,12 @@ namespace System.Reflection { public String CodeBase { -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#endif get { return _CodeBase; } -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#endif set { _CodeBase = value; } } public String EscapedCodeBase { - [System.Security.SecuritySafeCritical] // auto-generated get { if (_CodeBase == null) @@ -189,16 +183,15 @@ namespace System.Reflection { * if the file contains an assembly manifest. This method causes * the file to be opened and closed. */ - [System.Security.SecuritySafeCritical] // auto-generated static public AssemblyName GetAssemblyName(String assemblyFile) { if(assemblyFile == null) - throw new ArgumentNullException("assemblyFile"); + throw new ArgumentNullException(nameof(assemblyFile)); Contract.EndContractBlock(); // Assembly.GetNameInternal() will not demand path discovery // permission, so do that first. - String fullPath = Path.GetFullPathInternal(assemblyFile); + string fullPath = Path.GetFullPath(assemblyFile); new FileIOPermission( FileIOPermissionAccess.PathDiscovery, fullPath ).Demand(); return nGetFileInformation(fullPath); } @@ -230,7 +223,6 @@ namespace System.Reflection { // The compressed version of the public key formed from a truncated hash. // Will throw a SecurityException if _PublicKey is invalid - [System.Security.SecuritySafeCritical] // auto-generated public byte[] GetPublicKeyToken() { if (_PublicKeyToken == null) @@ -279,7 +271,6 @@ namespace System.Reflection { public String FullName { - [System.Security.SecuritySafeCritical] // auto-generated get { return nToString(); } @@ -295,11 +286,10 @@ namespace System.Reflection { return s; } - [System.Security.SecurityCritical] // auto-generated_required public void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) - throw new ArgumentNullException("info"); + throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); //Allocate the serialization info and serialize our static data. @@ -360,11 +350,10 @@ namespace System.Reflection { m_siInfo = info; } - [System.Security.SecuritySafeCritical] // auto-generated public AssemblyName(String assemblyName) { if (assemblyName == null) - throw new ArgumentNullException("assemblyName"); + throw new ArgumentNullException(nameof(assemblyName)); Contract.EndContractBlock(); if ((assemblyName.Length == 0) || (assemblyName[0] == '\0')) @@ -374,7 +363,6 @@ namespace System.Reflection { nInit(); } - [System.Security.SecuritySafeCritical] // auto-generated static public bool ReferenceMatchesDefinition(AssemblyName reference, AssemblyName definition) { @@ -389,7 +377,6 @@ namespace System.Reflection { /// "parse" tells us to parse the simple name of the assembly as if it was the full name /// almost never the right thing to do, but needed for compat - [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] static internal extern bool ReferenceMatchesDefinitionInternal(AssemblyName reference, AssemblyName definition, @@ -397,11 +384,9 @@ namespace System.Reflection { - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern void nInit(out RuntimeAssembly assembly, bool forIntrospection, bool raiseResolveEvent); - [System.Security.SecurityCritical] // auto-generated internal void nInit() { RuntimeAssembly dummy = null; @@ -486,54 +471,239 @@ namespace System.Reflection { _StrongNameKeyPair = keyPair; } -#if !FEATURE_CORECLR - void _AssemblyName.GetTypeInfoCount(out uint pcTInfo) + // This call opens and closes the file, but does not add the + // assembly to the domain. + [MethodImplAttribute(MethodImplOptions.InternalCall)] + static internal extern AssemblyName nGetFileInformation(String s); + + [MethodImplAttribute(MethodImplOptions.InternalCall)] + private extern String nToString(); + + [MethodImplAttribute(MethodImplOptions.InternalCall)] + private extern byte[] nGetPublicKeyToken(); + + static internal String EscapeCodeBase(String codebase) { - throw new NotImplementedException(); + if (codebase == null) + return string.Empty; + + int position = 0; + char[] dest = EscapeString(codebase, 0, codebase.Length, null, ref position, true, c_DummyChar, c_DummyChar, c_DummyChar); + if (dest == null) + return codebase; + + return new string(dest, 0, position); } - void _AssemblyName.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) + // This implementation of EscapeString has been copied from System.Private.Uri from corefx repo + // - forceX characters are always escaped if found + // - rsvd character will remain unescaped + // + // start - starting offset from input + // end - the exclusive ending offset in input + // destPos - starting offset in dest for output, on return this will be an exclusive "end" in the output. + // + // In case "dest" has lack of space it will be reallocated by preserving the _whole_ content up to current destPos + // + // Returns null if nothing has to be escaped AND passed dest was null, otherwise the resulting array with the updated destPos + // + internal unsafe static char[] EscapeString(string input, int start, int end, char[] dest, ref int destPos, + bool isUriString, char force1, char force2, char rsvd) { - throw new NotImplementedException(); + int i = start; + int prevInputPos = start; + byte* bytes = stackalloc byte[c_MaxUnicodeCharsReallocate * c_MaxUTF_8BytesPerUnicodeChar]; // 40*4=160 + + fixed (char* pStr = input) + { + for (; i < end; ++i) + { + char ch = pStr[i]; + + // a Unicode ? + if (ch > '\x7F') + { + short maxSize = (short)Math.Min(end - i, (int)c_MaxUnicodeCharsReallocate - 1); + + short count = 1; + for (; count < maxSize && pStr[i + count] > '\x7f'; ++count) + ; + + // Is the last a high surrogate? + if (pStr[i + count - 1] >= 0xD800 && pStr[i + count - 1] <= 0xDBFF) + { + // Should be a rare case where the app tries to feed an invalid Unicode surrogates pair + if (count == 1 || count == end - i) + throw new FormatException(Environment.GetResourceString("Arg_FormatException")); + // need to grab one more char as a Surrogate except when it's a bogus input + ++count; + } + + dest = EnsureDestinationSize(pStr, dest, i, + (short)(count * c_MaxUTF_8BytesPerUnicodeChar * c_EncodedCharsPerByte), + c_MaxUnicodeCharsReallocate * c_MaxUTF_8BytesPerUnicodeChar * c_EncodedCharsPerByte, + ref destPos, prevInputPos); + + short numberOfBytes = (short)Encoding.UTF8.GetBytes(pStr + i, count, bytes, + c_MaxUnicodeCharsReallocate * c_MaxUTF_8BytesPerUnicodeChar); + + // This is the only exception that built in UriParser can throw after a Uri ctor. + // Should not happen unless the app tries to feed an invalid Unicode String + if (numberOfBytes == 0) + throw new FormatException(Environment.GetResourceString("Arg_FormatException")); + + i += (count - 1); + + for (count = 0; count < numberOfBytes; ++count) + EscapeAsciiChar((char)bytes[count], dest, ref destPos); + + prevInputPos = i + 1; + } + else if (ch == '%' && rsvd == '%') + { + // Means we don't reEncode '%' but check for the possible escaped sequence + dest = EnsureDestinationSize(pStr, dest, i, c_EncodedCharsPerByte, + c_MaxAsciiCharsReallocate * c_EncodedCharsPerByte, ref destPos, prevInputPos); + if (i + 2 < end && EscapedAscii(pStr[i + 1], pStr[i + 2]) != c_DummyChar) + { + // leave it escaped + dest[destPos++] = '%'; + dest[destPos++] = pStr[i + 1]; + dest[destPos++] = pStr[i + 2]; + i += 2; + } + else + { + EscapeAsciiChar('%', dest, ref destPos); + } + prevInputPos = i + 1; + } + else if (ch == force1 || ch == force2) + { + dest = EnsureDestinationSize(pStr, dest, i, c_EncodedCharsPerByte, + c_MaxAsciiCharsReallocate * c_EncodedCharsPerByte, ref destPos, prevInputPos); + EscapeAsciiChar(ch, dest, ref destPos); + prevInputPos = i + 1; + } + else if (ch != rsvd && (isUriString ? !IsReservedUnreservedOrHash(ch) : !IsUnreserved(ch))) + { + dest = EnsureDestinationSize(pStr, dest, i, c_EncodedCharsPerByte, + c_MaxAsciiCharsReallocate * c_EncodedCharsPerByte, ref destPos, prevInputPos); + EscapeAsciiChar(ch, dest, ref destPos); + prevInputPos = i + 1; + } + } + + if (prevInputPos != i) + { + // need to fill up the dest array ? + if (prevInputPos != start || dest != null) + dest = EnsureDestinationSize(pStr, dest, i, 0, 0, ref destPos, prevInputPos); + } + } + + return dest; } - void _AssemblyName.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) + // + // ensure destination array has enough space and contains all the needed input stuff + // + private unsafe static char[] EnsureDestinationSize(char* pStr, char[] dest, int currentInputPos, + short charsToAdd, short minReallocateChars, ref int destPos, int prevInputPos) { - throw new NotImplementedException(); - } + if ((object)dest == null || dest.Length < destPos + (currentInputPos - prevInputPos) + charsToAdd) + { + // allocating or reallocating array by ensuring enough space based on maxCharsToAdd. + char[] newresult = new char[destPos + (currentInputPos - prevInputPos) + minReallocateChars]; + + if ((object)dest != null && destPos != 0) + Buffer.BlockCopy(dest, 0, newresult, 0, destPos << 1); + dest = newresult; + } - void _AssemblyName.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) + // ensuring we copied everything form the input string left before last escaping + while (prevInputPos != currentInputPos) + dest[destPos++] = pStr[prevInputPos++]; + return dest; + } + + internal static void EscapeAsciiChar(char ch, char[] to, ref int pos) { - throw new NotImplementedException(); + to[pos++] = '%'; + to[pos++] = s_hexUpperChars[(ch & 0xf0) >> 4]; + to[pos++] = s_hexUpperChars[ch & 0xf]; } -#endif -#if FEATURE_APTCA - internal string GetNameWithPublicKey() + internal static char EscapedAscii(char digit, char next) { - byte[] key = GetPublicKey(); + if (!(((digit >= '0') && (digit <= '9')) + || ((digit >= 'A') && (digit <= 'F')) + || ((digit >= 'a') && (digit <= 'f')))) + { + return c_DummyChar; + } + + int res = (digit <= '9') + ? ((int)digit - (int)'0') + : (((digit <= 'F') + ? ((int)digit - (int)'A') + : ((int)digit - (int)'a')) + + 10); + + if (!(((next >= '0') && (next <= '9')) + || ((next >= 'A') && (next <= 'F')) + || ((next >= 'a') && (next <= 'f')))) + { + return c_DummyChar; + } + + return (char)((res << 4) + ((next <= '9') + ? ((int)next - (int)'0') + : (((next <= 'F') + ? ((int)next - (int)'A') + : ((int)next - (int)'a')) + + 10))); + } - // The following string should not be localized because it is used in security decisions. - return Name + ", PublicKey=" + System.Security.Util.Hex.EncodeHexString(key); + private static unsafe bool IsReservedUnreservedOrHash(char c) + { + if (IsUnreserved(c)) + { + return true; + } + return (RFC3986ReservedMarks.IndexOf(c) >= 0); } -#endif - // This call opens and closes the file, but does not add the - // assembly to the domain. - [System.Security.SecurityCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.InternalCall)] - static internal extern AssemblyName nGetFileInformation(String s); + internal static unsafe bool IsUnreserved(char c) + { + if (IsAsciiLetterOrDigit(c)) + { + return true; + } + return (RFC3986UnreservedMarks.IndexOf(c) >= 0); + } - [System.Security.SecurityCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private extern String nToString(); + //Only consider ASCII characters + internal static bool IsAsciiLetter(char character) + { + return (character >= 'a' && character <= 'z') || + (character >= 'A' && character <= 'Z'); + } - [System.Security.SecurityCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private extern byte[] nGetPublicKeyToken(); - - [System.Security.SecurityCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.InternalCall)] - static internal extern String EscapeCodeBase(String codeBase); + internal static bool IsAsciiLetterOrDigit(char character) + { + return IsAsciiLetter(character) || (character >= '0' && character <= '9'); + } + + private static readonly char[] s_hexUpperChars = { + '0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; + internal const char c_DummyChar = (char)0xFFFF; //An Invalid Unicode character used as a dummy char passed into the parameter + private const short c_MaxAsciiCharsReallocate = 40; + private const short c_MaxUnicodeCharsReallocate = 40; + private const short c_MaxUTF_8BytesPerUnicodeChar = 4; + private const short c_EncodedCharsPerByte = 3; + private const string RFC3986ReservedMarks = @":/?#[]@!$&'()*+,;="; + private const string RFC3986UnreservedMarks = @"-._~"; } } diff --git a/src/mscorlib/src/System/Reflection/Associates.cs b/src/mscorlib/src/System/Reflection/Associates.cs index 8b34e77b63..9eaf74a6e9 100644 --- a/src/mscorlib/src/System/Reflection/Associates.cs +++ b/src/mscorlib/src/System/Reflection/Associates.cs @@ -8,6 +8,7 @@ namespace System.Reflection { using System; using System.Collections.Generic; + using System.Diagnostics; using System.Diagnostics.Contracts; internal static class Associates @@ -35,7 +36,6 @@ namespace System.Reflection return false; } - [System.Security.SecurityCritical] // auto-generated private static unsafe RuntimeMethodInfo AssignAssociates( int tkMethod, RuntimeType declaredType, @@ -44,8 +44,8 @@ namespace System.Reflection if (MetadataToken.IsNullToken(tkMethod)) return null; - Contract.Assert(declaredType != null); - Contract.Assert(reflectedType != null); + Debug.Assert(declaredType != null); + Debug.Assert(reflectedType != null); bool isInherited = declaredType != reflectedType; @@ -63,7 +63,7 @@ namespace System.Reflection } RuntimeMethodHandleInternal associateMethodHandle = ModuleHandle.ResolveMethodHandleInternalCore(RuntimeTypeHandle.GetModule(declaredType), tkMethod, genericArgumentHandles, genericArgumentCount, null, 0); - Contract.Assert(!associateMethodHandle.IsNullHandle(), "Failed to resolve associateRecord methodDef token"); + Debug.Assert(!associateMethodHandle.IsNullHandle(), "Failed to resolve associateRecord methodDef token"); if (isInherited) { @@ -109,7 +109,6 @@ namespace System.Reflection return associateMethod; } - [System.Security.SecurityCritical] // auto-generated internal static unsafe void AssignAssociates( MetadataImport scope, int mdPropEvent, diff --git a/src/mscorlib/src/System/Reflection/ComInterfaces.cs b/src/mscorlib/src/System/Reflection/ComInterfaces.cs index 63438115fc..6e4b0cc19a 100644 --- a/src/mscorlib/src/System/Reflection/ComInterfaces.cs +++ b/src/mscorlib/src/System/Reflection/ComInterfaces.cs @@ -2,248 +2,26 @@ // 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; -using System.Globalization; -using System.IO; -using System.Reflection; -using System.Runtime.InteropServices; -using System.Runtime.Serialization; -using System.Security.Permissions; -using System.Security.Policy; - namespace System.Runtime.InteropServices { [GuidAttribute("BCA8B44D-AAD6-3A86-8AB7-03349F4F2DA2")] [CLSCompliant(false)] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [TypeLibImportClassAttribute(typeof(System.Type))] -[System.Runtime.InteropServices.ComVisible(true)] + [System.Runtime.InteropServices.ComVisible(true)] public interface _Type { -#if !FEATURE_CORECLR - #region IDispatch Members - void GetTypeInfoCount(out uint pcTInfo); - void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); - void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); - void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); - #endregion - - #region Object Members - String ToString(); - bool Equals(Object other); - int GetHashCode(); - Type GetType(); - #endregion - - #region MemberInfo Members - MemberTypes MemberType { get; } - String Name { get; } - Type DeclaringType { get; } - Type ReflectedType { get; } - Object[] GetCustomAttributes(Type attributeType, bool inherit); - Object[] GetCustomAttributes(bool inherit); - bool IsDefined(Type attributeType, bool inherit); - #endregion - - #region Type Members - Guid GUID { get; } - Module Module { get; } - Assembly Assembly { get; } - RuntimeTypeHandle TypeHandle { get; } - String FullName { get; } - String Namespace { get; } - String AssemblyQualifiedName { get; } - int GetArrayRank(); - Type BaseType { get; } - - ConstructorInfo[] GetConstructors(BindingFlags bindingAttr); - Type GetInterface(String name, bool ignoreCase); - Type[] GetInterfaces(); - Type[] FindInterfaces(TypeFilter filter,Object filterCriteria); - EventInfo GetEvent(String name,BindingFlags bindingAttr); - EventInfo[] GetEvents(); - EventInfo[] GetEvents(BindingFlags bindingAttr); - Type[] GetNestedTypes(BindingFlags bindingAttr); - Type GetNestedType(String name, BindingFlags bindingAttr); - MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr); - MemberInfo[] GetDefaultMembers(); - MemberInfo[] FindMembers(MemberTypes memberType,BindingFlags bindingAttr,MemberFilter filter,Object filterCriteria); - Type GetElementType(); - bool IsSubclassOf(Type c); - bool IsInstanceOfType(Object o); - bool IsAssignableFrom(Type c); - InterfaceMapping GetInterfaceMap(Type interfaceType); - MethodInfo GetMethod(String name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers); - MethodInfo GetMethod(String name, BindingFlags bindingAttr); - MethodInfo[] GetMethods(BindingFlags bindingAttr); - FieldInfo GetField(String name, BindingFlags bindingAttr); - FieldInfo[] GetFields(BindingFlags bindingAttr); - PropertyInfo GetProperty(String name, BindingFlags bindingAttr); - PropertyInfo GetProperty(String name,BindingFlags bindingAttr,Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers); - PropertyInfo[] GetProperties(BindingFlags bindingAttr); - MemberInfo[] GetMember(String name, BindingFlags bindingAttr); - MemberInfo[] GetMembers(BindingFlags bindingAttr); - Object InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters); - Type UnderlyingSystemType - { - get; - } - - Object InvokeMember(String name,BindingFlags invokeAttr,Binder binder, Object target, Object[] args, CultureInfo culture); - Object InvokeMember(String name,BindingFlags invokeAttr,Binder binder, Object target, Object[] args); - ConstructorInfo GetConstructor(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers); - ConstructorInfo GetConstructor(BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers); - ConstructorInfo GetConstructor(Type[] types); - ConstructorInfo[] GetConstructors(); - ConstructorInfo TypeInitializer - { - get; - } - - MethodInfo GetMethod(String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers); - MethodInfo GetMethod(String name, Type[] types, ParameterModifier[] modifiers); - MethodInfo GetMethod(String name, Type[] types); - MethodInfo GetMethod(String name); - MethodInfo[] GetMethods(); - FieldInfo GetField(String name); - FieldInfo[] GetFields(); - Type GetInterface(String name); - EventInfo GetEvent(String name); - PropertyInfo GetProperty(String name, Type returnType, Type[] types,ParameterModifier[] modifiers); - PropertyInfo GetProperty(String name, Type returnType, Type[] types); - PropertyInfo GetProperty(String name, Type[] types); - PropertyInfo GetProperty(String name, Type returnType); - PropertyInfo GetProperty(String name); - PropertyInfo[] GetProperties(); - Type[] GetNestedTypes(); - Type GetNestedType(String name); - MemberInfo[] GetMember(String name); - MemberInfo[] GetMembers(); - TypeAttributes Attributes { get; } - bool IsNotPublic { get; } - bool IsPublic { get; } - bool IsNestedPublic { get; } - bool IsNestedPrivate { get; } - bool IsNestedFamily { get; } - bool IsNestedAssembly { get; } - bool IsNestedFamANDAssem { get; } - bool IsNestedFamORAssem { get; } - bool IsAutoLayout { get; } - bool IsLayoutSequential { get; } - bool IsExplicitLayout { get; } - bool IsClass { get; } - bool IsInterface { get; } - bool IsValueType { get; } - bool IsAbstract { get; } - bool IsSealed { get; } - bool IsEnum { get; } - bool IsSpecialName { get; } - bool IsImport { get; } - bool IsSerializable { get; } - bool IsAnsiClass { get; } - bool IsUnicodeClass { get; } - bool IsAutoClass { get; } - bool IsArray { get; } - bool IsByRef { get; } - bool IsPointer { get; } - bool IsPrimitive { get; } - bool IsCOMObject { get; } - bool HasElementType { get; } - bool IsContextful { get; } - bool IsMarshalByRef { get; } - bool Equals(Type o); - #endregion -#endif } [GuidAttribute("17156360-2f1a-384a-bc52-fde93c215c5b")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)] [TypeLibImportClassAttribute(typeof(System.Reflection.Assembly))] [CLSCompliant(false)] -[System.Runtime.InteropServices.ComVisible(true)] + [System.Runtime.InteropServices.ComVisible(true)] public interface _Assembly { -#if !FEATURE_CORECLR - #region Object Members - String ToString(); - bool Equals(Object other); - int GetHashCode(); - Type GetType(); - #endregion - - #region Assembly Members - String CodeBase { -#if FEATURE_CORECLR -[System.Security.SecurityCritical] // auto-generated -#endif -get; } - String EscapedCodeBase { get; } - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif - AssemblyName GetName(); - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif - AssemblyName GetName(bool copiedName); - String FullName { get; } - MethodInfo EntryPoint { get; } - Type GetType(String name); - Type GetType(String name, bool throwOnError); - Type[] GetExportedTypes(); - Type[] GetTypes(); - Stream GetManifestResourceStream(Type type, String name); - Stream GetManifestResourceStream(String name); - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif - FileStream GetFile(String name); - FileStream[] GetFiles(); - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif - FileStream[] GetFiles(bool getResourceModules); - String[] GetManifestResourceNames(); - ManifestResourceInfo GetManifestResourceInfo(String resourceName); - String Location { -#if FEATURE_CORECLR -[System.Security.SecurityCritical] // auto-generated -#endif -get; } -#if FEATURE_CAS_POLICY - Evidence Evidence { get; } -#endif // FEATURE_CAS_POLICY - Object[] GetCustomAttributes(Type attributeType, bool inherit); - Object[] GetCustomAttributes(bool inherit); - bool IsDefined(Type attributeType, bool inherit); -#if FEATURE_SERIALIZATION - [System.Security.SecurityCritical] // auto-generated_required - void GetObjectData(SerializationInfo info, StreamingContext context); -#endif - [method: System.Security.SecurityCritical] - event ModuleResolveEventHandler ModuleResolve; - Type GetType(String name, bool throwOnError, bool ignoreCase); - Assembly GetSatelliteAssembly(CultureInfo culture); - Assembly GetSatelliteAssembly(CultureInfo culture, Version version); -#if FEATURE_MULTIMODULE_ASSEMBLIES - Module LoadModule(String moduleName, byte[] rawModule); - Module LoadModule(String moduleName, byte[] rawModule, byte[] rawSymbolStore); -#endif - Object CreateInstance(String typeName); - Object CreateInstance(String typeName, bool ignoreCase); - Object CreateInstance(String typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes); - Module[] GetLoadedModules(); - Module[] GetLoadedModules(bool getResourceModules); - Module[] GetModules(); - Module[] GetModules(bool getResourceModules); - Module GetModule(String name); - AssemblyName[] GetReferencedAssemblies(); - bool GlobalAssemblyCache { get; } - #endregion -#endif } - [GuidAttribute("f7102fa9-cabb-3a74-a6da-b4567ef1b079")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [TypeLibImportClassAttribute(typeof(System.Reflection.MemberInfo))] @@ -251,34 +29,8 @@ get; } [System.Runtime.InteropServices.ComVisible(true)] public interface _MemberInfo { -#if !FEATURE_CORECLR - #region IDispatch Members - void GetTypeInfoCount(out uint pcTInfo); - void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); - void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); - void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); - #endregion - - #region Object Members - String ToString(); - bool Equals(Object other); - int GetHashCode(); - Type GetType(); - #endregion - - #region MemberInfo Members - MemberTypes MemberType { get; } - String Name { get; } - Type DeclaringType { get; } - Type ReflectedType { get; } - Object[] GetCustomAttributes(Type attributeType, bool inherit); - Object[] GetCustomAttributes(bool inherit); - bool IsDefined(Type attributeType, bool inherit); - #endregion -#endif } - [GuidAttribute("6240837A-707F-3181-8E98-A36AE086766B")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] @@ -286,57 +38,8 @@ get; } [System.Runtime.InteropServices.ComVisible(true)] public interface _MethodBase { -#if !FEATURE_CORECLR - #region IDispatch Members - void GetTypeInfoCount(out uint pcTInfo); - void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); - void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); - void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); - #endregion - - #region Object Members - String ToString(); - bool Equals(Object other); - int GetHashCode(); - Type GetType(); - #endregion - - #region MemberInfo Members - MemberTypes MemberType { get; } - String Name { get; } - Type DeclaringType { get; } - Type ReflectedType { get; } - Object[] GetCustomAttributes(Type attributeType, bool inherit); - Object[] GetCustomAttributes(bool inherit); - bool IsDefined(Type attributeType, bool inherit); - #endregion - - #region MethodBase Members - ParameterInfo[] GetParameters(); - MethodImplAttributes GetMethodImplementationFlags(); - RuntimeMethodHandle MethodHandle { get; } - MethodAttributes Attributes { get; } - CallingConventions CallingConvention { get; } - Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture); - bool IsPublic { get; } - bool IsPrivate { get; } - bool IsFamily { get; } - bool IsAssembly { get; } - bool IsFamilyAndAssembly { get; } - bool IsFamilyOrAssembly { get; } - bool IsStatic { get; } - bool IsFinal { get; } - bool IsVirtual { get; } - bool IsHideBySig { get; } - bool IsAbstract { get; } - bool IsSpecialName { get; } - bool IsConstructor { get; } - Object Invoke(Object obj, Object[] parameters); - #endregion -#endif } - [GuidAttribute("FFCC1B5D-ECB8-38DD-9B01-3DC8ABC2AA5F")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] @@ -344,62 +47,7 @@ get; } [System.Runtime.InteropServices.ComVisible(true)] public interface _MethodInfo { -#if !FEATURE_CORECLR - #region IDispatch Members - void GetTypeInfoCount(out uint pcTInfo); - void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); - void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); - void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); - #endregion - - #region Object Members - String ToString(); - bool Equals(Object other); - int GetHashCode(); - Type GetType(); - #endregion - - #region MemberInfo Members - MemberTypes MemberType { get; } - String Name { get; } - Type DeclaringType { get; } - Type ReflectedType { get; } - Object[] GetCustomAttributes(Type attributeType, bool inherit); - Object[] GetCustomAttributes(bool inherit); - bool IsDefined(Type attributeType, bool inherit); - #endregion - - #region MethodBase Members - ParameterInfo[] GetParameters(); - MethodImplAttributes GetMethodImplementationFlags(); - RuntimeMethodHandle MethodHandle { get; } - MethodAttributes Attributes { get; } - CallingConventions CallingConvention { get; } - Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture); - bool IsPublic { get; } - bool IsPrivate { get; } - bool IsFamily { get; } - bool IsAssembly { get; } - bool IsFamilyAndAssembly { get; } - bool IsFamilyOrAssembly { get; } - bool IsStatic { get; } - bool IsFinal { get; } - bool IsVirtual { get; } - bool IsHideBySig { get; } - bool IsAbstract { get; } - bool IsSpecialName { get; } - bool IsConstructor { get; } - Object Invoke(Object obj, Object[] parameters); - #endregion - - #region MethodInfo Members - Type ReturnType { get; } - ICustomAttributeProvider ReturnTypeCustomAttributes { get; } - MethodInfo GetBaseDefinition(); - #endregion -#endif } - [GuidAttribute("E9A19478-9646-3679-9B10-8411AE1FD57D")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] @@ -408,174 +56,26 @@ get; } [System.Runtime.InteropServices.ComVisible(true)] public interface _ConstructorInfo { -#if !FEATURE_CORECLR - #region IDispatch Members - void GetTypeInfoCount(out uint pcTInfo); - void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); - void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); - void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); - #endregion - - #region Object Members - String ToString(); - bool Equals(Object other); - int GetHashCode(); - Type GetType(); - #endregion - - #region MemberInfo Members - MemberTypes MemberType { get; } - String Name { get; } - Type DeclaringType { get; } - Type ReflectedType { get; } - Object[] GetCustomAttributes(Type attributeType, bool inherit); - Object[] GetCustomAttributes(bool inherit); - bool IsDefined(Type attributeType, bool inherit); - #endregion - - #region MethodBase Members - ParameterInfo[] GetParameters(); - MethodImplAttributes GetMethodImplementationFlags(); - RuntimeMethodHandle MethodHandle { get; } - MethodAttributes Attributes { get; } - CallingConventions CallingConvention { get; } - Object Invoke_2(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture); - bool IsPublic { get; } - bool IsPrivate { get; } - bool IsFamily { get; } - bool IsAssembly { get; } - bool IsFamilyAndAssembly { get; } - bool IsFamilyOrAssembly { get; } - bool IsStatic { get; } - bool IsFinal { get; } - bool IsVirtual { get; } - bool IsHideBySig { get; } - bool IsAbstract { get; } - bool IsSpecialName { get; } - bool IsConstructor { get; } - Object Invoke_3(Object obj, Object[] parameters); - #endregion - - #region ConstructorInfo - Object Invoke_4(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture); - Object Invoke_5(Object[] parameters); - #endregion -#endif } - [GuidAttribute("8A7C1442-A9FB-366B-80D8-4939FFA6DBE0")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.FieldInfo))] [System.Runtime.InteropServices.ComVisible(true)] public interface _FieldInfo - { -#if !FEATURE_CORECLR - #region IDispatch Members - void GetTypeInfoCount(out uint pcTInfo); - void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); - void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); - void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); - #endregion - - #region Object Members - String ToString(); - bool Equals(Object other); - int GetHashCode(); - Type GetType(); - #endregion - - #region MemberInfo Members - MemberTypes MemberType { get; } - String Name { get; } - Type DeclaringType { get; } - Type ReflectedType { get; } - Object[] GetCustomAttributes(Type attributeType, bool inherit); - Object[] GetCustomAttributes(bool inherit); - bool IsDefined(Type attributeType, bool inherit); - #endregion - - #region FieldInfo Members - Type FieldType { get; } - Object GetValue(Object obj); - Object GetValueDirect(TypedReference obj); - void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture); - void SetValueDirect(TypedReference obj,Object value); - RuntimeFieldHandle FieldHandle { get; } - FieldAttributes Attributes { get; } - void SetValue(Object obj, Object value); - bool IsPublic { get; } - bool IsPrivate { get; } - bool IsFamily { get; } - bool IsAssembly { get; } - bool IsFamilyAndAssembly { get; } - bool IsFamilyOrAssembly { get; } - bool IsStatic { get; } - bool IsInitOnly { get; } - bool IsLiteral { get; } - bool IsNotSerialized { get; } - bool IsSpecialName { get; } - bool IsPinvokeImpl { get; } - #endregion -#endif + { } - [GuidAttribute("F59ED4E4-E68F-3218-BD77-061AA82824BF")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.PropertyInfo))] -[System.Runtime.InteropServices.ComVisible(true)] + [System.Runtime.InteropServices.ComVisible(true)] public interface _PropertyInfo { -#if !FEATURE_CORECLR - #region IDispatch Members - void GetTypeInfoCount(out uint pcTInfo); - void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); - void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); - void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); - #endregion - - #region Object Members - String ToString(); - bool Equals(Object other); - int GetHashCode(); - Type GetType(); - #endregion - - #region MemberInfo Members - MemberTypes MemberType { get; } - String Name { get; } - Type DeclaringType { get; } - Type ReflectedType { get; } - Object[] GetCustomAttributes(Type attributeType, bool inherit); - Object[] GetCustomAttributes(bool inherit); - bool IsDefined(Type attributeType, bool inherit); - #endregion - - #region Property Members - Type PropertyType { get; } - Object GetValue(Object obj,Object[] index); - Object GetValue(Object obj,BindingFlags invokeAttr,Binder binder, Object[] index, CultureInfo culture); - void SetValue(Object obj, Object value, Object[] index); - void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture); - MethodInfo[] GetAccessors(bool nonPublic); - MethodInfo GetGetMethod(bool nonPublic); - MethodInfo GetSetMethod(bool nonPublic); - ParameterInfo[] GetIndexParameters(); - PropertyAttributes Attributes { get; } - bool CanRead { get; } - bool CanWrite { get; } - MethodInfo[] GetAccessors(); - MethodInfo GetGetMethod(); - MethodInfo GetSetMethod(); - bool IsSpecialName { get; } - #endregion -#endif } - [GuidAttribute("9DE59C64-D889-35A1-B897-587D74469E5B")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] @@ -583,91 +83,33 @@ get; } [System.Runtime.InteropServices.ComVisible(true)] public interface _EventInfo { -#if !FEATURE_CORECLR - #region IDispatch Members - void GetTypeInfoCount(out uint pcTInfo); - void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); - void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); - void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); - #endregion - - #region Object Members - String ToString(); - bool Equals(Object other); - int GetHashCode(); - Type GetType(); - #endregion - - #region MemberInfo Members - MemberTypes MemberType { get; } - String Name { get; } - Type DeclaringType { get; } - Type ReflectedType { get; } - Object[] GetCustomAttributes(Type attributeType, bool inherit); - Object[] GetCustomAttributes(bool inherit); - bool IsDefined(Type attributeType, bool inherit); - #endregion - - #region EventInfo Members - MethodInfo GetAddMethod(bool nonPublic); - MethodInfo GetRemoveMethod(bool nonPublic); - MethodInfo GetRaiseMethod(bool nonPublic); - EventAttributes Attributes { get; } - MethodInfo GetAddMethod(); - MethodInfo GetRemoveMethod(); - MethodInfo GetRaiseMethod(); - void AddEventHandler(Object target, Delegate handler); - void RemoveEventHandler(Object target, Delegate handler); - Type EventHandlerType { get; } - bool IsSpecialName { get; } - bool IsMulticast { get; } - #endregion -#endif } [GuidAttribute("993634C4-E47A-32CC-BE08-85F567DC27D6")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.ParameterInfo))] -[System.Runtime.InteropServices.ComVisible(true)] + [System.Runtime.InteropServices.ComVisible(true)] public interface _ParameterInfo { -#if !FEATURE_CORECLR - void GetTypeInfoCount(out uint pcTInfo); - void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); - void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); - void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); -#endif } [GuidAttribute("D002E9BA-D9E3-3749-B1D3-D565A08B13E7")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.Module))] -[System.Runtime.InteropServices.ComVisible(true)] + [System.Runtime.InteropServices.ComVisible(true)] public interface _Module { -#if !FEATURE_CORECLR - void GetTypeInfoCount(out uint pcTInfo); - void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); - void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); - void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); -#endif } [GuidAttribute("B42B6AAC-317E-34D5-9FA9-093BB4160C50")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.AssemblyName))] -[System.Runtime.InteropServices.ComVisible(true)] + [System.Runtime.InteropServices.ComVisible(true)] public interface _AssemblyName { -#if !FEATURE_CORECLR - void GetTypeInfoCount(out uint pcTInfo); - void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); - void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); - void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); -#endif } } diff --git a/src/mscorlib/src/System/Reflection/ConstructorInfo.cs b/src/mscorlib/src/System/Reflection/ConstructorInfo.cs index d5b5cc36eb..3d927fc85c 100644 --- a/src/mscorlib/src/System/Reflection/ConstructorInfo.cs +++ b/src/mscorlib/src/System/Reflection/ConstructorInfo.cs @@ -14,9 +14,6 @@ namespace System.Reflection using System.Runtime; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; -#if FEATURE_REMOTING - using System.Runtime.Remoting.Metadata; -#endif //FEATURE_REMOTING using System.Runtime.Serialization; using System.Security; using System.Security.Permissions; @@ -28,9 +25,6 @@ namespace System.Reflection [Serializable] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_ConstructorInfo))] -#pragma warning disable 618 - [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")] -#pragma warning restore 618 [System.Runtime.InteropServices.ComVisible(true)] public abstract class ConstructorInfo : MethodBase, _ConstructorInfo { @@ -101,57 +95,6 @@ namespace System.Reflection return Invoke(BindingFlags.Default, null, parameters, null); } #endregion - -#if !FEATURE_CORECLR - #region COM Interop Support - Type _ConstructorInfo.GetType() - { - return base.GetType(); - } - - Object _ConstructorInfo.Invoke_2(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) - { - return Invoke(obj, invokeAttr, binder, parameters, culture); - } - - Object _ConstructorInfo.Invoke_3(Object obj, Object[] parameters) - { - return Invoke(obj, parameters); - } - - Object _ConstructorInfo.Invoke_4(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) - { - return Invoke(invokeAttr, binder, parameters, culture); - } - - Object _ConstructorInfo.Invoke_5(Object[] parameters) - { - return Invoke(parameters); - } - - void _ConstructorInfo.GetTypeInfoCount(out uint pcTInfo) - { - throw new NotImplementedException(); - } - - void _ConstructorInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) - { - throw new NotImplementedException(); - } - - void _ConstructorInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) - { - throw new NotImplementedException(); - } - - // If you implement this method, make sure to include _ConstructorInfo.Invoke in VM\DangerousAPIs.h and - // include _ConstructorInfo in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp. - void _ConstructorInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) - { - throw new NotImplementedException(); - } - #endregion -#endif } [Serializable] @@ -205,7 +148,6 @@ namespace System.Reflection internal INVOCATION_FLAGS InvocationFlags { - [System.Security.SecuritySafeCritical] get { if ((m_invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0) @@ -261,7 +203,6 @@ namespace System.Reflection #endregion #region Constructor - [System.Security.SecurityCritical] // auto-generated internal RuntimeConstructorInfo( RuntimeMethodHandleInternal handle, RuntimeType declaringType, RuntimeTypeCache reflectedTypeCache, MethodAttributes methodAttributes, BindingFlags bindingFlags) @@ -276,40 +217,9 @@ namespace System.Reflection } #endregion -#if FEATURE_REMOTING - #region Legacy Remoting Cache - // The size of CachedData is accounted for by BaseObjectWithCachedData in object.h. - // This member is currently being used by Remoting for caching remoting data. If you - // need to cache data here, talk to the Remoting team to work out a mechanism, so that - // both caching systems can happily work together. - private RemotingMethodCachedData m_cachedData; - - internal RemotingMethodCachedData RemotingCache - { - get - { - // This grabs an internal copy of m_cachedData and uses - // that instead of looking at m_cachedData directly because - // the cache may get cleared asynchronously. This prevents - // us from having to take a lock. - RemotingMethodCachedData cache = m_cachedData; - if (cache == null) - { - cache = new RemotingMethodCachedData(this); - RemotingMethodCachedData ret = Interlocked.CompareExchange(ref m_cachedData, cache, null); - if (ret != null) - cache = ret; - } - return cache; - } - } - #endregion -#endif //FEATURE_REMOTING - #region NonPublic Methods RuntimeMethodHandleInternal IRuntimeMethodInfo.Value { - [System.Security.SecuritySafeCritical] get { return new RuntimeMethodHandleInternal(m_handle); @@ -397,28 +307,27 @@ namespace System.Reflection public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) - throw new ArgumentNullException("attributeType"); + throw new ArgumentNullException(nameof(attributeType)); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType"); + throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType)); return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType); } - [System.Security.SecuritySafeCritical] // auto-generated public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) - throw new ArgumentNullException("attributeType"); + throw new ArgumentNullException(nameof(attributeType)); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType"); + throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType)); return CustomAttribute.IsDefined(this, attributeRuntimeType); } @@ -433,7 +342,6 @@ namespace System.Reflection #region MemberInfo Overrides public override String Name { - [System.Security.SecuritySafeCritical] // auto-generated get { return RuntimeMethodHandle.GetName(this); } } [System.Runtime.InteropServices.ComVisible(true)] @@ -457,7 +365,6 @@ namespace System.Reflection public override int MetadataToken { - [System.Security.SecuritySafeCritical] // auto-generated get { return RuntimeMethodHandle.GetMethodDef(this); } } public override Module Module @@ -475,7 +382,6 @@ namespace System.Reflection // This seems to always returns System.Void. internal override Type GetReturnType() { return Signature.ReturnType; } - [System.Security.SecuritySafeCritical] // auto-generated internal override ParameterInfo[] GetParametersNoCopy() { if (m_parameters == null) @@ -532,7 +438,7 @@ namespace System.Reflection internal static void CheckCanCreateInstance(Type declaringType, bool isVarArg) { if (declaringType == null) - throw new ArgumentNullException("declaringType"); + throw new ArgumentNullException(nameof(declaringType)); Contract.EndContractBlock(); // ctor is ReflectOnly @@ -580,7 +486,6 @@ namespace System.Reflection throw new TargetException(); } - [System.Security.SecuritySafeCritical] // auto-generated [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable @@ -607,26 +512,10 @@ namespace System.Reflection if (obj != null) { - -#if FEATURE_CORECLR // 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; -#else // FEATURE_CORECLR - new SecurityPermission(SecurityPermissionFlag.SkipVerification).Demand(); -#endif // FEATURE_CORECLR - - } - -#if !FEATURE_CORECLR - if ((invocationFlags &(INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD | INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY)) != 0) - { - if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD) != 0) - CodeAccessPermission.Demand(PermissionType.ReflectionMemberAccess); - if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) != 0) - RuntimeMethodHandle.PerformSecurityCheck(obj, this, m_declaringType, (uint)m_invocationFlags); } -#endif // !FEATURE_CORECLR Signature sig = Signature; @@ -650,7 +539,6 @@ namespace System.Reflection } - [System.Security.SecuritySafeCritical] // overrides SC member #pragma warning disable 618 [ReflectionPermissionAttribute(SecurityAction.Demand, Flags = ReflectionPermissionFlag.MemberAccess)] #pragma warning restore 618 @@ -664,17 +552,17 @@ namespace System.Reflection public override bool IsSecurityCritical { - get { return RuntimeMethodHandle.IsSecurityCritical(this); } + get { return true; } } public override bool IsSecuritySafeCritical { - get { return RuntimeMethodHandle.IsSecuritySafeCritical(this); } + get { return false; } } public override bool IsSecurityTransparent { - get { return RuntimeMethodHandle.IsSecurityTransparent(this); } + get { return false; } } public override bool ContainsGenericParameters @@ -687,7 +575,6 @@ namespace System.Reflection #endregion #region ConstructorInfo Overrides - [System.Security.SecuritySafeCritical] // auto-generated [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable @@ -711,18 +598,6 @@ namespace System.Reflection } #endif -#if !FEATURE_CORECLR - if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD | INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY | INVOCATION_FLAGS.INVOCATION_FLAGS_IS_DELEGATE_CTOR)) != 0) - { - if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD) != 0) - CodeAccessPermission.Demand(PermissionType.ReflectionMemberAccess); - if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) != 0) - RuntimeMethodHandle.PerformSecurityCheck(null, this, m_declaringType, (uint)(m_invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_CONSTRUCTOR_INVOKE)); - if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_IS_DELEGATE_CTOR) != 0) - new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand(); - } -#endif // !FEATURE_CORECLR - // get the signature Signature sig = Signature; @@ -749,11 +624,10 @@ namespace System.Reflection #endregion #region ISerializable Implementation - [System.Security.SecurityCritical] // auto-generated public void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) - throw new ArgumentNullException("info"); + throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); MemberInfoSerializationHolder.GetSerializationInfo( info, @@ -777,5 +651,4 @@ namespace System.Reflection } #endregion } - } diff --git a/src/mscorlib/src/System/Reflection/CustomAttribute.cs b/src/mscorlib/src/System/Reflection/CustomAttribute.cs index 463c976357..e568a1702f 100644 --- a/src/mscorlib/src/System/Reflection/CustomAttribute.cs +++ b/src/mscorlib/src/System/Reflection/CustomAttribute.cs @@ -29,7 +29,7 @@ namespace System.Reflection public static IList<CustomAttributeData> GetCustomAttributes(MemberInfo target) { if (target == null) - throw new ArgumentNullException("target"); + throw new ArgumentNullException(nameof(target)); return target.GetCustomAttributesData(); } @@ -37,7 +37,7 @@ namespace System.Reflection public static IList<CustomAttributeData> GetCustomAttributes(Module target) { if (target == null) - throw new ArgumentNullException("target"); + throw new ArgumentNullException(nameof(target)); Contract.EndContractBlock(); return target.GetCustomAttributesData(); @@ -46,7 +46,7 @@ namespace System.Reflection public static IList<CustomAttributeData> GetCustomAttributes(Assembly target) { if (target == null) - throw new ArgumentNullException("target"); + throw new ArgumentNullException(nameof(target)); Contract.EndContractBlock(); return target.GetCustomAttributesData(); @@ -55,7 +55,7 @@ namespace System.Reflection public static IList<CustomAttributeData> GetCustomAttributes(ParameterInfo target) { if (target == null) - throw new ArgumentNullException("target"); + throw new ArgumentNullException(nameof(target)); Contract.EndContractBlock(); return target.GetCustomAttributesData(); @@ -63,10 +63,9 @@ namespace System.Reflection #endregion #region Internal Static Members - [System.Security.SecuritySafeCritical] // auto-generated internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeType target) { - Contract.Assert(target != null); + Debug.Assert(target != null); IList<CustomAttributeData> cad = GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken); @@ -86,10 +85,9 @@ namespace System.Reflection return Array.AsReadOnly(pca); } - [System.Security.SecuritySafeCritical] // auto-generated internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeFieldInfo target) { - Contract.Assert(target != null); + Debug.Assert(target != null); IList<CustomAttributeData> cad = GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken); @@ -109,10 +107,9 @@ namespace System.Reflection return Array.AsReadOnly(pca); } - [System.Security.SecuritySafeCritical] // auto-generated internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeMethodInfo target) { - Contract.Assert(target != null); + Debug.Assert(target != null); IList<CustomAttributeData> cad = GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken); @@ -132,34 +129,30 @@ namespace System.Reflection return Array.AsReadOnly(pca); } - [System.Security.SecuritySafeCritical] // auto-generated internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeConstructorInfo target) { - Contract.Assert(target != null); + Debug.Assert(target != null); return GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken); } - [System.Security.SecuritySafeCritical] // auto-generated internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeEventInfo target) { - Contract.Assert(target != null); + Debug.Assert(target != null); return GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken); } - [System.Security.SecuritySafeCritical] // auto-generated internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimePropertyInfo target) { - Contract.Assert(target != null); + Debug.Assert(target != null); return GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken); } - [System.Security.SecuritySafeCritical] // auto-generated internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeModule target) { - Contract.Assert(target != null); + Debug.Assert(target != null); if (target.IsResource()) return new List<CustomAttributeData>(); @@ -167,10 +160,9 @@ namespace System.Reflection return GetCustomAttributes(target, target.MetadataToken); } - [System.Security.SecuritySafeCritical] // auto-generated internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeAssembly target) { - Contract.Assert(target != null); + Debug.Assert(target != null); IList<CustomAttributeData> cad = GetCustomAttributes((RuntimeModule)target.ManifestModule, RuntimeAssembly.GetToken(target.GetNativeHandle())); @@ -190,10 +182,9 @@ namespace System.Reflection return Array.AsReadOnly(pca); } - [System.Security.SecuritySafeCritical] // auto-generated internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeParameterInfo target) { - Contract.Assert(target != null); + Debug.Assert(target != null); IList<CustomAttributeData> cad = GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken); @@ -279,7 +270,7 @@ namespace System.Reflection if (type.IsValueType) return CustomAttributeEncoding.Undefined; - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidKindOfTypeForCA"), "type"); + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidKindOfTypeForCA"), nameof(type)); } private static CustomAttributeType InitCustomAttributeType(RuntimeType parameterType) { @@ -302,7 +293,6 @@ namespace System.Reflection return new CustomAttributeType(encodedType, encodedArrayType, encodedEnumType, enumName); } - [System.Security.SecurityCritical] // auto-generated private static IList<CustomAttributeData> GetCustomAttributes(RuntimeModule module, int tkTarget) { CustomAttributeRecord[] records = GetCustomAttributeRecords(module, tkTarget); @@ -316,7 +306,6 @@ namespace System.Reflection #endregion #region Internal Static Members - [System.Security.SecurityCritical] // auto-generated internal unsafe static CustomAttributeRecord[] GetCustomAttributeRecords(RuntimeModule module, int targetToken) { MetadataImport scope = module.MetadataImport; @@ -369,7 +358,6 @@ namespace System.Reflection { } - [System.Security.SecuritySafeCritical] // auto-generated private CustomAttributeData(RuntimeModule scope, CustomAttributeRecord caRecord) { m_scope = scope; @@ -611,7 +599,7 @@ namespace System.Reflection public CustomAttributeNamedArgument(MemberInfo memberInfo, object value) { if (memberInfo == null) - throw new ArgumentNullException("memberInfo"); + throw new ArgumentNullException(nameof(memberInfo)); Type type = null; FieldInfo field = memberInfo as FieldInfo; @@ -631,7 +619,7 @@ namespace System.Reflection public CustomAttributeNamedArgument(MemberInfo memberInfo, CustomAttributeTypedArgument typedArgument) { if (memberInfo == null) - throw new ArgumentNullException("memberInfo"); + throw new ArgumentNullException(nameof(memberInfo)); m_memberInfo = memberInfo; m_value = typedArgument; @@ -749,11 +737,10 @@ namespace System.Reflection return typeof(object); default : - throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)encodedType), "encodedType"); + throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)encodedType), nameof(encodedType)); } } - [SecuritySafeCritical] private static object EncodedValueToRawValue(long val, CustomAttributeEncoding encodedType) { switch (encodedType) @@ -795,7 +782,7 @@ namespace System.Reflection unsafe { return *(double*)&val; } default: - throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)val), "val"); + throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)val), nameof(val)); } } private static RuntimeType ResolveType(RuntimeModule scope, string typeName) @@ -820,7 +807,7 @@ namespace System.Reflection { // value can be null. if (argumentType == null) - throw new ArgumentNullException("argumentType"); + throw new ArgumentNullException(nameof(argumentType)); m_value = (value == null) ? null : CanonicalizeValue(value); m_argumentType = argumentType; @@ -830,7 +817,7 @@ namespace System.Reflection { // value cannot be null. if (value == null) - throw new ArgumentNullException("value"); + throw new ArgumentNullException(nameof(value)); m_value = CanonicalizeValue(value); m_argumentType = value.GetType(); @@ -838,7 +825,7 @@ namespace System.Reflection private static object CanonicalizeValue(object value) { - Contract.Assert(value != null); + Debug.Assert(value != null); if (value.GetType().IsEnum) { @@ -852,7 +839,7 @@ namespace System.Reflection CustomAttributeEncoding encodedType = encodedArg.CustomAttributeType.EncodedType; if (encodedType == CustomAttributeEncoding.Undefined) - throw new ArgumentException("encodedArg"); + throw new ArgumentException(null, nameof(encodedArg)); else if (encodedType == CustomAttributeEncoding.Enum) { @@ -1015,7 +1002,6 @@ namespace System.Reflection internal struct CustomAttributeEncodedArgument { #region Parser - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void ParseAttributeArguments( IntPtr pCa, @@ -1024,18 +1010,17 @@ namespace System.Reflection ref CustomAttributeNamedParameter[] CustomAttributeTypedArgument, RuntimeAssembly assembly); - [System.Security.SecurityCritical] // auto-generated internal static void ParseAttributeArguments(ConstArray attributeBlob, ref CustomAttributeCtorParameter[] customAttributeCtorParameters, ref CustomAttributeNamedParameter[] customAttributeNamedParameters, RuntimeModule customAttributeModule) { if (customAttributeModule == null) - throw new ArgumentNullException("customAttributeModule"); + throw new ArgumentNullException(nameof(customAttributeModule)); Contract.EndContractBlock(); - Contract.Assert(customAttributeCtorParameters != null); - Contract.Assert(customAttributeNamedParameters != null); + Debug.Assert(customAttributeCtorParameters != null); + Debug.Assert(customAttributeNamedParameters != null); if (customAttributeCtorParameters.Length != 0 || customAttributeNamedParameters.Length != 0) { @@ -1083,7 +1068,7 @@ namespace System.Reflection public CustomAttributeNamedParameter(string argumentName, CustomAttributeEncoding fieldOrProperty, CustomAttributeType type) { if (argumentName == null) - throw new ArgumentNullException("argumentName"); + throw new ArgumentNullException(nameof(argumentName)); Contract.EndContractBlock(); m_argumentName = argumentName; @@ -1131,11 +1116,9 @@ namespace System.Reflection IntPtr m_Next; IntPtr m_Assembly; - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern void Push(RuntimeAssembly assembly); - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public extern void Pop(); @@ -1183,7 +1166,6 @@ namespace System.Reflection #endregion #region Internal Static Members - [System.Security.SecurityCritical] // auto-generated internal static bool IsDefined(RuntimeType type, RuntimeType caType, bool inherit) { Contract.Requires(type != null); @@ -1213,7 +1195,6 @@ namespace System.Reflection return false; } - [System.Security.SecuritySafeCritical] // auto-generated internal static bool IsDefined(RuntimeMethodInfo method, RuntimeType caType, bool inherit) { Contract.Requires(method != null); @@ -1241,7 +1222,6 @@ namespace System.Reflection return false; } - [System.Security.SecurityCritical] // auto-generated internal static bool IsDefined(RuntimeConstructorInfo ctor, RuntimeType caType) { Contract.Requires(ctor != null); @@ -1253,7 +1233,6 @@ namespace System.Reflection return IsCustomAttributeDefined(ctor.GetRuntimeModule(), ctor.MetadataToken, caType); } - [System.Security.SecurityCritical] // auto-generated internal static bool IsDefined(RuntimePropertyInfo property, RuntimeType caType) { Contract.Requires(property != null); @@ -1265,7 +1244,6 @@ namespace System.Reflection return IsCustomAttributeDefined(property.GetRuntimeModule(), property.MetadataToken, caType); } - [System.Security.SecurityCritical] // auto-generated internal static bool IsDefined(RuntimeEventInfo e, RuntimeType caType) { Contract.Requires(e != null); @@ -1277,7 +1255,6 @@ namespace System.Reflection return IsCustomAttributeDefined(e.GetRuntimeModule(), e.MetadataToken, caType); } - [System.Security.SecurityCritical] // auto-generated internal static bool IsDefined(RuntimeFieldInfo field, RuntimeType caType) { Contract.Requires(field != null); @@ -1289,7 +1266,6 @@ namespace System.Reflection return IsCustomAttributeDefined(field.GetRuntimeModule(), field.MetadataToken, caType); } - [System.Security.SecurityCritical] // auto-generated internal static bool IsDefined(RuntimeParameterInfo parameter, RuntimeType caType) { Contract.Requires(parameter != null); @@ -1301,7 +1277,6 @@ namespace System.Reflection return IsCustomAttributeDefined(parameter.GetRuntimeModule(), parameter.MetadataToken, caType); } - [System.Security.SecuritySafeCritical] // auto-generated internal static bool IsDefined(RuntimeAssembly assembly, RuntimeType caType) { Contract.Requires(assembly != null); @@ -1313,7 +1288,6 @@ namespace System.Reflection return IsCustomAttributeDefined(assembly.ManifestModule as RuntimeModule, RuntimeAssembly.GetToken(assembly.GetNativeHandle()), caType); } - [System.Security.SecurityCritical] // auto-generated internal static bool IsDefined(RuntimeModule module, RuntimeType caType) { Contract.Requires(module != null); @@ -1325,7 +1299,6 @@ namespace System.Reflection return IsCustomAttributeDefined(module, module.MetadataToken, caType); } - [System.Security.SecurityCritical] // auto-generated internal static Object[] GetCustomAttributes(RuntimeType type, RuntimeType caType, bool inherit) { Contract.Requires(type != null); @@ -1388,7 +1361,7 @@ namespace System.Reflection else { type = type.DeclaringType as RuntimeType; - Contract.Assert(type != null); + Debug.Assert(type != null); } } @@ -1397,16 +1370,7 @@ namespace System.Reflection private static bool SpecialAllowCriticalAttributes(RuntimeType type) { - // Types participating in Type Equivalence are always transparent. - // See TokenSecurityDescriptor::VerifySemanticDataComputed in securitymeta.cpp. - // Because of that we allow critical attributes applied to full trust equivalent types. - // DeclaringType is null for global methods and fields and the global type never participates in type equivalency. - -#if FEATURE_CORECLR return false; -#else - return type != null && type.Assembly.IsFullyTrusted && RuntimeTypeHandle.IsEquivalentType(type); -#endif //!FEATURE_CORECLR } private static bool AllowCriticalCustomAttributes(MethodBase method) @@ -1429,7 +1393,6 @@ namespace System.Reflection return AllowCriticalCustomAttributes(parameter.DefiningMethod); } - [System.Security.SecurityCritical] // auto-generated internal static Object[] GetCustomAttributes(RuntimeMethodInfo method, RuntimeType caType, bool inherit) { Contract.Requires(method != null); @@ -1474,7 +1437,6 @@ namespace System.Reflection return typedResult; } - [System.Security.SecuritySafeCritical] // auto-generated internal static Object[] GetCustomAttributes(RuntimeConstructorInfo ctor, RuntimeType caType) { Contract.Requires(ctor != null); @@ -1487,7 +1449,6 @@ namespace System.Reflection return attributes; } - [System.Security.SecuritySafeCritical] // auto-generated internal static Object[] GetCustomAttributes(RuntimePropertyInfo property, RuntimeType caType) { Contract.Requires(property != null); @@ -1506,7 +1467,6 @@ namespace System.Reflection return attributes; } - [System.Security.SecuritySafeCritical] // auto-generated internal static Object[] GetCustomAttributes(RuntimeEventInfo e, RuntimeType caType) { Contract.Requires(e != null); @@ -1524,7 +1484,6 @@ namespace System.Reflection return attributes; } - [System.Security.SecuritySafeCritical] // auto-generated internal static Object[] GetCustomAttributes(RuntimeFieldInfo field, RuntimeType caType) { Contract.Requires(field != null); @@ -1537,7 +1496,6 @@ namespace System.Reflection return attributes; } - [System.Security.SecuritySafeCritical] // auto-generated internal static Object[] GetCustomAttributes(RuntimeParameterInfo parameter, RuntimeType caType) { Contract.Requires(parameter != null); @@ -1550,7 +1508,6 @@ namespace System.Reflection return attributes; } - [System.Security.SecuritySafeCritical] // auto-generated internal static Object[] GetCustomAttributes(RuntimeAssembly assembly, RuntimeType caType) { Contract.Requires(assembly != null); @@ -1565,7 +1522,6 @@ namespace System.Reflection return attributes; } - [System.Security.SecuritySafeCritical] // auto-generated internal static Object[] GetCustomAttributes(RuntimeModule module, RuntimeType caType) { Contract.Requires(module != null); @@ -1579,20 +1535,17 @@ namespace System.Reflection return attributes; } - [System.Security.SecuritySafeCritical] internal static bool IsAttributeDefined(RuntimeModule decoratedModule, int decoratedMetadataToken, int attributeCtorToken) { return IsCustomAttributeDefined(decoratedModule, decoratedMetadataToken, null, attributeCtorToken, false); } - [System.Security.SecurityCritical] // auto-generated private static bool IsCustomAttributeDefined( RuntimeModule decoratedModule, int decoratedMetadataToken, RuntimeType attributeFilterType) { return IsCustomAttributeDefined(decoratedModule, decoratedMetadataToken, attributeFilterType, 0, false); } - [System.Security.SecurityCritical] // auto-generated private static bool IsCustomAttributeDefined( RuntimeModule decoratedModule, int decoratedMetadataToken, RuntimeType attributeFilterType, int attributeCtorToken, bool mustBeInheritable) { @@ -1604,7 +1557,7 @@ namespace System.Reflection if (attributeFilterType != null) { - Contract.Assert(attributeCtorToken == 0); + Debug.Assert(attributeCtorToken == 0); MetadataImport scope = decoratedModule.MetadataImport; RuntimeType attributeType; @@ -1627,8 +1580,8 @@ namespace System.Reflection } else { - Contract.Assert(attributeFilterType == null); - Contract.Assert(!MetadataToken.IsNullToken(attributeCtorToken)); + Debug.Assert(attributeFilterType == null); + Debug.Assert(!MetadataToken.IsNullToken(attributeCtorToken)); for (int i = 0; i < car.Length; i++) { @@ -1642,14 +1595,12 @@ namespace System.Reflection return false; } - [System.Security.SecurityCritical] // auto-generated private unsafe static object[] GetCustomAttributes( RuntimeModule decoratedModule, int decoratedMetadataToken, int pcaCount, RuntimeType attributeFilterType, bool isDecoratedTargetSecurityTransparent) { return GetCustomAttributes(decoratedModule, decoratedMetadataToken, pcaCount, attributeFilterType, false, null, isDecoratedTargetSecurityTransparent); } - [System.Security.SecurityCritical] private unsafe static object[] GetCustomAttributes( RuntimeModule decoratedModule, int decoratedMetadataToken, int pcaCount, RuntimeType attributeFilterType, bool mustBeInheritable, IList derivedAttributes, bool isDecoratedTargetSecurityTransparent) @@ -1841,7 +1792,6 @@ namespace System.Reflection return result; } - [System.Security.SecurityCritical] // auto-generated private unsafe static bool FilterCustomAttributeRecord( CustomAttributeRecord caRecord, MetadataImport scope, @@ -1885,19 +1835,6 @@ namespace System.Reflection return false; } -#if FEATURE_APTCA - // APTCA checks - RuntimeAssembly attributeAssembly = (RuntimeAssembly)attributeType.Assembly; - RuntimeAssembly decoratedModuleAssembly = (RuntimeAssembly)decoratedModule.Assembly; - - if (attributeAssembly != lastAptcaOkAssembly && - !RuntimeAssembly.AptcaCheck(attributeAssembly, decoratedModuleAssembly)) - return false; - - // Cache last successful APTCA check (optimization) - lastAptcaOkAssembly = decoratedModuleAssembly; -#endif // FEATURE_APTCA - // Resolve the attribute ctor ConstArray ctorSig = scope.GetMethodSignature(caRecord.tkCtor); isVarArg = (ctorSig[0] & 0x05) != 0; @@ -1944,7 +1881,7 @@ namespace System.Reflection else { // We need to relax this when we add support for other types of decorated tokens. - Contract.Assert(decoratedToken.IsModule || decoratedToken.IsAssembly, + Debug.Assert(decoratedToken.IsModule || decoratedToken.IsAssembly, "The decoratedToken must be either an assembly, a module, a type, or a member."); } @@ -1959,7 +1896,6 @@ namespace System.Reflection #endregion #region Private Static Methods - [System.Security.SecurityCritical] // auto-generated private static bool AttributeUsageCheck( RuntimeType attributeType, bool mustBeInheritable, object[] attributes, IList derivedAttributes) { @@ -1992,7 +1928,6 @@ namespace System.Reflection return true; } - [System.Security.SecurityCritical] // auto-generated internal static AttributeUsageAttribute GetAttributeUsage(RuntimeType decoratedAttribute) { RuntimeModule decoratedModule = decoratedAttribute.GetRuntimeModule(); @@ -2027,11 +1962,9 @@ namespace System.Reflection #endregion #region Private Static FCalls - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _ParseAttributeUsageAttribute( IntPtr pCa, int cCa, out int targets, out bool inherited, out bool allowMultiple); - [System.Security.SecurityCritical] // auto-generated private static void ParseAttributeUsageAttribute( ConstArray ca, out AttributeTargets targets, out bool inherited, out bool allowMultiple) { @@ -2040,10 +1973,8 @@ namespace System.Reflection targets = (AttributeTargets)_targets; } - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static unsafe extern Object _CreateCaObject(RuntimeModule pModule, IRuntimeMethodInfo pCtor, byte** ppBlob, byte* pEndBlob, int* pcNamedArgs); - [System.Security.SecurityCritical] // auto-generated private static unsafe Object CreateCaObject(RuntimeModule module, IRuntimeMethodInfo ctor, ref IntPtr blob, IntPtr blobEnd, out int namedArgs) { byte* pBlob = (byte*)blob; @@ -2055,11 +1986,9 @@ namespace System.Reflection return ca; } - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private unsafe extern static void _GetPropertyOrFieldData( RuntimeModule pModule, byte** ppBlobStart, byte* pBlobEnd, out string name, out bool bIsProperty, out RuntimeType type, out object value); - [System.Security.SecurityCritical] // auto-generated private unsafe static void GetPropertyOrFieldData( RuntimeModule module, ref IntPtr blobStart, IntPtr blobEnd, out string name, out bool isProperty, out RuntimeType type, out object value) { @@ -2069,7 +1998,6 @@ namespace System.Reflection blobStart = (IntPtr)pBlobStart; } - [System.Security.SecuritySafeCritical] private static object[] CreateAttributeArrayHelper(Type elementType, int elementCount) { return (object[])Array.UnsafeCreateInstance(elementType, elementCount); @@ -2089,18 +2017,13 @@ namespace System.Reflection #endregion #region FCalls - [System.Security.SecurityCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.InternalCall)] - unsafe private static extern void _GetSecurityAttributes(RuntimeModule module, int token, bool assembly, out object[] securityAttributes); - [System.Security.SecurityCritical] // auto-generated - unsafe internal static void GetSecurityAttributes(RuntimeModule module, int token, bool assembly, out object[] securityAttributes) + internal static void GetSecurityAttributes(RuntimeModule module, int token, bool assembly, out object[] securityAttributes) { - _GetSecurityAttributes(module.GetNativeHandle(), token, assembly, out securityAttributes); + securityAttributes = null; } #endregion #region Static Constructor - [System.Security.SecurityCritical] // auto-generated static PseudoCustomAttribute() { RuntimeType[] pcas = new RuntimeType[] @@ -2130,21 +2053,20 @@ namespace System.Reflection s_pca = temp_pca; } - [System.Security.SecurityCritical] // auto-generated [Conditional("_DEBUG")] private static void VerifyPseudoCustomAttribute(RuntimeType pca) { // If any of these are invariants are no longer true will have to // re-architect the PCA product logic and test cases -- you've been warned! - Contract.Assert(pca.BaseType == (RuntimeType)typeof(Attribute), "Pseudo CA Error"); + Debug.Assert(pca.BaseType == (RuntimeType)typeof(Attribute), "Pseudo CA Error"); AttributeUsageAttribute usage = CustomAttribute.GetAttributeUsage(pca); - Contract.Assert(usage.Inherited == false, "Pseudo CA Error"); + Debug.Assert(usage.Inherited == false, "Pseudo CA Error"); //AllowMultiple is true for TypeForwardedToAttribute - //Contract.Assert(usage.AllowMultiple == false, "Pseudo CA Error"); + //Debug.Assert(usage.AllowMultiple == false, "Pseudo CA Error"); } - #endregion +#endregion - #region Internal Static +#region Internal Static internal static bool IsSecurityAttribute(RuntimeType type) { #pragma warning disable 618 @@ -2152,7 +2074,6 @@ namespace System.Reflection #pragma warning restore 618 } - [System.Security.SecurityCritical] // auto-generated internal static Attribute[] GetCustomAttributes(RuntimeType type, RuntimeType caType, bool includeSecCa, out int count) { Contract.Requires(type != null); @@ -2196,7 +2117,6 @@ namespace System.Reflection count = pcas.Count; return pcas.ToArray(); } - [System.Security.SecurityCritical] // auto-generated internal static bool IsDefined(RuntimeType type, RuntimeType caType) { bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute); @@ -2221,7 +2141,6 @@ namespace System.Reflection return false; } - [System.Security.SecurityCritical] // auto-generated internal static Attribute[] GetCustomAttributes(RuntimeMethodInfo method, RuntimeType caType, bool includeSecCa, out int count) { Contract.Requires(method != null); @@ -2260,7 +2179,6 @@ namespace System.Reflection count = pcas.Count; return pcas.ToArray(); } - [System.Security.SecurityCritical] // auto-generated internal static bool IsDefined(RuntimeMethodInfo method, RuntimeType caType) { bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute); @@ -2286,7 +2204,6 @@ namespace System.Reflection return false; } - [System.Security.SecurityCritical] // auto-generated internal static Attribute[] GetCustomAttributes(RuntimeParameterInfo parameter, RuntimeType caType, out int count) { Contract.Requires(parameter != null); @@ -2323,7 +2240,6 @@ namespace System.Reflection } return pcas; } - [System.Security.SecurityCritical] // auto-generated internal static bool IsDefined(RuntimeParameterInfo parameter, RuntimeType caType) { bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute); @@ -2351,7 +2267,6 @@ namespace System.Reflection return false; } - [System.Security.SecurityCritical] // auto-generated internal static Attribute[] GetCustomAttributes(RuntimeAssembly assembly, RuntimeType caType, bool includeSecCa, out int count) { count = 0; @@ -2386,7 +2301,6 @@ namespace System.Reflection count = pcas.Count; return pcas.ToArray(); } - [System.Security.SecurityCritical] // auto-generated internal static bool IsDefined(RuntimeAssembly assembly, RuntimeType caType) { int count; @@ -2403,7 +2317,6 @@ namespace System.Reflection return false; } - [System.Security.SecurityCritical] // auto-generated internal static Attribute[] GetCustomAttributes(RuntimeFieldInfo field, RuntimeType caType, out int count) { Contract.Requires(field != null); @@ -2435,7 +2348,6 @@ namespace System.Reflection } return pcas; } - [System.Security.SecurityCritical] // auto-generated internal static bool IsDefined(RuntimeFieldInfo field, RuntimeType caType) { bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute); @@ -2458,7 +2370,6 @@ namespace System.Reflection return false; } - [System.Security.SecurityCritical] // auto-generated internal static Attribute[] GetCustomAttributes(RuntimeConstructorInfo ctor, RuntimeType caType, bool includeSecCa, out int count) { count = 0; @@ -2484,7 +2395,6 @@ namespace System.Reflection count = pcas.Count; return pcas.ToArray(); } - [System.Security.SecurityCritical] // auto-generated internal static bool IsDefined(RuntimeConstructorInfo ctor, RuntimeType caType) { bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute); @@ -2522,6 +2432,6 @@ namespace System.Reflection { return false; } - #endregion +#endregion } } diff --git a/src/mscorlib/src/System/Reflection/Emit/AQNBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/AQNBuilder.cs index 6484677c62..fb9324902a 100644 --- a/src/mscorlib/src/System/Reflection/Emit/AQNBuilder.cs +++ b/src/mscorlib/src/System/Reflection/Emit/AQNBuilder.cs @@ -22,59 +22,45 @@ namespace System.Reflection.Emit } #region QCalls - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern IntPtr CreateTypeNameBuilder(); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void ReleaseTypeNameBuilder(IntPtr pAQN); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void OpenGenericArguments(IntPtr tnb); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void CloseGenericArguments(IntPtr tnb); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void OpenGenericArgument(IntPtr tnb); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void CloseGenericArgument(IntPtr tnb); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void AddName(IntPtr tnb, string name); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void AddPointer(IntPtr tnb); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void AddByRef(IntPtr tnb); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void AddSzArray(IntPtr tnb); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void AddArray(IntPtr tnb, int rank); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void AddAssemblySpec(IntPtr tnb, string assemblySpec); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void ToString(IntPtr tnb, StringHandleOnStack retString); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void Clear(IntPtr tnb); @@ -83,7 +69,6 @@ namespace System.Reflection.Emit #region Static Members // TypeNameBuilder is NOT thread safe NOR reliable - [System.Security.SecuritySafeCritical] // auto-generated internal static string ToString(Type type, Format format) { if (format == Format.FullName || format == Format.AssemblyQualifiedName) @@ -107,12 +92,10 @@ namespace System.Reflection.Emit #region Constructor private TypeNameBuilder(IntPtr typeNameBuilder) { m_typeNameBuilder = typeNameBuilder; } - [System.Security.SecurityCritical] // auto-generated internal void Dispose() { ReleaseTypeNameBuilder(m_typeNameBuilder); } #endregion #region private Members - [System.Security.SecurityCritical] // auto-generated private void AddElementType(Type elementType) { if (elementType.HasElementType) @@ -131,7 +114,6 @@ namespace System.Reflection.Emit AddArray(elementType.GetArrayRank()); } - [System.Security.SecurityCritical] // auto-generated private void ConstructAssemblyQualifiedNameWorker(Type type, Format format) { Type rootType = type; @@ -179,29 +161,17 @@ namespace System.Reflection.Emit AddAssemblySpec(type.Module.Assembly.FullName); } - [System.Security.SecurityCritical] // auto-generated private void OpenGenericArguments() { OpenGenericArguments(m_typeNameBuilder); } - [System.Security.SecurityCritical] // auto-generated private void CloseGenericArguments() { CloseGenericArguments(m_typeNameBuilder); } - [System.Security.SecurityCritical] // auto-generated private void OpenGenericArgument() { OpenGenericArgument(m_typeNameBuilder); } - [System.Security.SecurityCritical] // auto-generated private void CloseGenericArgument() { CloseGenericArgument(m_typeNameBuilder); } - [System.Security.SecurityCritical] // auto-generated private void AddName(string name) { AddName(m_typeNameBuilder, name); } - [System.Security.SecurityCritical] // auto-generated private void AddPointer() { AddPointer(m_typeNameBuilder); } - [System.Security.SecurityCritical] // auto-generated private void AddByRef() { AddByRef(m_typeNameBuilder); } - [System.Security.SecurityCritical] // auto-generated private void AddSzArray() { AddSzArray(m_typeNameBuilder); } - [System.Security.SecurityCritical] // auto-generated private void AddArray(int rank) { AddArray(m_typeNameBuilder, rank); } - [System.Security.SecurityCritical] // auto-generated private void AddAssemblySpec(string assemblySpec) { AddAssemblySpec(m_typeNameBuilder, assemblySpec); } - [System.Security.SecuritySafeCritical] // auto-generated public override string ToString() { string ret = null; ToString(m_typeNameBuilder, JitHelpers.GetStringHandleOnStack(ref ret)); return ret; } - [System.Security.SecurityCritical] // auto-generated private void Clear() { Clear(m_typeNameBuilder); } #endregion } diff --git a/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilder.cs index 5e7f83f2df..9331ae193c 100644 --- a/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilder.cs +++ b/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilder.cs @@ -98,17 +98,11 @@ namespace System.Reflection.Emit throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly")); } - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif public override FileStream GetFile(String name) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly")); } - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif public override FileStream[] GetFiles(bool getResourceModules) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly")); @@ -131,9 +125,6 @@ namespace System.Reflection.Emit public override String Location { -#if FEATURE_CORECLR - [SecurityCritical] -#endif // FEATURE_CORECLR get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly")); @@ -142,9 +133,6 @@ namespace System.Reflection.Emit public override String CodeBase { -#if FEATURE_CORECLR - [SecurityCritical] -#endif // FEATURE_CORECLR get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly")); @@ -168,43 +156,20 @@ namespace System.Reflection.Emit // AssemblyBuilder class. // deliberately not [serializable] - [HostProtection(MayLeakOnAbort = true)] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_AssemblyBuilder))] [ComVisible(true)] public sealed class AssemblyBuilder : Assembly, _AssemblyBuilder { #region FCALL - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern RuntimeModule GetInMemoryAssemblyModule(RuntimeAssembly assembly); - [System.Security.SecurityCritical] // auto-generated private Module nGetInMemoryAssemblyModule() { return AssemblyBuilder.GetInMemoryAssemblyModule(GetNativeHandle()); } -#if !FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern RuntimeModule GetOnDiskAssemblyModule(RuntimeAssembly assembly); - - [System.Security.SecurityCritical] // auto-generated - private ModuleBuilder GetOnDiskAssemblyModuleBuilder() - { - if (m_onDiskAssemblyModuleBuilder == null) - { - Module module = AssemblyBuilder.GetOnDiskAssemblyModule(InternalAssembly.GetNativeHandle()); - ModuleBuilder modBuilder = new ModuleBuilder(this, (InternalModuleBuilder)module); - modBuilder.Init("RefEmit_OnDiskManifestModule", null, 0); - m_onDiskAssemblyModuleBuilder = modBuilder; - } - - return m_onDiskAssemblyModuleBuilder; - } -#endif // FEATURE_CORECLR - #endregion #region Internal Data Members @@ -215,9 +180,6 @@ namespace System.Reflection.Emit // Set to true if the manifest module was returned by code:DefineDynamicModule to the user private bool m_fManifestModuleUsedAsDefinedModule; internal const string MANIFEST_MODULE_NAME = "RefEmit_InMemoryManifestModule"; -#if !FEATURE_CORECLR - private ModuleBuilder m_onDiskAssemblyModuleBuilder; -#endif // !FEATURE_CORECLR #if FEATURE_APPX private bool m_profileAPICheck; @@ -226,27 +188,15 @@ namespace System.Reflection.Emit internal ModuleBuilder GetModuleBuilder(InternalModuleBuilder module) { Contract.Requires(module != null); - Contract.Assert(this.InternalAssembly == module.Assembly); + Debug.Assert(this.InternalAssembly == module.Assembly); lock(SyncRoot) { -#if !FEATURE_CORECLR - foreach (ModuleBuilder modBuilder in m_assemblyData.m_moduleBuilderList) - { - if (modBuilder.InternalModule == module) - return modBuilder; - } - - // m_onDiskAssemblyModuleBuilder is null before Save - if (m_onDiskAssemblyModuleBuilder != null && m_onDiskAssemblyModuleBuilder.InternalModule == module) - return m_onDiskAssemblyModuleBuilder; -#endif // !FEATURE_CORECLR - // in CoreCLR there is only one module in each dynamic assembly, the manifest module if (m_manifestModuleBuilder.InternalModule == module) return m_manifestModuleBuilder; - throw new ArgumentException("module"); + throw new ArgumentException(null, nameof(module)); } } @@ -271,7 +221,6 @@ namespace System.Reflection.Emit return InternalAssembly.GetNativeHandle(); } - [SecurityCritical] internal Version GetVersion() { return InternalAssembly.GetVersion(); @@ -289,7 +238,6 @@ namespace System.Reflection.Emit #endregion #region Constructor - [System.Security.SecurityCritical] // auto-generated internal AssemblyBuilder(AppDomain domain, AssemblyName name, AssemblyBuilderAccess access, @@ -303,13 +251,9 @@ namespace System.Reflection.Emit SecurityContextSource securityContextSource) { if (name == null) - throw new ArgumentNullException("name"); + throw new ArgumentNullException(nameof(name)); if (access != AssemblyBuilderAccess.Run -#if !FEATURE_CORECLR - && access != AssemblyBuilderAccess.Save - && access != AssemblyBuilderAccess.RunAndSave -#endif // !FEATURE_CORECLR #if FEATURE_REFLECTION_ONLY_LOAD && access != AssemblyBuilderAccess.ReflectionOnly #endif // FEATURE_REFLECTION_ONLY_LOAD @@ -318,25 +262,17 @@ namespace System.Reflection.Emit #endif // FEATURE_COLLECTIBLE_TYPES ) { - throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)access), "access"); + throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)access), nameof(access)); } if (securityContextSource < SecurityContextSource.CurrentAppDomain || securityContextSource > SecurityContextSource.CurrentAssembly) { - throw new ArgumentOutOfRangeException("securityContextSource"); + throw new ArgumentOutOfRangeException(nameof(securityContextSource)); } // Clone the name in case the caller modifies it underneath us. name = (AssemblyName)name.Clone(); - -#if !FEATURE_CORECLR - // Set the public key from the key pair if one has been provided. - // (Overwite any public key in the Assembly name, since it's no - // longer valid to have a disparity). - if (name.KeyPair != null) - name.SetPublicKey(name.KeyPair.PublicKey); -#endif // If the caller is trusted they can supply identity // evidence for the new assembly. Otherwise we copy the @@ -350,13 +286,6 @@ namespace System.Reflection.Emit new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand(); #pragma warning restore 618 -#if FEATURE_COLLECTIBLE_TYPES && !FEATURE_CORECLR - // Collectible assemblies require FullTrust. This demand may be removed if we deem the - // feature robust enough to be used directly by untrusted API consumers. - if (access == AssemblyBuilderAccess.RunAndCollect) - new PermissionSet(PermissionState.Unrestricted).Demand(); -#endif // FEATURE_COLLECTIBLE_TYPES && !FEATURE_CORECLR - // Scan the assembly level attributes for any attributes which modify how we create the // assembly. Currently, we look for any attribute which modifies the security transparency // of the assembly. @@ -379,41 +308,10 @@ namespace System.Reflection.Emit } else if (attribute.m_con.DeclaringType == typeof(SecurityCriticalAttribute)) { -#if !FEATURE_CORECLR - SecurityCriticalScope scope = SecurityCriticalScope.Everything; - if (attribute.m_constructorArgs != null && - attribute.m_constructorArgs.Length == 1 && - attribute.m_constructorArgs[0] is SecurityCriticalScope) - { - scope = (SecurityCriticalScope)attribute.m_constructorArgs[0]; - } - - assemblyFlags |= DynamicAssemblyFlags.Critical; - if (scope == SecurityCriticalScope.Everything) -#endif // !FEATURE_CORECLR { assemblyFlags |= DynamicAssemblyFlags.AllCritical; } } -#if !FEATURE_CORECLR - else if (attribute.m_con.DeclaringType == typeof(SecurityRulesAttribute)) - { - securityRulesBlob = new byte[attribute.m_blob.Length]; - Buffer.BlockCopy(attribute.m_blob, 0, securityRulesBlob, 0, securityRulesBlob.Length); - } - else if (attribute.m_con.DeclaringType == typeof(SecurityTreatAsSafeAttribute)) - { - assemblyFlags |= DynamicAssemblyFlags.TreatAsSafe; - } -#endif // !FEATURE_CORECLR -#if FEATURE_APTCA - else if (attribute.m_con.DeclaringType == typeof(AllowPartiallyTrustedCallersAttribute)) - { - assemblyFlags |= DynamicAssemblyFlags.Aptca; - aptcaBlob = new byte[attribute.m_blob.Length]; - Buffer.BlockCopy(attribute.m_blob, 0, aptcaBlob, 0, aptcaBlob.Length); - } -#endif // FEATURE_APTCA } #pragma warning restore 618 } @@ -458,7 +356,6 @@ namespace System.Reflection.Emit } } - [System.Security.SecurityCritical] // auto-generated private void InitManifestModule() { InternalModuleBuilder modBuilder = (InternalModuleBuilder)nGetInMemoryAssemblyModule(); @@ -487,7 +384,6 @@ namespace System.Reflection.Emit * to have a strong name and a hash will be computed when the assembly * is saved. **********************************************/ - [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public static AssemblyBuilder DefineDynamicAssembly( AssemblyName name, @@ -500,7 +396,6 @@ namespace System.Reflection.Emit null, null, null, null, ref stackMark, null, SecurityContextSource.CurrentAssembly); } - [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public static AssemblyBuilder DefineDynamicAssembly( AssemblyName name, @@ -518,7 +413,6 @@ namespace System.Reflection.Emit } - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern Assembly nCreateDynamicAssembly(AppDomain domain, AssemblyName name, @@ -535,7 +429,6 @@ namespace System.Reflection.Emit private class AssemblyBuilderLock { } - [System.Security.SecurityCritical] // auto-generated internal static AssemblyBuilder InternalDefineDynamicAssembly( AssemblyName name, AssemblyBuilderAccess access, @@ -548,13 +441,6 @@ namespace System.Reflection.Emit IEnumerable<CustomAttributeBuilder> unsafeAssemblyAttributes, SecurityContextSource securityContextSource) { -#if FEATURE_CAS_POLICY - if (evidence != null && !AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit")); - } -#endif // FEATURE_CAS_POLICY - lock (typeof(AssemblyBuilderLock)) { // we can only create dynamic assemblies in the current domain @@ -581,7 +467,6 @@ namespace System.Reflection.Emit * a transient module. * **********************************************/ - [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public ModuleBuilder DefineDynamicModule( String name) @@ -592,7 +477,6 @@ namespace System.Reflection.Emit return DefineDynamicModuleInternal(name, false, ref stackMark); } - [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public ModuleBuilder DefineDynamicModule( String name, @@ -604,7 +488,6 @@ namespace System.Reflection.Emit return DefineDynamicModuleInternal( name, emitSymbolInfo, ref stackMark ); } - [System.Security.SecurityCritical] // auto-generated private ModuleBuilder DefineDynamicModuleInternal( String name, bool emitSymbolInfo, // specify if emit symbol info or not @@ -616,115 +499,38 @@ namespace System.Reflection.Emit } } - [System.Security.SecurityCritical] // auto-generated private ModuleBuilder DefineDynamicModuleInternalNoLock( String name, bool emitSymbolInfo, // specify if emit symbol info or not ref StackCrawlMark stackMark) { if (name == null) - throw new ArgumentNullException("name"); + throw new ArgumentNullException(nameof(name)); if (name.Length == 0) - throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name"); + throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name)); if (name[0] == '\0') - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidName"), "name"); + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidName"), nameof(name)); Contract.Ensures(Contract.Result<ModuleBuilder>() != null); Contract.EndContractBlock(); BCLDebug.Log("DYNIL", "## DYNIL LOGGING: AssemblyBuilder.DefineDynamicModule( " + name + " )"); - Contract.Assert(m_assemblyData != null, "m_assemblyData is null in DefineDynamicModuleInternal"); + Debug.Assert(m_assemblyData != null, "m_assemblyData is null in DefineDynamicModuleInternal"); ModuleBuilder dynModule; ISymbolWriter writer = null; IntPtr pInternalSymWriter = new IntPtr(); - // create the dynamic module - -#if FEATURE_MULTIMODULE_ASSEMBLIES - -#if FEATURE_CORECLR -#error FEATURE_MULTIMODULE_ASSEMBLIES should always go with !FEATURE_CORECLR -#endif //FEATURE_CORECLR - - m_assemblyData.CheckNameConflict(name); - - if (m_fManifestModuleUsedAsDefinedModule == true) - { // We need to define a new module - int tkFile; - InternalModuleBuilder internalDynModule = (InternalModuleBuilder)DefineDynamicModule( - InternalAssembly, - emitSymbolInfo, - name, - name, - ref stackMark, - ref pInternalSymWriter, - true /*fIsTransient*/, - out tkFile); - dynModule = new ModuleBuilder(this, internalDynModule); - - // initialize the dynamic module's managed side information - dynModule.Init(name, null, tkFile); - } - else - { // We will reuse the manifest module - m_manifestModuleBuilder.ModifyModuleName(name); - dynModule = m_manifestModuleBuilder; - - if (emitSymbolInfo) - { - pInternalSymWriter = ModuleBuilder.nCreateISymWriterForDynamicModule(dynModule.InternalModule, name); - } - } - -#else // FEATURE_MULTIMODULE_ASSEMBLIES - // Without FEATURE_MULTIMODULE_ASSEMBLIES only one ModuleBuilder per AssemblyBuilder can be created + // create the dynamic module- only one ModuleBuilder per AssemblyBuilder can be created if (m_fManifestModuleUsedAsDefinedModule == true) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NoMultiModuleAssembly")); // Init(...) has already been called on m_manifestModuleBuilder in InitManifestModule() dynModule = m_manifestModuleBuilder; -#endif // FEATURE_MULTIMODULE_ASSEMBLIES // Create the symbol writer if (emitSymbolInfo) { -#if FEATURE_MULTIMODULE_ASSEMBLIES && !FEATURE_CORECLR - // this is the code path for the desktop runtime - - // create the default SymWriter - Assembly assem = LoadISymWrapper(); - Type symWriter = assem.GetType("System.Diagnostics.SymbolStore.SymWriter", true, false); - if (symWriter != null && !symWriter.IsVisible) - symWriter = null; - - if (symWriter == null) - { - // cannot find SymWriter - throw TypeLoadException since we couldnt find the type. - throw new TypeLoadException(Environment.GetResourceString(ResId.MissingType, "SymWriter")); - } - - new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand(); - - try - { - (new PermissionSet(PermissionState.Unrestricted)).Assert(); - writer = (ISymbolWriter)Activator.CreateInstance(symWriter); - - // Set the underlying writer for the managed writer - // that we're using. Note that this function requires - // unmanaged code access. - writer.SetUnderlyingWriter(pInternalSymWriter); - } - finally - { - CodeAccessPermission.RevertAssert(); - } -#endif // FEATURE_MULTIMODULE_ASSEMBLIES && !FEATURE_CORECLR - -#if !FEATURE_MULTIMODULE_ASSEMBLIES && FEATURE_CORECLR - // this is the code path for CoreCLR - writer = SymWrapperCore.SymWriter.CreateSymWriter(); // Set the underlying writer for the managed writer // that we're using. Note that this function requires @@ -741,7 +547,6 @@ namespace System.Reflection.Emit // In Telesto, we took the SetUnderlyingWriter method private as it's a very rickety method. // This might someday be a good move for the desktop CLR too. ((SymWrapperCore.SymWriter)writer).InternalSetUnderlyingWriter(pInternalSymWriter); -#endif // !FEATURE_MULTIMODULE_ASSEMBLIES && FEATURE_CORECLR } // Creating the symbol writer dynModule.SetSymWriter(writer); @@ -754,174 +559,6 @@ namespace System.Reflection.Emit return dynModule; } // DefineDynamicModuleInternalNoLock - -#if !FEATURE_CORECLR - // All dynamic modules in SilverLight are transient so we removed this overload of DefineDynamicModule - // Note that it is assumed that !FEATURE_CORECLR always goes with FEATURE_MULTIMODULE_ASSEMBLIES - // If we ever will build a non coreclr version of the runtime without FEATURE_MULTIMODULE_ASSEMBLIES - // we will need to make the same changes here as the ones we made in the transient overload - - /********************************************** - * - * Defines a named dynamic module. It is an error to define multiple - * modules within an Assembly with the same name. No symbol information - * will be emitted. - * - **********************************************/ - [System.Security.SecuritySafeCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable - public ModuleBuilder DefineDynamicModule( - String name, - String fileName) - { - Contract.Ensures(Contract.Result<ModuleBuilder>() != null); - - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - - // delegate to the next DefineDynamicModule - return DefineDynamicModuleInternal(name, fileName, false, ref stackMark); - } - - /********************************************** - * - * Emit symbol information if emitSymbolInfo is true using the - * default symbol writer interface. - * An exception will be thrown if the assembly is transient. - * - **********************************************/ - [System.Security.SecuritySafeCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable - public ModuleBuilder DefineDynamicModule( - String name, // module name - String fileName, // module file name - bool emitSymbolInfo) // specify if emit symbol info or not - { - Contract.Ensures(Contract.Result<ModuleBuilder>() != null); - - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - return DefineDynamicModuleInternal(name, fileName, emitSymbolInfo, ref stackMark); - } - - [System.Security.SecurityCritical] // auto-generated - private ModuleBuilder DefineDynamicModuleInternal( - String name, // module name - String fileName, // module file name - bool emitSymbolInfo, // specify if emit symbol info or not - ref StackCrawlMark stackMark) // stack crawl mark used to find caller - { - lock(SyncRoot) - { - return DefineDynamicModuleInternalNoLock(name, fileName, emitSymbolInfo, ref stackMark); - } - } - - // "name" will be used for: - // 1. The Name field in the Module table. - // 2. ModuleBuilder.GetModule(string). - // "fileName" will be used for: - // 1. The name field in the ModuleRef table when this module is being referenced by - // another module in the same assembly. - // 2. .file record in the in memory assembly manifest when the module is created in memory - // 3. .file record in the on disk assembly manifest when the assembly is saved to disk - // 4. The file name of the saved module. - [System.Security.SecurityCritical] // auto-generated - private ModuleBuilder DefineDynamicModuleInternalNoLock( - String name, // module name - String fileName, // module file name - bool emitSymbolInfo, // specify if emit symbol info or not - ref StackCrawlMark stackMark) // stack crawl mark used to find caller - { - if (name == null) - throw new ArgumentNullException("name"); - if (name.Length == 0) - throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name"); - if (name[0] == '\0') - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidName"), "name"); - - if (fileName == null) - throw new ArgumentNullException("fileName"); - if (fileName.Length == 0) - throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "fileName"); - if (!String.Equals(fileName, Path.GetFileName(fileName))) - throw new ArgumentException(Environment.GetResourceString("Argument_NotSimpleFileName"), "fileName"); - Contract.Ensures(Contract.Result<ModuleBuilder>() != null); - Contract.EndContractBlock(); - - BCLDebug.Log("DYNIL", "## DYNIL LOGGING: AssemblyBuilder.DefineDynamicModule( " + name + ", " + fileName + ", " + emitSymbolInfo + " )"); - if (m_assemblyData.m_access == AssemblyBuilderAccess.Run) - { - // Error! You cannot define a persistable module within a transient data. - throw new NotSupportedException(Environment.GetResourceString("Argument_BadPersistableModuleInTransientAssembly")); - } - - if (m_assemblyData.m_isSaved == true) - { - // assembly has been saved before! - throw new InvalidOperationException(Environment.GetResourceString( - "InvalidOperation_CannotAlterAssembly")); - } - - ModuleBuilder dynModule; - ISymbolWriter writer = null; - IntPtr pInternalSymWriter = new IntPtr(); - - // create the dynamic module - - m_assemblyData.CheckNameConflict(name); - m_assemblyData.CheckFileNameConflict(fileName); - - int tkFile; - InternalModuleBuilder internalDynModule = (InternalModuleBuilder)DefineDynamicModule( - InternalAssembly, - emitSymbolInfo, - name, - fileName, - ref stackMark, - ref pInternalSymWriter, - false /*fIsTransient*/, - out tkFile); - dynModule = new ModuleBuilder(this, internalDynModule); - - // initialize the dynamic module's managed side information - dynModule.Init(name, fileName, tkFile); - - // Create the symbol writer - if (emitSymbolInfo) - { - // create the default SymWriter - Assembly assem = LoadISymWrapper(); - Type symWriter = assem.GetType("System.Diagnostics.SymbolStore.SymWriter", true, false); - if (symWriter != null && !symWriter.IsVisible) - symWriter = null; - - if (symWriter == null) - { - // cannot find SymWriter - throw TypeLoadException since we couldnt find the type. - throw new TypeLoadException(Environment.GetResourceString("MissingType", "SymWriter")); - } - try - { - (new PermissionSet(PermissionState.Unrestricted)).Assert(); - writer = (ISymbolWriter)Activator.CreateInstance(symWriter); - - // Set the underlying writer for the managed writer - // that we're using. Note that this function requires - // unmanaged code access. - writer.SetUnderlyingWriter(pInternalSymWriter); - } - finally - { - CodeAccessPermission.RevertAssert(); - } - } - - dynModule.SetSymWriter(writer); - - m_assemblyData.AddModule(dynModule); - - return dynModule; - } // DefineDynamicModuleInternalNoLock -#endif // !FEATURE_CORECLR #endregion private Assembly LoadISymWrapper() @@ -970,170 +607,6 @@ namespace System.Reflection.Emit } } -#if !FEATURE_CORECLR - /********************************************** - * - * Define stand alone managed resource for Assembly - * - **********************************************/ - public IResourceWriter DefineResource( - String name, - String description, - String fileName) - { - return DefineResource(name, description, fileName, ResourceAttributes.Public); - } - - /********************************************** - * - * Define stand alone managed resource for Assembly - * - **********************************************/ - public IResourceWriter DefineResource( - String name, - String description, - String fileName, - ResourceAttributes attribute) - { - lock(SyncRoot) - { - return DefineResourceNoLock(name, description, fileName, attribute); - } - } - - private IResourceWriter DefineResourceNoLock( - String name, - String description, - String fileName, - ResourceAttributes attribute) - { - if (name == null) - throw new ArgumentNullException("name"); - if (name.Length == 0) - throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), name); - if (fileName == null) - throw new ArgumentNullException("fileName"); - if (fileName.Length == 0) - throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "fileName"); - if (!String.Equals(fileName, Path.GetFileName(fileName))) - throw new ArgumentException(Environment.GetResourceString("Argument_NotSimpleFileName"), "fileName"); - Contract.EndContractBlock(); - - BCLDebug.Log("DYNIL", "## DYNIL LOGGING: AssemblyBuilder.DefineResource( " + name + ", " + fileName + ")"); - - m_assemblyData.CheckResNameConflict(name); - m_assemblyData.CheckFileNameConflict(fileName); - - ResourceWriter resWriter; - String fullFileName; - - if (m_assemblyData.m_strDir == null) - { - // If assembly directory is null, use current directory - fullFileName = Path.Combine(Directory.GetCurrentDirectory(), fileName); - resWriter = new ResourceWriter(fullFileName); - } - else - { - // Form the full path given the directory provided by user - fullFileName = Path.Combine(m_assemblyData.m_strDir, fileName); - resWriter = new ResourceWriter(fullFileName); - } - // get the full path - fullFileName = Path.GetFullPath(fullFileName); - - // retrieve just the file name - fileName = Path.GetFileName(fullFileName); - - m_assemblyData.AddResWriter( new ResWriterData( resWriter, null, name, fileName, fullFileName, attribute) ); - return resWriter; - } - -#endif // !FEATURE_CORECLR - - /********************************************** - * - * Add an existing resource file to the Assembly - * - **********************************************/ - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif - public void AddResourceFile( - String name, - String fileName) - { - AddResourceFile(name, fileName, ResourceAttributes.Public); - } - - /********************************************** - * - * Add an existing resource file to the Assembly - * - **********************************************/ - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif - public void AddResourceFile( - String name, - String fileName, - ResourceAttributes attribute) - { - lock(SyncRoot) - { - AddResourceFileNoLock(name, fileName, attribute); - } - } - - [System.Security.SecuritySafeCritical] - private void AddResourceFileNoLock( - String name, - String fileName, - ResourceAttributes attribute) - { - if (name == null) - throw new ArgumentNullException("name"); - if (name.Length == 0) - throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), name); - if (fileName == null) - throw new ArgumentNullException("fileName"); - if (fileName.Length == 0) - throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), fileName); - if (!String.Equals(fileName, Path.GetFileName(fileName))) - throw new ArgumentException(Environment.GetResourceString("Argument_NotSimpleFileName"), "fileName"); - Contract.EndContractBlock(); - - BCLDebug.Log("DYNIL", "## DYNIL LOGGING: AssemblyBuilder.AddResourceFile( " + name + ", " + fileName + ")"); - - m_assemblyData.CheckResNameConflict(name); - m_assemblyData.CheckFileNameConflict(fileName); - - String fullFileName; - - if (m_assemblyData.m_strDir == null) - { - // If assembly directory is null, use current directory - fullFileName = Path.Combine(Directory.GetCurrentDirectory(), fileName); - } - else - { - // Form the full path given the directory provided by user - fullFileName = Path.Combine(m_assemblyData.m_strDir, fileName); - } - - // get the full path - fullFileName = Path.UnsafeGetFullPath(fullFileName); - - // retrieve just the file name - fileName = Path.GetFileName(fullFileName); - - if (File.UnsafeExists(fullFileName) == false) - throw new FileNotFoundException(Environment.GetResourceString( - "IO.FileNotFound_FileName", - fileName), fileName); - m_assemblyData.AddResWriter( new ResWriterData( null, null, name, fileName, fullFileName, attribute) ); - } - #region object overrides public override bool Equals(object obj) { @@ -1172,17 +645,11 @@ namespace System.Reflection.Emit return InternalAssembly.GetManifestResourceNames(); } - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif public override FileStream GetFile(String name) { return InternalAssembly.GetFile(name); } - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif public override FileStream[] GetFiles(bool getResourceModules) { return InternalAssembly.GetFiles(getResourceModules); @@ -1205,9 +672,6 @@ namespace System.Reflection.Emit public override String Location { - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif get { return InternalAssembly.Location; @@ -1224,9 +688,6 @@ namespace System.Reflection.Emit public override String CodeBase { - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif get { return InternalAssembly.CodeBase; @@ -1249,9 +710,6 @@ namespace System.Reflection.Emit return InternalAssembly.GetExportedTypes(); } - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif public override AssemblyName GetName(bool copiedName) { return InternalAssembly.GetName(copiedName); @@ -1270,33 +728,6 @@ namespace System.Reflection.Emit return InternalAssembly.GetType(name, throwOnError, ignoreCase); } -#if FEATURE_CAS_POLICY - public override Evidence Evidence - { - get - { - return InternalAssembly.Evidence; - } - } - - public override PermissionSet PermissionSet - { - [SecurityCritical] - get - { - return InternalAssembly.PermissionSet; - } - } - - public override SecurityRuleSet SecurityRuleSet - { - get - { - return InternalAssembly.SecurityRuleSet; - } - } -#endif // FEATURE_CAS_POLICY - public override Module ManifestModule { get @@ -1371,143 +802,8 @@ namespace System.Reflection.Emit } } #endregion - - - /********************************************** - * - * Add an unmanaged Version resource to the - * assembly - * - **********************************************/ - public void DefineVersionInfoResource( - String product, - String productVersion, - String company, - String copyright, - String trademark) - { - lock(SyncRoot) - { - DefineVersionInfoResourceNoLock( - product, - productVersion, - company, - copyright, - trademark); - } - } - - private void DefineVersionInfoResourceNoLock( - String product, - String productVersion, - String company, - String copyright, - String trademark) - { - if (m_assemblyData.m_strResourceFileName != null || - m_assemblyData.m_resourceBytes != null || - m_assemblyData.m_nativeVersion != null) - throw new ArgumentException(Environment.GetResourceString("Argument_NativeResourceAlreadyDefined")); - - m_assemblyData.m_nativeVersion = new NativeVersionInfo(); - - m_assemblyData.m_nativeVersion.m_strCopyright = copyright; - m_assemblyData.m_nativeVersion.m_strTrademark = trademark; - m_assemblyData.m_nativeVersion.m_strCompany = company; - m_assemblyData.m_nativeVersion.m_strProduct = product; - m_assemblyData.m_nativeVersion.m_strProductVersion = productVersion; - m_assemblyData.m_hasUnmanagedVersionInfo = true; - m_assemblyData.m_OverrideUnmanagedVersionInfo = true; - - } - - public void DefineVersionInfoResource() - { - lock(SyncRoot) - { - DefineVersionInfoResourceNoLock(); - } - } - - private void DefineVersionInfoResourceNoLock() - { - if (m_assemblyData.m_strResourceFileName != null || - m_assemblyData.m_resourceBytes != null || - m_assemblyData.m_nativeVersion != null) - throw new ArgumentException(Environment.GetResourceString("Argument_NativeResourceAlreadyDefined")); - - m_assemblyData.m_hasUnmanagedVersionInfo = true; - m_assemblyData.m_nativeVersion = new NativeVersionInfo(); - } - - public void DefineUnmanagedResource(Byte[] resource) - { - if (resource == null) - throw new ArgumentNullException("resource"); - Contract.EndContractBlock(); - - lock(SyncRoot) - { - DefineUnmanagedResourceNoLock(resource); - } - } - private void DefineUnmanagedResourceNoLock(Byte[] resource) - { - if (m_assemblyData.m_strResourceFileName != null || - m_assemblyData.m_resourceBytes != null || - m_assemblyData.m_nativeVersion != null) - throw new ArgumentException(Environment.GetResourceString("Argument_NativeResourceAlreadyDefined")); - - m_assemblyData.m_resourceBytes = new byte[resource.Length]; - Buffer.BlockCopy(resource, 0, m_assemblyData.m_resourceBytes, 0, resource.Length); - } - [System.Security.SecuritySafeCritical] // auto-generated - public void DefineUnmanagedResource(String resourceFileName) - { - if (resourceFileName == null) - throw new ArgumentNullException("resourceFileName"); - Contract.EndContractBlock(); - - lock(SyncRoot) - { - DefineUnmanagedResourceNoLock(resourceFileName); - } - } - - [System.Security.SecurityCritical] // auto-generated - private void DefineUnmanagedResourceNoLock(String resourceFileName) - { - if (m_assemblyData.m_strResourceFileName != null || - m_assemblyData.m_resourceBytes != null || - m_assemblyData.m_nativeVersion != null) - throw new ArgumentException(Environment.GetResourceString("Argument_NativeResourceAlreadyDefined")); - - // Check caller has the right to read the file. - string strFullFileName; - if (m_assemblyData.m_strDir == null) - { - // If assembly directory is null, use current directory - strFullFileName = Path.Combine(Directory.GetCurrentDirectory(), resourceFileName); - } - else - { - // Form the full path given the directory provided by user - strFullFileName = Path.Combine(m_assemblyData.m_strDir, resourceFileName); - } - strFullFileName = Path.GetFullPath(resourceFileName); - new FileIOPermission(FileIOPermissionAccess.Read, strFullFileName).Demand(); - - if (File.Exists(strFullFileName) == false) - throw new FileNotFoundException(Environment.GetResourceString( - "IO.FileNotFound_FileName", - resourceFileName), resourceFileName); - m_assemblyData.m_strResourceFileName = strFullFileName; - } - - - /********************************************** * * return a dynamic module with the specified name. @@ -1526,9 +822,9 @@ namespace System.Reflection.Emit String name) // the name of module for the look up { if (name == null) - throw new ArgumentNullException("name"); + throw new ArgumentNullException(nameof(name)); if (name.Length == 0) - throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name"); + throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name)); Contract.EndContractBlock(); BCLDebug.Log("DYNIL", "## DYNIL LOGGING: AssemblyBuilder.GetDynamicModule( " + name + " )"); @@ -1550,17 +846,11 @@ namespace System.Reflection.Emit * an exe. * **********************************************/ - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif public void SetEntryPoint( MethodInfo entryMethod) { SetEntryPoint(entryMethod, PEFileKinds.ConsoleApplication); } - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif public void SetEntryPoint( MethodInfo entryMethod, // entry method for the assembly. We use this to determine the entry module PEFileKinds fileKind) // file kind for the assembly. @@ -1577,7 +867,7 @@ namespace System.Reflection.Emit { if (entryMethod == null) - throw new ArgumentNullException("entryMethod"); + throw new ArgumentNullException(nameof(entryMethod)); Contract.EndContractBlock(); BCLDebug.Log("DYNIL", "## DYNIL LOGGING: AssemblyBuilder.SetEntryPoint"); @@ -1588,36 +878,19 @@ namespace System.Reflection.Emit m_assemblyData.m_entryPointMethod = entryMethod; m_assemblyData.m_peFileKind = fileKind; - -#if !FEATURE_CORECLR - // Setting the entry point - ModuleBuilder tmpMB = tmpModule as ModuleBuilder; - if (tmpMB != null) - m_assemblyData.m_entryPointModule = tmpMB; - else - m_assemblyData.m_entryPointModule = GetModuleBuilder((InternalModuleBuilder)tmpModule); - - MethodToken entryMethodToken = m_assemblyData.m_entryPointModule.GetMethodToken(entryMethod); - m_assemblyData.m_entryPointModule.SetEntryPoint(entryMethodToken); -#endif //!FEATURE_CORECLR } /********************************************** * Use this function if client decides to form the custom attribute blob themselves **********************************************/ - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #else - [System.Security.SecuritySafeCritical] - #endif [System.Runtime.InteropServices.ComVisible(true)] public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { if (con == null) - throw new ArgumentNullException("con"); + throw new ArgumentNullException(nameof(con)); if (binaryAttribute == null) - throw new ArgumentNullException("binaryAttribute"); + throw new ArgumentNullException(nameof(binaryAttribute)); Contract.EndContractBlock(); lock(SyncRoot) @@ -1626,7 +899,6 @@ namespace System.Reflection.Emit } } - [System.Security.SecurityCritical] // auto-generated private void SetCustomAttributeNoLock(ConstructorInfo con, byte[] binaryAttribute) { TypeBuilder.DefineCustomAttribute( @@ -1648,12 +920,11 @@ namespace System.Reflection.Emit /********************************************** * Use this function if client wishes to build CustomAttribute using CustomAttributeBuilder **********************************************/ - [System.Security.SecuritySafeCritical] // auto-generated public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { if (customBuilder == null) { - throw new ArgumentNullException("customBuilder"); + throw new ArgumentNullException(nameof(customBuilder)); } Contract.EndContractBlock(); @@ -1663,7 +934,6 @@ namespace System.Reflection.Emit } } - [System.Security.SecurityCritical] // auto-generated private void SetCustomAttributeNoLock(CustomAttributeBuilder customBuilder) { customBuilder.CreateCustomAttribute( @@ -1693,7 +963,6 @@ namespace System.Reflection.Emit Save(assemblyFileName, System.Reflection.PortableExecutableKinds.ILOnly, System.Reflection.ImageFileMachine.I386); } - [System.Security.SecuritySafeCritical] // auto-generated public void Save(String assemblyFileName, PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine) { @@ -1703,358 +972,15 @@ namespace System.Reflection.Emit } } -#if FEATURE_CORECLR private void SaveNoLock(String assemblyFileName, PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine) { - // AssemblyBuilderAccess.Save can never be set with FEATURE_CORECLR + // AssemblyBuilderAccess.Save can never be set in CoreCLR throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CantSaveTransientAssembly")); } -#else // FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - private void SaveNoLock(String assemblyFileName, - PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine) - { - if (assemblyFileName == null) - throw new ArgumentNullException("assemblyFileName"); - if (assemblyFileName.Length == 0) - throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "assemblyFileName"); - if (!String.Equals(assemblyFileName, Path.GetFileName(assemblyFileName))) - throw new ArgumentException(Environment.GetResourceString("Argument_NotSimpleFileName"), "assemblyFileName"); - Contract.EndContractBlock(); - - int i; - int size; - Type type; - TypeBuilder typeBuilder; - ModuleBuilder modBuilder; - String strModFileName; - ModuleBuilder assemblyModule; - ResWriterData tempRes; - int[] tkAttrs = null; - int[] tkAttrs2 = null; - ModuleBuilder onDiskAssemblyModule; - BCLDebug.Log("DYNIL","## DYNIL LOGGING: AssemblyBuilder.Save( " + assemblyFileName + " )"); - - String tmpVersionFile = null; - - try - { - if (m_assemblyData.m_iCABuilder != 0) - tkAttrs = new int[m_assemblyData.m_iCABuilder]; - if ( m_assemblyData.m_iCAs != 0) - tkAttrs2 = new int[m_assemblyData.m_iCAs]; - - if (m_assemblyData.m_isSaved == true) - { - // assembly has been saved before! - throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_AssemblyHasBeenSaved, - InternalAssembly.GetSimpleName())); - } - - if ((m_assemblyData.m_access & AssemblyBuilderAccess.Save) != AssemblyBuilderAccess.Save) - { - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CantSaveTransientAssembly")); - } - - // Check if assembly info is supposed to be stored with one of the module files. - assemblyModule = m_assemblyData.FindModuleWithFileName(assemblyFileName); - - if (assemblyModule != null) - { - m_onDiskAssemblyModuleBuilder = assemblyModule; - - // In memory this module is not the manifest module and has a valid file token - // On disk it will be the manifest module so lets clean the file token - // We should not retrieve FileToken after the assembly has been saved - // If that is absolutely necessary, we need two separate fields on ModuleBuilderData: - // the in memory file token and the on disk file token. - assemblyModule.m_moduleData.FileToken = 0; - } - else - { // If assembly is to be stored alone, then no file name should conflict with it. - // This check will ensure resource file names are different assembly file name. - m_assemblyData.CheckFileNameConflict(assemblyFileName); - } - - if (m_assemblyData.m_strDir == null) - { - // set it to current directory - m_assemblyData.m_strDir = Directory.GetCurrentDirectory(); - } - else if (Directory.Exists(m_assemblyData.m_strDir) == false) - { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectory", - m_assemblyData.m_strDir)); - } - - // after this point, assemblyFileName is the full path name. - assemblyFileName = Path.Combine(m_assemblyData.m_strDir, assemblyFileName); - assemblyFileName = Path.GetFullPath(assemblyFileName); - - // Check caller has the right to create the assembly file itself. - new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Append, assemblyFileName).Demand(); - - // 1. setup/create the IMetaDataAssemblyEmit for the on disk version - if (assemblyModule != null) - { - // prepare saving CAs on assembly def. We need to introduce the MemberRef for - // the CA's type first of all. This is for the case the we have embedded manifest. - // We need to introduce these MRs before we call PreSave where we will snap - // into a ondisk metadata. If we do it after this, the ondisk metadata will - // not contain the proper MRs. - // - for (i=0; i < m_assemblyData.m_iCABuilder; i++) - { - tkAttrs[i] = m_assemblyData.m_CABuilders[i].PrepareCreateCustomAttributeToDisk( - assemblyModule); - } - for (i=0; i < m_assemblyData.m_iCAs; i++) - { - tkAttrs2[i] = assemblyModule.InternalGetConstructorToken(m_assemblyData.m_CACons[i], true).Token; - } - assemblyModule.PreSave(assemblyFileName, portableExecutableKind, imageFileMachine); - } - - RuntimeModule runtimeAssemblyModule = (assemblyModule != null) ? assemblyModule.ModuleHandle.GetRuntimeModule() : null; - PrepareForSavingManifestToDisk(GetNativeHandle(), runtimeAssemblyModule); - - // This function will return the embedded manifest module, an already exposed ModuleBuilder - // created by user, or make the stand alone manifest module exposed through managed code. - // - onDiskAssemblyModule = GetOnDiskAssemblyModuleBuilder(); - - // Set any native resources on the OnDiskAssemblyModule. - if (m_assemblyData.m_strResourceFileName != null) - onDiskAssemblyModule.DefineUnmanagedResourceFileInternalNoLock(m_assemblyData.m_strResourceFileName); - else if (m_assemblyData.m_resourceBytes != null) - onDiskAssemblyModule.DefineUnmanagedResourceInternalNoLock(m_assemblyData.m_resourceBytes); - else if (m_assemblyData.m_hasUnmanagedVersionInfo == true) - { - // calculate unmanaged version info from assembly's custom attributes - m_assemblyData.FillUnmanagedVersionInfo(); - - String strFileVersion = m_assemblyData.m_nativeVersion.m_strFileVersion; - if (strFileVersion == null) - strFileVersion = GetVersion().ToString(); - - // Create the file. - CreateVersionInfoResource( - assemblyFileName, - m_assemblyData.m_nativeVersion.m_strTitle, // title - null, // Icon filename - m_assemblyData.m_nativeVersion.m_strDescription, // description - m_assemblyData.m_nativeVersion.m_strCopyright, - m_assemblyData.m_nativeVersion.m_strTrademark, - m_assemblyData.m_nativeVersion.m_strCompany, - m_assemblyData.m_nativeVersion.m_strProduct, - m_assemblyData.m_nativeVersion.m_strProductVersion, - strFileVersion, - m_assemblyData.m_nativeVersion.m_lcid, - m_assemblyData.m_peFileKind == PEFileKinds.Dll, - JitHelpers.GetStringHandleOnStack(ref tmpVersionFile)); - - onDiskAssemblyModule.DefineUnmanagedResourceFileInternalNoLock(tmpVersionFile); - } - - if (assemblyModule == null) - { - - // This is for introducing the MRs for CA's type. This case is for stand alone - // manifest. We need to wait till PrepareForSavingManifestToDisk is called. - // That will trigger the creation of the on-disk stand alone manifest module. - // - for (i=0; i < m_assemblyData.m_iCABuilder; i++) - { - tkAttrs[i] = m_assemblyData.m_CABuilders[i].PrepareCreateCustomAttributeToDisk( - onDiskAssemblyModule); - } - for (i=0; i < m_assemblyData.m_iCAs; i++) - { - tkAttrs2[i] = onDiskAssemblyModule.InternalGetConstructorToken(m_assemblyData.m_CACons[i], true).Token; - } - } - - // 2. save all of the persistable modules contained by this AssemblyBuilder except the module that is going to contain - // Assembly information - // - // 3. create the file list in the manifest and track the file token. If it is embedded assembly, - // the assembly file should not be on the file list. - // - size = m_assemblyData.m_moduleBuilderList.Count; - for (i = 0; i < size; i++) - { - ModuleBuilder mBuilder = (ModuleBuilder) m_assemblyData.m_moduleBuilderList[i]; - if (mBuilder.IsTransient() == false && mBuilder != assemblyModule) - { - strModFileName = mBuilder.m_moduleData.m_strFileName; - if (m_assemblyData.m_strDir != null) - { - strModFileName = Path.Combine(m_assemblyData.m_strDir, strModFileName); - strModFileName = Path.GetFullPath(strModFileName); - } - - // Check caller has the right to create the Module file itself. - new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Append, strModFileName).Demand(); - - mBuilder.m_moduleData.FileToken = AddFile(GetNativeHandle(), mBuilder.m_moduleData.m_strFileName); - mBuilder.PreSave(strModFileName, portableExecutableKind, imageFileMachine); - mBuilder.Save(strModFileName, false, portableExecutableKind, imageFileMachine); - - // Cannot set the hash value when creating the file since the file token - // is needed to created the entries for the embedded resources in the - // module and the resources need to be there before you figure the hash. - SetFileHashValue(GetNativeHandle(), mBuilder.m_moduleData.FileToken, strModFileName); - } - } - - // 4. Add the public ComType - for (i=0; i < m_assemblyData.m_iPublicComTypeCount; i++) - { - type = m_assemblyData.m_publicComTypeList[i]; - // If the type that was added as a Public Com Type was obtained via Reflection, - // it will be a System.RuntimeType, even if it was really, at the same time, - // a TypeBuilder. Unfortunately, you can't get back to the TypeBuilder, so - // this code has to deal with either-or. - if (type is RuntimeType) - { - // If type is a runtime type, it must be a baked TypeBuilder, - // ttype.Module should be an InternalModuleBuilder - - InternalModuleBuilder internalMB = (InternalModuleBuilder)type.Module; - modBuilder = this.GetModuleBuilder(internalMB); - if (modBuilder != assemblyModule) - DefineNestedComType(type, modBuilder.m_moduleData.FileToken, type.MetadataToken); - } - else - { - // Could assert that "type" is a TypeBuilder, but next statement throws if it isn't. - typeBuilder = (TypeBuilder) type; - // If type is a TypeBuilder, type.Module must be a ModuleBuilder. - modBuilder = typeBuilder.GetModuleBuilder(); - if (modBuilder != assemblyModule) - DefineNestedComType(type, modBuilder.m_moduleData.FileToken, typeBuilder.MetadataTokenInternal); - } - } - - // 5. write AssemblyDef's CAs (only if we are not saving directly the manifest module itself) - if (onDiskAssemblyModule != m_manifestModuleBuilder) - { - for (i = 0; i < m_assemblyData.m_iCABuilder; i++) - { - m_assemblyData.m_CABuilders[i].CreateCustomAttribute( - onDiskAssemblyModule, - AssemblyBuilderData.m_tkAssembly, // This is the AssemblyDef token - tkAttrs[i], true); - } - - for (i = 0; i < m_assemblyData.m_iCAs; i++) - { - TypeBuilder.DefineCustomAttribute( - onDiskAssemblyModule, // pass in the in-memory assembly module - AssemblyBuilderData.m_tkAssembly, // This is the AssemblyDef token - tkAttrs2[i], - m_assemblyData.m_CABytes[i], - true, false); - } - } - - // 6. write security permission requests to the manifest. -#pragma warning disable 618 - if (m_assemblyData.m_RequiredPset != null) - AddDeclarativeSecurity(m_assemblyData.m_RequiredPset, SecurityAction.RequestMinimum); - - if (m_assemblyData.m_RefusedPset != null) - AddDeclarativeSecurity(m_assemblyData.m_RefusedPset, SecurityAction.RequestRefuse); - - if (m_assemblyData.m_OptionalPset != null) - AddDeclarativeSecurity(m_assemblyData.m_OptionalPset, SecurityAction.RequestOptional); -#pragma warning restore 618 - - // 7. Save the stand alone managed resources - size = m_assemblyData.m_resWriterList.Count; - for (i = 0; i < size; i++) - { - tempRes = null; - - try - { - tempRes = (ResWriterData)m_assemblyData.m_resWriterList[i]; - - // If the user added an existing resource to the manifest, the - // corresponding ResourceWriter will be null. - if (tempRes.m_resWriter != null) - // Check caller has the right to create the Resource file itself. - new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Append, tempRes.m_strFullFileName).Demand(); - } - finally - { - if (tempRes != null && tempRes.m_resWriter != null) - tempRes.m_resWriter.Close(); - } - - // Add entry to manifest for this stand alone resource - AddStandAloneResource(GetNativeHandle(), tempRes.m_strName, tempRes.m_strFileName, tempRes.m_strFullFileName, (int)tempRes.m_attribute); - } - - // Save now!! - if (assemblyModule == null) - { - onDiskAssemblyModule.DefineNativeResource(portableExecutableKind, imageFileMachine); - - // Stand alone manifest - int entryPoint = (m_assemblyData.m_entryPointModule != null) ? m_assemblyData.m_entryPointModule.m_moduleData.FileToken : 0; - - SaveManifestToDisk(GetNativeHandle(), assemblyFileName, entryPoint, (int)m_assemblyData.m_peFileKind, - (int)portableExecutableKind, (int)imageFileMachine); - } - else - { - // embedded manifest - - // If the module containing the entry point is not the manifest file, we need to - // let the manifest file point to the module which contains the entry point. - // - // - // - // - if (m_assemblyData.m_entryPointModule != null && m_assemblyData.m_entryPointModule != assemblyModule) - assemblyModule.SetEntryPoint(new MethodToken(m_assemblyData.m_entryPointModule.m_moduleData.FileToken)); - assemblyModule.Save(assemblyFileName, true, portableExecutableKind, imageFileMachine); - } - m_assemblyData.m_isSaved = true; - } - finally - { - if (tmpVersionFile != null) - { - // Delete file. - System.IO.File.Delete(tmpVersionFile); - } - } - } -#endif // FEATURE_CORECLR - -#if FEATURE_CAS_POLICY - [System.Security.SecurityCritical] // auto-generated - private void AddDeclarativeSecurity(PermissionSet pset, SecurityAction action) - { - // Translate sets into internal encoding (uses standard binary serialization). - byte[] blob = pset.EncodeXml(); - AddDeclarativeSecurity(GetNativeHandle(), action, blob, blob.Length); - } -#endif // FEATURE_CAS_POLICY - internal bool IsPersistable() { -#if !FEATURE_CORECLR // AssemblyBuilderAccess.Save is never set in CoreCLR - if ((m_assemblyData.m_access & AssemblyBuilderAccess.Save) == AssemblyBuilderAccess.Save) - { - return true; - } - else -#endif // FEATURE_CORECLR { return false; } @@ -2065,7 +991,6 @@ namespace System.Reflection.Emit * Internal helper to walk the nested type hierachy * **********************************************/ - [System.Security.SecurityCritical] // auto-generated private int DefineNestedComType(Type type, int tkResolutionScope, int tkTypeDef) { Type enclosingType = type.DeclaringType; @@ -2080,7 +1005,6 @@ namespace System.Reflection.Emit return AddExportedTypeOnDisk(GetNativeHandle(), type.Name, tkResolutionScope, tkTypeDef, type.Attributes); } - [System.Security.SecurityCritical] // auto-generated internal int DefineExportedTypeInMemory(Type type, int tkResolutionScope, int tkTypeDef) { Type enclosingType = type.DeclaringType; @@ -2107,32 +1031,7 @@ namespace System.Reflection.Emit **********************************************/ private AssemblyBuilder() {} -#if !FEATURE_CORECLR - void _AssemblyBuilder.GetTypeInfoCount(out uint pcTInfo) - { - throw new NotImplementedException(); - } - - void _AssemblyBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) - { - throw new NotImplementedException(); - } - - void _AssemblyBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) - { - throw new NotImplementedException(); - } - - // If you implement this method, make sure to include _AssemblyBuilder.Invoke in VM\DangerousAPIs.h and - // include _AssemblyBuilder in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp. - void _AssemblyBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) - { - throw new NotImplementedException(); - } -#endif - // Create a new module in which to emit code. This module will not contain the manifest. - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] static private extern void DefineDynamicModule(RuntimeAssembly containingAssembly, @@ -2145,7 +1044,6 @@ namespace System.Reflection.Emit bool fIsTransient, out int tkFile); - [System.Security.SecurityCritical] // auto-generated private static Module DefineDynamicModule(RuntimeAssembly containingAssembly, bool emitSymbolInfo, String name, @@ -2171,12 +1069,10 @@ namespace System.Reflection.Emit } // The following functions are native helpers for creating on-disk manifest - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] static private extern void PrepareForSavingManifestToDisk(RuntimeAssembly assembly, RuntimeModule assemblyModule); // module to contain assembly information if assembly is embedded - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] static private extern void SaveManifestToDisk(RuntimeAssembly assembly, @@ -2186,19 +1082,16 @@ namespace System.Reflection.Emit int portableExecutableKind, int ImageFileMachine); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] static private extern int AddFile(RuntimeAssembly assembly, String strFileName); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] static private extern void SetFileHashValue(RuntimeAssembly assembly, int tkFile, String strFullFileName); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] static private extern int AddExportedTypeInMemory(RuntimeAssembly assembly, @@ -2207,7 +1100,6 @@ namespace System.Reflection.Emit int tkTypeDef, TypeAttributes flags); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] static private extern int AddExportedTypeOnDisk(RuntimeAssembly assembly, @@ -2217,7 +1109,6 @@ namespace System.Reflection.Emit TypeAttributes flags); // Add an entry to assembly's manifestResource table for a stand alone resource. - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] static private extern void AddStandAloneResource(RuntimeAssembly assembly, @@ -2226,7 +1117,6 @@ namespace System.Reflection.Emit String strFullFileName, int attribute); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] #pragma warning disable 618 @@ -2234,7 +1124,6 @@ namespace System.Reflection.Emit #pragma warning restore 618 // Functions for defining unmanaged resources. - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] static private extern void CreateVersionInfoResource(String filename, String title, String iconFilename, String description, diff --git a/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderAccess.cs b/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderAccess.cs index 00a961dd89..5c86d8ec87 100644 --- a/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderAccess.cs +++ b/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderAccess.cs @@ -8,17 +8,13 @@ using System; // EE uses these enum values..look for m_dwDynamicAssemblyAccess in Assembly.hpp namespace System.Reflection.Emit -{ +{ [Serializable] [System.Runtime.InteropServices.ComVisible(true)] [Flags] public enum AssemblyBuilderAccess { Run = 1, -#if !FEATURE_CORECLR // these are unsupported - Save = 2, - RunAndSave = Run | Save, -#endif // !FEATURE_CORECLR #if FEATURE_REFLECTION_ONLY_LOAD ReflectionOnly = 6, // 4 | Save, #endif // FEATURE_REFLECTION_ONLY_LOAD diff --git a/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderData.cs b/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderData.cs index f1a38c611b..f0f83e7d2a 100644 --- a/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderData.cs +++ b/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderData.cs @@ -14,11 +14,7 @@ namespace System.Reflection.Emit { using System.Security; using System.Diagnostics; using CultureInfo = System.Globalization.CultureInfo; -#if !FEATURE_CORECLR - using ResourceWriter = System.Resources.ResourceWriter; -#else // FEATURE_CORECLR using IResourceWriter = System.Resources.IResourceWriter; -#endif // !FEATURE_CORECLR using System.IO; using System.Runtime.Versioning; using System.Diagnostics.SymbolStore; @@ -29,7 +25,6 @@ namespace System.Reflection.Emit { // this class cannot be accessed from the EE. internal class AssemblyBuilderData { - [SecurityCritical] internal AssemblyBuilderData( InternalAssemblyBuilder assembly, String strAssemblyName, @@ -120,7 +115,6 @@ namespace System.Reflection.Emit { // If DefineUnmanagedVersionInfo is called, the parameter provided will override // the CA's value. // - [System.Security.SecurityCritical] // auto-generated internal void FillUnmanagedVersionInfo() { // Get the lcid set on the assembly name as default if available @@ -242,7 +236,7 @@ namespace System.Reflection.Emit { } // CultureInfo attribute overrides the lcid from AssemblyName. CultureInfo culture = new CultureInfo(m_CABuilders[i].m_constructorArgs[0].ToString()); -#if FEATURE_USE_LCID +#if FEATURE_USE_LCID m_nativeVersion.m_lcid = culture.LCID; #endif } @@ -469,7 +463,7 @@ namespace System.Reflection.Emit { // hard coding the assembly def token internal const int m_tkAssembly = 0x20000001; - + // Security permission requests internal PermissionSet m_RequiredPset; internal PermissionSet m_OptionalPset; @@ -485,10 +479,6 @@ namespace System.Reflection.Emit { internal MethodInfo m_entryPointMethod; internal Assembly m_ISymWrapperAssembly; -#if !FEATURE_CORECLR - internal ModuleBuilder m_entryPointModule; -#endif //!FEATURE_CORECLR - // For unmanaged resources internal String m_strResourceFileName; internal byte[] m_resourceBytes; @@ -507,7 +497,6 @@ namespace System.Reflection.Emit { **********************************************/ internal class ResWriterData { -#if FEATURE_CORECLR internal ResWriterData( IResourceWriter resWriter, Stream memoryStream, @@ -524,29 +513,8 @@ namespace System.Reflection.Emit { m_nextResWriter = null; m_attribute = attribute; } -#else - internal ResWriterData( - ResourceWriter resWriter, - Stream memoryStream, - String strName, - String strFileName, - String strFullFileName, - ResourceAttributes attribute) - { - m_resWriter = resWriter; - m_memoryStream = memoryStream; - m_strName = strName; - m_strFileName = strFileName; - m_strFullFileName = strFullFileName; - m_nextResWriter = null; - m_attribute = attribute; - } -#endif -#if !FEATURE_CORECLR - internal ResourceWriter m_resWriter; -#else // FEATURE_CORECLR - internal IResourceWriter m_resWriter; -#endif // !FEATURE_CORECLR + + internal IResourceWriter m_resWriter; internal String m_strName; internal String m_strFileName; internal String m_strFullFileName; diff --git a/src/mscorlib/src/System/Reflection/Emit/ComInterfaces.cs b/src/mscorlib/src/System/Reflection/Emit/ComInterfaces.cs index 0d8ce5a8d4..8dba934bde 100644 --- a/src/mscorlib/src/System/Reflection/Emit/ComInterfaces.cs +++ b/src/mscorlib/src/System/Reflection/Emit/ComInterfaces.cs @@ -2,33 +2,15 @@ // 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; -using System.Globalization; -using System.IO; -using System.Reflection; -using System.Runtime.InteropServices; -using System.Runtime.Serialization; -using System.Security.Permissions; -using System.Security.Policy; - namespace System.Runtime.InteropServices { [GuidAttribute("BEBB2505-8B54-3443-AEAD-142A16DD9CC7")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.AssemblyBuilder))] -[System.Runtime.InteropServices.ComVisible(true)] + [System.Runtime.InteropServices.ComVisible(true)] public interface _AssemblyBuilder { -#if !FEATURE_CORECLR - void GetTypeInfoCount(out uint pcTInfo); - - void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); - - void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); - - void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); -#endif } [GuidAttribute("ED3E4384-D7E2-3FA7-8FFD-8940D330519A")] @@ -38,141 +20,69 @@ namespace System.Runtime.InteropServices [System.Runtime.InteropServices.ComVisible(true)] public interface _ConstructorBuilder { -#if !FEATURE_CORECLR - void GetTypeInfoCount(out uint pcTInfo); - - void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); - - void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); - - void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); -#endif } [GuidAttribute("BE9ACCE8-AAFF-3B91-81AE-8211663F5CAD")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.CustomAttributeBuilder))] -[System.Runtime.InteropServices.ComVisible(true)] + [System.Runtime.InteropServices.ComVisible(true)] public interface _CustomAttributeBuilder { -#if !FEATURE_CORECLR - void GetTypeInfoCount(out uint pcTInfo); - - void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); - - void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); - - void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); -#endif } [GuidAttribute("C7BD73DE-9F85-3290-88EE-090B8BDFE2DF")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.EnumBuilder))] -[System.Runtime.InteropServices.ComVisible(true)] + [System.Runtime.InteropServices.ComVisible(true)] public interface _EnumBuilder { -#if !FEATURE_CORECLR - void GetTypeInfoCount(out uint pcTInfo); - - void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); - - void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); - - void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); -#endif } [GuidAttribute("AADABA99-895D-3D65-9760-B1F12621FAE8")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.EventBuilder))] -[System.Runtime.InteropServices.ComVisible(true)] + [System.Runtime.InteropServices.ComVisible(true)] public interface _EventBuilder { -#if !FEATURE_CORECLR - void GetTypeInfoCount(out uint pcTInfo); - - void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); - - void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); - - void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); -#endif } [GuidAttribute("CE1A3BF5-975E-30CC-97C9-1EF70F8F3993")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.FieldBuilder))] -[System.Runtime.InteropServices.ComVisible(true)] + [System.Runtime.InteropServices.ComVisible(true)] public interface _FieldBuilder { -#if !FEATURE_CORECLR - void GetTypeInfoCount(out uint pcTInfo); - - void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); - - void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); - - void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); -#endif } [GuidAttribute("A4924B27-6E3B-37F7-9B83-A4501955E6A7")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.ILGenerator))] -[System.Runtime.InteropServices.ComVisible(true)] + [System.Runtime.InteropServices.ComVisible(true)] public interface _ILGenerator { -#if !FEATURE_CORECLR - void GetTypeInfoCount(out uint pcTInfo); - - void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); - - void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); - - void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); -#endif } [GuidAttribute("4E6350D1-A08B-3DEC-9A3E-C465F9AEEC0C")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.LocalBuilder))] -[System.Runtime.InteropServices.ComVisible(true)] + [System.Runtime.InteropServices.ComVisible(true)] public interface _LocalBuilder { -#if !FEATURE_CORECLR - void GetTypeInfoCount(out uint pcTInfo); - - void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); - - void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); - - void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); -#endif } [GuidAttribute("007D8A14-FDF3-363E-9A0B-FEC0618260A2")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.MethodBuilder))] -[System.Runtime.InteropServices.ComVisible(true)] + [System.Runtime.InteropServices.ComVisible(true)] public interface _MethodBuilder { -#if !FEATURE_CORECLR - void GetTypeInfoCount(out uint pcTInfo); - - void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); - - void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); - - void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); -#endif } #if FEATURE_METHOD_RENTAL @@ -180,18 +90,9 @@ namespace System.Runtime.InteropServices [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.MethodRental))] -[System.Runtime.InteropServices.ComVisible(true)] + [System.Runtime.InteropServices.ComVisible(true)] public interface _MethodRental { -#if !FEATURE_CORECLR - void GetTypeInfoCount(out uint pcTInfo); - - void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); - - void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); - - void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); -#endif } #endif @@ -199,90 +100,44 @@ namespace System.Runtime.InteropServices [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.ModuleBuilder))] -[System.Runtime.InteropServices.ComVisible(true)] + [System.Runtime.InteropServices.ComVisible(true)] public interface _ModuleBuilder { -#if !FEATURE_CORECLR - void GetTypeInfoCount(out uint pcTInfo); - - void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); - - void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); - - void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); -#endif } [GuidAttribute("36329EBA-F97A-3565-BC07-0ED5C6EF19FC")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.ParameterBuilder))] -[System.Runtime.InteropServices.ComVisible(true)] + [System.Runtime.InteropServices.ComVisible(true)] public interface _ParameterBuilder { -#if !FEATURE_CORECLR - void GetTypeInfoCount(out uint pcTInfo); - - void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); - - void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); - - void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); -#endif } [GuidAttribute("15F9A479-9397-3A63-ACBD-F51977FB0F02")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.PropertyBuilder))] -[System.Runtime.InteropServices.ComVisible(true)] + [System.Runtime.InteropServices.ComVisible(true)] public interface _PropertyBuilder { -#if !FEATURE_CORECLR - void GetTypeInfoCount(out uint pcTInfo); - - void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); - - void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); - - void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); -#endif } [GuidAttribute("7D13DD37-5A04-393C-BBCA-A5FEA802893D")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.SignatureHelper))] -[System.Runtime.InteropServices.ComVisible(true)] + [System.Runtime.InteropServices.ComVisible(true)] public interface _SignatureHelper { -#if !FEATURE_CORECLR - void GetTypeInfoCount(out uint pcTInfo); - - void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); - - void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); - - void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); -#endif } [GuidAttribute("7E5678EE-48B3-3F83-B076-C58543498A58")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.TypeBuilder))] -[System.Runtime.InteropServices.ComVisible(true)] + [System.Runtime.InteropServices.ComVisible(true)] public interface _TypeBuilder { -#if !FEATURE_CORECLR - void GetTypeInfoCount(out uint pcTInfo); - - void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); - - void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); - - void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); -#endif } - } diff --git a/src/mscorlib/src/System/Reflection/Emit/ConstructorBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/ConstructorBuilder.cs index e5062d3365..ef76adcf80 100644 --- a/src/mscorlib/src/System/Reflection/Emit/ConstructorBuilder.cs +++ b/src/mscorlib/src/System/Reflection/Emit/ConstructorBuilder.cs @@ -16,7 +16,6 @@ namespace System.Reflection.Emit using System.Runtime.InteropServices; using System.Diagnostics.Contracts; - [HostProtection(MayLeakOnAbort = true)] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_ConstructorBuilder))] [System.Runtime.InteropServices.ComVisible(true)] @@ -31,7 +30,6 @@ namespace System.Reflection.Emit { } - [System.Security.SecurityCritical] // auto-generated internal ConstructorBuilder(String name, MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers, ModuleBuilder mod, TypeBuilder type) { @@ -49,7 +47,6 @@ namespace System.Reflection.Emit token = m_methodBuilder.GetToken(); } - [System.Security.SecurityCritical] // auto-generated internal ConstructorBuilder(String name, MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes, ModuleBuilder mod, TypeBuilder type) : this(name, attributes, callingConvention, parameterTypes, null, null, mod, type) @@ -205,9 +202,6 @@ namespace System.Reflection.Emit return m_methodBuilder.GetILGenerator(streamSize); } - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif public void SetMethodBody(byte[] il, int maxStack, byte[] localSignature, IEnumerable<ExceptionHandler> exceptionHandlers, IEnumerable<int> tokenFixups) { if (m_isDefaultConstructor) @@ -218,36 +212,6 @@ namespace System.Reflection.Emit m_methodBuilder.SetMethodBody(il, maxStack, localSignature, exceptionHandlers, tokenFixups); } -#if FEATURE_CAS_POLICY - [System.Security.SecuritySafeCritical] // auto-generated - public void AddDeclarativeSecurity(SecurityAction action, PermissionSet pset) - { - if (pset == null) - throw new ArgumentNullException("pset"); - -#pragma warning disable 618 - if (!Enum.IsDefined(typeof(SecurityAction), action) || - action == SecurityAction.RequestMinimum || - action == SecurityAction.RequestOptional || - action == SecurityAction.RequestRefuse) - { - throw new ArgumentOutOfRangeException("action"); - } -#pragma warning restore 618 - Contract.EndContractBlock(); - - // Cannot add declarative security after type is created. - if (m_methodBuilder.IsTypeCreated()) - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TypeHasBeenCreated")); - - // Translate permission set into serialized format (use standard binary serialization). - byte[] blob = pset.EncodeXml(); - - // Write the blob into the metadata. - TypeBuilder.AddDeclarativeSecurity(GetModuleBuilder().GetNativeHandle(), GetToken().Token, action, blob, blob.Length); - } -#endif // FEATURE_CAS_POLICY - public override CallingConventions CallingConvention { get @@ -282,9 +246,6 @@ namespace System.Reflection.Emit get { return m_methodBuilder.Signature; } } - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif [System.Runtime.InteropServices.ComVisible(true)] public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { @@ -308,28 +269,6 @@ namespace System.Reflection.Emit } #endregion - -#if !FEATURE_CORECLR - void _ConstructorBuilder.GetTypeInfoCount(out uint pcTInfo) - { - throw new NotImplementedException(); - } - - void _ConstructorBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) - { - throw new NotImplementedException(); - } - - void _ConstructorBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) - { - throw new NotImplementedException(); - } - - void _ConstructorBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) - { - throw new NotImplementedException(); - } -#endif } } diff --git a/src/mscorlib/src/System/Reflection/Emit/CustomAttributeBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/CustomAttributeBuilder.cs index 2a29a5c190..545657a053 100644 --- a/src/mscorlib/src/System/Reflection/Emit/CustomAttributeBuilder.cs +++ b/src/mscorlib/src/System/Reflection/Emit/CustomAttributeBuilder.cs @@ -22,9 +22,9 @@ namespace System.Reflection.Emit { using System.Security.Permissions; using System.Runtime.InteropServices; using System.Globalization; + using System.Diagnostics; using System.Diagnostics.Contracts; - [HostProtection(MayLeakOnAbort = true)] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_CustomAttributeBuilder))] [System.Runtime.InteropServices.ComVisible(true)] @@ -70,8 +70,14 @@ namespace System.Reflection.Emit { // Check that a type is suitable for use in a custom attribute. private bool ValidateType(Type t) { - if (t.IsPrimitive || t == typeof(String) || t == typeof(Type)) + if (t.IsPrimitive) + { + return t != typeof(IntPtr) && t != typeof(UIntPtr); + } + if (t == typeof(String) || t == typeof(Type)) + { return true; + } if (t.IsEnum) { switch (Type.GetTypeCode(Enum.GetUnderlyingType(t))) @@ -103,17 +109,17 @@ namespace System.Reflection.Emit { FieldInfo[] namedFields, Object[] fieldValues) { if (con == null) - throw new ArgumentNullException("con"); + throw new ArgumentNullException(nameof(con)); if (constructorArgs == null) - throw new ArgumentNullException("constructorArgs"); + throw new ArgumentNullException(nameof(constructorArgs)); if (namedProperties == null) - throw new ArgumentNullException("namedProperties"); + throw new ArgumentNullException(nameof(namedProperties)); if (propertyValues == null) - throw new ArgumentNullException("propertyValues"); + throw new ArgumentNullException(nameof(propertyValues)); if (namedFields == null) - throw new ArgumentNullException("namedFields"); + throw new ArgumentNullException(nameof(namedFields)); if (fieldValues == null) - throw new ArgumentNullException("fieldValues"); + throw new ArgumentNullException(nameof(fieldValues)); if (namedProperties.Length != propertyValues.Length) throw new ArgumentException(Environment.GetResourceString("Arg_ArrayLengthsDiffer"), "namedProperties, propertyValues"); if (namedFields.Length != fieldValues.Length) @@ -123,7 +129,7 @@ namespace System.Reflection.Emit { if ((con.Attributes & MethodAttributes.Static) == MethodAttributes.Static || (con.Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) throw new ArgumentException(Environment.GetResourceString("Argument_BadConstructor")); - + if ((con.CallingConvention & CallingConventions.Standard) != CallingConventions.Standard) throw new ArgumentException(Environment.GetResourceString("Argument_BadConstructorCallConv")); @@ -150,12 +156,16 @@ namespace System.Reflection.Emit { // Now verify that the types of the actual parameters are compatible with the types of the formal parameters. for (i = 0; i < paramTypes.Length; i++) { - if (constructorArgs[i] == null) + object constructorArg = constructorArgs[i]; + if (constructorArg == null) + { + if (paramTypes[i].IsValueType) + { + throw new ArgumentNullException($"{nameof(constructorArgs)}[{i}]"); + } continue; - TypeCode paramTC = Type.GetTypeCode(paramTypes[i]); - if (paramTC != Type.GetTypeCode(constructorArgs[i].GetType())) - if (paramTC != TypeCode.Object || !ValidateType(constructorArgs[i].GetType())) - throw new ArgumentException(Environment.GetResourceString("Argument_BadParameterTypeForConstructor", i)); + } + VerifyTypeAndPassedObjectType(paramTypes[i], constructorArg.GetType(), $"{nameof(constructorArgs)}[{i}]"); } // Allocate a memory stream to represent the CA blob in the metadata and a binary writer to help format it. @@ -176,12 +186,14 @@ namespace System.Reflection.Emit { for (i = 0; i < namedProperties.Length; i++) { // Validate the property. - if (namedProperties[i] == null) + PropertyInfo property = namedProperties[i]; + if (property == null) throw new ArgumentNullException("namedProperties[" + i + "]"); // Allow null for non-primitive types only. - Type propType = namedProperties[i].PropertyType; - if (propertyValues[i] == null && propType.IsPrimitive) + Type propType = property.PropertyType; + object propertyValue = propertyValues[i]; + if (propertyValue == null && propType.IsValueType) throw new ArgumentNullException("propertyValues[" + i + "]"); // Validate property type. @@ -189,55 +201,57 @@ namespace System.Reflection.Emit { throw new ArgumentException(Environment.GetResourceString("Argument_BadTypeInCustomAttribute")); // Property has to be writable. - if (!namedProperties[i].CanWrite) + if (!property.CanWrite) throw new ArgumentException(Environment.GetResourceString("Argument_NotAWritableProperty")); - + // Property has to be from the same class or base class as ConstructorInfo. - if (namedProperties[i].DeclaringType != con.DeclaringType + if (property.DeclaringType != con.DeclaringType && (!(con.DeclaringType is TypeBuilderInstantiation)) - && !con.DeclaringType.IsSubclassOf(namedProperties[i].DeclaringType)) + && !con.DeclaringType.IsSubclassOf(property.DeclaringType)) { // Might have failed check because one type is a XXXBuilder // and the other is not. Deal with these special cases // separately. - if (!TypeBuilder.IsTypeEqual(namedProperties[i].DeclaringType, con.DeclaringType)) + if (!TypeBuilder.IsTypeEqual(property.DeclaringType, con.DeclaringType)) { // IsSubclassOf is overloaded to do the right thing if // the constructor is a TypeBuilder, but we still need // to deal with the case where the property's declaring // type is one. - if (!(namedProperties[i].DeclaringType is TypeBuilder) || - !con.DeclaringType.IsSubclassOf(((TypeBuilder)namedProperties[i].DeclaringType).BakedRuntimeType)) + if (!(property.DeclaringType is TypeBuilder) || + !con.DeclaringType.IsSubclassOf(((TypeBuilder)property.DeclaringType).BakedRuntimeType)) throw new ArgumentException(Environment.GetResourceString("Argument_BadPropertyForConstructorBuilder")); } } // Make sure the property's type can take the given value. // Note that there will be no coersion. - if (propertyValues[i] != null && - propType != typeof(Object) && - Type.GetTypeCode(propertyValues[i].GetType()) != Type.GetTypeCode(propType)) - throw new ArgumentException(Environment.GetResourceString("Argument_ConstantDoesntMatch")); - + if (propertyValue != null) + { + VerifyTypeAndPassedObjectType(propType, propertyValue.GetType(), $"{nameof(propertyValues)}[{i}]"); + } + // First a byte indicating that this is a property. writer.Write((byte)CustomAttributeEncoding.Property); // Emit the property type, name and value. EmitType(writer, propType); EmitString(writer, namedProperties[i].Name); - EmitValue(writer, propType, propertyValues[i]); + EmitValue(writer, propType, propertyValue); } // Emit all the field sets. for (i = 0; i < namedFields.Length; i++) { // Validate the field. - if (namedFields[i] == null) + FieldInfo namedField = namedFields[i]; + if (namedField == null) throw new ArgumentNullException("namedFields[" + i + "]"); // Allow null for non-primitive types only. - Type fldType = namedFields[i].FieldType; - if (fieldValues[i] == null && fldType.IsPrimitive) + Type fldType = namedField.FieldType; + object fieldValue = fieldValues[i]; + if (fieldValue == null && fldType.IsValueType) throw new ArgumentNullException("fieldValues[" + i + "]"); // Validate field type. @@ -245,20 +259,20 @@ namespace System.Reflection.Emit { throw new ArgumentException(Environment.GetResourceString("Argument_BadTypeInCustomAttribute")); // Field has to be from the same class or base class as ConstructorInfo. - if (namedFields[i].DeclaringType != con.DeclaringType + if (namedField.DeclaringType != con.DeclaringType && (!(con.DeclaringType is TypeBuilderInstantiation)) - && !con.DeclaringType.IsSubclassOf(namedFields[i].DeclaringType)) + && !con.DeclaringType.IsSubclassOf(namedField.DeclaringType)) { // Might have failed check because one type is a XXXBuilder // and the other is not. Deal with these special cases // separately. - if (!TypeBuilder.IsTypeEqual(namedFields[i].DeclaringType, con.DeclaringType)) + if (!TypeBuilder.IsTypeEqual(namedField.DeclaringType, con.DeclaringType)) { // IsSubclassOf is overloaded to do the right thing if // the constructor is a TypeBuilder, but we still need // to deal with the case where the field's declaring // type is one. - if (!(namedFields[i].DeclaringType is TypeBuilder) || + if (!(namedField.DeclaringType is TypeBuilder) || !con.DeclaringType.IsSubclassOf(((TypeBuilder)namedFields[i].DeclaringType).BakedRuntimeType)) throw new ArgumentException(Environment.GetResourceString("Argument_BadFieldForConstructorBuilder")); } @@ -266,24 +280,36 @@ namespace System.Reflection.Emit { // Make sure the field's type can take the given value. // Note that there will be no coersion. - if (fieldValues[i] != null && - fldType != typeof(Object) && - Type.GetTypeCode(fieldValues[i].GetType()) != Type.GetTypeCode(fldType)) - throw new ArgumentException(Environment.GetResourceString("Argument_ConstantDoesntMatch")); + if (fieldValue != null) + { + VerifyTypeAndPassedObjectType(fldType, fieldValue.GetType(), $"{nameof(fieldValues)}[{i}]"); + } // First a byte indicating that this is a field. writer.Write((byte)CustomAttributeEncoding.Field); // Emit the field type, name and value. EmitType(writer, fldType); - EmitString(writer, namedFields[i].Name); - EmitValue(writer, fldType, fieldValues[i]); + EmitString(writer, namedField.Name); + EmitValue(writer, fldType, fieldValue); } // Create the blob array. m_blob = ((MemoryStream)writer.BaseStream).ToArray(); } + private static void VerifyTypeAndPassedObjectType(Type type, Type passedType, string paramName) + { + if (type != typeof(object) && Type.GetTypeCode(passedType) != Type.GetTypeCode(type)) + { + throw new ArgumentException(Environment.GetResourceString("Argument_ConstantDoesntMatch")); + } + if (passedType == typeof(IntPtr) || passedType == typeof(UIntPtr)) + { + throw new ArgumentException(Environment.GetResourceString("Argument_BadParameterTypeForCAB"), paramName); + } + } + private void EmitType(BinaryWriter writer, Type type) { if (type.IsPrimitive) @@ -327,7 +353,7 @@ namespace System.Reflection.Emit { writer.Write((byte)CustomAttributeEncoding.Double); break; default: - Contract.Assert(false, "Invalid primitive type"); + Debug.Assert(false, "Invalid primitive type"); break; } } @@ -411,7 +437,7 @@ namespace System.Reflection.Emit { writer.Write((ulong)value); break; default: - Contract.Assert(false, "Invalid enum base type"); + Debug.Assert(false, "Invalid enum base type"); break; } } @@ -489,7 +515,7 @@ namespace System.Reflection.Emit { writer.Write((double)value); break; default: - Contract.Assert(false, "Invalid primitive type"); + Debug.Assert(false, "Invalid primitive type"); break; } } @@ -524,7 +550,6 @@ namespace System.Reflection.Emit { // return the byte interpretation of the custom attribute - [System.Security.SecurityCritical] // auto-generated internal void CreateCustomAttribute(ModuleBuilder mod, int tkOwner) { CreateCustomAttribute(mod, tkOwner, mod.GetConstructorToken(m_con).Token, false); @@ -537,7 +562,6 @@ namespace System.Reflection.Emit { // This function has to be called before we snap the in-memory module for on disk (i.e. Presave on // ModuleBuilder. //************************************************* - [System.Security.SecurityCritical] // auto-generated internal int PrepareCreateCustomAttributeToDisk(ModuleBuilder mod) { return mod.InternalGetConstructorToken(m_con, true).Token; @@ -546,35 +570,12 @@ namespace System.Reflection.Emit { //************************************************* // Call this function with toDisk=1, after on disk module has been snapped. //************************************************* - [System.Security.SecurityCritical] // auto-generated internal void CreateCustomAttribute(ModuleBuilder mod, int tkOwner, int tkAttrib, bool toDisk) { TypeBuilder.DefineCustomAttribute(mod, tkOwner, tkAttrib, m_blob, toDisk, typeof(System.Diagnostics.DebuggableAttribute) == m_con.DeclaringType); } -#if !FEATURE_CORECLR - void _CustomAttributeBuilder.GetTypeInfoCount(out uint pcTInfo) - { - throw new NotImplementedException(); - } - - void _CustomAttributeBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) - { - throw new NotImplementedException(); - } - - void _CustomAttributeBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) - { - throw new NotImplementedException(); - } - - void _CustomAttributeBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) - { - throw new NotImplementedException(); - } -#endif - internal ConstructorInfo m_con; internal Object[] m_constructorArgs; internal byte[] m_blob; diff --git a/src/mscorlib/src/System/Reflection/Emit/DynamicILGenerator.cs b/src/mscorlib/src/System/Reflection/Emit/DynamicILGenerator.cs index b66fdad1e2..9e1d82986a 100644 --- a/src/mscorlib/src/System/Reflection/Emit/DynamicILGenerator.cs +++ b/src/mscorlib/src/System/Reflection/Emit/DynamicILGenerator.cs @@ -9,7 +9,6 @@ namespace System.Reflection.Emit using System; using System.Globalization; - using TextWriter = System.IO.TextWriter; using System.Diagnostics.SymbolStore; using System.Runtime.InteropServices; using System.Reflection; @@ -17,6 +16,7 @@ namespace System.Reflection.Emit using System.Collections.Generic; using System.Security.Permissions; using System.Threading; + using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Security; @@ -36,7 +36,6 @@ namespace System.Reflection.Emit } - [System.Security.SecurityCritical] // auto-generated internal void GetCallableMethod(RuntimeModule module, DynamicMethod dm) { dm.m_methodHandle = ModuleHandle.GetDynamicMethod(dm, @@ -62,7 +61,7 @@ namespace System.Reflection.Emit { LocalBuilder localBuilder; if (localType == null) - throw new ArgumentNullException("localType"); + throw new ArgumentNullException(nameof(localType)); Contract.EndContractBlock(); RuntimeType rtType = localType as RuntimeType; @@ -87,11 +86,10 @@ namespace System.Reflection.Emit // Token resolution calls // // - [System.Security.SecuritySafeCritical] // auto-generated public override void Emit(OpCode opcode, MethodInfo meth) { if (meth == null) - throw new ArgumentNullException("meth"); + throw new ArgumentNullException(nameof(meth)); Contract.EndContractBlock(); int stackchange = 0; @@ -101,7 +99,7 @@ namespace System.Reflection.Emit { RuntimeMethodInfo rtMeth = meth as RuntimeMethodInfo; if (rtMeth == null) - throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), "meth"); + throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), nameof(meth)); RuntimeType declaringType = rtMeth.GetRuntimeType(); if (declaringType != null && (declaringType.IsGenericType || declaringType.IsArray)) @@ -148,12 +146,12 @@ namespace System.Reflection.Emit public override void Emit(OpCode opcode, ConstructorInfo con) { if (con == null) - throw new ArgumentNullException("con"); + throw new ArgumentNullException(nameof(con)); Contract.EndContractBlock(); RuntimeConstructorInfo rtConstructor = con as RuntimeConstructorInfo; if (rtConstructor == null) - throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), "con"); + throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), nameof(con)); RuntimeType declaringType = rtConstructor.GetRuntimeType(); int token; @@ -176,7 +174,7 @@ namespace System.Reflection.Emit public override void Emit(OpCode opcode, Type type) { if (type == null) - throw new ArgumentNullException("type"); + throw new ArgumentNullException(nameof(type)); Contract.EndContractBlock(); RuntimeType rtType = type as RuntimeType; @@ -193,12 +191,12 @@ namespace System.Reflection.Emit public override void Emit(OpCode opcode, FieldInfo field) { if (field == null) - throw new ArgumentNullException("field"); + throw new ArgumentNullException(nameof(field)); Contract.EndContractBlock(); RuntimeFieldInfo runtimeField = field as RuntimeFieldInfo; if (runtimeField == null) - throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeFieldInfo"), "field"); + throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeFieldInfo"), nameof(field)); int token; if (field.DeclaringType == null) @@ -214,7 +212,7 @@ namespace System.Reflection.Emit public override void Emit(OpCode opcode, String str) { if (str == null) - throw new ArgumentNullException("str"); + throw new ArgumentNullException(nameof(str)); Contract.EndContractBlock(); int tempVal = GetTokenForString(str); @@ -228,7 +226,6 @@ namespace System.Reflection.Emit // Signature related calls (vararg, calli) // // - [System.Security.SecuritySafeCritical] // overrides SC public override void EmitCalli(OpCode opcode, CallingConventions callingConvention, Type returnType, @@ -307,20 +304,19 @@ namespace System.Reflection.Emit PutInteger4(token); } - [System.Security.SecuritySafeCritical] // auto-generated public override void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[] optionalParameterTypes) { if (methodInfo == null) - throw new ArgumentNullException("methodInfo"); + throw new ArgumentNullException(nameof(methodInfo)); if (!(opcode.Equals(OpCodes.Call) || opcode.Equals(OpCodes.Callvirt) || opcode.Equals(OpCodes.Newobj))) - throw new ArgumentException(Environment.GetResourceString("Argument_NotMethodCallOpcode"), "opcode"); + throw new ArgumentException(Environment.GetResourceString("Argument_NotMethodCallOpcode"), nameof(opcode)); if (methodInfo.ContainsGenericParameters) - throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), "methodInfo"); + throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), nameof(methodInfo)); if (methodInfo.DeclaringType != null && methodInfo.DeclaringType.ContainsGenericParameters) - throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), "methodInfo"); + throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), nameof(methodInfo)); Contract.EndContractBlock(); int tk; @@ -351,7 +347,7 @@ namespace System.Reflection.Emit public override void Emit(OpCode opcode, SignatureHelper signature) { if (signature == null) - throw new ArgumentNullException("signature"); + throw new ArgumentNullException(nameof(signature)); Contract.EndContractBlock(); int stackchange = 0; @@ -365,7 +361,7 @@ namespace System.Reflection.Emit // SignatureHelper. if (opcode.StackBehaviourPop == StackBehaviour.Varpop) { - Contract.Assert(opcode.Equals(OpCodes.Calli), + Debug.Assert(opcode.Equals(OpCodes.Calli), "Unexpected opcode encountered for StackBehaviour VarPop."); // Pop the arguments.. stackchange -= signature.ArgumentCount; @@ -421,7 +417,7 @@ namespace System.Reflection.Emit { // execute this branch if previous clause is Catch or Fault if (exceptionType == null) - throw new ArgumentNullException("exceptionType"); + throw new ArgumentNullException(nameof(exceptionType)); if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType")); @@ -482,7 +478,6 @@ namespace System.Reflection.Emit throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod")); } - [System.Security.SecurityCritical] // auto-generated private int GetMemberRefToken(MethodBase methodInfo, Type[] optionalParameterTypes) { Type[] parameterTypes; @@ -494,7 +489,7 @@ namespace System.Reflection.Emit DynamicMethod dm = methodInfo as DynamicMethod; if (rtMeth == null && dm == null) - throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), "methodInfo"); + throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), nameof(methodInfo)); ParameterInfo[] paramInfo = methodInfo.GetParametersNoCopy(); if (paramInfo != null && paramInfo.Length != 0) @@ -519,7 +514,6 @@ namespace System.Reflection.Emit return GetTokenForVarArgMethod(dm, sig); } - [System.Security.SecurityCritical] // auto-generated internal override SignatureHelper GetMemberRefSignature( CallingConventions call, Type returnType, @@ -704,9 +698,6 @@ namespace System.Reflection.Emit m_method.m_resolver = this; } -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#endif internal DynamicResolver(DynamicILInfo dynamicILInfo) { m_stackSize = dynamicILInfo.MaxStackSize; @@ -774,7 +765,6 @@ namespace System.Reflection.Emit { internal RuntimeMethodHandleInternal m_methodHandle; - [System.Security.SecuritySafeCritical] // auto-generated ~DestroyScout() { if (m_methodHandle.IsNullHandle()) @@ -887,7 +877,6 @@ namespace System.Reflection.Emit return m_exceptionHeader; } - [System.Security.SecurityCritical] // auto-generated internal override unsafe void GetEHInfo(int excNumber, void* exc) { CORINFO_EH_CLAUSE* exception = (CORINFO_EH_CLAUSE*)exc; @@ -922,7 +911,6 @@ namespace System.Reflection.Emit } #endif // FEATURE_COMPRESSEDSTACK - [System.Security.SecurityCritical] internal override void ResolveToken(int token, out IntPtr typeHandle, out IntPtr methodHandle, out IntPtr fieldHandle) { typeHandle = new IntPtr(); @@ -1003,9 +991,6 @@ namespace System.Reflection.Emit } -#if FEATURE_CORECLR -[System.Security.SecurityCritical] // auto-generated -#endif [System.Runtime.InteropServices.ComVisible(true)] public class DynamicILInfo { @@ -1032,7 +1017,6 @@ namespace System.Reflection.Emit #endregion #region Internal Methods - [System.Security.SecurityCritical] // auto-generated internal void GetCallableMethod(RuntimeModule module, DynamicMethod dm) { dm.m_methodHandle = ModuleHandle.GetDynamicMethod(dm, @@ -1064,15 +1048,14 @@ namespace System.Reflection.Emit m_maxStackSize = maxStackSize; } - [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] public unsafe void SetCode(byte* code, int codeSize, int maxStackSize) { if (codeSize < 0) - throw new ArgumentOutOfRangeException("codeSize", Environment.GetResourceString("ArgumentOutOfRange_GenericPositive")); + throw new ArgumentOutOfRangeException(nameof(codeSize), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive")); if (codeSize > 0 && code == null) - throw new ArgumentNullException("code"); + throw new ArgumentNullException(nameof(code)); Contract.EndContractBlock(); m_code = new byte[codeSize]; @@ -1090,15 +1073,14 @@ namespace System.Reflection.Emit m_exceptions = (exceptions != null) ? (byte[])exceptions.Clone() : EmptyArray<Byte>.Value; } - [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] public unsafe void SetExceptions(byte* exceptions, int exceptionsSize) { if (exceptionsSize < 0) - throw new ArgumentOutOfRangeException("exceptionsSize", Environment.GetResourceString("ArgumentOutOfRange_GenericPositive")); + throw new ArgumentOutOfRangeException(nameof(exceptionsSize), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive")); if (exceptionsSize > 0 && exceptions == null) - throw new ArgumentNullException("exceptions"); + throw new ArgumentNullException(nameof(exceptions)); Contract.EndContractBlock(); m_exceptions = new byte[exceptionsSize]; @@ -1115,15 +1097,14 @@ namespace System.Reflection.Emit m_localSignature = (localSignature != null) ? (byte[])localSignature.Clone() : EmptyArray<Byte>.Value; } - [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] public unsafe void SetLocalSignature(byte* localSignature, int signatureSize) { if (signatureSize < 0) - throw new ArgumentOutOfRangeException("signatureSize", Environment.GetResourceString("ArgumentOutOfRange_GenericPositive")); + throw new ArgumentOutOfRangeException(nameof(signatureSize), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive")); if (signatureSize > 0 && localSignature == null) - throw new ArgumentNullException("localSignature"); + throw new ArgumentNullException(nameof(localSignature)); Contract.EndContractBlock(); m_localSignature = new byte[signatureSize]; @@ -1136,7 +1117,6 @@ namespace System.Reflection.Emit #endregion #region Public Scope Methods - [System.Security.SecuritySafeCritical] // auto-generated public int GetTokenFor(RuntimeMethodHandle method) { return DynamicScope.GetTokenFor(method); @@ -1222,7 +1202,6 @@ namespace System.Reflection.Emit #endregion #region Public Methods - [System.Security.SecuritySafeCritical] // auto-generated public int GetTokenFor(RuntimeMethodHandle method) { IRuntimeMethodInfo methodReal = method.GetMethodInfo(); diff --git a/src/mscorlib/src/System/Reflection/Emit/DynamicMethod.cs b/src/mscorlib/src/System/Reflection/Emit/DynamicMethod.cs index 6f6b436706..1b8c97de65 100644 --- a/src/mscorlib/src/System/Reflection/Emit/DynamicMethod.cs +++ b/src/mscorlib/src/System/Reflection/Emit/DynamicMethod.cs @@ -15,6 +15,7 @@ namespace System.Reflection.Emit using System.Threading; using System.Runtime.CompilerServices; using System.Runtime.Versioning; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; @@ -25,9 +26,6 @@ namespace System.Reflection.Emit internal IRuntimeMethodInfo m_methodHandle; private RuntimeType m_returnType; private DynamicILGenerator m_ilGenerator; - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif private DynamicILInfo m_DynamicILInfo; private bool m_fInitLocals; private RuntimeModule m_module; @@ -72,7 +70,6 @@ namespace System.Reflection.Emit private DynamicMethod() { } - [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public DynamicMethod(string name, Type returnType, @@ -92,7 +89,6 @@ namespace System.Reflection.Emit ref stackMark); // transparentMethod } - [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public DynamicMethod(string name, Type returnType, @@ -113,11 +109,6 @@ namespace System.Reflection.Emit ref stackMark); // transparentMethod } - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #else - [System.Security.SecuritySafeCritical] - #endif [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public DynamicMethod(string name, Type returnType, @@ -137,11 +128,6 @@ namespace System.Reflection.Emit ref stackMark); // transparentMethod } - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #else - [System.Security.SecuritySafeCritical] - #endif [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public DynamicMethod(string name, Type returnType, @@ -162,11 +148,6 @@ namespace System.Reflection.Emit ref stackMark); // transparentMethod } - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #else - [System.Security.SecuritySafeCritical] - #endif [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public DynamicMethod(string name, MethodAttributes attributes, @@ -189,11 +170,6 @@ namespace System.Reflection.Emit ref stackMark); // transparentMethod } - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #else - [System.Security.SecuritySafeCritical] - #endif [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public DynamicMethod(string name, Type returnType, @@ -213,11 +189,6 @@ namespace System.Reflection.Emit ref stackMark); // transparentMethod } - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #else - [System.Security.SecuritySafeCritical] - #endif [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public DynamicMethod(string name, Type returnType, @@ -238,11 +209,6 @@ namespace System.Reflection.Emit ref stackMark); // transparentMethod } - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #else - [System.Security.SecuritySafeCritical] - #endif [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public DynamicMethod(string name, MethodAttributes attributes, @@ -286,7 +252,6 @@ namespace System.Reflection.Emit // We create a transparent assembly to host DynamicMethods. Since the assembly does not have any // non-public fields (or any fields at all), it is a safe anonymous assembly to host DynamicMethods - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable private static RuntimeModule GetDynamicMethodsModule() { @@ -302,21 +267,6 @@ namespace System.Reflection.Emit CustomAttributeBuilder transparencyAttribute = new CustomAttributeBuilder(transparencyCtor, EmptyArray<Object>.Value); List<CustomAttributeBuilder> assemblyAttributes = new List<CustomAttributeBuilder>(); assemblyAttributes.Add(transparencyAttribute); -#if !FEATURE_CORECLR - // On the desktop, we need to use the security rule set level 1 for anonymously hosted - // dynamic methods. In level 2, transparency rules are strictly enforced, which leads to - // errors when a fully trusted application causes a dynamic method to be generated that tries - // to call a method with a LinkDemand or a SecurityCritical method. To retain compatibility - // with the v2.0 and v3.x frameworks, these calls should be allowed. - // - // If this rule set was not explicitly called out, then the anonymously hosted dynamic methods - // assembly would inherit the rule set from the creating assembly - which would cause it to - // be level 2 because mscorlib.dll is using the level 2 rules. - ConstructorInfo securityRulesCtor = typeof(SecurityRulesAttribute).GetConstructor(new Type[] { typeof(SecurityRuleSet) }); - CustomAttributeBuilder securityRulesAttribute = - new CustomAttributeBuilder(securityRulesCtor, new object[] { SecurityRuleSet.Level1 }); - assemblyAttributes.Add(securityRulesAttribute); -#endif // !FEATURE_CORECLR AssemblyName assemblyName = new AssemblyName("Anonymously Hosted DynamicMethods Assembly"); StackCrawlMark stackMark = StackCrawlMark.LookForMe; @@ -338,7 +288,6 @@ namespace System.Reflection.Emit return s_anonymouslyHostedDynamicMethodsModule; } - [System.Security.SecurityCritical] // auto-generated private unsafe void Init(String name, MethodAttributes attributes, CallingConventions callingConvention, @@ -374,7 +323,7 @@ namespace System.Reflection.Emit if (transparentMethod) { - Contract.Assert(owner == null && m == null, "owner and m cannot be set for transparent methods"); + Debug.Assert(owner == null && m == null, "owner and m cannot be set for transparent methods"); m_module = GetDynamicMethodsModule(); if (skipVisibility) { @@ -387,9 +336,9 @@ namespace System.Reflection.Emit } else { - Contract.Assert(m != null || owner != null, "PerformSecurityCheck should ensure that either m or owner is set"); - Contract.Assert(m == null || !m.Equals(s_anonymouslyHostedDynamicMethodsModule), "The user cannot explicitly use this assembly"); - Contract.Assert(m == null || owner == null, "m and owner cannot both be set"); + Debug.Assert(m != null || owner != null, "PerformSecurityCheck should ensure that either m or owner is set"); + Debug.Assert(m == null || !m.Equals(s_anonymouslyHostedDynamicMethodsModule), "The user cannot explicitly use this assembly"); + Debug.Assert(m == null || owner == null, "m and owner cannot both be set"); if (m != null) m_module = m.ModuleHandle.GetRuntimeModule(); // this returns the underlying module for all RuntimeModule and ModuleBuilder objects. @@ -419,7 +368,7 @@ namespace System.Reflection.Emit m_methodHandle = null; if (name == null) - throw new ArgumentNullException("name"); + throw new ArgumentNullException(nameof(name)); #if FEATURE_APPX if (AppDomain.ProfileAPICheck) @@ -435,101 +384,23 @@ namespace System.Reflection.Emit m_dynMethod = new RTDynamicMethod(this, name, attributes, callingConvention); } - [System.Security.SecurityCritical] // auto-generated private void PerformSecurityCheck(Module m, ref StackCrawlMark stackMark, bool skipVisibility) { if (m == null) - throw new ArgumentNullException("m"); + throw new ArgumentNullException(nameof(m)); Contract.EndContractBlock(); -#if !FEATURE_CORECLR - - RuntimeModule rtModule; - ModuleBuilder mb = m as ModuleBuilder; - if (mb != null) - rtModule = mb.InternalModule; - else - rtModule = m as RuntimeModule; - - if (rtModule == null) - { - throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeModule"), "m"); - } - - // The user cannot explicitly use this assembly - if (rtModule == s_anonymouslyHostedDynamicMethodsModule) - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidValue"), "m"); - - // ask for member access if skip visibility - if (skipVisibility) - new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand(); - -#if !FEATURE_CORECLR - // ask for control evidence if outside of the caller assembly - RuntimeType callingType = RuntimeMethodHandle.GetCallerType(ref stackMark); - m_creatorAssembly = callingType.GetRuntimeAssembly(); - if (m.Assembly != m_creatorAssembly) - { - // Demand the permissions of the assembly where the DynamicMethod will live - CodeAccessSecurityEngine.ReflectionTargetDemandHelper(PermissionType.SecurityControlEvidence, - m.Assembly.PermissionSet); - } -#else //FEATURE_CORECLR -#pragma warning disable 618 - new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand(); -#pragma warning restore 618 -#endif //FEATURE_CORECLR -#endif //!FEATURE_CORECLR } - [System.Security.SecurityCritical] // auto-generated private void PerformSecurityCheck(Type owner, ref StackCrawlMark stackMark, bool skipVisibility) { if (owner == null) - throw new ArgumentNullException("owner"); -#if !FEATURE_CORECLR - - RuntimeType rtOwner = owner as RuntimeType; - if (rtOwner == null) - rtOwner = owner.UnderlyingSystemType as RuntimeType; - - if (rtOwner == null) - throw new ArgumentNullException("owner", Environment.GetResourceString("Argument_MustBeRuntimeType")); - - // get the type the call is coming from - RuntimeType callingType = RuntimeMethodHandle.GetCallerType(ref stackMark); - - // ask for member access if skip visibility - if (skipVisibility) - new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand(); - else - { - // if the call is not coming from the same class ask for member access - if (callingType != rtOwner) - new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand(); - } -#if !FEATURE_CORECLR - m_creatorAssembly = callingType.GetRuntimeAssembly(); - - // ask for control evidence if outside of the caller module - if (rtOwner.Assembly != m_creatorAssembly) - { - // Demand the permissions of the assembly where the DynamicMethod will live - CodeAccessSecurityEngine.ReflectionTargetDemandHelper(PermissionType.SecurityControlEvidence, - owner.Assembly.PermissionSet); - } -#else //FEATURE_CORECLR -#pragma warning disable 618 - new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand(); -#pragma warning restore 618 -#endif //FEATURE_CORECLR -#endif //!FEATURE_CORECLR + throw new ArgumentNullException(nameof(owner)); } // // Delegate and method creation // - [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(true)] public sealed override Delegate CreateDelegate(Type delegateType) { if (m_restrictedSkipVisibility) @@ -545,7 +416,6 @@ namespace System.Reflection.Emit return d; } - [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(true)] public sealed override Delegate CreateDelegate(Type delegateType, Object target) { if (m_restrictedSkipVisibility) @@ -578,7 +448,6 @@ namespace System.Reflection.Emit #endif // This is guaranteed to return a valid handle - [System.Security.SecurityCritical] // auto-generated internal unsafe RuntimeMethodHandle GetMethodDescriptor() { if (m_methodHandle == null) { lock (this) { @@ -636,83 +505,19 @@ namespace System.Reflection.Emit public override bool IsSecurityCritical { - [SecuritySafeCritical] - get - { - if (m_methodHandle != null) - { - return RuntimeMethodHandle.IsSecurityCritical(m_methodHandle); - } - else if (m_typeOwner != null) - { - RuntimeAssembly assembly = m_typeOwner.Assembly as RuntimeAssembly; - Contract.Assert(assembly != null); - - return assembly.IsAllSecurityCritical(); - } - else - { - RuntimeAssembly assembly = m_module.Assembly as RuntimeAssembly; - Contract.Assert(assembly != null); - - return assembly.IsAllSecurityCritical(); - } - } + get { return true; } } public override bool IsSecuritySafeCritical { - [SecuritySafeCritical] - get - { - if (m_methodHandle != null) - { - return RuntimeMethodHandle.IsSecuritySafeCritical(m_methodHandle); - } - else if (m_typeOwner != null) - { - RuntimeAssembly assembly = m_typeOwner.Assembly as RuntimeAssembly; - Contract.Assert(assembly != null); - - return assembly.IsAllPublicAreaSecuritySafeCritical(); - } - else - { - RuntimeAssembly assembly = m_module.Assembly as RuntimeAssembly; - Contract.Assert(assembly != null); - - return assembly.IsAllSecuritySafeCritical(); - } - } + get { return false; } } public override bool IsSecurityTransparent { - [SecuritySafeCritical] - get - { - if (m_methodHandle != null) - { - return RuntimeMethodHandle.IsSecurityTransparent(m_methodHandle); - } - else if (m_typeOwner != null) - { - RuntimeAssembly assembly = m_typeOwner.Assembly as RuntimeAssembly; - Contract.Assert(assembly != null); - - return !assembly.IsAllSecurityCritical(); - } - else - { - RuntimeAssembly assembly = m_module.Assembly as RuntimeAssembly; - Contract.Assert(assembly != null); - - return !assembly.IsAllSecurityCritical(); - } - } + get { return false; } } - [System.Security.SecuritySafeCritical] // auto-generated public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) { if ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) throw new NotSupportedException(Environment.GetResourceString("NotSupported_CallToVarArg")); @@ -789,7 +594,6 @@ namespace System.Reflection.Emit return null; } - [System.Security.SecuritySafeCritical] // auto-generated public DynamicILInfo GetDynamicILInfo() { #pragma warning disable 618 @@ -802,7 +606,6 @@ namespace System.Reflection.Emit return GetDynamicILInfo(new DynamicScope()); } - [System.Security.SecurityCritical] // auto-generated internal DynamicILInfo GetDynamicILInfo(DynamicScope scope) { if (m_DynamicILInfo == null) @@ -819,7 +622,6 @@ namespace System.Reflection.Emit return GetILGenerator(64); } - [System.Security.SecuritySafeCritical] // auto-generated public ILGenerator GetILGenerator(int streamSize) { if (m_ilGenerator == null) @@ -935,7 +737,7 @@ namespace System.Reflection.Emit public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) - throw new ArgumentNullException("attributeType"); + throw new ArgumentNullException(nameof(attributeType)); Contract.EndContractBlock(); if (attributeType.IsAssignableFrom(typeof(MethodImplAttribute))) @@ -951,7 +753,7 @@ namespace System.Reflection.Emit public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) - throw new ArgumentNullException("attributeType"); + throw new ArgumentNullException(nameof(attributeType)); Contract.EndContractBlock(); if (attributeType.IsAssignableFrom(typeof(MethodImplAttribute))) diff --git a/src/mscorlib/src/System/Reflection/Emit/EnumBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/EnumBuilder.cs index f8e3ab2991..82dc2828ca 100644 --- a/src/mscorlib/src/System/Reflection/Emit/EnumBuilder.cs +++ b/src/mscorlib/src/System/Reflection/Emit/EnumBuilder.cs @@ -23,7 +23,6 @@ namespace System.Reflection.Emit { using System.Security.Permissions; - [HostProtection(MayLeakOnAbort = true)] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_EnumBuilder))] [System.Runtime.InteropServices.ComVisible(true)] @@ -313,9 +312,6 @@ namespace System.Reflection.Emit { // Use this function if client decides to form the custom attribute blob themselves -#if FEATURE_CORECLR -[System.Security.SecurityCritical] // auto-generated -#endif [System.Runtime.InteropServices.ComVisible(true)] public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { @@ -398,7 +394,6 @@ namespace System.Reflection.Emit { // Constructs a EnumBuilder. // EnumBuilder can only be a top-level (not nested) enum type. - [System.Security.SecurityCritical] // auto-generated internal EnumBuilder( String name, // name of type Type underlyingType, // underlying type for an Enum @@ -407,36 +402,13 @@ namespace System.Reflection.Emit { { // Client should not set any bits other than the visibility bits. if ((visibility & ~TypeAttributes.VisibilityMask) != 0) - throw new ArgumentException(Environment.GetResourceString("Argument_ShouldOnlySetVisibilityFlags"), "name"); + throw new ArgumentException(Environment.GetResourceString("Argument_ShouldOnlySetVisibilityFlags"), nameof(name)); m_typeBuilder = new TypeBuilder(name, visibility | TypeAttributes.Sealed, typeof(System.Enum), null, module, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize, null); // Define the underlying field for the enum. It will be a non-static, private field with special name bit set. m_underlyingField = m_typeBuilder.DefineField("value__", underlyingType, FieldAttributes.Public | FieldAttributes.SpecialName | FieldAttributes.RTSpecialName); } -#if !FEATURE_CORECLR - void _EnumBuilder.GetTypeInfoCount(out uint pcTInfo) - { - throw new NotImplementedException(); - } - - void _EnumBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) - { - throw new NotImplementedException(); - } - - void _EnumBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) - { - throw new NotImplementedException(); - } - - void _EnumBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) - { - throw new NotImplementedException(); - } -#endif - - /***************************************************** * * private data members diff --git a/src/mscorlib/src/System/Reflection/Emit/EventBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/EventBuilder.cs index 42a5252102..449b20824c 100644 --- a/src/mscorlib/src/System/Reflection/Emit/EventBuilder.cs +++ b/src/mscorlib/src/System/Reflection/Emit/EventBuilder.cs @@ -24,7 +24,6 @@ namespace System.Reflection.Emit { // A EventBuilder is always associated with a TypeBuilder. The TypeBuilder.DefineEvent // method will return a new EventBuilder to a client. // - [HostProtection(MayLeakOnAbort = true)] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_EventBuilder))] [System.Runtime.InteropServices.ComVisible(true)] @@ -58,12 +57,11 @@ namespace System.Reflection.Emit { return m_evToken; } - [System.Security.SecurityCritical] // auto-generated private void SetMethodSemantics(MethodBuilder mdBuilder, MethodSemanticsAttributes semantics) { if (mdBuilder == null) { - throw new ArgumentNullException("mdBuilder"); + throw new ArgumentNullException(nameof(mdBuilder)); } Contract.EndContractBlock(); @@ -75,25 +73,21 @@ namespace System.Reflection.Emit { mdBuilder.GetToken().Token); } - [System.Security.SecuritySafeCritical] // auto-generated public void SetAddOnMethod(MethodBuilder mdBuilder) { SetMethodSemantics(mdBuilder, MethodSemanticsAttributes.AddOn); } - [System.Security.SecuritySafeCritical] // auto-generated public void SetRemoveOnMethod(MethodBuilder mdBuilder) { SetMethodSemantics(mdBuilder, MethodSemanticsAttributes.RemoveOn); } - [System.Security.SecuritySafeCritical] // auto-generated public void SetRaiseMethod(MethodBuilder mdBuilder) { SetMethodSemantics(mdBuilder, MethodSemanticsAttributes.Fire); } - [System.Security.SecuritySafeCritical] // auto-generated public void AddOtherMethod(MethodBuilder mdBuilder) { SetMethodSemantics(mdBuilder, MethodSemanticsAttributes.Other); @@ -101,18 +95,13 @@ namespace System.Reflection.Emit { // Use this function if client decides to form the custom attribute blob themselves -#if FEATURE_CORECLR -[System.Security.SecurityCritical] // auto-generated -#else -[System.Security.SecuritySafeCritical] -#endif [System.Runtime.InteropServices.ComVisible(true)] public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { if (con == null) - throw new ArgumentNullException("con"); + throw new ArgumentNullException(nameof(con)); if (binaryAttribute == null) - throw new ArgumentNullException("binaryAttribute"); + throw new ArgumentNullException(nameof(binaryAttribute)); Contract.EndContractBlock(); m_type.ThrowIfCreated(); @@ -125,41 +114,17 @@ namespace System.Reflection.Emit { } // Use this function if client wishes to build CustomAttribute using CustomAttributeBuilder - [System.Security.SecuritySafeCritical] // auto-generated public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { if (customBuilder == null) { - throw new ArgumentNullException("customBuilder"); + throw new ArgumentNullException(nameof(customBuilder)); } Contract.EndContractBlock(); m_type.ThrowIfCreated(); customBuilder.CreateCustomAttribute(m_module, m_evToken.Token); } -#if !FEATURE_CORECLR - void _EventBuilder.GetTypeInfoCount(out uint pcTInfo) - { - throw new NotImplementedException(); - } - - void _EventBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) - { - throw new NotImplementedException(); - } - - void _EventBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) - { - throw new NotImplementedException(); - } - - void _EventBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) - { - throw new NotImplementedException(); - } -#endif - - // These are package private so that TypeBuilder can access them. private String m_name; // The name of the event private EventToken m_evToken; // The token of this event @@ -167,8 +132,4 @@ namespace System.Reflection.Emit { private EventAttributes m_attributes; private TypeBuilder m_type; } - - - - } diff --git a/src/mscorlib/src/System/Reflection/Emit/FieldBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/FieldBuilder.cs index 0f2de5be43..595d60ada0 100644 --- a/src/mscorlib/src/System/Reflection/Emit/FieldBuilder.cs +++ b/src/mscorlib/src/System/Reflection/Emit/FieldBuilder.cs @@ -13,7 +13,6 @@ namespace System.Reflection.Emit using System.Security.Permissions; using System.Diagnostics.Contracts; - [HostProtection(MayLeakOnAbort = true)] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_FieldBuilder))] [System.Runtime.InteropServices.ComVisible(true)] @@ -29,21 +28,20 @@ namespace System.Reflection.Emit #endregion #region Constructor - [System.Security.SecurityCritical] // auto-generated internal FieldBuilder(TypeBuilder typeBuilder, String fieldName, Type type, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers, FieldAttributes attributes) { if (fieldName == null) - throw new ArgumentNullException("fieldName"); + throw new ArgumentNullException(nameof(fieldName)); if (fieldName.Length == 0) - throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "fieldName"); + throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(fieldName)); if (fieldName[0] == '\0') - throw new ArgumentException(Environment.GetResourceString("Argument_IllegalName"), "fieldName"); + throw new ArgumentException(Environment.GetResourceString("Argument_IllegalName"), nameof(fieldName)); if (type == null) - throw new ArgumentNullException("type"); + throw new ArgumentNullException(nameof(type)); if (type == typeof(void)) throw new ArgumentException(Environment.GetResourceString("Argument_BadFieldType")); @@ -69,7 +67,6 @@ namespace System.Reflection.Emit #endregion #region Internal Members - [System.Security.SecurityCritical] // auto-generated internal void SetData(byte[] data, int size) { ModuleBuilder.SetFieldRVAContent(m_typeBuilder.GetModuleBuilder().GetNativeHandle(), m_tkField.Token, data, size); @@ -181,11 +178,6 @@ namespace System.Reflection.Emit return m_tkField; } - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #else - [System.Security.SecuritySafeCritical] - #endif public void SetOffset(int iOffset) { m_typeBuilder.ThrowIfCreated(); @@ -193,12 +185,11 @@ namespace System.Reflection.Emit TypeBuilder.SetFieldLayoutOffset(m_typeBuilder.GetModuleBuilder().GetNativeHandle(), GetToken().Token, iOffset); } - [System.Security.SecuritySafeCritical] // auto-generated [Obsolete("An alternate API is available: Emit the MarshalAs custom attribute instead. http://go.microsoft.com/fwlink/?linkid=14202")] public void SetMarshal(UnmanagedMarshal unmanagedMarshal) { if (unmanagedMarshal == null) - throw new ArgumentNullException("unmanagedMarshal"); + throw new ArgumentNullException(nameof(unmanagedMarshal)); Contract.EndContractBlock(); m_typeBuilder.ThrowIfCreated(); @@ -208,7 +199,6 @@ namespace System.Reflection.Emit TypeBuilder.SetFieldMarshal(m_typeBuilder.GetModuleBuilder().GetNativeHandle(), GetToken().Token, ubMarshal, ubMarshal.Length); } - [System.Security.SecuritySafeCritical] // auto-generated public void SetConstant(Object defaultValue) { m_typeBuilder.ThrowIfCreated(); @@ -217,19 +207,14 @@ namespace System.Reflection.Emit } -#if FEATURE_CORECLR -[System.Security.SecurityCritical] // auto-generated -#else -[System.Security.SecuritySafeCritical] -#endif [System.Runtime.InteropServices.ComVisible(true)] public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { if (con == null) - throw new ArgumentNullException("con"); + throw new ArgumentNullException(nameof(con)); if (binaryAttribute == null) - throw new ArgumentNullException("binaryAttribute"); + throw new ArgumentNullException(nameof(binaryAttribute)); Contract.EndContractBlock(); ModuleBuilder module = m_typeBuilder.Module as ModuleBuilder; @@ -240,11 +225,10 @@ namespace System.Reflection.Emit m_tkField.Token, module.GetConstructorToken(con).Token, binaryAttribute, false, false); } - [System.Security.SecuritySafeCritical] // auto-generated public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { if (customBuilder == null) - throw new ArgumentNullException("customBuilder"); + throw new ArgumentNullException(nameof(customBuilder)); Contract.EndContractBlock(); m_typeBuilder.ThrowIfCreated(); @@ -255,27 +239,5 @@ namespace System.Reflection.Emit } #endregion - -#if !FEATURE_CORECLR - void _FieldBuilder.GetTypeInfoCount(out uint pcTInfo) - { - throw new NotImplementedException(); - } - - void _FieldBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) - { - throw new NotImplementedException(); - } - - void _FieldBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) - { - throw new NotImplementedException(); - } - - void _FieldBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) - { - throw new NotImplementedException(); - } -#endif } } diff --git a/src/mscorlib/src/System/Reflection/Emit/FlowControl.cs b/src/mscorlib/src/System/Reflection/Emit/FlowControl.cs index 5bfe5bb7bb..31bb564cf4 100644 --- a/src/mscorlib/src/System/Reflection/Emit/FlowControl.cs +++ b/src/mscorlib/src/System/Reflection/Emit/FlowControl.cs @@ -26,11 +26,8 @@ public enum FlowControl Cond_Branch = 3, Meta = 4, Next = 5, -#if !FEATURE_CORECLR - /// <internalonly/> [Obsolete("This API has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")] Phi = 6, -#endif Return = 7, Throw = 8, } diff --git a/src/mscorlib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs index bcf70dbe46..6987ea139d 100644 --- a/src/mscorlib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs +++ b/src/mscorlib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs @@ -212,9 +212,6 @@ namespace System.Reflection.Emit #endregion #region Public Members - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { m_type.SetGenParamCustomAttribute(con, binaryAttribute); diff --git a/src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs b/src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs index 15dece9fcb..ed0763bfda 100644 --- a/src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs +++ b/src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs @@ -7,12 +7,12 @@ namespace System.Reflection.Emit { using System; - using TextWriter = System.IO.TextWriter; using System.Diagnostics.SymbolStore; using System.Runtime.InteropServices; using System.Reflection; using System.Security.Permissions; using System.Globalization; + using System.Diagnostics; using System.Diagnostics.Contracts; [ClassInterface(ClassInterfaceType.None)] @@ -210,20 +210,17 @@ namespace System.Reflection.Emit } } - [System.Security.SecurityCritical] // auto-generated private int GetMethodToken(MethodBase method, Type[] optionalParameterTypes, bool useMethodDef) { return ((ModuleBuilder)m_methodBuilder.Module).GetMethodTokenInternal(method, optionalParameterTypes, useMethodDef); } - [System.Security.SecurityCritical] // auto-generated internal virtual SignatureHelper GetMemberRefSignature(CallingConventions call, Type returnType, Type[] parameterTypes, Type[] optionalParameterTypes) { return GetMemberRefSignature(call, returnType, parameterTypes, optionalParameterTypes, 0); } - [System.Security.SecurityCritical] // auto-generated private SignatureHelper GetMemberRefSignature(CallingConventions call, Type returnType, Type[] parameterTypes, Type[] optionalParameterTypes, int cGenericParameters) { @@ -414,7 +411,7 @@ namespace System.Reflection.Emit { if (m_RelocFixupCount == 0) { - Contract.Assert(m_RelocFixupList == null); + Debug.Assert(m_RelocFixupList == null); return null; } @@ -472,11 +469,10 @@ namespace System.Reflection.Emit PutInteger4(arg); } - [System.Security.SecuritySafeCritical] // auto-generated public virtual void Emit(OpCode opcode, MethodInfo meth) { if (meth == null) - throw new ArgumentNullException("meth"); + throw new ArgumentNullException(nameof(meth)); Contract.EndContractBlock(); if (opcode.Equals(OpCodes.Call) || opcode.Equals(OpCodes.Callvirt) || opcode.Equals(OpCodes.Newobj)) @@ -504,7 +500,6 @@ namespace System.Reflection.Emit } - [System.Security.SecuritySafeCritical] // auto-generated public virtual void EmitCalli(OpCode opcode, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, Type[] optionalParameterTypes) { @@ -593,14 +588,13 @@ namespace System.Reflection.Emit PutInteger4(modBuilder.GetSignatureToken(sig).Token); } - [System.Security.SecuritySafeCritical] // auto-generated public virtual void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[] optionalParameterTypes) { if (methodInfo == null) - throw new ArgumentNullException("methodInfo"); + throw new ArgumentNullException(nameof(methodInfo)); if (!(opcode.Equals(OpCodes.Call) || opcode.Equals(OpCodes.Callvirt) || opcode.Equals(OpCodes.Newobj))) - throw new ArgumentException(Environment.GetResourceString("Argument_NotMethodCallOpcode"), "opcode"); + throw new ArgumentException(Environment.GetResourceString("Argument_NotMethodCallOpcode"), nameof(opcode)); Contract.EndContractBlock(); @@ -634,7 +628,7 @@ namespace System.Reflection.Emit public virtual void Emit(OpCode opcode, SignatureHelper signature) { if (signature == null) - throw new ArgumentNullException("signature"); + throw new ArgumentNullException(nameof(signature)); Contract.EndContractBlock(); int stackchange = 0; @@ -653,7 +647,7 @@ namespace System.Reflection.Emit // SignatureHelper. if (opcode.StackBehaviourPop == StackBehaviour.Varpop) { - Contract.Assert(opcode.Equals(OpCodes.Calli), + Debug.Assert(opcode.Equals(OpCodes.Calli), "Unexpected opcode encountered for StackBehaviour VarPop."); // Pop the arguments.. stackchange -= signature.ArgumentCount; @@ -666,12 +660,11 @@ namespace System.Reflection.Emit PutInteger4(tempVal); } - [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(true)] public virtual void Emit(OpCode opcode, ConstructorInfo con) { if (con == null) - throw new ArgumentNullException("con"); + throw new ArgumentNullException(nameof(con)); Contract.EndContractBlock(); int stackchange = 0; @@ -687,7 +680,7 @@ namespace System.Reflection.Emit if (opcode.StackBehaviourPush == StackBehaviour.Varpush) { // Instruction must be one of call or callvirt. - Contract.Assert(opcode.Equals(OpCodes.Call) || + Debug.Assert(opcode.Equals(OpCodes.Call) || opcode.Equals(OpCodes.Callvirt), "Unexpected opcode encountered for StackBehaviour of VarPush."); stackchange++; @@ -695,7 +688,7 @@ namespace System.Reflection.Emit if (opcode.StackBehaviourPop == StackBehaviour.Varpop) { // Instruction must be one of call, callvirt or newobj. - Contract.Assert(opcode.Equals(OpCodes.Call) || + Debug.Assert(opcode.Equals(OpCodes.Call) || opcode.Equals(OpCodes.Callvirt) || opcode.Equals(OpCodes.Newobj), "Unexpected opcode encountered for StackBehaviour of VarPop."); @@ -710,7 +703,6 @@ namespace System.Reflection.Emit PutInteger4(tk); } - [System.Security.SecuritySafeCritical] // auto-generated public virtual void Emit(OpCode opcode, Type cls) { // Puts opcode onto the stream and then the metadata token represented @@ -750,7 +742,6 @@ namespace System.Reflection.Emit m_ILStream[m_length++] = (byte) (arg>>56); } - [System.Security.SecuritySafeCritical] // auto-generated unsafe public virtual void Emit(OpCode opcode, float arg) { EnsureCapacity(7); InternalEmit(opcode); @@ -761,7 +752,6 @@ namespace System.Reflection.Emit m_ILStream[m_length++] = (byte) (tempVal>>24); } - [System.Security.SecuritySafeCritical] // auto-generated unsafe public virtual void Emit(OpCode opcode, double arg) { EnsureCapacity(11); InternalEmit(opcode); @@ -805,7 +795,7 @@ namespace System.Reflection.Emit public virtual void Emit(OpCode opcode, Label[] labels) { if (labels == null) - throw new ArgumentNullException("labels"); + throw new ArgumentNullException(nameof(labels)); Contract.EndContractBlock(); // Emitting a switch table @@ -854,13 +844,13 @@ namespace System.Reflection.Emit if (local == null) { - throw new ArgumentNullException("local"); + throw new ArgumentNullException(nameof(local)); } Contract.EndContractBlock(); int tempVal = local.GetLocalIndex(); if (local.GetMethodBuilder() != m_methodBuilder) { - throw new ArgumentException(Environment.GetResourceString("Argument_UnmatchedMethodForLocal"), "local"); + throw new ArgumentException(Environment.GetResourceString("Argument_UnmatchedMethodForLocal"), nameof(local)); } // If the instruction is a ldloc, ldloca a stloc, morph it to the optimal form. if (opcode.Equals(OpCodes.Ldloc)) @@ -1020,7 +1010,7 @@ namespace System.Reflection.Emit public virtual void BeginExceptFilterBlock() { - // Begins a eception filter block. Emits a branch instruction to the end of the current exception block. + // Begins an exception filter block. Emits a branch instruction to the end of the current exception block. if (m_currExcStackCount == 0) throw new NotSupportedException(Environment.GetResourceString("Argument_NotInExceptionBlock")); @@ -1051,7 +1041,7 @@ namespace System.Reflection.Emit } else { // execute this branch if previous clause is Catch or Fault if (exceptionType==null) { - throw new ArgumentNullException("exceptionType"); + throw new ArgumentNullException(nameof(exceptionType)); } Label endLabel = current.GetEndLabel(); @@ -1153,7 +1143,7 @@ namespace System.Reflection.Emit // Emits the il to throw an exception if (excType==null) { - throw new ArgumentNullException("excType"); + throw new ArgumentNullException(nameof(excType)); } if (!excType.IsSubclassOf(typeof(Exception)) && excType!=typeof(Exception)) { @@ -1212,9 +1202,9 @@ namespace System.Reflection.Emit throw new ArgumentException(Environment.GetResourceString("NotSupported_OutputStreamUsingTypeBuilder")); } parameterTypes[0] = (Type)cls; - MethodInfo mi = typeof(TextWriter).GetMethod("WriteLine", parameterTypes); + MethodInfo mi = prop.ReturnType.GetMethod("WriteLine", parameterTypes); if (mi==null) { - throw new ArgumentException(Environment.GetResourceString("Argument_EmitWriteLineType"), "localBuilder"); + throw new ArgumentException(Environment.GetResourceString("Argument_EmitWriteLineType"), nameof(localBuilder)); } Emit(OpCodes.Callvirt, mi); @@ -1231,7 +1221,7 @@ namespace System.Reflection.Emit if (fld == null) { - throw new ArgumentNullException("fld"); + throw new ArgumentNullException(nameof(fld)); } Contract.EndContractBlock(); @@ -1250,9 +1240,9 @@ namespace System.Reflection.Emit throw new NotSupportedException(Environment.GetResourceString("NotSupported_OutputStreamUsingTypeBuilder")); } parameterTypes[0] = (Type)cls; - MethodInfo mi = typeof(TextWriter).GetMethod("WriteLine", parameterTypes); + MethodInfo mi = prop.ReturnType.GetMethod("WriteLine", parameterTypes); if (mi==null) { - throw new ArgumentException(Environment.GetResourceString("Argument_EmitWriteLineType"), "fld"); + throw new ArgumentException(Environment.GetResourceString("Argument_EmitWriteLineType"), nameof(fld)); } Emit(OpCodes.Callvirt, mi); } @@ -1283,7 +1273,7 @@ namespace System.Reflection.Emit } if (localType==null) { - throw new ArgumentNullException("localType"); + throw new ArgumentNullException(nameof(localType)); } if (methodBuilder.m_bIsBaked) { @@ -1304,10 +1294,10 @@ namespace System.Reflection.Emit // for the current active lexical scope. if (usingNamespace == null) - throw new ArgumentNullException("usingNamespace"); + throw new ArgumentNullException(nameof(usingNamespace)); if (usingNamespace.Length == 0) - throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "usingNamespace"); + throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(usingNamespace)); Contract.EndContractBlock(); int index; @@ -1335,7 +1325,7 @@ namespace System.Reflection.Emit { if (startLine == 0 || startLine < 0 || endLine == 0 || endLine < 0) { - throw new ArgumentOutOfRangeException("startLine"); + throw new ArgumentOutOfRangeException(nameof(startLine)); } Contract.EndContractBlock(); m_LineNumberInfo.AddLineNumberInfo(document, m_length, startLine, startColumn, endLine, endColumn); @@ -1362,28 +1352,6 @@ namespace System.Reflection.Emit #endregion #endregion - -#if !FEATURE_CORECLR - void _ILGenerator.GetTypeInfoCount(out uint pcTInfo) - { - throw new NotImplementedException(); - } - - void _ILGenerator.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) - { - throw new NotImplementedException(); - } - - void _ILGenerator.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) - { - throw new NotImplementedException(); - } - - void _ILGenerator.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) - { - throw new NotImplementedException(); - } -#endif } internal struct __FixupData @@ -1472,7 +1440,7 @@ namespace System.Reflection.Emit m_catchAddr[m_currentCatch] = -1; if (m_currentCatch > 0) { - Contract.Assert(m_catchEndAddr[m_currentCatch-1] == -1,"m_catchEndAddr[m_currentCatch-1] == -1"); + Debug.Assert(m_catchEndAddr[m_currentCatch-1] == -1,"m_catchEndAddr[m_currentCatch-1] == -1"); m_catchEndAddr[m_currentCatch-1] = catchorfilterAddr; } } @@ -1489,7 +1457,7 @@ namespace System.Reflection.Emit { if (m_type[m_currentCatch] != Filter) { - Contract.Assert(m_catchEndAddr[m_currentCatch-1] == -1,"m_catchEndAddr[m_currentCatch-1] == -1"); + Debug.Assert(m_catchEndAddr[m_currentCatch-1] == -1,"m_catchEndAddr[m_currentCatch-1] == -1"); m_catchEndAddr[m_currentCatch-1] = catchEndAddr; } } @@ -1531,9 +1499,9 @@ namespace System.Reflection.Emit } internal void Done(int endAddr) { - Contract.Assert(m_currentCatch > 0,"m_currentCatch > 0"); - Contract.Assert(m_catchAddr[m_currentCatch-1] > 0,"m_catchAddr[m_currentCatch-1] > 0"); - Contract.Assert(m_catchEndAddr[m_currentCatch-1] == -1,"m_catchEndAddr[m_currentCatch-1] == -1"); + Debug.Assert(m_currentCatch > 0,"m_currentCatch > 0"); + Debug.Assert(m_catchAddr[m_currentCatch-1] > 0,"m_catchAddr[m_currentCatch-1] > 0"); + Debug.Assert(m_catchEndAddr[m_currentCatch-1] == -1,"m_catchEndAddr[m_currentCatch-1] == -1"); m_catchEndAddr[m_currentCatch-1] = endAddr; m_currentState = State_Done; } @@ -1596,8 +1564,8 @@ namespace System.Reflection.Emit // not having a nesting relation. internal bool IsInner(__ExceptionInfo exc) { Contract.Requires(exc != null); - Contract.Assert(m_currentCatch > 0,"m_currentCatch > 0"); - Contract.Assert(exc.m_currentCatch > 0,"exc.m_currentCatch > 0"); + Debug.Assert(m_currentCatch > 0,"m_currentCatch > 0"); + Debug.Assert(exc.m_currentCatch > 0,"exc.m_currentCatch > 0"); int exclast = exc.m_currentCatch - 1; int last = m_currentCatch - 1; @@ -1606,7 +1574,7 @@ namespace System.Reflection.Emit return true; else if (exc.m_catchEndAddr[exclast] == m_catchEndAddr[last]) { - Contract.Assert(exc.GetEndAddress() != GetEndAddress(), + Debug.Assert(exc.GetEndAddress() != GetEndAddress(), "exc.GetEndAddress() != GetEndAddress()"); if (exc.GetEndAddress() > GetEndAddress()) return true; @@ -1762,9 +1730,6 @@ namespace System.Reflection.Emit } } - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif internal void EmitScopeTree(ISymbolWriter symWriter) { int i; @@ -1821,7 +1786,7 @@ namespace System.Reflection.Emit // make sure that arrays are large enough to hold addition info i = FindDocument(document); - Contract.Assert(i < m_DocumentCount, "Bad document look up!"); + Debug.Assert(i < m_DocumentCount, "Bad document look up!"); m_Documents[i].AddLineNumberInfo(document, iOffset, iStartLine, iStartColumn, iEndLine, iEndColumn); } @@ -1874,9 +1839,6 @@ namespace System.Reflection.Emit } } - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif internal void EmitLineNumberInfo(ISymbolWriter symWriter) { for (int i = 0; i < m_DocumentCount; i++) @@ -1912,7 +1874,7 @@ namespace System.Reflection.Emit int iEndLine, int iEndColumn) { - Contract.Assert(document == m_document, "Bad document look up!"); + Debug.Assert(document == m_document, "Bad document look up!"); // make sure that arrays are large enough to hold addition info EnsureCapacity(); @@ -1968,9 +1930,6 @@ namespace System.Reflection.Emit } } - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif internal void EmitLineNumberInfo(ISymbolWriter symWriter) { int[] iOffsetsTemp; diff --git a/src/mscorlib/src/System/Reflection/Emit/ISymWrapperCore.cs b/src/mscorlib/src/System/Reflection/Emit/ISymWrapperCore.cs index 00fdd00315..a737895829 100644 --- a/src/mscorlib/src/System/Reflection/Emit/ISymWrapperCore.cs +++ b/src/mscorlib/src/System/Reflection/Emit/ISymWrapperCore.cs @@ -2,10 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -#if FEATURE_CORECLR - namespace System.Reflection.Emit { using System; @@ -14,7 +10,6 @@ namespace System.Reflection.Emit using System.Runtime.CompilerServices; using System.Diagnostics.SymbolStore; - //----------------------------------------------------------------------------------- // On Telesto, we don't ship the ISymWrapper.dll assembly. However, ReflectionEmit // relies on that assembly to write out managed PDBs. @@ -58,9 +53,6 @@ namespace System.Reflection.Emit //------------------------------------------------------------------------------ // Ctor //------------------------------------------------------------------------------ - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif internal SymDocumentWriter(PunkSafeHandle pDocumentWriterSafeHandle) { m_pDocumentWriterSafeHandle = pDocumentWriterSafeHandle; @@ -72,9 +64,6 @@ namespace System.Reflection.Emit //------------------------------------------------------------------------------ // Returns the underlying ISymUnmanagedDocumentWriter* (as a safehandle.) //------------------------------------------------------------------------------ - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif internal PunkSafeHandle GetUnmanaged() { return m_pDocumentWriterSafeHandle; @@ -97,9 +86,6 @@ namespace System.Reflection.Emit //------------------------------------------------------------------------------ // SetCheckSum() wrapper //------------------------------------------------------------------------------ - #if FEATURE_CORECLR - [System.Security.SecuritySafeCritical] - #endif void ISymbolDocumentWriter.SetCheckSum(Guid algorithmId, byte [] checkSum) { int hr = m_vtable.SetCheckSum(m_pDocWriter, algorithmId, (uint)checkSum.Length, checkSum); @@ -109,7 +95,6 @@ namespace System.Reflection.Emit } } - [System.Security.SecurityCritical] private delegate int DSetCheckSum(ISymUnmanagedDocumentWriter * pThis, Guid algorithmId, uint checkSumSize, [In] byte[] checkSum); //------------------------------------------------------------------------------ @@ -117,7 +102,6 @@ namespace System.Reflection.Emit // exactly. If a member is declared as an IntPtr rather than a delegate, it means // we don't call that particular member. //------------------------------------------------------------------------------ - [System.Security.SecurityCritical] [StructLayout(LayoutKind.Sequential)] private struct ISymUnmanagedDocumentWriterVTable { @@ -126,9 +110,6 @@ namespace System.Reflection.Emit internal IntPtr Release; internal IntPtr SetSource; - #if FEATURE_CORECLR - [System.Security.SecurityCritical] - #endif internal DSetCheckSum SetCheckSum; } @@ -136,7 +117,6 @@ namespace System.Reflection.Emit // This layout must match the (start) of the unmanaged ISymUnmanagedDocumentWriter // COM object. //------------------------------------------------------------------------------ - [System.Security.SecurityCritical] [StructLayout(LayoutKind.Sequential)] private struct ISymUnmanagedDocumentWriter { @@ -146,19 +126,14 @@ namespace System.Reflection.Emit //------------------------------------------------------------------------------ // Stores underlying ISymUnmanagedDocumentWriter* pointer (wrapped in a safehandle.) //------------------------------------------------------------------------------ - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif private PunkSafeHandle m_pDocumentWriterSafeHandle; - [SecurityCritical] private ISymUnmanagedDocumentWriter * m_pDocWriter; //------------------------------------------------------------------------------ // Stores the "managed vtable" (actually a structure full of delegates that // P/Invoke to the corresponding unmanaged COM methods.) //------------------------------------------------------------------------------ - [SecurityCritical] private ISymUnmanagedDocumentWriterVTable m_vtable; @@ -212,9 +187,6 @@ namespace System.Reflection.Emit //------------------------------------------------------------------------------ // DefineDocument() wrapper //------------------------------------------------------------------------------ - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif ISymbolDocumentWriter ISymbolWriter.DefineDocument(String url, Guid language, Guid languageVendor, @@ -237,9 +209,6 @@ namespace System.Reflection.Emit //------------------------------------------------------------------------------ // SetUserEntryPoint() wrapper //------------------------------------------------------------------------------ - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif void ISymbolWriter.SetUserEntryPoint(SymbolToken entryMethod) { int hr = m_vtable.SetUserEntryPoint(m_pWriter, entryMethod.GetToken()); @@ -252,9 +221,6 @@ namespace System.Reflection.Emit //------------------------------------------------------------------------------ // OpenMethod() wrapper //------------------------------------------------------------------------------ - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif void ISymbolWriter.OpenMethod(SymbolToken method) { int hr = m_vtable.OpenMethod(m_pWriter, method.GetToken()); @@ -267,9 +233,6 @@ namespace System.Reflection.Emit //------------------------------------------------------------------------------ // CloseMethod() wrapper //------------------------------------------------------------------------------ - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif void ISymbolWriter.CloseMethod() { int hr = m_vtable.CloseMethod(m_pWriter); @@ -282,9 +245,6 @@ namespace System.Reflection.Emit //------------------------------------------------------------------------------ // DefineSequencePoints() wrapper //------------------------------------------------------------------------------ - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif void ISymbolWriter.DefineSequencePoints(ISymbolDocumentWriter document, int[] offsets, int[] lines, @@ -344,9 +304,6 @@ namespace System.Reflection.Emit //------------------------------------------------------------------------------ // OpenScope() wrapper //------------------------------------------------------------------------------ - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif int ISymbolWriter.OpenScope(int startOffset) { int ret; @@ -361,9 +318,6 @@ namespace System.Reflection.Emit //------------------------------------------------------------------------------ // CloseScope() wrapper //------------------------------------------------------------------------------ - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif void ISymbolWriter.CloseScope(int endOffset) { int hr = m_vtable.CloseScope(m_pWriter, endOffset); @@ -388,9 +342,6 @@ namespace System.Reflection.Emit //------------------------------------------------------------------------------ // DefineLocalVariable() wrapper //------------------------------------------------------------------------------ - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif void ISymbolWriter.DefineLocalVariable(String name, FieldAttributes attributes, byte[] signature, @@ -476,9 +427,6 @@ namespace System.Reflection.Emit //------------------------------------------------------------------------------ // SetSymAttribute() wrapper //------------------------------------------------------------------------------ - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif void ISymbolWriter.SetSymAttribute(SymbolToken parent, String name, byte[] data) { int hr = m_vtable.SetSymAttribute(m_pWriter, parent.GetToken(), name, data.Length, data); @@ -515,9 +463,6 @@ namespace System.Reflection.Emit //------------------------------------------------------------------------------ // UsingNamespace() wrapper //------------------------------------------------------------------------------ - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif void ISymbolWriter.UsingNamespace(String name) { int hr = m_vtable.UsingNamespace(m_pWriter, name); @@ -557,9 +502,6 @@ namespace System.Reflection.Emit // with the real ISymWrapper.dll, ISymWrapper performs *no* Release (or AddRef) on pointers // furnished through SetUnderlyingWriter. Lifetime management is entirely up to the caller. //------------------------------------------------------------------------------ - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif internal void InternalSetUnderlyingWriter(IntPtr ppUnderlyingWriter) { m_pWriter = *((ISymUnmanagedWriter**)ppUnderlyingWriter); @@ -569,7 +511,6 @@ namespace System.Reflection.Emit //------------------------------------------------------------------------------ // Define delegates for the unmanaged COM methods we invoke. //------------------------------------------------------------------------------ - [System.Security.SecurityCritical] private delegate int DInitialize(ISymUnmanagedWriter* pthis, IntPtr emitter, //IUnknown* [MarshalAs(UnmanagedType.LPWStr)] String filename, //WCHAR* @@ -577,7 +518,6 @@ namespace System.Reflection.Emit [MarshalAs(UnmanagedType.Bool)] bool fFullBuild ); - [System.Security.SecurityCritical] private delegate int DDefineDocument(ISymUnmanagedWriter* pthis, [MarshalAs(UnmanagedType.LPWStr)] String url, [In] ref Guid language, @@ -586,14 +526,10 @@ namespace System.Reflection.Emit [Out] out PunkSafeHandle ppsymUnmanagedDocumentWriter ); - [System.Security.SecurityCritical] private delegate int DSetUserEntryPoint(ISymUnmanagedWriter* pthis, int entryMethod); - [System.Security.SecurityCritical] private delegate int DOpenMethod(ISymUnmanagedWriter* pthis, int entryMethod); - [System.Security.SecurityCritical] private delegate int DCloseMethod(ISymUnmanagedWriter* pthis); - [System.Security.SecurityCritical] private delegate int DDefineSequencePoints(ISymUnmanagedWriter* pthis, PunkSafeHandle document, int spCount, @@ -603,15 +539,11 @@ namespace System.Reflection.Emit [In] int[] endLines, [In] int[] endColumns); - [System.Security.SecurityCritical] private delegate int DOpenScope(ISymUnmanagedWriter* pthis, int startOffset, [Out] out int pretval); - [System.Security.SecurityCritical] private delegate int DCloseScope(ISymUnmanagedWriter* pthis, int endOffset); - [System.Security.SecurityCritical] private delegate int DSetScopeRange(ISymUnmanagedWriter* pthis, int scopeID, int startOffset, int endOffset); - [System.Security.SecurityCritical] private delegate int DDefineLocalVariable(ISymUnmanagedWriter* pthis, [MarshalAs(UnmanagedType.LPWStr)] String name, int attributes, @@ -625,10 +557,8 @@ namespace System.Reflection.Emit int endOffset ); - [System.Security.SecurityCritical] private delegate int DClose(ISymUnmanagedWriter* pthis); - [System.Security.SecurityCritical] private delegate int DSetSymAttribute(ISymUnmanagedWriter* pthis, int parent, [MarshalAs(UnmanagedType.LPWStr)] String name, @@ -637,11 +567,8 @@ namespace System.Reflection.Emit ); - [System.Security.SecurityCritical] private delegate int DOpenNamespace(ISymUnmanagedWriter* pthis, [MarshalAs(UnmanagedType.LPWStr)] String name); - [System.Security.SecurityCritical] private delegate int DCloseNamespace(ISymUnmanagedWriter* pthis); - [System.Security.SecurityCritical] private delegate int DUsingNamespace(ISymUnmanagedWriter* pthis, [MarshalAs(UnmanagedType.LPWStr)] String name); @@ -658,77 +585,32 @@ namespace System.Reflection.Emit internal IntPtr AddRef; internal IntPtr Release; - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif internal DDefineDocument DefineDocument; - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif internal DSetUserEntryPoint SetUserEntryPoint; - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif internal DOpenMethod OpenMethod; - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif internal DCloseMethod CloseMethod; - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif internal DOpenScope OpenScope; - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif internal DCloseScope CloseScope; - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif internal DSetScopeRange SetScopeRange; - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif internal DDefineLocalVariable DefineLocalVariable; internal IntPtr DefineParameter; internal IntPtr DefineField; internal IntPtr DefineGlobalVariable; - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif internal DClose Close; - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif internal DSetSymAttribute SetSymAttribute; - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif internal DOpenNamespace OpenNamespace; - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif internal DCloseNamespace CloseNamespace; - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif internal DUsingNamespace UsingNamespace; internal IntPtr SetMethodSourceRange; - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif internal DInitialize Initialize; internal IntPtr GetDebugInfo; - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif internal DDefineSequencePoints DefineSequencePoints; } @@ -749,7 +631,6 @@ namespace System.Reflection.Emit // As with the real ISymWrapper.dll, ISymWrapper performs *no* Release (or AddRef) on this pointer. // Managing lifetime is up to the caller (coreclr.dll). //------------------------------------------------------------------------------ - [SecurityCritical] private ISymUnmanagedWriter *m_pWriter; //------------------------------------------------------------------------------ @@ -778,20 +659,13 @@ namespace System.Reflection.Emit // // Had to make this a non-nested class since FCall's don't like to bind to nested classes. //-------------------------------------------------------------------------------------- - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif sealed class PunkSafeHandle : SafeHandle { - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif internal PunkSafeHandle() : base((IntPtr)0, true) { } - [SecurityCritical] override protected bool ReleaseHandle() { m_Release(handle); @@ -800,7 +674,6 @@ namespace System.Reflection.Emit public override bool IsInvalid { - [SecurityCritical] get { return handle == ((IntPtr)0); } } @@ -810,19 +683,10 @@ namespace System.Reflection.Emit [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern IntPtr nGetDReleaseTarget(); // FCall gets us the native DRelease target (so we don't need named dllexport from coreclr.dll) - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif static PunkSafeHandle() { m_Release = (DRelease)(Marshal.GetDelegateForFunctionPointer(nGetDReleaseTarget(), typeof(DRelease))); m_Release((IntPtr)0); // make one call to make sure the delegate is fully prepped before we're in the critical finalizer situation. } - } // PunkSafeHandle - } //namespace System.Reflection.Emit - - -#endif //FEATURE_CORECLR - diff --git a/src/mscorlib/src/System/Reflection/Emit/LocalBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/LocalBuilder.cs index 4008703ca7..a34d5ebe5d 100644 --- a/src/mscorlib/src/System/Reflection/Emit/LocalBuilder.cs +++ b/src/mscorlib/src/System/Reflection/Emit/LocalBuilder.cs @@ -124,28 +124,6 @@ namespace System.Reflection.Emit } } #endregion - -#if !FEATURE_CORECLR - void _LocalBuilder.GetTypeInfoCount(out uint pcTInfo) - { - throw new NotImplementedException(); - } - - void _LocalBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) - { - throw new NotImplementedException(); - } - - void _LocalBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) - { - throw new NotImplementedException(); - } - - void _LocalBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) - { - throw new NotImplementedException(); - } -#endif } } diff --git a/src/mscorlib/src/System/Reflection/Emit/MethodBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/MethodBuilder.cs index 015a73be09..654e166a05 100644 --- a/src/mscorlib/src/System/Reflection/Emit/MethodBuilder.cs +++ b/src/mscorlib/src/System/Reflection/Emit/MethodBuilder.cs @@ -16,12 +16,12 @@ namespace System.Reflection.Emit using System.Collections.Generic; using System.Security.Permissions; using System.Runtime.InteropServices; + using System.Diagnostics; using System.Diagnostics.Contracts; - [HostProtection(MayLeakOnAbort = true)] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_MethodBuilder))] -[System.Runtime.InteropServices.ComVisible(true)] + [System.Runtime.InteropServices.ComVisible(true)] public sealed class MethodBuilder : MethodInfo, _MethodBuilder { #region Private Data Members @@ -90,16 +90,16 @@ namespace System.Reflection.Emit ModuleBuilder mod, TypeBuilder type, bool bIsGlobalMethod) { if (name == null) - throw new ArgumentNullException("name"); + throw new ArgumentNullException(nameof(name)); if (name.Length == 0) - throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name"); + throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name)); if (name[0] == '\0') - throw new ArgumentException(Environment.GetResourceString("Argument_IllegalName"), "name"); + throw new ArgumentException(Environment.GetResourceString("Argument_IllegalName"), nameof(name)); if (mod == null) - throw new ArgumentNullException("mod"); + throw new ArgumentNullException(nameof(mod)); Contract.EndContractBlock(); if (parameterTypes != null) @@ -107,7 +107,7 @@ namespace System.Reflection.Emit foreach(Type t in parameterTypes) { if (t == null) - throw new ArgumentNullException("parameterTypes"); + throw new ArgumentNullException(nameof(parameterTypes)); } } @@ -196,14 +196,13 @@ namespace System.Reflection.Emit m_module.CheckContext(types); } - [System.Security.SecurityCritical] // auto-generated internal void CreateMethodBodyHelper(ILGenerator il) { // Sets the IL of the method. An ILGenerator is passed as an argument and the method // queries this instance to get all of the information which it needs. if (il == null) { - throw new ArgumentNullException("il"); + throw new ArgumentNullException(nameof(il)); } Contract.EndContractBlock(); @@ -367,7 +366,7 @@ namespace System.Reflection.Emit } else { - Contract.Assert(false, "We should never get here!"); + Debug.Assert(false, "We should never get here!"); return null; } } @@ -389,7 +388,6 @@ namespace System.Reflection.Emit return m_mdMethodFixups; } - [System.Security.SecurityCritical] // auto-generated internal SignatureHelper GetMethodSignature() { if (m_parameterTypes == null) @@ -480,7 +478,6 @@ namespace System.Reflection.Emit #endregion #region Object Overrides - [System.Security.SecuritySafeCritical] // auto-generated public override bool Equals(Object obj) { if (!(obj is MethodBuilder)) { return false; @@ -505,7 +502,6 @@ namespace System.Reflection.Emit return this.m_strName.GetHashCode(); } - [System.Security.SecuritySafeCritical] // auto-generated public override String ToString() { StringBuilder sb = new StringBuilder(1000); @@ -599,17 +595,17 @@ namespace System.Reflection.Emit public override bool IsSecurityCritical { - get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); } + get { return true; } } public override bool IsSecuritySafeCritical { - get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); } + get { return false; } } public override bool IsSecurityTransparent { - get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); } + get { return false; } } #endregion @@ -693,10 +689,10 @@ namespace System.Reflection.Emit public GenericTypeParameterBuilder[] DefineGenericParameters (params string[] names) { if (names == null) - throw new ArgumentNullException("names"); + throw new ArgumentNullException(nameof(names)); if (names.Length == 0) - throw new ArgumentException(Environment.GetResourceString("Arg_EmptyArray"), "names"); + throw new ArgumentException(Environment.GetResourceString("Arg_EmptyArray"), nameof(names)); Contract.EndContractBlock(); if (m_inst != null) @@ -704,7 +700,7 @@ namespace System.Reflection.Emit for (int i = 0; i < names.Length; i ++) if (names[i] == null) - throw new ArgumentNullException("names"); + throw new ArgumentNullException(nameof(names)); if (m_tkMethod.Token != 0) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MethodBuilderBaked")); @@ -721,7 +717,6 @@ namespace System.Reflection.Emit #endregion #region Public Members - [System.Security.SecuritySafeCritical] // auto-generated public MethodToken GetToken() { // We used to always "tokenize" a MethodBuilder when it is constructed. After change list 709498 @@ -767,16 +762,15 @@ namespace System.Reflection.Emit m_containingType.m_lastTokenizedMethod = i; } - Contract.Assert(currentMethod == this, "We should have found this method in m_containingType.m_listMethods"); - Contract.Assert(currentToken.Token != 0, "The token should not be 0"); + Debug.Assert(currentMethod == this, "We should have found this method in m_containingType.m_listMethods"); + Debug.Assert(currentToken.Token != 0, "The token should not be 0"); return currentToken; } - [System.Security.SecurityCritical] // auto-generated private MethodToken GetTokenNoLock() { - Contract.Assert(m_tkMethod.Token == 0, "m_tkMethod should not have been initialized"); + Debug.Assert(m_tkMethod.Token == 0, "m_tkMethod should not have been initialized"); int sigLength; byte[] sigBytes = GetMethodSignature().InternalGetSignature(out sigLength); @@ -841,7 +835,6 @@ namespace System.Reflection.Emit } - [System.Security.SecuritySafeCritical] // auto-generated public ParameterBuilder DefineParameter(int position, ParameterAttributes attributes, String strParamName) { if (position < 0) @@ -858,7 +851,6 @@ namespace System.Reflection.Emit return new ParameterBuilder(this, position, attributes, strParamName); } - [System.Security.SecuritySafeCritical] // auto-generated [Obsolete("An alternate API is available: Emit the MarshalAs custom attribute instead. http://go.microsoft.com/fwlink/?linkid=14202")] public void SetMarshal(UnmanagedMarshal unmanagedMarshal) { @@ -915,55 +907,15 @@ namespace System.Reflection.Emit m_symCustomAttrs.Add(new SymCustomAttr(name, data)); } -#if FEATURE_CAS_POLICY - [System.Security.SecuritySafeCritical] // auto-generated - public void AddDeclarativeSecurity(SecurityAction action, PermissionSet pset) - { - if (pset == null) - throw new ArgumentNullException("pset"); - Contract.EndContractBlock(); - - ThrowIfGeneric (); - -#pragma warning disable 618 - if (!Enum.IsDefined(typeof(SecurityAction), action) || - action == SecurityAction.RequestMinimum || - action == SecurityAction.RequestOptional || - action == SecurityAction.RequestRefuse) - { - throw new ArgumentOutOfRangeException("action"); - } -#pragma warning restore 618 - - // cannot declarative security after type is created - m_containingType.ThrowIfCreated(); - - // Translate permission set into serialized format (uses standard binary serialization format). - byte[] blob = null; - int length = 0; - if (!pset.IsEmpty()) - { - blob = pset.EncodeXml(); - length = blob.Length; - } - - // Write the blob into the metadata. - TypeBuilder.AddDeclarativeSecurity(m_module.GetNativeHandle(), MetadataTokenInternal, action, blob, length); - } -#endif // FEATURE_CAS_POLICY - - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif public void SetMethodBody(byte[] il, int maxStack, byte[] localSignature, IEnumerable<ExceptionHandler> exceptionHandlers, IEnumerable<int> tokenFixups) { if (il == null) { - throw new ArgumentNullException("il", Environment.GetResourceString("ArgumentNull_Array")); + throw new ArgumentNullException(nameof(il), Environment.GetResourceString("ArgumentNull_Array")); } if (maxStack < 0) { - throw new ArgumentOutOfRangeException("maxStack", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); + throw new ArgumentOutOfRangeException(nameof(maxStack), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); @@ -1056,9 +1008,6 @@ namespace System.Reflection.Emit /// <summary> /// Obsolete. /// </summary> - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif public void CreateMethodBody(byte[] il, int count) { ThrowIfGeneric(); @@ -1075,7 +1024,7 @@ namespace System.Reflection.Emit if (il != null && (count < 0 || count > il.Length)) { - throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_Index")); + throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_Index")); } if (il == null) @@ -1095,7 +1044,6 @@ namespace System.Reflection.Emit m_bIsBaked = true; } - [System.Security.SecuritySafeCritical] // auto-generated public void SetImplementationFlags(MethodImplAttributes attributes) { ThrowIfGeneric (); @@ -1158,7 +1106,6 @@ namespace System.Reflection.Emit public String Signature { - [System.Security.SecuritySafeCritical] // auto-generated get { return GetMethodSignature().ToString(); @@ -1166,18 +1113,13 @@ namespace System.Reflection.Emit } -#if FEATURE_CORECLR -[System.Security.SecurityCritical] // auto-generated -#else -[System.Security.SecuritySafeCritical] -#endif [System.Runtime.InteropServices.ComVisible(true)] public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { if (con == null) - throw new ArgumentNullException("con"); + throw new ArgumentNullException(nameof(con)); if (binaryAttribute == null) - throw new ArgumentNullException("binaryAttribute"); + throw new ArgumentNullException(nameof(binaryAttribute)); Contract.EndContractBlock(); ThrowIfGeneric(); @@ -1191,11 +1133,10 @@ namespace System.Reflection.Emit ParseCA(con, binaryAttribute); } - [System.Security.SecuritySafeCritical] // auto-generated public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { if (customBuilder == null) - throw new ArgumentNullException("customBuilder"); + throw new ArgumentNullException(nameof(customBuilder)); Contract.EndContractBlock(); ThrowIfGeneric(); @@ -1239,29 +1180,6 @@ namespace System.Reflection.Emit internal bool m_isDllImport = false; #endregion - -#if !FEATURE_CORECLR - void _MethodBuilder.GetTypeInfoCount(out uint pcTInfo) - { - throw new NotImplementedException(); - } - - void _MethodBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) - { - throw new NotImplementedException(); - } - - void _MethodBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) - { - throw new NotImplementedException(); - } - - void _MethodBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) - { - throw new NotImplementedException(); - } -#endif - } internal class LocalSymInfo @@ -1366,9 +1284,6 @@ namespace System.Reflection.Emit checked { m_iNameSpaceCount++; } } - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif internal virtual void EmitLocalSymInfo(ISymbolWriter symWriter) { int i; @@ -1468,51 +1383,51 @@ namespace System.Reflection.Emit { if (tryOffset < 0) { - throw new ArgumentOutOfRangeException("tryOffset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); + throw new ArgumentOutOfRangeException(nameof(tryOffset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (tryLength < 0) { - throw new ArgumentOutOfRangeException("tryLength", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); + throw new ArgumentOutOfRangeException(nameof(tryLength), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (filterOffset < 0) { - throw new ArgumentOutOfRangeException("filterOffset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); + throw new ArgumentOutOfRangeException(nameof(filterOffset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (handlerOffset < 0) { - throw new ArgumentOutOfRangeException("handlerOffset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); + throw new ArgumentOutOfRangeException(nameof(handlerOffset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (handlerLength < 0) { - throw new ArgumentOutOfRangeException("handlerLength", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); + throw new ArgumentOutOfRangeException(nameof(handlerLength), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if ((long)tryOffset + tryLength > Int32.MaxValue) { - throw new ArgumentOutOfRangeException("tryLength", Environment.GetResourceString("ArgumentOutOfRange_Range", 0, Int32.MaxValue - tryOffset)); + throw new ArgumentOutOfRangeException(nameof(tryLength), Environment.GetResourceString("ArgumentOutOfRange_Range", 0, Int32.MaxValue - tryOffset)); } if ((long)handlerOffset + handlerLength > Int32.MaxValue) { - throw new ArgumentOutOfRangeException("handlerLength", Environment.GetResourceString("ArgumentOutOfRange_Range", 0, Int32.MaxValue - handlerOffset)); + throw new ArgumentOutOfRangeException(nameof(handlerLength), Environment.GetResourceString("ArgumentOutOfRange_Range", 0, Int32.MaxValue - handlerOffset)); } // Other tokens migth also be invalid. We only check nil tokens as the implementation (SectEH_Emit in corhlpr.cpp) requires it, // and we can't check for valid tokens until the module is baked. if (kind == ExceptionHandlingClauseOptions.Clause && (exceptionTypeToken & 0x00FFFFFF) == 0) { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidTypeToken", exceptionTypeToken), "exceptionTypeToken"); + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidTypeToken", exceptionTypeToken), nameof(exceptionTypeToken)); } Contract.EndContractBlock(); if (!IsValidKind(kind)) { - throw new ArgumentOutOfRangeException("kind", Environment.GetResourceString("ArgumentOutOfRange_Enum")); + throw new ArgumentOutOfRangeException(nameof(kind), Environment.GetResourceString("ArgumentOutOfRange_Enum")); } m_tryStartOffset = tryOffset; @@ -1527,13 +1442,13 @@ namespace System.Reflection.Emit internal ExceptionHandler(int tryStartOffset, int tryEndOffset, int filterOffset, int handlerStartOffset, int handlerEndOffset, int kind, int exceptionTypeToken) { - Contract.Assert(tryStartOffset >= 0); - Contract.Assert(tryEndOffset >= 0); - Contract.Assert(filterOffset >= 0); - Contract.Assert(handlerStartOffset >= 0); - Contract.Assert(handlerEndOffset >= 0); - Contract.Assert(IsValidKind((ExceptionHandlingClauseOptions)kind)); - Contract.Assert(kind != (int)ExceptionHandlingClauseOptions.Clause || (exceptionTypeToken & 0x00FFFFFF) != 0); + Debug.Assert(tryStartOffset >= 0); + Debug.Assert(tryEndOffset >= 0); + Debug.Assert(filterOffset >= 0); + Debug.Assert(handlerStartOffset >= 0); + Debug.Assert(handlerEndOffset >= 0); + Debug.Assert(IsValidKind((ExceptionHandlingClauseOptions)kind)); + Debug.Assert(kind != (int)ExceptionHandlingClauseOptions.Clause || (exceptionTypeToken & 0x00FFFFFF) != 0); m_tryStartOffset = tryStartOffset; m_tryEndOffset = tryEndOffset; diff --git a/src/mscorlib/src/System/Reflection/Emit/ModuleBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/ModuleBuilder.cs index ce2a592ae2..6884f50b0e 100644 --- a/src/mscorlib/src/System/Reflection/Emit/ModuleBuilder.cs +++ b/src/mscorlib/src/System/Reflection/Emit/ModuleBuilder.cs @@ -12,7 +12,6 @@ namespace System.Reflection.Emit using System.Diagnostics.SymbolStore; using System.Globalization; using System.Reflection; - using System.Diagnostics; using System.IO; using System.Resources; using System.Security; @@ -22,6 +21,7 @@ namespace System.Reflection.Emit using System.Threading; using System.Runtime.Versioning; using System.Runtime.CompilerServices; + using System.Diagnostics; using System.Diagnostics.Contracts; internal sealed class InternalModuleBuilder : RuntimeModule @@ -50,7 +50,6 @@ namespace System.Reflection.Emit } // deliberately not [serializable] - [HostProtection(MayLeakOnAbort = true)] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_ModuleBuilder))] [System.Runtime.InteropServices.ComVisible(true)] @@ -97,9 +96,6 @@ namespace System.Reflection.Emit private Dictionary<string, Type> m_TypeBuilderDict; private ISymbolWriter m_iSymWriter; internal ModuleBuilderData m_moduleData; -#if !FEATURE_CORECLR - private MethodToken m_EntryPoint; -#endif //!FEATURE_CORECLR internal InternalModuleBuilder m_internalModuleBuilder; // This is the "external" AssemblyBuilder // only the "external" ModuleBuilder has this set @@ -157,42 +153,35 @@ namespace System.Reflection.Emit } - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static int GetTypeRef(RuntimeModule module, String strFullName, RuntimeModule refedModule, String strRefedModuleFileName, int tkResolution); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static int GetMemberRef(RuntimeModule module, RuntimeModule refedModule, int tr, int defToken); - [System.Security.SecurityCritical] // auto-generated private int GetMemberRef(Module refedModule, int tr, int defToken) { return GetMemberRef(GetNativeHandle(), GetRuntimeModuleFromModule(refedModule).GetNativeHandle(), tr, defToken); } - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static int GetMemberRefFromSignature(RuntimeModule module, int tr, String methodName, byte[] signature, int length); - [System.Security.SecurityCritical] // auto-generated private int GetMemberRefFromSignature(int tr, String methodName, byte[] signature, int length) { return GetMemberRefFromSignature(GetNativeHandle(), tr, methodName, signature, length); } - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static int GetMemberRefOfMethodInfo(RuntimeModule module, int tr, IRuntimeMethodInfo method); - [System.Security.SecurityCritical] // auto-generated private int GetMemberRefOfMethodInfo(int tr, RuntimeMethodInfo method) { - Contract.Assert(method != null); + Debug.Assert(method != null); #if FEATURE_APPX if (ContainingAssemblyBuilder.ProfileAPICheck) @@ -205,10 +194,9 @@ namespace System.Reflection.Emit return GetMemberRefOfMethodInfo(GetNativeHandle(), tr, method); } - [System.Security.SecurityCritical] // auto-generated private int GetMemberRefOfMethodInfo(int tr, RuntimeConstructorInfo method) { - Contract.Assert(method != null); + Debug.Assert(method != null); #if FEATURE_APPX if (ContainingAssemblyBuilder.ProfileAPICheck) @@ -221,15 +209,13 @@ namespace System.Reflection.Emit return GetMemberRefOfMethodInfo(GetNativeHandle(), tr, method); } - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static int GetMemberRefOfFieldInfo(RuntimeModule module, int tkType, RuntimeTypeHandle declaringType, int tkField); - [System.Security.SecurityCritical] // auto-generated private int GetMemberRefOfFieldInfo(int tkType, RuntimeTypeHandle declaringType, RuntimeFieldInfo runtimeField) { - Contract.Assert(runtimeField != null); + Debug.Assert(runtimeField != null); #if FEATURE_APPX if (ContainingAssemblyBuilder.ProfileAPICheck) @@ -243,38 +229,31 @@ namespace System.Reflection.Emit return GetMemberRefOfFieldInfo(GetNativeHandle(), tkType, declaringType, runtimeField.MetadataToken); } - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static int GetTokenFromTypeSpec(RuntimeModule pModule, byte[] signature, int length); - [System.Security.SecurityCritical] // auto-generated private int GetTokenFromTypeSpec(byte[] signature, int length) { return GetTokenFromTypeSpec(GetNativeHandle(), signature, length); } - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static int GetArrayMethodToken(RuntimeModule module, int tkTypeSpec, String methodName, byte[] signature, int sigLength); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static int GetStringConstant(RuntimeModule module, String str, int length); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void PreSavePEFile(RuntimeModule module, int portableExecutableKind, int imageFileMachine); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void SavePEFile(RuntimeModule module, String fileName, int entryPoint, int isExe, bool isManifestFile); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void AddResource( @@ -282,17 +261,14 @@ namespace System.Reflection.Emit byte[] resBytes, int resByteCount, int tkFile, int attribute, int portableExecutableKind, int imageFileMachine); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void SetModuleName(RuntimeModule module, String strModuleName); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] internal extern static void SetFieldRVAContent(RuntimeModule module, int fdToken, byte[] data, int length); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void DefineNativeResourceFile(RuntimeModule module, @@ -300,7 +276,6 @@ namespace System.Reflection.Emit int portableExecutableKind, int ImageFileMachine); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void DefineNativeResourceBytes(RuntimeModule module, @@ -308,7 +283,6 @@ namespace System.Reflection.Emit int portableExecutableKind, int imageFileMachine); - [System.Security.SecurityCritical] // auto-generated internal void DefineNativeResource(PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine) { string strResourceFileName = m_moduleData.m_strResourceFileName; @@ -351,105 +325,7 @@ namespace System.Reflection.Emit return null; } - -#if !FEATURE_CORECLR - internal void SetEntryPoint(MethodToken entryPoint) - { - // Sets the entry point of the module to be a given method. If no entry point - // is specified, calling EmitPEFile will generate a dll. - // AssemblyBuilder.SetEntryPoint has already demanded required permission - m_EntryPoint = entryPoint; - } -#endif //!FEATURE_CORECLR - - -#if !FEATURE_CORECLR - // This is a helper called by AssemblyBuilder save to presave information for the persistable modules. - // no need to lock here because we have already taken the lock in AssemblyBuilder.Save - [System.Security.SecurityCritical] // auto-generated - internal void PreSave(String fileName, - PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine) - { - if (m_moduleData.m_isSaved == true) - { - // can only save once - throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, - Environment.GetResourceString("InvalidOperation_ModuleHasBeenSaved"), - m_moduleData.m_strModuleName)); - } - - if (m_moduleData.m_fGlobalBeenCreated == false && m_moduleData.m_fHasGlobal == true) - throw new NotSupportedException(Environment.GetResourceString("NotSupported_GlobalFunctionNotBaked")); - TypeBuilder typeBuilder; - foreach (Type item in m_TypeBuilderDict.Values) - { - if (item is TypeBuilder) - { - typeBuilder = (TypeBuilder)item; - } - else - { - EnumBuilder enumBuilder = (EnumBuilder)item; - typeBuilder = enumBuilder.m_typeBuilder; - } - - if (!typeBuilder.IsCreated()) - { - // cannot save to PE file without creating all of the types first - throw new NotSupportedException(String.Format(CultureInfo.InvariantCulture, - Environment.GetResourceString("NotSupported_NotAllTypesAreBaked"), - typeBuilder.FullName)); - } - } - - PreSavePEFile(GetNativeHandle(), (int)portableExecutableKind, (int)imageFileMachine); - } - - // no need to lock here because we have already taken the lock in AssemblyBuilder.Save - [System.Security.SecurityCritical] // auto-generated - internal void Save(String fileName, bool isAssemblyFile, PortableExecutableKinds portableExecutableKind, - ImageFileMachine imageFileMachine) - { - // This is a helper called by AssemblyBuilder save to save information for the persistable modules. - if (m_moduleData.m_embeddedRes != null) - { - // There are embedded resources for this module - ResWriterData resWriter; - - // Add each resource content into the to be saved PE file - for (resWriter = m_moduleData.m_embeddedRes; resWriter != null; resWriter = resWriter.m_nextResWriter) - { - if (resWriter.m_resWriter != null) - resWriter.m_resWriter.Generate(); - - byte[] resBytes = new byte[resWriter.m_memoryStream.Length]; - resWriter.m_memoryStream.Flush(); - resWriter.m_memoryStream.Position = 0; - resWriter.m_memoryStream.Read(resBytes, 0, resBytes.Length); - - AddResource(GetNativeHandle(), - resWriter.m_strName, - resBytes, - resBytes.Length, - m_moduleData.FileToken, - (int)resWriter.m_attribute, - (int)portableExecutableKind, - (int)imageFileMachine); - } - } - - DefineNativeResource(portableExecutableKind, imageFileMachine); - - PEFileKinds pekind = isAssemblyFile ? ContainingAssemblyBuilder.m_assemblyData.m_peFileKind : PEFileKinds.Dll; - - SavePEFile(GetNativeHandle(), fileName, m_EntryPoint.Token, (int)pekind, isAssemblyFile); - - m_moduleData.m_isSaved = true; - } -#endif // !FEATURE_CORECLR - - [System.Security.SecurityCritical] // auto-generated private int GetTypeRefNested(Type type, Module refedModule, String strRefedModuleFileName) { // This function will generate correct TypeRef token for top level type and nested type. @@ -464,8 +340,8 @@ namespace System.Reflection.Emit typeName = UnmangleTypeName(typeName); } - Contract.Assert(!type.IsByRef, "Must not be ByRef."); - Contract.Assert(!type.IsGenericType || type.IsGenericTypeDefinition, "Must not have generic arguments."); + Debug.Assert(!type.IsByRef, "Must not be ByRef."); + Debug.Assert(!type.IsGenericType || type.IsGenericTypeDefinition, "Must not have generic arguments."); #if FEATURE_APPX if (ContainingAssemblyBuilder.ProfileAPICheck) @@ -481,13 +357,12 @@ namespace System.Reflection.Emit return GetTypeRef(GetNativeHandle(), typeName, GetRuntimeModuleFromModule(refedModule).GetNativeHandle(), strRefedModuleFileName, tkResolution); } - [System.Security.SecurityCritical] // auto-generated internal MethodToken InternalGetConstructorToken(ConstructorInfo con, bool usingRef) { // Helper to get constructor token. If usingRef is true, we will never use the def token if (con == null) - throw new ArgumentNullException("con"); + throw new ArgumentNullException(nameof(con)); Contract.EndContractBlock(); int tr; @@ -556,7 +431,6 @@ namespace System.Reflection.Emit return new MethodToken( mr ); } - [System.Security.SecurityCritical] // auto-generated internal void Init(String strModuleName, String strFileName, int tkFile) { m_moduleData = new ModuleBuilderData(this, strModuleName, strFileName, tkFile); @@ -565,7 +439,6 @@ namespace System.Reflection.Emit // This is a method for changing module and file name of the manifest module (created by default for // each assembly). - [System.Security.SecurityCritical] // auto-generated internal void ModifyModuleName(string name) { // Reset the names in the managed ModuleBuilderData @@ -589,7 +462,7 @@ namespace System.Reflection.Emit } #endregion - + #region Module Overrides // m_internalModuleBuilder is null iff this is a "internal" ModuleBuilder @@ -622,7 +495,6 @@ namespace System.Reflection.Emit return m as RuntimeModule; } - [System.Security.SecurityCritical] // auto-generated private int GetMemberRefToken(MethodBase method, IEnumerable<Type> optionalParameterTypes) { Type[] parameterTypes; @@ -671,11 +543,11 @@ namespace System.Reflection.Emit } else { - Contract.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo); + Debug.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo); if (method.IsGenericMethod) { - Contract.Assert(masmi != null); + Debug.Assert(masmi != null); methDef = masmi.GetGenericMethodDefinition(); methDef = methDef.Module.ResolveMethod( @@ -728,7 +600,6 @@ namespace System.Reflection.Emit return GetMemberRefFromSignature(tkParent, method.Name, sigBytes, sigLength); } - [System.Security.SecurityCritical] // auto-generated internal SignatureHelper GetMemberRefSignature(CallingConventions call, Type returnType, Type[] parameterTypes, IEnumerable<Type> optionalParameterTypes, int cGenericParameters) { @@ -949,11 +820,6 @@ namespace System.Reflection.Emit public override String FullyQualifiedName { -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#else - [System.Security.SecuritySafeCritical] -#endif get { String fullyQualifiedName = m_moduleData.m_strFileName; @@ -962,7 +828,7 @@ namespace System.Reflection.Emit if (ContainingAssemblyBuilder.m_assemblyData.m_strDir != null) { fullyQualifiedName = Path.Combine(ContainingAssemblyBuilder.m_assemblyData.m_strDir, fullyQualifiedName); - fullyQualifiedName = Path.UnsafeGetFullPath(fullyQualifiedName); + fullyQualifiedName = Path.GetFullPath(fullyQualifiedName); } if (ContainingAssemblyBuilder.m_assemblyData.m_strDir != null && fullyQualifiedName != null) @@ -1085,18 +951,11 @@ namespace System.Reflection.Emit } } -#if FEATURE_X509 && FEATURE_CAS_POLICY - public override System.Security.Cryptography.X509Certificates.X509Certificate GetSignerCertificate() - { - return InternalModule.GetSignerCertificate(); - } -#endif // FEATURE_X509 && FEATURE_CAS_POLICY #endregion #region Public Members #region Define Type - [System.Security.SecuritySafeCritical] // auto-generated public TypeBuilder DefineType(String name) { Contract.Ensures(Contract.Result<TypeBuilder>() != null); @@ -1107,7 +966,6 @@ namespace System.Reflection.Emit } } - [System.Security.SecuritySafeCritical] // auto-generated public TypeBuilder DefineType(String name, TypeAttributes attr) { Contract.Ensures(Contract.Result<TypeBuilder>() != null); @@ -1118,7 +976,6 @@ namespace System.Reflection.Emit } } - [System.Security.SecuritySafeCritical] // auto-generated public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent) { Contract.Ensures(Contract.Result<TypeBuilder>() != null); @@ -1132,11 +989,6 @@ namespace System.Reflection.Emit } } -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#else - [System.Security.SecuritySafeCritical] -#endif public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent, int typesize) { Contract.Ensures(Contract.Result<TypeBuilder>() != null); @@ -1147,11 +999,6 @@ namespace System.Reflection.Emit } } -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#else - [System.Security.SecuritySafeCritical] -#endif public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent, PackingSize packingSize, int typesize) { Contract.Ensures(Contract.Result<TypeBuilder>() != null); @@ -1162,7 +1009,6 @@ namespace System.Reflection.Emit } } - [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(true)] public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent, Type[] interfaces) { @@ -1174,7 +1020,6 @@ namespace System.Reflection.Emit } } - [System.Security.SecurityCritical] // auto-generated private TypeBuilder DefineTypeNoLock(String name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packingSize, int typesize) { Contract.Ensures(Contract.Result<TypeBuilder>() != null); @@ -1182,11 +1027,6 @@ namespace System.Reflection.Emit return new TypeBuilder(name, attr, parent, interfaces, this, packingSize, typesize, null); ; } -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#else - [System.Security.SecuritySafeCritical] -#endif public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent, PackingSize packsize) { Contract.Ensures(Contract.Result<TypeBuilder>() != null); @@ -1197,7 +1037,6 @@ namespace System.Reflection.Emit } } - [System.Security.SecurityCritical] // auto-generated private TypeBuilder DefineTypeNoLock(String name, TypeAttributes attr, Type parent, PackingSize packsize) { Contract.Ensures(Contract.Result<TypeBuilder>() != null); @@ -1211,7 +1050,6 @@ namespace System.Reflection.Emit // This API can only be used to construct a top-level (not nested) enum type. // Nested enum types can be defined manually using ModuleBuilder.DefineType. - [System.Security.SecuritySafeCritical] // auto-generated public EnumBuilder DefineEnum(String name, TypeAttributes visibility, Type underlyingType) { Contract.Ensures(Contract.Result<EnumBuilder>() != null); @@ -1222,17 +1060,16 @@ namespace System.Reflection.Emit EnumBuilder enumBuilder = DefineEnumNoLock(name, visibility, underlyingType); // This enum is not generic, nested, and cannot have any element type. - Contract.Assert(name == enumBuilder.FullName); + Debug.Assert(name == enumBuilder.FullName); // Replace the TypeBuilder object in m_TypeBuilderDict with this EnumBuilder object. - Contract.Assert(enumBuilder.m_typeBuilder == m_TypeBuilderDict[name]); + Debug.Assert(enumBuilder.m_typeBuilder == m_TypeBuilderDict[name]); m_TypeBuilderDict[name] = enumBuilder; return enumBuilder; } } - [System.Security.SecurityCritical] // auto-generated private EnumBuilder DefineEnumNoLock(String name, TypeAttributes visibility, Type underlyingType) { Contract.Ensures(Contract.Result<EnumBuilder>() != null); @@ -1243,178 +1080,7 @@ namespace System.Reflection.Emit #endregion #region Define Resource -#if !FEATURE_CORECLR - public IResourceWriter DefineResource(String name, String description) - { - // Define embedded managed resource to be stored in this module - Contract.Ensures(Contract.Result<IResourceWriter>() != null); - - return DefineResource(name, description, ResourceAttributes.Public); - } - - public IResourceWriter DefineResource(String name, String description, ResourceAttributes attribute) - { - // Define embedded managed resource to be stored in this module - Contract.Ensures(Contract.Result<IResourceWriter>() != null); - - lock(SyncRoot) - { - return DefineResourceNoLock(name, description, attribute); - } - } - - private IResourceWriter DefineResourceNoLock(String name, String description, ResourceAttributes attribute) - { - // Define embedded managed resource to be stored in this module - - if (IsTransient()) - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadResourceContainer")); - - if (name == null) - throw new ArgumentNullException("name"); - if (name.Length == 0) - throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name"); - Contract.Ensures(Contract.Result<IResourceWriter>() != null); - Contract.EndContractBlock(); - - if (m_assemblyBuilder.IsPersistable()) - { - m_assemblyBuilder.m_assemblyData.CheckResNameConflict(name); - - MemoryStream stream = new MemoryStream(); - ResourceWriter resWriter = new ResourceWriter(stream); - ResWriterData resWriterData = new ResWriterData( resWriter, stream, name, String.Empty, String.Empty, attribute); - - // chain it to the embedded resource list - resWriterData.m_nextResWriter = m_moduleData.m_embeddedRes; - m_moduleData.m_embeddedRes = resWriterData; - return resWriter; - } - else - { - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadResourceContainer")); - } - } -#endif // !FEATURE_CORECLR - -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#endif - public void DefineManifestResource(String name, Stream stream, ResourceAttributes attribute) - { - if (name == null) - throw new ArgumentNullException("name"); - - if (stream == null) - throw new ArgumentNullException("stream"); - Contract.EndContractBlock(); - - // Define embedded managed resource to be stored in this module - lock(SyncRoot) - { - DefineManifestResourceNoLock(name, stream, attribute); - } - } - - private void DefineManifestResourceNoLock(String name, Stream stream, ResourceAttributes attribute) - { - // Define embedded managed resource to be stored in this module - if (IsTransient()) - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadResourceContainer")); - Contract.EndContractBlock(); - -#if !FEATURE_CORECLR - if (name == null) - throw new ArgumentNullException("name"); - if (name.Length == 0) - throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name"); - - if (m_assemblyBuilder.IsPersistable()) - { - m_assemblyBuilder.m_assemblyData.CheckResNameConflict(name); - - ResWriterData resWriterData = new ResWriterData( null, stream, name, String.Empty, String.Empty, attribute); - - // chain it to the embedded resource list - resWriterData.m_nextResWriter = m_moduleData.m_embeddedRes; - m_moduleData.m_embeddedRes = resWriterData; - } - else - { - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadResourceContainer")); - } -#endif // !FEATURE_CORECLR - } - - -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#endif - public void DefineUnmanagedResource(Byte[] resource) - { - lock(SyncRoot) - { - DefineUnmanagedResourceInternalNoLock(resource); - } - } - - internal void DefineUnmanagedResourceInternalNoLock(Byte[] resource) - { - if (resource == null) - throw new ArgumentNullException("resource"); - Contract.EndContractBlock(); - - if (m_moduleData.m_strResourceFileName != null || m_moduleData.m_resourceBytes != null) - throw new ArgumentException(Environment.GetResourceString("Argument_NativeResourceAlreadyDefined")); - - m_moduleData.m_resourceBytes = new byte[resource.Length]; - Buffer.BlockCopy(resource, 0, m_moduleData.m_resourceBytes, 0, resource.Length); - } - -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#else - [System.Security.SecuritySafeCritical] -#endif - public void DefineUnmanagedResource(String resourceFileName) - { - lock(SyncRoot) - { - DefineUnmanagedResourceFileInternalNoLock(resourceFileName); - } - } - - [System.Security.SecurityCritical] // auto-generated - internal void DefineUnmanagedResourceFileInternalNoLock(String resourceFileName) - { - if (resourceFileName == null) - throw new ArgumentNullException("resourceFileName"); - Contract.EndContractBlock(); - - if (m_moduleData.m_resourceBytes != null || m_moduleData.m_strResourceFileName != null) - throw new ArgumentException(Environment.GetResourceString("Argument_NativeResourceAlreadyDefined")); - - // Check caller has the right to read the file. - string strFullFileName; - strFullFileName = Path.UnsafeGetFullPath(resourceFileName); - new FileIOPermission(FileIOPermissionAccess.Read, strFullFileName).Demand(); - - new EnvironmentPermission(PermissionState.Unrestricted).Assert(); - try - { - if (File.UnsafeExists(resourceFileName) == false) - throw new FileNotFoundException(Environment.GetResourceString( - "IO.FileNotFound_FileName", - resourceFileName), resourceFileName); - } - finally - { - CodeAccessPermission.RevertAssert(); - } - - m_moduleData.m_strResourceFileName = strFullFileName; - } #endregion #region Define Global Method @@ -1453,10 +1119,10 @@ namespace System.Reflection.Emit throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_GlobalsHaveBeenCreated")); if (name == null) - throw new ArgumentNullException("name"); + throw new ArgumentNullException(nameof(name)); if (name.Length == 0) - throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name"); + throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name)); if ((attributes & MethodAttributes.Static) == 0) throw new ArgumentException(Environment.GetResourceString("Argument_GlobalFunctionHasToBeStatic")); @@ -1475,9 +1141,6 @@ namespace System.Reflection.Emit parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers); } -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#endif public MethodBuilder DefinePInvokeMethod(String name, String dllName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) @@ -1487,9 +1150,6 @@ namespace System.Reflection.Emit return DefinePInvokeMethod(name, dllName, name, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet); } -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#endif public MethodBuilder DefinePInvokeMethod(String name, String dllName, String entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) @@ -1503,9 +1163,6 @@ namespace System.Reflection.Emit } } -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#endif private MethodBuilder DefinePInvokeMethodNoLock(String name, String dllName, String entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) @@ -1548,9 +1205,6 @@ namespace System.Reflection.Emit #region Define Data -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#endif public FieldBuilder DefineInitializedData(String name, byte[] data, FieldAttributes attributes) { // This method will define an initialized Data in .sdata. @@ -1564,9 +1218,6 @@ namespace System.Reflection.Emit } } -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#endif private FieldBuilder DefineInitializedDataNoLock(String name, byte[] data, FieldAttributes attributes) { // This method will define an initialized Data in .sdata. @@ -1583,9 +1234,6 @@ namespace System.Reflection.Emit return m_moduleData.m_globalTypeBuilder.DefineInitializedData(name, data, attributes); } -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#endif public FieldBuilder DefineUninitializedData(String name, int size, FieldAttributes attributes) { Contract.Ensures(Contract.Result<FieldBuilder>() != null); @@ -1596,9 +1244,6 @@ namespace System.Reflection.Emit } } -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#endif private FieldBuilder DefineUninitializedDataNoLock(String name, int size, FieldAttributes attributes) { // This method will define an uninitialized Data in .sdata. @@ -1623,13 +1268,11 @@ namespace System.Reflection.Emit // 1. GetTypeToken // 2. ldtoken (see ILGenerator) // For all other occasions we should return the generic type instantiated on its formal parameters. - [System.Security.SecurityCritical] // auto-generated internal TypeToken GetTypeTokenInternal(Type type) { return GetTypeTokenInternal(type, false); } - [System.Security.SecurityCritical] // auto-generated private TypeToken GetTypeTokenInternal(Type type, bool getGenericDefinition) { lock(SyncRoot) @@ -1638,17 +1281,15 @@ namespace System.Reflection.Emit } } - [System.Security.SecuritySafeCritical] // auto-generated public TypeToken GetTypeToken(Type type) { return GetTypeTokenInternal(type, true); } - [System.Security.SecurityCritical] // auto-generated private TypeToken GetTypeTokenWorkerNoLock(Type type, bool getGenericDefinition) { if (type == null) - throw new ArgumentNullException("type"); + throw new ArgumentNullException(nameof(type)); Contract.EndContractBlock(); CheckContext(type); @@ -1710,19 +1351,6 @@ namespace System.Reflection.Emit // ModuleBuilder refedModuleBuilder = refedModule as ModuleBuilder; -#if !FEATURE_CORECLR - Contract.Assert(refedModuleBuilder != null || refedModule is RuntimeModule); - bool isRefedModuleTransient = refedModuleBuilder != null ? - refedModuleBuilder.IsTransient() : - ((RuntimeModule)refedModule).IsTransientInternal(); - - // We cannot have a non-transient module referencing to a transient module. - if (IsTransient() == false && isRefedModuleTransient) - { - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadTransientModuleReference")); - } -#endif // !FEATURE_CORECLR - String strRefedModuleFileName = String.Empty; if (refedModule.Assembly.Equals(this.Assembly)) { @@ -1753,7 +1381,6 @@ namespace System.Reflection.Emit return GetTypeToken(InternalModule.GetType(name, false, true)); } - [System.Security.SecuritySafeCritical] // auto-generated public MethodToken GetMethodToken(MethodInfo method) { lock(SyncRoot) @@ -1762,7 +1389,6 @@ namespace System.Reflection.Emit } } - [System.Security.SecurityCritical] // auto-generated internal MethodToken GetMethodTokenInternal(MethodInfo method) { lock(SyncRoot) @@ -1775,13 +1401,12 @@ namespace System.Reflection.Emit // 1. GetMethodToken // 2. ldtoken (see ILGenerator) // For all other occasions we should return the method on the generic type instantiated on the formal parameters. - [System.Security.SecurityCritical] // auto-generated private MethodToken GetMethodTokenNoLock(MethodInfo method, bool getGenericTypeDefinition) { // Return a MemberRef token if MethodInfo is not defined in this module. Or // return the MethodDef token. if (method == null) - throw new ArgumentNullException("method"); + throw new ArgumentNullException(nameof(method)); Contract.EndContractBlock(); int tr; @@ -1885,12 +1510,11 @@ namespace System.Reflection.Emit return new MethodToken(mr); } - [System.Security.SecuritySafeCritical] // auto-generated public MethodToken GetConstructorToken(ConstructorInfo constructor, IEnumerable<Type> optionalParameterTypes) { if (constructor == null) { - throw new ArgumentNullException("constructor"); + throw new ArgumentNullException(nameof(constructor)); } lock (SyncRoot) @@ -1900,12 +1524,11 @@ namespace System.Reflection.Emit } } - [System.Security.SecuritySafeCritical] // auto-generated public MethodToken GetMethodToken(MethodInfo method, IEnumerable<Type> optionalParameterTypes) { if (method == null) { - throw new ArgumentNullException("method"); + throw new ArgumentNullException(nameof(method)); } // useMethodDef flag only affects the result if we pass in a generic method definition. @@ -1922,7 +1545,6 @@ namespace System.Reflection.Emit } } - [System.Security.SecurityCritical] // auto-generated internal int GetMethodTokenInternal(MethodBase method, IEnumerable<Type> optionalParameterTypes, bool useMethodDef) { int tk = 0; @@ -1931,7 +1553,7 @@ namespace System.Reflection.Emit if (method.IsGenericMethod) { // Constructors cannot be generic. - Contract.Assert(methodInfo != null); + Debug.Assert(methodInfo != null); // Given M<Bar> unbind to M<S> MethodInfo methodInfoUnbound = methodInfo; @@ -1989,7 +1611,6 @@ namespace System.Reflection.Emit return tk; } - [System.Security.SecuritySafeCritical] // auto-generated public MethodToken GetArrayMethodToken(Type arrayClass, String methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) { @@ -1999,18 +1620,17 @@ namespace System.Reflection.Emit } } - [System.Security.SecurityCritical] // auto-generated private MethodToken GetArrayMethodTokenNoLock(Type arrayClass, String methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) { if (arrayClass == null) - throw new ArgumentNullException("arrayClass"); + throw new ArgumentNullException(nameof(arrayClass)); if (methodName == null) - throw new ArgumentNullException("methodName"); + throw new ArgumentNullException(nameof(methodName)); if (methodName.Length == 0) - throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "methodName"); + throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(methodName)); if (arrayClass.IsArray == false) throw new ArgumentException(Environment.GetResourceString("Argument_HasToBeArrayClass")); @@ -2035,7 +1655,6 @@ namespace System.Reflection.Emit typeSpec.Token, methodName, sigBytes, length)); } - [System.Security.SecuritySafeCritical] // auto-generated public MethodInfo GetArrayMethod(Type arrayClass, String methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) { @@ -2052,7 +1671,6 @@ namespace System.Reflection.Emit return new SymbolMethod(this, token, arrayClass, methodName, callingConvention, returnType, parameterTypes); } - [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(true)] public MethodToken GetConstructorToken(ConstructorInfo con) { @@ -2060,7 +1678,6 @@ namespace System.Reflection.Emit return InternalGetConstructorToken(con, false); } - [System.Security.SecuritySafeCritical] // auto-generated public FieldToken GetFieldToken(FieldInfo field) { lock(SyncRoot) @@ -2069,7 +1686,6 @@ namespace System.Reflection.Emit } } - [System.Security.SecurityCritical] // auto-generated private FieldToken GetFieldTokenNoLock(FieldInfo field) { if (field == null) { @@ -2158,12 +1774,11 @@ namespace System.Reflection.Emit return new FieldToken(mr, field.GetType()); } - [System.Security.SecuritySafeCritical] // auto-generated public StringToken GetStringConstant(String str) { if (str == null) { - throw new ArgumentNullException("str"); + throw new ArgumentNullException(nameof(str)); } Contract.EndContractBlock(); @@ -2172,7 +1787,6 @@ namespace System.Reflection.Emit return new StringToken(GetStringConstant(GetNativeHandle(), str, str.Length)); } - [System.Security.SecuritySafeCritical] // auto-generated public SignatureToken GetSignatureToken(SignatureHelper sigHelper) { // Define signature token given a signature helper. This will define a metadata @@ -2180,7 +1794,7 @@ namespace System.Reflection.Emit if (sigHelper == null) { - throw new ArgumentNullException("sigHelper"); + throw new ArgumentNullException(nameof(sigHelper)); } Contract.EndContractBlock(); @@ -2191,11 +1805,10 @@ namespace System.Reflection.Emit sigBytes = sigHelper.InternalGetSignature(out sigLength); return new SignatureToken(TypeBuilder.GetTokenFromSig(GetNativeHandle(), sigBytes, sigLength), this); } - [System.Security.SecuritySafeCritical] // auto-generated public SignatureToken GetSignatureToken(byte[] sigBytes, int sigLength) { if (sigBytes == null) - throw new ArgumentNullException("sigBytes"); + throw new ArgumentNullException(nameof(sigBytes)); Contract.EndContractBlock(); byte[] localSigBytes = new byte[sigBytes.Length]; @@ -2208,18 +1821,13 @@ namespace System.Reflection.Emit #region Other -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#else - [System.Security.SecuritySafeCritical] -#endif [System.Runtime.InteropServices.ComVisible(true)] public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { if (con == null) - throw new ArgumentNullException("con"); + throw new ArgumentNullException(nameof(con)); if (binaryAttribute == null) - throw new ArgumentNullException("binaryAttribute"); + throw new ArgumentNullException(nameof(binaryAttribute)); Contract.EndContractBlock(); TypeBuilder.DefineCustomAttribute( @@ -2230,12 +1838,11 @@ namespace System.Reflection.Emit false, false); } - [System.Security.SecuritySafeCritical] // auto-generated public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { if (customBuilder == null) { - throw new ArgumentNullException("customBuilder"); + throw new ArgumentNullException(nameof(customBuilder)); } Contract.EndContractBlock(); @@ -2276,14 +1883,11 @@ namespace System.Reflection.Emit return m_iSymWriter; } -#if FEATURE_CORECLR - [System.Security.SecuritySafeCritical] -#endif public ISymbolDocumentWriter DefineDocument(String url, Guid language, Guid languageVendor, Guid documentType) { // url cannot be null but can be an empty string if (url == null) - throw new ArgumentNullException("url"); + throw new ArgumentNullException(nameof(url)); Contract.EndContractBlock(); lock(SyncRoot) @@ -2292,9 +1896,6 @@ namespace System.Reflection.Emit } } -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#endif private ISymbolDocumentWriter DefineDocumentNoLock(String url, Guid language, Guid languageVendor, Guid documentType) { if (m_iSymWriter == null) @@ -2306,11 +1907,6 @@ namespace System.Reflection.Emit return m_iSymWriter.DefineDocument(url, language, languageVendor, documentType); } -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#else - [System.Security.SecuritySafeCritical] -#endif public void SetUserEntryPoint(MethodInfo entryPoint) { lock(SyncRoot) @@ -2319,7 +1915,6 @@ namespace System.Reflection.Emit } } - [System.Security.SecurityCritical] // auto-generated private void SetUserEntryPointNoLock(MethodInfo entryPoint) { // Set the user entry point. Compiler may generate startup stub before calling user main. @@ -2328,7 +1923,7 @@ namespace System.Reflection.Emit if (entryPoint == null) { - throw new ArgumentNullException("entryPoint"); + throw new ArgumentNullException(nameof(entryPoint)); } Contract.EndContractBlock(); @@ -2396,27 +1991,5 @@ namespace System.Reflection.Emit #endregion #endregion - -#if !FEATURE_CORECLR - void _ModuleBuilder.GetTypeInfoCount(out uint pcTInfo) - { - throw new NotImplementedException(); - } - - void _ModuleBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) - { - throw new NotImplementedException(); - } - - void _ModuleBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) - { - throw new NotImplementedException(); - } - - void _ModuleBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) - { - throw new NotImplementedException(); - } -#endif } } diff --git a/src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs b/src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs index 2bec04abe5..96e60d9a4e 100644 --- a/src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs +++ b/src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs @@ -9,6 +9,7 @@ namespace System.Reflection.Emit { using System; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; using System.IO; @@ -21,7 +22,6 @@ namespace System.Reflection.Emit [Serializable] internal class ModuleBuilderData { - [System.Security.SecurityCritical] // auto-generated internal ModuleBuilderData(ModuleBuilder module, String strModuleName, String strFileName, int tkFile) { m_globalTypeBuilder = new TypeBuilder(module); @@ -32,7 +32,6 @@ namespace System.Reflection.Emit } // Initialize module and file names. - [System.Security.SecurityCritical] // auto-generated private void InitNames(String strModuleName, String strFileName) { m_strModuleName = strModuleName; @@ -55,10 +54,9 @@ namespace System.Reflection.Emit // This is a method for changing module and file name of the manifest module (created by default for // each assembly). - [System.Security.SecurityCritical] // auto-generated internal virtual void ModifyModuleName(String strModuleName) { - Contract.Assert(m_strModuleName == AssemblyBuilder.MANIFEST_MODULE_NAME, "Changing names for non-manifest module"); + Debug.Assert(m_strModuleName == AssemblyBuilder.MANIFEST_MODULE_NAME, "Changing names for non-manifest module"); InitNames(strModuleName, null /*strFileName*/); } diff --git a/src/mscorlib/src/System/Reflection/Emit/Opcode.cs b/src/mscorlib/src/System/Reflection/Emit/Opcode.cs index cae4f0564e..d7bfacd568 100644 --- a/src/mscorlib/src/System/Reflection/Emit/Opcode.cs +++ b/src/mscorlib/src/System/Reflection/Emit/Opcode.cs @@ -36,7 +36,6 @@ public struct OpCode internal const int StackChangeShift = 28; // XXXX0000000000000000000000000000 -#if FEATURE_CORECLR private OpCodeValues m_value; private int m_flags; @@ -80,7 +79,6 @@ public struct OpCode } } - public StackBehaviour StackBehaviourPop { get @@ -112,121 +110,6 @@ public struct OpCode return (short)m_value; } } -#else // FEATURE_CORECLR - // - // The exact layout is part of the legacy COM mscorlib surface, so it is - // pretty much set in stone for desktop CLR. Ideally, we would use the packed - // bit field like for CoreCLR, but that would be a breaking change. - // - -// disable csharp compiler warning #0414: field assigned unused value -#pragma warning disable 0414 - private String m_stringname; // not used - computed lazily -#pragma warning restore 0414 - private StackBehaviour m_pop; - private StackBehaviour m_push; - private OperandType m_operand; - private OpCodeType m_type; - private int m_size; - private byte m_s1; - private byte m_s2; - private FlowControl m_ctrl; - - // Specifies whether the current instructions causes the control flow to - // change unconditionally. - private bool m_endsUncondJmpBlk; - - - // Specifies the stack change that the current instruction causes not - // taking into account the operand dependant stack changes. - private int m_stackChange; - - - internal OpCode(OpCodeValues value, int flags) - { - m_stringname = null; // computed lazily - m_pop = (StackBehaviour)((flags >> StackBehaviourPopShift) & StackBehaviourMask); - m_push = (StackBehaviour)((flags >> StackBehaviourPushShift) & StackBehaviourMask); - m_operand = (OperandType)(flags & OperandTypeMask); - m_type = (OpCodeType)((flags >> OpCodeTypeShift) & OpCodeTypeMask); - m_size = (flags >> SizeShift) & SizeMask; - m_s1 = (byte)((int)value >> 8); - m_s2 = (byte)(int)value; - m_ctrl = (FlowControl)((flags >> FlowControlShift) & FlowControlMask); - m_endsUncondJmpBlk = (flags & EndsUncondJmpBlkFlag) != 0; - m_stackChange = (flags >> StackChangeShift); - } - - internal bool EndsUncondJmpBlk() - { - return m_endsUncondJmpBlk; - } - - internal int StackChange() - { - return m_stackChange; - } - - public OperandType OperandType - { - get - { - return (m_operand); - } - } - - public FlowControl FlowControl - { - get - { - return (m_ctrl); - } - } - - public OpCodeType OpCodeType - { - get - { - return (m_type); - } - } - - - public StackBehaviour StackBehaviourPop - { - get - { - return (m_pop); - } - } - - public StackBehaviour StackBehaviourPush - { - get - { - return (m_push); - } - } - - public int Size - { - get - { - return (m_size); - } - } - - public short Value - { - get - { - if (m_size == 2) - return (short)(m_s1 << 8 | m_s2); - return (short)m_s2; - } - } -#endif // FEATURE_CORECLR - private static volatile string[] g_nameCache; @@ -308,5 +191,4 @@ public struct OpCode return Name; } } - } diff --git a/src/mscorlib/src/System/Reflection/Emit/OpcodeType.cs b/src/mscorlib/src/System/Reflection/Emit/OpcodeType.cs index 5ef5f80b15..3636cb7377 100644 --- a/src/mscorlib/src/System/Reflection/Emit/OpcodeType.cs +++ b/src/mscorlib/src/System/Reflection/Emit/OpcodeType.cs @@ -21,11 +21,8 @@ using System; public enum OpCodeType { -#if !FEATURE_CORECLR - /// <internalonly/> [Obsolete("This API has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")] Annotation = 0, -#endif Macro = 1, Nternal = 2, Objmodel = 3, diff --git a/src/mscorlib/src/System/Reflection/Emit/OperandType.cs b/src/mscorlib/src/System/Reflection/Emit/OperandType.cs index fdde19a73e..808844a017 100644 --- a/src/mscorlib/src/System/Reflection/Emit/OperandType.cs +++ b/src/mscorlib/src/System/Reflection/Emit/OperandType.cs @@ -27,11 +27,8 @@ public enum OperandType InlineI8 = 3, InlineMethod = 4, InlineNone = 5, -#if !FEATURE_CORECLR - /// <internalonly/> [Obsolete("This API has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")] InlinePhi = 6, -#endif InlineR = 7, InlineSig = 9, InlineString = 10, diff --git a/src/mscorlib/src/System/Reflection/Emit/ParameterBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/ParameterBuilder.cs index 693e2d3660..7909562baa 100644 --- a/src/mscorlib/src/System/Reflection/Emit/ParameterBuilder.cs +++ b/src/mscorlib/src/System/Reflection/Emit/ParameterBuilder.cs @@ -25,13 +25,12 @@ namespace System.Reflection.Emit { public class ParameterBuilder : _ParameterBuilder { // set ParamMarshal - [System.Security.SecuritySafeCritical] // auto-generated [Obsolete("An alternate API is available: Emit the MarshalAs custom attribute instead. http://go.microsoft.com/fwlink/?linkid=14202")] public virtual void SetMarshal(UnmanagedMarshal unmanagedMarshal) { if (unmanagedMarshal == null) { - throw new ArgumentNullException("unmanagedMarshal"); + throw new ArgumentNullException(nameof(unmanagedMarshal)); } Contract.EndContractBlock(); @@ -44,7 +43,6 @@ namespace System.Reflection.Emit { } // Set the default value of the parameter - [System.Security.SecuritySafeCritical] // auto-generated public virtual void SetConstant(Object defaultValue) { TypeBuilder.SetConstantValue( @@ -56,14 +54,13 @@ namespace System.Reflection.Emit { // Use this function if client decides to form the custom attribute blob themselves - [System.Security.SecuritySafeCritical] [System.Runtime.InteropServices.ComVisible(true)] public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { if (con == null) - throw new ArgumentNullException("con"); + throw new ArgumentNullException(nameof(con)); if (binaryAttribute == null) - throw new ArgumentNullException("binaryAttribute"); + throw new ArgumentNullException(nameof(binaryAttribute)); Contract.EndContractBlock(); TypeBuilder.DefineCustomAttribute( @@ -75,12 +72,11 @@ namespace System.Reflection.Emit { } // Use this function if client wishes to build CustomAttribute using CustomAttributeBuilder - [System.Security.SecuritySafeCritical] // auto-generated public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { if (customBuilder == null) { - throw new ArgumentNullException("customBuilder"); + throw new ArgumentNullException(nameof(customBuilder)); } Contract.EndContractBlock(); customBuilder.CreateCustomAttribute((ModuleBuilder) (m_methodBuilder .GetModule()), m_pdToken.Token); @@ -92,7 +88,6 @@ namespace System.Reflection.Emit { private ParameterBuilder() {} - [System.Security.SecurityCritical] // auto-generated internal ParameterBuilder( MethodBuilder methodBuilder, int sequence, @@ -117,28 +112,6 @@ namespace System.Reflection.Emit { return m_pdToken; } -#if !FEATURE_CORECLR - void _ParameterBuilder.GetTypeInfoCount(out uint pcTInfo) - { - throw new NotImplementedException(); - } - - void _ParameterBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) - { - throw new NotImplementedException(); - } - - void _ParameterBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) - { - throw new NotImplementedException(); - } - - void _ParameterBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) - { - throw new NotImplementedException(); - } -#endif - internal int MetadataTokenInternal { get { return m_pdToken.Token; } } public virtual String Name { diff --git a/src/mscorlib/src/System/Reflection/Emit/PropertyBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/PropertyBuilder.cs index 5ac69f205f..e7442b4e02 100644 --- a/src/mscorlib/src/System/Reflection/Emit/PropertyBuilder.cs +++ b/src/mscorlib/src/System/Reflection/Emit/PropertyBuilder.cs @@ -25,7 +25,6 @@ namespace System.Reflection.Emit { // A PropertyBuilder is always associated with a TypeBuilder. The TypeBuilder.DefineProperty // method will return a new PropertyBuilder to a client. // - [HostProtection(MayLeakOnAbort = true)] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_PropertyBuilder))] [System.Runtime.InteropServices.ComVisible(true)] @@ -47,11 +46,11 @@ namespace System.Reflection.Emit { TypeBuilder containingType) // the containing type { if (name == null) - throw new ArgumentNullException("name"); + throw new ArgumentNullException(nameof(name)); if (name.Length == 0) - throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name"); + throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name)); if (name[0] == '\0') - throw new ArgumentException(Environment.GetResourceString("Argument_IllegalName"), "name"); + throw new ArgumentException(Environment.GetResourceString("Argument_IllegalName"), nameof(name)); Contract.EndContractBlock(); m_name = name; @@ -67,7 +66,6 @@ namespace System.Reflection.Emit { //************************************************ // Set the default value of the Property //************************************************ - [System.Security.SecuritySafeCritical] // auto-generated public void SetConstant(Object defaultValue) { m_containingType.ThrowIfCreated(); @@ -103,12 +101,11 @@ namespace System.Reflection.Emit { } } - [System.Security.SecurityCritical] // auto-generated private void SetMethodSemantics(MethodBuilder mdBuilder, MethodSemanticsAttributes semantics) { if (mdBuilder == null) { - throw new ArgumentNullException("mdBuilder"); + throw new ArgumentNullException(nameof(mdBuilder)); } m_containingType.ThrowIfCreated(); @@ -119,21 +116,18 @@ namespace System.Reflection.Emit { mdBuilder.GetToken().Token); } - [System.Security.SecuritySafeCritical] // auto-generated public void SetGetMethod(MethodBuilder mdBuilder) { SetMethodSemantics(mdBuilder, MethodSemanticsAttributes.Getter); m_getMethod = mdBuilder; } - [System.Security.SecuritySafeCritical] // auto-generated public void SetSetMethod(MethodBuilder mdBuilder) { SetMethodSemantics(mdBuilder, MethodSemanticsAttributes.Setter); m_setMethod = mdBuilder; } - [System.Security.SecuritySafeCritical] // auto-generated public void AddOtherMethod(MethodBuilder mdBuilder) { SetMethodSemantics(mdBuilder, MethodSemanticsAttributes.Other); @@ -141,18 +135,13 @@ namespace System.Reflection.Emit { // Use this function if client decides to form the custom attribute blob themselves -#if FEATURE_CORECLR -[System.Security.SecurityCritical] // auto-generated -#else -[System.Security.SecuritySafeCritical] -#endif [System.Runtime.InteropServices.ComVisible(true)] public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { if (con == null) - throw new ArgumentNullException("con"); + throw new ArgumentNullException(nameof(con)); if (binaryAttribute == null) - throw new ArgumentNullException("binaryAttribute"); + throw new ArgumentNullException(nameof(binaryAttribute)); m_containingType.ThrowIfCreated(); TypeBuilder.DefineCustomAttribute( @@ -164,12 +153,11 @@ namespace System.Reflection.Emit { } // Use this function if client wishes to build CustomAttribute using CustomAttributeBuilder - [System.Security.SecuritySafeCritical] // auto-generated public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { if (customBuilder == null) { - throw new ArgumentNullException("customBuilder"); + throw new ArgumentNullException(nameof(customBuilder)); } m_containingType.ThrowIfCreated(); customBuilder.CreateCustomAttribute(m_moduleBuilder, m_prToken.Token); @@ -256,28 +244,6 @@ namespace System.Reflection.Emit { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); } -#if !FEATURE_CORECLR - void _PropertyBuilder.GetTypeInfoCount(out uint pcTInfo) - { - throw new NotImplementedException(); - } - - void _PropertyBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) - { - throw new NotImplementedException(); - } - - void _PropertyBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) - { - throw new NotImplementedException(); - } - - void _PropertyBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) - { - throw new NotImplementedException(); - } -#endif - public override String Name { get { return m_name; } } @@ -302,5 +268,4 @@ namespace System.Reflection.Emit { private MethodInfo m_setMethod; private TypeBuilder m_containingType; } - } diff --git a/src/mscorlib/src/System/Reflection/Emit/SignatureHelper.cs b/src/mscorlib/src/System/Reflection/Emit/SignatureHelper.cs index 35e8cc7e31..c40035bc40 100644 --- a/src/mscorlib/src/System/Reflection/Emit/SignatureHelper.cs +++ b/src/mscorlib/src/System/Reflection/Emit/SignatureHelper.cs @@ -8,6 +8,7 @@ namespace System.Reflection.Emit { using System.Text; using System; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Reflection; using System.Runtime.CompilerServices; @@ -25,19 +26,16 @@ namespace System.Reflection.Emit #endregion #region Static Members - [System.Security.SecuritySafeCritical] // auto-generated public static SignatureHelper GetMethodSigHelper(Module mod, Type returnType, Type[] parameterTypes) { return GetMethodSigHelper(mod, CallingConventions.Standard, returnType, null, null, parameterTypes, null, null); } - [System.Security.SecurityCritical] // auto-generated internal static SignatureHelper GetMethodSigHelper(Module mod, CallingConventions callingConvention, Type returnType, int cGenericParam) { return GetMethodSigHelper(mod, callingConvention, cGenericParam, returnType, null, null, null, null, null); } - [System.Security.SecuritySafeCritical] // auto-generated public static SignatureHelper GetMethodSigHelper(Module mod, CallingConventions callingConvention, Type returnType) { return GetMethodSigHelper(mod, callingConvention, returnType, null, null, null, null, null); @@ -52,7 +50,6 @@ namespace System.Reflection.Emit return sigHelp; } - [System.Security.SecurityCritical] // auto-generated internal static SignatureHelper GetMethodSigHelper( Module scope, CallingConventions callingConvention, Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers, @@ -62,7 +59,6 @@ namespace System.Reflection.Emit optionalReturnTypeCustomModifiers, parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers); } - [System.Security.SecurityCritical] // auto-generated internal static SignatureHelper GetMethodSigHelper( Module scope, CallingConventions callingConvention, int cGenericParam, Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers, @@ -96,7 +92,6 @@ namespace System.Reflection.Emit return sigHelp; } - [System.Security.SecuritySafeCritical] // auto-generated public static SignatureHelper GetMethodSigHelper(Module mod, CallingConvention unmanagedCallConv, Type returnType) { SignatureHelper sigHelp; @@ -123,7 +118,7 @@ namespace System.Reflection.Emit } else { - throw new ArgumentException(Environment.GetResourceString("Argument_UnknownUnmanagedCallConv"), "unmanagedCallConv"); + throw new ArgumentException(Environment.GetResourceString("Argument_UnknownUnmanagedCallConv"), nameof(unmanagedCallConv)); } sigHelp = new SignatureHelper(mod, intCall, returnType, null, null); @@ -168,7 +163,6 @@ namespace System.Reflection.Emit return GetPropertySigHelper(mod, (CallingConventions)0, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers); } - [System.Security.SecuritySafeCritical] // auto-generated public static SignatureHelper GetPropertySigHelper(Module mod, CallingConventions callingConvention, Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers, Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers) @@ -192,14 +186,13 @@ namespace System.Reflection.Emit return sigHelp; } - [System.Security.SecurityCritical] // auto-generated internal static SignatureHelper GetTypeSigToken(Module mod, Type type) { if (mod == null) throw new ArgumentNullException("module"); if (type == null) - throw new ArgumentNullException("type"); + throw new ArgumentNullException(nameof(type)); return new SignatureHelper(mod, type); } @@ -221,7 +214,6 @@ namespace System.Reflection.Emit Init(mod, callingConvention); } - [System.Security.SecurityCritical] // auto-generated private SignatureHelper(Module mod, MdSigCallingConvention callingConvention, int cGenericParameters, Type returnType, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers) { @@ -234,14 +226,12 @@ namespace System.Reflection.Emit AddOneArgTypeHelper(returnType, requiredCustomModifiers, optionalCustomModifiers); } - [System.Security.SecurityCritical] // auto-generated private SignatureHelper(Module mod, MdSigCallingConvention callingConvention, Type returnType, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers) : this(mod, callingConvention, 0, returnType, requiredCustomModifiers, optionalCustomModifiers) { } - [System.Security.SecurityCritical] // auto-generated private SignatureHelper(Module mod, Type type) { Init(mod); @@ -290,7 +280,6 @@ namespace System.Reflection.Emit #endregion #region Private Members - [System.Security.SecurityCritical] // auto-generated private void AddOneArgTypeHelper(Type argument, bool pinned) { if (pinned) @@ -299,7 +288,6 @@ namespace System.Reflection.Emit AddOneArgTypeHelper(argument); } - [System.Security.SecurityCritical] // auto-generated private void AddOneArgTypeHelper(Type clsArgument, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers) { // This function will not increase the argument count. It only fills in bytes @@ -315,18 +303,18 @@ namespace System.Reflection.Emit Type t = optionalCustomModifiers[i]; if (t == null) - throw new ArgumentNullException("optionalCustomModifiers"); + throw new ArgumentNullException(nameof(optionalCustomModifiers)); if (t.HasElementType) - throw new ArgumentException(Environment.GetResourceString("Argument_ArraysInvalid"), "optionalCustomModifiers"); + throw new ArgumentException(Environment.GetResourceString("Argument_ArraysInvalid"), nameof(optionalCustomModifiers)); if (t.ContainsGenericParameters) - throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), "optionalCustomModifiers"); + throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), nameof(optionalCustomModifiers)); AddElementType(CorElementType.CModOpt); int token = m_module.GetTypeToken(t).Token; - Contract.Assert(!MetadataToken.IsNullToken(token)); + Debug.Assert(!MetadataToken.IsNullToken(token)); AddToken(token); } } @@ -338,18 +326,18 @@ namespace System.Reflection.Emit Type t = requiredCustomModifiers[i]; if (t == null) - throw new ArgumentNullException("requiredCustomModifiers"); + throw new ArgumentNullException(nameof(requiredCustomModifiers)); if (t.HasElementType) - throw new ArgumentException(Environment.GetResourceString("Argument_ArraysInvalid"), "requiredCustomModifiers"); + throw new ArgumentException(Environment.GetResourceString("Argument_ArraysInvalid"), nameof(requiredCustomModifiers)); if (t.ContainsGenericParameters) - throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), "requiredCustomModifiers"); + throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), nameof(requiredCustomModifiers)); AddElementType(CorElementType.CModReqd); int token = m_module.GetTypeToken(t).Token; - Contract.Assert(!MetadataToken.IsNullToken(token)); + Debug.Assert(!MetadataToken.IsNullToken(token)); AddToken(token); } } @@ -357,9 +345,7 @@ namespace System.Reflection.Emit AddOneArgTypeHelper(clsArgument); } - [System.Security.SecurityCritical] // auto-generated private void AddOneArgTypeHelper(Type clsArgument) { AddOneArgTypeHelperWorker(clsArgument, false); } - [System.Security.SecurityCritical] // auto-generated private void AddOneArgTypeHelperWorker(Type clsArgument, bool lastWasGenericInst) { if (clsArgument.IsGenericParameter) @@ -613,7 +599,6 @@ namespace System.Reflection.Emit AddToken(clsToken.Token); } - [System.Security.SecurityCritical] // auto-generated private unsafe void InternalAddRuntimeType(Type type) { // Add a runtime type into the signature. @@ -822,11 +807,10 @@ namespace System.Reflection.Emit AddArgument(clsArgument, null, null); } - [System.Security.SecuritySafeCritical] // auto-generated public void AddArgument(Type argument, bool pinned) { if (argument == null) - throw new ArgumentNullException("argument"); + throw new ArgumentNullException(nameof(argument)); IncrementArgCounts(); AddOneArgTypeHelper(argument, pinned); @@ -835,10 +819,10 @@ namespace System.Reflection.Emit public void AddArguments(Type[] arguments, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers) { if (requiredCustomModifiers != null && (arguments == null || requiredCustomModifiers.Length != arguments.Length)) - throw new ArgumentException(Environment.GetResourceString("Argument_MismatchedArrays", "requiredCustomModifiers", "arguments")); + throw new ArgumentException(Environment.GetResourceString("Argument_MismatchedArrays", nameof(requiredCustomModifiers), nameof(arguments))); if (optionalCustomModifiers != null && (arguments == null || optionalCustomModifiers.Length != arguments.Length)) - throw new ArgumentException(Environment.GetResourceString("Argument_MismatchedArrays", "optionalCustomModifiers", "arguments")); + throw new ArgumentException(Environment.GetResourceString("Argument_MismatchedArrays", nameof(optionalCustomModifiers), nameof(arguments))); if (arguments != null) { @@ -851,14 +835,13 @@ namespace System.Reflection.Emit } } - [System.Security.SecuritySafeCritical] // auto-generated public void AddArgument(Type argument, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers) { if (m_sigDone) throw new ArgumentException(Environment.GetResourceString("Argument_SigIsFinalized")); if (argument == null) - throw new ArgumentNullException("argument"); + throw new ArgumentNullException(nameof(argument)); IncrementArgCounts(); @@ -968,28 +951,6 @@ namespace System.Reflection.Emit #endregion -#if !FEATURE_CORECLR - void _SignatureHelper.GetTypeInfoCount(out uint pcTInfo) - { - throw new NotImplementedException(); - } - - void _SignatureHelper.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) - { - throw new NotImplementedException(); - } - - void _SignatureHelper.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) - { - throw new NotImplementedException(); - } - - void _SignatureHelper.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) - { - throw new NotImplementedException(); - } -#endif - } } diff --git a/src/mscorlib/src/System/Reflection/Emit/SymbolMethod.cs b/src/mscorlib/src/System/Reflection/Emit/SymbolMethod.cs index 62780f4e3a..6b47770608 100644 --- a/src/mscorlib/src/System/Reflection/Emit/SymbolMethod.cs +++ b/src/mscorlib/src/System/Reflection/Emit/SymbolMethod.cs @@ -26,7 +26,6 @@ namespace System.Reflection.Emit #endregion #region Constructor - [System.Security.SecurityCritical] // auto-generated internal SymbolMethod(ModuleBuilder mod, MethodToken token, Type arrayClass, String methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) { diff --git a/src/mscorlib/src/System/Reflection/Emit/SymbolType.cs b/src/mscorlib/src/System/Reflection/Emit/SymbolType.cs index 633a2bffb4..84ece90982 100644 --- a/src/mscorlib/src/System/Reflection/Emit/SymbolType.cs +++ b/src/mscorlib/src/System/Reflection/Emit/SymbolType.cs @@ -234,7 +234,7 @@ namespace System.Reflection.Emit internal void SetElementType(Type baseType) { if (baseType == null) - throw new ArgumentNullException("baseType"); + throw new ArgumentNullException(nameof(baseType)); Contract.EndContractBlock(); m_baseType = baseType; diff --git a/src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs index 6db04717b5..73778d5f27 100644 --- a/src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs +++ b/src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs @@ -10,13 +10,13 @@ namespace System.Reflection.Emit { using System.Reflection; using System.Security; using System.Security.Permissions; - using System.Diagnostics; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Collections.Generic; using CultureInfo = System.Globalization.CultureInfo; using System.Threading; using System.Runtime.Versioning; + using System.Diagnostics; using System.Diagnostics.Contracts; @@ -35,7 +35,6 @@ namespace System.Reflection.Emit { Size128 = 128, } - [HostProtection(MayLeakOnAbort = true)] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_TypeBuilder))] [System.Runtime.InteropServices.ComVisible(true)] @@ -56,10 +55,10 @@ namespace System.Reflection.Emit { public CustAttr(ConstructorInfo con, byte[] binaryAttribute) { if (con == null) - throw new ArgumentNullException("con"); + throw new ArgumentNullException(nameof(con)); if (binaryAttribute == null) - throw new ArgumentNullException("binaryAttribute"); + throw new ArgumentNullException(nameof(binaryAttribute)); Contract.EndContractBlock(); m_con = con; @@ -69,13 +68,12 @@ namespace System.Reflection.Emit { public CustAttr(CustomAttributeBuilder customBuilder) { if (customBuilder == null) - throw new ArgumentNullException("customBuilder"); + throw new ArgumentNullException(nameof(customBuilder)); Contract.EndContractBlock(); m_customBuilder = customBuilder; } - [System.Security.SecurityCritical] // auto-generated public void Bake(ModuleBuilder module, int token) { if (m_customBuilder == null) @@ -105,13 +103,13 @@ namespace System.Reflection.Emit { // if we wanted to but that just complicates things so these checks are designed to prevent that scenario. if (method.IsGenericMethod && !method.IsGenericMethodDefinition) - throw new ArgumentException(Environment.GetResourceString("Argument_NeedGenericMethodDefinition"), "method"); + throw new ArgumentException(Environment.GetResourceString("Argument_NeedGenericMethodDefinition"), nameof(method)); if (method.DeclaringType == null || !method.DeclaringType.IsGenericTypeDefinition) - throw new ArgumentException(Environment.GetResourceString("Argument_MethodNeedGenericDeclaringType"), "method"); + throw new ArgumentException(Environment.GetResourceString("Argument_MethodNeedGenericDeclaringType"), nameof(method)); if (type.GetGenericTypeDefinition() != method.DeclaringType) - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidMethodDeclaringType"), "type"); + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidMethodDeclaringType"), nameof(type)); Contract.EndContractBlock(); // The following converts from Type or TypeBuilder of G<T> to TypeBuilderInstantiation G<T>. These types @@ -121,7 +119,7 @@ namespace System.Reflection.Emit { type = type.MakeGenericType(type.GetGenericArguments()); if (!(type is TypeBuilderInstantiation)) - throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), "type"); + throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), nameof(type)); return MethodOnTypeBuilderInstantiation.GetMethod(method, type as TypeBuilderInstantiation); } @@ -131,18 +129,18 @@ namespace System.Reflection.Emit { throw new ArgumentException(Environment.GetResourceString("Argument_MustBeTypeBuilder")); if (!constructor.DeclaringType.IsGenericTypeDefinition) - throw new ArgumentException(Environment.GetResourceString("Argument_ConstructorNeedGenericDeclaringType"), "constructor"); + throw new ArgumentException(Environment.GetResourceString("Argument_ConstructorNeedGenericDeclaringType"), nameof(constructor)); Contract.EndContractBlock(); if (!(type is TypeBuilderInstantiation)) - throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), "type"); + throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), nameof(type)); // TypeBuilder G<T> ==> TypeBuilderInstantiation G<T> if (type is TypeBuilder && type.IsGenericTypeDefinition) type = type.MakeGenericType(type.GetGenericArguments()); if (type.GetGenericTypeDefinition() != constructor.DeclaringType) - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidConstructorDeclaringType"), "type"); + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidConstructorDeclaringType"), nameof(type)); return ConstructorOnTypeBuilderInstantiation.GetConstructor(constructor, type as TypeBuilderInstantiation); } @@ -152,18 +150,18 @@ namespace System.Reflection.Emit { throw new ArgumentException(Environment.GetResourceString("Argument_MustBeTypeBuilder")); if (!field.DeclaringType.IsGenericTypeDefinition) - throw new ArgumentException(Environment.GetResourceString("Argument_FieldNeedGenericDeclaringType"), "field"); + throw new ArgumentException(Environment.GetResourceString("Argument_FieldNeedGenericDeclaringType"), nameof(field)); Contract.EndContractBlock(); if (!(type is TypeBuilderInstantiation)) - throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), "type"); + throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), nameof(type)); // TypeBuilder G<T> ==> TypeBuilderInstantiation G<T> if (type is TypeBuilder && type.IsGenericTypeDefinition) type = type.MakeGenericType(type.GetGenericArguments()); if (type.GetGenericTypeDefinition() != field.DeclaringType) - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFieldDeclaringType"), "type"); + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFieldDeclaringType"), nameof(type)); return FieldOnTypeBuilderInstantiation.GetField(field, type as TypeBuilderInstantiation); } @@ -174,36 +172,30 @@ namespace System.Reflection.Emit { #endregion #region Private Static FCalls - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void SetParentType(RuntimeModule module, int tdTypeDef, int tkParent); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void AddInterfaceImpl(RuntimeModule module, int tdTypeDef, int tkInterface); #endregion #region Internal Static FCalls - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] internal static extern int DefineMethod(RuntimeModule module, int tkParent, String name, byte[] signature, int sigLength, MethodAttributes attributes); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] internal static extern int DefineMethodSpec(RuntimeModule module, int tkParent, byte[] signature, int sigLength); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] internal static extern int DefineField(RuntimeModule module, int tkParent, String name, byte[] signature, int sigLength, FieldAttributes attributes); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void SetMethodIL(RuntimeModule module, int tk, bool isInitLocals, @@ -213,13 +205,11 @@ namespace System.Reflection.Emit { ExceptionHandler[] exceptions, int numExceptions, int [] tokenFixups, int numTokenFixups); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void DefineCustomAttribute(RuntimeModule module, int tkAssociate, int tkConstructor, byte[] attr, int attrLength, bool toDisk, bool updateCompilerFlags); - [System.Security.SecurityCritical] // auto-generated internal static void DefineCustomAttribute(ModuleBuilder module, int tkAssociate, int tkConstructor, byte[] attr, bool toDisk, bool updateCompilerFlags) { @@ -235,75 +225,56 @@ namespace System.Reflection.Emit { localAttr, (localAttr != null) ? localAttr.Length : 0, toDisk, updateCompilerFlags); } - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] internal static extern void SetPInvokeData(RuntimeModule module, String DllName, String name, int token, int linkFlags); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] internal static extern int DefineProperty(RuntimeModule module, int tkParent, String name, PropertyAttributes attributes, byte[] signature, int sigLength); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] internal static extern int DefineEvent(RuntimeModule module, int tkParent, String name, EventAttributes attributes, int tkEventType); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] internal static extern void DefineMethodSemantics(RuntimeModule module, int tkAssociation, MethodSemanticsAttributes semantics, int tkMethod); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] internal static extern void DefineMethodImpl(RuntimeModule module, int tkType, int tkBody, int tkDecl); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] internal static extern void SetMethodImpl(RuntimeModule module, int tkMethod, MethodImplAttributes MethodImplAttributes); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] internal static extern int SetParamInfo(RuntimeModule module, int tkMethod, int iSequence, ParameterAttributes iParamAttributes, String strParamName); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] internal static extern int GetTokenFromSig(RuntimeModule module, byte[] signature, int sigLength); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] internal static extern void SetFieldLayoutOffset(RuntimeModule module, int fdToken, int iOffset); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] internal static extern void SetClassLayout(RuntimeModule module, int tk, PackingSize iPackingSize, int iTypeSize); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] internal static extern void SetFieldMarshal(RuntimeModule module, int tk, byte[] ubMarshal, int ubSize); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern unsafe void SetConstantValue(RuntimeModule module, int tk, int corType, void* pValue); - -#if FEATURE_CAS_POLICY - [System.Security.SecurityCritical] // auto-generated - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - internal static extern void AddDeclarativeSecurity(RuntimeModule module, int parent, SecurityAction action, byte[] blob, int cb); -#endif #endregion #region Internal\Private Static Members @@ -381,7 +352,6 @@ namespace System.Reflection.Emit { return false; } - [System.Security.SecurityCritical] // auto-generated internal static unsafe void SetConstantValue(ModuleBuilder module, int tk, Type destType, Object value) { // This is a helper function that is used by ParameterBuilder, PropertyBuilder, @@ -433,7 +403,7 @@ namespace System.Reflection.Emit { } else // must be a runtime Enum Type { - Contract.Assert(destType is RuntimeType, "destType is not a runtime type, an EnumBuilder, or a TypeBuilder."); + Debug.Assert(destType is RuntimeType, "destType is not a runtime type, an EnumBuilder, or a TypeBuilder."); underlyingType = Enum.GetUnderlyingType(destType); @@ -576,7 +546,6 @@ namespace System.Reflection.Emit { m_typeInterfaces = new List<Type>(); } - [System.Security.SecurityCritical] // auto-generated internal TypeBuilder( String name, TypeAttributes attr, @@ -590,22 +559,21 @@ namespace System.Reflection.Emit { Init(name, attr, parent, interfaces, module, iPackingSize, iTypeSize, enclosingType); } - [System.Security.SecurityCritical] // auto-generated private void Init(String fullname, TypeAttributes attr, Type parent, Type[] interfaces, ModuleBuilder module, PackingSize iPackingSize, int iTypeSize, TypeBuilder enclosingType) { if (fullname == null) - throw new ArgumentNullException("fullname"); + throw new ArgumentNullException(nameof(fullname)); if (fullname.Length == 0) - throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "fullname"); + throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(fullname)); if (fullname[0] == '\0') - throw new ArgumentException(Environment.GetResourceString("Argument_IllegalName"), "fullname"); + throw new ArgumentException(Environment.GetResourceString("Argument_IllegalName"), nameof(fullname)); if (fullname.Length > 1023) - throw new ArgumentException(Environment.GetResourceString("Argument_TypeNameTooLong"), "fullname"); + throw new ArgumentException(Environment.GetResourceString("Argument_TypeNameTooLong"), nameof(fullname)); Contract.EndContractBlock(); int i; @@ -621,7 +589,7 @@ namespace System.Reflection.Emit { // Nested Type should have nested attribute set. // If we are renumbering TypeAttributes' bit, we need to change the logic here. if (((attr & TypeAttributes.VisibilityMask) == TypeAttributes.Public) ||((attr & TypeAttributes.VisibilityMask) == TypeAttributes.NotPublic)) - throw new ArgumentException(Environment.GetResourceString("Argument_BadNestedTypeFlags"), "attr"); + throw new ArgumentException(Environment.GetResourceString("Argument_BadNestedTypeFlags"), nameof(attr)); } int[] interfaceTokens = null; @@ -632,7 +600,7 @@ namespace System.Reflection.Emit { if (interfaces[i] == null) { // cannot contain null in the interface list - throw new ArgumentNullException("interfaces"); + throw new ArgumentNullException(nameof(interfaces)); } } interfaceTokens = new int[interfaces.Length + 1]; @@ -685,32 +653,12 @@ namespace System.Reflection.Emit { if ((m_iPackingSize != 0) ||(m_iTypeSize != 0)) SetClassLayout(GetModuleBuilder().GetNativeHandle(), m_tdType.Token, m_iPackingSize, m_iTypeSize); -#if !FEATURE_CORECLR - // If the type is public and it is contained in a assemblyBuilder, - // update the public COMType list. - if (IsPublicComType(this)) - { - if (containingAssem.IsPersistable() && m_module.IsTransient() == false) - { - // This will throw InvalidOperationException if the assembly has been saved - // Ideally we should reject all emit operations if the assembly has been saved, - // but that would be a breaking change for some. Currently you cannot define - // modules and public types, but you can still define private types and global methods. - containingAssem.m_assemblyData.AddPublicComType(this); - } - - // Now add the type to the ExportedType table - if (!m_module.Equals(containingAssem.ManifestModule)) - containingAssem.DefineExportedTypeInMemory(this, m_module.m_moduleData.FileToken, m_tdType.Token); - } -#endif m_module.AddType(FullName, this); } #endregion #region Private Members - [System.Security.SecurityCritical] // auto-generated private MethodBuilder DefinePInvokeMethodHelper( String name, String dllName, String importName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, @@ -733,7 +681,6 @@ namespace System.Reflection.Emit { } } - [System.Security.SecurityCritical] // auto-generated private MethodBuilder DefinePInvokeMethodHelperNoLock( String name, String dllName, String importName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, @@ -741,22 +688,22 @@ namespace System.Reflection.Emit { CallingConvention nativeCallConv, CharSet nativeCharSet) { if (name == null) - throw new ArgumentNullException("name"); + throw new ArgumentNullException(nameof(name)); if (name.Length == 0) - throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name"); + throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name)); if (dllName == null) - throw new ArgumentNullException("dllName"); + throw new ArgumentNullException(nameof(dllName)); if (dllName.Length == 0) - throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "dllName"); + throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(dllName)); if (importName == null) - throw new ArgumentNullException("importName"); + throw new ArgumentNullException(nameof(importName)); if (importName.Length == 0) - throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "importName"); + throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(importName)); if ((attributes & MethodAttributes.Abstract) != 0) throw new ArgumentException(Environment.GetResourceString("Argument_BadPInvokeMethod")); @@ -831,7 +778,6 @@ namespace System.Reflection.Emit { return method; } - [System.Security.SecurityCritical] // auto-generated private FieldBuilder DefineDataHelper(String name, byte[] data, int size, FieldAttributes attributes) { String strValueClassName; @@ -840,10 +786,10 @@ namespace System.Reflection.Emit { TypeAttributes typeAttributes; if (name == null) - throw new ArgumentNullException("name"); + throw new ArgumentNullException(nameof(name)); if (name.Length == 0) - throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name"); + throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name)); if (size <= 0 || size >= 0x003f0000) throw new ArgumentException(Environment.GetResourceString("Argument_BadSizeForData")); @@ -916,19 +862,16 @@ namespace System.Reflection.Emit { #endregion #region FCalls - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static int DefineType(RuntimeModule module, String fullname, int tkParent, TypeAttributes attributes, int tkEnclosingType, int[] interfaceTokens); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static int DefineGenericParam(RuntimeModule module, String name, int tkParent, GenericParameterAttributes attributes, int position, int[] constraints); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void TermCreateClass(RuntimeModule module, int tk, ObjectHandleOnStack type); @@ -1363,38 +1306,17 @@ namespace System.Reflection.Emit { public override bool IsSecurityCritical { - get - { - if (!IsCreated()) - throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated")); - Contract.EndContractBlock(); - - return m_bakedRuntimeType.IsSecurityCritical; - } + get { return true; } } public override bool IsSecuritySafeCritical { - get - { - if (!IsCreated()) - throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated")); - Contract.EndContractBlock(); - - return m_bakedRuntimeType.IsSecuritySafeCritical; - } + get { return false; } } public override bool IsSecurityTransparent { - get - { - if (!IsCreated()) - throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated")); - Contract.EndContractBlock(); - - return m_bakedRuntimeType.IsSecurityTransparent; - } + get { return false; } } [System.Runtime.InteropServices.ComVisible(true)] @@ -1479,7 +1401,6 @@ namespace System.Reflection.Emit { #endregion #region ICustomAttributeProvider Implementation - [System.Security.SecuritySafeCritical] // auto-generated public override Object[] GetCustomAttributes(bool inherit) { if (!IsCreated()) @@ -1489,38 +1410,36 @@ namespace System.Reflection.Emit { return CustomAttribute.GetCustomAttributes(m_bakedRuntimeType, typeof(object) as RuntimeType, inherit); } - [System.Security.SecuritySafeCritical] // auto-generated public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (!IsCreated()) throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated")); if (attributeType == null) - throw new ArgumentNullException("attributeType"); + throw new ArgumentNullException(nameof(attributeType)); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType"); + throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType)); return CustomAttribute.GetCustomAttributes(m_bakedRuntimeType, attributeRuntimeType, inherit); } - [System.Security.SecuritySafeCritical] // auto-generated public override bool IsDefined(Type attributeType, bool inherit) { if (!IsCreated()) throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated")); if (attributeType == null) - throw new ArgumentNullException("attributeType"); + throw new ArgumentNullException(nameof(attributeType)); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"caType"); + throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType)); return CustomAttribute.IsDefined(m_bakedRuntimeType, attributeRuntimeType, inherit); } @@ -1547,7 +1466,7 @@ namespace System.Reflection.Emit { public GenericTypeParameterBuilder[] DefineGenericParameters(params string[] names) { if (names == null) - throw new ArgumentNullException("names"); + throw new ArgumentNullException(nameof(names)); if (names.Length == 0) throw new ArgumentException(); @@ -1555,7 +1474,7 @@ namespace System.Reflection.Emit { for (int i = 0; i < names.Length; i ++) if (names[i] == null) - throw new ArgumentNullException("names"); + throw new ArgumentNullException(nameof(names)); if (m_inst != null) throw new InvalidOperationException(); @@ -1589,7 +1508,6 @@ namespace System.Reflection.Emit { #endregion #region Define Method - [System.Security.SecuritySafeCritical] // auto-generated public void DefineMethodOverride(MethodInfo methodInfoBody, MethodInfo methodInfoDeclaration) { lock(SyncRoot) @@ -1598,14 +1516,13 @@ namespace System.Reflection.Emit { } } - [System.Security.SecurityCritical] // auto-generated private void DefineMethodOverrideNoLock(MethodInfo methodInfoBody, MethodInfo methodInfoDeclaration) { if (methodInfoBody == null) - throw new ArgumentNullException("methodInfoBody"); + throw new ArgumentNullException(nameof(methodInfoBody)); if (methodInfoDeclaration == null) - throw new ArgumentNullException("methodInfoDeclaration"); + throw new ArgumentNullException(nameof(methodInfoDeclaration)); Contract.EndContractBlock(); ThrowIfCreated(); @@ -1671,10 +1588,10 @@ namespace System.Reflection.Emit { Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers) { if (name == null) - throw new ArgumentNullException("name"); + throw new ArgumentNullException(nameof(name)); if (name.Length == 0) - throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name"); + throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name)); Contract.Ensures(Contract.Result<MethodBuilder>() != null); Contract.EndContractBlock(); @@ -1686,10 +1603,10 @@ namespace System.Reflection.Emit { if (parameterTypes != null) { if (parameterTypeOptionalCustomModifiers != null && parameterTypeOptionalCustomModifiers.Length != parameterTypes.Length) - throw new ArgumentException(Environment.GetResourceString("Argument_MismatchedArrays", "parameterTypeOptionalCustomModifiers", "parameterTypes")); + throw new ArgumentException(Environment.GetResourceString("Argument_MismatchedArrays", nameof(parameterTypeOptionalCustomModifiers), nameof(parameterTypes))); if (parameterTypeRequiredCustomModifiers != null && parameterTypeRequiredCustomModifiers.Length != parameterTypes.Length) - throw new ArgumentException(Environment.GetResourceString("Argument_MismatchedArrays", "parameterTypeRequiredCustomModifiers", "parameterTypes")); + throw new ArgumentException(Environment.GetResourceString("Argument_MismatchedArrays", nameof(parameterTypeRequiredCustomModifiers), nameof(parameterTypes))); } ThrowIfCreated(); @@ -1725,7 +1642,6 @@ namespace System.Reflection.Emit { #endregion #region Define Constructor - [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(true)] public ConstructorBuilder DefineTypeInitializer() { @@ -1735,7 +1651,6 @@ namespace System.Reflection.Emit { } } - [System.Security.SecurityCritical] // auto-generated private ConstructorBuilder DefineTypeInitializerNoLock() { ThrowIfCreated(); @@ -1823,7 +1738,6 @@ namespace System.Reflection.Emit { return DefineConstructor(attributes, callingConvention, parameterTypes, null, null); } - [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(true)] public ConstructorBuilder DefineConstructor(MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers) @@ -1839,7 +1753,6 @@ namespace System.Reflection.Emit { } } - [System.Security.SecurityCritical] // auto-generated private ConstructorBuilder DefineConstructorNoLock(MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers) { @@ -1874,11 +1787,6 @@ namespace System.Reflection.Emit { #endregion #region Define PInvoke -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#else - [System.Security.SecuritySafeCritical] -#endif public MethodBuilder DefinePInvokeMethod(String name, String dllName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) @@ -1889,11 +1797,6 @@ namespace System.Reflection.Emit { return method; } -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#else - [System.Security.SecuritySafeCritical] -#endif public MethodBuilder DefinePInvokeMethod(String name, String dllName, String entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) @@ -1904,11 +1807,6 @@ namespace System.Reflection.Emit { return method; } -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#else - [System.Security.SecuritySafeCritical] -#endif public MethodBuilder DefinePInvokeMethod(String name, String dllName, String entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, @@ -1924,7 +1822,6 @@ namespace System.Reflection.Emit { #endregion #region Define Nested Type - [System.Security.SecuritySafeCritical] // auto-generated public TypeBuilder DefineNestedType(String name) { lock(SyncRoot) @@ -1933,7 +1830,6 @@ namespace System.Reflection.Emit { } } - [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(true)] public TypeBuilder DefineNestedType(String name, TypeAttributes attr, Type parent, Type[] interfaces) { @@ -1947,7 +1843,6 @@ namespace System.Reflection.Emit { } } - [System.Security.SecuritySafeCritical] // auto-generated public TypeBuilder DefineNestedType(String name, TypeAttributes attr, Type parent) { lock(SyncRoot) @@ -1956,7 +1851,6 @@ namespace System.Reflection.Emit { } } - [System.Security.SecuritySafeCritical] // auto-generated public TypeBuilder DefineNestedType(String name, TypeAttributes attr) { lock(SyncRoot) @@ -1965,11 +1859,6 @@ namespace System.Reflection.Emit { } } -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#else - [System.Security.SecuritySafeCritical] -#endif public TypeBuilder DefineNestedType(String name, TypeAttributes attr, Type parent, int typeSize) { lock(SyncRoot) @@ -1978,11 +1867,6 @@ namespace System.Reflection.Emit { } } -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#else - [System.Security.SecuritySafeCritical] -#endif public TypeBuilder DefineNestedType(String name, TypeAttributes attr, Type parent, PackingSize packSize) { lock(SyncRoot) @@ -1991,11 +1875,6 @@ namespace System.Reflection.Emit { } } -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#else - [System.Security.SecuritySafeCritical] -#endif public TypeBuilder DefineNestedType(String name, TypeAttributes attr, Type parent, PackingSize packSize, int typeSize) { lock (SyncRoot) @@ -2004,7 +1883,6 @@ namespace System.Reflection.Emit { } } - [System.Security.SecurityCritical] // auto-generated private TypeBuilder DefineNestedTypeNoLock(String name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packSize, int typeSize) { return new TypeBuilder(name, attr, parent, interfaces, m_module, packSize, typeSize, this); @@ -2018,7 +1896,6 @@ namespace System.Reflection.Emit { return DefineField(fieldName, type, null, null, attributes); } - [System.Security.SecuritySafeCritical] // auto-generated public FieldBuilder DefineField(String fieldName, Type type, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers, FieldAttributes attributes) { @@ -2028,7 +1905,6 @@ namespace System.Reflection.Emit { } } - [System.Security.SecurityCritical] // auto-generated private FieldBuilder DefineFieldNoLock(String fieldName, Type type, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers, FieldAttributes attributes) { @@ -2048,11 +1924,6 @@ namespace System.Reflection.Emit { return new FieldBuilder(this, fieldName, type, requiredCustomModifiers, optionalCustomModifiers, attributes); } -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#else - [System.Security.SecuritySafeCritical] -#endif public FieldBuilder DefineInitializedData(String name, byte[] data, FieldAttributes attributes) { lock(SyncRoot) @@ -2061,11 +1932,10 @@ namespace System.Reflection.Emit { } } - [System.Security.SecurityCritical] // auto-generated private FieldBuilder DefineInitializedDataNoLock(String name, byte[] data, FieldAttributes attributes) { if (data == null) - throw new ArgumentNullException("data"); + throw new ArgumentNullException(nameof(data)); Contract.EndContractBlock(); // This method will define an initialized Data in .sdata. @@ -2075,11 +1945,6 @@ namespace System.Reflection.Emit { return DefineDataHelper(name, data, data.Length, attributes); } -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#else - [System.Security.SecuritySafeCritical] -#endif public FieldBuilder DefineUninitializedData(String name, int size, FieldAttributes attributes) { lock(SyncRoot) @@ -2088,7 +1953,6 @@ namespace System.Reflection.Emit { } } - [System.Security.SecurityCritical] // auto-generated private FieldBuilder DefineUninitializedDataNoLock(String name, int size, FieldAttributes attributes) { // This method will define an uninitialized Data in .sdata. @@ -2121,7 +1985,6 @@ namespace System.Reflection.Emit { parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers); } - [System.Security.SecuritySafeCritical] // auto-generated public PropertyBuilder DefineProperty(String name, PropertyAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers) @@ -2133,15 +1996,14 @@ namespace System.Reflection.Emit { } } - [System.Security.SecurityCritical] // auto-generated private PropertyBuilder DefinePropertyNoLock(String name, PropertyAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers) { if (name == null) - throw new ArgumentNullException("name"); + throw new ArgumentNullException(nameof(name)); if (name.Length == 0) - throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name"); + throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name)); Contract.EndContractBlock(); CheckContext(returnType); @@ -2183,7 +2045,6 @@ namespace System.Reflection.Emit { this); } - [System.Security.SecuritySafeCritical] // auto-generated public EventBuilder DefineEvent(String name, EventAttributes attributes, Type eventtype) { lock(SyncRoot) @@ -2192,15 +2053,14 @@ namespace System.Reflection.Emit { } } - [System.Security.SecurityCritical] // auto-generated private EventBuilder DefineEventNoLock(String name, EventAttributes attributes, Type eventtype) { if (name == null) - throw new ArgumentNullException("name"); + throw new ArgumentNullException(nameof(name)); if (name.Length == 0) - throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name"); + throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name)); if (name[0] == '\0') - throw new ArgumentException(Environment.GetResourceString("Argument_IllegalName"), "name"); + throw new ArgumentException(Environment.GetResourceString("Argument_IllegalName"), nameof(name)); Contract.EndContractBlock(); int tkType; @@ -2234,7 +2094,6 @@ namespace System.Reflection.Emit { #region Create Type - [System.Security.SecuritySafeCritical] // auto-generated public TypeInfo CreateTypeInfo() { lock (SyncRoot) @@ -2243,7 +2102,6 @@ namespace System.Reflection.Emit { } } - [System.Security.SecuritySafeCritical] // auto-generated public Type CreateType() { lock (SyncRoot) @@ -2261,7 +2119,6 @@ namespace System.Reflection.Emit { m_module.CheckContext(types); } - [System.Security.SecurityCritical] // auto-generated private TypeInfo CreateTypeNoLock() { if (IsCreated()) @@ -2486,13 +2343,12 @@ namespace System.Reflection.Emit { } } - [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(true)] public void AddInterfaceImplementation(Type interfaceType) { if (interfaceType == null) { - throw new ArgumentNullException("interfaceType"); + throw new ArgumentNullException(nameof(interfaceType)); } Contract.EndContractBlock(); @@ -2506,50 +2362,6 @@ namespace System.Reflection.Emit { m_typeInterfaces.Add(interfaceType); } -#if FEATURE_CAS_POLICY - [System.Security.SecuritySafeCritical] // auto-generated - public void AddDeclarativeSecurity(SecurityAction action, PermissionSet pset) - { - lock(SyncRoot) - { - AddDeclarativeSecurityNoLock(action, pset); - } - } - - [System.Security.SecurityCritical] // auto-generated - private void AddDeclarativeSecurityNoLock(SecurityAction action, PermissionSet pset) - { - if (pset == null) - throw new ArgumentNullException("pset"); - -#pragma warning disable 618 - if (!Enum.IsDefined(typeof(SecurityAction), action) || - action == SecurityAction.RequestMinimum || - action == SecurityAction.RequestOptional || - action == SecurityAction.RequestRefuse) - { - throw new ArgumentOutOfRangeException("action"); - } -#pragma warning restore 618 - - Contract.EndContractBlock(); - - ThrowIfCreated(); - - // Translate permission set into serialized format(uses standard binary serialization format). - byte[] blob = null; - int length = 0; - if (!pset.IsEmpty()) - { - blob = pset.EncodeXml(); - length = blob.Length; - } - - // Write the blob into the metadata. - AddDeclarativeSecurity(m_module.GetNativeHandle(), m_tdType.Token, action, blob, length); - } -#endif // FEATURE_CAS_POLICY - public TypeToken TypeToken { get @@ -2562,30 +2374,24 @@ public TypeToken TypeToken } -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#else - [System.Security.SecuritySafeCritical] -#endif [System.Runtime.InteropServices.ComVisible(true)] public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { if (con == null) - throw new ArgumentNullException("con"); + throw new ArgumentNullException(nameof(con)); if (binaryAttribute == null) - throw new ArgumentNullException("binaryAttribute"); + throw new ArgumentNullException(nameof(binaryAttribute)); Contract.EndContractBlock(); TypeBuilder.DefineCustomAttribute(m_module, m_tdType.Token, ((ModuleBuilder)m_module).GetConstructorToken(con).Token, binaryAttribute, false, false); } - [System.Security.SecuritySafeCritical] // auto-generated public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { if (customBuilder == null) - throw new ArgumentNullException("customBuilder"); + throw new ArgumentNullException(nameof(customBuilder)); Contract.EndContractBlock(); customBuilder.CreateCustomAttribute((ModuleBuilder)m_module, m_tdType.Token); @@ -2594,27 +2400,5 @@ public TypeToken TypeToken #endregion #endregion - -#if !FEATURE_CORECLR - void _TypeBuilder.GetTypeInfoCount(out uint pcTInfo) - { - throw new NotImplementedException(); - } - - void _TypeBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) - { - throw new NotImplementedException(); - } - - void _TypeBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) - { - throw new NotImplementedException(); - } - - void _TypeBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) - { - throw new NotImplementedException(); - } -#endif } } diff --git a/src/mscorlib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs b/src/mscorlib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs index 13b98b6543..3bae585953 100644 --- a/src/mscorlib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs +++ b/src/mscorlib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs @@ -28,13 +28,13 @@ namespace System.Reflection.Emit throw new InvalidOperationException(); if (typeArguments == null) - throw new ArgumentNullException("typeArguments"); + throw new ArgumentNullException(nameof(typeArguments)); Contract.EndContractBlock(); foreach (Type t in typeArguments) { if (t == null) - throw new ArgumentNullException("typeArguments"); + throw new ArgumentNullException(nameof(typeArguments)); } return new TypeBuilderInstantiation(type, typeArguments); diff --git a/src/mscorlib/src/System/Reflection/Emit/UnmanagedMarshal.cs b/src/mscorlib/src/System/Reflection/Emit/UnmanagedMarshal.cs index 09eac3a272..28e95e2456 100644 --- a/src/mscorlib/src/System/Reflection/Emit/UnmanagedMarshal.cs +++ b/src/mscorlib/src/System/Reflection/Emit/UnmanagedMarshal.cs @@ -10,7 +10,6 @@ namespace System.Reflection.Emit // This class is describing the fieldmarshal. [Serializable] - [HostProtection(MayLeakOnAbort = true)] [System.Runtime.InteropServices.ComVisible(true)] [Obsolete("An alternate API is available: Emit the MarshalAs custom attribute instead. http://go.microsoft.com/fwlink/?linkid=14202")] public sealed class UnmanagedMarshal diff --git a/src/mscorlib/src/System/Reflection/Emit/XXXOnTypeBuilderInstantiation.cs b/src/mscorlib/src/System/Reflection/Emit/XXXOnTypeBuilderInstantiation.cs index 5b36e0e372..aaaffc0df6 100644 --- a/src/mscorlib/src/System/Reflection/Emit/XXXOnTypeBuilderInstantiation.cs +++ b/src/mscorlib/src/System/Reflection/Emit/XXXOnTypeBuilderInstantiation.cs @@ -11,6 +11,7 @@ namespace System.Reflection.Emit using System.Collections; using System.Collections.Generic; using System.Globalization; + using System.Diagnostics; using System.Diagnostics.Contracts; internal sealed class MethodOnTypeBuilderInstantiation : MethodInfo @@ -30,7 +31,7 @@ namespace System.Reflection.Emit #region Constructor internal MethodOnTypeBuilderInstantiation(MethodInfo method, TypeBuilderInstantiation type) { - Contract.Assert(method is MethodBuilder || method is RuntimeMethodInfo); + Debug.Assert(method is MethodBuilder || method is RuntimeMethodInfo); m_method = method; m_type = type; @@ -60,7 +61,7 @@ namespace System.Reflection.Emit return mb.MetadataTokenInternal; else { - Contract.Assert(m_method is RuntimeMethodInfo); + Debug.Assert(m_method is RuntimeMethodInfo); return m_method.MetadataToken; } } @@ -122,7 +123,7 @@ namespace System.Reflection.Emit #region Constructor internal ConstructorOnTypeBuilderInstantiation(ConstructorInfo constructor, TypeBuilderInstantiation type) { - Contract.Assert(constructor is ConstructorBuilder || constructor is RuntimeConstructorInfo); + Debug.Assert(constructor is ConstructorBuilder || constructor is RuntimeConstructorInfo); m_ctor = constructor; m_type = type; @@ -157,7 +158,7 @@ namespace System.Reflection.Emit return cb.MetadataTokenInternal; else { - Contract.Assert(m_ctor is RuntimeConstructorInfo); + Debug.Assert(m_ctor is RuntimeConstructorInfo); return m_ctor.MetadataToken; } } @@ -231,7 +232,7 @@ namespace System.Reflection.Emit #region Constructor internal FieldOnTypeBuilderInstantiation(FieldInfo field, TypeBuilderInstantiation type) { - Contract.Assert(field is FieldBuilder || field is RuntimeFieldInfo); + Debug.Assert(field is FieldBuilder || field is RuntimeFieldInfo); m_field = field; m_type = type; @@ -258,7 +259,7 @@ namespace System.Reflection.Emit return fb.MetadataTokenInternal; else { - Contract.Assert(m_field is RuntimeFieldInfo); + Debug.Assert(m_field is RuntimeFieldInfo); return m_field.MetadataToken; } } diff --git a/src/mscorlib/src/System/Reflection/EventInfo.cs b/src/mscorlib/src/System/Reflection/EventInfo.cs index 3fd1951b6c..0eabb9d03a 100644 --- a/src/mscorlib/src/System/Reflection/EventInfo.cs +++ b/src/mscorlib/src/System/Reflection/EventInfo.cs @@ -19,9 +19,6 @@ namespace System.Reflection [Serializable] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_EventInfo))] -#pragma warning disable 618 - [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")] -#pragma warning restore 618 [System.Runtime.InteropServices.ComVisible(true)] public abstract class EventInfo : MemberInfo, _EventInfo { @@ -123,7 +120,7 @@ namespace System.Reflection throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotSupportedOnWinRTEvent")); // Must be a normal non-WinRT event - Contract.Assert(addMethod.ReturnType == typeof(void)); + Debug.Assert(addMethod.ReturnType == typeof(void)); #endif // FEATURE_COMINTEROP addMethod.Invoke(target, new object[] { handler }); @@ -140,13 +137,13 @@ namespace System.Reflection #if FEATURE_COMINTEROP ParameterInfo[] parameters = removeMethod.GetParametersNoCopy(); - Contract.Assert(parameters != null && parameters.Length == 1); + Debug.Assert(parameters != null && parameters.Length == 1); if (parameters[0].ParameterType == typeof(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotSupportedOnWinRTEvent")); // Must be a normal non-WinRT event - Contract.Assert(parameters[0].ParameterType.BaseType == typeof(MulticastDelegate)); + Debug.Assert(parameters[0].ParameterType.BaseType == typeof(MulticastDelegate)); #endif // FEATURE_COMINTEROP removeMethod.Invoke(target, new object[] { handler }); @@ -190,35 +187,6 @@ namespace System.Reflection } } #endregion - -#if !FEATURE_CORECLR - Type _EventInfo.GetType() - { - return base.GetType(); - } - - void _EventInfo.GetTypeInfoCount(out uint pcTInfo) - { - throw new NotImplementedException(); - } - - void _EventInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) - { - throw new NotImplementedException(); - } - - void _EventInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) - { - throw new NotImplementedException(); - } - - // If you implement this method, make sure to include _EventInfo.Invoke in VM\DangerousAPIs.h and - // include _EventInfo in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp. - void _EventInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) - { - throw new NotImplementedException(); - } -#endif } [Serializable] @@ -228,7 +196,6 @@ namespace System.Reflection private int m_token; private EventAttributes m_flags; private string m_name; - [System.Security.SecurityCritical] private void* m_utf8name; private RuntimeTypeCache m_reflectedTypeCache; private RuntimeMethodInfo m_addMethod; @@ -244,12 +211,11 @@ namespace System.Reflection { // Used for dummy head node during population } - [System.Security.SecurityCritical] // auto-generated internal RuntimeEventInfo(int tkEvent, RuntimeType declaredType, RuntimeTypeCache reflectedTypeCache, out bool isPrivate) { Contract.Requires(declaredType != null); Contract.Requires(reflectedTypeCache != null); - Contract.Assert(!reflectedTypeCache.IsGlobal); + Debug.Assert(!reflectedTypeCache.IsGlobal); MetadataImport scope = declaredType.GetRuntimeModule().MetadataImport; @@ -305,28 +271,27 @@ namespace System.Reflection public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) - throw new ArgumentNullException("attributeType"); + throw new ArgumentNullException(nameof(attributeType)); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType"); + throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType)); return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType); } - [System.Security.SecuritySafeCritical] // auto-generated public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) - throw new ArgumentNullException("attributeType"); + throw new ArgumentNullException(nameof(attributeType)); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType"); + throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType)); return CustomAttribute.IsDefined(this, attributeRuntimeType); } @@ -341,7 +306,6 @@ namespace System.Reflection public override MemberTypes MemberType { get { return MemberTypes.Event; } } public override String Name { - [System.Security.SecuritySafeCritical] // auto-generated get { if (m_name == null) @@ -373,11 +337,10 @@ namespace System.Reflection #endregion #region ISerializable - [System.Security.SecurityCritical] // auto-generated_required public void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) - throw new ArgumentNullException("info"); + throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); MemberInfoSerializationHolder.GetSerializationInfo( diff --git a/src/mscorlib/src/System/Reflection/FieldInfo.cs b/src/mscorlib/src/System/Reflection/FieldInfo.cs index c6a44d412b..e61207a686 100644 --- a/src/mscorlib/src/System/Reflection/FieldInfo.cs +++ b/src/mscorlib/src/System/Reflection/FieldInfo.cs @@ -15,9 +15,6 @@ namespace System.Reflection using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; -#if FEATURE_REMOTING - using System.Runtime.Remoting.Metadata; -#endif //FEATURE_REMOTING using System.Runtime.Serialization; using System.Security.Permissions; using System.Threading; @@ -26,9 +23,6 @@ namespace System.Reflection [Serializable] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_FieldInfo))] -#pragma warning disable 618 - [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")] -#pragma warning restore 618 [System.Runtime.InteropServices.ComVisible(true)] public abstract class FieldInfo : MemberInfo, _FieldInfo { @@ -36,7 +30,7 @@ namespace System.Reflection public static FieldInfo GetFieldFromHandle(RuntimeFieldHandle handle) { if (handle.IsNullHandle()) - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHandle"), "handle"); + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHandle"), nameof(handle)); FieldInfo f = RuntimeType.GetFieldInfo(handle.GetRuntimeFieldInfo()); @@ -186,35 +180,6 @@ namespace System.Reflection } #endregion - -#if !FEATURE_CORECLR - Type _FieldInfo.GetType() - { - return base.GetType(); - } - - void _FieldInfo.GetTypeInfoCount(out uint pcTInfo) - { - throw new NotImplementedException(); - } - - void _FieldInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) - { - throw new NotImplementedException(); - } - - void _FieldInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) - { - throw new NotImplementedException(); - } - - // If you implement this method, make sure to include _FieldInfo.Invoke in VM\DangerousAPIs.h and - // include _FieldInfo in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp. - void _FieldInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) - { - throw new NotImplementedException(); - } -#endif } [Serializable] @@ -239,36 +204,6 @@ namespace System.Reflection } #endregion -#if FEATURE_REMOTING - #region Legacy Remoting Cache - // The size of CachedData is accounted for by BaseObjectWithCachedData in object.h. - // This member is currently being used by Remoting for caching remoting data. If you - // need to cache data here, talk to the Remoting team to work out a mechanism, so that - // both caching systems can happily work together. - private RemotingFieldCachedData m_cachedData; - - internal RemotingFieldCachedData RemotingCache - { - get - { - // This grabs an internal copy of m_cachedData and uses - // that instead of looking at m_cachedData directly because - // the cache may get cleared asynchronously. This prevents - // us from having to take a lock. - RemotingFieldCachedData cache = m_cachedData; - if (cache == null) - { - cache = new RemotingFieldCachedData(this); - RemotingFieldCachedData ret = Interlocked.CompareExchange(ref m_cachedData, cache, null); - if (ret != null) - cache = ret; - } - return cache; - } - } - #endregion -#endif //FEATURE_REMOTING - #region NonPublic Members internal BindingFlags BindingFlags { get { return m_bindingFlags; } } private RuntimeType ReflectedTypeInternal @@ -325,28 +260,27 @@ namespace System.Reflection public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) - throw new ArgumentNullException("attributeType"); + throw new ArgumentNullException(nameof(attributeType)); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType"); + throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType)); return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType); } - [System.Security.SecuritySafeCritical] // auto-generated public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) - throw new ArgumentNullException("attributeType"); + throw new ArgumentNullException(nameof(attributeType)); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType"); + throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType)); return CustomAttribute.IsDefined(this, attributeRuntimeType); } @@ -362,11 +296,10 @@ namespace System.Reflection #endregion #region ISerializable Implementation - [System.Security.SecurityCritical] // auto-generated public void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) - throw new ArgumentNullException("info"); + throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); MemberInfoSerializationHolder.GetSerializationInfo( info, @@ -382,7 +315,6 @@ namespace System.Reflection internal unsafe sealed class RtFieldInfo : RuntimeFieldInfo, IRuntimeFieldInfo { #region FCalls - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] static private extern void PerformVisibilityCheckOnField(IntPtr field, Object target, RuntimeType declaringType, FieldAttributes attr, uint invocationFlags); #endregion @@ -480,7 +412,6 @@ namespace System.Reflection private RuntimeAssembly GetRuntimeAssembly() { return m_declaringType.GetRuntimeAssembly(); } #region Constructor - [System.Security.SecurityCritical] // auto-generated internal RtFieldInfo( RuntimeFieldHandleInternal handle, RuntimeType declaringType, RuntimeTypeCache reflectedTypeCache, BindingFlags bindingFlags) : base(reflectedTypeCache, declaringType, bindingFlags) @@ -493,7 +424,6 @@ namespace System.Reflection #region Private Members RuntimeFieldHandleInternal IRuntimeFieldInfo.Value { - [System.Security.SecuritySafeCritical] get { return new RuntimeFieldHandleInternal(m_fieldHandle); @@ -535,7 +465,6 @@ namespace System.Reflection return m.m_fieldHandle == m_fieldHandle; } - [System.Security.SecurityCritical] [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] internal void InternalSetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture, ref StackCrawlMark stackMark) @@ -592,7 +521,6 @@ namespace System.Reflection // InternalSetValue() instead. When the caller needs to perform // consistency checks they should call CheckConsistency() before // calling this method. - [System.Security.SecurityCritical] // auto-generated [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] internal void UnsafeSetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) @@ -614,7 +542,6 @@ namespace System.Reflection } } - [System.Security.SecuritySafeCritical] [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] internal Object InternalGetValue(Object obj, ref StackCrawlMark stackMark) @@ -657,7 +584,6 @@ namespace System.Reflection // InternalGetValue() instead. When the caller needs to perform // consistency checks they should call CheckConsistency() before // calling this method. - [System.Security.SecurityCritical] [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] internal Object UnsafeGetValue(Object obj) @@ -685,7 +611,6 @@ namespace System.Reflection #region MemberInfo Overrides public override String Name { - [System.Security.SecuritySafeCritical] // auto-generated get { if (m_name == null) @@ -705,11 +630,9 @@ namespace System.Reflection public override int MetadataToken { - [System.Security.SecuritySafeCritical] // auto-generated get { return RuntimeFieldHandle.GetToken(this); } } - [System.Security.SecuritySafeCritical] // auto-generated internal override RuntimeModule GetRuntimeModule() { return RuntimeTypeHandle.GetModule(RuntimeFieldHandle.GetApproxDeclaringType(this)); @@ -726,7 +649,6 @@ namespace System.Reflection public override object GetRawConstantValue() { throw new InvalidOperationException(); } - [System.Security.SecuritySafeCritical] // auto-generated [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public override Object GetValueDirect(TypedReference obj) @@ -742,7 +664,6 @@ namespace System.Reflection } } - [System.Security.SecuritySafeCritical] // auto-generated [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) @@ -751,7 +672,6 @@ namespace System.Reflection InternalSetValue(obj, value, invokeAttr, binder, culture, ref stackMark); } - [System.Security.SecuritySafeCritical] // auto-generated [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public override void SetValueDirect(TypedReference obj, Object value) @@ -793,7 +713,6 @@ namespace System.Reflection public override Type FieldType { - [System.Security.SecuritySafeCritical] // auto-generated get { if (m_fieldType == null) @@ -803,13 +722,11 @@ namespace System.Reflection } } - [System.Security.SecuritySafeCritical] // auto-generated public override Type[] GetRequiredCustomModifiers() { return new Signature(this, m_declaringType).GetCustomModifiers(1, true); } - [System.Security.SecuritySafeCritical] // auto-generated public override Type[] GetOptionalCustomModifiers() { return new Signature(this, m_declaringType).GetCustomModifiers(1, false); @@ -857,7 +774,6 @@ namespace System.Reflection #region MemberInfo Overrides public override String Name { - [System.Security.SecuritySafeCritical] // auto-generated get { if (m_name == null) @@ -902,7 +818,6 @@ namespace System.Reflection public unsafe override Object GetRawConstantValue() { return GetValue(true); } - [System.Security.SecuritySafeCritical] // auto-generated private unsafe Object GetValue(bool raw) { // Cannot cache these because they could be user defined non-agile enumerations @@ -924,7 +839,6 @@ namespace System.Reflection public override Type FieldType { - [System.Security.SecuritySafeCritical] // auto-generated get { if (m_fieldType == null) diff --git a/src/mscorlib/src/System/Reflection/IntrospectionExtensions.cs b/src/mscorlib/src/System/Reflection/IntrospectionExtensions.cs index ce2630a908..49819a942f 100644 --- a/src/mscorlib/src/System/Reflection/IntrospectionExtensions.cs +++ b/src/mscorlib/src/System/Reflection/IntrospectionExtensions.cs @@ -8,28 +8,21 @@ ** ** ** -** Purpose: go from type to type info +** Purpose: Get the underlying TypeInfo from a Type ** ** =============================================================================*/ - namespace System.Reflection { - using System.Reflection; - public static class IntrospectionExtensions { - public static TypeInfo GetTypeInfo(this Type type){ - if(type == null){ - throw new ArgumentNullException("type"); - } + public static TypeInfo GetTypeInfo(this Type type) + { + if (type == null) + throw new ArgumentNullException(nameof(type)); + var rcType=(IReflectableType)type; - if(rcType==null){ - return null; - }else{ - return rcType.GetTypeInfo(); - } - } + return rcType.GetTypeInfo(); + } } } - diff --git a/src/mscorlib/src/System/Reflection/InvalidFilterCriteriaException.cs b/src/mscorlib/src/System/Reflection/InvalidFilterCriteriaException.cs index 7c980da379..fa95e37ad5 100644 --- a/src/mscorlib/src/System/Reflection/InvalidFilterCriteriaException.cs +++ b/src/mscorlib/src/System/Reflection/InvalidFilterCriteriaException.cs @@ -19,11 +19,7 @@ namespace System.Reflection { using ApplicationException = System.ApplicationException; [Serializable] [System.Runtime.InteropServices.ComVisible(true)] -#if FEATURE_CORECLR - public class InvalidFilterCriteriaException : Exception { -#else public class InvalidFilterCriteriaException : ApplicationException { -#endif // FEATURE_CORECLR public InvalidFilterCriteriaException() : base(Environment.GetResourceString("Arg_InvalidFilterCriteriaException")) { SetErrorCode(__HResults.COR_E_INVALIDFILTERCRITERIA); diff --git a/src/mscorlib/src/System/Reflection/LoaderAllocator.cs b/src/mscorlib/src/System/Reflection/LoaderAllocator.cs index a8b4b0c3a0..7c6c6bd0e8 100644 --- a/src/mscorlib/src/System/Reflection/LoaderAllocator.cs +++ b/src/mscorlib/src/System/Reflection/LoaderAllocator.cs @@ -34,11 +34,9 @@ namespace System.Reflection internal IntPtr m_nativeLoaderAllocator; [SuppressUnmanagedCodeSecurity] - [SecurityCritical] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] private static extern bool Destroy(IntPtr nativeLoaderAllocator); - [SecuritySafeCritical] ~LoaderAllocatorScout() { if (m_nativeLoaderAllocator.IsNull()) diff --git a/src/mscorlib/src/System/Reflection/MdConstant.cs b/src/mscorlib/src/System/Reflection/MdConstant.cs index 1941736787..e59244f109 100644 --- a/src/mscorlib/src/System/Reflection/MdConstant.cs +++ b/src/mscorlib/src/System/Reflection/MdConstant.cs @@ -10,7 +10,6 @@ namespace System.Reflection internal static class MdConstant { - [System.Security.SecurityCritical] // auto-generated public static unsafe Object GetValue(MetadataImport scope, int token, RuntimeTypeHandle fieldTypeHandle, bool raw) { CorElementType corElementType = 0; diff --git a/src/mscorlib/src/System/Reflection/MdImport.cs b/src/mscorlib/src/System/Reflection/MdImport.cs index 3bf8eddbcc..bbdf948f99 100644 --- a/src/mscorlib/src/System/Reflection/MdImport.cs +++ b/src/mscorlib/src/System/Reflection/MdImport.cs @@ -174,7 +174,6 @@ namespace System.Reflection public int Length { get { return m_length; } } public byte this[int index] { - [System.Security.SecuritySafeCritical] // auto-generated get { if (index < 0 || index >= m_length) @@ -269,7 +268,6 @@ namespace System.Reflection public int this[int index] { - [System.Security.SecurityCritical] get { Contract.Requires(0 <= index && index < Length); @@ -312,12 +310,10 @@ namespace System.Reflection #endregion #region Static Members - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _GetMarshalAs(IntPtr pNativeType, int cNativeType, out int unmanagedType, out int safeArraySubType, out string safeArrayUserDefinedSubType, out int arraySubType, out int sizeParamIndex, out int sizeConst, out string marshalType, out string marshalCookie, out int iidParamIndex); - [System.Security.SecurityCritical] // auto-generated internal static void GetMarshalAs(ConstArray nativeType, out UnmanagedType unmanagedType, out VarEnum safeArraySubType, out string safeArrayUserDefinedSubType, out UnmanagedType arraySubType, out int sizeParamIndex, out int sizeConst, out string marshalType, out string marshalCookie, @@ -351,56 +347,46 @@ namespace System.Reflection #endregion #region FCalls - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute (MethodImplOptions.InternalCall)] private unsafe static extern void _Enum(IntPtr scope, int type, int parent, out MetadataEnumResult result); - [System.Security.SecurityCritical] // auto-generated public unsafe void Enum(MetadataTokenType type, int parent, out MetadataEnumResult result) { _Enum(m_metadataImport2, (int)type, parent, out result); } - [System.Security.SecurityCritical] // auto-generated public unsafe void EnumNestedTypes(int mdTypeDef, out MetadataEnumResult result) { Enum(MetadataTokenType.TypeDef, mdTypeDef, out result); } - [System.Security.SecurityCritical] // auto-generated public unsafe void EnumCustomAttributes(int mdToken, out MetadataEnumResult result) { Enum(MetadataTokenType.CustomAttribute, mdToken, out result); } - [System.Security.SecurityCritical] // auto-generated public unsafe void EnumParams(int mdMethodDef, out MetadataEnumResult result) { Enum(MetadataTokenType.ParamDef, mdMethodDef, out result); } - [System.Security.SecurityCritical] // auto-generated public unsafe void EnumFields(int mdTypeDef, out MetadataEnumResult result) { Enum(MetadataTokenType.FieldDef, mdTypeDef, out result); } - [System.Security.SecurityCritical] // auto-generated public unsafe void EnumProperties(int mdTypeDef, out MetadataEnumResult result) { Enum(MetadataTokenType.Property, mdTypeDef, out result); } - [System.Security.SecurityCritical] // auto-generated public unsafe void EnumEvents(int mdTypeDef, out MetadataEnumResult result) { Enum(MetadataTokenType.Event, mdTypeDef, out result); } - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute (MethodImplOptions.InternalCall)] private static extern String _GetDefaultValue(IntPtr scope, int mdToken, out long value, out int length, out int corElementType); - [System.Security.SecurityCritical] // auto-generated public String GetDefaultValue(int mdToken, out long value, out int length, out CorElementType corElementType) { int _corElementType; @@ -410,10 +396,8 @@ namespace System.Reflection return stringVal; } - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute (MethodImplOptions.InternalCall)] private static unsafe extern void _GetUserString(IntPtr scope, int mdToken, void** name, out int length); - [System.Security.SecurityCritical] // auto-generated public unsafe String GetUserString(int mdToken) { void* name; @@ -436,10 +420,8 @@ namespace System.Reflection return new String(c); } - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute (MethodImplOptions.InternalCall)] private static unsafe extern void _GetName(IntPtr scope, int mdToken, void** name); - [System.Security.SecurityCritical] // auto-generated public unsafe Utf8String GetName(int mdToken) { void* name; @@ -448,10 +430,8 @@ namespace System.Reflection return new Utf8String(name); } - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute (MethodImplOptions.InternalCall)] private static unsafe extern void _GetNamespace(IntPtr scope, int mdToken, void** namesp); - [System.Security.SecurityCritical] // auto-generated public unsafe Utf8String GetNamespace(int mdToken) { void* namesp; @@ -460,10 +440,8 @@ namespace System.Reflection return new Utf8String(namesp); } - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute (MethodImplOptions.InternalCall)] private unsafe static extern void _GetEventProps(IntPtr scope, int mdToken, void** name, out int eventAttributes); - [System.Security.SecurityCritical] // auto-generated public unsafe void GetEventProps(int mdToken, out void* name, out EventAttributes eventAttributes) { int _eventAttributes; @@ -473,10 +451,8 @@ namespace System.Reflection eventAttributes = (EventAttributes)_eventAttributes; } - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute (MethodImplOptions.InternalCall)] private static extern void _GetFieldDefProps(IntPtr scope, int mdToken, out int fieldAttributes); - [System.Security.SecurityCritical] // auto-generated public void GetFieldDefProps(int mdToken, out FieldAttributes fieldAttributes) { int _fieldAttributes; @@ -484,11 +460,9 @@ namespace System.Reflection fieldAttributes = (FieldAttributes)_fieldAttributes; } - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute (MethodImplOptions.InternalCall)] private unsafe static extern void _GetPropertyProps(IntPtr scope, int mdToken, void** name, out int propertyAttributes, out ConstArray signature); - [System.Security.SecurityCritical] // auto-generated public unsafe void GetPropertyProps(int mdToken, out void* name, out PropertyAttributes propertyAttributes, out ConstArray signature) { int _propertyAttributes; @@ -498,11 +472,9 @@ namespace System.Reflection propertyAttributes = (PropertyAttributes)_propertyAttributes; } - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute (MethodImplOptions.InternalCall)] private static extern void _GetParentToken(IntPtr scope, int mdToken, out int tkParent); - [System.Security.SecurityCritical] // auto-generated public int GetParentToken(int tkToken) { int tkParent; @@ -510,11 +482,9 @@ namespace System.Reflection return tkParent; } - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _GetParamDefProps(IntPtr scope, int parameterToken, out int sequence, out int attributes); - [System.Security.SecurityCritical] // auto-generated public void GetParamDefProps(int parameterToken, out int sequence, out ParameterAttributes attributes) { int _attributes; @@ -524,13 +494,11 @@ namespace System.Reflection attributes = (ParameterAttributes)_attributes; } - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _GetGenericParamProps(IntPtr scope, int genericParameter, out int flags); - [System.Security.SecurityCritical] // auto-generated public void GetGenericParamProps( int genericParameter, out GenericParameterAttributes attributes) @@ -540,12 +508,10 @@ namespace System.Reflection attributes = (GenericParameterAttributes)_attributes; } - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _GetScopeProps(IntPtr scope, out Guid mvid); - [System.Security.SecurityCritical] // auto-generated public void GetScopeProps( out Guid mvid) { @@ -553,7 +519,6 @@ namespace System.Reflection } - [System.Security.SecurityCritical] // auto-generated public ConstArray GetMethodSignature(MetadataToken token) { if (token.IsMemberRef) @@ -562,13 +527,11 @@ namespace System.Reflection return GetSigOfMethodDef(token); } - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _GetSigOfMethodDef(IntPtr scope, int methodToken, ref ConstArray signature); - [System.Security.SecurityCritical] // auto-generated public ConstArray GetSigOfMethodDef(int methodToken) { ConstArray signature = new ConstArray(); @@ -578,13 +541,11 @@ namespace System.Reflection return signature; } - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _GetSignatureFromToken(IntPtr scope, int methodToken, ref ConstArray signature); - [System.Security.SecurityCritical] // auto-generated public ConstArray GetSignatureFromToken(int token) { ConstArray signature = new ConstArray(); @@ -594,13 +555,11 @@ namespace System.Reflection return signature; } - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _GetMemberRefProps(IntPtr scope, int memberTokenRef, out ConstArray signature); - [System.Security.SecurityCritical] // auto-generated public ConstArray GetMemberRefProps(int memberTokenRef) { ConstArray signature = new ConstArray(); @@ -610,14 +569,12 @@ namespace System.Reflection return signature; } - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _GetCustomAttributeProps(IntPtr scope, int customAttributeToken, out int constructorToken, out ConstArray signature); - [System.Security.SecurityCritical] // auto-generated public void GetCustomAttributeProps( int customAttributeToken, out int constructorToken, @@ -627,11 +584,9 @@ namespace System.Reflection out constructorToken, out signature); } - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _GetClassLayout(IntPtr scope, int typeTokenDef, out int packSize, out int classSize); - [System.Security.SecurityCritical] // auto-generated public void GetClassLayout( int typeTokenDef, out int packSize, @@ -640,11 +595,9 @@ namespace System.Reflection _GetClassLayout(m_metadataImport2, typeTokenDef, out packSize, out classSize); } - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool _GetFieldOffset(IntPtr scope, int typeTokenDef, int fieldTokenDef, out int offset); - [System.Security.SecurityCritical] // auto-generated public bool GetFieldOffset( int typeTokenDef, int fieldTokenDef, @@ -653,13 +606,11 @@ namespace System.Reflection return _GetFieldOffset(m_metadataImport2, typeTokenDef, fieldTokenDef, out offset); } - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _GetSigOfFieldDef(IntPtr scope, int fieldToken, ref ConstArray fieldMarshal); - [System.Security.SecurityCritical] // auto-generated public ConstArray GetSigOfFieldDef(int fieldToken) { ConstArray fieldMarshal = new ConstArray(); @@ -669,13 +620,11 @@ namespace System.Reflection return fieldMarshal; } - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _GetFieldMarshal(IntPtr scope, int fieldToken, ref ConstArray fieldMarshal); - [System.Security.SecurityCritical] // auto-generated public ConstArray GetFieldMarshal(int fieldToken) { ConstArray fieldMarshal = new ConstArray(); @@ -685,7 +634,6 @@ namespace System.Reflection return fieldMarshal; } - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private unsafe static extern void _GetPInvokeMap(IntPtr scope, int token, @@ -693,7 +641,6 @@ namespace System.Reflection void** importName, void** importDll); - [System.Security.SecurityCritical] // auto-generated public unsafe void GetPInvokeMap( int token, out PInvokeAttributes attributes, @@ -709,10 +656,8 @@ namespace System.Reflection attributes = (PInvokeAttributes)_attributes; } - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool _IsValidToken(IntPtr scope, int token); - [System.Security.SecurityCritical] // auto-generated public bool IsValidToken(int token) { return _IsValidToken(m_metadataImport2, token); diff --git a/src/mscorlib/src/System/Reflection/MemberInfo.cs b/src/mscorlib/src/System/Reflection/MemberInfo.cs index 248c78bf70..96a89ad37b 100644 --- a/src/mscorlib/src/System/Reflection/MemberInfo.cs +++ b/src/mscorlib/src/System/Reflection/MemberInfo.cs @@ -16,9 +16,6 @@ namespace System.Reflection [Serializable] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_MemberInfo))] -#pragma warning disable 618 - [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")] -#pragma warning restore 618 [System.Runtime.InteropServices.ComVisible(true)] public abstract class MemberInfo : ICustomAttributeProvider, _MemberInfo { @@ -116,33 +113,5 @@ namespace System.Reflection { return base.GetHashCode(); } - -#if !FEATURE_CORECLR - // this method is required so Object.GetType is not made final virtual by the compiler - Type _MemberInfo.GetType() - { - return base.GetType(); - } - - void _MemberInfo.GetTypeInfoCount(out uint pcTInfo) - { - throw new NotImplementedException(); - } - - void _MemberInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) - { - throw new NotImplementedException(); - } - - void _MemberInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) - { - throw new NotImplementedException(); - } - - void _MemberInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) - { - throw new NotImplementedException(); - } -#endif } } diff --git a/src/mscorlib/src/System/Reflection/MemberInfoSerializationHolder.cs b/src/mscorlib/src/System/Reflection/MemberInfoSerializationHolder.cs index c1b4ee5fe1..20ff37650c 100644 --- a/src/mscorlib/src/System/Reflection/MemberInfoSerializationHolder.cs +++ b/src/mscorlib/src/System/Reflection/MemberInfoSerializationHolder.cs @@ -31,7 +31,7 @@ namespace System.Reflection Type[] genericArguments) { if (info == null) - throw new ArgumentNullException("info"); + throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); String assemblyName = reflectedClass.Module.Assembly.FullName; @@ -65,7 +65,7 @@ namespace System.Reflection internal MemberInfoSerializationHolder(SerializationInfo info, StreamingContext context) { if (info == null) - throw new ArgumentNullException("info"); + throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); String assemblyName = info.GetString("AssemblyName"); @@ -86,7 +86,6 @@ namespace System.Reflection #endregion #region ISerializable - [System.Security.SecurityCritical] // auto-generated public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_Method)); @@ -94,7 +93,6 @@ namespace System.Reflection #endregion #region IObjectReference - [System.Security.SecurityCritical] // auto-generated public virtual Object GetRealObject(StreamingContext context) { if (m_memberName == null || m_reflectedType == null || m_memberType == 0) diff --git a/src/mscorlib/src/System/Reflection/Metadata/AssemblyExtensions.cs b/src/mscorlib/src/System/Reflection/Metadata/AssemblyExtensions.cs index dd5d69b1fb..388e4f475f 100644 --- a/src/mscorlib/src/System/Reflection/Metadata/AssemblyExtensions.cs +++ b/src/mscorlib/src/System/Reflection/Metadata/AssemblyExtensions.cs @@ -11,7 +11,6 @@ namespace System.Reflection.Metadata public static class AssemblyExtensions { [DllImport(JitHelpers.QCall)] - [SecurityCritical] // unsafe method [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] private unsafe static extern bool InternalTryGetRawMetadata(RuntimeAssembly assembly, ref byte* blob, ref int length); @@ -24,12 +23,11 @@ namespace System.Reflection.Metadata // associated, is alive. The caller is responsible for keeping the assembly object alive while accessing the // metadata blob. [CLSCompliant(false)] // out byte* blob - [SecurityCritical] // unsafe method public unsafe static bool TryGetRawMetadata(this Assembly assembly, out byte* blob, out int length) { if (assembly == null) { - throw new ArgumentNullException("assembly"); + throw new ArgumentNullException(nameof(assembly)); } blob = null; diff --git a/src/mscorlib/src/System/Reflection/MethodBase.cs b/src/mscorlib/src/System/Reflection/MethodBase.cs index 68363bf1e0..644a1ac0b0 100644 --- a/src/mscorlib/src/System/Reflection/MethodBase.cs +++ b/src/mscorlib/src/System/Reflection/MethodBase.cs @@ -50,9 +50,6 @@ namespace System.Reflection [Serializable] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_MethodBase))] -#pragma warning disable 618 - [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")] -#pragma warning restore 618 [System.Runtime.InteropServices.ComVisible(true)] public abstract class MethodBase : MemberInfo, _MethodBase { @@ -131,7 +128,6 @@ namespace System.Reflection #region Internal Members // used by EE - [System.Security.SecurityCritical] private IntPtr GetMethodDesc() { return MethodHandle.Value; } #if FEATURE_APPX @@ -243,7 +239,6 @@ namespace System.Reflection } } - [System.Security.SecuritySafeCritical] #pragma warning disable 618 [ReflectionPermissionAttribute(SecurityAction.Demand, Flags=ReflectionPermissionFlag.MemberAccess)] #pragma warning restore 618 @@ -329,7 +324,6 @@ namespace System.Reflection return parameterTypes; } - [System.Security.SecuritySafeCritical] internal Object[] CheckArguments(Object[] parameters, Binder binder, BindingFlags invokeAttr, CultureInfo culture, Signature sig) { @@ -347,7 +341,7 @@ namespace System.Reflection if (p == null) p = GetParametersNoCopy(); if (p[i].DefaultValue == System.DBNull.Value) - throw new ArgumentException(Environment.GetResourceString("Arg_VarMissNull"),"parameters"); + throw new ArgumentException(Environment.GetResourceString("Arg_VarMissNull"),nameof(parameters)); arg = p[i].DefaultValue; } copyOfParameters[i] = argRT.CheckValue(arg, binder, culture, invokeAttr); @@ -356,47 +350,5 @@ namespace System.Reflection return copyOfParameters; } #endregion - - #region _MethodBase Implementation -#if !FEATURE_CORECLR - Type _MethodBase.GetType() { return base.GetType(); } - bool _MethodBase.IsPublic { get { return IsPublic; } } - bool _MethodBase.IsPrivate { get { return IsPrivate; } } - bool _MethodBase.IsFamily { get { return IsFamily; } } - bool _MethodBase.IsAssembly { get { return IsAssembly; } } - bool _MethodBase.IsFamilyAndAssembly { get { return IsFamilyAndAssembly; } } - bool _MethodBase.IsFamilyOrAssembly { get { return IsFamilyOrAssembly; } } - bool _MethodBase.IsStatic { get { return IsStatic; } } - bool _MethodBase.IsFinal { get { return IsFinal; } } - bool _MethodBase.IsVirtual { get { return IsVirtual; } } - bool _MethodBase.IsHideBySig { get { return IsHideBySig; } } - bool _MethodBase.IsAbstract { get { return IsAbstract; } } - bool _MethodBase.IsSpecialName { get { return IsSpecialName; } } - bool _MethodBase.IsConstructor { get { return IsConstructor; } } - - void _MethodBase.GetTypeInfoCount(out uint pcTInfo) - { - throw new NotImplementedException(); - } - - void _MethodBase.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) - { - throw new NotImplementedException(); - } - - void _MethodBase.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) - { - throw new NotImplementedException(); - } - - // If you implement this method, make sure to include _MethodBase.Invoke in VM\DangerousAPIs.h and - // include _MethodBase in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp. - void _MethodBase.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) - { - throw new NotImplementedException(); - } -#endif - #endregion } - } diff --git a/src/mscorlib/src/System/Reflection/MethodBody.cs b/src/mscorlib/src/System/Reflection/MethodBody.cs index 81d7a9ea0e..4634623e26 100644 --- a/src/mscorlib/src/System/Reflection/MethodBody.cs +++ b/src/mscorlib/src/System/Reflection/MethodBody.cs @@ -7,6 +7,7 @@ using System; using System.Globalization; using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Reflection @@ -160,7 +161,7 @@ namespace System.Reflection #endregion #region Public Members - public virtual Type LocalType { get { Contract.Assert(m_type != null, "type must be set!"); return m_type; } } + public virtual Type LocalType { get { Debug.Assert(m_type != null, "type must be set!"); return m_type; } } public virtual bool IsPinned { get { return m_isPinned != 0; } } public virtual int LocalIndex { get { return m_localIndex; } } #endregion diff --git a/src/mscorlib/src/System/Reflection/MethodInfo.cs b/src/mscorlib/src/System/Reflection/MethodInfo.cs index eeb5a815a4..39387b1f8f 100644 --- a/src/mscorlib/src/System/Reflection/MethodInfo.cs +++ b/src/mscorlib/src/System/Reflection/MethodInfo.cs @@ -14,9 +14,6 @@ namespace System.Reflection using System.Runtime; using System.Runtime.InteropServices; using System.Runtime.ConstrainedExecution; -#if FEATURE_REMOTING - using System.Runtime.Remoting.Metadata; -#endif //FEATURE_REMOTING using System.Runtime.Serialization; using System.Security; using System.Security.Permissions; @@ -29,9 +26,6 @@ namespace System.Reflection [Serializable] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_MethodInfo))] -#pragma warning disable 618 - [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")] -#pragma warning restore 618 [System.Runtime.InteropServices.ComVisible(true)] public abstract class MethodInfo : MethodBase, _MethodInfo { @@ -91,35 +85,6 @@ namespace System.Reflection public virtual Delegate CreateDelegate(Type delegateType) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); } public virtual Delegate CreateDelegate(Type delegateType, Object target) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); } #endregion - -#if !FEATURE_CORECLR - Type _MethodInfo.GetType() - { - return base.GetType(); - } - - void _MethodInfo.GetTypeInfoCount(out uint pcTInfo) - { - throw new NotImplementedException(); - } - - void _MethodInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) - { - throw new NotImplementedException(); - } - - void _MethodInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) - { - throw new NotImplementedException(); - } - - // If you implement this method, make sure to include _MethodInfo.Invoke in VM\DangerousAPIs.h and - // include _MethodInfo in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp. - void _MethodInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) - { - throw new NotImplementedException(); - } -#endif } [Serializable] @@ -180,7 +145,6 @@ namespace System.Reflection internal INVOCATION_FLAGS InvocationFlags { - [System.Security.SecuritySafeCritical] get { if ((m_invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0) @@ -243,15 +207,14 @@ namespace System.Reflection #endregion #region Constructor - [System.Security.SecurityCritical] // auto-generated internal RuntimeMethodInfo( RuntimeMethodHandleInternal handle, RuntimeType declaringType, RuntimeTypeCache reflectedTypeCache, MethodAttributes methodAttributes, BindingFlags bindingFlags, object keepalive) { Contract.Ensures(!m_handle.IsNull()); - Contract.Assert(!handle.IsNullHandle()); - Contract.Assert(methodAttributes == RuntimeMethodHandle.GetAttributes(handle)); + Debug.Assert(!handle.IsNullHandle()); + Debug.Assert(methodAttributes == RuntimeMethodHandle.GetAttributes(handle)); m_bindingFlags = bindingFlags; m_declaringType = declaringType; @@ -262,40 +225,9 @@ namespace System.Reflection } #endregion -#if FEATURE_REMOTING - #region Legacy Remoting Cache - // The size of CachedData is accounted for by BaseObjectWithCachedData in object.h. - // This member is currently being used by Remoting for caching remoting data. If you - // need to cache data here, talk to the Remoting team to work out a mechanism, so that - // both caching systems can happily work together. - private RemotingMethodCachedData m_cachedData; - - internal RemotingMethodCachedData RemotingCache - { - get - { - // This grabs an internal copy of m_cachedData and uses - // that instead of looking at m_cachedData directly because - // the cache may get cleared asynchronously. This prevents - // us from having to take a lock. - RemotingMethodCachedData cache = m_cachedData; - if (cache == null) - { - cache = new RemotingMethodCachedData(this); - RemotingMethodCachedData ret = Interlocked.CompareExchange(ref m_cachedData, cache, null); - if (ret != null) - cache = ret; - } - return cache; - } - } - #endregion -#endif //FEATURE_REMOTING - #region Private Methods RuntimeMethodHandleInternal IRuntimeMethodInfo.Value { - [System.Security.SecuritySafeCritical] get { return new RuntimeMethodHandleInternal(m_handle); @@ -310,7 +242,6 @@ namespace System.Reflection } } - [System.Security.SecurityCritical] // auto-generated private ParameterInfo[] FetchNonReturnParameters() { if (m_parameters == null) @@ -319,7 +250,6 @@ namespace System.Reflection return m_parameters; } - [System.Security.SecurityCritical] // auto-generated private ParameterInfo FetchReturnParameter() { if (m_returnParameter == null) @@ -379,7 +309,6 @@ namespace System.Reflection return new RuntimeMethodHandle(this); } - [System.Security.SecuritySafeCritical] // auto-generated internal RuntimeMethodInfo GetParentDefinition() { if (!IsVirtual || m_declaringType.IsInterface) @@ -424,7 +353,6 @@ namespace System.Reflection return base.GetHashCode(); } - [System.Security.SecuritySafeCritical] // auto-generated public override bool Equals(object obj) { if (!IsGenericMethod) @@ -469,23 +397,21 @@ namespace System.Reflection #endregion #region ICustomAttributeProvider - [System.Security.SecuritySafeCritical] // auto-generated public override Object[] GetCustomAttributes(bool inherit) { return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType as RuntimeType, inherit); } - [System.Security.SecuritySafeCritical] // auto-generated public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) - throw new ArgumentNullException("attributeType"); + throw new ArgumentNullException(nameof(attributeType)); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType"); + throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType)); return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType, inherit); } @@ -493,13 +419,13 @@ namespace System.Reflection public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) - throw new ArgumentNullException("attributeType"); + throw new ArgumentNullException(nameof(attributeType)); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType"); + throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType)); return CustomAttribute.IsDefined(this, attributeRuntimeType, inherit); } @@ -513,7 +439,6 @@ namespace System.Reflection #region MemberInfo Overrides public override String Name { - [System.Security.SecuritySafeCritical] // auto-generated get { if (m_name == null) @@ -548,7 +473,6 @@ namespace System.Reflection public override MemberTypes MemberType { get { return MemberTypes.Method; } } public override int MetadataToken { - [System.Security.SecuritySafeCritical] // auto-generated get { return RuntimeMethodHandle.GetMethodDef(this); } } public override Module Module { get { return GetRuntimeModule(); } } @@ -558,20 +482,19 @@ namespace System.Reflection public override bool IsSecurityCritical { - get { return RuntimeMethodHandle.IsSecurityCritical(this); } + get { return true; } } public override bool IsSecuritySafeCritical { - get { return RuntimeMethodHandle.IsSecuritySafeCritical(this); } + get { return false; } } public override bool IsSecurityTransparent { - get { return RuntimeMethodHandle.IsSecurityTransparent(this); } + get { return false; } } - #endregion +#endregion - #region MethodBase Overrides - [System.Security.SecuritySafeCritical] // auto-generated +#region MethodBase Overrides internal override ParameterInfo[] GetParametersNoCopy() { FetchNonReturnParameters(); @@ -579,7 +502,6 @@ namespace System.Reflection return m_parameters; } - [System.Security.SecuritySafeCritical] // auto-generated [System.Diagnostics.Contracts.Pure] public override ParameterInfo[] GetParameters() { @@ -629,12 +551,6 @@ namespace System.Reflection } } - [System.Security.SecuritySafeCritical] // overrides SafeCritical member -#if !FEATURE_CORECLR -#pragma warning disable 618 - [ReflectionPermissionAttribute(SecurityAction.Demand, Flags = ReflectionPermissionFlag.MemberAccess)] -#pragma warning restore 618 -#endif public override MethodBody GetMethodBody() { MethodBody mb = RuntimeMethodHandle.GetMethodBody(this, ReflectedTypeInternal); @@ -642,9 +558,9 @@ namespace System.Reflection mb.m_methodBase = this; return mb; } - #endregion +#endregion - #region Invocation Logic(On MemberBase) +#region Invocation Logic(On MemberBase) private void CheckConsistency(Object target) { // only test instance methods @@ -660,7 +576,6 @@ namespace System.Reflection } } - [System.Security.SecuritySafeCritical] private void ThrowNoInvokeException() { // method is ReflectionOnly @@ -698,7 +613,6 @@ namespace System.Reflection throw new TargetException(); } - [System.Security.SecuritySafeCritical] [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable @@ -706,7 +620,7 @@ namespace System.Reflection { object[] arguments = InvokeArgumentsCheck(obj, invokeAttr, binder, parameters, culture); - #region Security Check +#region Security Check INVOCATION_FLAGS invocationFlags = InvocationFlags; #if FEATURE_APPX @@ -718,23 +632,11 @@ namespace System.Reflection throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", FullName)); } #endif - -#if !FEATURE_CORECLR - if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD | INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY)) != 0) - { - if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD) != 0) - CodeAccessPermission.Demand(PermissionType.ReflectionMemberAccess); - - if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) != 0) - RuntimeMethodHandle.PerformSecurityCheck(obj, this, m_declaringType, (uint)m_invocationFlags); - } -#endif // !FEATURE_CORECLR - #endregion +#endregion return UnsafeInvokeInternal(obj, parameters, arguments); } - [System.Security.SecurityCritical] [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] internal object UnsafeInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) @@ -744,7 +646,6 @@ namespace System.Reflection return UnsafeInvokeInternal(obj, parameters, arguments); } - [System.Security.SecurityCritical] [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] private object UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) @@ -793,9 +694,9 @@ namespace System.Reflection return null; } - #endregion +#endregion - #region MethodInfo Overrides +#region MethodInfo Overrides public override Type ReturnType { get { return Signature.ReturnType; } @@ -808,7 +709,6 @@ namespace System.Reflection public override ParameterInfo ReturnParameter { - [System.Security.SecuritySafeCritical] // auto-generated get { Contract.Ensures(m_returnParameter != null); @@ -818,7 +718,6 @@ namespace System.Reflection } } - [System.Security.SecuritySafeCritical] // auto-generated public override MethodInfo GetBaseDefinition() { if (!IsVirtual || IsStatic || m_declaringType == null || m_declaringType.IsInterface) @@ -844,7 +743,6 @@ namespace System.Reflection return(MethodInfo)RuntimeType.GetMethodBase(baseDeclaringType, baseMethodHandle); } - [System.Security.SecuritySafeCritical] public override Delegate CreateDelegate(Type delegateType) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; @@ -864,7 +762,6 @@ namespace System.Reflection ref stackMark); } - [System.Security.SecuritySafeCritical] public override Delegate CreateDelegate(Type delegateType, Object target) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; @@ -881,20 +778,19 @@ namespace System.Reflection ref stackMark); } - [System.Security.SecurityCritical] private Delegate CreateDelegateInternal(Type delegateType, Object firstArgument, DelegateBindingFlags bindingFlags, ref StackCrawlMark stackMark) { // Validate the parameters. if (delegateType == null) - throw new ArgumentNullException("delegateType"); + throw new ArgumentNullException(nameof(delegateType)); Contract.EndContractBlock(); RuntimeType rtType = delegateType as RuntimeType; if (rtType == null) - throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "delegateType"); + throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(delegateType)); if (!rtType.IsDelegate()) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), "delegateType"); + throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), nameof(delegateType)); Delegate d = Delegate.CreateDelegateInternal(rtType, this, firstArgument, bindingFlags, ref stackMark); if (d == null) @@ -905,14 +801,13 @@ namespace System.Reflection return d; } - #endregion +#endregion - #region Generics - [System.Security.SecuritySafeCritical] // auto-generated +#region Generics public override MethodInfo MakeGenericMethod(params Type[] methodInstantiation) { if (methodInstantiation == null) - throw new ArgumentNullException("methodInstantiation"); + throw new ArgumentNullException(nameof(methodInstantiation)); Contract.EndContractBlock(); RuntimeType[] methodInstantionRuntimeType = new RuntimeType[methodInstantiation.Length]; @@ -1017,14 +912,13 @@ namespace System.Reflection return false; } } - #endregion +#endregion - #region ISerializable Implementation - [System.Security.SecurityCritical] // auto-generated +#region ISerializable Implementation public void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) - throw new ArgumentNullException("info"); + throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); if (m_reflectedTypeCache.IsGlobal) @@ -1044,9 +938,9 @@ namespace System.Reflection { return ReturnType.FormatTypeName(true) + " " + FormatNameAndSig(true); } - #endregion +#endregion - #region Legacy Internal +#region Legacy Internal internal static MethodBase InternalGetCurrentMethod(ref StackCrawlMark stackMark) { IRuntimeMethodInfo method = RuntimeMethodHandle.GetCurrentMethod(ref stackMark); @@ -1056,6 +950,6 @@ namespace System.Reflection return RuntimeType.GetMethodBase(method); } - #endregion +#endregion } } diff --git a/src/mscorlib/src/System/Reflection/Missing.cs b/src/mscorlib/src/System/Reflection/Missing.cs index 8289193191..24bf77bd4e 100644 --- a/src/mscorlib/src/System/Reflection/Missing.cs +++ b/src/mscorlib/src/System/Reflection/Missing.cs @@ -24,11 +24,10 @@ namespace System.Reflection #endregion #region ISerializable - [System.Security.SecurityCritical] // auto-generated_required void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) - throw new ArgumentNullException("info"); + throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); UnitySerializationHolder.GetUnitySerializationInfo(info, this); diff --git a/src/mscorlib/src/System/Reflection/Module.cs b/src/mscorlib/src/System/Reflection/Module.cs index 34705a4211..b6be38e434 100644 --- a/src/mscorlib/src/System/Reflection/Module.cs +++ b/src/mscorlib/src/System/Reflection/Module.cs @@ -59,9 +59,6 @@ namespace System.Reflection [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_Module))] [System.Runtime.InteropServices.ComVisible(true)] -#pragma warning disable 618 - [PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted = true)] -#pragma warning restore 618 public abstract class Module : _Module, ISerializable, ICustomAttributeProvider { #region Static Constructor @@ -274,7 +271,6 @@ namespace System.Reflection } } - [System.Security.SecurityCritical] // auto-generated_required public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { throw new NotImplementedException(); @@ -299,9 +295,6 @@ namespace System.Reflection public virtual String FullyQualifiedName { -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#endif get { throw new NotImplementedException(); @@ -432,16 +425,16 @@ namespace System.Reflection String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { if (name == null) - throw new ArgumentNullException("name"); + throw new ArgumentNullException(nameof(name)); if (types == null) - throw new ArgumentNullException("types"); + throw new ArgumentNullException(nameof(types)); Contract.EndContractBlock(); for (int i = 0; i < types.Length; i++) { if (types[i] == null) - throw new ArgumentNullException("types"); + throw new ArgumentNullException(nameof(types)); } return GetMethodImpl(name, bindingAttr, binder, callConvention, types, modifiers); @@ -450,16 +443,16 @@ namespace System.Reflection public MethodInfo GetMethod(String name, Type[] types) { if (name == null) - throw new ArgumentNullException("name"); + throw new ArgumentNullException(nameof(name)); if (types == null) - throw new ArgumentNullException("types"); + throw new ArgumentNullException(nameof(types)); Contract.EndContractBlock(); for (int i = 0; i < types.Length; i++) { if (types[i] == null) - throw new ArgumentNullException("types"); + throw new ArgumentNullException(nameof(types)); } return GetMethodImpl(name, Module.DefaultLookup, null, CallingConventions.Any, types, null); @@ -468,7 +461,7 @@ namespace System.Reflection public MethodInfo GetMethod(String name) { if (name == null) - throw new ArgumentNullException("name"); + throw new ArgumentNullException(nameof(name)); Contract.EndContractBlock(); return GetMethodImpl(name, Module.DefaultLookup, null, CallingConventions.Any, @@ -543,36 +536,7 @@ namespace System.Reflection { return ModuleHandle.EmptyHandle; } - -#if FEATURE_X509 && FEATURE_CAS_POLICY - public virtual System.Security.Cryptography.X509Certificates.X509Certificate GetSignerCertificate() - { - throw new NotImplementedException(); - } -#endif // FEATURE_X509 && FEATURE_CAS_POLICY #endregion - -#if !FEATURE_CORECLR - void _Module.GetTypeInfoCount(out uint pcTInfo) - { - throw new NotImplementedException(); - } - - void _Module.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) - { - throw new NotImplementedException(); - } - - void _Module.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) - { - throw new NotImplementedException(); - } - - void _Module.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) - { - throw new NotImplementedException(); - } -#endif } [Serializable] @@ -581,46 +545,32 @@ namespace System.Reflection internal RuntimeModule() { throw new NotSupportedException(); } #region FCalls - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void GetType(RuntimeModule module, String className, bool ignoreCase, bool throwOnError, ObjectHandleOnStack type, ObjectHandleOnStack keepAlive); - [System.Security.SecurityCritical] [DllImport(JitHelpers.QCall)] [SuppressUnmanagedCodeSecurity] private static extern bool nIsTransientInternal(RuntimeModule module); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void GetScopeName(RuntimeModule module, StringHandleOnStack retString); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void GetFullyQualifiedName(RuntimeModule module, StringHandleOnStack retString); - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern static RuntimeType[] GetTypes(RuntimeModule module); - [System.Security.SecuritySafeCritical] // auto-generated internal RuntimeType[] GetDefinedTypes() { return GetTypes(GetNativeHandle()); } - [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern static bool IsResource(RuntimeModule module); - -#if FEATURE_X509 && FEATURE_CAS_POLICY - [System.Security.SecurityCritical] // auto-generated - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - static private extern void GetSignerCertificate(RuntimeModule module, ObjectHandleOnStack retData); -#endif // FEATURE_X509 && FEATURE_CAS_POLICY #endregion #region Module overrides @@ -646,18 +596,17 @@ namespace System.Reflection return typeHandleArgs; } - [System.Security.SecuritySafeCritical] // auto-generated public override byte[] ResolveSignature(int metadataToken) { MetadataToken tk = new MetadataToken(metadataToken); if (!MetadataImport.IsValidToken(tk)) - throw new ArgumentOutOfRangeException("metadataToken", + 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), - "metadataToken"); + nameof(metadataToken)); ConstArray signature; if (tk.IsMemberRef) @@ -673,13 +622,12 @@ namespace System.Reflection return sig; } - [System.Security.SecuritySafeCritical] // auto-generated public override MethodBase ResolveMethod(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { MetadataToken tk = new MetadataToken(metadataToken); if (!MetadataImport.IsValidToken(tk)) - throw new ArgumentOutOfRangeException("metadataToken", + throw new ArgumentOutOfRangeException(nameof(metadataToken), Environment.GetResourceString("Argument_InvalidToken", tk, this)); RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments); @@ -690,16 +638,16 @@ namespace System.Reflection if (!tk.IsMethodDef && !tk.IsMethodSpec) { if (!tk.IsMemberRef) - throw new ArgumentException("metadataToken", - Environment.GetResourceString("Argument_ResolveMethod", tk, this)); + 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("metadataToken", - Environment.GetResourceString("Argument_ResolveMethod", tk, this)); + throw new ArgumentException(Environment.GetResourceString("Argument_ResolveMethod", tk, this), + nameof(metadataToken)); } } @@ -724,13 +672,12 @@ namespace System.Reflection } } - [System.Security.SecurityCritical] // auto-generated private FieldInfo ResolveLiteralField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { MetadataToken tk = new MetadataToken(metadataToken); if (!MetadataImport.IsValidToken(tk) || !tk.IsFieldDef) - throw new ArgumentOutOfRangeException("metadataToken", + throw new ArgumentOutOfRangeException(nameof(metadataToken), String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_InvalidToken", tk, this))); int tkDeclaringType; @@ -752,17 +699,16 @@ namespace System.Reflection } catch { - throw new ArgumentException(Environment.GetResourceString("Argument_ResolveField", tk, this), "metadataToken"); + throw new ArgumentException(Environment.GetResourceString("Argument_ResolveField", tk, this), nameof(metadataToken)); } } - [System.Security.SecuritySafeCritical] // auto-generated public override FieldInfo ResolveField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { MetadataToken tk = new MetadataToken(metadataToken); if (!MetadataImport.IsValidToken(tk)) - throw new ArgumentOutOfRangeException("metadataToken", + throw new ArgumentOutOfRangeException(nameof(metadataToken), Environment.GetResourceString("Argument_InvalidToken", tk, this)); RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments); @@ -775,16 +721,16 @@ namespace System.Reflection if (!tk.IsFieldDef) { if (!tk.IsMemberRef) - throw new ArgumentException("metadataToken", - Environment.GetResourceString("Argument_ResolveField", tk, this)); + 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("metadataToken", - Environment.GetResourceString("Argument_ResolveField", tk, this)); + throw new ArgumentException(Environment.GetResourceString("Argument_ResolveField", tk, this), + nameof(metadataToken)); } fieldHandle = ModuleHandle.ResolveFieldHandleInternal(GetNativeHandle(), tk, typeArgs, methodArgs); @@ -811,20 +757,19 @@ namespace System.Reflection } } - [System.Security.SecuritySafeCritical] // auto-generated 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), "metadataToken"); + throw new ArgumentException(Environment.GetResourceString("Argument_ResolveModuleType", tk), nameof(metadataToken)); if (!MetadataImport.IsValidToken(tk)) - throw new ArgumentOutOfRangeException("metadataToken", + 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), "metadataToken"); + throw new ArgumentException(Environment.GetResourceString("Argument_ResolveType", tk, this), nameof(metadataToken)); RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments); RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments); @@ -834,7 +779,7 @@ namespace System.Reflection Type t = GetModuleHandle().ResolveTypeHandle(metadataToken, typeArgs, methodArgs).GetRuntimeType(); if (t == null) - throw new ArgumentException(Environment.GetResourceString("Argument_ResolveType", tk, this), "metadataToken"); + throw new ArgumentException(Environment.GetResourceString("Argument_ResolveType", tk, this), nameof(metadataToken)); return t; } @@ -844,7 +789,6 @@ namespace System.Reflection } } - [System.Security.SecuritySafeCritical] // auto-generated public override MemberInfo ResolveMember(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { MetadataToken tk = new MetadataToken(metadataToken); @@ -867,7 +811,7 @@ namespace System.Reflection if (tk.IsMemberRef) { if (!MetadataImport.IsValidToken(tk)) - throw new ArgumentOutOfRangeException("metadataToken", + throw new ArgumentOutOfRangeException(nameof(metadataToken), Environment.GetResourceString("Argument_InvalidToken", tk, this)); ConstArray sig = MetadataImport.GetMemberRefProps(tk); @@ -885,11 +829,10 @@ namespace System.Reflection } } - throw new ArgumentException("metadataToken", - Environment.GetResourceString("Argument_ResolveMember", tk, this)); + throw new ArgumentException(Environment.GetResourceString("Argument_ResolveMember", tk, this), + nameof(metadataToken)); } - [System.Security.SecuritySafeCritical] // auto-generated public override string ResolveString(int metadataToken) { MetadataToken tk = new MetadataToken(metadataToken); @@ -898,7 +841,7 @@ namespace System.Reflection String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_ResolveString"), metadataToken, ToString())); if (!MetadataImport.IsValidToken(tk)) - throw new ArgumentOutOfRangeException("metadataToken", + throw new ArgumentOutOfRangeException(nameof(metadataToken), String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_InvalidToken", tk, this))); string str = MetadataImport.GetUserString(metadataToken); @@ -917,7 +860,6 @@ namespace System.Reflection public override int MDStreamVersion { - [System.Security.SecuritySafeCritical] // auto-generated get { return ModuleHandle.GetMDStreamVersion(GetNativeHandle()); @@ -973,7 +915,6 @@ namespace System.Reflection } } - [System.Security.SecuritySafeCritical] internal bool IsTransientInternal() { return RuntimeModule.nIsTransientInternal(this.GetNativeHandle()); @@ -981,7 +922,6 @@ namespace System.Reflection internal MetadataImport MetadataImport { - [System.Security.SecurityCritical] // auto-generated get { unsafe @@ -1001,28 +941,27 @@ namespace System.Reflection public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) - throw new ArgumentNullException("attributeType"); + throw new ArgumentNullException(nameof(attributeType)); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType"); + throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType)); return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType); } - [System.Security.SecuritySafeCritical] // auto-generated public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) - throw new ArgumentNullException("attributeType"); + throw new ArgumentNullException(nameof(attributeType)); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType"); + throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType)); return CustomAttribute.IsDefined(this, attributeRuntimeType); } @@ -1034,24 +973,22 @@ namespace System.Reflection #endregion #region Public Virtuals - [System.Security.SecurityCritical] // auto-generated_required public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { - throw new ArgumentNullException("info"); + throw new ArgumentNullException(nameof(info)); } Contract.EndContractBlock(); UnitySerializationHolder.GetUnitySerializationInfo(info, UnitySerializationHolder.ModuleUnity, this.ScopeName, this.GetRuntimeAssembly()); } - [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(true)] 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("className"); + throw new ArgumentNullException(nameof(className)); RuntimeType retType = null; Object keepAlive = null; @@ -1060,7 +997,6 @@ namespace System.Reflection return retType; } - [System.Security.SecurityCritical] // auto-generated internal string GetFullyQualifiedName() { String fullyQualifiedName = null; @@ -1070,11 +1006,6 @@ namespace System.Reflection public override String FullyQualifiedName { -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated -#else - [System.Security.SecuritySafeCritical] -#endif get { String fullyQualifiedName = GetFullyQualifiedName(); @@ -1082,7 +1013,7 @@ namespace System.Reflection if (fullyQualifiedName != null) { bool checkPermission = true; try { - Path.GetFullPathInternal(fullyQualifiedName); + Path.GetFullPath(fullyQualifiedName); } catch(ArgumentException) { checkPermission = false; @@ -1096,7 +1027,6 @@ namespace System.Reflection } } - [System.Security.SecuritySafeCritical] // auto-generated public override Type[] GetTypes() { return GetTypes(GetNativeHandle()); @@ -1108,7 +1038,6 @@ namespace System.Reflection public override Guid ModuleVersionId { - [System.Security.SecuritySafeCritical] // auto-generated get { unsafe @@ -1122,7 +1051,6 @@ namespace System.Reflection public override int MetadataToken { - [System.Security.SecuritySafeCritical] // auto-generated get { return ModuleHandle.GetToken(GetNativeHandle()); @@ -1145,7 +1073,7 @@ namespace System.Reflection public override FieldInfo GetField(String name, BindingFlags bindingAttr) { if (name == null) - throw new ArgumentNullException("name"); + throw new ArgumentNullException(nameof(name)); if (RuntimeType == null) return null; @@ -1163,7 +1091,6 @@ namespace System.Reflection public override String ScopeName { - [System.Security.SecuritySafeCritical] // auto-generated get { string scopeName = null; @@ -1174,7 +1101,6 @@ namespace System.Reflection public override String Name { - [System.Security.SecuritySafeCritical] // auto-generated get { String s = GetFullyQualifiedName(); @@ -1215,16 +1141,6 @@ namespace System.Reflection { return this; } - -#if FEATURE_X509 && FEATURE_CAS_POLICY - [System.Security.SecuritySafeCritical] // auto-generated - public override System.Security.Cryptography.X509Certificates.X509Certificate GetSignerCertificate() - { - byte[] data = null; - GetSignerCertificate(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref data)); - return (data != null) ? new System.Security.Cryptography.X509Certificates.X509Certificate(data) : null; - } -#endif // FEATURE_X509 && FEATURE_CAS_POLICY #endregion } } diff --git a/src/mscorlib/src/System/Reflection/ParameterInfo.cs b/src/mscorlib/src/System/Reflection/ParameterInfo.cs index 63c6330b0a..6592e5aa20 100644 --- a/src/mscorlib/src/System/Reflection/ParameterInfo.cs +++ b/src/mscorlib/src/System/Reflection/ParameterInfo.cs @@ -8,13 +8,11 @@ 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; -#if FEATURE_REMOTING - using System.Runtime.Remoting.Metadata; -#endif //FEATURE_REMOTING using System.Security.Permissions; using System.Threading; using MdToken = System.Reflection.MetadataToken; @@ -157,7 +155,7 @@ namespace System.Reflection public virtual Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) - throw new ArgumentNullException("attributeType"); + throw new ArgumentNullException(nameof(attributeType)); Contract.EndContractBlock(); return EmptyArray<Object>.Value; @@ -166,7 +164,7 @@ namespace System.Reflection public virtual bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) - throw new ArgumentNullException("attributeType"); + throw new ArgumentNullException(nameof(attributeType)); Contract.EndContractBlock(); return false; @@ -180,35 +178,12 @@ namespace System.Reflection #region _ParameterInfo implementation -#if !FEATURE_CORECLR - void _ParameterInfo.GetTypeInfoCount(out uint pcTInfo) - { - throw new NotImplementedException(); - } - - void _ParameterInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) - { - throw new NotImplementedException(); - } - - void _ParameterInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) - { - throw new NotImplementedException(); - } - - void _ParameterInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) - { - throw new NotImplementedException(); - } -#endif - #endregion #region IObjectReference // In V4 RuntimeParameterInfo is introduced. // To support deserializing ParameterInfo instances serialized in earlier versions // we need to implement IObjectReference. - [System.Security.SecurityCritical] public object GetRealObject(StreamingContext context) { Contract.Ensures(Contract.Result<Object>() != null); @@ -261,26 +236,23 @@ namespace System.Reflection internal unsafe sealed class RuntimeParameterInfo : ParameterInfo, ISerializable { #region Static Members - [System.Security.SecurityCritical] // auto-generated internal unsafe static ParameterInfo[] GetParameters(IRuntimeMethodInfo method, MemberInfo member, Signature sig) { - Contract.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo); + Debug.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo); ParameterInfo dummy; return GetParameters(method, member, sig, out dummy, false); } - [System.Security.SecurityCritical] // auto-generated internal unsafe static ParameterInfo GetReturnParameter(IRuntimeMethodInfo method, MemberInfo member, Signature sig) { - Contract.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo); + Debug.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo); ParameterInfo returnParameter; GetParameters(method, member, sig, out returnParameter, true); return returnParameter; } - [System.Security.SecurityCritical] // auto-generated internal unsafe static ParameterInfo[] GetParameters( IRuntimeMethodInfo methodHandle, MemberInfo member, Signature sig, out ParameterInfo returnParameter, bool fetchReturnParameter) { @@ -392,18 +364,17 @@ namespace System.Reflection get { MethodBase result = m_originalMember != null ? m_originalMember : MemberImpl as MethodBase; - Contract.Assert(result != null); + Debug.Assert(result != null); return result; } } #endregion #region VTS magic to serialize/deserialized to/from pre-Whidbey endpoints. - [System.Security.SecurityCritical] public void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) - throw new ArgumentNullException("info"); + throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); // We could be serializing for consumption by a pre-Whidbey @@ -450,7 +421,7 @@ namespace System.Reflection // 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; - Contract.Assert(m_originalMember != null); + Debug.Assert(m_originalMember != null); // Populate all the caches -- we inherit this behavior from RTM NameImpl = accessor.Name; @@ -470,8 +441,8 @@ namespace System.Reflection int position, ParameterAttributes attributes, MemberInfo member) { Contract.Requires(member != null); - Contract.Assert(MdToken.IsNullToken(tkParamDef) == scope.Equals(MetadataImport.EmptyImport)); - Contract.Assert(MdToken.IsNullToken(tkParamDef) || MdToken.IsTokenOfType(tkParamDef, MetadataTokenType.ParamDef)); + Debug.Assert(MdToken.IsNullToken(tkParamDef) == scope.Equals(MetadataImport.EmptyImport)); + Debug.Assert(MdToken.IsNullToken(tkParamDef) || MdToken.IsTokenOfType(tkParamDef, MetadataTokenType.ParamDef)); PositionImpl = position; MemberImpl = member; @@ -513,7 +484,7 @@ namespace System.Reflection else parameterType = m_signature.Arguments[PositionImpl]; - Contract.Assert(parameterType != null); + 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; } @@ -524,7 +495,6 @@ namespace System.Reflection public override String Name { - [System.Security.SecuritySafeCritical] // auto-generated get { if (!m_nameIsCached) @@ -588,10 +558,9 @@ namespace System.Reflection } // returns DBNull.Value if the parameter doesn't have a default value - [System.Security.SecuritySafeCritical] private Object GetDefaultValueInternal(bool raw) { - Contract.Assert(!m_noMetadata); + Debug.Assert(!m_noMetadata); if (m_noDefaultValue) return DBNull.Value; @@ -728,7 +697,7 @@ namespace System.Reflection public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) - throw new ArgumentNullException("attributeType"); + throw new ArgumentNullException(nameof(attributeType)); Contract.EndContractBlock(); if (MdToken.IsNullToken(m_tkParamDef)) @@ -737,16 +706,15 @@ namespace System.Reflection RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "attributeType"); + throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType)); return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType); } - [System.Security.SecuritySafeCritical] // auto-generated public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) - throw new ArgumentNullException("attributeType"); + throw new ArgumentNullException(nameof(attributeType)); Contract.EndContractBlock(); if (MdToken.IsNullToken(m_tkParamDef)) @@ -755,7 +723,7 @@ namespace System.Reflection RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "attributeType"); + throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType)); return CustomAttribute.IsDefined(this, attributeRuntimeType); } @@ -765,31 +733,5 @@ namespace System.Reflection return CustomAttributeData.GetCustomAttributesInternal(this); } #endregion - -#if FEATURE_REMOTING - #region Remoting Cache - private RemotingParameterCachedData m_cachedData; - - internal RemotingParameterCachedData RemotingCache - { - get - { - // This grabs an internal copy of m_cachedData and uses - // that instead of looking at m_cachedData directly because - // the cache may get cleared asynchronously. This prevents - // us from having to take a lock. - RemotingParameterCachedData cache = m_cachedData; - if (cache == null) - { - cache = new RemotingParameterCachedData(this); - RemotingParameterCachedData ret = Interlocked.CompareExchange(ref m_cachedData, cache, null); - if (ret != null) - cache = ret; - } - return cache; - } - } - #endregion -#endif //FEATURE_REMOTING } } diff --git a/src/mscorlib/src/System/Reflection/Pointer.cs b/src/mscorlib/src/System/Reflection/Pointer.cs index 8105208288..95025b20ed 100644 --- a/src/mscorlib/src/System/Reflection/Pointer.cs +++ b/src/mscorlib/src/System/Reflection/Pointer.cs @@ -22,13 +22,11 @@ namespace System.Reflection { [System.Runtime.InteropServices.ComVisible(true)] public sealed class Pointer : ISerializable { - [SecurityCritical] unsafe private void* _ptr; private RuntimeType _ptrType; private Pointer() {} - [System.Security.SecurityCritical] // auto-generated private unsafe Pointer(SerializationInfo info, StreamingContext context) { _ptr = ((IntPtr)(info.GetValue("_ptr", typeof(IntPtr)))).ToPointer(); @@ -38,17 +36,16 @@ namespace System.Reflection { // This method will box an pointer. We save both the // value and the type so we can access it from the native code // during an Invoke. - [System.Security.SecurityCritical] // auto-generated public static unsafe Object Box(void *ptr,Type type) { if (type == null) - throw new ArgumentNullException("type"); + throw new ArgumentNullException(nameof(type)); if (!type.IsPointer) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBePointer"),"ptr"); + throw new ArgumentException(Environment.GetResourceString("Arg_MustBePointer"),nameof(ptr)); Contract.EndContractBlock(); RuntimeType rt = type as RuntimeType; if (rt == null) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBePointer"), "ptr"); + throw new ArgumentException(Environment.GetResourceString("Arg_MustBePointer"), nameof(ptr)); Pointer x = new Pointer(); x._ptr = ptr; @@ -57,10 +54,9 @@ namespace System.Reflection { } // Returned the stored pointer. - [System.Security.SecurityCritical] // auto-generated public static unsafe void* Unbox(Object ptr) { if (!(ptr is Pointer)) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBePointer"),"ptr"); + throw new ArgumentException(Environment.GetResourceString("Arg_MustBePointer"),nameof(ptr)); return ((Pointer)ptr)._ptr; } @@ -68,12 +64,10 @@ namespace System.Reflection { return _ptrType; } - [System.Security.SecurityCritical] // auto-generated internal unsafe Object GetPointerValue() { return (IntPtr)_ptr; } - [System.Security.SecurityCritical] unsafe void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("_ptr", new IntPtr(_ptr)); info.AddValue("_ptrType", _ptrType); diff --git a/src/mscorlib/src/System/Reflection/PropertyInfo.cs b/src/mscorlib/src/System/Reflection/PropertyInfo.cs index 3e451b15b6..e31b378924 100644 --- a/src/mscorlib/src/System/Reflection/PropertyInfo.cs +++ b/src/mscorlib/src/System/Reflection/PropertyInfo.cs @@ -22,9 +22,6 @@ namespace System.Reflection [Serializable] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_PropertyInfo))] -#pragma warning disable 618 - [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")] -#pragma warning restore 618 [System.Runtime.InteropServices.ComVisible(true)] public abstract class PropertyInfo : MemberInfo, _PropertyInfo { @@ -153,35 +150,6 @@ namespace System.Reflection public bool IsSpecialName { get { return(Attributes & PropertyAttributes.SpecialName) != 0; } } #endregion - -#if !FEATURE_CORECLR - Type _PropertyInfo.GetType() - { - return base.GetType(); - } - - void _PropertyInfo.GetTypeInfoCount(out uint pcTInfo) - { - throw new NotImplementedException(); - } - - void _PropertyInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) - { - throw new NotImplementedException(); - } - - void _PropertyInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) - { - throw new NotImplementedException(); - } - - // If you implement this method, make sure to include _PropertyInfo.Invoke in VM\DangerousAPIs.h and - // include _PropertyInfo in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp. - void _PropertyInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) - { - throw new NotImplementedException(); - } -#endif } [Serializable] @@ -190,7 +158,6 @@ namespace System.Reflection #region Private Data Members private int m_token; private string m_name; - [System.Security.SecurityCritical] private void* m_utf8name; private PropertyAttributes m_flags; private RuntimeTypeCache m_reflectedTypeCache; @@ -204,13 +171,12 @@ namespace System.Reflection #endregion #region Constructor - [System.Security.SecurityCritical] // auto-generated internal RuntimePropertyInfo( int tkProperty, RuntimeType declaredType, RuntimeTypeCache reflectedTypeCache, out bool isPrivate) { Contract.Requires(declaredType != null); Contract.Requires(reflectedTypeCache != null); - Contract.Assert(!reflectedTypeCache.IsGlobal); + Debug.Assert(!reflectedTypeCache.IsGlobal); MetadataImport scope = declaredType.GetRuntimeModule().MetadataImport; @@ -245,7 +211,6 @@ namespace System.Reflection internal Signature Signature { - [System.Security.SecuritySafeCritical] // auto-generated get { if (m_signature == null) @@ -332,28 +297,27 @@ namespace System.Reflection public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) - throw new ArgumentNullException("attributeType"); + throw new ArgumentNullException(nameof(attributeType)); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType"); + throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType)); return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType); } - [System.Security.SecuritySafeCritical] // auto-generated public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) - throw new ArgumentNullException("attributeType"); + throw new ArgumentNullException(nameof(attributeType)); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType"); + throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType)); return CustomAttribute.IsDefined(this, attributeRuntimeType); } @@ -368,7 +332,6 @@ namespace System.Reflection public override MemberTypes MemberType { get { return MemberTypes.Property; } } public override String Name { - [System.Security.SecuritySafeCritical] // auto-generated get { if (m_name == null) @@ -421,7 +384,6 @@ namespace System.Reflection return Signature.GetCustomModifiers(0, false); } - [System.Security.SecuritySafeCritical] // auto-generated internal object GetConstantValue(bool raw) { Object defaultValue = MdConstant.GetValue(GetRuntimeModule().MetadataImport, m_token, PropertyType.GetTypeHandleInternal(), raw); @@ -630,11 +592,10 @@ namespace System.Reflection #endregion #region ISerializable Implementation - [System.Security.SecurityCritical] // auto-generated public void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) - throw new ArgumentNullException("info"); + throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); MemberInfoSerializationHolder.GetSerializationInfo( diff --git a/src/mscorlib/src/System/Reflection/ReflectionContext.cs b/src/mscorlib/src/System/Reflection/ReflectionContext.cs index f9bfa87d76..34f692166c 100644 --- a/src/mscorlib/src/System/Reflection/ReflectionContext.cs +++ b/src/mscorlib/src/System/Reflection/ReflectionContext.cs @@ -28,7 +28,7 @@ namespace System.Reflection public virtual TypeInfo GetTypeForObject(object value) { if (value == null) - throw new ArgumentNullException("value"); + throw new ArgumentNullException(nameof(value)); return MapType(value.GetType().GetTypeInfo()); } diff --git a/src/mscorlib/src/System/Reflection/ReflectionTypeLoadException.cs b/src/mscorlib/src/System/Reflection/ReflectionTypeLoadException.cs index 9b55c260cf..70681138c5 100644 --- a/src/mscorlib/src/System/Reflection/ReflectionTypeLoadException.cs +++ b/src/mscorlib/src/System/Reflection/ReflectionTypeLoadException.cs @@ -65,10 +65,9 @@ namespace System.Reflection { get {return _exceptions;} } - [System.Security.SecurityCritical] // auto-generated_required public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info==null) { - throw new ArgumentNullException("info"); + throw new ArgumentNullException(nameof(info)); } Contract.EndContractBlock(); base.GetObjectData(info, context); diff --git a/src/mscorlib/src/System/Reflection/RuntimeReflectionExtensions.cs b/src/mscorlib/src/System/Reflection/RuntimeReflectionExtensions.cs index b4ef9b9902..00ab975842 100644 --- a/src/mscorlib/src/System/Reflection/RuntimeReflectionExtensions.cs +++ b/src/mscorlib/src/System/Reflection/RuntimeReflectionExtensions.cs @@ -72,7 +72,7 @@ namespace System.Reflection public static InterfaceMapping GetRuntimeInterfaceMap(this TypeInfo typeInfo, Type interfaceType) { - if (typeInfo == null) throw new ArgumentNullException("typeInfo"); + if (typeInfo == null) throw new ArgumentNullException(nameof(typeInfo)); if (!(typeInfo is RuntimeType)) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType")); return typeInfo.GetInterfaceMap(interfaceType); @@ -80,7 +80,7 @@ namespace System.Reflection public static MethodInfo GetMethodInfo(this Delegate del) { - if (del == null) throw new ArgumentNullException("del"); + if (del == null) throw new ArgumentNullException(nameof(del)); return del.Method; } diff --git a/src/mscorlib/src/System/Reflection/StrongNameKeyPair.cs b/src/mscorlib/src/System/Reflection/StrongNameKeyPair.cs index e8a441ca8f..8107cf4159 100644 --- a/src/mscorlib/src/System/Reflection/StrongNameKeyPair.cs +++ b/src/mscorlib/src/System/Reflection/StrongNameKeyPair.cs @@ -26,20 +26,7 @@ namespace System.Reflection using System.Runtime.Versioning; using Microsoft.Win32; using System.Diagnostics.Contracts; -#if !FEATURE_CORECLR - using Microsoft.Runtime.Hosting; -#endif -#if FEATURE_CORECLR - // Dummy type to avoid ifdefs in signature definitions - public class StrongNameKeyPair - { - private StrongNameKeyPair() - { - throw new NotSupportedException(); - } - } -#else [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public class StrongNameKeyPair : IDeserializationCallback, ISerializable @@ -50,14 +37,10 @@ namespace System.Reflection private byte[] _publicKey; // Build key pair from file. - [System.Security.SecuritySafeCritical] // auto-generated -#pragma warning disable 618 - [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)] -#pragma warning restore 618 public StrongNameKeyPair(FileStream keyPairFile) { if (keyPairFile == null) - throw new ArgumentNullException("keyPairFile"); + throw new ArgumentNullException(nameof(keyPairFile)); Contract.EndContractBlock(); int length = (int)keyPairFile.Length; @@ -68,14 +51,10 @@ namespace System.Reflection } // Build key pair from byte array in memory. - [System.Security.SecuritySafeCritical] // auto-generated -#pragma warning disable 618 - [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)] -#pragma warning restore 618 public StrongNameKeyPair(byte[] keyPairArray) { if (keyPairArray == null) - throw new ArgumentNullException("keyPairArray"); + throw new ArgumentNullException(nameof(keyPairArray)); Contract.EndContractBlock(); _keyPairArray = new byte[keyPairArray.Length]; @@ -83,27 +62,7 @@ namespace System.Reflection _keyPairExported = true; } - - // Reference key pair in named key container. - [System.Security.SecuritySafeCritical] // auto-generated -#pragma warning disable 618 - [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)] -#pragma warning restore 618 - public StrongNameKeyPair(String keyPairContainer) - { - if (keyPairContainer == null) - throw new ArgumentNullException("keyPairContainer"); - Contract.EndContractBlock(); - - _keyPairContainer = keyPairContainer; - - _keyPairExported = false; - } - - [System.Security.SecuritySafeCritical] // auto-generated -#pragma warning disable 618 - [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)] -#pragma warning restore 618 + protected StrongNameKeyPair (SerializationInfo info, StreamingContext context) { _keyPairExported = (bool) info.GetValue("_keyPairExported", typeof(bool)); _keyPairArray = (byte[]) info.GetValue("_keyPairArray", typeof(byte[])); @@ -111,68 +70,20 @@ namespace System.Reflection _publicKey = (byte[]) info.GetValue("_publicKey", typeof(byte[])); } - // Get the public portion of the key pair. - public byte[] PublicKey + public StrongNameKeyPair(String keyPairContainer) { - [System.Security.SecuritySafeCritical] // auto-generated - get - { - if (_publicKey == null) - { - _publicKey = ComputePublicKey(); - } - - byte[] publicKey = new byte[_publicKey.Length]; - Array.Copy(_publicKey, publicKey, _publicKey.Length); - - return publicKey; - } + throw new PlatformNotSupportedException(); } - - [System.Security.SecurityCritical] // auto-generated - private unsafe byte[] ComputePublicKey() + + public byte[] PublicKey { - byte[] publicKey = null; - - // Make sure pbPublicKey is not leaked with async exceptions - RuntimeHelpers.PrepareConstrainedRegions(); - try { - } - finally + get { - IntPtr pbPublicKey = IntPtr.Zero; - int cbPublicKey = 0; - - try - { - bool result; - if (_keyPairExported) - { - result = StrongNameHelpers.StrongNameGetPublicKey(null, _keyPairArray, _keyPairArray.Length, - out pbPublicKey, out cbPublicKey); - } - else - { - result = StrongNameHelpers.StrongNameGetPublicKey(_keyPairContainer, null, 0, - out pbPublicKey, out cbPublicKey); - } - if (!result) - throw new ArgumentException(Environment.GetResourceString("Argument_StrongNameGetPublicKey")); - - publicKey = new byte[cbPublicKey]; - Buffer.Memcpy(publicKey, 0, (byte*)(pbPublicKey.ToPointer()), 0, cbPublicKey); - } - finally - { - if (pbPublicKey != IntPtr.Zero) - StrongNameHelpers.StrongNameFreeBuffer(pbPublicKey); - } + throw new PlatformNotSupportedException(); } - return publicKey; } /// <internalonly/> - [System.Security.SecurityCritical] void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context) { info.AddValue("_keyPairExported", _keyPairExported); info.AddValue("_keyPairArray", _keyPairArray); @@ -182,13 +93,5 @@ namespace System.Reflection /// <internalonly/> void IDeserializationCallback.OnDeserialization (Object sender) {} - - // Internal routine used to retrieve key pair info from unmanaged code. - private bool GetKeyPair(out Object arrayOrContainer) - { - arrayOrContainer = _keyPairExported ? (Object)_keyPairArray : (Object)_keyPairContainer; - return _keyPairExported; - } } -#endif // FEATURE_CORECLR } diff --git a/src/mscorlib/src/System/Reflection/TargetException.cs b/src/mscorlib/src/System/Reflection/TargetException.cs index 02772f763f..9c56c121cc 100644 --- a/src/mscorlib/src/System/Reflection/TargetException.cs +++ b/src/mscorlib/src/System/Reflection/TargetException.cs @@ -19,11 +19,7 @@ namespace System.Reflection { using System.Runtime.Serialization; [Serializable] [System.Runtime.InteropServices.ComVisible(true)] -#if FEATURE_CORECLR - public class TargetException : Exception { -#else public class TargetException : ApplicationException { -#endif //FEATURE_CORECLR public TargetException() : base() { SetErrorCode(__HResults.COR_E_TARGET); } diff --git a/src/mscorlib/src/System/Reflection/TargetInvocationException.cs b/src/mscorlib/src/System/Reflection/TargetInvocationException.cs index 70de4227dd..4a32ed245d 100644 --- a/src/mscorlib/src/System/Reflection/TargetInvocationException.cs +++ b/src/mscorlib/src/System/Reflection/TargetInvocationException.cs @@ -19,11 +19,7 @@ namespace System.Reflection { using System.Runtime.Serialization; [Serializable] [System.Runtime.InteropServices.ComVisible(true)] -#if FEATURE_CORECLR - public sealed class TargetInvocationException : Exception { -#else public sealed class TargetInvocationException : ApplicationException { -#endif //FEATURE_CORECLR // This exception is not creatable without specifying the // inner exception. private TargetInvocationException() diff --git a/src/mscorlib/src/System/Reflection/TargetParameterCountException.cs b/src/mscorlib/src/System/Reflection/TargetParameterCountException.cs index 4f95b09c40..846732b449 100644 --- a/src/mscorlib/src/System/Reflection/TargetParameterCountException.cs +++ b/src/mscorlib/src/System/Reflection/TargetParameterCountException.cs @@ -19,11 +19,7 @@ namespace System.Reflection { using System.Runtime.Serialization; [Serializable] [System.Runtime.InteropServices.ComVisible(true)] -#if FEATURE_CORECLR - public sealed class TargetParameterCountException : Exception { -#else public sealed class TargetParameterCountException : ApplicationException { -#endif //FEATURE_CORECLR public TargetParameterCountException() : base(Environment.GetResourceString("Arg_TargetParameterCountException")) { SetErrorCode(__HResults.COR_E_TARGETPARAMCOUNT); diff --git a/src/mscorlib/src/System/Reflection/TypeDelegator.cs b/src/mscorlib/src/System/Reflection/TypeDelegator.cs index cad4a4295a..d715df8950 100644 --- a/src/mscorlib/src/System/Reflection/TypeDelegator.cs +++ b/src/mscorlib/src/System/Reflection/TypeDelegator.cs @@ -24,14 +24,11 @@ namespace System.Reflection { protected Type typeImpl; - #if FEATURE_CORECLR - [System.Security.SecuritySafeCritical] // auto-generated - #endif protected TypeDelegator() {} public TypeDelegator(Type delegatingType) { if (delegatingType == null) - throw new ArgumentNullException("delegatingType"); + throw new ArgumentNullException(nameof(delegatingType)); Contract.EndContractBlock(); typeImpl = delegatingType; |