Ptc.cs 26 KB

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