Utility.cs 8.0 KB

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