Ptc.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  1. using ARMeilleure.CodeGen;
  2. using ARMeilleure.CodeGen.Unwinding;
  3. using ARMeilleure.CodeGen.X86;
  4. using ARMeilleure.Memory;
  5. using ARMeilleure.Translation.Cache;
  6. using Ryujinx.Common.Configuration;
  7. using Ryujinx.Common.Logging;
  8. using System;
  9. using System.Buffers.Binary;
  10. using System.Collections.Concurrent;
  11. using System.Diagnostics;
  12. using System.IO;
  13. using System.IO.Compression;
  14. using System.Runtime.InteropServices;
  15. using System.Runtime.Serialization.Formatters.Binary;
  16. using System.Threading;
  17. using System.Threading.Tasks;
  18. namespace ARMeilleure.Translation.PTC
  19. {
  20. public static class Ptc
  21. {
  22. private const string HeaderMagic = "PTChd";
  23. private const int InternalVersion = 1519; //! To be incremented manually for each change to the ARMeilleure project.
  24. private const string ActualDir = "0";
  25. private const string BackupDir = "1";
  26. private const string TitleIdTextDefault = "0000000000000000";
  27. private const string DisplayVersionDefault = "0";
  28. internal const int PageTablePointerIndex = -1; // Must be a negative value.
  29. internal const int JumpPointerIndex = -2; // Must be a negative value.
  30. internal const int DynamicPointerIndex = -3; // Must be a negative value.
  31. private const CompressionLevel SaveCompressionLevel = CompressionLevel.Fastest;
  32. private static readonly MemoryStream _infosStream;
  33. private static readonly MemoryStream _codesStream;
  34. private static readonly MemoryStream _relocsStream;
  35. private static readonly MemoryStream _unwindInfosStream;
  36. private static readonly BinaryWriter _infosWriter;
  37. private static readonly BinaryFormatter _binaryFormatter;
  38. private static readonly ManualResetEvent _waitEvent;
  39. private static readonly AutoResetEvent _loggerEvent;
  40. private static readonly object _lock;
  41. private static bool _disposed;
  42. private static volatile int _translateCount;
  43. private static volatile int _rejitCount;
  44. internal static PtcJumpTable PtcJumpTable { get; private set; }
  45. internal static string TitleIdText { get; private set; }
  46. internal static string DisplayVersion { get; private set; }
  47. internal static string CachePathActual { get; private set; }
  48. internal static string CachePathBackup { get; private set; }
  49. internal static PtcState State { get; private set; }
  50. static Ptc()
  51. {
  52. _infosStream = new MemoryStream();
  53. _codesStream = new MemoryStream();
  54. _relocsStream = new MemoryStream();
  55. _unwindInfosStream = new MemoryStream();
  56. _infosWriter = new BinaryWriter(_infosStream, EncodingCache.UTF8NoBOM, true);
  57. _binaryFormatter = new BinaryFormatter();
  58. _waitEvent = new ManualResetEvent(true);
  59. _loggerEvent = new AutoResetEvent(false);
  60. _lock = new object();
  61. _disposed = false;
  62. PtcJumpTable = new PtcJumpTable();
  63. TitleIdText = TitleIdTextDefault;
  64. DisplayVersion = DisplayVersionDefault;
  65. CachePathActual = string.Empty;
  66. CachePathBackup = string.Empty;
  67. Disable();
  68. }
  69. public static void Initialize(string titleIdText, string displayVersion, bool enabled)
  70. {
  71. Wait();
  72. ClearMemoryStreams();
  73. PtcJumpTable.Clear();
  74. PtcProfiler.Stop();
  75. PtcProfiler.Wait();
  76. PtcProfiler.ClearEntries();
  77. if (String.IsNullOrEmpty(titleIdText) || titleIdText == TitleIdTextDefault)
  78. {
  79. TitleIdText = TitleIdTextDefault;
  80. DisplayVersion = DisplayVersionDefault;
  81. CachePathActual = string.Empty;
  82. CachePathBackup = string.Empty;
  83. Disable();
  84. return;
  85. }
  86. Logger.Info?.Print(LogClass.Ptc, $"Initializing Profiled Persistent Translation Cache (enabled: {enabled}).");
  87. TitleIdText = titleIdText;
  88. DisplayVersion = !String.IsNullOrEmpty(displayVersion) ? displayVersion : DisplayVersionDefault;
  89. if (enabled)
  90. {
  91. string workPathActual = Path.Combine(AppDataManager.GamesDirPath, TitleIdText, "cache", "cpu", ActualDir);
  92. string workPathBackup = Path.Combine(AppDataManager.GamesDirPath, TitleIdText, "cache", "cpu", BackupDir);
  93. if (!Directory.Exists(workPathActual))
  94. {
  95. Directory.CreateDirectory(workPathActual);
  96. }
  97. if (!Directory.Exists(workPathBackup))
  98. {
  99. Directory.CreateDirectory(workPathBackup);
  100. }
  101. CachePathActual = Path.Combine(workPathActual, DisplayVersion);
  102. CachePathBackup = Path.Combine(workPathBackup, DisplayVersion);
  103. Enable();
  104. PreLoad();
  105. PtcProfiler.PreLoad();
  106. }
  107. else
  108. {
  109. CachePathActual = string.Empty;
  110. CachePathBackup = string.Empty;
  111. Disable();
  112. }
  113. }
  114. internal static void ClearMemoryStreams()
  115. {
  116. _infosStream.SetLength(0L);
  117. _codesStream.SetLength(0L);
  118. _relocsStream.SetLength(0L);
  119. _unwindInfosStream.SetLength(0L);
  120. }
  121. private static void PreLoad()
  122. {
  123. string fileNameActual = String.Concat(CachePathActual, ".cache");
  124. string fileNameBackup = String.Concat(CachePathBackup, ".cache");
  125. FileInfo fileInfoActual = new FileInfo(fileNameActual);
  126. FileInfo fileInfoBackup = new FileInfo(fileNameBackup);
  127. if (fileInfoActual.Exists && fileInfoActual.Length != 0L)
  128. {
  129. if (!Load(fileNameActual))
  130. {
  131. if (fileInfoBackup.Exists && fileInfoBackup.Length != 0L)
  132. {
  133. Load(fileNameBackup);
  134. }
  135. }
  136. }
  137. else if (fileInfoBackup.Exists && fileInfoBackup.Length != 0L)
  138. {
  139. Load(fileNameBackup);
  140. }
  141. }
  142. private static bool Load(string fileName)
  143. {
  144. using (FileStream compressedStream = new FileStream(fileName, FileMode.Open))
  145. using (DeflateStream deflateStream = new DeflateStream(compressedStream, CompressionMode.Decompress, true))
  146. using (MemoryStream stream = new MemoryStream())
  147. using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
  148. {
  149. int hashSize = md5.HashSize / 8;
  150. try
  151. {
  152. deflateStream.CopyTo(stream);
  153. }
  154. catch
  155. {
  156. InvalidateCompressedStream(compressedStream);
  157. return false;
  158. }
  159. stream.Seek(0L, SeekOrigin.Begin);
  160. byte[] currentHash = new byte[hashSize];
  161. stream.Read(currentHash, 0, hashSize);
  162. byte[] expectedHash = md5.ComputeHash(stream);
  163. if (!CompareHash(currentHash, expectedHash))
  164. {
  165. InvalidateCompressedStream(compressedStream);
  166. return false;
  167. }
  168. stream.Seek((long)hashSize, SeekOrigin.Begin);
  169. Header header = ReadHeader(stream);
  170. if (header.Magic != HeaderMagic)
  171. {
  172. InvalidateCompressedStream(compressedStream);
  173. return false;
  174. }
  175. if (header.CacheFileVersion != InternalVersion)
  176. {
  177. InvalidateCompressedStream(compressedStream);
  178. return false;
  179. }
  180. if (header.FeatureInfo != GetFeatureInfo())
  181. {
  182. InvalidateCompressedStream(compressedStream);
  183. return false;
  184. }
  185. if (header.InfosLen % InfoEntry.Stride != 0)
  186. {
  187. InvalidateCompressedStream(compressedStream);
  188. return false;
  189. }
  190. byte[] infosBuf = new byte[header.InfosLen];
  191. byte[] codesBuf = new byte[header.CodesLen];
  192. byte[] relocsBuf = new byte[header.RelocsLen];
  193. byte[] unwindInfosBuf = new byte[header.UnwindInfosLen];
  194. stream.Read(infosBuf, 0, header.InfosLen);
  195. stream.Read(codesBuf, 0, header.CodesLen);
  196. stream.Read(relocsBuf, 0, header.RelocsLen);
  197. stream.Read(unwindInfosBuf, 0, header.UnwindInfosLen);
  198. try
  199. {
  200. PtcJumpTable = (PtcJumpTable)_binaryFormatter.Deserialize(stream);
  201. }
  202. catch
  203. {
  204. PtcJumpTable = new PtcJumpTable();
  205. InvalidateCompressedStream(compressedStream);
  206. return false;
  207. }
  208. _infosStream.Write(infosBuf, 0, header.InfosLen);
  209. _codesStream.Write(codesBuf, 0, header.CodesLen);
  210. _relocsStream.Write(relocsBuf, 0, header.RelocsLen);
  211. _unwindInfosStream.Write(unwindInfosBuf, 0, header.UnwindInfosLen);
  212. return true;
  213. }
  214. }
  215. private static bool CompareHash(ReadOnlySpan<byte> currentHash, ReadOnlySpan<byte> expectedHash)
  216. {
  217. return currentHash.SequenceEqual(expectedHash);
  218. }
  219. private static Header ReadHeader(MemoryStream stream)
  220. {
  221. using (BinaryReader headerReader = new BinaryReader(stream, EncodingCache.UTF8NoBOM, true))
  222. {
  223. Header header = new Header();
  224. header.Magic = headerReader.ReadString();
  225. header.CacheFileVersion = headerReader.ReadInt32();
  226. header.FeatureInfo = headerReader.ReadUInt64();
  227. header.InfosLen = headerReader.ReadInt32();
  228. header.CodesLen = headerReader.ReadInt32();
  229. header.RelocsLen = headerReader.ReadInt32();
  230. header.UnwindInfosLen = headerReader.ReadInt32();
  231. return header;
  232. }
  233. }
  234. private static void InvalidateCompressedStream(FileStream compressedStream)
  235. {
  236. compressedStream.SetLength(0L);
  237. }
  238. private static void PreSave(object state)
  239. {
  240. _waitEvent.Reset();
  241. string fileNameActual = String.Concat(CachePathActual, ".cache");
  242. string fileNameBackup = String.Concat(CachePathBackup, ".cache");
  243. FileInfo fileInfoActual = new FileInfo(fileNameActual);
  244. if (fileInfoActual.Exists && fileInfoActual.Length != 0L)
  245. {
  246. File.Copy(fileNameActual, fileNameBackup, true);
  247. }
  248. Save(fileNameActual);
  249. _waitEvent.Set();
  250. }
  251. private static void Save(string fileName)
  252. {
  253. using (MemoryStream stream = new MemoryStream())
  254. using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
  255. {
  256. int hashSize = md5.HashSize / 8;
  257. stream.Seek((long)hashSize, SeekOrigin.Begin);
  258. WriteHeader(stream);
  259. _infosStream.WriteTo(stream);
  260. _codesStream.WriteTo(stream);
  261. _relocsStream.WriteTo(stream);
  262. _unwindInfosStream.WriteTo(stream);
  263. _binaryFormatter.Serialize(stream, PtcJumpTable);
  264. stream.Seek((long)hashSize, SeekOrigin.Begin);
  265. byte[] hash = md5.ComputeHash(stream);
  266. stream.Seek(0L, SeekOrigin.Begin);
  267. stream.Write(hash, 0, hashSize);
  268. using (FileStream compressedStream = new FileStream(fileName, FileMode.OpenOrCreate))
  269. using (DeflateStream deflateStream = new DeflateStream(compressedStream, SaveCompressionLevel, true))
  270. {
  271. try
  272. {
  273. stream.WriteTo(deflateStream);
  274. }
  275. catch
  276. {
  277. compressedStream.Position = 0L;
  278. }
  279. if (compressedStream.Position < compressedStream.Length)
  280. {
  281. compressedStream.SetLength(compressedStream.Position);
  282. }
  283. }
  284. }
  285. }
  286. private static void WriteHeader(MemoryStream stream)
  287. {
  288. using (BinaryWriter headerWriter = new BinaryWriter(stream, EncodingCache.UTF8NoBOM, true))
  289. {
  290. headerWriter.Write((string)HeaderMagic); // Header.Magic
  291. headerWriter.Write((int)InternalVersion); // Header.CacheFileVersion
  292. headerWriter.Write((ulong)GetFeatureInfo()); // Header.FeatureInfo
  293. headerWriter.Write((int)_infosStream.Length); // Header.InfosLen
  294. headerWriter.Write((int)_codesStream.Length); // Header.CodesLen
  295. headerWriter.Write((int)_relocsStream.Length); // Header.RelocsLen
  296. headerWriter.Write((int)_unwindInfosStream.Length); // Header.UnwindInfosLen
  297. }
  298. }
  299. internal static void LoadTranslations(ConcurrentDictionary<ulong, TranslatedFunction> funcs, IntPtr pageTablePointer, JumpTable jumpTable)
  300. {
  301. if ((int)_infosStream.Length == 0 ||
  302. (int)_codesStream.Length == 0 ||
  303. (int)_relocsStream.Length == 0 ||
  304. (int)_unwindInfosStream.Length == 0)
  305. {
  306. return;
  307. }
  308. Debug.Assert(funcs.Count == 0);
  309. _infosStream.Seek(0L, SeekOrigin.Begin);
  310. _codesStream.Seek(0L, SeekOrigin.Begin);
  311. _relocsStream.Seek(0L, SeekOrigin.Begin);
  312. _unwindInfosStream.Seek(0L, SeekOrigin.Begin);
  313. using (BinaryReader infosReader = new BinaryReader(_infosStream, EncodingCache.UTF8NoBOM, true))
  314. using (BinaryReader codesReader = new BinaryReader(_codesStream, EncodingCache.UTF8NoBOM, true))
  315. using (BinaryReader relocsReader = new BinaryReader(_relocsStream, EncodingCache.UTF8NoBOM, true))
  316. using (BinaryReader unwindInfosReader = new BinaryReader(_unwindInfosStream, EncodingCache.UTF8NoBOM, true))
  317. {
  318. int infosEntriesCount = (int)_infosStream.Length / InfoEntry.Stride;
  319. for (int i = 0; i < infosEntriesCount; i++)
  320. {
  321. InfoEntry infoEntry = ReadInfo(infosReader);
  322. byte[] code = ReadCode(codesReader, infoEntry.CodeLen);
  323. if (infoEntry.RelocEntriesCount != 0)
  324. {
  325. RelocEntry[] relocEntries = GetRelocEntries(relocsReader, infoEntry.RelocEntriesCount);
  326. PatchCode(code, relocEntries, pageTablePointer, jumpTable);
  327. }
  328. UnwindInfo unwindInfo = ReadUnwindInfo(unwindInfosReader);
  329. TranslatedFunction func = FastTranslate(code, infoEntry.GuestSize, unwindInfo, infoEntry.HighCq);
  330. funcs.AddOrUpdate(infoEntry.Address, func, (key, oldFunc) => func.HighCq && !oldFunc.HighCq ? func : oldFunc);
  331. }
  332. }
  333. if (_infosStream.Position < _infosStream.Length ||
  334. _codesStream.Position < _codesStream.Length ||
  335. _relocsStream.Position < _relocsStream.Length ||
  336. _unwindInfosStream.Position < _unwindInfosStream.Length)
  337. {
  338. throw new Exception("Could not reach the end of one or more memory streams.");
  339. }
  340. jumpTable.Initialize(PtcJumpTable, funcs);
  341. PtcJumpTable.WriteJumpTable(jumpTable, funcs);
  342. PtcJumpTable.WriteDynamicTable(jumpTable);
  343. }
  344. private static InfoEntry ReadInfo(BinaryReader infosReader)
  345. {
  346. InfoEntry infoEntry = new InfoEntry();
  347. infoEntry.Address = infosReader.ReadUInt64();
  348. infoEntry.GuestSize = infosReader.ReadUInt64();
  349. infoEntry.HighCq = infosReader.ReadBoolean();
  350. infoEntry.CodeLen = infosReader.ReadInt32();
  351. infoEntry.RelocEntriesCount = infosReader.ReadInt32();
  352. return infoEntry;
  353. }
  354. private static byte[] ReadCode(BinaryReader codesReader, int codeLen)
  355. {
  356. byte[] codeBuf = new byte[codeLen];
  357. codesReader.Read(codeBuf, 0, codeLen);
  358. return codeBuf;
  359. }
  360. private static RelocEntry[] GetRelocEntries(BinaryReader relocsReader, int relocEntriesCount)
  361. {
  362. RelocEntry[] relocEntries = new RelocEntry[relocEntriesCount];
  363. for (int i = 0; i < relocEntriesCount; i++)
  364. {
  365. int position = relocsReader.ReadInt32();
  366. int index = relocsReader.ReadInt32();
  367. relocEntries[i] = new RelocEntry(position, index);
  368. }
  369. return relocEntries;
  370. }
  371. private static void PatchCode(Span<byte> code, RelocEntry[] relocEntries, IntPtr pageTablePointer, JumpTable jumpTable)
  372. {
  373. foreach (RelocEntry relocEntry in relocEntries)
  374. {
  375. ulong imm;
  376. if (relocEntry.Index == PageTablePointerIndex)
  377. {
  378. imm = (ulong)pageTablePointer.ToInt64();
  379. }
  380. else if (relocEntry.Index == JumpPointerIndex)
  381. {
  382. imm = (ulong)jumpTable.JumpPointer.ToInt64();
  383. }
  384. else if (relocEntry.Index == DynamicPointerIndex)
  385. {
  386. imm = (ulong)jumpTable.DynamicPointer.ToInt64();
  387. }
  388. else if (Delegates.TryGetDelegateFuncPtrByIndex(relocEntry.Index, out IntPtr funcPtr))
  389. {
  390. imm = (ulong)funcPtr.ToInt64();
  391. }
  392. else
  393. {
  394. throw new Exception($"Unexpected reloc entry {relocEntry}.");
  395. }
  396. BinaryPrimitives.WriteUInt64LittleEndian(code.Slice(relocEntry.Position, 8), imm);
  397. }
  398. }
  399. private static UnwindInfo ReadUnwindInfo(BinaryReader unwindInfosReader)
  400. {
  401. int pushEntriesLength = unwindInfosReader.ReadInt32();
  402. UnwindPushEntry[] pushEntries = new UnwindPushEntry[pushEntriesLength];
  403. for (int i = 0; i < pushEntriesLength; i++)
  404. {
  405. int pseudoOp = unwindInfosReader.ReadInt32();
  406. int prologOffset = unwindInfosReader.ReadInt32();
  407. int regIndex = unwindInfosReader.ReadInt32();
  408. int stackOffsetOrAllocSize = unwindInfosReader.ReadInt32();
  409. pushEntries[i] = new UnwindPushEntry((UnwindPseudoOp)pseudoOp, prologOffset, regIndex, stackOffsetOrAllocSize);
  410. }
  411. int prologueSize = unwindInfosReader.ReadInt32();
  412. return new UnwindInfo(pushEntries, prologueSize);
  413. }
  414. private static TranslatedFunction FastTranslate(byte[] code, ulong guestSize, UnwindInfo unwindInfo, bool highCq)
  415. {
  416. CompiledFunction cFunc = new CompiledFunction(code, unwindInfo);
  417. IntPtr codePtr = JitCache.Map(cFunc);
  418. GuestFunction gFunc = Marshal.GetDelegateForFunctionPointer<GuestFunction>(codePtr);
  419. TranslatedFunction tFunc = new TranslatedFunction(gFunc, guestSize, highCq);
  420. return tFunc;
  421. }
  422. internal static void MakeAndSaveTranslations(ConcurrentDictionary<ulong, TranslatedFunction> funcs, IMemoryManager memory, JumpTable jumpTable)
  423. {
  424. if (PtcProfiler.ProfiledFuncs.Count == 0)
  425. {
  426. return;
  427. }
  428. _translateCount = 0;
  429. _rejitCount = 0;
  430. ThreadPool.QueueUserWorkItem(TranslationLogger, (funcs.Count, PtcProfiler.ProfiledFuncs.Count));
  431. int maxDegreeOfParallelism = (Environment.ProcessorCount * 3) / 4;
  432. Parallel.ForEach(PtcProfiler.ProfiledFuncs, new ParallelOptions { MaxDegreeOfParallelism = maxDegreeOfParallelism }, (item, state) =>
  433. {
  434. ulong address = item.Key;
  435. Debug.Assert(PtcProfiler.IsAddressInStaticCodeRange(address));
  436. if (!funcs.ContainsKey(address))
  437. {
  438. TranslatedFunction func = Translator.Translate(memory, jumpTable, address, item.Value.mode, item.Value.highCq);
  439. funcs.TryAdd(address, func);
  440. if (func.HighCq)
  441. {
  442. jumpTable.RegisterFunction(address, func);
  443. }
  444. Interlocked.Increment(ref _translateCount);
  445. }
  446. else if (item.Value.highCq && !funcs[address].HighCq)
  447. {
  448. TranslatedFunction func = Translator.Translate(memory, jumpTable, address, item.Value.mode, highCq: true);
  449. funcs[address] = func;
  450. jumpTable.RegisterFunction(address, func);
  451. Interlocked.Increment(ref _rejitCount);
  452. }
  453. if (State != PtcState.Enabled)
  454. {
  455. state.Stop();
  456. }
  457. });
  458. _loggerEvent.Set();
  459. if (_translateCount != 0 || _rejitCount != 0)
  460. {
  461. PtcJumpTable.Initialize(jumpTable);
  462. PtcJumpTable.ReadJumpTable(jumpTable);
  463. PtcJumpTable.ReadDynamicTable(jumpTable);
  464. ThreadPool.QueueUserWorkItem(PreSave);
  465. }
  466. }
  467. private static void TranslationLogger(object state)
  468. {
  469. const int refreshRate = 1; // Seconds.
  470. (int funcsCount, int ProfiledFuncsCount) = ((int, int))state;
  471. do
  472. {
  473. Logger.Info?.Print(LogClass.Ptc, $"{funcsCount + _translateCount} of {ProfiledFuncsCount} functions to translate - {_rejitCount} functions rejited");
  474. }
  475. while (!_loggerEvent.WaitOne(refreshRate * 1000));
  476. Logger.Info?.Print(LogClass.Ptc, $"{funcsCount + _translateCount} of {ProfiledFuncsCount} functions to translate - {_rejitCount} functions rejited");
  477. }
  478. internal static void WriteInfoCodeReloc(ulong address, ulong guestSize, bool highCq, PtcInfo ptcInfo)
  479. {
  480. lock (_lock)
  481. {
  482. // WriteInfo.
  483. _infosWriter.Write((ulong)address); // InfoEntry.Address
  484. _infosWriter.Write((ulong)guestSize); // InfoEntry.GuestSize
  485. _infosWriter.Write((bool)highCq); // InfoEntry.HighCq
  486. _infosWriter.Write((int)ptcInfo.CodeStream.Length); // InfoEntry.CodeLen
  487. _infosWriter.Write((int)ptcInfo.RelocEntriesCount); // InfoEntry.RelocEntriesCount
  488. // WriteCode.
  489. ptcInfo.CodeStream.WriteTo(_codesStream);
  490. // WriteReloc.
  491. ptcInfo.RelocStream.WriteTo(_relocsStream);
  492. // WriteUnwindInfo.
  493. ptcInfo.UnwindInfoStream.WriteTo(_unwindInfosStream);
  494. }
  495. }
  496. private static ulong GetFeatureInfo()
  497. {
  498. return (ulong)HardwareCapabilities.FeatureInfoEdx << 32 | (uint)HardwareCapabilities.FeatureInfoEcx;
  499. }
  500. private struct Header
  501. {
  502. public string Magic;
  503. public int CacheFileVersion;
  504. public ulong FeatureInfo;
  505. public int InfosLen;
  506. public int CodesLen;
  507. public int RelocsLen;
  508. public int UnwindInfosLen;
  509. }
  510. private struct InfoEntry
  511. {
  512. public const int Stride = 25; // Bytes.
  513. public ulong Address;
  514. public ulong GuestSize;
  515. public bool HighCq;
  516. public int CodeLen;
  517. public int RelocEntriesCount;
  518. }
  519. private static void Enable()
  520. {
  521. State = PtcState.Enabled;
  522. }
  523. public static void Continue()
  524. {
  525. if (State == PtcState.Enabled)
  526. {
  527. State = PtcState.Continuing;
  528. }
  529. }
  530. public static void Close()
  531. {
  532. if (State == PtcState.Enabled ||
  533. State == PtcState.Continuing)
  534. {
  535. State = PtcState.Closing;
  536. }
  537. }
  538. internal static void Disable()
  539. {
  540. State = PtcState.Disabled;
  541. }
  542. private static void Wait()
  543. {
  544. _waitEvent.WaitOne();
  545. }
  546. public static void Dispose()
  547. {
  548. if (!_disposed)
  549. {
  550. _disposed = true;
  551. Wait();
  552. _waitEvent.Dispose();
  553. _infosWriter.Dispose();
  554. _infosStream.Dispose();
  555. _codesStream.Dispose();
  556. _relocsStream.Dispose();
  557. _unwindInfosStream.Dispose();
  558. }
  559. }
  560. }
  561. }