Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,16 @@ jobs:
/nologo
/verbosity:minimal

- name: Run the self-test harness
# MemoryXTest round-trips the library against its own process memory and
# exits non-zero on any failed check. A native exit code does not fail a
# PowerShell step on its own, so it is checked explicitly.
run: |
$exe = "MemoryXTest\bin\${{ matrix.configuration }}\MemoryXTest.exe"
if (-not (Test-Path $exe)) { throw "Harness not found at $exe" }
& $exe
if ($LASTEXITCODE -ne 0) { throw "Self-test harness failed with exit code $LASTEXITCODE" }

- name: Upload build output
uses: actions/upload-artifact@v7
with:
Expand Down
18 changes: 11 additions & 7 deletions MemoryX/Memory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,9 @@ public Boolean GetProcessHandle(int PID)
Process proc = Process.GetProcessById(PID);
this.processId = proc.Id;
this.processHandle = OpenProcess((int)ProcessAccess.AllAccess, false, processId);
return true;
// OpenProcess returns NULL on failure, typically when the caller is
// not elevated; reporting success there hides the real error.
return this.processHandle != IntPtr.Zero;
}
catch
{
Expand All @@ -198,7 +200,7 @@ public Boolean GetProcessHandle(String procName)
//take the first process
this.processId = proc.Id;
this.processHandle = OpenProcess((int)ProcessAccess.AllAccess, false, this.processId);
return true;
return this.processHandle != IntPtr.Zero;
}
return false;

Expand All @@ -225,7 +227,7 @@ public long GetBaseAddress(String moduleName)
}
return (long)baseAddress;
}
catch (Exception ex)
catch (Exception)
{
return (long)IntPtr.Zero;
}
Expand Down Expand Up @@ -272,7 +274,9 @@ public int WriteMemory(long lpBaseAddress, double value)

public int WriteMemory(long lpBaseAddress, byte value)
{
return WriteMemory(lpBaseAddress, BitConverter.GetBytes(value));
// BitConverter.GetBytes has no byte overload; passing one here promotes
// it to short and writes two bytes, so build the single-byte buffer.
return WriteMemory(lpBaseAddress, new byte[] { value });
}

public int WriteMemoryPointer(long lpBaseAddress, int[] offsets, int value)
Expand Down Expand Up @@ -313,9 +317,9 @@ public Single ReadSingle(long lpBaseAddress)
{
// http://www.pinvoke.net/default.aspx/kernel32.readprocessmemory
// http://stackoverflow.com/questions/30694922/modify-function-to-read-float-c-sharp
byte[] buffer = new byte[8];
ReadProcessMemory(processHandle, lpBaseAddress, buffer, 8, ref bytesRead);
return BitConverter.ToSingle(buffer, 0); ;
byte[] buffer = new byte[4];
ReadProcessMemory(processHandle, lpBaseAddress, buffer, 4, ref bytesRead);
return BitConverter.ToSingle(buffer, 0);
}

/// <summary>
Expand Down
1 change: 1 addition & 0 deletions MemoryXTest/MemoryXTest.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
Expand Down
195 changes: 142 additions & 53 deletions MemoryXTest/Program.cs
Original file line number Diff line number Diff line change
@@ -1,81 +1,170 @@
using System;
using System.Collections.Generic;
using System;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace MemoryXTest
{
class Program
/// <summary>
/// Self-verifying harness for <see cref="MemoryX.Memory"/>.
///
/// It commits a single page inside this very process, opens that process
/// through the library, and round-trips each read and write overload against
/// the page. That needs no external target process and no elevation, so it
/// runs unattended in CI.
///
/// Exits with 0 when every check passes and 1 when any check fails.
/// </summary>
internal static class Program
{
static void Main(string[] args)
{

MemoryX.Memory myProc = new MemoryX.Memory();

var procName = "Tutorial-x86_64";
var address = 0x0162DB00;

// for open our process
myProc.GetProcessHandle(procName);

//for some game you need to remove protection before Read or Write Value in address
myProc.RemoveProtection(address);
private const uint MEM_COMMIT = 0x1000;
private const uint MEM_RESERVE = 0x2000;
private const uint PAGE_READWRITE = 0x04;

// for write memory string value to memory
//myProc.WriteMemory(address, "Hello");
/// <summary>Exactly one page, so reads past the end land on unmapped memory.</summary>
private const int PageSize = 4096;

//// for write memory int value to memory
//myProc.WriteMemory(address, 12345);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr VirtualAlloc(IntPtr lpAddress, UIntPtr dwSize, uint flAllocationType, uint flProtect);

//// for write memory float or single value to memory
//myProc.WriteMemory(address, 3.1415928f);
private static int failures;

//// for write memory double value to memory
//myProc.WriteMemory(address, 7.1474d);
private static int Main()
{
// Memory declares lpBaseAddress as a 64-bit long, which only matches
// the native LPVOID parameter in a 64-bit process.
if (IntPtr.Size != 8)
{
Console.Error.WriteLine("FAIL the harness must run as a 64-bit process");
return 1;
}

IntPtr page = VirtualAlloc(IntPtr.Zero, new UIntPtr(PageSize), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
if (page == IntPtr.Zero)
{
Console.Error.WriteLine("FAIL VirtualAlloc failed with error {0}", Marshal.GetLastWin32Error());
return 1;
}

long baseAddress = page.ToInt64();
var mem = new MemoryX.Memory();

RunHandleChecks(mem);
RunRoundTripChecks(mem, baseAddress);
RunSingleByteWriteCheck(mem, baseAddress);
RunEndOfPageFloatCheck(mem, baseAddress);
RunBaseAddressChecks(mem);

mem.CloseProcessHandle();

Console.WriteLine();
if (failures == 0)
{
Console.WriteLine("All checks passed.");
return 0;
}

Console.Error.WriteLine("{0} check(s) failed.", failures);
return 1;
}

//// for write memory byte value to memory
//myProc.WriteMemory(address, 0xba);
private static void RunHandleChecks(MemoryX.Memory mem)
{
// A process id that cannot exist, so OpenProcess is never reached.
Check("GetProcessHandle rejects an unknown process id", !mem.GetProcessHandle(-1));

Check("GetProcessHandle opens the current process",
mem.GetProcessHandle(Process.GetCurrentProcess().Id));
Check("GetProcessHandle exposes a non-null handle", mem.GetProcessHandle() != IntPtr.Zero);
Check("GetProcessID reports the current process",
mem.GetProcessID() == Process.GetCurrentProcess().Id);
}

//// for write memory array of bytes value to memory
//myProc.WriteMemory(address, new byte[] { 0xaa, 0xbb, 0xcc });
private static void RunRoundTripChecks(MemoryX.Memory mem, long baseAddress)
{
var bytes = new byte[] { 0xAA, 0xBB, 0xCC };
mem.WriteMemory(baseAddress, bytes);
Check("byte[] round-trips", SequenceEqual(mem.ReadMemory(baseAddress, bytes.Length), bytes));
Check("GetBytesWritten reports the byte[] length", mem.GetBytesWritten() == bytes.Length);

mem.WriteMemory(baseAddress + 16, "Hello");
Check("string round-trips", mem.ReadString(baseAddress + 16, 5) == "Hello");

// write an array of bytes in to memory
myProc.WriteMemory(address, new byte[] { 0xaa, 0xbb, 0xcc });
mem.WriteMemory(baseAddress + 32, 12345);
Check("int round-trips", mem.ReadInt32(baseAddress + 32) == 12345);

// for read a memory address value and return to array of bytes value
byte[] arrBytes = myProc.ReadMemory(address, 5);
// for print byte values
foreach (byte b in arrBytes)
Console.WriteLine(b.ToString("X"));
mem.WriteMemory(baseAddress + 48, 3.1415928f);
Check("float round-trips", mem.ReadFloat(baseAddress + 48) == 3.1415928f);
Check("ReadSingle agrees with ReadFloat",
mem.ReadSingle(baseAddress + 48) == mem.ReadFloat(baseAddress + 48));

mem.WriteMemory(baseAddress + 64, 7.1474d);
Check("double round-trips", mem.ReadDouble(baseAddress + 64) == 7.1474d);
}

// for read a memory address value and return to double
Console.WriteLine(myProc.ReadDouble(address));
/// <summary>
/// Regression check: WriteMemory(long, byte) once forwarded to
/// BitConverter.GetBytes, which has no byte overload, so the argument was
/// promoted to short and clobbered the following byte.
/// </summary>
private static void RunSingleByteWriteCheck(MemoryX.Memory mem, long baseAddress)
{
long address = baseAddress + 80;
mem.WriteMemory(address, new byte[] { 0xFF, 0xFF, 0xFF, 0xFF });

mem.WriteMemory(address, (byte)0xBA);

// for read a memory address value and return to flot or Single
Console.WriteLine(myProc.ReadFloat(address));
byte[] after = mem.ReadMemory(address, 4);
Check("single-byte write stores the value", after[0] == 0xBA);
Check("single-byte write leaves the next 3 bytes untouched",
after[1] == 0xFF && after[2] == 0xFF && after[3] == 0xFF);
Check("GetBytesWritten reports one byte", mem.GetBytesWritten() == 1);
}

// for read memory and return to string value
Console.WriteLine(myProc.ReadString(address, 11));
/// <summary>
/// Regression check: ReadSingle once requested 8 bytes for a 4-byte value,
/// so a float at the end of a page failed to read and silently returned 0.
/// </summary>
private static void RunEndOfPageFloatCheck(MemoryX.Memory mem, long baseAddress)
{
long address = baseAddress + PageSize - sizeof(float);
mem.WriteMemory(address, 2.71828f);
Check("float at the end of a page reads back", mem.ReadFloat(address) == 2.71828f);
}

// for read a single byte value from memory
Console.WriteLine("BYTES IS " + myProc.ReadMemory(address , 1)[0].ToString("X"));
private static void RunBaseAddressChecks(MemoryX.Memory mem)
{
string moduleName = Process.GetCurrentProcess().MainModule.ModuleName;
Check("GetBaseAddress resolves the main module", mem.GetBaseAddress(moduleName) != 0);
Check("GetBaseAddress is case-insensitive",
mem.GetBaseAddress(moduleName.ToUpperInvariant()) == mem.GetBaseAddress(moduleName));
Check("GetBaseAddress returns 0 for an unknown module",
mem.GetBaseAddress("no-such-module-here.dll") == 0);
}

long addressOfPtr = myProc.GetBaseAddress("Tutorial-x86_64.exe") + 0x2C4A50;
long valueOfPtr = myProc.ReadInt32(addressOfPtr);
int myValue = myProc.ReadInt32(valueOfPtr);
private static bool SequenceEqual(byte[] actual, byte[] expected)
{
if (actual == null || actual.Length != expected.Length)
return false;

Console.WriteLine(addressOfPtr.ToString("X"));
Console.WriteLine(valueOfPtr.ToString("X"));
for (int i = 0; i < expected.Length; i++)
{
if (actual[i] != expected[i])
return false;
}

Console.WriteLine(myValue);
Console.ReadLine();
return true;
}

private static void Check(string description, bool passed)
{
if (passed)
{
Console.WriteLine("ok {0}", description);
return;
}

failures++;
Console.Error.WriteLine("FAIL {0}", description);
}
}
}
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,11 @@ OpenProcess using PID.

#### Write a single byte value into address

The cast matters: an unsuffixed literal such as `0xba` is an `int`, so it binds
to the `int` overload and writes four bytes.

```cs
WriteMemory(address, 0xba);
WriteMemory(address, (byte)0xba);
```

#### Write an array of bytes into address
Expand Down Expand Up @@ -140,7 +143,7 @@ Console.WriteLine(BitConverter.ToInt16(b, 0));
myProc.WriteMemory(address, 7.1474d);

// for write memory byte value to memory
myProc.WriteMemory(address, 0xba);
myProc.WriteMemory(address, (byte)0xba);

// for write memory array of bytes value to memory
myProc.WriteMemory(address, new byte[] { 0xaa, 0xbb, 0xcc });
Expand Down