Ptc.cs 37 KB

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