Utility.cs 9.3 KB

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