3 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
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:
13 // The above copyright notice and this permission notice shall be
14 // included in all copies or substantial portions of the Software.
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.
26 // System.Reflection.Emit/CustomAttributeBuilder.cs
29 // Paolo Molaro (lupus@ximian.com)
31 // (C) 2001 Ximian, Inc. http://www.ximian.com
36 using System.Reflection;
37 using System.Reflection.Emit;
38 using System.Runtime.CompilerServices;
39 using System.Runtime.InteropServices;
41 namespace System.Reflection.Emit {
43 [ComDefaultInterface (typeof (_CustomAttributeBuilder))]
44 [ClassInterface (ClassInterfaceType.None)]
45 [StructLayout (LayoutKind.Sequential)]
46 public class CustomAttributeBuilder : _CustomAttributeBuilder {
50 internal ConstructorInfo Ctor {
54 internal byte[] Data {
58 [MethodImplAttribute(MethodImplOptions.InternalCall)]
59 static extern byte[] GetBlob(Assembly asmb, ConstructorInfo con, object[] constructorArgs, PropertyInfo[] namedProperties, object[] propertyValues, FieldInfo[] namedFields, object[] fieldValues);
61 internal CustomAttributeBuilder( ConstructorInfo con, byte[] cdata) {
63 data = (byte[])cdata.Clone ();
64 /* should we check that the user supplied data is correct? */
67 public CustomAttributeBuilder( ConstructorInfo con, object[] constructorArgs)
69 Initialize (con, constructorArgs, new PropertyInfo [0], new object [0],
70 new FieldInfo [0], new object [0]);
72 public CustomAttributeBuilder( ConstructorInfo con, object[] constructorArgs,
73 FieldInfo[] namedFields, object[] fieldValues)
75 Initialize (con, constructorArgs, new PropertyInfo [0], new object [0],
76 namedFields, fieldValues);
78 public CustomAttributeBuilder( ConstructorInfo con, object[] constructorArgs,
79 PropertyInfo[] namedProperties, object[] propertyValues)
81 Initialize (con, constructorArgs, namedProperties, propertyValues, new FieldInfo [0],
84 public CustomAttributeBuilder( ConstructorInfo con, object[] constructorArgs,
85 PropertyInfo[] namedProperties, object[] propertyValues,
86 FieldInfo[] namedFields, object[] fieldValues)
88 Initialize (con, constructorArgs, namedProperties, propertyValues, namedFields, fieldValues);
91 private bool IsValidType (Type t)
93 /* FIXME: Add more checks */
94 if (t.IsArray && t.GetArrayRank () > 1)
96 if (t is TypeBuilder && t.IsEnum) {
97 // Check that the enum is properly constructed, the unmanaged code
99 Enum.GetUnderlyingType (t);
101 if (t.IsClass && !(t.IsArray || t == typeof (object) || t == typeof (Type) || t == typeof (string) || t.Assembly.GetName ().Name == "mscorlib"))
103 if (t.IsValueType && !(t.IsPrimitive || t.IsEnum || ((t.Assembly is AssemblyBuilder) && t.Assembly.GetName ().Name == "mscorlib")))
108 private bool IsValidParam (object o, Type paramType)
110 Type t = o.GetType ();
111 if (!IsValidType (t))
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)
122 static bool IsValidValue (Type type, object value) {
123 if (type.IsValueType && value == null)
125 if (type.IsArray && type.GetElementType ().IsValueType) {
126 foreach (var v in (Array)value) {
134 private void Initialize (ConstructorInfo con, object [] constructorArgs,
135 PropertyInfo [] namedProperties, object [] propertyValues,
136 FieldInfo [] namedFields, object [] fieldValues)
140 throw new ArgumentNullException ("con");
141 if (constructorArgs == null)
142 throw new ArgumentNullException ("constructorArgs");
143 if (namedProperties == null)
144 throw new ArgumentNullException ("namedProperties");
145 if (propertyValues == null)
146 throw new ArgumentNullException ("propertyValues");
147 if (namedFields == null)
148 throw new ArgumentNullException ("namedFields");
149 if (fieldValues == null)
150 throw new ArgumentNullException ("fieldValues");
151 if (con.GetParameterCount () != constructorArgs.Length)
152 throw new ArgumentException ("Parameter count does not match " +
153 "passed in argument value count.");
154 if (namedProperties.Length != propertyValues.Length)
155 throw new ArgumentException ("Array lengths must be the same.",
156 "namedProperties, propertyValues");
157 if (namedFields.Length != fieldValues.Length)
158 throw new ArgumentException ("Array lengths must be the same.",
159 "namedFields, fieldValues");
160 if ((con.Attributes & MethodAttributes.Static) == MethodAttributes.Static ||
161 (con.Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Private)
162 throw new ArgumentException ("Cannot have private or static constructor.");
164 Type atype = ctor.DeclaringType;
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])) {
180 // mcs allways uses object[] for array types and
181 // MS.NET allows this
183 if (!fi.FieldType.IsArray)
184 throw new ArgumentException ("Value of field '" + fi.Name + "' does not match field type: " + fi.FieldType);
190 foreach (PropertyInfo pi in namedProperties) {
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]);
209 foreach (ParameterInfo pi in GetParameters (con)) {
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.");
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 () + ".");
228 data = GetBlob (atype.Assembly, con, constructorArgs, namedProperties, propertyValues, namedFields, fieldValues);
232 internal static int decode_len (byte[] data, int pos, out int rpos) {
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];
240 len = ((data [pos] & 0x1f) << 24) + (data [pos + 1] << 16) + (data [pos + 2] << 8) + data [pos + 3];
247 internal static string string_from_bytes (byte[] data, int pos, int len)
249 return System.Text.Encoding.UTF8.GetString(data, pos, len);
252 internal string string_arg ()
255 int len = decode_len (data, pos, out pos);
256 return string_from_bytes (data, pos, len);
259 internal static UnmanagedMarshal get_umarshal (CustomAttributeBuilder customBuilder, bool is_field) {
260 byte[] data = customBuilder.Data;
261 UnmanagedType subtype = (UnmanagedType)0x50; /* NATIVE_MAX */
263 int sizeParamIndex = -1;
264 bool hasSize = false;
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;
273 string first_type_name = GetParameters (customBuilder.Ctor) [0].ParameterType.FullName;
275 if (first_type_name == "System.Int16")
277 int nnamed = (int)data [pos++];
278 nnamed |= ((int)data [pos++]) << 8;
280 for (int i = 0; i < nnamed; ++i) {
281 int paramType; // What is this ?
283 /* Skip field/property signature */
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);
293 int len = decode_len (data, pos, out pos);
294 string named_name = string_from_bytes (data, pos, len);
297 switch (named_name) {
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;
306 value = (int)data [pos++];
307 value |= ((int)data [pos++]) << 8;
308 value |= ((int)data [pos++]) << 16;
309 value |= ((int)data [pos++]) << 24;
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;
320 case "IidParameterIndex":
323 case "SafeArrayUserDefinedSubType":
324 len = decode_len (data, pos, out pos);
325 string_from_bytes (data, pos, len);
328 case "SizeParamIndex":
329 value = (int)data [pos++];
330 value |= ((int)data [pos++]) << 8;
331 sizeParamIndex = value;
335 len = decode_len (data, pos, out pos);
336 marshalTypeName = string_from_bytes (data, pos, len);
339 case "MarshalTypeRef":
340 len = decode_len (data, pos, out pos);
341 marshalTypeName = string_from_bytes (data, pos, len);
342 marshalTypeRef = Type.GetType (marshalTypeName);
345 case "MarshalCookie":
346 len = decode_len (data, pos, out pos);
347 marshalCookie = string_from_bytes (data, pos, len);
351 throw new Exception ("Unknown MarshalAsAttribute field: " + named_name);
355 switch ((UnmanagedType)utype) {
356 case UnmanagedType.LPArray:
358 return UnmanagedMarshal.DefineLPArrayInternal (subtype, sizeConst, sizeParamIndex);
360 return UnmanagedMarshal.DefineLPArray (subtype);
361 case UnmanagedType.SafeArray:
362 return UnmanagedMarshal.DefineSafeArray (subtype);
363 case UnmanagedType.ByValArray:
365 throw new ArgumentException ("Specified unmanaged type is only valid on fields");
367 return UnmanagedMarshal.DefineByValArray (sizeConst);
368 case UnmanagedType.ByValTStr:
369 return UnmanagedMarshal.DefineByValTStr (sizeConst);
370 case UnmanagedType.CustomMarshaler:
371 return UnmanagedMarshal.DefineCustom (marshalTypeRef, marshalCookie, marshalTypeName, Guid.Empty);
373 return UnmanagedMarshal.DefineUnmanagedMarshal ((UnmanagedType)utype);
377 static Type elementTypeToType (int elementType) {
378 /* Partition II, section 23.1.16 */
379 switch (elementType) {
381 return typeof (bool);
383 return typeof (char);
385 return typeof (sbyte);
387 return typeof (byte);
389 return typeof (short);
391 return typeof (ushort);
395 return typeof (uint);
397 return typeof (long);
399 return typeof (ulong);
401 return typeof (float);
403 return typeof (double);
405 return typeof (string);
407 throw new Exception ("Unknown element type '" + elementType + "'");
411 static object decode_cattr_value (Type t, byte[] data, int pos, out int rpos) {
412 switch (Type.GetTypeCode (t)) {
413 case TypeCode.String:
414 if (data [pos] == 0xff) {
418 int len = decode_len (data, pos, out pos);
420 return string_from_bytes (data, pos, len);
423 return data [pos] + (data [pos + 1] << 8) + (data [pos + 2] << 16) + (data [pos + 3] << 24);
424 case TypeCode.Boolean:
426 return (data [pos] == 0) ? false : true;
427 case TypeCode.Object:
428 int subtype = data [pos];
431 if (subtype >= 0x02 && subtype <= 0x0e)
432 return decode_cattr_value (elementTypeToType (subtype), data, pos, out rpos);
434 throw new Exception ("Subtype '" + subtype + "' of type object not yet handled in decode_cattr_value");
436 throw new Exception ("FIXME: Type " + t + " not yet handled in decode_cattr_value.");
440 internal struct CustomAttributeInfo {
441 public ConstructorInfo ctor;
442 public object[] ctorArgs;
443 public string[] namedParamNames;
444 public object[] namedParamValues;
447 internal static CustomAttributeInfo decode_cattr (CustomAttributeBuilder customBuilder) {
448 byte[] data = customBuilder.Data;
449 ConstructorInfo ctor = customBuilder.Ctor;
452 CustomAttributeInfo info = new CustomAttributeInfo ();
456 throw new Exception ("Custom attr length is only '" + data.Length + "'");
457 if ((data [0] != 0x1) || (data [1] != 0x00))
458 throw new Exception ("Prolog invalid");
461 ParameterInfo [] pi = GetParameters (ctor);
463 info.ctorArgs = new object [pi.Length];
464 for (int i = 0; i < pi.Length; ++i)
465 info.ctorArgs [i] = decode_cattr_value (pi [i].ParameterType, data, pos, out pos);
467 int num_named = data [pos] + (data [pos + 1] * 256);
470 info.namedParamNames = new string [num_named];
471 info.namedParamValues = new object [num_named];
472 for (int i = 0; i < num_named; ++i) {
473 int named_type = data [pos++];
474 int data_type = data [pos++];
475 string enum_type_name = null;
477 if (data_type == 0x55) {
478 int len2 = decode_len (data, pos, out pos);
479 enum_type_name = string_from_bytes (data, pos, len2);
483 int len = decode_len (data, pos, out pos);
484 string name = string_from_bytes (data, pos, len);
485 info.namedParamNames [i] = name;
488 if (named_type == 0x53) {
490 FieldInfo fi = ctor.DeclaringType.GetField (name, BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Instance);
492 throw new Exception ("Custom attribute type '" + ctor.DeclaringType + "' doesn't contain a field named '" + name + "'");
494 object val = decode_cattr_value (fi.FieldType, data, pos, out pos);
495 if (enum_type_name != null) {
496 Type enumType = Type.GetType (enum_type_name);
497 val = Enum.ToObject (enumType, val);
500 info.namedParamValues [i] = val;
504 throw new Exception ("Unknown named type: " + named_type);
510 void _CustomAttributeBuilder.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
512 throw new NotImplementedException ();
515 void _CustomAttributeBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
517 throw new NotImplementedException ();
520 void _CustomAttributeBuilder.GetTypeInfoCount (out uint pcTInfo)
522 throw new NotImplementedException ();
525 void _CustomAttributeBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
527 throw new NotImplementedException ();
530 static ParameterInfo [] GetParameters (ConstructorInfo ctor)
532 ConstructorBuilder cb = ctor as ConstructorBuilder;
534 return cb.GetParametersInternal ();
535 return ctor.GetParameters ();