Ptc.cs 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070
  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.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 = 2571; //! 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, 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. callCounter = new Counter<uint>(translator.CountTable);
  512. unsafe { imm = (IntPtr)Unsafe.AsPointer(ref callCounter.Value); }
  513. }
  514. else if (symbol == DispatchStubSymbol)
  515. {
  516. imm = translator.Stubs.DispatchStub;
  517. }
  518. if (imm == null)
  519. {
  520. throw new Exception($"Unexpected reloc entry {relocEntry}.");
  521. }
  522. BinaryPrimitives.WriteUInt64LittleEndian(code.Slice(relocEntry.Position, 8), (ulong)imm.Value);
  523. }
  524. }
  525. private static UnwindInfo ReadUnwindInfo(BinaryReader unwindInfosReader)
  526. {
  527. int pushEntriesLength = unwindInfosReader.ReadInt32();
  528. UnwindPushEntry[] pushEntries = new UnwindPushEntry[pushEntriesLength];
  529. for (int i = 0; i < pushEntriesLength; i++)
  530. {
  531. int pseudoOp = unwindInfosReader.ReadInt32();
  532. int prologOffset = unwindInfosReader.ReadInt32();
  533. int regIndex = unwindInfosReader.ReadInt32();
  534. int stackOffsetOrAllocSize = unwindInfosReader.ReadInt32();
  535. pushEntries[i] = new UnwindPushEntry((UnwindPseudoOp)pseudoOp, prologOffset, regIndex, stackOffsetOrAllocSize);
  536. }
  537. int prologueSize = unwindInfosReader.ReadInt32();
  538. return new UnwindInfo(pushEntries, prologueSize);
  539. }
  540. private static TranslatedFunction FastTranslate(
  541. byte[] code,
  542. Counter<uint> callCounter,
  543. ulong guestSize,
  544. UnwindInfo unwindInfo,
  545. bool highCq)
  546. {
  547. CompiledFunction cFunc = new CompiledFunction(code, unwindInfo);
  548. IntPtr codePtr = JitCache.Map(cFunc);
  549. GuestFunction gFunc = Marshal.GetDelegateForFunctionPointer<GuestFunction>(codePtr);
  550. TranslatedFunction tFunc = new TranslatedFunction(gFunc, callCounter, guestSize, highCq);
  551. return tFunc;
  552. }
  553. private static void UpdateInfo(InfoEntry infoEntry)
  554. {
  555. _infosStream.Seek(-Unsafe.SizeOf<InfoEntry>(), SeekOrigin.Current);
  556. SerializeStructure(_infosStream, infoEntry);
  557. }
  558. private static void StubCode(int index)
  559. {
  560. _codesList[index] = Array.Empty<byte>();
  561. }
  562. private static void StubReloc(int relocEntriesCount)
  563. {
  564. for (int i = 0; i < relocEntriesCount * RelocEntry.Stride; i++)
  565. {
  566. _relocsStream.WriteByte(FillingByte);
  567. }
  568. }
  569. private static void StubUnwindInfo(BinaryReader unwindInfosReader)
  570. {
  571. int pushEntriesLength = unwindInfosReader.ReadInt32();
  572. for (int i = 0; i < pushEntriesLength * UnwindPushEntry.Stride + UnwindInfo.Stride; i++)
  573. {
  574. _unwindInfosStream.WriteByte(FillingByte);
  575. }
  576. }
  577. internal static void MakeAndSaveTranslations(Translator translator)
  578. {
  579. var profiledFuncsToTranslate = PtcProfiler.GetProfiledFuncsToTranslate(translator.Functions);
  580. _translateCount = 0;
  581. _translateTotalCount = profiledFuncsToTranslate.Count;
  582. if (_translateTotalCount == 0)
  583. {
  584. ResetCarriersIfNeeded();
  585. GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
  586. return;
  587. }
  588. int degreeOfParallelism = Environment.ProcessorCount;
  589. // If there are enough cores lying around, we leave one alone for other tasks.
  590. if (degreeOfParallelism > 4)
  591. {
  592. degreeOfParallelism--;
  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(address, item.funcProfile.Mode, item.funcProfile.HighCq);
  611. bool isAddressUnique = translator.Functions.TryAdd(address, func);
  612. Debug.Assert(isAddressUnique, $"The address 0x{address:X16} is not unique.");
  613. Interlocked.Increment(ref _translateCount);
  614. translator.RegisterFunction(address, func);
  615. if (State != PtcState.Enabled)
  616. {
  617. break;
  618. }
  619. }
  620. }
  621. List<Thread> threads = new List<Thread>();
  622. for (int i = 0; i < degreeOfParallelism; i++)
  623. {
  624. Thread thread = new Thread(TranslateFuncs);
  625. thread.IsBackground = true;
  626. threads.Add(thread);
  627. }
  628. Stopwatch sw = Stopwatch.StartNew();
  629. threads.ForEach((thread) => thread.Start());
  630. threads.ForEach((thread) => thread.Join());
  631. threads.Clear();
  632. progressReportEvent.Set();
  633. progressReportThread.Join();
  634. sw.Stop();
  635. PtcStateChanged?.Invoke(PtcLoadingState.Loaded, _translateCount, _translateTotalCount);
  636. Logger.Info?.Print(LogClass.Ptc, $"{_translateCount} of {_translateTotalCount} functions translated | Thread count: {degreeOfParallelism} in {sw.Elapsed.TotalSeconds} s");
  637. Thread preSaveThread = new Thread(PreSave);
  638. preSaveThread.IsBackground = true;
  639. preSaveThread.Start();
  640. }
  641. private static void ReportProgress(object state)
  642. {
  643. const int refreshRate = 50; // ms.
  644. AutoResetEvent endEvent = (AutoResetEvent)state;
  645. int count = 0;
  646. do
  647. {
  648. int newCount = _translateCount;
  649. if (count != newCount)
  650. {
  651. PtcStateChanged?.Invoke(PtcLoadingState.Loading, newCount, _translateTotalCount);
  652. count = newCount;
  653. }
  654. }
  655. while (!endEvent.WaitOne(refreshRate));
  656. }
  657. internal static Hash128 ComputeHash(IMemoryManager memory, ulong address, ulong guestSize)
  658. {
  659. return XXHash128.ComputeHash(memory.GetSpan(address, checked((int)(guestSize))));
  660. }
  661. internal static void WriteInfoCodeRelocUnwindInfo(ulong address, ulong guestSize, Hash128 hash, bool highCq, PtcInfo ptcInfo)
  662. {
  663. lock (_lock)
  664. {
  665. InfoEntry infoEntry = new InfoEntry();
  666. infoEntry.Address = address;
  667. infoEntry.GuestSize = guestSize;
  668. infoEntry.Hash = hash;
  669. infoEntry.HighCq = highCq;
  670. infoEntry.Stubbed = false;
  671. infoEntry.CodeLength = ptcInfo.Code.Length;
  672. infoEntry.RelocEntriesCount = ptcInfo.RelocEntriesCount;
  673. SerializeStructure(_infosStream, infoEntry);
  674. WriteCode(ptcInfo.Code.AsSpan());
  675. // WriteReloc.
  676. ptcInfo.RelocStream.WriteTo(_relocsStream);
  677. // WriteUnwindInfo.
  678. ptcInfo.UnwindInfoStream.WriteTo(_unwindInfosStream);
  679. }
  680. }
  681. private static void WriteCode(ReadOnlySpan<byte> code)
  682. {
  683. _codesList.Add(code.ToArray());
  684. }
  685. internal static bool GetEndianness()
  686. {
  687. return BitConverter.IsLittleEndian;
  688. }
  689. private static ulong GetFeatureInfo()
  690. {
  691. return (ulong)HardwareCapabilities.FeatureInfoEdx << 32 | (uint)HardwareCapabilities.FeatureInfoEcx;
  692. }
  693. private static byte GetMemoryManagerMode()
  694. {
  695. return (byte)_memoryMode;
  696. }
  697. private static uint GetOSPlatform()
  698. {
  699. uint osPlatform = 0u;
  700. osPlatform |= (RuntimeInformation.IsOSPlatform(OSPlatform.FreeBSD) ? 1u : 0u) << 0;
  701. osPlatform |= (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? 1u : 0u) << 1;
  702. osPlatform |= (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? 1u : 0u) << 2;
  703. osPlatform |= (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? 1u : 0u) << 3;
  704. return osPlatform;
  705. }
  706. [StructLayout(LayoutKind.Sequential, Pack = 1/*, Size = 50*/)]
  707. private struct OuterHeader
  708. {
  709. public ulong Magic;
  710. public uint CacheFileVersion;
  711. public bool Endianness;
  712. public ulong FeatureInfo;
  713. public byte MemoryManagerMode;
  714. public uint OSPlatform;
  715. public long UncompressedStreamSize;
  716. public Hash128 HeaderHash;
  717. public void SetHeaderHash()
  718. {
  719. Span<OuterHeader> spanHeader = MemoryMarshal.CreateSpan(ref this, 1);
  720. HeaderHash = XXHash128.ComputeHash(MemoryMarshal.AsBytes(spanHeader).Slice(0, Unsafe.SizeOf<OuterHeader>() - Unsafe.SizeOf<Hash128>()));
  721. }
  722. public bool IsHeaderValid()
  723. {
  724. Span<OuterHeader> spanHeader = MemoryMarshal.CreateSpan(ref this, 1);
  725. return XXHash128.ComputeHash(MemoryMarshal.AsBytes(spanHeader).Slice(0, Unsafe.SizeOf<OuterHeader>() - Unsafe.SizeOf<Hash128>())) == HeaderHash;
  726. }
  727. }
  728. [StructLayout(LayoutKind.Sequential, Pack = 1/*, Size = 128*/)]
  729. private struct InnerHeader
  730. {
  731. public ulong Magic;
  732. public int InfosLength;
  733. public long CodesLength;
  734. public int RelocsLength;
  735. public int UnwindInfosLength;
  736. public Hash128 InfosHash;
  737. public Hash128 CodesHash;
  738. public Hash128 RelocsHash;
  739. public Hash128 UnwindInfosHash;
  740. public Hash128 HeaderHash;
  741. public void SetHeaderHash()
  742. {
  743. Span<InnerHeader> spanHeader = MemoryMarshal.CreateSpan(ref this, 1);
  744. HeaderHash = XXHash128.ComputeHash(MemoryMarshal.AsBytes(spanHeader).Slice(0, Unsafe.SizeOf<InnerHeader>() - Unsafe.SizeOf<Hash128>()));
  745. }
  746. public bool IsHeaderValid()
  747. {
  748. Span<InnerHeader> spanHeader = MemoryMarshal.CreateSpan(ref this, 1);
  749. return XXHash128.ComputeHash(MemoryMarshal.AsBytes(spanHeader).Slice(0, Unsafe.SizeOf<InnerHeader>() - Unsafe.SizeOf<Hash128>())) == HeaderHash;
  750. }
  751. }
  752. [StructLayout(LayoutKind.Sequential, Pack = 1/*, Size = 42*/)]
  753. private struct InfoEntry
  754. {
  755. public ulong Address;
  756. public ulong GuestSize;
  757. public Hash128 Hash;
  758. public bool HighCq;
  759. public bool Stubbed;
  760. public int CodeLength;
  761. public int RelocEntriesCount;
  762. }
  763. private static void Enable()
  764. {
  765. State = PtcState.Enabled;
  766. }
  767. public static void Continue()
  768. {
  769. if (State == PtcState.Enabled)
  770. {
  771. State = PtcState.Continuing;
  772. }
  773. }
  774. public static void Close()
  775. {
  776. if (State == PtcState.Enabled ||
  777. State == PtcState.Continuing)
  778. {
  779. State = PtcState.Closing;
  780. }
  781. }
  782. internal static void Disable()
  783. {
  784. State = PtcState.Disabled;
  785. }
  786. private static void Wait()
  787. {
  788. _waitEvent.WaitOne();
  789. }
  790. public static void Dispose()
  791. {
  792. if (!_disposed)
  793. {
  794. _disposed = true;
  795. Wait();
  796. _waitEvent.Dispose();
  797. DisposeCarriers();
  798. }
  799. }
  800. }
  801. }