Ptc.cs 25 KB

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