PtcProfiler.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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 ConcurrentQueue<(ulong address, ExecutionMode mode, bool highCq)> GetProfiledFuncsToTranslate(ConcurrentDictionary<ulong, TranslatedFunction> funcs)
  65. {
  66. var profiledFuncsToTranslate = new ConcurrentQueue<(ulong address, ExecutionMode mode, bool highCq)>();
  67. foreach (var profiledFunc in ProfiledFuncs)
  68. {
  69. ulong address = profiledFunc.Key;
  70. if (!funcs.ContainsKey(address))
  71. {
  72. profiledFuncsToTranslate.Enqueue((address, profiledFunc.Value.mode, profiledFunc.Value.highCq));
  73. }
  74. }
  75. return profiledFuncsToTranslate;
  76. }
  77. internal static void ClearEntries()
  78. {
  79. ProfiledFuncs.Clear();
  80. }
  81. internal static void PreLoad()
  82. {
  83. string fileNameActual = String.Concat(Ptc.CachePathActual, ".info");
  84. string fileNameBackup = String.Concat(Ptc.CachePathBackup, ".info");
  85. FileInfo fileInfoActual = new FileInfo(fileNameActual);
  86. FileInfo fileInfoBackup = new FileInfo(fileNameBackup);
  87. if (fileInfoActual.Exists && fileInfoActual.Length != 0L)
  88. {
  89. if (!Load(fileNameActual, false))
  90. {
  91. if (fileInfoBackup.Exists && fileInfoBackup.Length != 0L)
  92. {
  93. Load(fileNameBackup, true);
  94. }
  95. }
  96. }
  97. else if (fileInfoBackup.Exists && fileInfoBackup.Length != 0L)
  98. {
  99. Load(fileNameBackup, true);
  100. }
  101. }
  102. private static bool Load(string fileName, bool isBackup)
  103. {
  104. using (FileStream compressedStream = new FileStream(fileName, FileMode.Open))
  105. using (DeflateStream deflateStream = new DeflateStream(compressedStream, CompressionMode.Decompress, true))
  106. using (MemoryStream stream = new MemoryStream())
  107. using (MD5 md5 = MD5.Create())
  108. {
  109. int hashSize = md5.HashSize / 8;
  110. try
  111. {
  112. deflateStream.CopyTo(stream);
  113. }
  114. catch
  115. {
  116. InvalidateCompressedStream(compressedStream);
  117. return false;
  118. }
  119. stream.Seek(0L, SeekOrigin.Begin);
  120. byte[] currentHash = new byte[hashSize];
  121. stream.Read(currentHash, 0, hashSize);
  122. byte[] expectedHash = md5.ComputeHash(stream);
  123. if (!CompareHash(currentHash, expectedHash))
  124. {
  125. InvalidateCompressedStream(compressedStream);
  126. return false;
  127. }
  128. stream.Seek((long)hashSize, SeekOrigin.Begin);
  129. Header header = ReadHeader(stream);
  130. if (header.Magic != HeaderMagic)
  131. {
  132. InvalidateCompressedStream(compressedStream);
  133. return false;
  134. }
  135. if (header.InfoFileVersion != InternalVersion)
  136. {
  137. InvalidateCompressedStream(compressedStream);
  138. return false;
  139. }
  140. try
  141. {
  142. ProfiledFuncs = Deserialize(stream);
  143. }
  144. catch
  145. {
  146. ProfiledFuncs = new Dictionary<ulong, (ExecutionMode, bool)>();
  147. InvalidateCompressedStream(compressedStream);
  148. return false;
  149. }
  150. }
  151. long fileSize = new FileInfo(fileName).Length;
  152. Logger.Info?.Print(LogClass.Ptc, $"{(isBackup ? "Loaded Backup Profiling Info" : "Loaded Profiling Info")} (size: {fileSize} bytes, profiled functions: {ProfiledFuncs.Count}).");
  153. return true;
  154. }
  155. private static bool CompareHash(ReadOnlySpan<byte> currentHash, ReadOnlySpan<byte> expectedHash)
  156. {
  157. return currentHash.SequenceEqual(expectedHash);
  158. }
  159. private static Header ReadHeader(MemoryStream stream)
  160. {
  161. using (BinaryReader headerReader = new BinaryReader(stream, EncodingCache.UTF8NoBOM, true))
  162. {
  163. Header header = new Header();
  164. header.Magic = headerReader.ReadString();
  165. header.InfoFileVersion = headerReader.ReadUInt32();
  166. return header;
  167. }
  168. }
  169. private static Dictionary<ulong, (ExecutionMode, bool)> Deserialize(MemoryStream stream)
  170. {
  171. using (BinaryReader reader = new BinaryReader(stream, EncodingCache.UTF8NoBOM, true))
  172. {
  173. var profiledFuncs = new Dictionary<ulong, (ExecutionMode, bool)>();
  174. int profiledFuncsCount = reader.ReadInt32();
  175. for (int i = 0; i < profiledFuncsCount; i++)
  176. {
  177. ulong address = reader.ReadUInt64();
  178. ExecutionMode mode = (ExecutionMode)reader.ReadInt32();
  179. bool highCq = reader.ReadBoolean();
  180. profiledFuncs.Add(address, (mode, highCq));
  181. }
  182. return profiledFuncs;
  183. }
  184. }
  185. private static void InvalidateCompressedStream(FileStream compressedStream)
  186. {
  187. compressedStream.SetLength(0L);
  188. }
  189. private static void PreSave(object source, System.Timers.ElapsedEventArgs e)
  190. {
  191. _waitEvent.Reset();
  192. string fileNameActual = String.Concat(Ptc.CachePathActual, ".info");
  193. string fileNameBackup = String.Concat(Ptc.CachePathBackup, ".info");
  194. FileInfo fileInfoActual = new FileInfo(fileNameActual);
  195. if (fileInfoActual.Exists && fileInfoActual.Length != 0L)
  196. {
  197. File.Copy(fileNameActual, fileNameBackup, true);
  198. }
  199. Save(fileNameActual);
  200. _waitEvent.Set();
  201. }
  202. private static void Save(string fileName)
  203. {
  204. int profiledFuncsCount;
  205. using (MemoryStream stream = new MemoryStream())
  206. using (MD5 md5 = MD5.Create())
  207. {
  208. int hashSize = md5.HashSize / 8;
  209. stream.Seek((long)hashSize, SeekOrigin.Begin);
  210. WriteHeader(stream);
  211. lock (_lock)
  212. {
  213. Serialize(stream, ProfiledFuncs);
  214. profiledFuncsCount = ProfiledFuncs.Count;
  215. }
  216. stream.Seek((long)hashSize, SeekOrigin.Begin);
  217. byte[] hash = md5.ComputeHash(stream);
  218. stream.Seek(0L, SeekOrigin.Begin);
  219. stream.Write(hash, 0, hashSize);
  220. using (FileStream compressedStream = new FileStream(fileName, FileMode.OpenOrCreate))
  221. using (DeflateStream deflateStream = new DeflateStream(compressedStream, SaveCompressionLevel, true))
  222. {
  223. try
  224. {
  225. stream.WriteTo(deflateStream);
  226. }
  227. catch
  228. {
  229. compressedStream.Position = 0L;
  230. }
  231. if (compressedStream.Position < compressedStream.Length)
  232. {
  233. compressedStream.SetLength(compressedStream.Position);
  234. }
  235. }
  236. }
  237. long fileSize = new FileInfo(fileName).Length;
  238. Logger.Info?.Print(LogClass.Ptc, $"Saved Profiling Info (size: {fileSize} bytes, profiled functions: {profiledFuncsCount}).");
  239. }
  240. private static void WriteHeader(MemoryStream stream)
  241. {
  242. using (BinaryWriter headerWriter = new BinaryWriter(stream, EncodingCache.UTF8NoBOM, true))
  243. {
  244. headerWriter.Write((string)HeaderMagic); // Header.Magic
  245. headerWriter.Write((uint)InternalVersion); // Header.InfoFileVersion
  246. }
  247. }
  248. private static void Serialize(MemoryStream stream, Dictionary<ulong, (ExecutionMode mode, bool highCq)> profiledFuncs)
  249. {
  250. using (BinaryWriter writer = new BinaryWriter(stream, EncodingCache.UTF8NoBOM, true))
  251. {
  252. writer.Write((int)profiledFuncs.Count);
  253. foreach (var kv in profiledFuncs)
  254. {
  255. writer.Write((ulong)kv.Key); // address
  256. writer.Write((int)kv.Value.mode);
  257. writer.Write((bool)kv.Value.highCq);
  258. }
  259. }
  260. }
  261. private struct Header
  262. {
  263. public string Magic;
  264. public uint InfoFileVersion;
  265. }
  266. internal static void Start()
  267. {
  268. if (Ptc.State == PtcState.Enabled ||
  269. Ptc.State == PtcState.Continuing)
  270. {
  271. Enabled = true;
  272. _timer.Enabled = true;
  273. }
  274. }
  275. public static void Stop()
  276. {
  277. Enabled = false;
  278. if (!_disposed)
  279. {
  280. _timer.Enabled = false;
  281. }
  282. }
  283. internal static void Wait()
  284. {
  285. _waitEvent.WaitOne();
  286. }
  287. public static void Dispose()
  288. {
  289. if (!_disposed)
  290. {
  291. _disposed = true;
  292. _timer.Elapsed -= PreSave;
  293. _timer.Dispose();
  294. Wait();
  295. _waitEvent.Dispose();
  296. }
  297. }
  298. }
  299. }