use std::collections::BTreeMap;
use windows::Win32::Foundation::{GetLastError, SetLastError, HANDLE, INVALID_HANDLE_VALUE, NO_ERROR};
use windows::Win32::Storage::FileSystem::{GetFileType, FILE_TYPE_CHAR, FILE_TYPE_DISK, FILE_TYPE_PIPE};
use crate::error::Error;
use crate::stdio::Fd;
const FOPEN: u8 = 0x01; const FPIPE: u8 = 0x08; const FDEV: u8 = 0x40;
const HANDLE_SIZE: usize = size_of::<HANDLE>();
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum FdKind {
Pipe,
File,
CharDev,
}
pub(crate) struct FdTable {
pub bytes: Vec<u8>,
pub handles: Vec<HANDLE>,
}
pub(crate) fn classify(h: HANDLE) -> Result<FdKind, Error> {
unsafe { SetLastError(NO_ERROR) };
let file_type = unsafe { GetFileType(h) };
if file_type == FILE_TYPE_PIPE {
Ok(FdKind::Pipe)
} else if file_type == FILE_TYPE_CHAR {
Ok(FdKind::CharDev)
} else if file_type == FILE_TYPE_DISK {
Ok(FdKind::File)
} else {
let err = unsafe { GetLastError() };
if err == NO_ERROR {
Ok(FdKind::File)
} else {
Err(Error::Io(std::io::Error::from_raw_os_error(err.0 as i32)))
}
}
}
fn present_flag(kind: FdKind) -> u8 {
let kind_bits = match kind {
FdKind::Pipe => FPIPE,
FdKind::CharDev => FDEV,
FdKind::File => 0,
};
FOPEN | kind_bits
}
pub(crate) fn encoded_len(maxfd: i32) -> usize {
match usize::try_from(maxfd)
.ok()
.and_then(|m| m.checked_add(1))
.and_then(|n| n.checked_mul(1 + HANDLE_SIZE))
.and_then(|x| x.checked_add(4))
{
Some(len) if table_fits(len) => len,
_ => usize::MAX,
}
}
pub(crate) fn table_fits(byte_len: usize) -> bool {
byte_len <= u16::MAX as usize
}
pub(crate) fn encode(entries: &BTreeMap<Fd, (HANDLE, FdKind)>) -> FdTable {
let maxfd: i32 = entries.keys().next_back().map_or(-1, |fd| fd.raw());
debug_assert!(
entries.is_empty() || table_fits(encoded_len(maxfd)),
"encode called past the size cap; gate on table_fits(encoded_len(maxfd)) first"
);
let n: usize = usize::try_from(maxfd).map_or(0, |m| m + 1);
let mut bytes = Vec::with_capacity((1 + HANDLE_SIZE).saturating_mul(n).saturating_add(4));
bytes.extend_from_slice(&(n as i32).to_le_bytes());
let mut handles: Vec<HANDLE> = Vec::new();
for i in 0..n {
match entries.get(&Fd::from_raw(i as i32)) {
Some((_, kind)) => bytes.push(present_flag(*kind)),
None => bytes.push(0),
}
}
for i in 0..n {
match entries.get(&Fd::from_raw(i as i32)) {
Some((h, _)) => {
bytes.extend_from_slice(&(h.0 as usize).to_ne_bytes());
handles.push(*h);
}
None => bytes.extend_from_slice(&(INVALID_HANDLE_VALUE.0 as usize).to_ne_bytes()),
}
}
FdTable { bytes, handles }
}
#[cfg(test)]
#[path = "crt_fds_tests.rs"]
mod crt_fds_tests;