AMemoryHelper.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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 static byte[] ReadBytes(AMemory Memory, long Position, long Size)
  22. {
  23. byte[] Data = new byte[Size];
  24. for (long Offs = 0; Offs < Size; Offs++)
  25. {
  26. Data[Offs] = (byte)Memory.ReadByte(Position + Offs);
  27. }
  28. return Data;
  29. }
  30. public static void WriteBytes(AMemory Memory, long Position, byte[] Data)
  31. {
  32. for (int Offs = 0; Offs < Data.Length; Offs++)
  33. {
  34. Memory.WriteByte(Position + Offs, Data[Offs]);
  35. }
  36. }
  37. public unsafe static T Read<T>(AMemory Memory, long Position) where T : struct
  38. {
  39. long Size = Marshal.SizeOf<T>();
  40. if ((ulong)(Position + Size) > AMemoryMgr.AddrSize)
  41. {
  42. throw new ArgumentOutOfRangeException(nameof(Position));
  43. }
  44. IntPtr Ptr = new IntPtr((byte*)Memory.Ram + Position);
  45. return Marshal.PtrToStructure<T>(Ptr);
  46. }
  47. public unsafe static void Write<T>(AMemory Memory, long Position, T Value) where T : struct
  48. {
  49. long Size = Marshal.SizeOf<T>();
  50. if ((ulong)(Position + Size) > AMemoryMgr.AddrSize)
  51. {
  52. throw new ArgumentOutOfRangeException(nameof(Position));
  53. }
  54. IntPtr Ptr = new IntPtr((byte*)Memory.Ram + Position);
  55. Marshal.StructureToPtr<T>(Value, Ptr, false);
  56. }
  57. public static string ReadAsciiString(AMemory Memory, long Position, long MaxSize = -1)
  58. {
  59. using (MemoryStream MS = new MemoryStream())
  60. {
  61. for (long Offs = 0; Offs < MaxSize || MaxSize == -1; Offs++)
  62. {
  63. byte Value = (byte)Memory.ReadByte(Position + Offs);
  64. if (Value == 0)
  65. {
  66. break;
  67. }
  68. MS.WriteByte(Value);
  69. }
  70. return Encoding.ASCII.GetString(MS.ToArray());
  71. }
  72. }
  73. public static long PageRoundUp(long Value)
  74. {
  75. return (Value + AMemoryMgr.PageMask) & ~AMemoryMgr.PageMask;
  76. }
  77. public static long PageRoundDown(long Value)
  78. {
  79. return Value & ~AMemoryMgr.PageMask;
  80. }
  81. }
  82. }