env.rs - source
Description: Source of the Rust file `library/std/src/env.rs`.

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