Skip to content
Open
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="CommandLineParser" Version="2.9.1" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\OsuMemoryDataProvider\OsuMemoryDataProvider.csproj" />
</ItemGroup>

</Project>
115 changes: 115 additions & 0 deletions LinuxStructuredOsuMemoryProviderTester/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
using CommandLine;
using OsuMemoryDataProvider;
using System.Diagnostics;
using System.Text.Json;
using System.Text.Json.Serialization;

var parsedArgs = Parser.Default.ParseArguments<CommandLineOptions>(args).MapResult((o) => o, o => null);
if (parsedArgs == null)
return;

Console.WriteLine(JsonSerializer.Serialize(parsedArgs));

var reader = StructuredOsuMemoryReader.Instance;
reader.InvalidRead += readerOnInvalidRead;
var baseAddresses = StructuredOsuMemoryReader.Instance.OsuMemoryAddresses;

JsonSerializerOptions jsonSerializerOptions = new()
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
WriteIndented = parsedArgs.Indented,
};
var stopwatch = Stopwatch.StartNew();
double readTimeMs, readTimeMsMin, readTimeMsMax;
double _memoryReadTimeMin = double.PositiveInfinity;
double _memoryReadTimeMax = double.NegativeInfinity;
while (true)
{
while (!reader.CanRead)
{
Console.WriteLine("Waiting for osu! process...");
await Task.Delay(200);
};

stopwatch = Stopwatch.StartNew();

reader.TryRead(baseAddresses.Beatmap);
reader.TryRead(baseAddresses.Skin);
reader.TryRead(baseAddresses.GeneralData);
reader.TryRead(baseAddresses.BanchoUser);

if (baseAddresses.GeneralData.OsuStatus == OsuMemoryStatus.SongSelect)
reader.TryRead(baseAddresses.SongSelectionScores);
else
baseAddresses.SongSelectionScores.Scores.Clear();

if (baseAddresses.GeneralData.OsuStatus == OsuMemoryStatus.ResultsScreen)
reader.TryRead(baseAddresses.ResultsScreen);

if (baseAddresses.GeneralData.OsuStatus == OsuMemoryStatus.Playing)
{
reader.TryRead(baseAddresses.Player);
reader.TryRead(baseAddresses.LeaderBoard);
reader.TryRead(baseAddresses.KeyOverlay);
}
else
{
baseAddresses.LeaderBoard.Players.Clear();
}

var hitErrors = baseAddresses.Player?.HitErrors;
if (hitErrors != null)
{
var hitErrorsCount = hitErrors.Count;
hitErrors.Clear();
hitErrors.Add(hitErrorsCount);
}

stopwatch.Stop();
readTimeMs = stopwatch.ElapsedTicks / (double)TimeSpan.TicksPerMillisecond;
if (readTimeMs < _memoryReadTimeMin) _memoryReadTimeMin = readTimeMs;
if (readTimeMs > _memoryReadTimeMax) _memoryReadTimeMax = readTimeMs;

readTimeMsMin = _memoryReadTimeMin;
readTimeMsMax = _memoryReadTimeMax;

if (parsedArgs.Output)
Console.WriteLine(JsonSerializer.Serialize(baseAddresses, jsonSerializerOptions));

Console.WriteLine($"ReadTimeMS: {readTimeMs}{Environment.NewLine}" +
$"Min ReadTimeMS: {readTimeMsMin}{Environment.NewLine}" +
$"Max ReadTimeMS: {readTimeMsMax}{Environment.NewLine}" +
$"Press any key to reset min/max values{Environment.NewLine}");
if (parsedArgs.ExitAfter)
break;

if (Console.KeyAvailable)
{
Console.ReadKey(true);
while (Console.KeyAvailable)
Console.ReadKey(true);

_memoryReadTimeMin = double.PositiveInfinity;
_memoryReadTimeMax = double.NegativeInfinity;

}

await Task.Delay(parsedArgs.Delay);
}

void readerOnInvalidRead(object sender, (object readObject, string propPath) e)
{
Console.WriteLine($"{DateTime.Now:T} Error reading {e.propPath}{Environment.NewLine}");
}

class CommandLineOptions
{
[Option('o', "output", Required = false, Default = false, HelpText = "Send read memory values to stdout")]
public bool Output { get; set; }
[Option('i', "indentedOutput", Required = false, Default = false, HelpText = "Format memory values sent to stdout")]
public bool Indented { get; set; }
[Option('e', "exitAfter", Required = false, Default = false, HelpText = "exit after reading memory values once")]
public bool ExitAfter { get; set; }
[Option('d', "delay", Required = false, Default = 200, HelpText = "delay between reads when continuous is enabled")]
public int Delay { get; set; }
}
2 changes: 1 addition & 1 deletion OsuMemoryDataProvider/OsuMemoryDataProvider.csproj
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netcoreapp3.1;net472;net471;net5.0</TargetFrameworks>
<TargetFrameworks>net5.0;net6.0</TargetFrameworks>
<Platforms>x86;x64;AnyCPU</Platforms>
<OutputType>Library</OutputType>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
<PropertyGroup>
<TargetFrameworks>netcoreapp3.1;net472;net471;net5.0-windows</TargetFrameworks>
<TargetFrameworks>net5.0-windows</TargetFrameworks>
<Platforms>x86;x64;AnyCPU</Platforms>
<OutputType>WinExe</OutputType>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
Expand Down
19 changes: 17 additions & 2 deletions ProcessMemoryDataFinder.sln
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.29009.5
# Visual Studio Version 17
VisualStudioVersion = 17.5.33402.96
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ProcessMemoryDataFinder", "ProcessMemoryDataFinder\ProcessMemoryDataFinder.csproj", "{9960D641-300A-432C-AA04-C351A99B9ADB}"
EndProject
Expand All @@ -13,6 +13,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "osu!", "osu!", "{FD3B44E6-6
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StructuredOsuMemoryProviderTester", "StructuredOsuMemoryProviderTester\StructuredOsuMemoryProviderTester.csproj", "{2965C7BF-B5DD-4345-9DFD-4E6B7D93DC0A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LinuxStructuredOsuMemoryProviderTester", "LinuxStructuredOsuMemoryProviderTester\LinuxStructuredOsuMemoryProviderTester.csproj", "{55FA063E-A4AF-4CB1-9F04-E6D553113289}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -68,6 +70,18 @@ Global
{2965C7BF-B5DD-4345-9DFD-4E6B7D93DC0A}.Release|x64.Build.0 = Release|x64
{2965C7BF-B5DD-4345-9DFD-4E6B7D93DC0A}.Release|x86.ActiveCfg = Release|x86
{2965C7BF-B5DD-4345-9DFD-4E6B7D93DC0A}.Release|x86.Build.0 = Release|x86
{55FA063E-A4AF-4CB1-9F04-E6D553113289}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{55FA063E-A4AF-4CB1-9F04-E6D553113289}.Debug|Any CPU.Build.0 = Debug|Any CPU
{55FA063E-A4AF-4CB1-9F04-E6D553113289}.Debug|x64.ActiveCfg = Debug|Any CPU
{55FA063E-A4AF-4CB1-9F04-E6D553113289}.Debug|x64.Build.0 = Debug|Any CPU
{55FA063E-A4AF-4CB1-9F04-E6D553113289}.Debug|x86.ActiveCfg = Debug|Any CPU
{55FA063E-A4AF-4CB1-9F04-E6D553113289}.Debug|x86.Build.0 = Debug|Any CPU
{55FA063E-A4AF-4CB1-9F04-E6D553113289}.Release|Any CPU.ActiveCfg = Release|Any CPU
{55FA063E-A4AF-4CB1-9F04-E6D553113289}.Release|Any CPU.Build.0 = Release|Any CPU
{55FA063E-A4AF-4CB1-9F04-E6D553113289}.Release|x64.ActiveCfg = Release|Any CPU
{55FA063E-A4AF-4CB1-9F04-E6D553113289}.Release|x64.Build.0 = Release|Any CPU
{55FA063E-A4AF-4CB1-9F04-E6D553113289}.Release|x86.ActiveCfg = Release|Any CPU
{55FA063E-A4AF-4CB1-9F04-E6D553113289}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand All @@ -76,6 +90,7 @@ Global
{D117800F-072D-4AE4-9679-3E2A129A1A3C} = {FD3B44E6-66B3-4C58-B590-FB11B9CF6FF7}
{2450525D-627D-4ABA-ACF0-FA1AA76CE4A0} = {FD3B44E6-66B3-4C58-B590-FB11B9CF6FF7}
{2965C7BF-B5DD-4345-9DFD-4E6B7D93DC0A} = {FD3B44E6-66B3-4C58-B590-FB11B9CF6FF7}
{55FA063E-A4AF-4CB1-9F04-E6D553113289} = {FD3B44E6-66B3-4C58-B590-FB11B9CF6FF7}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {2FBAFFCF-2E42-43DD-B5D2-EFB906701CBF}
Expand Down
69 changes: 0 additions & 69 deletions ProcessMemoryDataFinder/API/Internals.cs

This file was deleted.

98 changes: 98 additions & 0 deletions ProcessMemoryDataFinder/API/Memory/LinuxMemoryReader.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;

namespace ProcessMemoryDataFinder.API.Memory
{
internal class LinuxMemoryReader : MemoryReader
{
public LinuxMemoryReader(int intPtrSize) : base(intPtrSize)
{
}

public override List<MEMORY_BASIC_INFORMATION> ReadProcessMaps(IntPtr processHandle, int processPID)
{
var result = new List<MEMORY_BASIC_INFORMATION>();
var rawProcessMaps = File.ReadAllLines($"/proc/{processPID}/maps");
for (int i = 0; i < rawProcessMaps.Length; i++)
{
var line = rawProcessMaps[i].AsSpan();
var addressStrLength = line.IndexOf('-');
var startAddressSpan = line[0..addressStrLength];
var endAddressSpan = line[(addressStrLength + 1)..(addressStrLength * 2 + 1)];
var flagsSpan = line[(addressStrLength * 2 + 2)..(addressStrLength * 2 + 6)];

var memInfo = new MEMORY_BASIC_INFORMATION();
memInfo.BaseAddress = new IntPtr(long.Parse(startAddressSpan, System.Globalization.NumberStyles.HexNumber));
var endRegionAddress = new IntPtr(long.Parse(endAddressSpan, System.Globalization.NumberStyles.HexNumber));
memInfo.RegionSize = IntPtrMath.SubstractIntPtrs(endRegionAddress, memInfo.BaseAddress);
//flags: rwxp
if (flagsSpan[1] != '-')
result.Add(memInfo);
}

return result;
}

public override bool ReadProcessMemory(IntPtr processHandle, int processPID, IntPtr address, uint size, byte[] targetArray, out int bytesRead)
=> ReadProcessMemoryUnsafe(address, processPID, size, targetArray, out bytesRead);

protected static unsafe bool ReadProcessMemoryUnsafe(IntPtr address, int processId, uint size, byte[] dumpArray, out int bytesRead)
{
//TODO: create block of memory upfront and recreate if size is less than requested.
var dumpPointer = Marshal.AllocCoTaskMem(dumpArray.Length);
try
{
var localIo = new iovec
{
iov_base = dumpPointer.ToPointer(),
iov_len = (int)size
};
var remoteIo = new iovec
{
iov_base = address.ToPointer(),
iov_len = (int)size
};

bytesRead = process_vm_readv(processId, &localIo, 1, &remoteIo, 1, 0);
if (bytesRead < 0)
return false;

//TODO: use spans
Marshal.Copy(dumpPointer, dumpArray, 0, bytesRead);
}
finally
{
Marshal.FreeCoTaskMem(dumpPointer);
}

return true;
}

[StructLayout(LayoutKind.Sequential)]
unsafe struct iovec
{
public void* iov_base;
public int iov_len;
}

/// <summary>
/// https://linux.die.net/man/2/process_vm_readv
/// </summary>
/// <param name="pid">Process Id</param>
/// <param name="local_iov">return struct buffer(s) to write the read data to.</param>
/// <param name="liovcnt">Amount of return structs provided. Unused here, always 1</param>
/// <param name="remote_iov">struct(s) containing address to read data from.</param>
/// <param name="riovcnt">Amount of address structs provided. Unused here, always 1</param>
/// <param name="flags">Unused, must be 0</param>
/// <returns>Amount of bytes read or -1 on error</returns>
[DllImport("libc", SetLastError = true)]
private static extern unsafe int process_vm_readv(int pid,
iovec* local_iov,
ulong liovcnt,
iovec* remote_iov,
ulong riovcnt,
ulong flags);
}
}
17 changes: 17 additions & 0 deletions ProcessMemoryDataFinder/API/Memory/MEMORY_BASIC_INFORMATION.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using System;
using System.Runtime.InteropServices;

namespace ProcessMemoryDataFinder.API.Memory
{
[StructLayout(LayoutKind.Sequential)]
public struct MEMORY_BASIC_INFORMATION
{
public IntPtr BaseAddress;
public IntPtr AllocationBase;
public uint AllocationProtect;
public IntPtr RegionSize;
public uint State;
public uint Protect;
public uint Type;
}
}
10 changes: 10 additions & 0 deletions ProcessMemoryDataFinder/API/Memory/Math/IIntPtrMath.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
using System;

namespace ProcessMemoryDataFinder.API.Memory.Math
{
public interface IIntPtrMath
{
IntPtr SumIntPtrs(IntPtr first, IntPtr second);
IntPtr SubstractIntPtrs(IntPtr first, IntPtr second);
}
}
Loading