AMemoryHelper.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System;
  2. using System.IO;
  3. using System.Runtime.InteropServices;
  4. using System.Text;
  5. namespace ChocolArm64.Memory
  6. {
  7. public static class AMemoryHelper
  8. {
  9. public static void FillWithZeros(AMemory Memory, long Position, int Size)
  10. {
  11. int Size8 = Size & ~(8 - 1);
  12. for (int Offs = 0; Offs < Size8; Offs += 8)
  13. {
  14. Memory.WriteInt64(Position + Offs, 0);
  15. }
  16. for (int Offs = Size8; Offs < (Size - Size8); Offs++)
  17. {
  18. Memory.WriteByte(Position + Offs, 0);
  19. }
  20. }
  21. public unsafe static T Read<T>(AMemory Memory, long Position) where T : struct
  22. {
  23. long Size = Marshal.SizeOf<T>();
  24. if ((ulong)(Position + Size) > AMemoryMgr.AddrSize)
  25. {
  26. throw new ArgumentOutOfRangeException(nameof(Position));
  27. }
  28. IntPtr Ptr = new IntPtr((byte*)Memory.Ram + Position);
  29. return Marshal.PtrToStructure<T>(Ptr);
  30. }
  31. public unsafe static void Write<T>(AMemory Memory, long Position, T Value) where T : struct
  32. {
  33. long Size = Marshal.SizeOf<T>();
  34. if ((ulong)(Position + Size) > AMemoryMgr.AddrSize)
  35. {
  36. throw new ArgumentOutOfRangeException(nameof(Position));
  37. }
  38. IntPtr Ptr = new IntPtr((byte*)Memory.Ram + Position);
  39. Marshal.StructureToPtr<T>(Value, Ptr, false);
  40. }
  41. public static string ReadAsciiString(AMemory Memory, long Position, long MaxSize = -1)
  42. {
  43. using (MemoryStream MS = new MemoryStream())
  44. {
  45. for (long Offs = 0; Offs < MaxSize || MaxSize == -1; Offs++)
  46. {
  47. byte Value = (byte)Memory.ReadByte(Position + Offs);
  48. if (Value == 0)
  49. {
  50. break;
  51. }
  52. MS.WriteByte(Value);
  53. }
  54. return Encoding.ASCII.GetString(MS.ToArray());
  55. }
  56. }
  57. public static long PageRoundUp(long Value)
  58. {
  59. return (Value + AMemoryMgr.PageMask) & ~AMemoryMgr.PageMask;
  60. }
  61. public static long PageRoundDown(long Value)
  62. {
  63. return Value & ~AMemoryMgr.PageMask;
  64. }
  65. }
  66. }