use std::io;
use windows::Wdk::System::Threading::ProcessBasicInformation;
use windows::Win32::Foundation::HANDLE;
use windows::Win32::System::Diagnostics::Debug::ReadProcessMemory;
use windows::Win32::System::Threading::{PEB, PROCESS_BASIC_INFORMATION};
use super::{open_for_resume, owner_of, process_pid_of, resume_thread, suspend_thread, thread_entries, ThreadHandle};
use crate::error::{io_context, nt_io_error, win32_io_error, Report};
#[derive(Debug)]
pub(crate) struct ProvenRoot(#[allow(dead_code, reason = "held for its suspend; closed on drop")] ThreadHandle);
pub(crate) fn prove_not_started(proc_handle: std::os::windows::io::RawHandle) -> Result<ProvenRoot, String> {
let process = HANDLE(proc_handle.cast());
let read = |what: &str, e: io::Error| format!("{what} failed: {report}", report = Report(&e));
let pid = process_pid_of(process).map_err(|e| read("GetProcessId", e))?;
let entries = thread_entries().map_err(|e| read("the thread snapshot", e))?;
let own: Vec<u32> = entries
.iter()
.filter(|e| e.th32OwnerProcessID == pid)
.map(|e| e.th32ThreadID)
.collect();
let [initial] = own[..] else {
return Err(format!(
"the snapshot lists {} threads for pid {pid}, not one",
own.len()
));
};
let call = |call: &str, e: windows::core::Error| {
read(&format!("{call} for thread {initial} of pid {pid}"), win32_io_error(e))
};
let thread = open_for_resume(initial).map_err(|e| call("OpenThread(suspend/resume)", e))?;
let owner = owner_of(&thread).map_err(|e| call("GetProcessIdOfThread", e))?;
if owner != pid {
return Err(format!("thread {initial} belongs to pid {owner}, not to pid {pid}"));
}
let previous = suspend_thread(&thread).map_err(|e| call("SuspendThread", e))?;
let Some(why) = unproved(previous, || loader_started(process)) else {
return Ok(ProvenRoot(thread));
};
match resume_thread(&thread) {
Ok(_) => Err(why),
Err(e) => Err(format!(
"{why}; undoing the read's suspend failed too: {}",
call("ResumeThread", e)
)),
}
}
fn unproved(previous: u32, loader: impl FnOnce() -> io::Result<bool>) -> Option<String> {
if previous == 0 {
return Some("its initial thread was running".to_owned());
}
match loader() {
Ok(false) => None,
Ok(true) => Some("the loader had initialised it".to_owned()),
Err(e) => Some(format!(
"reading the loader's state failed: {report}",
report = Report(&e)
)),
}
}
fn loader_started(process: HANDLE) -> io::Result<bool> {
#[cfg(test)]
super::forced(super::fault::Step::LoaderRead, None).map_err(win32_io_error)?;
let mut info = PROCESS_BASIC_INFORMATION::default();
unsafe { crate::identity::windows_query_process(process, ProcessBasicInformation, &mut info) }.map_err(
|status| {
io_context(
"NtQueryInformationProcess(ProcessBasicInformation) failed",
nt_io_error(status),
)
},
)?;
if info.PebBaseAddress.is_null() {
return Err(io::Error::other("the process has no PEB"));
}
let ldr_at = info
.PebBaseAddress
.cast::<u8>()
.wrapping_add(std::mem::offset_of!(PEB, Ldr));
let mut ldr: *mut core::ffi::c_void = std::ptr::null_mut();
let mut read = 0usize;
unsafe {
ReadProcessMemory(
process,
ldr_at.cast(),
std::ptr::addr_of_mut!(ldr).cast(),
size_of::<*mut core::ffi::c_void>(),
Some(&mut read),
)
}
.map_err(|e| io_context("ReadProcessMemory(PEB.Ldr) failed", win32_io_error(e)))?;
if read != size_of::<*mut core::ffi::c_void>() {
return Err(io::Error::other(format!(
"ReadProcessMemory(PEB.Ldr) read {read} bytes"
)));
}
Ok(!ldr.is_null())
}
#[cfg(test)]
#[path = "not_started_tests.rs"]
mod not_started_tests;