mxc-sdk 1.0.0

Importable library for starting MXC sandboxes in-process, with streaming stdio.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

use std::os::windows::ffi::OsStringExt;
use std::os::windows::io::{BorrowedHandle, FromRawHandle, OwnedHandle as StdOwnedHandle};
use std::path::PathBuf;
use std::sync::{Arc, Mutex, Weak};
use std::time::Duration;

use crate::mxc_common::error::WxcError;
use crate::mxc_common::sandbox_process::StreamCloser;
use crate::mxc_common::string_util;

use windows::core::PCWSTR;
use windows::Win32::Foundation::HMODULE;
use windows::Win32::Foundation::{
    CloseHandle, SetHandleInformation, HANDLE, HANDLE_FLAGS, HANDLE_FLAG_INHERIT, WAIT_OBJECT_0,
};
use windows::Win32::Security::{PSID, SECURITY_ATTRIBUTES};
use windows::Win32::Storage::FileSystem::{ReadFile, WriteFile};
use windows::Win32::System::LibraryLoader::{
    GetModuleFileNameW, GetModuleHandleExW, GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
    GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
};
use windows::Win32::System::Pipes::CreatePipe;
use windows::Win32::System::Threading::WaitForSingleObject;
use windows::Win32::System::IO::CancelIoEx;
use windows_core::BOOL;

/// Resolve the loaded module containing `address`.
///
/// Library consumers cannot use [`std::env::current_exe`] to locate native
/// sidecars: a framework-dependent .NET application may load `mxc_ffi.dll`
/// directly from its NuGet runtime-asset directory while `current_exe` points
/// at `dotnet.exe` or the managed application host.
pub fn module_path_for_address(address: *const ()) -> Result<PathBuf, String> {
    let mut module = HMODULE::default();
    unsafe {
        GetModuleHandleExW(
            GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
            PCWSTR(address.cast()),
            &mut module,
        )
    }
    .map_err(|error| format!("failed to locate the loaded module: {error}"))?;

    let mut path = vec![0u16; 32_768];
    let len = unsafe { GetModuleFileNameW(Some(module), &mut path) } as usize;
    if len == 0 {
        return Err(format!(
            "failed to resolve the loaded module path: {}",
            windows::core::Error::from_thread()
        ));
    }
    if len >= path.len() {
        return Err("the loaded module path exceeds the Windows path limit".to_string());
    }
    path.truncate(len);
    Ok(PathBuf::from(std::ffi::OsString::from_wide(&path)))
}

/// A readable end of an anonymous pipe (e.g. the child's stdout/stderr),
/// owning the handle and closing it on drop. Implements [`std::io::Read`]
/// via `ReadFile`; a broken pipe (all write ends closed) reads as EOF.
/// `Send` so it can be handed to a reader thread.
pub struct PipeReader(SendOwnedHandle);

impl PipeReader {
    /// Take ownership of `handle` (invalidating the source `OwnedHandle`).
    pub fn new(mut handle: OwnedHandle) -> Self {
        Self(SendOwnedHandle::take(&mut handle))
    }

    pub fn try_clone_owned_handle(&self) -> std::io::Result<StdOwnedHandle> {
        self.0.try_clone_owned_handle()
    }
}

impl std::io::Read for PipeReader {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        use windows::Win32::Foundation::ERROR_BROKEN_PIPE;
        let mut read: u32 = 0;
        // SAFETY: `self.0` owns a valid pipe handle for the lifetime of this
        // `PipeReader`; `buf`/`read` are valid local out-params for the call.
        match unsafe { ReadFile(self.0.get(), Some(buf), Some(&mut read), None) } {
            Ok(()) => Ok(read as usize),
            // Write ends all closed: normal end-of-stream, report EOF.
            Err(e) if e.code() == ERROR_BROKEN_PIPE.to_hresult() => Ok(0),
            Err(e) => Err(std::io::Error::other(e)),
        }
    }
}

/// Cancellation state shared between an [`InterruptiblePipeReader`] and its
/// [`PipeReadCanceller`]s. Owns the pipe handle — closed only when the **last**
/// reference drops, so a canceller's `CancelIoEx` can never race a closed (and
/// possibly reused) handle — plus the [`ReadGate`] the reader and cancellers
/// hand off through.
struct CancelablePipe {
    handle: SendOwnedHandle,
    gate: Mutex<ReadGate>,
}

/// Reader/canceller handshake, guarded by [`CancelablePipe::gate`].
///
/// `CancelIoEx` is *edge-triggered*: it aborts only I/O already pending when it
/// is called. A bare `cancelled` flag + a single `CancelIoEx` therefore has a
/// lost-wakeup race — a `close` landing between a read's flag check and its
/// `ReadFile` entering the kernel cancels nothing and never retries, parking the
/// read until real EOF. The mutex closes that race by ordering "a read is
/// starting" against "cancel requested": a racing `close` either sees the read
/// has not started (and the read then observes `cancelled`) or sees `reading`
/// and keeps issuing `CancelIoEx` until the read is aborted.
#[derive(Default)]
struct ReadGate {
    /// Set once `close` has been called; a read observing it returns EOF instead
    /// of issuing (or while abandoning) a `ReadFile`.
    cancelled: bool,
    /// True while a read is in — or about to enter — its blocking `ReadFile`, so
    /// `close` knows to keep issuing `CancelIoEx` until that read is aborted.
    reading: bool,
}

impl CancelablePipe {
    /// Lock the gate, tolerating a poisoned mutex (the guarded data is two
    /// bools with no broken invariant on panic).
    fn lock(&self) -> std::sync::MutexGuard<'_, ReadGate> {
        self.gate
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
    }
}

// SAFETY: the only non-`Sync` field is a process-global Windows HANDLE whose
// value is copied for `ReadFile` / `CancelIoEx`; issuing `CancelIoEx` from one
// thread to abort a `ReadFile` blocked on another is the documented, supported
// way to interrupt synchronous pipe I/O, and the reader/canceller handshake is
// serialised by `gate`. So sharing `&CancelablePipe` across threads is sound.
unsafe impl Sync for CancelablePipe {}

/// A readable pipe end (e.g. the child's stdout/stderr) whose blocking
/// `ReadFile` can be cancelled out-of-band via a [`PipeReadCanceller`] —
/// reporting EOF — without closing the child or its other streams. A broken
/// pipe (all write ends closed) still reads as EOF as usual. `Send` so it can
/// be handed to a reader thread. Single-reader: at most one thread may `read` it
/// at a time (any number of cancellers may fire concurrently).
pub struct InterruptiblePipeReader(Arc<CancelablePipe>);

impl InterruptiblePipeReader {
    /// Take ownership of `handle` (invalidating the source `OwnedHandle`).
    pub fn new(mut handle: OwnedHandle) -> Self {
        Self(Arc::new(CancelablePipe {
            handle: SendOwnedHandle::take(&mut handle),
            gate: Mutex::new(ReadGate::default()),
        }))
    }

    /// Mint a closer that EOFs this reader's `read` on demand. Several closers
    /// may be minted; they share one cancellation state. The closer holds only a
    /// [`Weak`] reference, so it never keeps the read handle open past this
    /// reader's lifetime.
    pub fn canceller(&self) -> PipeReadCanceller {
        PipeReadCanceller(Arc::downgrade(&self.0))
    }

    pub fn try_clone_owned_handle(&self) -> std::io::Result<StdOwnedHandle> {
        self.0.handle.try_clone_owned_handle()
    }
}

impl std::io::Read for InterruptiblePipeReader {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        use windows::Win32::Foundation::{ERROR_BROKEN_PIPE, ERROR_OPERATION_ABORTED};
        // Announce the read under the gate: a `close` that already fired makes us
        // EOF without touching the pipe; otherwise mark `reading` so a `close`
        // racing us keeps issuing `CancelIoEx` until our `ReadFile` is aborted.
        {
            let mut gate = self.0.lock();
            if gate.cancelled {
                return Ok(0);
            }
            gate.reading = true;
        }
        let mut read: u32 = 0;
        // SAFETY: the `Arc` keeps the pipe handle valid for this call;
        // `buf`/`read` are valid local out-params.
        let result = unsafe { ReadFile(self.0.handle.get(), Some(buf), Some(&mut read), None) };
        let cancelled = {
            let mut gate = self.0.lock();
            gate.reading = false;
            gate.cancelled
        };
        // If `close` fired while this read was in flight, drop any
        // completed-but-undelivered chunk and report EOF — matching the Unix
        // reader, which never delivers data once cancelled.
        if cancelled {
            return Ok(0);
        }
        match result {
            Ok(()) => Ok(read as usize),
            // Write ends all closed: normal end-of-stream, report EOF.
            Err(e) if e.code() == ERROR_BROKEN_PIPE.to_hresult() => Ok(0),
            // A canceller's `CancelIoEx` aborted this read: report EOF.
            Err(e) if e.code() == ERROR_OPERATION_ABORTED.to_hresult() => Ok(0),
            Err(e) => Err(std::io::Error::other(e)),
        }
    }
}

/// A [`StreamCloser`] for an [`InterruptiblePipeReader`]. Cloneable and
/// `Send + Sync` so a watchdog thread can hold and fire it; all clones share
/// one cancellation state and [`close`](StreamCloser::close) is idempotent.
/// Holds a [`Weak`] reference so a stored canceller never keeps the reader's
/// data-pipe handle open after the reader is dropped.
#[derive(Clone)]
pub struct PipeReadCanceller(Weak<CancelablePipe>);

impl StreamCloser for PipeReadCanceller {
    fn close(&self) {
        // Upgrade to a temporary strong ref for the duration of the cancel. If
        // the reader has already been dropped there is nothing to cancel (and
        // its handle is already closed), so this is a no-op.
        let Some(pipe) = self.0.upgrade() else {
            return;
        };
        // Mark cancelled once (so reads short-circuit to EOF), then abort an
        // in-flight read. Because `CancelIoEx` is edge-triggered, retry while a
        // read is in its announce→`ReadFile` window (`reading == true`): the next
        // iteration catches the `ReadFile` once it enters the kernel. The reader
        // clears `reading` when its `ReadFile` returns (aborted or with data),
        // which bounds the loop; if no read is in progress it exits at once.
        {
            let mut gate = pipe.lock();
            if gate.cancelled {
                return;
            }
            gate.cancelled = true;
        }
        loop {
            // SAFETY: the upgraded `Arc` keeps the handle valid; `CancelIoEx`
            // with a null overlapped aborts all outstanding synchronous I/O on
            // it. Ignore the result — a benign no-op (ERROR_NOT_FOUND) when none
            // is pending.
            unsafe {
                let _ = CancelIoEx(pipe.handle.get(), None);
            }
            if !pipe.lock().reading {
                return;
            }
            std::thread::sleep(Duration::from_millis(1));
        }
    }
}

/// A writable end of an anonymous pipe (e.g. the child's stdin), owning the
/// handle and closing it on drop (which sends EOF to the child). Implements
/// [`std::io::Write`] via `WriteFile`. `Send`.
pub struct PipeWriter(SendOwnedHandle);

impl PipeWriter {
    /// Take ownership of `handle` (invalidating the source `OwnedHandle`).
    pub fn new(mut handle: OwnedHandle) -> Self {
        Self(SendOwnedHandle::take(&mut handle))
    }

    pub fn try_clone_owned_handle(&self) -> std::io::Result<StdOwnedHandle> {
        self.0.try_clone_owned_handle()
    }
}

impl std::io::Write for PipeWriter {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        use windows::Win32::Foundation::ERROR_BROKEN_PIPE;
        let mut written: u32 = 0;
        // SAFETY: `self.0` owns a valid pipe handle for the lifetime of this
        // `PipeWriter`; `buf`/`written` are valid local params for the call.
        match unsafe { WriteFile(self.0.get(), Some(buf), Some(&mut written), None) } {
            Ok(()) => Ok(written as usize),
            // The read end is gone (child exited / closed its stdin): surface the
            // standard `BrokenPipe` kind so callers' graceful handling fires
            // instead of an opaque OS error.
            Err(e) if e.code() == ERROR_BROKEN_PIPE.to_hresult() => {
                Err(std::io::Error::from(std::io::ErrorKind::BrokenPipe))
            }
            Err(e) => Err(std::io::Error::other(e)),
        }
    }

    fn flush(&mut self) -> std::io::Result<()> {
        // Anonymous pipes are not buffered on the writer side.
        Ok(())
    }
}

const BUFFER_SIZE: u32 = 4096;
const MAX_OUTPUT_CHARS: usize = 1024 * 1024;

/// Thread-safe owned handle wrapper that transfers HANDLE ownership across thread boundaries.
/// After construction the source `OwnedHandle` is invalidated, and this wrapper is
/// responsible for closing the handle on drop.
///
/// SAFETY: Windows HANDLEs are process-wide and safe to use from any thread.
pub struct SendOwnedHandle(isize);
unsafe impl Send for SendOwnedHandle {}

impl SendOwnedHandle {
    /// Takes ownership of the handle from an `OwnedHandle`.
    /// The original `OwnedHandle` is invalidated and will not close the handle.
    pub fn take(handle: &mut OwnedHandle) -> Self {
        Self(handle.take().0 as isize)
    }

    pub fn get(&self) -> HANDLE {
        HANDLE(self.0 as *mut core::ffi::c_void)
    }

    fn try_clone_owned_handle(&self) -> std::io::Result<StdOwnedHandle> {
        // SAFETY: this wrapper owns a valid process-wide handle for the
        // duration of the borrow; `try_clone_to_owned` duplicates it.
        let borrowed = unsafe { BorrowedHandle::borrow_raw(self.get().0) };
        borrowed.try_clone_to_owned()
    }
}

impl Drop for SendOwnedHandle {
    fn drop(&mut self) {
        let h = HANDLE(self.0 as *mut core::ffi::c_void);
        if !h.is_invalid() && h != HANDLE::default() {
            unsafe {
                let _ = CloseHandle(h);
            }
        }
    }
}

/// RAII wrapper for a Windows HANDLE that calls CloseHandle on drop.
pub struct OwnedHandle(HANDLE);

impl OwnedHandle {
    pub fn new(h: HANDLE) -> Self {
        Self(h)
    }

    pub fn get(&self) -> HANDLE {
        self.0
    }

    pub fn take(&mut self) -> HANDLE {
        let h = self.0;
        self.0 = HANDLE::default();
        h
    }

    pub fn is_valid(&self) -> bool {
        !self.0.is_invalid() && self.0 != HANDLE::default()
    }

    /// Transfer this handle into the standard library's owning wrapper.
    pub fn try_into_std_owned_handle(mut self) -> std::io::Result<StdOwnedHandle> {
        if !self.is_valid() {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "cannot transfer an invalid Windows handle",
            ));
        }
        let raw = self.take().0;
        // SAFETY: `self` owned this valid handle and was invalidated by
        // `take`, so the returned wrapper becomes its sole owner.
        Ok(unsafe { StdOwnedHandle::from_raw_handle(raw) })
    }
}

impl Drop for OwnedHandle {
    fn drop(&mut self) {
        if self.is_valid() {
            unsafe {
                let _ = CloseHandle(self.0);
            }
        }
    }
}

/// Read all data from a pipe as UTF-8 text, capped at 1MB of characters.
pub fn read_from_pipe(pipe: HANDLE) -> String {
    let mut result = String::with_capacity(BUFFER_SIZE as usize);
    let mut char_count: usize = 0;
    let mut buffer = [0u8; BUFFER_SIZE as usize];
    loop {
        let mut bytes_read = 0u32;
        let ok = unsafe { ReadFile(pipe, Some(&mut buffer), Some(&mut bytes_read), None) };
        if ok.is_err() || bytes_read == 0 {
            break;
        }
        let chunk = String::from_utf8_lossy(&buffer[..bytes_read as usize]);
        let remaining = MAX_OUTPUT_CHARS.saturating_sub(char_count);
        if remaining == 0 {
            break;
        }
        let chunk_char_count = chunk.chars().count();
        if chunk_char_count > remaining {
            // Take only up to `remaining` chars
            let truncated: String = chunk.chars().take(remaining).collect();
            result.push_str(&truncated);
            break;
        }
        result.push_str(&chunk);
        char_count += chunk_char_count;
    }
    result
}

/// Create a pair of pipe handles (read, write) with appropriate inheritance.
/// If `no_inherit_read` is true, the read end is made non-inheritable;
/// otherwise the write end is made non-inheritable.
pub fn create_std_pipes(no_inherit_read: bool) -> Result<(OwnedHandle, OwnedHandle), WxcError> {
    let sa = SECURITY_ATTRIBUTES {
        nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
        bInheritHandle: BOOL::from(true),
        lpSecurityDescriptor: std::ptr::null_mut(),
    };
    let mut h_read = HANDLE::default();
    let mut h_write = HANDLE::default();

    unsafe {
        CreatePipe(&mut h_read, &mut h_write, Some(&sa), 0)
            .map_err(|_| WxcError::Process("Failed to create pipe".into()))?;

        let h_dup = if no_inherit_read { h_read } else { h_write };
        SetHandleInformation(h_dup, HANDLE_FLAG_INHERIT.0, HANDLE_FLAGS(0)).map_err(|_| {
            let _ = CloseHandle(h_read);
            let _ = CloseHandle(h_write);
            WxcError::Process("Failed to set handle information on pipe".into())
        })?;
    }

    Ok((OwnedHandle::new(h_read), OwnedHandle::new(h_write)))
}

/// Create an anonymous pipe whose read and write ends are both non-inheritable.
///
/// This is intended for in-process adapters where neither endpoint should leak
/// into subsequently spawned children.
pub fn create_local_pipe() -> Result<(OwnedHandle, OwnedHandle), WxcError> {
    let mut h_read = HANDLE::default();
    let mut h_write = HANDLE::default();

    // SAFETY: both output pointers are valid local variables. Passing no
    // security attributes creates non-inheritable handles.
    unsafe {
        CreatePipe(&mut h_read, &mut h_write, None, 0)
            .map_err(|error| WxcError::Process(format!("Failed to create local pipe: {error}")))?;
    }

    Ok((OwnedHandle::new(h_read), OwnedHandle::new(h_write)))
}

/// Remove a specific Python "Failed to find real location of ..." line from stderr.
pub fn suppress_python_location_error(stderr: &mut String) {
    let needle = "Failed to find real location of ";
    if let Some(pos) = stderr.find(needle) {
        if let Some(nl) = stderr[pos..].find('\n') {
            stderr.replace_range(pos..pos + nl + 1, "");
        } else {
            stderr.truncate(pos);
        }
    }
}

// ── Captured-output process execution ──────────────────────────────────────

/// Result of running a process with captured stdout/stderr.
#[derive(Debug)]
pub struct CapturedOutput {
    pub stdout: String,
    pub stderr: String,
    pub exit_code: i32,
}

/// Run an external process and capture its stdout/stderr into strings.
/// Uses reader threads to avoid pipe deadlocks, with a configurable timeout.
///
/// `application_name`, when `Some`, is passed verbatim as
/// `lpApplicationName` to `CreateProcessW`. This **disables Windows'
/// executable search order** — the OS will load exactly the binary
/// named, with no fallback to the loader's directory, the CWD, the
/// system directories, or `PATH`. Callers that have an authoritative
/// absolute path (resolved from a probe, e.g. via
/// [`crate::mxc_common::fallback_detector::find_bfscfg_exe`]) should pass it here
/// to defeat executable-search-order hijacking.
///
/// When `application_name` is `None`, the executable is resolved from
/// the first token of `command_line` according to the standard
/// `CreateProcessW` rules — vulnerable to search-order attacks if the
/// first token is a bare name.
///
/// This is used by `FileSystemBfsManager` (for `bfscfg.exe`) and the test
/// driver — anywhere we need to inspect process output rather than relay it.
pub fn run_process_with_captured_output(
    application_name: Option<&str>,
    command_line: &str,
    timeout_ms: u32,
) -> Result<CapturedOutput, WxcError> {
    use windows::Win32::System::Threading::{
        CreateProcessW, GetExitCodeProcess, TerminateProcess, CREATE_NO_WINDOW,
        PROCESS_INFORMATION, STARTF_USESTDHANDLES, STARTUPINFOW,
    };
    use windows_core::{PCWSTR, PWSTR};

    // Create pipes (stdin not connected to anything — child gets EOF)
    let (_stdin_read, _stdin_write) =
        create_std_pipes(false).map_err(|e| WxcError::Process(format!("stdin pipe: {}", e)))?;
    let (mut stdout_read, stdout_write) =
        create_std_pipes(true).map_err(|e| WxcError::Process(format!("stdout pipe: {}", e)))?;
    let (mut stderr_read, stderr_write) =
        create_std_pipes(true).map_err(|e| WxcError::Process(format!("stderr pipe: {}", e)))?;

    let si = STARTUPINFOW {
        cb: std::mem::size_of::<STARTUPINFOW>() as u32,
        dwFlags: STARTF_USESTDHANDLES,
        hStdInput: _stdin_read.get(),
        hStdOutput: stdout_write.get(),
        hStdError: stderr_write.get(),
        ..Default::default()
    };

    let mut cmd_wide = string_util::to_wide(command_line);
    // When `application_name` is `Some`, keep the wide buffer alive for
    // the duration of the `CreateProcessW` call so the `PCWSTR` we pass
    // remains valid.
    let app_wide: Option<Vec<u16>> = application_name.map(string_util::to_wide);
    let app_pcwstr: PCWSTR = match app_wide.as_ref() {
        Some(w) => PCWSTR(w.as_ptr()),
        None => PCWSTR::null(),
    };
    let mut pi = PROCESS_INFORMATION::default();

    unsafe {
        CreateProcessW(
            app_pcwstr,
            Some(PWSTR(cmd_wide.as_mut_ptr())),
            None,
            None,
            true,
            CREATE_NO_WINDOW,
            None,
            PCWSTR::null(),
            &si,
            &mut pi,
        )
        .map_err(|e| WxcError::Process(format!("CreateProcessW failed: {}", e)))?;
    }

    // Close child-side handles in the parent
    drop(_stdin_read);
    drop(stdout_write);
    drop(stderr_write);

    let process_handle = OwnedHandle::new(pi.hProcess);
    let _thread_handle = OwnedHandle::new(pi.hThread);

    // Spawn reader threads (using std::thread — we only need JoinHandle here)
    let stdout_send = SendOwnedHandle::take(&mut stdout_read);
    let stderr_send = SendOwnedHandle::take(&mut stderr_read);

    let stdout_thread = std::thread::spawn(move || read_from_pipe(stdout_send.get()));
    let stderr_thread = std::thread::spawn(move || read_from_pipe(stderr_send.get()));

    // Wait for process with timeout
    let wait_result = unsafe { WaitForSingleObject(process_handle.get(), timeout_ms) };

    if wait_result != WAIT_OBJECT_0 {
        unsafe {
            let _ = TerminateProcess(process_handle.get(), 1);
            // Wait for the OS to confirm the process is gone
            let _ = WaitForSingleObject(process_handle.get(), u32::MAX);
        }
        let _ = stdout_thread.join();
        let _ = stderr_thread.join();
        return Err(WxcError::Process("Process timed out".into()));
    }

    // Give reader threads a grace period (2s) to finish draining
    // We can't use WaitForMultipleObjects here since these are std::thread,
    // so just join with a reasonable expectation they'll finish quickly.
    let stdout_output = stdout_thread.join().unwrap_or_default();
    let stderr_output = stderr_thread.join().unwrap_or_default();

    let mut exit_code: u32 = 0;
    unsafe {
        GetExitCodeProcess(process_handle.get(), &mut exit_code)
            .map_err(|_| WxcError::Process("GetExitCodeProcess failed".into()))?;
    }

    Ok(CapturedOutput {
        stdout: stdout_output,
        stderr: stderr_output,
        exit_code: exit_code as i32,
    })
}

// ── Capability SID helpers ────────────────────────────────────────────────

/// A `SID_AND_ATTRIBUTES`-compatible struct for building capability arrays
/// and loopback exemption lists.
///
/// Using a manual struct avoids issues with conditional availability of
/// `windows::Win32::Security::SID_AND_ATTRIBUTES`.
#[repr(C)]
pub struct SidAndAttributes {
    pub sid: PSID,
    pub attributes: u32,
}

// ── Sibling binary resolution ─────────────────────────────────────────────

/// Return the directory containing the current executable.
pub fn exe_dir() -> Result<PathBuf, WxcError> {
    let exe = std::env::current_exe()
        .map_err(|e| WxcError::Process(format!("cannot determine exe path: {}", e)))?;
    exe.parent()
        .map(|p| p.to_path_buf())
        .ok_or_else(|| WxcError::Process("exe has no parent directory".to_string()))
}

/// Locate a sibling executable next to the current exe.
///
/// Returns the full path if the binary exists, or an error describing
/// where it was expected.
pub fn resolve_sibling_binary(name: &str) -> Result<PathBuf, WxcError> {
    let dir = exe_dir()?;
    let path = dir.join(name);
    if path.exists() {
        Ok(path)
    } else {
        Err(WxcError::Process(format!(
            "{} not found at {}",
            name,
            path.display()
        )))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use windows::Win32::Storage::FileSystem::WriteFile;

    #[test]
    fn module_path_for_address_finds_the_containing_binary() {
        let path = module_path_for_address(
            module_path_for_address_finds_the_containing_binary as *const (),
        )
        .unwrap();
        assert!(
            path.is_file(),
            "resolved module does not exist: {}",
            path.display()
        );
    }

    #[test]
    fn test_captured_output_stdout() {
        let output =
            run_process_with_captured_output(None, "cmd.exe /c echo hello world", 10000).unwrap();
        assert!(output.stdout.trim().contains("hello world"));
        assert_eq!(output.exit_code, 0);
    }

    #[test]
    fn test_captured_output_stderr() {
        let output =
            run_process_with_captured_output(None, "cmd.exe /c echo error_msg 1>&2", 10000)
                .unwrap();
        assert!(output.stderr.trim().contains("error_msg"));
    }

    #[test]
    fn test_captured_output_exit_code() {
        let output = run_process_with_captured_output(None, "cmd.exe /c exit 42", 10000).unwrap();
        assert_eq!(output.exit_code, 42);
    }

    #[test]
    fn test_captured_output_timeout() {
        // Use a very short timeout with a command that sleeps
        let result = run_process_with_captured_output(None, "cmd.exe /c ping -n 10 127.0.0.1", 500);
        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(err_msg.contains("timed out"));
    }

    #[test]
    fn test_read_from_pipe_basic() -> Result<(), Box<dyn std::error::Error>> {
        let (mut read_handle, write_handle) = create_local_pipe()?;
        let test_msg = b"test pipe content";
        let mut bytes_written = 0u32;
        unsafe {
            WriteFile(
                write_handle.get(),
                Some(test_msg),
                Some(&mut bytes_written),
                None,
            )?;
        }
        drop(write_handle);
        let output = read_from_pipe(read_handle.take());
        assert_eq!(output, "test pipe content");
        Ok(())
    }

    #[test]
    fn test_create_std_pipes_no_inherit_read() {
        use windows::Win32::Foundation::GetHandleInformation;

        let (read_handle, write_handle) = create_std_pipes(true).unwrap();
        let mut read_flags = 0u32;
        let mut write_flags = 0u32;
        unsafe {
            GetHandleInformation(read_handle.get(), &mut read_flags).unwrap();
            GetHandleInformation(write_handle.get(), &mut write_flags).unwrap();
        }
        // no_inherit_read=true: read end should NOT be inheritable, write end SHOULD be
        assert_eq!(
            read_flags & HANDLE_FLAG_INHERIT.0,
            0,
            "read end should be non-inheritable"
        );
        assert_ne!(
            write_flags & HANDLE_FLAG_INHERIT.0,
            0,
            "write end should be inheritable"
        );
    }

    #[test]
    fn test_create_std_pipes_no_inherit_write() {
        use windows::Win32::Foundation::GetHandleInformation;

        let (read_handle, write_handle) = create_std_pipes(false).unwrap();
        let mut read_flags = 0u32;
        let mut write_flags = 0u32;
        unsafe {
            GetHandleInformation(read_handle.get(), &mut read_flags).unwrap();
            GetHandleInformation(write_handle.get(), &mut write_flags).unwrap();
        }
        // no_inherit_read=false: read end SHOULD be inheritable, write end should NOT be
        assert_ne!(
            read_flags & HANDLE_FLAG_INHERIT.0,
            0,
            "read end should be inheritable"
        );
        assert_eq!(
            write_flags & HANDLE_FLAG_INHERIT.0,
            0,
            "write end should be non-inheritable"
        );
    }

    #[test]
    fn test_create_local_pipe_is_not_inheritable() -> Result<(), Box<dyn std::error::Error>> {
        use windows::Win32::Foundation::GetHandleInformation;

        let (read_handle, write_handle) = create_local_pipe()?;
        let mut read_flags = 0u32;
        let mut write_flags = 0u32;
        unsafe {
            GetHandleInformation(read_handle.get(), &mut read_flags)?;
            GetHandleInformation(write_handle.get(), &mut write_flags)?;
        }
        assert_eq!(read_flags & HANDLE_FLAG_INHERIT.0, 0);
        assert_eq!(write_flags & HANDLE_FLAG_INHERIT.0, 0);
        Ok(())
    }

    #[test]
    fn test_suppress_python_location_error_removes_line() {
        let mut stderr =
            "Some output\nFailed to find real location of python.exe\nMore output".to_string();
        suppress_python_location_error(&mut stderr);
        assert_eq!(stderr, "Some output\nMore output");
    }

    #[test]
    fn test_suppress_python_location_error_no_match() {
        let mut stderr = "Normal error output".to_string();
        suppress_python_location_error(&mut stderr);
        assert_eq!(stderr, "Normal error output");
    }
}