dure 0.2.1

Detachable Windows console sessions that outlive the terminal
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
//! Windows process, job, and spawn implementation.

use std::collections::HashMap;
use std::ffi::OsString;
use std::fmt::Write;
use std::mem::size_of;
use std::os::windows::ffi::{OsStrExt, OsStringExt};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Mutex, OnceLock};
use std::{env, iter, ptr};

use rand::RngExt;
use windows::Win32::Foundation::{
    CloseHandle, ERROR_ACCESS_DENIED, ERROR_INVALID_PARAMETER, FILETIME, GetLastError, HANDLE,
    INVALID_HANDLE_VALUE, WAIT_OBJECT_0, WAIT_TIMEOUT,
};
use windows::Win32::Storage::FileSystem::SearchPathW;
use windows::Win32::System::Console::HPCON;
use windows::Win32::System::JobObjects::{
    CreateJobObjectW, IsProcessInJob, JOB_OBJECT_LIMIT, JOB_OBJECT_LIMIT_BREAKAWAY_OK,
    JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, JOBOBJECT_EXTENDED_LIMIT_INFORMATION,
    JobObjectExtendedLimitInformation, QueryInformationJobObject, SetInformationJobObject,
};
use windows::Win32::System::Threading::{
    CREATE_BREAKAWAY_FROM_JOB, CREATE_UNICODE_ENVIRONMENT, CreateProcessW, DETACHED_PROCESS,
    DeleteProcThreadAttributeList, EXTENDED_STARTUPINFO_PRESENT, GetCurrentProcess,
    GetCurrentProcessId, GetExitCodeProcess, GetProcessId, GetProcessTimes, INFINITE,
    InitializeProcThreadAttributeList, LPPROC_THREAD_ATTRIBUTE_LIST, OpenProcess,
    PROC_THREAD_ATTRIBUTE_JOB_LIST, PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, PROCESS_ACCESS_RIGHTS,
    PROCESS_INFORMATION, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SYNCHRONIZE, PROCESS_TERMINATE,
    STARTF_USESTDHANDLES, STARTUPINFOEXW, STARTUPINFOW, TerminateProcess,
    UpdateProcThreadAttribute, WaitForSingleObject,
};
use windows::core::{BOOL, PCWSTR, PWSTR};

use crate::constants::TERMINATE_TIMEOUT;
use crate::durability::Durability;
use crate::pal::error::{PalError, PalErrorKind};
use crate::pal::ids::{AppId, JobId};
use crate::pal::processes::{
    AppSpawn, Breakaway, ProcessLiveness, Processes, SupervisorSpawn, resolve_command_path,
    windows_command_line,
};
use crate::pal::pseudoconsole::hpcon_for;
use crate::pal::raw_handle::RawHandle;
use crate::session_record::ProcessIdentity;

/// Real Windows process control.
#[derive(Debug, Default)]
pub(crate) struct BuildTargetProcesses;

struct HandleTable {
    jobs: HashMap<u64, Vec<RawHandle>>,
    apps: HashMap<u64, RawHandle>,
}

fn table() -> &'static Mutex<HandleTable> {
    static TABLE: OnceLock<Mutex<HandleTable>> = OnceLock::new();
    TABLE.get_or_init(|| {
        Mutex::new(HandleTable {
            jobs: HashMap::new(),
            apps: HashMap::new(),
        })
    })
}

fn next_id() -> u64 {
    static NEXT: AtomicU64 = AtomicU64::new(1);
    NEXT.fetch_add(1, Ordering::Relaxed)
}

/// Pseudoconsole plus lifetime job, both applied at `CreateProcessW`.
const APP_SPAWN_ATTRIBUTE_COUNT: u32 = 2;

fn filetime_u64(time: FILETIME) -> u64 {
    let high = u64::from(time.dwHighDateTime);
    let low = u64::from(time.dwLowDateTime);
    high.checked_shl(32)
        .expect("shifting a u32 into the high half of a u64 cannot overflow")
        | low
}

fn identity_of(handle: HANDLE) -> Result<ProcessIdentity, PalError> {
    let pid = {
        // SAFETY: `handle` is a valid process handle owned by the caller.
        unsafe { GetProcessId(handle) }
    };
    if pid == 0 {
        return Err(PalError::new(PalErrorKind::InspectFailed));
    }
    let mut creation = FILETIME::default();
    let mut exit = FILETIME::default();
    let mut kernel = FILETIME::default();
    let mut user = FILETIME::default();
    // SAFETY: all FILETIME pointers refer to stack values that outlive the call.
    unsafe {
        GetProcessTimes(
            handle,
            &raw mut creation,
            &raw mut exit,
            &raw mut kernel,
            &raw mut user,
        )
    }
    .map_err(|_error| PalError::new(PalErrorKind::InspectFailed))?;
    Ok(ProcessIdentity {
        pid,
        creation_time: filetime_u64(creation),
    })
}

fn open_verified(
    identity: &ProcessIdentity,
    access: PROCESS_ACCESS_RIGHTS,
) -> Result<HANDLE, PalError> {
    // SAFETY: pid is a numeric process id; OpenProcess does not retain aliasing
    // of Rust references.
    let opened = unsafe { OpenProcess(access, false, identity.pid) };
    let Ok(handle) = opened else {
        // SAFETY: immediately after the failed OpenProcess.
        let err = unsafe { GetLastError() };
        // A missing pid is NotFound (stale record). Access-denied and other
        // failures are InspectFailed so GC does not drop a live supervisor.
        if err == ERROR_INVALID_PARAMETER {
            return Err(PalError::new(PalErrorKind::NotFound));
        }
        return Err(PalError::new(PalErrorKind::InspectFailed));
    };
    match identity_of(handle) {
        Ok(actual) if actual.creation_time == identity.creation_time => Ok(handle),
        Ok(_) => {
            close(handle);
            Err(PalError::new(PalErrorKind::NotFound))
        }
        Err(error) => {
            close(handle);
            Err(error)
        }
    }
}

fn close(handle: HANDLE) {
    // SAFETY: `handle` is a process or job handle we own and never use again.
    _ = unsafe { CloseHandle(handle) };
}

/// Resolves a bare command name through the standard executable search order.
///
/// `CreateProcessW` performs no search when `lpApplicationName` is supplied, so
/// a bare `copilot.exe` would otherwise only be found in the launch directory.
/// Anything that already names a directory, and anything the search cannot
/// find, is returned unchanged so `CreateProcessW` reports the failure.
fn search_executable(exe: &Path) -> PathBuf {
    if exe.components().count() != 1 {
        return exe.to_path_buf();
    }
    let name = wide(&exe.to_string_lossy());
    // Applied only when the name carries no extension of its own, which is what
    // makes `dure run -- copilot` behave like typing it in the shell.
    let extension = wide(".exe");
    // Long enough for a traditional path; a longer result is retried at the
    // size the first call reports.
    let mut buf = vec![0_u16; 260];
    for _attempt in 0..2_u8 {
        // SAFETY: `name` and `extension` are NUL-terminated and are not retained
        // after the call. `buf` is exclusive for the call and its own length is
        // what bounds the write.
        let len = unsafe {
            SearchPathW(
                PCWSTR::null(),
                PCWSTR(name.as_ptr()),
                PCWSTR(extension.as_ptr()),
                Some(&mut buf),
                None,
            )
        } as usize;
        if len == 0 {
            break;
        }
        if len < buf.len() {
            return buf.get(..len).map_or_else(
                || exe.to_path_buf(),
                |found| PathBuf::from(OsString::from_wide(found)),
            );
        }
        buf = vec![0_u16; len];
    }
    exe.to_path_buf()
}

fn wide(s: &str) -> Vec<u16> {
    OsString::from(s)
        .encode_wide()
        .chain(iter::once(0))
        .collect()
}

/// Whether `process` belongs to any job object.
fn process_in_a_job(process: HANDLE) -> Result<bool, PalError> {
    let mut in_job = BOOL::default();
    // SAFETY: `process` is a valid process handle, a null job asks about any
    // job, and `in_job` outlives the call.
    unsafe { IsProcessInJob(process, None, &raw mut in_job) }
        .map_err(|_error| PalError::new(PalErrorKind::InspectFailed))?;
    Ok(in_job.as_bool())
}

/// What is known about the limits of the job this process is directly in.
///
/// Membership and limits are separate questions with separate failure modes, and
/// callers answer an unreadable job differently from no job at all.
enum JobLimits {
    /// The process belongs to no job object.
    None,
    /// The process belongs to a job whose limits could not be read.
    Unknown,
    /// The limit flags of the job the process is directly in.
    Known(JOB_OBJECT_LIMIT),
}

/// Read the limits of the job this process is directly in.
///
/// Windows reports only the immediate job, and only to the process itself, so
/// this says nothing about any ancestor job.
/// Ref: docs/implementation.md, "Job breakaway".
#[cfg_attr(coverage_nightly, coverage(off))]
fn immediate_job_limits() -> JobLimits {
    // SAFETY: the pseudo-handle this returns needs no state and is always valid.
    let current = unsafe { GetCurrentProcess() };
    match process_in_a_job(current) {
        Ok(false) => return JobLimits::None,
        Ok(true) => {}
        Err(_error) => return JobLimits::Unknown,
    }
    let mut info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
    // SAFETY: a null job handle asks about the job this process is directly in,
    // and `info` is a stack structure of the size the information class expects.
    let queried = unsafe {
        QueryInformationJobObject(
            None,
            JobObjectExtendedLimitInformation,
            ptr::from_mut(&mut info).cast(),
            u32::try_from(size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>())
                .expect("job info size fits in u32"),
            None,
        )
    };
    if queried.is_err() {
        return JobLimits::Unknown;
    }
    JobLimits::Known(info.BasicLimitInformation.LimitFlags)
}

/// Whether the job this process is directly in would refuse it a breakaway.
///
/// Windows reports a refused breakaway as a plain access-denied error, and an
/// unreadable image reports the same thing. Only a job that withholds
/// `JOB_OBJECT_LIMIT_BREAKAWAY_OK` can have refused one, so this is what tells
/// the two apart. A job whose limits cannot be read is assumed to be the cause,
/// because a process outside a job never sees this question at all.
#[cfg_attr(coverage_nightly, coverage(off))]
fn breakaway_forbidden() -> bool {
    match immediate_job_limits() {
        JobLimits::None => false,
        JobLimits::Unknown => true,
        JobLimits::Known(flags) => (flags & JOB_OBJECT_LIMIT_BREAKAWAY_OK).0 == 0,
    }
}

#[cfg_attr(coverage_nightly, coverage(off))]
#[cfg_attr(test, mutants::skip)]
impl BuildTargetProcesses {
    /// Create an unnamed kill-on-close job with the requested breakaway policy.
    ///
    /// Ref: docs/implementation.md, "Job breakaway".
    pub(crate) fn create_job(breakaway: Breakaway) -> Result<JobId, PalError> {
        Self::create_job_chain(&[breakaway])
    }

    /// Create a chain of nested jobs, outermost first.
    ///
    /// A process spawned into the chain joins every job in it, so the last
    /// policy is the one its breakaway is evaluated against and the earlier ones
    /// stay behind as ancestors.
    ///
    /// Ref: docs/implementation.md, "Job breakaway".
    pub(crate) fn create_job_chain(policies: &[Breakaway]) -> Result<JobId, PalError> {
        let mut handles = Vec::with_capacity(policies.len());
        for breakaway in policies {
            match create_job_handle(*breakaway) {
                Ok(handle) => handles.push(RawHandle::from_handle(handle)),
                Err(error) => {
                    // A partly built chain owns handles no id names yet, so it
                    // can only be released here.
                    for handle in handles {
                        close(handle.as_handle());
                    }
                    return Err(error);
                }
            }
        }
        let id = next_id();
        table()
            .lock()
            .expect("handle table")
            .jobs
            .insert(id, handles);
        Ok(JobId(id))
    }
}

#[cfg_attr(coverage_nightly, coverage(off))]
fn create_job_handle(breakaway: Breakaway) -> Result<HANDLE, PalError> {
    // SAFETY: a null name creates an unnamed job object.
    let handle = unsafe { CreateJobObjectW(None, PCWSTR::null()) }
        .map_err(|_error| PalError::new(PalErrorKind::Other))?;
    let mut info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
    info.BasicLimitInformation.LimitFlags = match breakaway {
        Breakaway::Permitted => JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | JOB_OBJECT_LIMIT_BREAKAWAY_OK,
        #[cfg(feature = "private-test-util")]
        Breakaway::Forbidden => JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
    };
    // SAFETY: `info` is a stack structure of the size SetInformationJobObject
    // expects for JobObjectExtendedLimitInformation.
    let configured = unsafe {
        SetInformationJobObject(
            handle,
            JobObjectExtendedLimitInformation,
            ptr::from_mut(&mut info).cast(),
            u32::try_from(size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>())
                .expect("job info size fits in u32"),
        )
    };
    if configured.is_err() {
        // The job exists but does not have the limits the caller asked for, so
        // it is never returned and nothing else can close it.
        // SAFETY: `handle` is the job just created and is not used again.
        unsafe {
            _ = CloseHandle(handle);
        }
        return Err(PalError::new(PalErrorKind::Other));
    }
    Ok(handle)
}

#[cfg_attr(coverage_nightly, coverage(off))]
#[cfg_attr(test, mutants::skip)]
impl Processes for BuildTargetProcesses {
    fn current_exe(&self) -> Result<PathBuf, PalError> {
        env::current_exe().map_err(PalError::from_io)
    }

    fn spawn_supervisor(&self, request: &SupervisorSpawn) -> Result<ProcessIdentity, PalError> {
        let mut cmd_wide = wide(&windows_command_line(
            &request.exe.to_string_lossy(),
            &request.args,
        ));
        let mut exe_wide = wide(&request.exe.to_string_lossy());
        let si = STARTUPINFOW {
            cb: u32::try_from(size_of::<STARTUPINFOW>()).expect("STARTUPINFOW fits in u32"),
            ..Default::default()
        };
        let mut pi = PROCESS_INFORMATION::default();
        let flags = CREATE_BREAKAWAY_FROM_JOB | DETACHED_PROCESS | CREATE_UNICODE_ENVIRONMENT;
        // SAFETY: `exe_wide` and `cmd_wide` are NUL-terminated. `si`/`pi` are
        // valid stack structures. No handle inherit list is passed because the
        // startup channel is a named pipe connected by name after spawn.
        let created = unsafe {
            CreateProcessW(
                PCWSTR(exe_wide.as_mut_ptr()),
                Some(PWSTR(cmd_wide.as_mut_ptr())),
                None,
                None,
                false,
                flags,
                None,
                None,
                &raw const si,
                &raw mut pi,
            )
        };
        created.map_err(|error| {
            // Windows reports a refused breakaway as plain access-denied, which
            // an unreadable image produces too. The job's breakaway policy
            // separates the two, so `run` can name the cause instead of
            // guessing at it.
            if error.code() == ERROR_ACCESS_DENIED.to_hresult() && breakaway_forbidden() {
                PalError::new(PalErrorKind::BreakawayDenied)
            } else {
                PalError::new(PalErrorKind::Other)
            }
        })?;
        close(pi.hThread);
        // Closed on both paths: an early return here would leave the detached
        // supervisor holding an unreferenced handle in this process.
        let identity = identity_of(pi.hProcess);
        close(pi.hProcess);
        identity
    }

    fn durability(&self) -> Durability {
        match immediate_job_limits() {
            JobLimits::None => Durability::Durable,
            // An unanswerable query is reported as the cautious answer: a
            // spurious warning costs the user a line of text, a missed one
            // costs a session.
            JobLimits::Unknown => Durability::TiedToLauncher,
            // Only kill-on-close ties this process's lifetime to the launcher's
            // job. Membership in a job without it is harmless, and terminals and
            // remote session hosts routinely impose such a job on everything
            // they start.
            JobLimits::Known(flags) => {
                if (flags & JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE).0 == 0 {
                    Durability::Durable
                } else {
                    Durability::TiedToLauncher
                }
            }
        }
    }

    fn probe(&self, identity: &ProcessIdentity) -> ProcessLiveness {
        let access = PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_SYNCHRONIZE;
        let handle = match open_verified(identity, access) {
            Ok(handle) => handle,
            Err(error) if error.kind() == PalErrorKind::NotFound => return ProcessLiveness::Dead,
            Err(_) => return ProcessLiveness::InspectFailed,
        };
        // SAFETY: `handle` is a process handle opened with SYNCHRONIZE. Zero
        // timeout distinguishes still-running (`WAIT_TIMEOUT`) from already
        // exited (`WAIT_OBJECT_0`). Exit code 259 is a valid exited status and
        // must not be treated as live.
        let wait = unsafe { WaitForSingleObject(handle, 0) };
        close(handle);
        if wait == WAIT_TIMEOUT {
            ProcessLiveness::Live
        } else if wait == WAIT_OBJECT_0 {
            ProcessLiveness::Dead
        } else {
            ProcessLiveness::InspectFailed
        }
    }

    fn terminate(&self, identity: &ProcessIdentity) -> Result<(), PalError> {
        let access = PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_SYNCHRONIZE | PROCESS_TERMINATE;
        let handle = open_verified(identity, access).map_err(|error| {
            if error.kind() == PalErrorKind::NotFound {
                PalError::new(PalErrorKind::NotFound)
            } else {
                PalError::new(PalErrorKind::InspectFailed)
            }
        })?;
        // SAFETY: `handle` is a process handle opened with PROCESS_TERMINATE
        // and verified to be the recorded process.
        let result = unsafe { TerminateProcess(handle, 1) };
        let settled = if result.is_ok() {
            // Termination is asynchronous. Reporting success while the process
            // still runs would let `kill` delete the record and reuse the id
            // while the old supervisor can still publish an attached flag and
            // recreate it, so wait for the process object to signal.
            // SAFETY: `handle` is a process handle opened with SYNCHRONIZE.
            let wait = unsafe {
                WaitForSingleObject(
                    handle,
                    u32::try_from(TERMINATE_TIMEOUT.as_millis())
                        .expect("terminate timeout fits in u32 milliseconds"),
                )
            };
            wait == WAIT_OBJECT_0
        } else {
            false
        };
        close(handle);
        result.map_err(|_error| PalError::new(PalErrorKind::Other))?;
        if settled {
            Ok(())
        } else {
            Err(PalError::new(PalErrorKind::Other))
        }
    }

    fn create_lifetime_job(&self) -> Result<JobId, PalError> {
        // The session job permits breakaway so a nested `dure run` inside the
        // app can still create an independent inner supervisor.
        // Ref: docs/implementation.md, "Job breakaway".
        Self::create_job(Breakaway::Permitted)
    }

    fn close_job(&self, job: JobId) {
        if let Some(handles) = table().lock().expect("handle table").jobs.remove(&job.0) {
            // Innermost first, so a kill-on-close ancestor never tears down a
            // job this still holds a handle to.
            for handle in handles.into_iter().rev() {
                close(handle.as_handle());
            }
        }
    }

    fn spawn_app(&self, request: &AppSpawn) -> Result<AppId, PalError> {
        let hpcon = hpcon_for(request.pty).ok_or_else(|| PalError::new(PalErrorKind::NotFound))?;
        let exe = search_executable(&resolve_command_path(
            request
                .command
                .first()
                .ok_or_else(|| PalError::new(PalErrorKind::Other))?,
            &request.launch_directory,
        ));
        let rest = request.command.get(1..).unwrap_or(&[]);
        let mut cmd_wide = wide(&windows_command_line(&exe.to_string_lossy(), rest));
        let mut exe_wide = wide(&exe.to_string_lossy());
        let mut dir_wide = wide(&request.launch_directory.to_string_lossy());

        // Outermost first: a process is assigned to the jobs in the order the
        // attribute lists them, which is what nests them.
        let mut job_list = table()
            .lock()
            .expect("handle table")
            .jobs
            .get(&request.job.0)
            .ok_or_else(|| PalError::new(PalErrorKind::NotFound))?
            .iter()
            .map(|handle| handle.as_handle())
            .collect::<Vec<_>>();

        // Pseudoconsole and lifetime job, both applied at CreateProcessW so the
        // app cannot run outside the job. CREATE_SUSPENDED plus a later
        // AssignProcessToJobObject delays console initialization and can leave
        // the child with pipes instead of a console.
        let attribute_count = APP_SPAWN_ATTRIBUTE_COUNT;
        let mut attr_size: usize = 0;
        // SAFETY: querying the required size; the null list pointer is allowed
        // when discovering the buffer length.
        _ = unsafe {
            InitializeProcThreadAttributeList(None, attribute_count, None, &raw mut attr_size)
        };
        let mut attr_buf = vec![0_u8; attr_size];
        let attr_list = LPPROC_THREAD_ATTRIBUTE_LIST(attr_buf.as_mut_ptr().cast());
        // SAFETY: `attr_buf` is the size reported by the previous call and lives
        // for the rest of this function.
        unsafe {
            InitializeProcThreadAttributeList(
                Some(attr_list),
                attribute_count,
                None,
                &raw mut attr_size,
            )
        }
        .map_err(|_error| PalError::new(PalErrorKind::Other))?;

        // PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE stores `lpValue` as the HPCON
        // itself. The Microsoft sample passes `hPC`, not `&hPC`.
        // Ref: https://learn.microsoft.com/windows/console/creating-a-pseudoconsole-session
        let hpcon_value = hpcon.0 as *const core::ffi::c_void;
        // SAFETY: the attribute list was initialized for two attributes. `hpcon`
        // is a live HPCON owned by the pseudoconsole PAL for `request.pty`.
        unsafe {
            UpdateProcThreadAttribute(
                attr_list,
                0,
                usize::try_from(PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE)
                    .expect("PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE fits in usize"),
                Some(hpcon_value),
                size_of::<HPCON>(),
                None,
                None,
            )
        }
        .map_err(|_error| PalError::new(PalErrorKind::Other))?;

        // SAFETY: the list still has a free slot. `job_list` holds the lifetime
        // job handles and lives until CreateProcessW returns.
        unsafe {
            UpdateProcThreadAttribute(
                attr_list,
                0,
                usize::try_from(PROC_THREAD_ATTRIBUTE_JOB_LIST)
                    .expect("PROC_THREAD_ATTRIBUTE_JOB_LIST fits in usize"),
                Some(job_list.as_mut_ptr().cast()),
                size_of::<HANDLE>()
                    .checked_mul(job_list.len())
                    .expect("job handle list size fits in usize"),
                None,
                None,
            )
        }
        .map_err(|_error| PalError::new(PalErrorKind::Other))?;

        let mut si = STARTUPINFOEXW::default();
        si.StartupInfo.cb =
            u32::try_from(size_of::<STARTUPINFOEXW>()).expect("STARTUPINFOEXW fits in u32");
        // Parent stdio is often redirected (SSH, `cargo test`). CreateProcess
        // copies those handle values into the child unless STARTF_USESTDHANDLES
        // overrides them, and the pseudoconsole attribute does not displace an
        // inherited value. Invalid std handles are what leaves the pseudoconsole
        // free to install console handles instead: without this the child sees
        // pipes, which the `helper_sees_a_console` integration test observes
        // directly.
        si.StartupInfo.dwFlags = STARTF_USESTDHANDLES;
        si.StartupInfo.hStdInput = INVALID_HANDLE_VALUE;
        si.StartupInfo.hStdOutput = INVALID_HANDLE_VALUE;
        si.StartupInfo.hStdError = INVALID_HANDLE_VALUE;
        si.lpAttributeList = attr_list;
        let mut pi = PROCESS_INFORMATION::default();
        let flags = EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT;
        // SAFETY: wide strings are NUL-terminated. Attribute list is initialized
        // with the pseudoconsole and job. Std handles are invalid so they are
        // not the parent's redirected pipes.
        let created = unsafe {
            CreateProcessW(
                PCWSTR(exe_wide.as_mut_ptr()),
                Some(PWSTR(cmd_wide.as_mut_ptr())),
                None,
                None,
                false,
                flags,
                None,
                PCWSTR(dir_wide.as_mut_ptr()),
                ptr::from_ref(&si.StartupInfo),
                &raw mut pi,
            )
        };
        // SAFETY: the list was initialized above and is no longer referenced by
        // the kernel after CreateProcessW returns.
        unsafe {
            DeleteProcThreadAttributeList(attr_list);
        }
        created.map_err(|_error| PalError::new(PalErrorKind::Other))?;

        close(pi.hThread);
        let id = next_id();
        table()
            .lock()
            .expect("handle table")
            .apps
            .insert(id, RawHandle::from_handle(pi.hProcess));
        Ok(AppId(id))
    }

    fn wait_app(&self, app: AppId) -> Result<i32, PalError> {
        let handle = table()
            .lock()
            .expect("handle table")
            .apps
            .get(&app.0)
            .copied()
            .ok_or_else(|| PalError::new(PalErrorKind::NotFound))?
            .as_handle();
        // SAFETY: `handle` is a process handle stored in the table.
        let wait = unsafe { WaitForSingleObject(handle, INFINITE) };
        if wait != WAIT_OBJECT_0 {
            return Err(PalError::new(PalErrorKind::Other));
        }
        let mut code = 0_u32;
        // SAFETY: the process has exited; `code` is a stack u32.
        unsafe { GetExitCodeProcess(handle, &raw mut code) }
            .map_err(|_error| PalError::new(PalErrorKind::Other))?;
        // Windows process statuses are `u32`; NTSTATUS-style failure codes use
        // the high bit and do not fit in a non-negative `i32`.
        Ok(code.cast_signed())
    }

    fn current_identity(&self) -> Result<ProcessIdentity, PalError> {
        // SAFETY: GetCurrentProcess returns a pseudo-handle that does not need
        // to be closed and is valid for the calling process.
        let handle = unsafe { GetCurrentProcess() };
        let mut identity = identity_of(handle)?;
        identity.pid = {
            // SAFETY: no preconditions.
            unsafe { GetCurrentProcessId() }
        };
        Ok(identity)
    }

    fn random_nonce(&self) -> String {
        // 128 bits of CSPRNG output, encoded as hex. This only has to be unique
        // among concurrent sessions for this user, not unguessable to other
        // users (the pipe ACL already restricts the creating user).
        let bytes: [u8; 16] = rand::rng().random();
        let mut nonce = String::with_capacity(32);
        for byte in bytes {
            write!(nonce, "{byte:02x}").expect("writing to String cannot fail");
        }
        nonce
    }
}