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