2 // System.Reflection.Emit.ConstructorBuilder.cs
5 // Paolo Molaro (lupus@ximian.com)
7 // (C) 2001 Ximian, Inc. http://www.ximian.com
11 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
13 // Permission is hereby granted, free of charge, to any person obtaining
14 // a copy of this software and associated documentation files (the
15 // "Software"), to deal in the Software without restriction, including
16 // without limitation the rights to use, copy, modify, merge, publish,
17 // distribute, sublicense, and/or sell copies of the Software, and to
18 // permit persons to whom the Software is furnished to do so, subject to
19 // the following conditions:
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
28 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
29 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
30 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
35 using System.Collections.Generic;
36 using System.Reflection;
37 using System.Reflection.Emit;
38 using System.Globalization;
39 using System.Security;
40 using System.Security.Permissions;
41 using System.Runtime.InteropServices;
42 using System.Diagnostics.SymbolStore;
44 namespace System.Reflection.Emit {
47 [ComDefaultInterface (typeof (_ConstructorBuilder))]
48 [ClassInterface (ClassInterfaceType.None)]
49 [StructLayout (LayoutKind.Sequential)]
50 public sealed class ConstructorBuilder : ConstructorInfo, _ConstructorBuilder {
52 #pragma warning disable 169, 414
53 private RuntimeMethodHandle mhandle;
54 private ILGenerator ilgen;
55 internal Type[] parameters;
56 private MethodAttributes attrs;
57 private MethodImplAttributes iattrs;
58 private int table_idx;
59 private CallingConventions call_conv;
60 private TypeBuilder type;
61 internal ParameterBuilder[] pinfo;
62 private CustomAttributeBuilder[] cattrs;
63 private bool init_locals = true;
64 private Type[][] paramModReq;
65 private Type[][] paramModOpt;
66 private RefEmitPermissionSet[] permissions;
67 #pragma warning restore 169, 414
69 internal ConstructorBuilder (TypeBuilder tb, MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes, Type[][] paramModReq, Type[][] paramModOpt)
71 attrs = attributes | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName;
72 call_conv = callingConvention;
73 if (parameterTypes != null) {
74 for (int i = 0; i < parameterTypes.Length; ++i)
75 if (parameterTypes [i] == null)
76 throw new ArgumentException ("Elements of the parameterTypes array cannot be null", "parameterTypes");
78 this.parameters = new Type [parameterTypes.Length];
79 System.Array.Copy (parameterTypes, this.parameters, parameterTypes.Length);
82 this.paramModReq = paramModReq;
83 this.paramModOpt = paramModOpt;
84 table_idx = get_next_table_index (this, 0x06, true);
86 ((ModuleBuilder) tb.Module).RegisterToken (this, GetToken ().Token);
90 public override CallingConventions CallingConvention {
96 public bool InitLocals {
105 internal TypeBuilder TypeBuilder {
111 public override MethodImplAttributes GetMethodImplementationFlags ()
116 public override ParameterInfo[] GetParameters ()
118 if (!type.is_created)
119 throw not_created ();
121 return GetParametersInternal ();
124 internal override ParameterInfo [] GetParametersInternal ()
126 if (parameters == null)
127 return EmptyArray<ParameterInfo>.Value;
129 ParameterInfo [] retval = new ParameterInfo [parameters.Length];
130 for (int i = 0; i < parameters.Length; i++)
131 retval [i] = ParameterInfo.New (pinfo == null ? null
132 : pinfo [i + 1], parameters [i], this, i + 1);
137 internal override int GetParametersCount ()
139 if (parameters == null)
142 return parameters.Length;
145 internal override Type GetParameterType (int pos) {
146 return parameters [pos];
149 internal MethodBase RuntimeResolve () {
150 return type.RuntimeResolve ().GetConstructor (this);
153 public override Object Invoke (Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
155 throw not_supported ();
158 public override object Invoke (BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
160 throw not_supported ();
163 public override RuntimeMethodHandle MethodHandle {
165 throw not_supported ();
169 public override MethodAttributes Attributes {
175 public override Type ReflectedType {
181 public override Type DeclaringType {
188 public Type ReturnType {
194 public override string Name {
196 return (attrs & MethodAttributes.Static) != 0 ? ConstructorInfo.TypeConstructorName : ConstructorInfo.ConstructorName;
200 public string Signature {
202 return "constructor signature";
206 public void AddDeclarativeSecurity (SecurityAction action, PermissionSet pset)
210 throw new ArgumentNullException ("pset");
211 if ((action == SecurityAction.RequestMinimum) ||
212 (action == SecurityAction.RequestOptional) ||
213 (action == SecurityAction.RequestRefuse))
214 throw new ArgumentOutOfRangeException ("action", "Request* values are not permitted");
218 if (permissions != null) {
219 /* Check duplicate actions */
220 foreach (RefEmitPermissionSet set in permissions)
221 if (set.action == action)
222 throw new InvalidOperationException ("Multiple permission sets specified with the same SecurityAction.");
224 RefEmitPermissionSet[] new_array = new RefEmitPermissionSet [permissions.Length + 1];
225 permissions.CopyTo (new_array, 0);
226 permissions = new_array;
229 permissions = new RefEmitPermissionSet [1];
231 permissions [permissions.Length - 1] = new RefEmitPermissionSet (action, pset.ToXml ().ToString ());
232 attrs |= MethodAttributes.HasSecurity;
236 public ParameterBuilder DefineParameter (int iSequence, ParameterAttributes attributes, string strParamName)
238 // The 0th ParameterBuilder does not correspond to an
239 // actual parameter, but .NETFramework lets you define
240 // it anyway. It is not useful.
241 if (iSequence < 0 || iSequence > GetParametersCount ())
242 throw new ArgumentOutOfRangeException ("iSequence");
244 throw not_after_created ();
246 ParameterBuilder pb = new ParameterBuilder (this, iSequence, attributes, strParamName);
248 pinfo = new ParameterBuilder [parameters.Length + 1];
249 pinfo [iSequence] = pb;
253 public override bool IsDefined (Type attributeType, bool inherit)
255 throw not_supported ();
258 public override object [] GetCustomAttributes (bool inherit)
260 throw not_supported ();
263 public override object [] GetCustomAttributes (Type attributeType, bool inherit)
265 throw not_supported ();
268 public ILGenerator GetILGenerator ()
270 return GetILGenerator (64);
273 public ILGenerator GetILGenerator (int streamSize)
277 ilgen = new ILGenerator (type.Module, ((ModuleBuilder)type.Module).GetTokenGenerator (), streamSize);
281 public void SetMethodBody (byte[] il, int maxStack, byte[] localSignature,
282 IEnumerable<ExceptionHandler> exceptionHandlers, IEnumerable<int> tokenFixups)
284 var ilgen = GetILGenerator ();
285 ilgen.Init (il, maxStack, localSignature, exceptionHandlers, tokenFixups);
289 public void SetCustomAttribute (CustomAttributeBuilder customBuilder)
291 if (customBuilder == null)
292 throw new ArgumentNullException ("customBuilder");
294 string attrname = customBuilder.Ctor.ReflectedType.FullName;
295 if (attrname == "System.Runtime.CompilerServices.MethodImplAttribute") {
296 byte[] data = customBuilder.Data;
297 int impla; // the (stupid) ctor takes a short or an int ...
298 impla = (int)data [2];
299 impla |= ((int)data [3]) << 8;
300 SetImplementationFlags ((MethodImplAttributes)impla);
303 if (cattrs != null) {
304 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
305 cattrs.CopyTo (new_array, 0);
306 new_array [cattrs.Length] = customBuilder;
309 cattrs = new CustomAttributeBuilder [1];
310 cattrs [0] = customBuilder;
315 public void SetCustomAttribute (ConstructorInfo con, byte[] binaryAttribute)
318 throw new ArgumentNullException ("con");
319 if (binaryAttribute == null)
320 throw new ArgumentNullException ("binaryAttribute");
322 SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
325 public void SetImplementationFlags (MethodImplAttributes attributes)
328 throw not_after_created ();
333 public Module GetModule ()
338 public MethodToken GetToken ()
340 return new MethodToken (0x06000000 | table_idx);
344 public void SetSymCustomAttribute (string name, byte[] data)
347 throw not_after_created ();
350 public override Module Module {
356 public override string ToString ()
358 return "ConstructorBuilder ['" + type.Name + "']";
361 internal void fixup ()
363 if (((attrs & (MethodAttributes.Abstract | MethodAttributes.PinvokeImpl)) == 0) && ((iattrs & (MethodImplAttributes.Runtime | MethodImplAttributes.InternalCall)) == 0)) {
364 if ((ilgen == null) || (ilgen.ILOffset == 0))
365 throw new InvalidOperationException ("Method '" + Name + "' does not have a method body.");
368 ilgen.label_fixup (this);
371 internal void ResolveUserTypes () {
372 TypeBuilder.ResolveUserTypes (parameters);
373 if (paramModReq != null) {
374 foreach (var types in paramModReq)
375 TypeBuilder.ResolveUserTypes (types);
377 if (paramModOpt != null) {
378 foreach (var types in paramModOpt)
379 TypeBuilder.ResolveUserTypes (types);
383 internal void FixupTokens (Dictionary<int, int> token_map, Dictionary<int, MemberInfo> member_map) {
385 ilgen.FixupTokens (token_map, member_map);
388 internal void GenerateDebugInfo (ISymbolWriter symbolWriter)
390 if (ilgen != null && ilgen.HasDebugInfo) {
391 SymbolToken token = new SymbolToken (GetToken().Token);
392 symbolWriter.OpenMethod (token);
393 symbolWriter.SetSymAttribute (token, "__name", System.Text.Encoding.UTF8.GetBytes (Name));
394 ilgen.GenerateDebugInfo (symbolWriter);
395 symbolWriter.CloseMethod ();
399 internal override int get_next_table_index (object obj, int table, bool inc)
401 return type.get_next_table_index (obj, table, inc);
404 private void RejectIfCreated ()
407 throw new InvalidOperationException ("Type definition of the method is complete.");
410 private Exception not_supported ()
412 return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
415 private Exception not_after_created ()
417 return new InvalidOperationException ("Unable to change after type has been created.");
420 private Exception not_created ()
422 return new NotSupportedException ("The type is not yet created.");
425 void _ConstructorBuilder.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
427 throw new NotImplementedException ();
430 void _ConstructorBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
432 throw new NotImplementedException ();
435 void _ConstructorBuilder.GetTypeInfoCount (out uint pcTInfo)
437 throw new NotImplementedException ();
440 void _ConstructorBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
442 throw new NotImplementedException ();