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