Utility.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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. public static IEnumerable<TNode> TopologicalSort<TNode>(IEnumerable<TNode> nodes, Func<TNode, IEnumerable<TNode>> dependencySelector)
  110. {
  111. List<TNode> sorted_list = new List<TNode>();
  112. HashSet<TNode> visited = new HashSet<TNode>();
  113. HashSet<TNode> sorted = new HashSet<TNode>();
  114. foreach (TNode input in nodes)
  115. {
  116. Stack<TNode> currentStack = new Stack<TNode>();
  117. if (!Visit(input, currentStack))
  118. {
  119. throw new Exception("Cyclic Dependency:\r\n" + currentStack.Select(x => $" - {x}") //append dashes
  120. .Aggregate((a, b) => $"{a}\r\n{b}")); //add new lines inbetween
  121. }
  122. }
  123. return sorted_list;
  124. bool Visit(TNode node, Stack<TNode> stack)
  125. {
  126. if (visited.Contains(node))
  127. {
  128. if (!sorted.Contains(node))
  129. {
  130. return false;
  131. }
  132. }
  133. else
  134. {
  135. visited.Add(node);
  136. stack.Push(node);
  137. foreach (var dep in dependencySelector(node))
  138. if (!Visit(dep, stack))
  139. return false;
  140. sorted.Add(node);
  141. sorted_list.Add(node);
  142. stack.Pop();
  143. }
  144. return true;
  145. }
  146. }
  147. /// <summary>
  148. /// Try to resolve and load the given assembly DLL.
  149. /// </summary>
  150. /// <param name="assemblyName">Name of the assembly, of the type <see cref="AssemblyName" />.</param>
  151. /// <param name="directory">Directory to search the assembly from.</param>
  152. /// <param name="assembly">The loaded assembly.</param>
  153. /// <returns>True, if the assembly was found and loaded. Otherwise, false.</returns>
  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[] potentialPaths = new[]
  162. {
  163. $"{assemblyName.Name}.dll",
  164. $"{assemblyName.Name}.exe"
  165. };
  166. foreach (var potentialPath in potentialPaths)
  167. {
  168. string path = Path.Combine(subDirectory, potentialPath);
  169. if (!File.Exists(path))
  170. continue;
  171. try
  172. {
  173. assembly = loader(path);
  174. }
  175. catch (Exception)
  176. {
  177. continue;
  178. }
  179. return true;
  180. }
  181. }
  182. return false;
  183. }
  184. public static bool IsSubtypeOf(this TypeDefinition self, Type td)
  185. {
  186. if (self.FullName == td.FullName)
  187. return true;
  188. return self.FullName != "System.Object" && (self.BaseType?.Resolve()?.IsSubtypeOf(td) ?? false);
  189. }
  190. /// <summary>
  191. /// Try to resolve and load the given assembly DLL.
  192. /// </summary>
  193. /// <param name="assemblyName">Name of the assembly, of the type <see cref="AssemblyName" />.</param>
  194. /// <param name="directory">Directory to search the assembly from.</param>
  195. /// <param name="assembly">The loaded assembly.</param>
  196. /// <returns>True, if the assembly was found and loaded. Otherwise, false.</returns>
  197. public static bool TryResolveDllAssembly(AssemblyName assemblyName, string directory, out Assembly assembly)
  198. {
  199. return TryResolveDllAssembly(assemblyName, directory, Assembly.LoadFile, out assembly);
  200. }
  201. /// <summary>
  202. /// Try to resolve and load the given assembly DLL.
  203. /// </summary>
  204. /// <param name="assemblyName">Name of the assembly, of the type <see cref="AssemblyName" />.</param>
  205. /// <param name="directory">Directory to search the assembly from.</param>
  206. /// <param name="assembly">The loaded assembly.</param>
  207. /// <returns>True, if the assembly was found and loaded. Otherwise, false.</returns>
  208. public static bool TryResolveDllAssembly(AssemblyName assemblyName, string directory, ReaderParameters readerParameters, out AssemblyDefinition assembly)
  209. {
  210. return TryResolveDllAssembly(assemblyName, directory, s => AssemblyDefinition.ReadAssembly(s, readerParameters), out assembly);
  211. }
  212. /// <summary>
  213. /// Tries to create a file with the given name
  214. /// </summary>
  215. /// <param name="path">Path of the file to create</param>
  216. /// <param name="mode">File open mode</param>
  217. /// <param name="fileStream">Resulting filestream</param>
  218. /// <param name="access">File access options</param>
  219. /// <param name="share">File share options</param>
  220. /// <returns></returns>
  221. public static bool TryOpenFileStream(string path, FileMode mode, out FileStream fileStream, FileAccess access = FileAccess.ReadWrite, FileShare share = FileShare.Read)
  222. {
  223. try
  224. {
  225. fileStream = new FileStream(path, mode, access, share);
  226. return true;
  227. }
  228. catch (IOException)
  229. {
  230. fileStream = null;
  231. return false;
  232. }
  233. }
  234. public static IEnumerable<MethodDefinition> EnumerateAllMethods(this TypeDefinition type)
  235. {
  236. var currentType = type;
  237. while (currentType != null)
  238. {
  239. foreach (var method in currentType.Methods)
  240. yield return method;
  241. currentType = currentType.BaseType?.Resolve();
  242. }
  243. }
  244. public static string ByteArrayToString(byte[] data)
  245. {
  246. StringBuilder builder = new StringBuilder(data.Length * 2);
  247. foreach (byte b in data)
  248. builder.AppendFormat("{0:x2}", b);
  249. return builder.ToString();
  250. }
  251. public static Platform CurrentPlatform { get; private set; } = CheckPlatform();
  252. // Adapted from https://github.com/MonoMod/MonoMod.Common/blob/master/Utils/PlatformHelper.cs#L13
  253. private static Platform CheckPlatform()
  254. {
  255. var pPlatform = typeof(Environment).GetProperty("Platform", BindingFlags.NonPublic | BindingFlags.Static);
  256. string platId = pPlatform != null ? pPlatform.GetValue(null, new object[0]).ToString() : Environment.OSVersion.Platform.ToString();
  257. platId = platId.ToLowerInvariant();
  258. var cur = Platform.Unknown;
  259. if (platId.Contains("win"))
  260. cur = Platform.Windows;
  261. else if (platId.Contains("mac") || platId.Contains("osx"))
  262. cur = Platform.MacOS;
  263. else if (platId.Contains("lin") || platId.Contains("unix"))
  264. cur = Platform.Linux;
  265. if (IntPtr.Size == 8)
  266. cur |= Platform.Bits64;
  267. return cur;
  268. }
  269. }
  270. }