Skip to main content

std/os/windows/
process.rs

1//! Windows-specific extensions to primitives in the [`std::process`] module.
2//!
3//! [`std::process`]: crate::process
4
5#![stable(feature = "process_extensions", since = "1.2.0")]
6
7use crate::ffi::{OsStr, c_void};
8use crate::macros::rustdoc_skip_body;
9use crate::mem::MaybeUninit;
10use crate::os::windows::io::{
11    AsHandle, AsRawHandle, BorrowedHandle, FromRawHandle, IntoRawHandle, OwnedHandle, RawHandle,
12};
13use crate::sys::{AsInner, AsInnerMut, FromInner, IntoInner};
14use crate::{io, marker, process, ptr, sys};
15
16#[stable(feature = "process_extensions", since = "1.2.0")]
17impl FromRawHandle for process::Stdio {
18    #[rustdoc_skip_body]
19    unsafe fn from_raw_handle(handle: RawHandle) -> process::Stdio {
20        let handle = unsafe { sys::handle::Handle::from_raw_handle(handle as *mut _) };
21        let io = sys::process::Stdio::Handle(handle);
22        process::Stdio::from_inner(io)
23    }
24}
25
26#[stable(feature = "io_safety", since = "1.63.0")]
27impl From<OwnedHandle> for process::Stdio {
28    /// Takes ownership of a handle and returns a [`Stdio`](process::Stdio)
29    /// that can attach a stream to it.
30    #[rustdoc_skip_body]
31    fn from(handle: OwnedHandle) -> process::Stdio {
32        let handle = sys::handle::Handle::from_inner(handle);
33        let io = sys::process::Stdio::Handle(handle);
34        process::Stdio::from_inner(io)
35    }
36}
37
38#[stable(feature = "process_extensions", since = "1.2.0")]
39impl AsRawHandle for process::Child {
40    #[inline]
41    #[rustdoc_skip_body]
42    fn as_raw_handle(&self) -> RawHandle {
43        self.as_inner().handle().as_raw_handle() as *mut _
44    }
45}
46
47#[stable(feature = "io_safety", since = "1.63.0")]
48impl AsHandle for process::Child {
49    #[inline]
50    #[rustdoc_skip_body]
51    fn as_handle(&self) -> BorrowedHandle<'_> {
52        self.as_inner().handle().as_handle()
53    }
54}
55
56#[stable(feature = "into_raw_os", since = "1.4.0")]
57impl IntoRawHandle for process::Child {
58    #[rustdoc_skip_body]
59    fn into_raw_handle(self) -> RawHandle {
60        self.into_inner().into_handle().into_raw_handle() as *mut _
61    }
62}
63
64#[stable(feature = "io_safety", since = "1.63.0")]
65impl From<process::Child> for OwnedHandle {
66    /// Takes ownership of a [`Child`](process::Child)'s process handle.
67    #[rustdoc_skip_body]
68    fn from(child: process::Child) -> OwnedHandle {
69        child.into_inner().into_handle().into_inner()
70    }
71}
72
73#[stable(feature = "process_extensions", since = "1.2.0")]
74impl AsRawHandle for process::ChildStdin {
75    #[inline]
76    #[rustdoc_skip_body]
77    fn as_raw_handle(&self) -> RawHandle {
78        self.as_inner().handle().as_raw_handle() as *mut _
79    }
80}
81
82#[stable(feature = "process_extensions", since = "1.2.0")]
83impl AsRawHandle for process::ChildStdout {
84    #[inline]
85    #[rustdoc_skip_body]
86    fn as_raw_handle(&self) -> RawHandle {
87        self.as_inner().handle().as_raw_handle() as *mut _
88    }
89}
90
91#[stable(feature = "process_extensions", since = "1.2.0")]
92impl AsRawHandle for process::ChildStderr {
93    #[inline]
94    #[rustdoc_skip_body]
95    fn as_raw_handle(&self) -> RawHandle {
96        self.as_inner().handle().as_raw_handle() as *mut _
97    }
98}
99
100#[stable(feature = "into_raw_os", since = "1.4.0")]
101impl IntoRawHandle for process::ChildStdin {
102    #[rustdoc_skip_body]
103    fn into_raw_handle(self) -> RawHandle {
104        self.into_inner().into_handle().into_raw_handle() as *mut _
105    }
106}
107
108#[stable(feature = "into_raw_os", since = "1.4.0")]
109impl IntoRawHandle for process::ChildStdout {
110    #[rustdoc_skip_body]
111    fn into_raw_handle(self) -> RawHandle {
112        self.into_inner().into_handle().into_raw_handle() as *mut _
113    }
114}
115
116#[stable(feature = "into_raw_os", since = "1.4.0")]
117impl IntoRawHandle for process::ChildStderr {
118    #[rustdoc_skip_body]
119    fn into_raw_handle(self) -> RawHandle {
120        self.into_inner().into_handle().into_raw_handle() as *mut _
121    }
122}
123
124/// Creates a `ChildStdin` from the provided `OwnedHandle`.
125///
126/// The provided handle must be asynchronous, as reading and
127/// writing from and to it is implemented using asynchronous APIs.
128#[stable(feature = "child_stream_from_fd", since = "1.74.0")]
129impl From<OwnedHandle> for process::ChildStdin {
130    #[rustdoc_skip_body]
131    fn from(handle: OwnedHandle) -> process::ChildStdin {
132        let handle = sys::handle::Handle::from_inner(handle);
133        let pipe = sys::process::ChildPipe::from_inner(handle);
134        process::ChildStdin::from_inner(pipe)
135    }
136}
137
138/// Creates a `ChildStdout` from the provided `OwnedHandle`.
139///
140/// The provided handle must be asynchronous, as reading and
141/// writing from and to it is implemented using asynchronous APIs.
142#[stable(feature = "child_stream_from_fd", since = "1.74.0")]
143impl From<OwnedHandle> for process::ChildStdout {
144    #[rustdoc_skip_body]
145    fn from(handle: OwnedHandle) -> process::ChildStdout {
146        let handle = sys::handle::Handle::from_inner(handle);
147        let pipe = sys::process::ChildPipe::from_inner(handle);
148        process::ChildStdout::from_inner(pipe)
149    }
150}
151
152/// Creates a `ChildStderr` from the provided `OwnedHandle`.
153///
154/// The provided handle must be asynchronous, as reading and
155/// writing from and to it is implemented using asynchronous APIs.
156#[stable(feature = "child_stream_from_fd", since = "1.74.0")]
157impl From<OwnedHandle> for process::ChildStderr {
158    #[rustdoc_skip_body]
159    fn from(handle: OwnedHandle) -> process::ChildStderr {
160        let handle = sys::handle::Handle::from_inner(handle);
161        let pipe = sys::process::ChildPipe::from_inner(handle);
162        process::ChildStderr::from_inner(pipe)
163    }
164}
165
166/// Windows-specific extensions to [`process::ExitStatus`].
167#[stable(feature = "exit_status_from", since = "1.12.0")]
168pub impl(self) trait ExitStatusExt {
169    /// Creates a new `ExitStatus` from the raw underlying `u32` return value of
170    /// a process.
171    #[stable(feature = "exit_status_from", since = "1.12.0")]
172    fn from_raw(raw: u32) -> Self;
173}
174
175#[stable(feature = "exit_status_from", since = "1.12.0")]
176impl ExitStatusExt for process::ExitStatus {
177    #[rustdoc_skip_body]
178    fn from_raw(raw: u32) -> Self {
179        process::ExitStatus::from_inner(From::from(raw))
180    }
181}
182
183/// Windows-specific extensions to the [`process::Command`] builder.
184#[stable(feature = "windows_process_extensions", since = "1.16.0")]
185pub impl(self) trait CommandExt {
186    /// Sets the [process creation flags][1] to be passed to `CreateProcess`.
187    ///
188    /// These will always be ORed with `CREATE_UNICODE_ENVIRONMENT`.
189    ///
190    /// [1]: https://docs.microsoft.com/en-us/windows/win32/procthread/process-creation-flags
191    #[stable(feature = "windows_process_extensions", since = "1.16.0")]
192    fn creation_flags(&mut self, flags: u32) -> &mut process::Command;
193
194    /// Places the child process on the desktop named `desktop` by setting the
195    /// `lpDesktop` field of the [STARTUPINFO][1] passed to `CreateProcess`.
196    ///
197    /// The name may be a desktop or a `window-station\desktop` path.
198    ///
199    /// [1]: <https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/ns-processthreadsapi-startupinfow>
200    #[unstable(feature = "windows_process_extensions_desktop", issue = "158852")]
201    fn desktop<S: AsRef<OsStr>>(&mut self, desktop: S) -> &mut process::Command;
202
203    /// Sets the field `wShowWindow` of [STARTUPINFO][1] that is passed to `CreateProcess`.
204    /// Allowed values are the ones listed in
205    /// <https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-showwindow>
206    ///
207    /// [1]: <https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/ns-processthreadsapi-startupinfow>
208    #[stable(feature = "windows_process_extensions_show_window", since = "1.100.0")]
209    fn show_window(&mut self, cmd_show: u16) -> &mut process::Command;
210
211    /// Forces all arguments to be wrapped in quote (`"`) characters.
212    ///
213    /// This is useful for passing arguments to [MSYS2/Cygwin][1] based
214    /// executables: these programs will expand unquoted arguments containing
215    /// wildcard characters (`?` and `*`) by searching for any file paths
216    /// matching the wildcard pattern.
217    ///
218    /// Adding quotes has no effect when passing arguments to programs
219    /// that use [msvcrt][2]. This includes programs built with both
220    /// MinGW and MSVC.
221    ///
222    /// [1]: <https://github.com/msys2/MSYS2-packages/issues/2176>
223    /// [2]: <https://msdn.microsoft.com/en-us/library/17w5ykft.aspx>
224    #[unstable(feature = "windows_process_extensions_force_quotes", issue = "82227")]
225    fn force_quotes(&mut self, enabled: bool) -> &mut process::Command;
226
227    /// Append literal text to the command line without any quoting or escaping.
228    ///
229    /// This is useful for passing arguments to applications that don't follow
230    /// the standard C run-time escaping rules, such as `cmd.exe /c`.
231    ///
232    /// # Batch files
233    ///
234    /// Note the `cmd /c` command line has slightly different escaping rules than batch files
235    /// themselves. If possible, it may be better to write complex arguments to a temporary
236    /// `.bat` file, with appropriate escaping, and simply run that using:
237    ///
238    /// ```no_run
239    /// # use std::process::Command;
240    /// # let temp_bat_file = "";
241    /// # #[allow(unused)]
242    /// let output = Command::new("cmd").args(["/c", &format!("\"{temp_bat_file}\"")]).output();
243    /// ```
244    ///
245    /// # Example
246    ///
247    /// Run a batch script using both trusted and untrusted arguments.
248    ///
249    /// ```no_run
250    /// #[cfg(windows)]
251    /// // `my_script_path` is a path to known bat file.
252    /// // `user_name` is an untrusted name given by the user.
253    /// fn run_script(
254    ///     my_script_path: &str,
255    ///     user_name: &str,
256    /// ) -> Result<std::process::Output, std::io::Error> {
257    ///     use std::io::{Error, ErrorKind};
258    ///     use std::os::windows::process::CommandExt;
259    ///     use std::process::Command;
260    ///
261    ///     // Create the command line, making sure to quote the script path.
262    ///     // This assumes the fixed arguments have been tested to work with the script we're using.
263    ///     let mut cmd_args = format!(r#""{my_script_path}" "--features=[a,b,c]""#);
264    ///
265    ///     // Make sure the user name is safe. In particular we need to be
266    ///     // cautious of ascii symbols that cmd may interpret specially.
267    ///     // Here we only allow alphanumeric characters.
268    ///     if !user_name.chars().all(|c| c.is_alphanumeric()) {
269    ///         return Err(Error::new(ErrorKind::InvalidInput, "invalid user name"));
270    ///     }
271    ///
272    ///     // now we have validated the user name, let's add that too.
273    ///     cmd_args.push_str(" --user ");
274    ///     cmd_args.push_str(user_name);
275    ///
276    ///     // call cmd.exe and return the output
277    ///     Command::new("cmd.exe")
278    ///         .arg("/c")
279    ///         // surround the entire command in an extra pair of quotes, as required by cmd.exe.
280    ///         .raw_arg(&format!("\"{cmd_args}\""))
281    ///         .output()
282    /// }
283    /// ````
284    #[stable(feature = "windows_process_extensions_raw_arg", since = "1.62.0")]
285    fn raw_arg<S: AsRef<OsStr>>(&mut self, text_to_append_as_is: S) -> &mut process::Command;
286
287    /// When [`process::Command`] creates pipes, request that our side is always async.
288    ///
289    /// By default [`process::Command`] may choose to use pipes where both ends
290    /// are opened for synchronous read or write operations. By using
291    /// `async_pipes(true)`, this behavior is overridden so that our side is
292    /// always async.
293    ///
294    /// This is important because if doing async I/O a pipe or a file has to be
295    /// opened for async access.
296    ///
297    /// The end of the pipe sent to the child process will always be synchronous
298    /// regardless of this option.
299    ///
300    /// # Example
301    ///
302    #[cfg_attr(windows, doc = "```")]
303    #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
304    /// #![feature(windows_process_extensions_async_pipes)]
305    /// use std::os::windows::process::CommandExt;
306    /// use std::process::{Command, Stdio};
307    ///
308    /// # let program = "";
309    ///
310    /// Command::new(program)
311    ///     .async_pipes(true)
312    ///     .stdin(Stdio::piped())
313    ///     .stdout(Stdio::piped())
314    ///     .stderr(Stdio::piped());
315    /// ```
316    #[unstable(feature = "windows_process_extensions_async_pipes", issue = "98289")]
317    fn async_pipes(&mut self, always_async: bool) -> &mut process::Command;
318
319    /// Executes the command as a child process with the given
320    /// [`ProcThreadAttributeList`], returning a handle to it.
321    ///
322    /// This method enables the customization of attributes for the spawned
323    /// child process on Windows systems.
324    /// Attributes offer extended configurability for process creation,
325    /// but their usage can be intricate and potentially unsafe.
326    ///
327    /// # Note
328    ///
329    /// By default, stdin, stdout, and stderr are inherited from the parent
330    /// process.
331    ///
332    /// # Example
333    ///
334    #[cfg_attr(windows, doc = "```")]
335    #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
336    /// #![feature(windows_process_extensions_raw_attribute)]
337    /// use std::os::windows::io::AsRawHandle;
338    /// use std::os::windows::process::{CommandExt, ProcThreadAttributeList};
339    /// use std::process::Command;
340    ///
341    /// # struct ProcessDropGuard(std::process::Child);
342    /// # impl Drop for ProcessDropGuard {
343    /// #     fn drop(&mut self) {
344    /// #         let _ = self.0.kill();
345    /// #     }
346    /// # }
347    /// #
348    /// let parent = Command::new("cmd").spawn()?;
349    /// let parent_process_handle = parent.as_raw_handle();
350    /// # let parent = ProcessDropGuard(parent);
351    ///
352    /// const PROC_THREAD_ATTRIBUTE_PARENT_PROCESS: usize = 0x00020000;
353    /// let mut attribute_list = ProcThreadAttributeList::build()
354    ///     .attribute(PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, &parent_process_handle)
355    ///     .finish()
356    ///     .unwrap();
357    ///
358    /// let mut child = Command::new("cmd").spawn_with_attributes(&attribute_list)?;
359    /// #
360    /// # child.kill()?;
361    /// # Ok::<(), std::io::Error>(())
362    /// ```
363    #[unstable(feature = "windows_process_extensions_raw_attribute", issue = "114854")]
364    fn spawn_with_attributes(
365        &mut self,
366        attribute_list: &ProcThreadAttributeList<'_>,
367    ) -> io::Result<process::Child>;
368
369    /// When true, sets the `STARTF_RUNFULLSCREEN` flag on the [STARTUPINFO][1] struct before passing it to `CreateProcess`.
370    ///
371    /// [1]: https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/ns-processthreadsapi-startupinfoa
372    #[unstable(feature = "windows_process_extensions_startupinfo", issue = "141010")]
373    fn startupinfo_fullscreen(&mut self, enabled: bool) -> &mut process::Command;
374
375    /// When true, sets the `STARTF_UNTRUSTEDSOURCE` flag on the [STARTUPINFO][1] struct before passing it to `CreateProcess`.
376    ///
377    /// [1]: https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/ns-processthreadsapi-startupinfoa
378    #[unstable(feature = "windows_process_extensions_startupinfo", issue = "141010")]
379    fn startupinfo_untrusted_source(&mut self, enabled: bool) -> &mut process::Command;
380
381    /// When specified, sets the following flags on the [STARTUPINFO][1] struct before passing it to `CreateProcess`:
382    /// - If `Some(true)`, sets `STARTF_FORCEONFEEDBACK`
383    /// - If `Some(false)`, sets `STARTF_FORCEOFFFEEDBACK`
384    /// - If `None`, does not set any flags
385    ///
386    /// [1]: https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/ns-processthreadsapi-startupinfoa
387    #[unstable(feature = "windows_process_extensions_startupinfo", issue = "141010")]
388    fn startupinfo_force_feedback(&mut self, enabled: Option<bool>) -> &mut process::Command;
389
390    /// If this flag is set to `true`, each inheritable handle in the calling
391    /// process is inherited by the new process. If the flag is `false`, the
392    /// handles are not inherited.
393    ///
394    /// The default value for this flag is `true`.
395    ///
396    /// **Note** that inherited handles have the same value and access rights
397    /// as the original handles. For additional discussion of inheritable handles,
398    /// see the [Remarks][1] section of the `CreateProcessW` documentation.
399    ///
400    /// [1]: https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessw#remarks
401    #[stable(
402        feature = "windows_process_extensions_inherit_handles",
403        since = "CURRENT_RUSTC_VERSION"
404    )]
405    fn inherit_handles(&mut self, inherit_handles: bool) -> &mut process::Command;
406}
407
408#[stable(feature = "windows_process_extensions", since = "1.16.0")]
409impl CommandExt for process::Command {
410    #[rustdoc_skip_body]
411    fn creation_flags(&mut self, flags: u32) -> &mut process::Command {
412        self.as_inner_mut().creation_flags(flags);
413        self
414    }
415
416    #[rustdoc_skip_body]
417    fn desktop<S: AsRef<OsStr>>(&mut self, desktop: S) -> &mut process::Command {
418        self.as_inner_mut().desktop(desktop.as_ref());
419        self
420    }
421
422    #[rustdoc_skip_body]
423    fn show_window(&mut self, cmd_show: u16) -> &mut process::Command {
424        self.as_inner_mut().show_window(Some(cmd_show));
425        self
426    }
427
428    #[rustdoc_skip_body]
429    fn force_quotes(&mut self, enabled: bool) -> &mut process::Command {
430        self.as_inner_mut().force_quotes(enabled);
431        self
432    }
433
434    #[rustdoc_skip_body]
435    fn raw_arg<S: AsRef<OsStr>>(&mut self, raw_text: S) -> &mut process::Command {
436        self.as_inner_mut().raw_arg(raw_text.as_ref());
437        self
438    }
439
440    fn async_pipes(&mut self, always_async: bool) -> &mut process::Command {
441        // FIXME: This currently has an intentional no-op implementation.
442        // For the time being our side of the pipes will always be async.
443        // Once the ecosystem has adjusted, we may then be able to start making
444        // use of synchronous pipes within the standard library.
445        let _ = always_async;
446        self
447    }
448
449    #[rustdoc_skip_body]
450    fn spawn_with_attributes(
451        &mut self,
452        attribute_list: &ProcThreadAttributeList<'_>,
453    ) -> io::Result<process::Child> {
454        self.as_inner_mut()
455            .spawn_with_attributes(sys::process::Stdio::Inherit, true, Some(attribute_list))
456            .map(process::Child::from_inner)
457    }
458
459    #[rustdoc_skip_body]
460    fn startupinfo_fullscreen(&mut self, enabled: bool) -> &mut process::Command {
461        self.as_inner_mut().startupinfo_fullscreen(enabled);
462        self
463    }
464
465    #[rustdoc_skip_body]
466    fn startupinfo_untrusted_source(&mut self, enabled: bool) -> &mut process::Command {
467        self.as_inner_mut().startupinfo_untrusted_source(enabled);
468        self
469    }
470
471    #[rustdoc_skip_body]
472    fn startupinfo_force_feedback(&mut self, enabled: Option<bool>) -> &mut process::Command {
473        self.as_inner_mut().startupinfo_force_feedback(enabled);
474        self
475    }
476
477    #[rustdoc_skip_body]
478    fn inherit_handles(&mut self, inherit_handles: bool) -> &mut process::Command {
479        self.as_inner_mut().inherit_handles(inherit_handles);
480        self
481    }
482}
483
484#[stable(feature = "windows_process_extensions_main_thread_handle", since = "1.100.0")]
485pub impl(self) trait ChildExt {
486    /// Extracts the main thread raw handle, without taking ownership
487    #[stable(feature = "windows_process_extensions_main_thread_handle", since = "1.100.0")]
488    fn main_thread_handle(&self) -> BorrowedHandle<'_>;
489}
490
491#[stable(feature = "windows_process_extensions_main_thread_handle", since = "1.100.0")]
492impl ChildExt for process::Child {
493    #[rustdoc_skip_body]
494    fn main_thread_handle(&self) -> BorrowedHandle<'_> {
495        self.handle.main_thread_handle()
496    }
497}
498
499/// Windows-specific extensions to [`process::ExitCode`].
500#[stable(feature = "windows_process_exit_code_from", since = "CURRENT_RUSTC_VERSION")]
501pub impl(self) trait ExitCodeExt {
502    /// Creates a new `ExitCode` from the raw underlying `u32` return value of
503    /// a process.
504    ///
505    /// The exit code should not be 259, as this conflicts with the `STILL_ACTIVE`
506    /// macro returned from the `GetExitCodeProcess` function to signal that the
507    /// process has yet to run to completion.
508    #[stable(feature = "windows_process_exit_code_from", since = "CURRENT_RUSTC_VERSION")]
509    fn from_raw(raw: u32) -> Self;
510}
511
512#[stable(feature = "windows_process_exit_code_from", since = "CURRENT_RUSTC_VERSION")]
513impl ExitCodeExt for process::ExitCode {
514    #[rustdoc_skip_body]
515    fn from_raw(raw: u32) -> Self {
516        process::ExitCode::from_inner(From::from(raw))
517    }
518}
519
520/// A wrapper around windows [`ProcThreadAttributeList`][1].
521///
522/// [1]: <https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-initializeprocthreadattributelist>
523#[derive(Debug)]
524#[unstable(feature = "windows_process_extensions_raw_attribute", issue = "114854")]
525pub struct ProcThreadAttributeList<'a> {
526    attribute_list: Box<[MaybeUninit<u8>]>,
527    _lifetime_marker: marker::PhantomData<&'a ()>,
528}
529
530#[unstable(feature = "windows_process_extensions_raw_attribute", issue = "114854")]
531impl<'a> ProcThreadAttributeList<'a> {
532    /// Creates a new builder for constructing a [`ProcThreadAttributeList`].
533    pub fn build() -> ProcThreadAttributeListBuilder<'a> {
534        ProcThreadAttributeListBuilder::new()
535    }
536
537    /// Returns a pointer to the underling attribute list.
538    #[doc(hidden)]
539    pub fn as_ptr(&self) -> *const MaybeUninit<u8> {
540        self.attribute_list.as_ptr()
541    }
542}
543
544#[unstable(feature = "windows_process_extensions_raw_attribute", issue = "114854")]
545impl<'a> Drop for ProcThreadAttributeList<'a> {
546    /// Deletes the attribute list.
547    ///
548    /// This method calls [`DeleteProcThreadAttributeList`][1] to delete the
549    /// underlying attribute list.
550    ///
551    /// [1]: <https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-deleteprocthreadattributelist>
552    #[rustdoc_skip_body]
553    fn drop(&mut self) {
554        let lp_attribute_list =
555            self.attribute_list.as_mut_ptr().cast::<sys::c::_PROC_THREAD_ATTRIBUTE_LIST>();
556        unsafe { sys::c::DeleteProcThreadAttributeList(lp_attribute_list) }
557    }
558}
559
560/// Builder for constructing a [`ProcThreadAttributeList`].
561#[derive(Clone, Debug)]
562#[unstable(feature = "windows_process_extensions_raw_attribute", issue = "114854")]
563pub struct ProcThreadAttributeListBuilder<'a> {
564    attributes: alloc::collections::BTreeMap<usize, ProcThreadAttributeValue>,
565    _lifetime_marker: marker::PhantomData<&'a ()>,
566}
567
568#[unstable(feature = "windows_process_extensions_raw_attribute", issue = "114854")]
569impl<'a> ProcThreadAttributeListBuilder<'a> {
570    fn new() -> Self {
571        ProcThreadAttributeListBuilder {
572            attributes: alloc::collections::BTreeMap::new(),
573            _lifetime_marker: marker::PhantomData,
574        }
575    }
576
577    /// Sets an attribute on the attribute list.
578    ///
579    /// The `attribute` parameter specifies the raw attribute to be set, while
580    /// the `value` parameter holds the value associated with that attribute.
581    /// Please refer to the [Windows documentation][1] for a list of valid attributes.
582    ///
583    /// # Note
584    ///
585    /// The maximum number of attributes is the value of [`u32::MAX`]. If this
586    /// limit is exceeded, the call to [`Self::finish`] will return an `Error`
587    /// indicating that the maximum number of attributes has been exceeded.
588    ///
589    /// # Safety Note
590    ///
591    /// Remember that improper use of attributes can lead to undefined behavior
592    /// or security vulnerabilities. Always consult the documentation and ensure
593    /// proper attribute values are used.
594    ///
595    /// [1]: <https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-updateprocthreadattribute#parameters>
596    pub fn attribute<T>(self, attribute: usize, value: &'a T) -> Self {
597        unsafe {
598            self.raw_attribute(attribute, ptr::addr_of!(*value).cast::<c_void>(), size_of::<T>())
599        }
600    }
601
602    /// Sets a raw attribute on the attribute list.
603    ///
604    /// This function is useful for setting attributes with pointers or sizes
605    /// that cannot be derived directly from their values.
606    ///
607    /// # Safety
608    ///
609    /// This function is marked as `unsafe` because it deals with raw pointers
610    /// and sizes. It is the responsibility of the caller to ensure the value
611    /// lives longer than the resulting [`ProcThreadAttributeList`] as well as
612    /// the validity of the size parameter.
613    ///
614    /// # Example
615    ///
616    #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
617    #[cfg_attr(all(windows, target_vendor = "win7"), doc = "```no_run")]
618    #[cfg_attr(all(windows, not(target_vendor = "win7")), doc = "```")]
619    /// #![feature(windows_process_extensions_raw_attribute)]
620    /// use std::ffi::c_void;
621    /// use std::os::windows::process::{CommandExt, ProcThreadAttributeList};
622    /// use std::os::windows::raw::HANDLE;
623    /// use std::process::Command;
624    ///
625    /// #[repr(C)]
626    /// pub struct COORD {
627    ///     pub X: i16,
628    ///     pub Y: i16,
629    /// }
630    ///
631    /// unsafe extern "system" {
632    ///     fn CreatePipe(
633    ///         hreadpipe: *mut HANDLE,
634    ///         hwritepipe: *mut HANDLE,
635    ///         lppipeattributes: *const c_void,
636    ///         nsize: u32,
637    ///     ) -> i32;
638    ///     fn CreatePseudoConsole(
639    ///         size: COORD,
640    ///         hinput: HANDLE,
641    ///         houtput: HANDLE,
642    ///         dwflags: u32,
643    ///         phpc: *mut isize,
644    ///     ) -> i32;
645    ///     fn CloseHandle(hobject: HANDLE) -> i32;
646    /// }
647    ///
648    /// let [mut input_read_side, mut output_write_side, mut output_read_side, mut input_write_side] =
649    ///     [unsafe { std::mem::zeroed::<HANDLE>() }; 4];
650    ///
651    /// unsafe {
652    ///     CreatePipe(&mut input_read_side, &mut input_write_side, std::ptr::null(), 0);
653    ///     CreatePipe(&mut output_read_side, &mut output_write_side, std::ptr::null(), 0);
654    /// }
655    ///
656    /// let size = COORD { X: 60, Y: 40 };
657    /// let mut h_pc = unsafe { std::mem::zeroed() };
658    /// unsafe { CreatePseudoConsole(size, input_read_side, output_write_side, 0, &mut h_pc) };
659    ///
660    /// unsafe { CloseHandle(input_read_side) };
661    /// unsafe { CloseHandle(output_write_side) };
662    ///
663    /// const PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE: usize = 131094;
664    ///
665    /// let attribute_list = unsafe {
666    ///     ProcThreadAttributeList::build()
667    ///         .raw_attribute(
668    ///             PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE,
669    ///             h_pc as *const c_void,
670    ///             size_of::<isize>(),
671    ///         )
672    ///         .finish()?
673    /// };
674    ///
675    /// let mut child = Command::new("cmd").spawn_with_attributes(&attribute_list)?;
676    /// #
677    /// # child.kill()?;
678    /// # Ok::<(), std::io::Error>(())
679    /// ```
680    pub unsafe fn raw_attribute<T>(
681        mut self,
682        attribute: usize,
683        value_ptr: *const T,
684        value_size: usize,
685    ) -> Self {
686        self.attributes.insert(
687            attribute,
688            ProcThreadAttributeValue { ptr: value_ptr.cast::<c_void>(), size: value_size },
689        );
690        self
691    }
692
693    /// Finalizes the construction of the `ProcThreadAttributeList`.
694    ///
695    /// # Errors
696    ///
697    /// Returns an error if the maximum number of attributes is exceeded
698    /// or if there is an I/O error during initialization.
699    #[rustdoc_skip_body]
700    pub fn finish(&self) -> io::Result<ProcThreadAttributeList<'a>> {
701        // To initialize our ProcThreadAttributeList, we need to determine
702        // how many bytes to allocate for it. The Windows API simplifies this
703        // process by allowing us to call `InitializeProcThreadAttributeList`
704        // with a null pointer to retrieve the required size.
705        let mut required_size = 0;
706        let Ok(attribute_count) = self.attributes.len().try_into() else {
707            return Err(io::const_error!(
708                io::ErrorKind::InvalidInput,
709                "maximum number of ProcThreadAttributes exceeded",
710            ));
711        };
712        unsafe {
713            sys::c::InitializeProcThreadAttributeList(
714                ptr::null_mut(),
715                attribute_count,
716                0,
717                &mut required_size,
718            )
719        };
720
721        let mut attribute_list = vec![MaybeUninit::uninit(); required_size].into_boxed_slice();
722
723        // Once we've allocated the necessary memory, it's safe to invoke
724        // `InitializeProcThreadAttributeList` to properly initialize the list.
725        sys::cvt(unsafe {
726            sys::c::InitializeProcThreadAttributeList(
727                attribute_list.as_mut_ptr().cast::<sys::c::_PROC_THREAD_ATTRIBUTE_LIST>(),
728                attribute_count,
729                0,
730                &mut required_size,
731            )
732        })?;
733
734        // # Add our attributes to the buffer.
735        // It's theoretically possible for the attribute count to exceed a u32
736        // value. Therefore, we ensure that we don't add more attributes than
737        // the buffer was initialized for.
738        for (&attribute, value) in self.attributes.iter().take(attribute_count as usize) {
739            sys::cvt(unsafe {
740                sys::c::UpdateProcThreadAttribute(
741                    attribute_list.as_mut_ptr().cast::<sys::c::_PROC_THREAD_ATTRIBUTE_LIST>(),
742                    0,
743                    attribute,
744                    value.ptr,
745                    value.size,
746                    ptr::null_mut(),
747                    ptr::null_mut(),
748                )
749            })?;
750        }
751
752        Ok(ProcThreadAttributeList { attribute_list, _lifetime_marker: marker::PhantomData })
753    }
754}
755
756/// Wrapper around the value data to be used as a Process Thread Attribute.
757#[derive(Clone, Debug)]
758struct ProcThreadAttributeValue {
759    ptr: *const c_void,
760    size: usize,
761}