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