]> git.lizzy.rs Git - rust.git/blob - library/std/src/env.rs
Rollup merge of #92058 - jsha:run-on-hover, r=GuillaumeGomez
[rust.git] / library / std / src / 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
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")]
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")]
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")]
118 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")]
146 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);
153     fn next(&mut self) -> Option<(String, String)> {
154         self.inner.next().map(|(a, b)| (a.into_string().unwrap(), b.into_string().unwrap()))
155     }
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 {
163     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);
171     fn next(&mut self) -> Option<(OsString, OsString)> {
172         self.inner.next()
173     }
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 {
181     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")]
210 pub fn var<K: AsRef<OsStr>>(key: K) -> Result<String, VarError> {
211     _var(key.as_ref())
212 }
213
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")]
251 pub fn var_os<K: AsRef<OsStr>>(key: K) -> Option<OsString> {
252     _var_os(key.as_ref())
253 }
254
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 {
280     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)]
293     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")]
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
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")]
372 pub fn remove_var<K: AsRef<OsStr>>(key: K) {
373     _remove_var(key.as_ref())
374 }
375
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")]
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;
425     fn next(&mut self) -> Option<PathBuf> {
426         self.inner.next()
427     }
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<'_> {
435     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")]
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 {
522     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)]
530     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")]
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 /// # Platform-specific behavior
587 ///
588 /// On Unix, 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 /// On Windows, the behavior is equivalent to that of [`GetTempPath2`][GetTempPath2] /
593 /// [`GetTempPath`][GetTempPath], which this function uses internally.
594 /// Note that, this [may change in the future][changes].
595 ///
596 /// [changes]: io#platform-specific-behavior
597 /// [GetTempPath2]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-gettemppath2a
598 /// [GetTempPath]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-gettemppatha
599 ///
600 /// ```no_run
601 /// use std::env;
602 ///
603 /// fn main() {
604 ///     let dir = env::temp_dir();
605 ///     println!("Temporary directory: {}", dir.display());
606 /// }
607 /// ```
608 #[must_use]
609 #[stable(feature = "env", since = "1.0.0")]
610 pub fn temp_dir() -> PathBuf {
611     os_imp::temp_dir()
612 }
613
614 /// Returns the full filesystem path of the current running executable.
615 ///
616 /// # Platform-specific behavior
617 ///
618 /// If the executable was invoked through a symbolic link, some platforms will
619 /// return the path of the symbolic link and other platforms will return the
620 /// path of the symbolic link’s target.
621 ///
622 /// If the executable is renamed while it is running, platforms may return the
623 /// path at the time it was loaded instead of the new path.
624 ///
625 /// # Errors
626 ///
627 /// Acquiring the path of the current executable is a platform-specific operation
628 /// that can fail for a good number of reasons. Some errors can include, but not
629 /// be limited to, filesystem operations failing or general syscall failures.
630 ///
631 /// # Security
632 ///
633 /// The output of this function should not be used in anything that might have
634 /// security implications. For example:
635 ///
636 /// ```
637 /// fn main() {
638 ///     println!("{:?}", std::env::current_exe());
639 /// }
640 /// ```
641 ///
642 /// On Linux systems, if this is compiled as `foo`:
643 ///
644 /// ```bash
645 /// $ rustc foo.rs
646 /// $ ./foo
647 /// Ok("/home/alex/foo")
648 /// ```
649 ///
650 /// And you make a hard link of the program:
651 ///
652 /// ```bash
653 /// $ ln foo bar
654 /// ```
655 ///
656 /// When you run it, you won’t get the path of the original executable, you’ll
657 /// get the path of the hard link:
658 ///
659 /// ```bash
660 /// $ ./bar
661 /// Ok("/home/alex/bar")
662 /// ```
663 ///
664 /// This sort of behavior has been known to [lead to privilege escalation] when
665 /// used incorrectly.
666 ///
667 /// [lead to privilege escalation]: https://securityvulns.com/Wdocument183.html
668 ///
669 /// # Examples
670 ///
671 /// ```
672 /// use std::env;
673 ///
674 /// match env::current_exe() {
675 ///     Ok(exe_path) => println!("Path of this executable is: {}",
676 ///                              exe_path.display()),
677 ///     Err(e) => println!("failed to get current exe path: {}", e),
678 /// };
679 /// ```
680 #[stable(feature = "env", since = "1.0.0")]
681 pub fn current_exe() -> io::Result<PathBuf> {
682     os_imp::current_exe()
683 }
684
685 /// An iterator over the arguments of a process, yielding a [`String`] value for
686 /// each argument.
687 ///
688 /// This struct is created by [`env::args()`]. See its documentation
689 /// for more.
690 ///
691 /// The first element is traditionally the path of the executable, but it can be
692 /// set to arbitrary text, and might not even exist. This means this property
693 /// should not be relied upon for security purposes.
694 ///
695 /// [`env::args()`]: args
696 #[must_use = "iterators are lazy and do nothing unless consumed"]
697 #[stable(feature = "env", since = "1.0.0")]
698 pub struct Args {
699     inner: ArgsOs,
700 }
701
702 /// An iterator over the arguments of a process, yielding an [`OsString`] value
703 /// for each argument.
704 ///
705 /// This struct is created by [`env::args_os()`]. See its documentation
706 /// for more.
707 ///
708 /// The first element is traditionally the path of the executable, but it can be
709 /// set to arbitrary text, and might not even exist. This means this property
710 /// should not be relied upon for security purposes.
711 ///
712 /// [`env::args_os()`]: args_os
713 #[must_use = "iterators are lazy and do nothing unless consumed"]
714 #[stable(feature = "env", since = "1.0.0")]
715 pub struct ArgsOs {
716     inner: sys::args::Args,
717 }
718
719 /// Returns the arguments that this program was started with (normally passed
720 /// via the command line).
721 ///
722 /// The first element is traditionally the path of the executable, but it can be
723 /// set to arbitrary text, and might not even exist. This means this property should
724 /// not be relied upon for security purposes.
725 ///
726 /// On Unix systems the shell usually expands unquoted arguments with glob patterns
727 /// (such as `*` and `?`). On Windows this is not done, and such arguments are
728 /// passed as-is.
729 ///
730 /// On glibc Linux systems, arguments are retrieved by placing a function in `.init_array`.
731 /// glibc passes `argc`, `argv`, and `envp` to functions in `.init_array`, as a non-standard
732 /// extension. This allows `std::env::args` to work even in a `cdylib` or `staticlib`, as it
733 /// does on macOS and Windows.
734 ///
735 /// # Panics
736 ///
737 /// The returned iterator will panic during iteration if any argument to the
738 /// process is not valid Unicode. If this is not desired,
739 /// use the [`args_os`] function instead.
740 ///
741 /// # Examples
742 ///
743 /// ```
744 /// use std::env;
745 ///
746 /// // Prints each argument on a separate line
747 /// for argument in env::args() {
748 ///     println!("{}", argument);
749 /// }
750 /// ```
751 #[stable(feature = "env", since = "1.0.0")]
752 pub fn args() -> Args {
753     Args { inner: args_os() }
754 }
755
756 /// Returns the arguments that this program was started with (normally passed
757 /// via the command line).
758 ///
759 /// The first element is traditionally the path of the executable, but it can be
760 /// set to arbitrary text, and might not even exist. This means this property should
761 /// not be relied upon for security purposes.
762 ///
763 /// On Unix systems the shell usually expands unquoted arguments with glob patterns
764 /// (such as `*` and `?`). On Windows this is not done, and such arguments are
765 /// passed as-is.
766 ///
767 /// On glibc Linux systems, arguments are retrieved by placing a function in `.init_array`.
768 /// glibc passes `argc`, `argv`, and `envp` to functions in `.init_array`, as a non-standard
769 /// extension. This allows `std::env::args_os` to work even in a `cdylib` or `staticlib`, as it
770 /// does on macOS and Windows.
771 ///
772 /// Note that the returned iterator will not check if the arguments to the
773 /// process are valid Unicode. If you want to panic on invalid UTF-8,
774 /// use the [`args`] function instead.
775 ///
776 /// # Examples
777 ///
778 /// ```
779 /// use std::env;
780 ///
781 /// // Prints each argument on a separate line
782 /// for argument in env::args_os() {
783 ///     println!("{:?}", argument);
784 /// }
785 /// ```
786 #[stable(feature = "env", since = "1.0.0")]
787 pub fn args_os() -> ArgsOs {
788     ArgsOs { inner: sys::args::args() }
789 }
790
791 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
792 impl !Send for Args {}
793
794 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
795 impl !Sync for Args {}
796
797 #[stable(feature = "env", since = "1.0.0")]
798 impl Iterator for Args {
799     type Item = String;
800     fn next(&mut self) -> Option<String> {
801         self.inner.next().map(|s| s.into_string().unwrap())
802     }
803     fn size_hint(&self) -> (usize, Option<usize>) {
804         self.inner.size_hint()
805     }
806 }
807
808 #[stable(feature = "env", since = "1.0.0")]
809 impl ExactSizeIterator for Args {
810     fn len(&self) -> usize {
811         self.inner.len()
812     }
813     fn is_empty(&self) -> bool {
814         self.inner.is_empty()
815     }
816 }
817
818 #[stable(feature = "env_iterators", since = "1.12.0")]
819 impl DoubleEndedIterator for Args {
820     fn next_back(&mut self) -> Option<String> {
821         self.inner.next_back().map(|s| s.into_string().unwrap())
822     }
823 }
824
825 #[stable(feature = "std_debug", since = "1.16.0")]
826 impl fmt::Debug for Args {
827     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
828         f.debug_struct("Args").field("inner", &self.inner.inner).finish()
829     }
830 }
831
832 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
833 impl !Send for ArgsOs {}
834
835 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
836 impl !Sync for ArgsOs {}
837
838 #[stable(feature = "env", since = "1.0.0")]
839 impl Iterator for ArgsOs {
840     type Item = OsString;
841     fn next(&mut self) -> Option<OsString> {
842         self.inner.next()
843     }
844     fn size_hint(&self) -> (usize, Option<usize>) {
845         self.inner.size_hint()
846     }
847 }
848
849 #[stable(feature = "env", since = "1.0.0")]
850 impl ExactSizeIterator for ArgsOs {
851     fn len(&self) -> usize {
852         self.inner.len()
853     }
854     fn is_empty(&self) -> bool {
855         self.inner.is_empty()
856     }
857 }
858
859 #[stable(feature = "env_iterators", since = "1.12.0")]
860 impl DoubleEndedIterator for ArgsOs {
861     fn next_back(&mut self) -> Option<OsString> {
862         self.inner.next_back()
863     }
864 }
865
866 #[stable(feature = "std_debug", since = "1.16.0")]
867 impl fmt::Debug for ArgsOs {
868     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
869         f.debug_struct("ArgsOs").field("inner", &self.inner).finish()
870     }
871 }
872
873 /// Constants associated with the current target
874 #[stable(feature = "env", since = "1.0.0")]
875 pub mod consts {
876     use crate::sys::env::os;
877
878     /// A string describing the architecture of the CPU that is currently
879     /// in use.
880     ///
881     /// Some possible values:
882     ///
883     /// - x86
884     /// - x86_64
885     /// - arm
886     /// - aarch64
887     /// - m68k
888     /// - mips
889     /// - mips64
890     /// - powerpc
891     /// - powerpc64
892     /// - riscv64
893     /// - s390x
894     /// - sparc64
895     #[stable(feature = "env", since = "1.0.0")]
896     pub const ARCH: &str = env!("STD_ENV_ARCH");
897
898     /// The family of the operating system. Example value is `unix`.
899     ///
900     /// Some possible values:
901     ///
902     /// - unix
903     /// - windows
904     #[stable(feature = "env", since = "1.0.0")]
905     pub const FAMILY: &str = os::FAMILY;
906
907     /// A string describing the specific operating system in use.
908     /// Example value is `linux`.
909     ///
910     /// Some possible values:
911     ///
912     /// - linux
913     /// - macos
914     /// - ios
915     /// - freebsd
916     /// - dragonfly
917     /// - netbsd
918     /// - openbsd
919     /// - solaris
920     /// - android
921     /// - windows
922     #[stable(feature = "env", since = "1.0.0")]
923     pub const OS: &str = os::OS;
924
925     /// Specifies the filename prefix used for shared libraries on this
926     /// platform. Example value is `lib`.
927     ///
928     /// Some possible values:
929     ///
930     /// - lib
931     /// - `""` (an empty string)
932     #[stable(feature = "env", since = "1.0.0")]
933     pub const DLL_PREFIX: &str = os::DLL_PREFIX;
934
935     /// Specifies the filename suffix used for shared libraries on this
936     /// platform. Example value is `.so`.
937     ///
938     /// Some possible values:
939     ///
940     /// - .so
941     /// - .dylib
942     /// - .dll
943     #[stable(feature = "env", since = "1.0.0")]
944     pub const DLL_SUFFIX: &str = os::DLL_SUFFIX;
945
946     /// Specifies the file extension used for shared libraries on this
947     /// platform that goes after the dot. Example value is `so`.
948     ///
949     /// Some possible values:
950     ///
951     /// - so
952     /// - dylib
953     /// - dll
954     #[stable(feature = "env", since = "1.0.0")]
955     pub const DLL_EXTENSION: &str = os::DLL_EXTENSION;
956
957     /// Specifies the filename suffix used for executable binaries on this
958     /// platform. Example value is `.exe`.
959     ///
960     /// Some possible values:
961     ///
962     /// - .exe
963     /// - .nexe
964     /// - .pexe
965     /// - `""` (an empty string)
966     #[stable(feature = "env", since = "1.0.0")]
967     pub const EXE_SUFFIX: &str = os::EXE_SUFFIX;
968
969     /// Specifies the file extension, if any, used for executable binaries
970     /// on this platform. Example value is `exe`.
971     ///
972     /// Some possible values:
973     ///
974     /// - exe
975     /// - `""` (an empty string)
976     #[stable(feature = "env", since = "1.0.0")]
977     pub const EXE_EXTENSION: &str = os::EXE_EXTENSION;
978 }