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