diff options
16 files changed, 451 insertions, 1154 deletions
diff --git a/src/System.Private.CoreLib/src/System/Reflection/Emit/AssemblyBuilder.cs b/src/System.Private.CoreLib/src/System/Reflection/Emit/AssemblyBuilder.cs index 06ed8d13dd..14330ae7e5 100644 --- a/src/System.Private.CoreLib/src/System/Reflection/Emit/AssemblyBuilder.cs +++ b/src/System.Private.CoreLib/src/System/Reflection/Emit/AssemblyBuilder.cs @@ -2,7 +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. -// // For each dynamic assembly there will be two AssemblyBuilder objects: the "internal" // AssemblyBuilder object and the "external" AssemblyBuilder object. // 1. The "internal" object is the real assembly object that the VM creates and knows about. However, @@ -19,25 +18,19 @@ // "internal" object. // // "internal" and "external" ModuleBuilders are similar -// + +using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.SymbolStore; +using System.Globalization; +using System.IO; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Security; +using System.Threading; namespace System.Reflection.Emit { - using System; - using System.Collections.Generic; - using System.Diagnostics; - using System.Diagnostics.SymbolStore; - using CultureInfo = System.Globalization.CultureInfo; - using System.IO; - using System.Reflection; - using System.Resources; - using System.Runtime.CompilerServices; - using System.Runtime.InteropServices; - using System.Runtime.Serialization; - using System.Runtime.Versioning; - using System.Security; - using System.Threading; - // When the user calls AppDomain.DefineDynamicAssembly the loader creates a new InternalAssemblyBuilder. // This InternalAssemblyBuilder can be retrieved via a call to Assembly.GetAssemblies() by untrusted code. // In the past, when InternalAssemblyBuilder was AssemblyBuilder, the untrusted user could down cast the @@ -58,23 +51,26 @@ namespace System.Reflection.Emit { private InternalAssemblyBuilder() { } - #region object overrides public override bool Equals(object obj) { if (obj == null) + { return false; + } if (obj is InternalAssemblyBuilder) - return ((object)this == obj); + { + return (object)this == obj; + } return obj.Equals(this); } - // Need a dummy GetHashCode to pair with Equals - public override int GetHashCode() { return base.GetHashCode(); } - #endregion + + public override int GetHashCode() => base.GetHashCode(); // Assembly methods that are overridden by AssemblyBuilder should be overridden by InternalAssemblyBuilder too #region Methods inherited from Assembly + public override string[] GetManifestResourceNames() { throw new NotSupportedException(SR.NotSupported_DynamicAssembly); @@ -107,18 +103,12 @@ namespace System.Reflection.Emit public override string Location { - get - { - throw new NotSupportedException(SR.NotSupported_DynamicAssembly); - } + get => throw new NotSupportedException(SR.NotSupported_DynamicAssembly); } public override string CodeBase { - get - { - throw new NotSupportedException(SR.NotSupported_DynamicAssembly); - } + get => throw new NotSupportedException(SR.NotSupported_DynamicAssembly); } public override Type[] GetExportedTypes() @@ -126,76 +116,54 @@ namespace System.Reflection.Emit throw new NotSupportedException(SR.NotSupported_DynamicAssembly); } - public override string ImageRuntimeVersion - { - get - { - return RuntimeEnvironment.GetSystemVersion(); - } - } + public override string ImageRuntimeVersion => RuntimeEnvironment.GetSystemVersion(); + #endregion } public sealed class AssemblyBuilder : Assembly { - #region FCALL [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern RuntimeModule GetInMemoryAssemblyModule(RuntimeAssembly assembly); - private Module nGetInMemoryAssemblyModule() - { - return AssemblyBuilder.GetInMemoryAssemblyModule(GetNativeHandle()); - } - - #endregion - #region Internal Data Members + // This is only valid in the "external" AssemblyBuilder - internal AssemblyBuilderData m_assemblyData; - private InternalAssemblyBuilder m_internalAssemblyBuilder; - private ModuleBuilder m_manifestModuleBuilder; + internal AssemblyBuilderData _assemblyData; + private readonly InternalAssemblyBuilder _internalAssemblyBuilder; + private ModuleBuilder _manifestModuleBuilder; // 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"; + private bool _isManifestModuleUsedAsDefinedModule; + + private const string ManifestModuleName = "RefEmit_InMemoryManifestModule"; internal ModuleBuilder GetModuleBuilder(InternalModuleBuilder module) { Debug.Assert(module != null); - Debug.Assert(this.InternalAssembly == module.Assembly); + Debug.Assert(InternalAssembly == module.Assembly); lock (SyncRoot) { // in CoreCLR there is only one module in each dynamic assembly, the manifest module - if (m_manifestModuleBuilder.InternalModule == module) - return m_manifestModuleBuilder; + if (_manifestModuleBuilder.InternalModule == module) + { + return _manifestModuleBuilder; + } throw new ArgumentException(null, nameof(module)); } } - internal object SyncRoot - { - get - { - return InternalAssembly.SyncRoot; - } - } + internal object SyncRoot => InternalAssembly.SyncRoot; - internal InternalAssemblyBuilder InternalAssembly - { - get - { - return m_internalAssemblyBuilder; - } - } + internal InternalAssemblyBuilder InternalAssembly => _internalAssemblyBuilder; + + internal RuntimeAssembly GetNativeHandle() => InternalAssembly.GetNativeHandle(); - internal RuntimeAssembly GetNativeHandle() - { - return InternalAssembly.GetNativeHandle(); - } #endregion #region Constructor + internal AssemblyBuilder(AppDomain domain, AssemblyName name, AssemblyBuilderAccess access, @@ -203,11 +171,10 @@ namespace System.Reflection.Emit IEnumerable<CustomAttributeBuilder> unsafeAssemblyAttributes) { if (name == null) + { throw new ArgumentNullException(nameof(name)); - - if (access != AssemblyBuilderAccess.Run - && access != AssemblyBuilderAccess.RunAndCollect - ) + } + if (access != AssemblyBuilderAccess.Run && access != AssemblyBuilderAccess.RunAndCollect) { throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)access), nameof(access)); } @@ -226,14 +193,12 @@ namespace System.Reflection.Emit assemblyAttributes = new List<CustomAttributeBuilder>(unsafeAssemblyAttributes); } - m_internalAssemblyBuilder = (InternalAssemblyBuilder)nCreateDynamicAssembly(domain, + _internalAssemblyBuilder = (InternalAssemblyBuilder)nCreateDynamicAssembly(domain, name, ref stackMark, access); - m_assemblyData = new AssemblyBuilderData(m_internalAssemblyBuilder, - name.Name, - access); + _assemblyData = new AssemblyBuilderData(_internalAssemblyBuilder, access); // Make sure that ManifestModule is properly initialized // We need to do this before setting any CustomAttribute @@ -242,18 +207,20 @@ namespace System.Reflection.Emit if (assemblyAttributes != null) { foreach (CustomAttributeBuilder assemblyAttribute in assemblyAttributes) + { SetCustomAttribute(assemblyAttribute); + } } } private void InitManifestModule() { - InternalModuleBuilder modBuilder = (InternalModuleBuilder)nGetInMemoryAssemblyModule(); + InternalModuleBuilder modBuilder = (InternalModuleBuilder)GetInMemoryAssemblyModule(GetNativeHandle()); // Note that this ModuleBuilder cannot be used for RefEmit yet // because it hasn't been initialized. // However, it can be used to set the custom attribute on the Assembly - m_manifestModuleBuilder = new ModuleBuilder(this, modBuilder); + _manifestModuleBuilder = new ModuleBuilder(this, modBuilder); // We are only setting the name in the managed ModuleBuilderData here. // The name in the underlying metadata will be set when the @@ -261,10 +228,11 @@ namespace System.Reflection.Emit // This name needs to stay in sync with that used in // Assembly::Init to call ReflectionModule::Create (in VM) - m_manifestModuleBuilder.Init(AssemblyBuilder.MANIFEST_MODULE_NAME, null, 0); + _manifestModuleBuilder.Init(ManifestModuleName); - m_fManifestModuleUsedAsDefinedModule = false; + _isManifestModuleUsedAsDefinedModule = false; } + #endregion #region DefineDynamicAssembly @@ -274,27 +242,21 @@ namespace System.Reflection.Emit /// to have a strong name and a hash will be computed when the assembly /// is saved. /// </summary> - [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod. - public static AssemblyBuilder DefineDynamicAssembly( - AssemblyName name, - AssemblyBuilderAccess access) + [DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod. + public static AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - return InternalDefineDynamicAssembly(name, access, - ref stackMark, null); + return InternalDefineDynamicAssembly(name, access, ref stackMark, null); } - [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod. + [DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod. public static AssemblyBuilder DefineDynamicAssembly( AssemblyName name, AssemblyBuilderAccess access, IEnumerable<CustomAttributeBuilder> assemblyAttributes) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - return InternalDefineDynamicAssembly(name, - access, - ref stackMark, - assemblyAttributes); + return InternalDefineDynamicAssembly(name, access, ref stackMark, assemblyAttributes); } @@ -314,36 +276,32 @@ namespace System.Reflection.Emit { lock (typeof(AssemblyBuilderLock)) { - // we can only create dynamic assemblies in the current domain + // We can only create dynamic assemblies in the current domain return new AssemblyBuilder(AppDomain.CurrentDomain, name, access, ref stackMark, unsafeAssemblyAttributes); - } //lock(typeof(AssemblyBuilderLock)) + } } #endregion #region DefineDynamicModule + /// <summary> /// Defines a named dynamic module. It is an error to define multiple /// modules within an Assembly with the same name. This dynamic module is /// a transient module. /// </summary> - [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod. - public ModuleBuilder DefineDynamicModule( - string name) + [DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod. + public ModuleBuilder DefineDynamicModule(string name) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return DefineDynamicModuleInternal(name, false, ref stackMark); } - - /// <param name = "name" ></ param > - /// <param name = "emitSymbolInfo" >Specify if emit symbol info or not.</ param > - [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod. - public ModuleBuilder DefineDynamicModule( - string name, - bool emitSymbolInfo) + + [DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod. + public ModuleBuilder DefineDynamicModule(string name, bool emitSymbolInfo) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return DefineDynamicModuleInternal(name, emitSymbolInfo, ref stackMark); @@ -366,89 +324,101 @@ namespace System.Reflection.Emit ref StackCrawlMark stackMark) { if (name == null) + { throw new ArgumentNullException(nameof(name)); + } if (name.Length == 0) + { throw new ArgumentException(SR.Argument_EmptyName, nameof(name)); + } if (name[0] == '\0') + { throw new ArgumentException(SR.Argument_InvalidName, nameof(name)); + } - Debug.Assert(m_assemblyData != null, "m_assemblyData is null in DefineDynamicModuleInternal"); - - ModuleBuilder dynModule; - ISymbolWriter writer = null; - IntPtr pInternalSymWriter = new IntPtr(); - - // create the dynamic module- only one ModuleBuilder per AssemblyBuilder can be created - if (m_fManifestModuleUsedAsDefinedModule == true) + // Create the dynamic module- only one ModuleBuilder per AssemblyBuilder can be created. + if (_isManifestModuleUsedAsDefinedModule) + { throw new InvalidOperationException(SR.InvalidOperation_NoMultiModuleAssembly); + } + + Debug.Assert(_assemblyData != null, "_assemblyData is null in DefineDynamicModuleInternal"); - // Init(...) has already been called on m_manifestModuleBuilder in InitManifestModule() - dynModule = m_manifestModuleBuilder; + // Init(...) has already been called on _manifestModuleBuilder in InitManifestModule() + ModuleBuilder dynModule = _manifestModuleBuilder; // Create the symbol writer + ISymbolWriter writer = null; if (emitSymbolInfo) { writer = SymWrapperCore.SymWriter.CreateSymWriter(); - string fileName = "Unused"; // this symfile is never written to disk so filename does not matter. - - // Pass the "real" module to the VM - pInternalSymWriter = ModuleBuilder.nCreateISymWriterForDynamicModule(dynModule.InternalModule, fileName); - - // 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. + // Pass the "real" module to the VM. + // This symfile is never written to disk so filename does not matter. + IntPtr pInternalSymWriter = ModuleBuilder.nCreateISymWriterForDynamicModule(dynModule.InternalModule, "Unused"); ((SymWrapperCore.SymWriter)writer).InternalSetUnderlyingWriter(pInternalSymWriter); - } // Creating the symbol writer + } dynModule.SetSymWriter(writer); - m_assemblyData.AddModule(dynModule); + _assemblyData._moduleBuilderList.Add(dynModule); - if (dynModule == m_manifestModuleBuilder) - { // We are reusing manifest module as user-defined dynamic module - m_fManifestModuleUsedAsDefinedModule = true; + if (dynModule == _manifestModuleBuilder) + { + // We are reusing manifest module as user-defined dynamic module + _isManifestModuleUsedAsDefinedModule = true; } return dynModule; - } // DefineDynamicModuleInternalNoLock + } #endregion internal void CheckContext(params Type[][] typess) { if (typess == null) + { return; + } foreach (Type[] types in typess) + { if (types != null) + { CheckContext(types); + } + } } internal void CheckContext(params Type[] types) { if (types == null) + { return; + } foreach (Type type in types) { if (type == null) + { continue; + } if (type.Module == null || type.Module.Assembly == null) + { throw new ArgumentException(SR.Argument_TypeNotValid); + } if (type.Module.Assembly == typeof(object).Module.Assembly) + { continue; + } } } - #region object overrides - public override bool Equals(object obj) - { - return InternalAssembly.Equals(obj); - } + public override bool Equals(object obj) => InternalAssembly.Equals(obj); + // Need a dummy GetHashCode to pair with Equals - public override int GetHashCode() { return InternalAssembly.GetHashCode(); } - #endregion + public override int GetHashCode() => InternalAssembly.GetHashCode(); #region ICustomAttributeProvider Members public override object[] GetCustomAttributes(bool inherit) @@ -470,9 +440,11 @@ namespace System.Reflection.Emit { return InternalAssembly.GetCustomAttributesData(); } + #endregion #region Assembly overrides + /// <returns>The names of all the resources.</returns> public override string[] GetManifestResourceNames() { @@ -504,109 +476,46 @@ namespace System.Reflection.Emit return InternalAssembly.GetManifestResourceInfo(resourceName); } - public override string Location - { - get - { - return InternalAssembly.Location; - } - } + public override string Location => InternalAssembly.Location; - public override string ImageRuntimeVersion - { - get - { - return InternalAssembly.ImageRuntimeVersion; - } - } + public override string ImageRuntimeVersion => InternalAssembly.ImageRuntimeVersion; - public override string CodeBase - { - get - { - return InternalAssembly.CodeBase; - } - } + public override string CodeBase => InternalAssembly.CodeBase; /// <sumary> /// Override the EntryPoint method on Assembly. /// This doesn't need to be synchronized because it is simple enough. /// </sumary> - public override MethodInfo EntryPoint - { - get - { - return m_assemblyData.m_entryPointMethod; - } - } + public override MethodInfo EntryPoint => _assemblyData._entryPointMethod; /// <sumary> /// Get an array of all the public types defined in this assembly. /// </sumary> - public override Type[] GetExportedTypes() - { - return InternalAssembly.GetExportedTypes(); - } + public override Type[] GetExportedTypes() => InternalAssembly.GetExportedTypes(); - public override AssemblyName GetName(bool copiedName) - { - return InternalAssembly.GetName(copiedName); - } + public override AssemblyName GetName(bool copiedName) => InternalAssembly.GetName(copiedName); - public override string FullName - { - get - { - return InternalAssembly.FullName; - } - } + public override string FullName => InternalAssembly.FullName; public override Type GetType(string name, bool throwOnError, bool ignoreCase) { return InternalAssembly.GetType(name, throwOnError, ignoreCase); } - public override Module ManifestModule - { - get - { - return m_manifestModuleBuilder.InternalModule; - } - } + public override Module ManifestModule => _manifestModuleBuilder.InternalModule; - public override bool ReflectionOnly - { - get - { - return InternalAssembly.ReflectionOnly; - } - } + public override bool ReflectionOnly => InternalAssembly.ReflectionOnly; - public override Module GetModule(string name) - { - return InternalAssembly.GetModule(name); - } + public override Module GetModule(string name) => InternalAssembly.GetModule(name); public override AssemblyName[] GetReferencedAssemblies() { return InternalAssembly.GetReferencedAssemblies(); } - public override bool GlobalAssemblyCache - { - get - { - return InternalAssembly.GlobalAssemblyCache; - } - } + public override bool GlobalAssemblyCache => InternalAssembly.GlobalAssemblyCache; - public override long HostContext - { - get - { - return InternalAssembly.HostContext; - } - } + public override long HostContext => InternalAssembly.HostContext; public override Module[] GetModules(bool getResourceModules) { @@ -618,7 +527,7 @@ namespace System.Reflection.Emit return InternalAssembly.GetLoadedModules(getResourceModules); } - [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod. + [DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod. public override Assembly GetSatelliteAssembly(CultureInfo culture) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; @@ -628,28 +537,22 @@ namespace System.Reflection.Emit /// <sumary> /// Useful for binding to a very specific version of a satellite assembly /// </sumary> - [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod. + [DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod. public override Assembly GetSatelliteAssembly(CultureInfo culture, Version version) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return InternalAssembly.InternalGetSatelliteAssembly(culture, version, ref stackMark); } - public override bool IsDynamic - { - get - { - return true; - } - } + public override bool IsDynamic => true; public override bool IsCollectible => InternalAssembly.IsCollectible; + #endregion /// <param name="name">The name of module for the look up.</param> /// <returns>Dynamic module with the specified name.</returns> - public ModuleBuilder GetDynamicModule( - string name) + public ModuleBuilder GetDynamicModule(string name) { lock (SyncRoot) { @@ -658,19 +561,21 @@ namespace System.Reflection.Emit } /// <param name="name">The name of module for the look up.</param> - private ModuleBuilder GetDynamicModuleNoLock( - string name) + private ModuleBuilder GetDynamicModuleNoLock(string name) { if (name == null) + { throw new ArgumentNullException(nameof(name)); + } if (name.Length == 0) + { throw new ArgumentException(SR.Argument_EmptyName, nameof(name)); + } - int size = m_assemblyData.m_moduleBuilderList.Count; - for (int i = 0; i < size; i++) + for (int i = 0; i < _assemblyData._moduleBuilderList.Count; i++) { - ModuleBuilder moduleBuilder = (ModuleBuilder)m_assemblyData.m_moduleBuilderList[i]; - if (moduleBuilder.m_moduleData.m_strModuleName.Equals(name)) + ModuleBuilder moduleBuilder = _assemblyData._moduleBuilderList[i]; + if (moduleBuilder._moduleData._moduleName.Equals(name)) { return moduleBuilder; } @@ -684,9 +589,13 @@ namespace System.Reflection.Emit public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { if (con == null) + { throw new ArgumentNullException(nameof(con)); + } if (binaryAttribute == null) + { throw new ArgumentNullException(nameof(binaryAttribute)); + } lock (SyncRoot) { @@ -697,19 +606,12 @@ namespace System.Reflection.Emit private void SetCustomAttributeNoLock(ConstructorInfo con, byte[] binaryAttribute) { TypeBuilder.DefineCustomAttribute( - m_manifestModuleBuilder, // pass in the in-memory assembly module - AssemblyBuilderData.m_tkAssembly, // This is the AssemblyDef token - m_manifestModuleBuilder.GetConstructorToken(con).Token, + _manifestModuleBuilder, // pass in the in-memory assembly module + AssemblyBuilderData.AssemblyDefToken, + _manifestModuleBuilder.GetConstructorToken(con).Token, binaryAttribute, false, - typeof(System.Diagnostics.DebuggableAttribute) == con.DeclaringType); - - // Track the CA for persistence - if (m_assemblyData.m_access != AssemblyBuilderAccess.Run) - { - // tracking the CAs for persistence - m_assemblyData.AddCustomAttribute(con, binaryAttribute); - } + typeof(DebuggableAttribute) == con.DeclaringType); } /// <summary> @@ -730,15 +632,7 @@ namespace System.Reflection.Emit private void SetCustomAttributeNoLock(CustomAttributeBuilder customBuilder) { - customBuilder.CreateCustomAttribute( - m_manifestModuleBuilder, - AssemblyBuilderData.m_tkAssembly); // This is the AssemblyDef token - - // Track the CA for persistence - if (m_assemblyData.m_access != AssemblyBuilderAccess.Run) - { - m_assemblyData.AddCustomAttribute(customBuilder); - } + customBuilder.CreateCustomAttribute(_manifestModuleBuilder, AssemblyBuilderData.AssemblyDefToken); } } } diff --git a/src/System.Private.CoreLib/src/System/Reflection/Emit/AssemblyBuilderData.cs b/src/System.Private.CoreLib/src/System/Reflection/Emit/AssemblyBuilderData.cs index e2f38a226f..1eacc38d73 100644 --- a/src/System.Private.CoreLib/src/System/Reflection/Emit/AssemblyBuilderData.cs +++ b/src/System.Private.CoreLib/src/System/Reflection/Emit/AssemblyBuilderData.cs @@ -2,19 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Collections.Generic; + namespace System.Reflection.Emit { - using System; - using IList = System.Collections.IList; - using System.Collections.Generic; - using System.Reflection; - using System.Security; - using System.Diagnostics; - using CultureInfo = System.Globalization.CultureInfo; - using System.IO; - using System.Runtime.Versioning; - using System.Diagnostics.SymbolStore; - /// <summary> /// This is a package private class. This class hold all of the managed /// data member for AssemblyBuilder. Note that what ever data members added to @@ -22,173 +13,31 @@ namespace System.Reflection.Emit /// </summary> internal class AssemblyBuilderData { - internal AssemblyBuilderData( - InternalAssemblyBuilder assembly, - string strAssemblyName, - AssemblyBuilderAccess access) - { - m_assembly = assembly; - m_strAssemblyName = strAssemblyName; - m_access = access; - m_moduleBuilderList = new List<ModuleBuilder>(); - m_resWriterList = new List<ResWriterData>(); + public const int AssemblyDefToken = 0x20000001; - m_peFileKind = PEFileKinds.Dll; - } - - /// <summary> - /// Helper to add a dynamic module into the tracking list. - /// </summary> - internal void AddModule(ModuleBuilder dynModule) - { - m_moduleBuilderList.Add(dynModule); - } + public readonly List<ModuleBuilder> _moduleBuilderList; + public readonly AssemblyBuilderAccess _access; + public MethodInfo _entryPointMethod; - /// <summary> - /// Helper to track CAs to persist onto disk. - /// </summary> - internal void AddCustomAttribute(CustomAttributeBuilder customBuilder) - { - // make sure we have room for this CA - if (m_CABuilders == null) - { - m_CABuilders = new CustomAttributeBuilder[m_iInitialSize]; - } - if (m_iCABuilder == m_CABuilders.Length) - { - CustomAttributeBuilder[] tempCABuilders = new CustomAttributeBuilder[m_iCABuilder * 2]; - Array.Copy(m_CABuilders, 0, tempCABuilders, 0, m_iCABuilder); - m_CABuilders = tempCABuilders; - } - m_CABuilders[m_iCABuilder] = customBuilder; + private readonly InternalAssemblyBuilder _assembly; - m_iCABuilder++; - } - - /// <summary> - /// Helper to track CAs to persist onto disk. - /// </summary> - internal void AddCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) + internal AssemblyBuilderData(InternalAssemblyBuilder assembly, AssemblyBuilderAccess access) { - // make sure we have room for this CA - if (m_CABytes == null) - { - m_CABytes = new byte[m_iInitialSize][]; - m_CACons = new ConstructorInfo[m_iInitialSize]; - } - if (m_iCAs == m_CABytes.Length) - { - // enlarge the arrays - byte[][] temp = new byte[m_iCAs * 2][]; - ConstructorInfo[] tempCon = new ConstructorInfo[m_iCAs * 2]; - for (int i = 0; i < m_iCAs; i++) - { - temp[i] = m_CABytes[i]; - tempCon[i] = m_CACons[i]; - } - m_CABytes = temp; - m_CACons = tempCon; - } - - byte[] attrs = new byte[binaryAttribute.Length]; - Buffer.BlockCopy(binaryAttribute, 0, attrs, 0, binaryAttribute.Length); - m_CABytes[m_iCAs] = attrs; - m_CACons[m_iCAs] = con; - m_iCAs++; + _assembly = assembly; + _access = access; + _moduleBuilderList = new List<ModuleBuilder>(); } - + /// <summary> /// Helper to ensure the type name is unique underneath assemblyBuilder. /// </summary> - internal void CheckTypeNameConflict(string strTypeName, TypeBuilder enclosingType) + public void CheckTypeNameConflict(string strTypeName, TypeBuilder enclosingType) { - for (int i = 0; i < m_moduleBuilderList.Count; i++) + for (int i = 0; i < _moduleBuilderList.Count; i++) { - ModuleBuilder curModule = m_moduleBuilderList[i]; + ModuleBuilder curModule = _moduleBuilderList[i]; curModule.CheckTypeNameConflict(strTypeName, enclosingType); } - - // Right now dynamic modules can only be added to dynamic assemblies in which - // all modules are dynamic. Otherwise we would also need to check loaded types. - // We only need to make this test for non-nested types since any - // duplicates in nested types will be caught at the top level. - // if (enclosingType == null && m_assembly.GetType(strTypeName, false, false) != null) - // { - // // Cannot have two types with the same name - // throw new ArgumentException(SR.Argument_DuplicateTypeName); - // } } - - internal List<ModuleBuilder> m_moduleBuilderList; - internal List<ResWriterData> m_resWriterList; - internal string m_strAssemblyName; - internal AssemblyBuilderAccess m_access; - private InternalAssemblyBuilder m_assembly; - - internal Type[] m_publicComTypeList; - internal int m_iPublicComTypeCount; - - internal bool m_isSaved; - internal const int m_iInitialSize = 16; - - // hard coding the assembly def token - internal const int m_tkAssembly = 0x20000001; - - // tracking AssemblyDef's CAs for persistence to disk - internal CustomAttributeBuilder[] m_CABuilders; - internal int m_iCABuilder; - internal byte[][] m_CABytes; - internal ConstructorInfo[] m_CACons; - internal int m_iCAs; - internal PEFileKinds m_peFileKind; // assembly file kind - internal MethodInfo m_entryPointMethod; - internal Assembly m_ISymWrapperAssembly; - - // For unmanaged resources - internal string m_strResourceFileName; - internal byte[] m_resourceBytes; - internal NativeVersionInfo m_nativeVersion; - internal bool m_hasUnmanagedVersionInfo; - internal bool m_OverrideUnmanagedVersionInfo; - } - - /// <summary> - /// Internal structure to track the list of ResourceWriter for - /// AssemblyBuilder & ModuleBuilder. - /// </summary> - internal class ResWriterData - { - internal string m_strName; - internal string m_strFileName; - internal string m_strFullFileName; - internal Stream m_memoryStream; - internal ResWriterData m_nextResWriter; - internal ResourceAttributes m_attribute; - } - - internal class NativeVersionInfo - { - internal NativeVersionInfo() - { - m_strDescription = null; - m_strCompany = null; - m_strTitle = null; - m_strCopyright = null; - m_strTrademark = null; - m_strProduct = null; - m_strProductVersion = null; - m_strFileVersion = null; - m_lcid = -1; - } - - internal string m_strDescription; - internal string m_strCompany; - internal string m_strTitle; - internal string m_strCopyright; - internal string m_strTrademark; - internal string m_strProduct; - internal string m_strProductVersion; - internal string m_strFileVersion; - internal int m_lcid; } } diff --git a/src/System.Private.CoreLib/src/System/Reflection/Emit/ConstructorBuilder.cs b/src/System.Private.CoreLib/src/System/Reflection/Emit/ConstructorBuilder.cs index 91e64e4f6b..895bbbc329 100644 --- a/src/System.Private.CoreLib/src/System/Reflection/Emit/ConstructorBuilder.cs +++ b/src/System.Private.CoreLib/src/System/Reflection/Emit/ConstructorBuilder.cs @@ -2,18 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// +using System.Globalization; namespace System.Reflection.Emit { - using System; - using System.Reflection; - using CultureInfo = System.Globalization.CultureInfo; - using System.Collections.Generic; - using System.Diagnostics.SymbolStore; - using System.Security; - using System.Runtime.InteropServices; - public sealed class ConstructorBuilder : ConstructorInfo { private readonly MethodBuilder m_methodBuilder; diff --git a/src/System.Private.CoreLib/src/System/Reflection/Emit/EventToken.cs b/src/System.Private.CoreLib/src/System/Reflection/Emit/EventToken.cs index 53dfa9a603..d0a406d89c 100644 --- a/src/System.Private.CoreLib/src/System/Reflection/Emit/EventToken.cs +++ b/src/System.Private.CoreLib/src/System/Reflection/Emit/EventToken.cs @@ -2,64 +2,29 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================ -** -** -** -** -** -** Propertybuilder is for client to define properties for a class -** -** -===========================================================*/ - -using System; -using System.Reflection; - namespace System.Reflection.Emit { public struct EventToken { public static readonly EventToken Empty = new EventToken(); - internal int m_event; + private int _token; - internal EventToken(int str) + internal EventToken(int eventToken) { - m_event = str; + _token = eventToken; } - public int Token - { - get { return m_event; } - } + public int Token => _token; - public override int GetHashCode() - { - return m_event; - } + public override int GetHashCode() => Token; - public override bool Equals(object obj) - { - if (obj is EventToken) - return Equals((EventToken)obj); - else - return false; - } + public override bool Equals(object obj) => obj is EventToken et && Equals(et); - public bool Equals(EventToken obj) - { - return obj.m_event == m_event; - } + public bool Equals(EventToken obj) => obj.Token == Token; - public static bool operator ==(EventToken a, EventToken b) - { - return a.Equals(b); - } + public static bool operator ==(EventToken a, EventToken b) => a.Equals(b); - public static bool operator !=(EventToken a, EventToken b) - { - return !(a == b); - } + public static bool operator !=(EventToken a, EventToken b) => !(a == b); } } diff --git a/src/System.Private.CoreLib/src/System/Reflection/Emit/FieldToken.cs b/src/System.Private.CoreLib/src/System/Reflection/Emit/FieldToken.cs index b6441bf4f2..c272919f4e 100644 --- a/src/System.Private.CoreLib/src/System/Reflection/Emit/FieldToken.cs +++ b/src/System.Private.CoreLib/src/System/Reflection/Emit/FieldToken.cs @@ -2,84 +2,37 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================ -** -** -** -** -** -** Purpose: Represents a Field to the ILGenerator Class -** -** -===========================================================*/ - -using System; -using System.Reflection; - namespace System.Reflection.Emit { - // The FieldToken class is an opaque representation of the Token returned - // by the Metadata to represent the field. FieldTokens are generated by - // Module.GetFieldToken(). There are no meaningful accessors on this class, - // but it can be passed to ILGenerator which understands it's internals. + /// <summary> + /// The FieldToken class is an opaque representation of the Token returned + /// by the Metadata to represent the field. FieldTokens are generated by + /// Module.GetFieldToken(). There are no meaningful accessors on this class, + /// but it can be passed to ILGenerator which understands it's internals. + /// </summary> public struct FieldToken { public static readonly FieldToken Empty = new FieldToken(); - internal int m_fieldTok; - internal object m_class; - - // Creates an empty FieldToken. A publicly visible constructor so that - // it can be created on the stack. - //public FieldToken() { - // m_fieldTok=0; - // m_attributes=0; - // m_class=null; - //} - // The actual constructor. Sets the field, attributes and class - // variables - - internal FieldToken(int field, Type fieldClass) - { - m_fieldTok = field; - m_class = fieldClass; - } - - public int Token - { - get { return m_fieldTok; } - } - + private readonly int _token; + private readonly object _class; - // Generates the hash code for this field. - public override int GetHashCode() + internal FieldToken(int fieldToken, Type fieldClass) { - return (m_fieldTok); + _token = fieldToken; + _class = fieldClass; } - // Returns true if obj is an instance of FieldToken and is - // equal to this instance. - public override bool Equals(object obj) - { - if (obj is FieldToken) - return Equals((FieldToken)obj); - else - return false; - } + public int Token => _token; + + public override int GetHashCode() => Token; + + public override bool Equals(object obj) => obj is FieldToken ft && Equals(ft); - public bool Equals(FieldToken obj) - { - return obj.m_fieldTok == m_fieldTok && obj.m_class == m_class; - } + public bool Equals(FieldToken obj) => obj.Token == Token && obj._class == _class; - public static bool operator ==(FieldToken a, FieldToken b) - { - return a.Equals(b); - } + public static bool operator ==(FieldToken a, FieldToken b) => a.Equals(b); - public static bool operator !=(FieldToken a, FieldToken b) - { - return !(a == b); - } + public static bool operator !=(FieldToken a, FieldToken b) => !(a == b); } } diff --git a/src/System.Private.CoreLib/src/System/Reflection/Emit/MethodToken.cs b/src/System.Private.CoreLib/src/System/Reflection/Emit/MethodToken.cs index 2c0a91872e..3546041e0b 100644 --- a/src/System.Private.CoreLib/src/System/Reflection/Emit/MethodToken.cs +++ b/src/System.Private.CoreLib/src/System/Reflection/Emit/MethodToken.cs @@ -2,63 +2,29 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================ -** -** -** -** -** -** Purpose: Represents a Method to the ILGenerator class. -** -** -===========================================================*/ - -using System; -using System.Reflection; - namespace System.Reflection.Emit { public struct MethodToken { public static readonly MethodToken Empty = new MethodToken(); - internal int m_method; - internal MethodToken(int str) - { - m_method = str; - } + private readonly int _token; - public int Token + internal MethodToken(int methodToken) { - get { return m_method; } + _token = methodToken; } - public override int GetHashCode() - { - return m_method; - } + public int Token => _token; - public override bool Equals(object obj) - { - if (obj is MethodToken) - return Equals((MethodToken)obj); - else - return false; - } + public override int GetHashCode() => Token; - public bool Equals(MethodToken obj) - { - return obj.m_method == m_method; - } + public override bool Equals(object obj) => obj is MethodToken mt && Equals(mt); - public static bool operator ==(MethodToken a, MethodToken b) - { - return a.Equals(b); - } + public bool Equals(MethodToken obj) => obj.Token == Token; - public static bool operator !=(MethodToken a, MethodToken b) - { - return !(a == b); - } + public static bool operator ==(MethodToken a, MethodToken b) => a.Equals(b); + + public static bool operator !=(MethodToken a, MethodToken b) => !(a == b); } } diff --git a/src/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilder.cs b/src/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilder.cs index d0b8c87ab0..8b0beb11c9 100644 --- a/src/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilder.cs +++ b/src/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilder.cs @@ -2,62 +2,45 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// +using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.SymbolStore; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; namespace System.Reflection.Emit { - using System.Runtime.InteropServices; - using System; - using System.Collections.Generic; - using System.Diagnostics.SymbolStore; - using System.Globalization; - using System.Reflection; - using System.IO; - using System.Resources; - using System.Security; - using System.Runtime.Serialization; - using System.Text; - using System.Threading; - using System.Runtime.Versioning; - using System.Runtime.CompilerServices; - using System.Diagnostics; - internal sealed class InternalModuleBuilder : RuntimeModule { - #region Private Data Members - // WARNING!! WARNING!! // InternalModuleBuilder should not contain any data members as its reflectbase is the same as Module. - #endregion private InternalModuleBuilder() { } - #region object overrides public override bool Equals(object obj) { if (obj == null) + { return false; + } if (obj is InternalModuleBuilder) + { return ((object)this == obj); + } return obj.Equals(this); } + // Need a dummy GetHashCode to pair with Equals - public override int GetHashCode() { return base.GetHashCode(); } - #endregion + public override int GetHashCode() => base.GetHashCode(); } // deliberately not [serializable] public class ModuleBuilder : Module { - #region FCalls - - [MethodImplAttribute(MethodImplOptions.InternalCall)] + [MethodImpl(MethodImplOptions.InternalCall)] internal static extern IntPtr nCreateISymWriterForDynamicModule(Module module, string filename); - #endregion - - #region Internal Static Members internal static string UnmangleTypeName(string typeName) { // Gets the original type name, without '+' name mangling. @@ -67,16 +50,22 @@ namespace System.Reflection.Emit { i = typeName.LastIndexOf('+', i); if (i == -1) + { break; + } bool evenSlashes = true; int iSlash = i; while (typeName[--iSlash] == '\\') + { evenSlashes = !evenSlashes; + } // Even number of slashes means this '+' is a name separator if (evenSlashes) + { break; + } i = iSlash; } @@ -84,39 +73,37 @@ namespace System.Reflection.Emit return typeName.Substring(i + 1); } - #endregion - #region Internal Data Members - // m_TypeBuilder contains both TypeBuilder and EnumBuilder objects - private Dictionary<string, Type> m_TypeBuilderDict; - private ISymbolWriter m_iSymWriter; - internal ModuleBuilderData m_moduleData; - internal InternalModuleBuilder m_internalModuleBuilder; + + // _TypeBuilder contains both TypeBuilder and EnumBuilder objects + private Dictionary<string, Type> _typeBuilderDict; + private ISymbolWriter _iSymWriter; + internal ModuleBuilderData _moduleData; + internal InternalModuleBuilder _internalModuleBuilder; // This is the "external" AssemblyBuilder // only the "external" ModuleBuilder has this set - private AssemblyBuilder m_assemblyBuilder; - internal AssemblyBuilder ContainingAssemblyBuilder { get { return m_assemblyBuilder; } } + private readonly AssemblyBuilder _assemblyBuilder; + internal AssemblyBuilder ContainingAssemblyBuilder => _assemblyBuilder; + #endregion #region Constructor + internal ModuleBuilder(AssemblyBuilder assemblyBuilder, InternalModuleBuilder internalModuleBuilder) { - m_internalModuleBuilder = internalModuleBuilder; - m_assemblyBuilder = assemblyBuilder; + _internalModuleBuilder = internalModuleBuilder; + _assemblyBuilder = assemblyBuilder; } + #endregion #region Private Members - internal void AddType(string name, Type type) - { - m_TypeBuilderDict.Add(name, type); - } + internal void AddType(string name, Type type) => _typeBuilderDict.Add(name, type); internal void CheckTypeNameConflict(string strTypeName, Type enclosingType) { - Type foundType = null; - if (m_TypeBuilderDict.TryGetValue(strTypeName, out foundType) && - object.ReferenceEquals(foundType.DeclaringType, enclosingType)) + if (_typeBuilderDict.TryGetValue(strTypeName, out Type foundType) && + ReferenceEquals(foundType.DeclaringType, enclosingType)) { // Cannot have two types with the same name throw new ArgumentException(SR.Argument_DuplicateTypeName); @@ -126,7 +113,6 @@ namespace System.Reflection.Emit private Type GetType(string strFormat, Type baseType) { // This function takes a string to describe the compound type, such as "[,][]", and a baseType. - if (strFormat == null || strFormat.Equals(string.Empty)) { return baseType; @@ -136,7 +122,6 @@ namespace System.Reflection.Emit return SymbolType.FormCompoundType(strFormat, baseType, 0); } - internal void CheckContext(params Type[][] typess) { ContainingAssemblyBuilder.CheckContext(typess); @@ -146,7 +131,6 @@ namespace System.Reflection.Emit ContainingAssemblyBuilder.CheckContext(types); } - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] private static extern int GetTypeRef(RuntimeModule module, string strFullName, RuntimeModule refedModule, string strRefedModuleFileName, int tkResolution); @@ -213,21 +197,25 @@ namespace System.Reflection.Emit #endregion #region Internal Members + internal virtual Type FindTypeBuilderWithName(string strTypeName, bool ignoreCase) { if (ignoreCase) { - foreach (string name in m_TypeBuilderDict.Keys) + foreach (string name in _typeBuilderDict.Keys) { if (string.Equals(name, strTypeName, StringComparison.OrdinalIgnoreCase)) - return m_TypeBuilderDict[name]; + { + return _typeBuilderDict[name]; + } } } else { - Type foundType; - if (m_TypeBuilderDict.TryGetValue(strTypeName, out foundType)) + if (_typeBuilderDict.TryGetValue(strTypeName, out Type foundType)) + { return foundType; + } } return null; @@ -236,7 +224,6 @@ namespace System.Reflection.Emit private int GetTypeRefNested(Type type, Module refedModule, string strRefedModuleFileName) { // This function will generate correct TypeRef token for top level type and nested type. - Type enclosingType = type.DeclaringType; int tkResolution = 0; string typeName = type.FullName; @@ -256,9 +243,10 @@ namespace System.Reflection.Emit 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(nameof(con)); + } int tr; int mr = 0; @@ -287,7 +275,6 @@ namespace System.Reflection.Emit { // constructor is not a dynamic field // We need to get the TypeRef tokens - tr = GetTypeTokenInternal(con.ReflectedType).Token; mr = GetMemberRefOfMethodInfo(tr, rtCon); } @@ -297,7 +284,9 @@ namespace System.Reflection.Emit // go through the slower code path, i.e. retrieve parameters and form signature helper. ParameterInfo[] parameters = con.GetParameters(); if (parameters == null) + { throw new ArgumentException(SR.Argument_InvalidConstructorInfo); + } Type[] parameterTypes = new Type[parameters.Length]; Type[][] requiredCustomModifiers = new Type[parameters.Length][]; @@ -306,7 +295,9 @@ namespace System.Reflection.Emit for (int i = 0; i < parameters.Length; i++) { if (parameters[i] == null) + { throw new ArgumentException(SR.Argument_InvalidConstructorInfo); + } parameterTypes[i] = parameters[i].ParameterType; requiredCustomModifiers[i] = parameters[i].GetRequiredCustomModifiers(); @@ -316,56 +307,33 @@ namespace System.Reflection.Emit tr = GetTypeTokenInternal(con.ReflectedType).Token; SignatureHelper sigHelp = SignatureHelper.GetMethodSigHelper(this, con.CallingConvention, null, null, null, parameterTypes, requiredCustomModifiers, optionalCustomModifiers); - int length; - byte[] sigBytes = sigHelp.InternalGetSignature(out length); - + byte[] sigBytes = sigHelp.InternalGetSignature(out int length); mr = GetMemberRefFromSignature(tr, con.Name, sigBytes, length); } return new MethodToken(mr); } - internal void Init(string strModuleName, string strFileName, int tkFile) + internal void Init(string strModuleName) { - m_moduleData = new ModuleBuilderData(this, strModuleName, strFileName, tkFile); - m_TypeBuilderDict = new Dictionary<string, Type>(); + _moduleData = new ModuleBuilderData(this, strModuleName); + _typeBuilderDict = new Dictionary<string, Type>(); } - internal void SetSymWriter(ISymbolWriter writer) - { - m_iSymWriter = writer; - } + internal void SetSymWriter(ISymbolWriter writer) => _iSymWriter = writer; - internal object SyncRoot - { - get - { - return ContainingAssemblyBuilder.SyncRoot; - } - } + internal object SyncRoot => ContainingAssemblyBuilder.SyncRoot; #endregion #region Module Overrides - // m_internalModuleBuilder is null iff this is a "internal" ModuleBuilder - internal InternalModuleBuilder InternalModule - { - get - { - return m_internalModuleBuilder; - } - } + // _internalModuleBuilder is null iff this is a "internal" ModuleBuilder + internal InternalModuleBuilder InternalModule => _internalModuleBuilder; - protected override ModuleHandle GetModuleHandleImpl() - { - return new ModuleHandle(GetNativeHandle()); - } + protected override ModuleHandle GetModuleHandleImpl() => new ModuleHandle(GetNativeHandle()); - internal RuntimeModule GetNativeHandle() - { - return InternalModule.GetNativeHandle(); - } + internal RuntimeModule GetNativeHandle() => InternalModule.GetNativeHandle(); private static RuntimeModule GetRuntimeModuleFromModule(Module m) { @@ -388,7 +356,9 @@ namespace System.Reflection.Emit if (method.IsGenericMethod) { if (!method.IsGenericMethodDefinition) + { throw new InvalidOperationException(); + } cGenericParameters = method.GetGenericArguments().Length; } @@ -435,14 +405,14 @@ namespace System.Reflection.Emit methDef = masmi.GetGenericMethodDefinition(); methDef = methDef.Module.ResolveMethod( method.MetadataToken, - methDef.DeclaringType != null ? methDef.DeclaringType.GetGenericArguments() : null, + methDef.DeclaringType?.GetGenericArguments(), methDef.GetGenericArguments()); } else { methDef = method.Module.ResolveMethod( method.MetadataToken, - method.DeclaringType != null ? method.DeclaringType.GetGenericArguments() : null, + method.DeclaringType?.GetGenericArguments(), null); } } @@ -456,14 +426,12 @@ namespace System.Reflection.Emit returnType = MethodBuilder.GetMethodBaseReturnType(method); } - int sigLength; byte[] sigBytes = GetMemberRefSignature(method.CallingConvention, returnType, parameterTypes, - optionalParameterTypes, cGenericParameters).InternalGetSignature(out sigLength); + optionalParameterTypes, cGenericParameters).InternalGetSignature(out int sigLength); if (method.DeclaringType.IsGenericType) { - int length; - byte[] sig = SignatureHelper.GetTypeSigToken(this, method.DeclaringType).InternalGetSignature(out length); + byte[] sig = SignatureHelper.GetTypeSigToken(this, method.DeclaringType).InternalGetSignature(out int length); tkParent = GetTokenFromTypeSpec(sig, length); } else if (!method.Module.Equals(this)) @@ -517,16 +485,13 @@ namespace System.Reflection.Emit #endregion - #region object overrides - public override bool Equals(object obj) - { - return InternalModule.Equals(obj); - } + public override bool Equals(object obj) => InternalModule.Equals(obj); + // Need a dummy GetHashCode to pair with Equals - public override int GetHashCode() { return InternalModule.GetHashCode(); } - #endregion + public override int GetHashCode() => InternalModule.GetHashCode(); #region ICustomAttributeProvider Members + public override object[] GetCustomAttributes(bool inherit) { return InternalModule.GetCustomAttributes(inherit); @@ -546,6 +511,7 @@ namespace System.Reflection.Emit { return InternalModule.GetCustomAttributesData(); } + #endregion #region Module Overrides @@ -560,11 +526,11 @@ namespace System.Reflection.Emit internal Type[] GetTypesNoLock() { - int size = m_TypeBuilderDict.Count; - Type[] typeList = new Type[m_TypeBuilderDict.Count]; + int size = _typeBuilderDict.Count; + Type[] typeList = new Type[_typeBuilderDict.Count]; int i = 0; - foreach (Type builder in m_TypeBuilderDict.Values) + foreach (Type builder in _typeBuilderDict.Values) { EnumBuilder enumBldr = builder as EnumBuilder; TypeBuilder tmpTypeBldr; @@ -668,7 +634,6 @@ namespace System.Reflection.Emit { // try to see if reflection can find the base type. It can be such that reflection // does not support the complex format string yet! - baseType = InternalModule.GetType(baseName, false, ignoreCase); } @@ -683,7 +648,7 @@ namespace System.Reflection.Emit int size; List<ModuleBuilder> modList; - modList = ContainingAssemblyBuilder.m_assemblyData.m_moduleBuilderList; + modList = ContainingAssemblyBuilder._assemblyData._moduleBuilderList; size = modList.Count; for (int i = 0; i < size && baseType == null; i++) { @@ -692,22 +657,20 @@ namespace System.Reflection.Emit } } if (baseType == null) + { return null; + } } if (parameters == null) + { return baseType; + } return GetType(parameters, baseType); } - public override string FullyQualifiedName - { - get - { - return m_moduleData.m_strFileName; - } - } + public override string FullyQualifiedName => _moduleData._moduleName; public override byte[] ResolveSignature(int metadataToken) { @@ -744,34 +707,13 @@ namespace System.Reflection.Emit InternalModule.GetPEKind(out peKind, out machine); } - public override int MDStreamVersion - { - get - { - return InternalModule.MDStreamVersion; - } - } + public override int MDStreamVersion => InternalModule.MDStreamVersion; - public override Guid ModuleVersionId - { - get - { - return InternalModule.ModuleVersionId; - } - } + public override Guid ModuleVersionId => InternalModule.ModuleVersionId; - public override int MetadataToken - { - get - { - return InternalModule.MetadataToken; - } - } + public override int MetadataToken => InternalModule.MetadataToken; - public override bool IsResource() - { - return InternalModule.IsResource(); - } + public override bool IsResource() => InternalModule.IsResource(); public override FieldInfo[] GetFields(BindingFlags bindingFlags) { @@ -795,35 +737,18 @@ namespace System.Reflection.Emit return InternalModule.GetMethodInternal(name, bindingAttr, binder, callConvention, types, modifiers); } - public override string ScopeName - { - get - { - return InternalModule.ScopeName; - } - } + public override string ScopeName => InternalModule.ScopeName; - public override string Name - { - get - { - return InternalModule.Name; - } - } + public override string Name => InternalModule.Name; - public override Assembly Assembly - { - get - { - return m_assemblyBuilder; - } - } + public override Assembly Assembly => _assemblyBuilder; #endregion #region Public Members #region Define Type + public TypeBuilder DefineType(string name) { lock (SyncRoot) @@ -844,7 +769,6 @@ namespace System.Reflection.Emit { lock (SyncRoot) { - // Why do we only call CheckContext here? Why don't we call it in the other overloads? CheckContext(parent); return DefineTypeNoLock(name, attr, parent, null, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize); @@ -907,17 +831,8 @@ namespace System.Reflection.Emit EnumBuilder enumBuilder = DefineEnumNoLock(name, visibility, underlyingType); // This enum is not generic, nested, and cannot have any element type. - - // We ought to be able to make the following assertions: - // - // Debug.Assert(name == enumBuilder.FullName); - // Debug.Assert(enumBuilder.m_typeBuilder == m_TypeBuilderDict[name]); - // - // but we can't because an embedded null ('\0') in the name will cause it to be truncated - // incorrectly. Fixing that would be a breaking change. - - // Replace the TypeBuilder object in m_TypeBuilderDict with this EnumBuilder object. - m_TypeBuilderDict[name] = enumBuilder; + // Replace the TypeBuilder object in _typeBuilderDict with this EnumBuilder object. + _typeBuilderDict[name] = enumBuilder; return enumBuilder; } @@ -930,9 +845,6 @@ namespace System.Reflection.Emit #endregion - #region Define Resource - - #endregion #region Define Global Method public MethodBuilder DefinePInvokeMethod(string name, string dllName, MethodAttributes attributes, @@ -948,7 +860,7 @@ namespace System.Reflection.Emit { lock (SyncRoot) { - //Global methods must be static. + // Global methods must be static. if ((attributes & MethodAttributes.Static) == 0) { throw new ArgumentException(SR.Argument_GlobalFunctionHasToBeStatic); @@ -957,8 +869,7 @@ namespace System.Reflection.Emit CheckContext(returnType); CheckContext(parameterTypes); - m_moduleData.m_fHasGlobal = true; - return m_moduleData.m_globalTypeBuilder.DefinePInvokeMethod(name, dllName, entryName, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet); + return _moduleData._globalTypeBuilder.DefinePInvokeMethod(name, dllName, entryName, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet); } } @@ -989,26 +900,29 @@ namespace System.Reflection.Emit Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers, Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers) { - if (m_moduleData.m_fGlobalBeenCreated == true) + if (_moduleData._hasGlobalBeenCreated) + { throw new InvalidOperationException(SR.InvalidOperation_GlobalsHaveBeenCreated); - + } if (name == null) + { throw new ArgumentNullException(nameof(name)); - + } if (name.Length == 0) + { throw new ArgumentException(SR.Argument_EmptyName, nameof(name)); - + } if ((attributes & MethodAttributes.Static) == 0) + { throw new ArgumentException(SR.Argument_GlobalFunctionHasToBeStatic); + } CheckContext(returnType); CheckContext(requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, parameterTypes); CheckContext(requiredParameterTypeCustomModifiers); CheckContext(optionalParameterTypeCustomModifiers); - m_moduleData.m_fHasGlobal = true; - - return m_moduleData.m_globalTypeBuilder.DefineMethod(name, attributes, callingConvention, + return _moduleData._globalTypeBuilder.DefineMethod(name, attributes, callingConvention, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers); } @@ -1023,13 +937,13 @@ namespace System.Reflection.Emit private void CreateGlobalFunctionsNoLock() { - if (m_moduleData.m_fGlobalBeenCreated) + if (_moduleData._hasGlobalBeenCreated) { // cannot create globals twice throw new InvalidOperationException(SR.InvalidOperation_NotADebugModule); } - m_moduleData.m_globalTypeBuilder.CreateType(); - m_moduleData.m_fGlobalBeenCreated = true; + _moduleData._globalTypeBuilder.CreateType(); + _moduleData._hasGlobalBeenCreated = true; } #endregion @@ -1053,13 +967,12 @@ namespace System.Reflection.Emit // This method will define an initialized Data in .sdata. // We will create a fake TypeDef to represent the data with size. This TypeDef // will be the signature for the Field. - if (m_moduleData.m_fGlobalBeenCreated == true) + if (_moduleData._hasGlobalBeenCreated == true) { throw new InvalidOperationException(SR.InvalidOperation_GlobalsHaveBeenCreated); } - m_moduleData.m_fHasGlobal = true; - return m_moduleData.m_globalTypeBuilder.DefineInitializedData(name, data, attributes); + return _moduleData._globalTypeBuilder.DefineInitializedData(name, data, attributes); } public FieldBuilder DefineUninitializedData(string name, int size, FieldAttributes attributes) @@ -1076,25 +989,25 @@ namespace System.Reflection.Emit // We will create a fake TypeDef to represent the data with size. This TypeDef // will be the signature for the Field. - if (m_moduleData.m_fGlobalBeenCreated == true) + if (_moduleData._hasGlobalBeenCreated) { throw new InvalidOperationException(SR.InvalidOperation_GlobalsHaveBeenCreated); } - m_moduleData.m_fHasGlobal = true; - return m_moduleData.m_globalTypeBuilder.DefineUninitializedData(name, size, attributes); + return _moduleData._globalTypeBuilder.DefineUninitializedData(name, size, attributes); } #endregion #region GetToken + // For a generic type definition, we should return the token for the generic type definition itself in two cases: // 1. GetTypeToken // 2. ldtoken (see ILGenerator) // For all other occasions we should return the generic type instantiated on its formal parameters. internal TypeToken GetTypeTokenInternal(Type type) { - return GetTypeTokenInternal(type, false); + return GetTypeTokenInternal(type, getGenericDefinition: false); } private TypeToken GetTypeTokenInternal(Type type, bool getGenericDefinition) @@ -1107,13 +1020,15 @@ namespace System.Reflection.Emit public TypeToken GetTypeToken(Type type) { - return GetTypeTokenInternal(type, true); + return GetTypeTokenInternal(type, getGenericDefinition: true); } private TypeToken GetTypeTokenWorkerNoLock(Type type, bool getGenericDefinition) { if (type == null) + { throw new ArgumentNullException(nameof(type)); + } CheckContext(type); @@ -1126,17 +1041,17 @@ namespace System.Reflection.Emit // multiple calles to this method with the same class have no additional side affects. // This function is optimized to use the TypeDef token if Type is within the same module. // We should also be aware of multiple dynamic modules and multiple implementation of Type!!! - if (type.IsByRef) + { throw new ArgumentException(SR.Argument_CannotGetTypeTokenForByRef); + } if ((type.IsGenericType && (!type.IsGenericTypeDefinition || !getGenericDefinition)) || type.IsGenericParameter || type.IsArray || type.IsPointer) { - int length; - byte[] sig = SignatureHelper.GetTypeSigToken(this, type).InternalGetSignature(out length); + byte[] sig = SignatureHelper.GetTypeSigToken(this, type).InternalGetSignature(out int length); return new TypeToken(GetTokenFromTypeSpec(sig, length)); } @@ -1149,16 +1064,11 @@ namespace System.Reflection.Emit GenericTypeParameterBuilder paramBuilder = null; EnumBuilder enumBuilder = type as EnumBuilder; - if (enumBuilder != null) - typeBuilder = enumBuilder.m_typeBuilder; - else - typeBuilder = type as TypeBuilder; + typeBuilder = enumBuilder != null ? enumBuilder.m_typeBuilder : type as TypeBuilder; if (typeBuilder != null) { - // optimization: if the type is defined in this module, - // just return the token - // + // If the type is defined in this module, just return the token. return typeBuilder.TypeToken; } else if ((paramBuilder = type as GenericTypeParameterBuilder) != null) @@ -1171,11 +1081,10 @@ namespace System.Reflection.Emit // After this point, the referenced module is not the same as the referencing // module. - // ModuleBuilder refedModuleBuilder = refedModule as ModuleBuilder; - string strRefedModuleFileName = string.Empty; - if (refedModule.Assembly.Equals(this.Assembly)) + string referencedModuleFileName = string.Empty; + if (refedModule.Assembly.Equals(Assembly)) { // if the referenced module is in the same assembly, the resolution // scope of the type token will be a module ref, we will need @@ -1185,12 +1094,12 @@ namespace System.Reflection.Emit // the file name of the referenced module. if (refedModuleBuilder == null) { - refedModuleBuilder = this.ContainingAssemblyBuilder.GetModuleBuilder((InternalModuleBuilder)refedModule); + refedModuleBuilder = ContainingAssemblyBuilder.GetModuleBuilder((InternalModuleBuilder)refedModule); } - strRefedModuleFileName = refedModuleBuilder.m_moduleData.m_strFileName; + referencedModuleFileName = refedModuleBuilder._moduleData._moduleName; } - return new TypeToken(GetTypeRefNested(type, refedModule, strRefedModuleFileName)); + return new TypeToken(GetTypeRefNested(type, refedModule, referencedModuleFileName)); } public TypeToken GetTypeToken(string name) @@ -1229,7 +1138,9 @@ namespace System.Reflection.Emit // Return a MemberRef token if MethodInfo is not defined in this module. Or // return the MethodDef token. if (method == null) + { throw new ArgumentNullException(nameof(method)); + } int tr; int mr = 0; @@ -1241,10 +1152,14 @@ namespace System.Reflection.Emit { int methodToken = methBuilder.MetadataTokenInternal; if (method.Module.Equals(this)) + { return new MethodToken(methodToken); + } if (method.DeclaringType == null) + { throw new InvalidOperationException(SR.InvalidOperation_CannotImportGlobalFromDifferentModule); + } // method is defined in a different module tr = getGenericTypeDefinition ? GetTypeToken(method.DeclaringType).Token : GetTypeTokenInternal(method.DeclaringType).Token; @@ -1268,7 +1183,9 @@ namespace System.Reflection.Emit // We need to get the TypeRef tokens if (declaringType == null) + { throw new InvalidOperationException(SR.InvalidOperation_CannotImportGlobalFromDifferentModule); + } RuntimeMethodInfo rtMeth = null; @@ -1323,8 +1240,7 @@ namespace System.Reflection.Emit sigHelp = SignatureHelper.GetMethodSigHelper(this, method.ReturnType, parameterTypes); } - int length; - byte[] sigBytes = sigHelp.InternalGetSignature(out length); + byte[] sigBytes = sigHelp.InternalGetSignature(out int length); mr = GetMemberRefFromSignature(tr, method.Name, sigBytes, length); } } @@ -1351,7 +1267,7 @@ namespace System.Reflection.Emit methodInfoUnbound = methodInfo.GetGenericMethodDefinition(); } - if (!this.Equals(methodInfoUnbound.Module) + if (!Equals(methodInfoUnbound.Module) || (methodInfoUnbound.DeclaringType != null && methodInfoUnbound.DeclaringType.IsGenericType)) { tk = GetMemberRefToken(methodInfoUnbound, null); @@ -1368,12 +1284,10 @@ namespace System.Reflection.Emit } // Create signature of method instantiation M<Bar> - int sigLength; - byte[] sigBytes = SignatureHelper.GetMethodSpecSigHelper( - this, methodInfo.GetGenericArguments()).InternalGetSignature(out sigLength); - // Create MethodSepc M<Bar> with parent G?.M<S> - tk = TypeBuilder.DefineMethodSpec(this.GetNativeHandle(), tk, sigBytes, sigLength); + byte[] sigBytes = SignatureHelper.GetMethodSpecSigHelper( + this, methodInfo.GetGenericArguments()).InternalGetSignature(out int sigLength); + tk = TypeBuilder.DefineMethodSpec(GetNativeHandle(), tk, sigBytes, sigLength); } else { @@ -1411,30 +1325,30 @@ namespace System.Reflection.Emit Type returnType, Type[] parameterTypes) { if (arrayClass == null) + { throw new ArgumentNullException(nameof(arrayClass)); - + } if (methodName == null) + { throw new ArgumentNullException(nameof(methodName)); - + } if (methodName.Length == 0) + { throw new ArgumentException(SR.Argument_EmptyName, nameof(methodName)); - - if (arrayClass.IsArray == false) + } + if (!arrayClass.IsArray) + { throw new ArgumentException(SR.Argument_HasToBeArrayClass); + } CheckContext(returnType, arrayClass); CheckContext(parameterTypes); // Return a token for the MethodInfo for a method on an Array. This is primarily // used to get the LoadElementAddress method. - - int length; - SignatureHelper sigHelp = SignatureHelper.GetMethodSigHelper( this, callingConvention, returnType, null, null, parameterTypes, null, null); - - byte[] sigBytes = sigHelp.InternalGetSignature(out length); - + byte[] sigBytes = sigHelp.InternalGetSignature(out int length); TypeToken typeSpec = GetTypeTokenInternal(arrayClass); return new MethodToken(GetArrayMethodToken(GetNativeHandle(), @@ -1489,8 +1403,7 @@ namespace System.Reflection.Emit { if (field.DeclaringType != null && field.DeclaringType.IsGenericType) { - int length; - byte[] sig = SignatureHelper.GetTypeSigToken(this, field.DeclaringType).InternalGetSignature(out length); + byte[] sig = SignatureHelper.GetTypeSigToken(this, field.DeclaringType).InternalGetSignature(out int length); tr = GetTokenFromTypeSpec(sig, length); mr = GetMemberRef(this, tr, fdBuilder.GetToken().Token); } @@ -1513,7 +1426,6 @@ namespace System.Reflection.Emit else if ((rtField = field as RuntimeFieldInfo) != null) { // FieldInfo is not an dynamic field - // We need to get the TypeRef tokens if (field.DeclaringType == null) { @@ -1522,8 +1434,7 @@ namespace System.Reflection.Emit if (field.DeclaringType != null && field.DeclaringType.IsGenericType) { - int length; - byte[] sig = SignatureHelper.GetTypeSigToken(this, field.DeclaringType).InternalGetSignature(out length); + byte[] sig = SignatureHelper.GetTypeSigToken(this, field.DeclaringType).InternalGetSignature(out int length); tr = GetTokenFromTypeSpec(sig, length); mr = GetMemberRefOfFieldInfo(tr, field.DeclaringType.GetTypeHandleInternal(), rtField); } @@ -1536,8 +1447,7 @@ namespace System.Reflection.Emit else if ((fOnTB = field as FieldOnTypeBuilderInstantiation) != null) { FieldInfo fb = fOnTB.FieldInfo; - int length; - byte[] sig = SignatureHelper.GetTypeSigToken(this, field.DeclaringType).InternalGetSignature(out length); + byte[] sig = SignatureHelper.GetTypeSigToken(this, field.DeclaringType).InternalGetSignature(out int length); tr = GetTokenFromTypeSpec(sig, length); mr = GetMemberRef(fb.ReflectedType.Module, tr, fOnTB.MetadataTokenInternal); } @@ -1550,9 +1460,7 @@ namespace System.Reflection.Emit sigHelp.AddArgument(field.FieldType, field.GetRequiredCustomModifiers(), field.GetOptionalCustomModifiers()); - int length; - byte[] sigBytes = sigHelp.InternalGetSignature(out length); - + byte[] sigBytes = sigHelp.InternalGetSignature(out int length); mr = GetMemberRefFromSignature(tr, field.Name, sigBytes, length); } @@ -1575,28 +1483,27 @@ namespace System.Reflection.Emit { // Define signature token given a signature helper. This will define a metadata // token for the signature described by SignatureHelper. - if (sigHelper == null) { throw new ArgumentNullException(nameof(sigHelper)); } - int sigLength; - byte[] sigBytes; - // get the signature in byte form - sigBytes = sigHelper.InternalGetSignature(out sigLength); - return new SignatureToken(TypeBuilder.GetTokenFromSig(GetNativeHandle(), sigBytes, sigLength), this); + byte[] sigBytes = sigHelper.InternalGetSignature(out int sigLength); + return new SignatureToken(TypeBuilder.GetTokenFromSig(GetNativeHandle(), sigBytes, sigLength)); } + public SignatureToken GetSignatureToken(byte[] sigBytes, int sigLength) { if (sigBytes == null) + { throw new ArgumentNullException(nameof(sigBytes)); + } byte[] localSigBytes = new byte[sigBytes.Length]; Buffer.BlockCopy(sigBytes, 0, localSigBytes, 0, sigBytes.Length); - return new SignatureToken(TypeBuilder.GetTokenFromSig(GetNativeHandle(), localSigBytes, sigLength), this); + return new SignatureToken(TypeBuilder.GetTokenFromSig(GetNativeHandle(), localSigBytes, sigLength)); } #endregion @@ -1606,14 +1513,18 @@ namespace System.Reflection.Emit public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { if (con == null) + { throw new ArgumentNullException(nameof(con)); + } if (binaryAttribute == null) + { throw new ArgumentNullException(nameof(binaryAttribute)); + } TypeBuilder.DefineCustomAttribute( this, 1, // This is hard coding the module token to 1 - this.GetConstructorToken(con).Token, + GetConstructorToken(con).Token, binaryAttribute, false, false); } @@ -1653,20 +1564,15 @@ namespace System.Reflection.Emit // writer access can cause AVs and other problems. The writer APIs should not be callable // directly by partial-trust code, but if they could this would be a security hole. // Regardless, this is a reliability bug. - // - // For these reasons, we should consider making this API internal in Arrowhead - // (as it is in Silverlight), and consider validating that we're within a call - // to TypeBuilder.CreateType whenever this is used. - internal ISymbolWriter GetSymWriter() - { - return m_iSymWriter; - } + internal ISymbolWriter GetSymWriter() => _iSymWriter; 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(nameof(url)); + } lock (SyncRoot) { @@ -1676,19 +1582,16 @@ namespace System.Reflection.Emit private ISymbolDocumentWriter DefineDocumentNoLock(string url, Guid language, Guid languageVendor, Guid documentType) { - if (m_iSymWriter == null) + if (_iSymWriter == null) { // Cannot DefineDocument when it is not a debug module throw new InvalidOperationException(SR.InvalidOperation_NotADebugModule); } - return m_iSymWriter.DefineDocument(url, language, languageVendor, documentType); + return _iSymWriter.DefineDocument(url, language, languageVendor, documentType); } - public bool IsTransient() - { - return InternalModule.IsTransientInternal(); - } + public bool IsTransient() => InternalModule.IsTransientInternal(); #endregion diff --git a/src/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilderData.cs b/src/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilderData.cs index 066bb24e6f..02e945b261 100644 --- a/src/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilderData.cs +++ b/src/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilderData.cs @@ -2,13 +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. -using System; -using System.Diagnostics; -using System.Globalization; -using System.IO; -using System.Reflection; -using System.Runtime.Versioning; - namespace System.Reflection.Emit { // This is a package private class. This class hold all of the managed @@ -16,47 +9,16 @@ namespace System.Reflection.Emit // this class cannot be accessed from the EE. internal class ModuleBuilderData { - internal ModuleBuilderData(ModuleBuilder module, string strModuleName, string strFileName, int tkFile) - { - m_globalTypeBuilder = new TypeBuilder(module); - m_module = module; - m_tkFile = tkFile; + public const string MultiByteValueClass = "$ArrayType$"; - InitNames(strModuleName, strFileName); - } + public readonly TypeBuilder _globalTypeBuilder; + public readonly string _moduleName; + public bool _hasGlobalBeenCreated; - // Initialize module and file names. - private void InitNames(string strModuleName, string strFileName) + internal ModuleBuilderData(ModuleBuilder module, string moduleName) { - m_strModuleName = strModuleName; - if (strFileName == null) - { - // fake a transient module file name - m_strFileName = strModuleName; - } - else - { - string strExtension = Path.GetExtension(strFileName); - if (strExtension == null || strExtension == string.Empty) - { - // This is required by our loader. It cannot load module file that does not have file extension. - throw new ArgumentException(SR.Format(SR.Argument_NoModuleFileExtension, strFileName)); - } - m_strFileName = strFileName; - } + _globalTypeBuilder = new TypeBuilder(module); + _moduleName = moduleName; } - - internal string m_strModuleName; // scope name (can be different from file name) - internal string m_strFileName; - internal bool m_fGlobalBeenCreated; - internal bool m_fHasGlobal; - internal TypeBuilder m_globalTypeBuilder; - internal ModuleBuilder m_module; - - private int m_tkFile; - internal bool m_isSaved; - internal const string MULTI_BYTE_VALUE_CLASS = "$ArrayType$"; - internal string m_strResourceFileName; - internal byte[] m_resourceBytes; } } diff --git a/src/System.Private.CoreLib/src/System/Reflection/Emit/ParameterBuilder.cs b/src/System.Private.CoreLib/src/System/Reflection/Emit/ParameterBuilder.cs index 2b0e18f4f8..d81fe7092c 100644 --- a/src/System.Private.CoreLib/src/System/Reflection/Emit/ParameterBuilder.cs +++ b/src/System.Private.CoreLib/src/System/Reflection/Emit/ParameterBuilder.cs @@ -2,21 +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. -/*============================================================ -** -** -** -** -** -** ParameterBuilder is used to create/associate parameter information -** -** -===========================================================*/ - -using System.Runtime.InteropServices; -using System; -using System.Reflection; - namespace System.Reflection.Emit { public class ParameterBuilder @@ -25,25 +10,28 @@ namespace System.Reflection.Emit public virtual void SetConstant(object defaultValue) { TypeBuilder.SetConstantValue( - m_methodBuilder.GetModuleBuilder(), - m_pdToken.Token, - m_iPosition == 0 ? m_methodBuilder.ReturnType : m_methodBuilder.m_parameterTypes[m_iPosition - 1], + _methodBuilder.GetModuleBuilder(), + _token.Token, + _position == 0 ? _methodBuilder.ReturnType : _methodBuilder.m_parameterTypes[_position - 1], defaultValue); } // Use this function if client decides to form the custom attribute blob themselves - public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { if (con == null) + { throw new ArgumentNullException(nameof(con)); + } if (binaryAttribute == null) + { throw new ArgumentNullException(nameof(binaryAttribute)); + } TypeBuilder.DefineCustomAttribute( - m_methodBuilder.GetModuleBuilder(), - m_pdToken.Token, - ((ModuleBuilder)m_methodBuilder.GetModule()).GetConstructorToken(con).Token, + _methodBuilder.GetModuleBuilder(), + _token.Token, + ((ModuleBuilder)_methodBuilder.GetModule()).GetConstructorToken(con).Token, binaryAttribute, false, false); } @@ -55,65 +43,48 @@ namespace System.Reflection.Emit { throw new ArgumentNullException(nameof(customBuilder)); } - customBuilder.CreateCustomAttribute((ModuleBuilder)(m_methodBuilder.GetModule()), m_pdToken.Token); + customBuilder.CreateCustomAttribute((ModuleBuilder)(_methodBuilder.GetModule()), _token.Token); } internal ParameterBuilder( MethodBuilder methodBuilder, int sequence, ParameterAttributes attributes, - string strParamName) // can be NULL string + string paramName) // can be NULL string { - m_iPosition = sequence; - m_strParamName = strParamName; - m_methodBuilder = methodBuilder; - m_strParamName = strParamName; - m_attributes = attributes; - m_pdToken = new ParameterToken(TypeBuilder.SetParamInfo( - m_methodBuilder.GetModuleBuilder().GetNativeHandle(), - m_methodBuilder.GetToken().Token, + _position = sequence; + _name = paramName; + _methodBuilder = methodBuilder; + _attributes = attributes; + _token = new ParameterToken(TypeBuilder.SetParamInfo( + _methodBuilder.GetModuleBuilder().GetNativeHandle(), + _methodBuilder.GetToken().Token, sequence, attributes, - strParamName)); + paramName)); } public virtual ParameterToken GetToken() { - return m_pdToken; + return _token; } - public virtual string Name - { - get { return m_strParamName; } - } + public virtual string Name => _name; - public virtual int Position - { - get { return m_iPosition; } - } + public virtual int Position => _position; - public virtual int Attributes - { - get { return (int)m_attributes; } - } + public virtual int Attributes => (int)_attributes; - public bool IsIn - { - get { return ((m_attributes & ParameterAttributes.In) != 0); } - } - public bool IsOut - { - get { return ((m_attributes & ParameterAttributes.Out) != 0); } - } - public bool IsOptional - { - get { return ((m_attributes & ParameterAttributes.Optional) != 0); } - } + public bool IsIn => (_attributes & ParameterAttributes.In) != 0; + + public bool IsOut => (_attributes & ParameterAttributes.Out) != 0; + + public bool IsOptional => (_attributes & ParameterAttributes.Optional) != 0; - private string m_strParamName; - private int m_iPosition; - private ParameterAttributes m_attributes; - private MethodBuilder m_methodBuilder; - private ParameterToken m_pdToken; + private readonly string _name; + private readonly int _position; + private readonly ParameterAttributes _attributes; + private MethodBuilder _methodBuilder; + private ParameterToken _token; } } diff --git a/src/System.Private.CoreLib/src/System/Reflection/Emit/ParameterToken.cs b/src/System.Private.CoreLib/src/System/Reflection/Emit/ParameterToken.cs index edb3514609..7eb917ddd6 100644 --- a/src/System.Private.CoreLib/src/System/Reflection/Emit/ParameterToken.cs +++ b/src/System.Private.CoreLib/src/System/Reflection/Emit/ParameterToken.cs @@ -2,66 +2,33 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================ -** -** -** -** -** -** Purpose: metadata tokens for a parameter -** -** -===========================================================*/ - -using System; -using System.Reflection; - namespace System.Reflection.Emit -{ - // The ParameterToken class is an opaque representation of the Token returned - // by the Metadata to represent the parameter. +{ + /// <summary> + /// The ParameterToken class is an opaque representation of the Token returned + /// by the Metadata to represent the parameter. + /// </summary> public struct ParameterToken { public static readonly ParameterToken Empty = new ParameterToken(); - internal int m_tkParameter; + private readonly int _token; - internal ParameterToken(int tkParam) + internal ParameterToken(int parameterToken) { - m_tkParameter = tkParam; + _token = parameterToken; } - public int Token - { - get { return m_tkParameter; } - } + public int Token => _token; - public override int GetHashCode() - { - return m_tkParameter; - } + public override int GetHashCode() => Token; - public override bool Equals(object obj) - { - if (obj is ParameterToken) - return Equals((ParameterToken)obj); - else - return false; - } + public override bool Equals(object obj) => obj is ParameterToken pt && Equals(pt); - public bool Equals(ParameterToken obj) - { - return obj.m_tkParameter == m_tkParameter; - } + public bool Equals(ParameterToken obj) => obj.Token == Token; - public static bool operator ==(ParameterToken a, ParameterToken b) - { - return a.Equals(b); - } + public static bool operator ==(ParameterToken a, ParameterToken b) => a.Equals(b); - public static bool operator !=(ParameterToken a, ParameterToken b) - { - return !(a == b); - } + public static bool operator !=(ParameterToken a, ParameterToken b) => !(a == b); } } diff --git a/src/System.Private.CoreLib/src/System/Reflection/Emit/PropertyToken.cs b/src/System.Private.CoreLib/src/System/Reflection/Emit/PropertyToken.cs index 25b92244cc..fe8d316fd7 100644 --- a/src/System.Private.CoreLib/src/System/Reflection/Emit/PropertyToken.cs +++ b/src/System.Private.CoreLib/src/System/Reflection/Emit/PropertyToken.cs @@ -2,66 +2,29 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================ -** -** -** -** -** -** Propertybuilder is for client to define properties for a class -** -** -===========================================================*/ - -using System; -using System.Reflection; - namespace System.Reflection.Emit { public struct PropertyToken { public static readonly PropertyToken Empty = new PropertyToken(); - internal int m_property; + private readonly int _token; - internal PropertyToken(int str) + internal PropertyToken(int propertyToken) { - m_property = str; + _token = propertyToken; } - public int Token - { - get { return m_property; } - } + public int Token => _token; - // Satisfy value class requirements - public override int GetHashCode() - { - return m_property; - } + public override int GetHashCode() => Token; - // Satisfy value class requirements - public override bool Equals(object obj) - { - if (obj is PropertyToken) - return Equals((PropertyToken)obj); - else - return false; - } + public override bool Equals(object obj) => obj is PropertyToken pt && Equals(pt); - public bool Equals(PropertyToken obj) - { - return obj.m_property == m_property; - } + public bool Equals(PropertyToken obj) => obj.Token == Token; - public static bool operator ==(PropertyToken a, PropertyToken b) - { - return a.Equals(b); - } + public static bool operator ==(PropertyToken a, PropertyToken b) => a.Equals(b); - public static bool operator !=(PropertyToken a, PropertyToken b) - { - return !(a == b); - } + public static bool operator !=(PropertyToken a, PropertyToken b) => !(a == b); } } diff --git a/src/System.Private.CoreLib/src/System/Reflection/Emit/SignatureToken.cs b/src/System.Private.CoreLib/src/System/Reflection/Emit/SignatureToken.cs index 780c61e314..ff61061b80 100644 --- a/src/System.Private.CoreLib/src/System/Reflection/Emit/SignatureToken.cs +++ b/src/System.Private.CoreLib/src/System/Reflection/Emit/SignatureToken.cs @@ -2,67 +2,29 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================ -** -** Signature: SignatureToken -** -** -** -** -** Purpose: Represents a Signature to the ILGenerator signature. -** -** -===========================================================*/ - -using System; -using System.Reflection; - namespace System.Reflection.Emit { public struct SignatureToken { public static readonly SignatureToken Empty = new SignatureToken(); - internal int m_signature; - internal ModuleBuilder m_moduleBuilder; + private int _token; - internal SignatureToken(int str, ModuleBuilder mod) + internal SignatureToken(int signatureToken) { - m_signature = str; - m_moduleBuilder = mod; + _token = signatureToken; } - public int Token - { - get { return m_signature; } - } + public int Token => _token; - public override int GetHashCode() - { - return m_signature; - } + public override int GetHashCode() => Token; - public override bool Equals(object obj) - { - if (obj is SignatureToken) - return Equals((SignatureToken)obj); - else - return false; - } + public override bool Equals(object obj) => obj is SignatureToken st && Equals(st); - public bool Equals(SignatureToken obj) - { - return obj.m_signature == m_signature; - } + public bool Equals(SignatureToken obj) => obj.Token == Token; - public static bool operator ==(SignatureToken a, SignatureToken b) - { - return a.Equals(b); - } + public static bool operator ==(SignatureToken a, SignatureToken b) => a.Equals(b); - public static bool operator !=(SignatureToken a, SignatureToken b) - { - return !(a == b); - } + public static bool operator !=(SignatureToken a, SignatureToken b) => !(a == b); } } diff --git a/src/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.cs b/src/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.cs index 30978730ff..16a64d9252 100644 --- a/src/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.cs +++ b/src/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.cs @@ -507,7 +507,7 @@ namespace System.Reflection.Emit AssemblyBuilder containingAssem = m_module.ContainingAssemblyBuilder; // cannot have two types within the same assembly of the same name - containingAssem.m_assemblyData.CheckTypeNameConflict(fullname, enclosingType); + containingAssem._assemblyData.CheckTypeNameConflict(fullname, enclosingType); if (enclosingType != null) { @@ -602,7 +602,7 @@ namespace System.Reflection.Emit ThrowIfCreated(); // form the value class name - strValueClassName = ModuleBuilderData.MULTI_BYTE_VALUE_CLASS + size.ToString(); + strValueClassName = ModuleBuilderData.MultiByteValueClass + size.ToString(); // Is this already defined in this module? Type temp = m_module.FindTypeBuilderWithName(strValueClassName, false); @@ -2123,7 +2123,7 @@ namespace System.Reflection.Emit exceptions, (exceptions != null) ? exceptions.Length : 0, tokenFixups, (tokenFixups != null) ? tokenFixups.Length : 0); - if (m_module.ContainingAssemblyBuilder.m_assemblyData.m_access == AssemblyBuilderAccess.Run) + if (m_module.ContainingAssemblyBuilder._assemblyData._access == AssemblyBuilderAccess.Run) { // if we don't need the data structures to build the method any more // throw them away. diff --git a/src/System.Private.CoreLib/src/System/Reflection/Emit/TypeToken.cs b/src/System.Private.CoreLib/src/System/Reflection/Emit/TypeToken.cs index 4825a04f24..ecb243273c 100644 --- a/src/System.Private.CoreLib/src/System/Reflection/Emit/TypeToken.cs +++ b/src/System.Private.CoreLib/src/System/Reflection/Emit/TypeToken.cs @@ -2,67 +2,30 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================ -** -** -** -** -** -** Purpose: Represents a Class to the ILGenerator class. -** -** -===========================================================*/ - -using System; -using System.Reflection; -using System.Threading; - namespace System.Reflection.Emit { public struct TypeToken { public static readonly TypeToken Empty = new TypeToken(); - internal int m_class; + private readonly int _token; - - internal TypeToken(int str) + internal TypeToken(int typeToken) { - m_class = str; + _token = typeToken; } - public int Token - { - get { return m_class; } - } + public int Token => _token; - public override int GetHashCode() - { - return m_class; - } + public override int GetHashCode() => Token; - public override bool Equals(object obj) - { - if (obj is TypeToken) - return Equals((TypeToken)obj); - else - return false; - } + public override bool Equals(object obj) => obj is TypeToken tt && Equals(tt); - public bool Equals(TypeToken obj) - { - return obj.m_class == m_class; - } + public bool Equals(TypeToken obj) => obj.Token == Token; - public static bool operator ==(TypeToken a, TypeToken b) - { - return a.Equals(b); - } + public static bool operator ==(TypeToken a, TypeToken b) => a.Equals(b); - public static bool operator !=(TypeToken a, TypeToken b) - { - return !(a == b); - } + public static bool operator !=(TypeToken a, TypeToken b) => !(a == b); } } diff --git a/src/System.Private.CoreLib/src/System/Reflection/RuntimeAssembly.cs b/src/System.Private.CoreLib/src/System/Reflection/RuntimeAssembly.cs index f885c15636..deac03b3b5 100644 --- a/src/System.Private.CoreLib/src/System/Reflection/RuntimeAssembly.cs +++ b/src/System.Private.CoreLib/src/System/Reflection/RuntimeAssembly.cs @@ -67,19 +67,9 @@ namespace System.Reflection return codeBase; } - public override string CodeBase - { - get - { - string codeBase = GetCodeBase(false); - return codeBase; - } - } + public override string CodeBase => GetCodeBase(false); - internal RuntimeAssembly GetNativeHandle() - { - return this; - } + internal RuntimeAssembly GetNativeHandle() => this; // If the assembly is copied before it is loaded, the codebase will be set to the // actual file loaded if copiedName is true. If it is false, then the original code base @@ -101,15 +91,12 @@ namespace System.Reflection GetFlags() | AssemblyNameFlags.PublicKey, null); // strong name key pair - PortableExecutableKinds pek; - ImageFileMachine ifm; - Module manifestModule = ManifestModule; if (manifestModule != null) { if (manifestModule.MDStreamVersion > 0x10000) { - ManifestModule.GetPEKind(out pek, out ifm); + ManifestModule.GetPEKind(out PortableExecutableKinds pek, out ImageFileMachine ifm); an.SetProcArchIndex(pek, ifm); } } diff --git a/src/vm/assembly.cpp b/src/vm/assembly.cpp index 02781aa110..a7315b3b5a 100644 --- a/src/vm/assembly.cpp +++ b/src/vm/assembly.cpp @@ -145,7 +145,7 @@ Assembly::Assembly(BaseDomain *pDomain, PEAssembly* pFile, DebuggerAssemblyContr STANDARD_VM_CONTRACT; } -// This name needs to stay in sync with AssemblyBuilder.MANIFEST_MODULE_NAME +// This name needs to stay in sync with AssemblyBuilder.ManifestModuleName // which is used in AssemblyBuilder.InitManifestModule #define REFEMIT_MANIFEST_MODULE_NAME W("RefEmit_InMemoryManifestModule") |