Utility.cs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Reflection.Emit;
  7. using Mono.Cecil;
  8. using MonoMod.Utils;
  9. namespace BepInEx
  10. {
  11. /// <summary>
  12. /// Generic helper properties and methods.
  13. /// </summary>
  14. public static class Utility
  15. {
  16. private static bool? sreEnabled;
  17. /// <summary>
  18. /// Whether current Common Language Runtime supports dynamic method generation using <see cref="System.Reflection.Emit"/> namespace.
  19. /// </summary>
  20. public static bool CLRSupportsDynamicAssemblies => CheckSRE();
  21. private static bool CheckSRE()
  22. {
  23. if (sreEnabled.HasValue)
  24. return sreEnabled.Value;
  25. try
  26. {
  27. // ReSharper disable once AssignNullToNotNullAttribute
  28. _ = new CustomAttributeBuilder(null, new object[0]);
  29. }
  30. catch (PlatformNotSupportedException)
  31. {
  32. sreEnabled = false;
  33. return sreEnabled.Value;
  34. }
  35. catch (ArgumentNullException)
  36. {
  37. // Suppress ArgumentNullException
  38. }
  39. sreEnabled = true;
  40. return sreEnabled.Value;
  41. }
  42. /// <summary>
  43. /// Try to perform an action.
  44. /// </summary>
  45. /// <param name="action">Action to perform.</param>
  46. /// <param name="exception">Possible exception that gets returned.</param>
  47. /// <returns>True, if action succeeded, false if an exception occured.</returns>
  48. public static bool TryDo(Action action, out Exception exception)
  49. {
  50. exception = null;
  51. try
  52. {
  53. action();
  54. return true;
  55. }
  56. catch (Exception e)
  57. {
  58. exception = e;
  59. return false;
  60. }
  61. }
  62. /// <summary>
  63. /// Combines multiple paths together, as the specific method is not available in .NET 3.5.
  64. /// </summary>
  65. /// <param name="parts">The multiple paths to combine together.</param>
  66. /// <returns>A combined path.</returns>
  67. public static string CombinePaths(params string[] parts) => parts.Aggregate(Path.Combine);
  68. /// <summary>
  69. /// Returns the parent directory of a path, optionally specifying the amount of levels.
  70. /// </summary>
  71. /// <param name="path">The path to get the parent directory of.</param>
  72. /// <param name="levels">The amount of levels to traverse. Defaults to 1</param>
  73. /// <returns>The parent directory.</returns>
  74. public static string ParentDirectory(string path, int levels = 1)
  75. {
  76. for (int i = 0; i < levels; i++)
  77. path = Path.GetDirectoryName(path);
  78. return path;
  79. }
  80. /// <summary>
  81. /// Tries to parse a bool, with a default value if unable to parse.
  82. /// </summary>
  83. /// <param name="input">The string to parse</param>
  84. /// <param name="defaultValue">The value to return if parsing is unsuccessful.</param>
  85. /// <returns>Boolean value of input if able to be parsed, otherwise default value.</returns>
  86. public static bool SafeParseBool(string input, bool defaultValue = false)
  87. {
  88. return Boolean.TryParse(input, out bool result) ? result : defaultValue;
  89. }
  90. /// <summary>
  91. /// Converts a file path into a UnityEngine.WWW format.
  92. /// </summary>
  93. /// <param name="path">The file path to convert.</param>
  94. /// <returns>A converted file path.</returns>
  95. public static string ConvertToWWWFormat(string path)
  96. {
  97. return $"file://{path.Replace('\\', '/')}";
  98. }
  99. /// <summary>
  100. /// Indicates whether a specified string is null, empty, or consists only of white-space characters.
  101. /// </summary>
  102. /// <param name="self">The string to test.</param>
  103. /// <returns>True if the value parameter is null or empty, or if value consists exclusively of white-space characters.</returns>
  104. public static bool IsNullOrWhiteSpace(this string self)
  105. {
  106. return self == null || self.All(Char.IsWhiteSpace);
  107. }
  108. /// <summary>
  109. /// Sorts a given dependency graph using a direct toposort, reporting possible cyclic dependencies.
  110. /// </summary>
  111. /// <param name="nodes">Nodes to sort</param>
  112. /// <param name="dependencySelector">Function that maps a node to a collection of its dependencies.</param>
  113. /// <typeparam name="TNode">Type of the node in a dependency graph.</typeparam>
  114. /// <returns>Collection of nodes sorted in the order of least dependencies to the most.</returns>
  115. /// <exception cref="Exception">Thrown when a cyclic dependency occurs.</exception>
  116. public static IEnumerable<TNode> TopologicalSort<TNode>(IEnumerable<TNode> nodes, Func<TNode, IEnumerable<TNode>> dependencySelector)
  117. {
  118. List<TNode> sorted_list = new List<TNode>();
  119. HashSet<TNode> visited = new HashSet<TNode>();
  120. HashSet<TNode> sorted = new HashSet<TNode>();
  121. foreach (TNode input in nodes)
  122. {
  123. Stack<TNode> currentStack = new Stack<TNode>();
  124. if (!Visit(input, currentStack))
  125. {
  126. throw new Exception("Cyclic Dependency:\r\n" + currentStack.Select(x => $" - {x}") //append dashes
  127. .Aggregate((a, b) => $"{a}\r\n{b}")); //add new lines inbetween
  128. }
  129. }
  130. return sorted_list;
  131. bool Visit(TNode node, Stack<TNode> stack)
  132. {
  133. if (visited.Contains(node))
  134. {
  135. if (!sorted.Contains(node))
  136. {
  137. return false;
  138. }
  139. }
  140. else
  141. {
  142. visited.Add(node);
  143. stack.Push(node);
  144. foreach (var dep in dependencySelector(node))
  145. if (!Visit(dep, stack))
  146. return false;
  147. sorted.Add(node);
  148. sorted_list.Add(node);
  149. stack.Pop();
  150. }
  151. return true;
  152. }
  153. }
  154. private static bool TryResolveDllAssembly<T>(AssemblyName assemblyName, string directory, Func<string, T> loader, out T assembly) where T : class
  155. {
  156. assembly = null;
  157. var potentialDirectories = new List<string> { directory };
  158. potentialDirectories.AddRange(Directory.GetDirectories(directory, "*", SearchOption.AllDirectories));
  159. foreach (string subDirectory in potentialDirectories)
  160. {
  161. string path = Path.Combine(subDirectory, $"{assemblyName.Name}.dll");
  162. if (!File.Exists(path))
  163. continue;
  164. try
  165. {
  166. assembly = loader(path);
  167. }
  168. catch (Exception)
  169. {
  170. continue;
  171. }
  172. return true;
  173. }
  174. return false;
  175. }
  176. /// <summary>
  177. /// Checks whether a given cecil type definition is a subtype of a provided type.
  178. /// </summary>
  179. /// <param name="self">Cecil type definition</param>
  180. /// <param name="td">Type to check against</param>
  181. /// <returns>Whether the given cecil type is a subtype of the type.</returns>
  182. public static bool IsSubtypeOf(this TypeDefinition self, Type td)
  183. {
  184. if (self.FullName == td.FullName)
  185. return true;
  186. return self.FullName != "System.Object" && (self.BaseType?.Resolve()?.IsSubtypeOf(td) ?? false);
  187. }
  188. /// <summary>
  189. /// Try to resolve and load the given assembly DLL.
  190. /// </summary>
  191. /// <param name="assemblyName">Name of the assembly, of the type <see cref="AssemblyName" />.</param>
  192. /// <param name="directory">Directory to search the assembly from.</param>
  193. /// <param name="assembly">The loaded assembly.</param>
  194. /// <returns>True, if the assembly was found and loaded. Otherwise, false.</returns>
  195. public static bool TryResolveDllAssembly(AssemblyName assemblyName, string directory, out Assembly assembly)
  196. {
  197. return TryResolveDllAssembly(assemblyName, directory, Assembly.LoadFile, out assembly);
  198. }
  199. /// <summary>
  200. /// Try to resolve and load the given assembly DLL.
  201. /// </summary>
  202. /// <param name="assemblyName">Name of the assembly, of the type <see cref="AssemblyName" />.</param>
  203. /// <param name="directory">Directory to search the assembly from.</param>
  204. /// <param name="readerParameters">Reader parameters that contain possible custom assembly resolver.</param>
  205. /// <param name="assembly">The loaded assembly.</param>
  206. /// <returns>True, if the assembly was found and loaded. Otherwise, false.</returns>
  207. public static bool TryResolveDllAssembly(AssemblyName assemblyName, string directory, ReaderParameters readerParameters, out AssemblyDefinition assembly)
  208. {
  209. return TryResolveDllAssembly(assemblyName, directory, s => AssemblyDefinition.ReadAssembly(s, readerParameters), out assembly);
  210. }
  211. /// <summary>
  212. /// Tries to create a file with the given name
  213. /// </summary>
  214. /// <param name="path">Path of the file to create</param>
  215. /// <param name="mode">File open mode</param>
  216. /// <param name="fileStream">Resulting filestream</param>
  217. /// <param name="access">File access options</param>
  218. /// <param name="share">File share options</param>
  219. /// <returns></returns>
  220. public static bool TryOpenFileStream(string path, FileMode mode, out FileStream fileStream, FileAccess access = FileAccess.ReadWrite, FileShare share = FileShare.Read)
  221. {
  222. try
  223. {
  224. fileStream = new FileStream(path, mode, access, share);
  225. return true;
  226. }
  227. catch (IOException)
  228. {
  229. fileStream = null;
  230. return false;
  231. }
  232. }
  233. /// <summary>
  234. /// Try to parse given string as an assembly name
  235. /// </summary>
  236. /// <param name="fullName">Fully qualified assembly name</param>
  237. /// <param name="assemblyName">Resulting <see cref="AssemblyName"/> instance</param>
  238. /// <returns><c>true</c>, if parsing was successful, otherwise <c>false</c></returns>
  239. /// <remarks>
  240. /// On some versions of mono, using <see cref="Assembly.GetName()"/> fails because it runs on unmanaged side
  241. /// which has problems with encoding.
  242. /// Using <see cref="AssemblyName"/> solves this by doing parsing on managed side instead.
  243. /// </remarks>
  244. public static bool TryParseAssemblyName(string fullName, out AssemblyName assemblyName)
  245. {
  246. try
  247. {
  248. assemblyName = new AssemblyName(fullName);
  249. return true;
  250. }
  251. catch (Exception e)
  252. {
  253. File.AppendAllText("tryparseerr.log", $"Failed to parse {fullName}: {e}");
  254. assemblyName = null;
  255. return false;
  256. }
  257. }
  258. }
  259. }