galaxy brain 2: bit of restructure (Bootstrap)

This commit is contained in:
Mino 2020-03-11 11:52:51 +09:00
parent 2438a89867
commit 350d2961c1
19 changed files with 345 additions and 136 deletions

View file

@ -0,0 +1,190 @@
using Dalamud.Bootstrap.Windows;
using Microsoft.Win32.SafeHandles;
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
namespace Dalamud.Bootstrap
{
/// <summary>
/// TODO
/// </summary>
internal sealed partial class Process : IDisposable
{
private SafeProcessHandle m_handle;
/// <summary>
/// Creates a process object that can be used to manipulate process's internal state.
/// </summary>
/// <param name="handle">A process handle. Note that this functinon will take the ownership of the handle.</param>
public Process(SafeProcessHandle handle)
{
m_handle = handle;
}
public void Dispose()
{
m_handle?.Dispose();
m_handle = null!;
}
public static Process Open(uint pid)
{
const PROCESS_ACCESS_RIGHT access = PROCESS_ACCESS_RIGHT.PROCESS_VM_OPERATION
| PROCESS_ACCESS_RIGHT.PROCESS_VM_READ
// | PROCESS_ACCESS_RIGHT.PROCESS_VM_WRITE // we don't need it for now
| PROCESS_ACCESS_RIGHT.PROCESS_QUERY_LIMITED_INFORMATION
| PROCESS_ACCESS_RIGHT.PROCESS_QUERY_INFORMATION
| PROCESS_ACCESS_RIGHT.PROCESS_CREATE_THREAD
| PROCESS_ACCESS_RIGHT.PROCESS_TERMINATE;
var handle = Win32.OpenProcess((uint) access, false, pid);
if (handle.IsInvalid)
{
throw new Win32Exception();
}
return new Process(handle);
}
public void Terminate(uint exitCode = 0)
{
if (!Win32.TerminateProcess(m_handle, exitCode))
{
throw new Win32Exception();
}
}
/// <summary>
/// Reads the process memory.
/// </summary>
/// <returns>
/// The number of bytes that is actually read.
/// </returns>
private int ReadMemory(IntPtr address, Span<byte> destination)
{
unsafe
{
fixed (byte* pDest = destination)
{
IntPtr bytesRead;
if (!Win32.ReadProcessMemory(m_handle, (void*)address, pDest, (IntPtr)destination.Length, &bytesRead))
{
throw new Win32Exception();
}
// this is okay as the length of the span can't be longer than int.Max
return (int)bytesRead;
}
}
}
private void ReadMemoryExact(IntPtr address, Span<byte> destination)
{
var totalBytesRead = 0;
while (totalBytesRead < destination.Length)
{
var bytesRead = ReadMemory(address + totalBytesRead, destination[totalBytesRead..]);
if (bytesRead == 0)
{
// prolly page fault; there's not much we can do here
throw new Win32Exception();
}
totalBytesRead += bytesRead;
}
}
private byte[] ReadMemoryExact(IntPtr address, int length)
{
var buffer = new byte[length];
ReadMemoryExact(address, buffer);
return buffer;
}
private T ReadMemoryValue<T>(IntPtr address) where T : unmanaged
{
unsafe
{
// This assumes that size of T is small enough to be safely allocated on the stack.
Span<byte> buffer = stackalloc byte[sizeof(T)];
ReadMemoryExact(address, buffer);
// this is still far better than allocating the temporary buffer on the heap when sizeof(T) is small enough.
return MemoryMarshal.Read<T>(buffer);
}
}
private IntPtr ReadPebAddress()
{
unsafe
{
var info = new PROCESS_BASIC_INFORMATION();
var status = Win32.NtQueryInformationProcess(m_handle, PROCESSINFOCLASS.ProcessBasicInformation, &info, sizeof(PROCESS_BASIC_INFORMATION), (IntPtr*)IntPtr.Zero);
if (!status.Success)
{
throw new NtException(status);
}
return info.PebBaseAddress;
}
}
public string[] ReadCommandLine()
{
unsafe
{
// Find where the command line is allocated
var pebAddr = ReadPebAddress();
var peb = ReadMemoryValue<PEB>(pebAddr);
var procParam = ReadMemoryValue<RTL_USER_PROCESS_PARAMETERS>(peb.ProcessParameters);
// Read the command line (which is utf16-like string)
var commandLine = ReadMemoryExact(procParam.CommandLine.Buffer, procParam.CommandLine.Length);
return ParseCommandLine(commandLine);
}
}
private static string[] ParseCommandLine(ReadOnlySpan<byte> commandLine)
{
unsafe
{
char** argv;
int argc;
fixed (byte* pCommandLine = commandLine)
{
// TODO: maybe explain why we can't just call .Split(' ')
// https://docs.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-commandlinetoargvw
argv = Win32.CommandLineToArgvW(pCommandLine, &argc);
}
if (argv == null)
{
throw new Win32Exception();
}
try
{
var arguments = new string[argc];
for (var i = 0; i < argc; i++)
{
arguments[i] = new string(argv[i]);
}
return arguments;
}
finally
{
Win32.LocalFree(argv);
}
}
}
}
}

View file

@ -0,0 +1,151 @@
using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;
namespace Dalamud.Bootstrap.Windows
{
internal static unsafe class Win32
{
[DllImport("kernel32", CallingConvention = CallingConvention.Winapi, SetLastError = true)]
public static extern SafeProcessHandle OpenProcess(uint dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, uint dwProcessId);
[DllImport("kernel32", CallingConvention = CallingConvention.Winapi, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool TerminateProcess(SafeProcessHandle hProcess, uint uExitCode);
[DllImport("ntdll", CallingConvention = CallingConvention.Winapi, SetLastError = true)]
public static extern NtStatus NtQueryInformationProcess(SafeProcessHandle processHandle, PROCESSINFOCLASS processInfoClass, void* processInformation, int processInformationLength, IntPtr* returnLength);
[DllImport("kernel32", CallingConvention = CallingConvention.Winapi, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ReadProcessMemory(SafeProcessHandle hProcess, void* lpBaseAddress, void* lpBuffer, IntPtr nSize, IntPtr* lpNumberOfBytesRead);
[DllImport("kernel32", CallingConvention = CallingConvention.Winapi, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WriteProcessMemory(SafeProcessHandle hProcess, void* lpBaseAddress, void* lpBuffer, IntPtr nSize, IntPtr* lpNumberOfBytesWritten);
[DllImport("kernel32", CallingConvention = CallingConvention.Winapi, SetLastError = true)]
public static extern void* LocalFree(void* hMem);
[DllImport("shell32", CallingConvention = CallingConvention.Winapi, SetLastError = true)]
public static extern char** CommandLineToArgvW(void* lpCmdLine, int* pNumArgs);
}
[StructLayout(LayoutKind.Sequential)]
internal partial struct NtStatus
{
public uint Value { get; }
}
internal partial struct NtStatus
{
public NtStatus(uint value)
{
Value = value;
}
/// <summary>
/// Equivalent to NT_SUCCESS
/// </summary>
public bool Success => Value <= 0x7FFFFFFF;
/// <summary>
/// Equivalent to NT_INFORMATION
/// </summary>
public bool Information => 0x40000000 <= Value && Value <= 0x7FFFFFFF;
/// <summary>
/// Equivalent to NT_WARNING
/// </summary>
public bool Warning => 0x80000000 <= Value && Value <= 0xBFFFFFFF;
/// <summary>
/// Equivalent to NT_ERROR
/// </summary>
public bool Error => 0xC0000000 <= Value;
}
[StructLayout(LayoutKind.Sequential)]
internal struct UNICODE_STRING
{
public ushort Length;
public ushort MaximumLength;
public IntPtr Buffer;
}
internal enum PROCESSINFOCLASS : uint
{
ProcessBasicInformation = 0,
ProcessDebugPort = 7,
ProcessWow64Information = 26,
ProcessImageFileName = 27,
ProcessBreakOnTermination = 29,
ProcessSubsystemInformation = 75,
}
[StructLayout(LayoutKind.Sequential)]
internal struct PROCESS_BASIC_INFORMATION
{
// https://github.com/processhacker/processhacker/blob/e43d7c0513ec5368c3309a58c9f2c2a3ca5de367/phnt/include/ntpsapi.h#L272
public NtStatus ExitStatus;
public IntPtr PebBaseAddress;
public IntPtr AffinityMask;
public IntPtr BasePriority;
public IntPtr UniqueProcessId;
public IntPtr InheritedFromUniqueProcessId;
}
[StructLayout(LayoutKind.Sequential)]
internal struct PEB
{
// https://github.com/processhacker/processhacker/blob/238287786b80abad647b988e60f69090cab4c8fe/phnt/include/ntpebteb.h#L57-L218
public byte InheritedAddressSpace;
public byte ReadImageFileExecOptions;
public byte BeingDebugged;
public byte BitField;
public IntPtr Mutant;
public IntPtr ImageBaseAddress;
public IntPtr Ldr;
public IntPtr ProcessParameters;
// ..snip..
}
[StructLayout(LayoutKind.Sequential)]
internal struct RTL_USER_PROCESS_PARAMETERS
{
public uint MaximumLength;
public uint LengthInitialized;
public uint Flags;
public uint DebugFlags;
public IntPtr ConsoleHandle;
public uint ConsoleFlags;
public IntPtr StandardInput;
public IntPtr StandardOutput;
public IntPtr StandardError;
public UNICODE_STRING CurrentDirectory_DosPath;
public IntPtr CurrentDirectory_Handle;
public UNICODE_STRING DllPath;
public UNICODE_STRING ImagePathName;
public UNICODE_STRING CommandLine;
// ..snip..
}
[Flags]
internal enum PROCESS_ACCESS_RIGHT : uint
{
PROCESS_TERMINATE = 0x1,
PROCESS_CREATE_THREAD = 0x2,
PROCESS_VM_OPERATION = 0x8,
PROCESS_VM_READ = 0x10,
PROCESS_VM_WRITE = 0x20,
PROCESS_DUP_HANDLE = 0x40,
PROCESS_CREATE_PROCESS = 0x80,
PROCESS_SET_QUOTA = 0x100,
PROCESS_SET_INFORMATION = 0x200,
PROCESS_QUERY_INFORMATION = 0x400,
PROCESS_SUSPEND_RESUME = 0x800,
PROCESS_QUERY_LIMITED_INFORMATION = 0x1000,
SYNCHRONIZE = 0x100000,
}
}