Utility.cs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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. namespace BepInEx
  9. {
  10. /// <summary>
  11. /// Generic helper properties and methods.
  12. /// </summary>
  13. public static class Utility
  14. {
  15. /// <summary>
  16. /// Whether current Common Language Runtime supports dynamic method generation using <see cref="System.Reflection.Emit"/> namespace.
  17. /// </summary>
  18. public static bool CLRSupportsDynamicAssemblies { get; }
  19. static Utility()
  20. {
  21. try
  22. {
  23. CLRSupportsDynamicAssemblies = true;
  24. // ReSharper disable once AssignNullToNotNullAttribute
  25. var m = new CustomAttributeBuilder(null, new object[0]);
  26. }
  27. catch (PlatformNotSupportedException)
  28. {
  29. CLRSupportsDynamicAssemblies = false;
  30. }
  31. catch (ArgumentNullException)
  32. {
  33. // Suppress ArgumentNullException
  34. }
  35. }
  36. /// <summary>
  37. /// Try to perform an action.
  38. /// </summary>
  39. /// <param name="action">Action to perform.</param>
  40. /// <param name="exception">Possible exception that gets returned.</param>
  41. /// <returns>True, if action succeeded, false if an exception occured.</returns>
  42. public static bool TryDo(Action action, out Exception exception)
  43. {
  44. exception = null;
  45. try
  46. {
  47. action();
  48. return true;
  49. }
  50. catch (Exception e)
  51. {
  52. exception = e;
  53. return false;
  54. }
  55. }
  56. /// <summary>
  57. /// Combines multiple paths together, as the specific method is not available in .NET 3.5.
  58. /// </summary>
  59. /// <param name="parts">The multiple paths to combine together.</param>
  60. /// <returns>A combined path.</returns>
  61. public static string CombinePaths(params string[] parts) => parts.Aggregate(Path.Combine);
  62. /// <summary>
  63. /// Tries to parse a bool, with a default value if unable to parse.
  64. /// </summary>
  65. /// <param name="input">The string to parse</param>
  66. /// <param name="defaultValue">The value to return if parsing is unsuccessful.</param>
  67. /// <returns>Boolean value of input if able to be parsed, otherwise default value.</returns>
  68. public static bool SafeParseBool(string input, bool defaultValue = false)
  69. {
  70. return Boolean.TryParse(input, out bool result) ? result : defaultValue;
  71. }
  72. /// <summary>
  73. /// Converts a file path into a UnityEngine.WWW format.
  74. /// </summary>
  75. /// <param name="path">The file path to convert.</param>
  76. /// <returns>A converted file path.</returns>
  77. public static string ConvertToWWWFormat(string path)
  78. {
  79. return $"file://{path.Replace('\\', '/')}";
  80. }
  81. /// <summary>
  82. /// Indicates whether a specified string is null, empty, or consists only of white-space characters.
  83. /// </summary>
  84. /// <param name="self">The string to test.</param>
  85. /// <returns>True if the value parameter is null or empty, or if value consists exclusively of white-space characters.</returns>
  86. public static bool IsNullOrWhiteSpace(this string self)
  87. {
  88. return self == null || self.All(Char.IsWhiteSpace);
  89. }
  90. public static IEnumerable<TNode> TopologicalSort<TNode>(IEnumerable<TNode> nodes, Func<TNode, IEnumerable<TNode>> dependencySelector)
  91. {
  92. List<TNode> sorted_list = new List<TNode>();
  93. HashSet<TNode> visited = new HashSet<TNode>();
  94. HashSet<TNode> sorted = new HashSet<TNode>();
  95. foreach (TNode input in nodes)
  96. {
  97. Stack<TNode> currentStack = new Stack<TNode>();
  98. if (!Visit(input, currentStack))
  99. {
  100. throw new Exception("Cyclic Dependency:\r\n" + currentStack.Select(x => $" - {x}") //append dashes
  101. .Aggregate((a, b) => $"{a}\r\n{b}")); //add new lines inbetween
  102. }
  103. }
  104. return sorted_list;
  105. bool Visit(TNode node, Stack<TNode> stack)
  106. {
  107. if (visited.Contains(node))
  108. {
  109. if (!sorted.Contains(node))
  110. {
  111. return false;
  112. }
  113. }
  114. else
  115. {
  116. visited.Add(node);
  117. stack.Push(node);
  118. foreach (var dep in dependencySelector(node))
  119. if (!Visit(dep, stack))
  120. return false;
  121. sorted.Add(node);
  122. sorted_list.Add(node);
  123. stack.Pop();
  124. }
  125. return true;
  126. }
  127. }
  128. /// <summary>
  129. /// Try to resolve and load the given assembly DLL.
  130. /// </summary>
  131. /// <param name="assemblyName">Name of the assembly, of the type <see cref="AssemblyName" />.</param>
  132. /// <param name="directory">Directory to search the assembly from.</param>
  133. /// <param name="assembly">The loaded assembly.</param>
  134. /// <returns>True, if the assembly was found and loaded. Otherwise, false.</returns>
  135. private static bool TryResolveDllAssembly<T>(AssemblyName assemblyName, string directory, Func<string, T> loader, out T assembly) where T : class
  136. {
  137. assembly = null;
  138. var potentialDirectories = new List<string> { directory };
  139. potentialDirectories.AddRange(Directory.GetDirectories(directory, "*", SearchOption.AllDirectories));
  140. foreach (string subDirectory in potentialDirectories)
  141. {
  142. string path = Path.Combine(subDirectory, $"{assemblyName.Name}.dll");
  143. if (!File.Exists(path))
  144. continue;
  145. try
  146. {
  147. assembly = loader(path);
  148. }
  149. catch (Exception)
  150. {
  151. continue;
  152. }
  153. return true;
  154. }
  155. return false;
  156. }
  157. public static bool IsSubtypeOf(this TypeDefinition self, Type td)
  158. {
  159. if (self.FullName == td.FullName)
  160. return true;
  161. return self.FullName != "System.Object" && (self.BaseType?.Resolve()?.IsSubtypeOf(td) ?? false);
  162. }
  163. /// <summary>
  164. /// Try to resolve and load the given assembly DLL.
  165. /// </summary>
  166. /// <param name="assemblyName">Name of the assembly, of the type <see cref="AssemblyName" />.</param>
  167. /// <param name="directory">Directory to search the assembly from.</param>
  168. /// <param name="assembly">The loaded assembly.</param>
  169. /// <returns>True, if the assembly was found and loaded. Otherwise, false.</returns>
  170. public static bool TryResolveDllAssembly(AssemblyName assemblyName, string directory, out Assembly assembly)
  171. {
  172. return TryResolveDllAssembly(assemblyName, directory, Assembly.LoadFile, out assembly);
  173. }
  174. /// <summary>
  175. /// Try to resolve and load the given assembly DLL.
  176. /// </summary>
  177. /// <param name="assemblyName">Name of the assembly, of the type <see cref="AssemblyName" />.</param>
  178. /// <param name="directory">Directory to search the assembly from.</param>
  179. /// <param name="assembly">The loaded assembly.</param>
  180. /// <returns>True, if the assembly was found and loaded. Otherwise, false.</returns>
  181. public static bool TryResolveDllAssembly(AssemblyName assemblyName, string directory, ReaderParameters readerParameters, out AssemblyDefinition assembly)
  182. {
  183. return TryResolveDllAssembly(assemblyName, directory, s => AssemblyDefinition.ReadAssembly(s, readerParameters), out assembly);
  184. }
  185. /// <summary>
  186. /// Tries to create a file with the given name
  187. /// </summary>
  188. /// <param name="path">Path of the file to create</param>
  189. /// <param name="mode">File open mode</param>
  190. /// <param name="fileStream">Resulting filestream</param>
  191. /// <param name="access">File access options</param>
  192. /// <param name="share">File share options</param>
  193. /// <returns></returns>
  194. public static bool TryOpenFileStream(string path, FileMode mode, out FileStream fileStream, FileAccess access = FileAccess.ReadWrite, FileShare share = FileShare.Read)
  195. {
  196. try
  197. {
  198. fileStream = new FileStream(path, mode, access, share);
  199. return true;
  200. }
  201. catch (IOException)
  202. {
  203. fileStream = null;
  204. return false;
  205. }
  206. }
  207. public static IEnumerable<MethodDefinition> EnumerateAllMethods(this TypeDefinition type)
  208. {
  209. var currentType = type;
  210. while (currentType != null)
  211. {
  212. foreach (var method in currentType.Methods)
  213. yield return method;
  214. currentType = currentType.BaseType?.Resolve();
  215. }
  216. }
  217. }
  218. }