Utility.cs 10 KB

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