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
35 using System.Reflection;
36 using System.Reflection.Emit;
37 using System.Runtime.CompilerServices;
38 using System.Runtime.InteropServices;
40 namespace System.Reflection.Emit {
43 [ComDefaultInterface (typeof (_CustomAttributeBuilder))]
45 [ClassInterface (ClassInterfaceType.None)]
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)
99 private void Initialize (ConstructorInfo con, object [] constructorArgs,
100 PropertyInfo [] namedProperties, object [] propertyValues,
101 FieldInfo [] namedFields, object [] fieldValues)
105 throw new ArgumentNullException ("con");
106 if (constructorArgs == null)
107 throw new ArgumentNullException ("constructorArgs");
108 if (namedProperties == null)
109 throw new ArgumentNullException ("namedProperties");
110 if (propertyValues == null)
111 throw new ArgumentNullException ("propertyValues");
112 if (namedFields == null)
113 throw new ArgumentNullException ("namedFields");
114 if (fieldValues == null)
115 throw new ArgumentNullException ("fieldValues");
116 if (con.GetParameterCount () != constructorArgs.Length)
117 throw new ArgumentException ("Parameter count does not match " +
118 "passed in argument value count.");
119 if (namedProperties.Length != propertyValues.Length)
120 throw new ArgumentException ("Array lengths must be the same.",
121 "namedProperties, propertyValues");
122 if (namedFields.Length != fieldValues.Length)
123 throw new ArgumentException ("Array lengths must be the same.",
124 "namedFields, fieldValues");
125 if ((con.Attributes & MethodAttributes.Static) == MethodAttributes.Static ||
126 (con.Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Private)
127 throw new ArgumentException ("Cannot have private or static constructor.");
129 Type atype = ctor.DeclaringType;
132 foreach (FieldInfo fi in namedFields) {
133 Type t = fi.DeclaringType;
134 if (!IsValidType (t))
135 throw new ArgumentException ("Field '" + fi.Name + "' does not have a valid type.");
136 if ((atype != t) && (!t.IsSubclassOf (atype)) && (!atype.IsSubclassOf (t)))
137 throw new ArgumentException ("Field '" + fi.Name + "' does not belong to the same class as the constructor");
138 // FIXME: Check enums and TypeBuilders as well
139 if (fieldValues [i] != null)
140 // IsEnum does not seem to work on TypeBuilders
141 if (!(fi.FieldType is TypeBuilder) && !fi.FieldType.IsEnum && !fi.FieldType.IsInstanceOfType (fieldValues [i])) {
143 // mcs allways uses object[] for array types and
144 // MS.NET allows this
146 if (!fi.FieldType.IsArray)
147 throw new ArgumentException ("Value of field '" + fi.Name + "' does not match field type: " + fi.FieldType);
153 foreach (PropertyInfo pi in namedProperties) {
155 throw new ArgumentException ("Property '" + pi.Name + "' does not have a setter.");
156 Type t = pi.DeclaringType;
157 if (!IsValidType (t))
158 throw new ArgumentException ("Property '" + pi.Name + "' does not have a valid type.");
159 if ((atype != t) && (!t.IsSubclassOf (atype)) && (!atype.IsSubclassOf (t)))
160 throw new ArgumentException ("Property '" + pi.Name + "' does not belong to the same class as the constructor");
161 if (propertyValues [i] != null) {
162 if (!(pi.PropertyType is TypeBuilder) && !pi.PropertyType.IsEnum && !pi.PropertyType.IsInstanceOfType (propertyValues [i]))
163 if (!pi.PropertyType.IsArray)
164 throw new ArgumentException ("Value of property '" + pi.Name + "' does not match property type: " + pi.PropertyType + " -> " + propertyValues [i]);
170 foreach (ParameterInfo pi in GetParameters (con)) {
172 Type paramType = pi.ParameterType;
173 if (!IsValidType (paramType))
174 throw new ArgumentException ("Argument " + i + " does not have a valid type.");
175 if (constructorArgs [i] != null)
176 if (!(paramType is TypeBuilder) && !paramType.IsEnum && !paramType.IsInstanceOfType (constructorArgs [i]))
177 if (!paramType.IsArray)
178 throw new ArgumentException ("Value of argument " + i + " does not match parameter type: " + paramType + " -> " + constructorArgs [i]);
183 data = GetBlob (atype.Assembly, con, constructorArgs, namedProperties, propertyValues, namedFields, fieldValues);
187 internal static int decode_len (byte[] data, int pos, out int rpos) {
189 if ((data [pos] & 0x80) == 0) {
190 len = (int)(data [pos++] & 0x7f);
191 } else if ((data [pos] & 0x40) == 0) {
192 len = ((data [pos] & 0x3f) << 8) + data [pos + 1];
195 len = ((data [pos] & 0x1f) << 24) + (data [pos + 1] << 16) + (data [pos + 2] << 8) + data [pos + 3];
202 internal static string string_from_bytes (byte[] data, int pos, int len)
204 return System.Text.Encoding.UTF8.GetString(data, pos, len);
207 internal string string_arg ()
210 int len = decode_len (data, pos, out pos);
211 return string_from_bytes (data, pos, len);
214 internal static UnmanagedMarshal get_umarshal (CustomAttributeBuilder customBuilder, bool is_field) {
215 byte[] data = customBuilder.Data;
216 UnmanagedType subtype = (UnmanagedType)0x50; /* NATIVE_MAX */
218 int sizeParamIndex = -1;
219 bool hasSize = false;
221 int utype; /* the (stupid) ctor takes a short or an enum ... */
222 string marshalTypeName = null;
223 Type marshalTypeRef = null;
224 string marshalCookie = String.Empty;
225 utype = (int)data [2];
226 utype |= ((int)data [3]) << 8;
228 string first_type_name = GetParameters (customBuilder.Ctor) [0].ParameterType.FullName;
230 if (first_type_name == "System.Int16")
232 int nnamed = (int)data [pos++];
233 nnamed |= ((int)data [pos++]) << 8;
235 for (int i = 0; i < nnamed; ++i) {
236 int paramType; // What is this ?
238 /* Skip field/property signature */
241 paramType = ((int)data [pos++]);
242 if (paramType == 0x55) {
243 /* enums, the value is preceeded by the type */
244 int len2 = decode_len (data, pos, out pos);
245 string_from_bytes (data, pos, len2);
248 int len = decode_len (data, pos, out pos);
249 string named_name = string_from_bytes (data, pos, len);
252 switch (named_name) {
254 value = (int)data [pos++];
255 value |= ((int)data [pos++]) << 8;
256 value |= ((int)data [pos++]) << 16;
257 value |= ((int)data [pos++]) << 24;
258 subtype = (UnmanagedType)value;
261 value = (int)data [pos++];
262 value |= ((int)data [pos++]) << 8;
263 value |= ((int)data [pos++]) << 16;
264 value |= ((int)data [pos++]) << 24;
268 case "SafeArraySubType":
269 value = (int)data[pos++];
270 value |= ((int)data[pos++]) << 8;
271 value |= ((int)data[pos++]) << 16;
272 value |= ((int)data[pos++]) << 24;
273 subtype = (UnmanagedType)value;
275 case "IidParameterIndex":
278 case "SafeArrayUserDefinedSubType":
279 len = decode_len (data, pos, out pos);
280 string_from_bytes (data, pos, len);
283 case "SizeParamIndex":
284 value = (int)data [pos++];
285 value |= ((int)data [pos++]) << 8;
286 sizeParamIndex = value;
290 len = decode_len (data, pos, out pos);
291 marshalTypeName = string_from_bytes (data, pos, len);
294 case "MarshalTypeRef":
295 len = decode_len (data, pos, out pos);
296 marshalTypeName = string_from_bytes (data, pos, len);
297 marshalTypeRef = Type.GetType (marshalTypeName);
300 case "MarshalCookie":
301 len = decode_len (data, pos, out pos);
302 marshalCookie = string_from_bytes (data, pos, len);
306 throw new Exception ("Unknown MarshalAsAttribute field: " + named_name);
310 switch ((UnmanagedType)utype) {
311 case UnmanagedType.LPArray:
313 return UnmanagedMarshal.DefineLPArrayInternal (subtype, sizeConst, sizeParamIndex);
315 return UnmanagedMarshal.DefineLPArray (subtype);
316 case UnmanagedType.SafeArray:
317 return UnmanagedMarshal.DefineSafeArray (subtype);
318 case UnmanagedType.ByValArray:
320 throw new ArgumentException ("Specified unmanaged type is only valid on fields");
322 return UnmanagedMarshal.DefineByValArray (sizeConst);
323 case UnmanagedType.ByValTStr:
324 return UnmanagedMarshal.DefineByValTStr (sizeConst);
325 case UnmanagedType.CustomMarshaler:
326 return UnmanagedMarshal.DefineCustom (marshalTypeRef, marshalCookie, marshalTypeName, Guid.Empty);
328 return UnmanagedMarshal.DefineUnmanagedMarshal ((UnmanagedType)utype);
332 static Type elementTypeToType (int elementType) {
333 /* Partition II, section 23.1.16 */
334 switch (elementType) {
336 return typeof (bool);
338 return typeof (char);
340 return typeof (sbyte);
342 return typeof (byte);
344 return typeof (short);
346 return typeof (ushort);
350 return typeof (uint);
352 return typeof (long);
354 return typeof (ulong);
356 return typeof (float);
358 return typeof (double);
360 return typeof (string);
362 throw new Exception ("Unknown element type '" + elementType + "'");
366 static object decode_cattr_value (Type t, byte[] data, int pos, out int rpos) {
367 switch (Type.GetTypeCode (t)) {
368 case TypeCode.String:
369 if (data [pos] == 0xff) {
373 int len = decode_len (data, pos, out pos);
375 return string_from_bytes (data, pos, len);
378 return data [pos] + (data [pos + 1] << 8) + (data [pos + 2] << 16) + (data [pos + 3] << 24);
379 case TypeCode.Boolean:
381 return (data [pos] == 0) ? false : true;
382 case TypeCode.Object:
383 int subtype = data [pos];
386 if (subtype >= 0x02 && subtype <= 0x0e)
387 return decode_cattr_value (elementTypeToType (subtype), data, pos, out rpos);
389 throw new Exception ("Subtype '" + subtype + "' of type object not yet handled in decode_cattr_value");
391 throw new Exception ("FIXME: Type " + t + " not yet handled in decode_cattr_value.");
395 internal struct CustomAttributeInfo {
396 public ConstructorInfo ctor;
397 public object[] ctorArgs;
398 public string[] namedParamNames;
399 public object[] namedParamValues;
402 internal static CustomAttributeInfo decode_cattr (CustomAttributeBuilder customBuilder) {
403 byte[] data = customBuilder.Data;
404 ConstructorInfo ctor = customBuilder.Ctor;
407 CustomAttributeInfo info = new CustomAttributeInfo ();
411 throw new Exception ("Custom attr length is only '" + data.Length + "'");
412 if ((data [0] != 0x1) || (data [1] != 0x00))
413 throw new Exception ("Prolog invalid");
416 ParameterInfo [] pi = GetParameters (ctor);
418 info.ctorArgs = new object [pi.Length];
419 for (int i = 0; i < pi.Length; ++i)
420 info.ctorArgs [i] = decode_cattr_value (pi [i].ParameterType, data, pos, out pos);
422 int num_named = data [pos] + (data [pos + 1] * 256);
425 info.namedParamNames = new string [num_named];
426 info.namedParamValues = new object [num_named];
427 for (int i = 0; i < num_named; ++i) {
428 int named_type = data [pos++];
429 int data_type = data [pos++];
430 string enum_type_name = null;
432 if (data_type == 0x55) {
433 int len2 = decode_len (data, pos, out pos);
434 enum_type_name = string_from_bytes (data, pos, len2);
438 int len = decode_len (data, pos, out pos);
439 string name = string_from_bytes (data, pos, len);
440 info.namedParamNames [i] = name;
443 if (named_type == 0x53) {
445 FieldInfo fi = ctor.DeclaringType.GetField (name, BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Instance);
447 throw new Exception ("Custom attribute type '" + ctor.DeclaringType + "' doesn't contain a field named '" + name + "'");
449 object val = decode_cattr_value (fi.FieldType, data, pos, out pos);
450 if (enum_type_name != null) {
451 Type enumType = Type.GetType (enum_type_name);
452 val = Enum.ToObject (enumType, val);
455 info.namedParamValues [i] = val;
459 throw new Exception ("Unknown named type: " + named_type);
465 void _CustomAttributeBuilder.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
467 throw new NotImplementedException ();
470 void _CustomAttributeBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
472 throw new NotImplementedException ();
475 void _CustomAttributeBuilder.GetTypeInfoCount (out uint pcTInfo)
477 throw new NotImplementedException ();
480 void _CustomAttributeBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
482 throw new NotImplementedException ();
485 static ParameterInfo [] GetParameters (ConstructorInfo ctor)
487 ConstructorBuilder cb = ctor as ConstructorBuilder;
489 return cb.GetParametersInternal ();
490 return ctor.GetParameters ();