1 // System.MonoCustomAttrs.cs
2 // Hooks into the runtime to get custom attributes for reflection handles
5 // Paolo Molaro (lupus@ximian.com)
6 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
8 // (c) 2002,2003 Ximian, Inc. (http://www.ximian.com)
12 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
14 // Permission is hereby granted, free of charge, to any person obtaining
15 // a copy of this software and associated documentation files (the
16 // "Software"), to deal in the Software without restriction, including
17 // without limitation the rights to use, copy, modify, merge, publish,
18 // distribute, sublicense, and/or sell copies of the Software, and to
19 // permit persons to whom the Software is furnished to do so, subject to
20 // the following conditions:
22 // The above copyright notice and this permission notice shall be
23 // included in all copies or substantial portions of the Software.
25 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
29 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
30 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
31 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
35 using System.Reflection;
36 using System.Collections;
37 using System.Runtime.CompilerServices;
38 using System.Reflection.Emit;
39 using System.Collections.Generic;
43 internal class MonoCustomAttrs
45 static Assembly corlib;
47 /* Treat as user types all corlib types extending System.Type that are not MonoType and TypeBuilder */
48 static bool IsUserCattrProvider (object obj)
50 Type type = obj as Type;
51 if ((type is MonoType) || (type is TypeBuilder))
56 corlib = typeof (int).Assembly;
57 return obj.GetType ().Assembly != corlib;
60 [MethodImplAttribute (MethodImplOptions.InternalCall)]
61 internal static extern object[] GetCustomAttributesInternal (ICustomAttributeProvider obj, Type attributeType, bool pseudoAttrs);
63 internal static object[] GetPseudoCustomAttributes (ICustomAttributeProvider obj, Type attributeType) {
64 object[] pseudoAttrs = null;
66 /* FIXME: Add other types */
67 if (obj is MonoMethod)
68 pseudoAttrs = ((MonoMethod)obj).GetPseudoCustomAttributes ();
69 else if (obj is FieldInfo)
70 pseudoAttrs = ((FieldInfo)obj).GetPseudoCustomAttributes ();
71 else if (obj is ParameterInfo)
72 pseudoAttrs = ((ParameterInfo)obj).GetPseudoCustomAttributes ();
74 pseudoAttrs = ((Type)obj).GetPseudoCustomAttributes ();
76 if ((attributeType != null) && (pseudoAttrs != null)) {
77 for (int i = 0; i < pseudoAttrs.Length; ++i)
78 if (attributeType.IsAssignableFrom (pseudoAttrs [i].GetType ()))
79 if (pseudoAttrs.Length == 1)
82 return new object [] { pseudoAttrs [i] };
83 return new object [0];
89 internal static object[] GetCustomAttributesBase (ICustomAttributeProvider obj, Type attributeType)
92 if (IsUserCattrProvider (obj))
93 attrs = obj.GetCustomAttributes (attributeType, true);
95 attrs = GetCustomAttributesInternal (obj, attributeType, false);
97 object[] pseudoAttrs = GetPseudoCustomAttributes (obj, attributeType);
98 if (pseudoAttrs != null) {
99 object[] res = new object [attrs.Length + pseudoAttrs.Length];
100 System.Array.Copy (attrs, res, attrs.Length);
101 System.Array.Copy (pseudoAttrs, 0, res, attrs.Length, pseudoAttrs.Length);
108 internal static Attribute GetCustomAttribute (ICustomAttributeProvider obj,
112 object[] res = GetCustomAttributes (obj, attributeType, inherit);
117 else if (res.Length > 1)
119 string msg = "'{0}' has more than one attribute of type '{1}";
120 msg = String.Format (msg, obj, attributeType);
121 throw new AmbiguousMatchException (msg);
124 return (Attribute) res[0];
127 internal static object[] GetCustomAttributes (ICustomAttributeProvider obj, Type attributeType, bool inherit)
130 throw new ArgumentNullException ("obj");
131 if (attributeType == null)
132 throw new ArgumentNullException ("attributeType");
134 if (attributeType == typeof (MonoCustomAttrs))
135 attributeType = null;
138 object[] res = GetCustomAttributesBase (obj, attributeType);
140 if (!inherit && res.Length == 1)
143 throw new CustomAttributeFormatException ("Invalid custom attribute format");
145 if (attributeType != null)
147 if (attributeType.IsAssignableFrom (res[0].GetType ()))
149 r = (object[]) Array.CreateInstance (attributeType, 1);
154 r = (object[]) Array.CreateInstance (attributeType, 0);
159 r = (object[]) Array.CreateInstance (res[0].GetType (), 1);
165 // if AttributeType is sealed, and Inherited is set to false, then
166 // there's no use in scanning base types
167 if ((attributeType != null && attributeType.IsSealed) && inherit)
169 AttributeUsageAttribute usageAttribute = RetrieveAttributeUsage (
171 if (!usageAttribute.Inherited)
177 int initialSize = res.Length < 16 ? res.Length : 16;
179 Hashtable attributeInfos = new Hashtable (initialSize);
180 ArrayList a = new ArrayList (initialSize);
181 ICustomAttributeProvider btype = obj;
183 int inheritanceLevel = 0;
187 foreach (object attr in res)
189 AttributeUsageAttribute usage;
191 throw new CustomAttributeFormatException ("Invalid custom attribute format");
193 Type attrType = attr.GetType ();
194 if (attributeType != null)
196 if (!attributeType.IsAssignableFrom (attrType))
202 AttributeInfo firstAttribute = (AttributeInfo) attributeInfos[attrType];
203 if (firstAttribute != null)
205 usage = firstAttribute.Usage;
209 usage = RetrieveAttributeUsage (attrType);
212 // only add attribute to the list of attributes if
213 // - we are on the first inheritance level, or the attribute can be inherited anyway
215 // - multiple attributes of the type are allowed
217 // - this is the first attribute we've discovered
219 // - the attribute is on same inheritance level than the first
220 // attribute that was discovered for this attribute type ))
221 if ((inheritanceLevel == 0 || usage.Inherited) && (usage.AllowMultiple ||
222 (firstAttribute == null || (firstAttribute != null
223 && firstAttribute.InheritanceLevel == inheritanceLevel))))
228 if (firstAttribute == null)
230 attributeInfos.Add (attrType, new AttributeInfo (usage, inheritanceLevel));
234 if ((btype = GetBase (btype)) != null)
237 res = GetCustomAttributesBase (btype, attributeType);
239 } while (inherit && btype != null);
241 object[] array = null;
242 if (attributeType == null || attributeType.IsValueType)
244 array = (object[]) Array.CreateInstance (typeof(Attribute), a.Count);
248 array = Array.CreateInstance (attributeType, a.Count) as object[];
251 // copy attributes to array
257 internal static object[] GetCustomAttributes (ICustomAttributeProvider obj, bool inherit)
260 throw new ArgumentNullException ("obj");
263 return (object[]) GetCustomAttributesBase (obj, null).Clone ();
265 return GetCustomAttributes (obj, typeof (MonoCustomAttrs), inherit);
268 [MethodImplAttribute (MethodImplOptions.InternalCall)]
269 static extern CustomAttributeData [] GetCustomAttributesDataInternal (ICustomAttributeProvider obj);
271 internal static IList<CustomAttributeData> GetCustomAttributesData (ICustomAttributeProvider obj)
274 throw new ArgumentNullException ("obj");
276 CustomAttributeData [] attrs = GetCustomAttributesDataInternal (obj);
277 return Array.AsReadOnly<CustomAttributeData> (attrs);
280 internal static bool IsDefined (ICustomAttributeProvider obj, Type attributeType, bool inherit)
282 if (attributeType == null)
283 throw new ArgumentNullException ("attributeType");
285 if (IsUserCattrProvider (obj))
286 return obj.IsDefined (attributeType, inherit);
288 if (IsDefinedInternal (obj, attributeType))
291 object[] pseudoAttrs = GetPseudoCustomAttributes (obj, attributeType);
292 if (pseudoAttrs != null) {
293 for (int i = 0; i < pseudoAttrs.Length; ++i)
294 if (attributeType.IsAssignableFrom (pseudoAttrs [i].GetType ()))
300 AttributeUsageAttribute usage = RetrieveAttributeUsage (attributeType);
301 if (!usage.Inherited)
306 // FIXME (bug #82431):
307 // on 2.0 profile we should always walk the inheritance
308 // chain and base the behavior on the inheritance level:
310 // 0 : return true if "attributeType" is assignable from
311 // any of the custom attributes
313 // > 0: return true if "attributeType" is assignable from
314 // any of the custom attributes and AttributeUsageAttribute
315 // .Inherited of the assignable attribute is true
317 ICustomAttributeProvider btype;
318 if (inherit && ((btype = GetBase (obj)) != null))
319 return IsDefined (btype, attributeType, inherit);
324 [MethodImplAttribute (MethodImplOptions.InternalCall)]
325 internal static extern bool IsDefinedInternal (ICustomAttributeProvider obj, Type AttributeType);
327 static PropertyInfo GetBasePropertyDefinition (PropertyInfo property)
329 MethodInfo method = property.GetGetMethod (true);
330 if (method == null || !method.IsVirtual)
331 method = property.GetSetMethod (true);
332 if (method == null || !method.IsVirtual)
335 MethodInfo baseMethod = method.GetBaseMethod ();
336 if (baseMethod != null && baseMethod != method) {
337 ParameterInfo[] parameters = property.GetIndexParameters ();
338 if (parameters != null && parameters.Length > 0) {
339 Type[] paramTypes = new Type[parameters.Length];
340 for (int i=0; i < paramTypes.Length; i++)
341 paramTypes[i] = parameters[i].ParameterType;
342 return baseMethod.DeclaringType.GetProperty (property.Name, property.PropertyType,
345 return baseMethod.DeclaringType.GetProperty (property.Name, property.PropertyType);
352 // Handles Type, MonoProperty and MonoMethod.
353 // The runtime has also cases for MonoEvent, MonoField, Assembly and ParameterInfo,
354 // but for those we return null here.
355 static ICustomAttributeProvider GetBase (ICustomAttributeProvider obj)
361 return ((Type) obj).BaseType;
363 MethodInfo method = null;
364 if (obj is MonoProperty)
365 return GetBasePropertyDefinition ((MonoProperty) obj);
366 else if (obj is MonoMethod)
367 method = (MethodInfo) obj;
370 * ParameterInfo -> null
375 if (method == null || !method.IsVirtual)
378 MethodInfo baseMethod = method.GetBaseDefinition ();
379 if (baseMethod == method)
385 private static AttributeUsageAttribute RetrieveAttributeUsage (Type attributeType)
387 if (attributeType == typeof (AttributeUsageAttribute))
388 /* Avoid endless recursion */
389 return new AttributeUsageAttribute (AttributeTargets.Class);
391 AttributeUsageAttribute usageAttribute = null;
392 object[] attribs = GetCustomAttributes (attributeType,
393 MonoCustomAttrs.AttributeUsageType, false);
394 if (attribs.Length == 0)
396 // if no AttributeUsage was defined on the attribute level, then
397 // try to retrieve if from its base type
398 if (attributeType.BaseType != null)
400 usageAttribute = RetrieveAttributeUsage (attributeType.BaseType);
403 if (usageAttribute != null)
405 // return AttributeUsage of base class
406 return usageAttribute;
409 // return default AttributeUsageAttribute if no AttributeUsage
410 // was defined on attribute, or its base class
411 return DefaultAttributeUsage;
413 // check if more than one AttributeUsageAttribute has been specified
415 // NOTE: compilers should prevent this, but that doesn't prevent
416 // anyone from using IL ofcourse
417 if (attribs.Length > 1)
419 throw new FormatException ("Duplicate AttributeUsageAttribute cannot be specified on an attribute type.");
422 return ((AttributeUsageAttribute) attribs[0]);
425 private static readonly Type AttributeUsageType = typeof(AttributeUsageAttribute);
426 private static readonly AttributeUsageAttribute DefaultAttributeUsage =
427 new AttributeUsageAttribute (AttributeTargets.All);
429 private class AttributeInfo
431 private AttributeUsageAttribute _usage;
432 private int _inheritanceLevel;
434 public AttributeInfo (AttributeUsageAttribute usage, int inheritanceLevel)
437 _inheritanceLevel = inheritanceLevel;
440 public AttributeUsageAttribute Usage
448 public int InheritanceLevel
452 return _inheritanceLevel;