AMemoryHelper.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. using System.IO;
  2. using System.Text;
  3. using System.Threading;
  4. namespace ChocolArm64.Memory
  5. {
  6. public static class AMemoryHelper
  7. {
  8. public static void FillWithZeros(AMemory Memory, long Position, int Size)
  9. {
  10. int Size8 = Size & ~(8 - 1);
  11. for (int Offs = 0; Offs < Size8; Offs += 8)
  12. {
  13. Memory.WriteInt64(Position + Offs, 0);
  14. }
  15. for (int Offs = Size8; Offs < (Size - Size8); Offs++)
  16. {
  17. Memory.WriteByte(Position + Offs, 0);
  18. }
  19. }
  20. public static int ReadInt32Exclusive(AMemory Memory, long Position)
  21. {
  22. while (!Memory.AcquireAddress(Position))
  23. {
  24. Thread.Yield();
  25. }
  26. int Value = Memory.ReadInt32(Position);
  27. Memory.ReleaseAddress(Position);
  28. return Value;
  29. }
  30. public static void WriteInt32Exclusive(AMemory Memory, long Position, int Value)
  31. {
  32. while (!Memory.AcquireAddress(Position))
  33. {
  34. Thread.Yield();
  35. }
  36. Memory.WriteInt32(Position, Value);
  37. Memory.ReleaseAddress(Position);
  38. }
  39. public static byte[] ReadBytes(AMemory Memory, long Position, int Size)
  40. {
  41. byte[] Data = new byte[Size];
  42. for (int Offs = 0; Offs < Size; Offs++)
  43. {
  44. Data[Offs] = (byte)Memory.ReadByte(Position + Offs);
  45. }
  46. return Data;
  47. }
  48. public static void WriteBytes(AMemory Memory, long Position, byte[] Data)
  49. {
  50. for (int Offs = 0; Offs < Data.Length; Offs++)
  51. {
  52. Memory.WriteByte(Position + Offs, Data[Offs]);
  53. }
  54. }
  55. public static string ReadAsciiString(AMemory Memory, long Position, int MaxSize = -1)
  56. {
  57. using (MemoryStream MS = new MemoryStream())
  58. {
  59. for (int Offs = 0; Offs < MaxSize || MaxSize == -1; Offs++)
  60. {
  61. byte Value = (byte)Memory.ReadByte(Position + Offs);
  62. if (Value == 0)
  63. {
  64. break;
  65. }
  66. MS.WriteByte(Value);
  67. }
  68. return Encoding.ASCII.GetString(MS.ToArray());
  69. }
  70. }
  71. public static long PageRoundUp(long Value)
  72. {
  73. return (Value + AMemoryMgr.PageMask) & ~AMemoryMgr.PageMask;
  74. }
  75. public static long PageRoundDown(long Value)
  76. {
  77. return Value & ~AMemoryMgr.PageMask;
  78. }
  79. }
  80. }