Skip to main content

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, paths as paths_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    paths_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    paths_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(#[automatically_derived]
#[stable(feature = "env", since = "1.0.0")]
impl ::core::fmt::Debug for VarError {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            VarError::NotPresent =>
                ::core::fmt::Formatter::write_str(f, "NotPresent"),
            VarError::NotUnicode(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "NotUnicode", &__self_0),
        }
    }
}Debug, #[automatically_derived]
#[stable(feature = "env", since = "1.0.0")]
impl ::core::cmp::PartialEq for VarError {
    #[inline]
    fn eq(&self, other: &VarError) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (VarError::NotUnicode(__self_0),
                    VarError::NotUnicode(__arg1_0)) => __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]
#[stable(feature = "env", since = "1.0.0")]
impl ::core::cmp::Eq for VarError {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<OsString>;
    }
}Eq, #[automatically_derived]
#[stable(feature = "env", since = "1.0.0")]
impl ::core::clone::Clone for VarError {
    #[inline]
    fn clone(&self) -> VarError {
        match self {
            VarError::NotPresent => VarError::NotPresent,
            VarError::NotUnicode(__self_0) =>
                VarError::NotUnicode(::core::clone::Clone::clone(__self_0)),
        }
    }
}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 => f.write_fmt(format_args!("environment variable not found"))write!(f, "environment variable not found"),
291            VarError::NotUnicode(ref s) => {
292                f.write_fmt(format_args!("environment variable was not valid unicode: {0:?}",
        s))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 sound to call in a single-threaded program.
307///
308/// This function is also always sound to call on Windows, in single-threaded
309/// and multi-threaded programs.
310///
311/// In multi-threaded programs on other operating systems, the only sound 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 sound 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        {
    ::core::panicking::panic_fmt(format_args!("failed to set environment variable `{0:?}` to `{1:?}`: {2}",
            key, value, e));
}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 sound to call in a single-threaded program.
370///
371/// This function is also always sound to call on Windows, in single-threaded
372/// and multi-threaded programs.
373///
374/// In multi-threaded programs on other operating systems, the only sound 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 sound 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| {
    ::core::panicking::panic_fmt(format_args!("failed to remove environment variable `{0:?}`: {1}",
            key, 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: paths_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: paths_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(#[automatically_derived]
#[stable(feature = "env", since = "1.0.0")]
impl ::core::fmt::Debug for JoinPathsError {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f,
            "JoinPathsError", "inner", &&self.inner)
    }
}Debug)]
509#[stable(feature = "env", since = "1.0.0")]
510pub struct JoinPathsError {
511    inner: paths_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 semicolon on
522/// UEFI), or if the system does not have a `PATH`-like variable (e.g. 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    paths_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")]
643#[doc(alias = "home")]
644pub fn home_dir() -> Option<PathBuf> {
645    paths_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/// Specifically, for non-SYSTEM processes, the function checks for the
675/// following environment variables in order and returns the first path found:
676///
677/// 1. The path specified by the `TMP` environment variable.
678/// 2. The path specified by the `TEMP` environment variable.
679/// 3. The path specified by the `USERPROFILE` environment variable.
680/// 4. The Windows directory.
681///
682/// When called from a process running as SYSTEM,
683/// [`GetTempPath2`][GetTempPath2] returns `C:\Windows\SystemTemp`
684/// regardless of environment variables.
685///
686/// Note that, this [may change in the future][changes].
687///
688/// [changes]: io#platform-specific-behavior
689/// [GetTempPath2]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-gettemppath2a
690/// [GetTempPath]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-gettemppatha
691/// [appledoc]: https://developer.apple.com/library/archive/documentation/Security/Conceptual/SecureCodingGuide/Articles/RaceConditions.html#//apple_ref/doc/uid/TP40002585-SW10
692///
693/// ```
694/// use std::env;
695///
696/// fn main() {
697///     let dir = env::temp_dir();
698///     println!("Temporary directory: {}", dir.display());
699/// }
700/// ```
701#[must_use]
702#[doc(alias = "GetTempPath", alias = "GetTempPath2")]
703#[stable(feature = "env", since = "1.0.0")]
704pub fn temp_dir() -> PathBuf {
705    paths_imp::temp_dir()
706}
707
708/// Returns the full filesystem path of the current running executable.
709///
710/// # Platform-specific behavior
711///
712/// If the executable was invoked through a symbolic link, some platforms will
713/// return the path of the symbolic link and other platforms will return the
714/// path of the symbolic link’s target.
715///
716/// If the executable is renamed while it is running, platforms may return the
717/// path at the time it was loaded instead of the new path.
718///
719/// # Errors
720///
721/// Acquiring the path of the current executable is a platform-specific operation
722/// that can fail for a good number of reasons. Some errors can include, but not
723/// be limited to, filesystem operations failing or general syscall failures.
724///
725/// # Security
726///
727/// The output of this function must be treated with care to avoid security
728/// vulnerabilities, particularly in processes that run with privileges higher
729/// than the user, such as setuid or setgid programs.
730///
731/// For example, on some Unix platforms, the result is calculated by
732/// searching `$PATH` for an executable matching `argv[0]`, but both the
733/// environment and arguments can be be set arbitrarily by the user who
734/// invokes the program.
735///
736/// On Linux, if `fs.secure_hardlinks` is not set, an attacker who can
737/// create hardlinks to the executable may be able to cause this function
738/// to return an attacker-controlled path, which they later replace with
739/// a different program.
740///
741/// This list of illustrative example attacks is not exhaustive.
742///
743/// # Examples
744///
745/// ```
746/// use std::env;
747///
748/// match env::current_exe() {
749///     Ok(exe_path) => println!("Path of this executable is: {}",
750///                              exe_path.display()),
751///     Err(e) => println!("failed to get current exe path: {e}"),
752/// };
753/// ```
754#[stable(feature = "env", since = "1.0.0")]
755pub fn current_exe() -> io::Result<PathBuf> {
756    paths_imp::current_exe()
757}
758
759/// An iterator over the arguments of a process, yielding a [`String`] value for
760/// each argument.
761///
762/// This struct is created by [`env::args()`]. See its documentation
763/// for more.
764///
765/// The first element is traditionally the path of the executable, but it can be
766/// set to arbitrary text, and might not even exist. This means this property
767/// should not be relied upon for security purposes.
768///
769/// [`env::args()`]: args
770#[must_use = "iterators are lazy and do nothing unless consumed"]
771#[stable(feature = "env", since = "1.0.0")]
772pub struct Args {
773    inner: ArgsOs,
774}
775
776/// An iterator over the arguments of a process, yielding an [`OsString`] value
777/// for each argument.
778///
779/// This struct is created by [`env::args_os()`]. See its documentation
780/// for more.
781///
782/// The first element is traditionally the path of the executable, but it can be
783/// set to arbitrary text, and might not even exist. This means this property
784/// should not be relied upon for security purposes.
785///
786/// [`env::args_os()`]: args_os
787#[must_use = "iterators are lazy and do nothing unless consumed"]
788#[stable(feature = "env", since = "1.0.0")]
789pub struct ArgsOs {
790    inner: sys::args::Args,
791}
792
793/// Returns the arguments that this program was started with (normally passed
794/// via the command line).
795///
796/// The first element is traditionally the path of the executable, but it can be
797/// set to arbitrary text, and might not even exist. This means this property should
798/// not be relied upon for security purposes.
799///
800/// On Unix systems the shell usually expands unquoted arguments with glob patterns
801/// (such as `*` and `?`). On Windows this is not done, and such arguments are
802/// passed as-is.
803///
804/// On glibc Linux systems, arguments are retrieved by placing a function in `.init_array`.
805/// glibc passes `argc`, `argv`, and `envp` to functions in `.init_array`, as a non-standard
806/// extension. This allows `std::env::args` to work even in a `cdylib` or `staticlib`, as it
807/// does on macOS and Windows.
808///
809/// # Panics
810///
811/// The returned iterator will panic during iteration if any argument to the
812/// process is not valid Unicode. If this is not desired,
813/// use the [`args_os`] function instead.
814///
815/// # Examples
816///
817/// ```
818/// use std::env;
819///
820/// // Prints each argument on a separate line
821/// for argument in env::args() {
822///     println!("{argument}");
823/// }
824/// ```
825#[stable(feature = "env", since = "1.0.0")]
826pub fn args() -> Args {
827    Args { inner: args_os() }
828}
829
830/// Returns the arguments that this program was started with (normally passed
831/// via the command line).
832///
833/// The first element is traditionally the path of the executable, but it can be
834/// set to arbitrary text, and might not even exist. This means this property should
835/// not be relied upon for security purposes.
836///
837/// On Unix systems the shell usually expands unquoted arguments with glob patterns
838/// (such as `*` and `?`). On Windows this is not done, and such arguments are
839/// passed as-is.
840///
841/// On glibc Linux systems, arguments are retrieved by placing a function in `.init_array`.
842/// glibc passes `argc`, `argv`, and `envp` to functions in `.init_array`, as a non-standard
843/// extension. This allows `std::env::args_os` to work even in a `cdylib` or `staticlib`, as it
844/// does on macOS and Windows.
845///
846/// Note that the returned iterator will not check if the arguments to the
847/// process are valid Unicode. If you want to panic on invalid UTF-8,
848/// use the [`args`] function instead.
849///
850/// # Examples
851///
852/// ```
853/// use std::env;
854///
855/// // Prints each argument on a separate line
856/// for argument in env::args_os() {
857///     println!("{argument:?}");
858/// }
859/// ```
860#[stable(feature = "env", since = "1.0.0")]
861pub fn args_os() -> ArgsOs {
862    ArgsOs { inner: sys::args::args() }
863}
864
865#[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
866impl !Send for Args {}
867
868#[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
869impl !Sync for Args {}
870
871#[stable(feature = "env", since = "1.0.0")]
872impl Iterator for Args {
873    type Item = String;
874
875    fn next(&mut self) -> Option<String> {
876        self.inner.next().map(|s| s.into_string().unwrap())
877    }
878
879    #[inline]
880    fn size_hint(&self) -> (usize, Option<usize>) {
881        self.inner.size_hint()
882    }
883
884    // Methods which skip args cannot simply delegate to the inner iterator,
885    // because `env::args` states that we will "panic during iteration if any
886    // argument to the process is not valid Unicode".
887    //
888    // This offers two possible interpretations:
889    // - a skipped argument is never encountered "during iteration"
890    // - even a skipped argument is encountered "during iteration"
891    //
892    // As a panic can be observed, we err towards validating even skipped
893    // arguments for now, though this is not explicitly promised by the API.
894}
895
896#[stable(feature = "env", since = "1.0.0")]
897impl ExactSizeIterator for Args {
898    #[inline]
899    fn len(&self) -> usize {
900        self.inner.len()
901    }
902
903    #[inline]
904    fn is_empty(&self) -> bool {
905        self.inner.is_empty()
906    }
907}
908
909#[stable(feature = "env_iterators", since = "1.12.0")]
910impl DoubleEndedIterator for Args {
911    fn next_back(&mut self) -> Option<String> {
912        self.inner.next_back().map(|s| s.into_string().unwrap())
913    }
914}
915
916#[stable(feature = "std_debug", since = "1.16.0")]
917impl fmt::Debug for Args {
918    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
919        let Self { inner: ArgsOs { inner } } = self;
920        f.debug_struct("Args").field("inner", inner).finish()
921    }
922}
923
924#[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
925impl !Send for ArgsOs {}
926
927#[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
928impl !Sync for ArgsOs {}
929
930#[stable(feature = "env", since = "1.0.0")]
931impl Iterator for ArgsOs {
932    type Item = OsString;
933
934    #[inline]
935    fn next(&mut self) -> Option<OsString> {
936        self.inner.next()
937    }
938
939    #[inline]
940    fn next_chunk<const N: usize>(
941        &mut self,
942    ) -> Result<[OsString; N], array::IntoIter<OsString, N>> {
943        self.inner.next_chunk()
944    }
945
946    #[inline]
947    fn size_hint(&self) -> (usize, Option<usize>) {
948        self.inner.size_hint()
949    }
950
951    #[inline]
952    fn count(self) -> usize {
953        self.inner.len()
954    }
955
956    #[inline]
957    fn last(self) -> Option<OsString> {
958        self.inner.last()
959    }
960
961    #[inline]
962    fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
963        self.inner.advance_by(n)
964    }
965
966    #[inline]
967    fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R
968    where
969        F: FnMut(B, Self::Item) -> R,
970        R: Try<Output = B>,
971    {
972        self.inner.try_fold(init, f)
973    }
974
975    #[inline]
976    fn fold<B, F>(self, init: B, f: F) -> B
977    where
978        F: FnMut(B, Self::Item) -> B,
979    {
980        self.inner.fold(init, f)
981    }
982}
983
984#[stable(feature = "env", since = "1.0.0")]
985impl ExactSizeIterator for ArgsOs {
986    #[inline]
987    fn len(&self) -> usize {
988        self.inner.len()
989    }
990
991    #[inline]
992    fn is_empty(&self) -> bool {
993        self.inner.is_empty()
994    }
995}
996
997#[stable(feature = "env_iterators", since = "1.12.0")]
998impl DoubleEndedIterator for ArgsOs {
999    #[inline]
1000    fn next_back(&mut self) -> Option<OsString> {
1001        self.inner.next_back()
1002    }
1003
1004    #[inline]
1005    fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
1006        self.inner.advance_back_by(n)
1007    }
1008}
1009
1010#[stable(feature = "std_debug", since = "1.16.0")]
1011impl fmt::Debug for ArgsOs {
1012    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1013        let Self { inner } = self;
1014        f.debug_struct("ArgsOs").field("inner", inner).finish()
1015    }
1016}
1017
1018/// Constants associated with the current target
1019#[stable(feature = "env", since = "1.0.0")]
1020pub mod consts {
1021    use crate::sys::env_consts::os;
1022
1023    /// A string describing the architecture of the CPU that is currently in use.
1024    /// An example value may be: `"x86"`, `"arm"` or `"riscv64"`.
1025    ///
1026    /// <details><summary>Full list of possible values</summary>
1027    ///
1028    /// * `"x86"`
1029    /// * `"x86_64"`
1030    /// * `"arm"`
1031    /// * `"aarch64"`
1032    /// * `"m68k"`
1033    /// * `"mips"`
1034    /// * `"mips32r6"`
1035    /// * `"mips64"`
1036    /// * `"mips64r6"`
1037    /// * `"csky"`
1038    /// * `"powerpc"`
1039    /// * `"powerpc64"`
1040    /// * `"riscv32"`
1041    /// * `"riscv64"`
1042    /// * `"s390x"`
1043    /// * `"sparc"`
1044    /// * `"sparc64"`
1045    /// * `"hexagon"`
1046    /// * `"loongarch32"`
1047    /// * `"loongarch64"`
1048    ///
1049    /// </details>
1050    #[stable(feature = "env", since = "1.0.0")]
1051    pub const ARCH: &str = "x86_64"env!("STD_ENV_ARCH");
1052
1053    /// A string describing the family of the operating system.
1054    /// An example value may be: `"unix"`, or `"windows"`.
1055    ///
1056    /// This value may be an empty string if the family is unknown.
1057    ///
1058    /// <details><summary>Full list of possible values</summary>
1059    ///
1060    /// * `"unix"`
1061    /// * `"windows"`
1062    /// * `"itron"`
1063    /// * `"wasm"`
1064    /// * `""`
1065    ///
1066    /// </details>
1067    #[stable(feature = "env", since = "1.0.0")]
1068    pub const FAMILY: &str = os::FAMILY;
1069
1070    /// A string describing the specific operating system in use.
1071    /// An example value may be: `"linux"`, or `"freebsd"`.
1072    ///
1073    /// <details><summary>Full list of possible values</summary>
1074    ///
1075    // tidy-alphabetical-start
1076    /// * `"aix"`
1077    /// * `"android"`
1078    /// * `"apple"`
1079    /// * `"dragonfly"`
1080    /// * `"emscripten"`
1081    /// * `"espidf"`
1082    /// * `"fortanix"`
1083    /// * `"freebsd"`
1084    /// * `"fuchsia"`
1085    /// * `"haiku"`
1086    /// * `"hermit"`
1087    /// * `"horizon"`
1088    /// * `"hurd"`
1089    /// * `"illumos"`
1090    /// * `"ios"`
1091    /// * `"l4re"`
1092    /// * `"linux"`
1093    /// * `"macos"`
1094    /// * `"netbsd"`
1095    /// * `"nto"`
1096    /// * `"openbsd"`
1097    /// * `"redox"`
1098    /// * `"solaris"`
1099    /// * `"solid_asp3"`
1100    /// * `"tvos"`
1101    /// * `"uefi"`
1102    /// * `"vexos"`
1103    /// * `"visionos"`
1104    /// * `"vita"`
1105    /// * `"vxworks"`
1106    /// * `"wasi"`
1107    /// * `"watchos"`
1108    /// * `"windows"`
1109    /// * `"xous"`
1110    // tidy-alphabetical-end
1111    ///
1112    /// </details>
1113    #[stable(feature = "env", since = "1.0.0")]
1114    pub const OS: &str = os::OS;
1115
1116    /// Specifies the filename prefix, if any, used for shared libraries on this platform.
1117    /// This is either `"lib"` or an empty string. (`""`).
1118    #[stable(feature = "env", since = "1.0.0")]
1119    pub const DLL_PREFIX: &str = os::DLL_PREFIX;
1120
1121    /// Specifies the filename suffix, if any, used for shared libraries on this platform.
1122    /// An example value may be: `".so"`, `".elf"`, or `".dll"`.
1123    ///
1124    /// The possible values are identical to those of [`DLL_EXTENSION`], but with the leading period included.
1125    #[stable(feature = "env", since = "1.0.0")]
1126    pub const DLL_SUFFIX: &str = os::DLL_SUFFIX;
1127
1128    /// Specifies the file extension, if any, used for shared libraries on this platform that goes after the dot.
1129    /// An example value may be: `"so"`, `"elf"`, or `"dll"`.
1130    ///
1131    /// <details><summary>Full list of possible values</summary>
1132    ///
1133    /// * `"so"`
1134    /// * `"dylib"`
1135    /// * `"dll"`
1136    /// * `"sgxs"`
1137    /// * `"a"`
1138    /// * `"elf"`
1139    /// * `"wasm"`
1140    /// * `""` (an empty string)
1141    ///
1142    /// </details>
1143    #[stable(feature = "env", since = "1.0.0")]
1144    pub const DLL_EXTENSION: &str = os::DLL_EXTENSION;
1145
1146    /// Specifies the filename suffix, if any, used for executable binaries on this platform.
1147    /// An example value may be: `".exe"`, or `".efi"`.
1148    ///
1149    /// The possible values are identical to those of [`EXE_EXTENSION`], but with the leading period included.
1150    #[stable(feature = "env", since = "1.0.0")]
1151    pub const EXE_SUFFIX: &str = os::EXE_SUFFIX;
1152
1153    /// Specifies the file extension, if any, used for executable binaries on this platform.
1154    /// An example value may be: `"exe"`, or an empty string (`""`).
1155    ///
1156    /// <details><summary>Full list of possible values</summary>
1157    ///
1158    /// * `"bin"`
1159    /// * `"exe"`
1160    /// * `"efi"`
1161    /// * `"js"`
1162    /// * `"sgxs"`
1163    /// * `"elf"`
1164    /// * `"wasm"`
1165    /// * `""` (an empty string)
1166    ///
1167    /// </details>
1168    #[stable(feature = "env", since = "1.0.0")]
1169    pub const EXE_EXTENSION: &str = os::EXE_EXTENSION;
1170}