2005-06-05 Peter Bartok <pbartok@novell.com>
[mono.git] / mcs / class / corlib / System.Reflection.Emit / CustomAttributeBuilder.cs
1
2 //
3 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
4 //
5 // Permission is hereby granted, free of charge, to any person obtaining
6 // a copy of this software and associated documentation files (the
7 // "Software"), to deal in the Software without restriction, including
8 // without limitation the rights to use, copy, modify, merge, publish,
9 // distribute, sublicense, and/or sell copies of the Software, and to
10 // permit persons to whom the Software is furnished to do so, subject to
11 // the following conditions:
12 // 
13 // The above copyright notice and this permission notice shall be
14 // included in all copies or substantial portions of the Software.
15 // 
16 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23 //
24
25 //
26 // System.Reflection.Emit/CustomAttributeBuilder.cs
27 //
28 // Author:
29 //   Paolo Molaro (lupus@ximian.com)
30 //
31 // (C) 2001 Ximian, Inc.  http://www.ximian.com
32 //
33
34 using System;
35 using System.Reflection;
36 using System.Reflection.Emit;
37 using System.Runtime.CompilerServices;
38 using System.Runtime.InteropServices;
39
40 namespace System.Reflection.Emit {
41         public class CustomAttributeBuilder {
42                 ConstructorInfo ctor;
43                 byte[] data;
44
45                 internal ConstructorInfo Ctor {
46                         get {return ctor;}
47                 }
48
49                 internal byte[] Data {
50                         get {return data;}
51                 }
52                 
53                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
54                 static extern byte[] GetBlob(Assembly asmb, ConstructorInfo con, object[] constructorArgs, PropertyInfo[] namedProperties, object[] propertyValues, FieldInfo[] namedFields, object[] fieldValues);
55                 
56                 internal CustomAttributeBuilder( ConstructorInfo con, byte[] cdata) {
57                         ctor = con;
58                         data = (byte[])cdata.Clone ();
59                         /* should we check that the user supplied data is correct? */
60                 }
61                 
62                 public CustomAttributeBuilder( ConstructorInfo con, object[] constructorArgs)
63                 {
64                         Initialize (con, constructorArgs, new PropertyInfo [0], new object [0],
65                                         new FieldInfo [0], new object [0]);
66                 }
67                 public CustomAttributeBuilder( ConstructorInfo con, object[] constructorArgs,
68                                 FieldInfo[] namedFields, object[] fieldValues) 
69                 {
70                         Initialize (con, constructorArgs, new PropertyInfo [0], new object [0],
71                                         namedFields, fieldValues);
72                 }
73                 public CustomAttributeBuilder( ConstructorInfo con, object[] constructorArgs,
74                                 PropertyInfo[] namedProperties, object[] propertyValues)
75                 {
76                         Initialize (con, constructorArgs, namedProperties, propertyValues, new FieldInfo [0],
77                                         new object [0]);
78                 }
79                 public CustomAttributeBuilder( ConstructorInfo con, object[] constructorArgs,
80                                 PropertyInfo[] namedProperties, object[] propertyValues,
81                                 FieldInfo[] namedFields, object[] fieldValues)
82                 {
83                         Initialize (con, constructorArgs, namedProperties, propertyValues, namedFields, fieldValues);
84                 }
85
86                 private bool IsValidType (Type t)
87                 {
88                         /* FIXME: Add more checks */
89                         if (t.IsArray && t.GetArrayRank () > 1)
90                                 return false;
91                         return true;
92                 }
93
94                 private void Initialize (ConstructorInfo con, object [] constructorArgs,
95                                 PropertyInfo [] namedProperties, object [] propertyValues,
96                                 FieldInfo [] namedFields, object [] fieldValues)
97                 {
98                         ctor = con;
99                         if (con == null)
100                                 throw new ArgumentNullException ("con");
101                         if (constructorArgs == null)
102                                 throw new ArgumentNullException ("constructorArgs");
103                         if (namedProperties == null)
104                                 throw new ArgumentNullException ("namedProperties");
105                         if (propertyValues == null)
106                                 throw new ArgumentNullException ("propertyValues");
107                         if (namedFields == null)
108                                 throw new ArgumentNullException ("namedFields");
109                         if (fieldValues == null)
110                                 throw new ArgumentNullException ("fieldValues");
111                         if (con.GetParameterCount () != constructorArgs.Length)
112                                 throw new ArgumentException ("Parameter count does not match " +
113                                                 "passed in argument value count.");
114                         if (namedProperties.Length != propertyValues.Length)
115                                 throw new ArgumentException ("Array lengths must be the same.",
116                                                 "namedProperties, propertyValues");
117                         if (namedFields.Length != fieldValues.Length)
118                                 throw new ArgumentException ("Array lengths must be the same.",
119                                                 "namedFields, fieldValues");
120                         if ((con.Attributes & MethodAttributes.Static) == MethodAttributes.Static ||
121                                         (con.Attributes & MethodAttributes.Private) == MethodAttributes.Private)
122                                 throw new ArgumentException ("Cannot have private or static constructor.");
123
124                         Type atype = ctor.DeclaringType;
125                         int i;
126                         i = 0;
127                         foreach (FieldInfo fi in namedFields) {
128                                 Type t = fi.DeclaringType;
129                                 if (!IsValidType (t))
130                                         throw new ArgumentException ("Field '" + fi.Name + "' does not have a valid type.");
131                                 if ((atype != t) && (!t.IsSubclassOf (atype)) && (!atype.IsSubclassOf (t)))
132                                         throw new ArgumentException ("Field '" + fi.Name + "' does not belong to the same class as the constructor");
133                                 // FIXME: Check enums and TypeBuilders as well
134                                 if (fieldValues [i] != null)
135                                         // IsEnum does not seem to work on TypeBuilders
136                                         if (!(fi.FieldType is TypeBuilder) && !fi.FieldType.IsEnum && !fi.FieldType.IsInstanceOfType (fieldValues [i])) {
137                                                 //
138                                                 // mcs allways uses object[] for array types and
139                                                 // MS.NET allows this
140                                                 //
141                                                 if (!fi.FieldType.IsArray)
142                                                         throw new ArgumentException ("Value of field '" + fi.Name + "' does not match field type: " + fi.FieldType);
143                                                 }
144                                 i ++;
145                         }
146
147                         i = 0;
148                         foreach (PropertyInfo pi in namedProperties) {
149                                 if (!pi.CanWrite)
150                                         throw new ArgumentException ("Property '" + pi.Name + "' does not have a setter.");
151                                 Type t = pi.DeclaringType;
152                                 if (!IsValidType (t))
153                                         throw new ArgumentException ("Property '" + pi.Name + "' does not have a valid type.");
154                                 if ((atype != t) && (!t.IsSubclassOf (atype)) && (!atype.IsSubclassOf (t)))
155                                         throw new ArgumentException ("Property '" + pi.Name + "' does not belong to the same class as the constructor");
156                                 if (propertyValues [i] != null) {
157                                         if (!(pi.PropertyType is TypeBuilder) && !pi.PropertyType.IsEnum && !pi.PropertyType.IsInstanceOfType (propertyValues [i]))
158                                                 if (!pi.PropertyType.IsArray)
159                                                         throw new ArgumentException ("Value of property '" + pi.Name + "' does not match property type: " + pi.PropertyType + " -> " + propertyValues [i]);
160                                 }
161                                 i ++;
162                         }
163
164                         i = 0;
165                         foreach (ParameterInfo pi in con.GetParameters ()) {
166                                 if (pi != null) {
167                                         Type paramType = pi.ParameterType;
168                                         if (!IsValidType (paramType))
169                                                 throw new ArgumentException ("Argument " + i + " does not have a valid type.");
170                                         if (constructorArgs [i] != null)
171                                                 if (!(paramType is TypeBuilder) && !paramType.IsEnum && !paramType.IsInstanceOfType (constructorArgs [i]))
172                                                         if (!paramType.IsArray)
173                                                                 throw new ArgumentException ("Value of argument " + i + " does not match parameter type: " + paramType + " -> " + constructorArgs [i]);
174                                 }
175                                 i ++;
176                         }
177                                 
178                         data = GetBlob (atype.Assembly, con, constructorArgs, namedProperties, propertyValues, namedFields, fieldValues);
179                 }
180
181                 /* helper methods */
182                 internal static int decode_len (byte[] data, int pos, out int rpos) {
183                         int len = 0;
184                         if ((data [pos] & 0x80) == 0) {
185                                 len = (int)(data [pos++] & 0x7f);
186                         } else if ((data [pos] & 0x40) == 0) {
187                                 len = ((data [pos] & 0x3f) << 8) + data [pos + 1];
188                                 pos += 2;
189                         } else {
190                                 len = ((data [pos] & 0x1f) << 24) + (data [pos + 1] << 16) + (data [pos + 2] << 8) + data [pos + 3];
191                                 pos += 4;
192                         }
193                         rpos = pos;
194                         return len;
195                 }
196
197                 internal static string string_from_bytes (byte[] data, int pos, int len) 
198                 {
199                         return System.Text.Encoding.UTF8.GetString(data, pos, len);
200                 }
201
202                 internal string string_arg ()
203                 {
204                         int pos = 2;
205                         int len = decode_len (data, pos, out pos);
206                         return string_from_bytes (data, pos, len);
207                 }                       
208
209                 internal static UnmanagedMarshal get_umarshal (CustomAttributeBuilder customBuilder, bool is_field) {
210                         byte[] data = customBuilder.Data;
211                         UnmanagedType subtype = (UnmanagedType)0x50; /* NATIVE_MAX */
212                         int sizeConst = -1;
213                         int sizeParamIndex = -1;
214                         bool hasSize = false;
215                         int value;
216                         int utype; /* the (stupid) ctor takes a short or an enum ... */
217                         Type marshalTypeRef = null;
218                         string marshalCookie = String.Empty;
219                         utype = (int)data [2];
220                         utype |= ((int)data [3]) << 8;
221
222                         string first_type_name = customBuilder.Ctor.GetParameters()[0].ParameterType.FullName;
223                         int pos = 6;
224                         if (first_type_name == "System.Int16")
225                                 pos = 4;
226                         int nnamed = (int)data [pos++];
227                         nnamed |= ((int)data [pos++]) << 8;
228                         
229                         for (int i = 0; i < nnamed; ++i) {
230                                 int paramType; // What is this ?
231                                 paramType = (int)data [pos++];
232                                 paramType |= ((int)data [pos++]) << 8;
233                                 int len = decode_len (data, pos, out pos);
234                                 string named_name = string_from_bytes (data, pos, len);
235                                 pos += len;
236
237                                 switch (named_name) {
238                                 case "ArraySubType":
239                                         value = (int)data [pos++];
240                                         value |= ((int)data [pos++]) << 8;
241                                         value |= ((int)data [pos++]) << 16;
242                                         value |= ((int)data [pos++]) << 24;
243                                         subtype = (UnmanagedType)value;
244                                         break;
245                                 case "SizeConst":
246                                         value = (int)data [pos++];
247                                         value |= ((int)data [pos++]) << 8;
248                                         value |= ((int)data [pos++]) << 16;
249                                         value |= ((int)data [pos++]) << 24;
250                                         sizeConst = value;
251                                         hasSize = true;
252                                         break;
253                                 case "SizeSizeParamIndex":
254                                         value = (int)data [pos++];
255                                         value |= ((int)data [pos++]) << 8;
256                                         sizeParamIndex = value;
257                                         hasSize = true;
258                                         break;
259                                 case "MarshalTypeRef":
260                                 case "MarshalType":
261                                         len = decode_len (data, pos, out pos);
262                                         marshalTypeRef = Type.GetType (string_from_bytes (data, pos, len));
263                                         pos += len;
264                                         break;
265                                 case "MarshalCookie":
266                                         len = decode_len (data, pos, out pos);
267                                         marshalCookie = string_from_bytes (data, pos, len);
268                                         pos += len;
269                                         break;
270                                 default:
271                                         len = decode_len(data, pos, out pos);
272                                         string_from_bytes (data, pos, len);
273                                         pos += len;
274                                         break;
275                                 }
276                         }
277
278                         switch ((UnmanagedType)utype) {
279                         case UnmanagedType.LPArray:
280                                 if (hasSize)
281                                         return UnmanagedMarshal.DefineLPArrayInternal (subtype, sizeConst, sizeParamIndex);
282                                 else
283                                         return UnmanagedMarshal.DefineLPArray (subtype);
284                         case UnmanagedType.SafeArray:
285                                 return UnmanagedMarshal.DefineSafeArray (subtype);
286                         case UnmanagedType.ByValArray:
287                                 return UnmanagedMarshal.DefineByValArray (sizeConst);
288                         case UnmanagedType.ByValTStr:
289                                 return UnmanagedMarshal.DefineByValTStr (sizeConst);
290                         case UnmanagedType.CustomMarshaler:
291                                 return UnmanagedMarshal.DefineCustom ( marshalTypeRef, marshalCookie, marshalTypeRef.ToString (), Guid.Empty);
292                         default:
293                                 return UnmanagedMarshal.DefineUnmanagedMarshal ((UnmanagedType)utype);
294                         }
295                 }
296
297                 static object decode_cattr_value (Type t, byte[] data, int pos, out int rpos) {
298                         switch (Type.GetTypeCode (t)) {
299                         case TypeCode.String:
300                                 int len = decode_len (data, pos, out pos);
301                                 rpos = pos + len;
302                                 return string_from_bytes (data, pos, len);
303                         case TypeCode.Int32:
304                                 rpos = pos + 4;
305                                 return data [pos] + (data [pos + 1] << 8) + (data [pos + 2] << 16) + (data [pos + 3] << 24);
306                         case TypeCode.Boolean:
307                                 rpos = pos + 1;
308                                 return (data [pos] == 0) ? false : true;
309                         default:
310                                 throw new Exception ("FIXME: Type " + t + " not yet handled in decode_cattr_value.");
311                         }
312                 }
313
314                 internal struct CustomAttributeInfo {
315                         public ConstructorInfo ctor;
316                         public object[] ctorArgs;
317                         public string[] namedParamNames;
318                         public object[] namedParamValues;
319                 }
320
321                 internal static CustomAttributeInfo decode_cattr (CustomAttributeBuilder customBuilder) {
322                         byte[] data = customBuilder.Data;
323                         ConstructorInfo ctor = customBuilder.Ctor;
324                         int pos = 0;
325
326                         CustomAttributeInfo info = new CustomAttributeInfo ();
327
328                         // Prolog
329                         if (data.Length < 2)
330                                 throw new Exception ();
331                         if ((data [0] != 0x1) || (data [1] != 0x00))
332                                 throw new Exception ();
333                         pos = 2;
334
335                         ParameterInfo [] pi = ctor.GetParameters ();
336                         info.ctor = ctor;
337                         info.ctorArgs = new object [pi.Length];
338                         for (int i = 0; i < pi.Length; ++i)
339                                 info.ctorArgs [i] = decode_cattr_value (pi [i].ParameterType, data, pos, out pos);
340
341                         int num_named = data [pos] + (data [pos + 1] * 256);
342                         pos += 2;
343
344                         info.namedParamNames = new string [num_named];
345                         info.namedParamValues = new object [num_named];
346                         for (int i = 0; i < num_named; ++i) {
347                                 int named_type = data [pos++];
348                                 int data_type = data [pos++];
349                                 string enum_type_name = null;
350
351                                 if (data_type == 0x55) {
352                                         int len2 = decode_len (data, pos, out pos);
353                                         enum_type_name = string_from_bytes (data, pos, len2);
354                                         pos += len2;
355                                 }
356
357                                 int len = decode_len (data, pos, out pos);
358                                 string name = string_from_bytes (data, pos, len);
359                                 info.namedParamNames [i] = name;
360                                 pos += len;
361
362                                 if (named_type == 0x53) {
363                                         /* Field */
364                                         FieldInfo fi = ctor.DeclaringType.GetField (name, BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Instance);
365                                         if (fi == null)
366                                                 throw new Exception ("Custom attribute type '" + ctor.DeclaringType + "' doesn't contain a field named '" + name + "'");
367
368                                         object val = decode_cattr_value (fi.FieldType, data, pos, out pos);
369                                         if (enum_type_name != null) {
370                                                 Type enumType = Type.GetType (enum_type_name);
371                                                 val = Enum.ToObject (enumType, val);
372                                         }
373
374                                         info.namedParamValues [i] = val;
375                                 }
376                                 else
377                                         // FIXME:
378                                         throw new Exception ();
379                         }
380
381                         return info;
382                 }
383         }
384 }