Merge pull request #409 from Alkarex/patch-1
[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 #if !FULL_AOT_RUNTIME
35 using System;
36 using System.Reflection;
37 using System.Reflection.Emit;
38 using System.Runtime.CompilerServices;
39 using System.Runtime.InteropServices;
40
41 namespace System.Reflection.Emit {
42         [ComVisible (true)]
43         [ComDefaultInterface (typeof (_CustomAttributeBuilder))]
44         [ClassInterface (ClassInterfaceType.None)]
45         [StructLayout (LayoutKind.Sequential)]
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                         if (t is TypeBuilder && t.IsEnum) {
97                                 // Check that the enum is properly constructed, the unmanaged code
98                                 // depends on this
99                                 Enum.GetUnderlyingType (t);
100                         }
101                         if (t.IsClass && !(t.IsArray || t == typeof (object) || t == typeof (Type) || t == typeof (string) || t.Assembly.GetName ().Name == "mscorlib"))
102                                 return false;
103                         if (t.IsValueType && !(t.IsPrimitive || t.IsEnum || ((t.Assembly is AssemblyBuilder) && t.Assembly.GetName ().Name == "mscorlib")))
104                                 return false;
105                         return true;
106                 }
107
108                 private bool IsValidParam (object o, Type paramType)
109                 {
110                         Type t = o.GetType ();
111                         if (!IsValidType (t))
112                                 return false;
113                         if (paramType == typeof (object)) {
114                                 if (t.IsArray && t.GetArrayRank () == 1)
115                                         return IsValidType (t.GetElementType ());
116                                 if (!t.IsPrimitive && !typeof (Type).IsAssignableFrom (t) && t != typeof (string) && !t.IsEnum)
117                                         return false;
118                         }
119                         return true;
120                 }
121
122                 static bool IsValidValue (Type type, object value) {
123                         if (type.IsValueType && value == null)
124                                 return false;
125                         if (type.IsArray && type.GetElementType ().IsValueType) {
126                                 foreach (var v in (Array)value) {
127                                         if (v == null)
128                                                 return false;
129                                 }
130                         }
131                         return true;
132                 } 
133
134                 private void Initialize (ConstructorInfo con, object [] constructorArgs,
135                                 PropertyInfo [] namedProperties, object [] propertyValues,
136                                 FieldInfo [] namedFields, object [] fieldValues)
137                 {
138                         ctor = con;
139                         if (con == null)
140                                 throw new ArgumentNullException ("con");
141                         if (constructorArgs == null)
142                                 throw new ArgumentNullException ("constructorArgs");
143                         if (namedProperties == null)
144                                 throw new ArgumentNullException ("namedProperties");
145                         if (propertyValues == null)
146                                 throw new ArgumentNullException ("propertyValues");
147                         if (namedFields == null)
148                                 throw new ArgumentNullException ("namedFields");
149                         if (fieldValues == null)
150                                 throw new ArgumentNullException ("fieldValues");
151                         if (con.GetParameterCount () != constructorArgs.Length)
152                                 throw new ArgumentException ("Parameter count does not match " +
153                                                 "passed in argument value count.");
154                         if (namedProperties.Length != propertyValues.Length)
155                                 throw new ArgumentException ("Array lengths must be the same.",
156                                                 "namedProperties, propertyValues");
157                         if (namedFields.Length != fieldValues.Length)
158                                 throw new ArgumentException ("Array lengths must be the same.",
159                                                 "namedFields, fieldValues");
160                         if ((con.Attributes & MethodAttributes.Static) == MethodAttributes.Static ||
161                                         (con.Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Private)
162                                 throw new ArgumentException ("Cannot have private or static constructor.");
163
164                         Type atype = ctor.DeclaringType;
165                         int i;
166                         i = 0;
167                         foreach (FieldInfo fi in namedFields) {
168                                 Type t = fi.DeclaringType;
169                                 if ((atype != t) && (!t.IsSubclassOf (atype)) && (!atype.IsSubclassOf (t)))
170                                         throw new ArgumentException ("Field '" + fi.Name + "' does not belong to the same class as the constructor");
171                                 if (!IsValidType (fi.FieldType))
172                                         throw new ArgumentException ("Field '" + fi.Name + "' does not have a valid type.");
173                                 if (!IsValidValue (fi.FieldType, fieldValues [i]))
174                                         throw new ArgumentException ("Field " + fi.Name + " is not a valid value.");
175                                 // FIXME: Check enums and TypeBuilders as well
176                                 if (fieldValues [i] != null)
177                                         // IsEnum does not seem to work on TypeBuilders
178                                         if (!(fi.FieldType is TypeBuilder) && !fi.FieldType.IsEnum && !fi.FieldType.IsInstanceOfType (fieldValues [i])) {
179                                                 //
180                                                 // mcs allways uses object[] for array types and
181                                                 // MS.NET allows this
182                                                 //
183                                                 if (!fi.FieldType.IsArray)
184                                                         throw new ArgumentException ("Value of field '" + fi.Name + "' does not match field type: " + fi.FieldType);
185                                                 }
186                                 i ++;
187                         }
188
189                         i = 0;
190                         foreach (PropertyInfo pi in namedProperties) {
191                                 if (!pi.CanWrite)
192                                         throw new ArgumentException ("Property '" + pi.Name + "' does not have a setter.");
193                                 Type t = pi.DeclaringType;
194                                 if ((atype != t) && (!t.IsSubclassOf (atype)) && (!atype.IsSubclassOf (t)))
195                                         throw new ArgumentException ("Property '" + pi.Name + "' does not belong to the same class as the constructor");
196                                 if (!IsValidType (pi.PropertyType))
197                                         throw new ArgumentException ("Property '" + pi.Name + "' does not have a valid type.");
198                                 if (!IsValidValue (pi.PropertyType, propertyValues [i]))
199                                         throw new ArgumentException ("Property " + pi.Name + " is not a valid value.");
200                                 if (propertyValues [i] != null) {
201                                         if (!(pi.PropertyType is TypeBuilder) && !pi.PropertyType.IsEnum && !pi.PropertyType.IsInstanceOfType (propertyValues [i]))
202                                                 if (!pi.PropertyType.IsArray)
203                                                         throw new ArgumentException ("Value of property '" + pi.Name + "' does not match property type: " + pi.PropertyType + " -> " + propertyValues [i]);
204                                 }
205                                 i ++;
206                         }
207
208                         i = 0;
209                         foreach (ParameterInfo pi in GetParameters (con)) {
210                                 if (pi != null) {
211                                         Type paramType = pi.ParameterType;
212                                         if (!IsValidType (paramType))
213                                                 throw new ArgumentException ("Parameter " + i + " does not have a valid type.");
214                                         if (!IsValidValue (paramType, constructorArgs [i]))
215                                                 throw new ArgumentException ("Parameter " + i + " is not a valid value.");
216                                         
217                                         if (constructorArgs [i] != null) {
218                                                 if (!(paramType is TypeBuilder) && !paramType.IsEnum && !paramType.IsInstanceOfType (constructorArgs [i]))
219                                                         if (!paramType.IsArray)
220                                                                 throw new ArgumentException ("Value of argument " + i + " does not match parameter type: " + paramType + " -> " + constructorArgs [i]);
221                                                 if (!IsValidParam (constructorArgs [i], paramType))
222                                                         throw new ArgumentException ("Cannot emit a CustomAttribute with argument of type " + constructorArgs [i].GetType () + "."); 
223                                         }
224                                 }
225                                 i ++;
226                         }
227                                 
228                         data = GetBlob (atype.Assembly, con, constructorArgs, namedProperties, propertyValues, namedFields, fieldValues);
229                 }
230
231                 /* helper methods */
232                 internal static int decode_len (byte[] data, int pos, out int rpos) {
233                         int len = 0;
234                         if ((data [pos] & 0x80) == 0) {
235                                 len = (int)(data [pos++] & 0x7f);
236                         } else if ((data [pos] & 0x40) == 0) {
237                                 len = ((data [pos] & 0x3f) << 8) + data [pos + 1];
238                                 pos += 2;
239                         } else {
240                                 len = ((data [pos] & 0x1f) << 24) + (data [pos + 1] << 16) + (data [pos + 2] << 8) + data [pos + 3];
241                                 pos += 4;
242                         }
243                         rpos = pos;
244                         return len;
245                 }
246
247                 internal static string string_from_bytes (byte[] data, int pos, int len) 
248                 {
249                         return System.Text.Encoding.UTF8.GetString(data, pos, len);
250                 }
251
252                 internal string string_arg ()
253                 {
254                         int pos = 2;
255                         int len = decode_len (data, pos, out pos);
256                         return string_from_bytes (data, pos, len);
257                 }                       
258
259                 internal static UnmanagedMarshal get_umarshal (CustomAttributeBuilder customBuilder, bool is_field) {
260                         byte[] data = customBuilder.Data;
261                         UnmanagedType subtype = (UnmanagedType)0x50; /* NATIVE_MAX */
262                         int sizeConst = -1;
263                         int sizeParamIndex = -1;
264                         bool hasSize = false;
265                         int value;
266                         int utype; /* the (stupid) ctor takes a short or an enum ... */
267                         string marshalTypeName = null;
268                         Type marshalTypeRef = null;
269                         string marshalCookie = String.Empty;
270                         utype = (int)data [2];
271                         utype |= ((int)data [3]) << 8;
272
273                         string first_type_name = GetParameters (customBuilder.Ctor) [0].ParameterType.FullName;
274                         int pos = 6;
275                         if (first_type_name == "System.Int16")
276                                 pos = 4;
277                         int nnamed = (int)data [pos++];
278                         nnamed |= ((int)data [pos++]) << 8;
279
280                         for (int i = 0; i < nnamed; ++i) {
281                                 int paramType; // What is this ?
282                                 
283                                 /* Skip field/property signature */
284                                 pos ++;
285                                 /* Read type */
286                                 paramType = ((int)data [pos++]);
287                                 if (paramType == 0x55) {
288                                         /* enums, the value is preceeded by the type */
289                                         int len2 = decode_len (data, pos, out pos);
290                                         string_from_bytes (data, pos, len2);
291                                         pos += len2;
292                                 }
293                                 int len = decode_len (data, pos, out pos);
294                                 string named_name = string_from_bytes (data, pos, len);
295                                 pos += len;
296
297                                 switch (named_name) {
298                                 case "ArraySubType":
299                                         value = (int)data [pos++];
300                                         value |= ((int)data [pos++]) << 8;
301                                         value |= ((int)data [pos++]) << 16;
302                                         value |= ((int)data [pos++]) << 24;
303                                         subtype = (UnmanagedType)value;
304                                         break;
305                                 case "SizeConst":
306                                         value = (int)data [pos++];
307                                         value |= ((int)data [pos++]) << 8;
308                                         value |= ((int)data [pos++]) << 16;
309                                         value |= ((int)data [pos++]) << 24;
310                                         sizeConst = value;
311                                         hasSize = true;
312                                         break;
313                                 case "SafeArraySubType":
314                                         value = (int)data[pos++];
315                                         value |= ((int)data[pos++]) << 8;
316                                         value |= ((int)data[pos++]) << 16;
317                                         value |= ((int)data[pos++]) << 24;
318                                         subtype = (UnmanagedType)value;
319                                         break;
320                                 case "IidParameterIndex":
321                                         pos += 4;
322                                         break;
323                                 case "SafeArrayUserDefinedSubType":
324                                         len = decode_len (data, pos, out pos);
325                                         string_from_bytes (data, pos, len);
326                                         pos += len;
327                                         break;
328                                 case "SizeParamIndex":
329                                         value = (int)data [pos++];
330                                         value |= ((int)data [pos++]) << 8;
331                                         sizeParamIndex = value;
332                                         hasSize = true;
333                                         break;
334                                 case "MarshalType":
335                                         len = decode_len (data, pos, out pos);
336                                         marshalTypeName = string_from_bytes (data, pos, len);
337                                         pos += len;
338                                         break;
339                                 case "MarshalTypeRef":
340                                         len = decode_len (data, pos, out pos);
341                                         marshalTypeName = string_from_bytes (data, pos, len);
342                                         marshalTypeRef = Type.GetType (marshalTypeName);
343                                         pos += len;
344                                         break;
345                                 case "MarshalCookie":
346                                         len = decode_len (data, pos, out pos);
347                                         marshalCookie = string_from_bytes (data, pos, len);
348                                         pos += len;
349                                         break;
350                                 default:
351                                         throw new Exception ("Unknown MarshalAsAttribute field: " + named_name);
352                                 }
353                         }
354
355                         switch ((UnmanagedType)utype) {
356                         case UnmanagedType.LPArray:
357                                 if (hasSize)
358                                         return UnmanagedMarshal.DefineLPArrayInternal (subtype, sizeConst, sizeParamIndex);
359                                 else
360                                         return UnmanagedMarshal.DefineLPArray (subtype);
361                         case UnmanagedType.SafeArray:
362                                 return UnmanagedMarshal.DefineSafeArray (subtype);
363                         case UnmanagedType.ByValArray:
364                                 if (!is_field)
365                                         throw new ArgumentException ("Specified unmanaged type is only valid on fields");
366                         
367                                 return UnmanagedMarshal.DefineByValArray (sizeConst);
368                         case UnmanagedType.ByValTStr:
369                                 return UnmanagedMarshal.DefineByValTStr (sizeConst);
370                         case UnmanagedType.CustomMarshaler:
371                                 return UnmanagedMarshal.DefineCustom (marshalTypeRef, marshalCookie, marshalTypeName, Guid.Empty);
372                         default:
373                                 return UnmanagedMarshal.DefineUnmanagedMarshal ((UnmanagedType)utype);
374                         }
375                 }
376
377                 static Type elementTypeToType (int elementType) {
378                         /* Partition II, section 23.1.16 */
379                         switch (elementType) {
380                         case 0x02:
381                                 return typeof (bool);
382                         case 0x03:
383                                 return typeof (char);
384                         case 0x04:
385                                 return typeof (sbyte);
386                         case 0x05:
387                                 return typeof (byte);
388                         case 0x06:
389                                 return typeof (short);
390                         case 0x07:
391                                 return typeof (ushort);
392                         case 0x08:
393                                 return typeof (int);
394                         case 0x09:
395                                 return typeof (uint);
396                         case 0x0a:
397                                 return typeof (long);
398                         case 0x0b:
399                                 return typeof (ulong);
400                         case 0x0c:
401                                 return typeof (float);
402                         case 0x0d:
403                                 return typeof (double);
404                         case 0x0e:
405                                 return typeof (string);
406                         default:
407                                 throw new Exception ("Unknown element type '" + elementType + "'");
408                         }
409                 }
410
411                 static object decode_cattr_value (Type t, byte[] data, int pos, out int rpos) {
412                         switch (Type.GetTypeCode (t)) {
413                         case TypeCode.String:
414                                 if (data [pos] == 0xff) {
415                                         rpos = pos + 1;
416                                         return null;
417                                 }
418                                 int len = decode_len (data, pos, out pos);
419                                 rpos = pos + len;
420                                 return string_from_bytes (data, pos, len);
421                         case TypeCode.Int32:
422                                 rpos = pos + 4;
423                                 return data [pos] + (data [pos + 1] << 8) + (data [pos + 2] << 16) + (data [pos + 3] << 24);
424                         case TypeCode.Boolean:
425                                 rpos = pos + 1;
426                                 return (data [pos] == 0) ? false : true;
427                         case TypeCode.Object:
428                                 int subtype = data [pos];
429                                 pos += 1;
430
431                                 if (subtype >= 0x02 && subtype <= 0x0e)
432                                         return decode_cattr_value (elementTypeToType (subtype), data, pos, out rpos);
433                                 else
434                                         throw new Exception ("Subtype '" + subtype + "' of type object not yet handled in decode_cattr_value");
435                         default:
436                                 throw new Exception ("FIXME: Type " + t + " not yet handled in decode_cattr_value.");
437                         }
438                 }
439
440                 internal struct CustomAttributeInfo {
441                         public ConstructorInfo ctor;
442                         public object[] ctorArgs;
443                         public string[] namedParamNames;
444                         public object[] namedParamValues;
445                 }
446
447                 internal static CustomAttributeInfo decode_cattr (CustomAttributeBuilder customBuilder) {
448                         byte[] data = customBuilder.Data;
449                         ConstructorInfo ctor = customBuilder.Ctor;
450                         int pos = 0;
451
452                         CustomAttributeInfo info = new CustomAttributeInfo ();
453
454                         // Prolog
455                         if (data.Length < 2)
456                                 throw new Exception ("Custom attr length is only '" + data.Length + "'");
457                         if ((data [0] != 0x1) || (data [1] != 0x00))
458                                 throw new Exception ("Prolog invalid");
459                         pos = 2;
460
461                         ParameterInfo [] pi = GetParameters (ctor);
462                         info.ctor = ctor;
463                         info.ctorArgs = new object [pi.Length];
464                         for (int i = 0; i < pi.Length; ++i)
465                                 info.ctorArgs [i] = decode_cattr_value (pi [i].ParameterType, data, pos, out pos);
466
467                         int num_named = data [pos] + (data [pos + 1] * 256);
468                         pos += 2;
469
470                         info.namedParamNames = new string [num_named];
471                         info.namedParamValues = new object [num_named];
472                         for (int i = 0; i < num_named; ++i) {
473                                 int named_type = data [pos++];
474                                 int data_type = data [pos++];
475                                 string enum_type_name = null;
476
477                                 if (data_type == 0x55) {
478                                         int len2 = decode_len (data, pos, out pos);
479                                         enum_type_name = string_from_bytes (data, pos, len2);
480                                         pos += len2;
481                                 }
482
483                                 int len = decode_len (data, pos, out pos);
484                                 string name = string_from_bytes (data, pos, len);
485                                 info.namedParamNames [i] = name;
486                                 pos += len;
487
488                                 if (named_type == 0x53) {
489                                         /* Field */
490                                         FieldInfo fi = ctor.DeclaringType.GetField (name, BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Instance);
491                                         if (fi == null)
492                                                 throw new Exception ("Custom attribute type '" + ctor.DeclaringType + "' doesn't contain a field named '" + name + "'");
493
494                                         object val = decode_cattr_value (fi.FieldType, data, pos, out pos);
495                                         if (enum_type_name != null) {
496                                                 Type enumType = Type.GetType (enum_type_name);
497                                                 val = Enum.ToObject (enumType, val);
498                                         }
499
500                                         info.namedParamValues [i] = val;
501                                 }
502                                 else
503                                         // FIXME:
504                                         throw new Exception ("Unknown named type: " + named_type);
505                         }
506
507                         return info;
508                 }
509
510                 void _CustomAttributeBuilder.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
511                 {
512                         throw new NotImplementedException ();
513                 }
514
515                 void _CustomAttributeBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
516                 {
517                         throw new NotImplementedException ();
518                 }
519
520                 void _CustomAttributeBuilder.GetTypeInfoCount (out uint pcTInfo)
521                 {
522                         throw new NotImplementedException ();
523                 }
524
525                 void _CustomAttributeBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
526                 {
527                         throw new NotImplementedException ();
528                 }
529
530                 static ParameterInfo [] GetParameters (ConstructorInfo ctor)
531                 {
532                         ConstructorBuilder cb = ctor as ConstructorBuilder;
533                         if (cb != null)
534                                 return cb.GetParametersInternal ();
535                         return ctor.GetParameters ();
536                 }
537         }
538 }
539 #endif