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