]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/solid/os.rs
Auto merge of #97870 - eggyal:inplace_fold_spec, r=wesleywiser
[rust.git] / library / std / src / sys / solid / os.rs
1 use super::unsupported;
2 use crate::convert::TryFrom;
3 use crate::error::Error as StdError;
4 use crate::ffi::{CStr, CString, OsStr, OsString};
5 use crate::fmt;
6 use crate::io;
7 use crate::os::{
8     raw::{c_char, c_int},
9     solid::ffi::{OsStrExt, OsStringExt},
10 };
11 use crate::path::{self, PathBuf};
12 use crate::sync::RwLock;
13 use crate::sys::common::small_c_string::run_with_cstr;
14 use crate::vec;
15
16 use super::{error, itron, memchr};
17
18 // `solid` directly maps `errno`s to μITRON error codes.
19 impl itron::error::ItronError {
20     #[inline]
21     pub(crate) fn as_io_error(self) -> crate::io::Error {
22         crate::io::Error::from_raw_os_error(self.as_raw())
23     }
24 }
25
26 pub fn errno() -> i32 {
27     0
28 }
29
30 pub fn error_string(errno: i32) -> String {
31     if let Some(name) = error::error_name(errno) { name.to_owned() } else { format!("{errno}") }
32 }
33
34 pub fn getcwd() -> io::Result<PathBuf> {
35     unsupported()
36 }
37
38 pub fn chdir(_: &path::Path) -> io::Result<()> {
39     unsupported()
40 }
41
42 pub struct SplitPaths<'a>(&'a !);
43
44 pub fn split_paths(_unparsed: &OsStr) -> SplitPaths<'_> {
45     panic!("unsupported")
46 }
47
48 impl<'a> Iterator for SplitPaths<'a> {
49     type Item = PathBuf;
50     fn next(&mut self) -> Option<PathBuf> {
51         *self.0
52     }
53 }
54
55 #[derive(Debug)]
56 pub struct JoinPathsError;
57
58 pub fn join_paths<I, T>(_paths: I) -> Result<OsString, JoinPathsError>
59 where
60     I: Iterator<Item = T>,
61     T: AsRef<OsStr>,
62 {
63     Err(JoinPathsError)
64 }
65
66 impl fmt::Display for JoinPathsError {
67     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68         "not supported on this platform yet".fmt(f)
69     }
70 }
71
72 impl StdError for JoinPathsError {
73     #[allow(deprecated)]
74     fn description(&self) -> &str {
75         "not supported on this platform yet"
76     }
77 }
78
79 pub fn current_exe() -> io::Result<PathBuf> {
80     unsupported()
81 }
82
83 static ENV_LOCK: RwLock<()> = RwLock::new(());
84
85 pub struct Env {
86     iter: vec::IntoIter<(OsString, OsString)>,
87 }
88
89 impl !Send for Env {}
90 impl !Sync for Env {}
91
92 impl Iterator for Env {
93     type Item = (OsString, OsString);
94     fn next(&mut self) -> Option<(OsString, OsString)> {
95         self.iter.next()
96     }
97     fn size_hint(&self) -> (usize, Option<usize>) {
98         self.iter.size_hint()
99     }
100 }
101
102 /// Returns a vector of (variable, value) byte-vector pairs for all the
103 /// environment variables of the current process.
104 pub fn env() -> Env {
105     extern "C" {
106         static mut environ: *const *const c_char;
107     }
108
109     unsafe {
110         let _guard = ENV_LOCK.read();
111         let mut result = Vec::new();
112         if !environ.is_null() {
113             while !(*environ).is_null() {
114                 if let Some(key_value) = parse(CStr::from_ptr(*environ).to_bytes()) {
115                     result.push(key_value);
116                 }
117                 environ = environ.add(1);
118             }
119         }
120         return Env { iter: result.into_iter() };
121     }
122
123     fn parse(input: &[u8]) -> Option<(OsString, OsString)> {
124         // Strategy (copied from glibc): Variable name and value are separated
125         // by an ASCII equals sign '='. Since a variable name must not be
126         // empty, allow variable names starting with an equals sign. Skip all
127         // malformed lines.
128         if input.is_empty() {
129             return None;
130         }
131         let pos = memchr::memchr(b'=', &input[1..]).map(|p| p + 1);
132         pos.map(|p| {
133             (
134                 OsStringExt::from_vec(input[..p].to_vec()),
135                 OsStringExt::from_vec(input[p + 1..].to_vec()),
136             )
137         })
138     }
139 }
140
141 pub fn getenv(k: &OsStr) -> Option<OsString> {
142     // environment variables with a nul byte can't be set, so their value is
143     // always None as well
144     let s = run_with_cstr(k.as_bytes(), |k| {
145         let _guard = ENV_LOCK.read();
146         Ok(unsafe { libc::getenv(k.as_ptr()) } as *const libc::c_char)
147     })
148     .ok()?;
149
150     if s.is_null() {
151         None
152     } else {
153         Some(OsStringExt::from_vec(unsafe { CStr::from_ptr(s) }.to_bytes().to_vec()))
154     }
155 }
156
157 pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> {
158     run_with_cstr(k.as_bytes(), |k| {
159         run_with_cstr(v.as_bytes(), |v| {
160             let _guard = ENV_LOCK.write();
161             cvt_env(unsafe { libc::setenv(k.as_ptr(), v.as_ptr(), 1) }).map(drop)
162         })
163     })
164 }
165
166 pub fn unsetenv(n: &OsStr) -> io::Result<()> {
167     run_with_cstr(n.as_bytes(), |nbuf| {
168         let _guard = ENV_LOCK.write();
169         cvt_env(unsafe { libc::unsetenv(nbuf.as_ptr()) }).map(drop)
170     })
171 }
172
173 /// In kmclib, `setenv` and `unsetenv` don't always set `errno`, so this
174 /// function just returns a generic error.
175 fn cvt_env(t: c_int) -> io::Result<c_int> {
176     if t == -1 { Err(io::const_io_error!(io::ErrorKind::Uncategorized, "failure")) } else { Ok(t) }
177 }
178
179 pub fn temp_dir() -> PathBuf {
180     panic!("no standard temporary directory on this platform")
181 }
182
183 pub fn home_dir() -> Option<PathBuf> {
184     None
185 }
186
187 pub fn exit(code: i32) -> ! {
188     rtabort!("exit({}) called", code);
189 }
190
191 pub fn getpid() -> u32 {
192     panic!("no pids on this platform")
193 }