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