2004-10-30 Zoltan Varga <vargaz@freemail.hu>
[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.IsAssignableFrom (fieldValues [i].GetType ())) {
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.IsAssignableFrom (propertyValues [i].GetType ()))
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.IsAssignableFrom (constructorArgs [i].GetType ()))
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.I4;
212                         int sizeConst = 0;
213                         int value;
214                         int utype; /* the (stupid) ctor takes a short or an enum ... */
215                         Type marshalTypeRef = null;
216                         string marshalCookie = String.Empty;
217                         utype = (int)data [2];
218                         utype |= ((int)data [3]) << 8;
219
220                         string first_type_name = customBuilder.Ctor.GetParameters()[0].ParameterType.FullName;
221                         int pos = 6;
222                         if (first_type_name == "System.Int16")
223                                 pos = 4;
224                         int nnamed = (int)data [pos++];
225                         nnamed |= ((int)data [pos++]) << 8;
226                         
227                         for (int i = 0; i < nnamed; ++i) {
228                                 int paramType; // What is this ?
229                                 paramType = (int)data [pos++];
230                                 paramType |= ((int)data [pos++]) << 8;
231                                 int len = decode_len (data, pos, out pos);
232                                 string named_name = string_from_bytes (data, pos, len);
233                                 pos += len;
234
235                                 switch (named_name) {
236                                 case "ArraySubType":
237                                         value = (int)data [pos++];
238                                         value |= ((int)data [pos++]) << 8;
239                                         value |= ((int)data [pos++]) << 16;
240                                         value |= ((int)data [pos++]) << 24;
241                                         subtype = (UnmanagedType)value;
242                                         break;
243                                 case "SizeConst":
244                                         value = (int)data [pos++];
245                                         value |= ((int)data [pos++]) << 8;
246                                         value |= ((int)data [pos++]) << 16;
247                                         value |= ((int)data [pos++]) << 24;
248                                         sizeConst = value;
249                                         break;
250                                 case "MarshalTypeRef":
251                                 case "MarshalType":
252                                         len = decode_len (data, pos, out pos);
253                                         marshalTypeRef = Type.GetType (string_from_bytes (data, pos, len));
254                                         pos += len;
255                                         break;
256                                 case "MarshalCookie":
257                                         len = decode_len (data, pos, out pos);
258                                         marshalCookie = string_from_bytes (data, pos, len);
259                                         pos += len;
260                                         break;
261                                 default:
262                                         len = decode_len(data, pos, out pos);
263                                         string v = string_from_bytes (data, pos, len);
264                                         pos += len;
265                                         break;
266                                 }
267                         }
268
269                         switch ((UnmanagedType)utype) {
270                         case UnmanagedType.LPArray:
271                                 return UnmanagedMarshal.DefineLPArray (subtype);
272                         case UnmanagedType.SafeArray:
273                                 return UnmanagedMarshal.DefineSafeArray (subtype);
274                         case UnmanagedType.ByValArray:
275                                 return UnmanagedMarshal.DefineByValArray (sizeConst);
276                         case UnmanagedType.ByValTStr:
277                                 return UnmanagedMarshal.DefineByValTStr (sizeConst);
278                         case UnmanagedType.CustomMarshaler:
279                                 return UnmanagedMarshal.DefineCustom ( marshalTypeRef, marshalCookie, marshalTypeRef.ToString (), Guid.Empty);
280                         default:
281                                 return UnmanagedMarshal.DefineUnmanagedMarshal ((UnmanagedType)utype);
282                         }
283                 }
284
285         }
286 }