Ptc.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739
  1. using ARMeilleure.CodeGen;
  2. using ARMeilleure.CodeGen.Unwinding;
  3. using ARMeilleure.Memory;
  4. using Ryujinx.Common.Configuration;
  5. using Ryujinx.Common.Logging;
  6. using System;
  7. using System.Buffers.Binary;
  8. using System.Collections.Concurrent;
  9. using System.Diagnostics;
  10. using System.IO;
  11. using System.IO.Compression;
  12. using System.Runtime.InteropServices;
  13. using System.Runtime.Intrinsics.X86;
  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 = 1447; //! 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. deflateStream.CopyTo(stream);
  150. stream.Seek(0L, SeekOrigin.Begin);
  151. byte[] currentHash = new byte[hashSize];
  152. stream.Read(currentHash, 0, hashSize);
  153. byte[] expectedHash = md5.ComputeHash(stream);
  154. if (!CompareHash(currentHash, expectedHash))
  155. {
  156. InvalidateCompressedStream(compressedStream);
  157. return false;
  158. }
  159. stream.Seek((long)hashSize, SeekOrigin.Begin);
  160. Header header = ReadHeader(stream);
  161. if (header.Magic != HeaderMagic)
  162. {
  163. InvalidateCompressedStream(compressedStream);
  164. return false;
  165. }
  166. if (header.CacheFileVersion != InternalVersion)
  167. {
  168. InvalidateCompressedStream(compressedStream);
  169. return false;
  170. }
  171. if (header.FeatureInfo != GetFeatureInfo())
  172. {
  173. InvalidateCompressedStream(compressedStream);
  174. return false;
  175. }
  176. if (header.InfosLen % InfoEntry.Stride != 0)
  177. {
  178. InvalidateCompressedStream(compressedStream);
  179. return false;
  180. }
  181. byte[] infosBuf = new byte[header.InfosLen];
  182. byte[] codesBuf = new byte[header.CodesLen];
  183. byte[] relocsBuf = new byte[header.RelocsLen];
  184. byte[] unwindInfosBuf = new byte[header.UnwindInfosLen];
  185. stream.Read(infosBuf, 0, header.InfosLen);
  186. stream.Read(codesBuf, 0, header.CodesLen);
  187. stream.Read(relocsBuf, 0, header.RelocsLen);
  188. stream.Read(unwindInfosBuf, 0, header.UnwindInfosLen);
  189. try
  190. {
  191. PtcJumpTable = (PtcJumpTable)_binaryFormatter.Deserialize(stream);
  192. }
  193. catch
  194. {
  195. PtcJumpTable = new PtcJumpTable();
  196. InvalidateCompressedStream(compressedStream);
  197. return false;
  198. }
  199. _infosStream.Write(infosBuf, 0, header.InfosLen);
  200. _codesStream.Write(codesBuf, 0, header.CodesLen);
  201. _relocsStream.Write(relocsBuf, 0, header.RelocsLen);
  202. _unwindInfosStream.Write(unwindInfosBuf, 0, header.UnwindInfosLen);
  203. return true;
  204. }
  205. }
  206. private static bool CompareHash(ReadOnlySpan<byte> currentHash, ReadOnlySpan<byte> expectedHash)
  207. {
  208. return currentHash.SequenceEqual(expectedHash);
  209. }
  210. private static Header ReadHeader(MemoryStream stream)
  211. {
  212. using (BinaryReader headerReader = new BinaryReader(stream, EncodingCache.UTF8NoBOM, true))
  213. {
  214. Header header = new Header();
  215. header.Magic = headerReader.ReadString();
  216. header.CacheFileVersion = headerReader.ReadInt32();
  217. header.FeatureInfo = headerReader.ReadUInt64();
  218. header.InfosLen = headerReader.ReadInt32();
  219. header.CodesLen = headerReader.ReadInt32();
  220. header.RelocsLen = headerReader.ReadInt32();
  221. header.UnwindInfosLen = headerReader.ReadInt32();
  222. return header;
  223. }
  224. }
  225. private static void InvalidateCompressedStream(FileStream compressedStream)
  226. {
  227. compressedStream.SetLength(0L);
  228. }
  229. private static void PreSave(object state)
  230. {
  231. _waitEvent.Reset();
  232. string fileNameActual = String.Concat(CachePathActual, ".cache");
  233. string fileNameBackup = String.Concat(CachePathBackup, ".cache");
  234. FileInfo fileInfoActual = new FileInfo(fileNameActual);
  235. if (fileInfoActual.Exists && fileInfoActual.Length != 0L)
  236. {
  237. File.Copy(fileNameActual, fileNameBackup, true);
  238. }
  239. Save(fileNameActual);
  240. _waitEvent.Set();
  241. }
  242. private static void Save(string fileName)
  243. {
  244. using (MemoryStream stream = new MemoryStream())
  245. using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
  246. {
  247. int hashSize = md5.HashSize / 8;
  248. stream.Seek((long)hashSize, SeekOrigin.Begin);
  249. WriteHeader(stream);
  250. _infosStream.WriteTo(stream);
  251. _codesStream.WriteTo(stream);
  252. _relocsStream.WriteTo(stream);
  253. _unwindInfosStream.WriteTo(stream);
  254. _binaryFormatter.Serialize(stream, PtcJumpTable);
  255. stream.Seek((long)hashSize, SeekOrigin.Begin);
  256. byte[] hash = md5.ComputeHash(stream);
  257. stream.Seek(0L, SeekOrigin.Begin);
  258. stream.Write(hash, 0, hashSize);
  259. using (FileStream compressedStream = new FileStream(fileName, FileMode.OpenOrCreate))
  260. using (DeflateStream deflateStream = new DeflateStream(compressedStream, SaveCompressionLevel, true))
  261. {
  262. try
  263. {
  264. stream.WriteTo(deflateStream);
  265. }
  266. catch
  267. {
  268. compressedStream.Position = 0L;
  269. }
  270. if (compressedStream.Position < compressedStream.Length)
  271. {
  272. compressedStream.SetLength(compressedStream.Position);
  273. }
  274. }
  275. }
  276. }
  277. private static void WriteHeader(MemoryStream stream)
  278. {
  279. using (BinaryWriter headerWriter = new BinaryWriter(stream, EncodingCache.UTF8NoBOM, true))
  280. {
  281. headerWriter.Write((string)HeaderMagic); // Header.Magic
  282. headerWriter.Write((int)InternalVersion); // Header.CacheFileVersion
  283. headerWriter.Write((ulong)GetFeatureInfo()); // Header.FeatureInfo
  284. headerWriter.Write((int)_infosStream.Length); // Header.InfosLen
  285. headerWriter.Write((int)_codesStream.Length); // Header.CodesLen
  286. headerWriter.Write((int)_relocsStream.Length); // Header.RelocsLen
  287. headerWriter.Write((int)_unwindInfosStream.Length); // Header.UnwindInfosLen
  288. }
  289. }
  290. internal static void LoadTranslations(ConcurrentDictionary<ulong, TranslatedFunction> funcs, IntPtr pageTablePointer, JumpTable jumpTable)
  291. {
  292. if ((int)_infosStream.Length == 0 ||
  293. (int)_codesStream.Length == 0 ||
  294. (int)_relocsStream.Length == 0 ||
  295. (int)_unwindInfosStream.Length == 0)
  296. {
  297. return;
  298. }
  299. Debug.Assert(funcs.Count == 0);
  300. _infosStream.Seek(0L, SeekOrigin.Begin);
  301. _codesStream.Seek(0L, SeekOrigin.Begin);
  302. _relocsStream.Seek(0L, SeekOrigin.Begin);
  303. _unwindInfosStream.Seek(0L, SeekOrigin.Begin);
  304. using (BinaryReader infosReader = new BinaryReader(_infosStream, EncodingCache.UTF8NoBOM, true))
  305. using (BinaryReader codesReader = new BinaryReader(_codesStream, EncodingCache.UTF8NoBOM, true))
  306. using (BinaryReader relocsReader = new BinaryReader(_relocsStream, EncodingCache.UTF8NoBOM, true))
  307. using (BinaryReader unwindInfosReader = new BinaryReader(_unwindInfosStream, EncodingCache.UTF8NoBOM, true))
  308. {
  309. int infosEntriesCount = (int)_infosStream.Length / InfoEntry.Stride;
  310. for (int i = 0; i < infosEntriesCount; i++)
  311. {
  312. InfoEntry infoEntry = ReadInfo(infosReader);
  313. byte[] code = ReadCode(codesReader, infoEntry.CodeLen);
  314. if (infoEntry.RelocEntriesCount != 0)
  315. {
  316. RelocEntry[] relocEntries = GetRelocEntries(relocsReader, infoEntry.RelocEntriesCount);
  317. PatchCode(code, relocEntries, pageTablePointer, jumpTable);
  318. }
  319. UnwindInfo unwindInfo = ReadUnwindInfo(unwindInfosReader);
  320. TranslatedFunction func = FastTranslate(code, unwindInfo, infoEntry.HighCq);
  321. funcs.AddOrUpdate((ulong)infoEntry.Address, func, (key, oldFunc) => func.HighCq && !oldFunc.HighCq ? func : oldFunc);
  322. }
  323. }
  324. if (_infosStream.Position < _infosStream.Length ||
  325. _codesStream.Position < _codesStream.Length ||
  326. _relocsStream.Position < _relocsStream.Length ||
  327. _unwindInfosStream.Position < _unwindInfosStream.Length)
  328. {
  329. throw new Exception("Could not reach the end of one or more memory streams.");
  330. }
  331. jumpTable.Initialize(PtcJumpTable, funcs);
  332. PtcJumpTable.WriteJumpTable(jumpTable, funcs);
  333. PtcJumpTable.WriteDynamicTable(jumpTable);
  334. }
  335. private static InfoEntry ReadInfo(BinaryReader infosReader)
  336. {
  337. InfoEntry infoEntry = new InfoEntry();
  338. infoEntry.Address = infosReader.ReadInt64();
  339. infoEntry.HighCq = infosReader.ReadBoolean();
  340. infoEntry.CodeLen = infosReader.ReadInt32();
  341. infoEntry.RelocEntriesCount = infosReader.ReadInt32();
  342. return infoEntry;
  343. }
  344. private static byte[] ReadCode(BinaryReader codesReader, int codeLen)
  345. {
  346. byte[] codeBuf = new byte[codeLen];
  347. codesReader.Read(codeBuf, 0, codeLen);
  348. return codeBuf;
  349. }
  350. private static RelocEntry[] GetRelocEntries(BinaryReader relocsReader, int relocEntriesCount)
  351. {
  352. RelocEntry[] relocEntries = new RelocEntry[relocEntriesCount];
  353. for (int i = 0; i < relocEntriesCount; i++)
  354. {
  355. int position = relocsReader.ReadInt32();
  356. int index = relocsReader.ReadInt32();
  357. relocEntries[i] = new RelocEntry(position, index);
  358. }
  359. return relocEntries;
  360. }
  361. private static void PatchCode(Span<byte> code, RelocEntry[] relocEntries, IntPtr pageTablePointer, JumpTable jumpTable)
  362. {
  363. foreach (RelocEntry relocEntry in relocEntries)
  364. {
  365. ulong imm;
  366. if (relocEntry.Index == PageTablePointerIndex)
  367. {
  368. imm = (ulong)pageTablePointer.ToInt64();
  369. }
  370. else if (relocEntry.Index == JumpPointerIndex)
  371. {
  372. imm = (ulong)jumpTable.JumpPointer.ToInt64();
  373. }
  374. else if (relocEntry.Index == DynamicPointerIndex)
  375. {
  376. imm = (ulong)jumpTable.DynamicPointer.ToInt64();
  377. }
  378. else if (Delegates.TryGetDelegateFuncPtrByIndex(relocEntry.Index, out IntPtr funcPtr))
  379. {
  380. imm = (ulong)funcPtr.ToInt64();
  381. }
  382. else
  383. {
  384. throw new Exception($"Unexpected reloc entry {relocEntry}.");
  385. }
  386. BinaryPrimitives.WriteUInt64LittleEndian(code.Slice(relocEntry.Position, 8), imm);
  387. }
  388. }
  389. private static UnwindInfo ReadUnwindInfo(BinaryReader unwindInfosReader)
  390. {
  391. int pushEntriesLength = unwindInfosReader.ReadInt32();
  392. UnwindPushEntry[] pushEntries = new UnwindPushEntry[pushEntriesLength];
  393. for (int i = 0; i < pushEntriesLength; i++)
  394. {
  395. int pseudoOp = unwindInfosReader.ReadInt32();
  396. int prologOffset = unwindInfosReader.ReadInt32();
  397. int regIndex = unwindInfosReader.ReadInt32();
  398. int stackOffsetOrAllocSize = unwindInfosReader.ReadInt32();
  399. pushEntries[i] = new UnwindPushEntry((UnwindPseudoOp)pseudoOp, prologOffset, regIndex, stackOffsetOrAllocSize);
  400. }
  401. int prologueSize = unwindInfosReader.ReadInt32();
  402. return new UnwindInfo(pushEntries, prologueSize);
  403. }
  404. private static TranslatedFunction FastTranslate(byte[] code, UnwindInfo unwindInfo, bool highCq)
  405. {
  406. CompiledFunction cFunc = new CompiledFunction(code, unwindInfo);
  407. IntPtr codePtr = JitCache.Map(cFunc);
  408. GuestFunction gFunc = Marshal.GetDelegateForFunctionPointer<GuestFunction>(codePtr);
  409. TranslatedFunction tFunc = new TranslatedFunction(gFunc, highCq);
  410. return tFunc;
  411. }
  412. internal static void MakeAndSaveTranslations(ConcurrentDictionary<ulong, TranslatedFunction> funcs, IMemoryManager memory, JumpTable jumpTable)
  413. {
  414. if (PtcProfiler.ProfiledFuncs.Count == 0)
  415. {
  416. return;
  417. }
  418. _translateCount = 0;
  419. _rejitCount = 0;
  420. ThreadPool.QueueUserWorkItem(TranslationLogger, (funcs.Count, PtcProfiler.ProfiledFuncs.Count));
  421. int maxDegreeOfParallelism = (Environment.ProcessorCount * 3) / 4;
  422. Parallel.ForEach(PtcProfiler.ProfiledFuncs, new ParallelOptions { MaxDegreeOfParallelism = maxDegreeOfParallelism }, (item, state) =>
  423. {
  424. ulong address = item.Key;
  425. Debug.Assert(PtcProfiler.IsAddressInStaticCodeRange(address));
  426. if (!funcs.ContainsKey(address))
  427. {
  428. TranslatedFunction func = Translator.Translate(memory, jumpTable, address, item.Value.mode, item.Value.highCq);
  429. funcs.TryAdd(address, func);
  430. if (func.HighCq)
  431. {
  432. jumpTable.RegisterFunction(address, func);
  433. }
  434. Interlocked.Increment(ref _translateCount);
  435. }
  436. else if (item.Value.highCq && !funcs[address].HighCq)
  437. {
  438. TranslatedFunction func = Translator.Translate(memory, jumpTable, address, item.Value.mode, highCq: true);
  439. funcs[address] = func;
  440. jumpTable.RegisterFunction(address, func);
  441. Interlocked.Increment(ref _rejitCount);
  442. }
  443. if (State != PtcState.Enabled)
  444. {
  445. state.Stop();
  446. }
  447. });
  448. _loggerEvent.Set();
  449. if (_translateCount != 0 || _rejitCount != 0)
  450. {
  451. PtcJumpTable.Initialize(jumpTable);
  452. PtcJumpTable.ReadJumpTable(jumpTable);
  453. PtcJumpTable.ReadDynamicTable(jumpTable);
  454. ThreadPool.QueueUserWorkItem(PreSave);
  455. }
  456. }
  457. private static void TranslationLogger(object state)
  458. {
  459. const int refreshRate = 1; // Seconds.
  460. (int funcsCount, int ProfiledFuncsCount) = ((int, int))state;
  461. do
  462. {
  463. Logger.Info?.Print(LogClass.Ptc, $"{funcsCount + _translateCount} of {ProfiledFuncsCount} functions to translate - {_rejitCount} functions rejited");
  464. }
  465. while (!_loggerEvent.WaitOne(refreshRate * 1000));
  466. Logger.Info?.Print(LogClass.Ptc, $"{funcsCount + _translateCount} of {ProfiledFuncsCount} functions to translate - {_rejitCount} functions rejited");
  467. }
  468. internal static void WriteInfoCodeReloc(long address, bool highCq, PtcInfo ptcInfo)
  469. {
  470. lock (_lock)
  471. {
  472. // WriteInfo.
  473. _infosWriter.Write((long)address); // InfoEntry.Address
  474. _infosWriter.Write((bool)highCq); // InfoEntry.HighCq
  475. _infosWriter.Write((int)ptcInfo.CodeStream.Length); // InfoEntry.CodeLen
  476. _infosWriter.Write((int)ptcInfo.RelocEntriesCount); // InfoEntry.RelocEntriesCount
  477. // WriteCode.
  478. ptcInfo.CodeStream.WriteTo(_codesStream);
  479. // WriteReloc.
  480. ptcInfo.RelocStream.WriteTo(_relocsStream);
  481. // WriteUnwindInfo.
  482. ptcInfo.UnwindInfoStream.WriteTo(_unwindInfosStream);
  483. }
  484. }
  485. private static ulong GetFeatureInfo()
  486. {
  487. ulong featureInfo = 0ul;
  488. featureInfo |= (Sse3.IsSupported ? 1ul : 0ul) << 0;
  489. featureInfo |= (Pclmulqdq.IsSupported ? 1ul : 0ul) << 1;
  490. featureInfo |= (Ssse3.IsSupported ? 1ul : 0ul) << 9;
  491. featureInfo |= (Fma.IsSupported ? 1ul : 0ul) << 12;
  492. featureInfo |= (Sse41.IsSupported ? 1ul : 0ul) << 19;
  493. featureInfo |= (Sse42.IsSupported ? 1ul : 0ul) << 20;
  494. featureInfo |= (Popcnt.IsSupported ? 1ul : 0ul) << 23;
  495. featureInfo |= (Aes.IsSupported ? 1ul : 0ul) << 25;
  496. featureInfo |= (Avx.IsSupported ? 1ul : 0ul) << 28;
  497. featureInfo |= (Sse.IsSupported ? 1ul : 0ul) << 57;
  498. featureInfo |= (Sse2.IsSupported ? 1ul : 0ul) << 58;
  499. return featureInfo;
  500. }
  501. private struct Header
  502. {
  503. public string Magic;
  504. public int CacheFileVersion;
  505. public ulong FeatureInfo;
  506. public int InfosLen;
  507. public int CodesLen;
  508. public int RelocsLen;
  509. public int UnwindInfosLen;
  510. }
  511. private struct InfoEntry
  512. {
  513. public const int Stride = 17; // Bytes.
  514. public long Address;
  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. }