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