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