using System.Collections.Generic;
using System.Diagnostics;
using Process = System.Diagnostics.Process;
using WhiteMagic.Execution;
using WhiteMagic.Hooking;
using WhiteMagic.Memory;
using WhiteMagic.ProcessDiscovery;
using WhiteMagic.Thread;
using WhiteMagic.Windows;
namespace WhiteMagic;
///
/// High-level entry point for a WhiteMagic session. Opens a process, exposes the
/// memory reader, execution tiers, hooking managers, and the
/// indexer.
///
public sealed class Magic : IDisposable
{
/// The underlying memory reader for this session.
public MemoryBase Memory { get; }
/// Out-of-process execution via CreateRemoteThread.
public RemoteThreadExecutor RemoteThread { get; }
/// Named byte-patch manager.
public PatchManager PatchManager => Memory.PatchManager;
/// Inline-detour manager (in-process only).
public DetourManager DetourManager => Memory.DetourManager;
///
/// Returns the memory region that contains .
///
public MemoryRegion QueryRegion(IntPtr address) => Memory.QueryRegion(address);
///
/// Enumerates the committed and reserved regions of the target process address space.
///
public IEnumerable Regions => Memory.EnumerateRegions();
///
/// Factory for discovering and operating on the target process's threads.
///
public ThreadFactory Threads => new ThreadFactory(Memory);
private Magic(MemoryBase memory)
{
Memory = memory;
RemoteThread = new RemoteThreadExecutor(memory);
}
/// Opens an external process for reading, writing, and execution.
public static Magic Open(Process process)
{
return new Magic(new ExternalReader(process));
}
///
/// Opens a target process by its image name. Throws if zero or more than one match.
///
public static Magic Open(string processName)
{
using Process process = ApplicationFinder.OpenProcess(processName);
return Open(process);
}
///
/// Opens the process that owns the top-level window with the specified title.
///
public static Magic OpenByWindowTitle(string title)
{
using Process process = ApplicationFinder.OpenByWindowTitle(title);
return Open(process);
}
///
/// Opens the process that owns the specified window handle.
///
public static Magic OpenByWindowHandle(IntPtr handle)
{
using Process process = ApplicationFinder.OpenByWindowHandle(handle);
return Open(process);
}
/// Creates an in-process session for the current process.
public static Magic OpenInProcess()
{
return new Magic(new InProcessReader());
}
///
/// Creates a main-thread pump that hooks the per-frame function at
/// .
///
public MainThreadPump CreateMainThreadPump(IntPtr frameAddress)
{
return new MainThreadPump(DetourManager, frameAddress);
}
/// Returns a at .
public RemotePointer this[IntPtr address] => new RemotePointer(Memory, address);
/// Returns the loaded named
/// (e.g. magic["user32"]["MessageBoxA"]).
public RemoteModule this[string moduleName] => new RemoteModule(this, moduleName);
///
public void Dispose()
{
Memory.Dispose();
}
}