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