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");
120 object[] res = GetCustomAttributesBase (obj, attributeType);
122 if (!inherit && res.Length == 1)
124 if (attributeType != null)
126 if (attributeType.IsAssignableFrom (res[0].GetType ()))
128 r = (object[]) Array.CreateInstance (attributeType, 1);
133 r = (object[]) Array.CreateInstance (attributeType, 0);
138 r = (object[]) Array.CreateInstance (res[0].GetType (), 1);
144 // if AttributeType is sealed, and Inherited is set to false, then
145 // there's no use in scanning base types
146 if ((attributeType != null && attributeType.IsSealed) && inherit)
148 AttributeUsageAttribute usageAttribute = RetrieveAttributeUsage (
150 if (!usageAttribute.Inherited)
156 int initialSize = res.Length < 16 ? res.Length : 16;
158 Hashtable attributeInfos = new Hashtable (initialSize);
159 ArrayList a = new ArrayList (initialSize);
160 ICustomAttributeProvider btype = obj;
162 int inheritanceLevel = 0;
166 foreach (object attr in res)
168 AttributeUsageAttribute usage;
170 Type attrType = attr.GetType ();
171 if (attributeType != null)
173 if (!attributeType.IsAssignableFrom (attrType))
179 AttributeInfo firstAttribute = (AttributeInfo) attributeInfos[attrType];
180 if (firstAttribute != null)
182 usage = firstAttribute.Usage;
186 usage = RetrieveAttributeUsage (attrType);
189 // only add attribute to the list of attributes if
190 // - we are on the first inheritance level, or the attribute can be inherited anyway
192 // - multiple attributes of the type are allowed
194 // - this is the first attribute we've discovered
196 // - the attribute is on same inheritance level than the first
197 // attribute that was discovered for this attribute type ))
198 if ((inheritanceLevel == 0 || usage.Inherited) && (usage.AllowMultiple ||
199 (firstAttribute == null || (firstAttribute != null
200 && firstAttribute.InheritanceLevel == inheritanceLevel))))
205 if (firstAttribute == null)
207 attributeInfos.Add (attrType, new AttributeInfo (usage, inheritanceLevel));
211 if ((btype = GetBase (btype)) != null)
214 res = GetCustomAttributesBase (btype, attributeType);
216 } while (inherit && btype != null);
218 object[] array = null;
219 if (attributeType == null || attributeType.IsValueType)
221 array = (object[]) Array.CreateInstance (typeof(Attribute), a.Count);
225 array = Array.CreateInstance (attributeType, a.Count) as object[];
228 // copy attributes to array
234 internal static object[] GetCustomAttributes (ICustomAttributeProvider obj, bool inherit)
237 throw new ArgumentNullException ("obj");
240 return (object[]) GetCustomAttributesBase (obj, null).Clone ();
242 return GetCustomAttributes (obj, null, inherit);
246 [MethodImplAttribute (MethodImplOptions.InternalCall)]
247 static extern CustomAttributeData [] GetCustomAttributesDataInternal (ICustomAttributeProvider obj);
249 internal static IList<CustomAttributeData> GetCustomAttributesData (ICustomAttributeProvider obj)
252 throw new ArgumentNullException ("obj");
254 CustomAttributeData [] attrs = GetCustomAttributesDataInternal (obj);
255 return Array.AsReadOnly<CustomAttributeData> (attrs);
259 internal static bool IsDefined (ICustomAttributeProvider obj, Type attributeType, bool inherit)
261 if (obj.GetType ().Assembly != typeof (int).Assembly)
262 // User types might overwrite GetCustomAttributes () but not
264 return obj.GetCustomAttributes (attributeType, inherit).Length > 0;
266 if (IsDefinedInternal (obj, attributeType))
269 object[] pseudoAttrs = GetPseudoCustomAttributes (obj, attributeType);
270 if (pseudoAttrs != null) {
271 for (int i = 0; i < pseudoAttrs.Length; ++i)
272 if (attributeType.IsAssignableFrom (pseudoAttrs [i].GetType ()))
276 AttributeUsageAttribute usage = RetrieveAttributeUsage (
279 ICustomAttributeProvider btype;
280 if (usage.Inherited && inherit && ((btype = GetBase (obj)) != null))
281 return IsDefined (btype, attributeType, inherit);
286 [MethodImplAttribute (MethodImplOptions.InternalCall)]
287 internal static extern bool IsDefinedInternal (ICustomAttributeProvider obj, Type AttributeType);
289 // Handles Type, MonoProperty and MonoMethod.
290 // The runtime has also cases for MonoEvent, MonoField, Assembly and ParameterInfo,
291 // but for those we return null here.
292 static ICustomAttributeProvider GetBase (ICustomAttributeProvider obj)
298 return ((Type) obj).BaseType;
300 MethodInfo method = null;
301 if (obj is MonoProperty)
303 MonoProperty prop = (MonoProperty) obj;
304 method = prop.GetGetMethod (true);
306 method = prop.GetSetMethod (true);
308 MonoProperty prop = (MonoProperty) obj;
309 if (prop.DeclaringType.BaseType != null) {
310 PropertyInfo baseProp = prop.DeclaringType.BaseType.GetProperty (prop.Name);
311 if (baseProp != prop)
317 else if (obj is MonoMethod)
319 method = (MethodInfo) obj;
323 * ParameterInfo -> null
328 if (method == null || !method.IsVirtual)
331 MethodInfo baseMethod = method.GetBaseDefinition ();
332 if (baseMethod == method)
338 private static AttributeUsageAttribute RetrieveAttributeUsage (Type attributeType)
340 if (attributeType == typeof (AttributeUsageAttribute))
341 /* Avoid endless recursion */
342 return new AttributeUsageAttribute (AttributeTargets.Class);
344 AttributeUsageAttribute usageAttribute = null;
345 object[] attribs = GetCustomAttributes (attributeType,
346 MonoCustomAttrs.AttributeUsageType, false);
347 if (attribs.Length == 0)
349 // if no AttributeUsage was defined on the attribute level, then
350 // try to retrieve if from its base type
351 if (attributeType.BaseType != null)
353 usageAttribute = RetrieveAttributeUsage (attributeType.BaseType);
356 if (usageAttribute != null)
358 // return AttributeUsage of base class
359 return usageAttribute;
362 // return default AttributeUsageAttribute if no AttributeUsage
363 // was defined on attribute, or its base class
364 return DefaultAttributeUsage;
366 // check if more than one AttributeUsageAttribute has been specified
368 // NOTE: compilers should prevent this, but that doesn't prevent
369 // anyone from using IL ofcourse
370 if (attribs.Length > 1)
372 throw new FormatException ("Duplicate AttributeUsageAttribute cannot be specified on an attribute type.");
375 return ((AttributeUsageAttribute) attribs[0]);
378 private static readonly Type AttributeUsageType = typeof(AttributeUsageAttribute);
379 private static readonly AttributeUsageAttribute DefaultAttributeUsage =
380 new AttributeUsageAttribute (AttributeTargets.All);
382 private class AttributeInfo
384 private AttributeUsageAttribute _usage;
385 private int _inheritanceLevel;
387 public AttributeInfo (AttributeUsageAttribute usage, int inheritanceLevel)
390 _inheritanceLevel = inheritanceLevel;
393 public AttributeUsageAttribute Usage
401 public int InheritanceLevel
405 return _inheritanceLevel;