PtcProfiler.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. using ARMeilleure.State;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.IO;
  6. using System.IO.Compression;
  7. using System.Runtime.Serialization.Formatters.Binary;
  8. using System.Security.Cryptography;
  9. using System.Threading;
  10. namespace ARMeilleure.Translation.PTC
  11. {
  12. public static class PtcProfiler
  13. {
  14. private const int SaveInterval = 30; // Seconds.
  15. private const CompressionLevel SaveCompressionLevel = CompressionLevel.Fastest;
  16. private static readonly BinaryFormatter _binaryFormatter;
  17. private static readonly System.Timers.Timer _timer;
  18. private static readonly ManualResetEvent _waitEvent;
  19. private static readonly object _lock;
  20. private static bool _disposed;
  21. internal static Dictionary<ulong, (ExecutionMode mode, bool highCq)> ProfiledFuncs { get; private set; } //! Not to be modified.
  22. internal static bool Enabled { get; private set; }
  23. public static ulong StaticCodeStart { internal get; set; }
  24. public static int StaticCodeSize { internal get; set; }
  25. static PtcProfiler()
  26. {
  27. _binaryFormatter = new BinaryFormatter();
  28. _timer = new System.Timers.Timer((double)SaveInterval * 1000d);
  29. _timer.Elapsed += PreSave;
  30. _waitEvent = new ManualResetEvent(true);
  31. _lock = new object();
  32. _disposed = false;
  33. ProfiledFuncs = new Dictionary<ulong, (ExecutionMode, bool)>();
  34. Enabled = false;
  35. }
  36. internal static void AddEntry(ulong address, ExecutionMode mode, bool highCq)
  37. {
  38. if (IsAddressInStaticCodeRange(address))
  39. {
  40. lock (_lock)
  41. {
  42. Debug.Assert(!highCq && !ProfiledFuncs.ContainsKey(address));
  43. ProfiledFuncs.TryAdd(address, (mode, highCq));
  44. }
  45. }
  46. }
  47. internal static void UpdateEntry(ulong address, ExecutionMode mode, bool highCq)
  48. {
  49. if (IsAddressInStaticCodeRange(address))
  50. {
  51. lock (_lock)
  52. {
  53. Debug.Assert(highCq && ProfiledFuncs.ContainsKey(address));
  54. ProfiledFuncs[address] = (mode, highCq);
  55. }
  56. }
  57. }
  58. internal static bool IsAddressInStaticCodeRange(ulong address)
  59. {
  60. return address >= StaticCodeStart && address < StaticCodeStart + (ulong)StaticCodeSize;
  61. }
  62. internal static void ClearEntries()
  63. {
  64. ProfiledFuncs.Clear();
  65. }
  66. internal static void PreLoad()
  67. {
  68. string fileNameActual = String.Concat(Ptc.CachePathActual, ".info");
  69. string fileNameBackup = String.Concat(Ptc.CachePathBackup, ".info");
  70. FileInfo fileInfoActual = new FileInfo(fileNameActual);
  71. FileInfo fileInfoBackup = new FileInfo(fileNameBackup);
  72. if (fileInfoActual.Exists && fileInfoActual.Length != 0L)
  73. {
  74. if (!Load(fileNameActual))
  75. {
  76. if (fileInfoBackup.Exists && fileInfoBackup.Length != 0L)
  77. {
  78. Load(fileNameBackup);
  79. }
  80. }
  81. }
  82. else if (fileInfoBackup.Exists && fileInfoBackup.Length != 0L)
  83. {
  84. Load(fileNameBackup);
  85. }
  86. }
  87. private static bool Load(string fileName)
  88. {
  89. using (FileStream compressedStream = new FileStream(fileName, FileMode.Open))
  90. using (DeflateStream deflateStream = new DeflateStream(compressedStream, CompressionMode.Decompress, true))
  91. using (MemoryStream stream = new MemoryStream())
  92. using (MD5 md5 = MD5.Create())
  93. {
  94. int hashSize = md5.HashSize / 8;
  95. deflateStream.CopyTo(stream);
  96. stream.Seek(0L, SeekOrigin.Begin);
  97. byte[] currentHash = new byte[hashSize];
  98. stream.Read(currentHash, 0, hashSize);
  99. byte[] expectedHash = md5.ComputeHash(stream);
  100. if (!CompareHash(currentHash, expectedHash))
  101. {
  102. InvalidateCompressedStream(compressedStream);
  103. return false;
  104. }
  105. stream.Seek((long)hashSize, SeekOrigin.Begin);
  106. try
  107. {
  108. ProfiledFuncs = (Dictionary<ulong, (ExecutionMode, bool)>)_binaryFormatter.Deserialize(stream);
  109. }
  110. catch
  111. {
  112. ProfiledFuncs = new Dictionary<ulong, (ExecutionMode, bool)>();
  113. InvalidateCompressedStream(compressedStream);
  114. return false;
  115. }
  116. return true;
  117. }
  118. }
  119. private static bool CompareHash(ReadOnlySpan<byte> currentHash, ReadOnlySpan<byte> expectedHash)
  120. {
  121. return currentHash.SequenceEqual(expectedHash);
  122. }
  123. private static void InvalidateCompressedStream(FileStream compressedStream)
  124. {
  125. compressedStream.SetLength(0L);
  126. }
  127. private static void PreSave(object source, System.Timers.ElapsedEventArgs e)
  128. {
  129. _waitEvent.Reset();
  130. string fileNameActual = String.Concat(Ptc.CachePathActual, ".info");
  131. string fileNameBackup = String.Concat(Ptc.CachePathBackup, ".info");
  132. FileInfo fileInfoActual = new FileInfo(fileNameActual);
  133. if (fileInfoActual.Exists && fileInfoActual.Length != 0L)
  134. {
  135. File.Copy(fileNameActual, fileNameBackup, true);
  136. }
  137. Save(fileNameActual);
  138. _waitEvent.Set();
  139. }
  140. private static void Save(string fileName)
  141. {
  142. using (MemoryStream stream = new MemoryStream())
  143. using (MD5 md5 = MD5.Create())
  144. {
  145. int hashSize = md5.HashSize / 8;
  146. stream.Seek((long)hashSize, SeekOrigin.Begin);
  147. lock (_lock)
  148. {
  149. _binaryFormatter.Serialize(stream, ProfiledFuncs);
  150. }
  151. stream.Seek((long)hashSize, SeekOrigin.Begin);
  152. byte[] hash = md5.ComputeHash(stream);
  153. stream.Seek(0L, SeekOrigin.Begin);
  154. stream.Write(hash, 0, hashSize);
  155. using (FileStream compressedStream = new FileStream(fileName, FileMode.OpenOrCreate))
  156. using (DeflateStream deflateStream = new DeflateStream(compressedStream, SaveCompressionLevel, true))
  157. {
  158. try
  159. {
  160. stream.WriteTo(deflateStream);
  161. }
  162. catch
  163. {
  164. compressedStream.Position = 0L;
  165. }
  166. if (compressedStream.Position < compressedStream.Length)
  167. {
  168. compressedStream.SetLength(compressedStream.Position);
  169. }
  170. }
  171. }
  172. }
  173. internal static void Start()
  174. {
  175. if (Ptc.State == PtcState.Enabled ||
  176. Ptc.State == PtcState.Continuing)
  177. {
  178. Enabled = true;
  179. _timer.Enabled = true;
  180. }
  181. }
  182. public static void Stop()
  183. {
  184. Enabled = false;
  185. if (!_disposed)
  186. {
  187. _timer.Enabled = false;
  188. }
  189. }
  190. internal static void Wait()
  191. {
  192. _waitEvent.WaitOne();
  193. }
  194. public static void Dispose()
  195. {
  196. if (!_disposed)
  197. {
  198. _disposed = true;
  199. _timer.Elapsed -= PreSave;
  200. _timer.Dispose();
  201. Wait();
  202. _waitEvent.Dispose();
  203. }
  204. }
  205. }
  206. }