• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
13 #[cfg(test)]
14 mod tests;
15 
16 use crate::error::Error;
17 use crate::ffi::{OsStr, OsString};
18 use crate::fmt;
19 use crate::io;
20 use crate::path::{Path, PathBuf};
21 use crate::sys;
22 use crate::sys::os as os_imp;
23 
24 /// Returns the current working directory as a [`PathBuf`].
25 ///
26 /// # Platform-specific behavior
27 ///
28 /// This function [currently] corresponds to the `getcwd` function on Unix
29 /// and the `GetCurrentDirectoryW` function on Windows.
30 ///
31 /// [currently]: crate::io#platform-specific-behavior
32 ///
33 /// # Errors
34 ///
35 /// Returns an [`Err`] if the current working directory value is invalid.
36 /// Possible cases:
37 ///
38 /// * Current directory does not exist.
39 /// * There are insufficient permissions to access the current directory.
40 ///
41 /// # Examples
42 ///
43 /// ```
44 /// use std::env;
45 ///
46 /// fn main() -> std::io::Result<()> {
47 ///     let path = env::current_dir()?;
48 ///     println!("The current directory is {}", path.display());
49 ///     Ok(())
50 /// }
51 /// ```
52 #[doc(alias = "pwd")]
53 #[doc(alias = "getcwd")]
54 #[doc(alias = "GetCurrentDirectory")]
55 #[stable(feature = "env", since = "1.0.0")]
current_dir() -> io::Result<PathBuf>56 pub fn current_dir() -> io::Result<PathBuf> {
57     os_imp::getcwd()
58 }
59 
60 /// Changes the current working directory to the specified path.
61 ///
62 /// # Platform-specific behavior
63 ///
64 /// This function [currently] corresponds to the `chdir` function on Unix
65 /// and the `SetCurrentDirectoryW` function on Windows.
66 ///
67 /// Returns an [`Err`] if the operation fails.
68 ///
69 /// [currently]: crate::io#platform-specific-behavior
70 ///
71 /// # Examples
72 ///
73 /// ```
74 /// use std::env;
75 /// use std::path::Path;
76 ///
77 /// let root = Path::new("/");
78 /// assert!(env::set_current_dir(&root).is_ok());
79 /// println!("Successfully changed working directory to {}!", root.display());
80 /// ```
81 #[doc(alias = "chdir")]
82 #[stable(feature = "env", since = "1.0.0")]
set_current_dir<P: AsRef<Path>>(path: P) -> io::Result<()>83 pub fn set_current_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
84     os_imp::chdir(path.as_ref())
85 }
86 
87 /// An iterator over a snapshot of the environment variables of this process.
88 ///
89 /// This structure is created by [`env::vars()`]. See its documentation for more.
90 ///
91 /// [`env::vars()`]: vars
92 #[stable(feature = "env", since = "1.0.0")]
93 pub struct Vars {
94     inner: VarsOs,
95 }
96 
97 /// An iterator over a snapshot of the environment variables of this process.
98 ///
99 /// This structure is created by [`env::vars_os()`]. See its documentation for more.
100 ///
101 /// [`env::vars_os()`]: vars_os
102 #[stable(feature = "env", since = "1.0.0")]
103 pub struct VarsOs {
104     inner: os_imp::Env,
105 }
106 
107 /// Returns an iterator of (variable, value) pairs of strings, for all the
108 /// environment variables of the current process.
109 ///
110 /// The returned iterator contains a snapshot of the process's environment
111 /// variables at the time of this invocation. Modifications to environment
112 /// variables afterwards will not be reflected in the returned iterator.
113 ///
114 /// # Panics
115 ///
116 /// While iterating, the returned iterator will panic if any key or value in the
117 /// environment is not valid unicode. If this is not desired, consider using
118 /// [`env::vars_os()`].
119 ///
120 /// # Examples
121 ///
122 /// ```
123 /// use std::env;
124 ///
125 /// // We will iterate through the references to the element returned by
126 /// // env::vars();
127 /// for (key, value) in env::vars() {
128 ///     println!("{key}: {value}");
129 /// }
130 /// ```
131 ///
132 /// [`env::vars_os()`]: vars_os
133 #[must_use]
134 #[stable(feature = "env", since = "1.0.0")]
vars() -> Vars135 pub fn vars() -> Vars {
136     Vars { inner: vars_os() }
137 }
138 
139 /// Returns an iterator of (variable, value) pairs of OS strings, for all the
140 /// environment variables of the current process.
141 ///
142 /// The returned iterator contains a snapshot of the process's environment
143 /// variables at the time of this invocation. Modifications to environment
144 /// variables afterwards will not be reflected in the returned iterator.
145 ///
146 /// Note that the returned iterator will not check if the environment variables
147 /// are valid Unicode. If you want to panic on invalid UTF-8,
148 /// use the [`vars`] function instead.
149 ///
150 /// # Examples
151 ///
152 /// ```
153 /// use std::env;
154 ///
155 /// // We will iterate through the references to the element returned by
156 /// // env::vars_os();
157 /// for (key, value) in env::vars_os() {
158 ///     println!("{key:?}: {value:?}");
159 /// }
160 /// ```
161 #[must_use]
162 #[stable(feature = "env", since = "1.0.0")]
vars_os() -> VarsOs163 pub fn vars_os() -> VarsOs {
164     VarsOs { inner: os_imp::env() }
165 }
166 
167 #[stable(feature = "env", since = "1.0.0")]
168 impl Iterator for Vars {
169     type Item = (String, String);
next(&mut self) -> Option<(String, String)>170     fn next(&mut self) -> Option<(String, String)> {
171         self.inner.next().map(|(a, b)| (a.into_string().unwrap(), b.into_string().unwrap()))
172     }
size_hint(&self) -> (usize, Option<usize>)173     fn size_hint(&self) -> (usize, Option<usize>) {
174         self.inner.size_hint()
175     }
176 }
177 
178 #[stable(feature = "std_debug", since = "1.16.0")]
179 impl fmt::Debug for Vars {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result180     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
181         f.debug_struct("Vars").finish_non_exhaustive()
182     }
183 }
184 
185 #[stable(feature = "env", since = "1.0.0")]
186 impl Iterator for VarsOs {
187     type Item = (OsString, OsString);
next(&mut self) -> Option<(OsString, OsString)>188     fn next(&mut self) -> Option<(OsString, OsString)> {
189         self.inner.next()
190     }
size_hint(&self) -> (usize, Option<usize>)191     fn size_hint(&self) -> (usize, Option<usize>) {
192         self.inner.size_hint()
193     }
194 }
195 
196 #[stable(feature = "std_debug", since = "1.16.0")]
197 impl fmt::Debug for VarsOs {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result198     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
199         f.debug_struct("VarOs").finish_non_exhaustive()
200     }
201 }
202 
203 /// Fetches the environment variable `key` from the current process.
204 ///
205 /// # Errors
206 ///
207 /// This function will return an error if the environment variable isn't set.
208 ///
209 /// This function may return an error if the environment variable's name contains
210 /// the equal sign character (`=`) or the NUL character.
211 ///
212 /// This function will return an error if the environment variable's value is
213 /// not valid Unicode. If this is not desired, consider using [`var_os`].
214 ///
215 /// # Examples
216 ///
217 /// ```
218 /// use std::env;
219 ///
220 /// let key = "HOME";
221 /// match env::var(key) {
222 ///     Ok(val) => println!("{key}: {val:?}"),
223 ///     Err(e) => println!("couldn't interpret {key}: {e}"),
224 /// }
225 /// ```
226 #[stable(feature = "env", since = "1.0.0")]
var<K: AsRef<OsStr>>(key: K) -> Result<String, VarError>227 pub fn var<K: AsRef<OsStr>>(key: K) -> Result<String, VarError> {
228     _var(key.as_ref())
229 }
230 
_var(key: &OsStr) -> Result<String, VarError>231 fn _var(key: &OsStr) -> Result<String, VarError> {
232     match var_os(key) {
233         Some(s) => s.into_string().map_err(VarError::NotUnicode),
234         None => Err(VarError::NotPresent),
235     }
236 }
237 
238 /// Fetches the environment variable `key` from the current process, returning
239 /// [`None`] if the variable isn't set or if there is another error.
240 ///
241 /// It may return `None` if the environment variable's name contains
242 /// the equal sign character (`=`) or the NUL character.
243 ///
244 /// Note that this function will not check if the environment variable
245 /// is valid Unicode. If you want to have an error on invalid UTF-8,
246 /// use the [`var`] function instead.
247 ///
248 /// # Examples
249 ///
250 /// ```
251 /// use std::env;
252 ///
253 /// let key = "HOME";
254 /// match env::var_os(key) {
255 ///     Some(val) => println!("{key}: {val:?}"),
256 ///     None => println!("{key} is not defined in the environment.")
257 /// }
258 /// ```
259 #[must_use]
260 #[stable(feature = "env", since = "1.0.0")]
var_os<K: AsRef<OsStr>>(key: K) -> Option<OsString>261 pub fn var_os<K: AsRef<OsStr>>(key: K) -> Option<OsString> {
262     _var_os(key.as_ref())
263 }
264 
_var_os(key: &OsStr) -> Option<OsString>265 fn _var_os(key: &OsStr) -> Option<OsString> {
266     os_imp::getenv(key)
267 }
268 
269 /// The error type for operations interacting with environment variables.
270 /// Possibly returned from [`env::var()`].
271 ///
272 /// [`env::var()`]: var
273 #[derive(Debug, PartialEq, Eq, Clone)]
274 #[stable(feature = "env", since = "1.0.0")]
275 pub enum VarError {
276     /// The specified environment variable was not present in the current
277     /// process's environment.
278     #[stable(feature = "env", since = "1.0.0")]
279     NotPresent,
280 
281     /// The specified environment variable was found, but it did not contain
282     /// valid unicode data. The found data is returned as a payload of this
283     /// variant.
284     #[stable(feature = "env", since = "1.0.0")]
285     NotUnicode(#[stable(feature = "env", since = "1.0.0")] OsString),
286 }
287 
288 #[stable(feature = "env", since = "1.0.0")]
289 impl fmt::Display for VarError {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result290     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
291         match *self {
292             VarError::NotPresent => write!(f, "environment variable not found"),
293             VarError::NotUnicode(ref s) => {
294                 write!(f, "environment variable was not valid unicode: {:?}", s)
295             }
296         }
297     }
298 }
299 
300 #[stable(feature = "env", since = "1.0.0")]
301 impl Error for VarError {
302     #[allow(deprecated)]
description(&self) -> &str303     fn description(&self) -> &str {
304         match *self {
305             VarError::NotPresent => "environment variable not found",
306             VarError::NotUnicode(..) => "environment variable was not valid unicode",
307         }
308     }
309 }
310 
311 /// Sets the environment variable `key` to the value `value` for the currently running
312 /// process.
313 ///
314 /// Note that while concurrent access to environment variables is safe in Rust,
315 /// some platforms only expose inherently unsafe non-threadsafe APIs for
316 /// inspecting the environment. As a result, extra care needs to be taken when
317 /// auditing calls to unsafe external FFI functions to ensure that any external
318 /// environment accesses are properly synchronized with accesses in Rust.
319 ///
320 /// Discussion of this unsafety on Unix may be found in:
321 ///
322 ///  - [Austin Group Bugzilla](https://austingroupbugs.net/view.php?id=188)
323 ///  - [GNU C library Bugzilla](https://sourceware.org/bugzilla/show_bug.cgi?id=15607#c2)
324 ///
325 /// # Panics
326 ///
327 /// This function may panic if `key` is empty, contains an ASCII equals sign `'='`
328 /// or the NUL character `'\0'`, or when `value` contains the NUL character.
329 ///
330 /// # Examples
331 ///
332 /// ```
333 /// use std::env;
334 ///
335 /// let key = "KEY";
336 /// env::set_var(key, "VALUE");
337 /// assert_eq!(env::var(key), Ok("VALUE".to_string()));
338 /// ```
339 #[stable(feature = "env", since = "1.0.0")]
set_var<K: AsRef<OsStr>, V: AsRef<OsStr>>(key: K, value: V)340 pub fn set_var<K: AsRef<OsStr>, V: AsRef<OsStr>>(key: K, value: V) {
341     _set_var(key.as_ref(), value.as_ref())
342 }
343 
_set_var(key: &OsStr, value: &OsStr)344 fn _set_var(key: &OsStr, value: &OsStr) {
345     os_imp::setenv(key, value).unwrap_or_else(|e| {
346         panic!("failed to set environment variable `{key:?}` to `{value:?}`: {e}")
347     })
348 }
349 
350 /// Removes an environment variable from the environment of the currently running process.
351 ///
352 /// Note that while concurrent access to environment variables is safe in Rust,
353 /// some platforms only expose inherently unsafe non-threadsafe APIs for
354 /// inspecting the environment. As a result extra care needs to be taken when
355 /// auditing calls to unsafe external FFI functions to ensure that any external
356 /// environment accesses are properly synchronized with accesses in Rust.
357 ///
358 /// Discussion of this unsafety on Unix may be found in:
359 ///
360 ///  - [Austin Group Bugzilla](https://austingroupbugs.net/view.php?id=188)
361 ///  - [GNU C library Bugzilla](https://sourceware.org/bugzilla/show_bug.cgi?id=15607#c2)
362 ///
363 /// # Panics
364 ///
365 /// This function may panic if `key` is empty, contains an ASCII equals sign
366 /// `'='` or the NUL character `'\0'`, or when the value contains the NUL
367 /// character.
368 ///
369 /// # Examples
370 ///
371 /// ```
372 /// use std::env;
373 ///
374 /// let key = "KEY";
375 /// env::set_var(key, "VALUE");
376 /// assert_eq!(env::var(key), Ok("VALUE".to_string()));
377 ///
378 /// env::remove_var(key);
379 /// assert!(env::var(key).is_err());
380 /// ```
381 #[stable(feature = "env", since = "1.0.0")]
remove_var<K: AsRef<OsStr>>(key: K)382 pub fn remove_var<K: AsRef<OsStr>>(key: K) {
383     _remove_var(key.as_ref())
384 }
385 
_remove_var(key: &OsStr)386 fn _remove_var(key: &OsStr) {
387     os_imp::unsetenv(key)
388         .unwrap_or_else(|e| panic!("failed to remove environment variable `{key:?}`: {e}"))
389 }
390 
391 /// An iterator that splits an environment variable into paths according to
392 /// platform-specific conventions.
393 ///
394 /// The iterator element type is [`PathBuf`].
395 ///
396 /// This structure is created by [`env::split_paths()`]. See its
397 /// documentation for more.
398 ///
399 /// [`env::split_paths()`]: split_paths
400 #[must_use = "iterators are lazy and do nothing unless consumed"]
401 #[stable(feature = "env", since = "1.0.0")]
402 pub struct SplitPaths<'a> {
403     inner: os_imp::SplitPaths<'a>,
404 }
405 
406 /// Parses input according to platform conventions for the `PATH`
407 /// environment variable.
408 ///
409 /// Returns an iterator over the paths contained in `unparsed`. The iterator
410 /// element type is [`PathBuf`].
411 ///
412 /// # Examples
413 ///
414 /// ```
415 /// use std::env;
416 ///
417 /// let key = "PATH";
418 /// match env::var_os(key) {
419 ///     Some(paths) => {
420 ///         for path in env::split_paths(&paths) {
421 ///             println!("'{}'", path.display());
422 ///         }
423 ///     }
424 ///     None => println!("{key} is not defined in the environment.")
425 /// }
426 /// ```
427 #[stable(feature = "env", since = "1.0.0")]
split_paths<T: AsRef<OsStr> + ?Sized>(unparsed: &T) -> SplitPaths<'_>428 pub fn split_paths<T: AsRef<OsStr> + ?Sized>(unparsed: &T) -> SplitPaths<'_> {
429     SplitPaths { inner: os_imp::split_paths(unparsed.as_ref()) }
430 }
431 
432 #[stable(feature = "env", since = "1.0.0")]
433 impl<'a> Iterator for SplitPaths<'a> {
434     type Item = PathBuf;
next(&mut self) -> Option<PathBuf>435     fn next(&mut self) -> Option<PathBuf> {
436         self.inner.next()
437     }
size_hint(&self) -> (usize, Option<usize>)438     fn size_hint(&self) -> (usize, Option<usize>) {
439         self.inner.size_hint()
440     }
441 }
442 
443 #[stable(feature = "std_debug", since = "1.16.0")]
444 impl fmt::Debug for SplitPaths<'_> {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result445     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
446         f.debug_struct("SplitPaths").finish_non_exhaustive()
447     }
448 }
449 
450 /// The error type for operations on the `PATH` variable. Possibly returned from
451 /// [`env::join_paths()`].
452 ///
453 /// [`env::join_paths()`]: join_paths
454 #[derive(Debug)]
455 #[stable(feature = "env", since = "1.0.0")]
456 pub struct JoinPathsError {
457     inner: os_imp::JoinPathsError,
458 }
459 
460 /// Joins a collection of [`Path`]s appropriately for the `PATH`
461 /// environment variable.
462 ///
463 /// # Errors
464 ///
465 /// Returns an [`Err`] (containing an error message) if one of the input
466 /// [`Path`]s contains an invalid character for constructing the `PATH`
467 /// variable (a double quote on Windows or a colon on Unix).
468 ///
469 /// # Examples
470 ///
471 /// Joining paths on a Unix-like platform:
472 ///
473 /// ```
474 /// use std::env;
475 /// use std::ffi::OsString;
476 /// use std::path::Path;
477 ///
478 /// fn main() -> Result<(), env::JoinPathsError> {
479 /// # if cfg!(unix) {
480 ///     let paths = [Path::new("/bin"), Path::new("/usr/bin")];
481 ///     let path_os_string = env::join_paths(paths.iter())?;
482 ///     assert_eq!(path_os_string, OsString::from("/bin:/usr/bin"));
483 /// # }
484 ///     Ok(())
485 /// }
486 /// ```
487 ///
488 /// Joining a path containing a colon on a Unix-like platform results in an
489 /// error:
490 ///
491 /// ```
492 /// # if cfg!(unix) {
493 /// use std::env;
494 /// use std::path::Path;
495 ///
496 /// let paths = [Path::new("/bin"), Path::new("/usr/bi:n")];
497 /// assert!(env::join_paths(paths.iter()).is_err());
498 /// # }
499 /// ```
500 ///
501 /// Using `env::join_paths()` with [`env::split_paths()`] to append an item to
502 /// the `PATH` environment variable:
503 ///
504 /// ```
505 /// use std::env;
506 /// use std::path::PathBuf;
507 ///
508 /// fn main() -> Result<(), env::JoinPathsError> {
509 ///     if let Some(path) = env::var_os("PATH") {
510 ///         let mut paths = env::split_paths(&path).collect::<Vec<_>>();
511 ///         paths.push(PathBuf::from("/home/xyz/bin"));
512 ///         let new_path = env::join_paths(paths)?;
513 ///         env::set_var("PATH", &new_path);
514 ///     }
515 ///
516 ///     Ok(())
517 /// }
518 /// ```
519 ///
520 /// [`env::split_paths()`]: split_paths
521 #[stable(feature = "env", since = "1.0.0")]
join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError> where I: IntoIterator<Item = T>, T: AsRef<OsStr>,522 pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
523 where
524     I: IntoIterator<Item = T>,
525     T: AsRef<OsStr>,
526 {
527     os_imp::join_paths(paths.into_iter()).map_err(|e| JoinPathsError { inner: e })
528 }
529 
530 #[stable(feature = "env", since = "1.0.0")]
531 impl fmt::Display for JoinPathsError {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result532     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
533         self.inner.fmt(f)
534     }
535 }
536 
537 #[stable(feature = "env", since = "1.0.0")]
538 impl Error for JoinPathsError {
539     #[allow(deprecated, deprecated_in_future)]
description(&self) -> &str540     fn description(&self) -> &str {
541         self.inner.description()
542     }
543 }
544 
545 /// Returns the path of the current user's home directory if known.
546 ///
547 /// # Unix
548 ///
549 /// - Returns the value of the 'HOME' environment variable if it is set
550 ///   (including to an empty string).
551 /// - Otherwise, it tries to determine the home directory by invoking the `getpwuid_r` function
552 ///   using the UID of the current user. An empty home directory field returned from the
553 ///   `getpwuid_r` function is considered to be a valid value.
554 /// - Returns `None` if the current user has no entry in the /etc/passwd file.
555 ///
556 /// # Windows
557 ///
558 /// - Returns the value of the 'HOME' environment variable if it is set
559 ///   (including to an empty string).
560 /// - Otherwise, returns the value of the 'USERPROFILE' environment variable if it is set
561 ///   (including to an empty string).
562 /// - If both do not exist, [`GetUserProfileDirectory`][msdn] is used to return the path.
563 ///
564 /// [msdn]: https://docs.microsoft.com/en-us/windows/win32/api/userenv/nf-userenv-getuserprofiledirectorya
565 ///
566 /// # Deprecation
567 ///
568 /// This function is deprecated because the behaviour on Windows is not correct.
569 /// The 'HOME' environment variable is not standard on Windows, and may not produce
570 /// desired results; for instance, under Cygwin or Mingw it will return `/home/you`
571 /// when it should return `C:\Users\you`.
572 ///
573 /// # Examples
574 ///
575 /// ```
576 /// use std::env;
577 ///
578 /// match env::home_dir() {
579 ///     Some(path) => println!("Your home directory, probably: {}", path.display()),
580 ///     None => println!("Impossible to get your home dir!"),
581 /// }
582 /// ```
583 #[deprecated(
584     since = "1.29.0",
585     note = "This function's behavior may be unexpected on Windows. \
586             Consider using a crate from crates.io instead."
587 )]
588 #[must_use]
589 #[stable(feature = "env", since = "1.0.0")]
home_dir() -> Option<PathBuf>590 pub fn home_dir() -> Option<PathBuf> {
591     os_imp::home_dir()
592 }
593 
594 /// Returns the path of a temporary directory.
595 ///
596 /// The temporary directory may be shared among users, or between processes
597 /// with different privileges; thus, the creation of any files or directories
598 /// in the temporary directory must use a secure method to create a uniquely
599 /// named file. Creating a file or directory with a fixed or predictable name
600 /// may result in "insecure temporary file" security vulnerabilities. Consider
601 /// using a crate that securely creates temporary files or directories.
602 ///
603 /// # Platform-specific behavior
604 ///
605 /// On Unix, returns the value of the `TMPDIR` environment variable if it is
606 /// set, otherwise for non-Android it returns `/tmp`. On Android, since there
607 /// is no global temporary folder (it is usually allocated per-app), it returns
608 /// `/data/local/tmp`.
609 /// On Windows, the behavior is equivalent to that of [`GetTempPath2`][GetTempPath2] /
610 /// [`GetTempPath`][GetTempPath], which this function uses internally.
611 /// Note that, this [may change in the future][changes].
612 ///
613 /// [changes]: io#platform-specific-behavior
614 /// [GetTempPath2]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-gettemppath2a
615 /// [GetTempPath]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-gettemppatha
616 ///
617 /// ```no_run
618 /// use std::env;
619 ///
620 /// fn main() {
621 ///     let dir = env::temp_dir();
622 ///     println!("Temporary directory: {}", dir.display());
623 /// }
624 /// ```
625 #[must_use]
626 #[stable(feature = "env", since = "1.0.0")]
temp_dir() -> PathBuf627 pub fn temp_dir() -> PathBuf {
628     os_imp::temp_dir()
629 }
630 
631 /// Returns the full filesystem path of the current running executable.
632 ///
633 /// # Platform-specific behavior
634 ///
635 /// If the executable was invoked through a symbolic link, some platforms will
636 /// return the path of the symbolic link and other platforms will return the
637 /// path of the symbolic link’s target.
638 ///
639 /// If the executable is renamed while it is running, platforms may return the
640 /// path at the time it was loaded instead of the new path.
641 ///
642 /// # Errors
643 ///
644 /// Acquiring the path of the current executable is a platform-specific operation
645 /// that can fail for a good number of reasons. Some errors can include, but not
646 /// be limited to, filesystem operations failing or general syscall failures.
647 ///
648 /// # Security
649 ///
650 /// The output of this function should not be trusted for anything
651 /// that might have security implications. Basically, if users can run
652 /// the executable, they can change the output arbitrarily.
653 ///
654 /// As an example, you can easily introduce a race condition. It goes
655 /// like this:
656 ///
657 /// 1. You get the path to the current executable using `current_exe()`, and
658 ///    store it in a variable.
659 /// 2. Time passes. A malicious actor removes the current executable, and
660 ///    replaces it with a malicious one.
661 /// 3. You then use the stored path to re-execute the current
662 ///    executable.
663 ///
664 /// You expected to safely execute the current executable, but you're
665 /// instead executing something completely different. The code you
666 /// just executed run with your privileges.
667 ///
668 /// This sort of behavior has been known to [lead to privilege escalation] when
669 /// used incorrectly.
670 ///
671 /// [lead to privilege escalation]: https://securityvulns.com/Wdocument183.html
672 ///
673 /// # Examples
674 ///
675 /// ```
676 /// use std::env;
677 ///
678 /// match env::current_exe() {
679 ///     Ok(exe_path) => println!("Path of this executable is: {}",
680 ///                              exe_path.display()),
681 ///     Err(e) => println!("failed to get current exe path: {e}"),
682 /// };
683 /// ```
684 #[stable(feature = "env", since = "1.0.0")]
current_exe() -> io::Result<PathBuf>685 pub fn current_exe() -> io::Result<PathBuf> {
686     os_imp::current_exe()
687 }
688 
689 /// An iterator over the arguments of a process, yielding a [`String`] value for
690 /// each argument.
691 ///
692 /// This struct is created by [`env::args()`]. See its documentation
693 /// for more.
694 ///
695 /// The first element is traditionally the path of the executable, but it can be
696 /// set to arbitrary text, and might not even exist. This means this property
697 /// should not be relied upon for security purposes.
698 ///
699 /// [`env::args()`]: args
700 #[must_use = "iterators are lazy and do nothing unless consumed"]
701 #[stable(feature = "env", since = "1.0.0")]
702 pub struct Args {
703     inner: ArgsOs,
704 }
705 
706 /// An iterator over the arguments of a process, yielding an [`OsString`] value
707 /// for each argument.
708 ///
709 /// This struct is created by [`env::args_os()`]. See its documentation
710 /// for more.
711 ///
712 /// The first element is traditionally the path of the executable, but it can be
713 /// set to arbitrary text, and might not even exist. This means this property
714 /// should not be relied upon for security purposes.
715 ///
716 /// [`env::args_os()`]: args_os
717 #[must_use = "iterators are lazy and do nothing unless consumed"]
718 #[stable(feature = "env", since = "1.0.0")]
719 pub struct ArgsOs {
720     inner: sys::args::Args,
721 }
722 
723 /// Returns the arguments that this program was started with (normally passed
724 /// via the command line).
725 ///
726 /// The first element is traditionally the path of the executable, but it can be
727 /// set to arbitrary text, and might not even exist. This means this property should
728 /// not be relied upon for security purposes.
729 ///
730 /// On Unix systems the shell usually expands unquoted arguments with glob patterns
731 /// (such as `*` and `?`). On Windows this is not done, and such arguments are
732 /// passed as-is.
733 ///
734 /// On glibc Linux systems, arguments are retrieved by placing a function in `.init_array`.
735 /// glibc passes `argc`, `argv`, and `envp` to functions in `.init_array`, as a non-standard
736 /// extension. This allows `std::env::args` to work even in a `cdylib` or `staticlib`, as it
737 /// does on macOS and Windows.
738 ///
739 /// # Panics
740 ///
741 /// The returned iterator will panic during iteration if any argument to the
742 /// process is not valid Unicode. If this is not desired,
743 /// use the [`args_os`] function instead.
744 ///
745 /// # Examples
746 ///
747 /// ```
748 /// use std::env;
749 ///
750 /// // Prints each argument on a separate line
751 /// for argument in env::args() {
752 ///     println!("{argument}");
753 /// }
754 /// ```
755 #[stable(feature = "env", since = "1.0.0")]
args() -> Args756 pub fn args() -> Args {
757     Args { inner: args_os() }
758 }
759 
760 /// Returns the arguments that this program was started with (normally passed
761 /// via the command line).
762 ///
763 /// The first element is traditionally the path of the executable, but it can be
764 /// set to arbitrary text, and might not even exist. This means this property should
765 /// not be relied upon for security purposes.
766 ///
767 /// On Unix systems the shell usually expands unquoted arguments with glob patterns
768 /// (such as `*` and `?`). On Windows this is not done, and such arguments are
769 /// passed as-is.
770 ///
771 /// On glibc Linux systems, arguments are retrieved by placing a function in `.init_array`.
772 /// glibc passes `argc`, `argv`, and `envp` to functions in `.init_array`, as a non-standard
773 /// extension. This allows `std::env::args_os` to work even in a `cdylib` or `staticlib`, as it
774 /// does on macOS and Windows.
775 ///
776 /// Note that the returned iterator will not check if the arguments to the
777 /// process are valid Unicode. If you want to panic on invalid UTF-8,
778 /// use the [`args`] function instead.
779 ///
780 /// # Examples
781 ///
782 /// ```
783 /// use std::env;
784 ///
785 /// // Prints each argument on a separate line
786 /// for argument in env::args_os() {
787 ///     println!("{argument:?}");
788 /// }
789 /// ```
790 #[stable(feature = "env", since = "1.0.0")]
args_os() -> ArgsOs791 pub fn args_os() -> ArgsOs {
792     ArgsOs { inner: sys::args::args() }
793 }
794 
795 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
796 impl !Send for Args {}
797 
798 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
799 impl !Sync for Args {}
800 
801 #[stable(feature = "env", since = "1.0.0")]
802 impl Iterator for Args {
803     type Item = String;
next(&mut self) -> Option<String>804     fn next(&mut self) -> Option<String> {
805         self.inner.next().map(|s| s.into_string().unwrap())
806     }
size_hint(&self) -> (usize, Option<usize>)807     fn size_hint(&self) -> (usize, Option<usize>) {
808         self.inner.size_hint()
809     }
810 }
811 
812 #[stable(feature = "env", since = "1.0.0")]
813 impl ExactSizeIterator for Args {
len(&self) -> usize814     fn len(&self) -> usize {
815         self.inner.len()
816     }
is_empty(&self) -> bool817     fn is_empty(&self) -> bool {
818         self.inner.is_empty()
819     }
820 }
821 
822 #[stable(feature = "env_iterators", since = "1.12.0")]
823 impl DoubleEndedIterator for Args {
next_back(&mut self) -> Option<String>824     fn next_back(&mut self) -> Option<String> {
825         self.inner.next_back().map(|s| s.into_string().unwrap())
826     }
827 }
828 
829 #[stable(feature = "std_debug", since = "1.16.0")]
830 impl fmt::Debug for Args {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result831     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
832         f.debug_struct("Args").field("inner", &self.inner.inner).finish()
833     }
834 }
835 
836 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
837 impl !Send for ArgsOs {}
838 
839 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
840 impl !Sync for ArgsOs {}
841 
842 #[stable(feature = "env", since = "1.0.0")]
843 impl Iterator for ArgsOs {
844     type Item = OsString;
next(&mut self) -> Option<OsString>845     fn next(&mut self) -> Option<OsString> {
846         self.inner.next()
847     }
size_hint(&self) -> (usize, Option<usize>)848     fn size_hint(&self) -> (usize, Option<usize>) {
849         self.inner.size_hint()
850     }
851 }
852 
853 #[stable(feature = "env", since = "1.0.0")]
854 impl ExactSizeIterator for ArgsOs {
len(&self) -> usize855     fn len(&self) -> usize {
856         self.inner.len()
857     }
is_empty(&self) -> bool858     fn is_empty(&self) -> bool {
859         self.inner.is_empty()
860     }
861 }
862 
863 #[stable(feature = "env_iterators", since = "1.12.0")]
864 impl DoubleEndedIterator for ArgsOs {
next_back(&mut self) -> Option<OsString>865     fn next_back(&mut self) -> Option<OsString> {
866         self.inner.next_back()
867     }
868 }
869 
870 #[stable(feature = "std_debug", since = "1.16.0")]
871 impl fmt::Debug for ArgsOs {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result872     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
873         f.debug_struct("ArgsOs").field("inner", &self.inner).finish()
874     }
875 }
876 
877 /// Constants associated with the current target
878 #[stable(feature = "env", since = "1.0.0")]
879 pub mod consts {
880     use crate::sys::env::os;
881 
882     /// A string describing the architecture of the CPU that is currently
883     /// in use.
884     ///
885     /// Some possible values:
886     ///
887     /// - x86
888     /// - x86_64
889     /// - arm
890     /// - aarch64
891     /// - loongarch64
892     /// - m68k
893     /// - mips
894     /// - mips64
895     /// - powerpc
896     /// - powerpc64
897     /// - riscv64
898     /// - s390x
899     /// - sparc64
900     #[stable(feature = "env", since = "1.0.0")]
901     pub const ARCH: &str = env!("STD_ENV_ARCH");
902 
903     /// The family of the operating system. Example value is `unix`.
904     ///
905     /// Some possible values:
906     ///
907     /// - unix
908     /// - windows
909     #[stable(feature = "env", since = "1.0.0")]
910     pub const FAMILY: &str = os::FAMILY;
911 
912     /// A string describing the specific operating system in use.
913     /// Example value is `linux`.
914     ///
915     /// Some possible values:
916     ///
917     /// - linux
918     /// - macos
919     /// - ios
920     /// - freebsd
921     /// - dragonfly
922     /// - netbsd
923     /// - openbsd
924     /// - solaris
925     /// - android
926     /// - windows
927     #[stable(feature = "env", since = "1.0.0")]
928     pub const OS: &str = os::OS;
929 
930     /// Specifies the filename prefix used for shared libraries on this
931     /// platform. Example value is `lib`.
932     ///
933     /// Some possible values:
934     ///
935     /// - lib
936     /// - `""` (an empty string)
937     #[stable(feature = "env", since = "1.0.0")]
938     pub const DLL_PREFIX: &str = os::DLL_PREFIX;
939 
940     /// Specifies the filename suffix used for shared libraries on this
941     /// platform. Example value is `.so`.
942     ///
943     /// Some possible values:
944     ///
945     /// - .so
946     /// - .dylib
947     /// - .dll
948     #[stable(feature = "env", since = "1.0.0")]
949     pub const DLL_SUFFIX: &str = os::DLL_SUFFIX;
950 
951     /// Specifies the file extension used for shared libraries on this
952     /// platform that goes after the dot. Example value is `so`.
953     ///
954     /// Some possible values:
955     ///
956     /// - so
957     /// - dylib
958     /// - dll
959     #[stable(feature = "env", since = "1.0.0")]
960     pub const DLL_EXTENSION: &str = os::DLL_EXTENSION;
961 
962     /// Specifies the filename suffix used for executable binaries on this
963     /// platform. Example value is `.exe`.
964     ///
965     /// Some possible values:
966     ///
967     /// - .exe
968     /// - .nexe
969     /// - .pexe
970     /// - `""` (an empty string)
971     #[stable(feature = "env", since = "1.0.0")]
972     pub const EXE_SUFFIX: &str = os::EXE_SUFFIX;
973 
974     /// Specifies the file extension, if any, used for executable binaries
975     /// on this platform. Example value is `exe`.
976     ///
977     /// Some possible values:
978     ///
979     /// - exe
980     /// - `""` (an empty string)
981     #[stable(feature = "env", since = "1.0.0")]
982     pub const EXE_EXTENSION: &str = os::EXE_EXTENSION;
983 }
984