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