aboutsummaryrefslogtreecommitdiff
path: root/ChocolArm64/Memory/AMemoryHelper.cs
blob: ea87783438a266f6370b804ce6f8cc06ee6280b7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;

namespace ChocolArm64.Memory
{
    public static class AMemoryHelper
    {
        public static void FillWithZeros(AMemory Memory, long Position, int Size)
        {
            int Size8 = Size & ~(8 - 1);

            for (int Offs = 0; Offs < Size8; Offs += 8)
            {
                Memory.WriteInt64(Position + Offs, 0);
            }

            for (int Offs = Size8; Offs < (Size - Size8); Offs++)
            {
                Memory.WriteByte(Position + Offs, 0);
            }
        }

        public unsafe static T Read<T>(AMemory Memory, long Position) where T : struct
        {
            long Size = Marshal.SizeOf<T>();

            Memory.EnsureRangeIsValid(Position, Size);

            IntPtr Ptr = (IntPtr)Memory.Translate(Position);

            return Marshal.PtrToStructure<T>(Ptr);
        }

        public unsafe static void Write<T>(AMemory Memory, long Position, T Value) where T : struct
        {
            long Size = Marshal.SizeOf<T>();

            Memory.EnsureRangeIsValid(Position, Size);

            IntPtr Ptr = (IntPtr)Memory.TranslateWrite(Position);

            Marshal.StructureToPtr<T>(Value, Ptr, false);
        }

        public static string ReadAsciiString(AMemory Memory, long Position, long MaxSize = -1)
        {
            using (MemoryStream MS = new MemoryStream())
            {
                for (long Offs = 0; Offs < MaxSize || MaxSize == -1; Offs++)
                {
                    byte Value = (byte)Memory.ReadByte(Position + Offs);

                    if (Value == 0)
                    {
                        break;
                    }

                    MS.WriteByte(Value);
                }

                return Encoding.ASCII.GetString(MS.ToArray());
            }
        }
    }
}