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