2007-11-14 Atsushi Enomoto <atsushi@ximian.com>
[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 con.GetParameters ()) {
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 = customBuilder.Ctor.GetParameters()[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                                 paramType = (int)data [pos++];
238                                 paramType |= ((int)data [pos++]) << 8;
239                                 int len = decode_len (data, pos, out pos);
240                                 string named_name = string_from_bytes (data, pos, len);
241                                 pos += len;
242
243                                 switch (named_name) {
244                                 case "ArraySubType":
245                                         value = (int)data [pos++];
246                                         value |= ((int)data [pos++]) << 8;
247                                         value |= ((int)data [pos++]) << 16;
248                                         value |= ((int)data [pos++]) << 24;
249                                         subtype = (UnmanagedType)value;
250                                         break;
251                                 case "SizeConst":
252                                         value = (int)data [pos++];
253                                         value |= ((int)data [pos++]) << 8;
254                                         value |= ((int)data [pos++]) << 16;
255                                         value |= ((int)data [pos++]) << 24;
256                                         sizeConst = value;
257                                         hasSize = true;
258                                         break;
259                                 case "SizeParamIndex":
260                                         value = (int)data [pos++];
261                                         value |= ((int)data [pos++]) << 8;
262                                         sizeParamIndex = value;
263                                         hasSize = true;
264                                         break;
265                                 case "MarshalType":
266                                         len = decode_len (data, pos, out pos);
267                                         marshalTypeName = string_from_bytes (data, pos, len);
268                                         pos += len;
269                                         break;
270                                 case "MarshalTypeRef":
271                                         len = decode_len (data, pos, out pos);
272                                         marshalTypeName = string_from_bytes (data, pos, len);
273                                         marshalTypeRef = Type.GetType (marshalTypeName);
274                                         pos += len;
275                                         break;
276                                 case "MarshalCookie":
277                                         len = decode_len (data, pos, out pos);
278                                         marshalCookie = string_from_bytes (data, pos, len);
279                                         pos += len;
280                                         break;
281                                 default:
282                                         len = decode_len(data, pos, out pos);
283                                         string_from_bytes (data, pos, len);
284                                         pos += len;
285                                         break;
286                                 }
287                         }
288
289                         switch ((UnmanagedType)utype) {
290                         case UnmanagedType.LPArray:
291                                 if (hasSize)
292                                         return UnmanagedMarshal.DefineLPArrayInternal (subtype, sizeConst, sizeParamIndex);
293                                 else
294                                         return UnmanagedMarshal.DefineLPArray (subtype);
295                         case UnmanagedType.SafeArray:
296                                 return UnmanagedMarshal.DefineSafeArray (subtype);
297                         case UnmanagedType.ByValArray:
298                                 return UnmanagedMarshal.DefineByValArray (sizeConst);
299                         case UnmanagedType.ByValTStr:
300                                 return UnmanagedMarshal.DefineByValTStr (sizeConst);
301                         case UnmanagedType.CustomMarshaler:
302                                 return UnmanagedMarshal.DefineCustom (marshalTypeRef, marshalCookie, marshalTypeName, Guid.Empty);
303                         default:
304                                 return UnmanagedMarshal.DefineUnmanagedMarshal ((UnmanagedType)utype);
305                         }
306                 }
307
308                 static Type elementTypeToType (int elementType) {
309                         /* Partition II, section 23.1.16 */
310                         switch (elementType) {
311                         case 0x02:
312                                 return typeof (bool);
313                         case 0x03:
314                                 return typeof (char);
315                         case 0x04:
316                                 return typeof (sbyte);
317                         case 0x05:
318                                 return typeof (byte);
319                         case 0x06:
320                                 return typeof (short);
321                         case 0x07:
322                                 return typeof (ushort);
323                         case 0x08:
324                                 return typeof (int);
325                         case 0x09:
326                                 return typeof (uint);
327                         case 0x0a:
328                                 return typeof (long);
329                         case 0x0b:
330                                 return typeof (ulong);
331                         case 0x0c:
332                                 return typeof (float);
333                         case 0x0d:
334                                 return typeof (double);
335                         case 0x0e:
336                                 return typeof (string);
337                         default:
338                                 throw new Exception ("Unknown element type '" + elementType + "'");
339                         }
340                 }
341
342                 static object decode_cattr_value (Type t, byte[] data, int pos, out int rpos) {
343                         switch (Type.GetTypeCode (t)) {
344                         case TypeCode.String:
345                                 if (data [pos] == 0xff) {
346                                         rpos = pos + 1;
347                                         return null;
348                                 }
349                                 int len = decode_len (data, pos, out pos);
350                                 rpos = pos + len;
351                                 return string_from_bytes (data, pos, len);
352                         case TypeCode.Int32:
353                                 rpos = pos + 4;
354                                 return data [pos] + (data [pos + 1] << 8) + (data [pos + 2] << 16) + (data [pos + 3] << 24);
355                         case TypeCode.Boolean:
356                                 rpos = pos + 1;
357                                 return (data [pos] == 0) ? false : true;
358                         case TypeCode.Object:
359                                 int subtype = data [pos];
360                                 pos += 1;
361
362                                 if (subtype >= 0x02 && subtype <= 0x0e)
363                                         return decode_cattr_value (elementTypeToType (subtype), data, pos, out rpos);
364                                 else
365                                         throw new Exception ("Subtype '" + subtype + "' of type object not yet handled in decode_cattr_value");
366                         default:
367                                 throw new Exception ("FIXME: Type " + t + " not yet handled in decode_cattr_value.");
368                         }
369                 }
370
371                 internal struct CustomAttributeInfo {
372                         public ConstructorInfo ctor;
373                         public object[] ctorArgs;
374                         public string[] namedParamNames;
375                         public object[] namedParamValues;
376                 }
377
378                 internal static CustomAttributeInfo decode_cattr (CustomAttributeBuilder customBuilder) {
379                         byte[] data = customBuilder.Data;
380                         ConstructorInfo ctor = customBuilder.Ctor;
381                         int pos = 0;
382
383                         CustomAttributeInfo info = new CustomAttributeInfo ();
384
385                         // Prolog
386                         if (data.Length < 2)
387                                 throw new Exception ("Custom attr length is only '" + data.Length + "'");
388                         if ((data [0] != 0x1) || (data [1] != 0x00))
389                                 throw new Exception ("Prolog invalid");
390                         pos = 2;
391
392                         ParameterInfo [] pi = ctor.GetParameters ();
393                         info.ctor = ctor;
394                         info.ctorArgs = new object [pi.Length];
395                         for (int i = 0; i < pi.Length; ++i)
396                                 info.ctorArgs [i] = decode_cattr_value (pi [i].ParameterType, data, pos, out pos);
397
398                         int num_named = data [pos] + (data [pos + 1] * 256);
399                         pos += 2;
400
401                         info.namedParamNames = new string [num_named];
402                         info.namedParamValues = new object [num_named];
403                         for (int i = 0; i < num_named; ++i) {
404                                 int named_type = data [pos++];
405                                 int data_type = data [pos++];
406                                 string enum_type_name = null;
407
408                                 if (data_type == 0x55) {
409                                         int len2 = decode_len (data, pos, out pos);
410                                         enum_type_name = string_from_bytes (data, pos, len2);
411                                         pos += len2;
412                                 }
413
414                                 int len = decode_len (data, pos, out pos);
415                                 string name = string_from_bytes (data, pos, len);
416                                 info.namedParamNames [i] = name;
417                                 pos += len;
418
419                                 if (named_type == 0x53) {
420                                         /* Field */
421                                         FieldInfo fi = ctor.DeclaringType.GetField (name, BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Instance);
422                                         if (fi == null)
423                                                 throw new Exception ("Custom attribute type '" + ctor.DeclaringType + "' doesn't contain a field named '" + name + "'");
424
425                                         object val = decode_cattr_value (fi.FieldType, data, pos, out pos);
426                                         if (enum_type_name != null) {
427                                                 Type enumType = Type.GetType (enum_type_name);
428                                                 val = Enum.ToObject (enumType, val);
429                                         }
430
431                                         info.namedParamValues [i] = val;
432                                 }
433                                 else
434                                         // FIXME:
435                                         throw new Exception ("Unknown named type: " + named_type);
436                         }
437
438                         return info;
439                 }
440
441                 void _CustomAttributeBuilder.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
442                 {
443                         throw new NotImplementedException ();
444                 }
445
446                 void _CustomAttributeBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
447                 {
448                         throw new NotImplementedException ();
449                 }
450
451                 void _CustomAttributeBuilder.GetTypeInfoCount (out uint pcTInfo)
452                 {
453                         throw new NotImplementedException ();
454                 }
455
456                 void _CustomAttributeBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
457                 {
458                         throw new NotImplementedException ();
459                 }
460         }
461 }