PtcProfiler.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. using ARMeilleure.State;
  2. using Ryujinx.Common.Logging;
  3. using System;
  4. using System.Collections.Concurrent;
  5. using System.Collections.Generic;
  6. using System.Diagnostics;
  7. using System.IO;
  8. using System.IO.Compression;
  9. using System.Security.Cryptography;
  10. using System.Threading;
  11. namespace ARMeilleure.Translation.PTC
  12. {
  13. public static class PtcProfiler
  14. {
  15. private const string HeaderMagic = "Phd";
  16. private const uint InternalVersion = 1713; //! Not to be incremented manually for each change to the ARMeilleure project.
  17. private const int SaveInterval = 30; // Seconds.
  18. private const CompressionLevel SaveCompressionLevel = CompressionLevel.Fastest;
  19. private static readonly System.Timers.Timer _timer;
  20. private static readonly ManualResetEvent _waitEvent;
  21. private static readonly object _lock;
  22. private static bool _disposed;
  23. internal static Dictionary<ulong, (ExecutionMode mode, bool highCq)> ProfiledFuncs { get; private set; }
  24. internal static bool Enabled { get; private set; }
  25. public static ulong StaticCodeStart { internal get; set; }
  26. public static ulong StaticCodeSize { internal get; set; }
  27. static PtcProfiler()
  28. {
  29. _timer = new System.Timers.Timer((double)SaveInterval * 1000d);
  30. _timer.Elapsed += PreSave;
  31. _waitEvent = new ManualResetEvent(true);
  32. _lock = new object();
  33. _disposed = false;
  34. ProfiledFuncs = new Dictionary<ulong, (ExecutionMode, bool)>();
  35. Enabled = false;
  36. }
  37. internal static void AddEntry(ulong address, ExecutionMode mode, bool highCq)
  38. {
  39. if (IsAddressInStaticCodeRange(address))
  40. {
  41. Debug.Assert(!highCq);
  42. lock (_lock)
  43. {
  44. ProfiledFuncs.TryAdd(address, (mode, highCq: false));
  45. }
  46. }
  47. }
  48. internal static void UpdateEntry(ulong address, ExecutionMode mode, bool highCq)
  49. {
  50. if (IsAddressInStaticCodeRange(address))
  51. {
  52. Debug.Assert(highCq);
  53. lock (_lock)
  54. {
  55. Debug.Assert(ProfiledFuncs.ContainsKey(address));
  56. ProfiledFuncs[address] = (mode, highCq: true);
  57. }
  58. }
  59. }
  60. internal static bool IsAddressInStaticCodeRange(ulong address)
  61. {
  62. return address >= StaticCodeStart && address < StaticCodeStart + StaticCodeSize;
  63. }
  64. internal static Dictionary<ulong, (ExecutionMode mode, bool highCq)> GetProfiledFuncsToTranslate(ConcurrentDictionary<ulong, TranslatedFunction> funcs)
  65. {
  66. var profiledFuncsToTranslate = new Dictionary<ulong, (ExecutionMode mode, bool highCq)>(ProfiledFuncs);
  67. foreach (ulong address in profiledFuncsToTranslate.Keys)
  68. {
  69. if (funcs.ContainsKey(address))
  70. {
  71. profiledFuncsToTranslate.Remove(address);
  72. }
  73. }
  74. return profiledFuncsToTranslate;
  75. }
  76. internal static void ClearEntries()
  77. {
  78. ProfiledFuncs.Clear();
  79. }
  80. internal static void PreLoad()
  81. {
  82. string fileNameActual = String.Concat(Ptc.CachePathActual, ".info");
  83. string fileNameBackup = String.Concat(Ptc.CachePathBackup, ".info");
  84. FileInfo fileInfoActual = new FileInfo(fileNameActual);
  85. FileInfo fileInfoBackup = new FileInfo(fileNameBackup);
  86. if (fileInfoActual.Exists && fileInfoActual.Length != 0L)
  87. {
  88. if (!Load(fileNameActual, false))
  89. {
  90. if (fileInfoBackup.Exists && fileInfoBackup.Length != 0L)
  91. {
  92. Load(fileNameBackup, true);
  93. }
  94. }
  95. }
  96. else if (fileInfoBackup.Exists && fileInfoBackup.Length != 0L)
  97. {
  98. Load(fileNameBackup, true);
  99. }
  100. }
  101. private static bool Load(string fileName, bool isBackup)
  102. {
  103. using (FileStream compressedStream = new FileStream(fileName, FileMode.Open))
  104. using (DeflateStream deflateStream = new DeflateStream(compressedStream, CompressionMode.Decompress, true))
  105. using (MemoryStream stream = new MemoryStream())
  106. using (MD5 md5 = MD5.Create())
  107. {
  108. int hashSize = md5.HashSize / 8;
  109. try
  110. {
  111. deflateStream.CopyTo(stream);
  112. }
  113. catch
  114. {
  115. InvalidateCompressedStream(compressedStream);
  116. return false;
  117. }
  118. stream.Seek(0L, SeekOrigin.Begin);
  119. byte[] currentHash = new byte[hashSize];
  120. stream.Read(currentHash, 0, hashSize);
  121. byte[] expectedHash = md5.ComputeHash(stream);
  122. if (!CompareHash(currentHash, expectedHash))
  123. {
  124. InvalidateCompressedStream(compressedStream);
  125. return false;
  126. }
  127. stream.Seek((long)hashSize, SeekOrigin.Begin);
  128. Header header = ReadHeader(stream);
  129. if (header.Magic != HeaderMagic)
  130. {
  131. InvalidateCompressedStream(compressedStream);
  132. return false;
  133. }
  134. if (header.InfoFileVersion != InternalVersion)
  135. {
  136. InvalidateCompressedStream(compressedStream);
  137. return false;
  138. }
  139. try
  140. {
  141. ProfiledFuncs = Deserialize(stream);
  142. }
  143. catch
  144. {
  145. ProfiledFuncs = new Dictionary<ulong, (ExecutionMode, bool)>();
  146. InvalidateCompressedStream(compressedStream);
  147. return false;
  148. }
  149. }
  150. long fileSize = new FileInfo(fileName).Length;
  151. Logger.Info?.Print(LogClass.Ptc, $"{(isBackup ? "Loaded Backup Profiling Info" : "Loaded Profiling Info")} (size: {fileSize} bytes, profiled functions: {ProfiledFuncs.Count}).");
  152. return true;
  153. }
  154. private static bool CompareHash(ReadOnlySpan<byte> currentHash, ReadOnlySpan<byte> expectedHash)
  155. {
  156. return currentHash.SequenceEqual(expectedHash);
  157. }
  158. private static Header ReadHeader(MemoryStream stream)
  159. {
  160. using (BinaryReader headerReader = new BinaryReader(stream, EncodingCache.UTF8NoBOM, true))
  161. {
  162. Header header = new Header();
  163. header.Magic = headerReader.ReadString();
  164. header.InfoFileVersion = headerReader.ReadUInt32();
  165. return header;
  166. }
  167. }
  168. private static Dictionary<ulong, (ExecutionMode, bool)> Deserialize(MemoryStream stream)
  169. {
  170. using (BinaryReader reader = new BinaryReader(stream, EncodingCache.UTF8NoBOM, true))
  171. {
  172. var profiledFuncs = new Dictionary<ulong, (ExecutionMode, bool)>();
  173. int profiledFuncsCount = reader.ReadInt32();
  174. for (int i = 0; i < profiledFuncsCount; i++)
  175. {
  176. ulong address = reader.ReadUInt64();
  177. ExecutionMode mode = (ExecutionMode)reader.ReadInt32();
  178. bool highCq = reader.ReadBoolean();
  179. profiledFuncs.Add(address, (mode, highCq));
  180. }
  181. return profiledFuncs;
  182. }
  183. }
  184. private static void InvalidateCompressedStream(FileStream compressedStream)
  185. {
  186. compressedStream.SetLength(0L);
  187. }
  188. private static void PreSave(object source, System.Timers.ElapsedEventArgs e)
  189. {
  190. _waitEvent.Reset();
  191. string fileNameActual = String.Concat(Ptc.CachePathActual, ".info");
  192. string fileNameBackup = String.Concat(Ptc.CachePathBackup, ".info");
  193. FileInfo fileInfoActual = new FileInfo(fileNameActual);
  194. if (fileInfoActual.Exists && fileInfoActual.Length != 0L)
  195. {
  196. File.Copy(fileNameActual, fileNameBackup, true);
  197. }
  198. Save(fileNameActual);
  199. _waitEvent.Set();
  200. }
  201. private static void Save(string fileName)
  202. {
  203. int profiledFuncsCount;
  204. using (MemoryStream stream = new MemoryStream())
  205. using (MD5 md5 = MD5.Create())
  206. {
  207. int hashSize = md5.HashSize / 8;
  208. stream.Seek((long)hashSize, SeekOrigin.Begin);
  209. WriteHeader(stream);
  210. lock (_lock)
  211. {
  212. Serialize(stream, ProfiledFuncs);
  213. profiledFuncsCount = ProfiledFuncs.Count;
  214. }
  215. stream.Seek((long)hashSize, SeekOrigin.Begin);
  216. byte[] hash = md5.ComputeHash(stream);
  217. stream.Seek(0L, SeekOrigin.Begin);
  218. stream.Write(hash, 0, hashSize);
  219. using (FileStream compressedStream = new FileStream(fileName, FileMode.OpenOrCreate))
  220. using (DeflateStream deflateStream = new DeflateStream(compressedStream, SaveCompressionLevel, true))
  221. {
  222. try
  223. {
  224. stream.WriteTo(deflateStream);
  225. }
  226. catch
  227. {
  228. compressedStream.Position = 0L;
  229. }
  230. if (compressedStream.Position < compressedStream.Length)
  231. {
  232. compressedStream.SetLength(compressedStream.Position);
  233. }
  234. }
  235. }
  236. long fileSize = new FileInfo(fileName).Length;
  237. Logger.Info?.Print(LogClass.Ptc, $"Saved Profiling Info (size: {fileSize} bytes, profiled functions: {profiledFuncsCount}).");
  238. }
  239. private static void WriteHeader(MemoryStream stream)
  240. {
  241. using (BinaryWriter headerWriter = new BinaryWriter(stream, EncodingCache.UTF8NoBOM, true))
  242. {
  243. headerWriter.Write((string)HeaderMagic); // Header.Magic
  244. headerWriter.Write((uint)InternalVersion); // Header.InfoFileVersion
  245. }
  246. }
  247. private static void Serialize(MemoryStream stream, Dictionary<ulong, (ExecutionMode mode, bool highCq)> profiledFuncs)
  248. {
  249. using (BinaryWriter writer = new BinaryWriter(stream, EncodingCache.UTF8NoBOM, true))
  250. {
  251. writer.Write((int)profiledFuncs.Count);
  252. foreach (var kv in profiledFuncs)
  253. {
  254. writer.Write((ulong)kv.Key); // address
  255. writer.Write((int)kv.Value.mode);
  256. writer.Write((bool)kv.Value.highCq);
  257. }
  258. }
  259. }
  260. private struct Header
  261. {
  262. public string Magic;
  263. public uint InfoFileVersion;
  264. }
  265. internal static void Start()
  266. {
  267. if (Ptc.State == PtcState.Enabled ||
  268. Ptc.State == PtcState.Continuing)
  269. {
  270. Enabled = true;
  271. _timer.Enabled = true;
  272. }
  273. }
  274. public static void Stop()
  275. {
  276. Enabled = false;
  277. if (!_disposed)
  278. {
  279. _timer.Enabled = false;
  280. }
  281. }
  282. internal static void Wait()
  283. {
  284. _waitEvent.WaitOne();
  285. }
  286. public static void Dispose()
  287. {
  288. if (!_disposed)
  289. {
  290. _disposed = true;
  291. _timer.Elapsed -= PreSave;
  292. _timer.Dispose();
  293. Wait();
  294. _waitEvent.Dispose();
  295. }
  296. }
  297. }
  298. }