AMemoryHelper.cs 2.6 KB

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