PtcProfiler.cs 12 KB

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