PtcProfiler.cs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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. try
  96. {
  97. deflateStream.CopyTo(stream);
  98. }
  99. catch
  100. {
  101. InvalidateCompressedStream(compressedStream);
  102. return false;
  103. }
  104. stream.Seek(0L, SeekOrigin.Begin);
  105. byte[] currentHash = new byte[hashSize];
  106. stream.Read(currentHash, 0, hashSize);
  107. byte[] expectedHash = md5.ComputeHash(stream);
  108. if (!CompareHash(currentHash, expectedHash))
  109. {
  110. InvalidateCompressedStream(compressedStream);
  111. return false;
  112. }
  113. stream.Seek((long)hashSize, SeekOrigin.Begin);
  114. try
  115. {
  116. ProfiledFuncs = (Dictionary<ulong, (ExecutionMode, bool)>)_binaryFormatter.Deserialize(stream);
  117. }
  118. catch
  119. {
  120. ProfiledFuncs = new Dictionary<ulong, (ExecutionMode, bool)>();
  121. InvalidateCompressedStream(compressedStream);
  122. return false;
  123. }
  124. return true;
  125. }
  126. }
  127. private static bool CompareHash(ReadOnlySpan<byte> currentHash, ReadOnlySpan<byte> expectedHash)
  128. {
  129. return currentHash.SequenceEqual(expectedHash);
  130. }
  131. private static void InvalidateCompressedStream(FileStream compressedStream)
  132. {
  133. compressedStream.SetLength(0L);
  134. }
  135. private static void PreSave(object source, System.Timers.ElapsedEventArgs e)
  136. {
  137. _waitEvent.Reset();
  138. string fileNameActual = String.Concat(Ptc.CachePathActual, ".info");
  139. string fileNameBackup = String.Concat(Ptc.CachePathBackup, ".info");
  140. FileInfo fileInfoActual = new FileInfo(fileNameActual);
  141. if (fileInfoActual.Exists && fileInfoActual.Length != 0L)
  142. {
  143. File.Copy(fileNameActual, fileNameBackup, true);
  144. }
  145. Save(fileNameActual);
  146. _waitEvent.Set();
  147. }
  148. private static void Save(string fileName)
  149. {
  150. using (MemoryStream stream = new MemoryStream())
  151. using (MD5 md5 = MD5.Create())
  152. {
  153. int hashSize = md5.HashSize / 8;
  154. stream.Seek((long)hashSize, SeekOrigin.Begin);
  155. lock (_lock)
  156. {
  157. _binaryFormatter.Serialize(stream, ProfiledFuncs);
  158. }
  159. stream.Seek((long)hashSize, SeekOrigin.Begin);
  160. byte[] hash = md5.ComputeHash(stream);
  161. stream.Seek(0L, SeekOrigin.Begin);
  162. stream.Write(hash, 0, hashSize);
  163. using (FileStream compressedStream = new FileStream(fileName, FileMode.OpenOrCreate))
  164. using (DeflateStream deflateStream = new DeflateStream(compressedStream, SaveCompressionLevel, true))
  165. {
  166. try
  167. {
  168. stream.WriteTo(deflateStream);
  169. }
  170. catch
  171. {
  172. compressedStream.Position = 0L;
  173. }
  174. if (compressedStream.Position < compressedStream.Length)
  175. {
  176. compressedStream.SetLength(compressedStream.Position);
  177. }
  178. }
  179. }
  180. }
  181. internal static void Start()
  182. {
  183. if (Ptc.State == PtcState.Enabled ||
  184. Ptc.State == PtcState.Continuing)
  185. {
  186. Enabled = true;
  187. _timer.Enabled = true;
  188. }
  189. }
  190. public static void Stop()
  191. {
  192. Enabled = false;
  193. if (!_disposed)
  194. {
  195. _timer.Enabled = false;
  196. }
  197. }
  198. internal static void Wait()
  199. {
  200. _waitEvent.WaitOne();
  201. }
  202. public static void Dispose()
  203. {
  204. if (!_disposed)
  205. {
  206. _disposed = true;
  207. _timer.Elapsed -= PreSave;
  208. _timer.Dispose();
  209. Wait();
  210. _waitEvent.Dispose();
  211. }
  212. }
  213. }
  214. }