Ptc.cs 38 KB

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