use std::ffi::c_void;
use std::mem::size_of;
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
use std::ptr::null_mut;
use windows_sys::Wdk::System::Threading::NtQueryInformationThread;
use windows_sys::Win32::Foundation::{HANDLE, INVALID_HANDLE_VALUE, LocalFree, WAIT_OBJECT_0};
use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory;
use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleW, GetProcAddress};
use windows_sys::Win32::System::Threading::{
GetCurrentProcess, GetThreadDescription, WaitForSingleObject,
};
const TEB_STACK_BASE: u64 = 0x08;
const TEB_STACK_LIMIT: u64 = 0x10;
const TEB_DEALLOCATION_STACK: u64 = 0x1478;
pub(super) unsafe fn owned(raw: HANDLE) -> Option<OwnedHandle> {
if raw.is_null() || raw == INVALID_HANDLE_VALUE {
return None;
}
Some(unsafe { OwnedHandle::from_raw_handle(raw) })
}
pub(super) fn raw(handle: &OwnedHandle) -> HANDLE {
handle.as_raw_handle()
}
pub(super) fn has_exited(handle: HANDLE) -> bool {
unsafe { WaitForSingleObject(handle, 0) == WAIT_OBJECT_0 }
}
pub(super) unsafe fn read_into(address: u64, dst: *mut u8, len: usize) -> usize {
let mut read = 0_usize;
let ok = unsafe {
ReadProcessMemory(
GetCurrentProcess(),
address as *const c_void,
dst.cast::<c_void>(),
len,
&raw mut read,
)
};
if ok == 0 { read.min(len) } else { len }
}
pub(super) fn read_u64(address: u64) -> Option<u64> {
let mut value = 0_u64;
let read = unsafe { read_into(address, (&raw mut value).cast::<u8>(), size_of::<u64>()) };
(read == size_of::<u64>()).then_some(value)
}
#[repr(C)]
struct ThreadBasicInformation {
exit_status: i32,
teb: *mut c_void,
process: usize,
thread: usize,
affinity: usize,
priority: i32,
base_priority: i32,
}
pub(super) fn teb(handle: HANDLE) -> Option<u64> {
let mut info = ThreadBasicInformation {
exit_status: 0,
teb: null_mut(),
process: 0,
thread: 0,
affinity: 0,
priority: 0,
base_priority: 0,
};
let size = u32::try_from(size_of::<ThreadBasicInformation>()).ok()?;
let status = unsafe {
NtQueryInformationThread(
handle,
0,
(&raw mut info).cast::<c_void>(),
size,
null_mut(),
)
};
(status >= 0 && !info.teb.is_null()).then_some(info.teb as u64)
}
pub(super) fn stack_bounds(teb: u64) -> Option<(u64, u64)> {
let high = read_u64(teb.checked_add(TEB_STACK_BASE)?)?;
let committed = read_u64(teb.checked_add(TEB_STACK_LIMIT)?)?;
let reserved = read_u64(teb.checked_add(TEB_DEALLOCATION_STACK)?)?;
let low = if reserved != 0 && reserved < high {
reserved
} else {
committed
};
(low != 0 && low < high && high.trailing_zeros() >= 3).then_some((low, high))
}
struct LocalString(*mut u16);
impl Drop for LocalString {
fn drop(&mut self) {
unsafe { LocalFree(self.0.cast::<c_void>()) };
}
}
pub(super) fn thread_name(handle: HANDLE) -> String {
let mut wide: *mut u16 = null_mut();
let result = unsafe { GetThreadDescription(handle, &raw mut wide) };
if result < 0 || wide.is_null() {
return String::new();
}
let owner = LocalString(wide);
let mut length = 0_usize;
while length < 4096 && unsafe { *owner.0.add(length) } != 0 {
length += 1;
}
let units = unsafe { std::slice::from_raw_parts(owner.0, length) };
String::from_utf16_lossy(units)
}
pub(super) fn export(
module: &str,
name: &std::ffi::CStr,
) -> Option<unsafe extern "system" fn() -> isize> {
let wide: Vec<u16> = module.encode_utf16().chain(Some(0)).collect();
let handle = unsafe { GetModuleHandleW(wide.as_ptr()) };
if handle.is_null() {
return None;
}
unsafe { GetProcAddress(handle, name.as_ptr().cast()) }
}