Skip to main content

quickgui_system/
process.rs

1use std::{
2    ffi::{OsStr, OsString},
3    path::{Path, PathBuf},
4    process::{Command, Stdio},
5};
6
7use crate::{Result, invalid, platform};
8
9/// Maximum arguments retained by one orderly relaunch request.
10pub const MAX_RELAUNCH_ARGUMENTS: usize = 256;
11/// Maximum encoded bytes retained by one relaunch argument or path.
12pub const MAX_RELAUNCH_VALUE_BYTES: usize = 32 * 1024;
13/// Maximum aggregate encoded argument bytes retained by one relaunch request.
14pub const MAX_RELAUNCH_ARGUMENT_BYTES: usize = 256 * 1024;
15
16/// Overrides for an orderly application relaunch.
17///
18/// Unspecified values preserve the current executable, arguments (excluding argument zero), and
19/// working directory. Environment variables are inherited when the prepared request is spawned.
20#[derive(Clone, Debug, Default, Eq, PartialEq)]
21pub struct RelaunchOptions {
22    executable: Option<PathBuf>,
23    arguments: Option<Vec<OsString>>,
24    working_directory: Option<PathBuf>,
25}
26
27impl RelaunchOptions {
28    pub fn new() -> Self {
29        Self::default()
30    }
31
32    pub fn executable(mut self, executable: impl Into<PathBuf>) -> Self {
33        self.executable = Some(executable.into());
34        self
35    }
36
37    pub fn arguments<I, S>(mut self, arguments: I) -> Self
38    where
39        I: IntoIterator<Item = S>,
40        S: Into<OsString>,
41    {
42        self.arguments = Some(arguments.into_iter().map(Into::into).collect());
43        self
44    }
45
46    pub fn without_arguments(mut self) -> Self {
47        self.arguments = Some(Vec::new());
48        self
49    }
50
51    pub fn working_directory(mut self, directory: impl Into<PathBuf>) -> Self {
52        self.working_directory = Some(directory.into());
53        self
54    }
55
56    pub fn executable_override(&self) -> Option<&Path> {
57        self.executable.as_deref()
58    }
59
60    pub fn argument_override(&self) -> Option<&[OsString]> {
61        self.arguments.as_deref()
62    }
63
64    pub fn working_directory_override(&self) -> Option<&Path> {
65        self.working_directory.as_deref()
66    }
67
68    /// Resolve inherited process values and validate the complete bounded request.
69    pub fn prepare(self) -> Result<RelaunchRequest> {
70        RelaunchRequest::prepare(self)
71    }
72}
73
74/// A complete, immutable process launch retained until orderly application teardown finishes.
75#[derive(Clone, Debug, Eq, PartialEq)]
76pub struct RelaunchRequest {
77    executable: PathBuf,
78    arguments: Vec<OsString>,
79    working_directory: PathBuf,
80}
81
82impl RelaunchRequest {
83    pub fn current() -> Result<Self> {
84        RelaunchOptions::default().prepare()
85    }
86
87    pub fn prepare(options: RelaunchOptions) -> Result<Self> {
88        let executable = match options.executable {
89            Some(executable) => executable,
90            None => std::env::current_exe().map_err(platform)?,
91        };
92        let arguments = options
93            .arguments
94            .unwrap_or_else(|| std::env::args_os().skip(1).collect());
95        let working_directory = match options.working_directory {
96            Some(directory) => directory,
97            None => std::env::current_dir().map_err(platform)?,
98        };
99        validate_absolute_path(&executable, "the relaunch executable")?;
100        validate_absolute_path(&working_directory, "the relaunch working directory")?;
101        if arguments.len() > MAX_RELAUNCH_ARGUMENTS {
102            return Err(invalid(format!(
103                "a relaunch cannot retain more than {MAX_RELAUNCH_ARGUMENTS} arguments"
104            )));
105        }
106        let mut total = 0_usize;
107        for argument in &arguments {
108            let encoded = encoded_len(argument.as_os_str());
109            if encoded > MAX_RELAUNCH_VALUE_BYTES || contains_nul(argument.as_os_str()) {
110                return Err(invalid(format!(
111                    "each relaunch argument must be NUL-free and at most {MAX_RELAUNCH_VALUE_BYTES} encoded bytes"
112                )));
113            }
114            total = total.saturating_add(encoded);
115            if total > MAX_RELAUNCH_ARGUMENT_BYTES {
116                return Err(invalid(format!(
117                    "relaunch arguments cannot exceed {MAX_RELAUNCH_ARGUMENT_BYTES} encoded bytes in aggregate"
118                )));
119            }
120        }
121        Ok(Self {
122            executable,
123            arguments,
124            working_directory,
125        })
126    }
127
128    pub fn executable(&self) -> &Path {
129        &self.executable
130    }
131
132    pub fn arguments(&self) -> &[OsString] {
133        &self.arguments
134    }
135
136    pub fn working_directory(&self) -> &Path {
137        &self.working_directory
138    }
139
140    /// Spawn the replacement process without invoking a shell.
141    ///
142    /// QuickGUI's application runtime calls this only after its child-first window teardown and
143    /// process-owned service cleanup have completed. Direct callers are responsible for choosing
144    /// an equivalent lifecycle boundary.
145    pub fn spawn(&self) -> Result<RelaunchedProcess> {
146        let child = Command::new(&self.executable)
147            .args(&self.arguments)
148            .current_dir(&self.working_directory)
149            .stdin(Stdio::null())
150            .stdout(Stdio::null())
151            .stderr(Stdio::null())
152            .spawn()
153            .map_err(platform)?;
154        Ok(RelaunchedProcess { id: child.id() })
155    }
156}
157
158/// Identity of a successfully spawned replacement process.
159#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
160pub struct RelaunchedProcess {
161    id: u32,
162}
163
164impl RelaunchedProcess {
165    pub const fn id(self) -> u32 {
166        self.id
167    }
168}
169
170fn validate_absolute_path(path: &Path, name: &str) -> Result<()> {
171    let value = path.as_os_str();
172    if !path.is_absolute()
173        || value.is_empty()
174        || contains_nul(value)
175        || encoded_len(value) > MAX_RELAUNCH_VALUE_BYTES
176    {
177        return Err(invalid(format!(
178            "{name} must be absolute, NUL-free, and at most {MAX_RELAUNCH_VALUE_BYTES} encoded bytes"
179        )));
180    }
181    Ok(())
182}
183
184#[cfg(unix)]
185fn encoded_len(value: &OsStr) -> usize {
186    use std::os::unix::ffi::OsStrExt;
187    value.as_bytes().len()
188}
189
190#[cfg(windows)]
191fn encoded_len(value: &OsStr) -> usize {
192    use std::os::windows::ffi::OsStrExt;
193    value.encode_wide().count().saturating_mul(2)
194}
195
196#[cfg(not(any(unix, windows)))]
197fn encoded_len(value: &OsStr) -> usize {
198    value.to_string_lossy().len()
199}
200
201#[cfg(unix)]
202fn contains_nul(value: &OsStr) -> bool {
203    use std::os::unix::ffi::OsStrExt;
204    value.as_bytes().contains(&0)
205}
206
207#[cfg(windows)]
208fn contains_nul(value: &OsStr) -> bool {
209    use std::os::windows::ffi::OsStrExt;
210    value.encode_wide().any(|unit| unit == 0)
211}
212
213#[cfg(not(any(unix, windows)))]
214fn contains_nul(value: &OsStr) -> bool {
215    value.to_string_lossy().contains('\0')
216}
217
218#[cfg(test)]
219mod tests {
220    use super::*;
221
222    #[test]
223    fn explicit_relaunch_request_preserves_native_values() {
224        let executable = std::env::current_exe().unwrap();
225        let directory = std::env::current_dir().unwrap();
226        let request = RelaunchOptions::new()
227            .executable(&executable)
228            .arguments([OsString::from("--restored"), OsString::from("value")])
229            .working_directory(&directory)
230            .prepare()
231            .unwrap();
232        assert_eq!(request.executable(), executable);
233        assert_eq!(
234            request.arguments(),
235            [OsString::from("--restored"), OsString::from("value")]
236        );
237        assert_eq!(request.working_directory(), directory);
238    }
239
240    #[test]
241    fn relaunch_request_rejects_relative_paths_and_unbounded_arguments() {
242        assert!(
243            RelaunchOptions::new()
244                .executable("relative-app")
245                .prepare()
246                .is_err()
247        );
248        let arguments = (0..=MAX_RELAUNCH_ARGUMENTS).map(|_| OsString::from("argument"));
249        assert!(
250            RelaunchOptions::new()
251                .executable(std::env::current_exe().unwrap())
252                .arguments(arguments)
253                .prepare()
254                .is_err()
255        );
256    }
257
258    #[test]
259    fn current_relaunch_request_is_fully_resolved() {
260        let request = RelaunchRequest::current().unwrap();
261        assert!(request.executable().is_absolute());
262        assert!(request.working_directory().is_absolute());
263        assert!(request.arguments().len() <= MAX_RELAUNCH_ARGUMENTS);
264    }
265}