AMemory.cs 20 KB

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