Ptc.cs 25 KB

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