You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

335 lines
17 KiB

4 years ago
4 years ago
  1. using IPA.Utilities.Async;
  2. using System;
  3. using System.Collections.Concurrent;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Reflection;
  7. using System.Reflection.Emit;
  8. using System.Threading;
  9. #if NET3
  10. using Net3_Proxy;
  11. using Array = Net3_Proxy.Array;
  12. #endif
  13. namespace IPA.Utilities
  14. {
  15. /// <summary>
  16. /// A type containing utilities for accessing non-public fields of objects.
  17. /// </summary>
  18. /// <typeparam name="T">the type that the fields are on</typeparam>
  19. /// <typeparam name="U">the type of the field to access</typeparam>
  20. /// <seealso cref="PropertyAccessor{T, U}"/>
  21. public static class FieldAccessor<T, U>
  22. {
  23. /// <summary>
  24. /// A delegate for a field accessor taking a <typeparamref name="T"/> ref and returning a <typeparamref name="U"/> ref.
  25. /// </summary>
  26. /// <param name="obj">the object to access the field of</param>
  27. /// <returns>a reference to the field's value</returns>
  28. public delegate ref U Accessor(ref T obj);
  29. private static Accessor MakeAccessor(string fieldName)
  30. {
  31. var field = typeof(T).GetField(fieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
  32. if (field == null)
  33. throw new MissingFieldException(typeof(T).Name, fieldName);
  34. if (field.FieldType != typeof(U))
  35. throw new ArgumentException($"Field '{fieldName}' not of type {typeof(U)}");
  36. var dynMethodName = $"<>_accessor__{fieldName}";
  37. // unfortunately DynamicMethod doesn't like having a ByRef return type, so reflection it
  38. var dyn = new DynamicMethod(dynMethodName, typeof(U), new[] { typeof(T).MakeByRefType() }, typeof(FieldAccessor<T, U>), true);
  39. ReflectionUtil.DynamicMethodReturnType.SetValue(dyn, typeof(U).MakeByRefType());
  40. var il = dyn.GetILGenerator();
  41. il.Emit(OpCodes.Ldarg_0);
  42. if (!typeof(T).IsValueType)
  43. il.Emit(OpCodes.Ldind_Ref);
  44. il.Emit(OpCodes.Ldflda, field);
  45. il.Emit(OpCodes.Ret);
  46. return (Accessor)dyn.CreateDelegate(typeof(Accessor));
  47. }
  48. // field name -> accessor
  49. private static readonly SingleCreationValueCache<string, Accessor> accessors = new SingleCreationValueCache<string, Accessor>();
  50. /// <summary>
  51. /// Gets an <see cref="Accessor"/> for the field named <paramref name="name"/> on <typeparamref name="T"/>.
  52. /// </summary>
  53. /// <param name="name">the field name</param>
  54. /// <returns>an accessor for the field</returns>
  55. /// <exception cref="MissingFieldException">if the field does not exist on <typeparamref name="T"/></exception>
  56. public static Accessor GetAccessor(string name)
  57. => accessors.GetOrAdd(name, MakeAccessor);
  58. /// <summary>
  59. /// Accesses a field for an object by name.
  60. /// </summary>
  61. /// <param name="obj">the object to access the field of</param>
  62. /// <param name="name">the name of the field to access</param>
  63. /// <returns>a reference to the object at the field</returns>
  64. /// <exception cref="MissingFieldException">if the field does not exist on <typeparamref name="T"/></exception>
  65. /// <seealso cref="GetAccessor(string)"/>
  66. public static ref U Access(ref T obj, string name) => ref GetAccessor(name)(ref obj);
  67. /// <summary>
  68. /// Gets the value of a field of an object by name.
  69. /// </summary>
  70. /// <remarks>
  71. /// The only good reason to use this over <see cref="Get(T, string)"/> is when you are working with a value type,
  72. /// as it prevents a copy.
  73. /// </remarks>
  74. /// <param name="obj">the object to access the field of</param>
  75. /// <param name="name">the name of the field to access</param>
  76. /// <returns>the value of the field</returns>
  77. /// <exception cref="MissingFieldException">if the field does not exist on <typeparamref name="T"/></exception>
  78. /// <seealso cref="Get(T, string)"/>
  79. /// <seealso cref="Access(ref T, string)"/>
  80. /// <seealso cref="GetAccessor(string)"/>
  81. public static U Get(ref T obj, string name) => Access(ref obj, name);
  82. /// <summary>
  83. /// Gets the value of a field of an object by name.
  84. /// </summary>
  85. /// <param name="obj">the object to access the field of</param>
  86. /// <param name="name">the name of the field to access</param>
  87. /// <returns>the value of the field</returns>
  88. /// <exception cref="MissingFieldException">if the field does not exist on <typeparamref name="T"/></exception>
  89. /// <seealso cref="Get(ref T, string)"/>
  90. /// <seealso cref="Access(ref T, string)"/>
  91. /// <seealso cref="GetAccessor(string)"/>
  92. public static U Get(T obj, string name) => Get(ref obj, name);
  93. /// <summary>
  94. /// Sets the value of a field for an object by name.
  95. /// </summary>
  96. /// <remarks>
  97. /// This overload must be used for value types.
  98. /// </remarks>
  99. /// <param name="obj">the object to set the field of</param>
  100. /// <param name="name">the name of the field</param>
  101. /// <param name="value">the value to set it to</param>
  102. /// <exception cref="MissingFieldException">if the field does not exist on <typeparamref name="T"/></exception>
  103. /// <seealso cref="Set(T, string, U)"/>
  104. /// <seealso cref="Access(ref T, string)"/>
  105. /// <seealso cref="GetAccessor(string)"/>
  106. public static void Set(ref T obj, string name, U value) => Access(ref obj, name) = value;
  107. /// <summary>
  108. /// Sets the value of a field for an object by name.
  109. /// </summary>
  110. /// <remarks>
  111. /// This overload cannot be safely used for value types. Use <see cref="Set(ref T, string, U)"/> instead.
  112. /// </remarks>
  113. /// <param name="obj">the object to set the field of</param>
  114. /// <param name="name">the name of the field</param>
  115. /// <param name="value">the value to set it to</param>
  116. /// <exception cref="MissingFieldException">if the field does not exist on <typeparamref name="T"/></exception>
  117. /// <seealso cref="Set(ref T, string, U)"/>
  118. /// <seealso cref="Access(ref T, string)"/>
  119. /// <seealso cref="GetAccessor(string)"/>
  120. public static void Set(T obj, string name, U value) => Set(ref obj, name, value);
  121. }
  122. /// <summary>
  123. /// A type containing utilities for accessing non-public properties of an object.
  124. /// </summary>
  125. /// <typeparam name="T">the type that the properties are on</typeparam>
  126. /// <typeparam name="U">the type of the property to access</typeparam>
  127. public static class PropertyAccessor<T, U>
  128. {
  129. /// <summary>
  130. /// A getter for a property.
  131. /// </summary>
  132. /// <param name="obj">the object it is a member of</param>
  133. /// <returns>the value of the property</returns>
  134. public delegate U Getter(ref T obj);
  135. /// <summary>
  136. /// A setter for a property.
  137. /// </summary>
  138. /// <param name="obj">the object it is a member of</param>
  139. /// <param name="val">the new property value</param>
  140. public delegate void Setter(ref T obj, U val);
  141. private static (Getter, Setter) MakeAccessors(string propName)
  142. {
  143. var prop = typeof(T).GetProperty(propName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
  144. if (prop == null)
  145. throw new MissingMemberException(typeof(T).Name, propName);
  146. if (prop.PropertyType != typeof(U))
  147. throw new ArgumentException($"Property '{propName}' on {typeof(T)} is not of type {typeof(U)}");
  148. var getM = prop.GetGetMethod(true);
  149. var setM = prop.GetSetMethod(true);
  150. Getter getter = null;
  151. Setter setter = null;
  152. if (typeof(T).IsValueType)
  153. {
  154. if (getM != null)
  155. getter = (Getter)Delegate.CreateDelegate(typeof(Getter), getM);
  156. if (setM != null)
  157. setter = (Setter)Delegate.CreateDelegate(typeof(Setter), setM);
  158. }
  159. else
  160. {
  161. if (getM != null)
  162. {
  163. var dyn = new DynamicMethod($"<>_get__{propName}", typeof(U), new[] { typeof(T).MakeByRefType() }, typeof(PropertyAccessor<T, U>), true);
  164. var il = dyn.GetILGenerator();
  165. il.Emit(OpCodes.Ldarg_0);
  166. il.Emit(OpCodes.Ldind_Ref);
  167. il.Emit(OpCodes.Tailcall);
  168. il.Emit(getM.IsVirtual ? OpCodes.Callvirt : OpCodes.Call, getM);
  169. il.Emit(OpCodes.Ret);
  170. getter = (Getter)dyn.CreateDelegate(typeof(Getter));
  171. }
  172. if (setM != null)
  173. {
  174. var dyn = new DynamicMethod($"<>_set__{propName}", typeof(void), new[] { typeof(T).MakeByRefType(), typeof(U) }, typeof(PropertyAccessor<T, U>), true);
  175. var il = dyn.GetILGenerator();
  176. il.Emit(OpCodes.Ldarg_0);
  177. il.Emit(OpCodes.Ldind_Ref);
  178. il.Emit(OpCodes.Ldarg_1);
  179. il.Emit(OpCodes.Tailcall);
  180. il.Emit(setM.IsVirtual ? OpCodes.Callvirt : OpCodes.Call, setM);
  181. il.Emit(OpCodes.Ret);
  182. setter = (Setter)dyn.CreateDelegate(typeof(Setter));
  183. }
  184. }
  185. return (getter, setter);
  186. }
  187. private static readonly SingleCreationValueCache<string, (Getter get, Setter set)> props
  188. = new SingleCreationValueCache<string, (Getter get, Setter set)>();
  189. private static (Getter get, Setter set) GetAccessors(string propName)
  190. => props.GetOrAdd(propName, MakeAccessors);
  191. /// <summary>
  192. /// Gets a <see cref="Getter"/> for the property identified by <paramref name="name"/>.
  193. /// </summary>
  194. /// <param name="name">the name of the property</param>
  195. /// <returns>a <see cref="Getter"/> that can access that property</returns>
  196. /// <exception cref="MissingMemberException">if the property does not exist</exception>
  197. public static Getter GetGetter(string name) => GetAccessors(name).get;
  198. /// <summary>
  199. /// Gets a <see cref="Setter"/> for the property identified by <paramref name="name"/>.
  200. /// </summary>
  201. /// <param name="name">the name of the property</param>
  202. /// <returns>a <see cref="Setter"/> that can access that property</returns>
  203. /// <exception cref="MissingMemberException">if the property does not exist</exception>
  204. public static Setter GetSetter(string name) => GetAccessors(name).set;
  205. /// <summary>
  206. /// Gets the value of the property identified by <paramref name="name"/> on <paramref name="obj"/>.
  207. /// </summary>
  208. /// <remarks>
  209. /// The only reason to use this over <see cref="Get(T, string)"/> is if you are using a value type because
  210. /// it avoids a copy.
  211. /// </remarks>
  212. /// <param name="obj">the instance to access</param>
  213. /// <param name="name">the name of the property</param>
  214. /// <returns>the value of the property</returns>
  215. /// <exception cref="MissingMemberException">if the property does not exist</exception>
  216. /// <seealso cref="Get(T, string)"/>
  217. /// <seealso cref="GetGetter(string)"/>
  218. public static U Get(ref T obj, string name) => GetGetter(name)(ref obj);
  219. /// <summary>
  220. /// Gets the value of the property identified by <paramref name="name"/> on <paramref name="obj"/>.
  221. /// </summary>
  222. /// <param name="obj">the instance to access</param>
  223. /// <param name="name">the name of the property</param>
  224. /// <returns>the value of the property</returns>
  225. /// <exception cref="MissingMemberException">if the property does not exist</exception>
  226. /// <seealso cref="Get(ref T, string)"/>
  227. /// <seealso cref="GetGetter(string)"/>
  228. public static U Get(T obj, string name) => GetGetter(name)(ref obj);
  229. /// <summary>
  230. /// Sets the value of the property identified by <paramref name="name"/> on <paramref name="obj"/>.
  231. /// </summary>
  232. /// <remarks>
  233. /// This overload must be used for value types.
  234. /// </remarks>
  235. /// <param name="obj">the instance to access</param>
  236. /// <param name="name">the name of the property</param>
  237. /// <param name="val">the new value of the property</param>
  238. /// <exception cref="MissingMemberException">if the property does not exist</exception>
  239. /// <seealso cref="Set(T, string, U)"/>
  240. /// <seealso cref="GetSetter(string)"/>
  241. public static void Set(ref T obj, string name, U val) => GetSetter(name)(ref obj, val);
  242. /// <summary>
  243. /// Sets the value of the property identified by <paramref name="name"/> on <paramref name="obj"/>.
  244. /// </summary>
  245. /// <remarks>
  246. /// This overload cannot be safely used for value types. Use <see cref="Set(ref T, string, U)"/> instead.
  247. /// </remarks>
  248. /// <param name="obj">the instance to access</param>
  249. /// <param name="name">the name of the property</param>
  250. /// <param name="val">the new value of the property</param>
  251. /// <exception cref="MissingMemberException">if the property does not exist</exception>
  252. /// <seealso cref="Set(ref T, string, U)"/>
  253. /// <seealso cref="GetSetter(string)"/>
  254. public static void Set(T obj, string name, U val) => GetSetter(name)(ref obj, val);
  255. }
  256. internal class AccessorDelegateInfo<TDelegate> where TDelegate : Delegate
  257. {
  258. public static readonly Type Type = typeof(TDelegate);
  259. public static readonly MethodInfo Invoke = Type.GetMethod("Invoke");
  260. public static readonly ParameterInfo[] Parameters = Invoke.GetParameters();
  261. }
  262. /// <summary>
  263. /// A type containing utilities for calling non-public methods on an object.
  264. /// </summary>
  265. /// <typeparam name="T">the type to find the methods on</typeparam>
  266. /// <typeparam name="TDelegate">the delegate type to create, and to use as a signature to search for</typeparam>
  267. public static class MethodAccessor<T, TDelegate> where TDelegate : Delegate
  268. {
  269. static MethodAccessor()
  270. {
  271. // ensure that first argument of delegate type is valid
  272. var firstArg = AccessorDelegateInfo<TDelegate>.Parameters.First();
  273. var firstType = firstArg.ParameterType;
  274. if (typeof(T).IsValueType)
  275. {
  276. if (!firstType.IsByRef)
  277. throw new InvalidOperationException("First parameter of a method accessor to a value type is not byref");
  278. else
  279. firstType = firstType.GetElementType(); // get the non-byref type to check compatability
  280. }
  281. if (!typeof(T).IsAssignableFrom(firstType))
  282. throw new InvalidOperationException("First parameter of a method accessor is not assignable to the method owning type");
  283. }
  284. private static TDelegate MakeDelegate(string name)
  285. {
  286. var delParams = AccessorDelegateInfo<TDelegate>.Parameters;
  287. var method = typeof(T).GetMethod(name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
  288. null, delParams.Skip(1).Select(p => p.ParameterType).ToArray(), Array.Empty<ParameterModifier>());
  289. if (method == null)
  290. throw new MissingMethodException(typeof(T).FullName, name);
  291. var retType = AccessorDelegateInfo<TDelegate>.Invoke.ReturnType;
  292. if (!retType.IsAssignableFrom(method.ReturnType))
  293. throw new ArgumentException($"The method found returns a type incompatable with the return type of {typeof(TDelegate)}");
  294. return (TDelegate)Delegate.CreateDelegate(AccessorDelegateInfo<TDelegate>.Type, method, true);
  295. }
  296. private static readonly SingleCreationValueCache<string, TDelegate> methods = new SingleCreationValueCache<string, TDelegate>();
  297. /// <summary>
  298. /// Gets a delegate to the named method with the signature specified by <typeparamref name="TDelegate"/>.
  299. /// </summary>
  300. /// <param name="name">the name of the method to get</param>
  301. /// <returns>a delegate that can call the specified method</returns>
  302. /// <exception cref="MissingMethodException">if <paramref name="name"/> does not represent the name of a method with the given signature</exception>
  303. /// <exception cref="ArgumentException">if the method found returns a type incompatable with the return type of <typeparamref name="TDelegate"/></exception>
  304. public static TDelegate GetDelegate(string name)
  305. => methods.GetOrAdd(name, MakeDelegate);
  306. }
  307. }