use core::ffi::c_void;
use core::ptr;
use crate::io::{IoSlice, IoSliceMut, SeekFrom};
use crate::sys::{cvt, dll, nt_error};
use crate::{BorrowedHandle, ErrorKind, OwnedHandle, Result};
#[repr(C)]
pub(crate) struct Overlapped {
pub(crate) internal: usize,
pub(crate) internal_high: usize,
pub(crate) offset: u32,
pub(crate) offset_high: u32,
pub(crate) event: *mut c_void,
}
impl Overlapped {
pub(crate) fn at(offset: u64) -> Self {
Self {
internal: 0,
internal_high: 0,
offset: offset as u32,
offset_high: (offset >> 32) as u32,
event: ptr::null_mut(),
}
}
}
#[repr(C)]
#[derive(Clone, Copy)]
pub(crate) struct OverlappedEntry {
pub(crate) key: usize,
pub(crate) overlapped: *mut c_void,
pub(crate) internal: usize,
pub(crate) bytes: u32,
}
impl OverlappedEntry {
pub(crate) const EMPTY: Self = Self {
key: 0,
overlapped: ptr::null_mut(),
internal: 0,
bytes: 0,
};
}
const _: () = {
assert!(size_of::<OverlappedEntry>() == 4 * size_of::<usize>());
assert!(size_of::<Overlapped>() == 3 * size_of::<usize>() + 8);
};
dll!("kernel32.dll" {
pub(crate) fn WaitForSingleObject(handle: *mut c_void, milliseconds: u32) -> u32;
pub(crate) fn Sleep(milliseconds: u32);
fn SetFilePointerEx(handle: *mut c_void, distance: i64, pos: *mut i64, method: u32) -> i32;
fn CreatePipe(
read: *mut *mut c_void,
write: *mut *mut c_void,
attributes: *const c_void,
size: u32,
) -> i32;
fn DuplicateHandle(
source_process: *mut c_void,
source: *mut c_void,
target_process: *mut c_void,
target: *mut *mut c_void,
access: u32,
inherit: i32,
options: u32,
) -> i32;
fn GetCurrentProcess() -> *mut c_void;
fn GetStdHandle(which: u32) -> *mut c_void;
fn GetConsoleMode(handle: *mut c_void, mode: *mut u32) -> i32;
fn SetHandleInformation(handle: *mut c_void, mask: u32, flags: u32) -> i32;
fn GetHandleInformation(handle: *mut c_void, flags: *mut u32) -> i32;
fn GetNamedPipeHandleStateW(
handle: *mut c_void,
state: *mut u32,
instances: *mut u32,
max_collection: *mut u32,
collect_timeout: *mut u32,
user_name: *mut u16,
user_name_len: u32,
) -> i32;
fn SetNamedPipeHandleState(
handle: *mut c_void,
mode: *const u32,
max_collection: *const u32,
collect_timeout: *const u32,
) -> i32;
});
#[repr(C)]
pub(crate) struct IoStatusBlock {
pub(crate) status: usize,
pub(crate) information: usize,
}
impl IoStatusBlock {
pub(crate) const PENDING: Self = Self {
status: STATUS_PENDING as usize,
information: 0,
};
}
#[derive(Default)]
#[repr(C)]
struct FilePipeLocalInformation {
pipe_type: u32,
configuration: u32,
maximum_instances: u32,
current_instances: u32,
inbound_quota: u32,
read_data_available: u32,
outbound_quota: u32,
write_quota_available: u32,
state: u32,
end: u32,
}
dll!("ntdll.dll" {
pub(crate) fn NtReadFile(
handle: *mut c_void,
event: *mut c_void,
apc_routine: *const c_void,
apc_context: *const c_void,
status: *mut IoStatusBlock,
buf: *mut u8,
len: u32,
offset: *const i64,
key: *const u32,
) -> i32;
pub(crate) fn NtWriteFile(
handle: *mut c_void,
event: *mut c_void,
apc_routine: *const c_void,
apc_context: *const c_void,
status: *mut IoStatusBlock,
buf: *const u8,
len: u32,
offset: *const i64,
key: *const u32,
) -> i32;
fn NtQueryInformationFile(
handle: *mut c_void,
status: *mut IoStatusBlock,
info: *mut c_void,
len: u32,
class: i32,
) -> i32;
});
const FILE_PIPE_LOCAL_INFORMATION: i32 = 24;
pub(crate) const STATUS_PENDING: i32 = 0x103;
const STATUS_BUFFER_OVERFLOW: i32 = 0x8000_0005u32 as i32;
const INFINITE: u32 = u32::MAX;
const WAIT_TIMEOUT: u32 = 258;
const ERROR_HANDLE_EOF: i32 = 38;
const ERROR_BROKEN_PIPE: i32 = 109;
const ERROR_NO_DATA: i32 = 232;
const PIPE_NOWAIT: u32 = 1;
const PIPE_READMODE_MESSAGE: u32 = 2;
const DUPLICATE_SAME_ACCESS: u32 = 2;
const HANDLE_FLAG_INHERIT: u32 = 1;
const STD_INPUT_HANDLE: u32 = -10i32 as u32;
const STD_OUTPUT_HANDLE: u32 = -11i32 as u32;
const STD_ERROR_HANDLE: u32 = -12i32 as u32;
#[derive(Clone, Copy)]
#[repr(C)]
pub(crate) struct RawIoSlice {
len: u32,
base: *mut u8,
}
impl RawIoSlice {
#[inline]
pub(crate) fn new(base: *mut u8, len: usize) -> Self {
Self {
len: len.min(u32::MAX as usize) as u32,
base,
}
}
#[inline]
pub(crate) fn ptr(&self) -> *mut u8 {
self.base
}
#[inline]
pub(crate) fn len(&self) -> usize {
self.len as usize
}
}
fn len32(len: usize) -> u32 {
len.min(u32::MAX as usize) as u32
}
const SHARED_SIGNAL_MS: u32 = 20;
pub(crate) unsafe fn wait_completion(signal: *mut c_void, own: bool, status: *const usize) -> i32 {
let current = || unsafe { ptr::read_volatile(status) } as i32;
loop {
let status = current();
if status != STATUS_PENDING {
return status;
}
let timeout = if own { INFINITE } else { SHARED_SIGNAL_MS };
let waited = unsafe { WaitForSingleObject(signal, timeout) };
if waited != WAIT_TIMEOUT && current() == STATUS_PENDING {
unsafe { Sleep(1) };
}
}
}
fn file_offset(offset: u64) -> Result<i64> {
i64::try_from(offset).map_err(|_| ErrorKind::InvalidInput.into())
}
pub(crate) unsafe fn completed(
handle: BorrowedHandle<'_>,
status: i32,
block: *const IoStatusBlock,
) -> (i32, usize) {
let status = if status == STATUS_PENDING {
unsafe { wait_completion(handle.as_raw(), false, &raw const (*block).status) }
} else {
status
};
(status, unsafe {
ptr::read_volatile(&raw const (*block).information)
})
}
fn nt_read(handle: BorrowedHandle<'_>, buf: &mut [u8], offset: Option<u64>) -> Result<usize> {
let offset = offset.map(file_offset).transpose()?;
let mut block = IoStatusBlock::PENDING;
let (status, done) = unsafe {
let status = NtReadFile(
handle.as_raw(),
ptr::null_mut(),
ptr::null(),
ptr::null(),
&raw mut block,
buf.as_mut_ptr(),
len32(buf.len()),
offset.as_ref().map_or(ptr::null(), ptr::from_ref),
ptr::null(),
);
completed(handle, status, &raw const block)
};
if status >= 0 || status == STATUS_BUFFER_OVERFLOW {
return Ok(done);
}
let error = nt_error(status);
match error.raw_os_error() {
ERROR_HANDLE_EOF | ERROR_BROKEN_PIPE => Ok(0),
ERROR_NO_DATA => Err(ErrorKind::WouldBlock.into()),
_ => Err(error),
}
}
fn nt_write(handle: BorrowedHandle<'_>, buf: &[u8], offset: Option<u64>) -> Result<usize> {
let offset = offset.map(file_offset).transpose()?;
let mut block = IoStatusBlock::PENDING;
let (status, done) = unsafe {
let status = NtWriteFile(
handle.as_raw(),
ptr::null_mut(),
ptr::null(),
ptr::null(),
&raw mut block,
buf.as_ptr(),
len32(buf.len()),
offset.as_ref().map_or(ptr::null(), ptr::from_ref),
ptr::null(),
);
completed(handle, status, &raw const block)
};
if status >= 0 {
Ok(done)
} else {
Err(nt_error(status))
}
}
pub(crate) fn read(handle: BorrowedHandle<'_>, buf: &mut [u8]) -> Result<usize> {
nt_read(handle, buf, None)
}
fn write_file(handle: BorrowedHandle<'_>, buf: &[u8]) -> Result<usize> {
nt_write(handle, buf, None)
}
fn pipe_room(handle: BorrowedHandle<'_>) -> Option<usize> {
let mut info = FilePipeLocalInformation::default();
let mut status_block = IoStatusBlock {
status: 0,
information: 0,
};
let status = unsafe {
NtQueryInformationFile(
handle.as_raw(),
&raw mut status_block,
(&raw mut info).cast(),
size_of::<FilePipeLocalInformation>() as u32,
FILE_PIPE_LOCAL_INFORMATION,
)
};
(status >= 0).then_some(info.write_quota_available as usize)
}
pub(crate) fn write(handle: BorrowedHandle<'_>, buf: &[u8]) -> Result<usize> {
let done = write_file(handle, buf)?;
if done > 0 || buf.is_empty() {
return Ok(done);
}
if let Some(room) = pipe_room(handle)
&& room > 0
&& room < buf.len()
{
let done = write_file(handle, &buf[..room])?;
if done > 0 {
return Ok(done);
}
}
let mut len = buf.len() / 2;
while len > 0 {
let done = write_file(handle, &buf[..len])?;
if done > 0 {
return Ok(done);
}
len /= 2;
}
Err(ErrorKind::WouldBlock.into())
}
pub(crate) fn read_at(handle: BorrowedHandle<'_>, buf: &mut [u8], offset: u64) -> Result<usize> {
nt_read(handle, buf, Some(offset))
}
pub(crate) fn write_at(handle: BorrowedHandle<'_>, buf: &[u8], offset: u64) -> Result<usize> {
nt_write(handle, buf, Some(offset))
}
pub(crate) fn read_vectored(
handle: BorrowedHandle<'_>,
bufs: &mut [IoSliceMut<'_>],
) -> Result<usize> {
match bufs.iter_mut().find(|buf| !buf.is_empty()) {
Some(buf) => read(handle, buf),
None => read(handle, &mut []),
}
}
pub(crate) fn write_vectored(handle: BorrowedHandle<'_>, bufs: &[IoSlice<'_>]) -> Result<usize> {
match bufs.iter().find(|buf| !buf.is_empty()) {
Some(buf) => write(handle, buf),
None => write(handle, &[]),
}
}
pub(crate) fn seek(handle: BorrowedHandle<'_>, pos: SeekFrom) -> Result<u64> {
let (offset, method) = match pos {
SeekFrom::Start(offset) => (offset as i64, 0),
SeekFrom::Current(offset) => (offset, 1),
SeekFrom::End(offset) => (offset, 2),
};
let mut pos = 0;
cvt(unsafe { SetFilePointerEx(handle.as_raw(), offset, &raw mut pos, method) })?;
Ok(pos as u64)
}
pub(crate) fn pipe() -> Result<(OwnedHandle, OwnedHandle)> {
let mut read = ptr::null_mut();
let mut write = ptr::null_mut();
cvt(unsafe { CreatePipe(&raw mut read, &raw mut write, ptr::null(), 0) })?;
Ok(unsafe { (OwnedHandle::from_raw(read), OwnedHandle::from_raw(write)) })
}
pub(crate) fn duplicate(handle: BorrowedHandle<'_>) -> Result<OwnedHandle> {
let mut new = ptr::null_mut();
cvt(unsafe {
let process = GetCurrentProcess();
DuplicateHandle(
process,
handle.as_raw(),
process,
&raw mut new,
0,
0,
DUPLICATE_SAME_ACCESS,
)
})?;
Ok(unsafe { OwnedHandle::from_raw(new) })
}
fn std_handle(which: u32) -> Option<BorrowedHandle<'static>> {
let handle = unsafe { GetStdHandle(which) };
if handle.is_null() || handle as isize == -1 {
return None;
}
Some(unsafe { BorrowedHandle::borrow_raw(handle) })
}
pub(crate) fn stdin() -> Option<BorrowedHandle<'static>> {
std_handle(STD_INPUT_HANDLE)
}
pub(crate) fn stdout() -> Option<BorrowedHandle<'static>> {
std_handle(STD_OUTPUT_HANDLE)
}
pub(crate) fn stderr() -> Option<BorrowedHandle<'static>> {
std_handle(STD_ERROR_HANDLE)
}
pub(crate) fn is_terminal(handle: BorrowedHandle<'_>) -> bool {
let mut mode = 0;
unsafe { GetConsoleMode(handle.as_raw(), &raw mut mode) != 0 }
}
pub(crate) fn set_inheritable(handle: BorrowedHandle<'_>, inheritable: bool) -> Result<()> {
let flags = if inheritable { HANDLE_FLAG_INHERIT } else { 0 };
cvt(unsafe { SetHandleInformation(handle.as_raw(), HANDLE_FLAG_INHERIT, flags) })
}
pub(crate) fn is_inheritable(handle: BorrowedHandle<'_>) -> Result<bool> {
let mut flags = 0;
cvt(unsafe { GetHandleInformation(handle.as_raw(), &raw mut flags) })?;
Ok(flags & HANDLE_FLAG_INHERIT != 0)
}
pub(crate) fn set_nonblocking(handle: BorrowedHandle<'_>, nonblocking: bool) -> Result<()> {
let mut state = 0;
let known = unsafe {
GetNamedPipeHandleStateW(
handle.as_raw(),
&raw mut state,
ptr::null_mut(),
ptr::null_mut(),
ptr::null_mut(),
ptr::null_mut(),
0,
)
} != 0;
let mut mode = if known {
state & PIPE_READMODE_MESSAGE
} else {
0
};
if nonblocking {
mode |= PIPE_NOWAIT;
}
cvt(unsafe {
SetNamedPipeHandleState(handle.as_raw(), &raw const mode, ptr::null(), ptr::null())
})
}