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