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.

260 lines
12 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. #nullable enable
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Reflection;
  6. using IPA.Logging;
  7. using IPA.Utilities;
  8. using IPA.AntiMalware;
  9. #if NET4
  10. using Expression = System.Linq.Expressions.Expression;
  11. using ExpressionEx = System.Linq.Expressions.Expression;
  12. #endif
  13. #if NET3
  14. using Net3_Proxy;
  15. #endif
  16. namespace IPA.Loader
  17. {
  18. /// <summary>
  19. /// The type that handles value injecting into a plugin's initialization methods.
  20. /// </summary>
  21. /// <remarks>
  22. /// The default injectors and what they provide are shown in this table.
  23. /// <list type="table">
  24. /// <listheader>
  25. /// <term>Parameter Type</term>
  26. /// <description>Injected Value</description>
  27. /// </listheader>
  28. /// <item>
  29. /// <term><see cref="Logger"/></term>
  30. /// <description>A <see cref="StandardLogger"/> specialized for the plugin being injected</description>
  31. /// </item>
  32. /// <item>
  33. /// <term><see cref="PluginMetadata"/></term>
  34. /// <description>The <see cref="PluginMetadata"/> of the plugin being injected</description>
  35. /// </item>
  36. /// <item>
  37. /// <term><see cref="Config.Config"/></term>
  38. /// <description>
  39. /// <para>A <see cref="Config.Config"/> object for the plugin being injected.</para>
  40. /// <para>
  41. /// These parameters may have <see cref="Config.Config.NameAttribute"/> and <see cref="Config.Config.PreferAttribute"/> to control
  42. /// how it is constructed.
  43. /// </para>
  44. /// </description>
  45. /// </item>
  46. /// </list>
  47. /// For all of the default injectors, only one of each will be generated, and any later parameters will recieve the same value as the first one.
  48. /// </remarks>
  49. public static class PluginInitInjector
  50. {
  51. /// <summary>
  52. /// A typed injector for a plugin's Init method. When registered, called for all associated types. If it returns null, the default for the type will be used.
  53. /// </summary>
  54. /// <param name="previous">the previous return value of the function, or <see langword="null"/> if never called for plugin.</param>
  55. /// <param name="param">the <see cref="ParameterInfo"/> of the parameter being injected.</param>
  56. /// <param name="meta">the <see cref="PluginMetadata"/> for the plugin being loaded.</param>
  57. /// <returns>the value to inject into that parameter.</returns>
  58. public delegate object? InjectParameter(object? previous, ParameterInfo param, PluginMetadata meta);
  59. /// <summary>
  60. /// A provider for parameter injectors to request injected values themselves.
  61. /// </summary>
  62. /// <remarks>
  63. /// Some injectors may look at attributes on the parameter to gain additional information about what it should provide.
  64. /// If an injector wants to allow end users to affect the things it requests, it may pass the parameter it is currently
  65. /// injecting for to this delegate along with a type override to select some other type.
  66. /// </remarks>
  67. /// <param name="forParam">the parameter that this is providing for.</param>
  68. /// <param name="typeOverride">an optional override for the parameter type.</param>
  69. /// <returns>the value that would otherwise be injected.</returns>
  70. public delegate object? InjectedValueProvider(ParameterInfo forParam, Type? typeOverride = null);
  71. /// <summary>
  72. /// A typed injector for a plugin's Init method. When registered, called for all associated types. If it returns null, the default for the type will be used.
  73. /// </summary>
  74. /// <param name="previous">the previous return value of the function, or <see langword="null"/> if never called for plugin.</param>
  75. /// <param name="param">the <see cref="ParameterInfo"/> of the parameter being injected.</param>
  76. /// <param name="meta">the <see cref="PluginMetadata"/> for the plugin being loaded.</param>
  77. /// <param name="provider">an <see cref="InjectedValueProvider"/> to allow the injector to request injected values.</param>
  78. /// <returns>the value to inject into that parameter.</returns>
  79. public delegate object? InjectParameterNested(object? previous, ParameterInfo param, PluginMetadata meta, InjectedValueProvider provider);
  80. /// <summary>
  81. /// Invokes the provider with <paramref name="param"/> and <typeparamref name="T"/> and casts the result to <typeparamref name="T"/>.
  82. /// </summary>
  83. /// <typeparam name="T">the type of object to be injected</typeparam>
  84. /// <param name="provider">the provider to invoke.</param>
  85. /// <param name="param">the parameter to provide for</param>
  86. /// <returns>the value requested, or <see langword="null"/>.</returns>
  87. public static T? Inject<T>(this InjectedValueProvider provider, ParameterInfo param)
  88. => (T?)provider?.Invoke(param, typeof(T));
  89. /// <summary>
  90. /// Adds an injector to be used when calling future plugins' Init methods.
  91. /// </summary>
  92. /// <param name="type">the type of the parameter.</param>
  93. /// <param name="injector">the function to call for injection.</param>
  94. public static void AddInjector(Type type, InjectParameter injector)
  95. => AddInjector(type, (pre, par, met, pro) => injector(pre, par, met));
  96. /// <summary>
  97. /// Adds an injector to be used when calling future plugins' Init methods.
  98. /// </summary>
  99. /// <param name="type">the type of the parameter.</param>
  100. /// <param name="injector">the function to call for injection.</param>
  101. public static void AddInjector(Type type, InjectParameterNested injector)
  102. {
  103. injectors.Add(new TypedInjector(type, injector));
  104. }
  105. private struct TypedInjector : IEquatable<TypedInjector>
  106. {
  107. public Type Type;
  108. public InjectParameterNested Injector;
  109. public TypedInjector(Type t, InjectParameterNested i)
  110. { Type = t; Injector = i; }
  111. public object? Inject(object? prev, ParameterInfo info, PluginMetadata meta, InjectedValueProvider provider)
  112. => Injector(prev, info, meta, provider);
  113. public bool Equals(TypedInjector other)
  114. => Type == other.Type && Injector == other.Injector;
  115. public override bool Equals(object obj)
  116. => obj is TypedInjector i && Equals(i);
  117. public override int GetHashCode()
  118. => Type.GetHashCode() ^ Injector.GetHashCode();
  119. public static bool operator ==(TypedInjector a, TypedInjector b) => a.Equals(b);
  120. public static bool operator !=(TypedInjector a, TypedInjector b) => !a.Equals(b);
  121. }
  122. private static readonly List<TypedInjector> injectors = new()
  123. {
  124. new TypedInjector(typeof(Logger), (prev, param, meta, _) => prev ?? new StandardLogger(meta.Name)),
  125. new TypedInjector(typeof(PluginMetadata), (prev, param, meta, _) => prev ?? meta),
  126. new TypedInjector(typeof(Config.Config), (prev, param, meta, _) => prev ?? Config.Config.GetConfigFor(meta.Name, param)),
  127. new TypedInjector(typeof(IAntiMalware), (prev, param, meta, _) => prev ?? AntiMalwareEngine.Engine)
  128. };
  129. private static int? MatchPriority(Type target, Type source)
  130. {
  131. if (target == source) return int.MaxValue;
  132. if (!target.IsAssignableFrom(source)) return null;
  133. if (!target.IsInterface && !source.IsSubclassOf(target)) return int.MinValue;
  134. int value = 0;
  135. while (true)
  136. {
  137. if (source == null) return value;
  138. if (target.IsInterface && source.GetInterfaces().Contains(target))
  139. return value;
  140. else if (target == source)
  141. return value;
  142. else
  143. {
  144. value--; // lower priority
  145. source = source.BaseType;
  146. }
  147. }
  148. }
  149. private static readonly MethodInfo InjectMethod = typeof(PluginInitInjector).GetMethod(nameof(Inject), BindingFlags.NonPublic | BindingFlags.Static);
  150. internal static Expression InjectedCallExpr(ParameterInfo[] initParams, Expression meta, Expression persistVar, Func<IEnumerable<Expression>, Expression> exprGen)
  151. {
  152. var arr = ExpressionEx.Variable(typeof(object[]), "initArr");
  153. return ExpressionEx.Block(new[] { arr },
  154. ExpressionEx.Assign(arr, Expression.Call(InjectMethod, Expression.Constant(initParams), meta, persistVar)),
  155. exprGen(initParams
  156. .Select(p => p.ParameterType)
  157. .Select((t, i) => (Expression)Expression.Convert(
  158. Expression.ArrayIndex(arr, Expression.Constant(i)), t))));
  159. }
  160. private static object? InjectForParameter(
  161. Dictionary<TypedInjector, object?> previousValues,
  162. PluginMetadata meta,
  163. ParameterInfo param,
  164. Type paramType,
  165. InjectedValueProvider provider)
  166. {
  167. var value = paramType.GetDefault();
  168. var toUse = injectors
  169. .Select(i => (inject: i, priority: MatchPriority(paramType, i.Type))) // check match priority, combine it
  170. .NonNull(t => t.priority) // filter null priorities
  171. .Select(t => (t.inject, priority: t.priority!.Value)) // remove nullable
  172. .OrderByDescending(t => t.priority) // sort by value
  173. .Select(t => t.inject); // remove priority value
  174. // this tries injectors in order of closest match by type provided
  175. foreach (var pair in toUse)
  176. {
  177. object? prev = null;
  178. if (previousValues.ContainsKey(pair))
  179. prev = previousValues[pair];
  180. var val = pair.Inject(prev, param, meta, provider);
  181. if (previousValues.ContainsKey(pair))
  182. previousValues[pair] = val;
  183. else
  184. previousValues.Add(pair, val);
  185. if (val == null) continue;
  186. value = val;
  187. break;
  188. }
  189. return value;
  190. }
  191. private class InjectedValueProviderWrapperImplementation
  192. {
  193. public Dictionary<TypedInjector, object?> PreviousValues { get; }
  194. public PluginMetadata Meta { get; }
  195. public InjectedValueProvider Provider { get; }
  196. public InjectedValueProviderWrapperImplementation(PluginMetadata meta)
  197. {
  198. Meta = meta;
  199. PreviousValues = new();
  200. Provider = Inject;
  201. }
  202. private object? Inject(ParameterInfo param, Type? typeOverride = null)
  203. => InjectForParameter(PreviousValues, Meta, param, typeOverride ?? param.ParameterType, Provider);
  204. }
  205. internal static object?[] Inject(ParameterInfo[] initParams, PluginMetadata meta, ref object? persist)
  206. {
  207. var initArgs = new List<object?>();
  208. var impl = persist as InjectedValueProviderWrapperImplementation;
  209. if (impl == null || impl.Meta != meta)
  210. {
  211. impl = new(meta);
  212. persist = impl;
  213. }
  214. foreach (var param in initParams)
  215. {
  216. var paramType = param.ParameterType;
  217. var value = InjectForParameter(impl.PreviousValues, meta, param, paramType, impl.Provider);
  218. initArgs.Add(value);
  219. }
  220. return initArgs.ToArray();
  221. }
  222. }
  223. }