1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Implementation of `std::os` functionality for unix systems
13 #![allow(unused_imports)] // lots of cfg code here
15 use os::unix::prelude::*;
17 use error::Error as StdError;
18 use ffi::{CString, CStr, OsString, OsStr};
22 use libc::{self, c_int, c_char, c_void};
23 use marker::PhantomData;
26 use path::{self, PathBuf};
30 use sys_common::mutex::Mutex;
35 const TMPBUF_SZ: usize = 128;
36 // We never call `ENV_LOCK.init()`, so it is UB to attempt to
37 // acquire this mutex reentrantly!
38 static ENV_LOCK: Mutex = Mutex::new();
42 #[cfg(not(target_os = "dragonfly"))]
43 #[cfg_attr(any(target_os = "linux",
44 target_os = "emscripten",
45 target_os = "fuchsia",
47 link_name = "__errno_location")]
48 #[cfg_attr(any(target_os = "bitrig",
50 target_os = "openbsd",
51 target_os = "android",
53 target_env = "newlib"),
54 link_name = "__errno")]
55 #[cfg_attr(target_os = "solaris", link_name = "___errno")]
56 #[cfg_attr(any(target_os = "macos",
58 target_os = "freebsd"),
59 link_name = "__error")]
60 #[cfg_attr(target_os = "haiku", link_name = "_errnop")]
61 fn errno_location() -> *mut c_int;
64 /// Returns the platform-specific value of errno
65 #[cfg(not(target_os = "dragonfly"))]
66 pub fn errno() -> i32 {
68 (*errno_location()) as i32
72 /// Sets the platform-specific value of errno
73 #[cfg(any(target_os = "solaris", target_os = "fuchsia"))] // only needed for readdir so far
74 pub fn set_errno(e: i32) {
76 *errno_location() = e as c_int
80 #[cfg(target_os = "dragonfly")]
81 pub fn errno() -> i32 {
87 unsafe { errno as i32 }
90 /// Gets a detailed string description for the given error number.
91 pub fn error_string(errno: i32) -> String {
93 #[cfg_attr(any(target_os = "linux", target_env = "newlib"),
94 link_name = "__xpg_strerror_r")]
95 fn strerror_r(errnum: c_int, buf: *mut c_char,
96 buflen: libc::size_t) -> c_int;
99 let mut buf = [0 as c_char; TMPBUF_SZ];
101 let p = buf.as_mut_ptr();
103 if strerror_r(errno as c_int, p, buf.len()) < 0 {
104 panic!("strerror_r failure");
107 let p = p as *const _;
108 str::from_utf8(CStr::from_ptr(p).to_bytes()).unwrap().to_owned()
112 pub fn getcwd() -> io::Result<PathBuf> {
113 let mut buf = Vec::with_capacity(512);
116 let ptr = buf.as_mut_ptr() as *mut libc::c_char;
117 if !libc::getcwd(ptr, buf.capacity()).is_null() {
118 let len = CStr::from_ptr(buf.as_ptr() as *const libc::c_char).to_bytes().len();
121 return Ok(PathBuf::from(OsString::from_vec(buf)));
123 let error = io::Error::last_os_error();
124 if error.raw_os_error() != Some(libc::ERANGE) {
129 // Trigger the internal buffer resizing logic of `Vec` by requiring
130 // more space than the current capacity.
131 let cap = buf.capacity();
138 pub fn chdir(p: &path::Path) -> io::Result<()> {
139 let p: &OsStr = p.as_ref();
140 let p = CString::new(p.as_bytes())?;
142 match libc::chdir(p.as_ptr()) == (0 as c_int) {
144 false => Err(io::Error::last_os_error()),
149 pub struct SplitPaths<'a> {
150 iter: iter::Map<slice::Split<'a, u8, fn(&u8) -> bool>,
151 fn(&'a [u8]) -> PathBuf>,
154 pub fn split_paths(unparsed: &OsStr) -> SplitPaths {
155 fn bytes_to_path(b: &[u8]) -> PathBuf {
156 PathBuf::from(<OsStr as OsStrExt>::from_bytes(b))
158 fn is_colon(b: &u8) -> bool { *b == b':' }
159 let unparsed = unparsed.as_bytes();
161 iter: unparsed.split(is_colon as fn(&u8) -> bool)
162 .map(bytes_to_path as fn(&[u8]) -> PathBuf)
166 impl<'a> Iterator for SplitPaths<'a> {
168 fn next(&mut self) -> Option<PathBuf> { self.iter.next() }
169 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
173 pub struct JoinPathsError;
175 pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
176 where I: Iterator<Item=T>, T: AsRef<OsStr>
178 let mut joined = Vec::new();
181 for (i, path) in paths.enumerate() {
182 let path = path.as_ref().as_bytes();
183 if i > 0 { joined.push(sep) }
184 if path.contains(&sep) {
185 return Err(JoinPathsError)
187 joined.extend_from_slice(path);
189 Ok(OsStringExt::from_vec(joined))
192 impl fmt::Display for JoinPathsError {
193 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
194 "path segment contains separator `:`".fmt(f)
198 impl StdError for JoinPathsError {
199 fn description(&self) -> &str { "failed to join paths" }
202 #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))]
203 pub fn current_exe() -> io::Result<PathBuf> {
205 let mut mib = [libc::CTL_KERN as c_int,
206 libc::KERN_PROC as c_int,
207 libc::KERN_PROC_PATHNAME as c_int,
210 cvt(libc::sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
211 ptr::null_mut(), &mut sz, ptr::null_mut(), 0))?;
213 return Err(io::Error::last_os_error())
215 let mut v: Vec<u8> = Vec::with_capacity(sz);
216 cvt(libc::sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
217 v.as_mut_ptr() as *mut libc::c_void, &mut sz,
218 ptr::null_mut(), 0))?;
220 return Err(io::Error::last_os_error());
222 v.set_len(sz - 1); // chop off trailing NUL
223 Ok(PathBuf::from(OsString::from_vec(v)))
227 #[cfg(target_os = "netbsd")]
228 pub fn current_exe() -> io::Result<PathBuf> {
229 fn sysctl() -> io::Result<PathBuf> {
231 let mib = [libc::CTL_KERN, libc::KERN_PROC_ARGS, -1, libc::KERN_PROC_PATHNAME];
232 let mut path_len: usize = 0;
233 cvt(libc::sysctl(mib.as_ptr(), mib.len() as ::libc::c_uint,
234 ptr::null_mut(), &mut path_len,
237 return Err(io::Error::new(io::ErrorKind::Other,
238 "KERN_PROC_PATHNAME sysctl returned zero-length string"))
240 let mut path: Vec<u8> = Vec::with_capacity(path_len);
241 cvt(libc::sysctl(mib.as_ptr(), mib.len() as ::libc::c_uint,
242 path.as_ptr() as *mut libc::c_void, &mut path_len,
244 path.set_len(path_len - 1); // chop off NUL
245 Ok(PathBuf::from(OsString::from_vec(path)))
248 fn procfs() -> io::Result<PathBuf> {
249 let curproc_exe = path::Path::new("/proc/curproc/exe");
250 if curproc_exe.is_file() {
251 return ::fs::read_link(curproc_exe);
253 Err(io::Error::new(io::ErrorKind::Other,
254 "/proc/curproc/exe doesn't point to regular file."))
256 sysctl().or_else(|_| procfs())
259 #[cfg(any(target_os = "bitrig", target_os = "openbsd"))]
260 pub fn current_exe() -> io::Result<PathBuf> {
262 let mut mib = [libc::CTL_KERN,
263 libc::KERN_PROC_ARGS,
265 libc::KERN_PROC_ARGV];
266 let mib = mib.as_mut_ptr();
267 let mut argv_len = 0;
268 cvt(libc::sysctl(mib, 4, ptr::null_mut(), &mut argv_len,
269 ptr::null_mut(), 0))?;
270 let mut argv = Vec::<*const libc::c_char>::with_capacity(argv_len as usize);
271 cvt(libc::sysctl(mib, 4, argv.as_mut_ptr() as *mut _,
272 &mut argv_len, ptr::null_mut(), 0))?;
273 argv.set_len(argv_len as usize);
274 if argv[0].is_null() {
275 return Err(io::Error::new(io::ErrorKind::Other,
276 "no current exe available"))
278 let argv0 = CStr::from_ptr(argv[0]).to_bytes();
279 if argv0[0] == b'.' || argv0.iter().any(|b| *b == b'/') {
280 ::fs::canonicalize(OsStr::from_bytes(argv0))
282 Ok(PathBuf::from(OsStr::from_bytes(argv0)))
287 #[cfg(any(target_os = "linux", target_os = "android", target_os = "emscripten"))]
288 pub fn current_exe() -> io::Result<PathBuf> {
289 let selfexe = PathBuf::from("/proc/self/exe");
290 if selfexe.exists() {
291 ::fs::read_link(selfexe)
293 Err(io::Error::new(io::ErrorKind::Other, "no /proc/self/exe available. Is /proc mounted?"))
297 #[cfg(any(target_os = "macos", target_os = "ios"))]
298 pub fn current_exe() -> io::Result<PathBuf> {
300 fn _NSGetExecutablePath(buf: *mut libc::c_char,
301 bufsize: *mut u32) -> libc::c_int;
305 _NSGetExecutablePath(ptr::null_mut(), &mut sz);
306 if sz == 0 { return Err(io::Error::last_os_error()); }
307 let mut v: Vec<u8> = Vec::with_capacity(sz as usize);
308 let err = _NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz);
309 if err != 0 { return Err(io::Error::last_os_error()); }
310 v.set_len(sz as usize - 1); // chop off trailing NUL
311 Ok(PathBuf::from(OsString::from_vec(v)))
315 #[cfg(any(target_os = "solaris"))]
316 pub fn current_exe() -> io::Result<PathBuf> {
318 fn getexecname() -> *const c_char;
321 let path = getexecname();
323 Err(io::Error::last_os_error())
325 let filename = CStr::from_ptr(path).to_bytes();
326 let path = PathBuf::from(<OsStr as OsStrExt>::from_bytes(filename));
328 // Prepend a current working directory to the path if
329 // it doesn't contain an absolute pathname.
330 if filename[0] == b'/' {
333 getcwd().map(|cwd| cwd.join(path))
339 #[cfg(target_os = "haiku")]
340 pub fn current_exe() -> io::Result<PathBuf> {
341 // Use Haiku's image info functions
348 init_routine: *mut libc::c_void, // function pointer
349 term_routine: *mut libc::c_void, // function pointer
352 name: [libc::c_char; 1024], // MAXPATHLEN
353 text: *mut libc::c_void,
354 data: *mut libc::c_void,
363 fn _get_next_image_info(team_id: i32, cookie: *mut i32,
364 info: *mut image_info, size: i32) -> i32;
367 let mut info: image_info = mem::zeroed();
368 let mut cookie: i32 = 0;
369 // the executable can be found at team id 0
370 let result = _get_next_image_info(0, &mut cookie, &mut info,
371 mem::size_of::<image_info>() as i32);
374 Err(io::Error::new(ErrorKind::Other, "Error getting executable path"))
376 let name = CStr::from_ptr(info.name.as_ptr()).to_bytes();
377 Ok(PathBuf::from(OsStr::from_bytes(name)))
382 #[cfg(any(target_os = "fuchsia", target_os = "l4re", target_os = "hermit"))]
383 pub fn current_exe() -> io::Result<PathBuf> {
385 Err(io::Error::new(ErrorKind::Other, "Not yet implemented!"))
389 iter: vec::IntoIter<(OsString, OsString)>,
390 _dont_send_or_sync_me: PhantomData<*mut ()>,
393 impl Iterator for Env {
394 type Item = (OsString, OsString);
395 fn next(&mut self) -> Option<(OsString, OsString)> { self.iter.next() }
396 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
399 #[cfg(target_os = "macos")]
400 pub unsafe fn environ() -> *mut *const *const c_char {
401 extern { fn _NSGetEnviron() -> *mut *const *const c_char; }
405 #[cfg(not(target_os = "macos"))]
406 pub unsafe fn environ() -> *mut *const *const c_char {
407 extern { static mut environ: *const *const c_char; }
411 /// Returns a vector of (variable, value) byte-vector pairs for all the
412 /// environment variables of the current process.
413 pub fn env() -> Env {
415 let _guard = ENV_LOCK.lock();
416 let mut environ = *environ();
417 let mut result = Vec::new();
418 while environ != ptr::null() && *environ != ptr::null() {
419 if let Some(key_value) = parse(CStr::from_ptr(*environ).to_bytes()) {
420 result.push(key_value);
422 environ = environ.offset(1);
425 iter: result.into_iter(),
426 _dont_send_or_sync_me: PhantomData,
430 fn parse(input: &[u8]) -> Option<(OsString, OsString)> {
431 // Strategy (copied from glibc): Variable name and value are separated
432 // by an ASCII equals sign '='. Since a variable name must not be
433 // empty, allow variable names starting with an equals sign. Skip all
435 if input.is_empty() {
438 let pos = memchr::memchr(b'=', &input[1..]).map(|p| p + 1);
440 OsStringExt::from_vec(input[..p].to_vec()),
441 OsStringExt::from_vec(input[p+1..].to_vec()),
446 pub fn getenv(k: &OsStr) -> io::Result<Option<OsString>> {
447 // environment variables with a nul byte can't be set, so their value is
448 // always None as well
449 let k = CString::new(k.as_bytes())?;
451 let _guard = ENV_LOCK.lock();
452 let s = libc::getenv(k.as_ptr()) as *const libc::c_char;
453 let ret = if s.is_null() {
456 Some(OsStringExt::from_vec(CStr::from_ptr(s).to_bytes().to_vec()))
462 pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> {
463 let k = CString::new(k.as_bytes())?;
464 let v = CString::new(v.as_bytes())?;
467 let _guard = ENV_LOCK.lock();
468 cvt(libc::setenv(k.as_ptr(), v.as_ptr(), 1)).map(|_| ())
472 pub fn unsetenv(n: &OsStr) -> io::Result<()> {
473 let nbuf = CString::new(n.as_bytes())?;
476 let _guard = ENV_LOCK.lock();
477 cvt(libc::unsetenv(nbuf.as_ptr())).map(|_| ())
481 pub fn page_size() -> usize {
483 libc::sysconf(libc::_SC_PAGESIZE) as usize
487 pub fn temp_dir() -> PathBuf {
488 ::env::var_os("TMPDIR").map(PathBuf::from).unwrap_or_else(|| {
489 if cfg!(target_os = "android") {
490 PathBuf::from("/data/local/tmp")
492 PathBuf::from("/tmp")
497 pub fn home_dir() -> Option<PathBuf> {
498 return ::env::var_os("HOME").or_else(|| unsafe {
500 }).map(PathBuf::from);
502 #[cfg(any(target_os = "android",
504 target_os = "emscripten"))]
505 unsafe fn fallback() -> Option<OsString> { None }
506 #[cfg(not(any(target_os = "android",
508 target_os = "emscripten")))]
509 unsafe fn fallback() -> Option<OsString> {
510 let amt = match libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) {
511 n if n < 0 => 512 as usize,
514 let mut buf = Vec::with_capacity(amt);
515 let mut passwd: libc::passwd = mem::zeroed();
516 let mut result = ptr::null_mut();
517 match libc::getpwuid_r(libc::getuid(), &mut passwd, buf.as_mut_ptr(),
518 buf.capacity(), &mut result) {
519 0 if !result.is_null() => {
520 let ptr = passwd.pw_dir as *const _;
521 let bytes = CStr::from_ptr(ptr).to_bytes().to_vec();
522 Some(OsStringExt::from_vec(bytes))
529 pub fn exit(code: i32) -> ! {
530 unsafe { libc::exit(code as c_int) }
533 pub fn getpid() -> u32 {
534 unsafe { libc::getpid() as u32 }
537 pub fn getppid() -> u32 {
538 unsafe { libc::getppid() as u32 }
541 #[cfg(target_env = "gnu")]
542 pub fn glibc_version() -> Option<(usize, usize)> {
543 if let Some(Ok(version_str)) = glibc_version_cstr().map(CStr::to_str) {
544 parse_glibc_version(version_str)
550 #[cfg(target_env = "gnu")]
551 fn glibc_version_cstr() -> Option<&'static CStr> {
553 fn gnu_get_libc_version() -> *const libc::c_char
555 if let Some(f) = gnu_get_libc_version.get() {
556 unsafe { Some(CStr::from_ptr(f())) }
562 // Returns Some((major, minor)) if the string is a valid "x.y" version,
563 // ignoring any extra dot-separated parts. Otherwise return None.
564 #[cfg(target_env = "gnu")]
565 fn parse_glibc_version(version: &str) -> Option<(usize, usize)> {
566 let mut parsed_ints = version.split('.').map(str::parse::<usize>).fuse();
567 match (parsed_ints.next(), parsed_ints.next()) {
568 (Some(Ok(major)), Some(Ok(minor))) => Some((major, minor)),
573 #[cfg(all(test, target_env = "gnu"))]
578 fn test_glibc_version() {
579 // This mostly just tests that the weak linkage doesn't panic wildly...
584 fn test_parse_glibc_version() {
586 ("0.0", Some((0, 0))),
587 ("01.+2", Some((1, 2))),
588 ("3.4.5.six", Some((3, 4))),
594 for &(version_str, parsed) in cases.iter() {
595 assert_eq!(parsed, parse_glibc_version(version_str));