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;
40 using System.Collections.Generic;
45 internal class MonoCustomAttrs
47 [MethodImplAttribute (MethodImplOptions.InternalCall)]
48 internal static extern object[] GetCustomAttributesInternal (ICustomAttributeProvider obj, Type attributeType, bool pseudoAttrs);
50 internal static object[] GetPseudoCustomAttributes (ICustomAttributeProvider obj, Type attributeType) {
51 #if NET_2_0 || BOOTSTRAP_NET_2_0
52 object[] pseudoAttrs = null;
54 /* FIXME: Add other types */
55 if (obj is MonoMethod)
56 pseudoAttrs = ((MonoMethod)obj).GetPseudoCustomAttributes ();
57 else if (obj is FieldInfo)
58 pseudoAttrs = ((FieldInfo)obj).GetPseudoCustomAttributes ();
59 else if (obj is ParameterInfo)
60 pseudoAttrs = ((ParameterInfo)obj).GetPseudoCustomAttributes ();
62 pseudoAttrs = ((Type)obj).GetPseudoCustomAttributes ();
64 if ((attributeType != null) && (pseudoAttrs != null)) {
65 for (int i = 0; i < pseudoAttrs.Length; ++i)
66 if (attributeType.IsAssignableFrom (pseudoAttrs [i].GetType ()))
67 if (pseudoAttrs.Length == 1)
70 return new object [] { pseudoAttrs [i] };
71 return new object [0];
80 internal static object[] GetCustomAttributesBase (ICustomAttributeProvider obj, Type attributeType)
82 object[] attrs = GetCustomAttributesInternal (obj, attributeType, false);
84 object[] pseudoAttrs = GetPseudoCustomAttributes (obj, attributeType);
85 if (pseudoAttrs != null) {
86 object[] res = new object [attrs.Length + pseudoAttrs.Length];
87 System.Array.Copy (attrs, res, attrs.Length);
88 System.Array.Copy (pseudoAttrs, 0, res, attrs.Length, pseudoAttrs.Length);
95 internal static Attribute GetCustomAttribute (ICustomAttributeProvider obj,
99 object[] res = GetCustomAttributes (obj, attributeType, inherit);
104 else if (res.Length > 1)
106 string msg = "'{0}' has more than one attribute of type '{1}";
107 msg = String.Format (msg, obj, attributeType);
108 throw new AmbiguousMatchException (msg);
111 return (Attribute) res[0];
114 internal static object[] GetCustomAttributes (ICustomAttributeProvider obj, Type attributeType, bool inherit)
117 throw new ArgumentNullException ("obj");
118 if (attributeType == null)
119 throw new ArgumentNullException ("attributeType");
121 if (attributeType == typeof (MonoCustomAttrs))
122 attributeType = null;
125 object[] res = GetCustomAttributesBase (obj, attributeType);
127 if (!inherit && res.Length == 1)
129 if (attributeType != null)
131 if (attributeType.IsAssignableFrom (res[0].GetType ()))
133 r = (object[]) Array.CreateInstance (attributeType, 1);
138 r = (object[]) Array.CreateInstance (attributeType, 0);
143 r = (object[]) Array.CreateInstance (res[0].GetType (), 1);
149 // if AttributeType is sealed, and Inherited is set to false, then
150 // there's no use in scanning base types
151 if ((attributeType != null && attributeType.IsSealed) && inherit)
153 AttributeUsageAttribute usageAttribute = RetrieveAttributeUsage (
155 if (!usageAttribute.Inherited)
161 int initialSize = res.Length < 16 ? res.Length : 16;
163 Hashtable attributeInfos = new Hashtable (initialSize);
164 ArrayList a = new ArrayList (initialSize);
165 ICustomAttributeProvider btype = obj;
167 int inheritanceLevel = 0;
171 foreach (object attr in res)
173 AttributeUsageAttribute usage;
175 Type attrType = attr.GetType ();
176 if (attributeType != null)
178 if (!attributeType.IsAssignableFrom (attrType))
184 AttributeInfo firstAttribute = (AttributeInfo) attributeInfos[attrType];
185 if (firstAttribute != null)
187 usage = firstAttribute.Usage;
191 usage = RetrieveAttributeUsage (attrType);
194 // only add attribute to the list of attributes if
195 // - we are on the first inheritance level, or the attribute can be inherited anyway
197 // - multiple attributes of the type are allowed
199 // - this is the first attribute we've discovered
201 // - the attribute is on same inheritance level than the first
202 // attribute that was discovered for this attribute type ))
203 if ((inheritanceLevel == 0 || usage.Inherited) && (usage.AllowMultiple ||
204 (firstAttribute == null || (firstAttribute != null
205 && firstAttribute.InheritanceLevel == inheritanceLevel))))
210 if (firstAttribute == null)
212 attributeInfos.Add (attrType, new AttributeInfo (usage, inheritanceLevel));
216 if ((btype = GetBase (btype)) != null)
219 res = GetCustomAttributesBase (btype, attributeType);
221 } while (inherit && btype != null);
223 object[] array = null;
224 if (attributeType == null || attributeType.IsValueType)
226 array = (object[]) Array.CreateInstance (typeof(Attribute), a.Count);
230 array = Array.CreateInstance (attributeType, a.Count) as object[];
233 // copy attributes to array
239 internal static object[] GetCustomAttributes (ICustomAttributeProvider obj, bool inherit)
242 throw new ArgumentNullException ("obj");
245 return (object[]) GetCustomAttributesBase (obj, null).Clone ();
247 return GetCustomAttributes (obj, typeof (MonoCustomAttrs), inherit);
251 [MethodImplAttribute (MethodImplOptions.InternalCall)]
252 static extern CustomAttributeData [] GetCustomAttributesDataInternal (ICustomAttributeProvider obj);
254 internal static IList<CustomAttributeData> GetCustomAttributesData (ICustomAttributeProvider obj)
257 throw new ArgumentNullException ("obj");
259 CustomAttributeData [] attrs = GetCustomAttributesDataInternal (obj);
260 return Array.AsReadOnly<CustomAttributeData> (attrs);
264 internal static bool IsDefined (ICustomAttributeProvider obj, Type attributeType, bool inherit)
266 if (attributeType == null)
267 throw new ArgumentNullException ("attributeType");
269 if (obj.GetType ().Assembly != typeof (int).Assembly)
270 // User types might overwrite GetCustomAttributes () but not
272 return obj.GetCustomAttributes (attributeType, inherit).Length > 0;
274 if (IsDefinedInternal (obj, attributeType))
277 object[] pseudoAttrs = GetPseudoCustomAttributes (obj, attributeType);
278 if (pseudoAttrs != null) {
279 for (int i = 0; i < pseudoAttrs.Length; ++i)
280 if (attributeType.IsAssignableFrom (pseudoAttrs [i].GetType ()))
286 AttributeUsageAttribute usage = RetrieveAttributeUsage (attributeType);
287 if (!usage.Inherited)
292 // FIXME (bug #82431):
293 // on 2.0 profile we should always walk the inheritance
294 // chain and base the behavior on the inheritance level:
296 // 0 : return true if "attributeType" is assignable from
297 // any of the custom attributes
299 // > 0: return true if "attributeType" is assignable from
300 // any of the custom attributes and AttributeUsageAttribute
301 // .Inherited of the assignable attribute is true
303 ICustomAttributeProvider btype;
304 if (inherit && ((btype = GetBase (obj)) != null))
305 return IsDefined (btype, attributeType, inherit);
310 [MethodImplAttribute (MethodImplOptions.InternalCall)]
311 internal static extern bool IsDefinedInternal (ICustomAttributeProvider obj, Type AttributeType);
313 static PropertyInfo GetBasePropertyDefinition (PropertyInfo property)
315 MethodInfo method = property.GetGetMethod (true);
316 if (method == null || !method.IsVirtual)
317 method = property.GetSetMethod (true);
318 if (method == null || !method.IsVirtual)
321 MethodInfo baseMethod = method.GetBaseDefinition ();
322 if (baseMethod != null && baseMethod != method) {
323 ParameterInfo[] parameters = property.GetIndexParameters ();
324 if (parameters != null && parameters.Length > 0) {
325 Type[] paramTypes = new Type[parameters.Length];
326 for (int i=0; i < paramTypes.Length; i++)
327 paramTypes[i] = parameters[i].ParameterType;
328 return baseMethod.DeclaringType.GetProperty (property.Name, property.PropertyType,
331 return baseMethod.DeclaringType.GetProperty (property.Name, property.PropertyType);
338 // Handles Type, MonoProperty and MonoMethod.
339 // The runtime has also cases for MonoEvent, MonoField, Assembly and ParameterInfo,
340 // but for those we return null here.
341 static ICustomAttributeProvider GetBase (ICustomAttributeProvider obj)
347 return ((Type) obj).BaseType;
349 MethodInfo method = null;
350 if (obj is MonoProperty)
351 return GetBasePropertyDefinition ((MonoProperty) obj);
352 else if (obj is MonoMethod)
353 method = (MethodInfo) obj;
356 * ParameterInfo -> null
361 if (method == null || !method.IsVirtual)
364 MethodInfo baseMethod = method.GetBaseDefinition ();
365 if (baseMethod == method)
371 private static AttributeUsageAttribute RetrieveAttributeUsage (Type attributeType)
373 if (attributeType == typeof (AttributeUsageAttribute))
374 /* Avoid endless recursion */
375 return new AttributeUsageAttribute (AttributeTargets.Class);
377 AttributeUsageAttribute usageAttribute = null;
378 object[] attribs = GetCustomAttributes (attributeType,
379 MonoCustomAttrs.AttributeUsageType, false);
380 if (attribs.Length == 0)
382 // if no AttributeUsage was defined on the attribute level, then
383 // try to retrieve if from its base type
384 if (attributeType.BaseType != null)
386 usageAttribute = RetrieveAttributeUsage (attributeType.BaseType);
389 if (usageAttribute != null)
391 // return AttributeUsage of base class
392 return usageAttribute;
395 // return default AttributeUsageAttribute if no AttributeUsage
396 // was defined on attribute, or its base class
397 return DefaultAttributeUsage;
399 // check if more than one AttributeUsageAttribute has been specified
401 // NOTE: compilers should prevent this, but that doesn't prevent
402 // anyone from using IL ofcourse
403 if (attribs.Length > 1)
405 throw new FormatException ("Duplicate AttributeUsageAttribute cannot be specified on an attribute type.");
408 return ((AttributeUsageAttribute) attribs[0]);
411 private static readonly Type AttributeUsageType = typeof(AttributeUsageAttribute);
412 private static readonly AttributeUsageAttribute DefaultAttributeUsage =
413 new AttributeUsageAttribute (AttributeTargets.All);
415 private class AttributeInfo
417 private AttributeUsageAttribute _usage;
418 private int _inheritanceLevel;
420 public AttributeInfo (AttributeUsageAttribute usage, int inheritanceLevel)
423 _inheritanceLevel = inheritanceLevel;
426 public AttributeUsageAttribute Usage
434 public int InheritanceLevel
438 return _inheritanceLevel;