use std::ffi::{c_void, CStr, CString};
use std::fmt::Write;
use std::net::Ipv4Addr;
use std::ptr;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Condvar, Mutex};
use std::time::{Duration, Instant};
use crate::mxc_common::logger::Logger;
use crate::mxc_common::models::{PortMapping, ScriptResponse};
use crate::mxc_common::mxc_error::ApiFailure;
use crate::mxc_common::string_util::{to_wide, CoTaskMemPWSTR};
use crate::wslc_common::daemon_protocol::ExecTerminal;
use crate::wslc_common::error::{sdk_api_failure, WslcError, WslcStepError};
use crate::wslc_common::policy_mapping::VolumeMount;
use crate::wslc_common::process_env::{self, EnvScope};
use crate::wslc_common::sdk_init;
use crate::wslc_common::session_resources;
use crate::wslc_common::wslc_bindings::*;
const E_SHARING_VIOLATION: HRESULT = 0x8007_0020_u32 as HRESULT;
pub const SESSION_BOOT_TIMEOUT_MS: u32 = 180_000;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct SessionSizing {
pub cpu_count: Option<u32>,
pub memory_mb: Option<u64>,
pub gpu: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HostCapacity {
pub total_memory_mb: u64,
pub logical_cpus: u32,
}
fn host_capacity() -> Option<HostCapacity> {
use windows::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
use windows::Win32::System::Threading::{GetActiveProcessorCount, ALL_PROCESSOR_GROUPS};
let mut status = MEMORYSTATUSEX {
dwLength: std::mem::size_of::<MEMORYSTATUSEX>() as u32,
..Default::default()
};
unsafe { GlobalMemoryStatusEx(&mut status) }.ok()?;
let logical_cpus = unsafe { GetActiveProcessorCount(ALL_PROCESSOR_GROUPS) };
Some(HostCapacity {
total_memory_mb: status.ullTotalPhys / (1024 * 1024),
logical_cpus,
})
}
fn sizing_fits_host(sizing: SessionSizing, host: HostCapacity) -> Result<(), ScriptResponse> {
let Some(cpu_count) = sizing.cpu_count.filter(|cpus| *cpus > 0) else {
return Ok(());
};
if cpu_count > host.logical_cpus {
return Err(WslcError::Rejected(format!(
"cpu_count {cpu_count} exceeds the {} logical processors this host has; \
WSLc does not oversubscribe processors, though memory_mb may exceed \
installed memory because it is a ceiling rather than a reservation",
host.logical_cpus
))
.into_response());
}
Ok(())
}
pub fn check_sizing_against_host(sizing: SessionSizing) -> Result<(), ScriptResponse> {
match host_capacity() {
Some(host) => sizing_fits_host(sizing, host),
None => Ok(()),
}
}
pub(crate) fn sdk_error(context: &str, hr: HRESULT, sdk_msg: &str) -> ScriptResponse {
WslcError::sdk(context, hr, sdk_msg).into_response()
}
pub(crate) fn sdk_step_error(operation: &str, hr: HRESULT, sdk_msg: &str) -> WslcStepError {
sdk_step_error_with_context(operation, &format!("{operation} failed"), hr, sdk_msg)
}
pub(crate) fn sdk_step_error_with_context(
operation: &str,
context: &str,
hr: HRESULT,
sdk_msg: &str,
) -> WslcStepError {
WslcError::sdk(context, hr, sdk_msg)
.into_step_error()
.with_api_failure(sdk_api_failure(operation, hr))
}
pub(crate) fn cstr_bytes(field: &str, value: &str) -> Result<Vec<u8>, ScriptResponse> {
std::ffi::CString::new(value)
.map(|c| c.into_bytes_with_nul())
.map_err(|_| {
WslcError::Rejected(format!(
"{field} contains an interior NUL byte, which is not a valid C string"
))
.into_response()
})
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OutStream {
Stdout,
Stderr,
}
pub type OutputSink = Box<dyn Fn(OutStream, &[u8]) + Send + Sync>;
pub type StdinConsumer =
Box<dyn FnOnce(std::fs::File) -> std::io::Result<Box<dyn StdinControl>> + Send>;
pub trait StdinControl: Send {
fn freeze(&self);
fn close(self: Box<Self>);
}
pub struct IoContext {
pub(crate) stdout: Arc<Mutex<Vec<u8>>>,
pub(crate) stderr: Arc<Mutex<Vec<u8>>>,
pub(crate) exited: Arc<(Mutex<bool>, Condvar)>,
sink: Option<OutputSink>,
capture: Capture,
}
const MAX_CAPTURED_STREAM_BYTES: usize = 8 * 1024 * 1024;
const STREAM_TRUNCATION_MARKER: &[u8] = b"\n[output truncated: stream exceeded capture cap]\n";
fn append_capped(buf: &mut Vec<u8>, bytes: &[u8]) {
if buf.len() >= MAX_CAPTURED_STREAM_BYTES {
return;
}
let remaining = MAX_CAPTURED_STREAM_BYTES - buf.len();
if bytes.len() <= remaining {
buf.extend_from_slice(bytes);
} else {
buf.extend_from_slice(&bytes[..remaining]);
buf.extend_from_slice(STREAM_TRUNCATION_MARKER);
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Capture {
Head,
Tail(usize),
}
impl Capture {
fn append(self, buf: &mut Vec<u8>, bytes: &[u8]) {
match self {
Capture::Head => append_capped(buf, bytes),
Capture::Tail(limit) => append_newest(buf, bytes, limit),
}
}
}
fn append_newest(buf: &mut Vec<u8>, bytes: &[u8], limit: usize) {
buf.extend_from_slice(bytes);
if buf.len() <= limit {
return;
}
let excess = buf.len() - limit;
let first_whole_line = buf[excess - 1..]
.iter()
.position(|&b| b == b'\n')
.map_or(excess, |offset| excess + offset);
buf.drain(..first_whole_line);
}
unsafe extern "C" fn io_callback(
io_handle: WslcProcessIOHandle,
data: *const BYTE,
data_size: u32,
context: *mut c_void,
) {
if context.is_null() || data.is_null() || data_size == 0 {
return;
}
let ctx = &*(context as *const IoContext);
let bytes = std::slice::from_raw_parts(data, data_size as usize);
match io_handle {
WslcProcessIOHandle::WSLC_PROCESS_IO_HANDLE_STDOUT => match ctx.sink.as_ref() {
Some(sink) => sink(OutStream::Stdout, bytes),
None => {
let mut buf = ctx.stdout.lock().unwrap_or_else(|e| e.into_inner());
ctx.capture.append(&mut buf, bytes);
}
},
WslcProcessIOHandle::WSLC_PROCESS_IO_HANDLE_STDERR => match ctx.sink.as_ref() {
Some(sink) => sink(OutStream::Stderr, bytes),
None => {
let mut buf = ctx.stderr.lock().unwrap_or_else(|e| e.into_inner());
ctx.capture.append(&mut buf, bytes);
}
},
_ => {}
}
}
unsafe extern "C" fn exit_callback(_exit_code: i32, context: *mut c_void) {
if context.is_null() {
return;
}
let ctx = Arc::from_raw(context as *const IoContext);
let mut exited = ctx.exited.0.lock().unwrap_or_else(|e| e.into_inner());
*exited = true;
ctx.exited.1.notify_all();
}
pub(crate) struct CommandLineBuffers {
_argv_cstrings: Vec<Vec<u8>>,
_argv: Vec<PCSTR>,
_env_cstrings: Vec<Vec<u8>>,
_env_ptrs: Vec<PCSTR>,
}
pub(crate) unsafe fn set_command_line_and_env(
sdk: &WslcSdk,
settings: *mut WslcProcessSettings,
scope: EnvScope,
env: &[String],
script_code: &str,
) -> Result<CommandLineBuffers, WslcStepError> {
set_argv_and_env(
sdk,
settings,
&process_env::argv_words(scope, env, script_code),
&process_env::sdk_entries(scope, env),
)
}
unsafe fn set_argv_and_env(
sdk: &WslcSdk,
settings: *mut WslcProcessSettings,
argv: &[String],
env: &[String],
) -> Result<CommandLineBuffers, WslcStepError> {
let argv_cstrings = argv
.iter()
.map(|word| cstr_bytes("command", word))
.collect::<Result<Vec<_>, _>>()?;
let argv: Vec<PCSTR> = argv_cstrings.iter().map(|w| w.as_ptr() as PCSTR).collect();
let hr = sdk.WslcSetProcessSettingsCmdLine(settings, argv.as_ptr(), argv.len());
if hr != S_OK {
return Err(sdk_step_error("WslcSetProcessSettingsCmdLine", hr, ""));
}
let env_cstrings: Vec<Vec<u8>> = env
.iter()
.map(|e| cstr_bytes("environment variable", e))
.collect::<Result<Vec<_>, _>>()?;
let mut env_ptrs: Vec<PCSTR> = Vec::new();
if !env_cstrings.is_empty() {
env_ptrs = env_cstrings.iter().map(|e| e.as_ptr() as PCSTR).collect();
let hr =
sdk.WslcSetProcessSettingsEnvVariables(settings, env_ptrs.as_ptr(), env_ptrs.len());
if hr != S_OK {
return Err(sdk_step_error("WslcSetProcessSettingsEnvVariables", hr, ""));
}
}
Ok(CommandLineBuffers {
_argv_cstrings: argv_cstrings,
_argv: argv,
_env_cstrings: env_cstrings,
_env_ptrs: env_ptrs,
})
}
pub struct ProcessSettings {
raw: WslcProcessSettings,
io_ctx: Arc<IoContext>,
sdk_io_ref: SdkIoRef,
_command: CommandLineBuffers,
_cwd_cstr: Option<Vec<u8>>,
}
struct SdkIoRef(Option<*const IoContext>);
impl SdkIoRef {
fn none() -> Self {
Self(None)
}
fn disarm(&mut self) -> Option<*const IoContext> {
self.0.take()
}
}
impl Drop for SdkIoRef {
fn drop(&mut self) {
if let Some(p) = self.0.take() {
unsafe {
drop(Arc::from_raw(p));
}
}
}
}
impl ProcessSettings {
pub unsafe fn build(
sdk: &WslcSdk,
script_code: &str,
env: &[String],
scope: EnvScope,
working_directory: &str,
sink: Option<OutputSink>,
) -> Result<Self, WslcStepError> {
Self::build_inner(
sdk,
&process_env::argv_words(scope, env, script_code),
&process_env::sdk_entries(scope, env),
working_directory,
true,
sink,
Capture::Head,
)
}
pub unsafe fn build_detached(
sdk: &WslcSdk,
script_code: &str,
env: &[String],
scope: EnvScope,
working_directory: &str,
) -> Result<Self, WslcStepError> {
Self::build_inner(
sdk,
&process_env::argv_words(scope, env, script_code),
&process_env::sdk_entries(scope, env),
working_directory,
false,
None,
Capture::Head,
)
}
pub(crate) unsafe fn build_argv(
sdk: &WslcSdk,
argv: &[String],
env: &[String],
capture: Capture,
) -> Result<Self, WslcStepError> {
Self::build_inner(sdk, argv, env, "", true, None, capture)
}
unsafe fn build_inner(
sdk: &WslcSdk,
argv: &[String],
env: &[String],
working_directory: &str,
register_callbacks: bool,
sink: Option<OutputSink>,
capture: Capture,
) -> Result<Self, WslcStepError> {
let mut raw = std::mem::zeroed::<WslcProcessSettings>();
let hr = sdk.WslcInitProcessSettings(&mut raw);
if hr != S_OK {
return Err(sdk_step_error("WslcInitProcessSettings", hr, ""));
}
let io_ctx = Arc::new(IoContext {
stdout: Arc::new(Mutex::new(Vec::new())),
stderr: Arc::new(Mutex::new(Vec::new())),
exited: Arc::new((Mutex::new(false), Condvar::new())),
sink,
capture,
});
let mut sdk_io_ref = SdkIoRef::none();
if register_callbacks {
let io_ctx_raw = Arc::into_raw(Arc::clone(&io_ctx)) as *mut c_void;
let callbacks = WslcProcessCallbacks {
onStdOut: Some(io_callback),
onStdErr: Some(io_callback),
onExit: Some(exit_callback),
};
let hr = sdk.WslcSetProcessSettingsCallbacks(&mut raw, &callbacks, io_ctx_raw);
if hr != S_OK {
drop(Arc::from_raw(io_ctx_raw as *const IoContext));
return Err(sdk_step_error("WslcSetProcessSettingsCallbacks", hr, ""));
}
sdk_io_ref = SdkIoRef(Some(io_ctx_raw as *const IoContext));
}
let command = set_argv_and_env(sdk, &mut raw, argv, env)?;
let mut cwd_cstr: Option<Vec<u8>> = None;
if !working_directory.is_empty() {
if !working_directory.starts_with('/') {
return Err(WslcError::Rejected(format!(
"working_directory must be an absolute in-container path (got {working_directory:?})"
))
.into());
}
let c = cstr_bytes("working_directory", working_directory)?;
let hr = sdk.WslcSetProcessSettingsWorkingDirectory(&mut raw, c.as_ptr() as PCSTR);
if hr != S_OK {
return Err(sdk_step_error(
"WslcSetProcessSettingsWorkingDirectory",
hr,
"",
));
}
cwd_cstr = Some(c);
}
Ok(ProcessSettings {
raw,
io_ctx,
sdk_io_ref,
_command: command,
_cwd_cstr: cwd_cstr,
})
}
pub unsafe fn mark_process_created(&mut self) {
let _ = self.sdk_io_ref.disarm();
}
pub fn io_ctx(&self) -> &IoContext {
&self.io_ctx
}
pub fn raw_mut(&mut self) -> &mut WslcProcessSettings {
&mut self.raw
}
}
static WINDOWS_LOOPBACK: sockaddr_storage = sockaddr_storage {
ss_family: 2, __ss_pad1: [0, 0, 127, 0, 0, 1],
__ss_align: 0,
__ss_pad2: [0; 112],
};
pub(crate) fn sdk_port_mappings(mappings: &[PortMapping]) -> Vec<WslcContainerPortMapping> {
mappings
.iter()
.map(|pm| WslcContainerPortMapping {
windowsPort: pm.windows_port,
containerPort: pm.container_port,
protocol: if pm.protocol == "udp" {
WslcPortProtocol::WSLC_PORT_PROTOCOL_UDP
} else {
WslcPortProtocol::WSLC_PORT_PROTOCOL_TCP
},
windowsAddress: ptr::from_ref(&WINDOWS_LOOPBACK).cast_mut(),
})
.collect()
}
#[derive(Clone, Copy, Debug)]
pub enum ContainerNetworking<'a> {
None,
Nat,
Network(&'a CStr),
Proxied {
name: &'a CStr,
network: &'a CStr,
address: Ipv4Addr,
},
}
pub struct ContainerSettings {
raw: WslcContainerSettings,
_image_cstr: Vec<u8>,
_wide_paths: Vec<(Vec<u16>, Vec<u8>)>,
_volumes: Vec<WslcContainerVolume>,
_port_mappings: Vec<WslcContainerPortMapping>,
_names: Vec<CString>,
_address: Option<Box<IN_ADDR>>,
_networks: Vec<WslcContainerNetwork>,
_capability_drops: Vec<PCSTR>,
}
impl ContainerSettings {
pub unsafe fn build(
sdk: &WslcSdk,
image: &str,
mounts: &[VolumeMount],
port_mappings: &[PortMapping],
networking: ContainerNetworking,
flags: WslcContainerFlags,
logger: &mut Logger,
) -> Result<Self, WslcStepError> {
let image_cstr = cstr_bytes("image", image)?;
let mut raw = std::mem::zeroed::<WslcContainerSettings>();
let hr = sdk.WslcInitContainerSettings(image_cstr.as_ptr() as PCSTR, &mut raw);
if hr != S_OK {
return Err(sdk_step_error("WslcInitContainerSettings", hr, ""));
}
let mut port_vec: Vec<WslcContainerPortMapping> = Vec::new();
if !port_mappings.is_empty() {
port_vec = sdk_port_mappings(port_mappings);
let hr = sdk.WslcSetContainerSettingsPortMappings(
&mut raw,
port_vec.as_ptr(),
port_vec.len() as u32,
);
if hr != S_OK {
return Err(sdk_step_error(
"WslcSetContainerSettingsPortMappings",
hr,
"",
));
}
let _ = writeln!(
logger,
"[WSLC] {} port mapping(s) configured",
port_vec.len()
);
}
let wide_paths: Vec<(Vec<u16>, Vec<u8>)> = mounts
.iter()
.map(|m| {
let win: Vec<u16> = to_wide(&m.windows_path);
let ctr: Vec<u8> = cstr_bytes("mount container_path", &m.container_path)?;
Ok((win, ctr))
})
.collect::<Result<Vec<_>, ScriptResponse>>()?;
let mut volumes: Vec<WslcContainerVolume> = Vec::new();
if !mounts.is_empty() {
volumes = wide_paths
.iter()
.zip(mounts.iter())
.map(|((win, ctr), m)| WslcContainerVolume {
windowsPath: win.as_ptr(),
containerPath: ctr.as_ptr() as PCSTR,
readOnly: if m.read_only { 1 } else { 0 },
})
.collect();
let hr = sdk.WslcSetContainerSettingsVolumes(
&mut raw,
volumes.as_ptr(),
volumes.len() as u32,
);
if hr != S_OK {
return Err(sdk_step_error("WslcSetContainerSettingsVolumes", hr, ""));
}
let _ = writeln!(
logger,
"[WSLC] {} volume mount(s) configured",
volumes.len()
);
}
let mut names = Vec::new();
let mut address = None;
let mut networks = Vec::new();
let mut capability_drops = Vec::new();
let mode = match networking {
ContainerNetworking::None => {
Some(WslcContainerNetworkingMode::WSLC_CONTAINER_NETWORKING_MODE_NONE)
}
ContainerNetworking::Nat => {
Some(WslcContainerNetworkingMode::WSLC_CONTAINER_NETWORKING_MODE_BRIDGED)
}
ContainerNetworking::Network(network) => {
names.push(network.to_owned());
networks.push(session_resources::network(&names[0], ptr::null()));
let _ = writeln!(logger, "[WSLC] Network: {}", network.to_string_lossy());
None
}
ContainerNetworking::Proxied {
name,
network,
address: ip,
} => {
names.extend([name.to_owned(), network.to_owned()]);
let hr = sdk.WslcSetContainerSettingsName(&mut raw, names[0].as_ptr());
if hr != S_OK {
return Err(sdk_step_error("WslcSetContainerSettingsName", hr, ""));
}
let ip: &IN_ADDR = address.insert(Box::new(session_resources::in_addr_of(ip)));
networks.push(session_resources::network(&names[1], ip));
capability_drops.push(c"NET_RAW".as_ptr());
let hr = sdk.WslcSetContainerSettingsCapabilityDrops(
&mut raw,
capability_drops.as_ptr(),
capability_drops.len() as u32,
);
if hr != S_OK {
return Err(sdk_step_error(
"WslcSetContainerSettingsCapabilityDrops",
hr,
"",
));
}
let _ = writeln!(logger, "[WSLC] Networking: built-in proxy");
None
}
};
if let Some(mode) = mode {
let hr = sdk.WslcSetContainerSettingsNetworkingMode(&mut raw, mode);
if hr != S_OK {
return Err(sdk_step_error(
"WslcSetContainerSettingsNetworkingMode",
hr,
"",
));
}
let _ = writeln!(logger, "[WSLC] Networking mode: {:?}", mode);
}
if !networks.is_empty() {
let hr = sdk.WslcSetContainerSettingsNetworks(
&mut raw,
networks.as_ptr(),
networks.len() as u32,
);
if hr != S_OK {
return Err(sdk_step_error("WslcSetContainerSettingsNetworks", hr, ""));
}
}
let hr = sdk.WslcSetContainerSettingsFlags(&mut raw, flags);
if hr != S_OK {
return Err(sdk_step_error("WslcSetContainerSettingsFlags", hr, ""));
}
Ok(ContainerSettings {
raw,
_image_cstr: image_cstr,
_wide_paths: wide_paths,
_volumes: volumes,
_port_mappings: port_vec,
_names: names,
_address: address,
_networks: networks,
_capability_drops: capability_drops,
})
}
pub fn raw_mut(&mut self) -> &mut WslcContainerSettings {
&mut self.raw
}
pub fn raw(&self) -> &WslcContainerSettings {
&self.raw
}
}
pub const KEEPALIVE_SCRIPT: &str = "while true; do sleep 86400; done";
pub unsafe fn load_sdk_checked(logger: &mut Logger) -> Result<WslcSdk, WslcStepError> {
let sdk = WslcSdk::load().map_err(|e| WslcError::Unavailable(e).into_step_error())?;
let mut missing = WslcComponentFlags::WSLC_COMPONENT_FLAG_NONE;
let hr = sdk.WslcGetMissingComponents(&mut missing);
if hr != S_OK {
return Err(sdk_step_error("WslcGetMissingComponents", hr, ""));
}
if missing.any_missing() {
return Err(WslcError::Unavailable(sdk_init::prerequisite_error(missing)).into());
}
let _ = writeln!(logger, "[WSLC][daemon] Runtime check passed");
Ok(sdk)
}
#[derive(Debug)]
pub struct SessionCreateFailure {
pub response: WslcStepError,
pub store_may_be_held: bool,
}
impl From<WslcStepError> for SessionCreateFailure {
fn from(response: WslcStepError) -> Self {
Self {
response,
store_may_be_held: false,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum HostLoopback {
Off,
IfSupported,
Required,
}
pub fn host_loopback_unsupported() -> WslcStepError {
WslcError::Unavailable(
"WSLc: network.ingress.hostLoopback 'allow' and a runtimeConfig.networkProxy \
on Windows loopback need WSL 3.0.5 or later. Run `wsl --update`"
.to_string(),
)
.into_step_error()
}
pub(crate) unsafe fn create_session(
sdk: &WslcSdk,
session_name: &str,
storage_path: &str,
sizing: SessionSizing,
mut host_loopback: HostLoopback,
logger: &mut Logger,
) -> Result<(WslcSessionGuard, bool), WslcStepError> {
let name_wide: Vec<u16> = to_wide(session_name);
let storage_wide: Vec<u16> = to_wide(storage_path);
let host_loopback_name = CString::new(crate::wslc_gateway_policy::HOST_LOOPBACK_NAME)
.expect("the host loopback name has no NUL");
loop {
let mut settings = std::mem::zeroed::<WslcSessionSettings>();
let hr =
sdk.WslcInitSessionSettings(name_wide.as_ptr(), storage_wide.as_ptr(), &mut settings);
if hr != S_OK {
return Err(sdk_step_error("WslcInitSessionSettings", hr, ""));
}
apply_session_sizing(sdk, &mut settings, sizing)?;
let with_host_loopback = host_loopback != HostLoopback::Off;
if with_host_loopback {
let hr =
sdk.WslcSetSessionSettingsHostLoopback(&mut settings, host_loopback_name.as_ptr());
if hr != S_OK {
return Err(sdk_step_error("WslcSetSessionSettingsHostLoopback", hr, ""));
}
}
let mut session: WslcSession = ptr::null_mut();
let mut err_msg = CoTaskMemPWSTR::null();
let hr = sdk.WslcCreateSession(&mut settings, &mut session, err_msg.as_mut_ptr());
if hr != S_OK {
host_loopback = host_loopback_for_retry(hr, host_loopback, &err_msg.to_string_lossy())?;
let _ = writeln!(
logger,
"[WSLC] This WSL can't map Windows loopback into session '{session_name}'; \
creating it without"
);
continue;
}
if with_host_loopback {
let _ = writeln!(
logger,
"[WSLC] Session reaches Windows loopback as {}",
crate::wslc_gateway_policy::HOST_LOOPBACK_NAME
);
}
let guard = WslcSessionGuard::from_raw(
session,
sdk.terminate_session_fn(),
sdk.release_session_fn(),
);
return Ok((guard, with_host_loopback));
}
}
fn host_loopback_for_retry(
hr: HRESULT,
host_loopback: HostLoopback,
sdk_msg: &str,
) -> Result<HostLoopback, WslcStepError> {
match host_loopback {
HostLoopback::IfSupported if hr == WSLC_E_RUNTIME_UPDATE_NEEDED => Ok(HostLoopback::Off),
HostLoopback::Required if hr == WSLC_E_RUNTIME_UPDATE_NEEDED => {
Err(host_loopback_unsupported()
.with_api_failure(sdk_api_failure("WslcCreateSession", hr)))
}
_ => Err(sdk_step_error("WslcCreateSession", hr, sdk_msg)),
}
}
pub unsafe fn create_daemon_session(
sdk: &WslcSdk,
session_name: &str,
storage_path: &str,
sizing: SessionSizing,
logger: &mut Logger,
) -> Result<(WslcSessionGuard, bool), SessionCreateFailure> {
let started = Instant::now();
let (guard, host_loopback) = create_session(
sdk,
session_name,
storage_path,
sizing,
HostLoopback::IfSupported,
logger,
)?;
let created_in = started.elapsed();
let probed = Instant::now();
let probe = validate_store_access(sdk, guard.as_raw(), storage_path);
let probed_in = probed.elapsed();
let _ = writeln!(
logger,
"[WSLC][daemon] Session '{session_name}' on store {storage_path}: create \
{:.1}s, store probe {:.1}s, probe {}",
created_in.as_secs_f32(),
probed_in.as_secs_f32(),
if probe.is_ok() { "ok" } else { "failed" }
);
if let Err(response) = probe {
let store_may_be_held = match release_daemon_session(guard, session_name, logger) {
Ok(()) => false,
Err(release) => {
let _ = writeln!(logger, "[WSLC][daemon] {}", release.error_message);
true
}
};
return Err(SessionCreateFailure {
response,
store_may_be_held,
});
}
Ok((guard, host_loopback))
}
unsafe fn apply_session_sizing(
sdk: &WslcSdk,
settings: &mut WslcSessionSettings,
sizing: SessionSizing,
) -> Result<(), WslcStepError> {
check_sizing_against_host(sizing)?;
if let Some(cpu) = sizing.cpu_count {
let hr = sdk.WslcSetSessionSettingsCpuCount(settings, cpu);
if hr != S_OK {
return Err(sdk_step_error("WslcSetSessionSettingsCpuCount", hr, ""));
}
}
if let Some(memory_mb) = sizing.memory_mb {
let memory_mb = u32::try_from(memory_mb).map_err(|_| {
WslcError::Rejected(format!(
"memory_mb {memory_mb} exceeds the {} MB the WSLc SDK accepts",
u32::MAX
))
.into_step_error()
})?;
let hr = sdk.WslcSetSessionSettingsMemory(settings, memory_mb);
if hr != S_OK {
return Err(sdk_step_error("WslcSetSessionSettingsMemory", hr, ""));
}
}
let hr = sdk.WslcSetSessionSettingsTimeout(settings, SESSION_BOOT_TIMEOUT_MS);
if hr != S_OK {
return Err(sdk_step_error("WslcSetSessionSettingsTimeout", hr, ""));
}
if sizing.gpu {
let hr = sdk.WslcSetSessionSettingsFeatureFlags(
settings,
WslcSessionFeatureFlags::WSLC_SESSION_FEATURE_FLAG_ENABLE_GPU,
);
if hr != S_OK {
return Err(sdk_step_error("WslcSetSessionSettingsFeatureFlags", hr, ""));
}
}
Ok(())
}
pub fn release_daemon_session(
session: WslcSessionGuard,
session_name: &str,
logger: &mut Logger,
) -> Result<(), WslcStepError> {
let hr = session.release_checked();
if hr != S_OK {
return Err(sdk_step_error(
"WslcTerminateSession",
hr,
&format!(
"the WSL2 utility VM for session '{session_name}' may still be running, so its \
image store cannot be reused yet"
),
));
}
let _ = writeln!(logger, "[WSLC][daemon] Session '{session_name}' released");
Ok(())
}
pub unsafe fn validate_store_access(
sdk: &WslcSdk,
session: WslcSession,
storage_path: &str,
) -> Result<(), WslcStepError> {
list_stored_images(sdk, session)
.map(|_| ())
.map_err(|hr| store_access_failure(hr, storage_path))
}
fn store_access_failure(hr: HRESULT, storage_path: &str) -> WslcStepError {
if hr == E_SHARING_VIOLATION {
sdk_step_error_with_context(
"WslcListSessionImages",
"WSLc store unavailable",
hr,
&format!(
"the image store at {storage_path} is already held by another live session. \
A running wxc-wslc-daemon.exe releases it after its idle timeout; a \
create-and-run execution releases it when the run ends; a slot being \
warmed by --setup-wslc releases it when the warm finishes"
),
)
} else {
sdk_step_error_with_context(
"WslcListSessionImages",
"WslcListSessionImages failed",
hr,
&format!("could not read the image store at {storage_path}"),
)
}
}
pub(crate) struct StoredImage {
pub(crate) name: String,
pub(crate) sha256: [u8; 32],
}
pub(crate) unsafe fn list_stored_images(
sdk: &WslcSdk,
session: WslcSession,
) -> Result<Vec<StoredImage>, HRESULT> {
let mut images: *mut WslcImageInfo = ptr::null_mut();
let mut count: u32 = 0;
let hr = sdk.WslcListSessionImages(session, &mut images, &mut count);
if hr != S_OK {
return Err(hr);
}
if images.is_null() {
return Ok(Vec::new());
}
let mut stored = Vec::with_capacity(count as usize);
for info in std::slice::from_raw_parts(images, count as usize) {
let bytes = std::slice::from_raw_parts(info.name.as_ptr().cast::<u8>(), info.name.len());
let end = bytes.iter().position(|&b| b == 0).unwrap_or(bytes.len());
if let Ok(name) = std::str::from_utf8(&bytes[..end]) {
stored.push(StoredImage {
name: name.to_string(),
sha256: info.sha256,
});
}
}
windows::Win32::System::Com::CoTaskMemFree(Some(images as *const c_void));
Ok(stored)
}
fn container_flags(gpu: bool) -> WslcContainerFlags {
if gpu {
WslcContainerFlags::WSLC_CONTAINER_FLAG_ENABLE_GPU
} else {
WslcContainerFlags::WSLC_CONTAINER_FLAG_NONE
}
}
#[allow(clippy::too_many_arguments)]
pub unsafe fn create_daemon_container(
sdk: &WslcSdk,
session: WslcSession,
image: &str,
mounts: &[VolumeMount],
port_mappings: &[PortMapping],
networking: ContainerNetworking,
gpu: bool,
keepalive: &mut ProcessSettings,
logger: &mut Logger,
) -> Result<WslcContainerGuard, WslcStepError> {
let mut container_settings = ContainerSettings::build(
sdk,
image,
mounts,
port_mappings,
networking,
container_flags(gpu),
logger,
)?;
let hr =
sdk.WslcSetContainerSettingsInitProcess(container_settings.raw_mut(), keepalive.raw_mut());
if hr != S_OK {
return Err(sdk_step_error(
"WslcSetContainerSettingsInitProcess",
hr,
"",
));
}
let mut container: WslcContainer = ptr::null_mut();
let mut err_msg = CoTaskMemPWSTR::null();
let hr = sdk.WslcCreateContainer(
session,
container_settings.raw(),
&mut container,
err_msg.as_mut_ptr(),
);
if hr != S_OK {
let msg = err_msg.to_string_lossy();
return Err(sdk_step_error("WslcCreateContainer", hr, &msg));
}
let _ = writeln!(logger, "[WSLC][daemon] Container created");
Ok(WslcContainerGuard::from_raw(
container,
sdk.release_container_fn(),
))
}
pub unsafe fn start_daemon_container(
sdk: &WslcSdk,
container: WslcContainer,
logger: &mut Logger,
) -> Result<(), WslcStepError> {
let mut err_msg = CoTaskMemPWSTR::null();
let hr = sdk.WslcStartContainer(
container,
WslcContainerStartFlags::WSLC_CONTAINER_START_FLAG_NONE,
err_msg.as_mut_ptr(),
);
if hr != S_OK {
let msg = err_msg.to_string_lossy();
return Err(sdk_step_error("WslcStartContainer", hr, &msg));
}
let _ = writeln!(logger, "[WSLC][daemon] Container started");
Ok(())
}
const EXEC_WAIT_POLL_INTERVAL: Duration = Duration::from_millis(100);
const EXIT_CALLBACK_WAIT: Duration = Duration::from_secs(30);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ExecInterruption {
TimedOut,
Cancelled,
}
impl ExecInterruption {
fn get_interruption_word(self) -> &'static str {
match self {
Self::TimedOut => "timeout",
Self::Cancelled => "cancellation",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ExitWait {
Signalled,
Interrupted(ExecInterruption),
NoEvent,
Failed { wait_result: u32, last_error: u32 },
}
fn wait_slice(timeout: Option<Duration>, elapsed: Duration) -> Duration {
timeout
.map(|limit| limit.saturating_sub(elapsed))
.unwrap_or(EXEC_WAIT_POLL_INTERVAL)
.min(EXEC_WAIT_POLL_INTERVAL)
}
fn wait_slice_ms(timeout: Option<Duration>, elapsed: Duration) -> u32 {
u32::try_from(wait_slice(timeout, elapsed).as_millis())
.expect("poll interval is bounded to 100ms")
}
fn requested_interruption(
cancelled: bool,
timeout: Option<Duration>,
elapsed: Duration,
) -> Option<ExecInterruption> {
if cancelled {
Some(ExecInterruption::Cancelled)
} else if timeout.is_some_and(|limit| elapsed >= limit) {
Some(ExecInterruption::TimedOut)
} else {
None
}
}
unsafe fn wait_for_exit_event(
exit_event: HANDLE,
io_ctx: &IoContext,
timeout: Option<Duration>,
cancellation: &AtomicBool,
) -> ExitWait {
let started = Instant::now();
loop {
if let Some(interruption) = requested_interruption(
cancellation.load(Ordering::Acquire),
timeout,
started.elapsed(),
) {
return ExitWait::Interrupted(interruption);
}
if exit_event.is_null() {
if wait_for_exit_callback_slice(io_ctx, wait_slice(timeout, started.elapsed())) {
return ExitWait::NoEvent;
}
continue;
}
let wait_result = unsafe {
windows::Win32::System::Threading::WaitForSingleObject(
windows::Win32::Foundation::HANDLE(exit_event),
wait_slice_ms(timeout, started.elapsed()),
)
};
if wait_result == windows::Win32::Foundation::WAIT_OBJECT_0 {
return ExitWait::Signalled;
}
if wait_result != windows::Win32::Foundation::WAIT_TIMEOUT {
let last_error = unsafe { windows::Win32::Foundation::GetLastError() };
return ExitWait::Failed {
wait_result: wait_result.0,
last_error: last_error.0,
};
}
}
}
fn wait_for_exit_callback_slice(io_ctx: &IoContext, wait: Duration) -> bool {
let (lock, cvar) = &*io_ctx.exited;
let mut exited = lock.lock().unwrap_or_else(|e| e.into_inner());
if !*exited {
let result = cvar
.wait_timeout(exited, wait)
.unwrap_or_else(|e| e.into_inner());
exited = result.0;
}
*exited
}
fn wait_for_exit_callback(io_ctx: &IoContext) -> bool {
wait_for_exit_callback_slice(io_ctx, EXIT_CALLBACK_WAIT)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProcessCompletion {
Confirmed(ExecTerminal),
TerminationUnconfirmed,
}
fn natural_exit_confirmed(exit_wait: ExitWait, callback_confirmed: bool) -> bool {
matches!(exit_wait, ExitWait::Signalled)
|| (matches!(exit_wait, ExitWait::NoEvent) && callback_confirmed)
}
#[cfg(any(test, all(feature = "test-support", debug_assertions)))]
const TEST_EXIT_CODE_FAILURE_SCRIPT: &str = "true # mxc-test-force-wslc-get-exit-code-failure";
#[cfg(any(test, all(feature = "test-support", debug_assertions)))]
fn forced_exit_code_result(
script_code: &str,
natural_exit_confirmed: bool,
result: HRESULT,
) -> HRESULT {
if result == S_OK && natural_exit_confirmed && script_code == TEST_EXIT_CODE_FAILURE_SCRIPT {
E_FAIL
} else {
result
}
}
pub(crate) fn test_exit_code_result(
script_code: &str,
natural_exit_confirmed: bool,
result: HRESULT,
) -> HRESULT {
#[cfg(all(feature = "test-support", debug_assertions))]
let result = forced_exit_code_result(script_code, natural_exit_confirmed, result);
let _ = (script_code, natural_exit_confirmed);
result
}
fn classify_completion(exit_wait: ExitWait, confirmed: bool, exit_code: i32) -> ProcessCompletion {
if natural_exit_confirmed(exit_wait, confirmed) {
return ProcessCompletion::Confirmed(ExecTerminal::Exited(exit_code));
}
match exit_wait {
ExitWait::Interrupted(ExecInterruption::TimedOut) if confirmed => {
ProcessCompletion::Confirmed(ExecTerminal::TimedOut)
}
ExitWait::Interrupted(ExecInterruption::Cancelled) if confirmed => {
ProcessCompletion::Confirmed(ExecTerminal::Cancelled)
}
ExitWait::Interrupted(_) | ExitWait::Failed { .. } => {
ProcessCompletion::TerminationUnconfirmed
}
ExitWait::NoEvent | ExitWait::Signalled => ProcessCompletion::TerminationUnconfirmed,
}
}
fn unconfirmed_api_failure(
completion: ProcessCompletion,
kill_hr: HRESULT,
exit_code_hr: HRESULT,
) -> Option<Box<ApiFailure>> {
if completion != ProcessCompletion::TerminationUnconfirmed {
return None;
}
[
("WslcSignalProcess", kill_hr),
("WslcGetProcessExitCode", exit_code_hr),
]
.into_iter()
.find(|&(_, hr)| hr != S_OK)
.map(|(operation, hr)| Box::new(sdk_api_failure(operation, hr)))
}
#[derive(Debug)]
pub struct ExecOutcome {
pub completion: ProcessCompletion,
pub stdout: Vec<u8>,
pub stderr: Vec<u8>,
pub post_launch_error: Option<WslcStepError>,
pub unconfirmed_api_failure: Option<Box<ApiFailure>>,
pub held_stdin: Option<StdinHold>,
}
#[expect(
clippy::too_many_arguments,
reason = "thin FFI boundary mirrors the SDK process inputs at its single call site"
)]
pub unsafe fn exec_in_container(
sdk: &WslcSdk,
container: WslcContainer,
script_code: &str,
env: &[String],
scope: EnvScope,
working_directory: &str,
timeout_ms: u32,
cancellation: &AtomicBool,
sink: Option<OutputSink>,
stdin: Option<StdinConsumer>,
logger: &mut Logger,
) -> Result<ExecOutcome, WslcStepError> {
let mut process_settings =
ProcessSettings::build(sdk, script_code, env, scope, working_directory, sink)?;
if stdin.is_some() {
let hr = sdk.WslcSetProcessSettingsFlags(
process_settings.raw_mut(),
WslcProcessFlags::WSLC_PROCESS_FLAG_STDIN,
);
if hr != S_OK {
return Err(sdk_step_error("WslcSetProcessSettingsFlags", hr, ""));
}
}
let mut process: WslcProcess = ptr::null_mut();
let mut err_msg = CoTaskMemPWSTR::null();
let hr = sdk.WslcCreateContainerProcess(
container,
process_settings.raw_mut(),
&mut process,
err_msg.as_mut_ptr(),
);
if hr != S_OK {
let msg = err_msg.to_string_lossy();
return Err(sdk_step_error("WslcCreateContainerProcess", hr, &msg));
}
let process_guard = WslcProcessGuard::from_raw(process, sdk.release_process_fn());
process_settings.mark_process_created();
let mut stdin_guard = StdinHold::default();
let forwards_stdin = stdin.is_some();
if let Some(consumer) = stdin {
match attach_stdin(sdk, process_guard.as_raw(), consumer) {
Ok(close) => stdin_guard = StdinHold::new(close),
Err(error) => {
let kill_hr =
sdk.WslcSignalProcess(process_guard.as_raw(), WslcSignal::WSLC_SIGNAL_SIGKILL);
if wait_for_exit_callback(process_settings.io_ctx()) {
return Err(error);
}
let completion = ProcessCompletion::TerminationUnconfirmed;
return Ok(ExecOutcome {
completion,
stdout: Vec::new(),
stderr: Vec::new(),
post_launch_error: Some(error),
unconfirmed_api_failure: unconfirmed_api_failure(completion, kill_hr, S_OK),
held_stdin: None,
});
}
}
}
let mut exit_event: HANDLE = ptr::null_mut();
let hr = sdk.WslcGetProcessExitEvent(process_guard.as_raw(), &mut exit_event);
if hr != S_OK {
return Ok(ExecOutcome {
completion: ProcessCompletion::TerminationUnconfirmed,
stdout: Vec::new(),
stderr: Vec::new(),
post_launch_error: Some(sdk_step_error("WslcGetProcessExitEvent", hr, "")),
unconfirmed_api_failure: None,
held_stdin: Some(stdin_guard),
});
}
let timeout = (timeout_ms > 0).then(|| Duration::from_millis(u64::from(timeout_ms)));
let exit_wait =
wait_for_exit_event(exit_event, process_settings.io_ctx(), timeout, cancellation);
if let ExitWait::Failed {
wait_result,
last_error,
} = exit_wait
{
let _ = writeln!(
logger,
"[WSLC][daemon] Warning: waiting on the exec exit event failed: \
WaitForSingleObject returned 0x{wait_result:08X} \
(GetLastError 0x{last_error:08X}); container state is unknown"
);
}
let interruption = match exit_wait {
ExitWait::Interrupted(interruption) => Some(interruption),
_ => None,
};
let mut kill_hr = S_OK;
if let Some(interruption) = interruption {
if forwards_stdin {
stdin_guard.freeze();
let _ = writeln!(
logger,
"[WSLC][daemon] exec {} — not signalling a process that reads forwarded \
stdin; it is stopped with its container",
interruption.get_interruption_word()
);
} else {
let _ = writeln!(
logger,
"[WSLC][daemon] exec {} — killing process",
interruption.get_interruption_word()
);
kill_hr =
sdk.WslcSignalProcess(process_guard.as_raw(), WslcSignal::WSLC_SIGNAL_SIGKILL);
if kill_hr != S_OK {
let _ = writeln!(
logger,
"[WSLC][daemon] Warning: WslcSignalProcess(SIGKILL) failed (hr=0x{:08X}); \
process may still be running",
kill_hr as u32
);
}
}
}
let mut confirmed = wait_for_exit_callback(process_settings.io_ctx());
if interruption.is_some() && !confirmed {
confirmed = wait_for_exit_callback(process_settings.io_ctx());
if !confirmed {
let _ = writeln!(
logger,
"[WSLC][daemon] Warning: exit callback did not fire after SIGKILL; \
process may still be running"
);
}
}
let mut exit_code: i32 = -1;
let natural_exit_confirmed = natural_exit_confirmed(exit_wait, confirmed);
let exit_code_hr = test_exit_code_result(
script_code,
natural_exit_confirmed,
sdk.WslcGetProcessExitCode(process_guard.as_raw(), &mut exit_code),
);
if exit_code_hr != S_OK {
if natural_exit_confirmed {
return Err(sdk_step_error("WslcGetProcessExitCode", exit_code_hr, ""));
}
let _ = writeln!(
logger,
"[WSLC][daemon] Warning: WslcGetProcessExitCode failed while termination was \
unconfirmed (hr=0x{:08X})",
exit_code_hr as u32
);
}
let stdout = process_settings
.io_ctx()
.stdout
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone();
let stderr = process_settings
.io_ctx()
.stderr
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone();
let completion = classify_completion(exit_wait, confirmed, exit_code);
match completion {
ProcessCompletion::Confirmed(ExecTerminal::TimedOut) => {
let _ = writeln!(
logger,
"[WSLC][daemon] Process killed after {}",
ExecInterruption::TimedOut.get_interruption_word()
);
}
ProcessCompletion::Confirmed(ExecTerminal::Cancelled) => {
let _ = writeln!(
logger,
"[WSLC][daemon] Process killed after {}",
ExecInterruption::Cancelled.get_interruption_word()
);
}
ProcessCompletion::Confirmed(ExecTerminal::Exited(exit_code)) => {
let _ = writeln!(
logger,
"[WSLC][daemon] Process exited with code {}",
exit_code
);
}
ProcessCompletion::TerminationUnconfirmed if matches!(exit_wait, ExitWait::NoEvent) => {
let _ = writeln!(
logger,
"[WSLC][daemon] Warning: exec never reported an exit (no exit event, no exit \
callback); container state is unknown"
);
}
ProcessCompletion::TerminationUnconfirmed => {}
}
let held_stdin = match completion {
ProcessCompletion::Confirmed(_) => {
drop(stdin_guard);
None
}
ProcessCompletion::TerminationUnconfirmed => Some(stdin_guard),
};
Ok(ExecOutcome {
completion,
stdout,
stderr,
post_launch_error: None,
unconfirmed_api_failure: unconfirmed_api_failure(completion, kill_hr, exit_code_hr),
held_stdin,
})
}
#[derive(Default)]
pub struct StdinHold(Mutex<Option<Box<dyn StdinControl>>>);
impl StdinHold {
fn new(control: Box<dyn StdinControl>) -> Self {
Self(Mutex::new(Some(control)))
}
fn freeze(&self) {
if let Some(control) = self
.0
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.as_ref()
{
control.freeze();
}
}
}
impl Drop for StdinHold {
fn drop(&mut self) {
let control = self
.0
.get_mut()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.take();
if let Some(control) = control {
control.close();
}
}
}
impl std::fmt::Debug for StdinHold {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("StdinHold")
}
}
unsafe fn attach_stdin(
sdk: &WslcSdk,
process: WslcProcess,
consumer: StdinConsumer,
) -> Result<Box<dyn StdinControl>, WslcStepError> {
use std::os::windows::io::FromRawHandle;
let mut handle: HANDLE = ptr::null_mut();
let hr = sdk.WslcGetProcessIOHandle(
process,
WslcProcessIOHandle::WSLC_PROCESS_IO_HANDLE_STDIN,
&mut handle,
);
if hr != S_OK || handle.is_null() {
return Err(sdk_step_error_with_context(
"WslcGetProcessIOHandle",
"WslcGetProcessIOHandle(stdin) failed",
hr,
"",
));
}
let stdin = std::fs::File::from_raw_handle(handle);
consumer(stdin).map_err(|error| {
WslcError::Runtime(format!("could not start forwarding stdin: {error}")).into_step_error()
})
}
pub unsafe fn stop_daemon_container(
sdk: &WslcSdk,
container: WslcContainer,
logger: &mut Logger,
) -> Result<(), WslcStepError> {
let mut err_msg = CoTaskMemPWSTR::null();
let hr = sdk.WslcStopContainer(
container,
WslcSignal::WSLC_SIGNAL_SIGTERM,
10,
err_msg.as_mut_ptr(),
);
if hr != S_OK {
let msg = err_msg.to_string_lossy();
return Err(sdk_step_error("WslcStopContainer", hr, &msg));
}
let _ = writeln!(logger, "[WSLC][daemon] Container stopped");
Ok(())
}
pub unsafe fn delete_daemon_container(
sdk: &WslcSdk,
container: WslcContainer,
logger: &mut Logger,
) -> Result<(), WslcStepError> {
let mut err_msg = CoTaskMemPWSTR::null();
let hr = sdk.WslcDeleteContainer(
container,
WslcDeleteContainerFlags::WSLC_DELETE_CONTAINER_FLAG_FORCE,
err_msg.as_mut_ptr(),
);
if hr != S_OK {
let msg = err_msg.to_string_lossy();
return Err(sdk_step_error("WslcDeleteContainer", hr, &msg));
}
let _ = writeln!(logger, "[WSLC][daemon] Container deleted");
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::mxc_common::models::FailurePhase;
#[test]
fn test_exit_code_failure_requires_the_exact_successful_natural_exit() {
let access_denied = 0x8007_0005_u32 as HRESULT;
assert_eq!(
forced_exit_code_result(TEST_EXIT_CODE_FAILURE_SCRIPT, true, S_OK),
E_FAIL
);
assert_eq!(
forced_exit_code_result(TEST_EXIT_CODE_FAILURE_SCRIPT, true, access_denied),
access_denied
);
assert_eq!(
forced_exit_code_result(TEST_EXIT_CODE_FAILURE_SCRIPT, false, S_OK),
S_OK
);
assert_eq!(
forced_exit_code_result(
"true # mxc-test-force-wslc-get-exit-code-failure ",
true,
S_OK
),
S_OK
);
}
#[cfg(all(feature = "test-support", debug_assertions))]
#[test]
fn the_exit_code_failure_marker_fails_the_call_with_test_support() {
assert_eq!(
test_exit_code_result(TEST_EXIT_CODE_FAILURE_SCRIPT, true, S_OK),
E_FAIL
);
}
#[cfg(not(all(feature = "test-support", debug_assertions)))]
#[test]
fn the_exit_code_failure_marker_is_inert_without_test_support() {
assert_eq!(
test_exit_code_result(TEST_EXIT_CODE_FAILURE_SCRIPT, true, S_OK),
S_OK
);
}
const TEST_HOST: HostCapacity = HostCapacity {
total_memory_mb: 16 * 1024,
logical_cpus: 8,
};
#[test]
fn port_mappings_bind_windows_ipv4_loopback() {
let mapping = PortMapping {
windows_port: 8080,
container_port: 80,
protocol: "tcp".to_string(),
};
let sdk = sdk_port_mappings(&[mapping]);
let address = unsafe { &*sdk[0].windowsAddress };
assert_eq!(address.ss_family, 2);
assert_eq!(address.__ss_pad1, [0, 0, 127, 0, 0, 1]);
}
#[test]
fn a_processor_count_the_host_cannot_supply_is_refused() {
let refused = sizing_fits_host(
SessionSizing {
cpu_count: Some(TEST_HOST.logical_cpus + 1),
..SessionSizing::default()
},
TEST_HOST,
)
.expect_err("more processors than the host has must be refused");
assert_eq!(refused.failure_phase, FailurePhase::Rejected);
assert!(
refused.error_message.contains('9') && refused.error_message.contains('8'),
"the refusal must name both what was asked and what the host has: {}",
refused.error_message
);
}
#[test]
fn a_processor_count_the_host_can_supply_is_allowed() {
for cpus in [1, TEST_HOST.logical_cpus] {
assert!(
sizing_fits_host(
SessionSizing {
cpu_count: Some(cpus),
..SessionSizing::default()
},
TEST_HOST,
)
.is_ok(),
"{cpus} processors is within the host's {}",
TEST_HOST.logical_cpus
);
}
}
#[test]
fn memory_past_installed_is_allowed_because_it_is_a_ceiling() {
assert!(
sizing_fits_host(
SessionSizing {
memory_mb: Some(TEST_HOST.total_memory_mb * 8),
..SessionSizing::default()
},
TEST_HOST,
)
.is_ok(),
"memory_mb is a ceiling the host backs on demand, not a reservation"
);
}
#[test]
fn zero_is_a_default_sentinel_rather_than_a_size() {
assert!(sizing_fits_host(
SessionSizing {
cpu_count: Some(0),
memory_mb: Some(0),
gpu: false,
},
TEST_HOST,
)
.is_ok());
}
#[test]
fn absent_sizing_is_allowed() {
assert!(sizing_fits_host(SessionSizing::default(), TEST_HOST).is_ok());
}
#[test]
fn a_gpu_session_creates_gpu_containers() {
assert_eq!(
container_flags(true),
WslcContainerFlags::WSLC_CONTAINER_FLAG_ENABLE_GPU
);
assert_eq!(
container_flags(false),
WslcContainerFlags::WSLC_CONTAINER_FLAG_NONE
);
}
#[test]
fn a_held_store_is_reported_as_held_rather_than_as_a_failed_call() {
let resp = store_access_failure(E_SHARING_VIOLATION, r"C:\slots\slot-0");
assert!(
resp.error_message
.contains("already held by another live session"),
"a sharing violation is the one store failure a caller can wait out: {}",
resp.error_message
);
assert!(resp.error_message.contains(r"C:\slots\slot-0"));
assert!(resp.error_message.contains("idle timeout"));
assert!(
resp.error_message.contains("--setup-wslc"),
"warming holds a slot's store too, and that holder clears on its own: {}",
resp.error_message
);
assert!(resp.error_message.contains("80070020"));
}
#[test]
fn any_other_store_failure_keeps_the_call_that_produced_it() {
let resp = store_access_failure(-2147467259, r"C:\slots\slot-0");
assert!(
resp.error_message.contains("WslcListSessionImages failed"),
"an unrecognised failure must not be attributed to another holder: {}",
resp.error_message
);
assert!(!resp.error_message.contains("already held"));
assert!(resp.error_message.contains(r"C:\slots\slot-0"));
}
#[test]
fn a_failed_sdk_call_keeps_its_message_and_names_the_call() {
let error = sdk_step_error(
"WslcStartContainer",
0x8007_2740_u32 as HRESULT,
"Only one usage of each socket address is normally permitted.",
);
assert_eq!(
error.error_message,
"WslcStartContainer failed: Only one usage of each socket address is normally \
permitted. (HRESULT 0x80072740)"
);
let failure = error.api_failure.as_deref().expect("api failure");
assert_eq!(failure.operation, "WslcStartContainer");
assert_eq!(failure.native_code.as_deref(), Some("0x80072740"));
}
#[test]
fn a_store_failure_is_attributed_to_bring_up() {
assert_eq!(
store_access_failure(E_SHARING_VIOLATION, "store").failure_phase,
FailurePhase::LaunchFailed,
"a held store frees up on its own, so this must not read as a rejection"
);
}
#[test]
fn cstr_bytes_nul_terminates_a_plain_value() {
let bytes = cstr_bytes("command", "echo hi").expect("plain value is a valid C string");
assert_eq!(bytes, b"echo hi\0");
}
#[test]
fn cstr_bytes_accepts_empty() {
let bytes = cstr_bytes("working_directory", "").expect("empty value is a valid C string");
assert_eq!(bytes, b"\0");
}
#[test]
fn cstr_bytes_rejects_interior_nul() {
let err = cstr_bytes("command", "echo\0rm -rf /")
.expect_err("an interior NUL must be rejected, not silently truncated");
let msg = format!("{:?}", err);
assert!(msg.contains("command"), "error names the field: {msg}");
assert!(
msg.contains("interior NUL"),
"error explains the cause: {msg}"
);
}
#[test]
fn wait_slice_is_bounded_by_poll_interval_and_deadline() {
assert_eq!(wait_slice(None, Duration::ZERO), Duration::from_millis(100));
assert_eq!(
wait_slice(Some(Duration::from_millis(250)), Duration::from_millis(225),),
Duration::from_millis(25)
);
assert_eq!(wait_slice_ms(None, Duration::ZERO), 100);
assert_eq!(
wait_slice_ms(Some(Duration::from_millis(250)), Duration::from_millis(25)),
100
);
assert_eq!(
wait_slice_ms(Some(Duration::from_millis(250)), Duration::from_millis(225)),
25
);
assert_eq!(
wait_slice_ms(Some(Duration::from_millis(250)), Duration::from_millis(250)),
0
);
}
#[test]
fn cancellation_takes_precedence_over_an_expired_timeout() {
assert_eq!(
requested_interruption(
true,
Some(Duration::from_millis(10)),
Duration::from_millis(10),
),
Some(ExecInterruption::Cancelled)
);
}
#[test]
fn timeout_requires_a_nonzero_deadline_to_expire() {
assert_eq!(
requested_interruption(false, None, Duration::from_secs(1)),
None
);
assert_eq!(
requested_interruption(
false,
Some(Duration::from_millis(10)),
Duration::from_millis(9),
),
None
);
assert_eq!(
requested_interruption(
false,
Some(Duration::from_millis(10)),
Duration::from_millis(10),
),
Some(ExecInterruption::TimedOut)
);
}
#[test]
fn completion_classification_requires_positive_exit_evidence() {
assert_eq!(
classify_completion(ExitWait::Signalled, false, 7),
ProcessCompletion::Confirmed(ExecTerminal::Exited(7))
);
assert_eq!(
classify_completion(ExitWait::NoEvent, true, 8),
ProcessCompletion::Confirmed(ExecTerminal::Exited(8))
);
assert_eq!(
classify_completion(ExitWait::Interrupted(ExecInterruption::TimedOut), true, -1,),
ProcessCompletion::Confirmed(ExecTerminal::TimedOut)
);
assert_eq!(
classify_completion(ExitWait::Interrupted(ExecInterruption::Cancelled), true, -1,),
ProcessCompletion::Confirmed(ExecTerminal::Cancelled)
);
assert_eq!(
classify_completion(
ExitWait::Interrupted(ExecInterruption::Cancelled),
false,
-1,
),
ProcessCompletion::TerminationUnconfirmed
);
assert_eq!(
classify_completion(
ExitWait::Failed {
wait_result: 1,
last_error: 2,
},
true,
0,
),
ProcessCompletion::TerminationUnconfirmed
);
assert_eq!(
classify_completion(ExitWait::NoEvent, false, -1),
ProcessCompletion::TerminationUnconfirmed
);
}
#[test]
fn an_unconfirmed_run_names_its_first_failed_kill_or_exit_code_call() {
let unconfirmed = ProcessCompletion::TerminationUnconfirmed;
let kill_failed = 0x8007_001f_u32 as HRESULT;
let kill_failure = ApiFailure::new("WslcSignalProcess").with_native_code("0x8007001f");
let exit_code_failure =
ApiFailure::new("WslcGetProcessExitCode").with_native_code("0x80004005");
assert_eq!(
unconfirmed_api_failure(unconfirmed, kill_failed, E_FAIL).as_deref(),
Some(&kill_failure)
);
assert_eq!(
unconfirmed_api_failure(unconfirmed, S_OK, E_FAIL).as_deref(),
Some(&exit_code_failure)
);
assert_eq!(unconfirmed_api_failure(unconfirmed, S_OK, S_OK), None);
assert_eq!(
unconfirmed_api_failure(
ProcessCompletion::Confirmed(ExecTerminal::TimedOut),
kill_failed,
E_FAIL,
),
None,
"a confirmed timeout must stay a timeout"
);
}
#[test]
fn a_streaming_callback_captures_nothing() {
let streamed = Arc::new(Mutex::new(Vec::new()));
let seen = Arc::clone(&streamed);
let io_ctx = Arc::new(IoContext {
stdout: Arc::new(Mutex::new(Vec::new())),
stderr: Arc::new(Mutex::new(Vec::new())),
exited: Arc::new((Mutex::new(false), Condvar::new())),
sink: Some(Box::new(move |kind, bytes| {
seen.lock().unwrap().push((kind, bytes.to_vec()));
})),
capture: Capture::Head,
});
let payload = b"streamed-not-captured";
let raw = Arc::into_raw(Arc::clone(&io_ctx));
unsafe {
io_callback(
WslcProcessIOHandle::WSLC_PROCESS_IO_HANDLE_STDOUT,
payload.as_ptr(),
payload.len() as u32,
raw as *mut c_void,
);
drop(Arc::from_raw(raw));
}
assert_eq!(
streamed.lock().unwrap().as_slice(),
&[(OutStream::Stdout, payload.to_vec())]
);
assert!(
io_ctx.stdout.lock().unwrap().is_empty(),
"a streamed chunk must not also be captured"
);
}
#[test]
fn null_exit_event_still_observes_cancellation() {
let io_ctx = IoContext {
stdout: Arc::new(Mutex::new(Vec::new())),
stderr: Arc::new(Mutex::new(Vec::new())),
exited: Arc::new((Mutex::new(false), Condvar::new())),
sink: None,
capture: Capture::Head,
};
let cancellation = AtomicBool::new(true);
let result = unsafe { wait_for_exit_event(ptr::null_mut(), &io_ctx, None, &cancellation) };
assert_eq!(result, ExitWait::Interrupted(ExecInterruption::Cancelled));
}
#[test]
fn null_exit_event_uses_callback_as_natural_exit_evidence() {
let io_ctx = IoContext {
stdout: Arc::new(Mutex::new(Vec::new())),
stderr: Arc::new(Mutex::new(Vec::new())),
exited: Arc::new((Mutex::new(true), Condvar::new())),
sink: None,
capture: Capture::Head,
};
let cancellation = AtomicBool::new(false);
let result = unsafe { wait_for_exit_event(ptr::null_mut(), &io_ctx, None, &cancellation) };
assert_eq!(result, ExitWait::NoEvent);
}
#[test]
fn an_older_wsl_gets_one_retry_without_host_loopback_only_when_it_is_optional() {
let old_wsl = WSLC_E_RUNTIME_UPDATE_NEEDED;
let refused = sdk_api_failure("WslcCreateSession", old_wsl);
let retry = host_loopback_for_retry(old_wsl, HostLoopback::IfSupported, "")
.expect("an optional host loopback is dropped for an older WSL");
assert_eq!(retry, HostLoopback::Off);
let refused_again = host_loopback_for_retry(old_wsl, retry, "")
.expect_err("the retry without host loopback is the last attempt");
assert_eq!(refused_again.failure_phase, FailurePhase::LaunchFailed);
assert_eq!(refused_again.api_failure.as_deref(), Some(&refused));
let required = host_loopback_for_retry(old_wsl, HostLoopback::Required, "")
.expect_err("a required host loopback is never dropped");
assert_eq!(required.failure_phase, FailurePhase::BackendUnavailable);
assert!(
required.error_message.contains("wsl --update"),
"{}",
required.error_message
);
assert_eq!(required.api_failure.as_deref(), Some(&refused));
}
#[test]
fn other_session_failures_are_returned_whatever_host_loopback_asks() {
for host_loopback in [
HostLoopback::Off,
HostLoopback::IfSupported,
HostLoopback::Required,
] {
let error = host_loopback_for_retry(E_FAIL, host_loopback, "no VM")
.expect_err("only an older WSL is retried");
assert_eq!(
error.failure_phase,
FailurePhase::LaunchFailed,
"{host_loopback:?}"
);
assert!(
error.error_message.contains("no VM"),
"{}",
error.error_message
);
assert_eq!(
error.api_failure.as_deref(),
Some(&sdk_api_failure("WslcCreateSession", E_FAIL))
);
}
}
#[test]
fn sustained_output_keeps_only_the_newest_whole_lines_under_a_tail_capture() {
let io_ctx = Arc::new(IoContext {
stdout: Arc::new(Mutex::new(Vec::new())),
stderr: Arc::new(Mutex::new(Vec::new())),
exited: Arc::new((Mutex::new(false), Condvar::new())),
sink: None,
capture: Capture::Tail(64),
});
let raw = Arc::into_raw(Arc::clone(&io_ctx));
unsafe {
for i in 0..1000 {
let line = format!("DENY request {i}\n");
io_callback(
WslcProcessIOHandle::WSLC_PROCESS_IO_HANDLE_STDOUT,
line.as_ptr(),
line.len() as u32,
raw as *mut c_void,
);
let kept = io_ctx.stdout.lock().unwrap().len();
assert!(kept <= 64, "{kept} bytes kept after line {i}");
}
drop(Arc::from_raw(raw));
}
let kept = String::from_utf8(io_ctx.stdout.lock().unwrap().clone()).unwrap();
assert!(kept.starts_with("DENY "), "{kept:?}");
assert!(kept.ends_with("DENY request 999\n"), "{kept:?}");
}
#[test]
fn a_tail_capture_keeps_the_newest_bytes_of_a_line_longer_than_its_limit() {
let mut buf = Vec::new();
Capture::Tail(4).append(&mut buf, b"abcdefgh");
assert_eq!(buf, b"efgh");
}
}