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(feature = "windows_process_extensions_inherit_handles", since = "1.101.0")]
402 fn inherit_handles(&mut self, inherit_handles: bool) -> &mut process::Command;
403}
404
405#[stable(feature = "windows_process_extensions", since = "1.16.0")]
406impl CommandExt for process::Command {
407 #[rustdoc_skip_body]
408 fn creation_flags(&mut self, flags: u32) -> &mut process::Command {
409 self.as_inner_mut().creation_flags(flags);
410 self
411 }
412
413 #[rustdoc_skip_body]
414 fn desktop<S: AsRef<OsStr>>(&mut self, desktop: S) -> &mut process::Command {
415 self.as_inner_mut().desktop(desktop.as_ref());
416 self
417 }
418
419 #[rustdoc_skip_body]
420 fn show_window(&mut self, cmd_show: u16) -> &mut process::Command {
421 self.as_inner_mut().show_window(Some(cmd_show));
422 self
423 }
424
425 #[rustdoc_skip_body]
426 fn force_quotes(&mut self, enabled: bool) -> &mut process::Command {
427 self.as_inner_mut().force_quotes(enabled);
428 self
429 }
430
431 #[rustdoc_skip_body]
432 fn raw_arg<S: AsRef<OsStr>>(&mut self, raw_text: S) -> &mut process::Command {
433 self.as_inner_mut().raw_arg(raw_text.as_ref());
434 self
435 }
436
437 fn async_pipes(&mut self, always_async: bool) -> &mut process::Command {
438 // FIXME: This currently has an intentional no-op implementation.
439 // For the time being our side of the pipes will always be async.
440 // Once the ecosystem has adjusted, we may then be able to start making
441 // use of synchronous pipes within the standard library.
442 let _ = always_async;
443 self
444 }
445
446 #[rustdoc_skip_body]
447 fn spawn_with_attributes(
448 &mut self,
449 attribute_list: &ProcThreadAttributeList<'_>,
450 ) -> io::Result<process::Child> {
451 self.as_inner_mut()
452 .spawn_with_attributes(sys::process::Stdio::Inherit, true, Some(attribute_list))
453 .map(process::Child::from_inner)
454 }
455
456 #[rustdoc_skip_body]
457 fn startupinfo_fullscreen(&mut self, enabled: bool) -> &mut process::Command {
458 self.as_inner_mut().startupinfo_fullscreen(enabled);
459 self
460 }
461
462 #[rustdoc_skip_body]
463 fn startupinfo_untrusted_source(&mut self, enabled: bool) -> &mut process::Command {
464 self.as_inner_mut().startupinfo_untrusted_source(enabled);
465 self
466 }
467
468 #[rustdoc_skip_body]
469 fn startupinfo_force_feedback(&mut self, enabled: Option<bool>) -> &mut process::Command {
470 self.as_inner_mut().startupinfo_force_feedback(enabled);
471 self
472 }
473
474 #[rustdoc_skip_body]
475 fn inherit_handles(&mut self, inherit_handles: bool) -> &mut process::Command {
476 self.as_inner_mut().inherit_handles(inherit_handles);
477 self
478 }
479}
480
481#[stable(feature = "windows_process_extensions_main_thread_handle", since = "1.100.0")]
482pub impl(self) trait ChildExt {
483 /// Extracts the main thread raw handle, without taking ownership
484 #[stable(feature = "windows_process_extensions_main_thread_handle", since = "1.100.0")]
485 fn main_thread_handle(&self) -> BorrowedHandle<'_>;
486}
487
488#[stable(feature = "windows_process_extensions_main_thread_handle", since = "1.100.0")]
489impl ChildExt for process::Child {
490 #[rustdoc_skip_body]
491 fn main_thread_handle(&self) -> BorrowedHandle<'_> {
492 self.handle.main_thread_handle()
493 }
494}
495
496/// Windows-specific extensions to [`process::ExitCode`].
497#[stable(feature = "windows_process_exit_code_from", since = "1.101.0")]
498pub impl(self) trait ExitCodeExt {
499 /// Creates a new `ExitCode` from the raw underlying `u32` return value of
500 /// a process.
501 ///
502 /// The exit code should not be 259, as this conflicts with the `STILL_ACTIVE`
503 /// macro returned from the `GetExitCodeProcess` function to signal that the
504 /// process has yet to run to completion.
505 #[stable(feature = "windows_process_exit_code_from", since = "1.101.0")]
506 fn from_raw(raw: u32) -> Self;
507}
508
509#[stable(feature = "windows_process_exit_code_from", since = "1.101.0")]
510impl ExitCodeExt for process::ExitCode {
511 #[rustdoc_skip_body]
512 fn from_raw(raw: u32) -> Self {
513 process::ExitCode::from_inner(From::from(raw))
514 }
515}
516
517/// A wrapper around windows [`ProcThreadAttributeList`][1].
518///
519/// [1]: <https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-initializeprocthreadattributelist>
520#[derive(Debug)]
521#[unstable(feature = "windows_process_extensions_raw_attribute", issue = "114854")]
522pub struct ProcThreadAttributeList<'a> {
523 attribute_list: Box<[MaybeUninit<u8>]>,
524 _lifetime_marker: marker::PhantomData<&'a ()>,
525}
526
527#[unstable(feature = "windows_process_extensions_raw_attribute", issue = "114854")]
528impl<'a> ProcThreadAttributeList<'a> {
529 /// Creates a new builder for constructing a [`ProcThreadAttributeList`].
530 pub fn build() -> ProcThreadAttributeListBuilder<'a> {
531 ProcThreadAttributeListBuilder::new()
532 }
533
534 /// Returns a pointer to the underling attribute list.
535 #[doc(hidden)]
536 pub fn as_ptr(&self) -> *const MaybeUninit<u8> {
537 self.attribute_list.as_ptr()
538 }
539}
540
541#[unstable(feature = "windows_process_extensions_raw_attribute", issue = "114854")]
542impl<'a> Drop for ProcThreadAttributeList<'a> {
543 /// Deletes the attribute list.
544 ///
545 /// This method calls [`DeleteProcThreadAttributeList`][1] to delete the
546 /// underlying attribute list.
547 ///
548 /// [1]: <https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-deleteprocthreadattributelist>
549 #[rustdoc_skip_body]
550 fn drop(&mut self) {
551 let lp_attribute_list =
552 self.attribute_list.as_mut_ptr().cast::<sys::c::_PROC_THREAD_ATTRIBUTE_LIST>();
553 unsafe { sys::c::DeleteProcThreadAttributeList(lp_attribute_list) }
554 }
555}
556
557/// Builder for constructing a [`ProcThreadAttributeList`].
558#[derive(Clone, Debug)]
559#[unstable(feature = "windows_process_extensions_raw_attribute", issue = "114854")]
560pub struct ProcThreadAttributeListBuilder<'a> {
561 attributes: alloc::collections::BTreeMap<usize, ProcThreadAttributeValue>,
562 _lifetime_marker: marker::PhantomData<&'a ()>,
563}
564
565#[unstable(feature = "windows_process_extensions_raw_attribute", issue = "114854")]
566impl<'a> ProcThreadAttributeListBuilder<'a> {
567 fn new() -> Self {
568 ProcThreadAttributeListBuilder {
569 attributes: alloc::collections::BTreeMap::new(),
570 _lifetime_marker: marker::PhantomData,
571 }
572 }
573
574 /// Sets an attribute on the attribute list.
575 ///
576 /// The `attribute` parameter specifies the raw attribute to be set, while
577 /// the `value` parameter holds the value associated with that attribute.
578 /// Please refer to the [Windows documentation][1] for a list of valid attributes.
579 ///
580 /// # Note
581 ///
582 /// The maximum number of attributes is the value of [`u32::MAX`]. If this
583 /// limit is exceeded, the call to [`Self::finish`] will return an `Error`
584 /// indicating that the maximum number of attributes has been exceeded.
585 ///
586 /// # Safety Note
587 ///
588 /// Remember that improper use of attributes can lead to undefined behavior
589 /// or security vulnerabilities. Always consult the documentation and ensure
590 /// proper attribute values are used.
591 ///
592 /// [1]: <https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-updateprocthreadattribute#parameters>
593 pub fn attribute<T>(self, attribute: usize, value: &'a T) -> Self {
594 unsafe {
595 self.raw_attribute(attribute, ptr::addr_of!(*value).cast::<c_void>(), size_of::<T>())
596 }
597 }
598
599 /// Sets a raw attribute on the attribute list.
600 ///
601 /// This function is useful for setting attributes with pointers or sizes
602 /// that cannot be derived directly from their values.
603 ///
604 /// # Safety
605 ///
606 /// This function is marked as `unsafe` because it deals with raw pointers
607 /// and sizes. It is the responsibility of the caller to ensure the value
608 /// lives longer than the resulting [`ProcThreadAttributeList`] as well as
609 /// the validity of the size parameter.
610 ///
611 /// # Example
612 ///
613 #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
614 #[cfg_attr(all(windows, target_vendor = "win7"), doc = "```no_run")]
615 #[cfg_attr(all(windows, not(target_vendor = "win7")), doc = "```")]
616 /// #![feature(windows_process_extensions_raw_attribute)]
617 /// use std::ffi::c_void;
618 /// use std::os::windows::process::{CommandExt, ProcThreadAttributeList};
619 /// use std::os::windows::raw::HANDLE;
620 /// use std::process::Command;
621 ///
622 /// #[repr(C)]
623 /// pub struct COORD {
624 /// pub X: i16,
625 /// pub Y: i16,
626 /// }
627 ///
628 /// unsafe extern "system" {
629 /// fn CreatePipe(
630 /// hreadpipe: *mut HANDLE,
631 /// hwritepipe: *mut HANDLE,
632 /// lppipeattributes: *const c_void,
633 /// nsize: u32,
634 /// ) -> i32;
635 /// fn CreatePseudoConsole(
636 /// size: COORD,
637 /// hinput: HANDLE,
638 /// houtput: HANDLE,
639 /// dwflags: u32,
640 /// phpc: *mut isize,
641 /// ) -> i32;
642 /// fn CloseHandle(hobject: HANDLE) -> i32;
643 /// }
644 ///
645 /// let [mut input_read_side, mut output_write_side, mut output_read_side, mut input_write_side] =
646 /// [unsafe { std::mem::zeroed::<HANDLE>() }; 4];
647 ///
648 /// unsafe {
649 /// CreatePipe(&mut input_read_side, &mut input_write_side, std::ptr::null(), 0);
650 /// CreatePipe(&mut output_read_side, &mut output_write_side, std::ptr::null(), 0);
651 /// }
652 ///
653 /// let size = COORD { X: 60, Y: 40 };
654 /// let mut h_pc = unsafe { std::mem::zeroed() };
655 /// unsafe { CreatePseudoConsole(size, input_read_side, output_write_side, 0, &mut h_pc) };
656 ///
657 /// unsafe { CloseHandle(input_read_side) };
658 /// unsafe { CloseHandle(output_write_side) };
659 ///
660 /// const PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE: usize = 131094;
661 ///
662 /// let attribute_list = unsafe {
663 /// ProcThreadAttributeList::build()
664 /// .raw_attribute(
665 /// PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE,
666 /// h_pc as *const c_void,
667 /// size_of::<isize>(),
668 /// )
669 /// .finish()?
670 /// };
671 ///
672 /// let mut child = Command::new("cmd").spawn_with_attributes(&attribute_list)?;
673 /// #
674 /// # child.kill()?;
675 /// # Ok::<(), std::io::Error>(())
676 /// ```
677 pub unsafe fn raw_attribute<T>(
678 mut self,
679 attribute: usize,
680 value_ptr: *const T,
681 value_size: usize,
682 ) -> Self {
683 self.attributes.insert(
684 attribute,
685 ProcThreadAttributeValue { ptr: value_ptr.cast::<c_void>(), size: value_size },
686 );
687 self
688 }
689
690 /// Finalizes the construction of the `ProcThreadAttributeList`.
691 ///
692 /// # Errors
693 ///
694 /// Returns an error if the maximum number of attributes is exceeded
695 /// or if there is an I/O error during initialization.
696 #[rustdoc_skip_body]
697 pub fn finish(&self) -> io::Result<ProcThreadAttributeList<'a>> {
698 // To initialize our ProcThreadAttributeList, we need to determine
699 // how many bytes to allocate for it. The Windows API simplifies this
700 // process by allowing us to call `InitializeProcThreadAttributeList`
701 // with a null pointer to retrieve the required size.
702 let mut required_size = 0;
703 let Ok(attribute_count) = self.attributes.len().try_into() else {
704 return Err(io::const_error!(
705 io::ErrorKind::InvalidInput,
706 "maximum number of ProcThreadAttributes exceeded",
707 ));
708 };
709 unsafe {
710 sys::c::InitializeProcThreadAttributeList(
711 ptr::null_mut(),
712 attribute_count,
713 0,
714 &mut required_size,
715 )
716 };
717
718 let mut attribute_list = vec![MaybeUninit::uninit(); required_size].into_boxed_slice();
719
720 // Once we've allocated the necessary memory, it's safe to invoke
721 // `InitializeProcThreadAttributeList` to properly initialize the list.
722 sys::cvt(unsafe {
723 sys::c::InitializeProcThreadAttributeList(
724 attribute_list.as_mut_ptr().cast::<sys::c::_PROC_THREAD_ATTRIBUTE_LIST>(),
725 attribute_count,
726 0,
727 &mut required_size,
728 )
729 })?;
730
731 // # Add our attributes to the buffer.
732 // It's theoretically possible for the attribute count to exceed a u32
733 // value. Therefore, we ensure that we don't add more attributes than
734 // the buffer was initialized for.
735 for (&attribute, value) in self.attributes.iter().take(attribute_count as usize) {
736 sys::cvt(unsafe {
737 sys::c::UpdateProcThreadAttribute(
738 attribute_list.as_mut_ptr().cast::<sys::c::_PROC_THREAD_ATTRIBUTE_LIST>(),
739 0,
740 attribute,
741 value.ptr,
742 value.size,
743 ptr::null_mut(),
744 ptr::null_mut(),
745 )
746 })?;
747 }
748
749 Ok(ProcThreadAttributeList { attribute_list, _lifetime_marker: marker::PhantomData })
750 }
751}
752
753/// Wrapper around the value data to be used as a Process Thread Attribute.
754#[derive(Clone, Debug)]
755struct ProcThreadAttributeValue {
756 ptr: *const c_void,
757 size: usize,
758}