2 // MonoCustomAttrs.cs: Hooks into the runtime to get custom attributes for reflection handles
5 // Paolo Molaro (lupus@ximian.com)
6 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
7 // Marek Safar (marek.safar@gmail.com)
9 // (c) 2002,2003 Ximian, Inc. (http://www.ximian.com)
10 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
11 // Copyright (C) 2013 Xamarin, Inc (http://www.xamarin.com)
13 // Permission is hereby granted, free of charge, to any person obtaining
14 // a copy of this software and associated documentation files (the
15 // "Software"), to deal in the Software without restriction, including
16 // without limitation the rights to use, copy, modify, merge, publish,
17 // distribute, sublicense, and/or sell copies of the Software, and to
18 // permit persons to whom the Software is furnished to do so, subject to
19 // the following conditions:
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
28 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
29 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
30 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
34 using System.Reflection;
35 using System.Collections;
36 using System.Runtime.CompilerServices;
38 using System.Reflection.Emit;
41 using System.Collections.Generic;
45 static class MonoCustomAttrs
47 static Assembly corlib;
49 static Dictionary<Type, AttributeUsageAttribute> usage_cache;
51 /* Treat as user types all corlib types extending System.Type that are not MonoType and TypeBuilder */
52 static bool IsUserCattrProvider (object obj)
54 Type type = obj as Type;
56 if ((type is MonoType) || (type is TypeBuilder))
64 corlib = typeof (int).Assembly;
65 return obj.GetType ().Assembly != corlib;
68 [MethodImplAttribute (MethodImplOptions.InternalCall)]
69 internal static extern object[] GetCustomAttributesInternal (ICustomAttributeProvider obj, Type attributeType, bool pseudoAttrs);
71 internal static object[] GetPseudoCustomAttributes (ICustomAttributeProvider obj, Type attributeType) {
72 object[] pseudoAttrs = null;
74 /* FIXME: Add other types */
75 if (obj is MonoMethod)
76 pseudoAttrs = ((MonoMethod)obj).GetPseudoCustomAttributes ();
77 else if (obj is FieldInfo)
78 pseudoAttrs = ((FieldInfo)obj).GetPseudoCustomAttributes ();
79 else if (obj is ParameterInfo)
80 pseudoAttrs = ((ParameterInfo)obj).GetPseudoCustomAttributes ();
82 pseudoAttrs = ((Type)obj).GetPseudoCustomAttributes ();
84 if ((attributeType != null) && (pseudoAttrs != null)) {
85 for (int i = 0; i < pseudoAttrs.Length; ++i)
86 if (attributeType.IsAssignableFrom (pseudoAttrs [i].GetType ()))
87 if (pseudoAttrs.Length == 1)
90 return new object [] { pseudoAttrs [i] };
91 return EmptyArray<object>.Value;
97 internal static object[] GetCustomAttributesBase (ICustomAttributeProvider obj, Type attributeType, bool inheritedOnly)
100 if (IsUserCattrProvider (obj))
101 attrs = obj.GetCustomAttributes (attributeType, true);
103 attrs = GetCustomAttributesInternal (obj, attributeType, false);
106 // All pseudo custom attributes are Inherited = false hence we can avoid
107 // building attributes array which would be discarded by inherited checks
109 if (!inheritedOnly) {
110 object[] pseudoAttrs = GetPseudoCustomAttributes (obj, attributeType);
111 if (pseudoAttrs != null) {
112 object[] res = new object [attrs.Length + pseudoAttrs.Length];
113 System.Array.Copy (attrs, res, attrs.Length);
114 System.Array.Copy (pseudoAttrs, 0, res, attrs.Length, pseudoAttrs.Length);
122 internal static Attribute GetCustomAttribute (ICustomAttributeProvider obj,
126 object[] res = GetCustomAttributes (obj, attributeType, inherit);
131 else if (res.Length > 1)
133 string msg = "'{0}' has more than one attribute of type '{1}";
134 msg = String.Format (msg, obj, attributeType);
135 throw new AmbiguousMatchException (msg);
138 return (Attribute) res[0];
141 internal static object[] GetCustomAttributes (ICustomAttributeProvider obj, Type attributeType, bool inherit)
144 throw new ArgumentNullException ("obj");
145 if (attributeType == null)
146 throw new ArgumentNullException ("attributeType");
148 if (attributeType == typeof (MonoCustomAttrs))
149 attributeType = null;
152 object[] res = GetCustomAttributesBase (obj, attributeType, false);
154 if (!inherit && res.Length == 1) {
156 throw new CustomAttributeFormatException ("Invalid custom attribute format");
158 if (attributeType != null) {
159 if (attributeType.IsAssignableFrom (res[0].GetType ())) {
160 r = (object[]) Array.CreateInstance (attributeType, 1);
163 r = (object[]) Array.CreateInstance (attributeType, 0);
166 r = (object[]) Array.CreateInstance (res[0].GetType (), 1);
172 if (inherit && GetBase (obj) == null)
175 // if AttributeType is sealed, and Inherited is set to false, then
176 // there's no use in scanning base types
177 if ((attributeType != null && attributeType.IsSealed) && inherit) {
178 AttributeUsageAttribute usageAttribute = RetrieveAttributeUsage (
180 if (!usageAttribute.Inherited)
184 var initialSize = Math.Max (res.Length, 16);
185 List<Object> a = null;
186 ICustomAttributeProvider btype = obj;
189 /* Non-inherit case */
191 if (attributeType == null) {
192 foreach (object attr in res) {
194 throw new CustomAttributeFormatException ("Invalid custom attribute format");
196 var result = new Attribute [res.Length];
197 res.CopyTo (result, 0);
201 a = new List<object> (initialSize);
202 foreach (object attr in res) {
204 throw new CustomAttributeFormatException ("Invalid custom attribute format");
206 Type attrType = attr.GetType ();
207 if (attributeType != null && !attributeType.IsAssignableFrom (attrType))
212 if (attributeType == null || attributeType.IsValueType)
213 array = new Attribute [a.Count];
215 array = Array.CreateInstance (attributeType, a.Count) as object[];
221 var attributeInfos = new Dictionary<Type, AttributeInfo> (initialSize);
222 int inheritanceLevel = 0;
223 a = new List<object> (initialSize);
226 foreach (object attr in res) {
227 AttributeUsageAttribute usage;
229 throw new CustomAttributeFormatException ("Invalid custom attribute format");
231 Type attrType = attr.GetType ();
232 if (attributeType != null) {
233 if (!attributeType.IsAssignableFrom (attrType))
237 AttributeInfo firstAttribute;
238 if (attributeInfos.TryGetValue (attrType, out firstAttribute))
239 usage = firstAttribute.Usage;
241 usage = RetrieveAttributeUsage (attrType);
243 // only add attribute to the list of attributes if
244 // - we are on the first inheritance level, or the attribute can be inherited anyway
246 // - multiple attributes of the type are allowed
248 // - this is the first attribute we've discovered
250 // - the attribute is on same inheritance level than the first
251 // attribute that was discovered for this attribute type ))
252 if ((inheritanceLevel == 0 || usage.Inherited) && (usage.AllowMultiple ||
253 (firstAttribute == null || (firstAttribute != null
254 && firstAttribute.InheritanceLevel == inheritanceLevel))))
257 if (firstAttribute == null)
258 attributeInfos.Add (attrType, new AttributeInfo (usage, inheritanceLevel));
261 if ((btype = GetBase (btype)) != null) {
263 res = GetCustomAttributesBase (btype, attributeType, true);
265 } while (inherit && btype != null);
267 if (attributeType == null || attributeType.IsValueType)
268 array = new Attribute [a.Count];
270 array = Array.CreateInstance (attributeType, a.Count) as object[];
272 // copy attributes to array
278 internal static object[] GetCustomAttributes (ICustomAttributeProvider obj, bool inherit)
281 throw new ArgumentNullException ("obj");
284 return (object[]) GetCustomAttributesBase (obj, null, false).Clone ();
286 return GetCustomAttributes (obj, typeof (MonoCustomAttrs), inherit);
289 [MethodImplAttribute (MethodImplOptions.InternalCall)]
290 static extern CustomAttributeData [] GetCustomAttributesDataInternal (ICustomAttributeProvider obj);
292 internal static IList<CustomAttributeData> GetCustomAttributesData (ICustomAttributeProvider obj)
295 throw new ArgumentNullException ("obj");
297 CustomAttributeData [] attrs = GetCustomAttributesDataInternal (obj);
298 return Array.AsReadOnly<CustomAttributeData> (attrs);
301 internal static bool IsDefined (ICustomAttributeProvider obj, Type attributeType, bool inherit)
303 if (attributeType == null)
304 throw new ArgumentNullException ("attributeType");
306 AttributeUsageAttribute usage = null;
308 if (IsUserCattrProvider (obj))
309 return obj.IsDefined (attributeType, inherit);
311 if (IsDefinedInternal (obj, attributeType))
314 object[] pseudoAttrs = GetPseudoCustomAttributes (obj, attributeType);
315 if (pseudoAttrs != null) {
316 for (int i = 0; i < pseudoAttrs.Length; ++i)
317 if (attributeType.IsAssignableFrom (pseudoAttrs[i].GetType ()))
325 usage = RetrieveAttributeUsage (attributeType);
326 if (!usage.Inherited)
331 } while (obj != null);
336 [MethodImplAttribute (MethodImplOptions.InternalCall)]
337 internal static extern bool IsDefinedInternal (ICustomAttributeProvider obj, Type AttributeType);
339 static PropertyInfo GetBasePropertyDefinition (MonoProperty property)
341 MethodInfo method = property.GetGetMethod (true);
342 if (method == null || !method.IsVirtual)
343 method = property.GetSetMethod (true);
344 if (method == null || !method.IsVirtual)
347 MethodInfo baseMethod = method.GetBaseMethod ();
348 if (baseMethod != null && baseMethod != method) {
349 ParameterInfo[] parameters = property.GetIndexParameters ();
350 if (parameters != null && parameters.Length > 0) {
351 Type[] paramTypes = new Type[parameters.Length];
352 for (int i=0; i < paramTypes.Length; i++)
353 paramTypes[i] = parameters[i].ParameterType;
354 return baseMethod.DeclaringType.GetProperty (property.Name, property.PropertyType,
357 return baseMethod.DeclaringType.GetProperty (property.Name, property.PropertyType);
364 static EventInfo GetBaseEventDefinition (MonoEvent evt)
366 MethodInfo method = evt.GetAddMethod (true);
367 if (method == null || !method.IsVirtual)
368 method = evt.GetRaiseMethod (true);
369 if (method == null || !method.IsVirtual)
370 method = evt.GetRemoveMethod (true);
371 if (method == null || !method.IsVirtual)
374 MethodInfo baseMethod = method.GetBaseMethod ();
375 if (baseMethod != null && baseMethod != method) {
376 BindingFlags flags = method.IsPublic ? BindingFlags.Public : BindingFlags.NonPublic;
377 flags |= method.IsStatic ? BindingFlags.Static : BindingFlags.Instance;
379 return baseMethod.DeclaringType.GetEvent (evt.Name, flags);
384 // Handles Type, MonoProperty and MonoMethod.
385 // The runtime has also cases for MonoEvent, MonoField, Assembly and ParameterInfo,
386 // but for those we return null here.
387 static ICustomAttributeProvider GetBase (ICustomAttributeProvider obj)
393 return ((Type) obj).BaseType;
395 MethodInfo method = null;
396 if (obj is MonoProperty)
397 return GetBasePropertyDefinition ((MonoProperty) obj);
398 else if (obj is MonoEvent)
399 return GetBaseEventDefinition ((MonoEvent)obj);
400 else if (obj is MonoMethod)
401 method = (MethodInfo) obj;
404 * ParameterInfo -> null
409 if (method == null || !method.IsVirtual)
412 MethodInfo baseMethod = method.GetBaseMethod ();
413 if (baseMethod == method)
419 private static AttributeUsageAttribute RetrieveAttributeUsageNoCache (Type attributeType)
421 if (attributeType == typeof (AttributeUsageAttribute))
422 /* Avoid endless recursion */
423 return new AttributeUsageAttribute (AttributeTargets.Class);
425 AttributeUsageAttribute usageAttribute = null;
426 object[] attribs = GetCustomAttributes (attributeType, typeof(AttributeUsageAttribute), false);
427 if (attribs.Length == 0)
429 // if no AttributeUsage was defined on the attribute level, then
430 // try to retrieve if from its base type
431 if (attributeType.BaseType != null)
433 usageAttribute = RetrieveAttributeUsage (attributeType.BaseType);
436 if (usageAttribute != null)
438 // return AttributeUsage of base class
439 return usageAttribute;
442 // return default AttributeUsageAttribute if no AttributeUsage
443 // was defined on attribute, or its base class
444 return DefaultAttributeUsage;
446 // check if more than one AttributeUsageAttribute has been specified
448 // NOTE: compilers should prevent this, but that doesn't prevent
449 // anyone from using IL ofcourse
450 if (attribs.Length > 1)
452 throw new FormatException ("Duplicate AttributeUsageAttribute cannot be specified on an attribute type.");
455 return ((AttributeUsageAttribute) attribs[0]);
458 static AttributeUsageAttribute RetrieveAttributeUsage (Type attributeType)
460 AttributeUsageAttribute usageAttribute = null;
461 /* Usage a thread-local cache to speed this up, since it is called a lot from GetCustomAttributes () */
462 if (usage_cache == null)
463 usage_cache = new Dictionary<Type, AttributeUsageAttribute> ();
464 if (usage_cache.TryGetValue (attributeType, out usageAttribute))
465 return usageAttribute;
466 usageAttribute = RetrieveAttributeUsageNoCache (attributeType);
467 usage_cache [attributeType] = usageAttribute;
468 return usageAttribute;
471 private static readonly AttributeUsageAttribute DefaultAttributeUsage =
472 new AttributeUsageAttribute (AttributeTargets.All);
474 private class AttributeInfo
476 private AttributeUsageAttribute _usage;
477 private int _inheritanceLevel;
479 public AttributeInfo (AttributeUsageAttribute usage, int inheritanceLevel)
482 _inheritanceLevel = inheritanceLevel;
485 public AttributeUsageAttribute Usage
493 public int InheritanceLevel
497 return _inheritanceLevel;