Lightweight coding agent that runs in your terminal
Rust
Upgrade Windows bindings to `windows-sys` 0.61.2 (#50058)
Tamir Dubersteinb06b7d2f7773
diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lockindex 3a5853ad9c..ff2059d2f5 100644--- a/codex-rs/Cargo.lock+++ b/codex-rs/Cargo.lock@@ -2231,7 +2231,7 @@ dependencies = ["tokio","tokio-tungstenite","tracing",- "windows-sys 0.52.0",+ "windows-sys 0.61.2",][[package]]@@ -2596,7 +2596,7 @@ dependencies = ["url","vt100","which 8.0.0",- "windows-sys 0.52.0",+ "windows-sys 0.61.2","wiremock","zstd",]@@ -2837,7 +2837,7 @@ dependencies = ["tracing","wildmatch","winapi-util",- "windows-sys 0.52.0",+ "windows-sys 0.61.2",][[package]]@@ -3032,6 +3032,7 @@ dependencies = ["walkdir","which 8.0.0","whoami 1.6.1",+ "windows-sys 0.61.2","wiremock","zstd",]@@ -3252,7 +3253,7 @@ dependencies = ["tracing-subscriber","url","uuid",- "windows-sys 0.52.0",+ "windows-sys 0.61.2","wiremock",]@@ -3704,7 +3705,7 @@ dependencies = ["tracing","tracing-opentelemetry","tracing-subscriber",- "windows-sys 0.52.0",+ "windows-sys 0.61.2","zstd",]@@ -4153,7 +4154,7 @@ dependencies = ["tracing","tracing-subscriber","url",- "windows-sys 0.52.0",+ "windows-sys 0.61.2",][[package]]@@ -4424,7 +4425,7 @@ dependencies = ["urlencoding","webbrowser","which 8.0.0",- "windows-sys 0.52.0",+ "windows-sys 0.61.2","wiremock",]@@ -4884,7 +4885,7 @@ dependencies = ["vt100","webbrowser","which 8.0.0",- "windows-sys 0.52.0",+ "windows-sys 0.61.2","winsplit","wiremock","zbus",@@ -4901,7 +4902,7 @@ dependencies = ["tokio","tokio-util","uds_windows",- "windows-sys 0.52.0",+ "windows-sys 0.61.2",][[package]]@@ -5070,7 +5071,7 @@ dependencies = ["dunce","pretty_assertions","tempfile",- "windows-sys 0.52.0",+ "windows-sys 0.61.2",][[package]]@@ -5318,7 +5319,7 @@ dependencies = ["tokio","tracing-appender","windows 0.58.0",- "windows-sys 0.52.0",+ "windows-sys 0.61.2",][[package]]@@ -5335,7 +5336,7 @@ dependencies = ["tokio","toml 0.9.11+spec-1.1.0","windows 0.58.0",- "windows-sys 0.52.0",+ "windows-sys 0.61.2",][[package]]diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.tomlindex 717891fc4b..66186f8968 100644--- a/codex-rs/Cargo.toml+++ b/codex-rs/Cargo.toml@@ -549,6 +549,7 @@ which = "8"whoami = "1.6.1"wildmatch = "2.6.1"winapi-util = "0.1.11"+windows-sys = "0.61.2"zip = "2.4.2"zstd = "0.13"diff --git a/codex-rs/app-server-daemon/Cargo.toml b/codex-rs/app-server-daemon/Cargo.tomlindex 591432bd28..4dabe9bc27 100644--- a/codex-rs/app-server-daemon/Cargo.toml+++ b/codex-rs/app-server-daemon/Cargo.toml@@ -44,4 +44,4 @@ codex-utils-cargo-bin = { workspace = true }pretty_assertions = { workspace = true }[target.'cfg(windows)'.dependencies]-windows-sys = { version = "0.52", features = ["Win32_Foundation", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_JobObjects", "Win32_Security", "Win32_Security_Authorization", "Win32_System_Threading"] }+windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_JobObjects", "Win32_Security", "Win32_Security_Authorization", "Win32_System_Threading"] }diff --git a/codex-rs/app-server-daemon/src/backend/windows.rs b/codex-rs/app-server-daemon/src/backend/windows.rsindex af72ebef29..0c2022fd59 100644--- a/codex-rs/app-server-daemon/src/backend/windows.rs+++ b/codex-rs/app-server-daemon/src/backend/windows.rs@@ -22,6 +22,7 @@ use windows_sys::Win32::Foundation::ERROR_INVALID_HANDLE;use windows_sys::Win32::Foundation::ERROR_INVALID_PARAMETER;use windows_sys::Win32::Foundation::ERROR_LOCK_VIOLATION;use windows_sys::Win32::Foundation::FILETIME;+use windows_sys::Win32::Foundation::HANDLE;use windows_sys::Win32::Foundation::HANDLE_FLAG_INHERIT;use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;use windows_sys::Win32::Foundation::SetHandleInformation;@@ -67,13 +68,13 @@ pub(super) fn spawn_without_inheriting_stdio(("stdout", io::stdout().as_raw_handle()),("stderr", io::stderr().as_raw_handle()),] {- if handle.is_null() || handle as isize == INVALID_HANDLE_VALUE {+ if handle.is_null() || handle == INVALID_HANDLE_VALUE {continue;}// SAFETY: these are borrowed standard handles; changing the inherit// flag neither closes them nor changes their read/write access.if unsafe {- SetHandleInformation(handle as _, HANDLE_FLAG_INHERIT, /*dwflags*/ 0)+ SetHandleInformation(handle, HANDLE_FLAG_INHERIT, /*dwflags*/ 0)} == 0{let error = io::Error::last_os_error();@@ -91,16 +92,16 @@ pub(super) fn spawn_without_inheriting_stdio(/// Reports whether this process has administrator privileges, rather than/// merely belonging to an administrator account.pub fn is_elevated() -> Result<bool> {- let mut token = 0;+ let mut token = std::ptr::null_mut();if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } == 0 {return Err(io::Error::last_os_error()).context("failed to query daemon launcher token");}- let token = unsafe { OwnedHandle::from_raw_handle(token as _) };+ let token = unsafe { OwnedHandle::from_raw_handle(token) };let mut elevation: TOKEN_ELEVATION = unsafe { std::mem::zeroed() };let mut returned = 0;if unsafe {GetTokenInformation(- token.as_raw_handle() as _,+ token.as_raw_handle(),TokenElevation,(&mut elevation as *mut TOKEN_ELEVATION).cast(),std::mem::size_of::<TOKEN_ELEVATION>() as u32,@@ -181,7 +182,7 @@ impl Process {let handle = unsafe {OpenProcess(access, /*binherithandle*/ 0, pid)};- if handle == 0 {+ if handle.is_null() {let err = io::Error::last_os_error();return if err.raw_os_error() == Some(ERROR_INVALID_PARAMETER as i32) {Ok(None)@@ -189,9 +190,7 @@ impl Process {Err(err).context("failed to open daemon process")};}- Ok(Some(Self(unsafe {- OwnedHandle::from_raw_handle(handle as _)- })))+ Ok(Some(Self(unsafe { OwnedHandle::from_raw_handle(handle) })))}pub(super) fn start_time(&self) -> Result<String> {@@ -201,7 +200,7 @@ impl Process {let mut user = created;if unsafe {GetProcessTimes(- self.0.as_raw_handle() as _,+ self.0.as_raw_handle(),&mut created,&mut exited,&mut kernel,@@ -219,7 +218,7 @@ impl Process {pub(super) fn is_running(&self) -> Result<bool> {match unsafe {- WaitForSingleObject(self.0.as_raw_handle() as _, /*dwmilliseconds*/ 0)+ WaitForSingleObject(self.0.as_raw_handle(), /*dwmilliseconds*/ 0)} {WAIT_TIMEOUT => Ok(true),WAIT_OBJECT_0 => Ok(false),@@ -231,7 +230,7 @@ impl Process {if !self.is_running()? {return Ok(());}- let pid = unsafe { GetProcessId(self.0.as_raw_handle() as _) };+ let pid = unsafe { GetProcessId(self.0.as_raw_handle()) };let Some(target) = Self::open_with_access(pid,PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_SYNCHRONIZE | PROCESS_TERMINATE,@@ -245,7 +244,7 @@ impl Process {return Ok(());}if unsafe {- TerminateProcess(target.0.as_raw_handle() as _, /*uexitcode*/ 1)+ TerminateProcess(target.0.as_raw_handle(), /*uexitcode*/ 1)} == 0{return Err(io::Error::last_os_error()).context("failed to terminate daemon process");@@ -258,7 +257,7 @@ pub(crate) fn try_lock_file(file: &tokio::fs::File) -> Result<bool> {let mut overlapped = unsafe { std::mem::zeroed() };if unsafe {LockFileEx(- file.as_raw_handle() as _,+ file.as_raw_handle(),LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY,/*dwreserved*/ 0,/*nnumberofbytestolocklow*/ 1,@@ -287,15 +286,15 @@ pub(crate) fn installer_job(child: &tokio::process::Child) -> Result<OwnedHandlelet process = child.raw_handle().context("installer process handle is unavailable")?;- process_job(process as isize)+ process_job(process)}-fn process_job(process: isize) -> Result<OwnedHandle> {+fn process_job(process: HANDLE) -> Result<OwnedHandle> {let job = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) };- if job == 0 {+ if job.is_null() {return Err(io::Error::last_os_error()).context("failed to create updater job");}- let owned = unsafe { OwnedHandle::from_raw_handle(job as _) };+ let owned = unsafe { OwnedHandle::from_raw_handle(job) };let mut limits: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = unsafe { std::mem::zeroed() };limits.BasicLimitInformation.LimitFlags =JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | JOB_OBJECT_LIMIT_BREAKAWAY_OK;diff --git a/codex-rs/app-server-daemon/src/backend/windows_tests.rs b/codex-rs/app-server-daemon/src/backend/windows_tests.rsindex 1910b2c96f..1311dfd79c 100644--- a/codex-rs/app-server-daemon/src/backend/windows_tests.rs+++ b/codex-rs/app-server-daemon/src/backend/windows_tests.rs@@ -32,8 +32,8 @@ async fn captured_stdio_closes_while_child_is_alive() {}let handles = [- std::io::stdout().as_raw_handle() as _,- std::io::stderr().as_raw_handle() as _,+ std::io::stdout().as_raw_handle(),+ std::io::stderr().as_raw_handle(),];for handle in handles {assert_ne!(@@ -137,16 +137,13 @@ fn detached_launch_preflight_rejects_restrictive_job() {let executable = std::env::current_exe().expect("test executable");if std::env::var_os(CHILD).is_some() {let job = unsafe { super::CreateJobObjectW(std::ptr::null(), std::ptr::null()) };- assert_ne!(job, 0);+ assert!(!job.is_null());let job = unsafe {- <std::os::windows::io::OwnedHandle as std::os::windows::io::FromRawHandle>::from_raw_handle(job as _)+ <std::os::windows::io::OwnedHandle as std::os::windows::io::FromRawHandle>::from_raw_handle(job)};assert_ne!(unsafe {- super::AssignProcessToJobObject(- job.as_raw_handle() as _,- super::GetCurrentProcess(),- )+ super::AssignProcessToJobObject(job.as_raw_handle(), super::GetCurrentProcess())},0);@@ -189,8 +186,8 @@ fn detached_launch_preflight_allows_residual_job() {let mut jobs = Vec::new();for inner in [false, true] {let job = unsafe { super::CreateJobObjectW(std::ptr::null(), std::ptr::null()) };- assert_ne!(job, 0);- let job = unsafe { OwnedHandle::from_raw_handle(job as _) };+ assert!(!job.is_null());+ let job = unsafe { OwnedHandle::from_raw_handle(job) };if inner {let mut limits: super::JOBOBJECT_EXTENDED_LIMIT_INFORMATION =unsafe { std::mem::zeroed() };@@ -198,7 +195,7 @@ fn detached_launch_preflight_allows_residual_job() {assert_ne!(unsafe {super::SetInformationJobObject(- job.as_raw_handle() as _,+ job.as_raw_handle(),super::JobObjectExtendedLimitInformation,(&limits as *const super::JOBOBJECT_EXTENDED_LIMIT_INFORMATION).cast(),std::mem::size_of_val(&limits) as u32,@@ -209,10 +206,7 @@ fn detached_launch_preflight_allows_residual_job() {}assert_ne!(unsafe {- super::AssignProcessToJobObject(- job.as_raw_handle() as _,- super::GetCurrentProcess(),- )+ super::AssignProcessToJobObject(job.as_raw_handle(), super::GetCurrentProcess())},0);@@ -231,15 +225,15 @@ fn detached_launch_preflight_allows_residual_job() {let mut in_inner = 0;let outer_checked = unsafe {IsProcessInJob(- probe.as_raw_handle() as _,- jobs[0].as_raw_handle() as _,+ probe.as_raw_handle(),+ jobs[0].as_raw_handle(),&mut in_outer,)};let inner_checked = unsafe {IsProcessInJob(- probe.as_raw_handle() as _,- jobs[1].as_raw_handle() as _,+ probe.as_raw_handle(),+ jobs[1].as_raw_handle(),&mut in_inner,)};@@ -285,15 +279,15 @@ fn detached_launch_preflight_allows_residual_job() {let ready = temp.path().join("ready").exists();let outer_checked = unsafe {IsProcessInJob(- process.0.as_raw_handle() as _,- jobs[0].as_raw_handle() as _,+ process.0.as_raw_handle(),+ jobs[0].as_raw_handle(),&mut in_outer,)};let inner_checked = unsafe {IsProcessInJob(- process.0.as_raw_handle() as _,- jobs[1].as_raw_handle() as _,+ process.0.as_raw_handle(),+ jobs[1].as_raw_handle(),&mut in_inner,)};@@ -351,7 +345,7 @@ async fn identity_queries_do_not_require_termination_access() {// that could let the caller reopen the process with termination access.assert_eq!(unsafe {- TerminateProcess(process.0.as_raw_handle() as _, /*uexitcode*/ 1)+ TerminateProcess(process.0.as_raw_handle(), /*uexitcode*/ 1)},0);diff --git a/codex-rs/app-server-daemon/src/prepare_install_windows.rs b/codex-rs/app-server-daemon/src/prepare_install_windows.rsindex 5b74d0f56b..f20fc9e421 100644--- a/codex-rs/app-server-daemon/src/prepare_install_windows.rs+++ b/codex-rs/app-server-daemon/src/prepare_install_windows.rs@@ -75,7 +75,7 @@ fn retarget_junction(current: &Path, release: &Path) -> Result<()> {let mut returned = 0;if unsafe {DeviceIoControl(- handle.as_raw_handle() as isize,+ handle.as_raw_handle(),FSCTL_SET_REPARSE_POINT,data.as_ptr().cast(),data.len() as u32,diff --git a/codex-rs/cli/Cargo.toml b/codex-rs/cli/Cargo.tomlindex 0c67a20cd2..608921c370 100644--- a/codex-rs/cli/Cargo.toml+++ b/codex-rs/cli/Cargo.toml@@ -112,7 +112,7 @@ tikv-jemallocator = { workspace = true }[target.'cfg(target_os = "windows")'.dependencies]codex_windows_sandbox = { package = "codex-windows-sandbox", path = "../windows-sandbox-rs" }-windows-sys = { version = "0.52", features = [+windows-sys = { workspace = true, features = ["Win32_Foundation","Win32_Storage_Packaging_Appx","Win32_System_Console",diff --git a/codex-rs/cli/src/doctor.rs b/codex-rs/cli/src/doctor.rsindex 3dc3d07b83..bcb53df6a7 100644--- a/codex-rs/cli/src/doctor.rs+++ b/codex-rs/cli/src/doctor.rs@@ -1722,6 +1722,7 @@ fn terminal_check(no_color_flag: bool) -> DoctorCheck {#[cfg(windows)]fn windows_console_details() -> Vec<String> {+ use windows_sys::Win32::Foundation::HANDLE;use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;use windows_sys::Win32::System::Console::ENABLE_VIRTUAL_TERMINAL_PROCESSING;use windows_sys::Win32::System::Console::GetConsoleCP;@@ -1745,8 +1746,8 @@ fn windows_console_details() -> Vec<String> {GetStdHandle(STD_ERROR_HANDLE)}));- fn console_mode_detail(label: &str, handle: isize) -> String {- if handle == 0 || handle == INVALID_HANDLE_VALUE {+ fn console_mode_detail(label: &str, handle: HANDLE) -> String {+ if handle.is_null() || handle == INVALID_HANDLE_VALUE {return format!("{label}: unavailable");}let mut mode = 0_u32;diff --git a/codex-rs/cli/src/doctor/desktop/platform.rs b/codex-rs/cli/src/doctor/desktop/platform.rsindex b06685a8d2..0f167adc92 100644--- a/codex-rs/cli/src/doctor/desktop/platform.rs+++ b/codex-rs/cli/src/doctor/desktop/platform.rs@@ -101,15 +101,15 @@ pub(super) fn application_running(application: &InstalledApp, candidate_pid: u32#[cfg(target_os = "windows")]fn process_package_family(pid: u32) -> Option<String> {let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };- if handle == 0 {+ if handle.is_null() {return None;}- let process = unsafe { OwnedHandle::from_raw_handle(handle as _) };+ let process = unsafe { OwnedHandle::from_raw_handle(handle) };let mut family_length = 0;let result = unsafe {GetPackageFamilyName(- process.as_raw_handle() as _,+ process.as_raw_handle(),&mut family_length,std::ptr::null_mut(),)@@ -121,7 +121,7 @@ fn process_package_family(pid: u32) -> Option<String> {let mut family = vec![0_u16; family_length as usize];let result = unsafe {GetPackageFamilyName(- process.as_raw_handle() as _,+ process.as_raw_handle(),&mut family_length,family.as_mut_ptr(),)diff --git a/codex-rs/cli/src/doctor/windows_dev_drive.rs b/codex-rs/cli/src/doctor/windows_dev_drive.rsindex af0a90a7ab..99cc9cef81 100644--- a/codex-rs/cli/src/doctor/windows_dev_drive.rs+++ b/codex-rs/cli/src/doctor/windows_dev_drive.rs@@ -133,7 +133,7 @@ fn volume_flags(path: &Path) -> io::Result<u32> {let mut bytes_returned = 0;if unsafe {DeviceIoControl(- handle.as_raw_handle() as isize,+ handle.as_raw_handle(),QUERY_PERSISTENT_VOLUME_STATE,state_ptr.cast_const().cast(),state_size,diff --git a/codex-rs/config/Cargo.toml b/codex-rs/config/Cargo.tomlindex 9be1fb4f47..b4be94bb58 100644--- a/codex-rs/config/Cargo.toml+++ b/codex-rs/config/Cargo.toml@@ -57,7 +57,7 @@ core-foundation = "0.9"[target.'cfg(target_os = "windows")'.dependencies]codex-windows-sandbox = { workspace = true }winapi-util = { workspace = true }-windows-sys = { version = "0.52", features = [+windows-sys = { workspace = true, features = ["Win32_Foundation","Win32_System_Com","Win32_UI_Shell",diff --git a/codex-rs/config/src/loader/mod.rs b/codex-rs/config/src/loader/mod.rsindex 4c2d851041..33854b0270 100644--- a/codex-rs/config/src/loader/mod.rs+++ b/codex-rs/config/src/loader/mod.rs@@ -842,7 +842,12 @@ fn windows_program_data_dir_from_known_folder() -> io::Result<PathBuf> {// SAFETY: SHGetKnownFolderPath initializes path_ptr with a CoTaskMem-allocated,// null-terminated UTF-16 string on success.let hr = unsafe {- SHGetKnownFolderPath(&FOLDERID_ProgramData, known_folder_flags, 0, &mut path_ptr)+ SHGetKnownFolderPath(+ &FOLDERID_ProgramData,+ known_folder_flags,+ std::ptr::null_mut(),+ &mut path_ptr,+ )};if hr != 0 {return Err(io::Error::other(format!(diff --git a/codex-rs/core/Cargo.toml b/codex-rs/core/Cargo.tomlindex ff0bbb4f92..cfd7236881 100644--- a/codex-rs/core/Cargo.toml+++ b/codex-rs/core/Cargo.toml@@ -175,6 +175,9 @@ walkdir = { workspace = true }wiremock = { workspace = true }zstd = { workspace = true }+[target.'cfg(windows)'.dev-dependencies]+windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_System_Threading"] }+[package.metadata.cargo-shear]ignored = ["openssl-sys"]ignored-paths = ["tests/remote_env_windows/*.rs"]diff --git a/codex-rs/core/tests/suite/mcp_refresh_cleanup.rs b/codex-rs/core/tests/suite/mcp_refresh_cleanup.rsindex e4be9e8e5f..9a278f88be 100644--- a/codex-rs/core/tests/suite/mcp_refresh_cleanup.rs+++ b/codex-rs/core/tests/suite/mcp_refresh_cleanup.rs@@ -7,15 +7,120 @@ use codex_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID;use codex_config::types::McpServerConfig;use codex_config::types::McpServerTransportConfig;use codex_protocol::protocol::Op;-use core_test_support::process::process_is_alive;use core_test_support::process::wait_for_pid_file;-use core_test_support::process::wait_for_process_exit;use core_test_support::responses;use core_test_support::skip_if_no_network;use core_test_support::stdio_server_bin;use core_test_support::test_codex::test_codex;use core_test_support::wait_for_mcp_server;+struct McpServerProcess {+ pid: String,+ // Retain the process object instead of reopening its PID after lifecycle actions.+ #[cfg(windows)]+ handle: std::os::windows::io::OwnedHandle,+}++impl McpServerProcess {+ fn observe_running(pid: String) -> anyhow::Result<Self> {+ let process = cfg_select! {+ unix => { Self { pid } }+ windows => {{+ use std::io;+ use std::num::NonZeroU32;+ use std::os::windows::io::FromRawHandle;+ use std::os::windows::io::OwnedHandle;++ use anyhow::Context;+ use windows_sys::Win32::System::Threading::OpenProcess;+ use windows_sys::Win32::System::Threading::PROCESS_SYNCHRONIZE;++ let process_id = pid+ .parse::<NonZeroU32>()+ .with_context(|| format!("invalid MCP server PID {pid}"))?;+ // SAFETY: The PID is nonzero, and the returned handle is checked before use.+ let handle = unsafe {+ OpenProcess(+ PROCESS_SYNCHRONIZE,+ /*binherithandle*/ 0,+ process_id.get(),+ )+ };+ if handle.is_null() {+ return Err(io::Error::last_os_error())+ .with_context(|| format!("failed to open MCP server process {pid}"));+ }+ // SAFETY: OpenProcess returned a non-null owned process handle.+ let handle = unsafe { OwnedHandle::from_raw_handle(handle) };+ Self { pid, handle }+ }}+ };+ let alive = process.is_alive()?;+ anyhow::ensure!(alive, "MCP server process {} is not running", process.pid);+ Ok(process)+ }++ fn is_alive(&self) -> anyhow::Result<bool> {+ cfg_select! {+ unix => {{+ use core_test_support::process::process_is_alive;++ let Self { pid } = self;+ process_is_alive(pid)+ }}+ windows => {{+ use std::io;+ use std::os::windows::io::AsRawHandle;++ use anyhow::Context;+ use windows_sys::Win32::Foundation::WAIT_FAILED;+ use windows_sys::Win32::Foundation::WAIT_OBJECT_0;+ use windows_sys::Win32::Foundation::WAIT_TIMEOUT;+ use windows_sys::Win32::System::Threading::WaitForSingleObject;++ let Self { pid, handle } = self;+ // SAFETY: The owned handle stays open for this nonblocking wait.+ let wait_result = unsafe {+ WaitForSingleObject(handle.as_raw_handle(), /*dwmilliseconds*/ 0)+ };+ match wait_result {+ WAIT_TIMEOUT => Ok(true),+ WAIT_OBJECT_0 => Ok(false),+ WAIT_FAILED => Err(io::Error::last_os_error())+ .with_context(|| format!("failed to wait for MCP server process {pid}")),+ result => anyhow::bail!("unexpected wait result {result} for MCP server process {pid}"),+ }+ }}+ }+ }++ async fn wait_for_exit(&self) -> anyhow::Result<()> {+ cfg_select! {+ unix => {{+ use core_test_support::process::wait_for_process_exit;++ let Self { pid } = self;+ wait_for_process_exit(pid).await+ }}+ windows => {{+ use anyhow::Context;++ tokio::time::timeout(Duration::from_secs(2), async {+ loop {+ let alive = self.is_alive()?;+ if !alive {+ return Ok(());+ }+ tokio::time::sleep(Duration::from_millis(25)).await;+ }+ })+ .await+ .context("timed out waiting for process to exit")?+ }}+ }+ }+}+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]async fn refresh_keeps_superseded_mcp_server_alive_for_in_flight_calls() -> anyhow::Result<()> {skip_if_no_network!(Ok(()));@@ -71,7 +176,7 @@ async fn refresh_keeps_superseded_mcp_server_alive_for_in_flight_calls() -> anyhwait_for_mcp_server(&fixture.codex, "refresh_cleanup").await?;let superseded_pid = wait_for_pid_file(&pid_file).await?;- assert!(process_is_alive(&superseded_pid)?);+ let superseded = McpServerProcess::observe_running(superseded_pid)?;let barrier = serde_json::json!({"id": "mcp-refresh-cleanup",@@ -119,8 +224,10 @@ async fn refresh_keeps_superseded_mcp_server_alive_for_in_flight_calls() -> anyhfixture.submit_turn("refresh MCP servers").await?;let replacement_pid = wait_for_pid_file(&pid_file).await?;- assert_ne!(replacement_pid, superseded_pid);- assert!(process_is_alive(&superseded_pid)?);+ let replacement = McpServerProcess::observe_running(replacement_pid)?;+ assert_ne!(replacement.pid, superseded.pid);+ let superseded_alive = superseded.is_alive()?;+ assert!(superseded_alive);long_call.abort();assert!(long_call@@ -128,9 +235,10 @@ async fn refresh_keeps_superseded_mcp_server_alive_for_in_flight_calls() -> anyh.expect_err("call should be aborted").is_cancelled());- wait_for_process_exit(&superseded_pid).await?;- assert!(process_is_alive(&replacement_pid)?);+ superseded.wait_for_exit().await?;+ let replacement_alive = replacement.is_alive()?;+ assert!(replacement_alive);fixture.codex.shutdown_and_wait().await?;- wait_for_process_exit(&replacement_pid).await+ replacement.wait_for_exit().await}diff --git a/codex-rs/core/tests/suite/mod.rs b/codex-rs/core/tests/suite/mod.rsindex 2971b1201d..aedd5de7ed 100644--- a/codex-rs/core/tests/suite/mod.rs+++ b/codex-rs/core/tests/suite/mod.rs@@ -129,7 +129,6 @@ mod mcp_auth_refresh;mod mcp_ema_config;mod mcp_extension_protocol;mod mcp_optional_startup_grace;-#[cfg(unix)]mod mcp_refresh_cleanup;mod mcp_startup_refresh_http_proxy;mod mcp_subagent_elicitation;diff --git a/codex-rs/exec-server/Cargo.toml b/codex-rs/exec-server/Cargo.tomlindex 25500aaaf5..710f344058 100644--- a/codex-rs/exec-server/Cargo.toml+++ b/codex-rs/exec-server/Cargo.toml@@ -80,12 +80,11 @@ rustix = { workspace = true, features = ["fs"] }tempfile = { workspace = true }[target.'cfg(windows)'.dependencies]-windows-sys = { version = "0.52", features = [+windows-sys = { workspace = true, features = ["Win32_Foundation","Win32_Security","Win32_Storage_FileSystem","Win32_System_IO",- "Win32_System_Kernel","Win32_System_Pipes","Win32_System_Threading",] }diff --git a/codex-rs/exec-server/src/no_follow/windows.rs b/codex-rs/exec-server/src/no_follow/windows.rsindex b8eebb5eb2..0a66882678 100644--- a/codex-rs/exec-server/src/no_follow/windows.rs+++ b/codex-rs/exec-server/src/no_follow/windows.rs@@ -8,7 +8,6 @@ use std::os::windows::ffi::OsStrExt;use std::os::windows::io::AsRawHandle;use std::os::windows::io::FromRawHandle;use std::os::windows::io::OwnedHandle;-use std::os::windows::io::RawHandle;use std::path::Component;use std::path::Path;use std::path::PathBuf;@@ -17,6 +16,8 @@ use std::ptr;use windows_sys::Win32::Foundation::HANDLE;use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;use windows_sys::Win32::Foundation::NTSTATUS;+use windows_sys::Win32::Foundation::OBJ_CASE_INSENSITIVE;+use windows_sys::Win32::Foundation::OBJ_DONT_REPARSE;use windows_sys::Win32::Foundation::RtlNtStatusToDosError;use windows_sys::Win32::Foundation::UNICODE_STRING;use windows_sys::Win32::Security::SECURITY_QUALITY_OF_SERVICE;@@ -34,8 +35,6 @@ use windows_sys::Win32::Storage::FileSystem::FileDispositionInfo;use windows_sys::Win32::Storage::FileSystem::SetFileInformationByHandle;use windows_sys::Win32::System::IO::IO_STATUS_BLOCK;use windows_sys::Win32::System::IO::IO_STATUS_BLOCK_0;-use windows_sys::Win32::System::Kernel::OBJ_CASE_INSENSITIVE;-use windows_sys::Win32::System::Kernel::OBJ_DONT_REPARSE;const FILE_DIRECTORY_FILE: u32 = 0x0000_0001;const FILE_SYNCHRONOUS_IO_NONALERT: u32 = 0x0000_0020;@@ -46,7 +45,6 @@ const FILE_OPEN_IF: u32 = 3;const SYNCHRONIZE_ACCESS: u32 = 0x0010_0000;const STATUS_REPARSE_POINT_ENCOUNTERED: NTSTATUS = 0xC000_050B_u32 as i32;const SECURITY_STATIC_TRACKING: u8 = 0;-const BOOLEAN_TRUE: u8 = 1;#[repr(C)]struct ObjectAttributes {@@ -141,13 +139,13 @@ fn open_handle(Length: size_of::<SECURITY_QUALITY_OF_SERVICE>() as u32,ImpersonationLevel: SecurityIdentification,ContextTrackingMode: SECURITY_STATIC_TRACKING,- EffectiveOnly: BOOLEAN_TRUE,+ EffectiveOnly: true,};let object_attributes = ObjectAttributes {length: size_of::<ObjectAttributes>() as u32,- root_directory: 0,+ root_directory: ptr::null_mut(),object_name: &object_name,- attributes: OBJ_CASE_INSENSITIVE as u32 | OBJ_DONT_REPARSE as u32,+ attributes: OBJ_CASE_INSENSITIVE | OBJ_DONT_REPARSE,security_descriptor: ptr::null(),security_quality_of_service: (&raw const security_quality_of_service).cast(),};@@ -155,7 +153,7 @@ fn open_handle(Anonymous: IO_STATUS_BLOCK_0 { Status: 0 },Information: 0,};- let mut handle = 0;+ let mut handle = ptr::null_mut();let status = unsafe {NtCreateFile(&mut handle,@@ -181,13 +179,13 @@ fn open_handle(let code = unsafe { RtlNtStatusToDosError(status) };return Err(io::Error::from_raw_os_error(code as i32));}- if handle == 0 || handle == INVALID_HANDLE_VALUE {+ if handle.is_null() || handle == INVALID_HANDLE_VALUE {return Err(io::Error::other("NtCreateFile returned an invalid filesystem handle",));}- Ok(unsafe { OwnedHandle::from_raw_handle(handle as RawHandle) })+ Ok(unsafe { OwnedHandle::from_raw_handle(handle) })}fn open_entry(path: &Path) -> io::Result<std::fs::File> {@@ -298,12 +296,10 @@ fn remove_sync(path: &Path, recursive: bool, force: bool) -> io::Result<()> {FILE_NON_DIRECTORY_FILE};let handle = open_handle(path, DELETE, FILE_OPEN, create_options)?;- let disposition = FILE_DISPOSITION_INFO {- DeleteFile: BOOLEAN_TRUE,- };+ let disposition = FILE_DISPOSITION_INFO { DeleteFile: true };let result = unsafe {SetFileInformationByHandle(- handle.as_raw_handle() as HANDLE,+ handle.as_raw_handle(),FileDispositionInfo,(&raw const disposition).cast(),size_of::<FILE_DISPOSITION_INFO>() as u32,diff --git a/codex-rs/exec-server/src/no_follow/windows_tests.rs b/codex-rs/exec-server/src/no_follow/windows_tests.rsindex d9e3b0bbeb..a07cf74b4b 100644--- a/codex-rs/exec-server/src/no_follow/windows_tests.rs+++ b/codex-rs/exec-server/src/no_follow/windows_tests.rs@@ -29,7 +29,7 @@ fn native_open_rejects_named_pipes_before_connecting() {)};assert_ne!(pipe, INVALID_HANDLE_VALUE);- let _pipe = unsafe { OwnedHandle::from_raw_handle(pipe as RawHandle) };+ let _pipe = unsafe { OwnedHandle::from_raw_handle(pipe) };let error = open_handle(&client_path,diff --git a/codex-rs/exec-server/src/regular_file.rs b/codex-rs/exec-server/src/regular_file.rsindex d942e9215e..2e74373242 100644--- a/codex-rs/exec-server/src/regular_file.rs+++ b/codex-rs/exec-server/src/regular_file.rs@@ -76,12 +76,11 @@ fn configure_open(_options: &mut std::fs::OpenOptions) {}#[cfg(windows)]pub(crate) fn is_disk_file(file: &impl std::os::windows::io::AsRawHandle) -> bool {- use windows_sys::Win32::Foundation::HANDLE;use windows_sys::Win32::Storage::FileSystem::FILE_TYPE_DISK;use windows_sys::Win32::Storage::FileSystem::GetFileType;// SAFETY: `file` owns this handle for the duration of the call.- unsafe { GetFileType(file.as_raw_handle() as HANDLE) == FILE_TYPE_DISK }+ unsafe { GetFileType(file.as_raw_handle()) == FILE_TYPE_DISK }}#[cfg(not(windows))]diff --git a/codex-rs/exec-server/src/sandboxed_file_open.rs b/codex-rs/exec-server/src/sandboxed_file_open.rsindex 875c7aca05..18e78e1746 100644--- a/codex-rs/exec-server/src/sandboxed_file_open.rs+++ b/codex-rs/exec-server/src/sandboxed_file_open.rs@@ -182,16 +182,16 @@ fn duplicate_file_handle(process_id: u32, file_handle: u64) -> io::Result<std::f// SAFETY: OpenProcess returns an owned handle or null on failure.let process = unsafe { OpenProcess(PROCESS_DUP_HANDLE, 0, process_id) };- if process == 0 {+ if process.is_null() {return Err(io::Error::last_os_error());}// SAFETY: The successful OpenProcess result is owned by this scope.- let process = unsafe { OwnedHandle::from_raw_handle(process as _) };- let mut duplicated: HANDLE = 0;+ let process = unsafe { OwnedHandle::from_raw_handle(process) };+ let mut duplicated = std::ptr::null_mut();// SAFETY: Both process handles remain valid and duplicated receives an owned file handle.if unsafe {DuplicateHandle(- process.as_raw_handle() as HANDLE,+ process.as_raw_handle(),file_handle as HANDLE,GetCurrentProcess(),&raw mut duplicated,@@ -204,5 +204,5 @@ fn duplicate_file_handle(process_id: u32, file_handle: u64) -> io::Result<std::freturn Err(io::Error::last_os_error());}// SAFETY: DuplicateHandle transferred ownership of the new file handle.- Ok(unsafe { std::fs::File::from_raw_handle(duplicated as _) })+ Ok(unsafe { std::fs::File::from_raw_handle(duplicated) })}diff --git a/codex-rs/exec-server/tests/file_system_windows.rs b/codex-rs/exec-server/tests/file_system_windows.rsindex a7ec5e7090..bbcd2c0698 100644--- a/codex-rs/exec-server/tests/file_system_windows.rs+++ b/codex-rs/exec-server/tests/file_system_windows.rs@@ -40,6 +40,7 @@ use test_case::test_case;use tokio::net::windows::named_pipe::ServerOptions;use tokio::time::timeout;use uuid::Uuid;+use windows_sys::Win32::Foundation::HANDLE;use windows_sys::Win32::System::Threading::GetCurrentProcess;use crate::support::FileSystemImplementation;@@ -653,7 +654,7 @@ fn process_private_desktops() -> Result<BTreeSet<String>> {// Native layout: https://github.com/winsiderss/phnt/blob/master/ntpsapi.h#[repr(C)]struct HandleEntry {- handle: isize,+ handle: HANDLE,_handle_count: usize,_pointer_count: usize,_granted_access: u32,@@ -664,7 +665,7 @@ fn process_private_desktops() -> Result<BTreeSet<String>> {#[link(name = "ntdll")]unsafe extern "system" {fn NtQueryInformationProcess(- process: isize,+ process: HANDLE,class: u32,information: *mut c_void,length: u32,@@ -674,7 +675,7 @@ fn process_private_desktops() -> Result<BTreeSet<String>> {#[link(name = "user32")]unsafe extern "system" {fn GetUserObjectInformationW(- object: isize,+ object: HANDLE,index: i32,information: *mut c_void,length: u32,diff --git a/codex-rs/http-client/Cargo.toml b/codex-rs/http-client/Cargo.tomlindex d59c2e78f7..8583220338 100644--- a/codex-rs/http-client/Cargo.toml+++ b/codex-rs/http-client/Cargo.toml@@ -32,7 +32,7 @@ system-configuration = { workspace = true }[target.'cfg(target_os = "windows")'.dependencies]rustls-platform-verifier = "0.7.0"-windows-sys = { version = "0.52", features = [+windows-sys = { workspace = true, features = ["Win32_Foundation","Win32_Networking_WinHttp",] }diff --git a/codex-rs/mxc-sandbox/Cargo.toml b/codex-rs/mxc-sandbox/Cargo.tomlindex 0518fa7976..49b5c16e66 100644--- a/codex-rs/mxc-sandbox/Cargo.toml+++ b/codex-rs/mxc-sandbox/Cargo.toml@@ -31,7 +31,7 @@ appcontainer_common = { workspace = true }learning_mode_windows = { workspace = true }# 1.2.4 imports OneCore_apiset, which the GNU Windows toolchain does not ship.tracelogging = "=1.2.3"-windows-sys = { version = "0.61", features = [+windows-sys = { workspace = true, features = ["Win32_Foundation","Win32_Storage_FileSystem","Win32_System_Com",diff --git a/codex-rs/network-proxy/Cargo.toml b/codex-rs/network-proxy/Cargo.tomlindex bda4261602..1fc4a89b6b 100644--- a/codex-rs/network-proxy/Cargo.toml+++ b/codex-rs/network-proxy/Cargo.toml@@ -66,7 +66,7 @@ security-framework = "3"[target.'cfg(windows)'.dependencies]schannel = "0.1"-windows-sys = { version = "0.52", features = [+windows-sys = { workspace = true, features = ["Win32_Foundation","Win32_NetworkManagement_IpHelper","Win32_Networking_WinSock",diff --git a/codex-rs/network-proxy/src/windows_tcp_attribution.rs b/codex-rs/network-proxy/src/windows_tcp_attribution.rsindex 5146d5e6ce..8134d04f0e 100644--- a/codex-rs/network-proxy/src/windows_tcp_attribution.rs+++ b/codex-rs/network-proxy/src/windows_tcp_attribution.rs@@ -8,7 +8,6 @@ use std::net::SocketAddrV4;use std::os::windows::io::AsRawHandle;use std::os::windows::io::FromRawHandle;use std::os::windows::io::OwnedHandle;-use std::os::windows::io::RawHandle;use windows_sys::Win32::Foundation::ERROR_INSUFFICIENT_BUFFER;use windows_sys::Win32::Foundation::GetLastError;@@ -16,7 +15,6 @@ use windows_sys::Win32::Foundation::HANDLE;use windows_sys::Win32::Foundation::HLOCAL;use windows_sys::Win32::Foundation::LocalFree;use windows_sys::Win32::Foundation::NO_ERROR;-use windows_sys::Win32::Foundation::PSID;use windows_sys::Win32::NetworkManagement::IpHelper::GetExtendedTcpTable;use windows_sys::Win32::NetworkManagement::IpHelper::MIB_TCPROW_OWNER_PID;use windows_sys::Win32::NetworkManagement::IpHelper::MIB_TCPTABLE_OWNER_PID;@@ -24,6 +22,7 @@ use windows_sys::Win32::NetworkManagement::IpHelper::TCP_TABLE_OWNER_PID_CONNECTuse windows_sys::Win32::Networking::WinSock::AF_INET;use windows_sys::Win32::Security::Authorization::ConvertSidToStringSidW;use windows_sys::Win32::Security::GetTokenInformation;+use windows_sys::Win32::Security::PSID;use windows_sys::Win32::Security::SID_AND_ATTRIBUTES;use windows_sys::Win32::Security::TOKEN_GROUPS;use windows_sys::Win32::Security::TOKEN_QUERY;@@ -180,14 +179,9 @@ fn restricting_sids_for_process(process_id: u32) -> io::Result<Vec<String>> {let process_handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, process_id) };let process = owned_handle(process_handle, "open proxy client process")?;- let mut token_handle: HANDLE = 0;- let opened = unsafe {- OpenProcessToken(- process.as_raw_handle() as HANDLE,- TOKEN_QUERY,- &mut token_handle,- )- };+ let mut token_handle = std::ptr::null_mut();+ let opened =+ unsafe { OpenProcessToken(process.as_raw_handle(), TOKEN_QUERY, &mut token_handle) };if opened == 0 {return Err(last_error("open proxy client process token"));}@@ -196,7 +190,7 @@ fn restricting_sids_for_process(process_id: u32) -> io::Result<Vec<String>> {let mut byte_len = 0_u32;let queried = unsafe {GetTokenInformation(- token.as_raw_handle() as HANDLE,+ token.as_raw_handle(),TokenRestrictedSids,std::ptr::null_mut(),0,@@ -210,7 +204,7 @@ fn restricting_sids_for_process(process_id: u32) -> io::Result<Vec<String>> {let mut buffer = aligned_buffer(byte_len as usize)?;let queried = unsafe {GetTokenInformation(- token.as_raw_handle() as HANDLE,+ token.as_raw_handle(),TokenRestrictedSids,buffer.as_mut_ptr().cast::<c_void>(),byte_len,@@ -294,10 +288,10 @@ fn aligned_buffer(byte_len: usize) -> io::Result<Vec<usize>> {}fn owned_handle(handle: HANDLE, operation: &str) -> io::Result<OwnedHandle> {- if handle == 0 {+ if handle.is_null() {return Err(last_error(operation));}- Ok(unsafe { OwnedHandle::from_raw_handle(handle as RawHandle) })+ Ok(unsafe { OwnedHandle::from_raw_handle(handle) })}fn win32_error(operation: &str, error_code: u32) -> io::Error {diff --git a/codex-rs/network-proxy/tests/windows_stable_ingress.rs b/codex-rs/network-proxy/tests/windows_stable_ingress.rsindex 66038ce4ef..1e04563c6e 100644--- a/codex-rs/network-proxy/tests/windows_stable_ingress.rs+++ b/codex-rs/network-proxy/tests/windows_stable_ingress.rs@@ -405,18 +405,15 @@ fn run_restricted_child_blocking() -> anyhow::Result<()> {let route_sid = LocalSid::from_string(route_sid)?;let capability_sid = LocalSid::from_string("S-1-5-21-10-20-30-40")?;- let base_token = unsafe {- OwnedHandle::from_raw_handle(get_current_token_for_restriction()? as *mut std::ffi::c_void)- };+ let base_token = unsafe { OwnedHandle::from_raw_handle(get_current_token_for_restriction()?) };let restricted_token = unsafe {create_readonly_token_with_caps_and_user_from(- base_token.as_raw_handle() as isize,+ base_token.as_raw_handle(),&[capability_sid.as_ptr()],&[route_sid.as_ptr()],)?};- let restricted_token =- unsafe { OwnedHandle::from_raw_handle(restricted_token as *mut std::ffi::c_void) };+ let restricted_token = unsafe { OwnedHandle::from_raw_handle(restricted_token) };let mut env = std::env::vars().collect::<HashMap<_, _>>();env.insert(HTTP_ADDR_ENV.to_string(), http_addr.to_string());@@ -445,7 +442,7 @@ fn run_restricted_child_blocking(let cwd = std::env::current_dir()?;let spawned = unsafe {create_process_as_user(- restricted_token.as_raw_handle() as isize,+ restricted_token.as_raw_handle(),&command,&cwd,&env,@@ -455,27 +452,23 @@ fn run_restricted_child_blocking(LaunchDesktop::prepare(/*logs_base_dir*/ None)?,)?};- let process = unsafe {- OwnedHandle::from_raw_handle(spawned.process_info.hProcess as *mut std::ffi::c_void)- };- let _thread = unsafe {- OwnedHandle::from_raw_handle(spawned.process_info.hThread as *mut std::ffi::c_void)- };+ let process = unsafe { OwnedHandle::from_raw_handle(spawned.process_info.hProcess) };+ let _thread = unsafe { OwnedHandle::from_raw_handle(spawned.process_info.hThread) };let wait = unsafe {WaitForSingleObject(- process.as_raw_handle() as isize,+ process.as_raw_handle(),/*dwMilliseconds*/ CHILD_TIMEOUT_MS,)};if wait != WAIT_OBJECT_0 {unsafe {- TerminateProcess(process.as_raw_handle() as isize, 1);+ TerminateProcess(process.as_raw_handle(), 1);}}let mut exit_code = 1_u32;unsafe {- GetExitCodeProcess(process.as_raw_handle() as isize, &mut exit_code);+ GetExitCodeProcess(process.as_raw_handle(), &mut exit_code);}anyhow::ensure!(wait == WAIT_OBJECT_0 && exit_code == 0,diff --git a/codex-rs/rmcp-client/Cargo.toml b/codex-rs/rmcp-client/Cargo.tomlindex 81758721ca..4702b0f53f 100644--- a/codex-rs/rmcp-client/Cargo.toml+++ b/codex-rs/rmcp-client/Cargo.toml@@ -90,7 +90,7 @@ keyring = { workspace = true, features = ["apple-native"] }[target.'cfg(target_os = "windows")'.dependencies]keyring = { workspace = true, features = ["windows-native"] }-windows-sys = { version = "0.52", features = ["Win32_Storage_FileSystem"] }+windows-sys = { workspace = true, features = ["Win32_Storage_FileSystem"] }[target.'cfg(any(target_os = "freebsd", target_os = "openbsd"))'.dependencies]keyring = { workspace = true, features = ["sync-secret-service"] }diff --git a/codex-rs/tui/Cargo.toml b/codex-rs/tui/Cargo.tomlindex 9d61157c42..45f5866515 100644--- a/codex-rs/tui/Cargo.toml+++ b/codex-rs/tui/Cargo.toml@@ -150,7 +150,7 @@ zbus = "4.4.0"[target.'cfg(windows)'.dependencies]which = { workspace = true }-windows-sys = { version = "0.52", features = [+windows-sys = { workspace = true, features = ["Win32_Foundation","Win32_Globalization","Win32_Security",diff --git a/codex-rs/tui/src/ide_context/windows_pipe.rs b/codex-rs/tui/src/ide_context/windows_pipe.rsindex 584e87ffd4..4f6ffb829e 100644--- a/codex-rs/tui/src/ide_context/windows_pipe.rs+++ b/codex-rs/tui/src/ide_context/windows_pipe.rs@@ -4,12 +4,13 @@ use std::io;use std::io::Read;use std::io::Write;use std::os::windows::ffi::OsStrExt;+use std::os::windows::io::AsRawHandle;+use std::os::windows::io::FromRawHandle;+use std::os::windows::io::OwnedHandle;use std::path::PathBuf;use std::ptr;use std::time::Instant;-use windows_sys::Win32::Foundation::BOOL;-use windows_sys::Win32::Foundation::CloseHandle;use windows_sys::Win32::Foundation::ERROR_IO_PENDING;use windows_sys::Win32::Foundation::ERROR_NOT_FOUND;use windows_sys::Win32::Foundation::GENERIC_READ;@@ -44,10 +45,10 @@ use windows_sys::Win32::System::Threading::OpenProcess;use windows_sys::Win32::System::Threading::OpenProcessToken;use windows_sys::Win32::System::Threading::PROCESS_QUERY_LIMITED_INFORMATION;use windows_sys::Win32::System::Threading::WaitForSingleObject;+use windows_sys::core::BOOL;const TRUE: BOOL = 1;const FALSE: BOOL = 0;-const NULL_HANDLE: HANDLE = 0;pub(super) struct WindowsPipeStream {handle: OwnedHandle,@@ -73,15 +74,16 @@ impl WindowsPipeStream {| FILE_FLAG_OVERLAPPED| SECURITY_SQOS_PRESENT| SECURITY_IDENTIFICATION,- NULL_HANDLE,+ ptr::null_mut(),)};if handle == INVALID_HANDLE_VALUE {return Err(io::Error::last_os_error());}- let handle = OwnedHandle(handle);- validate_pipe_server_owner(handle.raw())?;+ // SAFETY: CreateFileW returned an owned pipe handle.+ let handle = unsafe { OwnedHandle::from_raw_handle(handle) };+ validate_pipe_server_owner(handle.as_raw_handle())?;Ok(Self { handle, deadline })}@@ -101,7 +103,7 @@ impl Read for WindowsPipeStream {let mut operation = OverlappedOperation::new()?;let result = unsafe {ReadFile(- self.handle.raw(),+ self.handle.as_raw_handle(),buf.as_mut_ptr(),bytes_to_read,ptr::null_mut(),@@ -109,7 +111,7 @@ impl Read for WindowsPipeStream {)};- operation.complete(self.handle.raw(), result, self.deadline)+ operation.complete(self.handle.as_raw_handle(), result, self.deadline)}}@@ -123,7 +125,7 @@ impl Write for WindowsPipeStream {let mut operation = OverlappedOperation::new()?;let result = unsafe {WriteFile(- self.handle.raw(),+ self.handle.as_raw_handle(),buf.as_ptr(),bytes_to_write,ptr::null_mut(),@@ -131,7 +133,7 @@ impl Write for WindowsPipeStream {)};- operation.complete(self.handle.raw(), result, self.deadline)+ operation.complete(self.handle.as_raw_handle(), result, self.deadline)}fn flush(&mut self) -> io::Result<()> {@@ -147,14 +149,15 @@ struct OverlappedOperation {impl OverlappedOperation {fn new() -> io::Result<Self> {let event = unsafe { CreateEventW(ptr::null(), TRUE, FALSE, ptr::null()) };- if event == 0 {+ if event.is_null() {return Err(io::Error::last_os_error());}let mut overlapped = unsafe { std::mem::zeroed::<OVERLAPPED>() };overlapped.hEvent = event;Ok(Self {- event: OwnedHandle(event),+ // SAFETY: CreateEventW returned an owned event handle.+ event: unsafe { OwnedHandle::from_raw_handle(event) },overlapped,})}@@ -177,7 +180,9 @@ impl OverlappedOperation {// Use a zero wait after the deadline so pending overlapped I/O still flows through// cancel_and_timeout instead of returning while the OS operation owns this OVERLAPPED.- match unsafe { WaitForSingleObject(self.event.raw(), remaining_timeout_ms(deadline)) } {+ match unsafe {+ WaitForSingleObject(self.event.as_raw_handle(), remaining_timeout_ms(deadline))+ } {WAIT_OBJECT_0 => {}WAIT_TIMEOUT => return Err(self.cancel_and_timeout(handle)),WAIT_FAILED => return Err(io::Error::last_os_error()),@@ -225,30 +230,12 @@ impl OverlappedOperation {}}-struct OwnedHandle(HANDLE);--impl OwnedHandle {- fn raw(&self) -> HANDLE {- self.0- }-}--impl Drop for OwnedHandle {- fn drop(&mut self) {- if self.0 != 0 && self.0 != INVALID_HANDLE_VALUE {- unsafe {- CloseHandle(self.0);- }- }- }-}-struct TokenUserBuffer {buffer: Vec<u8>,}impl TokenUserBuffer {- fn sid(&self) -> io::Result<windows_sys::Win32::Foundation::PSID> {+ fn sid(&self) -> io::Result<windows_sys::Win32::Security::PSID> {if self.buffer.len() < std::mem::size_of::<TOKEN_USER>() {return Err(io::Error::new(io::ErrorKind::InvalidData,@@ -274,14 +261,15 @@ fn validate_pipe_server_owner(pipe_handle: HANDLE) -> io::Result<()> {let server_process =unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, server_process_id) };- if server_process == 0 {+ if server_process.is_null() {return Err(io::Error::last_os_error());}- let server_process = OwnedHandle(server_process);- let server_token = open_process_token(server_process.raw())?;+ // SAFETY: OpenProcess returned an owned process handle.+ let server_process = unsafe { OwnedHandle::from_raw_handle(server_process) };+ let server_token = open_process_token(server_process.as_raw_handle())?;let current_token = open_process_token(unsafe { GetCurrentProcess() })?;- let server_user = token_user(server_token.raw())?;- let current_user = token_user(current_token.raw())?;+ let server_user = token_user(server_token.as_raw_handle())?;+ let current_user = token_user(current_token.as_raw_handle())?;if unsafe { EqualSid(server_user.sid()?, current_user.sid()?) } == 0 {return Err(io::Error::new(@@ -294,13 +282,14 @@ fn validate_pipe_server_owner(pipe_handle: HANDLE) -> io::Result<()> {}fn open_process_token(process: HANDLE) -> io::Result<OwnedHandle> {- let mut token = 0;+ let mut token = ptr::null_mut();let result = unsafe { OpenProcessToken(process, TOKEN_QUERY, &mut token) };if result == 0 {return Err(io::Error::last_os_error());}- Ok(OwnedHandle(token))+ // SAFETY: OpenProcessToken returned an owned token handle.+ Ok(unsafe { OwnedHandle::from_raw_handle(token) })}fn token_user(token: HANDLE) -> io::Result<TokenUserBuffer> {diff --git a/codex-rs/tui/src/ide_context/windows_pipe_tests.rs b/codex-rs/tui/src/ide_context/windows_pipe_tests.rsindex 123a47198e..1740644eb7 100644--- a/codex-rs/tui/src/ide_context/windows_pipe_tests.rs+++ b/codex-rs/tui/src/ide_context/windows_pipe_tests.rs@@ -39,10 +39,10 @@ fn pipe_server_cannot_impersonate_client() {)};assert_ne!(pipe, INVALID_HANDLE_VALUE);- let pipe = OwnedHandle(pipe);+ let pipe = unsafe { OwnedHandle::from_raw_handle(pipe) };let server = std::thread::spawn(move || {- if unsafe { ConnectNamedPipe(pipe.raw(), ptr::null_mut()) } == FALSE {+ if unsafe { ConnectNamedPipe(pipe.as_raw_handle(), ptr::null_mut()) } == FALSE {assert_eq!(io::Error::last_os_error().raw_os_error(),Some(ERROR_PIPE_CONNECTED as i32)@@ -54,7 +54,7 @@ fn pipe_server_cannot_impersonate_client() {assert_ne!(unsafe {ReadFile(- pipe.raw(),+ pipe.as_raw_handle(),message.as_mut_ptr(),message.len() as u32,&mut bytes_read,@@ -63,19 +63,22 @@ fn pipe_server_cannot_impersonate_client() {},FALSE);- assert_ne!(unsafe { ImpersonateNamedPipeClient(pipe.raw()) }, FALSE);+ assert_ne!(+ unsafe { ImpersonateNamedPipeClient(pipe.as_raw_handle()) },+ FALSE+ );- let mut token = NULL_HANDLE;+ let mut token = ptr::null_mut();assert_ne!(unsafe { OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &mut token) },FALSE);- let token = OwnedHandle(token);+ let token = unsafe { OwnedHandle::from_raw_handle(token) };let mut impersonation_level = 0;let mut return_length = 0;let result = unsafe {GetTokenInformation(- token.raw(),+ token.as_raw_handle(),TokenImpersonationLevel,(&raw mut impersonation_level).cast(),std::mem::size_of_val(&impersonation_level) as u32,diff --git a/codex-rs/tui/src/screen_reader.rs b/codex-rs/tui/src/screen_reader.rsindex e4bc3919b5..10d24217f4 100644--- a/codex-rs/tui/src/screen_reader.rs+++ b/codex-rs/tui/src/screen_reader.rs@@ -122,13 +122,13 @@ async fn detect() -> bool {let detected = {use windows_sys::Win32::UI::WindowsAndMessaging::SPI_GETSCREENREADER;use windows_sys::Win32::UI::WindowsAndMessaging::SystemParametersInfoW;- let mut enabled: windows_sys::Win32::Foundation::BOOL = 0;+ let mut enabled: windows_sys::core::BOOL = 0;// SAFETY: SPI_GETSCREENREADER writes one BOOL to this valid, aligned pointer.let success = unsafe {SystemParametersInfoW(SPI_GETSCREENREADER,/*uiparam*/ 0,- (&mut enabled as *mut windows_sys::Win32::Foundation::BOOL).cast(),+ (&mut enabled as *mut windows_sys::core::BOOL).cast(),/*fwinini*/ 0,)};diff --git a/codex-rs/tui/src/system_motion.rs b/codex-rs/tui/src/system_motion.rsindex a3c941a21e..b11c643320 100644--- a/codex-rs/tui/src/system_motion.rs+++ b/codex-rs/tui/src/system_motion.rs@@ -34,13 +34,13 @@ async fn detect() -> Option<MotionMode> {use windows_sys::Win32::UI::WindowsAndMessaging::SPI_GETCLIENTAREAANIMATION;use windows_sys::Win32::UI::WindowsAndMessaging::SystemParametersInfoW;- let mut enabled: windows_sys::Win32::Foundation::BOOL = 0;+ let mut enabled: windows_sys::core::BOOL = 0;// SAFETY: SPI_GETCLIENTAREAANIMATION writes one BOOL to this valid, aligned pointer.let success = unsafe {SystemParametersInfoW(SPI_GETCLIENTAREAANIMATION,/*uiparam*/ 0,- (&mut enabled as *mut windows_sys::Win32::Foundation::BOOL).cast(),+ (&mut enabled as *mut windows_sys::core::BOOL).cast(),/*fwinini*/ 0,)};diff --git a/codex-rs/tui/src/terminal_probe/windows.rs b/codex-rs/tui/src/terminal_probe/windows.rsindex b47e8a3b98..bf06a68565 100644--- a/codex-rs/tui/src/terminal_probe/windows.rs+++ b/codex-rs/tui/src/terminal_probe/windows.rs@@ -344,7 +344,7 @@ fn decode_color_ref(color_ref: u32) -> (u8, u8, u8) {fn std_handle(kind: u32) -> io::Result<HANDLE> {let handle = unsafe { GetStdHandle(kind) };- if handle == 0 || handle == INVALID_HANDLE_VALUE {+ if handle.is_null() || handle == INVALID_HANDLE_VALUE {return Err(io::Error::last_os_error());}Ok(handle)diff --git a/codex-rs/tui/src/tui.rs b/codex-rs/tui/src/tui.rsindex 50b4e80e76..69abbb388e 100644--- a/codex-rs/tui/src/tui.rs+++ b/codex-rs/tui/src/tui.rs@@ -441,7 +441,7 @@ fn flush_terminal_input_buffer() {use windows_sys::Win32::System::Console::STD_INPUT_HANDLE;let handle = unsafe { GetStdHandle(STD_INPUT_HANDLE) };- if handle == INVALID_HANDLE_VALUE || handle == 0 {+ if handle == INVALID_HANDLE_VALUE || handle.is_null() {let err = unsafe { GetLastError() };tracing::warn!("failed to get stdin handle for flush: error {err}");return;@@ -1529,7 +1529,7 @@ fn ensure_virtual_terminal_processing() -> Result<()> {use windows_sys::Win32::System::Console::SetConsoleMode;fn enable_for_handle(handle: HANDLE) -> Result<()> {- if handle == INVALID_HANDLE_VALUE || handle == 0 {+ if handle == INVALID_HANDLE_VALUE || handle.is_null() {return Ok(());}diff --git a/codex-rs/tui/src/tui/alternate_screen_windows_tests.rs b/codex-rs/tui/src/tui/alternate_screen_windows_tests.rsindex ce2ae815bc..6ae454c0a9 100644--- a/codex-rs/tui/src/tui/alternate_screen_windows_tests.rs+++ b/codex-rs/tui/src/tui/alternate_screen_windows_tests.rs@@ -17,7 +17,7 @@ const CHILD_ENV: &str = "CODEX_TUI_MOUSE_CAPTURE_TEST_CHILD";fn console_mode(input: &File) -> u32 {let mut mode = 0;// SAFETY: input is an open console handle and mode points to writable storage.- let result = unsafe { GetConsoleMode(input.as_raw_handle() as isize, &mut mode) };+ let result = unsafe { GetConsoleMode(input.as_raw_handle(), &mut mode) };assert_ne!(result, 0, "{}", std::io::Error::last_os_error());mode}@@ -51,7 +51,7 @@ fn mouse_capture_restores_console_mode_and_encoding() {.expect("open console input");let initial_mode = console_mode(&input) & !ENABLE_MOUSE_INPUT;// SAFETY: input is an open console handle and initial_mode is a valid console input mode.- let result = unsafe { SetConsoleMode(input.as_raw_handle() as isize, initial_mode) };+ let result = unsafe { SetConsoleMode(input.as_raw_handle(), initial_mode) };assert_ne!(result, 0, "{}", std::io::Error::last_os_error());let original_mode = console_mode(&input);assert_eq!(original_mode & ENABLE_MOUSE_INPUT, 0);diff --git a/codex-rs/tui/src/tui/input_boundary.rs b/codex-rs/tui/src/tui/input_boundary.rsindex 8930959ade..c9a16e579d 100644--- a/codex-rs/tui/src/tui/input_boundary.rs+++ b/codex-rs/tui/src/tui/input_boundary.rs@@ -105,7 +105,7 @@ fn terminal_input_is_readable() -> Result<bool> {use windows_sys::Win32::System::Console::STD_INPUT_HANDLE;let handle = unsafe { GetStdHandle(STD_INPUT_HANDLE) };- if handle == INVALID_HANDLE_VALUE || handle == 0 {+ if handle == INVALID_HANDLE_VALUE || handle.is_null() {return Err(io::Error::other("terminal input handle is unavailable"));}diff --git a/codex-rs/tui/src/tui/windows_console.rs b/codex-rs/tui/src/tui/windows_console.rsindex e328f4ef50..8b56d0a068 100644--- a/codex-rs/tui/src/tui/windows_console.rs+++ b/codex-rs/tui/src/tui/windows_console.rs@@ -29,7 +29,7 @@ fn current_input_mode() -> Option<(windows_sys::Win32::Foundation::HANDLE, u32)>use windows_sys::Win32::System::Console::STD_INPUT_HANDLE;let handle = unsafe { GetStdHandle(STD_INPUT_HANDLE) };- if handle == INVALID_HANDLE_VALUE || handle == 0 {+ if handle == INVALID_HANDLE_VALUE || handle.is_null() {return None;}diff --git a/codex-rs/uds/Cargo.toml b/codex-rs/uds/Cargo.tomlindex a1f199ed46..a985ebd3a6 100644--- a/codex-rs/uds/Cargo.toml+++ b/codex-rs/uds/Cargo.toml@@ -22,7 +22,7 @@ libc = { workspace = true }async-io = { workspace = true }tokio-util = { workspace = true, features = ["compat"] }uds_windows = { workspace = true }-windows-sys = { version = "0.52", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_Threading", "Win32_System_SystemServices", "Win32_Networking_WinSock", "Win32_System_IO"] }+windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_Threading", "Win32_System_SystemServices", "Win32_Networking_WinSock", "Win32_System_IO"] }[dev-dependencies]pretty_assertions = { workspace = true }diff --git a/codex-rs/uds/src/windows_peer.rs b/codex-rs/uds/src/windows_peer.rsindex 722133365b..99a5835556 100644--- a/codex-rs/uds/src/windows_peer.rs+++ b/codex-rs/uds/src/windows_peer.rs@@ -55,20 +55,20 @@ pub(super) fn ensure_non_elevated_peer(socket: RawSocket) -> io::Result<()> {pid,)};- if process == 0 {+ if process.is_null() {return Err(io::Error::last_os_error());}- let _process = unsafe { OwnedHandle::from_raw_handle(process as _) };- let mut token = 0;+ let _process = unsafe { OwnedHandle::from_raw_handle(process) };+ let mut token = ptr::null_mut();if unsafe { OpenProcessToken(process, TOKEN_QUERY, &mut token) } == 0 {return Err(io::Error::last_os_error());}- let _token = unsafe { OwnedHandle::from_raw_handle(token as _) };- let mut current_token = 0;+ let _token = unsafe { OwnedHandle::from_raw_handle(token) };+ let mut current_token = ptr::null_mut();if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut current_token) } == 0 {return Err(io::Error::last_os_error());}- let _current_token = unsafe { OwnedHandle::from_raw_handle(current_token as _) };+ let _current_token = unsafe { OwnedHandle::from_raw_handle(current_token) };let current_user = crate::windows_security::token_user(current_token)?;let peer_user = crate::windows_security::token_user(token)?;let same_user = unsafe {diff --git a/codex-rs/uds/src/windows_security.rs b/codex-rs/uds/src/windows_security.rsindex 9b818d8411..90dc6f3a6a 100644--- a/codex-rs/uds/src/windows_security.rs+++ b/codex-rs/uds/src/windows_security.rs@@ -92,11 +92,11 @@ pub(super) fn prepare_private_directory(path: &Path) -> io::Result<()> {// Keep the pointer-aligned buffer alive while using its TOKEN_USER SID.pub(super) fn current_user() -> io::Result<Vec<usize>> {// Token information contains pointers, so allocate pointer-aligned storage.- let mut token = 0;+ let mut token = ptr::null_mut();if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } == 0 {return Err(io::Error::last_os_error());}- let _token = unsafe { OwnedHandle::from_raw_handle(token as _) };+ let _token = unsafe { OwnedHandle::from_raw_handle(token) };token_user(token)}diff --git a/codex-rs/uds/src/windows_socket_validation.rs b/codex-rs/uds/src/windows_socket_validation.rsindex 26a955bc28..bd468b6649 100644--- a/codex-rs/uds/src/windows_socket_validation.rs+++ b/codex-rs/uds/src/windows_socket_validation.rs@@ -67,13 +67,13 @@ pub(super) fn validate_private_directory(directory: &Path) -> io::Result<(PathBuptr::null(),OPEN_EXISTING,FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,- /*htemplatefile*/ 0,+ ptr::null_mut(),)};if handle == INVALID_HANDLE_VALUE {return Err(io::Error::last_os_error());}- let guard = unsafe { OwnedHandle::from_raw_handle(handle as _) };+ let guard = unsafe { OwnedHandle::from_raw_handle(handle) };let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };if unsafe { GetFileInformationByHandle(handle, &mut info) } == 0 {return Err(io::Error::last_os_error());diff --git a/codex-rs/utils/path-utils/Cargo.toml b/codex-rs/utils/path-utils/Cargo.tomlindex 6757b3f69c..c4cc1c7481 100644--- a/codex-rs/utils/path-utils/Cargo.toml+++ b/codex-rs/utils/path-utils/Cargo.toml@@ -13,7 +13,7 @@ dunce = { workspace = true }tempfile = { workspace = true }[target.'cfg(windows)'.dependencies]-windows-sys = { version = "0.52", features = [+windows-sys = { workspace = true, features = ["Win32_Foundation","Win32_System_Com","Win32_UI_Shell",diff --git a/codex-rs/utils/path-utils/src/system_commands.rs b/codex-rs/utils/path-utils/src/system_commands.rsindex f687d6b609..7e51da40aa 100644--- a/codex-rs/utils/path-utils/src/system_commands.rs+++ b/codex-rs/utils/path-utils/src/system_commands.rs@@ -138,7 +138,7 @@ fn installation_roots() -> Vec<PathBuf> {SHGetKnownFolderPath(id,KF_FLAG_DEFAULT_PATH as u32,- /*htoken*/ 0,+ std::ptr::null_mut(),&mut path,)};diff --git a/codex-rs/utils/sleep-inhibitor/Cargo.toml b/codex-rs/utils/sleep-inhibitor/Cargo.tomlindex f2abb6df21..14ab4d675e 100644--- a/codex-rs/utils/sleep-inhibitor/Cargo.toml+++ b/codex-rs/utils/sleep-inhibitor/Cargo.toml@@ -17,7 +17,7 @@ core-foundation = "0.9"libc = { workspace = true }[target.'cfg(target_os = "windows")'.dependencies]-windows-sys = { version = "0.61.2", features = [+windows-sys = { workspace = true, features = ["Win32_Foundation","Win32_System_Power","Win32_System_SystemServices",diff --git a/codex-rs/windows-sandbox-rs/Cargo.toml b/codex-rs/windows-sandbox-rs/Cargo.tomlindex 2f8d9d9258..a798fb828d 100644--- a/codex-rs/windows-sandbox-rs/Cargo.toml+++ b/codex-rs/windows-sandbox-rs/Cargo.toml@@ -78,7 +78,6 @@ features = ["Win32_System_WindowsProgramming","Win32_System_IO","Win32_System_Memory",- "Win32_System_Kernel","Win32_System_Console","Win32_System_RemoteDesktop","Win32_Storage_FileSystem",@@ -99,7 +98,7 @@ features = ["Win32_System_Registry","Win32_System_Services",]-version = "0.52"+workspace = true[dev-dependencies]codex-utils-cargo-bin = { workspace = true }diff --git a/codex-rs/windows-sandbox-rs/src/acl.rs b/codex-rs/windows-sandbox-rs/src/acl.rsindex b0f466f2ac..0ef5e44ffc 100644--- a/codex-rs/windows-sandbox-rs/src/acl.rs+++ b/codex-rs/windows-sandbox-rs/src/acl.rs@@ -1097,9 +1097,9 @@ pub unsafe fn allow_null_device(psid: *mut c_void) {std::ptr::null_mut(),OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,- 0,+ std::ptr::null_mut(),);- if h == 0 || h == INVALID_HANDLE_VALUE {+ if h.is_null() || h == INVALID_HANDLE_VALUE {return;}let mut p_sd: *mut c_void = std::ptr::null_mut();diff --git a/codex-rs/windows-sandbox-rs/src/bin/command_runner/win.rs b/codex-rs/windows-sandbox-rs/src/bin/command_runner/win.rsindex 8a00f8cb05..e2dcb6721e 100644--- a/codex-rs/windows-sandbox-rs/src/bin/command_runner/win.rs+++ b/codex-rs/windows-sandbox-rs/src/bin/command_runner/win.rs@@ -51,7 +51,10 @@ use codex_windows_sandbox::token_mode_for_permission_profile;use codex_windows_sandbox::write_frame;use std::ffi::OsStr;use std::fs::File;+use std::os::windows::io::AsHandle;+use std::os::windows::io::AsRawHandle;use std::os::windows::io::FromRawHandle;+use std::os::windows::io::OwnedHandle;use std::path::Path;use std::path::PathBuf;use std::ptr;@@ -67,6 +70,7 @@ use windows_sys::Win32::Storage::FileSystem::FILE_GENERIC_READ;use windows_sys::Win32::Storage::FileSystem::FILE_GENERIC_WRITE;use windows_sys::Win32::Storage::FileSystem::OPEN_EXISTING;use windows_sys::Win32::System::Console::COORD;+use windows_sys::Win32::System::Console::HPCON;use windows_sys::Win32::System::Console::ResizePseudoConsole;use windows_sys::Win32::System::Threading::GetExitCodeProcess;use windows_sys::Win32::System::Threading::GetProcessId;@@ -89,10 +93,16 @@ struct IpcSpawnedProcess {stderr_handle: HANDLE,stdin_handle: Option<HANDLE>,conpty_owner: Option<codex_windows_sandbox::ConptyInstance>,- hpc_handle: Option<HANDLE>,+ hpc_handle: Option<HPCON>,_pipe_handles: Option<PipeSpawnHandles>,}+struct NonOwningProcessHandle(HANDLE);++// SAFETY: Process handles are opaque process-wide tokens that may be used from+// any thread. This wrapper does not own the handle or extend its lifetime.+unsafe impl Send for NonOwningProcessHandle {}+/// Small RAII wrapper for raw Win32 handles.////// The elevated runner has a few early-return paths where we acquire a token, job, or pipe@@ -113,14 +123,14 @@ impl OwnedWinHandle {// Transfer ownership to the caller. After this point the caller is responsible for// eventually closing the returned HANDLE.let handle = self.0;- self.0 = 0;+ self.0 = std::ptr::null_mut();handle}}impl Drop for OwnedWinHandle {fn drop(&mut self) {- if self.0 != 0 && self.0 != INVALID_HANDLE_VALUE {+ if !self.0.is_null() && self.0 != INVALID_HANDLE_VALUE {unsafe {CloseHandle(self.0);}@@ -139,7 +149,7 @@ fn open_pipe(name: &str, access: u32) -> Result<HANDLE> {std::ptr::null_mut(),OPEN_EXISTING,0,- 0,+ std::ptr::null_mut(),)};if handle == windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE {@@ -198,7 +208,7 @@ fn read_spawn_request(reader: &mut File) -> Result<SpawnRequest> {fn read_acl_mutex_exists() -> Result<bool> {let name = to_wide(OsStr::new(READ_ACL_MUTEX_NAME));let handle = unsafe { OpenMutexW(MUTEX_ALL_ACCESS, 0, name.as_ptr()) };- if handle == 0 {+ if handle.is_null() {let err = unsafe { GetLastError() };if err == ERROR_FILE_NOT_FOUND {return Ok(false);@@ -268,7 +278,7 @@ fn spawn_ipc_process(req: &SpawnRequest) -> Result<IpcSpawnedProcess> {.map(LocalSid::as_ptr).collect();let base = OwnedWinHandle::new(unsafe { get_current_token_for_restriction()? });- let h_token = OwnedWinHandle::new(unsafe {+ let h_token = unsafe {match token_mode {WindowsSandboxTokenMode::ReadOnlyCapability => {create_readonly_token_with_caps_and_user_from(@@ -285,7 +295,9 @@ fn spawn_ipc_process(req: &SpawnRequest) -> Result<IpcSpawnedProcess> {)}}- }?);+ }?;+ // SAFETY: Both token helpers transfer ownership of the returned handle to the caller.+ let h_token = unsafe { OwnedHandle::from_raw_handle(h_token) };unsafe {// These ACL adjustments need the raw SID values, but ownership stays with `cap_psids`.// We do not manually `LocalFree` anything here; the wrappers handle every return path.@@ -303,11 +315,11 @@ fn spawn_ipc_process(req: &SpawnRequest) -> Result<IpcSpawnedProcess> {)?;let mut conpty_owner = None;- let mut hpc_handle: Option<HANDLE> = None;+ let mut hpc_handle: Option<HPCON> = None;let mut pipe_handles = None;let (pi, job, stdout_handle, stderr_handle, stdin_handle) = if req.tty {let (pi, mut conpty) = codex_windows_sandbox::spawn_conpty_process_as_user(- h_token.raw(),+ h_token.as_handle(),&req.command,&effective_cwd,&req.env,@@ -342,7 +354,7 @@ fn spawn_ipc_process(req: &SpawnRequest) -> Result<IpcSpawnedProcess> {StdinMode::Closed};let spawned_pipes: PipeSpawnHandles = spawn_process_with_pipes(- h_token.raw(),+ h_token.as_handle(),&req.command,&effective_cwd,&req.env,@@ -382,6 +394,8 @@ fn spawn_output_reader(stream: OutputStream,log_dir: Option<PathBuf>,) -> std::thread::JoinHandle<()> {+ // SAFETY: The spawn path transfers this pipe's read end to the reader.+ let handle = unsafe { OwnedHandle::from_raw_handle(handle) };read_handle_loop(handle, move |chunk| {let msg = FramedMessage {version: IPC_PROTOCOL_VERSION,@@ -403,13 +417,17 @@ fn spawn_output_reader(})}-fn terminate_job_or_process(job: &JobObject, process: HANDLE, log_dir: Option<&Path>) {+fn terminate_job_or_process(+ job: &JobObject,+ process: &NonOwningProcessHandle,+ log_dir: Option<&Path>,+) {if let Err(job_err) = job.terminate() {log_note(&format!("runner failed to terminate process tree: {job_err}"),log_dir,);- if unsafe { TerminateProcess(process, 1) } == 0 {+ if unsafe { TerminateProcess(process.0, 1) } == 0 {log_note(&format!("runner failed to terminate root process: {}", unsafe {GetLastError()@@ -424,18 +442,20 @@ fn terminate_job_or_process(job: &JobObject, process: HANDLE, log_dir: Option<&Pfn spawn_input_loop(mut reader: File,stdin_handle: Option<HANDLE>,- hpc_handle: Arc<StdMutex<Option<HANDLE>>>,+ hpc_handle: Arc<StdMutex<Option<HPCON>>>,job: Arc<JobObject>,- process: HANDLE,+ process: NonOwningProcessHandle,log_dir: Option<PathBuf>,) -> std::thread::JoinHandle<()> {+ // SAFETY: The spawn path transfers the pipe's write end to this input loop.+ let stdin_handle = stdin_handle.map(|handle| unsafe { OwnedHandle::from_raw_handle(handle) });std::thread::spawn(move || {let mut stdin_handle = stdin_handle;loop {let msg = match read_frame(&mut reader) {Ok(Some(v)) => v,Ok(None) | Err(_) => {- terminate_job_or_process(&job, process, log_dir.as_deref());+ terminate_job_or_process(&job, &process, log_dir.as_deref());break;}};@@ -444,7 +464,7 @@ fn spawn_input_loop(let Ok(bytes) = decode_bytes(&payload.data_b64) else {continue;};- if let Some(handle) = stdin_handle {+ if let Some(handle) = &stdin_handle {let mut offset = 0usize;// `WriteFile` can report success after consuming only part of the buffer// when the target is a pipe. Treat this like a normal partial write and@@ -460,7 +480,7 @@ fn spawn_input_loop(let mut written = 0u32;let ok = unsafe {windows_sys::Win32::Storage::FileSystem::WriteFile(- handle,+ handle.as_raw_handle(),chunk.as_ptr(),chunk_len as u32,&mut written,@@ -475,9 +495,6 @@ fn spawn_input_loop(),log_dir.as_deref(),);- unsafe {- CloseHandle(handle);- }stdin_handle = None;break;}@@ -486,9 +503,6 @@ fn spawn_input_loop("runner stdin write made no progress; closing child stdin",log_dir.as_deref(),);- unsafe {- CloseHandle(handle);- }stdin_handle = None;break;}@@ -497,11 +511,7 @@ fn spawn_input_loop(}}Message::CloseStdin { .. } => {- if let Some(handle) = stdin_handle.take() {- unsafe {- CloseHandle(handle);- }- }+ drop(stdin_handle.take());}Message::Resize {payload: ResizePayload { rows, cols },@@ -521,7 +531,7 @@ fn spawn_input_loop(}}Message::Terminate { .. } => {- terminate_job_or_process(&job, process, log_dir.as_deref());+ terminate_job_or_process(&job, &process, log_dir.as_deref());}Message::SpawnRequest { .. } => {}Message::SpawnReady { .. } => {}@@ -530,11 +540,6 @@ fn spawn_input_loop(Message::Error { .. } => {}}}- if let Some(handle) = stdin_handle {- unsafe {- CloseHandle(handle);- }- }})}@@ -645,7 +650,7 @@ pub fn main() -> Result<()> {stdin_handle,Arc::clone(&hpc_handle),Arc::clone(&job),- pi.hProcess,+ NonOwningProcessHandle(pi.hProcess),log_dir_owned,);@@ -653,7 +658,7 @@ pub fn main() -> Result<()> {let wait_res = unsafe { WaitForSingleObject(pi.hProcess, timeout) };let timed_out = wait_res == WAIT_TIMEOUT;let child_stopped = if timed_out {- terminate_job_or_process(&job, pi.hProcess, log_dir);+ terminate_job_or_process(&job, &NonOwningProcessHandle(pi.hProcess), log_dir);let termination_wait = unsafe { WaitForSingleObject(pi.hProcess, TERMINATION_WAIT_MS) };if termination_wait == WAIT_TIMEOUT {log_note(@@ -683,10 +688,10 @@ pub fn main() -> Result<()> {GetExitCodeProcess(pi.hProcess, &mut raw_exit);exit_code = raw_exit as i32;}- if pi.hThread != 0 {+ if !pi.hThread.is_null() {CloseHandle(pi.hThread);}- if pi.hProcess != 0 {+ if !pi.hProcess.is_null() {CloseHandle(pi.hProcess);}}diff --git a/codex-rs/windows-sandbox-rs/src/bin/command_runner/win/input_loop_tests.rs b/codex-rs/windows-sandbox-rs/src/bin/command_runner/win/input_loop_tests.rsindex 13b94fa3eb..23344b2cee 100644--- a/codex-rs/windows-sandbox-rs/src/bin/command_runner/win/input_loop_tests.rs+++ b/codex-rs/windows-sandbox-rs/src/bin/command_runner/win/input_loop_tests.rs@@ -16,6 +16,7 @@ use windows_sys::Win32::System::Threading::OpenProcess;use windows_sys::Win32::System::Threading::PROCESS_SYNCHRONIZE;use windows_sys::Win32::System::Threading::WaitForSingleObject;+use super::NonOwningProcessHandle;use super::spawn_input_loop;#[tokio::test]@@ -50,16 +51,16 @@ async fn disconnected_control_pipe_terminates_elevated_helper_and_descendants()descendant_pid,)};- anyhow::ensure!(descendant != 0, "failed to open sandbox descendant");+ anyhow::ensure!(!descendant.is_null(), "failed to open sandbox descendant");let descendant = unsafe { OwnedHandle::from_raw_handle(descendant as _) };- let process = helper.raw_handle().context("helper process handle")? as _;+ let process = helper.raw_handle().context("helper process handle")?;let input_loop = spawn_input_loop(tempfile::tempfile()?,/*stdin_handle*/ None,Arc::new(Mutex::new(None)),Arc::clone(&job),- process,+ NonOwningProcessHandle(process),/*log_dir*/ None,);input_loopdiff --git a/codex-rs/windows-sandbox-rs/src/conpty/mod.rs b/codex-rs/windows-sandbox-rs/src/conpty/mod.rsindex 352105a040..86839955e8 100644--- a/codex-rs/windows-sandbox-rs/src/conpty/mod.rs+++ b/codex-rs/windows-sandbox-rs/src/conpty/mod.rs@@ -19,13 +19,16 @@ use codex_utils_pty::RawConPty;use std::collections::HashMap;use std::ffi::c_void;use std::os::windows::io::AsRawHandle;+use std::os::windows::io::BorrowedHandle;+use std::os::windows::io::FromRawHandle;use std::os::windows::io::IntoRawHandle;+use std::os::windows::io::OwnedHandle;use std::path::Path;use std::sync::Arc;-use windows_sys::Win32::Foundation::CloseHandle;use windows_sys::Win32::Foundation::GetLastError;use windows_sys::Win32::Foundation::HANDLE;use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;+use windows_sys::Win32::System::Console::HPCON;use windows_sys::Win32::System::Threading::CREATE_UNICODE_ENVIRONMENT;use windows_sys::Win32::System::Threading::CreateProcessAsUserW;use windows_sys::Win32::System::Threading::EXTENDED_STARTUPINFO_PRESENT;@@ -38,39 +41,37 @@ use crate::process::make_env_block;/// Owns a ConPTY handle and its backing pipe handles.pub struct ConptyInstance {pseudoconsole: Option<PsuedoCon>,- input_write: HANDLE,- output_read: HANDLE,+ input_write: Option<OwnedHandle>,+ output_read: Option<OwnedHandle>,job: Option<Arc<JobObject>>,_desktop: Option<LaunchDesktop>,}impl Drop for ConptyInstance {fn drop(&mut self) {- unsafe {- if self.input_write != 0 && self.input_write != INVALID_HANDLE_VALUE {- CloseHandle(self.input_write);- }- if self.output_read != 0 && self.output_read != INVALID_HANDLE_VALUE {- CloseHandle(self.output_read);- }- }- let _ = self.pseudoconsole.take();+ drop(self.input_write.take());+ drop(self.output_read.take());+ drop(self.pseudoconsole.take());}}impl ConptyInstance {- pub fn raw_handle(&self) -> Option<HANDLE> {+ pub fn raw_handle(&self) -> Option<HPCON> {self.pseudoconsole.as_ref()- .map(|pseudoconsole| pseudoconsole.raw_handle() as HANDLE)+ .map(|pseudoconsole| pseudoconsole.raw_handle() as HPCON)}pub fn take_input_write(&mut self) -> HANDLE {- std::mem::replace(&mut self.input_write, 0)+ self.input_write+ .take()+ .map_or(std::ptr::null_mut(), IntoRawHandle::into_raw_handle)}pub fn take_output_read(&mut self) -> HANDLE {- std::mem::replace(&mut self.output_read, 0)+ self.output_read+ .take()+ .map_or(std::ptr::null_mut(), IntoRawHandle::into_raw_handle)}/// Returns the Job Object containing the spawned process, if this instance owns one.@@ -87,11 +88,14 @@ impl ConptyInstance {pub fn create_conpty(cols: i16, rows: i16) -> Result<ConptyInstance> {let raw = RawConPty::new(cols, rows)?;let (pseudoconsole, input_write, output_read) = raw.into_handles();+ // SAFETY: into_raw_handle transfers each pipe to its new owner.+ let input_write = unsafe { OwnedHandle::from_raw_handle(input_write.into_raw_handle()) };+ let output_read = unsafe { OwnedHandle::from_raw_handle(output_read.into_raw_handle()) };Ok(ConptyInstance {pseudoconsole: Some(pseudoconsole),- input_write: input_write.into_raw_handle() as HANDLE,- output_read: output_read.into_raw_handle() as HANDLE,+ input_write: Some(input_write),+ output_read: Some(output_read),job: None,_desktop: None,})@@ -102,7 +106,7 @@ pub fn create_conpty(cols: i16, rows: i16) -> Result<ConptyInstance> {/// This is the main shared ConPTY entry point and is used by both the legacy/direct path/// and the elevated runner path whenever a PTY-backed sandboxed process is needed.pub fn spawn_conpty_process_as_user(- h_token: HANDLE,+ h_token: BorrowedHandle<'_>,argv: &[String],cwd: &Path,env_map: &HashMap<String, String>,@@ -126,11 +130,14 @@ pub fn spawn_conpty_process_as_user(let raw = RawConPty::new(/*cols*/ 80, /*rows*/ 24)?;let (pseudoconsole, input_write, output_read) = raw.into_handles();- let hpc = pseudoconsole.raw_handle() as HANDLE;+ let hpc = pseudoconsole.raw_handle() as HPCON;+ // SAFETY: into_raw_handle transfers each pipe to its new owner.+ let input_write = unsafe { OwnedHandle::from_raw_handle(input_write.into_raw_handle()) };+ let output_read = unsafe { OwnedHandle::from_raw_handle(output_read.into_raw_handle()) };let conpty = ConptyInstance {pseudoconsole: Some(pseudoconsole),- input_write: input_write.into_raw_handle() as HANDLE,- output_read: output_read.into_raw_handle() as HANDLE,+ input_write: Some(input_write),+ output_read: Some(output_read),job: Some(Arc::clone(&job)),_desktop: Some(desktop),};@@ -146,7 +153,7 @@ pub fn spawn_conpty_process_as_user(let mut pi: PROCESS_INFORMATION = unsafe { std::mem::zeroed() };let ok = unsafe {CreateProcessAsUserW(- h_token,+ h_token.as_raw_handle(),std::ptr::null(),cmdline.as_mut_ptr(),std::ptr::null_mut(),diff --git a/codex-rs/windows-sandbox-rs/src/desktop.rs b/codex-rs/windows-sandbox-rs/src/desktop.rsindex cfd50fa06a..815d135b22 100644--- a/codex-rs/windows-sandbox-rs/src/desktop.rs+++ b/codex-rs/windows-sandbox-rs/src/desktop.rs@@ -61,6 +61,7 @@ use windows_sys::Win32::System::StationsAndDesktops::DESKTOP_SWITCHDESKTOP;use windows_sys::Win32::System::StationsAndDesktops::DESKTOP_WRITE_DAC;use windows_sys::Win32::System::StationsAndDesktops::DESKTOP_WRITE_OWNER;use windows_sys::Win32::System::StationsAndDesktops::DESKTOP_WRITEOBJECTS;+use windows_sys::Win32::System::StationsAndDesktops::HDESK;use windows_sys::Win32::System::StationsAndDesktops::OpenDesktopW;const PRIVATE_DESKTOP_PREFIX: &str = "CodexSandboxDesktop-";@@ -242,7 +243,7 @@ impl LaunchDesktop {DESKTOP_PARTICIPANT_ACCESS,)};- if handle == 0 {+ if handle.is_null() {anyhow::bail!("OpenDesktopW failed: {}", unsafe { GetLastError() });}Ok(Self {@@ -327,7 +328,7 @@ pub(crate) fn shared_private_desktop_for_user(unsafe {LocalFree(security_descriptor as HLOCAL);}- if handle == 0 {+ if handle.is_null() {logging::debug_log(&format!("CreateDesktopW failed for shared private desktop: {error}"),logs_base_dir,@@ -348,10 +349,15 @@ pub(crate) fn shared_private_desktop_for_user(}struct PrivateDesktop {- handle: isize,+ handle: HDESK,name: String,}+// SAFETY: HDESK is an opaque Windows handle, and this owner only uses it through+// Windows APIs. After setup, its only handle operation is CloseDesktop, which+// reports failure if a thread in the calling process is using the handle.+unsafe impl Send for PrivateDesktop {}+impl PrivateDesktop {fn create(logs_base_dir: Option<&Path>) -> Result<Self> {let mut rng = SmallRng::from_entropy();@@ -367,7 +373,7 @@ impl PrivateDesktop {ptr::null_mut(),)};- if handle == 0 {+ if handle.is_null() {let err = unsafe { GetLastError() } as i32;logging::debug_log(&format!(@@ -391,7 +397,7 @@ impl PrivateDesktop {}}-unsafe fn grant_desktop_access(handle: isize, logs_base_dir: Option<&Path>) -> Result<()> {+unsafe fn grant_desktop_access(handle: HDESK, logs_base_dir: Option<&Path>) -> Result<()> {let token = get_current_token_for_restriction()?;let mut logon_sid = get_logon_sid_bytes(token)?;CloseHandle(token);@@ -454,7 +460,7 @@ unsafe fn grant_desktop_access(handle: isize, logs_base_dir: Option<&Path>) -> Rimpl Drop for PrivateDesktop {fn drop(&mut self) {unsafe {- if self.handle != 0 {+ if !self.handle.is_null() {let _ = CloseDesktop(self.handle);}}diff --git a/codex-rs/windows-sandbox-rs/src/desktop_tests.rs b/codex-rs/windows-sandbox-rs/src/desktop_tests.rsindex abe6f8077c..00d516058f 100644--- a/codex-rs/windows-sandbox-rs/src/desktop_tests.rs+++ b/codex-rs/windows-sandbox-rs/src/desktop_tests.rs@@ -222,7 +222,7 @@ fn current_account_name() -> Result<String> {// Bazel does not provide USERDOMAIN or USERNAME in the test environment.let mut account = [0; (DNLEN + UNLEN + 2) as usize];let mut length = account.len() as u32;- if unsafe { GetUserNameExW(NameSamCompatible, account.as_mut_ptr(), &mut length) } == 0 {+ if !unsafe { GetUserNameExW(NameSamCompatible, account.as_mut_ptr(), &mut length) } {return Err(std::io::Error::last_os_error().into());}Ok(String::from_utf16(&account[..length as usize])?)diff --git a/codex-rs/windows-sandbox-rs/src/elevated/runner_client.rs b/codex-rs/windows-sandbox-rs/src/elevated/runner_client.rsindex 28100b20e3..3049a8c4cb 100644--- a/codex-rs/windows-sandbox-rs/src/elevated/runner_client.rs+++ b/codex-rs/windows-sandbox-rs/src/elevated/runner_client.rs@@ -58,6 +58,18 @@ const RUNNER_PIPE_CONNECT_TIMEOUT: Duration = Duration::from_secs(15);const RUNNER_ERROR_MODE_FLAGS: u32 = 0x0001 | 0x0002;const WAIT_OBJECT_0: u32 = 0;+struct NonOwningHandle(HANDLE);++// SAFETY: Pipe and thread handles are opaque process-wide tokens that may be+// passed between threads. This wrapper does not own or extend their lifetime.+unsafe impl Send for NonOwningHandle {}++impl NonOwningHandle {+ fn raw(&self) -> HANDLE {+ self.0+ }+}+#[derive(Debug)]pub(crate) struct RunnerLogonError {pub(crate) code: u32,@@ -227,12 +239,13 @@ fn connect_pipe_with_timeout(let pipe_label_for_thread = pipe_label.clone();let (thread_handle_tx, thread_handle_rx) = mpsc::sync_channel(1);let (connect_result_tx, connect_result_rx) = mpsc::sync_channel(1);+ let h_pipe = NonOwningHandle(h_pipe);let mut connect_thread = Some(thread::Builder::new().name(format!("codex-runner-connect-{pipe_label}")).spawn(move || {let current_process = unsafe { GetCurrentProcess() };- let mut thread_handle = 0;+ let mut thread_handle = std::ptr::null_mut();let duplicate_ok = unsafe {DuplicateHandle(current_process,@@ -254,9 +267,9 @@ fn connect_pipe_with_timeout(// Publish the helper thread HANDLE before the blocking pipe connect so the// parent can cancel this specific operation if it times out.- let _ = thread_handle_tx.send(Ok(thread_handle));+ let _ = thread_handle_tx.send(Ok(NonOwningHandle(thread_handle)));- let result = connect_pipe(h_pipe, expected_runner_pid)+ let result = connect_pipe(h_pipe.raw(), expected_runner_pid).map_err(anyhow::Error::from).context(format!("connect {pipe_label_for_thread}"));let _ = connect_result_tx.send(result);@@ -277,12 +290,12 @@ fn connect_pipe_with_timeout(if let Some(result) = try_take_completed_connect_result(&mut connect_thread,&connect_result_rx,- thread_handle,+ thread_handle.raw(),&pipe_label,)? {result} else {- let cancel_ok = unsafe { CancelSynchronousIo(thread_handle) };+ let cancel_ok = unsafe { CancelSynchronousIo(thread_handle.raw()) };if cancel_ok == 0 {let err = unsafe { GetLastError() };if err != ERROR_NOT_FOUND {@@ -292,7 +305,7 @@ fn connect_pipe_with_timeout(} else if let Some(result) = try_take_completed_connect_result(&mut connect_thread,&connect_result_rx,- thread_handle,+ thread_handle.raw(),&pipe_label,)? {result@@ -324,7 +337,7 @@ fn connect_pipe_with_timeout(};unsafe {- CloseHandle(thread_handle);+ CloseHandle(thread_handle.raw());}resultdiff --git a/codex-rs/windows-sandbox-rs/src/elevated/runner_pipe.rs b/codex-rs/windows-sandbox-rs/src/elevated/runner_pipe.rsindex 463005ce77..b7cd5b2416 100644--- a/codex-rs/windows-sandbox-rs/src/elevated/runner_pipe.rs+++ b/codex-rs/windows-sandbox-rs/src/elevated/runner_pipe.rs@@ -92,7 +92,7 @@ pub fn create_named_pipe(name: &str, access: u32, sandbox_username: &str) -> io:unsafe {LocalFree(sd as HLOCAL);}- if h == 0 || h == windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE {+ if h.is_null() || h == windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE {return Err(io::Error::from_raw_os_error(unsafe {GetLastError() as i32}));diff --git a/codex-rs/windows-sandbox-rs/src/file_write.rs b/codex-rs/windows-sandbox-rs/src/file_write.rsindex e8a2932bcf..e0c5b3cb09 100644--- a/codex-rs/windows-sandbox-rs/src/file_write.rs+++ b/codex-rs/windows-sandbox-rs/src/file_write.rs@@ -77,7 +77,7 @@ pub fn write_file_atomically(path: &Path, contents: &[u8]) -> Result<()> {Information: 0,};unsafe {- (*info).Anonymous.ReplaceIfExists = 1;+ (*info).Anonymous.ReplaceIfExists = true;(*info).RootDirectory = directory.as_raw_handle() as HANDLE;(*info).FileNameLength = u32::try_from(size_of_val(name.as_slice()))?;let filename = buffer@@ -106,7 +106,7 @@ pub fn write_file_atomically(path: &Path, contents: &[u8]) -> Result<()> {if result.is_err() {// Clean up only the file we created, not a pathname the caller could// have replaced. Preserve the original write/rename error.- let disposition = FILE_DISPOSITION_INFO { DeleteFile: 1 };+ let disposition = FILE_DISPOSITION_INFO { DeleteFile: true };unsafe {SetFileInformationByHandle(file.as_raw_handle() as HANDLE,diff --git a/codex-rs/windows-sandbox-rs/src/hide_users.rs b/codex-rs/windows-sandbox-rs/src/hide_users.rsindex c036a2c4d5..1e4548354d 100644--- a/codex-rs/windows-sandbox-rs/src/hide_users.rs+++ b/codex-rs/windows-sandbox-rs/src/hide_users.rs@@ -42,7 +42,7 @@ pub fn hide_newly_created_users(usernames: &[String], log_base: &Path) {}pub(crate) fn unhide_sandbox_users(usernames: &[&str]) -> anyhow::Result<()> {- let mut key: HKEY = 0;+ let mut key: HKEY = std::ptr::null_mut();match unsafe {RegOpenKeyExW(HKEY_LOCAL_MACHINE,@@ -146,7 +146,7 @@ fn hide_users_in_winlogon(usernames: &[String], log_base: &Path) -> anyhow::Resufn create_userlist_key() -> anyhow::Result<HKEY> {let key_path = to_wide(USERLIST_KEY_PATH);- let mut key: HKEY = 0;+ let mut key: HKEY = std::ptr::null_mut();let status = unsafe {RegCreateKeyExW(HKEY_LOCAL_MACHINE,diff --git a/codex-rs/windows-sandbox-rs/src/identity.rs b/codex-rs/windows-sandbox-rs/src/identity.rsindex 1472249759..022c9f8ee5 100644--- a/codex-rs/windows-sandbox-rs/src/identity.rs+++ b/codex-rs/windows-sandbox-rs/src/identity.rs@@ -210,7 +210,7 @@ pub fn logon_existing_sandbox_account("sandbox account record does not match the managed account");let password = crate::to_wide(decode_password(&record)?);- let mut token = 0;+ let mut token = std::ptr::null_mut();if unsafe {LogonUserW(crate::to_wide(account.username()).as_ptr(),diff --git a/codex-rs/windows-sandbox-rs/src/lib.rs b/codex-rs/windows-sandbox-rs/src/lib.rsindex 26c40ec680..7008cd188b 100644--- a/codex-rs/windows-sandbox-rs/src/lib.rs+++ b/codex-rs/windows-sandbox-rs/src/lib.rs@@ -573,6 +573,18 @@ mod windows_impl {type PipeHandles = ((HANDLE, HANDLE), (HANDLE, HANDLE), (HANDLE, HANDLE));+ struct NonOwningPipeHandle(HANDLE);++ // SAFETY: Pipe handles are opaque process-wide tokens that may be used from+ // any thread. This wrapper does not own the handle or extend its lifetime.+ unsafe impl Send for NonOwningPipeHandle {}++ impl NonOwningPipeHandle {+ fn raw(&self) -> HANDLE {+ self.0+ }+ }+enum WaitOutcome {Exited,TimedOut,@@ -618,12 +630,12 @@ mod windows_impl {}unsafe fn setup_stdio_pipes() -> io::Result<PipeHandles> {- let mut in_r: HANDLE = 0;- let mut in_w: HANDLE = 0;- let mut out_r: HANDLE = 0;- let mut out_w: HANDLE = 0;- let mut err_r: HANDLE = 0;- let mut err_w: HANDLE = 0;+ let mut in_r: HANDLE = std::ptr::null_mut();+ let mut in_w: HANDLE = std::ptr::null_mut();+ let mut out_r: HANDLE = std::ptr::null_mut();+ let mut out_w: HANDLE = std::ptr::null_mut();+ let mut err_r: HANDLE = std::ptr::null_mut();+ let mut err_w: HANDLE = std::ptr::null_mut();if CreatePipe(&mut in_r, &mut in_w, ptr::null_mut(), 0) == 0 {return Err(io::Error::from_raw_os_error(GetLastError() as i32));}@@ -797,6 +809,8 @@ mod windows_impl {let (tx_out, rx_out) = std::sync::mpsc::channel::<Vec<u8>>();let (tx_err, rx_err) = std::sync::mpsc::channel::<Vec<u8>>();+ let out_r = NonOwningPipeHandle(out_r);+ let err_r = NonOwningPipeHandle(err_r);let t_out = std::thread::spawn(move || {let mut buf = Vec::new();let mut tmp = [0u8; 8192];@@ -804,7 +818,7 @@ mod windows_impl {let mut read_bytes: u32 = 0;let ok = unsafe {windows_sys::Win32::Storage::FileSystem::ReadFile(- out_r,+ out_r.raw(),tmp.as_mut_ptr(),tmp.len() as u32,&mut read_bytes,@@ -825,7 +839,7 @@ mod windows_impl {let mut read_bytes: u32 = 0;let ok = unsafe {windows_sys::Win32::Storage::FileSystem::ReadFile(- err_r,+ err_r.raw(),tmp.as_mut_ptr(),tmp.len() as u32,&mut read_bytes,@@ -875,10 +889,10 @@ mod windows_impl {}unsafe {- if pi.hThread != 0 {+ if !pi.hThread.is_null() {CloseHandle(pi.hThread);}- if pi.hProcess != 0 {+ if !pi.hProcess.is_null() {CloseHandle(pi.hProcess);}CloseHandle(security.h_token);diff --git a/codex-rs/windows-sandbox-rs/src/no_reparse_dir.rs b/codex-rs/windows-sandbox-rs/src/no_reparse_dir.rsindex cb14621f6b..0abb616fac 100644--- a/codex-rs/windows-sandbox-rs/src/no_reparse_dir.rs+++ b/codex-rs/windows-sandbox-rs/src/no_reparse_dir.rs@@ -23,6 +23,8 @@ use std::ptr;use windows_sys::Win32::Foundation::HANDLE;use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;use windows_sys::Win32::Foundation::NTSTATUS;+use windows_sys::Win32::Foundation::OBJ_CASE_INSENSITIVE;+use windows_sys::Win32::Foundation::OBJ_DONT_REPARSE;use windows_sys::Win32::Foundation::RtlNtStatusToDosError;use windows_sys::Win32::Foundation::UNICODE_STRING;use windows_sys::Win32::Storage::FileSystem::DELETE;@@ -33,8 +35,6 @@ use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_WRITE;use windows_sys::Win32::Storage::FileSystem::QueryDosDeviceW;use windows_sys::Win32::System::IO::IO_STATUS_BLOCK;use windows_sys::Win32::System::IO::IO_STATUS_BLOCK_0;-use windows_sys::Win32::System::Kernel::OBJ_CASE_INSENSITIVE;-use windows_sys::Win32::System::Kernel::OBJ_DONT_REPARSE;const FILE_OPEN: u32 = 1;const FILE_CREATE: u32 = 2;@@ -123,7 +123,7 @@ pub fn open_directory_no_reparse() -> Result<OwnedHandle> {let mut nt_path = local_directory_nt_path(path)?;open_no_reparse(- /*root_directory*/ 0,+ ptr::null_mut(),&mut nt_path,desired_access,share_access,@@ -241,7 +241,7 @@ pub(crate) fn open_no_reparse(length: size_of::<ObjectAttributes>() as u32,root_directory,object_name: &object_name,- attributes: OBJ_CASE_INSENSITIVE as u32 | OBJ_DONT_REPARSE as u32,+ attributes: OBJ_CASE_INSENSITIVE | OBJ_DONT_REPARSE,security_descriptor: ptr::null(),security_quality_of_service: ptr::null(),};@@ -249,7 +249,7 @@ pub(crate) fn open_no_reparse(Anonymous: IO_STATUS_BLOCK_0 { Status: 0 },Information: 0,};- let mut handle = 0;+ let mut handle = std::ptr::null_mut();let status = unsafe {NtCreateFile(&mut handle,@@ -273,10 +273,10 @@ pub(crate) fn open_no_reparse(return Err(std::io::Error::from_raw_os_error(error as i32)).context("NtCreateFile");}ensure!(- handle != 0 && handle != INVALID_HANDLE_VALUE,+ !handle.is_null() && handle != INVALID_HANDLE_VALUE,"NtCreateFile returned an invalid handle");- Ok(unsafe { OwnedHandle::from_raw_handle(handle as *mut c_void) })+ Ok(unsafe { OwnedHandle::from_raw_handle(handle) })}#[cfg(test)]diff --git a/codex-rs/windows-sandbox-rs/src/proc_thread_attr.rs b/codex-rs/windows-sandbox-rs/src/proc_thread_attr.rsindex 12c9b3c864..aa0850aa36 100644--- a/codex-rs/windows-sandbox-rs/src/proc_thread_attr.rs+++ b/codex-rs/windows-sandbox-rs/src/proc_thread_attr.rs@@ -2,6 +2,7 @@ use std::ffi::c_void;use std::io;use windows_sys::Win32::Foundation::GetLastError;use windows_sys::Win32::Foundation::HANDLE;+use windows_sys::Win32::System::Console::HPCON;use windows_sys::Win32::System::Threading::DeleteProcThreadAttributeList;use windows_sys::Win32::System::Threading::InitializeProcThreadAttributeList;use windows_sys::Win32::System::Threading::LPPROC_THREAD_ATTRIBUTE_LIST;@@ -52,13 +53,13 @@ impl ProcThreadAttributeList {self.buffer.as_mut_ptr() as LPPROC_THREAD_ATTRIBUTE_LIST}- pub fn set_pseudoconsole(&mut self, hpc: isize) -> io::Result<()> {+ pub fn set_pseudoconsole(&mut self, hpc: HPCON) -> io::Result<()> {// SAFETY: `hpc` is the Windows-defined value and size for this attribute.unsafe {self.update(PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE,hpc as *mut c_void,- std::mem::size_of::<HANDLE>(),+ std::mem::size_of::<HPCON>(),)}}diff --git a/codex-rs/windows-sandbox-rs/src/process.rs b/codex-rs/windows-sandbox-rs/src/process.rsindex 76e664a937..e8049d6beb 100644--- a/codex-rs/windows-sandbox-rs/src/process.rs+++ b/codex-rs/windows-sandbox-rs/src/process.rs@@ -11,6 +11,8 @@ use codex_utils_pty::JobObject;use std::collections::HashMap;use std::ffi::c_void;use std::os::windows::io::AsRawHandle;+use std::os::windows::io::BorrowedHandle;+use std::os::windows::io::OwnedHandle;use std::path::Path;use std::ptr;use std::sync::Arc;@@ -70,7 +72,7 @@ pub fn make_env_block(env: &HashMap<String, String>) -> Vec<u16> {unsafe fn ensure_inheritable_stdio(si: &mut STARTUPINFOW) -> Result<()> {for kind in [STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, STD_ERROR_HANDLE] {let h = GetStdHandle(kind);- if h == 0 || h == INVALID_HANDLE_VALUE {+ if h.is_null() || h == INVALID_HANDLE_VALUE {return Err(anyhow!("GetStdHandle failed: {}", GetLastError()));}if SetHandleInformation(h, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT) == 0 {@@ -225,7 +227,7 @@ impl PipeSpawnHandles {/// Spawns a process with anonymous pipes and returns the relevant handles.#[allow(clippy::too_many_arguments)]pub fn spawn_process_with_pipes(- h_token: HANDLE,+ h_token: BorrowedHandle<'_>,argv: &[String],cwd: &Path,env_map: &HashMap<String, String>,@@ -235,12 +237,12 @@ pub fn spawn_process_with_pipes(desktop: LaunchDesktop,logs_base_dir: Option<&Path>,) -> Result<PipeSpawnHandles> {- let mut in_r: HANDLE = 0;- let mut in_w: HANDLE = 0;- let mut out_r: HANDLE = 0;- let mut out_w: HANDLE = 0;- let mut err_r: HANDLE = 0;- let mut err_w: HANDLE = 0;+ let mut in_r: HANDLE = std::ptr::null_mut();+ let mut in_w: HANDLE = std::ptr::null_mut();+ let mut out_r: HANDLE = std::ptr::null_mut();+ let mut out_w: HANDLE = std::ptr::null_mut();+ let mut err_r: HANDLE = std::ptr::null_mut();+ let mut err_w: HANDLE = std::ptr::null_mut();unsafe {if CreatePipe(&mut in_r, &mut in_w, ptr::null_mut(), 0) == 0 {return Err(anyhow!("CreatePipe stdin failed: {}", GetLastError()));@@ -269,7 +271,7 @@ pub fn spawn_process_with_pipes(let stdio = Some((in_r, out_w, stderr_handle));let spawn_result = unsafe {create_process_as_user(- h_token,+ h_token.as_raw_handle(),argv,cwd,env_map,@@ -329,8 +331,8 @@ pub fn spawn_process_with_pipes(})}-/// Reads a HANDLE until EOF and invokes `on_chunk` for each read.-pub fn read_handle_loop<F>(handle: HANDLE, mut on_chunk: F) -> std::thread::JoinHandle<()>+/// Reads an owned handle until EOF and invokes `on_chunk` for each read.+pub fn read_handle_loop<F>(handle: OwnedHandle, mut on_chunk: F) -> std::thread::JoinHandle<()>whereF: FnMut(&[u8]) + Send + 'static,{@@ -340,7 +342,7 @@ wherelet mut read_bytes: u32 = 0;let ok = unsafe {ReadFile(- handle,+ handle.as_raw_handle(),buf.as_mut_ptr(),buf.len() as u32,&mut read_bytes,@@ -352,8 +354,5 @@ where}on_chunk(&buf[..read_bytes as usize]);}- unsafe {- CloseHandle(handle);- }})}diff --git a/codex-rs/windows-sandbox-rs/src/provisioning_client.rs b/codex-rs/windows-sandbox-rs/src/provisioning_client.rsindex d1daafafee..70b1b73602 100644--- a/codex-rs/windows-sandbox-rs/src/provisioning_client.rs+++ b/codex-rs/windows-sandbox-rs/src/provisioning_client.rs@@ -29,12 +29,12 @@ use windows_sys::Win32::Foundation::ERROR_SEM_TIMEOUT;use windows_sys::Win32::Foundation::ERROR_SERVICE_DOES_NOT_EXIST;use windows_sys::Win32::Foundation::ERROR_SERVICE_MARKED_FOR_DELETE;use windows_sys::Win32::Foundation::HANDLE;-use windows_sys::Win32::Security::SC_HANDLE;use windows_sys::Win32::Storage::FileSystem::SECURITY_IMPERSONATION;use windows_sys::Win32::Storage::FileSystem::SECURITY_SQOS_PRESENT;use windows_sys::Win32::System::Pipes::GetNamedPipeServerProcessId;use windows_sys::Win32::System::Pipes::WaitNamedPipeW;use windows_sys::Win32::System::Services;+use windows_sys::Win32::System::Services::SC_HANDLE;const PROVISIONING_TIMEOUT: Duration = Duration::from_secs(120);const SERVICE_STARTUP_TIMEOUT: Duration = Duration::from_secs(5);@@ -387,7 +387,7 @@ fn verify_server(pipe: HANDLE) -> anyhow::Result<u32> {fn query_service_status() -> anyhow::Result<Services::SERVICE_STATUS_PROCESS> {let manager =unsafe { Services::OpenSCManagerW(ptr::null(), ptr::null(), Services::SC_MANAGER_CONNECT) };- if manager == 0 {+ if manager.is_null() {return Err(io::Error::last_os_error()).context("open service control manager");}let manager = ServiceHandle(manager);@@ -400,7 +400,7 @@ fn query_service_status() -> anyhow::Result<Services::SERVICE_STATUS_PROCESS> {Services::SERVICE_QUERY_STATUS,)};- if service == 0 {+ if service.is_null() {return Err(io::Error::last_os_error()).context("open sandbox provisioning service");}let service = ServiceHandle(service);@@ -426,7 +426,7 @@ struct ServiceHandle(SC_HANDLE);impl Drop for ServiceHandle {fn drop(&mut self) {- if self.0 != 0 {+ if !self.0.is_null() {unsafe { Services::CloseServiceHandle(self.0) };}}diff --git a/codex-rs/windows-sandbox-rs/src/runtime_ownership.rs b/codex-rs/windows-sandbox-rs/src/runtime_ownership.rsindex ace6baaa05..d5ec71b6c0 100644--- a/codex-rs/windows-sandbox-rs/src/runtime_ownership.rs+++ b/codex-rs/windows-sandbox-rs/src/runtime_ownership.rs@@ -149,7 +149,7 @@ pub(crate) fn current_setup_user() -> Result<String> {use std::os::windows::io::OwnedHandle;use windows_sys::Win32::Security as security;use windows_sys::Win32::System::Threading as threading;- let mut token = 0;+ let mut token = std::ptr::null_mut();if unsafe {threading::OpenProcessToken(threading::GetCurrentProcess(),@@ -226,7 +226,7 @@ pub fn save_installation(record: &InstallationRecord) -> Result<()> {}fn flush_installation(path: &str) -> Result<()> {- let mut key = 0;+ let mut key = std::ptr::null_mut();let status = unsafe {registry::RegOpenKeyExW(registry::HKEY_LOCAL_MACHINE,diff --git a/codex-rs/windows-sandbox-rs/src/setup.rs b/codex-rs/windows-sandbox-rs/src/setup.rsindex 618ea85011..6380ae42ee 100644--- a/codex-rs/windows-sandbox-rs/src/setup.rs+++ b/codex-rs/windows-sandbox-rs/src/setup.rs@@ -527,7 +527,11 @@ fn is_elevated() -> Result<bool> {));}let mut is_member = 0i32;- let check = CheckTokenMembership(0, administrators_group, &mut is_member as *mut _);+ let check = CheckTokenMembership(+ std::ptr::null_mut(),+ administrators_group,+ &mut is_member as *mut _,+ );FreeSid(administrators_group as *mut _);if check == 0 {return Err(anyhow!("CheckTokenMembership failed: {}", GetLastError()));@@ -1039,7 +1043,7 @@ fn run_setup_exe_payload(// Hide the window for the elevated helper.sei.nShow = 0; // SW_HIDElet ok = unsafe { ShellExecuteExW(&mut sei) };- if ok == 0 || sei.hProcess == 0 {+ if ok == 0 || sei.hProcess.is_null() {let last_error = unsafe { GetLastError() };let code = if last_error == ERROR_CANCELLED {SetupErrorCode::OrchestratorHelperLaunchCanceleddiff --git a/codex-rs/windows-sandbox-rs/src/setup_launch.rs b/codex-rs/windows-sandbox-rs/src/setup_launch.rsindex a811b6acca..7384c5f675 100644--- a/codex-rs/windows-sandbox-rs/src/setup_launch.rs+++ b/codex-rs/windows-sandbox-rs/src/setup_launch.rs@@ -34,7 +34,7 @@ pub(super) fn spawn_with_retained_handles(.spawn()?;let initialized = (|| {for handle in retained_handles {- let mut child_handle = 0;+ let mut child_handle = std::ptr::null_mut();if unsafe {DuplicateHandle(GetCurrentProcess(),diff --git a/codex-rs/windows-sandbox-rs/src/setup_mutex.rs b/codex-rs/windows-sandbox-rs/src/setup_mutex.rsindex dcb8f6f0c1..9f7f46b4c4 100644--- a/codex-rs/windows-sandbox-rs/src/setup_mutex.rs+++ b/codex-rs/windows-sandbox-rs/src/setup_mutex.rs@@ -64,7 +64,7 @@ pub fn acquire_sandbox_setup_lock(timeout_ms: u32) -> Result<SandboxSetupLock> {let handle = unsafe {CreateMutexW(&attributes, /*binitialowner*/ 0, name.as_ptr())};- let result = if handle == 0 {+ let result = if handle.is_null() {Err(io::Error::last_os_error())} else {Ok(unsafe { OwnedHandle::from_raw_handle(handle as _) })diff --git a/codex-rs/windows-sandbox-rs/src/setup_provisioning/read_acl_mutex.rs b/codex-rs/windows-sandbox-rs/src/setup_provisioning/read_acl_mutex.rsindex 7954826bd4..9a60942fe9 100644--- a/codex-rs/windows-sandbox-rs/src/setup_provisioning/read_acl_mutex.rs+++ b/codex-rs/windows-sandbox-rs/src/setup_provisioning/read_acl_mutex.rs@@ -29,7 +29,7 @@ impl Drop for ReadAclMutexGuard {pub(super) fn read_acl_mutex_exists() -> Result<bool> {let name = to_wide(OsStr::new(READ_ACL_MUTEX_NAME));let handle = unsafe { OpenMutexW(MUTEX_ALL_ACCESS, 0, name.as_ptr()) };- if handle == 0 {+ if handle.is_null() {let err = unsafe { GetLastError() };if err == ERROR_FILE_NOT_FOUND {return Ok(false);@@ -45,7 +45,7 @@ pub(super) fn read_acl_mutex_exists() -> Result<bool> {pub(super) fn acquire_read_acl_mutex() -> Result<Option<ReadAclMutexGuard>> {let name = to_wide(OsStr::new(READ_ACL_MUTEX_NAME));let handle = unsafe { CreateMutexW(std::ptr::null_mut(), 1, name.as_ptr()) };- if handle == 0 {+ if handle.is_null() {return Err(anyhow::anyhow!("CreateMutexW failed: {}", unsafe {GetLastError()}));diff --git a/codex-rs/windows-sandbox-rs/src/setup_provisioning/sandbox_users.rs b/codex-rs/windows-sandbox-rs/src/setup_provisioning/sandbox_users.rsindex b36879b64a..480bbf7c39 100644--- a/codex-rs/windows-sandbox-rs/src/setup_provisioning/sandbox_users.rs+++ b/codex-rs/windows-sandbox-rs/src/setup_provisioning/sandbox_users.rs@@ -449,7 +449,7 @@ pub(super) fn prepare_setup_marker(&security_attributes,CREATE_NEW,FILE_ATTRIBUTE_NORMAL,- /*htemplatefile*/ 0,+ std::ptr::null_mut(),)};let create_error = unsafe { GetLastError() };@@ -466,7 +466,7 @@ pub(super) fn prepare_setup_marker(),)));}- let file = unsafe { File::from_raw_handle(marker_handle as *mut c_void) };+ let file = unsafe { File::from_raw_handle(marker_handle) };match mode {SetupMode::ProvisionOnly => Ok(PreparedSetupMarker::Retained(file)),SetupMode::Full | SetupMode::InteractiveProvision | SetupMode::ReadAclsOnly => {diff --git a/codex-rs/windows-sandbox-rs/src/setup_provisioning/setup_runtime_bin_tests.rs b/codex-rs/windows-sandbox-rs/src/setup_provisioning/setup_runtime_bin_tests.rsindex 5a6c1fcc27..010d75abc9 100644--- a/codex-rs/windows-sandbox-rs/src/setup_provisioning/setup_runtime_bin_tests.rs+++ b/codex-rs/windows-sandbox-rs/src/setup_provisioning/setup_runtime_bin_tests.rs@@ -31,7 +31,7 @@ fn runtime_repair_preserves_other_trustees_inherited_file_denial() {let mut member = 0;assert_ne!(unsafe {- CheckTokenMembership(/*tokenhandle*/ 0, granted_sid.as_ptr(), &mut member)+ CheckTokenMembership(std::ptr::null_mut(), granted_sid.as_ptr(), &mut member)},0,);diff --git a/codex-rs/windows-sandbox-rs/src/setup_refresh_tests.rs b/codex-rs/windows-sandbox-rs/src/setup_refresh_tests.rsindex 51cd8cb39a..accb381891 100644--- a/codex-rs/windows-sandbox-rs/src/setup_refresh_tests.rs+++ b/codex-rs/windows-sandbox-rs/src/setup_refresh_tests.rs@@ -19,7 +19,7 @@ const HOME_ENV: &str = "CODEX_TEST_REFRESH_CONSOLE_HOME";#[test]fn refresh_helper_has_no_console() -> Result<()> {if let Some(home) = std::env::var_os(HOME_ENV).map(PathBuf::from) {- assert_eq!(unsafe { GetConsoleWindow() }, 0);+ assert!(unsafe { GetConsoleWindow() }.is_null());run_setup_refresh_payload(HELPER_TEST, &home)?;assert_eq!(fs::read(home.join("probe"))?, b"no console");return Ok(());@@ -58,7 +58,7 @@ fn refresh_console_probe() -> Result<()> {return Ok(());}let home = PathBuf::from(std::env::var_os(HOME_ENV).expect("detached probe home"));- assert_eq!(unsafe { GetConsoleWindow() }, 0);+ assert!(unsafe { GetConsoleWindow() }.is_null());fs::write(home.join("probe"), b"no console")?;Ok(())}diff --git a/codex-rs/windows-sandbox-rs/src/token.rs b/codex-rs/windows-sandbox-rs/src/token.rsindex 4f8e437af8..f09dabd6f1 100644--- a/codex-rs/windows-sandbox-rs/src/token.rs+++ b/codex-rs/windows-sandbox-rs/src/token.rs@@ -180,7 +180,7 @@ pub unsafe fn get_current_token_for_restriction() -> Result<HANDLE> {| TOKEN_ADJUST_DEFAULT| TOKEN_ADJUST_SESSIONID| TOKEN_ADJUST_PRIVILEGES;- let mut h: HANDLE = 0;+ let mut h: HANDLE = std::ptr::null_mut();#[link(name = "advapi32")]unsafe extern "system" {fn OpenProcessToken(@@ -321,7 +321,7 @@ pub unsafe fn get_logon_sid_bytes(h_token: HANDLE) -> Result<Vec<u8>> {if ok != 0 {let lt: TOKEN_LINKED_TOKEN =std::ptr::read_unaligned(ln_buf.as_ptr() as *const TOKEN_LINKED_TOKEN);- if lt.linked_token != 0 {+ if !lt.linked_token.is_null() {let res = scan_token_groups_for_logon(lt.linked_token);CloseHandle(lt.linked_token);if let Some(v) = res {@@ -496,7 +496,7 @@ unsafe fn create_token_with_caps_from(entries[logon_idx + 1].Sid = psid_everyone;entries[logon_idx + 1].Attributes = 0;- let mut new_token: HANDLE = 0;+ let mut new_token: HANDLE = std::ptr::null_mut();let flags = DISABLE_MAX_PRIVILEGE | LUA_TOKEN | WRITE_RESTRICTED;let ok = CreateRestrictedToken(base_token,diff --git a/codex-rs/windows-sandbox-rs/src/token_groups_tests.rs b/codex-rs/windows-sandbox-rs/src/token_groups_tests.rsindex 7a002c0eb9..d14b835082 100644--- a/codex-rs/windows-sandbox-rs/src/token_groups_tests.rs+++ b/codex-rs/windows-sandbox-rs/src/token_groups_tests.rs@@ -97,7 +97,7 @@ fn rejects_malformed_and_out_of_buffer_sids() {#[test]fn queries_current_token_with_a_caller_size_limit() -> Result<()> {- let mut raw = 0;+ let mut raw = std::ptr::null_mut();ensure!(unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut raw) } != 0);let _token = unsafe { OwnedHandle::from_raw_handle(raw as _) };assert!(diff --git a/codex-rs/windows-sandbox-rs/src/token_tests.rs b/codex-rs/windows-sandbox-rs/src/token_tests.rsindex cb54b15c6c..c1856dae1e 100644--- a/codex-rs/windows-sandbox-rs/src/token_tests.rs+++ b/codex-rs/windows-sandbox-rs/src/token_tests.rs@@ -166,7 +166,7 @@ fn default_objects_deny_other_logons_even_with_the_same_owner() -> Result<()> {Sid: sid,Attributes: 0,});- let mut other = 0;+ let mut other = std::ptr::null_mut();ensure!(CreateRestrictedToken(base_raw,@@ -184,7 +184,7 @@ fn default_objects_deny_other_logons_even_with_the_same_owner() -> Result<()> {);let other = OwnedHandle::from_raw_handle(other as _);for (token, same_logon) in [(&victim, true), (&other, false)] {- let mut impersonation = 0;+ let mut impersonation = std::ptr::null_mut();ensure!(DuplicateToken(token.as_raw_handle() as _,diff --git a/codex-rs/windows-sandbox-rs/src/token_user_tests.rs b/codex-rs/windows-sandbox-rs/src/token_user_tests.rsindex 15a7c1e58a..b2614ce099 100644--- a/codex-rs/windows-sandbox-rs/src/token_user_tests.rs+++ b/codex-rs/windows-sandbox-rs/src/token_user_tests.rs@@ -68,11 +68,11 @@ fn rejects_truncated_user_and_malformed_sid() -> Result<()> {#[test]fn queries_current_user_and_rejects_invalid_token() -> Result<()> {- let mut raw = 0;+ let mut raw = std::ptr::null_mut();ensure!(unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut raw) } != 0);let _token = unsafe { OwnedHandle::from_raw_handle(raw as _) };let user = unsafe { get_user_sid_bytes(raw) }?;assert!(unsafe { IsValidSid(user.as_ptr() as _) } != 0);- assert!(unsafe { get_user_sid_bytes(0) }.is_err());+ assert!(unsafe { get_user_sid_bytes(std::ptr::null_mut()) }.is_err());Ok(())}diff --git a/codex-rs/windows-sandbox-rs/src/unified_exec/backends/legacy.rs b/codex-rs/windows-sandbox-rs/src/unified_exec/backends/legacy.rsindex f6726d7275..d2bfe7941f 100644--- a/codex-rs/windows-sandbox-rs/src/unified_exec/backends/legacy.rs+++ b/codex-rs/windows-sandbox-rs/src/unified_exec/backends/legacy.rs@@ -28,6 +28,10 @@ use codex_utils_pty::SpawnedProcess;use codex_utils_pty::TerminalSize;use codex_utils_pty::WindowsTtyInputNormalizer;use std::collections::HashMap;+use std::os::windows::io::AsRawHandle;+use std::os::windows::io::BorrowedHandle;+use std::os::windows::io::FromRawHandle;+use std::os::windows::io::OwnedHandle;use std::path::Path;use std::ptr;use std::sync::Arc;@@ -38,9 +42,9 @@ use tokio::sync::oneshot;use windows_sys::Win32::Foundation::CloseHandle;use windows_sys::Win32::Foundation::GetLastError;use windows_sys::Win32::Foundation::HANDLE;-use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;use windows_sys::Win32::Storage::FileSystem::WriteFile;use windows_sys::Win32::System::Console::COORD;+use windows_sys::Win32::System::Console::HPCON;use windows_sys::Win32::System::Console::ResizePseudoConsole;use windows_sys::Win32::System::Threading::GetExitCodeProcess;use windows_sys::Win32::System::Threading::INFINITE;@@ -50,12 +54,24 @@ use windows_sys::Win32::System::Threading::WaitForSingleObject;const WAIT_TIMEOUT: u32 = 0x0000_0102;+struct NonOwningProcessHandle(HANDLE);++// SAFETY: Process handles are opaque process-wide tokens that may be used from+// any thread. This wrapper does not own the handle or extend its lifetime.+unsafe impl Send for NonOwningProcessHandle {}++impl NonOwningProcessHandle {+ fn raw(&self) -> HANDLE {+ self.0+ }+}+struct LegacyProcessHandles {process: PROCESS_INFORMATION,job: Arc<JobObject>,output_join: std::thread::JoinHandle<()>,writer_handle: tokio::task::JoinHandle<()>,- hpc: Option<HANDLE>,+ hpc: Option<HPCON>,conpty_owner: Option<ConptyInstance>,token_handle: HANDLE,desktop: Option<LaunchDesktop>,@@ -78,6 +94,8 @@ fn spawn_legacy_process(logs_base_dir: Option<&Path>,) -> Result<LegacyProcessHandles> {let h_token = security.h_token;+ // SAFETY: The caller keeps security.h_token open throughout this synchronous spawn.+ let token = unsafe { BorrowedHandle::borrow_raw(h_token) };let launch_desktop = match private_desktop_name {Some(name) => LaunchDesktop::open_private(name)?,None => LaunchDesktop::prepare_legacy(@@ -91,7 +109,7 @@ fn spawn_legacy_process(};let (pi, job, output_join, writer_handle, hpc, conpty_owner, desktop) = if tty {let (pi, mut conpty) =- spawn_conpty_process_as_user(h_token, command, cwd, env_map, launch_desktop)?;+ spawn_conpty_process_as_user(token, command, cwd, env_map, launch_desktop)?;let job = conpty.job().ok_or_else(|| anyhow::anyhow!("spawned ConPTY is missing its process job"))?;@@ -105,7 +123,7 @@ fn spawn_legacy_process((pi, job, output_join, writer_handle, hpc, Some(conpty), None)} else {let pipe_handles = spawn_process_with_pipes(- h_token,+ token,command,cwd,env_map,@@ -162,6 +180,8 @@ fn spawn_output_reader(output_read: HANDLE,output_tx: broadcast::Sender<Vec<u8>>,) -> std::thread::JoinHandle<()> {+ // SAFETY: The spawn path transfers this pipe's read end to the reader.+ let output_read = unsafe { OwnedHandle::from_raw_handle(output_read) };read_handle_loop(output_read, move |chunk| {let _ = output_tx.send(chunk.to_vec());})@@ -172,10 +192,12 @@ fn spawn_input_writer(mut writer_rx: mpsc::Receiver<Vec<u8>>,normalize_newlines: bool,) -> tokio::task::JoinHandle<()> {+ // SAFETY: The spawn path transfers the pipe's write end to this writer.+ let input_write = input_write.map(|handle| unsafe { OwnedHandle::from_raw_handle(handle) });tokio::task::spawn_blocking(move || {let mut windows_input = WindowsTtyInputNormalizer::default();while let Some(bytes) = writer_rx.blocking_recv() {- let Some(handle) = input_write else {+ let Some(handle) = &input_write else {continue;};let bytes = if normalize_newlines {@@ -183,21 +205,16 @@ fn spawn_input_writer(} else {bytes};- if write_all_handle(handle, &bytes).is_err() {+ if write_all_handle(handle.as_raw_handle(), &bytes).is_err() {break;}}- if let Some(handle) = input_write {- unsafe {- CloseHandle(handle);- }- }})}fn terminate_job_or_process(job: &JobObject,- process_handle: &Arc<StdMutex<Option<HANDLE>>>,+ process_handle: &Arc<StdMutex<Option<NonOwningProcessHandle>>>,logs_base_dir: Option<&Path>,) {if let Err(job_err) = job.terminate() {@@ -207,7 +224,7 @@ fn terminate_job_or_process();if let Ok(guard) = process_handle.lock()&& let Some(handle) = guard.as_ref()- && unsafe { TerminateProcess(*handle, 1) } == 0+ && unsafe { TerminateProcess(handle.raw(), 1) } == 0{log_note(&format!(@@ -247,8 +264,8 @@ fn write_all_handle(handle: HANDLE, mut bytes: &[u8]) -> Result<()> {#[allow(clippy::too_many_arguments)]fn finalize_exit(exit_tx: oneshot::Sender<i32>,- process_handle: Arc<StdMutex<Option<HANDLE>>>,- thread_handle: HANDLE,+ process_handle: Arc<StdMutex<Option<NonOwningProcessHandle>>>,+ thread_handle: OwnedHandle,output_join: std::thread::JoinHandle<()>,logs_base_dir: Option<&Path>,command: Vec<String>,@@ -259,8 +276,8 @@ fn finalize_exit(&& let Some(handle) = guard.as_ref(){unsafe {- WaitForSingleObject(*handle, INFINITE);- GetExitCodeProcess(*handle, &mut raw_exit);+ WaitForSingleObject(handle.raw(), INFINITE);+ GetExitCodeProcess(handle.raw(), &mut raw_exit);}}raw_exit as i32@@ -269,14 +286,12 @@ fn finalize_exit(let _ = output_join.join();let _ = exit_tx.send(exit_code);- unsafe {- if thread_handle != 0 && thread_handle != INVALID_HANDLE_VALUE {- CloseHandle(thread_handle);- }- if let Ok(mut guard) = process_handle.lock()- && let Some(handle) = guard.take()- {- CloseHandle(handle);+ drop(thread_handle);+ if let Ok(mut guard) = process_handle.lock()+ && let Some(handle) = guard.take()+ {+ unsafe {+ CloseHandle(handle.raw());}}@@ -287,7 +302,7 @@ fn finalize_exit(}}-fn resize_conpty_handle(hpc: &Arc<StdMutex<Option<HANDLE>>>, size: TerminalSize) -> Result<()> {+fn resize_conpty_handle(hpc: &Arc<StdMutex<Option<HPCON>>>, size: TerminalSize) -> Result<()> {let guard = hpc.lock().map_err(|_| anyhow::anyhow!("failed to lock ConPTY handle"))?;@@ -423,8 +438,13 @@ pub(crate) async fn spawn_windows_sandbox_session_legacy(};let hpc_handle = hpc.map(|hpc| Arc::new(StdMutex::new(Some(hpc))));- let process_handle = Arc::new(StdMutex::new(Some(pi.hProcess)));+ let process_handle = Arc::new(StdMutex::new(Some(NonOwningProcessHandle(pi.hProcess))));let wait_handle = Arc::clone(&process_handle);+ let wait_process_handle = NonOwningProcessHandle(pi.hProcess);+ // SAFETY: Successful process creation transfers this thread handle to the wait path.+ let thread_handle = unsafe { OwnedHandle::from_raw_handle(pi.hThread) };+ // SAFETY: spawn_legacy_process transfers the restricted token on success.+ let token_handle = unsafe { OwnedHandle::from_raw_handle(token_handle) };let job_for_wait = Arc::clone(&job);let command_for_wait = command.clone();let hpc_for_wait = hpc_handle.clone();@@ -432,7 +452,7 @@ pub(crate) async fn spawn_windows_sandbox_session_legacy(std::thread::spawn(move || {let _desktop = desktop;let timeout = timeout_ms.map(|ms| ms as u32).unwrap_or(INFINITE);- let wait_res = unsafe { WaitForSingleObject(pi.hProcess, timeout) };+ let wait_res = unsafe { WaitForSingleObject(wait_process_handle.raw(), timeout) };if wait_res == WAIT_TIMEOUT {terminate_job_or_process(&job_for_wait, &wait_handle, wait_logs_base_dir.as_deref());} else if let Err(err) = job_for_wait.preserve_descendants() {@@ -447,15 +467,11 @@ pub(crate) async fn spawn_windows_sandbox_session_legacy(let _ = guard.take();}drop(conpty_owner.take());- unsafe {- if token_handle != 0 && token_handle != INVALID_HANDLE_VALUE {- CloseHandle(token_handle);- }- }+ drop(token_handle);finalize_exit(exit_tx,wait_handle,- pi.hThread,+ thread_handle,output_join,wait_logs_base_dir.as_deref(),command_for_wait,diff --git a/codex-rs/windows-sandbox-rs/src/unified_exec/tests.rs b/codex-rs/windows-sandbox-rs/src/unified_exec/tests.rsindex 4520a51a88..be2d1bf07c 100644--- a/codex-rs/windows-sandbox-rs/src/unified_exec/tests.rs+++ b/codex-rs/windows-sandbox-rs/src/unified_exec/tests.rs@@ -138,7 +138,7 @@ fn wait_for_path(path: &Path, timeout: Duration) -> bool {fn open_process_for_wait(pid: u32) -> std::io::Result<OwnedHandle> {let handle = unsafe { OpenProcess(PROCESS_SYNCHRONIZE, 0, pid) };- if handle == 0 {+ if handle.is_null() {return Err(std::io::Error::last_os_error());}Ok(unsafe { OwnedHandle::from_raw_handle(handle as _) })diff --git a/codex-rs/windows-sandbox-rs/src/uninstall_windows/principals.rs b/codex-rs/windows-sandbox-rs/src/uninstall_windows/principals.rsindex ef79a21980..ab80a94b24 100644--- a/codex-rs/windows-sandbox-rs/src/uninstall_windows/principals.rs+++ b/codex-rs/windows-sandbox-rs/src/uninstall_windows/principals.rs@@ -125,7 +125,7 @@ impl SandboxUser {let profile_key = to_wide(format!(r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\{sid}"));- let mut key = 0;+ let mut key = std::ptr::null_mut();let status = unsafe {registry::RegOpenKeyExW(registry::HKEY_LOCAL_MACHINE,diff --git a/codex-rs/windows-sandbox-rs/src/uninstall_windows/principals_tests.rs b/codex-rs/windows-sandbox-rs/src/uninstall_windows/principals_tests.rsindex 4e8380d7f5..cc95e4d0e2 100644--- a/codex-rs/windows-sandbox-rs/src/uninstall_windows/principals_tests.rs+++ b/codex-rs/windows-sandbox-rs/src/uninstall_windows/principals_tests.rs@@ -54,7 +54,7 @@ impl ProfileFixture {let sid = string_from_sid_bytes(&self.user.sid).map_err(anyhow::Error::msg)?;let deadline = Instant::now() + Duration::from_secs(10);loop {- let mut key = 0;+ let mut key = std::ptr::null_mut();let status = unsafe {registry::RegOpenKeyExW(registry::HKEY_USERS,@@ -199,7 +199,7 @@ fn profile_cleanup_preserves_account_until_profile_can_be_deleted() -> Result<()fixture.user.remove()?;assert_eq!(local_user_flags(name)?, None);assert!(!path.exists());- let mut key = 0;+ let mut key = std::ptr::null_mut();let status = unsafe {registry::RegOpenKeyExW(registry::HKEY_LOCAL_MACHINE,diff --git a/codex-rs/windows-sandbox-rs/src/uninstall_windows/processes.rs b/codex-rs/windows-sandbox-rs/src/uninstall_windows/processes.rsindex 5cb57079e0..13d65003d6 100644--- a/codex-rs/windows-sandbox-rs/src/uninstall_windows/processes.rs+++ b/codex-rs/windows-sandbox-rs/src/uninstall_windows/processes.rs@@ -128,15 +128,15 @@ fn sandbox_processes(users: &DisabledSandboxUsers) -> Result<Vec<OwnedHandle>> {process.ProcessId,)};- if handle == 0 {+ if handle.is_null() {let error = io::Error::last_os_error();if error.raw_os_error() == Some(ERROR_INVALID_PARAMETER as i32) {continue;}return Err(error).context("open sandbox process for uninstall");}- let handle = unsafe { OwnedHandle::from_raw_handle(handle as *mut c_void) };- let mut token = 0;+ let handle = unsafe { OwnedHandle::from_raw_handle(handle) };+ let mut token = std::ptr::null_mut();if unsafe { OpenProcessToken(handle.as_raw_handle() as HANDLE, TOKEN_QUERY, &mut token) }== 0{@@ -149,7 +149,7 @@ fn sandbox_processes(users: &DisabledSandboxUsers) -> Result<Vec<OwnedHandle>> {}return Err(error).context("identify sandbox process before uninstall");}- let token = unsafe { OwnedHandle::from_raw_handle(token as *mut c_void) };+ let token = unsafe { OwnedHandle::from_raw_handle(token) };let sid = unsafe { get_user_sid_bytes(token.as_raw_handle() as HANDLE) }?;// A PID can be reused after enumeration. Check the opened process before terminating it.if users.sids().any(|user_sid| user_sid == sid.as_slice()) {diff --git a/codex-rs/windows-sandbox-rs/src/uninstall_windows/retained_logons_tests.rs b/codex-rs/windows-sandbox-rs/src/uninstall_windows/retained_logons_tests.rsindex 255c5c5747..44d9bdcced 100644--- a/codex-rs/windows-sandbox-rs/src/uninstall_windows/retained_logons_tests.rs+++ b/codex-rs/windows-sandbox-rs/src/uninstall_windows/retained_logons_tests.rs@@ -17,7 +17,7 @@ use windows_sys::Win32::System::Threading::GetCurrentProcess;use windows_sys::Win32::System::Threading::OpenProcessToken;fn current_process_token() -> Result<OwnedHandle> {- let mut raw = 0;+ let mut raw = std::ptr::null_mut();ensure!(unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut raw) } != 0,"open current-process token: {}",diff --git a/codex-rs/windows-sandbox-rs/tests/helper_manifest.rs b/codex-rs/windows-sandbox-rs/tests/helper_manifest.rsindex 0428f906aa..f068108117 100644--- a/codex-rs/windows-sandbox-rs/tests/helper_manifest.rs+++ b/codex-rs/windows-sandbox-rs/tests/helper_manifest.rs@@ -34,11 +34,11 @@ fn setup_helper_embeds_as_invoker_manifest() -> Result<()> {let module = unsafe {LoadLibraryExW(setup_path.as_ptr(),- /*hfile*/ 0,+ std::ptr::null_mut(),LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_IMAGE_RESOURCE,)};- if module == 0 {+ if module.is_null() {return Err(io::Error::last_os_error()).with_context(|| format!("load setup helper {}", setup_executable.display()));}@@ -50,7 +50,7 @@ fn setup_helper_embeds_as_invoker_manifest() -> Result<()> {std::ptr::without_provenance(RT_MANIFEST as usize),)};- if resource == 0 {+ if resource.is_null() {return Err(io::Error::last_os_error()).context("find numeric RT_MANIFEST resource ID 1");}diff --git a/codex-rs/windows-sandbox-service/Cargo.toml b/codex-rs/windows-sandbox-service/Cargo.tomlindex f6209b5409..381fec9888 100644--- a/codex-rs/windows-sandbox-service/Cargo.toml+++ b/codex-rs/windows-sandbox-service/Cargo.toml@@ -39,7 +39,7 @@ features = [][target.'cfg(windows)'.dependencies.windows-sys]-version = "0.52"+workspace = truefeatures = ["Win32_Foundation","Win32_NetworkManagement_NetManagement",diff --git a/codex-rs/windows-sandbox-service/src/ipc.rs b/codex-rs/windows-sandbox-service/src/ipc.rsindex 3c90977862..2d8e9ad1d6 100644--- a/codex-rs/windows-sandbox-service/src/ipc.rs+++ b/codex-rs/windows-sandbox-service/src/ipc.rs@@ -19,13 +19,16 @@ use codex_windows_sandbox::ProvisioningMessage;use codex_windows_sandbox::SandboxProvisioningResponse;use codex_windows_sandbox::to_wide;use codex_windows_sandbox::write_provisioning_frame;-pub(crate) use home::OwnedHandle;pub(crate) use home::pin_directory;pub(crate) use home::pin_existing_ancestors;pub(crate) use request::ProvisioningRequest;pub(crate) use request::ServiceRequest;use request::validate_request;use std::mem::size_of;+use std::os::windows::io::AsHandle;+use std::os::windows::io::AsRawHandle;+use std::os::windows::io::BorrowedHandle;+use std::os::windows::io::OwnedHandle;use std::ptr;use std::sync::Arc;use std::sync::atomic::AtomicBool;@@ -82,7 +85,7 @@ pub(crate) fn run(while refresh_session(&shutdown, &on_session_change).context("refresh the recorded sandbox owner")?{- let connection = accept_pipe_connection(listener.pipe.0)?;+ let connection = accept_pipe_connection(listener.pipe.as_raw_handle())?;// A session refresh can finish cleanup. Never dispatch an already accepted// connection after it stops the listener, including a disconnected wakeup.if !refresh_session(&shutdown, &on_session_change)@@ -94,16 +97,17 @@ pub(crate) fn run(continue;}- let authorized_process =- match crate::package_identity::authorize_client_process(listener.pipe.0) {- Ok(process) => process,- Err(_) => {- unsafe { pipes::DisconnectNamedPipe(listener.pipe.0) };- continue;- }- };+ let authorized_process = match crate::package_identity::authorize_client_process(+ listener.pipe.as_raw_handle(),+ ) {+ Ok(process) => process,+ Err(_) => {+ unsafe { pipes::DisconnectNamedPipe(listener.pipe.as_raw_handle()) };+ continue;+ }+ };let result = handle_request(- listener.pipe.0,+ listener.pipe.as_handle(),&authorized_process,&listener.sandbox_sid,&shutdown,@@ -159,7 +163,7 @@ fn write_response(let mut written = 0;let sent = unsafe {filesystem::WriteFile(- pipe.0,+ pipe.as_raw_handle(),frame.as_ptr(),frame.len() as u32,&mut written,@@ -171,7 +175,7 @@ fn write_response(while !shutdown.load(Ordering::Acquire) && Instant::now() < deadline {if unsafe {pipes::PeekNamedPipe(- pipe.0,+ pipe.as_raw_handle(),ptr::null_mut(),0,ptr::null_mut(),@@ -237,7 +241,7 @@ pub(crate) fn wake(pipe_name: &str, is_stopped: impl Fn() -> bool) {ptr::null(),filesystem::OPEN_EXISTING,/*dwflagsandattributes*/ 0,- /*htemplatefile*/ 0,+ ptr::null_mut(),)};if handle != foundation::INVALID_HANDLE_VALUE {@@ -254,7 +258,7 @@ fn pipe_security_descriptor(sandbox_sid: &str) -> String {}fn handle_request(- pipe: HANDLE,+ pipe: BorrowedHandle<'_>,authorized_process: &crate::package_identity::AuthorizedClientProcess,sandbox_sid: &[u8],shutdown: &AtomicBool,@@ -277,7 +281,7 @@ fn handle_request(let mut available = 0;if unsafe {pipes::PeekNamedPipe(- pipe,+ pipe.as_raw_handle(),ptr::null_mut(),0,ptr::null_mut(),@@ -295,7 +299,7 @@ fn handle_request(let mut read = 0;if unsafe {filesystem::ReadFile(- pipe,+ pipe.as_raw_handle(),request[request_length..].as_mut_ptr(),available,&mut read,diff --git a/codex-rs/windows-sandbox-service/src/ipc/authentication.rs b/codex-rs/windows-sandbox-service/src/ipc/authentication.rsindex 40f56d0294..353d888806 100644--- a/codex-rs/windows-sandbox-service/src/ipc/authentication.rs+++ b/codex-rs/windows-sandbox-service/src/ipc/authentication.rs@@ -11,16 +11,17 @@ use std::ffi::OsString;use std::ffi::c_void;use std::mem::size_of;use std::os::windows::ffi::OsStringExt;+use std::os::windows::io::AsHandle;+use std::os::windows::io::AsRawHandle;use std::os::windows::io::BorrowedHandle;-use std::os::windows::io::IntoRawHandle;+use std::os::windows::io::FromRawHandle;+use std::os::windows::io::OwnedHandle;use std::path::PathBuf;-use windows_sys::Win32::Foundation::HANDLE;use windows_sys::Win32::Security as security;use windows_sys::Win32::Storage::FileSystem as filesystem;use windows_sys::Win32::System::Pipes as pipes;use windows_sys::Win32::System::Threading as threading;-use super::home::OwnedHandle;use super::home::prepare_codex_home;use super::request::ServiceRequest;@@ -38,7 +39,7 @@ pub(crate) struct ClientIdentity {}pub(super) fn authenticate_client(- pipe: HANDLE,+ pipe: BorrowedHandle<'_>,authorized_process: &crate::package_identity::AuthorizedClientProcess,sandbox_sid: &[u8],request: &ServiceRequest,@@ -60,7 +61,7 @@ pub(super) fn authenticate_client(&identity.codex_home,&request.settings,&request.listeners,- identity.token.0,+ identity.token.as_raw_handle(),)}};@@ -72,7 +73,7 @@ pub(super) fn authenticate_client(}fn authenticate_impersonated_client(- pipe: HANDLE,+ pipe: BorrowedHandle<'_>,authorized_process: &crate::package_identity::AuthorizedClientProcess,sandbox_sid: &[u8],request: &ServiceRequest,@@ -85,10 +86,10 @@ fn authenticate_impersonated_client(.is_ok_and(|current| current == sandbox_sid),codex_windows_sandbox::SANDBOX_GROUP_CHANGED);- if unsafe { pipes::ImpersonateNamedPipeClient(pipe) } == 0 {+ if unsafe { pipes::ImpersonateNamedPipeClient(pipe.as_raw_handle()) } == 0 {return Err(std::io::Error::last_os_error()).context("impersonate provisioning client");}- let mut raw_token = 0;+ let mut raw_token = std::ptr::null_mut();if unsafe {threading::OpenThreadToken(threading::GetCurrentThread(),@@ -100,14 +101,15 @@ fn authenticate_impersonated_client({return Err(std::io::Error::last_os_error()).context("open provisioning client token");}- let token = OwnedHandle(raw_token);- crate::package_identity::authorize_client(authorized_process, token.0)+ // SAFETY: OpenThreadToken transferred this handle on success.+ let token = unsafe { OwnedHandle::from_raw_handle(raw_token) };+ crate::package_identity::authorize_client(authorized_process, token.as_raw_handle()).context("authorize the packaged Codex provisioning client")?;let mut session = 0_u32;let mut returned = 0_u32;if unsafe {security::GetTokenInformation(- token.0,+ token.as_raw_handle(),security::TokenSessionId,(&raw mut session).cast(),size_of::<u32>() as u32,@@ -124,7 +126,7 @@ fn authenticate_impersonated_client(let mut is_sandbox_member = 0;if unsafe {security::CheckTokenMembership(- token.0,+ token.as_raw_handle(),sandbox_sid.as_ptr() as *mut c_void,&mut is_sandbox_member,)@@ -136,7 +138,7 @@ fn authenticate_impersonated_client(bail!("sandbox accounts cannot request provisioning");}- let user = unsafe { codex_windows_sandbox::get_user_sid_bytes(token.0) }+ let user = unsafe { codex_windows_sandbox::get_user_sid_bytes(token.as_raw_handle()) }.context("read provisioning client identity")?;let user_sid = string_from_sid_bytes(&user).map_err(anyhow::Error::msg)?;let account = unsafe { codex_windows_sandbox::account_name_from_sid(user.as_ptr() as _) }@@ -170,7 +172,7 @@ fn authenticate_impersonated_client(DirectoryOpenDisposition::OpenExisting,)?;// Bind the guard to the authorized directory before resolving its pathname.- let guard = create_directory_guard(unsafe { BorrowedHandle::borrow_raw(home.0 as _) })?;+ let guard = create_directory_guard(home.as_handle())?;drop(super::home::pin_directory(requested_home,filesystem::FILE_READ_ATTRIBUTES,@@ -181,7 +183,7 @@ fn authenticate_impersonated_client(let path = loop {let length = unsafe {filesystem::GetFinalPathNameByHandleW(- home.0,+ home.as_raw_handle(),buffer.as_mut_ptr(),buffer.len() as u32,filesystem::FILE_NAME_NORMALIZED | filesystem::VOLUME_NAME_DOS,@@ -197,12 +199,12 @@ fn authenticate_impersonated_client(buffer.resize(length as usize, /*value*/ 0);};handles.push(home);- handles.push(OwnedHandle(guard.into_raw_handle() as HANDLE));+ handles.push(guard);(path, handles)}};let desktop_installation =- crate::installation_record::read_desktop_installation(&codex_home, token.0)+ crate::installation_record::read_desktop_installation(&codex_home, token.as_raw_handle()).inspect_err(|_| {crate::service::log_error(crate::service::EVENT_SERVICE_FAILED,diff --git a/codex-rs/windows-sandbox-service/src/ipc/home.rs b/codex-rs/windows-sandbox-service/src/ipc/home.rsindex 6ddbfd90a1..a17411750d 100644--- a/codex-rs/windows-sandbox-service/src/ipc/home.rs+++ b/codex-rs/windows-sandbox-service/src/ipc/home.rs@@ -11,29 +11,18 @@ use codex_windows_sandbox::open_directory_no_reparse;use codex_windows_sandbox::to_wide;use codex_windows_sandbox::validate_local_directory_path;use std::os::windows::fs::MetadataExt;-use std::os::windows::io::BorrowedHandle;-use std::os::windows::io::IntoRawHandle;+use std::os::windows::io::AsHandle;+use std::os::windows::io::OwnedHandle;use std::path::Component;use std::path::Path;use std::path::PathBuf;use windows_sys::Win32::Foundation as foundation;-use windows_sys::Win32::Foundation::HANDLE;use windows_sys::Win32::Storage::FileSystem as filesystem;use super::ServiceUnavailable;const DRIVE_FIXED: u32 = 3;-pub(crate) struct OwnedHandle(pub(crate) HANDLE);--impl Drop for OwnedHandle {- fn drop(&mut self) {- if self.0 != 0 && self.0 != foundation::INVALID_HANDLE_VALUE {- unsafe { foundation::CloseHandle(self.0) };- }- }-}-pub(super) fn prepare_codex_home(requested: &Path,runtime: SetupRuntime,@@ -121,9 +110,7 @@ pub(super) fn prepare_codex_home(}})?;if index != 0 {- // The handle is owned here and remains live until the guard is installed.- let directory_handle = unsafe { BorrowedHandle::borrow_raw(handle.0 as _) };- let guard = create_directory_guard(directory_handle)?;+ let guard = create_directory_guard(handle.as_handle())?;// Reject conversion before guard creation; after creation the retained// file prevents this directory from becoming empty and being converted.drop(pin_directory(@@ -131,7 +118,7 @@ pub(super) fn prepare_codex_home(filesystem::FILE_READ_ATTRIBUTES,DirectoryOpenDisposition::OpenExisting,)?);- handles.push(OwnedHandle(guard.into_raw_handle() as HANDLE));+ handles.push(guard);}handles.push(handle);if index == 0 {@@ -179,5 +166,5 @@ pub(crate) fn pin_directory(disposition,).with_context(|| format!("pin {}", path.display()))?;- Ok(OwnedHandle(handle.into_raw_handle() as HANDLE))+ Ok(handle)}diff --git a/codex-rs/windows-sandbox-service/src/ipc/listener.rs b/codex-rs/windows-sandbox-service/src/ipc/listener.rsindex de6d3595b4..3895e3a98b 100644--- a/codex-rs/windows-sandbox-service/src/ipc/listener.rs+++ b/codex-rs/windows-sandbox-service/src/ipc/listener.rs@@ -8,6 +8,9 @@ use codex_windows_sandbox::ensure_sandbox_users_group;use codex_windows_sandbox::string_from_sid_bytes;use codex_windows_sandbox::to_wide;use std::mem::size_of;+use std::os::windows::io::AsRawHandle;+use std::os::windows::io::FromRawHandle;+use std::os::windows::io::OwnedHandle;use std::ptr;use windows_sys::Win32::Foundation as foundation;use windows_sys::Win32::Security as security;@@ -16,7 +19,6 @@ use windows_sys::Win32::Storage::FileSystem as filesystem;use windows_sys::Win32::System::Pipes as pipes;use super::MAX_REQUEST_BYTES;-use super::OwnedHandle;use super::pipe_security_descriptor;pub(super) struct ProvisioningListener {@@ -52,7 +54,7 @@ impl ProvisioningListener {codex_windows_sandbox::resolve_sid(codex_windows_sandbox::SANDBOX_USERS_GROUP)};if current_group.is_ok_and(|current| current == self.sandbox_sid) {- unsafe { pipes::DisconnectNamedPipe(self.pipe.0) };+ unsafe { pipes::DisconnectNamedPipe(self.pipe.as_raw_handle()) };return Ok(self);}// A stale deny SID was refused before dispatch. Close this first-instance@@ -114,5 +116,6 @@ fn create_provisioning_pipe(if pipe == foundation::INVALID_HANDLE_VALUE {return Err(std::io::Error::last_os_error()).context("create provisioning pipe");}- Ok((descriptor, OwnedHandle(pipe)))+ // SAFETY: CreateNamedPipeW transferred this pipe handle on success.+ Ok((descriptor, unsafe { OwnedHandle::from_raw_handle(pipe) }))}diff --git a/codex-rs/windows-sandbox-service/src/ipc_tests.rs b/codex-rs/windows-sandbox-service/src/ipc_tests.rsindex 2a72163a42..14a7dbdc5d 100644--- a/codex-rs/windows-sandbox-service/src/ipc_tests.rs+++ b/codex-rs/windows-sandbox-service/src/ipc_tests.rs@@ -1,5 +1,4 @@use super::MAX_RESPONSE_MESSAGE_BYTES;-use super::OwnedHandle;use super::PipeConnection;use super::ServiceRequest;use super::accept_pipe_connection;@@ -26,6 +25,9 @@ use codex_windows_sandbox::read_provisioning_frame;use codex_windows_sandbox::to_wide;use codex_windows_sandbox::write_provisioning_frame;use pretty_assertions::assert_eq;+use std::os::windows::io::AsRawHandle;+use std::os::windows::io::FromRawHandle;+use std::os::windows::io::OwnedHandle;use std::path::Path;use std::path::PathBuf;use std::ptr;@@ -40,6 +42,12 @@ use windows_sys::Win32::Storage::FileSystem as filesystem;use windows_sys::Win32::Storage::Packaging::Appx;use windows_sys::Win32::System::Pipes as pipes;+struct NonOwningPipeHandle(foundation::HANDLE);++// SAFETY: Pipe handles are opaque process-wide tokens that may be passed between+// threads. This wrapper does not own the handle or extend its lifetime.+unsafe impl Send for NonOwningPipeHandle {}+#[test]fn provisioning_error_response_preserves_causes_within_message_limits() {let error = anyhow::anyhow!("Windows error\t5\n")@@ -560,7 +568,8 @@ fn unpackaged_pipe_clients_are_rejected_before_sending_a_request() {)};assert_ne!(server, foundation::INVALID_HANDLE_VALUE);- let server = OwnedHandle(server);+ // SAFETY: CreateNamedPipeW returned a valid owned handle.+ let server = unsafe { OwnedHandle::from_raw_handle(server) };let client = unsafe {filesystem::CreateFileW(@@ -570,18 +579,19 @@ fn unpackaged_pipe_clients_are_rejected_before_sending_a_request() {ptr::null(),filesystem::OPEN_EXISTING,0,- 0,+ ptr::null_mut(),)};assert_ne!(client, foundation::INVALID_HANDLE_VALUE);- let _client = OwnedHandle(client);+ // SAFETY: CreateFileW returned a valid owned handle.+ let _client = unsafe { OwnedHandle::from_raw_handle(client) };- let connected = unsafe { pipes::ConnectNamedPipe(server.0, ptr::null_mut()) };+ let connected = unsafe { pipes::ConnectNamedPipe(server.as_raw_handle(), ptr::null_mut()) };assert!(connected != 0 || unsafe { foundation::GetLastError() } == foundation::ERROR_PIPE_CONNECTED);- let error = match crate::package_identity::authorize_client_process(server.0) {+ let error = match crate::package_identity::authorize_client_process(server.as_raw_handle()) {Ok(_) => panic!("an unpackaged client was authorized without sending a request"),Err(error) => error,};@@ -616,7 +626,8 @@ fn disconnected_pipe_clients_do_not_prevent_subsequent_connections() {)};assert_ne!(server, foundation::INVALID_HANDLE_VALUE);- let server = OwnedHandle(server);+ // SAFETY: CreateNamedPipeW returned a valid owned handle.+ let server = unsafe { OwnedHandle::from_raw_handle(server) };let first_client = unsafe {filesystem::CreateFileW(@@ -626,19 +637,24 @@ fn disconnected_pipe_clients_do_not_prevent_subsequent_connections() {ptr::null(),filesystem::OPEN_EXISTING,0,- 0,+ ptr::null_mut(),)};assert_ne!(first_client, foundation::INVALID_HANDLE_VALUE);- drop(OwnedHandle(first_client));+ // SAFETY: CreateFileW returned a valid owned handle.+ drop(unsafe { OwnedHandle::from_raw_handle(first_client) });assert_eq!(- accept_pipe_connection(server.0).unwrap(),+ accept_pipe_connection(server.as_raw_handle()).unwrap(),PipeConnection::Disconnected);- let server_handle = server.0;- let listener = std::thread::spawn(move || accept_pipe_connection(server_handle));+ let server_handle = NonOwningPipeHandle(server.as_raw_handle());+ let listener = std::thread::spawn(move || {+ // Capture the wrapper rather than its raw pointer field.+ let server_handle = &server_handle;+ accept_pipe_connection(server_handle.0)+ });let available = unsafe { pipes::WaitNamedPipeW(name.as_ptr(), 5_000) };assert_ne!(available,@@ -654,7 +670,7 @@ fn disconnected_pipe_clients_do_not_prevent_subsequent_connections() {ptr::null(),filesystem::OPEN_EXISTING,0,- 0,+ ptr::null_mut(),)};assert_ne!(@@ -663,14 +679,18 @@ fn disconnected_pipe_clients_do_not_prevent_subsequent_connections() {"connect replacement named-pipe client: {}",std::io::Error::last_os_error());- let next_client = OwnedHandle(next_client);+ // SAFETY: CreateFileW returned a valid owned handle.+ let next_client = unsafe { OwnedHandle::from_raw_handle(next_client) };assert_eq!(listener.join().expect("join named-pipe listener").unwrap(),PipeConnection::Connected);drop(next_client);- assert_ne!(unsafe { pipes::DisconnectNamedPipe(server.0) }, 0);+ assert_ne!(+ unsafe { pipes::DisconnectNamedPipe(server.as_raw_handle()) },+ 0+ );let timeout = Duration::from_secs(5);let deadline = Instant::now() + timeout;@@ -687,7 +707,7 @@ fn disconnected_pipe_clients_do_not_prevent_subsequent_connections() {let (accepted_tx, accepted_rx) = mpsc::channel();let listener = std::thread::spawn(move || {- let _ = accepted_tx.send(accept_pipe_connection(server.0));+ let _ = accepted_tx.send(accept_pipe_connection(server.as_raw_handle()));drop(server);});let accepted = accepted_rx.recv_timeout(timeout);diff --git a/codex-rs/windows-sandbox-service/src/machine_policy.rs b/codex-rs/windows-sandbox-service/src/machine_policy.rsindex 97c0d9f28f..0154ab2968 100644--- a/codex-rs/windows-sandbox-service/src/machine_policy.rs+++ b/codex-rs/windows-sandbox-service/src/machine_policy.rs@@ -17,6 +17,14 @@ use tokio::sync::Notify;use windows_sys::Win32::Foundation::HANDLE;use windows_sys::Win32::Security::ImpersonateLoggedOnUser;+struct NonOwningImpersonationToken(HANDLE);++// SAFETY: Windows access token handles are opaque process-wide values that may+// be shared between threads. This wrapper does not own the token or extend its+// lifetime.+unsafe impl Send for NonOwningImpersonationToken {}+unsafe impl Sync for NonOwningImpersonationToken {}+pub(crate) fn validate_provisioning_settings(codex_home: &Path,settings: &WindowsSandboxProvisioningSettings,@@ -25,10 +33,13 @@ pub(crate) fn validate_provisioning_settings() -> Result<()> {let impersonation_failure = Arc::new(Notify::new());let worker_impersonation_failure = Arc::clone(&impersonation_failure);+ let impersonation_token = NonOwningImpersonationToken(impersonation_token);let runtime = tokio::runtime::Builder::new_current_thread().enable_all().on_thread_start(move || {- if unsafe { ImpersonateLoggedOnUser(impersonation_token) } == 0 {+ // Capture the wrapper rather than its raw pointer field.+ let impersonation_token = &impersonation_token;+ if unsafe { ImpersonateLoggedOnUser(impersonation_token.0) } == 0 {let error = std::io::Error::last_os_error();worker_impersonation_failure.notify_one();panic!(diff --git a/codex-rs/windows-sandbox-service/src/machine_policy_tests.rs b/codex-rs/windows-sandbox-service/src/machine_policy_tests.rsindex 17b92359cc..d142034940 100644--- a/codex-rs/windows-sandbox-service/src/machine_policy_tests.rs+++ b/codex-rs/windows-sandbox-service/src/machine_policy_tests.rs@@ -18,7 +18,7 @@ fn runtime_worker_impersonation_failure_rejects_provisioning() {&std::env::temp_dir(),&WindowsSandboxProvisioningSettings::default(),&WindowsSandboxProxyListeners::default(),- /*impersonation_token*/ 0,+ std::ptr::null_mut(),).expect_err("runtime workers must not load configuration without impersonating the client");diff --git a/codex-rs/windows-sandbox-service/src/package_identity.rs b/codex-rs/windows-sandbox-service/src/package_identity.rsindex 8fc5e949df..69b7093912 100644--- a/codex-rs/windows-sandbox-service/src/package_identity.rs+++ b/codex-rs/windows-sandbox-service/src/package_identity.rs@@ -1,6 +1,9 @@//! Binds provisioning requests to the packaged Codex client and its Windows user.use std::io;+use std::os::windows::io::AsRawHandle;+use std::os::windows::io::FromRawHandle;+use std::os::windows::io::OwnedHandle;#[cfg(debug_assertions)]use std::sync::atomic::AtomicBool;#[cfg(debug_assertions)]@@ -9,7 +12,6 @@ use std::sync::atomic::Ordering;use anyhow::Context;use anyhow::Result;use anyhow::bail;-use windows_sys::Win32::Foundation as foundation;use windows_sys::Win32::Foundation::HANDLE;use windows_sys::Win32::Security as security;use windows_sys::Win32::System::Pipes;@@ -23,20 +25,10 @@ pub(crate) use registered::require_runtime_package_family;#[cfg(debug_assertions)]static FOREGROUND_MODE: AtomicBool = AtomicBool::new(false);-struct OwnedHandle(HANDLE);-pub(crate) struct AuthorizedClientProcess {handle: OwnedHandle,}-impl Drop for OwnedHandle {- fn drop(&mut self) {- if self.0 != 0 && self.0 != foundation::INVALID_HANDLE_VALUE {- unsafe { foundation::CloseHandle(self.0) };- }- }-}-#[cfg(debug_assertions)]pub(crate) fn enable_foreground_mode() {FOREGROUND_MODE.store(true, Ordering::Release);@@ -52,13 +44,15 @@ pub(crate) fn authorize_client_process(pipe: HANDLE) -> Result<AuthorizedClientPlet process = unsafe {Threading::OpenProcess(Threading::PROCESS_QUERY_LIMITED_INFORMATION, 0, process_id)};- if process == 0 {+ if process.is_null() {return Err(io::Error::last_os_error()).context("open the provisioning client process");}- let process = OwnedHandle(process);+ // SAFETY: OpenProcess transferred this handle on success.+ let process = unsafe { OwnedHandle::from_raw_handle(process) };- let client_family = unsafe { codex_windows_sandbox::process_package_family(process.0) }- .context("read provisioning client package identity")?;+ let client_family =+ unsafe { codex_windows_sandbox::process_package_family(process.as_raw_handle()) }+ .context("read provisioning client package identity")?;let service_family =unsafe { codex_windows_sandbox::process_package_family(Threading::GetCurrentProcess()) }.context("read provisioning service package identity")?;@@ -90,17 +84,23 @@ pub(crate) fn authorize_client(process: &AuthorizedClientProcess,client_token: HANDLE,) -> Result<()> {- let mut process_token = 0;+ let mut process_token = std::ptr::null_mut();if unsafe {- Threading::OpenProcessToken(process.handle.0, security::TOKEN_QUERY, &mut process_token)+ Threading::OpenProcessToken(+ process.handle.as_raw_handle(),+ security::TOKEN_QUERY,+ &mut process_token,+ )} == 0{return Err(io::Error::last_os_error()).context("open the provisioning client process token");}- let process_token = OwnedHandle(process_token);- let process_user = unsafe { codex_windows_sandbox::get_user_sid_bytes(process_token.0) }- .context("read the client process user")?;+ // SAFETY: OpenProcessToken transferred this handle on success.+ let process_token = unsafe { OwnedHandle::from_raw_handle(process_token) };+ let process_user =+ unsafe { codex_windows_sandbox::get_user_sid_bytes(process_token.as_raw_handle()) }+ .context("read the client process user")?;let impersonated_user = unsafe { codex_windows_sandbox::get_user_sid_bytes(client_token) }.context("read the impersonated client user")?;if process_user != impersonated_user {diff --git a/codex-rs/windows-sandbox-service/src/package_identity/registered.rs b/codex-rs/windows-sandbox-service/src/package_identity/registered.rsindex f473bec6ea..34414a29e0 100644--- a/codex-rs/windows-sandbox-service/src/package_identity/registered.rs+++ b/codex-rs/windows-sandbox-service/src/package_identity/registered.rs@@ -1,6 +1,8 @@//! Admits registered Core only from the service's installed package version and//! prevents legacy setup from replacing accounts owned by a registered runtime.+use std::os::windows::io::AsRawHandle;+use anyhow::Context;use anyhow::Result;use anyhow::bail;@@ -31,8 +33,9 @@ pub(crate) fn authorize_setup_runtime(}fn authorize_runtime_client_process(process: &AuthorizedClientProcess) -> Result<()> {- let client_family = unsafe { codex_windows_sandbox::process_package_family(process.handle.0) }- .context("read runtime registration client package family")?;+ let client_family =+ unsafe { codex_windows_sandbox::process_package_family(process.handle.as_raw_handle()) }+ .context("read runtime registration client package family")?;let service_family =unsafe { codex_windows_sandbox::process_package_family(Threading::GetCurrentProcess()) }.context("read runtime registration service package family")?;@@ -40,7 +43,12 @@ fn authorize_runtime_client_process(process: &AuthorizedClientProcess) -> Resultlet mut image = [0u16; 32768];let mut length = image.len() as u32;if unsafe {- Threading::QueryFullProcessImageNameW(process.handle.0, 0, image.as_mut_ptr(), &mut length)+ Threading::QueryFullProcessImageNameW(+ process.handle.as_raw_handle(),+ 0,+ image.as_mut_ptr(),+ &mut length,+ )} == 0{return Err(std::io::Error::last_os_error()).context("read provisioning client image");diff --git a/codex-rs/windows-sandbox-service/src/package_lifecycle.rs b/codex-rs/windows-sandbox-service/src/package_lifecycle.rsindex f53143c743..aa58215027 100644--- a/codex-rs/windows-sandbox-service/src/package_lifecycle.rs+++ b/codex-rs/windows-sandbox-service/src/package_lifecycle.rs@@ -3,8 +3,10 @@use std::cell::RefCell;use std::io;-use std::os::windows::io::BorrowedHandle;-use std::os::windows::io::IntoRawHandle;+use std::os::windows::io::AsHandle;+use std::os::windows::io::AsRawHandle;+use std::os::windows::io::FromRawHandle;+use std::os::windows::io::OwnedHandle;use std::path::PathBuf;use std::sync::Arc;use std::sync::atomic::AtomicBool;@@ -35,7 +37,6 @@ use windows_sys::Win32::System::RemoteDesktop::WTSFreeMemory;use windows_sys::Win32::System::RemoteDesktop::WTSQueryUserToken;use crate::installation_record::InstallationRecord;-use crate::ipc::OwnedHandle;mod cleanup;mod registered;@@ -102,7 +103,7 @@ impl PackageLifecycle {}let saved_record = record.clone();- with_owner_impersonation(user_token.0, || {+ with_owner_impersonation(user_token.as_raw_handle(), || {let mut directory_handles = Vec::new();let mut directory_guard = None;let codex_home = match crate::ipc::pin_existing_ancestors(@@ -113,15 +114,14 @@ impl PackageLifecycle {let home = directory_handles.last().context("pin the registered home")?;- let guard =- create_directory_guard(unsafe { BorrowedHandle::borrow_raw(home.0 as _) })?;+ let guard = create_directory_guard(home.as_handle())?;// Reject a conversion that happened before the handle-relative guard was created.drop(crate::ipc::pin_directory(&record.codex_home,filesystem::FILE_READ_ATTRIBUTES,DirectoryOpenDisposition::OpenExisting,)?);- directory_guard = Some(OwnedHandle(guard.into_raw_handle() as HANDLE));+ directory_guard = Some(guard);Ok(())}) {Ok(()) => Some(record.codex_home.clone()),@@ -219,12 +219,13 @@ impl PackageLifecycle {{return Ok(());}- let mut raw_token = 0;+ let mut raw_token = std::ptr::null_mut();if unsafe { WTSQueryUserToken(session_id, &mut raw_token) } == 0 {return Err(io::Error::last_os_error()).context("open the logged-in user's token");}- let token = crate::ipc::OwnedHandle(raw_token);- let user = unsafe { codex_windows_sandbox::get_user_sid_bytes(token.0) }?;+ // SAFETY: WTSQueryUserToken transferred this handle on success.+ let token = unsafe { OwnedHandle::from_raw_handle(raw_token) };+ let user = unsafe { codex_windows_sandbox::get_user_sid_bytes(token.as_raw_handle()) }?;let user_sid = string_from_sid_bytes(&user).map_err(anyhow::Error::msg)?;ensure!(user_sid == record.user_sid,diff --git a/codex-rs/windows-sandbox-service/src/package_lifecycle/cleanup.rs b/codex-rs/windows-sandbox-service/src/package_lifecycle/cleanup.rsindex fa4844efa2..03fb2b8fd8 100644--- a/codex-rs/windows-sandbox-service/src/package_lifecycle/cleanup.rs+++ b/codex-rs/windows-sandbox-service/src/package_lifecycle/cleanup.rs@@ -2,6 +2,7 @@//! Owner impersonation, directory pins, and registration-aware cleanup order are preserved.use std::io;+use std::os::windows::io::AsRawHandle;use std::path::Path;use std::sync::atomic::AtomicBool;@@ -33,7 +34,10 @@ pub(super) fn clean_up(// Remove exact grants from the locked cleanup record before native account deletion.if let Some(record) = runtime {log_cleanup("removing registered runtime metadata");- crate::registered_runtime::remove_metadata(installation.user_token.0, record)?;+ crate::registered_runtime::remove_metadata(+ installation.user_token.as_raw_handle(),+ record,+ )?;}log_cleanup("removing native sandbox resources");let mut prune_codex_home = false;@@ -55,7 +59,7 @@ pub(super) fn clean_up(return Ok(());};// The marker is user-writable. It must never authorize deletion as LocalSystem.- with_owner_impersonation(installation.user_token.0, || {+ with_owner_impersonation(installation.user_token.as_raw_handle(), || {let mut errors = Vec::new();let mut record_result = |operation: &str, result: io::Result<()>| match result {Ok(()) => log_cleanup(&format!("{operation}: completed")),@@ -133,13 +137,15 @@ pub(super) fn clean_up(if prune_codex_home && let Some(home) = &codex_home {// Keep the home pinned through native retries. Empty-root pruning is best effort// so a failure cannot restart native cleanup through an unpinned home.- if let Err(error) = with_owner_impersonation(installation.user_token.0, || {- if installation.directory_guard.take().is_some() {- installation.directory_handles.pop();- }- remove_empty_directory(home, "codex home");- Ok(())- }) {+ if let Err(error) =+ with_owner_impersonation(installation.user_token.as_raw_handle(), || {+ if installation.directory_guard.take().is_some() {+ installation.directory_handles.pop();+ }+ remove_empty_directory(home, "codex home");+ Ok(())+ })+ {log_error(EVENT_CLEANUP_DETAIL,&format!("remove empty codex home: failed, {error:#}"),diff --git a/codex-rs/windows-sandbox-service/src/package_lifecycle/registered.rs b/codex-rs/windows-sandbox-service/src/package_lifecycle/registered.rsindex 3b0cdc294f..cbddff1399 100644--- a/codex-rs/windows-sandbox-service/src/package_lifecycle/registered.rs+++ b/codex-rs/windows-sandbox-service/src/package_lifecycle/registered.rs@@ -1,6 +1,7 @@//! Registered runtime ownership and uninstall policy for the shared package watcher.//! Native cleanup stays inside the caller's setup lock and precedes package removal.+use std::os::windows::io::AsRawHandle;use std::sync::atomic::AtomicBool;use std::sync::atomic::Ordering;@@ -81,7 +82,10 @@ pub(super) fn clean_up(lifecycle: &PackageLifecycle, record: InstallationRecord)let installation = installation.as_ref().context("authenticated installation is missing")?;- crate::registered_runtime::prepare_removal(installation.user_token.0, &mut record)?+ crate::registered_runtime::prepare_removal(+ installation.user_token.as_raw_handle(),+ &mut record,+ )?};let prepared =prepare_packaged_windows_sandbox_cleanup_with_retained_tokens(&removal.tokens())?;diff --git a/codex-rs/windows-sandbox-service/src/provisioning.rs b/codex-rs/windows-sandbox-service/src/provisioning.rsindex cf91b51cde..bc99a9e362 100644--- a/codex-rs/windows-sandbox-service/src/provisioning.rs+++ b/codex-rs/windows-sandbox-service/src/provisioning.rs@@ -3,8 +3,9 @@mod registered;use std::os::windows::fs::MetadataExt;-use std::os::windows::io::BorrowedHandle;-use std::os::windows::io::IntoRawHandle;+use std::os::windows::io::AsHandle;+use std::os::windows::io::AsRawHandle;+use std::os::windows::io::OwnedHandle;use std::sync::atomic::AtomicBool;use anyhow::Context;@@ -17,7 +18,6 @@ use windows_sys::Win32::Storage::FileSystem as filesystem;use crate::installation_record::InstallationRecord;use crate::ipc::ClientIdentity;-use crate::ipc::OwnedHandle;use crate::ipc::ServiceRequest;// The lifecycle callback validates ownership and returns the canonical saved record.@@ -29,8 +29,9 @@ fn register_owner(codex_windows_sandbox::SetupRuntime,) -> Result<InstallationRecord>,) -> Result<InstallationRecord> {- let token = unsafe { BorrowedHandle::borrow_raw(identity.token.0 as _) }- .try_clone_to_owned()+ let token = identity+ .token+ .try_clone().context("retain authenticated uninstall owner")?;on_authenticated_user(InstallationRecord {@@ -40,7 +41,7 @@ fn register_owner(desktop_installation: identity.desktop_installation.clone(),runtime: None,},- OwnedHandle(token.into_raw_handle() as _),+ token,identity.runtime,)}@@ -49,7 +50,7 @@ fn setup_is_complete(identity: &ClientIdentity,settings: &codex_windows_sandbox::WindowsSandboxProvisioningSettings,) -> Result<bool> {- crate::package_lifecycle::with_owner_impersonation(identity.token.0, || {+ crate::package_lifecycle::with_owner_impersonation(identity.token.as_raw_handle(), || {Ok(codex_windows_sandbox::sandbox_setup_is_complete_with_settings(&identity.codex_home,@@ -116,7 +117,7 @@ pub(crate) fn run(.directory_handles.iter()// The identity owns these handles through the synchronous helper launch and wait.- .map(|handle| unsafe { BorrowedHandle::borrow_raw(handle.0 as _) })+ .map(AsHandle::as_handle).collect::<Vec<_>>();match run_elevated_provisioning_setup_with_retained_handles(&identity.codex_home,diff --git a/codex-rs/windows-sandbox-service/src/provisioning/registered.rs b/codex-rs/windows-sandbox-service/src/provisioning/registered.rsindex 0d5f4fe762..124ef5d4b3 100644--- a/codex-rs/windows-sandbox-service/src/provisioning/registered.rs+++ b/codex-rs/windows-sandbox-service/src/provisioning/registered.rs@@ -1,5 +1,7 @@//! The registered-Core setup transaction: admit, provision, register, then publish readiness.+use std::os::windows::io::AsRawHandle;+use std::os::windows::io::OwnedHandle;use std::sync::atomic::AtomicBool;use anyhow::Context;@@ -20,7 +22,6 @@ use windows_sys::Win32::NetworkManagement::NetManagement::UF_PASSWORD_EXPIRED;use crate::installation_record::InstallationRecord;use crate::installation_record::RuntimeRegistration;use crate::ipc::ClientIdentity;-use crate::ipc::OwnedHandle;#[cfg(test)]#[path = "registered_tests.rs"]@@ -99,14 +100,17 @@ pub(super) fn run(if setup_complete && !request.refresh_only {setup_complete = !credentials_need_repair(|account| {- crate::package_lifecycle::with_owner_impersonation(identity.token.0, || {- let mut pins = Vec::new();- crate::ipc::pin_existing_ancestors(- &sandbox_secrets_dir(&identity.codex_home),- &mut pins,- )?;- logon_existing_sandbox_account(&identity.codex_home, account).map(drop)- })+ crate::package_lifecycle::with_owner_impersonation(+ identity.token.as_raw_handle(),+ || {+ let mut pins = Vec::new();+ crate::ipc::pin_existing_ancestors(+ &sandbox_secrets_dir(&identity.codex_home),+ &mut pins,+ )?;+ logon_existing_sandbox_account(&identity.codex_home, account).map(drop)+ },+ ).with_context(|| format!("check registered sandbox account {account:?}"))},|| {diff --git a/codex-rs/windows-sandbox-service/src/registered_runtime.rs b/codex-rs/windows-sandbox-service/src/registered_runtime.rsindex 554cece304..a1e6802142 100644--- a/codex-rs/windows-sandbox-service/src/registered_runtime.rs+++ b/codex-rs/windows-sandbox-service/src/registered_runtime.rs@@ -71,13 +71,13 @@ impl Drop for AccountProfile {impl AccountProfile {fn unload_profile(&mut self) -> Result<()> {- if self.profile != 0 {+ if !self.profile.is_null() {let unloaded =unsafe { UnloadUserProfile(self.token.as_raw_handle() as _, self.profile) };BOOL(unloaded).ok().context("unload managed runtime account profile")?;- self.profile = 0;+ self.profile = std::ptr::null_mut();}Ok(())}@@ -99,7 +99,7 @@ pub(crate) fn provision(SandboxRuntimeAccount::Offline,SandboxRuntimeAccount::Online,] {- let token = with_owner_impersonation(identity.token.0, || {+ let token = with_owner_impersonation(identity.token.as_raw_handle(), || {let mut pins = Vec::new();crate::ipc::pin_existing_ancestors(&sandbox_secrets_dir(&identity.codex_home),@@ -206,7 +206,7 @@ pub(crate) fn provision("runtime registration completed without the expected package");}- metadata::grant(identity.token.0, &profile.user_sid, record)+ metadata::grant(identity.token.as_raw_handle(), &profile.user_sid, record).context("grant managed runtime metadata permissions")?;profile.unload_profile()?;}diff --git a/codex-rs/windows-sandbox-service/src/registered_runtime/removal.rs b/codex-rs/windows-sandbox-service/src/registered_runtime/removal.rsindex 507cfad4b6..79b11bc8c1 100644--- a/codex-rs/windows-sandbox-service/src/registered_runtime/removal.rs+++ b/codex-rs/windows-sandbox-service/src/registered_runtime/removal.rs@@ -207,7 +207,7 @@ pub(crate) fn prepare(// Do not relax process handle inheritance. Only these validated token handles// are duplicated into the exact child process, with inheritance disabled.for (target, token) in targets.iter_mut().zip(&tokens) {- let mut remote = 0;+ let mut remote = std::ptr::null_mut();let duplicated = unsafe {DuplicateHandle(threading::GetCurrentProcess(),diff --git a/codex-rs/windows-sandbox-service/src/service.rs b/codex-rs/windows-sandbox-service/src/service.rsindex a650e31689..32f7c510f1 100644--- a/codex-rs/windows-sandbox-service/src/service.rs+++ b/codex-rs/windows-sandbox-service/src/service.rs@@ -56,12 +56,19 @@ const MAX_EVENT_MESSAGE_UNITS: usize = 1024;static SERVICE_STATE: OnceLock<ServiceState> = OnceLock::new();+struct ServiceStatusToken(SERVICE_STATUS_HANDLE);++// SAFETY: Windows permits threads in the calling process to use this opaque+// status token. The token does not need closing; this wrapper only shares it.+unsafe impl Send for ServiceStatusToken {}+unsafe impl Sync for ServiceStatusToken {}+struct ServiceState {service_name: String,pipe_name: String,shutdown: Arc<AtomicBool>,uninstalling: Arc<AtomicBool>,- status_handle: OnceLock<SERVICE_STATUS_HANDLE>,+ status_handle: OnceLock<ServiceStatusToken>,current_status: AtomicU32,stop_requested: AtomicBool,}@@ -155,12 +162,12 @@ fn service_main_inner(state: &ServiceState) -> Result<()> {ptr::null(),)};- if status_handle == 0 {+ if status_handle.is_null() {return Err(io::Error::last_os_error()).context("register the service control handler");}state.status_handle- .set(status_handle)+ .set(ServiceStatusToken(status_handle)).map_err(|_| anyhow::anyhow!("the service status handle was already registered"))?;state.report_status(SERVICE_START_PENDING, NO_ERROR)?;@@ -246,7 +253,7 @@ fn log_event(event_type: u16, event_id: u32, message: &str) {.chain(std::iter::once(0)).collect::<Vec<_>>();let event_log = unsafe { RegisterEventSourceW(ptr::null(), source.as_ptr()) };- if event_log == 0 {+ if event_log.is_null() {eprintln!("unable to open the Windows event log: {message}");return;}@@ -288,7 +295,7 @@ fn log_event(event_type: u16, event_id: u32, message: &str) {impl ServiceState {fn report_status(&self, current_status: u32, win32_exit_code: u32) -> Result<()> {- let status_handle = *self+ let status_handle = self.status_handle.get().context("the service status handle was not registered")?;@@ -309,7 +316,7 @@ impl ServiceState {self.current_status.store(current_status, Ordering::Release);// The SCM synchronously copies the status structure during this call.- let updated = unsafe { SetServiceStatus(status_handle, &status) };+ let updated = unsafe { SetServiceStatus(status_handle.0, &status) };if updated == 0 {return Err(io::Error::last_os_error()).context("update the Windows service status");}diff --git a/codex-rs/windows-sandbox-service/src/service/runtime_lifecycle.rs b/codex-rs/windows-sandbox-service/src/service/runtime_lifecycle.rsindex 76727cc21d..b540ba8b35 100644--- a/codex-rs/windows-sandbox-service/src/service/runtime_lifecycle.rs+++ b/codex-rs/windows-sandbox-service/src/service/runtime_lifecycle.rs@@ -23,7 +23,7 @@ use crate::package_lifecycle::PackageLifecycle;#[cfg(debug_assertions)]pub(super) fn foreground_owner(mut record: crate::installation_record::InstallationRecord,- _token: crate::ipc::OwnedHandle,+ _token: std::os::windows::io::OwnedHandle,runtime: codex_windows_sandbox::SetupRuntime,) -> Result<crate::installation_record::InstallationRecord> {let _lock = codex_windows_sandbox::acquire_sandbox_setup_lock(/*timeout_ms*/ 5_000)?;