Updates referencesource to .NET 4.7
[mono.git] / mcs / class / referencesource / mscorlib / system / reflection / emit / modulebuilder.cs
1 // ==++==
2 // 
3 //   Copyright (c) Microsoft Corporation.  All rights reserved.
4 // 
5 // ==--==
6 // <OWNER>Microsoft</OWNER>
7 // 
8
9 namespace System.Reflection.Emit 
10 {
11     using System.Runtime.InteropServices;
12     using System;
13     using System.Collections.Generic;
14     using System.Diagnostics.SymbolStore;
15     using System.Globalization;
16     using System.Reflection;
17     using System.Diagnostics;
18     using System.IO;
19     using System.Resources;
20     using System.Security;
21     using System.Security.Permissions;
22     using System.Runtime.Serialization;
23     using System.Text;
24     using System.Threading;
25     using System.Runtime.Versioning;
26     using System.Runtime.CompilerServices;
27     using System.Diagnostics.Contracts;
28
29     internal sealed class InternalModuleBuilder : RuntimeModule
30     {
31         #region Private Data Members
32         // WARNING!! WARNING!!
33         // InternalModuleBuilder should not contain any data members as its reflectbase is the same as Module.
34         #endregion
35
36         private InternalModuleBuilder() { }
37
38         #region object overrides
39         public override bool Equals(object obj)
40         {
41             if (obj == null)
42                 return false;
43
44             if (obj is InternalModuleBuilder)
45                 return ((object)this == obj);
46
47             return obj.Equals(this);
48         }
49         // Need a dummy GetHashCode to pair with Equals
50         public override int GetHashCode() { return base.GetHashCode(); }
51         #endregion
52     }
53
54     // deliberately not [serializable]
55     [HostProtection(MayLeakOnAbort = true)]
56     [ClassInterface(ClassInterfaceType.None)]
57     [ComDefaultInterface(typeof(_ModuleBuilder))]
58     [System.Runtime.InteropServices.ComVisible(true)]
59     public class ModuleBuilder : Module, _ModuleBuilder
60     {
61         #region FCalls
62
63         [ResourceExposure(ResourceScope.Machine)]
64         [MethodImplAttribute(MethodImplOptions.InternalCall)]
65         internal static extern IntPtr nCreateISymWriterForDynamicModule(Module module, String filename);
66
67         #endregion
68
69         #region Internal Static Members
70         static internal String UnmangleTypeName(String typeName)
71         {
72             // Gets the original type name, without '+' name mangling.
73
74             int i = typeName.Length - 1;
75             while (true)
76             {
77                 i = typeName.LastIndexOf('+', i);
78                 if (i == -1)
79                     break;
80
81                 bool evenSlashes = true;
82                 int iSlash = i;
83                 while (typeName[--iSlash] == '\\')
84                     evenSlashes = !evenSlashes;
85
86                 // Even number of slashes means this '+' is a name separator
87                 if (evenSlashes)
88                     break;
89
90                 i = iSlash;
91             }
92
93             return typeName.Substring(i + 1);
94         }
95
96         #endregion
97
98         #region Intenral Data Members
99         // m_TypeBuilder contains both TypeBuilder and EnumBuilder objects
100         private Dictionary<string, Type> m_TypeBuilderDict;
101         private ISymbolWriter m_iSymWriter;
102         internal ModuleBuilderData m_moduleData;
103 #if !FEATURE_CORECLR
104         private MethodToken m_EntryPoint;
105 #endif //!FEATURE_CORECLR
106         internal InternalModuleBuilder m_internalModuleBuilder;
107         // This is the "external" AssemblyBuilder
108         // only the "external" ModuleBuilder has this set
109         private AssemblyBuilder m_assemblyBuilder;
110         internal AssemblyBuilder ContainingAssemblyBuilder { get { return m_assemblyBuilder; } }
111         #endregion
112
113         #region Constructor
114         internal ModuleBuilder(AssemblyBuilder assemblyBuilder, InternalModuleBuilder internalModuleBuilder)
115         {
116             m_internalModuleBuilder = internalModuleBuilder;
117             m_assemblyBuilder = assemblyBuilder;
118         }
119         #endregion
120
121         #region Private Members
122         internal void AddType(string name, Type type)
123         {
124             m_TypeBuilderDict.Add(name, type);
125         }
126
127         internal void CheckTypeNameConflict(String strTypeName, Type enclosingType)
128         {
129             Type foundType = null;
130             if (m_TypeBuilderDict.TryGetValue(strTypeName, out foundType) &&
131                 object.ReferenceEquals(foundType.DeclaringType, enclosingType))
132             {
133                 // Cannot have two types with the same name
134                 throw new ArgumentException(Environment.GetResourceString("Argument_DuplicateTypeName"));
135             }
136         }
137
138         private Type GetType(String strFormat, Type baseType)
139         {
140             // This function takes a string to describe the compound type, such as "[,][]", and a baseType.
141
142             if (strFormat == null || strFormat.Equals(String.Empty))
143             {
144                 return baseType;
145             }
146
147             // convert the format string to byte array and then call FormCompoundType
148             char[]      bFormat = strFormat.ToCharArray();
149             return SymbolType.FormCompoundType(bFormat, baseType, 0);
150
151         }
152         
153         
154         internal void CheckContext(params Type[][] typess)
155         {
156             ContainingAssemblyBuilder.CheckContext(typess);
157         }
158         internal void CheckContext(params Type[] types)
159         {
160             ContainingAssemblyBuilder.CheckContext(types);
161         }
162
163
164         [System.Security.SecurityCritical]  // auto-generated
165         [ResourceExposure(ResourceScope.Machine)]
166         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
167         [SuppressUnmanagedCodeSecurity]
168         private extern static int GetTypeRef(RuntimeModule module, String strFullName, RuntimeModule refedModule, String strRefedModuleFileName, int tkResolution);
169
170         [System.Security.SecurityCritical]  // auto-generated
171         [ResourceExposure(ResourceScope.None)]
172         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
173         [SuppressUnmanagedCodeSecurity]
174         private extern static int GetMemberRef(RuntimeModule module, RuntimeModule refedModule, int tr, int defToken);
175
176         [System.Security.SecurityCritical]  // auto-generated
177         private int GetMemberRef(Module refedModule, int tr, int defToken)
178         {
179             return GetMemberRef(GetNativeHandle(), GetRuntimeModuleFromModule(refedModule).GetNativeHandle(), tr, defToken);
180         }
181
182         [System.Security.SecurityCritical]  // auto-generated
183         [ResourceExposure(ResourceScope.None)]
184         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
185         [SuppressUnmanagedCodeSecurity]
186         private extern static int GetMemberRefFromSignature(RuntimeModule module, int tr, String methodName, byte[] signature, int length);
187
188         [System.Security.SecurityCritical]  // auto-generated
189         private int GetMemberRefFromSignature(int tr, String methodName, byte[] signature, int length)
190         {
191             return GetMemberRefFromSignature(GetNativeHandle(), tr, methodName, signature, length);
192         }
193
194         [System.Security.SecurityCritical]  // auto-generated
195         [ResourceExposure(ResourceScope.None)]
196         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
197         [SuppressUnmanagedCodeSecurity]
198         private extern static int GetMemberRefOfMethodInfo(RuntimeModule module, int tr, IRuntimeMethodInfo method);
199
200         [System.Security.SecurityCritical]  // auto-generated
201         private int GetMemberRefOfMethodInfo(int tr, RuntimeMethodInfo method)
202         {
203             Contract.Assert(method != null);
204
205 #if FEATURE_APPX
206             if (ContainingAssemblyBuilder.ProfileAPICheck)
207             {
208                 if ((method.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
209                     throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", method.FullName));
210             }
211 #endif
212
213             return GetMemberRefOfMethodInfo(GetNativeHandle(), tr, method);
214         }
215
216         [System.Security.SecurityCritical]  // auto-generated
217         private int GetMemberRefOfMethodInfo(int tr, RuntimeConstructorInfo method)
218         {
219             Contract.Assert(method != null);
220
221 #if FEATURE_APPX
222             if (ContainingAssemblyBuilder.ProfileAPICheck)
223             {
224                 if ((method.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
225                     throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", method.FullName));
226             }
227 #endif
228
229             return GetMemberRefOfMethodInfo(GetNativeHandle(), tr, method);
230         }
231
232         [System.Security.SecurityCritical]  // auto-generated
233         [ResourceExposure(ResourceScope.None)]
234         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
235         [SuppressUnmanagedCodeSecurity]
236         private extern static int GetMemberRefOfFieldInfo(RuntimeModule module, int tkType, RuntimeTypeHandle declaringType, int tkField);
237
238         [System.Security.SecurityCritical]  // auto-generated
239         private int GetMemberRefOfFieldInfo(int tkType, RuntimeTypeHandle declaringType, RuntimeFieldInfo runtimeField)
240         {
241             Contract.Assert(runtimeField != null);
242
243 #if FEATURE_APPX
244             if (ContainingAssemblyBuilder.ProfileAPICheck)
245             {
246                 RtFieldInfo rtField = runtimeField as RtFieldInfo;
247                 if (rtField != null && (rtField.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
248                 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtField.FullName));
249             }
250 #endif
251
252             return GetMemberRefOfFieldInfo(GetNativeHandle(), tkType, declaringType, runtimeField.MetadataToken);
253         }
254
255         [System.Security.SecurityCritical]  // auto-generated
256         [ResourceExposure(ResourceScope.None)]
257         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
258         [SuppressUnmanagedCodeSecurity]
259         private extern static int GetTokenFromTypeSpec(RuntimeModule pModule, byte[] signature, int length);
260
261         [System.Security.SecurityCritical]  // auto-generated
262         private int GetTokenFromTypeSpec(byte[] signature, int length)
263         {
264             return GetTokenFromTypeSpec(GetNativeHandle(), signature, length);
265         }
266
267         [System.Security.SecurityCritical]  // auto-generated
268         [ResourceExposure(ResourceScope.None)]
269         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
270         [SuppressUnmanagedCodeSecurity]
271         private extern static int GetArrayMethodToken(RuntimeModule module, int tkTypeSpec, String methodName, byte[] signature, int sigLength);
272
273         [System.Security.SecurityCritical]  // auto-generated
274         [ResourceExposure(ResourceScope.None)]
275         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
276         [SuppressUnmanagedCodeSecurity]
277         private extern static int GetStringConstant(RuntimeModule module, String str, int length);
278
279         [System.Security.SecurityCritical]  // auto-generated
280         [ResourceExposure(ResourceScope.None)]
281         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
282         [SuppressUnmanagedCodeSecurity]
283         private extern static void PreSavePEFile(RuntimeModule module, int portableExecutableKind, int imageFileMachine);
284
285         [System.Security.SecurityCritical]  // auto-generated
286         [ResourceExposure(ResourceScope.Machine)]
287         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
288         [SuppressUnmanagedCodeSecurity]
289         private extern static void SavePEFile(RuntimeModule module, String fileName, int entryPoint, int isExe, bool isManifestFile);
290
291         [System.Security.SecurityCritical]  // auto-generated
292         [ResourceExposure(ResourceScope.None)]
293         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
294         [SuppressUnmanagedCodeSecurity]
295         private extern static void AddResource(
296             RuntimeModule module, String strName, 
297             byte[] resBytes, int resByteCount, int tkFile, int attribute,
298             int portableExecutableKind, int imageFileMachine);
299
300         [System.Security.SecurityCritical]  // auto-generated
301         [ResourceExposure(ResourceScope.Machine)]
302         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
303         [SuppressUnmanagedCodeSecurity]
304         private extern static void SetModuleName(RuntimeModule module, String strModuleName);
305
306         [System.Security.SecurityCritical]  // auto-generated
307         [ResourceExposure(ResourceScope.None)]
308         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
309         [SuppressUnmanagedCodeSecurity]
310         internal extern static void SetFieldRVAContent(RuntimeModule module, int fdToken, byte[] data, int length);
311
312 #if !FEATURE_PAL
313         [System.Security.SecurityCritical]  // auto-generated
314         [ResourceExposure(ResourceScope.Machine)]
315         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
316         [SuppressUnmanagedCodeSecurity]
317         private extern static void DefineNativeResourceFile(RuntimeModule module, 
318                                                             String strFilename, 
319                                                             int portableExecutableKind, 
320                                                             int ImageFileMachine);
321
322         [System.Security.SecurityCritical]  // auto-generated
323         [ResourceExposure(ResourceScope.None)]
324         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
325         [SuppressUnmanagedCodeSecurity]
326         private extern static void DefineNativeResourceBytes(RuntimeModule module,
327                                                              byte[] pbResource, int cbResource, 
328                                                              int portableExecutableKind, 
329                                                              int imageFileMachine);
330 #endif
331
332         [System.Security.SecurityCritical]  // auto-generated
333         internal void DefineNativeResource(PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
334         {
335 #if !FEATURE_PAL
336             string strResourceFileName = m_moduleData.m_strResourceFileName;
337             byte[] resourceBytes = m_moduleData.m_resourceBytes;
338
339             if (strResourceFileName != null)
340             {
341                 DefineNativeResourceFile(GetNativeHandle(),
342                     strResourceFileName,
343                     (int)portableExecutableKind, (int)imageFileMachine);
344             }
345             else
346             if (resourceBytes != null)
347             {
348                 DefineNativeResourceBytes(GetNativeHandle(),
349                     resourceBytes, resourceBytes.Length,
350                     (int)portableExecutableKind, (int)imageFileMachine);
351             }
352 #endif // !FEATURE_PAL
353         }
354
355         #endregion
356
357         #region Internal Members
358         internal virtual Type FindTypeBuilderWithName(String strTypeName, bool ignoreCase)
359         {
360             if (ignoreCase)
361             {
362                 foreach (string name in m_TypeBuilderDict.Keys)
363                 {
364                     if (String.Compare(name, strTypeName, (StringComparison.OrdinalIgnoreCase)) == 0)
365                         return m_TypeBuilderDict[name];
366                 }
367             }
368             else
369             {
370                 Type foundType;
371                 if (m_TypeBuilderDict.TryGetValue(strTypeName, out foundType))
372                     return foundType;
373             }
374
375             return null;
376         }
377         
378 #if !FEATURE_CORECLR
379         internal void SetEntryPoint(MethodToken entryPoint)
380         {           
381             // Sets the entry point of the module to be a given method.  If no entry point
382             // is specified, calling EmitPEFile will generate a dll.
383             // AssemblyBuilder.SetEntryPoint has already demanded required permission
384             m_EntryPoint = entryPoint;
385         }
386 #endif //!FEATURE_CORECLR
387
388
389 #if !FEATURE_CORECLR
390         // This is a helper called by AssemblyBuilder save to presave information for the persistable modules.
391         // no need to lock here because we have already taken the lock in AssemblyBuilder.Save
392         [System.Security.SecurityCritical]  // auto-generated
393         [ResourceExposure(ResourceScope.Machine)]
394         [ResourceConsumption(ResourceScope.Machine)]
395         internal void PreSave(String fileName,
396             PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
397         {
398             if (m_moduleData.m_isSaved == true)
399             {
400                 // can only save once
401                 throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture,
402                     Environment.GetResourceString("InvalidOperation_ModuleHasBeenSaved"),
403                     m_moduleData.m_strModuleName));
404             }
405         
406             if (m_moduleData.m_fGlobalBeenCreated == false && m_moduleData.m_fHasGlobal == true)
407                 throw new NotSupportedException(Environment.GetResourceString("NotSupported_GlobalFunctionNotBaked")); 
408
409             TypeBuilder typeBuilder;
410             foreach (Type item in m_TypeBuilderDict.Values)
411             {
412                 if (item is TypeBuilder)
413                 {
414                     typeBuilder = (TypeBuilder)item;
415                 }
416                 else
417                 {
418                     EnumBuilder enumBuilder = (EnumBuilder)item;
419                     typeBuilder = enumBuilder.m_typeBuilder;
420                 }
421
422                 if (!typeBuilder.IsCreated())
423                 {
424                     // cannot save to PE file without creating all of the types first 
425                     throw new NotSupportedException(String.Format(CultureInfo.InvariantCulture,
426                         Environment.GetResourceString("NotSupported_NotAllTypesAreBaked"), 
427                         typeBuilder.FullName)); 
428                 }
429             }
430
431             PreSavePEFile(GetNativeHandle(), (int)portableExecutableKind, (int)imageFileMachine);
432         }
433
434         // no need to lock here because we have already taken the lock in AssemblyBuilder.Save
435         [System.Security.SecurityCritical]  // auto-generated
436         [ResourceExposure(ResourceScope.Machine)]
437         [ResourceConsumption(ResourceScope.Machine)]
438         internal void Save(String fileName, bool isAssemblyFile, PortableExecutableKinds portableExecutableKind, 
439             ImageFileMachine imageFileMachine)
440         {
441             // This is a helper called by AssemblyBuilder save to save information for the persistable modules.
442             if (m_moduleData.m_embeddedRes != null)
443             {
444                 // There are embedded resources for this module
445                 ResWriterData   resWriter;
446
447                 // Add each resource content into the to be saved PE file
448                 for (resWriter = m_moduleData.m_embeddedRes; resWriter != null; resWriter = resWriter.m_nextResWriter)
449                 {
450                     if (resWriter.m_resWriter != null)
451                         resWriter.m_resWriter.Generate();                    
452                     
453                     byte[] resBytes = new byte[resWriter.m_memoryStream.Length];
454                     resWriter.m_memoryStream.Flush();
455                     resWriter.m_memoryStream.Position = 0;
456                     resWriter.m_memoryStream.Read(resBytes, 0, resBytes.Length);
457
458                     AddResource(GetNativeHandle(),
459                                 resWriter.m_strName, 
460                                 resBytes,
461                                 resBytes.Length,
462                                 m_moduleData.FileToken,
463                                 (int)resWriter.m_attribute, 
464                                 (int)portableExecutableKind,
465                                 (int)imageFileMachine);
466                 }
467             }
468
469             DefineNativeResource(portableExecutableKind, imageFileMachine);
470
471             PEFileKinds pekind = isAssemblyFile ? ContainingAssemblyBuilder.m_assemblyData.m_peFileKind : PEFileKinds.Dll;
472
473             SavePEFile(GetNativeHandle(), fileName, m_EntryPoint.Token, (int)pekind, isAssemblyFile); 
474
475             m_moduleData.m_isSaved = true;
476         }
477 #endif // !FEATURE_CORECLR
478
479         [System.Security.SecurityCritical]  // auto-generated
480         [ResourceExposure(ResourceScope.Machine)]
481         [ResourceConsumption(ResourceScope.Machine)]
482         private int GetTypeRefNested(Type type, Module refedModule, String strRefedModuleFileName)
483         {
484             // This function will generate correct TypeRef token for top level type and nested type.
485
486             Type enclosingType = type.DeclaringType;
487             int tkResolution = 0;
488             String typeName = type.FullName;
489
490             if (enclosingType != null)
491             {
492                 tkResolution = GetTypeRefNested(enclosingType, refedModule, strRefedModuleFileName);
493                 typeName = UnmangleTypeName(typeName);
494             }
495
496             Contract.Assert(!type.IsByRef, "Must not be ByRef.");
497             Contract.Assert(!type.IsGenericType || type.IsGenericTypeDefinition, "Must not have generic arguments.");
498
499 #if FEATURE_APPX
500             if (ContainingAssemblyBuilder.ProfileAPICheck)
501             {
502                 RuntimeType rtType = type as RuntimeType;
503                 if (rtType != null && (rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
504                 {
505                     throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtType.FullName));
506                 }
507             }
508 #endif
509
510             return GetTypeRef(GetNativeHandle(), typeName, GetRuntimeModuleFromModule(refedModule).GetNativeHandle(), strRefedModuleFileName, tkResolution);
511         }
512
513         [System.Security.SecurityCritical]  // auto-generated
514         internal MethodToken InternalGetConstructorToken(ConstructorInfo con, bool usingRef)
515         {
516             // Helper to get constructor token. If usingRef is true, we will never use the def token
517
518             if (con == null)
519                 throw new ArgumentNullException("con");
520             Contract.EndContractBlock();
521
522             int tr;
523             int mr = 0;
524
525             ConstructorBuilder conBuilder = null;
526             ConstructorOnTypeBuilderInstantiation conOnTypeBuilderInst = null;
527             RuntimeConstructorInfo rtCon = null;
528
529             if ( (conBuilder = con as ConstructorBuilder) != null )
530             {
531                 if (usingRef == false && conBuilder.Module.Equals(this))
532                     return conBuilder.GetToken();
533
534                 // constructor is defined in a different module
535                 tr = GetTypeTokenInternal(con.ReflectedType).Token;
536                 mr = GetMemberRef(con.ReflectedType.Module, tr, conBuilder.GetToken().Token);
537             }
538             else if ( (conOnTypeBuilderInst = con as ConstructorOnTypeBuilderInstantiation) != null )
539             {
540                 if (usingRef == true) throw new InvalidOperationException();
541
542                 tr = GetTypeTokenInternal(con.DeclaringType).Token;
543                 mr = GetMemberRef(con.DeclaringType.Module, tr, conOnTypeBuilderInst.MetadataTokenInternal);
544             }
545             else if ( (rtCon = con as RuntimeConstructorInfo) != null && con.ReflectedType.IsArray == false)
546             {
547                 // constructor is not a dynamic field
548                 // We need to get the TypeRef tokens
549
550                 tr = GetTypeTokenInternal(con.ReflectedType).Token;
551                 mr = GetMemberRefOfMethodInfo(tr, rtCon);
552             }
553             else
554             {
555                 // some user derived ConstructorInfo
556                 // go through the slower code path, i.e. retrieve parameters and form signature helper.
557                 ParameterInfo[] parameters = con.GetParameters();
558                 if (parameters == null)
559                     throw new ArgumentException(Environment.GetResourceString("Argument_InvalidConstructorInfo"));
560
561                 int count = parameters.Length;
562                 Type[] parameterTypes = new Type[count];
563                 Type[][] requiredCustomModifiers = new Type[count][];
564                 Type[][] optionalCustomModifiers = new Type[count][];
565
566                 for (int i = 0; i < count; i++)
567                 {
568                     if (parameters[i] == null)
569                         throw new ArgumentException(Environment.GetResourceString("Argument_InvalidConstructorInfo"));
570
571                     parameterTypes[i] = parameters[i].ParameterType;
572                     requiredCustomModifiers[i] = parameters[i].GetRequiredCustomModifiers();
573                     optionalCustomModifiers[i] = parameters[i].GetOptionalCustomModifiers();
574                 }
575
576                 tr = GetTypeTokenInternal(con.ReflectedType).Token;
577
578                 SignatureHelper sigHelp = SignatureHelper.GetMethodSigHelper(this, con.CallingConvention, null, null, null, parameterTypes, requiredCustomModifiers, optionalCustomModifiers);
579                 int length;
580                 byte[] sigBytes = sigHelp.InternalGetSignature(out length);
581
582                 mr = GetMemberRefFromSignature(tr, con.Name, sigBytes, length);
583             }
584             
585             return new MethodToken( mr );
586         }
587
588         [System.Security.SecurityCritical]  // auto-generated
589         [ResourceExposure(ResourceScope.Machine)]
590         [ResourceConsumption(ResourceScope.Machine)]
591         internal void Init(String strModuleName, String strFileName, int tkFile)
592         {
593             m_moduleData = new ModuleBuilderData(this, strModuleName, strFileName, tkFile);
594             m_TypeBuilderDict = new Dictionary<string, Type>();
595         }
596
597         // This is a method for changing module and file name of the manifest module (created by default for 
598         // each assembly).
599         [System.Security.SecurityCritical]  // auto-generated
600         [ResourceExposure(ResourceScope.Machine)]
601         [ResourceConsumption(ResourceScope.Machine)]
602         internal void ModifyModuleName(string name)
603         {
604             // Reset the names in the managed ModuleBuilderData
605             m_moduleData.ModifyModuleName(name);
606
607             // Reset the name in the underlying metadata
608             ModuleBuilder.SetModuleName(GetNativeHandle(), name);
609         }
610
611         internal void SetSymWriter(ISymbolWriter writer)
612         {
613             m_iSymWriter = writer;
614         }
615
616         internal object SyncRoot
617         {
618             get
619             {
620                 return ContainingAssemblyBuilder.SyncRoot;
621             }
622         }
623
624         #endregion
625             
626         #region Module Overrides
627             
628         // m_internalModuleBuilder is null iff this is a "internal" ModuleBuilder
629         internal InternalModuleBuilder InternalModule
630         {
631             get
632             {
633                 return m_internalModuleBuilder;
634             }
635         }
636
637         internal override ModuleHandle GetModuleHandle()
638         {
639             return new ModuleHandle(GetNativeHandle());
640         }
641
642         internal RuntimeModule GetNativeHandle()
643         {
644             return InternalModule.GetNativeHandle();
645         }
646
647         private static RuntimeModule GetRuntimeModuleFromModule(Module m)
648         {
649             ModuleBuilder mb = m as ModuleBuilder;
650             if (mb != null)
651             {
652                 return mb.InternalModule;
653             }
654
655             return m as RuntimeModule;
656         }
657
658         [System.Security.SecurityCritical]  // auto-generated
659         private int GetMemberRefToken(MethodBase method, IEnumerable<Type> optionalParameterTypes)
660         {
661             Type[] parameterTypes;
662             Type returnType;
663             int tkParent;
664             int cGenericParameters = 0;
665
666             if (method.IsGenericMethod)
667             {
668                 if (!method.IsGenericMethodDefinition)
669                     throw new InvalidOperationException();
670
671                 cGenericParameters = method.GetGenericArguments().Length;
672             }
673
674             if (optionalParameterTypes != null)
675             {
676                 if ((method.CallingConvention & CallingConventions.VarArgs) == 0)
677                 {
678                     // Client should not supply optional parameter in default calling convention
679                     throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAVarArgCallingConvention"));
680                 }
681             }
682
683             MethodInfo masmi = method as MethodInfo;
684
685             if (method.DeclaringType.IsGenericType)
686             {
687                 MethodBase methDef = null; // methodInfo = G<Foo>.M<Bar> ==> methDef = G<T>.M<S>
688
689                 MethodOnTypeBuilderInstantiation motbi;
690                 ConstructorOnTypeBuilderInstantiation cotbi;
691
692                 if ((motbi = method as MethodOnTypeBuilderInstantiation) != null)
693                 {
694                     methDef = motbi.m_method;
695                 }
696                 else if ((cotbi = method as ConstructorOnTypeBuilderInstantiation) != null)
697                 {
698                     methDef = cotbi.m_ctor;
699                 }
700                 else if (method is MethodBuilder || method is ConstructorBuilder)
701                 {
702                     // methodInfo must be GenericMethodDefinition; trying to emit G<?>.M<S>
703                     methDef = method;
704                 }
705                 else
706                 {
707                     Contract.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo);
708
709                     if (method.IsGenericMethod)
710                     {
711                         Contract.Assert(masmi != null);
712
713                         methDef = masmi.GetGenericMethodDefinition();
714                         methDef = methDef.Module.ResolveMethod(
715                             method.MetadataToken,
716                             methDef.DeclaringType != null ? methDef.DeclaringType.GetGenericArguments() : null,
717                             methDef.GetGenericArguments());
718                     }
719                     else
720                     {
721                         methDef = method.Module.ResolveMethod(
722                             method.MetadataToken,
723                             method.DeclaringType != null ? method.DeclaringType.GetGenericArguments() : null,
724                             null);
725                     }
726                 }
727
728                 parameterTypes = methDef.GetParameterTypes();
729                 returnType = MethodBuilder.GetMethodBaseReturnType(methDef);
730             }
731             else
732             {
733                 parameterTypes = method.GetParameterTypes();
734                 returnType = MethodBuilder.GetMethodBaseReturnType(method);
735             }
736
737             int sigLength;
738             byte[] sigBytes = GetMemberRefSignature(method.CallingConvention, returnType, parameterTypes,
739                 optionalParameterTypes, cGenericParameters).InternalGetSignature(out sigLength);
740
741             if (method.DeclaringType.IsGenericType)
742             {
743                 int length;
744                 byte[] sig = SignatureHelper.GetTypeSigToken(this, method.DeclaringType).InternalGetSignature(out length);
745                 tkParent = GetTokenFromTypeSpec(sig, length);
746             }
747             else if (!method.Module.Equals(this))
748             {
749                 // Use typeRef as parent because the method's declaringType lives in a different assembly                
750                 tkParent = GetTypeToken(method.DeclaringType).Token;
751             }
752             else
753             {
754                 // Use methodDef as parent because the method lives in this assembly and its declaringType has no generic arguments
755                 if (masmi != null)
756                     tkParent = GetMethodToken(masmi).Token;
757                 else
758                     tkParent = GetConstructorToken(method as ConstructorInfo).Token;
759             }
760
761             return GetMemberRefFromSignature(tkParent, method.Name, sigBytes, sigLength);
762         }
763
764         [System.Security.SecurityCritical]  // auto-generated
765         internal SignatureHelper GetMemberRefSignature(CallingConventions call, Type returnType,
766             Type[] parameterTypes, IEnumerable<Type> optionalParameterTypes, int cGenericParameters) 
767         {
768             int cParams = (parameterTypes == null) ? 0 : parameterTypes.Length;
769             SignatureHelper sig = SignatureHelper.GetMethodSigHelper(this, call, returnType, cGenericParameters);
770
771             for (int i = 0; i < cParams; i++)
772             {
773                 sig.AddArgument(parameterTypes[i]);
774             }
775
776             if (optionalParameterTypes != null) {
777                 int i = 0;
778                 foreach (Type type in optionalParameterTypes)
779                 {
780                     // add the sentinel
781                     if (i == 0)
782                     {
783                         sig.AddSentinel();
784                     }
785
786                     sig.AddArgument(type);
787                     i++;
788                 }
789             }
790
791             return sig;
792         }
793
794         #endregion
795
796         #region object overrides
797         public override bool Equals(object obj)
798         {
799             return InternalModule.Equals(obj);
800         }
801         // Need a dummy GetHashCode to pair with Equals
802         public override int GetHashCode() { return InternalModule.GetHashCode(); }
803         #endregion
804
805         #region ICustomAttributeProvider Members
806         public override Object[] GetCustomAttributes(bool inherit)
807         {
808             return InternalModule.GetCustomAttributes(inherit);
809         }
810
811         public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
812         {
813             return InternalModule.GetCustomAttributes(attributeType, inherit);
814         }
815
816         public override bool IsDefined(Type attributeType, bool inherit)
817         {
818             return InternalModule.IsDefined(attributeType, inherit);
819         }
820
821         public override IList<CustomAttributeData> GetCustomAttributesData()
822         {
823             return InternalModule.GetCustomAttributesData();
824         }
825         #endregion
826
827         #region Module Overrides
828
829         public override Type[] GetTypes()
830         {
831             lock(SyncRoot)
832             {
833                 return GetTypesNoLock();
834             }
835         }
836
837         internal Type[] GetTypesNoLock()
838         {
839             int size = m_TypeBuilderDict.Count;
840             Type[] typeList = new Type[m_TypeBuilderDict.Count];
841             int i = 0;
842
843             foreach (Type builder in m_TypeBuilderDict.Values)
844             {
845                 EnumBuilder enumBldr = builder as EnumBuilder;
846                 TypeBuilder tmpTypeBldr;
847
848                 if (enumBldr != null)
849                     tmpTypeBldr = enumBldr.m_typeBuilder;
850                 else
851                     tmpTypeBldr = (TypeBuilder)builder;
852                     
853                 // We should not return TypeBuilders.
854                 // Otherwise anyone can emit code in it.
855                 if (tmpTypeBldr.IsCreated())
856                     typeList[i++] = tmpTypeBldr.UnderlyingSystemType;
857                 else
858                     typeList[i++] = builder;
859             }
860
861             return typeList;
862         }
863
864         [System.Runtime.InteropServices.ComVisible(true)]
865         public override Type GetType(String className)
866         {
867             return GetType(className, false, false);
868         }
869         
870         [System.Runtime.InteropServices.ComVisible(true)]
871         public override Type GetType(String className, bool ignoreCase)
872         {
873             return GetType(className, false, ignoreCase);
874         }
875         
876         [System.Runtime.InteropServices.ComVisible(true)]
877         public override Type GetType(String className, bool throwOnError, bool ignoreCase)
878         {
879             lock(SyncRoot)
880             {
881                 return GetTypeNoLock(className, throwOnError, ignoreCase);
882             }
883         }
884
885         private Type GetTypeNoLock(String className, bool throwOnError, bool ignoreCase)
886         {
887             // public API to to a type. The reason that we need this function override from module
888             // is because clients might need to get foo[] when foo is being built. For example, if 
889             // foo class contains a data member of type foo[].
890             // This API first delegate to the Module.GetType implementation. If succeeded, great! 
891             // If not, we have to look up the current module to find the TypeBuilder to represent the base
892             // type and form the Type object for "foo[,]".
893                 
894             // Module.GetType() will verify className.                
895             Type baseType = InternalModule.GetType(className, throwOnError, ignoreCase);
896             if (baseType != null)
897                 return baseType;
898
899             // Now try to see if we contain a TypeBuilder for this type or not.
900             // Might have a compound type name, indicated via an unescaped
901             // '[', '*' or '&'. Split the name at this point.
902             String baseName = null;
903             String parameters = null;
904             int startIndex = 0;
905
906             while (startIndex <= className.Length)
907             {
908                 // Are there any possible special characters left?
909                 int i = className.IndexOfAny(new char[]{'[', '*', '&'}, startIndex);
910                 if (i == -1)
911                 {
912                     // No, type name is simple.
913                     baseName = className;
914                     parameters = null;
915                     break;
916                 }
917
918                 // Found a potential special character, but it might be escaped.
919                 int slashes = 0;
920                 for (int j = i - 1; j >= 0 && className[j] == '\\'; j--)
921                     slashes++;
922
923                 // Odd number of slashes indicates escaping.
924                 if (slashes % 2 == 1)
925                 {
926                     startIndex = i + 1;
927                     continue;
928                 }
929
930                 // Found the end of the base type name.
931                 baseName = className.Substring(0, i);
932                 parameters = className.Substring(i);
933                 break;
934             }
935
936             // If we didn't find a basename yet, the entire class name is
937             // the base name and we don't have a composite type.
938             if (baseName == null)
939             {
940                 baseName = className;
941                 parameters = null;
942             }
943
944             baseName = baseName.Replace(@"\\",@"\").Replace(@"\[",@"[").Replace(@"\*",@"*").Replace(@"\&",@"&");
945
946             if (parameters != null)
947             {
948                 // try to see if reflection can find the base type. It can be such that reflection
949                 // does not support the complex format string yet!
950
951                 baseType = InternalModule.GetType(baseName, false, ignoreCase);
952             }
953
954             if (baseType == null)
955             {
956                 // try to find it among the unbaked types.
957                 // starting with the current module first of all.
958                 baseType = FindTypeBuilderWithName(baseName, ignoreCase);
959                 if (baseType == null && Assembly is AssemblyBuilder)
960                 {
961                     // now goto Assembly level to find the type.
962                     int size;
963                     List<ModuleBuilder> modList;
964
965                     modList = ContainingAssemblyBuilder.m_assemblyData.m_moduleBuilderList;
966                     size = modList.Count;
967                     for (int i = 0; i < size && baseType == null; i++)
968                     {
969                         ModuleBuilder mBuilder = modList[i];
970                         baseType = mBuilder.FindTypeBuilderWithName(baseName, ignoreCase);
971                     }
972                 }
973                 if (baseType == null)
974                     return null;
975             }
976
977             if (parameters == null)         
978                 return baseType;
979         
980             return GetType(parameters, baseType);
981         }
982
983         public override String FullyQualifiedName
984         {
985 #if FEATURE_CORECLR
986             [System.Security.SecurityCritical] // auto-generated
987 #else
988             [System.Security.SecuritySafeCritical]
989 #endif
990             [ResourceExposure(ResourceScope.Machine)]
991             [ResourceConsumption(ResourceScope.Machine)]
992             get
993             {
994                 String fullyQualifiedName = m_moduleData.m_strFileName;
995                 if (fullyQualifiedName == null)
996                     return null;
997                 if (ContainingAssemblyBuilder.m_assemblyData.m_strDir != null)
998                 {
999                     fullyQualifiedName = Path.Combine(ContainingAssemblyBuilder.m_assemblyData.m_strDir, fullyQualifiedName);
1000                     fullyQualifiedName = Path.UnsafeGetFullPath(fullyQualifiedName);
1001                 }
1002                 
1003                 if (ContainingAssemblyBuilder.m_assemblyData.m_strDir != null && fullyQualifiedName != null) 
1004                 {
1005                     new FileIOPermission( FileIOPermissionAccess.PathDiscovery, fullyQualifiedName ).Demand();
1006                 }
1007
1008                 return fullyQualifiedName;
1009             }
1010         }
1011
1012         public override byte[] ResolveSignature(int metadataToken)
1013         {
1014             return InternalModule.ResolveSignature(metadataToken);
1015         }
1016
1017         public override MethodBase ResolveMethod(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
1018         {
1019             return InternalModule.ResolveMethod(metadataToken, genericTypeArguments, genericMethodArguments);
1020         }
1021
1022         public override FieldInfo ResolveField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
1023         {
1024             return InternalModule.ResolveField(metadataToken, genericTypeArguments, genericMethodArguments);
1025         }
1026
1027         public override Type ResolveType(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
1028         {
1029             return InternalModule.ResolveType(metadataToken, genericTypeArguments, genericMethodArguments);
1030         }
1031
1032         public override MemberInfo ResolveMember(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
1033         {
1034             return InternalModule.ResolveMember(metadataToken, genericTypeArguments, genericMethodArguments);
1035         }
1036
1037         public override string ResolveString(int metadataToken)
1038         {
1039             return InternalModule.ResolveString(metadataToken);
1040         }
1041
1042         public override void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine)
1043         {
1044             InternalModule.GetPEKind(out peKind, out machine);
1045         }
1046
1047         public override int MDStreamVersion
1048         {
1049             get
1050             {
1051                 return InternalModule.MDStreamVersion;
1052             }
1053         }
1054
1055         public override Guid ModuleVersionId
1056         {
1057             get
1058             {
1059                 return InternalModule.ModuleVersionId;
1060             }
1061         }
1062
1063         public override int MetadataToken
1064         {
1065             get
1066             {
1067                 return InternalModule.MetadataToken;
1068             }
1069         }
1070
1071         public override bool IsResource()
1072         {
1073             return InternalModule.IsResource();
1074         }
1075
1076         public override FieldInfo[] GetFields(BindingFlags bindingFlags)
1077         {
1078             return InternalModule.GetFields(bindingFlags);
1079         }
1080
1081         public override FieldInfo GetField(String name, BindingFlags bindingAttr)
1082         {
1083             return InternalModule.GetField(name, bindingAttr);
1084         }
1085
1086         public override MethodInfo[] GetMethods(BindingFlags bindingFlags)
1087         {
1088             return InternalModule.GetMethods(bindingFlags);
1089         }
1090
1091         protected override MethodInfo GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder,
1092             CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
1093         {
1094             // Cannot call InternalModule.GetMethods because it doesn't allow types to be null
1095             return InternalModule.GetMethodInternal(name, bindingAttr, binder, callConvention, types, modifiers);
1096         }
1097
1098         public override String ScopeName
1099         {
1100             get
1101             {
1102                 return InternalModule.ScopeName;
1103             }
1104         }
1105
1106         [ResourceExposure(ResourceScope.None)]
1107         [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
1108         public override String Name
1109         {
1110             get
1111             {
1112                 return InternalModule.Name;
1113             }
1114         }
1115
1116         public override Assembly Assembly
1117         {
1118             [Pure]
1119             get
1120             {
1121                 return m_assemblyBuilder;
1122             }
1123         }
1124
1125 #if FEATURE_X509 && FEATURE_CAS_POLICY
1126         public override System.Security.Cryptography.X509Certificates.X509Certificate GetSignerCertificate()
1127         {
1128             return InternalModule.GetSignerCertificate();
1129         }
1130 #endif // FEATURE_X509 && FEATURE_CAS_POLICY
1131         #endregion
1132
1133         #region Public Members
1134
1135         #region Define Type
1136         [System.Security.SecuritySafeCritical]  // auto-generated
1137         public TypeBuilder DefineType(String name)
1138         {
1139             Contract.Ensures(Contract.Result<TypeBuilder>() != null);
1140
1141             lock(SyncRoot)
1142             {
1143                 return DefineTypeNoLock(name, TypeAttributes.NotPublic, null, null, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
1144             }
1145         }
1146
1147         [System.Security.SecuritySafeCritical]  // auto-generated
1148         public TypeBuilder DefineType(String name, TypeAttributes attr)
1149         {
1150             Contract.Ensures(Contract.Result<TypeBuilder>() != null);
1151
1152             lock(SyncRoot)
1153             {
1154                 return DefineTypeNoLock(name, attr, null, null, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
1155             }
1156         }
1157
1158         [System.Security.SecuritySafeCritical]  // auto-generated
1159         public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent)
1160         {
1161             Contract.Ensures(Contract.Result<TypeBuilder>() != null);
1162
1163             lock(SyncRoot)
1164             {
1165                 // Why do we only call CheckContext here? Why don't we call it in the other overloads?
1166                 CheckContext(parent);
1167
1168                 return DefineTypeNoLock(name, attr, parent, null, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
1169             }
1170         }
1171
1172 #if FEATURE_CORECLR
1173         [System.Security.SecurityCritical] // auto-generated
1174 #else
1175         [System.Security.SecuritySafeCritical]
1176 #endif
1177         public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent, int typesize)
1178         {
1179             Contract.Ensures(Contract.Result<TypeBuilder>() != null);
1180
1181             lock(SyncRoot)
1182             {
1183                 return DefineTypeNoLock(name, attr, parent, null, PackingSize.Unspecified, typesize);
1184             }
1185         }
1186
1187 #if FEATURE_CORECLR
1188         [System.Security.SecurityCritical] // auto-generated
1189 #else
1190         [System.Security.SecuritySafeCritical]
1191 #endif
1192         public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent, PackingSize packingSize, int typesize)
1193         {
1194             Contract.Ensures(Contract.Result<TypeBuilder>() != null);
1195
1196             lock (SyncRoot)
1197             {
1198                 return DefineTypeNoLock(name, attr, parent, null, packingSize, typesize);
1199             }
1200         }
1201
1202         [System.Security.SecuritySafeCritical]  // auto-generated
1203         [System.Runtime.InteropServices.ComVisible(true)]
1204         public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent, Type[] interfaces)
1205         {
1206             Contract.Ensures(Contract.Result<TypeBuilder>() != null);
1207
1208             lock(SyncRoot)
1209             {
1210                 return DefineTypeNoLock(name, attr, parent, interfaces, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
1211             }
1212         }
1213
1214         [System.Security.SecurityCritical]  // auto-generated
1215         private TypeBuilder DefineTypeNoLock(String name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packingSize, int typesize)
1216         {
1217             Contract.Ensures(Contract.Result<TypeBuilder>() != null);
1218
1219             return new TypeBuilder(name, attr, parent, interfaces, this, packingSize, typesize, null); ;
1220         }
1221
1222 #if FEATURE_CORECLR
1223         [System.Security.SecurityCritical] // auto-generated
1224 #else
1225         [System.Security.SecuritySafeCritical]
1226 #endif
1227         public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent, PackingSize packsize)
1228         {
1229             Contract.Ensures(Contract.Result<TypeBuilder>() != null);
1230
1231             lock(SyncRoot)
1232             {
1233                 return DefineTypeNoLock(name, attr, parent, packsize);
1234             }
1235         }
1236
1237         [System.Security.SecurityCritical]  // auto-generated
1238         private TypeBuilder DefineTypeNoLock(String name, TypeAttributes attr, Type parent, PackingSize packsize)
1239         {
1240             Contract.Ensures(Contract.Result<TypeBuilder>() != null);
1241
1242             return new TypeBuilder(name, attr, parent, null, this, packsize, TypeBuilder.UnspecifiedTypeSize, null);
1243         }
1244
1245         #endregion
1246
1247         #region Define Enum
1248
1249         // This API can only be used to construct a top-level (not nested) enum type.
1250         // Nested enum types can be defined manually using ModuleBuilder.DefineType.
1251         [System.Security.SecuritySafeCritical]  // auto-generated
1252         public EnumBuilder DefineEnum(String name, TypeAttributes visibility, Type underlyingType)
1253         {
1254             Contract.Ensures(Contract.Result<EnumBuilder>() != null);
1255
1256             CheckContext(underlyingType);
1257             lock(SyncRoot)
1258             {
1259                 EnumBuilder enumBuilder = DefineEnumNoLock(name, visibility, underlyingType);
1260
1261                 // This enum is not generic, nested, and cannot have any element type.
1262                 Contract.Assert(name == enumBuilder.FullName);
1263
1264                 // Replace the TypeBuilder object in m_TypeBuilderDict with this EnumBuilder object.
1265                 Contract.Assert(enumBuilder.m_typeBuilder == m_TypeBuilderDict[name]);
1266                 m_TypeBuilderDict[name] = enumBuilder;
1267
1268                 return enumBuilder;
1269             }
1270         }
1271
1272         [System.Security.SecurityCritical]  // auto-generated
1273         private EnumBuilder DefineEnumNoLock(String name, TypeAttributes visibility, Type underlyingType)
1274         {
1275             Contract.Ensures(Contract.Result<EnumBuilder>() != null);
1276
1277             return new EnumBuilder(name, underlyingType, visibility, this);
1278         }
1279     
1280         #endregion
1281
1282         #region Define Resource
1283 #if !FEATURE_CORECLR
1284         public IResourceWriter DefineResource(String name, String description)
1285         {
1286             // Define embedded managed resource to be stored in this module
1287             Contract.Ensures(Contract.Result<IResourceWriter>() != null);
1288              
1289             return DefineResource(name, description, ResourceAttributes.Public);
1290         }
1291
1292         public IResourceWriter DefineResource(String name, String description, ResourceAttributes attribute)
1293         {
1294             // Define embedded managed resource to be stored in this module
1295             Contract.Ensures(Contract.Result<IResourceWriter>() != null);
1296
1297             lock(SyncRoot)
1298             {
1299                 return DefineResourceNoLock(name, description, attribute);
1300             }
1301         }
1302
1303         private IResourceWriter DefineResourceNoLock(String name, String description, ResourceAttributes attribute)
1304         {
1305             // Define embedded managed resource to be stored in this module
1306
1307             if (IsTransient())
1308                 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadResourceContainer"));
1309
1310             if (name == null)
1311                 throw new ArgumentNullException("name");
1312             if (name.Length == 0)
1313                 throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name");
1314             Contract.Ensures(Contract.Result<IResourceWriter>() != null);
1315             Contract.EndContractBlock();
1316
1317             if (m_assemblyBuilder.IsPersistable())
1318             {
1319                 m_assemblyBuilder.m_assemblyData.CheckResNameConflict(name);
1320
1321                     MemoryStream stream = new MemoryStream();
1322                     ResourceWriter resWriter = new ResourceWriter(stream);
1323                     ResWriterData resWriterData = new ResWriterData( resWriter, stream, name, String.Empty, String.Empty, attribute);
1324
1325                 // chain it to the embedded resource list
1326                 resWriterData.m_nextResWriter = m_moduleData.m_embeddedRes;
1327                 m_moduleData.m_embeddedRes = resWriterData;
1328                 return resWriter;
1329             }
1330             else
1331             {
1332                 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadResourceContainer"));
1333             }
1334         }
1335 #endif // !FEATURE_CORECLR
1336
1337 #if FEATURE_CORECLR
1338         [System.Security.SecurityCritical] // auto-generated
1339 #endif
1340         public void DefineManifestResource(String name, Stream stream, ResourceAttributes attribute)
1341         {
1342             if (name == null)
1343                 throw new ArgumentNullException("name");
1344             
1345             if (stream == null)
1346                 throw new ArgumentNullException("stream");
1347             Contract.EndContractBlock();
1348
1349             // Define embedded managed resource to be stored in this module
1350
1351             lock(SyncRoot)
1352             {
1353                 DefineManifestResourceNoLock(name, stream, attribute);
1354             }
1355         }
1356
1357         private void DefineManifestResourceNoLock(String name, Stream stream, ResourceAttributes attribute)
1358         {
1359             // Define embedded managed resource to be stored in this module
1360            if (IsTransient())
1361                 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadResourceContainer"));
1362            Contract.EndContractBlock();
1363
1364 #if !FEATURE_CORECLR
1365             if (name == null)
1366                 throw new ArgumentNullException("name");
1367             if (name.Length == 0)
1368                 throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name");
1369         
1370             if (m_assemblyBuilder.IsPersistable())
1371             {
1372                 m_assemblyBuilder.m_assemblyData.CheckResNameConflict(name);
1373
1374                 ResWriterData resWriterData = new ResWriterData( null, stream, name, String.Empty, String.Empty, attribute);
1375     
1376                 // chain it to the embedded resource list
1377                 resWriterData.m_nextResWriter = m_moduleData.m_embeddedRes;
1378                 m_moduleData.m_embeddedRes = resWriterData;
1379             }
1380             else
1381             { 
1382                 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadResourceContainer"));
1383             }
1384 #endif // !FEATURE_CORECLR
1385         }
1386
1387
1388 #if FEATURE_CORECLR
1389         [System.Security.SecurityCritical] // auto-generated
1390 #endif
1391         public void DefineUnmanagedResource(Byte[] resource)
1392         {
1393             lock(SyncRoot)
1394             {
1395                 DefineUnmanagedResourceInternalNoLock(resource);
1396             }
1397         }
1398
1399         internal void DefineUnmanagedResourceInternalNoLock(Byte[] resource)
1400         {
1401             if (resource == null)
1402                 throw new ArgumentNullException("resource");
1403             Contract.EndContractBlock();
1404
1405             if (m_moduleData.m_strResourceFileName != null || m_moduleData.m_resourceBytes != null)
1406                 throw new ArgumentException(Environment.GetResourceString("Argument_NativeResourceAlreadyDefined"));
1407                         
1408             m_moduleData.m_resourceBytes = new byte[resource.Length];
1409             System.Array.Copy(resource, m_moduleData.m_resourceBytes, resource.Length);
1410         }
1411
1412 #if FEATURE_CORECLR
1413         [System.Security.SecurityCritical] // auto-generated
1414 #else
1415         [System.Security.SecuritySafeCritical]
1416 #endif
1417         [ResourceExposure(ResourceScope.Machine)]
1418         [ResourceConsumption(ResourceScope.Machine)]
1419         public void DefineUnmanagedResource(String resourceFileName)
1420         {
1421             lock(SyncRoot)
1422             {
1423                 DefineUnmanagedResourceFileInternalNoLock(resourceFileName);
1424             }
1425         }
1426
1427         [System.Security.SecurityCritical]  // auto-generated
1428         [ResourceExposure(ResourceScope.Machine)]
1429         [ResourceConsumption(ResourceScope.Machine)]
1430         internal void DefineUnmanagedResourceFileInternalNoLock(String resourceFileName)
1431         {
1432             if (resourceFileName == null)
1433                 throw new ArgumentNullException("resourceFileName");
1434             Contract.EndContractBlock();
1435
1436             if (m_moduleData.m_resourceBytes != null || m_moduleData.m_strResourceFileName != null)
1437                 throw new ArgumentException(Environment.GetResourceString("Argument_NativeResourceAlreadyDefined"));
1438
1439             // Check caller has the right to read the file.
1440             string strFullFileName;
1441             strFullFileName = Path.UnsafeGetFullPath(resourceFileName);
1442             new FileIOPermission(FileIOPermissionAccess.Read, strFullFileName).Demand();
1443
1444             new EnvironmentPermission(PermissionState.Unrestricted).Assert();
1445             try
1446             {
1447                 if (File.UnsafeExists(resourceFileName) == false)
1448                     throw new FileNotFoundException(Environment.GetResourceString(
1449                         "IO.FileNotFound_FileName",
1450                         resourceFileName), resourceFileName);
1451             }
1452             finally
1453             {
1454                 CodeAccessPermission.RevertAssert();
1455             }
1456
1457             m_moduleData.m_strResourceFileName = strFullFileName;
1458         }
1459         #endregion
1460
1461         #region Define Global Method
1462         public MethodBuilder DefineGlobalMethod(String name, MethodAttributes attributes, Type returnType, Type[] parameterTypes)
1463         {
1464             Contract.Ensures(Contract.Result<MethodBuilder>() != null);
1465
1466             return DefineGlobalMethod(name, attributes, CallingConventions.Standard, returnType, parameterTypes);
1467         }
1468
1469         public MethodBuilder DefineGlobalMethod(String name, MethodAttributes attributes, CallingConventions callingConvention, 
1470             Type returnType, Type[] parameterTypes)
1471         {
1472             Contract.Ensures(Contract.Result<MethodBuilder>() != null);
1473
1474             return DefineGlobalMethod(name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null);
1475         }
1476
1477         public MethodBuilder DefineGlobalMethod(String name, MethodAttributes attributes, CallingConventions callingConvention, 
1478             Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers,
1479             Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
1480         {
1481             lock(SyncRoot)
1482             {
1483                 return DefineGlobalMethodNoLock(name, attributes, callingConvention, returnType, 
1484                                                 requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers,
1485                                                 parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
1486             }
1487         }
1488
1489         private MethodBuilder DefineGlobalMethodNoLock(String name, MethodAttributes attributes, CallingConventions callingConvention, 
1490             Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers,
1491             Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
1492         {
1493             if (m_moduleData.m_fGlobalBeenCreated == true)
1494                 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_GlobalsHaveBeenCreated"));
1495         
1496             if (name == null)
1497                 throw new ArgumentNullException("name");
1498
1499             if (name.Length == 0)
1500                 throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name");
1501         
1502             if ((attributes & MethodAttributes.Static) == 0)
1503                 throw new ArgumentException(Environment.GetResourceString("Argument_GlobalFunctionHasToBeStatic"));
1504             Contract.Ensures(Contract.Result<MethodBuilder>() != null);
1505             Contract.EndContractBlock();
1506
1507             CheckContext(returnType);
1508             CheckContext(requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, parameterTypes);
1509             CheckContext(requiredParameterTypeCustomModifiers);
1510             CheckContext(optionalParameterTypeCustomModifiers);
1511
1512             m_moduleData.m_fHasGlobal = true;
1513
1514             return m_moduleData.m_globalTypeBuilder.DefineMethod(name, attributes, callingConvention, 
1515                 returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, 
1516                 parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
1517         }
1518         
1519 #if FEATURE_CORECLR
1520         [System.Security.SecurityCritical] // auto-generated
1521 #endif
1522         public MethodBuilder DefinePInvokeMethod(String name, String dllName, MethodAttributes attributes, 
1523             CallingConventions callingConvention, Type returnType, Type[] parameterTypes, 
1524             CallingConvention nativeCallConv, CharSet nativeCharSet)
1525         {
1526             Contract.Ensures(Contract.Result<MethodBuilder>() != null);
1527
1528             return DefinePInvokeMethod(name, dllName, name, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet);
1529         }
1530
1531 #if FEATURE_CORECLR
1532         [System.Security.SecurityCritical] // auto-generated
1533 #endif
1534         public MethodBuilder DefinePInvokeMethod(String name, String dllName, String entryName, MethodAttributes attributes, 
1535             CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, 
1536             CharSet nativeCharSet)
1537         {
1538             Contract.Ensures(Contract.Result<MethodBuilder>() != null);
1539
1540             lock(SyncRoot)
1541             {
1542                 return DefinePInvokeMethodNoLock(name, dllName, entryName, attributes, callingConvention, 
1543                                                  returnType, parameterTypes, nativeCallConv, nativeCharSet);
1544             }
1545         }
1546
1547 #if FEATURE_CORECLR
1548         [System.Security.SecurityCritical] // auto-generated
1549 #endif
1550         private MethodBuilder DefinePInvokeMethodNoLock(String name, String dllName, String entryName, MethodAttributes attributes, 
1551             CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, 
1552             CharSet nativeCharSet)
1553         {
1554             //Global methods must be static.        
1555             if ((attributes & MethodAttributes.Static) == 0)
1556             {
1557                 throw new ArgumentException(Environment.GetResourceString("Argument_GlobalFunctionHasToBeStatic"));
1558             }
1559             Contract.Ensures(Contract.Result<MethodBuilder>() != null);
1560             Contract.EndContractBlock();
1561
1562             CheckContext(returnType);
1563             CheckContext(parameterTypes);
1564
1565             m_moduleData.m_fHasGlobal = true;
1566             return m_moduleData.m_globalTypeBuilder.DefinePInvokeMethod(name, dllName, entryName, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet);
1567         }
1568         
1569         public void CreateGlobalFunctions()
1570         {
1571             lock(SyncRoot)
1572             {
1573                 CreateGlobalFunctionsNoLock();
1574             }
1575         }
1576
1577         private void CreateGlobalFunctionsNoLock()
1578         {
1579             if (m_moduleData.m_fGlobalBeenCreated)
1580             {
1581                 // cannot create globals twice
1582                 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotADebugModule"));
1583             }
1584             m_moduleData.m_globalTypeBuilder.CreateType();
1585             m_moduleData.m_fGlobalBeenCreated = true;
1586         }
1587     
1588         #endregion
1589
1590         #region Define Data
1591
1592 #if FEATURE_CORECLR
1593         [System.Security.SecurityCritical] // auto-generated
1594 #endif
1595         public FieldBuilder DefineInitializedData(String name, byte[] data, FieldAttributes attributes)
1596         {
1597             // This method will define an initialized Data in .sdata. 
1598             // We will create a fake TypeDef to represent the data with size. This TypeDef
1599             // will be the signature for the Field.         
1600             Contract.Ensures(Contract.Result<FieldBuilder>() != null);
1601
1602             lock(SyncRoot)
1603             {
1604                 return DefineInitializedDataNoLock(name, data, attributes);
1605             }
1606         }
1607
1608 #if FEATURE_CORECLR
1609         [System.Security.SecurityCritical] // auto-generated
1610 #endif
1611         private FieldBuilder DefineInitializedDataNoLock(String name, byte[] data, FieldAttributes attributes)
1612         {
1613             // This method will define an initialized Data in .sdata. 
1614             // We will create a fake TypeDef to represent the data with size. This TypeDef
1615             // will be the signature for the Field.
1616             if (m_moduleData.m_fGlobalBeenCreated == true)
1617             {
1618                 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_GlobalsHaveBeenCreated"));
1619             }
1620             Contract.Ensures(Contract.Result<FieldBuilder>() != null);
1621             Contract.EndContractBlock();
1622         
1623             m_moduleData.m_fHasGlobal = true;
1624             return m_moduleData.m_globalTypeBuilder.DefineInitializedData(name, data, attributes);
1625         }
1626         
1627 #if FEATURE_CORECLR
1628         [System.Security.SecurityCritical] // auto-generated
1629 #endif
1630         public FieldBuilder DefineUninitializedData(String name, int size, FieldAttributes attributes)
1631         {
1632             Contract.Ensures(Contract.Result<FieldBuilder>() != null);
1633
1634             lock(SyncRoot)
1635             {
1636                 return DefineUninitializedDataNoLock(name, size, attributes);
1637             }
1638         }
1639
1640 #if FEATURE_CORECLR
1641         [System.Security.SecurityCritical] // auto-generated
1642 #endif
1643         private FieldBuilder DefineUninitializedDataNoLock(String name, int size, FieldAttributes attributes)
1644         {
1645             // This method will define an uninitialized Data in .sdata. 
1646             // We will create a fake TypeDef to represent the data with size. This TypeDef
1647             // will be the signature for the Field. 
1648
1649             if (m_moduleData.m_fGlobalBeenCreated == true)
1650             {
1651                 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_GlobalsHaveBeenCreated"));
1652             }
1653             Contract.Ensures(Contract.Result<FieldBuilder>() != null);
1654             Contract.EndContractBlock();
1655         
1656             m_moduleData.m_fHasGlobal = true;
1657             return m_moduleData.m_globalTypeBuilder.DefineUninitializedData(name, size, attributes);
1658         }
1659                 
1660         #endregion
1661
1662         #region GetToken
1663         // For a generic type definition, we should return the token for the generic type definition itself in two cases: 
1664         //   1. GetTypeToken
1665         //   2. ldtoken (see ILGenerator)
1666         // For all other occasions we should return the generic type instantiated on its formal parameters.
1667         [System.Security.SecurityCritical]  // auto-generated
1668         internal TypeToken GetTypeTokenInternal(Type type)
1669         {
1670             return GetTypeTokenInternal(type, false);
1671         }
1672
1673         [System.Security.SecurityCritical]  // auto-generated
1674         private TypeToken GetTypeTokenInternal(Type type, bool getGenericDefinition)
1675         {
1676             lock(SyncRoot)
1677             {
1678                 return GetTypeTokenWorkerNoLock(type, getGenericDefinition);
1679             }
1680         }
1681
1682         [System.Security.SecuritySafeCritical]  // auto-generated
1683         public TypeToken GetTypeToken(Type type)
1684         {        
1685             return GetTypeTokenInternal(type, true);
1686         }
1687
1688         [System.Security.SecurityCritical]  // auto-generated
1689         [ResourceExposure(ResourceScope.None)]
1690         [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
1691         private TypeToken GetTypeTokenWorkerNoLock(Type type, bool getGenericDefinition)
1692         {
1693             if (type == null)
1694                 throw new ArgumentNullException("type");
1695             Contract.EndContractBlock();
1696
1697             CheckContext(type);
1698             
1699             // Return a token for the class relative to the Module.  Tokens
1700             // are used to indentify objects when the objects are used in IL
1701             // instructions.  Tokens are always relative to the Module.  For example,
1702             // the token value for System.String is likely to be different from
1703             // Module to Module.  Calling GetTypeToken will cause a reference to be
1704             // added to the Module.  This reference becomes a perminate part of the Module,
1705             // multiple calles to this method with the same class have no additional side affects.
1706             // This function is optimized to use the TypeDef token if Type is within the same module.
1707             // We should also be aware of multiple dynamic modules and multiple implementation of Type!!!
1708
1709             if (type.IsByRef)
1710                 throw new ArgumentException(Environment.GetResourceString("Argument_CannotGetTypeTokenForByRef"));
1711
1712             if ((type.IsGenericType && (!type.IsGenericTypeDefinition || !getGenericDefinition)) ||
1713                 type.IsGenericParameter ||
1714                 type.IsArray ||
1715                 type.IsPointer)
1716             {
1717                 int length;
1718                 byte[] sig = SignatureHelper.GetTypeSigToken(this, type).InternalGetSignature(out length);
1719                 return new TypeToken(GetTokenFromTypeSpec(sig, length));
1720             }
1721
1722             Module refedModule = type.Module;
1723
1724             if (refedModule.Equals(this))
1725             {
1726                 // no need to do anything additional other than defining the TypeRef Token
1727                 TypeBuilder typeBuilder = null;
1728                 GenericTypeParameterBuilder paramBuilder = null;
1729
1730                 EnumBuilder enumBuilder = type as EnumBuilder;
1731                 if (enumBuilder != null)
1732                     typeBuilder = enumBuilder.m_typeBuilder;
1733                 else
1734                     typeBuilder = type as TypeBuilder;
1735
1736                 if (typeBuilder != null)
1737                 {
1738                     // optimization: if the type is defined in this module,
1739                     // just return the token
1740                     //
1741                     return typeBuilder.TypeToken;
1742                 }
1743                 else if ((paramBuilder = type as GenericTypeParameterBuilder) != null)
1744                 {
1745                     return new TypeToken(paramBuilder.MetadataTokenInternal);
1746                 }
1747                 
1748                 return new TypeToken(GetTypeRefNested(type, this, String.Empty));
1749             }
1750                     
1751             // After this point, the referenced module is not the same as the referencing
1752             // module.
1753             //
1754             ModuleBuilder refedModuleBuilder = refedModule as ModuleBuilder;
1755
1756 #if !FEATURE_CORECLR
1757             Contract.Assert(refedModuleBuilder != null || refedModule is RuntimeModule);
1758             bool isRefedModuleTransient = refedModuleBuilder != null ?
1759                                           refedModuleBuilder.IsTransient() :
1760                                           ((RuntimeModule)refedModule).IsTransientInternal();
1761
1762             // We cannot have a non-transient module referencing to a transient module.
1763             if (IsTransient() == false && isRefedModuleTransient)
1764             {
1765                 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadTransientModuleReference"));
1766             }
1767 #endif // !FEATURE_CORECLR
1768
1769             String strRefedModuleFileName = String.Empty;
1770             if (refedModule.Assembly.Equals(this.Assembly))
1771             {
1772                 // if the referenced module is in the same assembly, the resolution
1773                 // scope of the type token will be a module ref, we will need
1774                 // the file name of the referenced module for that.
1775                 // if the refed module is in a different assembly, the resolution
1776                 // scope of the type token will be an assembly ref. We don't need
1777                 // the file name of the referenced module.
1778                 if (refedModuleBuilder == null)
1779                 {
1780                     refedModuleBuilder = this.ContainingAssemblyBuilder.GetModuleBuilder((InternalModuleBuilder)refedModule);
1781                 }
1782                 strRefedModuleFileName = refedModuleBuilder.m_moduleData.m_strFileName;
1783             }
1784
1785             return new TypeToken(GetTypeRefNested(type, refedModule, strRefedModuleFileName));
1786         }
1787         
1788         public TypeToken GetTypeToken(String name)
1789         {
1790             // Return a token for the class relative to the Module. 
1791             // Module.GetType() verifies name
1792             
1793             // Unfortunately, we will need to load the Type and then call GetTypeToken in 
1794             // order to correctly track the assembly reference information.
1795             
1796             return GetTypeToken(InternalModule.GetType(name, false, true));
1797         }
1798
1799         [System.Security.SecuritySafeCritical]  // auto-generated
1800         public MethodToken GetMethodToken(MethodInfo method)
1801         {
1802             lock(SyncRoot)
1803             {
1804                 return GetMethodTokenNoLock(method, true);
1805             }
1806         }
1807
1808         [System.Security.SecurityCritical]  // auto-generated
1809         internal MethodToken GetMethodTokenInternal(MethodInfo method)
1810         {
1811             lock(SyncRoot)
1812             {
1813                 return GetMethodTokenNoLock(method, false);
1814             }
1815         }
1816
1817         // For a method on a generic type, we should return the methoddef token on the generic type definition in two cases
1818         //   1. GetMethodToken
1819         //   2. ldtoken (see ILGenerator)
1820         // For all other occasions we should return the method on the generic type instantiated on the formal parameters.
1821         [System.Security.SecurityCritical]  // auto-generated
1822         private MethodToken GetMethodTokenNoLock(MethodInfo method, bool getGenericTypeDefinition)
1823         {
1824             // Return a MemberRef token if MethodInfo is not defined in this module. Or 
1825             // return the MethodDef token. 
1826             if (method == null)
1827                 throw new ArgumentNullException("method");
1828             Contract.EndContractBlock();
1829
1830             int tr;
1831             int mr = 0;
1832             
1833             SymbolMethod symMethod = null;
1834             MethodBuilder methBuilder = null;
1835
1836             if ( (methBuilder = method as MethodBuilder) != null )
1837             {
1838                 int methodToken = methBuilder.MetadataTokenInternal;
1839                 if (method.Module.Equals(this))
1840                     return new MethodToken(methodToken);
1841
1842                 if (method.DeclaringType == null)
1843                     throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotImportGlobalFromDifferentModule"));
1844
1845                 // method is defined in a different module
1846                 tr = getGenericTypeDefinition ? GetTypeToken(method.DeclaringType).Token : GetTypeTokenInternal(method.DeclaringType).Token;
1847                 mr = GetMemberRef(method.DeclaringType.Module, tr, methodToken);
1848             }
1849             else if (method is MethodOnTypeBuilderInstantiation)
1850             {
1851                 return new MethodToken(GetMemberRefToken(method, null));
1852             }
1853             else if ((symMethod = method as SymbolMethod) != null)
1854             {
1855                 if (symMethod.GetModule() == this)
1856                     return symMethod.GetToken();
1857
1858                 // form the method token
1859                 return symMethod.GetToken(this);
1860             }
1861             else
1862             {
1863                 Type declaringType = method.DeclaringType;
1864
1865                 // We need to get the TypeRef tokens
1866                 if (declaringType == null)
1867                     throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotImportGlobalFromDifferentModule"));
1868
1869                 RuntimeMethodInfo rtMeth = null;
1870
1871                 if (declaringType.IsArray == true)
1872                 {
1873                     // use reflection to build signature to work around the E_T_VAR problem in EEClass
1874                     ParameterInfo[] paramInfo = method.GetParameters();
1875                     
1876                     Type[] tt = new Type[paramInfo.Length];
1877                     
1878                     for (int i = 0; i < paramInfo.Length; i++)
1879                         tt[i] = paramInfo[i].ParameterType;
1880
1881                     return GetArrayMethodToken(declaringType, method.Name, method.CallingConvention, method.ReturnType, tt);
1882                 }
1883                 else if ( (rtMeth = method as RuntimeMethodInfo) != null )
1884                 {
1885                     tr = getGenericTypeDefinition ? GetTypeToken(method.DeclaringType).Token : GetTypeTokenInternal(method.DeclaringType).Token;
1886                     mr = GetMemberRefOfMethodInfo(tr, rtMeth);
1887                 }
1888                 else
1889                 {
1890                     // some user derived ConstructorInfo
1891                     // go through the slower code path, i.e. retrieve parameters and form signature helper.
1892                     ParameterInfo[] parameters = method.GetParameters();
1893
1894                     Type[] parameterTypes = new Type[parameters.Length];
1895                     Type[][] requiredCustomModifiers = new Type[parameterTypes.Length][];
1896                     Type[][] optionalCustomModifiers = new Type[parameterTypes.Length][];
1897
1898                     for (int i = 0; i < parameters.Length; i++)
1899                     {
1900                         parameterTypes[i] = parameters[i].ParameterType;
1901                         requiredCustomModifiers[i] = parameters[i].GetRequiredCustomModifiers();
1902                         optionalCustomModifiers[i] = parameters[i].GetOptionalCustomModifiers();
1903                     }
1904           
1905                     tr = getGenericTypeDefinition ? GetTypeToken(method.DeclaringType).Token : GetTypeTokenInternal(method.DeclaringType).Token;
1906
1907                     SignatureHelper sigHelp;
1908
1909                     try 
1910                     {
1911                         sigHelp = SignatureHelper.GetMethodSigHelper(
1912                         this, method.CallingConvention, method.ReturnType, 
1913                         method.ReturnParameter.GetRequiredCustomModifiers(), method.ReturnParameter.GetOptionalCustomModifiers(), 
1914                         parameterTypes, requiredCustomModifiers, optionalCustomModifiers);
1915                     } 
1916                     catch(NotImplementedException)
1917                     {
1918                         // Legacy code deriving from MethodInfo may not have implemented ReturnParameter.
1919                         sigHelp = SignatureHelper.GetMethodSigHelper(this, method.ReturnType, parameterTypes);
1920                     }
1921
1922                     int length;                                           
1923                     byte[] sigBytes = sigHelp.InternalGetSignature(out length);
1924                     mr = GetMemberRefFromSignature(tr, method.Name, sigBytes, length);
1925                 }
1926             }
1927
1928             return new MethodToken(mr);
1929         }
1930
1931         [System.Security.SecuritySafeCritical]  // auto-generated
1932         public MethodToken GetConstructorToken(ConstructorInfo constructor, IEnumerable<Type> optionalParameterTypes)
1933         {
1934             if (constructor == null)
1935             {
1936                 throw new ArgumentNullException("constructor");
1937             }
1938
1939             lock (SyncRoot)
1940             {
1941                 // useMethodDef is not applicable - constructors aren't generic
1942                 return new MethodToken(GetMethodTokenInternal(constructor, optionalParameterTypes, false));
1943             }
1944         }
1945
1946         [System.Security.SecuritySafeCritical]  // auto-generated
1947         public MethodToken GetMethodToken(MethodInfo method, IEnumerable<Type> optionalParameterTypes)
1948         {
1949             if (method == null)
1950             {
1951                 throw new ArgumentNullException("method");
1952             }
1953
1954             // useMethodDef flag only affects the result if we pass in a generic method definition. 
1955             // If the caller is looking for a token for an ldtoken/ldftn/ldvirtftn instruction and passes in a generic method definition info/builder, 
1956             // we correclty return the MethodDef/Ref token of the generic definition that can be used with ldtoken/ldftn/ldvirtftn. 
1957             //
1958             // If the caller is looking for a token for a call/callvirt/jmp instruction and passes in a generic method definition info/builder,
1959             // we also return the generic MethodDef/Ref token, which is indeed not acceptable for call/callvirt/jmp instruction.
1960             // But the caller can always instantiate the info/builder and pass it in. Then we build the right MethodSpec.
1961
1962             lock (SyncRoot)
1963             {
1964                 return new MethodToken(GetMethodTokenInternal(method, optionalParameterTypes, true));
1965             }
1966         }
1967
1968         [System.Security.SecurityCritical]  // auto-generated
1969         internal int GetMethodTokenInternal(MethodBase method, IEnumerable<Type> optionalParameterTypes, bool useMethodDef)
1970         {
1971             int tk = 0;
1972             MethodInfo methodInfo = method as MethodInfo;
1973
1974             if (method.IsGenericMethod)
1975             {
1976                 // Constructors cannot be generic.
1977                 Contract.Assert(methodInfo != null);
1978
1979                 // Given M<Bar> unbind to M<S>
1980                 MethodInfo methodInfoUnbound = methodInfo;
1981                 bool isGenericMethodDef = methodInfo.IsGenericMethodDefinition;
1982
1983                 if (!isGenericMethodDef)
1984                 {
1985                     methodInfoUnbound = methodInfo.GetGenericMethodDefinition();
1986                 }
1987
1988                 if (!this.Equals(methodInfoUnbound.Module)
1989                     || (methodInfoUnbound.DeclaringType != null && methodInfoUnbound.DeclaringType.IsGenericType))
1990                 {
1991                     tk = GetMemberRefToken(methodInfoUnbound, null);
1992                 }
1993                 else
1994                 {
1995                     tk = GetMethodTokenInternal(methodInfoUnbound).Token;
1996                 }
1997
1998                 // For Ldtoken, Ldftn, and Ldvirtftn, we should emit the method def/ref token for a generic method definition.
1999                 if (isGenericMethodDef && useMethodDef)
2000                 {
2001                     return tk;
2002                 }
2003
2004                 // Create signature of method instantiation M<Bar>
2005                 int sigLength;
2006                 byte[] sigBytes = SignatureHelper.GetMethodSpecSigHelper(
2007                     this, methodInfo.GetGenericArguments()).InternalGetSignature(out sigLength);
2008
2009                 // Create MethodSepc M<Bar> with parent G?.M<S> 
2010                 tk = TypeBuilder.DefineMethodSpec(this.GetNativeHandle(), tk, sigBytes, sigLength);
2011             }
2012             else
2013             {
2014                 if (((method.CallingConvention & CallingConventions.VarArgs) == 0) &&
2015                     (method.DeclaringType == null || !method.DeclaringType.IsGenericType))
2016                 {
2017                     if (methodInfo != null)
2018                     {
2019                         tk = GetMethodTokenInternal(methodInfo).Token;
2020                     }
2021                     else
2022                     {
2023                         tk = GetConstructorToken(method as ConstructorInfo).Token;
2024                     }
2025                 }
2026                 else
2027                 {
2028                     tk = GetMemberRefToken(method, optionalParameterTypes);
2029                 }
2030             }
2031
2032             return tk;
2033         }
2034     
2035         [System.Security.SecuritySafeCritical]  // auto-generated
2036         public MethodToken GetArrayMethodToken(Type arrayClass, String methodName, CallingConventions callingConvention, 
2037             Type returnType, Type[] parameterTypes)
2038         {
2039             lock(SyncRoot)
2040             {
2041                 return GetArrayMethodTokenNoLock(arrayClass, methodName, callingConvention, returnType, parameterTypes);
2042             }
2043         }
2044
2045         [System.Security.SecurityCritical]  // auto-generated
2046         private MethodToken GetArrayMethodTokenNoLock(Type arrayClass, String methodName, CallingConventions callingConvention, 
2047             Type returnType, Type[] parameterTypes)
2048         {
2049             if (arrayClass == null)
2050                 throw new ArgumentNullException("arrayClass");
2051
2052             if (methodName == null)
2053                 throw new ArgumentNullException("methodName");
2054
2055             if (methodName.Length == 0)
2056                 throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "methodName");
2057
2058             if (arrayClass.IsArray == false)
2059                 throw new ArgumentException(Environment.GetResourceString("Argument_HasToBeArrayClass")); 
2060             Contract.EndContractBlock();
2061
2062             CheckContext(returnType, arrayClass);
2063             CheckContext(parameterTypes);
2064
2065             // Return a token for the MethodInfo for a method on an Array.  This is primarily
2066             // used to get the LoadElementAddress method. 
2067
2068             int length;
2069
2070             SignatureHelper sigHelp = SignatureHelper.GetMethodSigHelper(
2071                 this, callingConvention, returnType, null, null, parameterTypes, null, null);
2072
2073             byte[] sigBytes = sigHelp.InternalGetSignature(out length);
2074
2075             TypeToken typeSpec = GetTypeTokenInternal(arrayClass);
2076
2077             return new MethodToken(GetArrayMethodToken(GetNativeHandle(),
2078                 typeSpec.Token, methodName, sigBytes, length));
2079         }
2080
2081         [System.Security.SecuritySafeCritical]  // auto-generated
2082         public MethodInfo GetArrayMethod(Type arrayClass, String methodName, CallingConventions callingConvention, 
2083             Type returnType, Type[] parameterTypes)
2084         {
2085             CheckContext(returnType, arrayClass);
2086             CheckContext(parameterTypes);
2087
2088             // GetArrayMethod is useful when you have an array of a type whose definition has not been completed and 
2089             // you want to access methods defined on Array. For example, you might define a type and want to define a 
2090             // method that takes an array of the type as a parameter. In order to access the elements of the array, 
2091             // you will need to call methods of the Array class.
2092
2093             MethodToken token = GetArrayMethodToken(arrayClass, methodName, callingConvention, returnType, parameterTypes);
2094
2095             return new SymbolMethod(this, token, arrayClass, methodName, callingConvention, returnType, parameterTypes);
2096         }
2097
2098         [System.Security.SecuritySafeCritical]  // auto-generated
2099         [System.Runtime.InteropServices.ComVisible(true)]
2100         public MethodToken GetConstructorToken(ConstructorInfo con)
2101         {
2102             // Return a token for the ConstructorInfo relative to the Module. 
2103             return InternalGetConstructorToken(con, false);
2104         }
2105
2106         [System.Security.SecuritySafeCritical]  // auto-generated
2107         public FieldToken GetFieldToken(FieldInfo field) 
2108         {
2109             lock(SyncRoot)
2110             {
2111                 return GetFieldTokenNoLock(field);
2112             }
2113         }
2114
2115         [System.Security.SecurityCritical]  // auto-generated
2116         private FieldToken GetFieldTokenNoLock(FieldInfo field) 
2117         {
2118             if (field == null) {
2119                 throw new ArgumentNullException("con");
2120             }
2121             Contract.EndContractBlock();
2122
2123             int     tr;
2124             int     mr = 0;
2125
2126             FieldBuilder fdBuilder = null;
2127             RuntimeFieldInfo rtField = null;
2128             FieldOnTypeBuilderInstantiation fOnTB = null;
2129
2130             if ((fdBuilder = field as FieldBuilder) != null)
2131             {
2132                 if (field.DeclaringType != null && field.DeclaringType.IsGenericType)
2133                 {
2134                     int length;
2135                     byte[] sig = SignatureHelper.GetTypeSigToken(this, field.DeclaringType).InternalGetSignature(out length);
2136                     tr = GetTokenFromTypeSpec(sig, length);
2137                     mr = GetMemberRef(this, tr, fdBuilder.GetToken().Token);
2138                 }
2139                 else if (fdBuilder.Module.Equals(this))
2140                 {
2141                     // field is defined in the same module
2142                     return fdBuilder.GetToken();
2143                 }
2144                 else
2145                 {
2146                     // field is defined in a different module
2147                     if (field.DeclaringType == null)
2148                     {
2149                         throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotImportGlobalFromDifferentModule"));
2150                     }
2151                     tr = GetTypeTokenInternal(field.DeclaringType).Token;
2152                     mr = GetMemberRef(field.ReflectedType.Module, tr, fdBuilder.GetToken().Token);
2153                 }
2154             }
2155             else if ( (rtField = field as RuntimeFieldInfo) != null)
2156             {
2157                 // FieldInfo is not an dynamic field
2158                 
2159                 // We need to get the TypeRef tokens
2160                 if (field.DeclaringType == null)
2161                 {
2162                     throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotImportGlobalFromDifferentModule"));
2163                 }
2164                 
2165                 if (field.DeclaringType != null && field.DeclaringType.IsGenericType)
2166                 {
2167                     int length;
2168                     byte[] sig = SignatureHelper.GetTypeSigToken(this, field.DeclaringType).InternalGetSignature(out length);
2169                     tr = GetTokenFromTypeSpec(sig, length);
2170                     mr = GetMemberRefOfFieldInfo(tr, field.DeclaringType.GetTypeHandleInternal(), rtField);
2171                 }
2172                 else
2173                 {
2174                     tr = GetTypeTokenInternal(field.DeclaringType).Token;       
2175                     mr = GetMemberRefOfFieldInfo(tr, field.DeclaringType.GetTypeHandleInternal(), rtField);
2176                 }
2177             }
2178             else if ( (fOnTB = field as FieldOnTypeBuilderInstantiation) != null)
2179             {
2180                 FieldInfo fb = fOnTB.FieldInfo;
2181                 int length;
2182                 byte[] sig = SignatureHelper.GetTypeSigToken(this, field.DeclaringType).InternalGetSignature(out length);
2183                 tr = GetTokenFromTypeSpec(sig, length);
2184                 mr = GetMemberRef(fb.ReflectedType.Module, tr, fOnTB.MetadataTokenInternal);
2185             }
2186             else
2187             {
2188                 // user defined FieldInfo
2189                 tr = GetTypeTokenInternal(field.ReflectedType).Token;
2190
2191                 SignatureHelper sigHelp = SignatureHelper.GetFieldSigHelper(this);
2192
2193                 sigHelp.AddArgument(field.FieldType, field.GetRequiredCustomModifiers(), field.GetOptionalCustomModifiers());
2194
2195                 int length;
2196                 byte[] sigBytes = sigHelp.InternalGetSignature(out length);
2197
2198                 mr = GetMemberRefFromSignature(tr, field.Name, sigBytes, length);
2199             }
2200             
2201             return new FieldToken(mr, field.GetType());
2202         }
2203         
2204         [System.Security.SecuritySafeCritical]  // auto-generated
2205         public StringToken GetStringConstant(String str) 
2206         {
2207             if (str == null)
2208             {
2209                 throw new ArgumentNullException("str");
2210             }
2211             Contract.EndContractBlock();
2212
2213             // Returns a token representing a String constant.  If the string 
2214             // value has already been defined, the existing token will be returned.
2215             return new StringToken(GetStringConstant(GetNativeHandle(), str, str.Length));
2216         }
2217     
2218         [System.Security.SecuritySafeCritical]  // auto-generated
2219         public SignatureToken GetSignatureToken(SignatureHelper sigHelper)
2220         {
2221             // Define signature token given a signature helper. This will define a metadata
2222             // token for the signature described by SignatureHelper.
2223
2224             if (sigHelper == null)
2225             {
2226                 throw new ArgumentNullException("sigHelper");
2227             }
2228             Contract.EndContractBlock();
2229
2230             int sigLength;
2231             byte[] sigBytes;
2232     
2233             // get the signature in byte form
2234             sigBytes = sigHelper.InternalGetSignature(out sigLength);
2235             return new SignatureToken(TypeBuilder.GetTokenFromSig(GetNativeHandle(), sigBytes, sigLength), this);
2236         }           
2237         [System.Security.SecuritySafeCritical]  // auto-generated
2238         public SignatureToken GetSignatureToken(byte[] sigBytes, int sigLength)
2239         {
2240             if (sigBytes == null)
2241                 throw new ArgumentNullException("sigBytes");
2242             Contract.EndContractBlock();
2243
2244             byte[] localSigBytes = new byte[sigBytes.Length];
2245             Array.Copy(sigBytes, localSigBytes, sigBytes.Length);
2246
2247             return new SignatureToken(TypeBuilder.GetTokenFromSig(GetNativeHandle(), localSigBytes, sigLength), this);
2248         }
2249     
2250         #endregion
2251
2252         #region Other
2253
2254 #if FEATURE_CORECLR
2255         [System.Security.SecurityCritical] // auto-generated
2256 #else
2257         [System.Security.SecuritySafeCritical]
2258 #endif
2259         [System.Runtime.InteropServices.ComVisible(true)]
2260         public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
2261         {
2262             if (con == null)
2263                 throw new ArgumentNullException("con");
2264             if (binaryAttribute == null)
2265                 throw new ArgumentNullException("binaryAttribute");
2266             Contract.EndContractBlock();
2267             
2268             TypeBuilder.DefineCustomAttribute(
2269                 this,
2270                 1,                                          // This is hard coding the module token to 1
2271                 this.GetConstructorToken(con).Token,
2272                 binaryAttribute,
2273                 false, false);
2274         }
2275
2276         [System.Security.SecuritySafeCritical]  // auto-generated
2277         public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
2278         {
2279             if (customBuilder == null)
2280             {
2281                 throw new ArgumentNullException("customBuilder");
2282             }
2283             Contract.EndContractBlock();
2284
2285             customBuilder.CreateCustomAttribute(this, 1);   // This is hard coding the module token to 1
2286         }
2287
2288         // This API returns the symbol writer being used to write debug symbols for this 
2289         // module (if any).
2290         // 
2291         // WARNING: It is unlikely this API can be used correctly by applications in any 
2292         // reasonable way.  It may be called internally from within TypeBuilder.CreateType.
2293         // 
2294         // Specifically:
2295         // 1. The underlying symbol writer (written in unmanaged code) is not necessarily well
2296         // hardenned and fuzz-tested against malicious API calls.  The security of partial-trust
2297         // symbol writing is improved by restricting usage of the writer APIs to the well-structured
2298         // uses in ModuleBuilder. 
2299         // 2. TypeBuilder.CreateType emits all the symbols for the type.  This will effectively 
2300         // overwrite anything someone may have written manually about the type (specifically 
2301         // ISymbolWriter.OpenMethod is specced to clear anything previously written for the 
2302         // specified method)
2303         // 3. Someone could technically update the symbols for a method after CreateType is 
2304         // called, but the debugger (which uses these symbols) assumes that they are only 
2305         // updated at TypeBuilder.CreateType time.  The changes wouldn't be visible (committed 
2306         // to the underlying stream) until another type was baked.
2307         // 4. Access to the writer is supposed to be synchronized (the underlying COM API is 
2308         // not thread safe, and these are only thin wrappers on top of them).  Exposing this 
2309         // directly allows the synchronization to be violated.  We know that concurrent symbol 
2310         // writer access can cause AVs and other problems.  The writer APIs should not be callable
2311         // directly by partial-trust code, but if they could this would be a security hole.  
2312         // Regardless, this is a reliability bug.  
2313         // 
2314         // For these reasons, we should consider making this API internal in Arrowhead
2315         // (as it is in Silverlight), and consider validating that we're within a call
2316         // to TypeBuilder.CreateType whenever this is used.
2317         public ISymbolWriter GetSymWriter()
2318         {
2319             return m_iSymWriter;
2320         }
2321
2322 #if FEATURE_CORECLR
2323         [System.Security.SecuritySafeCritical] 
2324 #endif
2325         public ISymbolDocumentWriter DefineDocument(String url, Guid language, Guid languageVendor, Guid documentType)
2326         {
2327             // url cannot be null but can be an empty string 
2328             if (url == null)
2329                 throw new ArgumentNullException("url");
2330             Contract.EndContractBlock();
2331
2332             lock(SyncRoot)
2333             {
2334                 return DefineDocumentNoLock(url, language, languageVendor, documentType);
2335             }
2336         }
2337
2338 #if FEATURE_CORECLR
2339         [System.Security.SecurityCritical] // auto-generated
2340 #endif
2341         private ISymbolDocumentWriter DefineDocumentNoLock(String url, Guid language, Guid languageVendor, Guid documentType)
2342         {
2343             if (m_iSymWriter == null)
2344             {
2345                 // Cannot DefineDocument when it is not a debug module
2346                 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotADebugModule"));
2347             }
2348
2349             return m_iSymWriter.DefineDocument(url, language, languageVendor, documentType);
2350         }
2351     
2352 #if FEATURE_CORECLR
2353         [System.Security.SecurityCritical] // auto-generated
2354 #else
2355         [System.Security.SecuritySafeCritical]
2356 #endif
2357         public void SetUserEntryPoint(MethodInfo entryPoint)
2358         {
2359             lock(SyncRoot)
2360             {
2361                 SetUserEntryPointNoLock(entryPoint);
2362             }
2363         }
2364
2365         [System.Security.SecurityCritical]  // auto-generated
2366         private void SetUserEntryPointNoLock(MethodInfo entryPoint)
2367         {
2368             // Set the user entry point. Compiler may generate startup stub before calling user main.
2369             // The startup stub will be the entry point. While the user "main" will be the user entry
2370             // point so that debugger will not step into the compiler entry point.
2371
2372             if (entryPoint == null)
2373             {
2374                 throw new ArgumentNullException("entryPoint");
2375             }
2376             Contract.EndContractBlock();
2377         
2378             if (m_iSymWriter == null)
2379             {
2380                 // Cannot set entry point when it is not a debug module
2381                 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotADebugModule"));
2382             }
2383
2384             if (entryPoint.DeclaringType != null)
2385             {
2386                 if (!entryPoint.Module.Equals(this))
2387                 {
2388                     // you cannot pass in a MethodInfo that is not contained by this ModuleBuilder
2389                     throw new InvalidOperationException(Environment.GetResourceString("Argument_NotInTheSameModuleBuilder"));
2390                 }
2391             }
2392             else
2393             {
2394                 // unfortunately this check is missing for global function passed in as RuntimeMethodInfo. 
2395                 // The problem is that Reflection does not 
2396                 // allow us to get the containing module giving a global function
2397                 MethodBuilder mb = entryPoint as MethodBuilder;
2398                 if (mb != null && mb.GetModuleBuilder() != this)
2399                 {
2400                     // you cannot pass in a MethodInfo that is not contained by this ModuleBuilder
2401                     throw new InvalidOperationException(Environment.GetResourceString("Argument_NotInTheSameModuleBuilder"));                    
2402                 }                    
2403             }
2404                 
2405             // get the metadata token value and create the SymbolStore's token value class
2406             SymbolToken       tkMethod = new SymbolToken(GetMethodTokenInternal(entryPoint).Token);
2407
2408             // set the UserEntryPoint
2409             m_iSymWriter.SetUserEntryPoint(tkMethod);
2410         }
2411     
2412         public void SetSymCustomAttribute(String name, byte[] data)
2413         {
2414             lock(SyncRoot)
2415             {
2416                 SetSymCustomAttributeNoLock(name, data);
2417             }
2418         }
2419
2420         private void SetSymCustomAttributeNoLock(String name, byte[] data)
2421         {
2422             if (m_iSymWriter == null)
2423             {
2424                 // Cannot SetSymCustomAttribute when it is not a debug module
2425                 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotADebugModule"));
2426             }
2427
2428             // This API has never worked.  It seems like we might want to call m_iSymWriter.SetSymAttribute,
2429             // but we don't have a metadata token to associate the attribute with.  Instead 
2430             // MethodBuilder.SetSymCustomAttribute could be used to associate a symbol attribute with a specific method.
2431         }
2432     
2433         [Pure]
2434         public bool IsTransient()
2435         {
2436             return InternalModule.IsTransientInternal();
2437         }
2438
2439         #endregion
2440
2441         #endregion    
2442
2443 #if !FEATURE_CORECLR
2444         void _ModuleBuilder.GetTypeInfoCount(out uint pcTInfo)
2445         {
2446             throw new NotImplementedException();
2447         }
2448
2449         void _ModuleBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
2450         {
2451             throw new NotImplementedException();
2452         }
2453
2454         void _ModuleBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
2455         {
2456             throw new NotImplementedException();
2457         }
2458
2459         void _ModuleBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
2460         {
2461             throw new NotImplementedException();
2462         }
2463 #endif
2464     }
2465 }