Merge pull request #2542 from akoeplinger/remove-changelog
[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.GetParametersCount () != 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 #if FEATURE_COMINTEROP
362                         case UnmanagedType.SafeArray:
363                                 return UnmanagedMarshal.DefineSafeArray (subtype);
364 #endif
365                         case UnmanagedType.ByValArray:
366                                 if (!is_field)
367                                         throw new ArgumentException ("Specified unmanaged type is only valid on fields");
368                         
369                                 return UnmanagedMarshal.DefineByValArray (sizeConst);
370                         case UnmanagedType.ByValTStr:
371                                 return UnmanagedMarshal.DefineByValTStr (sizeConst);
372 #if FEATURE_COMINTEROP
373                         case UnmanagedType.CustomMarshaler:
374                                 return UnmanagedMarshal.DefineCustom (marshalTypeRef, marshalCookie, marshalTypeName, Guid.Empty);
375 #endif
376                         default:
377                                 return UnmanagedMarshal.DefineUnmanagedMarshal ((UnmanagedType)utype);
378                         }
379                 }
380
381                 static Type elementTypeToType (int elementType) {
382                         /* Partition II, section 23.1.16 */
383                         switch (elementType) {
384                         case 0x02:
385                                 return typeof (bool);
386                         case 0x03:
387                                 return typeof (char);
388                         case 0x04:
389                                 return typeof (sbyte);
390                         case 0x05:
391                                 return typeof (byte);
392                         case 0x06:
393                                 return typeof (short);
394                         case 0x07:
395                                 return typeof (ushort);
396                         case 0x08:
397                                 return typeof (int);
398                         case 0x09:
399                                 return typeof (uint);
400                         case 0x0a:
401                                 return typeof (long);
402                         case 0x0b:
403                                 return typeof (ulong);
404                         case 0x0c:
405                                 return typeof (float);
406                         case 0x0d:
407                                 return typeof (double);
408                         case 0x0e:
409                                 return typeof (string);
410                         default:
411                                 throw new Exception ("Unknown element type '" + elementType + "'");
412                         }
413                 }
414
415                 static object decode_cattr_value (Type t, byte[] data, int pos, out int rpos) {
416                         switch (Type.GetTypeCode (t)) {
417                         case TypeCode.String:
418                                 if (data [pos] == 0xff) {
419                                         rpos = pos + 1;
420                                         return null;
421                                 }
422                                 int len = decode_len (data, pos, out pos);
423                                 rpos = pos + len;
424                                 return string_from_bytes (data, pos, len);
425                         case TypeCode.Int32:
426                                 rpos = pos + 4;
427                                 return data [pos] + (data [pos + 1] << 8) + (data [pos + 2] << 16) + (data [pos + 3] << 24);
428                         case TypeCode.Boolean:
429                                 rpos = pos + 1;
430                                 return (data [pos] == 0) ? false : true;
431                         case TypeCode.Object:
432                                 int subtype = data [pos];
433                                 pos += 1;
434
435                                 if (subtype >= 0x02 && subtype <= 0x0e)
436                                         return decode_cattr_value (elementTypeToType (subtype), data, pos, out rpos);
437                                 else
438                                         throw new Exception ("Subtype '" + subtype + "' of type object not yet handled in decode_cattr_value");
439                         default:
440                                 throw new Exception ("FIXME: Type " + t + " not yet handled in decode_cattr_value.");
441                         }
442                 }
443
444                 internal struct CustomAttributeInfo {
445                         public ConstructorInfo ctor;
446                         public object[] ctorArgs;
447                         public string[] namedParamNames;
448                         public object[] namedParamValues;
449                 }
450
451                 internal static CustomAttributeInfo decode_cattr (CustomAttributeBuilder customBuilder) {
452                         byte[] data = customBuilder.Data;
453                         ConstructorInfo ctor = customBuilder.Ctor;
454                         int pos = 0;
455
456                         CustomAttributeInfo info = new CustomAttributeInfo ();
457
458                         // Prolog
459                         if (data.Length < 2)
460                                 throw new Exception ("Custom attr length is only '" + data.Length + "'");
461                         if ((data [0] != 0x1) || (data [1] != 0x00))
462                                 throw new Exception ("Prolog invalid");
463                         pos = 2;
464
465                         ParameterInfo [] pi = GetParameters (ctor);
466                         info.ctor = ctor;
467                         info.ctorArgs = new object [pi.Length];
468                         for (int i = 0; i < pi.Length; ++i)
469                                 info.ctorArgs [i] = decode_cattr_value (pi [i].ParameterType, data, pos, out pos);
470
471                         int num_named = data [pos] + (data [pos + 1] * 256);
472                         pos += 2;
473
474                         info.namedParamNames = new string [num_named];
475                         info.namedParamValues = new object [num_named];
476                         for (int i = 0; i < num_named; ++i) {
477                                 int named_type = data [pos++];
478                                 int data_type = data [pos++];
479                                 string enum_type_name = null;
480
481                                 if (data_type == 0x55) {
482                                         int len2 = decode_len (data, pos, out pos);
483                                         enum_type_name = string_from_bytes (data, pos, len2);
484                                         pos += len2;
485                                 }
486
487                                 int len = decode_len (data, pos, out pos);
488                                 string name = string_from_bytes (data, pos, len);
489                                 info.namedParamNames [i] = name;
490                                 pos += len;
491
492                                 if (named_type == 0x53) {
493                                         /* Field */
494                                         FieldInfo fi = ctor.DeclaringType.GetField (name, BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Instance);
495                                         if (fi == null)
496                                                 throw new Exception ("Custom attribute type '" + ctor.DeclaringType + "' doesn't contain a field named '" + name + "'");
497
498                                         object val = decode_cattr_value (fi.FieldType, data, pos, out pos);
499                                         if (enum_type_name != null) {
500                                                 Type enumType = Type.GetType (enum_type_name);
501                                                 val = Enum.ToObject (enumType, val);
502                                         }
503
504                                         info.namedParamValues [i] = val;
505                                 }
506                                 else
507                                         // FIXME:
508                                         throw new Exception ("Unknown named type: " + named_type);
509                         }
510
511                         return info;
512                 }
513
514                 void _CustomAttributeBuilder.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
515                 {
516                         throw new NotImplementedException ();
517                 }
518
519                 void _CustomAttributeBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
520                 {
521                         throw new NotImplementedException ();
522                 }
523
524                 void _CustomAttributeBuilder.GetTypeInfoCount (out uint pcTInfo)
525                 {
526                         throw new NotImplementedException ();
527                 }
528
529                 void _CustomAttributeBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
530                 {
531                         throw new NotImplementedException ();
532                 }
533
534                 static ParameterInfo [] GetParameters (ConstructorInfo ctor)
535                 {
536                         ConstructorBuilder cb = ctor as ConstructorBuilder;
537                         if (cb != null)
538                                 return cb.GetParametersInternal ();
539                                 
540                         return ctor.GetParametersInternal ();
541                 }
542         }
543 }
544 #endif