We need you! We're working hard on the next version of Developer Fusion - Let us know what you think we should be up to!

The Labs \ Source Viewer \ SSCLI \ System.Reflection.Emit \ ModuleBuilder

  1. // ==++==
  2. //
  3. //
  4. // Copyright (c) 2006 Microsoft Corporation. All rights reserved.
  5. //
  6. // The use and distribution terms for this software are contained in the file
  7. // named license.txt, which can be found in the root of this distribution.
  8. // By using this software in any fashion, you are agreeing to be bound by the
  9. // terms of this license.
  10. //
  11. // You must not remove this notice, or any other, from this software.
  12. //
  13. //
  14. // ==--==
  15. namespace System.Reflection.Emit
  16. {
  17.     using System.Runtime.InteropServices;
  18.     using System;
  19.     using IList = System.Collections.IList;
  20.     using ArrayList = System.Collections.ArrayList;
  21.     using CultureInfo = System.Globalization.CultureInfo;
  22.     using ResourceWriter = System.Resources.ResourceWriter;
  23.     using IResourceWriter = System.Resources.IResourceWriter;
  24.     using System.Diagnostics.SymbolStore;
  25.     using System.Reflection;
  26.     using System.Diagnostics;
  27.     using System.IO;
  28.     using System.Security;
  29.     using System.Security.Permissions;
  30.     using System.Runtime.Serialization;
  31.     using System.Text;
  32.     using System.Threading;
  33.     using System.Runtime.Versioning;
  34.    
  35.     // deliberately not [serializable]
  36.     [HostProtection(MayLeakOnAbort = true)]
  37.     [ClassInterface(ClassInterfaceType.None)]
  38.     [ComDefaultInterface(typeof(_ModuleBuilder))]
  39.     [System.Runtime.InteropServices.ComVisible(true)]
  40.     public class ModuleBuilder : Module, _ModuleBuilder
  41.     {
  42.         #region Internal Static Members
  43.         static internal string UnmangleTypeName(string typeName)
  44.         {
  45.             // Gets the original type name, without '+' name mangling.
  46.            
  47.             int i = typeName.Length - 1;
  48.             while (true) {
  49.                 i = typeName.LastIndexOf('+', i);
  50.                 if (i == -1)
  51.                     break;
  52.                
  53.                 bool evenSlashes = true;
  54.                 int iSlash = i;
  55.                 while (typeName[--iSlash] == '\\')
  56.                     evenSlashes = !evenSlashes;
  57.                
  58.                 // Even number of slashes means this '+' is a name separator
  59.                 if (evenSlashes)
  60.                     break;
  61.                
  62.                 i = iSlash;
  63.             }
  64.            
  65.             return typeName.Substring(i + 1);
  66.         }
  67.        
  68.         #endregion
  69.        
  70.         #region Private Data Members
  71.         // WARNING!! WARNING!!
  72.         // ModuleBuilder should not contain any data members as its reflectbase is the same as Module.
  73.         #endregion
  74.        
  75.         #region Constructor
  76.         private ModuleBuilder()
  77.         {
  78.         }
  79.        
  80.         #endregion
  81.        
  82.         #region Private Members
  83.         private Type GetType(string strFormat, Type baseType)
  84.         {
  85.             // This function takes a string to describe the compound type, such as "[,][]", and a baseType.
  86.            
  87.             if (strFormat == null || strFormat.Equals(String.Empty)) {
  88.                 return baseType;
  89.             }
  90.            
  91.             // convert the format string to byte array and then call FormCompoundType
  92.             char[] bFormat = strFormat.ToCharArray();
  93.             return SymbolType.FormCompoundType(bFormat, baseType, 0);
  94.            
  95.         }
  96.        
  97.        
  98.         internal void CheckContext(params Type[][] typess)
  99.         {
  100.             ((AssemblyBuilder)Assembly).CheckContext(typess);
  101.         }
  102.         internal void CheckContext(params Type[] types)
  103.         {
  104.             ((AssemblyBuilder)Assembly).CheckContext(types);
  105.         }
  106.         #endregion
  107.        
  108.         #region Internal Members
  109.         internal virtual Type FindTypeBuilderWithName(string strTypeName, bool ignoreCase)
  110.         {
  111.             int size = m_TypeBuilderList.Count;
  112.             int i;
  113.             Type typeTemp = null;
  114.            
  115.             for (i = 0; i < size; i++) {
  116.                 typeTemp = (Type)m_TypeBuilderList[i];
  117.                 if (ignoreCase == true) {
  118.                     if (String.Compare(typeTemp.FullName, strTypeName, ((ignoreCase) ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) == 0)
  119.                         break;
  120.                 }
  121.                 else {
  122.                     if (typeTemp.FullName.Equals(strTypeName))
  123.                         break;
  124.                 }
  125.             }
  126.             if (i == size)
  127.                 typeTemp = null;
  128.            
  129.             return typeTemp;
  130.         }
  131.        
  132.         internal Type GetRootElementType(Type type)
  133.         {
  134.             // This function will walk compound type to the inner most BaseType. Such as returning int for "ptr[] int".
  135.             if (type.IsByRef == false && type.IsPointer == false && type.IsArray == false)
  136.                 return type;
  137.            
  138.             return GetRootElementType(type.GetElementType());
  139.         }
  140.        
  141.         internal void SetEntryPoint(MethodInfo entryPoint)
  142.         {
  143.             // Sets the entry point of the module to be a given method. If no entry point
  144.             // is specified, calling EmitPEFile will generate a dll.
  145.             CodeAccessPermission.DemandInternal(PermissionType.ReflectionEmit);
  146.             m_EntryPoint = GetMethodToken(entryPoint);
  147.         }
  148.        
  149.        
  150.         internal void PreSave(string fileName, PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
  151.         {
  152.             if (Assembly.m_assemblyData.m_isSynchronized) {
  153.                 lock (Assembly.m_assemblyData) {
  154.                     PreSaveNoLock(fileName, portableExecutableKind, imageFileMachine);
  155.                 }
  156.             }
  157.             else {
  158.                 PreSaveNoLock(fileName, portableExecutableKind, imageFileMachine);
  159.             }
  160.         }
  161.        
  162.         private void PreSaveNoLock(string fileName, PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
  163.         {
  164.             // This is a helper called by AssemblyBuilder save to presave information for the persistable modules.
  165.             object item;
  166.             TypeBuilder typeBuilder;
  167.             if (m_moduleData.m_isSaved == true) {
  168.                 // can only save once
  169.                 throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, Environment.GetResourceString("InvalidOperation_ModuleHasBeenSaved"), m_moduleData.m_strModuleName));
  170.             }
  171.            
  172.             if (m_moduleData.m_fGlobalBeenCreated == false && m_moduleData.m_fHasGlobal == true)
  173.                 throw new NotSupportedException(Environment.GetResourceString("NotSupported_GlobalFunctionNotBaked"));
  174.            
  175.             int size = m_TypeBuilderList.Count;
  176.             for (int i = 0; i < size; i++) {
  177.                 item = m_TypeBuilderList[i];
  178.                 if (item is TypeBuilder) {
  179.                     typeBuilder = (TypeBuilder)item;
  180.                 }
  181.                 else {
  182.                     EnumBuilder enumBuilder = (EnumBuilder)item;
  183.                     typeBuilder = enumBuilder.m_typeBuilder;
  184.                 }
  185.                 if (typeBuilder.m_hasBeenCreated == false && typeBuilder.m_isHiddenType == false) {
  186.                     // cannot save to PE file without creating all of the types first
  187.                     throw new NotSupportedException(String.Format(CultureInfo.InvariantCulture, Environment.GetResourceString("NotSupported_NotAllTypesAreBaked"), typeBuilder.FullName));
  188.                 }
  189.             }
  190.            
  191.             InternalPreSavePEFile((int)portableExecutableKind, (int)imageFileMachine);
  192.         }
  193.        
  194.         internal void Save(string fileName, bool isAssemblyFile, PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
  195.         {
  196.             if (Assembly.m_assemblyData.m_isSynchronized) {
  197.                 lock (Assembly.m_assemblyData) {
  198.                     SaveNoLock(fileName, isAssemblyFile, portableExecutableKind, imageFileMachine);
  199.                 }
  200.             }
  201.             else {
  202.                 SaveNoLock(fileName, isAssemblyFile, portableExecutableKind, imageFileMachine);
  203.             }
  204.         }
  205.        
  206.         private void SaveNoLock(string fileName, bool isAssemblyFile, PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
  207.         {
  208.             // This is a helper called by AssemblyBuilder save to save information for the persistable modules.
  209.             if (m_moduleData.m_embeddedRes != null) {
  210.                 // There are embedded resources for this module
  211.                 ResWriterData resWriter;
  212.                 int iCount;
  213.                
  214.                 // Set the number of resources embedded in this PE
  215.                 for (resWriter = m_moduleData.m_embeddedRes,iCount = 0; resWriter != null; resWriter = resWriter.m_nextResWriter,iCount++)
  216.                     ;
  217.                 InternalSetResourceCounts(iCount);
  218.                
  219.                 // Add each resource content into the to be saved PE file
  220.                 for (resWriter = m_moduleData.m_embeddedRes; resWriter != null; resWriter = resWriter.m_nextResWriter) {
  221.                     if (resWriter.m_resWriter != null)
  222.                         resWriter.m_resWriter.Generate();
  223.                    
  224.                     byte[] resBytes = new byte[resWriter.m_memoryStream.Length];
  225.                     resWriter.m_memoryStream.Flush();
  226.                     resWriter.m_memoryStream.Position = 0;
  227.                     resWriter.m_memoryStream.Read(resBytes, 0, resBytes.Length);
  228.                     InternalAddResource(resWriter.m_strName, resBytes, resBytes.Length, m_moduleData.m_tkFile, (int)resWriter.m_attribute, (int)portableExecutableKind, (int)imageFileMachine);
  229.                 }
  230.             }
  231.            
  232.            
  233.             if (isAssemblyFile)
  234.                 InternalSavePEFile(fileName, m_EntryPoint, (int)Assembly.m_assemblyData.m_peFileKind, true);
  235.             else
  236.                 InternalSavePEFile(fileName, m_EntryPoint, (int)PEFileKinds.Dll, false);
  237.             m_moduleData.m_isSaved = true;
  238.         }
  239.        
  240.         internal int GetTypeRefNested(Type type, Module refedModule, string strRefedModuleFileName)
  241.         {
  242.             // This function will generate correct TypeRef token for top level type and nested type.
  243.            
  244.             Type enclosingType = type.DeclaringType;
  245.             int tkResolution = 0;
  246.             string typeName = type.FullName;
  247.            
  248.             if (enclosingType != null) {
  249.                 tkResolution = GetTypeRefNested(enclosingType, refedModule, strRefedModuleFileName);
  250.                 typeName = UnmangleTypeName(typeName);
  251.             }
  252.            
  253.             return InternalGetTypeToken(typeName, refedModule, strRefedModuleFileName, tkResolution);
  254.         }
  255.        
  256.         internal MethodToken InternalGetConstructorToken(ConstructorInfo con, bool usingRef)
  257.         {
  258.             // Helper to get constructor token. If usingRef is true, we will never use the def token
  259.            
  260.            
  261.             int tr;
  262.             int mr = 0;
  263.            
  264.             if (con == null)
  265.                 throw new ArgumentNullException("con");
  266.            
  267.             if (con is ConstructorBuilder) {
  268.                 ConstructorBuilder conBuilder = con as ConstructorBuilder;
  269.                 if (usingRef == false && conBuilder.ReflectedType.Module.Equals(this))
  270.                     return conBuilder.GetToken();
  271.                
  272.                 // constructor is defined in a different module
  273.                 tr = GetTypeToken(con.ReflectedType).Token;
  274.                 mr = InternalGetMemberRef(con.ReflectedType.Module, tr, conBuilder.GetToken().Token);
  275.             }
  276.             else if (con is ConstructorOnTypeBuilderInstantiation) {
  277.                 ConstructorOnTypeBuilderInstantiation conBuilder = con as ConstructorOnTypeBuilderInstantiation;
  278.                 if (usingRef == true)
  279.                     throw new InvalidOperationException();
  280.                
  281.                 tr = GetTypeToken(con.DeclaringType).Token;
  282.                 mr = InternalGetMemberRef(con.DeclaringType.Module, tr, conBuilder.m_ctor.MetadataTokenInternal);
  283.             }
  284.             else if (con is RuntimeConstructorInfo && con.ReflectedType.IsArray == false) {
  285.                 // constructor is not a dynamic field
  286.                 // We need to get the TypeRef tokens
  287.                
  288.                 tr = GetTypeToken(con.ReflectedType).Token;
  289.                 mr = InternalGetMemberRefOfMethodInfo(tr, con.GetMethodHandle());
  290.             }
  291.             else {
  292.                 // some user derived ConstructorInfo
  293.                 // go through the slower code path, i.e. retrieve parameters and form signature helper.
  294.                 ParameterInfo[] parameters = con.GetParameters();
  295.                 Type[] parameterTypes = new Type[parameters.Length];
  296.                 Type[][] requiredCustomModifiers = new Type[parameterTypes.Length][];
  297.                 Type[][] optionalCustomModifiers = new Type[parameterTypes.Length][];
  298.                
  299.                 for (int i = 0; i < parameters.Length; i++) {
  300.                     parameterTypes[i] = parameters[i].ParameterType;
  301.                     requiredCustomModifiers[i] = parameters[i].GetRequiredCustomModifiers();
  302.                     optionalCustomModifiers[i] = parameters[i].GetOptionalCustomModifiers();
  303.                 }
  304.                
  305.                 tr = GetTypeToken(con.ReflectedType).Token;
  306.                
  307.                 SignatureHelper sigHelp = SignatureHelper.GetMethodSigHelper(this, con.CallingConvention, null, null, null, parameterTypes, requiredCustomModifiers, optionalCustomModifiers);
  308.                 int length;
  309.                 byte[] sigBytes = sigHelp.InternalGetSignature(out length);
  310.                
  311.                 mr = InternalGetMemberRefFromSignature(tr, con.Name, sigBytes, length);
  312.             }
  313.            
  314.             return new MethodToken(mr);
  315.         }
  316.        
  317.         internal void Init(string strModuleName, string strFileName, ISymbolWriter writer)
  318.         {
  319.             m_moduleData = new ModuleBuilderData(this, strModuleName, strFileName);
  320.             m_TypeBuilderList = new ArrayList();
  321.             m_iSymWriter = writer;
  322.            
  323.             if (writer != null) {
  324.                 // Set the underlying writer for the managed writer
  325.                 // that we're using. Note that this function requires
  326.                 // unmanaged code access.
  327.                 new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert();
  328.                 writer.SetUnderlyingWriter(m_pInternalSymWriter);
  329.             }
  330.         }
  331.        
  332.         [ResourceExposure(ResourceScope.Machine)]
  333.         [ResourceConsumption(ResourceScope.Machine)]
  334.         internal void DefineUnmanagedResourceFileInternal(string resourceFileName)
  335.         {
  336.             // Shouldn't have resource bytes, but a previous file is OK, because assemblyBuilder.Save
  337.             // creates then deletes a temp file.
  338.             if (m_moduleData.m_resourceBytes != null)
  339.                 throw new ArgumentException(Environment.GetResourceString("Argument_NativeResourceAlreadyDefined"));
  340.            
  341.             if (resourceFileName == null)
  342.                 throw new ArgumentNullException("resourceFileName");
  343.            
  344.             if (m_moduleData.m_fHasExplicitUnmanagedResource)
  345.                 throw new ArgumentException(Environment.GetResourceString("Argument_NativeResourceAlreadyDefined"));
  346.            
  347.             CodeAccessPermission.DemandInternal(PermissionType.ReflectionEmit);
  348.            
  349.             // Check caller has the right to read the file.
  350.             string strFullFileName;
  351.             strFullFileName = Path.GetFullPath(resourceFileName);
  352.             new FileIOPermission(FileIOPermissionAccess.Read, strFullFileName).Demand();
  353.            
  354.             new EnvironmentPermission(PermissionState.Unrestricted).Assert();
  355.             try {
  356.                 if (File.Exists(resourceFileName) == false)
  357.                     throw new FileNotFoundException(String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("IO.FileNotFound_FileName"), resourceFileName), resourceFileName);
  358.             }
  359.             finally {
  360.                 CodeAccessPermission.RevertAssert();
  361.             }
  362.            
  363.             m_moduleData.m_strResourceFileName = strFullFileName;
  364.         }
  365.        
  366.         #endregion
  367.        
  368.         #region Module Overrides
  369.         public override Type[] GetTypes()
  370.         {
  371.             int size = m_TypeBuilderList.Count;
  372.             Type[] moduleTypes = new Type[size];
  373.             TypeBuilder tmpTypeBldr;
  374.             int filtered = 0;
  375.            
  376.             for (int i = 0; i < size; i++) {
  377.                 EnumBuilder enumBldr = m_TypeBuilderList[i] as EnumBuilder;
  378.                 tmpTypeBldr = m_TypeBuilderList[i] as TypeBuilder;
  379.                 if (enumBldr != null)
  380.                     tmpTypeBldr = enumBldr.m_typeBuilder;
  381.                
  382.                 if (tmpTypeBldr != null) {
  383.                     if (tmpTypeBldr.m_hasBeenCreated)
  384.                         moduleTypes[i] = tmpTypeBldr.UnderlyingSystemType;
  385.                     else
  386.                         moduleTypes[i] = tmpTypeBldr;
  387.                 }
  388.                 else {
  389.                     // RuntimeType case: This will happen in TlbImp.
  390.                     moduleTypes[i] = (Type)m_TypeBuilderList[i];
  391.                 }
  392.             }
  393.            
  394.             if (filtered > 0) {
  395.                 Type[] filteredTypes = new Type[size - filtered];
  396.                 int src;
  397.                 int dst;
  398.                 for (src = 0,dst = 0; src < size; src++) {
  399.                     if (moduleTypes[src] != null) {
  400.                         filteredTypes[dst] = moduleTypes[src];
  401.                         dst++;
  402.                     }
  403.                 }
  404.                 moduleTypes = filteredTypes;
  405.             }
  406.            
  407.             return moduleTypes;
  408.         }
  409.        
  410.         [System.Runtime.InteropServices.ComVisible(true)]
  411.         public override Type GetType(string className)
  412.         {
  413.             return GetType(className, false, false);
  414.         }
  415.        
  416.         [System.Runtime.InteropServices.ComVisible(true)]
  417.         public override Type GetType(string className, bool ignoreCase)
  418.         {
  419.             return GetType(className, false, ignoreCase);
  420.         }
  421.        
  422.         [System.Runtime.InteropServices.ComVisible(true)]
  423.         public override Type GetType(string className, bool throwOnError, bool ignoreCase)
  424.         {
  425.             if (Assembly.m_assemblyData.m_isSynchronized) {
  426.                 lock (Assembly.m_assemblyData) {
  427.                     return GetTypeNoLock(className, throwOnError, ignoreCase);
  428.                 }
  429.             }
  430.             else {
  431.                 return GetTypeNoLock(className, throwOnError, ignoreCase);
  432.             }
  433.         }
  434.        
  435.         private Type GetTypeNoLock(string className, bool throwOnError, bool ignoreCase)
  436.         {
  437.             // public API to to a type. The reason that we need this function override from module
  438.             // is because clients might need to get foo[] when foo is being built. For example, if
  439.             // foo class contains a data member of type foo[].
  440.             // This API first delegate to the Module.GetType implementation. If succeeded, great!
  441.             // If not, we have to look up the current module to find the TypeBuilder to represent the base
  442.             // type and form the Type object for "foo[,]".
  443.            
  444.             // Module.GetType() will verify className.
  445.             Type baseType = base.GetType(className, throwOnError, ignoreCase);
  446.             if (baseType != null)
  447.                 return baseType;
  448.            
  449.             // Now try to see if we contain a TypeBuilder for this type or not.
  450.             // Might have a compound type name, indicated via an unescaped
  451.             // '[', '*' or '&'. Split the name at this point.
  452.             string baseName = null;
  453.             string parameters = null;
  454.             int startIndex = 0;
  455.            
  456.             while (startIndex <= className.Length) {
  457.                 // Are there any possible special characters left?
  458.                 int i = className.IndexOfAny(new char[] {'[', '*', '&'}, startIndex);
  459.                 if (i == -1) {
  460.                     // No, type name is simple.
  461.                     baseName = className;
  462.                     parameters = null;
  463.                     break;
  464.                 }
  465.                
  466.                 // Found a potential special character, but it might be escaped.
  467.                 int slashes = 0;
  468.                 for (int j = i - 1; j >= 0 && className[j] == '\\'; j--)
  469.                     slashes++;
  470.                
  471.                 // Odd number of slashes indicates escaping.
  472.                 if (slashes % 2 == 1) {
  473.                     startIndex = i + 1;
  474.                     continue;
  475.                 }
  476.                
  477.                 // Found the end of the base type name.
  478.                 baseName = className.Substring(0, i);
  479.                 parameters = className.Substring(i);
  480.                 break;
  481.             }
  482.            
  483.             // If we didn't find a basename yet, the entire class name is
  484.             // the base name and we don't have a composite type.
  485.             if (baseName == null) {
  486.                 baseName = className;
  487.                 parameters = null;
  488.             }
  489.            
  490.             baseName = baseName.Replace("\\\\", "\\").Replace("\\[", "[").Replace("\\*", "*").Replace("\\&", "&");
  491.            
  492.             if (parameters != null) {
  493.                 // try to see if reflection can find the base type. It can be such that reflection
  494.                 // does not support the complex format string yet!
  495.                
  496.                 baseType = base.GetType(baseName, false, ignoreCase);
  497.             }
  498.            
  499.             if (baseType == null) {
  500.                 // try to find it among the unbaked types.
  501.                 // starting with the current module first of all.
  502.                 baseType = FindTypeBuilderWithName(baseName, ignoreCase);
  503.                 if (baseType == null && Assembly is AssemblyBuilder) {
  504.                     // now goto Assembly level to find the type.
  505.                     int size;
  506.                     ArrayList modList;
  507.                    
  508.                     modList = Assembly.m_assemblyData.m_moduleBuilderList;
  509.                     size = modList.Count;
  510.                     for (int i = 0; i < size && baseType == null; i++) {
  511.                         ModuleBuilder mBuilder = (ModuleBuilder)modList[i];
  512.                         baseType = mBuilder.FindTypeBuilderWithName(baseName, ignoreCase);
  513.                     }
  514.                 }
  515.                 if (baseType == null)
  516.                     return null;
  517.             }
  518.            
  519.             if (parameters == null)
  520.                 return baseType;
  521.            
  522.             return GetType(parameters, baseType);
  523.         }
  524.        
  525.         public override string FullyQualifiedName {
  526.             [ResourceExposure(ResourceScope.Machine)]
  527.             [ResourceConsumption(ResourceScope.Machine)]
  528.             get {
  529.                 string fullyQualifiedName = m_moduleData.m_strFileName;
  530.                 if (fullyQualifiedName == null)
  531.                     return null;
  532.                 if (Assembly.m_assemblyData.m_strDir != null) {
  533.                     fullyQualifiedName = Path.Combine(Assembly.m_assemblyData.m_strDir, fullyQualifiedName);
  534.                     fullyQualifiedName = Path.GetFullPath(fullyQualifiedName);
  535.                 }
  536.                
  537.                 if (Assembly.m_assemblyData.m_strDir != null && fullyQualifiedName != null) {
  538.                     new FileIOPermission(FileIOPermissionAccess.PathDiscovery, fullyQualifiedName).Demand();
  539.                 }
  540.                
  541.                 return fullyQualifiedName;
  542.             }
  543.         }
  544.        
  545.         #endregion
  546.        
  547.         #region Public Members
  548.        
  549.         #region Define Type
  550.         public TypeBuilder DefineType(string name)
  551.         {
  552.             CodeAccessPermission.DemandInternal(PermissionType.ReflectionEmit);
  553.             if (Assembly.m_assemblyData.m_isSynchronized) {
  554.                 lock (Assembly.m_assemblyData) {
  555.                     return DefineTypeNoLock(name);
  556.                 }
  557.             }
  558.             else {
  559.                 return DefineTypeNoLock(name);
  560.             }
  561.         }
  562.        
  563.         private TypeBuilder DefineTypeNoLock(string name)
  564.         {
  565.             TypeBuilder typeBuilder;
  566.             typeBuilder = new TypeBuilder(name, TypeAttributes.NotPublic, null, null, this, PackingSize.Unspecified, null);
  567.             m_TypeBuilderList.Add(typeBuilder);
  568.             return typeBuilder;
  569.         }
  570.        
  571.         public TypeBuilder DefineType(string name, TypeAttributes attr)
  572.         {
  573.             CodeAccessPermission.DemandInternal(PermissionType.ReflectionEmit);
  574.             if (Assembly.m_assemblyData.m_isSynchronized) {
  575.                 lock (Assembly.m_assemblyData) {
  576.                     return DefineTypeNoLock(name, attr);
  577.                 }
  578.             }
  579.             else {
  580.                 return DefineTypeNoLock(name, attr);
  581.             }
  582.         }
  583.        
  584.         private TypeBuilder DefineTypeNoLock(string name, TypeAttributes attr)
  585.         {
  586.             TypeBuilder typeBuilder;
  587.             typeBuilder = new TypeBuilder(name, attr, null, null, this, PackingSize.Unspecified, null);
  588.             m_TypeBuilderList.Add(typeBuilder);
  589.             return typeBuilder;
  590.         }
  591.        
  592.         public TypeBuilder DefineType(string name, TypeAttributes attr, Type parent)
  593.         {
  594.             CodeAccessPermission.DemandInternal(PermissionType.ReflectionEmit);
  595.             if (Assembly.m_assemblyData.m_isSynchronized) {
  596.                 lock (Assembly.m_assemblyData) {
  597.                     return DefineTypeNoLock(name, attr, parent);
  598.                 }
  599.             }
  600.             else {
  601.                 return DefineTypeNoLock(name, attr, parent);
  602.             }
  603.         }
  604.        
  605.         private TypeBuilder DefineTypeNoLock(string name, TypeAttributes attr, Type parent)
  606.         {
  607.             CheckContext(parent);
  608.            
  609.             TypeBuilder typeBuilder;
  610.            
  611.             typeBuilder = new TypeBuilder(name, attr, parent, null, this, PackingSize.Unspecified, null);
  612.             m_TypeBuilderList.Add(typeBuilder);
  613.             return typeBuilder;
  614.         }
  615.        
  616.         public TypeBuilder DefineType(string name, TypeAttributes attr, Type parent, int typesize)
  617.         {
  618.             CodeAccessPermission.DemandInternal(PermissionType.ReflectionEmit);
  619.             if (Assembly.m_assemblyData.m_isSynchronized) {
  620.                 lock (Assembly.m_assemblyData) {
  621.                     return DefineTypeNoLock(name, attr, parent, typesize);
  622.                 }
  623.             }
  624.             else {
  625.             &