std/
env.rs

1//! Inspection and manipulation of the process's environment.
2//!
3//! This module contains functions to inspect various aspects such as
4//! environment variables, process arguments, the current directory, and various
5//! other important directories.
6//!
7//! There are several functions and structs in this module that have a
8//! counterpart ending in `os`. Those ending in `os` will return an [`OsString`]
9//! and those without will return a [`String`].
10
11#![stable(feature = "env", since = "1.0.0")]
12
13use crate::error::Error;
14use crate::ffi::{OsStr, OsString};
15use crate::num::NonZero;
16use crate::ops::Try;
17use crate::path::{Path, PathBuf};
18use crate::sys::{env as env_imp, os as os_imp};
19use crate::{array, fmt, io, sys};
20
21/// Returns the current working directory as a [`PathBuf`].
22///
23/// # Platform-specific behavior
24///
25/// This function [currently] corresponds to the `getcwd` function on Unix
26/// and the `GetCurrentDirectoryW` function on Windows.
27///
28/// [currently]: crate::io#platform-specific-behavior
29///
30/// # Errors
31///
32/// Returns an [`Err`] if the current working directory value is invalid.
33/// Possible cases:
34///
35/// * Current directory does not exist.
36/// * There are insufficient permissions to access the current directory.
37///
38/// # Examples
39///
40/// ```
41/// use std::env;
42///
43/// fn main() -> std::io::Result<()> {
44///     let path = env::current_dir()?;
45///     println!("The current directory is {}", path.display());
46///     Ok(())
47/// }
48/// ```
49#[doc(alias = "pwd")]
50#[doc(alias = "getcwd")]
51#[doc(alias = "GetCurrentDirectory")]
52#[stable(feature = "env", since = "1.0.0")]
53pub fn current_dir() -> io::Result<PathBuf> {
54    os_imp::getcwd()
55}
56
57/// Changes the current working directory to the specified path.
58///
59/// # Platform-specific behavior
60///
61/// This function [currently] corresponds to the `chdir` function on Unix
62/// and the `SetCurrentDirectoryW` function on Windows.
63///
64/// Returns an [`Err`] if the operation fails.
65///
66/// [currently]: crate::io#platform-specific-behavior
67///
68/// # Examples
69///
70/// ```ignore-vxworks
71/// # // AdaCore: On VxWorks, '/' is not a queryable file system root
72/// use std::env;
73/// use std::path::Path;
74///
75/// let root = Path::new("/");
76/// assert!(env::set_current_dir(&root).is_ok());
77/// println!("Successfully changed working directory to {}!", root.display());
78/// ```
79#[doc(alias = "chdir", alias = "SetCurrentDirectory", alias = "SetCurrentDirectoryW")]
80#[stable(feature = "env", since = "1.0.0")]
81pub fn set_current_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
82    os_imp::chdir(path.as_ref())
83}
84
85/// An iterator over a snapshot of the environment variables of this process.
86///
87/// This structure is created by [`env::vars()`]. See its documentation for more.
88///
89/// [`env::vars()`]: vars
90#[stable(feature = "env", since = "1.0.0")]
91pub struct Vars {
92    inner: VarsOs,
93}
94
95/// An iterator over a snapshot of the environment variables of this process.
96///
97/// This structure is created by [`env::vars_os()`]. See its documentation for more.
98///
99/// [`env::vars_os()`]: vars_os
100#[stable(feature = "env", since = "1.0.0")]
101pub struct VarsOs {
102    inner: env_imp::Env,
103}
104
105/// Returns an iterator of (variable, value) pairs of strings, for all the
106/// environment variables of the current process.
107///
108/// The returned iterator contains a snapshot of the process's environment
109/// variables at the time of this invocation. Modifications to environment
110/// variables afterwards will not be reflected in the returned iterator.
111///
112/// # Panics
113///
114/// While iterating, the returned iterator will panic if any key or value in the
115/// environment is not valid unicode. If this is not desired, consider using
116/// [`env::vars_os()`].
117///
118/// # Examples
119///
120/// ```
121/// // Print all environment variables.
122/// for (key, value) in std::env::vars() {
123///     println!("{key}: {value}");
124/// }
125/// ```
126///
127/// [`env::vars_os()`]: vars_os
128#[must_use]
129#[stable(feature = "env", since = "1.0.0")]
130pub fn vars() -> Vars {
131    Vars { inner: vars_os() }
132}
133
134/// Returns an iterator of (variable, value) pairs of OS strings, for all the
135/// environment variables of the current process.
136///
137/// The returned iterator contains a snapshot of the process's environment
138/// variables at the time of this invocation. Modifications to environment
139/// variables afterwards will not be reflected in the returned iterator.
140///
141/// Note that the returned iterator will not check if the environment variables
142/// are valid Unicode. If you want to panic on invalid UTF-8,
143/// use the [`vars`] function instead.
144///
145/// # Examples
146///
147/// ```
148/// // Print all environment variables.
149/// for (key, value) in std::env::vars_os() {
150///     println!("{key:?}: {value:?}");
151/// }
152/// ```
153#[must_use]
154#[stable(feature = "env", since = "1.0.0")]
155pub fn vars_os() -> VarsOs {
156    VarsOs { inner: env_imp::env() }
157}
158
159#[stable(feature = "env", since = "1.0.0")]
160impl Iterator for Vars {
161    type Item = (String, String);
162    fn next(&mut self) -> Option<(String, String)> {
163        self.inner.next().map(|(a, b)| (a.into_string().unwrap(), b.into_string().unwrap()))
164    }
165    fn size_hint(&self) -> (usize, Option<usize>) {
166        self.inner.size_hint()
167    }
168}
169
170#[stable(feature = "std_debug", since = "1.16.0")]
171impl fmt::Debug for Vars {
172    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
173        let Self { inner: VarsOs { inner } } = self;
174        f.debug_struct("Vars").field("inner", inner).finish()
175    }
176}
177
178#[stable(feature = "env", since = "1.0.0")]
179impl Iterator for VarsOs {
180    type Item = (OsString, OsString);
181    fn next(&mut self) -> Option<(OsString, OsString)> {
182        self.inner.next()
183    }
184    fn size_hint(&self) -> (usize, Option<usize>) {
185        self.inner.size_hint()
186    }
187}
188
189#[stable(feature = "std_debug", since = "1.16.0")]
190impl fmt::Debug for VarsOs {
191    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192        let Self { inner } = self;
193        f.debug_struct("VarsOs").field("inner", inner).finish()
194    }
195}
196
197/// Fetches the environment variable `key` from the current process.
198///
199/// # Errors
200///
201/// Returns [`VarError::NotPresent`] if:
202/// - The variable is not set.
203/// - The variable's name contains an equal sign or NUL (`'='` or `'\0'`).
204///
205/// Returns [`VarError::NotUnicode`] if the variable's value is not valid
206/// Unicode. If this is not desired, consider using [`var_os`].
207///
208/// Use [`env!`] or [`option_env!`] instead if you want to check environment
209/// variables at compile time.
210///
211/// # Examples
212///
213/// ```
214/// use std::env;
215///
216/// let key = "HOME";
217/// match env::var(key) {
218///     Ok(val) => println!("{key}: {val:?}"),
219///     Err(e) => println!("couldn't interpret {key}: {e}"),
220/// }
221/// ```
222#[stable(feature = "env", since = "1.0.0")]
223pub fn var<K: AsRef<OsStr>>(key: K) -> Result<String, VarError> {
224    _var(key.as_ref())
225}
226
227fn _var(key: &OsStr) -> Result<String, VarError> {
228    match var_os(key) {
229        Some(s) => s.into_string().map_err(VarError::NotUnicode),
230        None => Err(VarError::NotPresent),
231    }
232}
233
234/// Fetches the environment variable `key` from the current process, returning
235/// [`None`] if the variable isn't set or if there is another error.
236///
237/// It may return `None` if the environment variable's name contains
238/// the equal sign character (`=`) or the NUL character.
239///
240/// Note that this function will not check if the environment variable
241/// is valid Unicode. If you want to have an error on invalid UTF-8,
242/// use the [`var`] function instead.
243///
244/// # Examples
245///
246/// ```
247/// use std::env;
248///
249/// let key = "HOME";
250/// match env::var_os(key) {
251///     Some(val) => println!("{key}: {val:?}"),
252///     None => println!("{key} is not defined in the environment.")
253/// }
254/// ```
255///
256/// If expecting a delimited variable (such as `PATH`), [`split_paths`]
257/// can be used to separate items.
258#[must_use]
259#[stable(feature = "env", since = "1.0.0")]
260pub fn var_os<K: AsRef<OsStr>>(key: K) -> Option<OsString> {
261    _var_os(key.as_ref())
262}
263
264fn _var_os(key: &OsStr) -> Option<OsString> {
265    env_imp::getenv(key)
266}
267
268/// The error type for operations interacting with environment variables.
269/// Possibly returned from [`env::var()`].
270///
271/// [`env::var()`]: var
272#[derive(Debug, PartialEq, Eq, Clone)]
273#[stable(feature = "env", since = "1.0.0")]
274pub enum VarError {
275    /// The specified environment variable was not present in the current
276    /// process's environment.
277    #[stable(feature = "env", since = "1.0.0")]
278    NotPresent,
279
280    /// The specified environment variable was found, but it did not contain
281    /// valid unicode data. The found data is returned as a payload of this
282    /// variant.
283    #[stable(feature = "env", since = "1.0.0")]
284    NotUnicode(#[stable(feature = "env", since = "1.0.0")] OsString),
285}
286
287#[stable(feature = "env", since = "1.0.0")]
288impl fmt::Display for VarError {
289    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
290        match *self {
291            VarError::NotPresent => write!(f, "environment variable not found"),
292            VarError::NotUnicode(ref s) => {
293                write!(f, "environment variable was not valid unicode: {:?}", s)
294            }
295        }
296    }
297}
298
299#[stable(feature = "env", since = "1.0.0")]
300impl Error for VarError {}
301
302/// Sets the environment variable `key` to the value `value` for the currently running
303/// process.
304///
305/// # Safety
306///
307/// This function is safe to call in a single-threaded program.
308///
309/// This function is also always safe to call on Windows, in single-threaded
310/// and multi-threaded programs.
311///
312/// In multi-threaded programs on other operating systems, the only safe option is
313/// to not use `set_var` or `remove_var` at all.
314///
315/// The exact requirement is: you
316/// must ensure that there are no other threads concurrently writing or
317/// *reading*(!) the environment through functions or global variables other
318/// than the ones in this module. The problem is that these operating systems
319/// do not provide a thread-safe way to read the environment, and most C
320/// libraries, including libc itself, do not advertise which functions read
321/// from the environment. Even functions from the Rust standard library may
322/// read the environment without going through this module, e.g. for DNS
323/// lookups from [`std::net::ToSocketAddrs`]. No stable guarantee is made about
324/// which functions may read from the environment in future versions of a
325/// library. All this makes it not practically possible for you to guarantee
326/// that no other thread will read the environment, so the only safe option is
327/// to not use `set_var` or `remove_var` in multi-threaded programs at all.
328///
329/// Discussion of this unsafety on Unix may be found in:
330///
331///  - [Austin Group Bugzilla (for POSIX)](https://austingroupbugs.net/view.php?id=188)
332///  - [GNU C library Bugzilla](https://sourceware.org/bugzilla/show_bug.cgi?id=15607#c2)
333///
334/// To pass an environment variable to a child process, you can instead use [`Command::env`].
335///
336/// [`std::net::ToSocketAddrs`]: crate::net::ToSocketAddrs
337/// [`Command::env`]: crate::process::Command::env
338///
339/// # Panics
340///
341/// This function may panic if `key` is empty, contains an ASCII equals sign `'='`
342/// or the NUL character `'\0'`, or when `value` contains the NUL character.
343///
344/// # Examples
345///
346/// ```
347/// use std::env;
348///
349/// let key = "KEY";
350/// unsafe {
351///     env::set_var(key, "VALUE");
352/// }
353/// assert_eq!(env::var(key), Ok("VALUE".to_string()));
354/// ```
355#[rustc_deprecated_safe_2024(
356    audit_that = "the environment access only happens in single-threaded code"
357)]
358#[stable(feature = "env", since = "1.0.0")]
359pub unsafe fn set_var<K: AsRef<OsStr>, V: AsRef<OsStr>>(key: K, value: V) {
360    let (key, value) = (key.as_ref(), value.as_ref());
361    unsafe { env_imp::setenv(key, value) }.unwrap_or_else(|e| {
362        panic!("failed to set environment variable `{key:?}` to `{value:?}`: {e}")
363    })
364}
365
366/// Removes an environment variable from the environment of the currently running process.
367///
368/// # Safety
369///
370/// This function is safe to call in a single-threaded program.
371///
372/// This function is also always safe to call on Windows, in single-threaded
373/// and multi-threaded programs.
374///
375/// In multi-threaded programs on other operating systems, the only safe option is
376/// to not use `set_var` or `remove_var` at all.
377///
378/// The exact requirement is: you
379/// must ensure that there are no other threads concurrently writing or
380/// *reading*(!) the environment through functions or global variables other
381/// than the ones in this module. The problem is that these operating systems
382/// do not provide a thread-safe way to read the environment, and most C
383/// libraries, including libc itself, do not advertise which functions read
384/// from the environment. Even functions from the Rust standard library may
385/// read the environment without going through this module, e.g. for DNS
386/// lookups from [`std::net::ToSocketAddrs`]. No stable guarantee is made about
387/// which functions may read from the environment in future versions of a
388/// library. All this makes it not practically possible for you to guarantee
389/// that no other thread will read the environment, so the only safe option is
390/// to not use `set_var` or `remove_var` in multi-threaded programs at all.
391///
392/// Discussion of this unsafety on Unix may be found in:
393///
394///  - [Austin Group Bugzilla](https://austingroupbugs.net/view.php?id=188)
395///  - [GNU C library Bugzilla](https://sourceware.org/bugzilla/show_bug.cgi?id=15607#c2)
396///
397/// To prevent a child process from inheriting an environment variable, you can
398/// instead use [`Command::env_remove`] or [`Command::env_clear`].
399///
400/// [`std::net::ToSocketAddrs`]: crate::net::ToSocketAddrs
401/// [`Command::env_remove`]: crate::process::Command::env_remove
402/// [`Command::env_clear`]: crate::process::Command::env_clear
403///
404/// # Panics
405///
406/// This function may panic if `key` is empty, contains an ASCII equals sign
407/// `'='` or the NUL character `'\0'`, or when the value contains the NUL
408/// character.
409///
410/// # Examples
411///
412/// ```no_run
413/// use std::env;
414///
415/// let key = "KEY";
416/// unsafe {
417///     env::set_var(key, "VALUE");
418/// }
419/// assert_eq!(env::var(key), Ok("VALUE".to_string()));
420///
421/// unsafe {
422///     env::remove_var(key);
423/// }
424/// assert!(env::var(key).is_err());
425/// ```
426#[rustc_deprecated_safe_2024(
427    audit_that = "the environment access only happens in single-threaded code"
428)]
429#[stable(feature = "env", since = "1.0.0")]
430pub unsafe fn remove_var<K: AsRef<OsStr>>(key: K) {
431    let key = key.as_ref();
432    unsafe { env_imp::unsetenv(key) }
433        .unwrap_or_else(|e| panic!("failed to remove environment variable `{key:?}`: {e}"))
434}
435
436/// An iterator that splits an environment variable into paths according to
437/// platform-specific conventions.
438///
439/// The iterator element type is [`PathBuf`].
440///
441/// This structure is created by [`env::split_paths()`]. See its
442/// documentation for more.
443///
444/// [`env::split_paths()`]: split_paths
445#[must_use = "iterators are lazy and do nothing unless consumed"]
446#[stable(feature = "env", since = "1.0.0")]
447pub struct SplitPaths<'a> {
448    inner: os_imp::SplitPaths<'a>,
449}
450
451/// Parses input according to platform conventions for the `PATH`
452/// environment variable.
453///
454/// Returns an iterator over the paths contained in `unparsed`. The iterator
455/// element type is [`PathBuf`].
456///
457/// On most Unix platforms, the separator is `:` and on Windows it is `;`. This
458/// also performs unquoting on Windows.
459///
460/// [`join_paths`] can be used to recombine elements.
461///
462/// # Panics
463///
464/// This will panic on systems where there is no delimited `PATH` variable,
465/// such as UEFI.
466///
467/// # Examples
468///
469/// ```
470/// use std::env;
471///
472/// let key = "PATH";
473/// match env::var_os(key) {
474///     Some(paths) => {
475///         for path in env::split_paths(&paths) {
476///             println!("'{}'", path.display());
477///         }
478///     }
479///     None => println!("{key} is not defined in the environment.")
480/// }
481/// ```
482#[stable(feature = "env", since = "1.0.0")]
483pub fn split_paths<T: AsRef<OsStr> + ?Sized>(unparsed: &T) -> SplitPaths<'_> {
484    SplitPaths { inner: os_imp::split_paths(unparsed.as_ref()) }
485}
486
487#[stable(feature = "env", since = "1.0.0")]
488impl<'a> Iterator for SplitPaths<'a> {
489    type Item = PathBuf;
490    fn next(&mut self) -> Option<PathBuf> {
491        self.inner.next()
492    }
493    fn size_hint(&self) -> (usize, Option<usize>) {
494        self.inner.size_hint()
495    }
496}
497
498#[stable(feature = "std_debug", since = "1.16.0")]
499impl fmt::Debug for SplitPaths<'_> {
500    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
501        f.debug_struct("SplitPaths").finish_non_exhaustive()
502    }
503}
504
505/// The error type for operations on the `PATH` variable. Possibly returned from
506/// [`env::join_paths()`].
507///
508/// [`env::join_paths()`]: join_paths
509#[derive(Debug)]
510#[stable(feature = "env", since = "1.0.0")]
511pub struct JoinPathsError {
512    inner: os_imp::JoinPathsError,
513}
514
515/// Joins a collection of [`Path`]s appropriately for the `PATH`
516/// environment variable.
517///
518/// # Errors
519///
520/// Returns an [`Err`] (containing an error message) if one of the input
521/// [`Path`]s contains an invalid character for constructing the `PATH`
522/// variable (a double quote on Windows or a colon on Unix), or if the system
523/// does not have a `PATH`-like variable (e.g. UEFI or WASI).
524///
525/// # Examples
526///
527/// Joining paths on a Unix-like platform:
528///
529/// ```
530/// use std::env;
531/// use std::ffi::OsString;
532/// use std::path::Path;
533///
534/// fn main() -> Result<(), env::JoinPathsError> {
535/// # if cfg!(unix) {
536///     let paths = [Path::new("/bin"), Path::new("/usr/bin")];
537///     let path_os_string = env::join_paths(paths.iter())?;
538///     assert_eq!(path_os_string, OsString::from("/bin:/usr/bin"));
539/// # }
540///     Ok(())
541/// }
542/// ```
543///
544/// Joining a path containing a colon on a Unix-like platform results in an
545/// error:
546///
547/// ```
548/// # if cfg!(unix) {
549/// use std::env;
550/// use std::path::Path;
551///
552/// let paths = [Path::new("/bin"), Path::new("/usr/bi:n")];
553/// assert!(env::join_paths(paths.iter()).is_err());
554/// # }
555/// ```
556///
557/// Using `env::join_paths()` with [`env::split_paths()`] to append an item to
558/// the `PATH` environment variable:
559///
560/// ```
561/// use std::env;
562/// use std::path::PathBuf;
563///
564/// fn main() -> Result<(), env::JoinPathsError> {
565///     if let Some(path) = env::var_os("PATH") {
566///         let mut paths = env::split_paths(&path).collect::<Vec<_>>();
567///         paths.push(PathBuf::from("/home/xyz/bin"));
568///         let new_path = env::join_paths(paths)?;
569///         unsafe { env::set_var("PATH", &new_path); }
570///     }
571///
572///     Ok(())
573/// }
574/// ```
575///
576/// [`env::split_paths()`]: split_paths
577#[stable(feature = "env", since = "1.0.0")]
578pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
579where
580    I: IntoIterator<Item = T>,
581    T: AsRef<OsStr>,
582{
583    os_imp::join_paths(paths.into_iter()).map_err(|e| JoinPathsError { inner: e })
584}
585
586#[stable(feature = "env", since = "1.0.0")]
587impl fmt::Display for JoinPathsError {
588    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
589        self.inner.fmt(f)
590    }
591}
592
593#[stable(feature = "env", since = "1.0.0")]
594impl Error for JoinPathsError {
595    #[allow(deprecated, deprecated_in_future)]
596    fn description(&self) -> &str {
597        self.inner.description()
598    }
599}
600
601/// Returns the path of the current user's home directory if known.
602///
603/// This may return `None` if getting the directory fails or if the platform does not have user home directories.
604///
605/// For storing user data and configuration it is often preferable to use more specific directories.
606/// For example, [XDG Base Directories] on Unix or the `LOCALAPPDATA` and `APPDATA` environment variables on Windows.
607///
608/// [XDG Base Directories]: https://specifications.freedesktop.org/basedir-spec/latest/
609///
610/// # Unix
611///
612/// - Returns the value of the 'HOME' environment variable if it is set
613///   (and not an empty string).
614/// - Otherwise, it tries to determine the home directory by invoking the `getpwuid_r` function
615///   using the UID of the current user. An empty home directory field returned from the
616///   `getpwuid_r` function is considered to be a valid value.
617/// - Returns `None` if the current user has no entry in the /etc/passwd file.
618///
619/// # Windows
620///
621/// - Returns the value of the 'USERPROFILE' environment variable if it is set, and is not an empty string.
622/// - Otherwise, [`GetUserProfileDirectory`][msdn] is used to return the path. This may change in the future.
623///
624/// [msdn]: https://docs.microsoft.com/en-us/windows/win32/api/userenv/nf-userenv-getuserprofiledirectorya
625///
626/// In UWP (Universal Windows Platform) targets this function is unimplemented and always returns `None`.
627///
628/// Before Rust 1.85.0, this function used to return the value of the 'HOME' environment variable
629/// on Windows, which in Cygwin or Mingw environments could return non-standard paths like `/home/you`
630/// instead of `C:\Users\you`.
631///
632/// # Examples
633///
634/// ```
635/// use std::env;
636///
637/// match env::home_dir() {
638///     Some(path) => println!("Your home directory, probably: {}", path.display()),
639///     None => println!("Impossible to get your home dir!"),
640/// }
641/// ```
642#[must_use]
643#[stable(feature = "env", since = "1.0.0")]
644pub fn home_dir() -> Option<PathBuf> {
645    os_imp::home_dir()
646}
647
648/// Returns the path of a temporary directory.
649///
650/// The temporary directory may be shared among users, or between processes
651/// with different privileges; thus, the creation of any files or directories
652/// in the temporary directory must use a secure method to create a uniquely
653/// named file. Creating a file or directory with a fixed or predictable name
654/// may result in "insecure temporary file" security vulnerabilities. Consider
655/// using a crate that securely creates temporary files or directories.
656///
657/// Note that the returned value may be a symbolic link, not a directory.
658///
659/// # Platform-specific behavior
660///
661/// On Unix, returns the value of the `TMPDIR` environment variable if it is
662/// set, otherwise the value is OS-specific:
663/// - On Android, there is no global temporary folder (it is usually allocated
664///   per-app), it will return the application's cache dir if the program runs
665///   in application's namespace and system version is Android 13 (or above), or
666///   `/data/local/tmp` otherwise.
667/// - On Darwin-based OSes (macOS, iOS, etc) it returns the directory provided
668///   by `confstr(_CS_DARWIN_USER_TEMP_DIR, ...)`, as recommended by [Apple's
669///   security guidelines][appledoc].
670/// - On all other unix-based OSes, it returns `/tmp`.
671///
672/// On Windows, the behavior is equivalent to that of [`GetTempPath2`][GetTempPath2] /
673/// [`GetTempPath`][GetTempPath], which this function uses internally.
674///
675/// Note that, this [may change in the future][changes].
676///
677/// [changes]: io#platform-specific-behavior
678/// [GetTempPath2]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-gettemppath2a
679/// [GetTempPath]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-gettemppatha
680/// [appledoc]: https://developer.apple.com/library/archive/documentation/Security/Conceptual/SecureCodingGuide/Articles/RaceConditions.html#//apple_ref/doc/uid/TP40002585-SW10
681///
682/// ```no_run
683/// use std::env;
684///
685/// fn main() {
686///     let dir = env::temp_dir();
687///     println!("Temporary directory: {}", dir.display());
688/// }
689/// ```
690#[must_use]
691#[doc(alias = "GetTempPath", alias = "GetTempPath2")]
692#[stable(feature = "env", since = "1.0.0")]
693pub fn temp_dir() -> PathBuf {
694    os_imp::temp_dir()
695}
696
697/// Returns the full filesystem path of the current running executable.
698///
699/// # Platform-specific behavior
700///
701/// If the executable was invoked through a symbolic link, some platforms will
702/// return the path of the symbolic link and other platforms will return the
703/// path of the symbolic link’s target.
704///
705/// If the executable is renamed while it is running, platforms may return the
706/// path at the time it was loaded instead of the new path.
707///
708/// # Errors
709///
710/// Acquiring the path of the current executable is a platform-specific operation
711/// that can fail for a good number of reasons. Some errors can include, but not
712/// be limited to, filesystem operations failing or general syscall failures.
713///
714/// # Security
715///
716/// The output of this function should not be trusted for anything
717/// that might have security implications. Basically, if users can run
718/// the executable, they can change the output arbitrarily.
719///
720/// As an example, you can easily introduce a race condition. It goes
721/// like this:
722///
723/// 1. You get the path to the current executable using `current_exe()`, and
724///    store it in a variable.
725/// 2. Time passes. A malicious actor removes the current executable, and
726///    replaces it with a malicious one.
727/// 3. You then use the stored path to re-execute the current
728///    executable.
729///
730/// You expected to safely execute the current executable, but you're
731/// instead executing something completely different. The code you
732/// just executed run with your privileges.
733///
734/// This sort of behavior has been known to [lead to privilege escalation] when
735/// used incorrectly.
736///
737/// [lead to privilege escalation]: https://securityvulns.com/Wdocument183.html
738///
739/// # Examples
740///
741/// ```
742/// use std::env;
743///
744/// match env::current_exe() {
745///     Ok(exe_path) => println!("Path of this executable is: {}",
746///                              exe_path.display()),
747///     Err(e) => println!("failed to get current exe path: {e}"),
748/// };
749/// ```
750#[stable(feature = "env", since = "1.0.0")]
751pub fn current_exe() -> io::Result<PathBuf> {
752    os_imp::current_exe()
753}
754
755/// An iterator over the arguments of a process, yielding a [`String`] value for
756/// each argument.
757///
758/// This struct is created by [`env::args()`]. See its documentation
759/// for more.
760///
761/// The first element is traditionally the path of the executable, but it can be
762/// set to arbitrary text, and might not even exist. This means this property
763/// should not be relied upon for security purposes.
764///
765/// [`env::args()`]: args
766#[must_use = "iterators are lazy and do nothing unless consumed"]
767#[stable(feature = "env", since = "1.0.0")]
768pub struct Args {
769    inner: ArgsOs,
770}
771
772/// An iterator over the arguments of a process, yielding an [`OsString`] value
773/// for each argument.
774///
775/// This struct is created by [`env::args_os()`]. See its documentation
776/// for more.
777///
778/// The first element is traditionally the path of the executable, but it can be
779/// set to arbitrary text, and might not even exist. This means this property
780/// should not be relied upon for security purposes.
781///
782/// [`env::args_os()`]: args_os
783#[must_use = "iterators are lazy and do nothing unless consumed"]
784#[stable(feature = "env", since = "1.0.0")]
785pub struct ArgsOs {
786    inner: sys::args::Args,
787}
788
789/// Returns the arguments that this program was started with (normally passed
790/// via the command line).
791///
792/// The first element is traditionally the path of the executable, but it can be
793/// set to arbitrary text, and might not even exist. This means this property should
794/// not be relied upon for security purposes.
795///
796/// On Unix systems the shell usually expands unquoted arguments with glob patterns
797/// (such as `*` and `?`). On Windows this is not done, and such arguments are
798/// passed as-is.
799///
800/// On glibc Linux systems, arguments are retrieved by placing a function in `.init_array`.
801/// glibc passes `argc`, `argv`, and `envp` to functions in `.init_array`, as a non-standard
802/// extension. This allows `std::env::args` to work even in a `cdylib` or `staticlib`, as it
803/// does on macOS and Windows.
804///
805/// # Panics
806///
807/// The returned iterator will panic during iteration if any argument to the
808/// process is not valid Unicode. If this is not desired,
809/// use the [`args_os`] function instead.
810///
811/// # Examples
812///
813/// ```
814/// use std::env;
815///
816/// // Prints each argument on a separate line
817/// for argument in env::args() {
818///     println!("{argument}");
819/// }
820/// ```
821#[stable(feature = "env", since = "1.0.0")]
822pub fn args() -> Args {
823    Args { inner: args_os() }
824}
825
826/// Returns the arguments that this program was started with (normally passed
827/// via the command line).
828///
829/// The first element is traditionally the path of the executable, but it can be
830/// set to arbitrary text, and might not even exist. This means this property should
831/// not be relied upon for security purposes.
832///
833/// On Unix systems the shell usually expands unquoted arguments with glob patterns
834/// (such as `*` and `?`). On Windows this is not done, and such arguments are
835/// passed as-is.
836///
837/// On glibc Linux systems, arguments are retrieved by placing a function in `.init_array`.
838/// glibc passes `argc`, `argv`, and `envp` to functions in `.init_array`, as a non-standard
839/// extension. This allows `std::env::args_os` to work even in a `cdylib` or `staticlib`, as it
840/// does on macOS and Windows.
841///
842/// Note that the returned iterator will not check if the arguments to the
843/// process are valid Unicode. If you want to panic on invalid UTF-8,
844/// use the [`args`] function instead.
845///
846/// # Examples
847///
848/// ```
849/// use std::env;
850///
851/// // Prints each argument on a separate line
852/// for argument in env::args_os() {
853///     println!("{argument:?}");
854/// }
855/// ```
856#[stable(feature = "env", since = "1.0.0")]
857pub fn args_os() -> ArgsOs {
858    ArgsOs { inner: sys::args::args() }
859}
860
861#[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
862impl !Send for Args {}
863
864#[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
865impl !Sync for Args {}
866
867#[stable(feature = "env", since = "1.0.0")]
868impl Iterator for Args {
869    type Item = String;
870
871    fn next(&mut self) -> Option<String> {
872        self.inner.next().map(|s| s.into_string().unwrap())
873    }
874
875    #[inline]
876    fn size_hint(&self) -> (usize, Option<usize>) {
877        self.inner.size_hint()
878    }
879
880    // Methods which skip args cannot simply delegate to the inner iterator,
881    // because `env::args` states that we will "panic during iteration if any
882    // argument to the process is not valid Unicode".
883    //
884    // This offers two possible interpretations:
885    // - a skipped argument is never encountered "during iteration"
886    // - even a skipped argument is encountered "during iteration"
887    //
888    // As a panic can be observed, we err towards validating even skipped
889    // arguments for now, though this is not explicitly promised by the API.
890}
891
892#[stable(feature = "env", since = "1.0.0")]
893impl ExactSizeIterator for Args {
894    #[inline]
895    fn len(&self) -> usize {
896        self.inner.len()
897    }
898
899    #[inline]
900    fn is_empty(&self) -> bool {
901        self.inner.is_empty()
902    }
903}
904
905#[stable(feature = "env_iterators", since = "1.12.0")]
906impl DoubleEndedIterator for Args {
907    fn next_back(&mut self) -> Option<String> {
908        self.inner.next_back().map(|s| s.into_string().unwrap())
909    }
910}
911
912#[stable(feature = "std_debug", since = "1.16.0")]
913impl fmt::Debug for Args {
914    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
915        let Self { inner: ArgsOs { inner } } = self;
916        f.debug_struct("Args").field("inner", inner).finish()
917    }
918}
919
920#[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
921impl !Send for ArgsOs {}
922
923#[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
924impl !Sync for ArgsOs {}
925
926#[stable(feature = "env", since = "1.0.0")]
927impl Iterator for ArgsOs {
928    type Item = OsString;
929
930    #[inline]
931    fn next(&mut self) -> Option<OsString> {
932        self.inner.next()
933    }
934
935    #[inline]
936    fn next_chunk<const N: usize>(
937        &mut self,
938    ) -> Result<[OsString; N], array::IntoIter<OsString, N>> {
939        self.inner.next_chunk()
940    }
941
942    #[inline]
943    fn size_hint(&self) -> (usize, Option<usize>) {
944        self.inner.size_hint()
945    }
946
947    #[inline]
948    fn count(self) -> usize {
949        self.inner.len()
950    }
951
952    #[inline]
953    fn last(self) -> Option<OsString> {
954        self.inner.last()
955    }
956
957    #[inline]
958    fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
959        self.inner.advance_by(n)
960    }
961
962    #[inline]
963    fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R
964    where
965        F: FnMut(B, Self::Item) -> R,
966        R: Try<Output = B>,
967    {
968        self.inner.try_fold(init, f)
969    }
970
971    #[inline]
972    fn fold<B, F>(self, init: B, f: F) -> B
973    where
974        F: FnMut(B, Self::Item) -> B,
975    {
976        self.inner.fold(init, f)
977    }
978}
979
980#[stable(feature = "env", since = "1.0.0")]
981impl ExactSizeIterator for ArgsOs {
982    #[inline]
983    fn len(&self) -> usize {
984        self.inner.len()
985    }
986
987    #[inline]
988    fn is_empty(&self) -> bool {
989        self.inner.is_empty()
990    }
991}
992
993#[stable(feature = "env_iterators", since = "1.12.0")]
994impl DoubleEndedIterator for ArgsOs {
995    #[inline]
996    fn next_back(&mut self) -> Option<OsString> {
997        self.inner.next_back()
998    }
999
1000    #[inline]
1001    fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
1002        self.inner.advance_back_by(n)
1003    }
1004}
1005
1006#[stable(feature = "std_debug", since = "1.16.0")]
1007impl fmt::Debug for ArgsOs {
1008    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1009        let Self { inner } = self;
1010        f.debug_struct("ArgsOs").field("inner", inner).finish()
1011    }
1012}
1013
1014/// Constants associated with the current target
1015#[stable(feature = "env", since = "1.0.0")]
1016pub mod consts {
1017    use crate::sys::env_consts::os;
1018
1019    /// A string describing the architecture of the CPU that is currently in use.
1020    /// An example value may be: `"x86"`, `"arm"` or `"riscv64"`.
1021    ///
1022    /// <details><summary>Full list of possible values</summary>
1023    ///
1024    /// * `"x86"`
1025    /// * `"x86_64"`
1026    /// * `"arm"`
1027    /// * `"aarch64"`
1028    /// * `"m68k"`
1029    /// * `"mips"`
1030    /// * `"mips32r6"`
1031    /// * `"mips64"`
1032    /// * `"mips64r6"`
1033    /// * `"csky"`
1034    /// * `"powerpc"`
1035    /// * `"powerpc64"`
1036    /// * `"riscv32"`
1037    /// * `"riscv64"`
1038    /// * `"s390x"`
1039    /// * `"sparc"`
1040    /// * `"sparc64"`
1041    /// * `"hexagon"`
1042    /// * `"loongarch32"`
1043    /// * `"loongarch64"`
1044    ///
1045    /// </details>
1046    #[stable(feature = "env", since = "1.0.0")]
1047    pub const ARCH: &str = env!("STD_ENV_ARCH");
1048
1049    /// A string describing the family of the operating system.
1050    /// An example value may be: `"unix"`, or `"windows"`.
1051    ///
1052    /// This value may be an empty string if the family is unknown.
1053    ///
1054    /// <details><summary>Full list of possible values</summary>
1055    ///
1056    /// * `"unix"`
1057    /// * `"windows"`
1058    /// * `"itron"`
1059    /// * `"wasm"`
1060    /// * `""`
1061    ///
1062    /// </details>
1063    #[stable(feature = "env", since = "1.0.0")]
1064    pub const FAMILY: &str = os::FAMILY;
1065
1066    /// A string describing the specific operating system in use.
1067    /// An example value may be: `"linux"`, or `"freebsd"`.
1068    ///
1069    /// <details><summary>Full list of possible values</summary>
1070    ///
1071    /// * `"linux"`
1072    /// * `"windows"`
1073    /// * `"macos"`
1074    /// * `"android"`
1075    /// * `"ios"`
1076    /// * `"openbsd"`
1077    /// * `"freebsd"`
1078    /// * `"netbsd"`
1079    /// * `"wasi"`
1080    /// * `"hermit"`
1081    /// * `"aix"`
1082    /// * `"apple"`
1083    /// * `"dragonfly"`
1084    /// * `"emscripten"`
1085    /// * `"espidf"`
1086    /// * `"fortanix"`
1087    /// * `"uefi"`
1088    /// * `"fuchsia"`
1089    /// * `"haiku"`
1090    /// * `"hermit"`
1091    /// * `"watchos"`
1092    /// * `"visionos"`
1093    /// * `"tvos"`
1094    /// * `"horizon"`
1095    /// * `"hurd"`
1096    /// * `"illumos"`
1097    /// * `"l4re"`
1098    /// * `"nto"`
1099    /// * `"redox"`
1100    /// * `"solaris"`
1101    /// * `"solid_asp3"`
1102    /// * `"vexos"`
1103    /// * `"vita"`
1104    /// * `"vxworks"`
1105    /// * `"xous"`
1106    ///
1107    /// </details>
1108    #[stable(feature = "env", since = "1.0.0")]
1109    pub const OS: &str = os::OS;
1110
1111    /// Specifies the filename prefix, if any, used for shared libraries on this platform.
1112    /// This is either `"lib"` or an empty string. (`""`).
1113    #[stable(feature = "env", since = "1.0.0")]
1114    pub const DLL_PREFIX: &str = os::DLL_PREFIX;
1115
1116    /// Specifies the filename suffix, if any, used for shared libraries on this platform.
1117    /// An example value may be: `".so"`, `".elf"`, or `".dll"`.
1118    ///
1119    /// The possible values are identical to those of [`DLL_EXTENSION`], but with the leading period included.
1120    #[stable(feature = "env", since = "1.0.0")]
1121    pub const DLL_SUFFIX: &str = os::DLL_SUFFIX;
1122
1123    /// Specifies the file extension, if any, used for shared libraries on this platform that goes after the dot.
1124    /// An example value may be: `"so"`, `"elf"`, or `"dll"`.
1125    ///
1126    /// <details><summary>Full list of possible values</summary>
1127    ///
1128    /// * `"so"`
1129    /// * `"dylib"`
1130    /// * `"dll"`
1131    /// * `"sgxs"`
1132    /// * `"a"`
1133    /// * `"elf"`
1134    /// * `"wasm"`
1135    /// * `""` (an empty string)
1136    ///
1137    /// </details>
1138    #[stable(feature = "env", since = "1.0.0")]
1139    pub const DLL_EXTENSION: &str = os::DLL_EXTENSION;
1140
1141    /// Specifies the filename suffix, if any, used for executable binaries on this platform.
1142    /// An example value may be: `".exe"`, or `".efi"`.
1143    ///
1144    /// The possible values are identical to those of [`EXE_EXTENSION`], but with the leading period included.
1145    #[stable(feature = "env", since = "1.0.0")]
1146    pub const EXE_SUFFIX: &str = os::EXE_SUFFIX;
1147
1148    /// Specifies the file extension, if any, used for executable binaries on this platform.
1149    /// An example value may be: `"exe"`, or an empty string (`""`).
1150    ///
1151    /// <details><summary>Full list of possible values</summary>
1152    ///
1153    /// * `"bin"`
1154    /// * `"exe"`
1155    /// * `"efi"`
1156    /// * `"js"`
1157    /// * `"sgxs"`
1158    /// * `"elf"`
1159    /// * `"wasm"`
1160    /// * `""` (an empty string)
1161    ///
1162    /// </details>
1163    #[stable(feature = "env", since = "1.0.0")]
1164    pub const EXE_EXTENSION: &str = os::EXE_EXTENSION;
1165}