Ptc.cs 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107
  1. using ARMeilleure.CodeGen;
  2. using ARMeilleure.CodeGen.Unwinding;
  3. using ARMeilleure.CodeGen.X86;
  4. using ARMeilleure.Common;
  5. using ARMeilleure.Memory;
  6. using ARMeilleure.Translation.Cache;
  7. using Ryujinx.Common;
  8. using Ryujinx.Common.Configuration;
  9. using Ryujinx.Common.Logging;
  10. using System;
  11. using System.Buffers.Binary;
  12. using System.Collections.Concurrent;
  13. using System.Collections.Generic;
  14. using System.Diagnostics;
  15. using System.IO;
  16. using System.IO.Compression;
  17. using System.Runtime;
  18. using System.Runtime.CompilerServices;
  19. using System.Runtime.InteropServices;
  20. using System.Threading;
  21. using static ARMeilleure.Translation.PTC.PtcFormatter;
  22. namespace ARMeilleure.Translation.PTC
  23. {
  24. public static class Ptc
  25. {
  26. private const string OuterHeaderMagicString = "PTCohd\0\0";
  27. private const string InnerHeaderMagicString = "PTCihd\0\0";
  28. private const uint InternalVersion = 2289; //! To be incremented manually for each change to the ARMeilleure project.
  29. private const string ActualDir = "0";
  30. private const string BackupDir = "1";
  31. private const string TitleIdTextDefault = "0000000000000000";
  32. private const string DisplayVersionDefault = "0";
  33. internal const int PageTablePointerIndex = -1; // Must be a negative value.
  34. internal const int JumpPointerIndex = -2; // Must be a negative value.
  35. internal const int DynamicPointerIndex = -3; // Must be a negative value.
  36. internal const int CountTableIndex = -4; // Must be a negative value.
  37. private const byte FillingByte = 0x00;
  38. private const CompressionLevel SaveCompressionLevel = CompressionLevel.Fastest;
  39. // Carriers.
  40. private static MemoryStream _infosStream;
  41. private static List<byte[]> _codesList;
  42. private static MemoryStream _relocsStream;
  43. private static MemoryStream _unwindInfosStream;
  44. private static readonly ulong _outerHeaderMagic;
  45. private static readonly ulong _innerHeaderMagic;
  46. private static readonly ManualResetEvent _waitEvent;
  47. private static readonly object _lock;
  48. private static bool _disposed;
  49. internal static PtcJumpTable PtcJumpTable { get; private set; }
  50. internal static string TitleIdText { get; private set; }
  51. internal static string DisplayVersion { get; private set; }
  52. private static MemoryManagerMode _memoryMode;
  53. internal static string CachePathActual { get; private set; }
  54. internal static string CachePathBackup { get; private set; }
  55. internal static PtcState State { get; private set; }
  56. // Progress reporting helpers.
  57. private static volatile int _translateCount;
  58. private static volatile int _translateTotalCount;
  59. public static event Action<PtcLoadingState, int, int> PtcStateChanged;
  60. static Ptc()
  61. {
  62. InitializeCarriers();
  63. _outerHeaderMagic = BinaryPrimitives.ReadUInt64LittleEndian(EncodingCache.UTF8NoBOM.GetBytes(OuterHeaderMagicString).AsSpan());
  64. _innerHeaderMagic = BinaryPrimitives.ReadUInt64LittleEndian(EncodingCache.UTF8NoBOM.GetBytes(InnerHeaderMagicString).AsSpan());
  65. _waitEvent = new ManualResetEvent(true);
  66. _lock = new object();
  67. _disposed = false;
  68. PtcJumpTable = new PtcJumpTable();
  69. TitleIdText = TitleIdTextDefault;
  70. DisplayVersion = DisplayVersionDefault;
  71. CachePathActual = string.Empty;
  72. CachePathBackup = string.Empty;
  73. Disable();
  74. }
  75. public static void Initialize(string titleIdText, string displayVersion, bool enabled, MemoryManagerMode memoryMode)
  76. {
  77. Wait();
  78. PtcProfiler.Wait();
  79. PtcProfiler.ClearEntries();
  80. Logger.Info?.Print(LogClass.Ptc, $"Initializing Profiled Persistent Translation Cache (enabled: {enabled}).");
  81. if (!enabled || string.IsNullOrEmpty(titleIdText) || titleIdText == TitleIdTextDefault)
  82. {
  83. TitleIdText = TitleIdTextDefault;
  84. DisplayVersion = DisplayVersionDefault;
  85. CachePathActual = string.Empty;
  86. CachePathBackup = string.Empty;
  87. Disable();
  88. return;
  89. }
  90. TitleIdText = titleIdText;
  91. DisplayVersion = !string.IsNullOrEmpty(displayVersion) ? displayVersion : DisplayVersionDefault;
  92. _memoryMode = memoryMode;
  93. string workPathActual = Path.Combine(AppDataManager.GamesDirPath, TitleIdText, "cache", "cpu", ActualDir);
  94. string workPathBackup = Path.Combine(AppDataManager.GamesDirPath, TitleIdText, "cache", "cpu", BackupDir);
  95. if (!Directory.Exists(workPathActual))
  96. {
  97. Directory.CreateDirectory(workPathActual);
  98. }
  99. if (!Directory.Exists(workPathBackup))
  100. {
  101. Directory.CreateDirectory(workPathBackup);
  102. }
  103. CachePathActual = Path.Combine(workPathActual, DisplayVersion);
  104. CachePathBackup = Path.Combine(workPathBackup, DisplayVersion);
  105. PreLoad();
  106. PtcProfiler.PreLoad();
  107. Enable();
  108. }
  109. private static void InitializeCarriers()
  110. {
  111. _infosStream = new MemoryStream();
  112. _codesList = new List<byte[]>();
  113. _relocsStream = new MemoryStream();
  114. _unwindInfosStream = new MemoryStream();
  115. }
  116. private static void DisposeCarriers()
  117. {
  118. _infosStream.Dispose();
  119. _codesList.Clear();
  120. _relocsStream.Dispose();
  121. _unwindInfosStream.Dispose();
  122. }
  123. private static bool AreCarriersEmpty()
  124. {
  125. return _infosStream.Length == 0L && _codesList.Count == 0 && _relocsStream.Length == 0L && _unwindInfosStream.Length == 0L;
  126. }
  127. private static void ResetCarriersIfNeeded()
  128. {
  129. if (AreCarriersEmpty())
  130. {
  131. return;
  132. }
  133. DisposeCarriers();
  134. InitializeCarriers();
  135. }
  136. private static void PreLoad()
  137. {
  138. string fileNameActual = string.Concat(CachePathActual, ".cache");
  139. string fileNameBackup = string.Concat(CachePathBackup, ".cache");
  140. FileInfo fileInfoActual = new FileInfo(fileNameActual);
  141. FileInfo fileInfoBackup = new FileInfo(fileNameBackup);
  142. if (fileInfoActual.Exists && fileInfoActual.Length != 0L)
  143. {
  144. if (!Load(fileNameActual, false))
  145. {
  146. if (fileInfoBackup.Exists && fileInfoBackup.Length != 0L)
  147. {
  148. Load(fileNameBackup, true);
  149. }
  150. }
  151. }
  152. else if (fileInfoBackup.Exists && fileInfoBackup.Length != 0L)
  153. {
  154. Load(fileNameBackup, true);
  155. }
  156. }
  157. private static unsafe bool Load(string fileName, bool isBackup)
  158. {
  159. using (FileStream compressedStream = new(fileName, FileMode.Open))
  160. using (DeflateStream deflateStream = new(compressedStream, CompressionMode.Decompress, true))
  161. {
  162. OuterHeader outerHeader = DeserializeStructure<OuterHeader>(compressedStream);
  163. if (!outerHeader.IsHeaderValid())
  164. {
  165. InvalidateCompressedStream(compressedStream);
  166. return false;
  167. }
  168. if (outerHeader.Magic != _outerHeaderMagic)
  169. {
  170. InvalidateCompressedStream(compressedStream);
  171. return false;
  172. }
  173. if (outerHeader.CacheFileVersion != InternalVersion)
  174. {
  175. InvalidateCompressedStream(compressedStream);
  176. return false;
  177. }
  178. if (outerHeader.Endianness != GetEndianness())
  179. {
  180. InvalidateCompressedStream(compressedStream);
  181. return false;
  182. }
  183. if (outerHeader.FeatureInfo != GetFeatureInfo())
  184. {
  185. InvalidateCompressedStream(compressedStream);
  186. return false;
  187. }
  188. if (outerHeader.MemoryManagerMode != GetMemoryManagerMode())
  189. {
  190. InvalidateCompressedStream(compressedStream);
  191. return false;
  192. }
  193. if (outerHeader.OSPlatform != GetOSPlatform())
  194. {
  195. InvalidateCompressedStream(compressedStream);
  196. return false;
  197. }
  198. IntPtr intPtr = IntPtr.Zero;
  199. try
  200. {
  201. intPtr = Marshal.AllocHGlobal(new IntPtr(outerHeader.UncompressedStreamSize));
  202. using (UnmanagedMemoryStream stream = new((byte*)intPtr.ToPointer(), outerHeader.UncompressedStreamSize, outerHeader.UncompressedStreamSize, FileAccess.ReadWrite))
  203. {
  204. try
  205. {
  206. deflateStream.CopyTo(stream);
  207. }
  208. catch
  209. {
  210. InvalidateCompressedStream(compressedStream);
  211. return false;
  212. }
  213. Debug.Assert(stream.Position == stream.Length);
  214. stream.Seek(0L, SeekOrigin.Begin);
  215. InnerHeader innerHeader = DeserializeStructure<InnerHeader>(stream);
  216. if (!innerHeader.IsHeaderValid())
  217. {
  218. InvalidateCompressedStream(compressedStream);
  219. return false;
  220. }
  221. if (innerHeader.Magic != _innerHeaderMagic)
  222. {
  223. InvalidateCompressedStream(compressedStream);
  224. return false;
  225. }
  226. ReadOnlySpan<byte> infosBytes = new(stream.PositionPointer, innerHeader.InfosLength);
  227. stream.Seek(innerHeader.InfosLength, SeekOrigin.Current);
  228. Hash128 infosHash = XXHash128.ComputeHash(infosBytes);
  229. if (innerHeader.InfosHash != infosHash)
  230. {
  231. InvalidateCompressedStream(compressedStream);
  232. return false;
  233. }
  234. ReadOnlySpan<byte> codesBytes = (int)innerHeader.CodesLength > 0 ? new(stream.PositionPointer, (int)innerHeader.CodesLength) : ReadOnlySpan<byte>.Empty;
  235. stream.Seek(innerHeader.CodesLength, SeekOrigin.Current);
  236. Hash128 codesHash = XXHash128.ComputeHash(codesBytes);
  237. if (innerHeader.CodesHash != codesHash)
  238. {
  239. InvalidateCompressedStream(compressedStream);
  240. return false;
  241. }
  242. ReadOnlySpan<byte> relocsBytes = new(stream.PositionPointer, innerHeader.RelocsLength);
  243. stream.Seek(innerHeader.RelocsLength, SeekOrigin.Current);
  244. Hash128 relocsHash = XXHash128.ComputeHash(relocsBytes);
  245. if (innerHeader.RelocsHash != relocsHash)
  246. {
  247. InvalidateCompressedStream(compressedStream);
  248. return false;
  249. }
  250. ReadOnlySpan<byte> unwindInfosBytes = new(stream.PositionPointer, innerHeader.UnwindInfosLength);
  251. stream.Seek(innerHeader.UnwindInfosLength, SeekOrigin.Current);
  252. Hash128 unwindInfosHash = XXHash128.ComputeHash(unwindInfosBytes);
  253. if (innerHeader.UnwindInfosHash != unwindInfosHash)
  254. {
  255. InvalidateCompressedStream(compressedStream);
  256. return false;
  257. }
  258. ReadOnlySpan<byte> ptcJumpTableBytes = new(stream.PositionPointer, innerHeader.PtcJumpTableLength);
  259. stream.Seek(innerHeader.PtcJumpTableLength, SeekOrigin.Current);
  260. Debug.Assert(stream.Position == stream.Length);
  261. Hash128 ptcJumpTableHash = XXHash128.ComputeHash(ptcJumpTableBytes);
  262. if (innerHeader.PtcJumpTableHash != ptcJumpTableHash)
  263. {
  264. InvalidateCompressedStream(compressedStream);
  265. return false;
  266. }
  267. stream.Seek((long)Unsafe.SizeOf<InnerHeader>(), SeekOrigin.Begin);
  268. _infosStream.Write(infosBytes);
  269. stream.Seek(innerHeader.InfosLength, SeekOrigin.Current);
  270. _codesList.ReadFrom(stream);
  271. _relocsStream.Write(relocsBytes);
  272. stream.Seek(innerHeader.RelocsLength, SeekOrigin.Current);
  273. _unwindInfosStream.Write(unwindInfosBytes);
  274. stream.Seek(innerHeader.UnwindInfosLength, SeekOrigin.Current);
  275. PtcJumpTable = PtcJumpTable.Deserialize(stream);
  276. Debug.Assert(stream.Position == stream.Length);
  277. }
  278. }
  279. finally
  280. {
  281. if (intPtr != IntPtr.Zero)
  282. {
  283. Marshal.FreeHGlobal(intPtr);
  284. }
  285. }
  286. }
  287. long fileSize = new FileInfo(fileName).Length;
  288. Logger.Info?.Print(LogClass.Ptc, $"{(isBackup ? "Loaded Backup Translation Cache" : "Loaded Translation Cache")} (size: {fileSize} bytes, translated functions: {GetEntriesCount()}).");
  289. return true;
  290. }
  291. private static void InvalidateCompressedStream(FileStream compressedStream)
  292. {
  293. compressedStream.SetLength(0L);
  294. }
  295. private static void PreSave()
  296. {
  297. _waitEvent.Reset();
  298. try
  299. {
  300. string fileNameActual = string.Concat(CachePathActual, ".cache");
  301. string fileNameBackup = string.Concat(CachePathBackup, ".cache");
  302. FileInfo fileInfoActual = new FileInfo(fileNameActual);
  303. if (fileInfoActual.Exists && fileInfoActual.Length != 0L)
  304. {
  305. File.Copy(fileNameActual, fileNameBackup, true);
  306. }
  307. Save(fileNameActual);
  308. }
  309. finally
  310. {
  311. ResetCarriersIfNeeded();
  312. PtcJumpTable.ClearIfNeeded();
  313. GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
  314. }
  315. _waitEvent.Set();
  316. }
  317. private static unsafe void Save(string fileName)
  318. {
  319. int translatedFuncsCount;
  320. InnerHeader innerHeader = new InnerHeader();
  321. innerHeader.Magic = _innerHeaderMagic;
  322. innerHeader.InfosLength = (int)_infosStream.Length;
  323. innerHeader.CodesLength = _codesList.Length();
  324. innerHeader.RelocsLength = (int)_relocsStream.Length;
  325. innerHeader.UnwindInfosLength = (int)_unwindInfosStream.Length;
  326. innerHeader.PtcJumpTableLength = PtcJumpTable.GetSerializeSize(PtcJumpTable);
  327. OuterHeader outerHeader = new OuterHeader();
  328. outerHeader.Magic = _outerHeaderMagic;
  329. outerHeader.CacheFileVersion = InternalVersion;
  330. outerHeader.Endianness = GetEndianness();
  331. outerHeader.FeatureInfo = GetFeatureInfo();
  332. outerHeader.MemoryManagerMode = GetMemoryManagerMode();
  333. outerHeader.OSPlatform = GetOSPlatform();
  334. outerHeader.UncompressedStreamSize =
  335. (long)Unsafe.SizeOf<InnerHeader>() +
  336. innerHeader.InfosLength +
  337. innerHeader.CodesLength +
  338. innerHeader.RelocsLength +
  339. innerHeader.UnwindInfosLength +
  340. innerHeader.PtcJumpTableLength;
  341. outerHeader.SetHeaderHash();
  342. IntPtr intPtr = IntPtr.Zero;
  343. try
  344. {
  345. intPtr = Marshal.AllocHGlobal(new IntPtr(outerHeader.UncompressedStreamSize));
  346. using (UnmanagedMemoryStream stream = new((byte*)intPtr.ToPointer(), outerHeader.UncompressedStreamSize, outerHeader.UncompressedStreamSize, FileAccess.ReadWrite))
  347. {
  348. stream.Seek((long)Unsafe.SizeOf<InnerHeader>(), SeekOrigin.Begin);
  349. ReadOnlySpan<byte> infosBytes = new(stream.PositionPointer, innerHeader.InfosLength);
  350. _infosStream.WriteTo(stream);
  351. ReadOnlySpan<byte> codesBytes = (int)innerHeader.CodesLength > 0 ? new(stream.PositionPointer, (int)innerHeader.CodesLength) : ReadOnlySpan<byte>.Empty;
  352. _codesList.WriteTo(stream);
  353. ReadOnlySpan<byte> relocsBytes = new(stream.PositionPointer, innerHeader.RelocsLength);
  354. _relocsStream.WriteTo(stream);
  355. ReadOnlySpan<byte> unwindInfosBytes = new(stream.PositionPointer, innerHeader.UnwindInfosLength);
  356. _unwindInfosStream.WriteTo(stream);
  357. ReadOnlySpan<byte> ptcJumpTableBytes = new(stream.PositionPointer, innerHeader.PtcJumpTableLength);
  358. PtcJumpTable.Serialize(stream, PtcJumpTable);
  359. Debug.Assert(stream.Position == stream.Length);
  360. innerHeader.InfosHash = XXHash128.ComputeHash(infosBytes);
  361. innerHeader.CodesHash = XXHash128.ComputeHash(codesBytes);
  362. innerHeader.RelocsHash = XXHash128.ComputeHash(relocsBytes);
  363. innerHeader.UnwindInfosHash = XXHash128.ComputeHash(unwindInfosBytes);
  364. innerHeader.PtcJumpTableHash = XXHash128.ComputeHash(ptcJumpTableBytes);
  365. innerHeader.SetHeaderHash();
  366. stream.Seek(0L, SeekOrigin.Begin);
  367. SerializeStructure(stream, innerHeader);
  368. translatedFuncsCount = GetEntriesCount();
  369. ResetCarriersIfNeeded();
  370. PtcJumpTable.ClearIfNeeded();
  371. using (FileStream compressedStream = new(fileName, FileMode.OpenOrCreate))
  372. using (DeflateStream deflateStream = new(compressedStream, SaveCompressionLevel, true))
  373. {
  374. try
  375. {
  376. SerializeStructure(compressedStream, outerHeader);
  377. stream.Seek(0L, SeekOrigin.Begin);
  378. stream.CopyTo(deflateStream);
  379. }
  380. catch
  381. {
  382. compressedStream.Position = 0L;
  383. }
  384. if (compressedStream.Position < compressedStream.Length)
  385. {
  386. compressedStream.SetLength(compressedStream.Position);
  387. }
  388. }
  389. }
  390. }
  391. finally
  392. {
  393. if (intPtr != IntPtr.Zero)
  394. {
  395. Marshal.FreeHGlobal(intPtr);
  396. }
  397. }
  398. long fileSize = new FileInfo(fileName).Length;
  399. if (fileSize != 0L)
  400. {
  401. Logger.Info?.Print(LogClass.Ptc, $"Saved Translation Cache (size: {fileSize} bytes, translated functions: {translatedFuncsCount}).");
  402. }
  403. }
  404. internal static void LoadTranslations(
  405. ConcurrentDictionary<ulong, TranslatedFunction> funcs,
  406. IMemoryManager memory,
  407. JumpTable jumpTable,
  408. EntryTable<uint> countTable)
  409. {
  410. if (AreCarriersEmpty())
  411. {
  412. return;
  413. }
  414. long infosStreamLength = _infosStream.Length;
  415. long relocsStreamLength = _relocsStream.Length;
  416. long unwindInfosStreamLength = _unwindInfosStream.Length;
  417. _infosStream.Seek(0L, SeekOrigin.Begin);
  418. _relocsStream.Seek(0L, SeekOrigin.Begin);
  419. _unwindInfosStream.Seek(0L, SeekOrigin.Begin);
  420. using (BinaryReader relocsReader = new(_relocsStream, EncodingCache.UTF8NoBOM, true))
  421. using (BinaryReader unwindInfosReader = new(_unwindInfosStream, EncodingCache.UTF8NoBOM, true))
  422. {
  423. for (int index = 0; index < GetEntriesCount(); index++)
  424. {
  425. InfoEntry infoEntry = DeserializeStructure<InfoEntry>(_infosStream);
  426. if (infoEntry.Stubbed)
  427. {
  428. SkipCode(index, infoEntry.CodeLength);
  429. SkipReloc(infoEntry.RelocEntriesCount);
  430. SkipUnwindInfo(unwindInfosReader);
  431. continue;
  432. }
  433. bool isEntryChanged = infoEntry.Hash != ComputeHash(memory, infoEntry.Address, infoEntry.GuestSize);
  434. if (isEntryChanged || (!infoEntry.HighCq && PtcProfiler.ProfiledFuncs.TryGetValue(infoEntry.Address, out var value) && value.HighCq))
  435. {
  436. infoEntry.Stubbed = true;
  437. infoEntry.CodeLength = 0;
  438. UpdateInfo(infoEntry);
  439. StubCode(index);
  440. StubReloc(infoEntry.RelocEntriesCount);
  441. StubUnwindInfo(unwindInfosReader);
  442. if (isEntryChanged)
  443. {
  444. PtcJumpTable.Clean(infoEntry.Address);
  445. Logger.Info?.Print(LogClass.Ptc, $"Invalidated translated function (address: 0x{infoEntry.Address:X16})");
  446. }
  447. continue;
  448. }
  449. byte[] code = ReadCode(index, infoEntry.CodeLength);
  450. Counter<uint> callCounter = null;
  451. if (infoEntry.RelocEntriesCount != 0)
  452. {
  453. RelocEntry[] relocEntries = GetRelocEntries(relocsReader, infoEntry.RelocEntriesCount);
  454. PatchCode(code, relocEntries, memory.PageTablePointer, jumpTable, countTable, out callCounter);
  455. }
  456. UnwindInfo unwindInfo = ReadUnwindInfo(unwindInfosReader);
  457. TranslatedFunction func = FastTranslate(code, callCounter, infoEntry.GuestSize, unwindInfo, infoEntry.HighCq);
  458. bool isAddressUnique = funcs.TryAdd(infoEntry.Address, func);
  459. Debug.Assert(isAddressUnique, $"The address 0x{infoEntry.Address:X16} is not unique.");
  460. }
  461. }
  462. if (_infosStream.Length != infosStreamLength || _infosStream.Position != infosStreamLength ||
  463. _relocsStream.Length != relocsStreamLength || _relocsStream.Position != relocsStreamLength ||
  464. _unwindInfosStream.Length != unwindInfosStreamLength || _unwindInfosStream.Position != unwindInfosStreamLength)
  465. {
  466. throw new Exception("The length of a memory stream has changed, or its position has not reached or has exceeded its end.");
  467. }
  468. jumpTable.Initialize(PtcJumpTable, funcs);
  469. PtcJumpTable.WriteJumpTable(jumpTable, funcs);
  470. PtcJumpTable.WriteDynamicTable(jumpTable);
  471. Logger.Info?.Print(LogClass.Ptc, $"{funcs.Count} translated functions loaded");
  472. }
  473. private static int GetEntriesCount()
  474. {
  475. return _codesList.Count;
  476. }
  477. [Conditional("DEBUG")]
  478. private static void SkipCode(int index, int codeLength)
  479. {
  480. Debug.Assert(_codesList[index].Length == 0);
  481. Debug.Assert(codeLength == 0);
  482. }
  483. private static void SkipReloc(int relocEntriesCount)
  484. {
  485. _relocsStream.Seek(relocEntriesCount * RelocEntry.Stride, SeekOrigin.Current);
  486. }
  487. private static void SkipUnwindInfo(BinaryReader unwindInfosReader)
  488. {
  489. int pushEntriesLength = unwindInfosReader.ReadInt32();
  490. _unwindInfosStream.Seek(pushEntriesLength * UnwindPushEntry.Stride + UnwindInfo.Stride, SeekOrigin.Current);
  491. }
  492. private static byte[] ReadCode(int index, int codeLength)
  493. {
  494. Debug.Assert(_codesList[index].Length == codeLength);
  495. return _codesList[index];
  496. }
  497. private static RelocEntry[] GetRelocEntries(BinaryReader relocsReader, int relocEntriesCount)
  498. {
  499. RelocEntry[] relocEntries = new RelocEntry[relocEntriesCount];
  500. for (int i = 0; i < relocEntriesCount; i++)
  501. {
  502. int position = relocsReader.ReadInt32();
  503. int index = relocsReader.ReadInt32();
  504. relocEntries[i] = new RelocEntry(position, index);
  505. }
  506. return relocEntries;
  507. }
  508. private static void PatchCode(
  509. Span<byte> code,
  510. RelocEntry[] relocEntries,
  511. IntPtr pageTablePointer,
  512. JumpTable jumpTable,
  513. EntryTable<uint> countTable,
  514. out Counter<uint> callCounter)
  515. {
  516. callCounter = null;
  517. foreach (RelocEntry relocEntry in relocEntries)
  518. {
  519. ulong imm;
  520. if (relocEntry.Index == PageTablePointerIndex)
  521. {
  522. imm = (ulong)pageTablePointer.ToInt64();
  523. }
  524. else if (relocEntry.Index == JumpPointerIndex)
  525. {
  526. imm = (ulong)jumpTable.JumpPointer.ToInt64();
  527. }
  528. else if (relocEntry.Index == DynamicPointerIndex)
  529. {
  530. imm = (ulong)jumpTable.DynamicPointer.ToInt64();
  531. }
  532. else if (relocEntry.Index == CountTableIndex)
  533. {
  534. callCounter = new Counter<uint>(countTable);
  535. unsafe { imm = (ulong)Unsafe.AsPointer(ref callCounter.Value); }
  536. }
  537. else if (Delegates.TryGetDelegateFuncPtrByIndex(relocEntry.Index, out IntPtr funcPtr))
  538. {
  539. imm = (ulong)funcPtr.ToInt64();
  540. }
  541. else
  542. {
  543. throw new Exception($"Unexpected reloc entry {relocEntry}.");
  544. }
  545. BinaryPrimitives.WriteUInt64LittleEndian(code.Slice(relocEntry.Position, 8), imm);
  546. }
  547. }
  548. private static UnwindInfo ReadUnwindInfo(BinaryReader unwindInfosReader)
  549. {
  550. int pushEntriesLength = unwindInfosReader.ReadInt32();
  551. UnwindPushEntry[] pushEntries = new UnwindPushEntry[pushEntriesLength];
  552. for (int i = 0; i < pushEntriesLength; i++)
  553. {
  554. int pseudoOp = unwindInfosReader.ReadInt32();
  555. int prologOffset = unwindInfosReader.ReadInt32();
  556. int regIndex = unwindInfosReader.ReadInt32();
  557. int stackOffsetOrAllocSize = unwindInfosReader.ReadInt32();
  558. pushEntries[i] = new UnwindPushEntry((UnwindPseudoOp)pseudoOp, prologOffset, regIndex, stackOffsetOrAllocSize);
  559. }
  560. int prologueSize = unwindInfosReader.ReadInt32();
  561. return new UnwindInfo(pushEntries, prologueSize);
  562. }
  563. private static TranslatedFunction FastTranslate(
  564. byte[] code,
  565. Counter<uint> callCounter,
  566. ulong guestSize,
  567. UnwindInfo unwindInfo,
  568. bool highCq)
  569. {
  570. CompiledFunction cFunc = new CompiledFunction(code, unwindInfo);
  571. IntPtr codePtr = JitCache.Map(cFunc);
  572. GuestFunction gFunc = Marshal.GetDelegateForFunctionPointer<GuestFunction>(codePtr);
  573. TranslatedFunction tFunc = new TranslatedFunction(gFunc, callCounter, guestSize, highCq);
  574. return tFunc;
  575. }
  576. private static void UpdateInfo(InfoEntry infoEntry)
  577. {
  578. _infosStream.Seek(-Unsafe.SizeOf<InfoEntry>(), SeekOrigin.Current);
  579. SerializeStructure(_infosStream, infoEntry);
  580. }
  581. private static void StubCode(int index)
  582. {
  583. _codesList[index] = Array.Empty<byte>();
  584. }
  585. private static void StubReloc(int relocEntriesCount)
  586. {
  587. for (int i = 0; i < relocEntriesCount * RelocEntry.Stride; i++)
  588. {
  589. _relocsStream.WriteByte(FillingByte);
  590. }
  591. }
  592. private static void StubUnwindInfo(BinaryReader unwindInfosReader)
  593. {
  594. int pushEntriesLength = unwindInfosReader.ReadInt32();
  595. for (int i = 0; i < pushEntriesLength * UnwindPushEntry.Stride + UnwindInfo.Stride; i++)
  596. {
  597. _unwindInfosStream.WriteByte(FillingByte);
  598. }
  599. }
  600. internal static void MakeAndSaveTranslations(
  601. ConcurrentDictionary<ulong, TranslatedFunction> funcs,
  602. IMemoryManager memory,
  603. JumpTable jumpTable,
  604. EntryTable<uint> countTable)
  605. {
  606. var profiledFuncsToTranslate = PtcProfiler.GetProfiledFuncsToTranslate(funcs);
  607. _translateCount = 0;
  608. _translateTotalCount = profiledFuncsToTranslate.Count;
  609. int degreeOfParallelism = new DegreeOfParallelism(4d, 75d, 12.5d).GetDegreeOfParallelism(0, 32);
  610. if (_translateTotalCount == 0 || degreeOfParallelism == 0)
  611. {
  612. ResetCarriersIfNeeded();
  613. PtcJumpTable.ClearIfNeeded();
  614. GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
  615. return;
  616. }
  617. Logger.Info?.Print(LogClass.Ptc, $"{_translateCount} of {_translateTotalCount} functions translated | Thread count: {degreeOfParallelism}");
  618. PtcStateChanged?.Invoke(PtcLoadingState.Start, _translateCount, _translateTotalCount);
  619. using AutoResetEvent progressReportEvent = new AutoResetEvent(false);
  620. Thread progressReportThread = new Thread(ReportProgress)
  621. {
  622. Name = "Ptc.ProgressReporter",
  623. Priority = ThreadPriority.Lowest,
  624. IsBackground = true
  625. };
  626. progressReportThread.Start(progressReportEvent);
  627. void TranslateFuncs()
  628. {
  629. while (profiledFuncsToTranslate.TryDequeue(out var item))
  630. {
  631. ulong address = item.address;
  632. Debug.Assert(PtcProfiler.IsAddressInStaticCodeRange(address));
  633. TranslatedFunction func = Translator.Translate(memory, jumpTable, countTable, address, item.funcProfile.Mode, item.funcProfile.HighCq);
  634. bool isAddressUnique = funcs.TryAdd(address, func);
  635. Debug.Assert(isAddressUnique, $"The address 0x{address:X16} is not unique.");
  636. if (func.HighCq)
  637. {
  638. jumpTable.RegisterFunction(address, func);
  639. }
  640. Interlocked.Increment(ref _translateCount);
  641. if (State != PtcState.Enabled)
  642. {
  643. break;
  644. }
  645. }
  646. Translator.DisposePools();
  647. }
  648. List<Thread> threads = new List<Thread>();
  649. for (int i = 0; i < degreeOfParallelism; i++)
  650. {
  651. Thread thread = new Thread(TranslateFuncs);
  652. thread.IsBackground = true;
  653. threads.Add(thread);
  654. }
  655. threads.ForEach((thread) => thread.Start());
  656. threads.ForEach((thread) => thread.Join());
  657. threads.Clear();
  658. progressReportEvent.Set();
  659. progressReportThread.Join();
  660. PtcStateChanged?.Invoke(PtcLoadingState.Loaded, _translateCount, _translateTotalCount);
  661. Logger.Info?.Print(LogClass.Ptc, $"{_translateCount} of {_translateTotalCount} functions translated | Thread count: {degreeOfParallelism}");
  662. PtcJumpTable.Initialize(jumpTable);
  663. PtcJumpTable.ReadJumpTable(jumpTable);
  664. PtcJumpTable.ReadDynamicTable(jumpTable);
  665. Thread preSaveThread = new Thread(PreSave);
  666. preSaveThread.IsBackground = true;
  667. preSaveThread.Start();
  668. }
  669. private static void ReportProgress(object state)
  670. {
  671. const int refreshRate = 50; // ms.
  672. AutoResetEvent endEvent = (AutoResetEvent)state;
  673. int count = 0;
  674. do
  675. {
  676. int newCount = _translateCount;
  677. if (count != newCount)
  678. {
  679. PtcStateChanged?.Invoke(PtcLoadingState.Loading, newCount, _translateTotalCount);
  680. count = newCount;
  681. }
  682. }
  683. while (!endEvent.WaitOne(refreshRate));
  684. }
  685. internal static Hash128 ComputeHash(IMemoryManager memory, ulong address, ulong guestSize)
  686. {
  687. return XXHash128.ComputeHash(memory.GetSpan(address, checked((int)(guestSize))));
  688. }
  689. internal static void WriteInfoCodeRelocUnwindInfo(ulong address, ulong guestSize, Hash128 hash, bool highCq, PtcInfo ptcInfo)
  690. {
  691. lock (_lock)
  692. {
  693. InfoEntry infoEntry = new InfoEntry();
  694. infoEntry.Address = address;
  695. infoEntry.GuestSize = guestSize;
  696. infoEntry.Hash = hash;
  697. infoEntry.HighCq = highCq;
  698. infoEntry.Stubbed = false;
  699. infoEntry.CodeLength = ptcInfo.Code.Length;
  700. infoEntry.RelocEntriesCount = ptcInfo.RelocEntriesCount;
  701. SerializeStructure(_infosStream, infoEntry);
  702. WriteCode(ptcInfo.Code.AsSpan());
  703. // WriteReloc.
  704. ptcInfo.RelocStream.WriteTo(_relocsStream);
  705. // WriteUnwindInfo.
  706. ptcInfo.UnwindInfoStream.WriteTo(_unwindInfosStream);
  707. }
  708. }
  709. private static void WriteCode(ReadOnlySpan<byte> code)
  710. {
  711. _codesList.Add(code.ToArray());
  712. }
  713. internal static bool GetEndianness()
  714. {
  715. return BitConverter.IsLittleEndian;
  716. }
  717. private static ulong GetFeatureInfo()
  718. {
  719. return (ulong)HardwareCapabilities.FeatureInfoEdx << 32 | (uint)HardwareCapabilities.FeatureInfoEcx;
  720. }
  721. private static byte GetMemoryManagerMode()
  722. {
  723. return (byte)_memoryMode;
  724. }
  725. private static uint GetOSPlatform()
  726. {
  727. uint osPlatform = 0u;
  728. osPlatform |= (RuntimeInformation.IsOSPlatform(OSPlatform.FreeBSD) ? 1u : 0u) << 0;
  729. osPlatform |= (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? 1u : 0u) << 1;
  730. osPlatform |= (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? 1u : 0u) << 2;
  731. osPlatform |= (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? 1u : 0u) << 3;
  732. return osPlatform;
  733. }
  734. [StructLayout(LayoutKind.Sequential, Pack = 1/*, Size = 50*/)]
  735. private struct OuterHeader
  736. {
  737. public ulong Magic;
  738. public uint CacheFileVersion;
  739. public bool Endianness;
  740. public ulong FeatureInfo;
  741. public byte MemoryManagerMode;
  742. public uint OSPlatform;
  743. public long UncompressedStreamSize;
  744. public Hash128 HeaderHash;
  745. public void SetHeaderHash()
  746. {
  747. Span<OuterHeader> spanHeader = MemoryMarshal.CreateSpan(ref this, 1);
  748. HeaderHash = XXHash128.ComputeHash(MemoryMarshal.AsBytes(spanHeader).Slice(0, Unsafe.SizeOf<OuterHeader>() - Unsafe.SizeOf<Hash128>()));
  749. }
  750. public bool IsHeaderValid()
  751. {
  752. Span<OuterHeader> spanHeader = MemoryMarshal.CreateSpan(ref this, 1);
  753. return XXHash128.ComputeHash(MemoryMarshal.AsBytes(spanHeader).Slice(0, Unsafe.SizeOf<OuterHeader>() - Unsafe.SizeOf<Hash128>())) == HeaderHash;
  754. }
  755. }
  756. [StructLayout(LayoutKind.Sequential, Pack = 1/*, Size = 128*/)]
  757. private struct InnerHeader
  758. {
  759. public ulong Magic;
  760. public int InfosLength;
  761. public long CodesLength;
  762. public int RelocsLength;
  763. public int UnwindInfosLength;
  764. public int PtcJumpTableLength;
  765. public Hash128 InfosHash;
  766. public Hash128 CodesHash;
  767. public Hash128 RelocsHash;
  768. public Hash128 UnwindInfosHash;
  769. public Hash128 PtcJumpTableHash;
  770. public Hash128 HeaderHash;
  771. public void SetHeaderHash()
  772. {
  773. Span<InnerHeader> spanHeader = MemoryMarshal.CreateSpan(ref this, 1);
  774. HeaderHash = XXHash128.ComputeHash(MemoryMarshal.AsBytes(spanHeader).Slice(0, Unsafe.SizeOf<InnerHeader>() - Unsafe.SizeOf<Hash128>()));
  775. }
  776. public bool IsHeaderValid()
  777. {
  778. Span<InnerHeader> spanHeader = MemoryMarshal.CreateSpan(ref this, 1);
  779. return XXHash128.ComputeHash(MemoryMarshal.AsBytes(spanHeader).Slice(0, Unsafe.SizeOf<InnerHeader>() - Unsafe.SizeOf<Hash128>())) == HeaderHash;
  780. }
  781. }
  782. [StructLayout(LayoutKind.Sequential, Pack = 1/*, Size = 42*/)]
  783. private struct InfoEntry
  784. {
  785. public ulong Address;
  786. public ulong GuestSize;
  787. public Hash128 Hash;
  788. public bool HighCq;
  789. public bool Stubbed;
  790. public int CodeLength;
  791. public int RelocEntriesCount;
  792. }
  793. private static void Enable()
  794. {
  795. State = PtcState.Enabled;
  796. }
  797. public static void Continue()
  798. {
  799. if (State == PtcState.Enabled)
  800. {
  801. State = PtcState.Continuing;
  802. }
  803. }
  804. public static void Close()
  805. {
  806. if (State == PtcState.Enabled ||
  807. State == PtcState.Continuing)
  808. {
  809. State = PtcState.Closing;
  810. }
  811. }
  812. internal static void Disable()
  813. {
  814. State = PtcState.Disabled;
  815. }
  816. private static void Wait()
  817. {
  818. _waitEvent.WaitOne();
  819. }
  820. public static void Dispose()
  821. {
  822. if (!_disposed)
  823. {
  824. _disposed = true;
  825. Wait();
  826. _waitEvent.Dispose();
  827. DisposeCarriers();
  828. }
  829. }
  830. }
  831. }