using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
namespace read_memory_64_bit_linux
{
public struct MEMORY_BASIC_INFORMATION64
{
public ulong BaseAddress;
public ulong AllocationBase;
public int AllocationProtect;
public int __alignment1;
public ulong RegionSize;
public int State;
public int Protect;
public int Type;
public int __alignment2;
}
public enum MemoryInformationState : int
{
MEM_COMMIT = 0x1000,
MEM_FREE = 0x10000,
MEM_RESERVE = 0x2000,
}
public enum MemoryInformationType : int
{
MEM_IMAGE = 0x1000000,
MEM_MAPPED = 0x40000,
MEM_PRIVATE = 0x20000,
}
[Flags]
public enum MemoryInformationProtection : int
{
PAGE_EXECUTE = 0x10,
PAGE_EXECUTE_READ = 0x20,
PAGE_EXECUTE_READWRITE = 0x40,
PAGE_EXECUTE_WRITECOPY = 0x80,
PAGE_NOACCESS = 0x01,
PAGE_READONLY = 0x02,
PAGE_READWRITE = 0x04,
PAGE_WRITECOPY = 0x08,
PAGE_TARGETS_INVALID = 0x40000000,
PAGE_TARGETS_NO_UPDATE = 0x40000000,
PAGE_GUARD = 0x100,
PAGE_NOCACHE = 0x200,
PAGE_WRITECOMBINE = 0x400,
}
class Program
{
static int Main(string[] args)
{
// ... (command-line parsing as in the original code)
var processIdArgument = /* ... get from command line arguments */ "1234";
var processId = int.Parse(processIdArgument);
var processSampleFile = GetProcessSampleFileFromProcessId(processId);
// ... rest of the code
return 0;
}
static byte[] GetProcessSampleFileFromProcessId(int processId)
{
var logEntries = new List<string>();
void logLine(string lineText)
{
logEntries.Add(lineText);
Console.WriteLine(lineText);
}
logLine("Reading from process " + processId + ".");
var committedRegions = new List<(ulong baseAddress, byte[] content)>();
using (var mapsFile = new StreamReader($"/proc/{processId}/maps")) {
string line;
while ((line = mapsFile.ReadLine()) != null) {
var match = Regex.Match(line, @"^([0-9a-fA-F]+)-([0-9a-fA-F]+)\s+([rwxps-]+)\s+([0-9a-fA-F]+)\s+([0-9a-fA-F]+)\s+([0-9]+)\s*(.*)$");
if (!match.Success)
continue;
var startAddress = ulong.Parse(match.Groups[1].Value, System.Globalization.NumberStyles.HexNumber);
var endAddress = ulong.Parse(match.Groups[2].Value, System.Globalization.NumberStyles.HexNumber);
var permissions = match.Groups[3].Value;
var offset = ulong.Parse(match.Groups[4].Value, System.Globalization.NumberStyles.HexNumber);
var dev = match.Groups[5].Value;
var inode = int.Parse(match.Groups[6].Value);
var pathname = match.Groups[7].Value;
var regionSize = endAddress - startAddress;
logLine($"{startAddress}-{endAddress -1} : {regionSize} bytes, permissions = {permissions}, pathname = {pathname}");
var regionProtection =
(permissions.Contains('r') ? MemoryInformationProtection.PAGE_READONLY : 0) |
(permissions.Contains('w') ? MemoryInformationProtection.PAGE_READWRITE : 0) |
(permissions.Contains('x') ? MemoryInformationProtection.PAGE_EXECUTE : 0);
if (!permissions.Contains('r'))
continue;
using (var memFile = new FileStream($"/proc/{processId}/mem", FileMode.Open, FileAccess.Read)) {
memFile.Seek((long)startAddress, SeekOrigin.Begin);
var regionContentBuffer = new byte[regionSize];
var bytesRead = memFile.Read(regionContentBuffer, 0, regionContentBuffer.Length);
if (bytesRead != regionContentBuffer.Length)
throw new Exception($"Failed to ReadProcessMemory at 0x{startAddress:X}: Only read " + bytesRead + " bytes.");
committedRegions.Add((startAddress, regionContentBuffer));
}
}
}
logLine($"Found {committedRegions.Count} committed regions with a total size of {committedRegions.Select(region => region.content.Length).Sum()}.");
return ProcessSample.ZipArchiveFromProcessSample(committedRegions.ToImmutableList(), logEntries.ToImmutableList());
}
// ... (other classes, e.g. EveOnline64, MemoryReader, ProcessSample adapted to work with Linux)
}
class ProcessSample
{
static public byte[] ZipArchiveFromProcessSample(
IImmutableList<(ulong baseAddress, byte[] content)> memoryRegions,
IImmutableList<string> logEntries)
{
var zipArchiveEntries =
memoryRegions.ToImmutableDictionary(
region => (IImmutableList<string>)(new[] { "Process", "Memory", $"0x{region.baseAddress:X}" }.ToImmutableList()),
region => region.content)
.Add(new[] { "copy-memory-log" }.ToImmutableList(), System.Text.Encoding.UTF8.GetBytes(String.Join("\n", logEntries)));
return Pine.ZipArchive.ZipArchiveFromEntries(zipArchiveEntries);
}
static public (IImmutableList<(ulong baseAddress, byte[] content)> memoryRegions, IImmutableList<string> copyMemoryLog) ProcessSampleFromZipArchive(byte[] sampleFile)
{
var files =
Pine.ZipArchive.EntriesFromZipArchive(sampleFile);
IEnumerable<(IImmutableList<string> filePath, byte[] fileContent)> GetFilesInDirectory(IImmutableList<string> directory)
{
foreach (var fileFullPathAndContent in files)
{
var fullPath = fileFullPathAndContent.name.Split(new[] { '/', '\\' });
if (!fullPath.Take(directory.Count).SequenceEqual(directory))
continue;
yield return (fullPath.Skip(directory.Count).ToImmutableList(), fileFullPathAndContent.content);
}
}
var memoryRegions =
GetFilesInDirectory(ImmutableList.Create("Process", "Memory"))
.Where(fileSubpathAndContent => fileSubpathAndContent.filePath.Count == 1)
.Select(fileSubpathAndContent =>
{
var baseAddressBase16 = System.Text.RegularExpressions.Regex.Match(fileSubpathAndContent.filePath.Single(), @"0x(.+)").Groups[1].Value;
var baseAddress = ulong.Parse(baseAddressBase16, System.Globalization.NumberStyles.HexNumber);
return (baseAddress, content: fileSubpathAndContent.fileContent);
}).ToImmutableList();
return (memoryRegions, null);
}
}
}