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