mscorlib(4.0.0.0) API with additions
MethodBuilder.cs
6 using System.Security;
8 using System.Text;
9 
10 namespace System.Reflection.Emit
11 {
13  [ClassInterface(ClassInterfaceType.None)]
14  [ComDefaultInterface(typeof(_MethodBuilder))]
15  [ComVisible(true)]
16  [HostProtection(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
17  public sealed class MethodBuilder : MethodInfo, _MethodBuilder
18  {
19  private struct SymCustomAttr
20  {
21  public string m_name;
22 
23  public byte[] m_data;
24 
25  public SymCustomAttr(string name, byte[] data)
26  {
27  m_name = name;
28  m_data = data;
29  }
30  }
31 
32  internal string m_strName;
33 
34  private MethodToken m_tkMethod;
35 
36  private ModuleBuilder m_module;
37 
38  internal TypeBuilder m_containingType;
39 
40  private int[] m_mdMethodFixups;
41 
42  private byte[] m_localSignature;
43 
44  internal LocalSymInfo m_localSymInfo;
45 
46  internal ILGenerator m_ilGenerator;
47 
48  private byte[] m_ubBody;
49 
50  private ExceptionHandler[] m_exceptions;
51 
52  private const int DefaultMaxStack = 16;
53 
54  private int m_maxStack = 16;
55 
56  internal bool m_bIsBaked;
57 
58  private bool m_bIsGlobalMethod;
59 
60  private bool m_fInitLocals;
61 
62  private MethodAttributes m_iAttributes;
63 
64  private CallingConventions m_callingConvention;
65 
66  private MethodImplAttributes m_dwMethodImplFlags;
67 
68  private SignatureHelper m_signature;
69 
70  internal Type[] m_parameterTypes;
71 
72  private ParameterBuilder m_retParam;
73 
74  private Type m_returnType;
75 
76  private Type[] m_returnTypeRequiredCustomModifiers;
77 
78  private Type[] m_returnTypeOptionalCustomModifiers;
79 
80  private Type[][] m_parameterTypeRequiredCustomModifiers;
81 
82  private Type[][] m_parameterTypeOptionalCustomModifiers;
83 
84  private GenericTypeParameterBuilder[] m_inst;
85 
86  private bool m_bIsGenMethDef;
87 
88  private List<SymCustomAttr> m_symCustomAttrs;
89 
90  internal bool m_canBeRuntimeImpl;
91 
92  internal bool m_isDllImport;
93 
94  internal int ExceptionHandlerCount
95  {
96  get
97  {
98  if (m_exceptions == null)
99  {
100  return 0;
101  }
102  return m_exceptions.Length;
103  }
104  }
105 
108  public override string Name => m_strName;
109 
110  internal int MetadataTokenInternal => GetToken().Token;
111 
114  public override Module Module => m_containingType.Module;
115 
118  public override Type DeclaringType
119  {
120  get
121  {
122  if (m_containingType.m_isHiddenGlobalType)
123  {
124  return null;
125  }
126  return m_containingType;
127  }
128  }
129 
133 
136  public override Type ReflectedType => DeclaringType;
137 
140  public override MethodAttributes Attributes => m_iAttributes;
141 
144  public override CallingConventions CallingConvention => m_callingConvention;
145 
149  public override RuntimeMethodHandle MethodHandle
150  {
151  get
152  {
153  throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
154  }
155  }
156 
160  public override bool IsSecurityCritical
161  {
162  get
163  {
164  throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
165  }
166  }
167 
171  public override bool IsSecuritySafeCritical
172  {
173  get
174  {
175  throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
176  }
177  }
178 
182  public override bool IsSecurityTransparent
183  {
184  get
185  {
186  throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
187  }
188  }
189 
192  public override Type ReturnType => m_returnType;
193 
197  public override ParameterInfo ReturnParameter
198  {
199  get
200  {
201  if (!m_bIsBaked || m_containingType == null || m_containingType.BakedRuntimeType == null)
202  {
203  throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TypeNotCreated"));
204  }
205  MethodInfo method = m_containingType.GetMethod(m_strName, m_parameterTypes);
206  return method.ReturnParameter;
207  }
208  }
209 
213  public override bool IsGenericMethodDefinition => m_bIsGenMethDef;
214 
218  public override bool ContainsGenericParameters
219  {
220  get
221  {
222  throw new NotSupportedException();
223  }
224  }
225 
229  public override bool IsGenericMethod => m_inst != null;
230 
235  public bool InitLocals
236  {
237  get
238  {
239  ThrowIfGeneric();
240  return m_fInitLocals;
241  }
242  set
243  {
244  ThrowIfGeneric();
245  m_fInitLocals = value;
246  }
247  }
248 
251  public string Signature
252  {
253  [SecuritySafeCritical]
254  get
255  {
256  return GetMethodSignature().ToString();
257  }
258  }
259 
260  internal MethodBuilder(string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, ModuleBuilder mod, TypeBuilder type, bool bIsGlobalMethod)
261  {
262  Init(name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null, mod, type, bIsGlobalMethod);
263  }
264 
265  internal MethodBuilder(string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers, ModuleBuilder mod, TypeBuilder type, bool bIsGlobalMethod)
266  {
267  Init(name, attributes, callingConvention, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers, mod, type, bIsGlobalMethod);
268  }
269 
270  private void Init(string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers, ModuleBuilder mod, TypeBuilder type, bool bIsGlobalMethod)
271  {
272  if (name == null)
273  {
274  throw new ArgumentNullException("name");
275  }
276  if (name.Length == 0)
277  {
278  throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name");
279  }
280  if (name[0] == '\0')
281  {
282  throw new ArgumentException(Environment.GetResourceString("Argument_IllegalName"), "name");
283  }
284  if (mod == null)
285  {
286  throw new ArgumentNullException("mod");
287  }
288  if (parameterTypes != null)
289  {
290  foreach (Type left in parameterTypes)
291  {
292  if (left == null)
293  {
294  throw new ArgumentNullException("parameterTypes");
295  }
296  }
297  }
298  m_strName = name;
299  m_module = mod;
300  m_containingType = type;
301  m_returnType = returnType;
302  if ((attributes & MethodAttributes.Static) == MethodAttributes.PrivateScope)
303  {
304  callingConvention |= CallingConventions.HasThis;
305  }
306  else if ((attributes & MethodAttributes.Virtual) != 0)
307  {
308  throw new ArgumentException(Environment.GetResourceString("Arg_NoStaticVirtual"));
309  }
310  if ((attributes & MethodAttributes.SpecialName) != MethodAttributes.SpecialName && (type.Attributes & TypeAttributes.ClassSemanticsMask) == TypeAttributes.ClassSemanticsMask && (attributes & (MethodAttributes.Virtual | MethodAttributes.Abstract)) != (MethodAttributes.Virtual | MethodAttributes.Abstract) && (attributes & MethodAttributes.Static) == MethodAttributes.PrivateScope)
311  {
312  throw new ArgumentException(Environment.GetResourceString("Argument_BadAttributeOnInterfaceMethod"));
313  }
314  m_callingConvention = callingConvention;
315  if (parameterTypes != null)
316  {
317  m_parameterTypes = new Type[parameterTypes.Length];
318  Array.Copy(parameterTypes, m_parameterTypes, parameterTypes.Length);
319  }
320  else
321  {
322  m_parameterTypes = null;
323  }
324  m_returnTypeRequiredCustomModifiers = returnTypeRequiredCustomModifiers;
325  m_returnTypeOptionalCustomModifiers = returnTypeOptionalCustomModifiers;
326  m_parameterTypeRequiredCustomModifiers = parameterTypeRequiredCustomModifiers;
327  m_parameterTypeOptionalCustomModifiers = parameterTypeOptionalCustomModifiers;
328  m_iAttributes = attributes;
329  m_bIsGlobalMethod = bIsGlobalMethod;
330  m_bIsBaked = false;
331  m_fInitLocals = true;
332  m_localSymInfo = new LocalSymInfo();
333  m_ubBody = null;
334  m_ilGenerator = null;
335  m_dwMethodImplFlags = MethodImplAttributes.IL;
336  }
337 
338  internal void CheckContext(params Type[][] typess)
339  {
340  m_module.CheckContext(typess);
341  }
342 
343  internal void CheckContext(params Type[] types)
344  {
345  m_module.CheckContext(types);
346  }
347 
348  [SecurityCritical]
349  internal void CreateMethodBodyHelper(ILGenerator il)
350  {
351  if (il == null)
352  {
353  throw new ArgumentNullException("il");
354  }
355  int num = 0;
356  ModuleBuilder module = m_module;
357  m_containingType.ThrowIfCreated();
358  if (m_bIsBaked)
359  {
360  throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MethodHasBody"));
361  }
362  if (il.m_methodBuilder != this && il.m_methodBuilder != null)
363  {
364  throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadILGeneratorUsage"));
365  }
366  ThrowIfShouldNotHaveBody();
367  if (il.m_ScopeTree.m_iOpenScopeCount != 0)
368  {
369  throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_OpenLocalVariableScope"));
370  }
371  m_ubBody = il.BakeByteArray();
372  m_mdMethodFixups = il.GetTokenFixups();
373  __ExceptionInfo[] exceptions = il.GetExceptions();
374  int num2 = CalculateNumberOfExceptions(exceptions);
375  if (num2 > 0)
376  {
377  m_exceptions = new ExceptionHandler[num2];
378  for (int i = 0; i < exceptions.Length; i++)
379  {
380  int[] filterAddresses = exceptions[i].GetFilterAddresses();
381  int[] catchAddresses = exceptions[i].GetCatchAddresses();
382  int[] catchEndAddresses = exceptions[i].GetCatchEndAddresses();
383  Type[] catchClass = exceptions[i].GetCatchClass();
384  int numberOfCatches = exceptions[i].GetNumberOfCatches();
385  int startAddress = exceptions[i].GetStartAddress();
386  int endAddress = exceptions[i].GetEndAddress();
387  int[] exceptionTypes = exceptions[i].GetExceptionTypes();
388  for (int j = 0; j < numberOfCatches; j++)
389  {
390  int exceptionTypeToken = 0;
391  if (catchClass[j] != null)
392  {
393  exceptionTypeToken = module.GetTypeTokenInternal(catchClass[j]).Token;
394  }
395  switch (exceptionTypes[j])
396  {
397  case 0:
398  case 1:
399  case 4:
400  m_exceptions[num++] = new ExceptionHandler(startAddress, endAddress, filterAddresses[j], catchAddresses[j], catchEndAddresses[j], exceptionTypes[j], exceptionTypeToken);
401  break;
402  case 2:
403  m_exceptions[num++] = new ExceptionHandler(startAddress, exceptions[i].GetFinallyEndAddress(), filterAddresses[j], catchAddresses[j], catchEndAddresses[j], exceptionTypes[j], exceptionTypeToken);
404  break;
405  }
406  }
407  }
408  }
409  m_bIsBaked = true;
410  if (module.GetSymWriter() != null)
411  {
412  SymbolToken method = new SymbolToken(MetadataTokenInternal);
413  ISymbolWriter symWriter = module.GetSymWriter();
414  symWriter.OpenMethod(method);
415  symWriter.OpenScope(0);
416  if (m_symCustomAttrs != null)
417  {
418  foreach (SymCustomAttr symCustomAttr in m_symCustomAttrs)
419  {
420  module.GetSymWriter().SetSymAttribute(new SymbolToken(MetadataTokenInternal), symCustomAttr.m_name, symCustomAttr.m_data);
421  }
422  }
423  if (m_localSymInfo != null)
424  {
425  m_localSymInfo.EmitLocalSymInfo(symWriter);
426  }
427  il.m_ScopeTree.EmitScopeTree(symWriter);
428  il.m_LineNumberInfo.EmitLineNumberInfo(symWriter);
429  symWriter.CloseScope(il.ILOffset);
430  symWriter.CloseMethod();
431  }
432  }
433 
434  internal void ReleaseBakedStructures()
435  {
436  if (m_bIsBaked)
437  {
438  m_ubBody = null;
439  m_localSymInfo = null;
440  m_mdMethodFixups = null;
441  m_localSignature = null;
442  m_exceptions = null;
443  }
444  }
445 
446  internal override Type[] GetParameterTypes()
447  {
448  if (m_parameterTypes == null)
449  {
450  m_parameterTypes = EmptyArray<Type>.Value;
451  }
452  return m_parameterTypes;
453  }
454 
455  internal static Type GetMethodBaseReturnType(MethodBase method)
456  {
457  MethodInfo methodInfo = null;
458  ConstructorInfo constructorInfo = null;
459  if ((methodInfo = (method as MethodInfo)) != null)
460  {
461  return methodInfo.ReturnType;
462  }
463  if ((constructorInfo = (method as ConstructorInfo)) != null)
464  {
465  return constructorInfo.GetReturnType();
466  }
467  return null;
468  }
469 
470  internal void SetToken(MethodToken token)
471  {
472  m_tkMethod = token;
473  }
474 
475  internal byte[] GetBody()
476  {
477  return m_ubBody;
478  }
479 
480  internal int[] GetTokenFixups()
481  {
482  return m_mdMethodFixups;
483  }
484 
485  [SecurityCritical]
486  internal SignatureHelper GetMethodSignature()
487  {
488  if (m_parameterTypes == null)
489  {
490  m_parameterTypes = EmptyArray<Type>.Value;
491  }
492  m_signature = SignatureHelper.GetMethodSigHelper(m_module, m_callingConvention, (m_inst != null) ? m_inst.Length : 0, (m_returnType == null) ? typeof(void) : m_returnType, m_returnTypeRequiredCustomModifiers, m_returnTypeOptionalCustomModifiers, m_parameterTypes, m_parameterTypeRequiredCustomModifiers, m_parameterTypeOptionalCustomModifiers);
493  return m_signature;
494  }
495 
496  internal byte[] GetLocalSignature(out int signatureLength)
497  {
498  if (m_localSignature != null)
499  {
500  signatureLength = m_localSignature.Length;
501  return m_localSignature;
502  }
503  if (m_ilGenerator != null && m_ilGenerator.m_localCount != 0)
504  {
505  return m_ilGenerator.m_localSignature.InternalGetSignature(out signatureLength);
506  }
507  return SignatureHelper.GetLocalVarSigHelper(m_module).InternalGetSignature(out signatureLength);
508  }
509 
510  internal int GetMaxStack()
511  {
512  if (m_ilGenerator != null)
513  {
514  return m_ilGenerator.GetMaxStackSize() + ExceptionHandlerCount;
515  }
516  return m_maxStack;
517  }
518 
519  internal ExceptionHandler[] GetExceptionHandlers()
520  {
521  return m_exceptions;
522  }
523 
524  internal int CalculateNumberOfExceptions(__ExceptionInfo[] excp)
525  {
526  int num = 0;
527  if (excp == null)
528  {
529  return 0;
530  }
531  for (int i = 0; i < excp.Length; i++)
532  {
533  num += excp[i].GetNumberOfCatches();
534  }
535  return num;
536  }
537 
538  internal bool IsTypeCreated()
539  {
540  if (m_containingType != null)
541  {
542  return m_containingType.IsCreated();
543  }
544  return false;
545  }
546 
547  internal TypeBuilder GetTypeBuilder()
548  {
549  return m_containingType;
550  }
551 
552  internal ModuleBuilder GetModuleBuilder()
553  {
554  return m_module;
555  }
556 
561  [SecuritySafeCritical]
562  public override bool Equals(object obj)
563  {
564  if (!(obj is MethodBuilder))
565  {
566  return false;
567  }
568  if (!m_strName.Equals(((MethodBuilder)obj).m_strName))
569  {
570  return false;
571  }
572  if (m_iAttributes != ((MethodBuilder)obj).m_iAttributes)
573  {
574  return false;
575  }
576  SignatureHelper methodSignature = ((MethodBuilder)obj).GetMethodSignature();
577  if (methodSignature.Equals(GetMethodSignature()))
578  {
579  return true;
580  }
581  return false;
582  }
583 
586  public override int GetHashCode()
587  {
588  return m_strName.GetHashCode();
589  }
590 
593  [SecuritySafeCritical]
594  public override string ToString()
595  {
596  StringBuilder stringBuilder = new StringBuilder(1000);
597  stringBuilder.Append("Name: " + m_strName + " " + Environment.NewLine);
598  stringBuilder.Append("Attributes: " + (int)m_iAttributes + Environment.NewLine);
599  stringBuilder.Append("Method Signature: " + GetMethodSignature() + Environment.NewLine);
600  stringBuilder.Append(Environment.NewLine);
601  return stringBuilder.ToString();
602  }
603 
612  public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
613  {
614  throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
615  }
616 
620  {
621  return m_dwMethodImplFlags;
622  }
623 
626  public override MethodInfo GetBaseDefinition()
627  {
628  return this;
629  }
630 
634  public override ParameterInfo[] GetParameters()
635  {
636  if (!m_bIsBaked || m_containingType == null || m_containingType.BakedRuntimeType == null)
637  {
638  throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_TypeNotCreated"));
639  }
640  MethodInfo method = m_containingType.GetMethod(m_strName, m_parameterTypes);
641  return method.GetParameters();
642  }
643 
648  public override object[] GetCustomAttributes(bool inherit)
649  {
650  throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
651  }
652 
658  public override object[] GetCustomAttributes(Type attributeType, bool inherit)
659  {
660  throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
661  }
662 
669  public override bool IsDefined(Type attributeType, bool inherit)
670  {
671  throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
672  }
673 
678  {
679  if (!IsGenericMethod)
680  {
681  throw new InvalidOperationException();
682  }
683  return this;
684  }
685 
688  public override Type[] GetGenericArguments()
689  {
690  return m_inst;
691  }
692 
696  public override MethodInfo MakeGenericMethod(params Type[] typeArguments)
697  {
698  return MethodBuilderInstantiation.MakeGenericMethod(this, typeArguments);
699  }
700 
709  public GenericTypeParameterBuilder[] DefineGenericParameters(params string[] names)
710  {
711  if (names == null)
712  {
713  throw new ArgumentNullException("names");
714  }
715  if (names.Length == 0)
716  {
717  throw new ArgumentException(Environment.GetResourceString("Arg_EmptyArray"), "names");
718  }
719  if (m_inst != null)
720  {
721  throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_GenericParametersAlreadySet"));
722  }
723  for (int i = 0; i < names.Length; i++)
724  {
725  if (names[i] == null)
726  {
727  throw new ArgumentNullException("names");
728  }
729  }
730  if (m_tkMethod.Token != 0)
731  {
732  throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MethodBuilderBaked"));
733  }
734  m_bIsGenMethDef = true;
735  m_inst = new GenericTypeParameterBuilder[names.Length];
736  for (int j = 0; j < names.Length; j++)
737  {
738  m_inst[j] = new GenericTypeParameterBuilder(new TypeBuilder(names[j], j, this));
739  }
740  return m_inst;
741  }
742 
743  internal void ThrowIfGeneric()
744  {
746  {
747  throw new InvalidOperationException();
748  }
749  }
750 
753  [SecuritySafeCritical]
755  {
756  if (m_tkMethod.Token != 0)
757  {
758  return m_tkMethod;
759  }
760  MethodBuilder methodBuilder = null;
761  MethodToken result = new MethodToken(0);
762  lock (m_containingType.m_listMethods)
763  {
764  if (m_tkMethod.Token != 0)
765  {
766  return m_tkMethod;
767  }
768  int i;
769  for (i = m_containingType.m_lastTokenizedMethod + 1; i < m_containingType.m_listMethods.Count; i++)
770  {
771  methodBuilder = m_containingType.m_listMethods[i];
772  result = methodBuilder.GetTokenNoLock();
773  if (methodBuilder == this)
774  {
775  break;
776  }
777  }
778  m_containingType.m_lastTokenizedMethod = i;
779  return result;
780  }
781  }
782 
783  [SecurityCritical]
784  private MethodToken GetTokenNoLock()
785  {
786  int length;
787  byte[] signature = GetMethodSignature().InternalGetSignature(out length);
788  int num = TypeBuilder.DefineMethod(m_module.GetNativeHandle(), m_containingType.MetadataTokenInternal, m_strName, signature, length, Attributes);
789  m_tkMethod = new MethodToken(num);
790  if (m_inst != null)
791  {
792  GenericTypeParameterBuilder[] inst = m_inst;
793  foreach (GenericTypeParameterBuilder genericTypeParameterBuilder in inst)
794  {
795  if (!genericTypeParameterBuilder.m_type.IsCreated())
796  {
797  genericTypeParameterBuilder.m_type.CreateType();
798  }
799  }
800  }
801  TypeBuilder.SetMethodImpl(m_module.GetNativeHandle(), num, m_dwMethodImplFlags);
802  return m_tkMethod;
803  }
804 
808  public void SetParameters(params Type[] parameterTypes)
809  {
810  CheckContext(parameterTypes);
811  SetSignature(null, null, null, parameterTypes, null, null);
812  }
813 
817  public void SetReturnType(Type returnType)
818  {
819  CheckContext(returnType);
820  SetSignature(returnType, null, null, null, null, null);
821  }
822 
831  public void SetSignature(Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
832  {
833  if (m_tkMethod.Token == 0)
834  {
835  CheckContext(returnType);
836  CheckContext(returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes);
837  CheckContext(parameterTypeRequiredCustomModifiers);
838  CheckContext(parameterTypeOptionalCustomModifiers);
839  ThrowIfGeneric();
840  if (returnType != null)
841  {
842  m_returnType = returnType;
843  }
844  if (parameterTypes != null)
845  {
846  m_parameterTypes = new Type[parameterTypes.Length];
847  Array.Copy(parameterTypes, m_parameterTypes, parameterTypes.Length);
848  }
849  m_returnTypeRequiredCustomModifiers = returnTypeRequiredCustomModifiers;
850  m_returnTypeOptionalCustomModifiers = returnTypeOptionalCustomModifiers;
851  m_parameterTypeRequiredCustomModifiers = parameterTypeRequiredCustomModifiers;
852  m_parameterTypeOptionalCustomModifiers = parameterTypeOptionalCustomModifiers;
853  }
854  }
855 
865  [SecuritySafeCritical]
866  public ParameterBuilder DefineParameter(int position, ParameterAttributes attributes, string strParamName)
867  {
868  if (position < 0)
869  {
870  throw new ArgumentOutOfRangeException(Environment.GetResourceString("ArgumentOutOfRange_ParamSequence"));
871  }
872  ThrowIfGeneric();
873  m_containingType.ThrowIfCreated();
874  if (position > 0 && (m_parameterTypes == null || position > m_parameterTypes.Length))
875  {
876  throw new ArgumentOutOfRangeException(Environment.GetResourceString("ArgumentOutOfRange_ParamSequence"));
877  }
878  attributes &= ~ParameterAttributes.ReservedMask;
879  return new ParameterBuilder(this, position, attributes, strParamName);
880  }
881 
885  [SecuritySafeCritical]
886  [Obsolete("An alternate API is available: Emit the MarshalAs custom attribute instead. http://go.microsoft.com/fwlink/?linkid=14202")]
887  public void SetMarshal(UnmanagedMarshal unmanagedMarshal)
888  {
889  ThrowIfGeneric();
890  m_containingType.ThrowIfCreated();
891  if (m_retParam == null)
892  {
893  m_retParam = new ParameterBuilder(this, 0, ParameterAttributes.None, null);
894  }
895  m_retParam.SetMarshal(unmanagedMarshal);
896  }
897 
902  public void SetSymCustomAttribute(string name, byte[] data)
903  {
904  ThrowIfGeneric();
905  m_containingType.ThrowIfCreated();
906  ModuleBuilder module = m_module;
907  if (module.GetSymWriter() == null)
908  {
909  throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotADebugModule"));
910  }
911  if (m_symCustomAttrs == null)
912  {
913  m_symCustomAttrs = new List<SymCustomAttr>();
914  }
915  m_symCustomAttrs.Add(new SymCustomAttr(name, data));
916  }
917 
925  [SecuritySafeCritical]
927  {
928  if (pset == null)
929  {
930  throw new ArgumentNullException("pset");
931  }
932  ThrowIfGeneric();
933  if (!Enum.IsDefined(typeof(SecurityAction), action) || action == SecurityAction.RequestMinimum || action == SecurityAction.RequestOptional || action == SecurityAction.RequestRefuse)
934  {
935  throw new ArgumentOutOfRangeException("action");
936  }
937  m_containingType.ThrowIfCreated();
938  byte[] array = null;
939  int cb = 0;
940  if (!pset.IsEmpty())
941  {
942  array = pset.EncodeXml();
943  cb = array.Length;
944  }
945  TypeBuilder.AddDeclarativeSecurity(m_module.GetNativeHandle(), MetadataTokenInternal, action, array, cb);
946  }
947 
959  public void SetMethodBody(byte[] il, int maxStack, byte[] localSignature, IEnumerable<ExceptionHandler> exceptionHandlers, IEnumerable<int> tokenFixups)
960  {
961  if (il == null)
962  {
963  throw new ArgumentNullException("il", Environment.GetResourceString("ArgumentNull_Array"));
964  }
965  if (maxStack < 0)
966  {
967  throw new ArgumentOutOfRangeException("maxStack", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
968  }
969  if (m_bIsBaked)
970  {
971  throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MethodBaked"));
972  }
973  m_containingType.ThrowIfCreated();
974  ThrowIfGeneric();
975  byte[] localSignature2 = null;
976  ExceptionHandler[] array = null;
977  int[] array2 = null;
978  byte[] array3 = (byte[])il.Clone();
979  if (localSignature != null)
980  {
981  localSignature2 = (byte[])localSignature.Clone();
982  }
983  if (exceptionHandlers != null)
984  {
985  array = ToArray(exceptionHandlers);
986  CheckExceptionHandlerRanges(array, array3.Length);
987  }
988  if (tokenFixups != null)
989  {
990  array2 = ToArray(tokenFixups);
991  int num = array3.Length - 4;
992  for (int i = 0; i < array2.Length; i++)
993  {
994  if (array2[i] < 0 || array2[i] > num)
995  {
996  throw new ArgumentOutOfRangeException("tokenFixups[" + i + "]", Environment.GetResourceString("ArgumentOutOfRange_Range", 0, num));
997  }
998  }
999  }
1000  m_ubBody = array3;
1001  m_localSignature = localSignature2;
1002  m_exceptions = array;
1003  m_mdMethodFixups = array2;
1004  m_maxStack = maxStack;
1005  m_ilGenerator = null;
1006  m_bIsBaked = true;
1007  }
1008 
1009  private static T[] ToArray<T>(IEnumerable<T> sequence)
1010  {
1011  T[] array = sequence as T[];
1012  if (array != null)
1013  {
1014  return (T[])array.Clone();
1015  }
1016  return new List<T>(sequence).ToArray();
1017  }
1018 
1019  private static void CheckExceptionHandlerRanges(ExceptionHandler[] exceptionHandlers, int maxOffset)
1020  {
1021  int num = 0;
1022  ExceptionHandler exceptionHandler;
1023  while (true)
1024  {
1025  if (num < exceptionHandlers.Length)
1026  {
1027  exceptionHandler = exceptionHandlers[num];
1028  if (exceptionHandler.m_filterOffset > maxOffset || exceptionHandler.m_tryEndOffset > maxOffset || exceptionHandler.m_handlerEndOffset > maxOffset)
1029  {
1030  throw new ArgumentOutOfRangeException("exceptionHandlers[" + num + "]", Environment.GetResourceString("ArgumentOutOfRange_Range", 0, maxOffset));
1031  }
1032  if (exceptionHandler.Kind == ExceptionHandlingClauseOptions.Clause && exceptionHandler.ExceptionTypeToken == 0)
1033  {
1034  break;
1035  }
1036  num++;
1037  continue;
1038  }
1039  return;
1040  }
1041  throw new ArgumentException(Environment.GetResourceString("Argument_InvalidTypeToken", exceptionHandler.ExceptionTypeToken), "exceptionHandlers[" + num + "]");
1042  }
1043 
1049  public void CreateMethodBody(byte[] il, int count)
1050  {
1051  ThrowIfGeneric();
1052  if (m_bIsBaked)
1053  {
1054  throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MethodBaked"));
1055  }
1056  m_containingType.ThrowIfCreated();
1057  if (il != null && (count < 0 || count > il.Length))
1058  {
1059  throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_Index"));
1060  }
1061  if (il == null)
1062  {
1063  m_ubBody = null;
1064  return;
1065  }
1066  m_ubBody = new byte[count];
1067  Array.Copy(il, m_ubBody, count);
1068  m_localSignature = null;
1069  m_exceptions = null;
1070  m_mdMethodFixups = null;
1071  m_maxStack = 16;
1072  m_bIsBaked = true;
1073  }
1074 
1078  [SecuritySafeCritical]
1080  {
1081  ThrowIfGeneric();
1082  m_containingType.ThrowIfCreated();
1083  m_dwMethodImplFlags = attributes;
1084  m_canBeRuntimeImpl = true;
1085  TypeBuilder.SetMethodImpl(m_module.GetNativeHandle(), MetadataTokenInternal, attributes);
1086  }
1087 
1092  {
1093  ThrowIfGeneric();
1094  ThrowIfShouldNotHaveBody();
1095  if (m_ilGenerator == null)
1096  {
1097  m_ilGenerator = new ILGenerator(this);
1098  }
1099  return m_ilGenerator;
1100  }
1101 
1106  public ILGenerator GetILGenerator(int size)
1107  {
1108  ThrowIfGeneric();
1109  ThrowIfShouldNotHaveBody();
1110  if (m_ilGenerator == null)
1111  {
1112  m_ilGenerator = new ILGenerator(this, size);
1113  }
1114  return m_ilGenerator;
1115  }
1116 
1117  private void ThrowIfShouldNotHaveBody()
1118  {
1119  if ((m_dwMethodImplFlags & MethodImplAttributes.CodeTypeMask) != 0 || (m_dwMethodImplFlags & MethodImplAttributes.ManagedMask) != 0 || (m_iAttributes & MethodAttributes.PinvokeImpl) != 0 || m_isDllImport)
1120  {
1121  throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ShouldNotHaveMethodBody"));
1122  }
1123  }
1124 
1128  {
1129  return GetModuleBuilder();
1130  }
1131 
1138  [SecuritySafeCritical]
1139  [ComVisible(true)]
1140  public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
1141  {
1142  if (con == null)
1143  {
1144  throw new ArgumentNullException("con");
1145  }
1146  if (binaryAttribute == null)
1147  {
1148  throw new ArgumentNullException("binaryAttribute");
1149  }
1150  ThrowIfGeneric();
1151  TypeBuilder.DefineCustomAttribute(m_module, MetadataTokenInternal, m_module.GetConstructorToken(con).Token, binaryAttribute, toDisk: false, updateCompilerFlags: false);
1152  if (IsKnownCA(con))
1153  {
1154  ParseCA(con, binaryAttribute);
1155  }
1156  }
1157 
1163  [SecuritySafeCritical]
1164  public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
1165  {
1166  if (customBuilder == null)
1167  {
1168  throw new ArgumentNullException("customBuilder");
1169  }
1170  ThrowIfGeneric();
1171  customBuilder.CreateCustomAttribute(m_module, MetadataTokenInternal);
1172  if (IsKnownCA(customBuilder.m_con))
1173  {
1174  ParseCA(customBuilder.m_con, customBuilder.m_blob);
1175  }
1176  }
1177 
1178  private bool IsKnownCA(ConstructorInfo con)
1179  {
1180  Type declaringType = con.DeclaringType;
1181  if (declaringType == typeof(MethodImplAttribute))
1182  {
1183  return true;
1184  }
1185  if (declaringType == typeof(DllImportAttribute))
1186  {
1187  return true;
1188  }
1189  return false;
1190  }
1191 
1192  private void ParseCA(ConstructorInfo con, byte[] blob)
1193  {
1194  Type declaringType = con.DeclaringType;
1195  if (declaringType == typeof(MethodImplAttribute))
1196  {
1197  m_canBeRuntimeImpl = true;
1198  }
1199  else if (declaringType == typeof(DllImportAttribute))
1200  {
1201  m_canBeRuntimeImpl = true;
1202  m_isDllImport = true;
1203  }
1204  }
1205 
1209  void _MethodBuilder.GetTypeInfoCount(out uint pcTInfo)
1210  {
1211  throw new NotImplementedException();
1212  }
1213 
1219  void _MethodBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
1220  {
1221  throw new NotImplementedException();
1222  }
1223 
1231  void _MethodBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
1232  {
1233  throw new NotImplementedException();
1234  }
1235 
1246  void _MethodBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
1247  {
1248  throw new NotImplementedException();
1249  }
1250  }
1251 }
void SetMethodBody(byte[] il, int maxStack, byte[] localSignature, IEnumerable< ExceptionHandler > exceptionHandlers, IEnumerable< int > tokenFixups)
Creates the body of the method by using a specified byte array of Microsoft intermediate language (MS...
Performs reflection on a module.
Definition: Module.cs:17
Discovers the attributes of a parameter and provides access to parameter metadata.
Module GetModule()
Returns a reference to the module that contains this method.
MethodAttributes
Specifies flags for method attributes. These flags are defined in the corhdr.h file.
void SetImplementationFlags(MethodImplAttributes attributes)
Sets the implementation flags for this method.
static string NewLine
Gets the newline string defined for this environment.
Definition: Environment.cs:449
The T:System.Diagnostics.SymbolStore.SymbolToken structure is an object representation of a token tha...
Definition: SymbolToken.cs:7
Type CreateType()
Creates a T:System.Type object for the class. After defining fields and methods on the class,...
The exception that is thrown when a null reference (Nothing in Visual Basic) is passed to a method th...
void SetSignature(Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
Sets the method signature, including the return type, the parameter types, and the required and optio...
void AddDeclarativeSecurity(SecurityAction action, PermissionSet pset)
Adds declarative security to this method.
override ParameterInfo ReturnParameter
Gets a T:System.Reflection.ParameterInfo object that contains information about the return type of th...
void SetCustomAttribute(CustomAttributeBuilder customBuilder)
Sets a custom attribute using a custom attribute builder.
Defines and creates generic type parameters for dynamically defined generic types and methods....
unsafe override string ToString()
Converts the value of this instance to a T:System.String.
override bool IsDefined(Type attributeType, bool inherit)
Checks if the specified custom attribute type is defined.
MethodImplAttributes
Specifies flags for the attributes of a method implementation.
MethodToken GetToken()
Returns the MethodToken that represents the token for this method.
GenericTypeParameterBuilder [] DefineGenericParameters(params string[] names)
Sets the number of generic type parameters for the current method, specifies their names,...
Discovers the attributes of a method and provides access to method metadata.
Definition: MethodInfo.cs:13
override string Name
Retrieves the name of this method.
void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
Sets a custom attribute using a specified custom attribute blob.
void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
Maps a set of names to a corresponding set of dispatch identifiers.
ILGenerator GetILGenerator(int size)
Returns an ILGenerator for this method with the specified Microsoft intermediate language (MSIL) stre...
Discovers the attributes of a class constructor and provides access to constructor metadata.
The MethodToken struct is an object representation of a token that represents a method.
Definition: MethodToken.cs:8
BindingFlags
Specifies flags that control binding and the way in which the search for members and types is conduct...
Definition: BindingFlags.cs:10
Definition: __Canon.cs:3
void SetSymCustomAttribute(string name, byte[] data)
Set a symbolic custom attribute using a blob.
The exception that is thrown when the value of an argument is outside the allowable range of values a...
virtual MethodInfo MakeGenericMethod(params Type[] typeArguments)
Substitutes the elements of an array of types for the type parameters of the current generic method d...
Definition: MethodInfo.cs:134
override bool Equals(object obj)
Determines whether the given object is equal to this instance.
void CreateMethodBody(byte[] il, int count)
Creates the body of the method using a supplied byte array of Microsoft intermediate language (MSIL) ...
CallingConvention
Specifies the calling convention required to call methods implemented in unmanaged code.
override Type DeclaringType
Gets the type that declares the current nested type or generic type parameter.
Definition: Type.cs:54
override bool IsSecurityTransparent
Throws a T:System.NotSupportedException in all cases.
string Signature
Retrieves the signature of the method.
Exposes the enumerator, which supports a simple iteration over a collection of a specified type....
Definition: IEnumerable.cs:9
Provides methods for building signatures.
void OpenMethod(SymbolToken method)
Opens a method to place symbol information into.
override ParameterInfo [] GetParameters()
Returns the parameters of this method.
Creates or associates parameter information.
override bool Equals(object obj)
Checks if this instance is equal to the given object.
MethodToken GetConstructorToken(ConstructorInfo constructor, IEnumerable< Type > optionalParameterTypes)
Returns the token used to identify the constructor that has the specified attributes and parameter ty...
Generates Microsoft intermediate language (MSIL) instructions.
Definition: ILGenerator.cs:12
override object [] GetCustomAttributes(bool inherit)
Returns all the custom attributes defined for this method.
void SetReturnType(Type returnType)
Sets the return type of the method.
void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
Retrieves the type information for an object, which can be used to get the type information for an in...
CallingConventions
Defines the valid calling conventions for a method.
SecurityAction
Specifies the security actions that can be performed using declarative security.
void CloseScope(int endOffset)
Closes the current lexical scope.
Provides information about, and means to manipulate, the current environment and platform....
Definition: Environment.cs:21
static bool IsDefined(Type enumType, object value)
Returns an indication whether a constant with a specified value exists in a specified enumeration.
Definition: Enum.cs:577
T:System.RuntimeMethodHandle is a handle to the internal metadata representation of a method.
StringBuilder Append(char value, int repeatCount)
Appends a specified number of copies of the string representation of a Unicode character to this inst...
Represents a collection that can contain many different types of permissions.
Defines and creates new instances of classes during run time.
Definition: TypeBuilder.cs:15
Indicates that the attributed method is exposed by an unmanaged dynamic-link library (DLL) as a stati...
override bool IsSecuritySafeCritical
Throws a T:System.NotSupportedException in all cases.
void SetMarshal(UnmanagedMarshal unmanagedMarshal)
Sets marshaling information for the return type of this method.
Provides the base class for enumerations.
Definition: Enum.cs:14
override object [] GetCustomAttributes(Type attributeType, bool inherit)
Returns the custom attributes identified by the given type.
override Type ReflectedType
Retrieves the class that was used in reflection to obtain this object.
override Module Module
Retrieves the dynamic module that contains this type definition.
Definition: TypeBuilder.cs:133
bool IsEmpty()
Gets a value indicating whether the T:System.Security.PermissionSet is empty.
virtual ParameterInfo ReturnParameter
Gets a T:System.Reflection.ParameterInfo object that contains information about the return type of th...
Definition: MethodInfo.cs:36
Defines and represents a module in a dynamic assembly.
Specifies the details of how a method is implemented. This class cannot be inherited.
override ICustomAttributeProvider ReturnTypeCustomAttributes
Returns the custom attributes of the method's return type.
override bool IsSecurityCritical
Throws a T:System.NotSupportedException in all cases.
ILGenerator GetILGenerator()
Returns an ILGenerator for this method with a default Microsoft intermediate language (MSIL) stream s...
override MethodAttributes Attributes
Retrieves the attributes for this method.
override MethodInfo MakeGenericMethod(params Type[] typeArguments)
Returns a generic method constructed from the current generic method definition using the specified g...
Provides methods for creating, manipulating, searching, and sorting arrays, thereby serving as the ba...
Definition: Array.cs:17
Represents type declarations: class types, interface types, array types, value types,...
Definition: Type.cs:18
override string ToString()
Returns this MethodBuilder instance as a string.
override bool IsGenericMethodDefinition
Gets a value indicating whether the current T:System.Reflection.Emit.MethodBuilder object represents ...
ParameterAttributes
Defines the attributes that can be associated with a parameter. These are defined in CorHdr....
override bool IsGenericMethod
Gets a value indicating whether the method is a generic method.
override MethodImplAttributes GetMethodImplementationFlags()
Returns the implementation flags for the method.
override Type ReturnType
Gets the return type of the method represented by this T:System.Reflection.Emit.MethodBuilder.
Selects a member from a list of candidates, and performs type conversion from actual argument type to...
Definition: Binder.cs:10
TypeAttributes
Specifies type attributes.
Defines and represents a method (or constructor) on a dynamic class.
Represents a mutable string of characters. This class cannot be inherited.To browse the ....
Type DeclaringType
Provides COM objects with version-independent access to the P:System.Reflection.MemberInfo....
override string ToString()
Returns a string representing the signature arguments.
The exception that is thrown when one of the arguments provided to a method is not valid.
Represents the class that describes how to marshal a field from managed to unmanaged code....
static void Copy(Array sourceArray, Array destinationArray, int length)
Copies a range of elements from an T:System.Array starting at the first element and pastes them into ...
Definition: Array.cs:1275
override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
Dynamically invokes the method reflected by this instance on the given object, passing along the spec...
Represents a symbol writer for managed code.
Definition: ISymbolWriter.cs:8
Represents an exception handler in a byte array of IL to be passed to a method such as M:System....
static MethodInfo GetMethod(Type type, MethodInfo method)
Returns the method of the specified constructed generic type that corresponds to the specified method...
Definition: TypeBuilder.cs:340
int Token
Returns the metadata token for this method.
Definition: MethodToken.cs:17
ISymbolWriter GetSymWriter()
Returns the symbol writer associated with this dynamic module.
override Type DeclaringType
Returns the type that declares this method.
ParameterBuilder DefineParameter(int position, ParameterAttributes attributes, string strParamName)
Sets the parameter attributes and the name of a parameter of this method, or of the return value of t...
override Type [] GetGenericArguments()
Returns an array of T:System.Reflection.Emit.GenericTypeParameterBuilder objects that represent the t...
void CloseMethod()
Closes the current method.
void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
Provides access to properties and methods exposed by an object.
override MethodInfo GetBaseDefinition()
Return the base implementation for a method.
The exception that is thrown when a method call is invalid for the object's current state.
static SignatureHelper GetMethodSigHelper(Module mod, Type returnType, Type[] parameterTypes)
Returns a signature helper for a method with a standard calling convention, given the method's module...
ClassInterfaceType
Identifies the type of class interface that is generated for a class.
int OpenScope(int startOffset)
Opens a new lexical scope in the current method.
override RuntimeMethodHandle MethodHandle
Retrieves the internal handle for the method. Use this handle to access the underlying metadata handl...
void GetTypeInfoCount(out uint pcTInfo)
Retrieves the number of type information interfaces that an object provides (either 0 or 1).
ExceptionHandlingClauseOptions
Identifies kinds of exception-handling clauses.
Provides information about a specific culture (called a locale for unmanaged code development)....
Definition: CultureInfo.cs:16
The exception that is thrown when an invoked method is not supported, or when there is an attempt to ...
Exposes the T:System.Reflection.Emit.MethodBuilder class to unmanaged code.
virtual void SetMarshal(UnmanagedMarshal unmanagedMarshal)
Specifies the marshaling for this parameter.
bool InitLocals
Gets or sets a Boolean value that specifies whether the local variables in this method are zero initi...
T [] ToArray()
Copies the elements of the T:System.Collections.Generic.List`1 to a new array.
Definition: List.cs:1531
bool IsCreated()
Returns a value that indicates whether the current dynamic type has been created.
Definition: TypeBuilder.cs:974
override int GetHashCode()
Gets the hash code for this method.
override MethodInfo GetGenericMethodDefinition()
Returns this method.
override bool ContainsGenericParameters
Not supported for this type.
void SetParameters(params Type[] parameterTypes)
Sets the number and types of parameters for a method.
Provides custom attributes for reflection objects that support them.
abstract ParameterInfo [] GetParameters()
When overridden in a derived class, gets the parameters of the specified method or constructor.