1//! Implementation of `std::os` functionality for unix systems
2
3#![allow(unused_imports)] // lots of cfg code here
4
5#[cfg(test)]
6mod tests;
7
8use crate::os::unix::prelude::*;
9
10use crate::error::Error as StdError;
11use crate::ffi::{CStr, CString, OsStr, OsString};
12use crate::fmt;
13use crate::io;
14use crate::iter;
15use crate::mem;
16use crate::path::{self, PathBuf};
17use crate::ptr;
18use crate::slice;
19use crate::str;
20use crate::sync::{PoisonError, RwLock};
21use crate::sys::common::small_c_string::{run_path_with_cstr, run_with_cstr};
22use crate::sys::cvt;
23use crate::sys::fd;
24use crate::sys::memchr;
25use crate::vec;
26
27#[cfg(all(target_env = "gnu", not(target_os = "vxworks")))]
28use crate::sys::weak::weak;
29
30use libc::{c_char, c_int, c_void};
31
32const TMPBUF_SZ: usize = 128;
33
34cfg_if::cfg_if! {
35 if #[cfg(target_os = "redox")] {
36 const PATH_SEPARATOR: u8 = b';';
37 } else {
38 const PATH_SEPARATOR: u8 = b':';
39 }
40}
41
42extern "C" {
43 #[cfg(not(any(target_os = "dragonfly", target_os = "vxworks")))]
44 #[cfg_attr(
45 any(
46 target_os = "linux",
47 target_os = "emscripten",
48 target_os = "fuchsia",
49 target_os = "l4re",
50 target_os = "hurd",
51 ),
52 link_name = "__errno_location"
53 )]
54 #[cfg_attr(
55 any(
56 target_os = "netbsd",
57 target_os = "openbsd",
58 target_os = "android",
59 target_os = "redox",
60 target_env = "newlib"
61 ),
62 link_name = "__errno"
63 )]
64 #[cfg_attr(any(target_os = "solaris", target_os = "illumos"), link_name = "___errno")]
65 #[cfg_attr(target_os = "nto", link_name = "__get_errno_ptr")]
66 #[cfg_attr(
67 any(
68 target_os = "macos",
69 target_os = "ios",
70 target_os = "tvos",
71 target_os = "freebsd",
72 target_os = "watchos"
73 ),
74 link_name = "__error"
75 )]
76 #[cfg_attr(target_os = "haiku", link_name = "_errnop")]
77 #[cfg_attr(target_os = "aix", link_name = "_Errno")]
78 fn errno_location() -> *mut c_int;
79}
80
81/// Returns the platform-specific value of errno
82#[cfg(not(any(target_os = "dragonfly", target_os = "vxworks")))]
83pub fn errno() -> i32 {
84 unsafe { (*errno_location()) as i32 }
85}
86
87/// Sets the platform-specific value of errno
88#[cfg(all(not(target_os = "dragonfly"), not(target_os = "vxworks")))] // needed for readdir and syscall!
89#[allow(dead_code)] // but not all target cfgs actually end up using it
90pub fn set_errno(e: i32) {
91 unsafe { *errno_location() = e as c_int }
92}
93
94#[cfg(target_os = "vxworks")]
95pub fn errno() -> i32 {
96 unsafe { libc::errnoGet() }
97}
98
99#[cfg(target_os = "dragonfly")]
100pub fn errno() -> i32 {
101 extern "C" {
102 #[thread_local]
103 static errno: c_int;
104 }
105
106 unsafe { errno as i32 }
107}
108
109#[cfg(target_os = "dragonfly")]
110#[allow(dead_code)]
111pub fn set_errno(e: i32) {
112 extern "C" {
113 #[thread_local]
114 static mut errno: c_int;
115 }
116
117 unsafe {
118 errno = e;
119 }
120}
121
122/// Gets a detailed string description for the given error number.
123pub fn error_string(errno: i32) -> String {
124 extern "C" {
125 #[cfg_attr(
126 all(
127 any(target_os = "linux", target_os = "hurd", target_env = "newlib"),
128 not(target_env = "ohos")
129 ),
130 link_name = "__xpg_strerror_r"
131 )]
132 fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: libc::size_t) -> c_int;
133 }
134
135 let mut buf = [0 as c_char; TMPBUF_SZ];
136
137 let p = buf.as_mut_ptr();
138 unsafe {
139 if strerror_r(errno as c_int, p, buf.len()) < 0 {
140 panic!("strerror_r failure");
141 }
142
143 let p = p as *const _;
144 // We can't always expect a UTF-8 environment. When we don't get that luxury,
145 // it's better to give a low-quality error message than none at all.
146 String::from_utf8_lossy(CStr::from_ptr(p).to_bytes()).into()
147 }
148}
149
150#[cfg(target_os = "espidf")]
151pub fn getcwd() -> io::Result<PathBuf> {
152 Ok(PathBuf::from("/"))
153}
154
155#[cfg(not(target_os = "espidf"))]
156pub fn getcwd() -> io::Result<PathBuf> {
157 let mut buf = Vec::with_capacity(512);
158 loop {
159 unsafe {
160 let ptr = buf.as_mut_ptr() as *mut libc::c_char;
161 if !libc::getcwd(ptr, buf.capacity()).is_null() {
162 let len = CStr::from_ptr(buf.as_ptr() as *const libc::c_char).to_bytes().len();
163 buf.set_len(len);
164 buf.shrink_to_fit();
165 return Ok(PathBuf::from(OsString::from_vec(buf)));
166 } else {
167 let error = io::Error::last_os_error();
168 if error.raw_os_error() != Some(libc::ERANGE) {
169 return Err(error);
170 }
171 }
172
173 // Trigger the internal buffer resizing logic of `Vec` by requiring
174 // more space than the current capacity.
175 let cap = buf.capacity();
176 buf.set_len(cap);
177 buf.reserve(1);
178 }
179 }
180}
181
182#[cfg(target_os = "espidf")]
183pub fn chdir(_p: &path::Path) -> io::Result<()> {
184 super::unsupported::unsupported()
185}
186
187#[cfg(not(target_os = "espidf"))]
188pub fn chdir(p: &path::Path) -> io::Result<()> {
189 let result: ! = run_path_with_cstr(path:p, |p: &CStr| unsafe { Ok(libc::chdir(p.as_ptr())) })?;
190 if result == 0 { Ok(()) } else { Err(io::Error::last_os_error()) }
191}
192
193pub struct SplitPaths<'a> {
194 iter: iter::Map<slice::Split<'a, u8, fn(&u8) -> bool>, fn(&'a [u8]) -> PathBuf>,
195}
196
197pub fn split_paths(unparsed: &OsStr) -> SplitPaths<'_> {
198 fn bytes_to_path(b: &[u8]) -> PathBuf {
199 PathBuf::from(<OsStr as OsStrExt>::from_bytes(slice:b))
200 }
201 fn is_separator(b: &u8) -> bool {
202 *b == PATH_SEPARATOR
203 }
204 let unparsed: &[u8] = unparsed.as_bytes();
205 SplitPaths {
206 iter: unparsedSplit<'_, u8, fn(&u8) -> …>
207 .split(pred:is_separator as fn(&u8) -> bool)
208 .map(bytes_to_path as fn(&[u8]) -> PathBuf),
209 }
210}
211
212impl<'a> Iterator for SplitPaths<'a> {
213 type Item = PathBuf;
214 fn next(&mut self) -> Option<PathBuf> {
215 self.iter.next()
216 }
217 fn size_hint(&self) -> (usize, Option<usize>) {
218 self.iter.size_hint()
219 }
220}
221
222#[derive(Debug)]
223pub struct JoinPathsError;
224
225pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
226where
227 I: Iterator<Item = T>,
228 T: AsRef<OsStr>,
229{
230 let mut joined: Vec = Vec::new();
231
232 for (i: usize, path: T) in paths.enumerate() {
233 let path: &[u8] = path.as_ref().as_bytes();
234 if i > 0 {
235 joined.push(PATH_SEPARATOR)
236 }
237 if path.contains(&PATH_SEPARATOR) {
238 return Err(JoinPathsError);
239 }
240 joined.extend_from_slice(path);
241 }
242 Ok(OsStringExt::from_vec(joined))
243}
244
245impl fmt::Display for JoinPathsError {
246 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
247 write!(f, "path segment contains separator `{}`", char::from(PATH_SEPARATOR))
248 }
249}
250
251impl StdError for JoinPathsError {
252 #[allow(deprecated)]
253 fn description(&self) -> &str {
254 "failed to join paths"
255 }
256}
257
258#[cfg(target_os = "aix")]
259pub fn current_exe() -> io::Result<PathBuf> {
260 use crate::io::ErrorKind;
261
262 #[cfg(test)]
263 use realstd::env;
264
265 #[cfg(not(test))]
266 use crate::env;
267
268 let exe_path = env::args().next().ok_or(io::const_io_error!(
269 ErrorKind::NotFound,
270 "an executable path was not found because no arguments were provided through argv"
271 ))?;
272 let path = PathBuf::from(exe_path);
273 if path.is_absolute() {
274 return path.canonicalize();
275 }
276 // Search PWD to infer current_exe.
277 if let Some(pstr) = path.to_str()
278 && pstr.contains("/")
279 {
280 return getcwd().map(|cwd| cwd.join(path))?.canonicalize();
281 }
282 // Search PATH to infer current_exe.
283 if let Some(p) = getenv(OsStr::from_bytes("PATH".as_bytes())) {
284 for search_path in split_paths(&p) {
285 let pb = search_path.join(&path);
286 if pb.is_file()
287 && let Ok(metadata) = crate::fs::metadata(&pb)
288 && metadata.permissions().mode() & 0o111 != 0
289 {
290 return pb.canonicalize();
291 }
292 }
293 }
294 Err(io::const_io_error!(ErrorKind::NotFound, "an executable path was not found"))
295}
296
297#[cfg(any(target_os = "freebsd", target_os = "dragonfly"))]
298pub fn current_exe() -> io::Result<PathBuf> {
299 unsafe {
300 let mut mib = [
301 libc::CTL_KERN as c_int,
302 libc::KERN_PROC as c_int,
303 libc::KERN_PROC_PATHNAME as c_int,
304 -1 as c_int,
305 ];
306 let mut sz = 0;
307 cvt(libc::sysctl(
308 mib.as_mut_ptr(),
309 mib.len() as libc::c_uint,
310 ptr::null_mut(),
311 &mut sz,
312 ptr::null_mut(),
313 0,
314 ))?;
315 if sz == 0 {
316 return Err(io::Error::last_os_error());
317 }
318 let mut v: Vec<u8> = Vec::with_capacity(sz);
319 cvt(libc::sysctl(
320 mib.as_mut_ptr(),
321 mib.len() as libc::c_uint,
322 v.as_mut_ptr() as *mut libc::c_void,
323 &mut sz,
324 ptr::null_mut(),
325 0,
326 ))?;
327 if sz == 0 {
328 return Err(io::Error::last_os_error());
329 }
330 v.set_len(sz - 1); // chop off trailing NUL
331 Ok(PathBuf::from(OsString::from_vec(v)))
332 }
333}
334
335#[cfg(target_os = "netbsd")]
336pub fn current_exe() -> io::Result<PathBuf> {
337 fn sysctl() -> io::Result<PathBuf> {
338 unsafe {
339 let mib = [libc::CTL_KERN, libc::KERN_PROC_ARGS, -1, libc::KERN_PROC_PATHNAME];
340 let mut path_len: usize = 0;
341 cvt(libc::sysctl(
342 mib.as_ptr(),
343 mib.len() as libc::c_uint,
344 ptr::null_mut(),
345 &mut path_len,
346 ptr::null(),
347 0,
348 ))?;
349 if path_len <= 1 {
350 return Err(io::const_io_error!(
351 io::ErrorKind::Uncategorized,
352 "KERN_PROC_PATHNAME sysctl returned zero-length string",
353 ));
354 }
355 let mut path: Vec<u8> = Vec::with_capacity(path_len);
356 cvt(libc::sysctl(
357 mib.as_ptr(),
358 mib.len() as libc::c_uint,
359 path.as_ptr() as *mut libc::c_void,
360 &mut path_len,
361 ptr::null(),
362 0,
363 ))?;
364 path.set_len(path_len - 1); // chop off NUL
365 Ok(PathBuf::from(OsString::from_vec(path)))
366 }
367 }
368 fn procfs() -> io::Result<PathBuf> {
369 let curproc_exe = path::Path::new("/proc/curproc/exe");
370 if curproc_exe.is_file() {
371 return crate::fs::read_link(curproc_exe);
372 }
373 Err(io::const_io_error!(
374 io::ErrorKind::Uncategorized,
375 "/proc/curproc/exe doesn't point to regular file.",
376 ))
377 }
378 sysctl().or_else(|_| procfs())
379}
380
381#[cfg(target_os = "openbsd")]
382pub fn current_exe() -> io::Result<PathBuf> {
383 unsafe {
384 let mut mib = [libc::CTL_KERN, libc::KERN_PROC_ARGS, libc::getpid(), libc::KERN_PROC_ARGV];
385 let mib = mib.as_mut_ptr();
386 let mut argv_len = 0;
387 cvt(libc::sysctl(mib, 4, ptr::null_mut(), &mut argv_len, ptr::null_mut(), 0))?;
388 let mut argv = Vec::<*const libc::c_char>::with_capacity(argv_len as usize);
389 cvt(libc::sysctl(mib, 4, argv.as_mut_ptr() as *mut _, &mut argv_len, ptr::null_mut(), 0))?;
390 argv.set_len(argv_len as usize);
391 if argv[0].is_null() {
392 return Err(io::const_io_error!(
393 io::ErrorKind::Uncategorized,
394 "no current exe available",
395 ));
396 }
397 let argv0 = CStr::from_ptr(argv[0]).to_bytes();
398 if argv0[0] == b'.' || argv0.iter().any(|b| *b == b'/') {
399 crate::fs::canonicalize(OsStr::from_bytes(argv0))
400 } else {
401 Ok(PathBuf::from(OsStr::from_bytes(argv0)))
402 }
403 }
404}
405
406#[cfg(any(
407 target_os = "linux",
408 target_os = "hurd",
409 target_os = "android",
410 target_os = "emscripten"
411))]
412pub fn current_exe() -> io::Result<PathBuf> {
413 match crate::fs::read_link(path:"/proc/self/exe") {
414 Err(ref e: &Error) if e.kind() == io::ErrorKind::NotFound => Err(io::const_io_error!(
415 io::ErrorKind::Uncategorized,
416 "no /proc/self/exe available. Is /proc mounted?",
417 )),
418 other: Result => other,
419 }
420}
421
422#[cfg(target_os = "nto")]
423pub fn current_exe() -> io::Result<PathBuf> {
424 let mut e = crate::fs::read("/proc/self/exefile")?;
425 // Current versions of QNX Neutrino provide a null-terminated path.
426 // Ensure the trailing null byte is not returned here.
427 if let Some(0) = e.last() {
428 e.pop();
429 }
430 Ok(PathBuf::from(OsString::from_vec(e)))
431}
432
433#[cfg(any(target_os = "macos", target_os = "ios", target_os = "tvos", target_os = "watchos"))]
434pub fn current_exe() -> io::Result<PathBuf> {
435 unsafe {
436 let mut sz: u32 = 0;
437 libc::_NSGetExecutablePath(ptr::null_mut(), &mut sz);
438 if sz == 0 {
439 return Err(io::Error::last_os_error());
440 }
441 let mut v: Vec<u8> = Vec::with_capacity(sz as usize);
442 let err = libc::_NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz);
443 if err != 0 {
444 return Err(io::Error::last_os_error());
445 }
446 v.set_len(sz as usize - 1); // chop off trailing NUL
447 Ok(PathBuf::from(OsString::from_vec(v)))
448 }
449}
450
451#[cfg(any(target_os = "solaris", target_os = "illumos"))]
452pub fn current_exe() -> io::Result<PathBuf> {
453 if let Ok(path) = crate::fs::read_link("/proc/self/path/a.out") {
454 Ok(path)
455 } else {
456 unsafe {
457 let path = libc::getexecname();
458 if path.is_null() {
459 Err(io::Error::last_os_error())
460 } else {
461 let filename = CStr::from_ptr(path).to_bytes();
462 let path = PathBuf::from(<OsStr as OsStrExt>::from_bytes(filename));
463
464 // Prepend a current working directory to the path if
465 // it doesn't contain an absolute pathname.
466 if filename[0] == b'/' { Ok(path) } else { getcwd().map(|cwd| cwd.join(path)) }
467 }
468 }
469 }
470}
471
472#[cfg(target_os = "haiku")]
473pub fn current_exe() -> io::Result<PathBuf> {
474 unsafe {
475 let mut info: mem::MaybeUninit<libc::image_info> = mem::MaybeUninit::uninit();
476 let mut cookie: i32 = 0;
477 // the executable can be found at team id 0
478 let result = libc::_get_next_image_info(
479 0,
480 &mut cookie,
481 info.as_mut_ptr(),
482 mem::size_of::<libc::image_info>(),
483 );
484 if result != 0 {
485 use crate::io::ErrorKind;
486 Err(io::const_io_error!(ErrorKind::Uncategorized, "Error getting executable path"))
487 } else {
488 let name = CStr::from_ptr((*info.as_ptr()).name.as_ptr()).to_bytes();
489 Ok(PathBuf::from(OsStr::from_bytes(name)))
490 }
491 }
492}
493
494#[cfg(target_os = "redox")]
495pub fn current_exe() -> io::Result<PathBuf> {
496 crate::fs::read_to_string("sys:exe").map(PathBuf::from)
497}
498
499#[cfg(target_os = "l4re")]
500pub fn current_exe() -> io::Result<PathBuf> {
501 use crate::io::ErrorKind;
502 Err(io::const_io_error!(ErrorKind::Unsupported, "Not yet implemented!"))
503}
504
505#[cfg(target_os = "vxworks")]
506pub fn current_exe() -> io::Result<PathBuf> {
507 #[cfg(test)]
508 use realstd::env;
509
510 #[cfg(not(test))]
511 use crate::env;
512
513 let exe_path = env::args().next().unwrap();
514 let path = path::Path::new(&exe_path);
515 path.canonicalize()
516}
517
518#[cfg(any(target_os = "espidf", target_os = "horizon", target_os = "vita"))]
519pub fn current_exe() -> io::Result<PathBuf> {
520 super::unsupported::unsupported()
521}
522
523#[cfg(target_os = "fuchsia")]
524pub fn current_exe() -> io::Result<PathBuf> {
525 use crate::io::ErrorKind;
526
527 #[cfg(test)]
528 use realstd::env;
529
530 #[cfg(not(test))]
531 use crate::env;
532
533 let exe_path = env::args().next().ok_or(io::const_io_error!(
534 ErrorKind::Uncategorized,
535 "an executable path was not found because no arguments were provided through argv"
536 ))?;
537 let path = PathBuf::from(exe_path);
538
539 // Prepend the current working directory to the path if it's not absolute.
540 if !path.is_absolute() { getcwd().map(|cwd| cwd.join(path)) } else { Ok(path) }
541}
542
543pub struct Env {
544 iter: vec::IntoIter<(OsString, OsString)>,
545}
546
547// FIXME(https://github.com/rust-lang/rust/issues/114583): Remove this when <OsStr as Debug>::fmt matches <str as Debug>::fmt.
548pub struct EnvStrDebug<'a> {
549 slice: &'a [(OsString, OsString)],
550}
551
552impl fmt::Debug for EnvStrDebug<'_> {
553 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
554 let Self { slice: &&[(OsString, OsString)] } = self;
555 f&mut DebugList<'_, '_>.debug_list()
556 .entries(slice.iter().map(|(a: &OsString, b: &OsString)| (a.to_str().unwrap(), b.to_str().unwrap())))
557 .finish()
558 }
559}
560
561impl Env {
562 pub fn str_debug(&self) -> impl fmt::Debug + '_ {
563 let Self { iter: &IntoIter<(OsString, OsString)> } = self;
564 EnvStrDebug { slice: iter.as_slice() }
565 }
566}
567
568impl fmt::Debug for Env {
569 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
570 let Self { iter: &IntoIter<(OsString, OsString)> } = self;
571 f.debug_list().entries(iter.as_slice()).finish()
572 }
573}
574
575impl !Send for Env {}
576impl !Sync for Env {}
577
578impl Iterator for Env {
579 type Item = (OsString, OsString);
580 fn next(&mut self) -> Option<(OsString, OsString)> {
581 self.iter.next()
582 }
583 fn size_hint(&self) -> (usize, Option<usize>) {
584 self.iter.size_hint()
585 }
586}
587
588#[cfg(target_os = "macos")]
589pub unsafe fn environ() -> *mut *const *const c_char {
590 libc::_NSGetEnviron() as *mut *const *const c_char
591}
592
593#[cfg(not(target_os = "macos"))]
594pub unsafe fn environ() -> *mut *const *const c_char {
595 extern "C" {
596 static mut environ: *const *const c_char;
597 }
598 ptr::addr_of_mut!(environ)
599}
600
601static ENV_LOCK: RwLock<()> = RwLock::new(());
602
603pub fn env_read_lock() -> impl Drop {
604 ENV_LOCK.read().unwrap_or_else(op:PoisonError::into_inner)
605}
606
607/// Returns a vector of (variable, value) byte-vector pairs for all the
608/// environment variables of the current process.
609pub fn env() -> Env {
610 unsafe {
611 let _guard = env_read_lock();
612 let mut environ = *environ();
613 let mut result = Vec::new();
614 if !environ.is_null() {
615 while !(*environ).is_null() {
616 if let Some(key_value) = parse(CStr::from_ptr(*environ).to_bytes()) {
617 result.push(key_value);
618 }
619 environ = environ.add(1);
620 }
621 }
622 return Env { iter: result.into_iter() };
623 }
624
625 fn parse(input: &[u8]) -> Option<(OsString, OsString)> {
626 // Strategy (copied from glibc): Variable name and value are separated
627 // by an ASCII equals sign '='. Since a variable name must not be
628 // empty, allow variable names starting with an equals sign. Skip all
629 // malformed lines.
630 if input.is_empty() {
631 return None;
632 }
633 let pos = memchr::memchr(b'=', &input[1..]).map(|p| p + 1);
634 pos.map(|p| {
635 (
636 OsStringExt::from_vec(input[..p].to_vec()),
637 OsStringExt::from_vec(input[p + 1..].to_vec()),
638 )
639 })
640 }
641}
642
643pub fn getenv(k: &OsStr) -> Option<OsString> {
644 // environment variables with a nul byte can't be set, so their value is
645 // always None as well
646 run_with_cstrOption>(k.as_bytes(), |k: &CStr| {
647 let _guard: impl Sized = env_read_lock();
648 let v: *const i8 = unsafe { libc::getenv(k.as_ptr()) } as *const libc::c_char;
649
650 if v.is_null() {
651 Ok(None)
652 } else {
653 // SAFETY: `v` cannot be mutated while executing this line since we've a read lock
654 let bytes: Vec = unsafe { CStr::from_ptr(v) }.to_bytes().to_vec();
655
656 Ok(Some(OsStringExt::from_vec(bytes)))
657 }
658 })
659 .ok()
660 .flatten()
661}
662
663pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> {
664 run_with_cstr(k.as_bytes(), |k: &CStr| {
665 run_with_cstr(v.as_bytes(), |v: &CStr| {
666 let _guard: Result, …> = ENV_LOCK.write();
667 cvt(unsafe { libc::setenv(k.as_ptr(), v.as_ptr(), 1) }).map(op:drop)
668 })
669 })
670}
671
672pub fn unsetenv(n: &OsStr) -> io::Result<()> {
673 run_with_cstr(n.as_bytes(), |nbuf: &CStr| {
674 let _guard: Result, …> = ENV_LOCK.write();
675 cvt(unsafe { libc::unsetenv(nbuf.as_ptr()) }).map(op:drop)
676 })
677}
678
679#[cfg(not(target_os = "espidf"))]
680pub fn page_size() -> usize {
681 unsafe { libc::sysconf(libc::_SC_PAGESIZE) as usize }
682}
683
684pub fn temp_dir() -> PathBuf {
685 crate::env::var_os(key:"TMPDIR").map(PathBuf::from).unwrap_or_else(|| {
686 if cfg!(target_os = "android") {
687 PathBuf::from("/data/local/tmp")
688 } else {
689 PathBuf::from("/tmp")
690 }
691 })
692}
693
694pub fn home_dir() -> Option<PathBuf> {
695 return crate::env::var_os("HOME").or_else(|| unsafe { fallback() }).map(PathBuf::from);
696
697 #[cfg(any(
698 target_os = "android",
699 target_os = "ios",
700 target_os = "tvos",
701 target_os = "watchos",
702 target_os = "emscripten",
703 target_os = "redox",
704 target_os = "vxworks",
705 target_os = "espidf",
706 target_os = "horizon",
707 target_os = "vita",
708 ))]
709 unsafe fn fallback() -> Option<OsString> {
710 None
711 }
712 #[cfg(not(any(
713 target_os = "android",
714 target_os = "ios",
715 target_os = "tvos",
716 target_os = "watchos",
717 target_os = "emscripten",
718 target_os = "redox",
719 target_os = "vxworks",
720 target_os = "espidf",
721 target_os = "horizon",
722 target_os = "vita",
723 )))]
724 unsafe fn fallback() -> Option<OsString> {
725 let amt = match libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) {
726 n if n < 0 => 512 as usize,
727 n => n as usize,
728 };
729 let mut buf = Vec::with_capacity(amt);
730 let mut passwd: libc::passwd = mem::zeroed();
731 let mut result = ptr::null_mut();
732 match libc::getpwuid_r(
733 libc::getuid(),
734 &mut passwd,
735 buf.as_mut_ptr(),
736 buf.capacity(),
737 &mut result,
738 ) {
739 0 if !result.is_null() => {
740 let ptr = passwd.pw_dir as *const _;
741 let bytes = CStr::from_ptr(ptr).to_bytes().to_vec();
742 Some(OsStringExt::from_vec(bytes))
743 }
744 _ => None,
745 }
746 }
747}
748
749pub fn exit(code: i32) -> ! {
750 unsafe { libc::exit(code as c_int) }
751}
752
753pub fn getpid() -> u32 {
754 unsafe { libc::getpid() as u32 }
755}
756
757pub fn getppid() -> u32 {
758 unsafe { libc::getppid() as u32 }
759}
760
761#[cfg(all(target_os = "linux", target_env = "gnu"))]
762pub fn glibc_version() -> Option<(usize, usize)> {
763 extern "C" {
764 fn gnu_get_libc_version() -> *const libc::c_char;
765 }
766 let version_cstr: &CStr = unsafe { CStr::from_ptr(gnu_get_libc_version()) };
767 if let Ok(version_str: &str) = version_cstr.to_str() {
768 parse_glibc_version(version_str)
769 } else {
770 None
771 }
772}
773
774// Returns Some((major, minor)) if the string is a valid "x.y" version,
775// ignoring any extra dot-separated parts. Otherwise return None.
776#[cfg(all(target_os = "linux", target_env = "gnu"))]
777fn parse_glibc_version(version: &str) -> Option<(usize, usize)> {
778 let mut parsed_ints: impl Iterator> = version.split('.').map(str::parse::<usize>).fuse();
779 match (parsed_ints.next(), parsed_ints.next()) {
780 (Some(Ok(major: usize)), Some(Ok(minor: usize))) => Some((major, minor)),
781 _ => None,
782 }
783}
784