Utility.cs 10 KB

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