AMemory.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  1. using ChocolArm64.Exceptions;
  2. using ChocolArm64.State;
  3. using System;
  4. using System.Collections.Concurrent;
  5. using System.Collections.Generic;
  6. using System.Runtime.CompilerServices;
  7. using System.Runtime.InteropServices;
  8. using System.Runtime.Intrinsics;
  9. using System.Runtime.Intrinsics.X86;
  10. using System.Threading;
  11. namespace ChocolArm64.Memory
  12. {
  13. public unsafe class AMemory : IAMemory, IDisposable
  14. {
  15. private const int PTLvl0Bits = 13;
  16. private const int PTLvl1Bits = 14;
  17. private const int PTPageBits = 12;
  18. private const int PTLvl0Size = 1 << PTLvl0Bits;
  19. private const int PTLvl1Size = 1 << PTLvl1Bits;
  20. public const int PageSize = 1 << PTPageBits;
  21. private const int PTLvl0Mask = PTLvl0Size - 1;
  22. private const int PTLvl1Mask = PTLvl1Size - 1;
  23. public const int PageMask = PageSize - 1;
  24. private const int PTLvl0Bit = PTPageBits + PTLvl1Bits;
  25. private const int PTLvl1Bit = PTPageBits;
  26. private const long ErgMask = (4 << AThreadState.ErgSizeLog2) - 1;
  27. private class ArmMonitor
  28. {
  29. public long Position;
  30. public bool ExState;
  31. public bool HasExclusiveAccess(long Position)
  32. {
  33. return this.Position == Position && ExState;
  34. }
  35. }
  36. private Dictionary<AThreadState, ArmMonitor> Monitors;
  37. private ConcurrentDictionary<long, IntPtr> ObservedPages;
  38. public IntPtr Ram { get; private set; }
  39. private byte* RamPtr;
  40. private byte*** PageTable;
  41. public AMemory(IntPtr Ram)
  42. {
  43. Monitors = new Dictionary<AThreadState, ArmMonitor>();
  44. ObservedPages = new ConcurrentDictionary<long, IntPtr>();
  45. this.Ram = Ram;
  46. RamPtr = (byte*)Ram;
  47. PageTable = (byte***)Marshal.AllocHGlobal(PTLvl0Size * IntPtr.Size);
  48. for (int L0 = 0; L0 < PTLvl0Size; L0++)
  49. {
  50. PageTable[L0] = null;
  51. }
  52. }
  53. public void RemoveMonitor(AThreadState State)
  54. {
  55. lock (Monitors)
  56. {
  57. ClearExclusive(State);
  58. Monitors.Remove(State);
  59. }
  60. }
  61. public void SetExclusive(AThreadState ThreadState, long Position)
  62. {
  63. Position &= ~ErgMask;
  64. lock (Monitors)
  65. {
  66. foreach (ArmMonitor Mon in Monitors.Values)
  67. {
  68. if (Mon.Position == Position && Mon.ExState)
  69. {
  70. Mon.ExState = false;
  71. }
  72. }
  73. if (!Monitors.TryGetValue(ThreadState, out ArmMonitor ThreadMon))
  74. {
  75. ThreadMon = new ArmMonitor();
  76. Monitors.Add(ThreadState, ThreadMon);
  77. }
  78. ThreadMon.Position = Position;
  79. ThreadMon.ExState = true;
  80. }
  81. }
  82. public bool TestExclusive(AThreadState ThreadState, long Position)
  83. {
  84. //Note: Any call to this method also should be followed by a
  85. //call to ClearExclusiveForStore if this method returns true.
  86. Position &= ~ErgMask;
  87. Monitor.Enter(Monitors);
  88. if (!Monitors.TryGetValue(ThreadState, out ArmMonitor ThreadMon))
  89. {
  90. return false;
  91. }
  92. bool ExState = ThreadMon.HasExclusiveAccess(Position);
  93. if (!ExState)
  94. {
  95. Monitor.Exit(Monitors);
  96. }
  97. return ExState;
  98. }
  99. public void ClearExclusiveForStore(AThreadState ThreadState)
  100. {
  101. if (Monitors.TryGetValue(ThreadState, out ArmMonitor ThreadMon))
  102. {
  103. ThreadMon.ExState = false;
  104. }
  105. Monitor.Exit(Monitors);
  106. }
  107. public void ClearExclusive(AThreadState ThreadState)
  108. {
  109. lock (Monitors)
  110. {
  111. if (Monitors.TryGetValue(ThreadState, out ArmMonitor ThreadMon))
  112. {
  113. ThreadMon.ExState = false;
  114. }
  115. }
  116. }
  117. public void WriteInt32ToSharedAddr(long Position, int Value)
  118. {
  119. long MaskedPosition = Position & ~ErgMask;
  120. lock (Monitors)
  121. {
  122. foreach (ArmMonitor Mon in Monitors.Values)
  123. {
  124. if (Mon.Position == MaskedPosition && Mon.ExState)
  125. {
  126. Mon.ExState = false;
  127. }
  128. }
  129. WriteInt32(Position, Value);
  130. }
  131. }
  132. public sbyte ReadSByte(long Position)
  133. {
  134. return (sbyte)ReadByte(Position);
  135. }
  136. public short ReadInt16(long Position)
  137. {
  138. return (short)ReadUInt16(Position);
  139. }
  140. public int ReadInt32(long Position)
  141. {
  142. return (int)ReadUInt32(Position);
  143. }
  144. public long ReadInt64(long Position)
  145. {
  146. return (long)ReadUInt64(Position);
  147. }
  148. public byte ReadByte(long Position)
  149. {
  150. return *((byte*)Translate(Position));
  151. }
  152. public ushort ReadUInt16(long Position)
  153. {
  154. return *((ushort*)Translate(Position));
  155. }
  156. public uint ReadUInt32(long Position)
  157. {
  158. return *((uint*)Translate(Position));
  159. }
  160. public ulong ReadUInt64(long Position)
  161. {
  162. return *((ulong*)Translate(Position));
  163. }
  164. public Vector128<float> ReadVector8(long Position)
  165. {
  166. if (Sse2.IsSupported)
  167. {
  168. return Sse.StaticCast<byte, float>(Sse2.SetVector128(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ReadByte(Position)));
  169. }
  170. else
  171. {
  172. throw new PlatformNotSupportedException();
  173. }
  174. }
  175. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  176. public Vector128<float> ReadVector16(long Position)
  177. {
  178. if (Sse2.IsSupported)
  179. {
  180. return Sse.StaticCast<ushort, float>(Sse2.Insert(Sse2.SetZeroVector128<ushort>(), ReadUInt16(Position), 0));
  181. }
  182. else
  183. {
  184. throw new PlatformNotSupportedException();
  185. }
  186. }
  187. [MethodImpl(MethodImplOptions.NoInlining)]
  188. public Vector128<float> ReadVector32(long Position)
  189. {
  190. if (Sse.IsSupported)
  191. {
  192. return Sse.LoadScalarVector128((float*)Translate(Position));
  193. }
  194. else
  195. {
  196. throw new PlatformNotSupportedException();
  197. }
  198. }
  199. [MethodImpl(MethodImplOptions.NoInlining)]
  200. public Vector128<float> ReadVector64(long Position)
  201. {
  202. if (Sse2.IsSupported)
  203. {
  204. return Sse.StaticCast<double, float>(Sse2.LoadScalarVector128((double*)Translate(Position)));
  205. }
  206. else
  207. {
  208. throw new PlatformNotSupportedException();
  209. }
  210. }
  211. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  212. public Vector128<float> ReadVector128(long Position)
  213. {
  214. if (Sse.IsSupported)
  215. {
  216. return Sse.LoadVector128((float*)Translate(Position));
  217. }
  218. else
  219. {
  220. throw new PlatformNotSupportedException();
  221. }
  222. }
  223. public byte[] ReadBytes(long Position, long Size)
  224. {
  225. if ((uint)Size > int.MaxValue)
  226. {
  227. throw new ArgumentOutOfRangeException(nameof(Size));
  228. }
  229. EnsureRangeIsValid(Position, Size);
  230. byte[] Data = new byte[Size];
  231. Marshal.Copy((IntPtr)Translate(Position), Data, 0, (int)Size);
  232. return Data;
  233. }
  234. public void WriteSByte(long Position, sbyte Value)
  235. {
  236. WriteByte(Position, (byte)Value);
  237. }
  238. public void WriteInt16(long Position, short Value)
  239. {
  240. WriteUInt16(Position, (ushort)Value);
  241. }
  242. public void WriteInt32(long Position, int Value)
  243. {
  244. WriteUInt32(Position, (uint)Value);
  245. }
  246. public void WriteInt64(long Position, long Value)
  247. {
  248. WriteUInt64(Position, (ulong)Value);
  249. }
  250. public void WriteByte(long Position, byte Value)
  251. {
  252. *((byte*)TranslateWrite(Position)) = Value;
  253. }
  254. public void WriteUInt16(long Position, ushort Value)
  255. {
  256. *((ushort*)TranslateWrite(Position)) = Value;
  257. }
  258. public void WriteUInt32(long Position, uint Value)
  259. {
  260. *((uint*)TranslateWrite(Position)) = Value;
  261. }
  262. public void WriteUInt64(long Position, ulong Value)
  263. {
  264. *((ulong*)TranslateWrite(Position)) = Value;
  265. }
  266. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  267. public void WriteVector8(long Position, Vector128<float> Value)
  268. {
  269. if (Sse41.IsSupported)
  270. {
  271. WriteByte(Position, Sse41.Extract(Sse.StaticCast<float, byte>(Value), 0));
  272. }
  273. else if (Sse2.IsSupported)
  274. {
  275. WriteByte(Position, (byte)Sse2.Extract(Sse.StaticCast<float, ushort>(Value), 0));
  276. }
  277. else
  278. {
  279. throw new PlatformNotSupportedException();
  280. }
  281. }
  282. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  283. public void WriteVector16(long Position, Vector128<float> Value)
  284. {
  285. if (Sse2.IsSupported)
  286. {
  287. WriteUInt16(Position, Sse2.Extract(Sse.StaticCast<float, ushort>(Value), 0));
  288. }
  289. else
  290. {
  291. throw new PlatformNotSupportedException();
  292. }
  293. }
  294. [MethodImpl(MethodImplOptions.NoInlining)]
  295. public void WriteVector32(long Position, Vector128<float> Value)
  296. {
  297. if (Sse.IsSupported)
  298. {
  299. Sse.StoreScalar((float*)TranslateWrite(Position), Value);
  300. }
  301. else
  302. {
  303. throw new PlatformNotSupportedException();
  304. }
  305. }
  306. [MethodImpl(MethodImplOptions.NoInlining)]
  307. public void WriteVector64(long Position, Vector128<float> Value)
  308. {
  309. if (Sse2.IsSupported)
  310. {
  311. Sse2.StoreScalar((double*)TranslateWrite(Position), Sse.StaticCast<float, double>(Value));
  312. }
  313. else
  314. {
  315. throw new PlatformNotSupportedException();
  316. }
  317. }
  318. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  319. public void WriteVector128(long Position, Vector128<float> Value)
  320. {
  321. if (Sse.IsSupported)
  322. {
  323. Sse.Store((float*)TranslateWrite(Position), Value);
  324. }
  325. else
  326. {
  327. throw new PlatformNotSupportedException();
  328. }
  329. }
  330. public void WriteBytes(long Position, byte[] Data)
  331. {
  332. EnsureRangeIsValid(Position, (uint)Data.Length);
  333. Marshal.Copy(Data, 0, (IntPtr)TranslateWrite(Position), Data.Length);
  334. }
  335. public void Map(long VA, long PA, long Size)
  336. {
  337. SetPTEntries(VA, RamPtr + PA, Size);
  338. }
  339. public void Unmap(long Position, long Size)
  340. {
  341. SetPTEntries(Position, null, Size);
  342. StopObservingRegion(Position, Size);
  343. }
  344. public bool IsMapped(long Position)
  345. {
  346. if (!(IsValidPosition(Position)))
  347. {
  348. return false;
  349. }
  350. long L0 = (Position >> PTLvl0Bit) & PTLvl0Mask;
  351. long L1 = (Position >> PTLvl1Bit) & PTLvl1Mask;
  352. if (PageTable[L0] == null)
  353. {
  354. return false;
  355. }
  356. return PageTable[L0][L1] != null || ObservedPages.ContainsKey(Position >> PTPageBits);
  357. }
  358. public long GetPhysicalAddress(long VirtualAddress)
  359. {
  360. byte* Ptr = Translate(VirtualAddress);
  361. return (long)(Ptr - RamPtr);
  362. }
  363. internal byte* Translate(long Position)
  364. {
  365. long L0 = (Position >> PTLvl0Bit) & PTLvl0Mask;
  366. long L1 = (Position >> PTLvl1Bit) & PTLvl1Mask;
  367. long Old = Position;
  368. byte** Lvl1 = PageTable[L0];
  369. if ((Position >> (PTLvl0Bit + PTLvl0Bits)) != 0)
  370. {
  371. goto Unmapped;
  372. }
  373. if (Lvl1 == null)
  374. {
  375. goto Unmapped;
  376. }
  377. Position &= PageMask;
  378. byte* Ptr = Lvl1[L1];
  379. if (Ptr == null)
  380. {
  381. goto Unmapped;
  382. }
  383. return Ptr + Position;
  384. Unmapped:
  385. return HandleNullPte(Old);
  386. }
  387. private byte* HandleNullPte(long Position)
  388. {
  389. long Key = Position >> PTPageBits;
  390. if (ObservedPages.TryGetValue(Key, out IntPtr Ptr))
  391. {
  392. return (byte*)Ptr + (Position & PageMask);
  393. }
  394. throw new VmmPageFaultException(Position);
  395. }
  396. internal byte* TranslateWrite(long Position)
  397. {
  398. long L0 = (Position >> PTLvl0Bit) & PTLvl0Mask;
  399. long L1 = (Position >> PTLvl1Bit) & PTLvl1Mask;
  400. long Old = Position;
  401. byte** Lvl1 = PageTable[L0];
  402. if ((Position >> (PTLvl0Bit + PTLvl0Bits)) != 0)
  403. {
  404. goto Unmapped;
  405. }
  406. if (Lvl1 == null)
  407. {
  408. goto Unmapped;
  409. }
  410. Position &= PageMask;
  411. byte* Ptr = Lvl1[L1];
  412. if (Ptr == null)
  413. {
  414. goto Unmapped;
  415. }
  416. return Ptr + Position;
  417. Unmapped:
  418. return HandleNullPteWrite(Old);
  419. }
  420. private byte* HandleNullPteWrite(long Position)
  421. {
  422. long Key = Position >> PTPageBits;
  423. if (ObservedPages.TryGetValue(Key, out IntPtr Ptr))
  424. {
  425. SetPTEntry(Position, (byte*)Ptr);
  426. return (byte*)Ptr + (Position & PageMask);
  427. }
  428. throw new VmmPageFaultException(Position);
  429. }
  430. private void SetPTEntries(long VA, byte* Ptr, long Size)
  431. {
  432. long EndPosition = (VA + Size + PageMask) & ~PageMask;
  433. while ((ulong)VA < (ulong)EndPosition)
  434. {
  435. SetPTEntry(VA, Ptr);
  436. VA += PageSize;
  437. if (Ptr != null)
  438. {
  439. Ptr += PageSize;
  440. }
  441. }
  442. }
  443. private void SetPTEntry(long Position, byte* Ptr)
  444. {
  445. if (!IsValidPosition(Position))
  446. {
  447. throw new ArgumentOutOfRangeException(nameof(Position));
  448. }
  449. long L0 = (Position >> PTLvl0Bit) & PTLvl0Mask;
  450. long L1 = (Position >> PTLvl1Bit) & PTLvl1Mask;
  451. if (PageTable[L0] == null)
  452. {
  453. byte** Lvl1 = (byte**)Marshal.AllocHGlobal(PTLvl1Size * IntPtr.Size);
  454. for (int ZL1 = 0; ZL1 < PTLvl1Size; ZL1++)
  455. {
  456. Lvl1[ZL1] = null;
  457. }
  458. Thread.MemoryBarrier();
  459. PageTable[L0] = Lvl1;
  460. }
  461. PageTable[L0][L1] = Ptr;
  462. }
  463. public (bool[], int) IsRegionModified(long Position, long Size)
  464. {
  465. long EndPosition = (Position + Size + PageMask) & ~PageMask;
  466. Position &= ~PageMask;
  467. Size = EndPosition - Position;
  468. bool[] Modified = new bool[Size >> PTPageBits];
  469. int Count = 0;
  470. lock (ObservedPages)
  471. {
  472. for (int Page = 0; Page < Modified.Length; Page++)
  473. {
  474. byte* Ptr = Translate(Position);
  475. if (ObservedPages.TryAdd(Position >> PTPageBits, (IntPtr)Ptr))
  476. {
  477. Modified[Page] = true;
  478. Count++;
  479. }
  480. else
  481. {
  482. long L0 = (Position >> PTLvl0Bit) & PTLvl0Mask;
  483. long L1 = (Position >> PTLvl1Bit) & PTLvl1Mask;
  484. byte** Lvl1 = PageTable[L0];
  485. if (Lvl1 != null)
  486. {
  487. if (Modified[Page] = Lvl1[L1] != null)
  488. {
  489. Count++;
  490. }
  491. }
  492. }
  493. SetPTEntry(Position, null);
  494. Position += PageSize;
  495. }
  496. }
  497. return (Modified, Count);
  498. }
  499. public void StopObservingRegion(long Position, long Size)
  500. {
  501. long EndPosition = (Position + Size + PageMask) & ~PageMask;
  502. while (Position < EndPosition)
  503. {
  504. lock (ObservedPages)
  505. {
  506. if (ObservedPages.TryRemove(Position >> PTPageBits, out IntPtr Ptr))
  507. {
  508. SetPTEntry(Position, (byte*)Ptr);
  509. }
  510. }
  511. Position += PageSize;
  512. }
  513. }
  514. public IntPtr GetHostAddress(long Position, long Size)
  515. {
  516. EnsureRangeIsValid(Position, Size);
  517. return (IntPtr)Translate(Position);
  518. }
  519. internal void EnsureRangeIsValid(long Position, long Size)
  520. {
  521. long EndPos = Position + Size;
  522. Position &= ~PageMask;
  523. long ExpectedPA = GetPhysicalAddress(Position);
  524. while ((ulong)Position < (ulong)EndPos)
  525. {
  526. long PA = GetPhysicalAddress(Position);
  527. if (PA != ExpectedPA)
  528. {
  529. throw new VmmAccessException(Position, Size);
  530. }
  531. Position += PageSize;
  532. ExpectedPA += PageSize;
  533. }
  534. }
  535. public bool IsValidPosition(long Position)
  536. {
  537. return Position >> (PTLvl0Bits + PTLvl1Bits + PTPageBits) == 0;
  538. }
  539. public void Dispose()
  540. {
  541. Dispose(true);
  542. }
  543. protected virtual void Dispose(bool disposing)
  544. {
  545. if (PageTable == null)
  546. {
  547. return;
  548. }
  549. for (int L0 = 0; L0 < PTLvl0Size; L0++)
  550. {
  551. if (PageTable[L0] != null)
  552. {
  553. Marshal.FreeHGlobal((IntPtr)PageTable[L0]);
  554. }
  555. PageTable[L0] = null;
  556. }
  557. Marshal.FreeHGlobal((IntPtr)PageTable);
  558. PageTable = null;
  559. }
  560. }
  561. }