3 // Copyright (c) Microsoft Corporation. All rights reserved.
6 // <OWNER>Microsoft</OWNER>
9 namespace System.Reflection.Emit
11 using System.Runtime.InteropServices;
13 using System.Collections.Generic;
14 using System.Diagnostics.SymbolStore;
15 using System.Globalization;
16 using System.Reflection;
17 using System.Diagnostics;
19 using System.Resources;
20 using System.Security;
21 using System.Security.Permissions;
22 using System.Runtime.Serialization;
24 using System.Threading;
25 using System.Runtime.Versioning;
26 using System.Runtime.CompilerServices;
27 using System.Diagnostics.Contracts;
29 internal sealed class InternalModuleBuilder : RuntimeModule
31 #region Private Data Members
32 // WARNING!! WARNING!!
33 // InternalModuleBuilder should not contain any data members as its reflectbase is the same as Module.
36 private InternalModuleBuilder() { }
38 #region object overrides
39 public override bool Equals(object obj)
44 if (obj is InternalModuleBuilder)
45 return ((object)this == obj);
47 return obj.Equals(this);
49 // Need a dummy GetHashCode to pair with Equals
50 public override int GetHashCode() { return base.GetHashCode(); }
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
63 [ResourceExposure(ResourceScope.Machine)]
64 [MethodImplAttribute(MethodImplOptions.InternalCall)]
65 internal static extern IntPtr nCreateISymWriterForDynamicModule(Module module, String filename);
69 #region Internal Static Members
70 static internal String UnmangleTypeName(String typeName)
72 // Gets the original type name, without '+' name mangling.
74 int i = typeName.Length - 1;
77 i = typeName.LastIndexOf('+', i);
81 bool evenSlashes = true;
83 while (typeName[--iSlash] == '\\')
84 evenSlashes = !evenSlashes;
86 // Even number of slashes means this '+' is a name separator
93 return typeName.Substring(i + 1);
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;
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; } }
114 internal ModuleBuilder(AssemblyBuilder assemblyBuilder, InternalModuleBuilder internalModuleBuilder)
116 m_internalModuleBuilder = internalModuleBuilder;
117 m_assemblyBuilder = assemblyBuilder;
121 #region Private Members
122 internal void AddType(string name, Type type)
124 m_TypeBuilderDict.Add(name, type);
127 internal void CheckTypeNameConflict(String strTypeName, Type enclosingType)
129 Type foundType = null;
130 if (m_TypeBuilderDict.TryGetValue(strTypeName, out foundType) &&
131 object.ReferenceEquals(foundType.DeclaringType, enclosingType))
133 // Cannot have two types with the same name
134 throw new ArgumentException(Environment.GetResourceString("Argument_DuplicateTypeName"));
138 private Type GetType(String strFormat, Type baseType)
140 // This function takes a string to describe the compound type, such as "[,][]", and a baseType.
142 if (strFormat == null || strFormat.Equals(String.Empty))
147 // convert the format string to byte array and then call FormCompoundType
148 char[] bFormat = strFormat.ToCharArray();
149 return SymbolType.FormCompoundType(bFormat, baseType, 0);
154 internal void CheckContext(params Type[][] typess)
156 ContainingAssemblyBuilder.CheckContext(typess);
158 internal void CheckContext(params Type[] types)
160 ContainingAssemblyBuilder.CheckContext(types);
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);
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);
176 [System.Security.SecurityCritical] // auto-generated
177 private int GetMemberRef(Module refedModule, int tr, int defToken)
179 return GetMemberRef(GetNativeHandle(), GetRuntimeModuleFromModule(refedModule).GetNativeHandle(), tr, defToken);
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);
188 [System.Security.SecurityCritical] // auto-generated
189 private int GetMemberRefFromSignature(int tr, String methodName, byte[] signature, int length)
191 return GetMemberRefFromSignature(GetNativeHandle(), tr, methodName, signature, length);
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);
200 [System.Security.SecurityCritical] // auto-generated
201 private int GetMemberRefOfMethodInfo(int tr, RuntimeMethodInfo method)
203 Contract.Assert(method != null);
206 if (ContainingAssemblyBuilder.ProfileAPICheck)
208 if ((method.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
209 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", method.FullName));
213 return GetMemberRefOfMethodInfo(GetNativeHandle(), tr, method);
216 [System.Security.SecurityCritical] // auto-generated
217 private int GetMemberRefOfMethodInfo(int tr, RuntimeConstructorInfo method)
219 Contract.Assert(method != null);
222 if (ContainingAssemblyBuilder.ProfileAPICheck)
224 if ((method.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
225 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", method.FullName));
229 return GetMemberRefOfMethodInfo(GetNativeHandle(), tr, method);
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);
238 [System.Security.SecurityCritical] // auto-generated
239 private int GetMemberRefOfFieldInfo(int tkType, RuntimeTypeHandle declaringType, RuntimeFieldInfo runtimeField)
241 Contract.Assert(runtimeField != null);
244 if (ContainingAssemblyBuilder.ProfileAPICheck)
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));
252 return GetMemberRefOfFieldInfo(GetNativeHandle(), tkType, declaringType, runtimeField.MetadataToken);
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);
261 [System.Security.SecurityCritical] // auto-generated
262 private int GetTokenFromTypeSpec(byte[] signature, int length)
264 return GetTokenFromTypeSpec(GetNativeHandle(), signature, length);
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);
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);
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);
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);
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);
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);
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);
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,
319 int portableExecutableKind,
320 int ImageFileMachine);
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);
332 [System.Security.SecurityCritical] // auto-generated
333 internal void DefineNativeResource(PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
336 string strResourceFileName = m_moduleData.m_strResourceFileName;
337 byte[] resourceBytes = m_moduleData.m_resourceBytes;
339 if (strResourceFileName != null)
341 DefineNativeResourceFile(GetNativeHandle(),
343 (int)portableExecutableKind, (int)imageFileMachine);
346 if (resourceBytes != null)
348 DefineNativeResourceBytes(GetNativeHandle(),
349 resourceBytes, resourceBytes.Length,
350 (int)portableExecutableKind, (int)imageFileMachine);
352 #endif // !FEATURE_PAL
357 #region Internal Members
358 internal virtual Type FindTypeBuilderWithName(String strTypeName, bool ignoreCase)
362 foreach (string name in m_TypeBuilderDict.Keys)
364 if (String.Compare(name, strTypeName, (StringComparison.OrdinalIgnoreCase)) == 0)
365 return m_TypeBuilderDict[name];
371 if (m_TypeBuilderDict.TryGetValue(strTypeName, out foundType))
379 internal void SetEntryPoint(MethodToken entryPoint)
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;
386 #endif //!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)
398 if (m_moduleData.m_isSaved == true)
400 // can only save once
401 throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture,
402 Environment.GetResourceString("InvalidOperation_ModuleHasBeenSaved"),
403 m_moduleData.m_strModuleName));
406 if (m_moduleData.m_fGlobalBeenCreated == false && m_moduleData.m_fHasGlobal == true)
407 throw new NotSupportedException(Environment.GetResourceString("NotSupported_GlobalFunctionNotBaked"));
409 TypeBuilder typeBuilder;
410 foreach (Type item in m_TypeBuilderDict.Values)
412 if (item is TypeBuilder)
414 typeBuilder = (TypeBuilder)item;
418 EnumBuilder enumBuilder = (EnumBuilder)item;
419 typeBuilder = enumBuilder.m_typeBuilder;
422 if (!typeBuilder.IsCreated())
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));
431 PreSavePEFile(GetNativeHandle(), (int)portableExecutableKind, (int)imageFileMachine);
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)
441 // This is a helper called by AssemblyBuilder save to save information for the persistable modules.
442 if (m_moduleData.m_embeddedRes != null)
444 // There are embedded resources for this module
445 ResWriterData resWriter;
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)
450 if (resWriter.m_resWriter != null)
451 resWriter.m_resWriter.Generate();
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);
458 AddResource(GetNativeHandle(),
462 m_moduleData.FileToken,
463 (int)resWriter.m_attribute,
464 (int)portableExecutableKind,
465 (int)imageFileMachine);
469 DefineNativeResource(portableExecutableKind, imageFileMachine);
471 PEFileKinds pekind = isAssemblyFile ? ContainingAssemblyBuilder.m_assemblyData.m_peFileKind : PEFileKinds.Dll;
473 SavePEFile(GetNativeHandle(), fileName, m_EntryPoint.Token, (int)pekind, isAssemblyFile);
475 m_moduleData.m_isSaved = true;
477 #endif // !FEATURE_CORECLR
479 [System.Security.SecurityCritical] // auto-generated
480 [ResourceExposure(ResourceScope.Machine)]
481 [ResourceConsumption(ResourceScope.Machine)]
482 private int GetTypeRefNested(Type type, Module refedModule, String strRefedModuleFileName)
484 // This function will generate correct TypeRef token for top level type and nested type.
486 Type enclosingType = type.DeclaringType;
487 int tkResolution = 0;
488 String typeName = type.FullName;
490 if (enclosingType != null)
492 tkResolution = GetTypeRefNested(enclosingType, refedModule, strRefedModuleFileName);
493 typeName = UnmangleTypeName(typeName);
496 Contract.Assert(!type.IsByRef, "Must not be ByRef.");
497 Contract.Assert(!type.IsGenericType || type.IsGenericTypeDefinition, "Must not have generic arguments.");
500 if (ContainingAssemblyBuilder.ProfileAPICheck)
502 RuntimeType rtType = type as RuntimeType;
503 if (rtType != null && (rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
505 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtType.FullName));
510 return GetTypeRef(GetNativeHandle(), typeName, GetRuntimeModuleFromModule(refedModule).GetNativeHandle(), strRefedModuleFileName, tkResolution);
513 [System.Security.SecurityCritical] // auto-generated
514 internal MethodToken InternalGetConstructorToken(ConstructorInfo con, bool usingRef)
516 // Helper to get constructor token. If usingRef is true, we will never use the def token
519 throw new ArgumentNullException("con");
520 Contract.EndContractBlock();
525 ConstructorBuilder conBuilder = null;
526 ConstructorOnTypeBuilderInstantiation conOnTypeBuilderInst = null;
527 RuntimeConstructorInfo rtCon = null;
529 if ( (conBuilder = con as ConstructorBuilder) != null )
531 if (usingRef == false && conBuilder.Module.Equals(this))
532 return conBuilder.GetToken();
534 // constructor is defined in a different module
535 tr = GetTypeTokenInternal(con.ReflectedType).Token;
536 mr = GetMemberRef(con.ReflectedType.Module, tr, conBuilder.GetToken().Token);
538 else if ( (conOnTypeBuilderInst = con as ConstructorOnTypeBuilderInstantiation) != null )
540 if (usingRef == true) throw new InvalidOperationException();
542 tr = GetTypeTokenInternal(con.DeclaringType).Token;
543 mr = GetMemberRef(con.DeclaringType.Module, tr, conOnTypeBuilderInst.MetadataTokenInternal);
545 else if ( (rtCon = con as RuntimeConstructorInfo) != null && con.ReflectedType.IsArray == false)
547 // constructor is not a dynamic field
548 // We need to get the TypeRef tokens
550 tr = GetTypeTokenInternal(con.ReflectedType).Token;
551 mr = GetMemberRefOfMethodInfo(tr, rtCon);
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"));
561 int count = parameters.Length;
562 Type[] parameterTypes = new Type[count];
563 Type[][] requiredCustomModifiers = new Type[count][];
564 Type[][] optionalCustomModifiers = new Type[count][];
566 for (int i = 0; i < count; i++)
568 if (parameters[i] == null)
569 throw new ArgumentException(Environment.GetResourceString("Argument_InvalidConstructorInfo"));
571 parameterTypes[i] = parameters[i].ParameterType;
572 requiredCustomModifiers[i] = parameters[i].GetRequiredCustomModifiers();
573 optionalCustomModifiers[i] = parameters[i].GetOptionalCustomModifiers();
576 tr = GetTypeTokenInternal(con.ReflectedType).Token;
578 SignatureHelper sigHelp = SignatureHelper.GetMethodSigHelper(this, con.CallingConvention, null, null, null, parameterTypes, requiredCustomModifiers, optionalCustomModifiers);
580 byte[] sigBytes = sigHelp.InternalGetSignature(out length);
582 mr = GetMemberRefFromSignature(tr, con.Name, sigBytes, length);
585 return new MethodToken( mr );
588 [System.Security.SecurityCritical] // auto-generated
589 [ResourceExposure(ResourceScope.Machine)]
590 [ResourceConsumption(ResourceScope.Machine)]
591 internal void Init(String strModuleName, String strFileName, int tkFile)
593 m_moduleData = new ModuleBuilderData(this, strModuleName, strFileName, tkFile);
594 m_TypeBuilderDict = new Dictionary<string, Type>();
597 // This is a method for changing module and file name of the manifest module (created by default for
599 [System.Security.SecurityCritical] // auto-generated
600 [ResourceExposure(ResourceScope.Machine)]
601 [ResourceConsumption(ResourceScope.Machine)]
602 internal void ModifyModuleName(string name)
604 // Reset the names in the managed ModuleBuilderData
605 m_moduleData.ModifyModuleName(name);
607 // Reset the name in the underlying metadata
608 ModuleBuilder.SetModuleName(GetNativeHandle(), name);
611 internal void SetSymWriter(ISymbolWriter writer)
613 m_iSymWriter = writer;
616 internal object SyncRoot
620 return ContainingAssemblyBuilder.SyncRoot;
626 #region Module Overrides
628 // m_internalModuleBuilder is null iff this is a "internal" ModuleBuilder
629 internal InternalModuleBuilder InternalModule
633 return m_internalModuleBuilder;
637 internal override ModuleHandle GetModuleHandle()
639 return new ModuleHandle(GetNativeHandle());
642 internal RuntimeModule GetNativeHandle()
644 return InternalModule.GetNativeHandle();
647 private static RuntimeModule GetRuntimeModuleFromModule(Module m)
649 ModuleBuilder mb = m as ModuleBuilder;
652 return mb.InternalModule;
655 return m as RuntimeModule;
658 [System.Security.SecurityCritical] // auto-generated
659 private int GetMemberRefToken(MethodBase method, IEnumerable<Type> optionalParameterTypes)
661 Type[] parameterTypes;
664 int cGenericParameters = 0;
666 if (method.IsGenericMethod)
668 if (!method.IsGenericMethodDefinition)
669 throw new InvalidOperationException();
671 cGenericParameters = method.GetGenericArguments().Length;
674 if (optionalParameterTypes != null)
676 if ((method.CallingConvention & CallingConventions.VarArgs) == 0)
678 // Client should not supply optional parameter in default calling convention
679 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAVarArgCallingConvention"));
683 MethodInfo masmi = method as MethodInfo;
685 if (method.DeclaringType.IsGenericType)
687 MethodBase methDef = null; // methodInfo = G<Foo>.M<Bar> ==> methDef = G<T>.M<S>
689 MethodOnTypeBuilderInstantiation motbi;
690 ConstructorOnTypeBuilderInstantiation cotbi;
692 if ((motbi = method as MethodOnTypeBuilderInstantiation) != null)
694 methDef = motbi.m_method;
696 else if ((cotbi = method as ConstructorOnTypeBuilderInstantiation) != null)
698 methDef = cotbi.m_ctor;
700 else if (method is MethodBuilder || method is ConstructorBuilder)
702 // methodInfo must be GenericMethodDefinition; trying to emit G<?>.M<S>
707 Contract.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo);
709 if (method.IsGenericMethod)
711 Contract.Assert(masmi != null);
713 methDef = masmi.GetGenericMethodDefinition();
714 methDef = methDef.Module.ResolveMethod(
715 method.MetadataToken,
716 methDef.DeclaringType != null ? methDef.DeclaringType.GetGenericArguments() : null,
717 methDef.GetGenericArguments());
721 methDef = method.Module.ResolveMethod(
722 method.MetadataToken,
723 method.DeclaringType != null ? method.DeclaringType.GetGenericArguments() : null,
728 parameterTypes = methDef.GetParameterTypes();
729 returnType = MethodBuilder.GetMethodBaseReturnType(methDef);
733 parameterTypes = method.GetParameterTypes();
734 returnType = MethodBuilder.GetMethodBaseReturnType(method);
738 byte[] sigBytes = GetMemberRefSignature(method.CallingConvention, returnType, parameterTypes,
739 optionalParameterTypes, cGenericParameters).InternalGetSignature(out sigLength);
741 if (method.DeclaringType.IsGenericType)
744 byte[] sig = SignatureHelper.GetTypeSigToken(this, method.DeclaringType).InternalGetSignature(out length);
745 tkParent = GetTokenFromTypeSpec(sig, length);
747 else if (!method.Module.Equals(this))
749 // Use typeRef as parent because the method's declaringType lives in a different assembly
750 tkParent = GetTypeToken(method.DeclaringType).Token;
754 // Use methodDef as parent because the method lives in this assembly and its declaringType has no generic arguments
756 tkParent = GetMethodToken(masmi).Token;
758 tkParent = GetConstructorToken(method as ConstructorInfo).Token;
761 return GetMemberRefFromSignature(tkParent, method.Name, sigBytes, sigLength);
764 [System.Security.SecurityCritical] // auto-generated
765 internal SignatureHelper GetMemberRefSignature(CallingConventions call, Type returnType,
766 Type[] parameterTypes, IEnumerable<Type> optionalParameterTypes, int cGenericParameters)
768 int cParams = (parameterTypes == null) ? 0 : parameterTypes.Length;
769 SignatureHelper sig = SignatureHelper.GetMethodSigHelper(this, call, returnType, cGenericParameters);
771 for (int i = 0; i < cParams; i++)
773 sig.AddArgument(parameterTypes[i]);
776 if (optionalParameterTypes != null) {
778 foreach (Type type in optionalParameterTypes)
786 sig.AddArgument(type);
796 #region object overrides
797 public override bool Equals(object obj)
799 return InternalModule.Equals(obj);
801 // Need a dummy GetHashCode to pair with Equals
802 public override int GetHashCode() { return InternalModule.GetHashCode(); }
805 #region ICustomAttributeProvider Members
806 public override Object[] GetCustomAttributes(bool inherit)
808 return InternalModule.GetCustomAttributes(inherit);
811 public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
813 return InternalModule.GetCustomAttributes(attributeType, inherit);
816 public override bool IsDefined(Type attributeType, bool inherit)
818 return InternalModule.IsDefined(attributeType, inherit);
821 public override IList<CustomAttributeData> GetCustomAttributesData()
823 return InternalModule.GetCustomAttributesData();
827 #region Module Overrides
829 public override Type[] GetTypes()
833 return GetTypesNoLock();
837 internal Type[] GetTypesNoLock()
839 int size = m_TypeBuilderDict.Count;
840 Type[] typeList = new Type[m_TypeBuilderDict.Count];
843 foreach (Type builder in m_TypeBuilderDict.Values)
845 EnumBuilder enumBldr = builder as EnumBuilder;
846 TypeBuilder tmpTypeBldr;
848 if (enumBldr != null)
849 tmpTypeBldr = enumBldr.m_typeBuilder;
851 tmpTypeBldr = (TypeBuilder)builder;
853 // We should not return TypeBuilders.
854 // Otherwise anyone can emit code in it.
855 if (tmpTypeBldr.IsCreated())
856 typeList[i++] = tmpTypeBldr.UnderlyingSystemType;
858 typeList[i++] = builder;
864 [System.Runtime.InteropServices.ComVisible(true)]
865 public override Type GetType(String className)
867 return GetType(className, false, false);
870 [System.Runtime.InteropServices.ComVisible(true)]
871 public override Type GetType(String className, bool ignoreCase)
873 return GetType(className, false, ignoreCase);
876 [System.Runtime.InteropServices.ComVisible(true)]
877 public override Type GetType(String className, bool throwOnError, bool ignoreCase)
881 return GetTypeNoLock(className, throwOnError, ignoreCase);
885 private Type GetTypeNoLock(String className, bool throwOnError, bool ignoreCase)
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[,]".
894 // Module.GetType() will verify className.
895 Type baseType = InternalModule.GetType(className, throwOnError, ignoreCase);
896 if (baseType != null)
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;
906 while (startIndex <= className.Length)
908 // Are there any possible special characters left?
909 int i = className.IndexOfAny(new char[]{'[', '*', '&'}, startIndex);
912 // No, type name is simple.
913 baseName = className;
918 // Found a potential special character, but it might be escaped.
920 for (int j = i - 1; j >= 0 && className[j] == '\\'; j--)
923 // Odd number of slashes indicates escaping.
924 if (slashes % 2 == 1)
930 // Found the end of the base type name.
931 baseName = className.Substring(0, i);
932 parameters = className.Substring(i);
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)
940 baseName = className;
944 baseName = baseName.Replace(@"\\",@"\").Replace(@"\[",@"[").Replace(@"\*",@"*").Replace(@"\&",@"&");
946 if (parameters != null)
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!
951 baseType = InternalModule.GetType(baseName, false, ignoreCase);
954 if (baseType == null)
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)
961 // now goto Assembly level to find the type.
963 List<ModuleBuilder> modList;
965 modList = ContainingAssemblyBuilder.m_assemblyData.m_moduleBuilderList;
966 size = modList.Count;
967 for (int i = 0; i < size && baseType == null; i++)
969 ModuleBuilder mBuilder = modList[i];
970 baseType = mBuilder.FindTypeBuilderWithName(baseName, ignoreCase);
973 if (baseType == null)
977 if (parameters == null)
980 return GetType(parameters, baseType);
983 public override String FullyQualifiedName
986 [System.Security.SecurityCritical] // auto-generated
988 [System.Security.SecuritySafeCritical]
990 [ResourceExposure(ResourceScope.Machine)]
991 [ResourceConsumption(ResourceScope.Machine)]
994 String fullyQualifiedName = m_moduleData.m_strFileName;
995 if (fullyQualifiedName == null)
997 if (ContainingAssemblyBuilder.m_assemblyData.m_strDir != null)
999 fullyQualifiedName = Path.Combine(ContainingAssemblyBuilder.m_assemblyData.m_strDir, fullyQualifiedName);
1000 fullyQualifiedName = Path.UnsafeGetFullPath(fullyQualifiedName);
1003 if (ContainingAssemblyBuilder.m_assemblyData.m_strDir != null && fullyQualifiedName != null)
1005 new FileIOPermission( FileIOPermissionAccess.PathDiscovery, fullyQualifiedName ).Demand();
1008 return fullyQualifiedName;
1012 public override byte[] ResolveSignature(int metadataToken)
1014 return InternalModule.ResolveSignature(metadataToken);
1017 public override MethodBase ResolveMethod(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
1019 return InternalModule.ResolveMethod(metadataToken, genericTypeArguments, genericMethodArguments);
1022 public override FieldInfo ResolveField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
1024 return InternalModule.ResolveField(metadataToken, genericTypeArguments, genericMethodArguments);
1027 public override Type ResolveType(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
1029 return InternalModule.ResolveType(metadataToken, genericTypeArguments, genericMethodArguments);
1032 public override MemberInfo ResolveMember(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
1034 return InternalModule.ResolveMember(metadataToken, genericTypeArguments, genericMethodArguments);
1037 public override string ResolveString(int metadataToken)
1039 return InternalModule.ResolveString(metadataToken);
1042 public override void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine)
1044 InternalModule.GetPEKind(out peKind, out machine);
1047 public override int MDStreamVersion
1051 return InternalModule.MDStreamVersion;
1055 public override Guid ModuleVersionId
1059 return InternalModule.ModuleVersionId;
1063 public override int MetadataToken
1067 return InternalModule.MetadataToken;
1071 public override bool IsResource()
1073 return InternalModule.IsResource();
1076 public override FieldInfo[] GetFields(BindingFlags bindingFlags)
1078 return InternalModule.GetFields(bindingFlags);
1081 public override FieldInfo GetField(String name, BindingFlags bindingAttr)
1083 return InternalModule.GetField(name, bindingAttr);
1086 public override MethodInfo[] GetMethods(BindingFlags bindingFlags)
1088 return InternalModule.GetMethods(bindingFlags);
1091 protected override MethodInfo GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder,
1092 CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
1094 // Cannot call InternalModule.GetMethods because it doesn't allow types to be null
1095 return InternalModule.GetMethodInternal(name, bindingAttr, binder, callConvention, types, modifiers);
1098 public override String ScopeName
1102 return InternalModule.ScopeName;
1106 [ResourceExposure(ResourceScope.None)]
1107 [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
1108 public override String Name
1112 return InternalModule.Name;
1116 public override Assembly Assembly
1121 return m_assemblyBuilder;
1125 #if FEATURE_X509 && FEATURE_CAS_POLICY
1126 public override System.Security.Cryptography.X509Certificates.X509Certificate GetSignerCertificate()
1128 return InternalModule.GetSignerCertificate();
1130 #endif // FEATURE_X509 && FEATURE_CAS_POLICY
1133 #region Public Members
1136 [System.Security.SecuritySafeCritical] // auto-generated
1137 public TypeBuilder DefineType(String name)
1139 Contract.Ensures(Contract.Result<TypeBuilder>() != null);
1143 return DefineTypeNoLock(name, TypeAttributes.NotPublic, null, null, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
1147 [System.Security.SecuritySafeCritical] // auto-generated
1148 public TypeBuilder DefineType(String name, TypeAttributes attr)
1150 Contract.Ensures(Contract.Result<TypeBuilder>() != null);
1154 return DefineTypeNoLock(name, attr, null, null, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
1158 [System.Security.SecuritySafeCritical] // auto-generated
1159 public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent)
1161 Contract.Ensures(Contract.Result<TypeBuilder>() != null);
1165 // Why do we only call CheckContext here? Why don't we call it in the other overloads?
1166 CheckContext(parent);
1168 return DefineTypeNoLock(name, attr, parent, null, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
1173 [System.Security.SecurityCritical] // auto-generated
1175 [System.Security.SecuritySafeCritical]
1177 public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent, int typesize)
1179 Contract.Ensures(Contract.Result<TypeBuilder>() != null);
1183 return DefineTypeNoLock(name, attr, parent, null, PackingSize.Unspecified, typesize);
1188 [System.Security.SecurityCritical] // auto-generated
1190 [System.Security.SecuritySafeCritical]
1192 public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent, PackingSize packingSize, int typesize)
1194 Contract.Ensures(Contract.Result<TypeBuilder>() != null);
1198 return DefineTypeNoLock(name, attr, parent, null, packingSize, typesize);
1202 [System.Security.SecuritySafeCritical] // auto-generated
1203 [System.Runtime.InteropServices.ComVisible(true)]
1204 public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent, Type[] interfaces)
1206 Contract.Ensures(Contract.Result<TypeBuilder>() != null);
1210 return DefineTypeNoLock(name, attr, parent, interfaces, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
1214 [System.Security.SecurityCritical] // auto-generated
1215 private TypeBuilder DefineTypeNoLock(String name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packingSize, int typesize)
1217 Contract.Ensures(Contract.Result<TypeBuilder>() != null);
1219 return new TypeBuilder(name, attr, parent, interfaces, this, packingSize, typesize, null); ;
1223 [System.Security.SecurityCritical] // auto-generated
1225 [System.Security.SecuritySafeCritical]
1227 public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent, PackingSize packsize)
1229 Contract.Ensures(Contract.Result<TypeBuilder>() != null);
1233 return DefineTypeNoLock(name, attr, parent, packsize);
1237 [System.Security.SecurityCritical] // auto-generated
1238 private TypeBuilder DefineTypeNoLock(String name, TypeAttributes attr, Type parent, PackingSize packsize)
1240 Contract.Ensures(Contract.Result<TypeBuilder>() != null);
1242 return new TypeBuilder(name, attr, parent, null, this, packsize, TypeBuilder.UnspecifiedTypeSize, null);
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)
1254 Contract.Ensures(Contract.Result<EnumBuilder>() != null);
1256 CheckContext(underlyingType);
1259 EnumBuilder enumBuilder = DefineEnumNoLock(name, visibility, underlyingType);
1261 // This enum is not generic, nested, and cannot have any element type.
1262 Contract.Assert(name == enumBuilder.FullName);
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;
1272 [System.Security.SecurityCritical] // auto-generated
1273 private EnumBuilder DefineEnumNoLock(String name, TypeAttributes visibility, Type underlyingType)
1275 Contract.Ensures(Contract.Result<EnumBuilder>() != null);
1277 return new EnumBuilder(name, underlyingType, visibility, this);
1282 #region Define Resource
1283 #if !FEATURE_CORECLR
1284 public IResourceWriter DefineResource(String name, String description)
1286 // Define embedded managed resource to be stored in this module
1287 Contract.Ensures(Contract.Result<IResourceWriter>() != null);
1289 return DefineResource(name, description, ResourceAttributes.Public);
1292 public IResourceWriter DefineResource(String name, String description, ResourceAttributes attribute)
1294 // Define embedded managed resource to be stored in this module
1295 Contract.Ensures(Contract.Result<IResourceWriter>() != null);
1299 return DefineResourceNoLock(name, description, attribute);
1303 private IResourceWriter DefineResourceNoLock(String name, String description, ResourceAttributes attribute)
1305 // Define embedded managed resource to be stored in this module
1308 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadResourceContainer"));
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();
1317 if (m_assemblyBuilder.IsPersistable())
1319 m_assemblyBuilder.m_assemblyData.CheckResNameConflict(name);
1321 MemoryStream stream = new MemoryStream();
1322 ResourceWriter resWriter = new ResourceWriter(stream);
1323 ResWriterData resWriterData = new ResWriterData( resWriter, stream, name, String.Empty, String.Empty, attribute);
1325 // chain it to the embedded resource list
1326 resWriterData.m_nextResWriter = m_moduleData.m_embeddedRes;
1327 m_moduleData.m_embeddedRes = resWriterData;
1332 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadResourceContainer"));
1335 #endif // !FEATURE_CORECLR
1338 [System.Security.SecurityCritical] // auto-generated
1340 public void DefineManifestResource(String name, Stream stream, ResourceAttributes attribute)
1343 throw new ArgumentNullException("name");
1346 throw new ArgumentNullException("stream");
1347 Contract.EndContractBlock();
1349 // Define embedded managed resource to be stored in this module
1353 DefineManifestResourceNoLock(name, stream, attribute);
1357 private void DefineManifestResourceNoLock(String name, Stream stream, ResourceAttributes attribute)
1359 // Define embedded managed resource to be stored in this module
1361 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadResourceContainer"));
1362 Contract.EndContractBlock();
1364 #if !FEATURE_CORECLR
1366 throw new ArgumentNullException("name");
1367 if (name.Length == 0)
1368 throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name");
1370 if (m_assemblyBuilder.IsPersistable())
1372 m_assemblyBuilder.m_assemblyData.CheckResNameConflict(name);
1374 ResWriterData resWriterData = new ResWriterData( null, stream, name, String.Empty, String.Empty, attribute);
1376 // chain it to the embedded resource list
1377 resWriterData.m_nextResWriter = m_moduleData.m_embeddedRes;
1378 m_moduleData.m_embeddedRes = resWriterData;
1382 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadResourceContainer"));
1384 #endif // !FEATURE_CORECLR
1389 [System.Security.SecurityCritical] // auto-generated
1391 public void DefineUnmanagedResource(Byte[] resource)
1395 DefineUnmanagedResourceInternalNoLock(resource);
1399 internal void DefineUnmanagedResourceInternalNoLock(Byte[] resource)
1401 if (resource == null)
1402 throw new ArgumentNullException("resource");
1403 Contract.EndContractBlock();
1405 if (m_moduleData.m_strResourceFileName != null || m_moduleData.m_resourceBytes != null)
1406 throw new ArgumentException(Environment.GetResourceString("Argument_NativeResourceAlreadyDefined"));
1408 m_moduleData.m_resourceBytes = new byte[resource.Length];
1409 System.Array.Copy(resource, m_moduleData.m_resourceBytes, resource.Length);
1413 [System.Security.SecurityCritical] // auto-generated
1415 [System.Security.SecuritySafeCritical]
1417 [ResourceExposure(ResourceScope.Machine)]
1418 [ResourceConsumption(ResourceScope.Machine)]
1419 public void DefineUnmanagedResource(String resourceFileName)
1423 DefineUnmanagedResourceFileInternalNoLock(resourceFileName);
1427 [System.Security.SecurityCritical] // auto-generated
1428 [ResourceExposure(ResourceScope.Machine)]
1429 [ResourceConsumption(ResourceScope.Machine)]
1430 internal void DefineUnmanagedResourceFileInternalNoLock(String resourceFileName)
1432 if (resourceFileName == null)
1433 throw new ArgumentNullException("resourceFileName");
1434 Contract.EndContractBlock();
1436 if (m_moduleData.m_resourceBytes != null || m_moduleData.m_strResourceFileName != null)
1437 throw new ArgumentException(Environment.GetResourceString("Argument_NativeResourceAlreadyDefined"));
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();
1444 new EnvironmentPermission(PermissionState.Unrestricted).Assert();
1447 if (File.UnsafeExists(resourceFileName) == false)
1448 throw new FileNotFoundException(Environment.GetResourceString(
1449 "IO.FileNotFound_FileName",
1450 resourceFileName), resourceFileName);
1454 CodeAccessPermission.RevertAssert();
1457 m_moduleData.m_strResourceFileName = strFullFileName;
1461 #region Define Global Method
1462 public MethodBuilder DefineGlobalMethod(String name, MethodAttributes attributes, Type returnType, Type[] parameterTypes)
1464 Contract.Ensures(Contract.Result<MethodBuilder>() != null);
1466 return DefineGlobalMethod(name, attributes, CallingConventions.Standard, returnType, parameterTypes);
1469 public MethodBuilder DefineGlobalMethod(String name, MethodAttributes attributes, CallingConventions callingConvention,
1470 Type returnType, Type[] parameterTypes)
1472 Contract.Ensures(Contract.Result<MethodBuilder>() != null);
1474 return DefineGlobalMethod(name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null);
1477 public MethodBuilder DefineGlobalMethod(String name, MethodAttributes attributes, CallingConventions callingConvention,
1478 Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers,
1479 Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
1483 return DefineGlobalMethodNoLock(name, attributes, callingConvention, returnType,
1484 requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers,
1485 parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
1489 private MethodBuilder DefineGlobalMethodNoLock(String name, MethodAttributes attributes, CallingConventions callingConvention,
1490 Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers,
1491 Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
1493 if (m_moduleData.m_fGlobalBeenCreated == true)
1494 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_GlobalsHaveBeenCreated"));
1497 throw new ArgumentNullException("name");
1499 if (name.Length == 0)
1500 throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name");
1502 if ((attributes & MethodAttributes.Static) == 0)
1503 throw new ArgumentException(Environment.GetResourceString("Argument_GlobalFunctionHasToBeStatic"));
1504 Contract.Ensures(Contract.Result<MethodBuilder>() != null);
1505 Contract.EndContractBlock();
1507 CheckContext(returnType);
1508 CheckContext(requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, parameterTypes);
1509 CheckContext(requiredParameterTypeCustomModifiers);
1510 CheckContext(optionalParameterTypeCustomModifiers);
1512 m_moduleData.m_fHasGlobal = true;
1514 return m_moduleData.m_globalTypeBuilder.DefineMethod(name, attributes, callingConvention,
1515 returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers,
1516 parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
1520 [System.Security.SecurityCritical] // auto-generated
1522 public MethodBuilder DefinePInvokeMethod(String name, String dllName, MethodAttributes attributes,
1523 CallingConventions callingConvention, Type returnType, Type[] parameterTypes,
1524 CallingConvention nativeCallConv, CharSet nativeCharSet)
1526 Contract.Ensures(Contract.Result<MethodBuilder>() != null);
1528 return DefinePInvokeMethod(name, dllName, name, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet);
1532 [System.Security.SecurityCritical] // auto-generated
1534 public MethodBuilder DefinePInvokeMethod(String name, String dllName, String entryName, MethodAttributes attributes,
1535 CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv,
1536 CharSet nativeCharSet)
1538 Contract.Ensures(Contract.Result<MethodBuilder>() != null);
1542 return DefinePInvokeMethodNoLock(name, dllName, entryName, attributes, callingConvention,
1543 returnType, parameterTypes, nativeCallConv, nativeCharSet);
1548 [System.Security.SecurityCritical] // auto-generated
1550 private MethodBuilder DefinePInvokeMethodNoLock(String name, String dllName, String entryName, MethodAttributes attributes,
1551 CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv,
1552 CharSet nativeCharSet)
1554 //Global methods must be static.
1555 if ((attributes & MethodAttributes.Static) == 0)
1557 throw new ArgumentException(Environment.GetResourceString("Argument_GlobalFunctionHasToBeStatic"));
1559 Contract.Ensures(Contract.Result<MethodBuilder>() != null);
1560 Contract.EndContractBlock();
1562 CheckContext(returnType);
1563 CheckContext(parameterTypes);
1565 m_moduleData.m_fHasGlobal = true;
1566 return m_moduleData.m_globalTypeBuilder.DefinePInvokeMethod(name, dllName, entryName, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet);
1569 public void CreateGlobalFunctions()
1573 CreateGlobalFunctionsNoLock();
1577 private void CreateGlobalFunctionsNoLock()
1579 if (m_moduleData.m_fGlobalBeenCreated)
1581 // cannot create globals twice
1582 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotADebugModule"));
1584 m_moduleData.m_globalTypeBuilder.CreateType();
1585 m_moduleData.m_fGlobalBeenCreated = true;
1593 [System.Security.SecurityCritical] // auto-generated
1595 public FieldBuilder DefineInitializedData(String name, byte[] data, FieldAttributes attributes)
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);
1604 return DefineInitializedDataNoLock(name, data, attributes);
1609 [System.Security.SecurityCritical] // auto-generated
1611 private FieldBuilder DefineInitializedDataNoLock(String name, byte[] data, FieldAttributes attributes)
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)
1618 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_GlobalsHaveBeenCreated"));
1620 Contract.Ensures(Contract.Result<FieldBuilder>() != null);
1621 Contract.EndContractBlock();
1623 m_moduleData.m_fHasGlobal = true;
1624 return m_moduleData.m_globalTypeBuilder.DefineInitializedData(name, data, attributes);
1628 [System.Security.SecurityCritical] // auto-generated
1630 public FieldBuilder DefineUninitializedData(String name, int size, FieldAttributes attributes)
1632 Contract.Ensures(Contract.Result<FieldBuilder>() != null);
1636 return DefineUninitializedDataNoLock(name, size, attributes);
1641 [System.Security.SecurityCritical] // auto-generated
1643 private FieldBuilder DefineUninitializedDataNoLock(String name, int size, FieldAttributes attributes)
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.
1649 if (m_moduleData.m_fGlobalBeenCreated == true)
1651 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_GlobalsHaveBeenCreated"));
1653 Contract.Ensures(Contract.Result<FieldBuilder>() != null);
1654 Contract.EndContractBlock();
1656 m_moduleData.m_fHasGlobal = true;
1657 return m_moduleData.m_globalTypeBuilder.DefineUninitializedData(name, size, attributes);
1663 // For a generic type definition, we should return the token for the generic type definition itself in two cases:
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)
1670 return GetTypeTokenInternal(type, false);
1673 [System.Security.SecurityCritical] // auto-generated
1674 private TypeToken GetTypeTokenInternal(Type type, bool getGenericDefinition)
1678 return GetTypeTokenWorkerNoLock(type, getGenericDefinition);
1682 [System.Security.SecuritySafeCritical] // auto-generated
1683 public TypeToken GetTypeToken(Type type)
1685 return GetTypeTokenInternal(type, true);
1688 [System.Security.SecurityCritical] // auto-generated
1689 [ResourceExposure(ResourceScope.None)]
1690 [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
1691 private TypeToken GetTypeTokenWorkerNoLock(Type type, bool getGenericDefinition)
1694 throw new ArgumentNullException("type");
1695 Contract.EndContractBlock();
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!!!
1710 throw new ArgumentException(Environment.GetResourceString("Argument_CannotGetTypeTokenForByRef"));
1712 if ((type.IsGenericType && (!type.IsGenericTypeDefinition || !getGenericDefinition)) ||
1713 type.IsGenericParameter ||
1718 byte[] sig = SignatureHelper.GetTypeSigToken(this, type).InternalGetSignature(out length);
1719 return new TypeToken(GetTokenFromTypeSpec(sig, length));
1722 Module refedModule = type.Module;
1724 if (refedModule.Equals(this))
1726 // no need to do anything additional other than defining the TypeRef Token
1727 TypeBuilder typeBuilder = null;
1728 GenericTypeParameterBuilder paramBuilder = null;
1730 EnumBuilder enumBuilder = type as EnumBuilder;
1731 if (enumBuilder != null)
1732 typeBuilder = enumBuilder.m_typeBuilder;
1734 typeBuilder = type as TypeBuilder;
1736 if (typeBuilder != null)
1738 // optimization: if the type is defined in this module,
1739 // just return the token
1741 return typeBuilder.TypeToken;
1743 else if ((paramBuilder = type as GenericTypeParameterBuilder) != null)
1745 return new TypeToken(paramBuilder.MetadataTokenInternal);
1748 return new TypeToken(GetTypeRefNested(type, this, String.Empty));
1751 // After this point, the referenced module is not the same as the referencing
1754 ModuleBuilder refedModuleBuilder = refedModule as ModuleBuilder;
1756 #if !FEATURE_CORECLR
1757 Contract.Assert(refedModuleBuilder != null || refedModule is RuntimeModule);
1758 bool isRefedModuleTransient = refedModuleBuilder != null ?
1759 refedModuleBuilder.IsTransient() :
1760 ((RuntimeModule)refedModule).IsTransientInternal();
1762 // We cannot have a non-transient module referencing to a transient module.
1763 if (IsTransient() == false && isRefedModuleTransient)
1765 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadTransientModuleReference"));
1767 #endif // !FEATURE_CORECLR
1769 String strRefedModuleFileName = String.Empty;
1770 if (refedModule.Assembly.Equals(this.Assembly))
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)
1780 refedModuleBuilder = this.ContainingAssemblyBuilder.GetModuleBuilder((InternalModuleBuilder)refedModule);
1782 strRefedModuleFileName = refedModuleBuilder.m_moduleData.m_strFileName;
1785 return new TypeToken(GetTypeRefNested(type, refedModule, strRefedModuleFileName));
1788 public TypeToken GetTypeToken(String name)
1790 // Return a token for the class relative to the Module.
1791 // Module.GetType() verifies name
1793 // Unfortunately, we will need to load the Type and then call GetTypeToken in
1794 // order to correctly track the assembly reference information.
1796 return GetTypeToken(InternalModule.GetType(name, false, true));
1799 [System.Security.SecuritySafeCritical] // auto-generated
1800 public MethodToken GetMethodToken(MethodInfo method)
1804 return GetMethodTokenNoLock(method, true);
1808 [System.Security.SecurityCritical] // auto-generated
1809 internal MethodToken GetMethodTokenInternal(MethodInfo method)
1813 return GetMethodTokenNoLock(method, false);
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)
1824 // Return a MemberRef token if MethodInfo is not defined in this module. Or
1825 // return the MethodDef token.
1827 throw new ArgumentNullException("method");
1828 Contract.EndContractBlock();
1833 SymbolMethod symMethod = null;
1834 MethodBuilder methBuilder = null;
1836 if ( (methBuilder = method as MethodBuilder) != null )
1838 int methodToken = methBuilder.MetadataTokenInternal;
1839 if (method.Module.Equals(this))
1840 return new MethodToken(methodToken);
1842 if (method.DeclaringType == null)
1843 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotImportGlobalFromDifferentModule"));
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);
1849 else if (method is MethodOnTypeBuilderInstantiation)
1851 return new MethodToken(GetMemberRefToken(method, null));
1853 else if ((symMethod = method as SymbolMethod) != null)
1855 if (symMethod.GetModule() == this)
1856 return symMethod.GetToken();
1858 // form the method token
1859 return symMethod.GetToken(this);
1863 Type declaringType = method.DeclaringType;
1865 // We need to get the TypeRef tokens
1866 if (declaringType == null)
1867 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotImportGlobalFromDifferentModule"));
1869 RuntimeMethodInfo rtMeth = null;
1871 if (declaringType.IsArray == true)
1873 // use reflection to build signature to work around the E_T_VAR problem in EEClass
1874 ParameterInfo[] paramInfo = method.GetParameters();
1876 Type[] tt = new Type[paramInfo.Length];
1878 for (int i = 0; i < paramInfo.Length; i++)
1879 tt[i] = paramInfo[i].ParameterType;
1881 return GetArrayMethodToken(declaringType, method.Name, method.CallingConvention, method.ReturnType, tt);
1883 else if ( (rtMeth = method as RuntimeMethodInfo) != null )
1885 tr = getGenericTypeDefinition ? GetTypeToken(method.DeclaringType).Token : GetTypeTokenInternal(method.DeclaringType).Token;
1886 mr = GetMemberRefOfMethodInfo(tr, rtMeth);
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();
1894 Type[] parameterTypes = new Type[parameters.Length];
1895 Type[][] requiredCustomModifiers = new Type[parameterTypes.Length][];
1896 Type[][] optionalCustomModifiers = new Type[parameterTypes.Length][];
1898 for (int i = 0; i < parameters.Length; i++)
1900 parameterTypes[i] = parameters[i].ParameterType;
1901 requiredCustomModifiers[i] = parameters[i].GetRequiredCustomModifiers();
1902 optionalCustomModifiers[i] = parameters[i].GetOptionalCustomModifiers();
1905 tr = getGenericTypeDefinition ? GetTypeToken(method.DeclaringType).Token : GetTypeTokenInternal(method.DeclaringType).Token;
1907 SignatureHelper sigHelp;
1911 sigHelp = SignatureHelper.GetMethodSigHelper(
1912 this, method.CallingConvention, method.ReturnType,
1913 method.ReturnParameter.GetRequiredCustomModifiers(), method.ReturnParameter.GetOptionalCustomModifiers(),
1914 parameterTypes, requiredCustomModifiers, optionalCustomModifiers);
1916 catch(NotImplementedException)
1918 // Legacy code deriving from MethodInfo may not have implemented ReturnParameter.
1919 sigHelp = SignatureHelper.GetMethodSigHelper(this, method.ReturnType, parameterTypes);
1923 byte[] sigBytes = sigHelp.InternalGetSignature(out length);
1924 mr = GetMemberRefFromSignature(tr, method.Name, sigBytes, length);
1928 return new MethodToken(mr);
1931 [System.Security.SecuritySafeCritical] // auto-generated
1932 public MethodToken GetConstructorToken(ConstructorInfo constructor, IEnumerable<Type> optionalParameterTypes)
1934 if (constructor == null)
1936 throw new ArgumentNullException("constructor");
1941 // useMethodDef is not applicable - constructors aren't generic
1942 return new MethodToken(GetMethodTokenInternal(constructor, optionalParameterTypes, false));
1946 [System.Security.SecuritySafeCritical] // auto-generated
1947 public MethodToken GetMethodToken(MethodInfo method, IEnumerable<Type> optionalParameterTypes)
1951 throw new ArgumentNullException("method");
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.
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.
1964 return new MethodToken(GetMethodTokenInternal(method, optionalParameterTypes, true));
1968 [System.Security.SecurityCritical] // auto-generated
1969 internal int GetMethodTokenInternal(MethodBase method, IEnumerable<Type> optionalParameterTypes, bool useMethodDef)
1972 MethodInfo methodInfo = method as MethodInfo;
1974 if (method.IsGenericMethod)
1976 // Constructors cannot be generic.
1977 Contract.Assert(methodInfo != null);
1979 // Given M<Bar> unbind to M<S>
1980 MethodInfo methodInfoUnbound = methodInfo;
1981 bool isGenericMethodDef = methodInfo.IsGenericMethodDefinition;
1983 if (!isGenericMethodDef)
1985 methodInfoUnbound = methodInfo.GetGenericMethodDefinition();
1988 if (!this.Equals(methodInfoUnbound.Module)
1989 || (methodInfoUnbound.DeclaringType != null && methodInfoUnbound.DeclaringType.IsGenericType))
1991 tk = GetMemberRefToken(methodInfoUnbound, null);
1995 tk = GetMethodTokenInternal(methodInfoUnbound).Token;
1998 // For Ldtoken, Ldftn, and Ldvirtftn, we should emit the method def/ref token for a generic method definition.
1999 if (isGenericMethodDef && useMethodDef)
2004 // Create signature of method instantiation M<Bar>
2006 byte[] sigBytes = SignatureHelper.GetMethodSpecSigHelper(
2007 this, methodInfo.GetGenericArguments()).InternalGetSignature(out sigLength);
2009 // Create MethodSepc M<Bar> with parent G?.M<S>
2010 tk = TypeBuilder.DefineMethodSpec(this.GetNativeHandle(), tk, sigBytes, sigLength);
2014 if (((method.CallingConvention & CallingConventions.VarArgs) == 0) &&
2015 (method.DeclaringType == null || !method.DeclaringType.IsGenericType))
2017 if (methodInfo != null)
2019 tk = GetMethodTokenInternal(methodInfo).Token;
2023 tk = GetConstructorToken(method as ConstructorInfo).Token;
2028 tk = GetMemberRefToken(method, optionalParameterTypes);
2035 [System.Security.SecuritySafeCritical] // auto-generated
2036 public MethodToken GetArrayMethodToken(Type arrayClass, String methodName, CallingConventions callingConvention,
2037 Type returnType, Type[] parameterTypes)
2041 return GetArrayMethodTokenNoLock(arrayClass, methodName, callingConvention, returnType, parameterTypes);
2045 [System.Security.SecurityCritical] // auto-generated
2046 private MethodToken GetArrayMethodTokenNoLock(Type arrayClass, String methodName, CallingConventions callingConvention,
2047 Type returnType, Type[] parameterTypes)
2049 if (arrayClass == null)
2050 throw new ArgumentNullException("arrayClass");
2052 if (methodName == null)
2053 throw new ArgumentNullException("methodName");
2055 if (methodName.Length == 0)
2056 throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "methodName");
2058 if (arrayClass.IsArray == false)
2059 throw new ArgumentException(Environment.GetResourceString("Argument_HasToBeArrayClass"));
2060 Contract.EndContractBlock();
2062 CheckContext(returnType, arrayClass);
2063 CheckContext(parameterTypes);
2065 // Return a token for the MethodInfo for a method on an Array. This is primarily
2066 // used to get the LoadElementAddress method.
2070 SignatureHelper sigHelp = SignatureHelper.GetMethodSigHelper(
2071 this, callingConvention, returnType, null, null, parameterTypes, null, null);
2073 byte[] sigBytes = sigHelp.InternalGetSignature(out length);
2075 TypeToken typeSpec = GetTypeTokenInternal(arrayClass);
2077 return new MethodToken(GetArrayMethodToken(GetNativeHandle(),
2078 typeSpec.Token, methodName, sigBytes, length));
2081 [System.Security.SecuritySafeCritical] // auto-generated
2082 public MethodInfo GetArrayMethod(Type arrayClass, String methodName, CallingConventions callingConvention,
2083 Type returnType, Type[] parameterTypes)
2085 CheckContext(returnType, arrayClass);
2086 CheckContext(parameterTypes);
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.
2093 MethodToken token = GetArrayMethodToken(arrayClass, methodName, callingConvention, returnType, parameterTypes);
2095 return new SymbolMethod(this, token, arrayClass, methodName, callingConvention, returnType, parameterTypes);
2098 [System.Security.SecuritySafeCritical] // auto-generated
2099 [System.Runtime.InteropServices.ComVisible(true)]
2100 public MethodToken GetConstructorToken(ConstructorInfo con)
2102 // Return a token for the ConstructorInfo relative to the Module.
2103 return InternalGetConstructorToken(con, false);
2106 [System.Security.SecuritySafeCritical] // auto-generated
2107 public FieldToken GetFieldToken(FieldInfo field)
2111 return GetFieldTokenNoLock(field);
2115 [System.Security.SecurityCritical] // auto-generated
2116 private FieldToken GetFieldTokenNoLock(FieldInfo field)
2118 if (field == null) {
2119 throw new ArgumentNullException("con");
2121 Contract.EndContractBlock();
2126 FieldBuilder fdBuilder = null;
2127 RuntimeFieldInfo rtField = null;
2128 FieldOnTypeBuilderInstantiation fOnTB = null;
2130 if ((fdBuilder = field as FieldBuilder) != null)
2132 if (field.DeclaringType != null && field.DeclaringType.IsGenericType)
2135 byte[] sig = SignatureHelper.GetTypeSigToken(this, field.DeclaringType).InternalGetSignature(out length);
2136 tr = GetTokenFromTypeSpec(sig, length);
2137 mr = GetMemberRef(this, tr, fdBuilder.GetToken().Token);
2139 else if (fdBuilder.Module.Equals(this))
2141 // field is defined in the same module
2142 return fdBuilder.GetToken();
2146 // field is defined in a different module
2147 if (field.DeclaringType == null)
2149 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotImportGlobalFromDifferentModule"));
2151 tr = GetTypeTokenInternal(field.DeclaringType).Token;
2152 mr = GetMemberRef(field.ReflectedType.Module, tr, fdBuilder.GetToken().Token);
2155 else if ( (rtField = field as RuntimeFieldInfo) != null)
2157 // FieldInfo is not an dynamic field
2159 // We need to get the TypeRef tokens
2160 if (field.DeclaringType == null)
2162 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotImportGlobalFromDifferentModule"));
2165 if (field.DeclaringType != null && field.DeclaringType.IsGenericType)
2168 byte[] sig = SignatureHelper.GetTypeSigToken(this, field.DeclaringType).InternalGetSignature(out length);
2169 tr = GetTokenFromTypeSpec(sig, length);
2170 mr = GetMemberRefOfFieldInfo(tr, field.DeclaringType.GetTypeHandleInternal(), rtField);
2174 tr = GetTypeTokenInternal(field.DeclaringType).Token;
2175 mr = GetMemberRefOfFieldInfo(tr, field.DeclaringType.GetTypeHandleInternal(), rtField);
2178 else if ( (fOnTB = field as FieldOnTypeBuilderInstantiation) != null)
2180 FieldInfo fb = fOnTB.FieldInfo;
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);
2188 // user defined FieldInfo
2189 tr = GetTypeTokenInternal(field.ReflectedType).Token;
2191 SignatureHelper sigHelp = SignatureHelper.GetFieldSigHelper(this);
2193 sigHelp.AddArgument(field.FieldType, field.GetRequiredCustomModifiers(), field.GetOptionalCustomModifiers());
2196 byte[] sigBytes = sigHelp.InternalGetSignature(out length);
2198 mr = GetMemberRefFromSignature(tr, field.Name, sigBytes, length);
2201 return new FieldToken(mr, field.GetType());
2204 [System.Security.SecuritySafeCritical] // auto-generated
2205 public StringToken GetStringConstant(String str)
2209 throw new ArgumentNullException("str");
2211 Contract.EndContractBlock();
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));
2218 [System.Security.SecuritySafeCritical] // auto-generated
2219 public SignatureToken GetSignatureToken(SignatureHelper sigHelper)
2221 // Define signature token given a signature helper. This will define a metadata
2222 // token for the signature described by SignatureHelper.
2224 if (sigHelper == null)
2226 throw new ArgumentNullException("sigHelper");
2228 Contract.EndContractBlock();
2233 // get the signature in byte form
2234 sigBytes = sigHelper.InternalGetSignature(out sigLength);
2235 return new SignatureToken(TypeBuilder.GetTokenFromSig(GetNativeHandle(), sigBytes, sigLength), this);
2237 [System.Security.SecuritySafeCritical] // auto-generated
2238 public SignatureToken GetSignatureToken(byte[] sigBytes, int sigLength)
2240 if (sigBytes == null)
2241 throw new ArgumentNullException("sigBytes");
2242 Contract.EndContractBlock();
2244 byte[] localSigBytes = new byte[sigBytes.Length];
2245 Array.Copy(sigBytes, localSigBytes, sigBytes.Length);
2247 return new SignatureToken(TypeBuilder.GetTokenFromSig(GetNativeHandle(), localSigBytes, sigLength), this);
2255 [System.Security.SecurityCritical] // auto-generated
2257 [System.Security.SecuritySafeCritical]
2259 [System.Runtime.InteropServices.ComVisible(true)]
2260 public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
2263 throw new ArgumentNullException("con");
2264 if (binaryAttribute == null)
2265 throw new ArgumentNullException("binaryAttribute");
2266 Contract.EndContractBlock();
2268 TypeBuilder.DefineCustomAttribute(
2270 1, // This is hard coding the module token to 1
2271 this.GetConstructorToken(con).Token,
2276 [System.Security.SecuritySafeCritical] // auto-generated
2277 public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
2279 if (customBuilder == null)
2281 throw new ArgumentNullException("customBuilder");
2283 Contract.EndContractBlock();
2285 customBuilder.CreateCustomAttribute(this, 1); // This is hard coding the module token to 1
2288 // This API returns the symbol writer being used to write debug symbols for this
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.
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.
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()
2319 return m_iSymWriter;
2323 [System.Security.SecuritySafeCritical]
2325 public ISymbolDocumentWriter DefineDocument(String url, Guid language, Guid languageVendor, Guid documentType)
2327 // url cannot be null but can be an empty string
2329 throw new ArgumentNullException("url");
2330 Contract.EndContractBlock();
2334 return DefineDocumentNoLock(url, language, languageVendor, documentType);
2339 [System.Security.SecurityCritical] // auto-generated
2341 private ISymbolDocumentWriter DefineDocumentNoLock(String url, Guid language, Guid languageVendor, Guid documentType)
2343 if (m_iSymWriter == null)
2345 // Cannot DefineDocument when it is not a debug module
2346 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotADebugModule"));
2349 return m_iSymWriter.DefineDocument(url, language, languageVendor, documentType);
2353 [System.Security.SecurityCritical] // auto-generated
2355 [System.Security.SecuritySafeCritical]
2357 public void SetUserEntryPoint(MethodInfo entryPoint)
2361 SetUserEntryPointNoLock(entryPoint);
2365 [System.Security.SecurityCritical] // auto-generated
2366 private void SetUserEntryPointNoLock(MethodInfo entryPoint)
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.
2372 if (entryPoint == null)
2374 throw new ArgumentNullException("entryPoint");
2376 Contract.EndContractBlock();
2378 if (m_iSymWriter == null)
2380 // Cannot set entry point when it is not a debug module
2381 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotADebugModule"));
2384 if (entryPoint.DeclaringType != null)
2386 if (!entryPoint.Module.Equals(this))
2388 // you cannot pass in a MethodInfo that is not contained by this ModuleBuilder
2389 throw new InvalidOperationException(Environment.GetResourceString("Argument_NotInTheSameModuleBuilder"));
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)
2400 // you cannot pass in a MethodInfo that is not contained by this ModuleBuilder
2401 throw new InvalidOperationException(Environment.GetResourceString("Argument_NotInTheSameModuleBuilder"));
2405 // get the metadata token value and create the SymbolStore's token value class
2406 SymbolToken tkMethod = new SymbolToken(GetMethodTokenInternal(entryPoint).Token);
2408 // set the UserEntryPoint
2409 m_iSymWriter.SetUserEntryPoint(tkMethod);
2412 public void SetSymCustomAttribute(String name, byte[] data)
2416 SetSymCustomAttributeNoLock(name, data);
2420 private void SetSymCustomAttributeNoLock(String name, byte[] data)
2422 if (m_iSymWriter == null)
2424 // Cannot SetSymCustomAttribute when it is not a debug module
2425 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotADebugModule"));
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.
2434 public bool IsTransient()
2436 return InternalModule.IsTransientInternal();
2443 #if !FEATURE_CORECLR
2444 void _ModuleBuilder.GetTypeInfoCount(out uint pcTInfo)
2446 throw new NotImplementedException();
2449 void _ModuleBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
2451 throw new NotImplementedException();
2454 void _ModuleBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
2456 throw new NotImplementedException();
2459 void _ModuleBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
2461 throw new NotImplementedException();