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 static ENV_LOCK: Mutex = Mutex::new();
40 #[cfg(not(target_os = "dragonfly"))]
41 #[cfg_attr(any(target_os = "linux", target_os = "emscripten"),
42 link_name = "__errno_location")]
43 #[cfg_attr(any(target_os = "bitrig",
45 target_os = "openbsd",
46 target_os = "android",
47 target_env = "newlib"),
48 link_name = "__errno")]
49 #[cfg_attr(target_os = "solaris", link_name = "___errno")]
50 #[cfg_attr(any(target_os = "macos",
52 target_os = "freebsd"),
53 link_name = "__error")]
54 #[cfg_attr(target_os = "haiku", link_name = "_errnop")]
55 fn errno_location() -> *mut c_int;
58 /// Returns the platform-specific value of errno
59 #[cfg(not(target_os = "dragonfly"))]
60 pub fn errno() -> i32 {
62 (*errno_location()) as i32
66 /// Sets the platform-specific value of errno
67 #[cfg(target_os = "solaris")] // only needed for readdir so far
68 pub fn set_errno(e: i32) {
70 *errno_location() = e as c_int
74 #[cfg(target_os = "dragonfly")]
75 pub fn errno() -> i32 {
84 /// Gets a detailed string description for the given error number.
85 pub fn error_string(errno: i32) -> String {
87 #[cfg_attr(any(target_os = "linux", target_env = "newlib"),
88 link_name = "__xpg_strerror_r")]
89 fn strerror_r(errnum: c_int, buf: *mut c_char,
90 buflen: libc::size_t) -> c_int;
93 let mut buf = [0 as c_char; TMPBUF_SZ];
95 let p = buf.as_mut_ptr();
97 if strerror_r(errno as c_int, p, buf.len() as libc::size_t) < 0 {
98 panic!("strerror_r failure");
101 let p = p as *const _;
102 str::from_utf8(CStr::from_ptr(p).to_bytes()).unwrap().to_owned()
106 pub fn getcwd() -> io::Result<PathBuf> {
107 let mut buf = Vec::with_capacity(512);
110 let ptr = buf.as_mut_ptr() as *mut libc::c_char;
111 if !libc::getcwd(ptr, buf.capacity() as libc::size_t).is_null() {
112 let len = CStr::from_ptr(buf.as_ptr() as *const libc::c_char).to_bytes().len();
115 return Ok(PathBuf::from(OsString::from_vec(buf)));
117 let error = io::Error::last_os_error();
118 if error.raw_os_error() != Some(libc::ERANGE) {
123 // Trigger the internal buffer resizing logic of `Vec` by requiring
124 // more space than the current capacity.
125 let cap = buf.capacity();
132 pub fn chdir(p: &path::Path) -> io::Result<()> {
133 let p: &OsStr = p.as_ref();
134 let p = CString::new(p.as_bytes())?;
136 match libc::chdir(p.as_ptr()) == (0 as c_int) {
138 false => Err(io::Error::last_os_error()),
143 pub struct SplitPaths<'a> {
144 iter: iter::Map<slice::Split<'a, u8, fn(&u8) -> bool>,
145 fn(&'a [u8]) -> PathBuf>,
148 pub fn split_paths(unparsed: &OsStr) -> SplitPaths {
149 fn bytes_to_path(b: &[u8]) -> PathBuf {
150 PathBuf::from(<OsStr as OsStrExt>::from_bytes(b))
152 fn is_colon(b: &u8) -> bool { *b == b':' }
153 let unparsed = unparsed.as_bytes();
155 iter: unparsed.split(is_colon as fn(&u8) -> bool)
156 .map(bytes_to_path as fn(&[u8]) -> PathBuf)
160 impl<'a> Iterator for SplitPaths<'a> {
162 fn next(&mut self) -> Option<PathBuf> { self.iter.next() }
163 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
167 pub struct JoinPathsError;
169 pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
170 where I: Iterator<Item=T>, T: AsRef<OsStr>
172 let mut joined = Vec::new();
175 for (i, path) in paths.enumerate() {
176 let path = path.as_ref().as_bytes();
177 if i > 0 { joined.push(sep) }
178 if path.contains(&sep) {
179 return Err(JoinPathsError)
181 joined.extend_from_slice(path);
183 Ok(OsStringExt::from_vec(joined))
186 impl fmt::Display for JoinPathsError {
187 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
188 "path segment contains separator `:`".fmt(f)
192 impl StdError for JoinPathsError {
193 fn description(&self) -> &str { "failed to join paths" }
196 #[cfg(target_os = "freebsd")]
197 pub fn current_exe() -> io::Result<PathBuf> {
199 let mut mib = [libc::CTL_KERN as c_int,
200 libc::KERN_PROC as c_int,
201 libc::KERN_PROC_PATHNAME as c_int,
203 let mut sz: libc::size_t = 0;
204 cvt(libc::sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
205 ptr::null_mut(), &mut sz, ptr::null_mut(),
206 0 as libc::size_t))?;
208 return Err(io::Error::last_os_error())
210 let mut v: Vec<u8> = Vec::with_capacity(sz as usize);
211 cvt(libc::sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
212 v.as_mut_ptr() as *mut libc::c_void, &mut sz,
213 ptr::null_mut(), 0 as libc::size_t))?;
215 return Err(io::Error::last_os_error());
217 v.set_len(sz as usize - 1); // chop off trailing NUL
218 Ok(PathBuf::from(OsString::from_vec(v)))
222 #[cfg(target_os = "dragonfly")]
223 pub fn current_exe() -> io::Result<PathBuf> {
224 ::fs::read_link("/proc/curproc/file")
227 #[cfg(target_os = "netbsd")]
228 pub fn current_exe() -> io::Result<PathBuf> {
229 ::fs::read_link("/proc/curproc/exe")
232 #[cfg(any(target_os = "bitrig", target_os = "openbsd"))]
233 pub fn current_exe() -> io::Result<PathBuf> {
235 let mut mib = [libc::CTL_KERN,
236 libc::KERN_PROC_ARGS,
238 libc::KERN_PROC_ARGV];
239 let mib = mib.as_mut_ptr();
240 let mut argv_len = 0;
241 cvt(libc::sysctl(mib, 4, ptr::null_mut(), &mut argv_len,
242 ptr::null_mut(), 0))?;
243 let mut argv = Vec::<*const libc::c_char>::with_capacity(argv_len as usize);
244 cvt(libc::sysctl(mib, 4, argv.as_mut_ptr() as *mut _,
245 &mut argv_len, ptr::null_mut(), 0))?;
246 argv.set_len(argv_len as usize);
247 if argv[0].is_null() {
248 return Err(io::Error::new(io::ErrorKind::Other,
249 "no current exe available"))
251 let argv0 = CStr::from_ptr(argv[0]).to_bytes();
252 if argv0[0] == b'.' || argv0.iter().any(|b| *b == b'/') {
253 ::fs::canonicalize(OsStr::from_bytes(argv0))
255 Ok(PathBuf::from(OsStr::from_bytes(argv0)))
260 #[cfg(any(target_os = "linux", target_os = "android", target_os = "emscripten"))]
261 pub fn current_exe() -> io::Result<PathBuf> {
262 ::fs::read_link("/proc/self/exe")
265 #[cfg(any(target_os = "macos", target_os = "ios"))]
266 pub fn current_exe() -> io::Result<PathBuf> {
268 fn _NSGetExecutablePath(buf: *mut libc::c_char,
269 bufsize: *mut u32) -> libc::c_int;
273 _NSGetExecutablePath(ptr::null_mut(), &mut sz);
274 if sz == 0 { return Err(io::Error::last_os_error()); }
275 let mut v: Vec<u8> = Vec::with_capacity(sz as usize);
276 let err = _NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz);
277 if err != 0 { return Err(io::Error::last_os_error()); }
278 v.set_len(sz as usize - 1); // chop off trailing NUL
279 Ok(PathBuf::from(OsString::from_vec(v)))
283 #[cfg(any(target_os = "solaris"))]
284 pub fn current_exe() -> io::Result<PathBuf> {
286 fn getexecname() -> *const c_char;
289 let path = getexecname();
291 Err(io::Error::last_os_error())
293 let filename = CStr::from_ptr(path).to_bytes();
294 let path = PathBuf::from(<OsStr as OsStrExt>::from_bytes(filename));
296 // Prepend a current working directory to the path if
297 // it doesn't contain an absolute pathname.
298 if filename[0] == b'/' {
301 getcwd().map(|cwd| cwd.join(path))
307 #[cfg(target_os = "haiku")]
308 pub fn current_exe() -> io::Result<PathBuf> {
309 // Use Haiku's image info functions
316 init_routine: *mut libc::c_void, // function pointer
317 term_routine: *mut libc::c_void, // function pointer
320 name: [libc::c_char; 1024], // MAXPATHLEN
321 text: *mut libc::c_void,
322 data: *mut libc::c_void,
331 fn _get_next_image_info(team_id: i32, cookie: *mut i32,
332 info: *mut image_info, size: i32) -> i32;
335 let mut info: image_info = mem::zeroed();
336 let mut cookie: i32 = 0;
337 // the executable can be found at team id 0
338 let result = _get_next_image_info(0, &mut cookie, &mut info,
339 mem::size_of::<image_info>() as i32);
342 Err(io::Error::new(ErrorKind::Other, "Error getting executable path"))
344 let name = CStr::from_ptr(info.name.as_ptr()).to_bytes();
345 Ok(PathBuf::from(OsStr::from_bytes(name)))
351 iter: vec::IntoIter<OsString>,
352 _dont_send_or_sync_me: PhantomData<*mut ()>,
355 impl Iterator for Args {
356 type Item = OsString;
357 fn next(&mut self) -> Option<OsString> { self.iter.next() }
358 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
361 impl ExactSizeIterator for Args {
362 fn len(&self) -> usize { self.iter.len() }
365 impl DoubleEndedIterator for Args {
366 fn next_back(&mut self) -> Option<OsString> { self.iter.next_back() }
369 /// Returns the command line arguments
371 /// Returns a list of the command line arguments.
372 #[cfg(target_os = "macos")]
373 pub fn args() -> Args {
375 // These functions are in crt_externs.h.
376 fn _NSGetArgc() -> *mut c_int;
377 fn _NSGetArgv() -> *mut *mut *mut c_char;
381 let (argc, argv) = (*_NSGetArgc() as isize,
382 *_NSGetArgv() as *const *const c_char);
383 (0.. argc as isize).map(|i| {
384 let bytes = CStr::from_ptr(*argv.offset(i)).to_bytes().to_vec();
385 OsStringExt::from_vec(bytes)
386 }).collect::<Vec<_>>()
389 iter: vec.into_iter(),
390 _dont_send_or_sync_me: PhantomData,
394 // As _NSGetArgc and _NSGetArgv aren't mentioned in iOS docs
395 // and use underscores in their names - they're most probably
396 // are considered private and therefore should be avoided
397 // Here is another way to get arguments using Objective C
400 // In general it looks like:
402 // let args = [[NSProcessInfo processInfo] arguments]
403 // for i in (0..[args count])
404 // res.push([args objectAtIndex:i])
406 #[cfg(target_os = "ios")]
407 pub fn args() -> Args {
411 fn sel_registerName(name: *const libc::c_uchar) -> Sel;
412 fn objc_msgSend(obj: NsId, sel: Sel, ...) -> NsId;
413 fn objc_getClass(class_name: *const libc::c_uchar) -> NsId;
416 #[link(name = "Foundation", kind = "framework")]
417 #[link(name = "objc")]
418 #[cfg(not(cargobuild))]
421 type Sel = *const libc::c_void;
422 type NsId = *const libc::c_void;
424 let mut res = Vec::new();
427 let process_info_sel = sel_registerName("processInfo\0".as_ptr());
428 let arguments_sel = sel_registerName("arguments\0".as_ptr());
429 let utf8_sel = sel_registerName("UTF8String\0".as_ptr());
430 let count_sel = sel_registerName("count\0".as_ptr());
431 let object_at_sel = sel_registerName("objectAtIndex:\0".as_ptr());
433 let klass = objc_getClass("NSProcessInfo\0".as_ptr());
434 let info = objc_msgSend(klass, process_info_sel);
435 let args = objc_msgSend(info, arguments_sel);
437 let cnt: usize = mem::transmute(objc_msgSend(args, count_sel));
439 let tmp = objc_msgSend(args, object_at_sel, i);
440 let utf_c_str: *const libc::c_char =
441 mem::transmute(objc_msgSend(tmp, utf8_sel));
442 let bytes = CStr::from_ptr(utf_c_str).to_bytes();
443 res.push(OsString::from(str::from_utf8(bytes).unwrap()))
447 Args { iter: res.into_iter(), _dont_send_or_sync_me: PhantomData }
450 #[cfg(any(target_os = "linux",
451 target_os = "android",
452 target_os = "freebsd",
453 target_os = "dragonfly",
454 target_os = "bitrig",
455 target_os = "netbsd",
456 target_os = "openbsd",
457 target_os = "solaris",
459 target_os = "emscripten",
460 target_os = "haiku"))]
461 pub fn args() -> Args {
463 let bytes = sys_common::args::clone().unwrap_or(Vec::new());
464 let v: Vec<OsString> = bytes.into_iter().map(|v| {
465 OsStringExt::from_vec(v)
467 Args { iter: v.into_iter(), _dont_send_or_sync_me: PhantomData }
471 iter: vec::IntoIter<(OsString, OsString)>,
472 _dont_send_or_sync_me: PhantomData<*mut ()>,
475 impl Iterator for Env {
476 type Item = (OsString, OsString);
477 fn next(&mut self) -> Option<(OsString, OsString)> { self.iter.next() }
478 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
481 #[cfg(target_os = "macos")]
482 pub unsafe fn environ() -> *mut *const *const c_char {
483 extern { fn _NSGetEnviron() -> *mut *const *const c_char; }
487 #[cfg(not(target_os = "macos"))]
488 pub unsafe fn environ() -> *mut *const *const c_char {
489 extern { static mut environ: *const *const c_char; }
493 /// Returns a vector of (variable, value) byte-vector pairs for all the
494 /// environment variables of the current process.
495 pub fn env() -> Env {
498 let mut environ = *environ();
499 if environ == ptr::null() {
501 panic!("os::env() failure getting env string from OS: {}",
502 io::Error::last_os_error());
504 let mut result = Vec::new();
505 while *environ != ptr::null() {
506 if let Some(key_value) = parse(CStr::from_ptr(*environ).to_bytes()) {
507 result.push(key_value);
509 environ = environ.offset(1);
512 iter: result.into_iter(),
513 _dont_send_or_sync_me: PhantomData,
519 fn parse(input: &[u8]) -> Option<(OsString, OsString)> {
520 // Strategy (copied from glibc): Variable name and value are separated
521 // by an ASCII equals sign '='. Since a variable name must not be
522 // empty, allow variable names starting with an equals sign. Skip all
524 if input.is_empty() {
527 let pos = memchr::memchr(b'=', &input[1..]).map(|p| p + 1);
529 OsStringExt::from_vec(input[..p].to_vec()),
530 OsStringExt::from_vec(input[p+1..].to_vec()),
535 pub fn getenv(k: &OsStr) -> io::Result<Option<OsString>> {
536 // environment variables with a nul byte can't be set, so their value is
537 // always None as well
538 let k = CString::new(k.as_bytes())?;
541 let s = libc::getenv(k.as_ptr()) as *const _;
542 let ret = if s.is_null() {
545 Some(OsStringExt::from_vec(CStr::from_ptr(s).to_bytes().to_vec()))
552 pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> {
553 let k = CString::new(k.as_bytes())?;
554 let v = CString::new(v.as_bytes())?;
558 let ret = cvt(libc::setenv(k.as_ptr(), v.as_ptr(), 1)).map(|_| ());
564 pub fn unsetenv(n: &OsStr) -> io::Result<()> {
565 let nbuf = CString::new(n.as_bytes())?;
569 let ret = cvt(libc::unsetenv(nbuf.as_ptr())).map(|_| ());
575 pub fn page_size() -> usize {
577 libc::sysconf(libc::_SC_PAGESIZE) as usize
581 pub fn temp_dir() -> PathBuf {
582 ::env::var_os("TMPDIR").map(PathBuf::from).unwrap_or_else(|| {
583 if cfg!(target_os = "android") {
584 PathBuf::from("/data/local/tmp")
586 PathBuf::from("/tmp")
591 pub fn home_dir() -> Option<PathBuf> {
592 return ::env::var_os("HOME").or_else(|| unsafe {
594 }).map(PathBuf::from);
596 #[cfg(any(target_os = "android",
599 target_os = "emscripten"))]
600 unsafe fn fallback() -> Option<OsString> { None }
601 #[cfg(not(any(target_os = "android",
604 target_os = "emscripten")))]
605 unsafe fn fallback() -> Option<OsString> {
606 #[cfg(not(target_os = "solaris"))]
607 unsafe fn getpwduid_r(me: libc::uid_t, passwd: &mut libc::passwd,
608 buf: &mut Vec<c_char>) -> Option<()> {
609 let mut result = ptr::null_mut();
610 match libc::getpwuid_r(me, passwd, buf.as_mut_ptr(),
611 buf.capacity() as libc::size_t,
613 0 if !result.is_null() => Some(()),
618 #[cfg(target_os = "solaris")]
619 unsafe fn getpwduid_r(me: libc::uid_t, passwd: &mut libc::passwd,
620 buf: &mut Vec<c_char>) -> Option<()> {
621 // getpwuid_r semantics is different on Illumos/Solaris:
622 // http://illumos.org/man/3c/getpwuid_r
623 let result = libc::getpwuid_r(me, passwd, buf.as_mut_ptr(),
624 buf.capacity() as libc::size_t);
625 if result.is_null() { None } else { Some(()) }
628 let amt = match libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) {
629 n if n < 0 => 512 as usize,
632 let mut buf = Vec::with_capacity(amt);
633 let mut passwd: libc::passwd = mem::zeroed();
635 if getpwduid_r(libc::getuid(), &mut passwd, &mut buf).is_some() {
636 let ptr = passwd.pw_dir as *const _;
637 let bytes = CStr::from_ptr(ptr).to_bytes().to_vec();
638 Some(OsStringExt::from_vec(bytes))
645 pub fn exit(code: i32) -> ! {
646 unsafe { libc::exit(code as c_int) }