Ptc.cs 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091
  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 = 2721; //! 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. 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);
  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 ulong GetFeatureInfo()
  709. {
  710. return (ulong)HardwareCapabilities.FeatureInfoEdx << 32 | (uint)HardwareCapabilities.FeatureInfoEcx;
  711. }
  712. private static byte GetMemoryManagerMode()
  713. {
  714. return (byte)_memoryMode;
  715. }
  716. private static uint GetOSPlatform()
  717. {
  718. uint osPlatform = 0u;
  719. osPlatform |= (RuntimeInformation.IsOSPlatform(OSPlatform.FreeBSD) ? 1u : 0u) << 0;
  720. osPlatform |= (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? 1u : 0u) << 1;
  721. osPlatform |= (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? 1u : 0u) << 2;
  722. osPlatform |= (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? 1u : 0u) << 3;
  723. return osPlatform;
  724. }
  725. [StructLayout(LayoutKind.Sequential, Pack = 1/*, Size = 50*/)]
  726. private struct OuterHeader
  727. {
  728. public ulong Magic;
  729. public uint CacheFileVersion;
  730. public bool Endianness;
  731. public ulong FeatureInfo;
  732. public byte MemoryManagerMode;
  733. public uint OSPlatform;
  734. public long UncompressedStreamSize;
  735. public Hash128 HeaderHash;
  736. public void SetHeaderHash()
  737. {
  738. Span<OuterHeader> spanHeader = MemoryMarshal.CreateSpan(ref this, 1);
  739. HeaderHash = XXHash128.ComputeHash(MemoryMarshal.AsBytes(spanHeader).Slice(0, Unsafe.SizeOf<OuterHeader>() - Unsafe.SizeOf<Hash128>()));
  740. }
  741. public bool IsHeaderValid()
  742. {
  743. Span<OuterHeader> spanHeader = MemoryMarshal.CreateSpan(ref this, 1);
  744. return XXHash128.ComputeHash(MemoryMarshal.AsBytes(spanHeader).Slice(0, Unsafe.SizeOf<OuterHeader>() - Unsafe.SizeOf<Hash128>())) == HeaderHash;
  745. }
  746. }
  747. [StructLayout(LayoutKind.Sequential, Pack = 1/*, Size = 128*/)]
  748. private struct InnerHeader
  749. {
  750. public ulong Magic;
  751. public int InfosLength;
  752. public long CodesLength;
  753. public int RelocsLength;
  754. public int UnwindInfosLength;
  755. public Hash128 InfosHash;
  756. public Hash128 CodesHash;
  757. public Hash128 RelocsHash;
  758. public Hash128 UnwindInfosHash;
  759. public Hash128 HeaderHash;
  760. public void SetHeaderHash()
  761. {
  762. Span<InnerHeader> spanHeader = MemoryMarshal.CreateSpan(ref this, 1);
  763. HeaderHash = XXHash128.ComputeHash(MemoryMarshal.AsBytes(spanHeader).Slice(0, Unsafe.SizeOf<InnerHeader>() - Unsafe.SizeOf<Hash128>()));
  764. }
  765. public bool IsHeaderValid()
  766. {
  767. Span<InnerHeader> spanHeader = MemoryMarshal.CreateSpan(ref this, 1);
  768. return XXHash128.ComputeHash(MemoryMarshal.AsBytes(spanHeader).Slice(0, Unsafe.SizeOf<InnerHeader>() - Unsafe.SizeOf<Hash128>())) == HeaderHash;
  769. }
  770. }
  771. [StructLayout(LayoutKind.Sequential, Pack = 1/*, Size = 42*/)]
  772. private struct InfoEntry
  773. {
  774. public ulong Address;
  775. public ulong GuestSize;
  776. public Hash128 Hash;
  777. public bool HighCq;
  778. public bool Stubbed;
  779. public int CodeLength;
  780. public int RelocEntriesCount;
  781. }
  782. private static void Enable()
  783. {
  784. State = PtcState.Enabled;
  785. }
  786. public static void Continue()
  787. {
  788. if (State == PtcState.Enabled)
  789. {
  790. State = PtcState.Continuing;
  791. }
  792. }
  793. public static void Close()
  794. {
  795. if (State == PtcState.Enabled ||
  796. State == PtcState.Continuing)
  797. {
  798. State = PtcState.Closing;
  799. }
  800. }
  801. internal static void Disable()
  802. {
  803. State = PtcState.Disabled;
  804. }
  805. private static void Wait()
  806. {
  807. _waitEvent.WaitOne();
  808. }
  809. public static void Dispose()
  810. {
  811. if (!_disposed)
  812. {
  813. _disposed = true;
  814. Wait();
  815. _waitEvent.Dispose();
  816. DisposeCarriers();
  817. }
  818. }
  819. }
  820. }