Skip to main content

reverie_process/
builder.rs

1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 * All rights reserved.
4 *
5 * This source code is licensed under the BSD-style license found in the
6 * LICENSE file in the root directory of this source tree.
7 */
8
9use std::borrow::Cow;
10use std::collections::BTreeMap;
11use std::ffi::OsStr;
12use std::ffi::OsString;
13use std::io;
14use std::os::unix::ffi::OsStrExt;
15use std::os::unix::fs::PermissionsExt;
16use std::path;
17use std::path::Path;
18use std::path::PathBuf;
19
20use syscalls::Errno;
21
22use super::Command;
23use super::Container;
24use super::Mount;
25use super::Namespace;
26use super::PtyChild;
27use super::Stdio;
28use super::seccomp;
29use super::util::CStringArray;
30use super::util::to_cstring;
31
32impl Command {
33    /// Constructs a new `Command` for launching the program at path `program`,
34    /// with the following default configuration:
35    ///
36    /// * No arguments to the program
37    /// * Inherit the current process's environment
38    /// * Inherit the current process's working directory
39    /// * Inherit stdin/stdout/stderr for `spawn` or `status`, but create pipes
40    ///   for `output`
41    ///
42    /// Builder methods are provided to change these defaults and
43    /// otherwise configure the process.
44    ///
45    /// If `program` is not an absolute path, the `PATH` will be searched in an
46    /// OS-defined way.
47    ///
48    /// # Examples
49    ///
50    /// Basic usage:
51    ///
52    /// ```no_run
53    /// use reverie_process::Command;
54    /// let command = Command::new("sh");
55    /// ```
56    pub fn new<S: AsRef<OsStr>>(program: S) -> Self {
57        let program = to_cstring(program);
58
59        let mut args = CStringArray::with_capacity(1);
60        args.push(program.clone());
61
62        Self {
63            program,
64            args,
65            pre_exec: Vec::new(),
66            terminal_execve: None,
67            container: Container::new(),
68        }
69    }
70
71    /// Sets the path to the program. This can be used to override what was
72    /// already set in [`Command::new`].
73    ///
74    /// NOTE: This also changes argument 0 to match `program`.
75    pub fn program<S: AsRef<OsStr>>(&mut self, program: S) -> &mut Self {
76        let cstring = to_cstring(program);
77        self.program = cstring.clone();
78        self.args.set(0, cstring);
79        self
80    }
81
82    /// Explicitly sets the first argument. By default, this is the same as the
83    /// program path and is what you want in most cases.
84    pub fn arg0<S: AsRef<OsStr>>(&mut self, arg0: S) -> &mut Self {
85        self.args.set(0, to_cstring(arg0));
86        self
87    }
88
89    /// Gets the first argument. Unless [`Command::arg0`] was used, this returns
90    /// the same string as [`Command::get_program`].
91    pub fn get_arg0(&self) -> &OsStr {
92        OsStr::from_bytes(self.args.get(0).to_bytes())
93    }
94
95    /// Adds an argument to pass to the program.
96    ///
97    /// Only one argument can be passed per use. So instead of:
98    ///
99    /// ```no_run
100    /// reverie_process::Command::new("sh").arg("-C /path/to/repo");
101    /// ```
102    ///
103    /// usage would be:
104    ///
105    /// ```no_run
106    /// reverie_process::Command::new("sh")
107    ///     .arg("-C")
108    ///     .arg("/path/to/repo");
109    /// ```
110    ///
111    /// To pass multiple arguments see [`args`].
112    ///
113    /// [`args`]: method@Self::args
114    ///
115    /// # Examples
116    ///
117    /// Basic usage:
118    ///
119    /// ```no_run
120    /// use reverie_process::Command;
121    ///
122    /// let command = Command::new("ls").arg("-l").arg("-a");
123    /// ```
124    pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Self {
125        self.args.push(to_cstring(arg));
126        self
127    }
128
129    /// Adds multiple arguments to pass to the program.
130    ///
131    /// To pass a single argument see [`arg`].
132    ///
133    /// [`arg`]: method@Self::arg
134    ///
135    /// # Examples
136    ///
137    /// Basic usage:
138    ///
139    /// ```no_run
140    /// use reverie_process::Command;
141    ///
142    /// let command = Command::new("ls").args(&["-l", "-a"]);
143    /// ```
144    pub fn args<I, S>(&mut self, args: I) -> &mut Self
145    where
146        I: IntoIterator<Item = S>,
147        S: AsRef<OsStr>,
148    {
149        for arg in args {
150            self.arg(arg);
151        }
152        self
153    }
154
155    /// Returns an iterator of the arguments that will be passed to the program.
156    ///
157    /// This does not include the program name itself. It only includes the
158    /// arguments specified with [`Command::arg`] and [`Command::args`].
159    pub fn get_args(&self) -> impl Iterator<Item = &OsStr> {
160        self.args
161            .iter()
162            .skip(1)
163            .map(|arg| OsStr::from_bytes(arg.to_bytes()))
164    }
165
166    /// Prepends arguments to the beginning of the command. Note that arguments
167    /// are prepended *after* arg0, but before the rest of the arguments.
168    pub fn prepend_args<I, S>(&mut self, args: I) -> &mut Self
169    where
170        I: IntoIterator<Item = S>,
171        S: AsRef<OsStr>,
172    {
173        let new_args = CStringArray::with_capacity(self.args.len() + 1);
174        let mut old_args = core::mem::replace(&mut self.args, new_args).into_iter();
175
176        // Add arg0 first
177        if let Some(arg0) = old_args.next() {
178            self.args.push(arg0);
179        }
180
181        // Add the new arguments
182        self.args(args);
183
184        // Add the rest of the old arguments
185        for arg in old_args {
186            self.args.push(arg);
187        }
188
189        self
190    }
191
192    /// Inserts or updates an environment variable mapping.
193    ///
194    /// Note that environment variable names are case-insensitive (but
195    /// case-preserving) on Windows, and case-sensitive on all other platforms.
196    ///
197    /// # Examples
198    ///
199    /// Basic usage:
200    ///
201    /// ```no_run
202    /// use reverie_process::Command;
203    ///
204    /// let command = Command::new("ls").env("PATH", "/bin");
205    /// ```
206    pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Self
207    where
208        K: AsRef<OsStr>,
209        V: AsRef<OsStr>,
210    {
211        self.container.env(key, val);
212        self
213    }
214
215    /// Adds or updates multiple environment variable mappings.
216    ///
217    /// # Examples
218    ///
219    /// Basic usage:
220    ///
221    /// ```no_run
222    /// use std::collections::HashMap;
223    /// use std::env;
224    ///
225    /// use reverie_process::Command;
226    /// use reverie_process::Stdio;
227    ///
228    /// let filtered_env: HashMap<String, String> = env::vars()
229    ///     .filter(|&(ref k, _)| k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH")
230    ///     .collect();
231    ///
232    /// let command = Command::new("printenv")
233    ///     .stdin(Stdio::null())
234    ///     .stdout(Stdio::inherit())
235    ///     .env_clear()
236    ///     .envs(&filtered_env);
237    /// ```
238    pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Self
239    where
240        I: IntoIterator<Item = (K, V)>,
241        K: AsRef<OsStr>,
242        V: AsRef<OsStr>,
243    {
244        self.container.envs(vars);
245        self
246    }
247
248    /// Removes an environment variable mapping.
249    ///
250    /// # Examples
251    ///
252    /// Basic usage:
253    ///
254    /// ```no_run
255    /// use reverie_process::Command;
256    ///
257    /// let command = Command::new("ls").env_remove("PATH");
258    /// ```
259    pub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Self {
260        self.container.env_remove(key);
261        self
262    }
263
264    /// Clears the entire environment map for the child process.
265    ///
266    /// # Examples
267    ///
268    /// Basic usage:
269    ///
270    /// ```no_run
271    /// use reverie_process::Command;
272    ///
273    /// let command = Command::new("ls").env_clear();
274    /// ```
275    pub fn env_clear(&mut self) -> &mut Self {
276        self.container.env_clear();
277        self
278    }
279
280    /// Sets the working directory for the child process.
281    ///
282    /// # Interaction with `chroot`
283    ///
284    /// The working directory is set *after* the chroot is performed (if a chroot
285    /// directory is specified). Thus, the path given is relative to the chroot
286    /// directory. Otherwise, if no chroot directory is specified, the working
287    /// directory is relative to the current working directory of the parent
288    /// process at the time the child process is spawned.
289    ///
290    /// # Platform-specific behavior
291    ///
292    /// If the program path is relative (e.g., `"./script.sh"`), it's ambiguous
293    /// whether it should be interpreted relative to the parent's working
294    /// directory or relative to `current_dir`. The behavior in this case is
295    /// platform specific and unstable, and it's recommended to use
296    /// [`canonicalize`] to get an absolute program path instead.
297    ///
298    /// [`canonicalize`]: std::fs::canonicalize()
299    ///
300    /// # Examples
301    ///
302    /// Basic usage:
303    ///
304    /// ```no_run
305    /// use reverie_process::Command;
306    ///
307    /// let command = Command::new("ls").current_dir("/bin");
308    /// ```
309    pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Self {
310        self.container.current_dir(dir);
311        self
312    }
313
314    /// Sets configuration for the child process's standard input (stdin) handle.
315    ///
316    /// Defaults to [`Stdio::inherit`] when used with `spawn` or `status`, and
317    /// defaults to [`Stdio::piped`] when used with `output`.
318    ///
319    /// # Examples
320    ///
321    /// Basic usage:
322    ///
323    /// ```no_run
324    /// use reverie_process::Command;
325    /// use reverie_process::Stdio;
326    ///
327    /// let command = Command::new("ls").stdin(Stdio::null());
328    /// ```
329    pub fn stdin<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Self {
330        self.container.stdin(cfg);
331        self
332    }
333
334    /// Sets configuration for the child process's standard output (stdout)
335    /// handle.
336    ///
337    /// Defaults to [`Stdio::inherit`] when used with `spawn` or `status`, and
338    /// defaults to [`Stdio::piped`] when used with `output`.
339    ///
340    /// # Examples
341    ///
342    /// Basic usage:
343    ///
344    /// ```no_run
345    /// use reverie_process::Command;
346    /// use reverie_process::Stdio;
347    ///
348    /// let command = Command::new("ls").stdout(Stdio::null());
349    /// ```
350    pub fn stdout<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Self {
351        self.container.stdout(cfg);
352        self
353    }
354
355    /// Sets configuration for the child process's standard error (stderr)
356    /// handle.
357    ///
358    /// Defaults to [`Stdio::inherit`] when used with `spawn` or `status`, and
359    /// defaults to [`Stdio::piped`] when used with `output`.
360    ///
361    /// # Examples
362    ///
363    /// Basic usage:
364    ///
365    /// ```no_run
366    /// use reverie_process::Command;
367    /// use reverie_process::Stdio;
368    ///
369    /// let command = Command::new("ls").stderr(Stdio::null());
370    /// ```
371    pub fn stderr<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Self {
372        self.container.stderr(cfg);
373        self
374    }
375
376    /// Changes the root directory of the calling process to the specified path.
377    /// This directory will be inherited by all child processes of the calling
378    /// process.
379    ///
380    /// Note that changing the root directory may cause the program to not be
381    /// found. As such, the program path should be relative to this directory.
382    pub fn chroot<P: AsRef<Path>>(&mut self, chroot: P) -> &mut Self {
383        self.container.chroot(chroot);
384        self
385    }
386
387    /// Unshares parts of the process execution context that are normally shared
388    /// with the parent process. This is useful for executing the child process
389    /// in a new namespace.
390    pub fn unshare(&mut self, namespace: Namespace) -> &mut Self {
391        self.container.unshare(namespace);
392        self
393    }
394
395    /// Schedules a closure to be run just before the `exec` function is invoked.
396    ///
397    /// The closure is allowed to return an I/O error whose OS error code will be
398    /// communicated back to the parent and returned as an error from when the
399    /// spawn was requested.
400    ///
401    /// Multiple closures can be registered and they will be called in order of
402    /// their registration. If a closure returns `Err` then no further closures
403    /// will be called and the spawn operation will immediately return with a
404    /// failure.
405    ///
406    /// # Safety
407    ///
408    /// This closure will be run in the context of the child process after a
409    /// `fork`. This primarily means that any modifications made to memory on
410    /// behalf of this closure will **not** be visible to the parent process.
411    /// This is often a very constrained environment where normal operations like
412    /// `malloc` or acquiring a mutex are not guaranteed to work (due to other
413    /// threads perhaps still running when the `fork` was run).
414    ///
415    /// This also means that all resources such as file descriptors and
416    /// memory-mapped regions got duplicated. It is your responsibility to make
417    /// sure that the closure does not violate library invariants by making
418    /// invalid use of these duplicates.
419    ///
420    /// When this closure is run, aspects such as the stdio file descriptors and
421    /// working directory have successfully been changed, so output to these
422    /// locations may not appear where intended.
423    pub unsafe fn pre_exec<F>(&mut self, f: F) -> &mut Self
424    where
425        F: FnMut() -> Result<(), Errno> + Send + Sync + 'static,
426    {
427        self.pre_exec.push(Box::new(f));
428        self
429    }
430
431    /// Select a trusted terminal entry for the final original `execve`.
432    ///
433    /// The supplied entry receives the same prepared program, argv and envp
434    /// used by ordinary spawn. No PATH search, script fallback or vector
435    /// rewrite is performed on this path. A relative program is refused.
436    ///
437    /// # Safety
438    /// The caller qualifies the actual entry, child setup, inherited filter
439    /// and gate mapping. The entry must allocate and free nothing, preserve
440    /// all supplied vector bytes, issue the actual original target exec and
441    /// terminate through the surviving gate on every returned kernel error.
442    /// No replacement helper image or success-return path is permitted.
443    pub unsafe fn terminal_execve(&mut self, entry: super::TerminalExecve) -> &mut Self {
444        self.terminal_execve = Some(entry);
445        self
446    }
447
448    /// Returns the path to the program that was given to [`Command::new`].
449    ///
450    /// # Examples
451    ///
452    /// ```
453    /// use reverie_process::Command;
454    ///
455    /// let cmd = Command::new("echo");
456    /// assert_eq!(cmd.get_program(), "echo");
457    /// ```
458    pub fn get_program(&self) -> &OsStr {
459        OsStr::from_bytes(self.program.to_bytes())
460    }
461
462    /// Returns the working directory for the child process.
463    ///
464    /// This returns None if the working directory will not be changed.
465    pub fn get_current_dir(&self) -> Option<&Path> {
466        self.container.get_current_dir()
467    }
468
469    /// Returns an iterator of the environment variables that will be set when
470    /// the process is spawned. Note that this does not include any environment
471    /// variables inherited from the parent process.
472    pub fn get_envs(&self) -> impl Iterator<Item = (&OsStr, Option<&OsStr>)> {
473        self.container.get_envs()
474    }
475
476    /// Returns a mapping of all environment variables that the new child process
477    /// will inherit.
478    pub fn get_captured_envs(&self) -> BTreeMap<OsString, OsString> {
479        self.container.get_captured_envs()
480    }
481
482    /// Gets an environment variable. If the child process is to inherit this
483    /// environment variable from the current process, then this returns the
484    /// current process's environment variable unless it is to be overridden.
485    pub fn get_env<K: AsRef<OsStr>>(&self, env: K) -> Option<Cow<'_, OsStr>> {
486        self.container.get_env(env)
487    }
488
489    /// Maps one user ID to another.
490    ///
491    /// Implies `Namespace::USER`.
492    ///
493    /// # Example
494    ///
495    /// This is can be used to gain `CAP_SYS_ADMIN` privileges in the user
496    /// namespace by mapping the root user inside the container to the current
497    /// user outside of the container.
498    ///
499    /// ```no_run
500    /// use reverie_process::Command;
501    ///
502    /// let command = Command::new("ls").map_uid(1, unsafe { libc::getuid() });
503    /// ```
504    ///
505    /// # Implementation
506    ///
507    /// This modifies `/proc/{pid}/uid_map` where `{pid}` is the PID of the child
508    /// process. See [`user_namespaces(7)`] for more details.
509    ///
510    /// [`user_namespaces(7)`]: https://man7.org/linux/man-pages/man7/user_namespaces.7.html
511    pub fn map_uid(&mut self, inside_uid: libc::uid_t, outside_uid: libc::uid_t) -> &mut Self {
512        self.container.map_uid(inside_uid, outside_uid);
513        self
514    }
515
516    /// Maps potentially many user IDs inside the new user namespace to user IDs
517    /// outside of the user namespace.
518    ///
519    /// Implies `Namespace::USER`.
520    ///
521    /// # Implementation
522    ///
523    /// This modifies `/proc/{pid}/uid_map` where `{pid}` is the PID of the child
524    /// process. See [`user_namespaces(7)`] for more details.
525    ///
526    /// [`user_namespaces(7)`]: https://man7.org/linux/man-pages/man7/user_namespaces.7.html
527    pub fn map_uid_range(
528        &mut self,
529        starting_inside_uid: libc::uid_t,
530        starting_outside_uid: libc::uid_t,
531        count: u32,
532    ) -> &mut Self {
533        self.container
534            .map_uid_range(starting_inside_uid, starting_outside_uid, count);
535        self
536    }
537
538    /// Convience function for mapping root (inside the container) to the current
539    /// user ID (outside the container). This is useful for gaining new
540    /// capabilities inside the container, such as being able to mount file
541    /// systems.
542    ///
543    /// Implies `Namespace::USER`.
544    ///
545    /// This is the same as:
546    /// ```no_run
547    /// use reverie_process::Command;
548    ///
549    /// let command = Command::new("ls")
550    ///     .map_uid(0, unsafe { libc::geteuid() })
551    ///     .map_gid(0, unsafe { libc::getegid() });
552    /// ```
553    pub fn map_root(&mut self) -> &mut Self {
554        self.container.map_root();
555        self
556    }
557
558    /// Maps one group ID to another.
559    ///
560    /// Implies `Namespace::USER`.
561    ///
562    /// # Implementation
563    ///
564    /// This modifies `/proc/{pid}/gid_map` where `{pid}` is the PID of the child
565    /// process. See [`user_namespaces(7)`] for more details.
566    ///
567    /// [`user_namespaces(7)`]: https://man7.org/linux/man-pages/man7/user_namespaces.7.html
568    pub fn map_gid(&mut self, inside_gid: libc::gid_t, outside_gid: libc::gid_t) -> &mut Self {
569        self.container.map_gid(inside_gid, outside_gid);
570        self
571    }
572
573    /// Maps potentially many group IDs inside the new user namespace to group
574    /// IDs outside of the user namespace.
575    ///
576    /// Implies `Namespace::USER`.
577    ///
578    /// # Implementation
579    ///
580    /// This modifies `/proc/{pid}/gid_map` where `{pid}` is the PID of the child
581    /// process. See [`user_namespaces(7)`] for more details.
582    ///
583    /// [`user_namespaces(7)`]: https://man7.org/linux/man-pages/man7/user_namespaces.7.html
584    pub fn map_gid_range(
585        &mut self,
586        starting_inside_gid: libc::gid_t,
587        starting_outside_gid: libc::gid_t,
588        count: u32,
589    ) -> &mut Self {
590        self.container
591            .map_gid_range(starting_inside_gid, starting_outside_gid, count);
592        self
593    }
594
595    /// Sets the hostname of the container.
596    ///
597    /// Implies `Namespace::UTS`, which requires `CAP_SYS_ADMIN`.
598    ///
599    /// ```no_run
600    /// use reverie_process::Command;
601    ///
602    /// let command = Command::new("cat")
603    ///     .arg("/proc/sys/kernel/hostname")
604    ///     .map_root()
605    ///     .hostname("foobar.local");
606    /// ```
607    pub fn hostname<S: Into<OsString>>(&mut self, hostname: S) -> &mut Self {
608        self.container.hostname(hostname);
609        self
610    }
611
612    /// Sets the domain name of the container.
613    ///
614    /// Implies `Namespace::UTS`, which requires `CAP_SYS_ADMIN`.
615    ///
616    /// # Example
617    ///
618    /// ```no_run
619    /// use reverie_process::Command;
620    ///
621    /// let command = Command::new("cat")
622    ///     .arg("/proc/sys/kernel/domainname")
623    ///     .map_root()
624    ///     .domainname("foobar");
625    /// ```
626    pub fn domainname<S: Into<OsString>>(&mut self, domainname: S) -> &mut Self {
627        self.container.domainname(domainname);
628        self
629    }
630
631    /// Gets the hostname of the container.
632    pub fn get_hostname(&self) -> Option<&OsStr> {
633        self.container.get_hostname()
634    }
635
636    /// Gets the domainname of the container.
637    pub fn get_domainname(&self) -> Option<&OsStr> {
638        self.container.get_domainname()
639    }
640
641    /// Adds a file system to be mounted. Note that these are mounted in the same
642    /// order as given.
643    ///
644    /// Implies `Namespace::MOUNT`. Note that `Namespace::USER` should also have
645    /// been set and `map_uid` should have been called in order to gain the
646    /// privileges required to mount.
647    pub fn mount(&mut self, mount: Mount) -> &mut Self {
648        self.container.mount(mount);
649        self
650    }
651
652    /// Adds multiple mounts.
653    pub fn mounts<I>(&mut self, mounts: I) -> &mut Self
654    where
655        I: IntoIterator<Item = Mount>,
656    {
657        self.container.mounts(mounts);
658        self
659    }
660
661    /// Sets up the container to have local networking only. This will prevent
662    /// any network communication to the outside world.
663    ///
664    /// Implies `Namespace::NETWORK` and `Namespace::MOUNT`.
665    ///
666    /// This also causes a fresh `/sys` to be mounted to avoid seeing the host
667    /// network interfaces in `/sys/class/net`.
668    pub fn local_networking_only(&mut self) -> &mut Self {
669        self.container.local_networking_only();
670        self
671    }
672
673    /// Sets the seccomp filter. The filter is loaded immediately before `execve`
674    /// and *after* all `pre_exec` callbacks have been executed. Thus, you will
675    /// still be able to call filtered syscalls from `pre_exec` callbacks.
676    pub fn seccomp(&mut self, filter: seccomp::Filter) -> &mut Self {
677        self.container.seccomp(filter);
678        self
679    }
680
681    /// Indicates that we want to listen for seccomp events using
682    /// [seccomp_unotify(2)](https://man7.org/linux/man-pages/man2/seccomp_unotify.2.html).
683    ///
684    /// If this is set, the seccomp listener file descriptor will be accessible
685    /// via the `Child`.
686    pub fn seccomp_notify(&mut self) -> &mut Self {
687        self.container.seccomp_notify();
688        self
689    }
690
691    /// Sets the controlling pseudoterminal for the child process).
692    ///
693    /// In the child process, this has the effect of:
694    ///  1. Creating a new session (with `setsid()`).
695    ///  2. Using an `ioctl` to set the controlling terminal.
696    ///  3. Setting this file descriptor as the stdio streams.
697    ///
698    /// NOTE: Since this modifies the stdio streams, calling this will reset
699    /// [`Self::stdin`], [`Self::stdout`], and [`Self::stderr`] back to
700    /// [`Stdio::inherit()`].
701    pub fn pty(&mut self, child: PtyChild) -> &mut Self {
702        self.container.pty(child);
703        self
704    }
705
706    /// Finds the path to the program.
707    pub fn find_program(&self) -> io::Result<PathBuf> {
708        let program = Path::new(self.get_program());
709
710        if program.is_absolute() {
711            // Note: We shouldn't canonicalize here since that will follow
712            // symlinks. Instead, just make sure the file exists and is
713            // executable.
714            let metadata = program.metadata()?;
715
716            if metadata.is_file() && metadata.permissions().mode() & 0o111 != 0 {
717                Ok(program.to_path_buf())
718            } else {
719                Err(Errno::EPERM.into())
720            }
721        } else if program.components().count() == 1 {
722            let path = self.get_env("PATH").unwrap_or_default();
723
724            let paths = path
725                .as_bytes()
726                .split(|c| *c == b':')
727                .map(|bytes| Path::new(OsStr::from_bytes(bytes)));
728
729            find_program_in_paths(program, paths)
730                .ok_or_else(|| io::Error::other(format!("Could not find {:?} in $PATH", program)))
731                .map(path::absolute)?
732        } else {
733            // Assume it's in the current directory
734            let mut path = match self.get_current_dir() {
735                Some(path) => path.to_owned(),
736                None => std::env::current_dir()?,
737            };
738            path.push(program);
739            path.canonicalize()
740        }
741    }
742}
743
744fn find_program_in_paths<I, S>(program: &Path, iter: I) -> Option<PathBuf>
745where
746    I: IntoIterator<Item = S>,
747    S: AsRef<Path>,
748{
749    for path in iter.into_iter() {
750        let path = path.as_ref().join(program);
751        if let Ok(metadata) = path.metadata()
752            && metadata.is_file()
753        {
754            if metadata.permissions().mode() & 0o111 != 0 {
755                return Some(path);
756            } else {
757                continue;
758            }
759
760            #[cfg(not(unix))]
761            return Some(path);
762        }
763    }
764
765    None
766}
767
768#[cfg(test)]
769mod tests {
770    use super::*;
771
772    #[test]
773    fn find_program() {
774        assert!(Command::new("cat").find_program().unwrap().is_absolute(),);
775    }
776
777    #[test]
778    fn get_program() {
779        assert_eq!(Command::new("cat").get_program(), "cat");
780    }
781
782    #[test]
783    fn get_arg0() {
784        assert_eq!(Command::new("cat").get_arg0(), "cat");
785        assert_eq!(Command::new("cat").arg0("dog").get_arg0(), "dog");
786        assert_eq!(
787            Command::new("cat").arg0("dog").program("catdog").get_arg0(),
788            "catdog"
789        );
790    }
791
792    #[test]
793    fn get_args() {
794        assert_eq!(
795            Command::new("cat")
796                .arg("a")
797                .arg("b")
798                .arg("c")
799                .get_args()
800                .collect::<Vec<_>>(),
801            &[OsStr::new("a"), OsStr::new("b"), OsStr::new("c")]
802        );
803    }
804
805    #[test]
806    fn prepend_args() {
807        let mut command = Command::new("echo");
808        command.args(["1", "2", "3"]);
809        command.prepend_args(["a", "b", "c"]);
810        assert_eq!(command.get_arg0(), "echo");
811
812        let args = command.get_args().collect::<Vec<_>>();
813        assert_eq!(
814            args,
815            &[
816                OsStr::new("a"),
817                "b".as_ref(),
818                "c".as_ref(),
819                "1".as_ref(),
820                "2".as_ref(),
821                "3".as_ref()
822            ]
823        );
824    }
825}