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#[stable(feature = "env_vars_unimpl_send_sync", since = "CURRENT_RUSTC_VERSION")]
105impl !Send for VarsOs {}
106
107#[stable(feature = "env_vars_unimpl_send_sync", since = "CURRENT_RUSTC_VERSION")]
108impl !Sync for VarsOs {}
109
110/// Returns an iterator of (variable, value) pairs of strings, for all the
111/// environment variables of the current process.
112///
113/// The returned iterator contains a snapshot of the process's environment
114/// variables at the time of this invocation. Modifications to environment
115/// variables afterwards will not be reflected in the returned iterator.
116///
117/// # Panics
118///
119/// While iterating, the returned iterator will panic if any key or value in the
120/// environment is not valid unicode. If this is not desired, consider using
121/// [`env::vars_os()`].
122///
123/// # Examples
124///
125/// ```
126/// // Print all environment variables.
127/// for (key, value) in std::env::vars() {
128///     println!("{key}: {value}");
129/// }
130/// ```
131///
132/// [`env::vars_os()`]: vars_os
133#[must_use]
134#[stable(feature = "env", since = "1.0.0")]
135pub fn vars() -> Vars {
136    Vars { inner: vars_os() }
137}
138
139/// Returns an iterator of (variable, value) pairs of OS strings, for all the
140/// environment variables of the current process.
141///
142/// The returned iterator contains a snapshot of the process's environment
143/// variables at the time of this invocation. Modifications to environment
144/// variables afterwards will not be reflected in the returned iterator.
145///
146/// Note that the returned iterator will not check if the environment variables
147/// are valid Unicode. If you want to panic on invalid UTF-8,
148/// use the [`vars`] function instead.
149///
150/// # Examples
151///
152/// ```
153/// // Print all environment variables.
154/// for (key, value) in std::env::vars_os() {
155///     println!("{key:?}: {value:?}");
156/// }
157/// ```
158#[must_use]
159#[stable(feature = "env", since = "1.0.0")]
160pub fn vars_os() -> VarsOs {
161    VarsOs { inner: env_imp::env() }
162}
163
164#[stable(feature = "env", since = "1.0.0")]
165impl Iterator for Vars {
166    type Item = (String, String);
167    fn next(&mut self) -> Option<(String, String)> {
168        self.inner.next().map(|(a, b)| (a.into_string().unwrap(), b.into_string().unwrap()))
169    }
170    fn size_hint(&self) -> (usize, Option<usize>) {
171        self.inner.size_hint()
172    }
173}
174
175#[stable(feature = "std_debug", since = "1.16.0")]
176impl fmt::Debug for Vars {
177    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
178        let Self { inner: VarsOs { inner } } = self;
179        f.debug_struct("Vars").field("inner", inner).finish()
180    }
181}
182
183#[stable(feature = "env", since = "1.0.0")]
184impl Iterator for VarsOs {
185    type Item = (OsString, OsString);
186    fn next(&mut self) -> Option<(OsString, OsString)> {
187        self.inner.next()
188    }
189    fn size_hint(&self) -> (usize, Option<usize>) {
190        self.inner.size_hint()
191    }
192}
193
194#[stable(feature = "std_debug", since = "1.16.0")]
195impl fmt::Debug for VarsOs {
196    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
197        let Self { inner } = self;
198        f.debug_struct("VarsOs").field("inner", inner).finish()
199    }
200}
201
202/// Fetches the environment variable `key` from the current process.
203///
204/// # Errors
205///
206/// Returns [`VarError::NotPresent`] if:
207/// - The variable is not set.
208/// - The variable's name contains an equal sign or NUL (`'='` or `'\0'`).
209///
210/// Returns [`VarError::NotUnicode`] if the variable's value is not valid
211/// Unicode. If this is not desired, consider using [`var_os`].
212///
213/// Use [`env!`] or [`option_env!`] instead if you want to check environment
214/// variables at compile time.
215///
216/// # Examples
217///
218/// ```
219/// use std::env;
220///
221/// let key = "HOME";
222/// match env::var(key) {
223///     Ok(val) => println!("{key}: {val:?}"),
224///     Err(e) => println!("couldn't interpret {key}: {e}"),
225/// }
226/// ```
227#[stable(feature = "env", since = "1.0.0")]
228pub fn var<K: AsRef<OsStr>>(key: K) -> Result<String, VarError> {
229    fn inner(key: &OsStr) -> Result<String, VarError> {
230        env_imp::getenv(key)
231            .ok_or(VarError::NotPresent)?
232            .into_string()
233            .map_err(VarError::NotUnicode)
234    }
235    inner(key.as_ref())
236}
237
238/// Fetches the environment variable `key` from the current process, returning
239/// [`None`] if the variable isn't set or if there is another error.
240///
241/// It may return `None` if the environment variable's name contains
242/// the equal sign character (`=`) or the NUL character.
243///
244/// Note that this function will not check if the environment variable
245/// is valid Unicode. If you want to have an error on invalid UTF-8,
246/// use the [`var`] function instead.
247///
248/// # Examples
249///
250/// ```
251/// use std::env;
252///
253/// let key = "HOME";
254/// match env::var_os(key) {
255///     Some(val) => println!("{key}: {val:?}"),
256///     None => println!("{key} is not defined in the environment.")
257/// }
258/// ```
259///
260/// If expecting a delimited variable (such as `PATH`), [`split_paths`]
261/// can be used to separate items.
262#[must_use]
263#[stable(feature = "env", since = "1.0.0")]
264pub fn var_os<K: AsRef<OsStr>>(key: K) -> Option<OsString> {
265    env_imp::getenv(key.as_ref())
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 sound to call in a single-threaded program.
308///
309/// This function is also always sound to call on Windows, in single-threaded
310/// and multi-threaded programs.
311///
312/// In multi-threaded programs on other operating systems, the only sound 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 sound 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 sound to call in a single-threaded program.
371///
372/// This function is also always sound to call on Windows, in single-threaded
373/// and multi-threaded programs.
374///
375/// In multi-threaded programs on other operating systems, the only sound 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 sound 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: paths_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: paths_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: paths_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 semicolon on
523/// UEFI), or if the system does not have a `PATH`-like variable (e.g. 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    paths_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//  feature(xdg_basedir): This should link to std::os::unix::xdg once it's stabilized
610///
611/// # Unix
612///
613/// - Returns the value of the 'HOME' environment variable if it is set
614///   (and not an empty string).
615/// - Otherwise, it tries to determine the home directory by invoking the `getpwuid_r` function
616///   using the UID of the current user. An empty home directory field returned from the
617///   `getpwuid_r` function is considered to be a valid value.
618/// - Returns `None` if the current user has no entry in the /etc/passwd file.
619///
620/// # Windows
621///
622/// - Returns the value of the 'USERPROFILE' environment variable if it is set, and is not an empty string.
623/// - Otherwise, [`GetUserProfileDirectory`][msdn] is used to return the path. This may change in the future.
624///
625/// [msdn]: https://docs.microsoft.com/en-us/windows/win32/api/userenv/nf-userenv-getuserprofiledirectorya
626///
627/// In UWP (Universal Windows Platform) targets this function is unimplemented and always returns `None`.
628///
629/// Before Rust 1.85.0, this function used to return the value of the 'HOME' environment variable
630/// on Windows, which in Cygwin or Mingw environments could return non-standard paths like `/home/you`
631/// instead of `C:\Users\you`.
632///
633/// # Examples
634///
635/// ```
636/// use std::env;
637///
638/// match env::home_dir() {
639///     Some(path) => println!("Your home directory, probably: {}", path.display()),
640///     None => println!("Impossible to get your home dir!"),
641/// }
642/// ```
643#[must_use]
644#[stable(feature = "env", since = "1.0.0")]
645#[doc(alias = "home")]
646pub fn home_dir() -> Option<PathBuf> {
647    paths_imp::home_dir()
648}
649
650/// Returns the path of a temporary directory.
651///
652/// The temporary directory may be shared among users, or between processes
653/// with different privileges; thus, the creation of any files or directories
654/// in the temporary directory must use a secure method to create a uniquely
655/// named file. Creating a file or directory with a fixed or predictable name
656/// may result in "insecure temporary file" security vulnerabilities. Consider
657/// using a crate that securely creates temporary files or directories.
658///
659/// Note that the returned value may be a symbolic link, not a directory.
660///
661/// # Platform-specific behavior
662///
663/// On Unix, returns the value of the `TMPDIR` environment variable if it is
664/// set, otherwise the value is OS-specific:
665/// - On Android, there is no global temporary folder (it is usually allocated
666///   per-app), it will return the application's cache dir if the program runs
667///   in application's namespace and system version is Android 13 (or above), or
668///   `/data/local/tmp` otherwise.
669/// - On Darwin-based OSes (macOS, iOS, etc) it returns the directory provided
670///   by `confstr(_CS_DARWIN_USER_TEMP_DIR, ...)`, as recommended by [Apple's
671///   security guidelines][appledoc].
672/// - On all other unix-based OSes, it returns `/tmp`.
673///
674/// On Windows, the behavior is equivalent to that of [`GetTempPath2`][GetTempPath2] /
675/// [`GetTempPath`][GetTempPath], which this function uses internally.
676/// Specifically, for non-SYSTEM processes, the function checks for the
677/// following environment variables in order and returns the first path found:
678///
679/// 1. The path specified by the `TMP` environment variable.
680/// 2. The path specified by the `TEMP` environment variable.
681/// 3. The path specified by the `USERPROFILE` environment variable.
682/// 4. The Windows directory.
683///
684/// When called from a process running as SYSTEM,
685/// [`GetTempPath2`][GetTempPath2] returns `C:\Windows\SystemTemp`
686/// regardless of environment variables.
687///
688/// Note that, this [may change in the future][changes].
689///
690/// [changes]: io#platform-specific-behavior
691/// [GetTempPath2]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-gettemppath2a
692/// [GetTempPath]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-gettemppatha
693/// [appledoc]: https://developer.apple.com/library/archive/documentation/Security/Conceptual/SecureCodingGuide/Articles/RaceConditions.html#//apple_ref/doc/uid/TP40002585-SW10
694///
695/// ```
696/// use std::env;
697///
698/// fn main() {
699///     let dir = env::temp_dir();
700///     println!("Temporary directory: {}", dir.display());
701/// }
702/// ```
703#[must_use]
704#[doc(alias = "GetTempPath", alias = "GetTempPath2")]
705#[stable(feature = "env", since = "1.0.0")]
706pub fn temp_dir() -> PathBuf {
707    paths_imp::temp_dir()
708}
709
710/// Returns the full filesystem path of the current running executable.
711///
712/// # Platform-specific behavior
713///
714/// If the executable was invoked through a symbolic link, some platforms will
715/// return the path of the symbolic link and other platforms will return the
716/// path of the symbolic link’s target.
717///
718/// If the executable is renamed while it is running, platforms may return the
719/// path at the time it was loaded instead of the new path.
720///
721/// # Errors
722///
723/// Acquiring the path of the current executable is a platform-specific operation
724/// that can fail for a good number of reasons. Some errors can include, but not
725/// be limited to, filesystem operations failing or general syscall failures.
726///
727/// # Security
728///
729/// The output of this function must be treated with care to avoid security
730/// vulnerabilities, particularly in processes that run with privileges higher
731/// than the user, such as setuid or setgid programs.
732///
733/// For example, on some Unix platforms, the result is calculated by
734/// searching `$PATH` for an executable matching `argv[0]`, but both the
735/// environment and arguments can be be set arbitrarily by the user who
736/// invokes the program.
737///
738/// On Linux, if `fs.secure_hardlinks` is not set, an attacker who can
739/// create hardlinks to the executable may be able to cause this function
740/// to return an attacker-controlled path, which they later replace with
741/// a different program.
742///
743/// This list of illustrative example attacks is not exhaustive.
744///
745/// # Examples
746///
747/// ```
748/// use std::env;
749///
750/// match env::current_exe() {
751///     Ok(exe_path) => println!("Path of this executable is: {}",
752///                              exe_path.display()),
753///     Err(e) => println!("failed to get current exe path: {e}"),
754/// };
755/// ```
756#[stable(feature = "env", since = "1.0.0")]
757pub fn current_exe() -> io::Result<PathBuf> {
758    paths_imp::current_exe()
759}
760
761/// An iterator over the arguments of a process, yielding a [`String`] value for
762/// each argument.
763///
764/// This struct is created by [`env::args()`]. See its documentation
765/// for more.
766///
767/// The first element is traditionally the path of the executable, but it can be
768/// set to arbitrary text, and might not even exist. This means this property
769/// should not be relied upon for security purposes.
770///
771/// [`env::args()`]: args
772#[must_use = "iterators are lazy and do nothing unless consumed"]
773#[stable(feature = "env", since = "1.0.0")]
774pub struct Args {
775    inner: ArgsOs,
776}
777
778/// An iterator over the arguments of a process, yielding an [`OsString`] value
779/// for each argument.
780///
781/// This struct is created by [`env::args_os()`]. See its documentation
782/// for more.
783///
784/// The first element is traditionally the path of the executable, but it can be
785/// set to arbitrary text, and might not even exist. This means this property
786/// should not be relied upon for security purposes.
787///
788/// [`env::args_os()`]: args_os
789#[must_use = "iterators are lazy and do nothing unless consumed"]
790#[stable(feature = "env", since = "1.0.0")]
791pub struct ArgsOs {
792    inner: sys::args::Args,
793}
794
795/// Returns the arguments that this program was started with (normally passed
796/// via the command line).
797///
798/// The first element is traditionally the path of the executable, but it can be
799/// set to arbitrary text, and might not even exist. This means this property should
800/// not be relied upon for security purposes.
801///
802/// On Unix systems the shell usually expands unquoted arguments with glob patterns
803/// (such as `*` and `?`). On Windows this is not done, and such arguments are
804/// passed as-is.
805///
806/// On glibc Linux systems, arguments are retrieved by placing a function in `.init_array`.
807/// glibc passes `argc`, `argv`, and `envp` to functions in `.init_array`, as a non-standard
808/// extension. This allows `std::env::args` to work even in a `cdylib` or `staticlib`, as it
809/// does on macOS and Windows.
810///
811/// # Panics
812///
813/// The returned iterator will panic during iteration if any argument to the
814/// process is not valid Unicode. If this is not desired,
815/// use the [`args_os`] function instead.
816///
817/// # Examples
818///
819/// ```
820/// use std::env;
821///
822/// // Prints each argument on a separate line
823/// for argument in env::args() {
824///     println!("{argument}");
825/// }
826/// ```
827#[stable(feature = "env", since = "1.0.0")]
828pub fn args() -> Args {
829    Args { inner: args_os() }
830}
831
832/// Returns the arguments that this program was started with (normally passed
833/// via the command line).
834///
835/// The first element is traditionally the path of the executable, but it can be
836/// set to arbitrary text, and might not even exist. This means this property should
837/// not be relied upon for security purposes.
838///
839/// On Unix systems the shell usually expands unquoted arguments with glob patterns
840/// (such as `*` and `?`). On Windows this is not done, and such arguments are
841/// passed as-is.
842///
843/// On glibc Linux systems, arguments are retrieved by placing a function in `.init_array`.
844/// glibc passes `argc`, `argv`, and `envp` to functions in `.init_array`, as a non-standard
845/// extension. This allows `std::env::args_os` to work even in a `cdylib` or `staticlib`, as it
846/// does on macOS and Windows.
847///
848/// Note that the returned iterator will not check if the arguments to the
849/// process are valid Unicode. If you want to panic on invalid UTF-8,
850/// use the [`args`] function instead.
851///
852/// # Examples
853///
854/// ```
855/// use std::env;
856///
857/// // Prints each argument on a separate line
858/// for argument in env::args_os() {
859///     println!("{argument:?}");
860/// }
861/// ```
862#[stable(feature = "env", since = "1.0.0")]
863pub fn args_os() -> ArgsOs {
864    ArgsOs { inner: sys::args::args() }
865}
866
867#[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
868impl !Send for Args {}
869
870#[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
871impl !Sync for Args {}
872
873#[stable(feature = "env", since = "1.0.0")]
874impl Iterator for Args {
875    type Item = String;
876
877    fn next(&mut self) -> Option<String> {
878        self.inner.next().map(|s| s.into_string().unwrap())
879    }
880
881    #[inline]
882    fn size_hint(&self) -> (usize, Option<usize>) {
883        self.inner.size_hint()
884    }
885
886    // Methods which skip args cannot simply delegate to the inner iterator,
887    // because `env::args` states that we will "panic during iteration if any
888    // argument to the process is not valid Unicode".
889    //
890    // This offers two possible interpretations:
891    // - a skipped argument is never encountered "during iteration"
892    // - even a skipped argument is encountered "during iteration"
893    //
894    // As a panic can be observed, we err towards validating even skipped
895    // arguments for now, though this is not explicitly promised by the API.
896}
897
898#[stable(feature = "env", since = "1.0.0")]
899impl ExactSizeIterator for Args {
900    #[inline]
901    fn len(&self) -> usize {
902        self.inner.len()
903    }
904
905    #[inline]
906    fn is_empty(&self) -> bool {
907        self.inner.is_empty()
908    }
909}
910
911#[stable(feature = "env_iterators", since = "1.12.0")]
912impl DoubleEndedIterator for Args {
913    fn next_back(&mut self) -> Option<String> {
914        self.inner.next_back().map(|s| s.into_string().unwrap())
915    }
916}
917
918#[stable(feature = "std_debug", since = "1.16.0")]
919impl fmt::Debug for Args {
920    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
921        let Self { inner: ArgsOs { inner } } = self;
922        f.debug_struct("Args").field("inner", inner).finish()
923    }
924}
925
926#[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
927impl !Send for ArgsOs {}
928
929#[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
930impl !Sync for ArgsOs {}
931
932#[stable(feature = "env", since = "1.0.0")]
933impl Iterator for ArgsOs {
934    type Item = OsString;
935
936    #[inline]
937    fn next(&mut self) -> Option<OsString> {
938        self.inner.next()
939    }
940
941    #[inline]
942    fn next_chunk<const N: usize>(
943        &mut self,
944    ) -> Result<[OsString; N], array::IntoIter<OsString, N>> {
945        self.inner.next_chunk()
946    }
947
948    #[inline]
949    fn size_hint(&self) -> (usize, Option<usize>) {
950        self.inner.size_hint()
951    }
952
953    #[inline]
954    fn count(self) -> usize {
955        self.inner.len()
956    }
957
958    #[inline]
959    fn last(self) -> Option<OsString> {
960        self.inner.last()
961    }
962
963    #[inline]
964    fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
965        self.inner.advance_by(n)
966    }
967
968    #[inline]
969    fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R
970    where
971        F: FnMut(B, Self::Item) -> R,
972        R: Try<Output = B>,
973    {
974        self.inner.try_fold(init, f)
975    }
976
977    #[inline]
978    fn fold<B, F>(self, init: B, f: F) -> B
979    where
980        F: FnMut(B, Self::Item) -> B,
981    {
982        self.inner.fold(init, f)
983    }
984}
985
986#[stable(feature = "env", since = "1.0.0")]
987impl ExactSizeIterator for ArgsOs {
988    #[inline]
989    fn len(&self) -> usize {
990        self.inner.len()
991    }
992
993    #[inline]
994    fn is_empty(&self) -> bool {
995        self.inner.is_empty()
996    }
997}
998
999#[stable(feature = "env_iterators", since = "1.12.0")]
1000impl DoubleEndedIterator for ArgsOs {
1001    #[inline]
1002    fn next_back(&mut self) -> Option<OsString> {
1003        self.inner.next_back()
1004    }
1005
1006    #[inline]
1007    fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
1008        self.inner.advance_back_by(n)
1009    }
1010}
1011
1012#[stable(feature = "std_debug", since = "1.16.0")]
1013impl fmt::Debug for ArgsOs {
1014    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1015        let Self { inner } = self;
1016        f.debug_struct("ArgsOs").field("inner", inner).finish()
1017    }
1018}
1019
1020/// Constants associated with the current target
1021#[stable(feature = "env", since = "1.0.0")]
1022pub mod consts {
1023    use crate::sys::env_consts::os;
1024
1025    /// A string describing the architecture of the CPU that is currently in use.
1026    /// An example value may be: `"x86"`, `"arm"` or `"riscv64"`.
1027    ///
1028    /// <details><summary>Full list of possible values</summary>
1029    ///
1030    /// * `"x86"`
1031    /// * `"x86_64"`
1032    /// * `"arm"`
1033    /// * `"aarch64"`
1034    /// * `"m68k"`
1035    /// * `"mips"`
1036    /// * `"mips32r6"`
1037    /// * `"mips64"`
1038    /// * `"mips64r6"`
1039    /// * `"csky"`
1040    /// * `"powerpc"`
1041    /// * `"powerpc64"`
1042    /// * `"riscv32"`
1043    /// * `"riscv64"`
1044    /// * `"s390x"`
1045    /// * `"sparc"`
1046    /// * `"sparc64"`
1047    /// * `"hexagon"`
1048    /// * `"loongarch32"`
1049    /// * `"loongarch64"`
1050    ///
1051    /// </details>
1052    #[stable(feature = "env", since = "1.0.0")]
1053    pub const ARCH: &str = env!("STD_ENV_ARCH");
1054
1055    /// A string describing the family of the operating system.
1056    /// An example value may be: `"unix"`, or `"windows"`.
1057    ///
1058    /// This value may be an empty string if the family is unknown.
1059    ///
1060    /// <details><summary>Full list of possible values</summary>
1061    ///
1062    /// * `"unix"`
1063    /// * `"windows"`
1064    /// * `"itron"`
1065    /// * `"wasm"`
1066    /// * `""`
1067    ///
1068    /// </details>
1069    #[stable(feature = "env", since = "1.0.0")]
1070    pub const FAMILY: &str = os::FAMILY;
1071
1072    /// A string describing the specific operating system in use.
1073    /// An example value may be: `"linux"`, or `"freebsd"`.
1074    ///
1075    /// <details><summary>Full list of possible values</summary>
1076    ///
1077    // tidy-alphabetical-start
1078    /// * `"aix"`
1079    /// * `"android"`
1080    /// * `"apple"`
1081    /// * `"dragonfly"`
1082    /// * `"emscripten"`
1083    /// * `"espidf"`
1084    /// * `"fortanix"`
1085    /// * `"freebsd"`
1086    /// * `"fuchsia"`
1087    /// * `"haiku"`
1088    /// * `"hermit"`
1089    /// * `"horizon"`
1090    /// * `"hurd"`
1091    /// * `"illumos"`
1092    /// * `"ios"`
1093    /// * `"l4re"`
1094    /// * `"linux"`
1095    /// * `"macos"`
1096    /// * `"netbsd"`
1097    /// * `"nto"`
1098    /// * `"openbsd"`
1099    /// * `"redox"`
1100    /// * `"solaris"`
1101    /// * `"solid_asp3"`
1102    /// * `"tvos"`
1103    /// * `"uefi"`
1104    /// * `"vexos"`
1105    /// * `"visionos"`
1106    /// * `"vita"`
1107    /// * `"vxworks"`
1108    /// * `"wasi"`
1109    /// * `"watchos"`
1110    /// * `"windows"`
1111    /// * `"xous"`
1112    // tidy-alphabetical-end
1113    ///
1114    /// </details>
1115    #[stable(feature = "env", since = "1.0.0")]
1116    pub const OS: &str = os::OS;
1117
1118    /// Specifies the filename prefix, if any, used for shared libraries on this platform.
1119    /// This is either `"lib"` or an empty string. (`""`).
1120    #[stable(feature = "env", since = "1.0.0")]
1121    pub const DLL_PREFIX: &str = os::DLL_PREFIX;
1122
1123    /// Specifies the filename suffix, if any, used for shared libraries on this platform.
1124    /// An example value may be: `".so"`, `".elf"`, or `".dll"`.
1125    ///
1126    /// The possible values are identical to those of [`DLL_EXTENSION`], but with the leading period included.
1127    #[stable(feature = "env", since = "1.0.0")]
1128    pub const DLL_SUFFIX: &str = os::DLL_SUFFIX;
1129
1130    /// Specifies the file extension, if any, used for shared libraries on this platform that goes after the dot.
1131    /// An example value may be: `"so"`, `"elf"`, or `"dll"`.
1132    ///
1133    /// <details><summary>Full list of possible values</summary>
1134    ///
1135    /// * `"so"`
1136    /// * `"dylib"`
1137    /// * `"dll"`
1138    /// * `"sgxs"`
1139    /// * `"a"`
1140    /// * `"elf"`
1141    /// * `"wasm"`
1142    /// * `""` (an empty string)
1143    ///
1144    /// </details>
1145    #[stable(feature = "env", since = "1.0.0")]
1146    pub const DLL_EXTENSION: &str = os::DLL_EXTENSION;
1147
1148    /// Specifies the filename suffix, if any, used for executable binaries on this platform.
1149    /// An example value may be: `".exe"`, or `".efi"`.
1150    ///
1151    /// The possible values are identical to those of [`EXE_EXTENSION`], but with the leading period included.
1152    #[stable(feature = "env", since = "1.0.0")]
1153    pub const EXE_SUFFIX: &str = os::EXE_SUFFIX;
1154
1155    /// Specifies the file extension, if any, used for executable binaries on this platform.
1156    /// An example value may be: `"exe"`, or an empty string (`""`).
1157    ///
1158    /// <details><summary>Full list of possible values</summary>
1159    ///
1160    /// * `"bin"`
1161    /// * `"exe"`
1162    /// * `"efi"`
1163    /// * `"js"`
1164    /// * `"sgxs"`
1165    /// * `"elf"`
1166    /// * `"wasm"`
1167    /// * `""` (an empty string)
1168    ///
1169    /// </details>
1170    #[stable(feature = "env", since = "1.0.0")]
1171    pub const EXE_EXTENSION: &str = os::EXE_EXTENSION;
1172}