2009-07-11 Michael Barker <mike@middlesoft.co.uk>
[mono.git] / mcs / class / corlib / System.Reflection.Emit / CustomAttributeBuilder.cs
1
2 //
3 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
4 //
5 // Permission is hereby granted, free of charge, to any person obtaining
6 // a copy of this software and associated documentation files (the
7 // "Software"), to deal in the Software without restriction, including
8 // without limitation the rights to use, copy, modify, merge, publish,
9 // distribute, sublicense, and/or sell copies of the Software, and to
10 // permit persons to whom the Software is furnished to do so, subject to
11 // the following conditions:
12 // 
13 // The above copyright notice and this permission notice shall be
14 // included in all copies or substantial portions of the Software.
15 // 
16 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23 //
24
25 //
26 // System.Reflection.Emit/CustomAttributeBuilder.cs
27 //
28 // Author:
29 //   Paolo Molaro (lupus@ximian.com)
30 //
31 // (C) 2001 Ximian, Inc.  http://www.ximian.com
32 //
33
34 using System;
35 using System.Reflection;
36 using System.Reflection.Emit;
37 using System.Runtime.CompilerServices;
38 using System.Runtime.InteropServices;
39
40 namespace System.Reflection.Emit {
41 #if NET_2_0
42         [ComVisible (true)]
43         [ComDefaultInterface (typeof (_CustomAttributeBuilder))]
44 #endif
45         [ClassInterface (ClassInterfaceType.None)]
46         public class CustomAttributeBuilder : _CustomAttributeBuilder {
47                 ConstructorInfo ctor;
48                 byte[] data;
49
50                 internal ConstructorInfo Ctor {
51                         get {return ctor;}
52                 }
53
54                 internal byte[] Data {
55                         get {return data;}
56                 }
57                 
58                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
59                 static extern byte[] GetBlob(Assembly asmb, ConstructorInfo con, object[] constructorArgs, PropertyInfo[] namedProperties, object[] propertyValues, FieldInfo[] namedFields, object[] fieldValues);
60                 
61                 internal CustomAttributeBuilder( ConstructorInfo con, byte[] cdata) {
62                         ctor = con;
63                         data = (byte[])cdata.Clone ();
64                         /* should we check that the user supplied data is correct? */
65                 }
66                 
67                 public CustomAttributeBuilder( ConstructorInfo con, object[] constructorArgs)
68                 {
69                         Initialize (con, constructorArgs, new PropertyInfo [0], new object [0],
70                                         new FieldInfo [0], new object [0]);
71                 }
72                 public CustomAttributeBuilder( ConstructorInfo con, object[] constructorArgs,
73                                 FieldInfo[] namedFields, object[] fieldValues) 
74                 {
75                         Initialize (con, constructorArgs, new PropertyInfo [0], new object [0],
76                                         namedFields, fieldValues);
77                 }
78                 public CustomAttributeBuilder( ConstructorInfo con, object[] constructorArgs,
79                                 PropertyInfo[] namedProperties, object[] propertyValues)
80                 {
81                         Initialize (con, constructorArgs, namedProperties, propertyValues, new FieldInfo [0],
82                                         new object [0]);
83                 }
84                 public CustomAttributeBuilder( ConstructorInfo con, object[] constructorArgs,
85                                 PropertyInfo[] namedProperties, object[] propertyValues,
86                                 FieldInfo[] namedFields, object[] fieldValues)
87                 {
88                         Initialize (con, constructorArgs, namedProperties, propertyValues, namedFields, fieldValues);
89                 }
90
91                 private bool IsValidType (Type t)
92                 {
93                         /* FIXME: Add more checks */
94                         if (t.IsArray && t.GetArrayRank () > 1)
95                                 return false;
96                         return true;
97                 }
98
99                 private void Initialize (ConstructorInfo con, object [] constructorArgs,
100                                 PropertyInfo [] namedProperties, object [] propertyValues,
101                                 FieldInfo [] namedFields, object [] fieldValues)
102                 {
103                         ctor = con;
104                         if (con == null)
105                                 throw new ArgumentNullException ("con");
106                         if (constructorArgs == null)
107                                 throw new ArgumentNullException ("constructorArgs");
108                         if (namedProperties == null)
109                                 throw new ArgumentNullException ("namedProperties");
110                         if (propertyValues == null)
111                                 throw new ArgumentNullException ("propertyValues");
112                         if (namedFields == null)
113                                 throw new ArgumentNullException ("namedFields");
114                         if (fieldValues == null)
115                                 throw new ArgumentNullException ("fieldValues");
116                         if (con.GetParameterCount () != constructorArgs.Length)
117                                 throw new ArgumentException ("Parameter count does not match " +
118                                                 "passed in argument value count.");
119                         if (namedProperties.Length != propertyValues.Length)
120                                 throw new ArgumentException ("Array lengths must be the same.",
121                                                 "namedProperties, propertyValues");
122                         if (namedFields.Length != fieldValues.Length)
123                                 throw new ArgumentException ("Array lengths must be the same.",
124                                                 "namedFields, fieldValues");
125                         if ((con.Attributes & MethodAttributes.Static) == MethodAttributes.Static ||
126                                         (con.Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Private)
127                                 throw new ArgumentException ("Cannot have private or static constructor.");
128
129                         Type atype = ctor.DeclaringType;
130                         int i;
131                         i = 0;
132                         foreach (FieldInfo fi in namedFields) {
133                                 Type t = fi.DeclaringType;
134                                 if (!IsValidType (t))
135                                         throw new ArgumentException ("Field '" + fi.Name + "' does not have a valid type.");
136                                 if ((atype != t) && (!t.IsSubclassOf (atype)) && (!atype.IsSubclassOf (t)))
137                                         throw new ArgumentException ("Field '" + fi.Name + "' does not belong to the same class as the constructor");
138                                 // FIXME: Check enums and TypeBuilders as well
139                                 if (fieldValues [i] != null)
140                                         // IsEnum does not seem to work on TypeBuilders
141                                         if (!(fi.FieldType is TypeBuilder) && !fi.FieldType.IsEnum && !fi.FieldType.IsInstanceOfType (fieldValues [i])) {
142                                                 //
143                                                 // mcs allways uses object[] for array types and
144                                                 // MS.NET allows this
145                                                 //
146                                                 if (!fi.FieldType.IsArray)
147                                                         throw new ArgumentException ("Value of field '" + fi.Name + "' does not match field type: " + fi.FieldType);
148                                                 }
149                                 i ++;
150                         }
151
152                         i = 0;
153                         foreach (PropertyInfo pi in namedProperties) {
154                                 if (!pi.CanWrite)
155                                         throw new ArgumentException ("Property '" + pi.Name + "' does not have a setter.");
156                                 Type t = pi.DeclaringType;
157                                 if (!IsValidType (t))
158                                         throw new ArgumentException ("Property '" + pi.Name + "' does not have a valid type.");
159                                 if ((atype != t) && (!t.IsSubclassOf (atype)) && (!atype.IsSubclassOf (t)))
160                                         throw new ArgumentException ("Property '" + pi.Name + "' does not belong to the same class as the constructor");
161                                 if (propertyValues [i] != null) {
162                                         if (!(pi.PropertyType is TypeBuilder) && !pi.PropertyType.IsEnum && !pi.PropertyType.IsInstanceOfType (propertyValues [i]))
163                                                 if (!pi.PropertyType.IsArray)
164                                                         throw new ArgumentException ("Value of property '" + pi.Name + "' does not match property type: " + pi.PropertyType + " -> " + propertyValues [i]);
165                                 }
166                                 i ++;
167                         }
168
169                         i = 0;
170                         foreach (ParameterInfo pi in GetParameters (con)) {
171                                 if (pi != null) {
172                                         Type paramType = pi.ParameterType;
173                                         if (!IsValidType (paramType))
174                                                 throw new ArgumentException ("Argument " + i + " does not have a valid type.");
175                                         if (constructorArgs [i] != null)
176                                                 if (!(paramType is TypeBuilder) && !paramType.IsEnum && !paramType.IsInstanceOfType (constructorArgs [i]))
177                                                         if (!paramType.IsArray)
178                                                                 throw new ArgumentException ("Value of argument " + i + " does not match parameter type: " + paramType + " -> " + constructorArgs [i]);
179                                 }
180                                 i ++;
181                         }
182                                 
183                         data = GetBlob (atype.Assembly, con, constructorArgs, namedProperties, propertyValues, namedFields, fieldValues);
184                 }
185
186                 /* helper methods */
187                 internal static int decode_len (byte[] data, int pos, out int rpos) {
188                         int len = 0;
189                         if ((data [pos] & 0x80) == 0) {
190                                 len = (int)(data [pos++] & 0x7f);
191                         } else if ((data [pos] & 0x40) == 0) {
192                                 len = ((data [pos] & 0x3f) << 8) + data [pos + 1];
193                                 pos += 2;
194                         } else {
195                                 len = ((data [pos] & 0x1f) << 24) + (data [pos + 1] << 16) + (data [pos + 2] << 8) + data [pos + 3];
196                                 pos += 4;
197                         }
198                         rpos = pos;
199                         return len;
200                 }
201
202                 internal static string string_from_bytes (byte[] data, int pos, int len) 
203                 {
204                         return System.Text.Encoding.UTF8.GetString(data, pos, len);
205                 }
206
207                 internal string string_arg ()
208                 {
209                         int pos = 2;
210                         int len = decode_len (data, pos, out pos);
211                         return string_from_bytes (data, pos, len);
212                 }                       
213
214                 internal static UnmanagedMarshal get_umarshal (CustomAttributeBuilder customBuilder, bool is_field) {
215                         byte[] data = customBuilder.Data;
216                         UnmanagedType subtype = (UnmanagedType)0x50; /* NATIVE_MAX */
217                         int sizeConst = -1;
218                         int sizeParamIndex = -1;
219                         bool hasSize = false;
220                         int value;
221                         int utype; /* the (stupid) ctor takes a short or an enum ... */
222                         string marshalTypeName = null;
223                         Type marshalTypeRef = null;
224                         string marshalCookie = String.Empty;
225                         utype = (int)data [2];
226                         utype |= ((int)data [3]) << 8;
227
228                         string first_type_name = GetParameters (customBuilder.Ctor) [0].ParameterType.FullName;
229                         int pos = 6;
230                         if (first_type_name == "System.Int16")
231                                 pos = 4;
232                         int nnamed = (int)data [pos++];
233                         nnamed |= ((int)data [pos++]) << 8;
234
235                         for (int i = 0; i < nnamed; ++i) {
236                                 int paramType; // What is this ?
237                                 
238                                 /* Skip field/property signature */
239                                 pos ++;
240                                 /* Read type */
241                                 paramType = ((int)data [pos++]);
242                                 if (paramType == 0x55) {
243                                         /* enums, the value is preceeded by the type */
244                                         int len2 = decode_len (data, pos, out pos);
245                                         string_from_bytes (data, pos, len2);
246                                         pos += len2;
247                                 }
248                                 int len = decode_len (data, pos, out pos);
249                                 string named_name = string_from_bytes (data, pos, len);
250                                 pos += len;
251
252                                 switch (named_name) {
253                                 case "ArraySubType":
254                                         value = (int)data [pos++];
255                                         value |= ((int)data [pos++]) << 8;
256                                         value |= ((int)data [pos++]) << 16;
257                                         value |= ((int)data [pos++]) << 24;
258                                         subtype = (UnmanagedType)value;
259                                         break;
260                                 case "SizeConst":
261                                         value = (int)data [pos++];
262                                         value |= ((int)data [pos++]) << 8;
263                                         value |= ((int)data [pos++]) << 16;
264                                         value |= ((int)data [pos++]) << 24;
265                                         sizeConst = value;
266                                         hasSize = true;
267                                         break;
268                                 case "SafeArraySubType":
269                                         value = (int)data[pos++];
270                                         value |= ((int)data[pos++]) << 8;
271                                         value |= ((int)data[pos++]) << 16;
272                                         value |= ((int)data[pos++]) << 24;
273                                         subtype = (UnmanagedType)value;
274                                         break;
275                                 case "IidParameterIndex":
276                                         pos += 4;
277                                         break;
278                                 case "SafeArrayUserDefinedSubType":
279                                         len = decode_len (data, pos, out pos);
280                                         string_from_bytes (data, pos, len);
281                                         pos += len;
282                                         break;
283                                 case "SizeParamIndex":
284                                         value = (int)data [pos++];
285                                         value |= ((int)data [pos++]) << 8;
286                                         sizeParamIndex = value;
287                                         hasSize = true;
288                                         break;
289                                 case "MarshalType":
290                                         len = decode_len (data, pos, out pos);
291                                         marshalTypeName = string_from_bytes (data, pos, len);
292                                         pos += len;
293                                         break;
294                                 case "MarshalTypeRef":
295                                         len = decode_len (data, pos, out pos);
296                                         marshalTypeName = string_from_bytes (data, pos, len);
297                                         marshalTypeRef = Type.GetType (marshalTypeName);
298                                         pos += len;
299                                         break;
300                                 case "MarshalCookie":
301                                         len = decode_len (data, pos, out pos);
302                                         marshalCookie = string_from_bytes (data, pos, len);
303                                         pos += len;
304                                         break;
305                                 default:
306                                         throw new Exception ("Unknown MarshalAsAttribute field: " + named_name);
307                                 }
308                         }
309
310                         switch ((UnmanagedType)utype) {
311                         case UnmanagedType.LPArray:
312                                 if (hasSize)
313                                         return UnmanagedMarshal.DefineLPArrayInternal (subtype, sizeConst, sizeParamIndex);
314                                 else
315                                         return UnmanagedMarshal.DefineLPArray (subtype);
316                         case UnmanagedType.SafeArray:
317                                 return UnmanagedMarshal.DefineSafeArray (subtype);
318                         case UnmanagedType.ByValArray:
319                                 if (!is_field)
320                                         throw new ArgumentException ("Specified unmanaged type is only valid on fields");
321                         
322                                 return UnmanagedMarshal.DefineByValArray (sizeConst);
323                         case UnmanagedType.ByValTStr:
324                                 return UnmanagedMarshal.DefineByValTStr (sizeConst);
325                         case UnmanagedType.CustomMarshaler:
326                                 return UnmanagedMarshal.DefineCustom (marshalTypeRef, marshalCookie, marshalTypeName, Guid.Empty);
327                         default:
328                                 return UnmanagedMarshal.DefineUnmanagedMarshal ((UnmanagedType)utype);
329                         }
330                 }
331
332                 static Type elementTypeToType (int elementType) {
333                         /* Partition II, section 23.1.16 */
334                         switch (elementType) {
335                         case 0x02:
336                                 return typeof (bool);
337                         case 0x03:
338                                 return typeof (char);
339                         case 0x04:
340                                 return typeof (sbyte);
341                         case 0x05:
342                                 return typeof (byte);
343                         case 0x06:
344                                 return typeof (short);
345                         case 0x07:
346                                 return typeof (ushort);
347                         case 0x08:
348                                 return typeof (int);
349                         case 0x09:
350                                 return typeof (uint);
351                         case 0x0a:
352                                 return typeof (long);
353                         case 0x0b:
354                                 return typeof (ulong);
355                         case 0x0c:
356                                 return typeof (float);
357                         case 0x0d:
358                                 return typeof (double);
359                         case 0x0e:
360                                 return typeof (string);
361                         default:
362                                 throw new Exception ("Unknown element type '" + elementType + "'");
363                         }
364                 }
365
366                 static object decode_cattr_value (Type t, byte[] data, int pos, out int rpos) {
367                         switch (Type.GetTypeCode (t)) {
368                         case TypeCode.String:
369                                 if (data [pos] == 0xff) {
370                                         rpos = pos + 1;
371                                         return null;
372                                 }
373                                 int len = decode_len (data, pos, out pos);
374                                 rpos = pos + len;
375                                 return string_from_bytes (data, pos, len);
376                         case TypeCode.Int32:
377                                 rpos = pos + 4;
378                                 return data [pos] + (data [pos + 1] << 8) + (data [pos + 2] << 16) + (data [pos + 3] << 24);
379                         case TypeCode.Boolean:
380                                 rpos = pos + 1;
381                                 return (data [pos] == 0) ? false : true;
382                         case TypeCode.Object:
383                                 int subtype = data [pos];
384                                 pos += 1;
385
386                                 if (subtype >= 0x02 && subtype <= 0x0e)
387                                         return decode_cattr_value (elementTypeToType (subtype), data, pos, out rpos);
388                                 else
389                                         throw new Exception ("Subtype '" + subtype + "' of type object not yet handled in decode_cattr_value");
390                         default:
391                                 throw new Exception ("FIXME: Type " + t + " not yet handled in decode_cattr_value.");
392                         }
393                 }
394
395                 internal struct CustomAttributeInfo {
396                         public ConstructorInfo ctor;
397                         public object[] ctorArgs;
398                         public string[] namedParamNames;
399                         public object[] namedParamValues;
400                 }
401
402                 internal static CustomAttributeInfo decode_cattr (CustomAttributeBuilder customBuilder) {
403                         byte[] data = customBuilder.Data;
404                         ConstructorInfo ctor = customBuilder.Ctor;
405                         int pos = 0;
406
407                         CustomAttributeInfo info = new CustomAttributeInfo ();
408
409                         // Prolog
410                         if (data.Length < 2)
411                                 throw new Exception ("Custom attr length is only '" + data.Length + "'");
412                         if ((data [0] != 0x1) || (data [1] != 0x00))
413                                 throw new Exception ("Prolog invalid");
414                         pos = 2;
415
416                         ParameterInfo [] pi = GetParameters (ctor);
417                         info.ctor = ctor;
418                         info.ctorArgs = new object [pi.Length];
419                         for (int i = 0; i < pi.Length; ++i)
420                                 info.ctorArgs [i] = decode_cattr_value (pi [i].ParameterType, data, pos, out pos);
421
422                         int num_named = data [pos] + (data [pos + 1] * 256);
423                         pos += 2;
424
425                         info.namedParamNames = new string [num_named];
426                         info.namedParamValues = new object [num_named];
427                         for (int i = 0; i < num_named; ++i) {
428                                 int named_type = data [pos++];
429                                 int data_type = data [pos++];
430                                 string enum_type_name = null;
431
432                                 if (data_type == 0x55) {
433                                         int len2 = decode_len (data, pos, out pos);
434                                         enum_type_name = string_from_bytes (data, pos, len2);
435                                         pos += len2;
436                                 }
437
438                                 int len = decode_len (data, pos, out pos);
439                                 string name = string_from_bytes (data, pos, len);
440                                 info.namedParamNames [i] = name;
441                                 pos += len;
442
443                                 if (named_type == 0x53) {
444                                         /* Field */
445                                         FieldInfo fi = ctor.DeclaringType.GetField (name, BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Instance);
446                                         if (fi == null)
447                                                 throw new Exception ("Custom attribute type '" + ctor.DeclaringType + "' doesn't contain a field named '" + name + "'");
448
449                                         object val = decode_cattr_value (fi.FieldType, data, pos, out pos);
450                                         if (enum_type_name != null) {
451                                                 Type enumType = Type.GetType (enum_type_name);
452                                                 val = Enum.ToObject (enumType, val);
453                                         }
454
455                                         info.namedParamValues [i] = val;
456                                 }
457                                 else
458                                         // FIXME:
459                                         throw new Exception ("Unknown named type: " + named_type);
460                         }
461
462                         return info;
463                 }
464
465                 void _CustomAttributeBuilder.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
466                 {
467                         throw new NotImplementedException ();
468                 }
469
470                 void _CustomAttributeBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
471                 {
472                         throw new NotImplementedException ();
473                 }
474
475                 void _CustomAttributeBuilder.GetTypeInfoCount (out uint pcTInfo)
476                 {
477                         throw new NotImplementedException ();
478                 }
479
480                 void _CustomAttributeBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
481                 {
482                         throw new NotImplementedException ();
483                 }
484
485                 static ParameterInfo [] GetParameters (ConstructorInfo ctor)
486                 {
487                         ConstructorBuilder cb = ctor as ConstructorBuilder;
488                         if (cb != null)
489                                 return cb.GetParametersInternal ();
490                         return ctor.GetParameters ();
491                 }
492         }
493 }