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[] binaryAttribute) {
63 throw new ArgumentNullException ("con");
64 if (binaryAttribute == null)
65 throw new ArgumentNullException ("binaryAttribute");
67 data = (byte[])binaryAttribute.Clone ();
68 /* should we check that the user supplied data is correct? */
71 public CustomAttributeBuilder( ConstructorInfo con, object[] constructorArgs)
73 Initialize (con, constructorArgs, new PropertyInfo [0], new object [0],
74 new FieldInfo [0], new object [0]);
76 public CustomAttributeBuilder( ConstructorInfo con, object[] constructorArgs,
77 FieldInfo[] namedFields, object[] fieldValues)
79 Initialize (con, constructorArgs, new PropertyInfo [0], new object [0],
80 namedFields, fieldValues);
82 public CustomAttributeBuilder( ConstructorInfo con, object[] constructorArgs,
83 PropertyInfo[] namedProperties, object[] propertyValues)
85 Initialize (con, constructorArgs, namedProperties, propertyValues, new FieldInfo [0],
88 public CustomAttributeBuilder( ConstructorInfo con, object[] constructorArgs,
89 PropertyInfo[] namedProperties, object[] propertyValues,
90 FieldInfo[] namedFields, object[] fieldValues)
92 Initialize (con, constructorArgs, namedProperties, propertyValues, namedFields, fieldValues);
95 private bool IsValidType (Type t)
97 /* FIXME: Add more checks */
98 if (t.IsArray && t.GetArrayRank () > 1)
100 if (t is TypeBuilder && t.IsEnum) {
101 // Check that the enum is properly constructed, the unmanaged code
103 Enum.GetUnderlyingType (t);
105 if (t.IsClass && !(t.IsArray || t == typeof (object) || t == typeof (Type) || t == typeof (string) || t.Assembly.GetName ().Name == "mscorlib"))
107 if (t.IsValueType && !(t.IsPrimitive || t.IsEnum || ((t.Assembly is AssemblyBuilder) && t.Assembly.GetName ().Name == "mscorlib")))
112 private bool IsValidParam (object o, Type paramType)
114 Type t = o.GetType ();
115 if (!IsValidType (t))
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)
126 static bool IsValidValue (Type type, object value) {
127 if (type.IsValueType && value == null)
129 if (type.IsArray && type.GetElementType ().IsValueType) {
130 foreach (var v in (Array)value) {
138 private void Initialize (ConstructorInfo con, object [] constructorArgs,
139 PropertyInfo [] namedProperties, object [] propertyValues,
140 FieldInfo [] namedFields, object [] fieldValues)
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.");
168 Type atype = ctor.DeclaringType;
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])) {
184 // mcs allways uses object[] for array types and
185 // MS.NET allows this
187 if (!fi.FieldType.IsArray)
188 throw new ArgumentException ("Value of field '" + fi.Name + "' does not match field type: " + fi.FieldType);
194 foreach (PropertyInfo pi in namedProperties) {
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]);
213 foreach (ParameterInfo pi in GetParameters (con)) {
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.");
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 () + ".");
232 data = GetBlob (atype.Assembly, con, constructorArgs, namedProperties, propertyValues, namedFields, fieldValues);
236 internal static int decode_len (byte[] data, int pos, out int rpos) {
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];
244 len = ((data [pos] & 0x1f) << 24) + (data [pos + 1] << 16) + (data [pos + 2] << 8) + data [pos + 3];
251 internal static string string_from_bytes (byte[] data, int pos, int len)
253 return System.Text.Encoding.UTF8.GetString(data, pos, len);
256 internal string string_arg ()
259 int len = decode_len (data, pos, out pos);
260 return string_from_bytes (data, pos, len);
263 internal static UnmanagedMarshal get_umarshal (CustomAttributeBuilder customBuilder, bool is_field) {
264 byte[] data = customBuilder.Data;
265 UnmanagedType subtype = (UnmanagedType)0x50; /* NATIVE_MAX */
267 int sizeParamIndex = -1;
268 bool hasSize = false;
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;
277 string first_type_name = GetParameters (customBuilder.Ctor) [0].ParameterType.FullName;
279 if (first_type_name == "System.Int16")
281 int nnamed = (int)data [pos++];
282 nnamed |= ((int)data [pos++]) << 8;
284 for (int i = 0; i < nnamed; ++i) {
285 int paramType; // What is this ?
287 /* Skip field/property signature */
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);
297 int len = decode_len (data, pos, out pos);
298 string named_name = string_from_bytes (data, pos, len);
301 switch (named_name) {
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;
310 value = (int)data [pos++];
311 value |= ((int)data [pos++]) << 8;
312 value |= ((int)data [pos++]) << 16;
313 value |= ((int)data [pos++]) << 24;
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;
324 case "IidParameterIndex":
327 case "SafeArrayUserDefinedSubType":
328 len = decode_len (data, pos, out pos);
329 string_from_bytes (data, pos, len);
332 case "SizeParamIndex":
333 value = (int)data [pos++];
334 value |= ((int)data [pos++]) << 8;
335 sizeParamIndex = value;
339 len = decode_len (data, pos, out pos);
340 marshalTypeName = string_from_bytes (data, pos, len);
343 case "MarshalTypeRef":
344 len = decode_len (data, pos, out pos);
345 marshalTypeName = string_from_bytes (data, pos, len);
346 marshalTypeRef = Type.GetType (marshalTypeName);
349 case "MarshalCookie":
350 len = decode_len (data, pos, out pos);
351 marshalCookie = string_from_bytes (data, pos, len);
355 throw new Exception ("Unknown MarshalAsAttribute field: " + named_name);
359 switch ((UnmanagedType)utype) {
360 case UnmanagedType.LPArray:
362 return UnmanagedMarshal.DefineLPArrayInternal (subtype, sizeConst, sizeParamIndex);
364 return UnmanagedMarshal.DefineLPArray (subtype);
365 #if FEATURE_COMINTEROP
366 case UnmanagedType.SafeArray:
367 return UnmanagedMarshal.DefineSafeArray (subtype);
369 case UnmanagedType.ByValArray:
371 throw new ArgumentException ("Specified unmanaged type is only valid on fields");
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);
381 return UnmanagedMarshal.DefineUnmanagedMarshal ((UnmanagedType)utype);
385 static Type elementTypeToType (int elementType) {
386 /* Partition II, section 23.1.16 */
387 switch (elementType) {
389 return typeof (bool);
391 return typeof (char);
393 return typeof (sbyte);
395 return typeof (byte);
397 return typeof (short);
399 return typeof (ushort);
403 return typeof (uint);
405 return typeof (long);
407 return typeof (ulong);
409 return typeof (float);
411 return typeof (double);
413 return typeof (string);
415 throw new Exception ("Unknown element type '" + elementType + "'");
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) {
426 int len = decode_len (data, pos, out pos);
428 return string_from_bytes (data, pos, len);
431 return data [pos] + (data [pos + 1] << 8) + (data [pos + 2] << 16) + (data [pos + 3] << 24);
432 case TypeCode.Boolean:
434 return (data [pos] == 0) ? false : true;
435 case TypeCode.Object:
436 int subtype = data [pos];
439 if (subtype >= 0x02 && subtype <= 0x0e)
440 return decode_cattr_value (elementTypeToType (subtype), data, pos, out rpos);
442 throw new Exception ("Subtype '" + subtype + "' of type object not yet handled in decode_cattr_value");
444 throw new Exception ("FIXME: Type " + t + " not yet handled in decode_cattr_value.");
448 internal struct CustomAttributeInfo {
449 public ConstructorInfo ctor;
450 public object[] ctorArgs;
451 public string[] namedParamNames;
452 public object[] namedParamValues;
455 internal static CustomAttributeInfo decode_cattr (CustomAttributeBuilder customBuilder) {
456 byte[] data = customBuilder.Data;
457 ConstructorInfo ctor = customBuilder.Ctor;
460 CustomAttributeInfo info = new CustomAttributeInfo ();
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");
469 ParameterInfo [] pi = GetParameters (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);
475 int num_named = data [pos] + (data [pos + 1] * 256);
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;
485 if (data_type == 0x55) {
486 int len2 = decode_len (data, pos, out pos);
487 enum_type_name = string_from_bytes (data, pos, len2);
491 int len = decode_len (data, pos, out pos);
492 string name = string_from_bytes (data, pos, len);
493 info.namedParamNames [i] = name;
496 if (named_type == 0x53) {
498 FieldInfo fi = ctor.DeclaringType.GetField (name, BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Instance);
500 throw new Exception ("Custom attribute type '" + ctor.DeclaringType + "' doesn't contain a field named '" + name + "'");
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);
508 info.namedParamValues [i] = val;
512 throw new Exception ("Unknown named type: " + named_type);
518 void _CustomAttributeBuilder.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
520 throw new NotImplementedException ();
523 void _CustomAttributeBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
525 throw new NotImplementedException ();
528 void _CustomAttributeBuilder.GetTypeInfoCount (out uint pcTInfo)
530 throw new NotImplementedException ();
533 void _CustomAttributeBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
535 throw new NotImplementedException ();
538 static ParameterInfo [] GetParameters (ConstructorInfo ctor)
540 ConstructorBuilder cb = ctor as ConstructorBuilder;
542 return cb.GetParametersInternal ();
544 return ctor.GetParametersInternal ();