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
16 use os::unix::prelude::*;
18 use error::Error as StdError;
19 use ffi::{CString, CStr, OsString, OsStr};
23 use libc::{self, c_int, c_char, c_void};
24 use marker::PhantomData;
27 use path::{self, PathBuf};
31 use sys_common::mutex::Mutex;
36 const TMPBUF_SZ: usize = 128;
37 static ENV_LOCK: Mutex = Mutex::new();
41 #[cfg(not(target_os = "dragonfly"))]
42 #[cfg_attr(any(target_os = "linux", target_os = "emscripten"),
43 link_name = "__errno_location")]
44 #[cfg_attr(any(target_os = "bitrig",
46 target_os = "openbsd",
47 target_os = "android",
48 target_env = "newlib"),
49 link_name = "__errno")]
50 #[cfg_attr(target_os = "solaris", link_name = "___errno")]
51 #[cfg_attr(any(target_os = "macos",
53 target_os = "freebsd"),
54 link_name = "__error")]
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))
308 iter: vec::IntoIter<OsString>,
309 _dont_send_or_sync_me: PhantomData<*mut ()>,
312 impl Iterator for Args {
313 type Item = OsString;
314 fn next(&mut self) -> Option<OsString> { self.iter.next() }
315 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
318 impl ExactSizeIterator for Args {
319 fn len(&self) -> usize { self.iter.len() }
322 impl DoubleEndedIterator for Args {
323 fn next_back(&mut self) -> Option<OsString> { self.iter.next_back() }
326 /// Returns the command line arguments
328 /// Returns a list of the command line arguments.
329 #[cfg(target_os = "macos")]
330 pub fn args() -> Args {
332 // These functions are in crt_externs.h.
333 fn _NSGetArgc() -> *mut c_int;
334 fn _NSGetArgv() -> *mut *mut *mut c_char;
338 let (argc, argv) = (*_NSGetArgc() as isize,
339 *_NSGetArgv() as *const *const c_char);
340 (0.. argc as isize).map(|i| {
341 let bytes = CStr::from_ptr(*argv.offset(i)).to_bytes().to_vec();
342 OsStringExt::from_vec(bytes)
343 }).collect::<Vec<_>>()
346 iter: vec.into_iter(),
347 _dont_send_or_sync_me: PhantomData,
351 // As _NSGetArgc and _NSGetArgv aren't mentioned in iOS docs
352 // and use underscores in their names - they're most probably
353 // are considered private and therefore should be avoided
354 // Here is another way to get arguments using Objective C
357 // In general it looks like:
359 // let args = [[NSProcessInfo processInfo] arguments]
360 // for i in (0..[args count])
361 // res.push([args objectAtIndex:i])
363 #[cfg(target_os = "ios")]
364 pub fn args() -> Args {
368 fn sel_registerName(name: *const libc::c_uchar) -> Sel;
369 fn objc_msgSend(obj: NsId, sel: Sel, ...) -> NsId;
370 fn objc_getClass(class_name: *const libc::c_uchar) -> NsId;
373 #[link(name = "Foundation", kind = "framework")]
374 #[link(name = "objc")]
375 #[cfg(not(cargobuild))]
378 type Sel = *const libc::c_void;
379 type NsId = *const libc::c_void;
381 let mut res = Vec::new();
384 let process_info_sel = sel_registerName("processInfo\0".as_ptr());
385 let arguments_sel = sel_registerName("arguments\0".as_ptr());
386 let utf8_sel = sel_registerName("UTF8String\0".as_ptr());
387 let count_sel = sel_registerName("count\0".as_ptr());
388 let object_at_sel = sel_registerName("objectAtIndex:\0".as_ptr());
390 let klass = objc_getClass("NSProcessInfo\0".as_ptr());
391 let info = objc_msgSend(klass, process_info_sel);
392 let args = objc_msgSend(info, arguments_sel);
394 let cnt: usize = mem::transmute(objc_msgSend(args, count_sel));
396 let tmp = objc_msgSend(args, object_at_sel, i);
397 let utf_c_str: *const libc::c_char =
398 mem::transmute(objc_msgSend(tmp, utf8_sel));
399 let bytes = CStr::from_ptr(utf_c_str).to_bytes();
400 res.push(OsString::from(str::from_utf8(bytes).unwrap()))
404 Args { iter: res.into_iter(), _dont_send_or_sync_me: PhantomData }
407 #[cfg(any(target_os = "linux",
408 target_os = "android",
409 target_os = "freebsd",
410 target_os = "dragonfly",
411 target_os = "bitrig",
412 target_os = "netbsd",
413 target_os = "openbsd",
414 target_os = "solaris",
416 target_os = "emscripten"))]
417 pub fn args() -> Args {
419 let bytes = sys_common::args::clone().unwrap_or(Vec::new());
420 let v: Vec<OsString> = bytes.into_iter().map(|v| {
421 OsStringExt::from_vec(v)
423 Args { iter: v.into_iter(), _dont_send_or_sync_me: PhantomData }
427 iter: vec::IntoIter<(OsString, OsString)>,
428 _dont_send_or_sync_me: PhantomData<*mut ()>,
431 impl Iterator for Env {
432 type Item = (OsString, OsString);
433 fn next(&mut self) -> Option<(OsString, OsString)> { self.iter.next() }
434 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
437 #[cfg(target_os = "macos")]
438 pub unsafe fn environ() -> *mut *const *const c_char {
439 extern { fn _NSGetEnviron() -> *mut *const *const c_char; }
443 #[cfg(not(target_os = "macos"))]
444 pub unsafe fn environ() -> *mut *const *const c_char {
445 extern { static mut environ: *const *const c_char; }
449 /// Returns a vector of (variable, value) byte-vector pairs for all the
450 /// environment variables of the current process.
451 pub fn env() -> Env {
454 let mut environ = *environ();
455 if environ == ptr::null() {
457 panic!("os::env() failure getting env string from OS: {}",
458 io::Error::last_os_error());
460 let mut result = Vec::new();
461 while *environ != ptr::null() {
462 if let Some(key_value) = parse(CStr::from_ptr(*environ).to_bytes()) {
463 result.push(key_value);
465 environ = environ.offset(1);
468 iter: result.into_iter(),
469 _dont_send_or_sync_me: PhantomData,
475 fn parse(input: &[u8]) -> Option<(OsString, OsString)> {
476 // Strategy (copied from glibc): Variable name and value are separated
477 // by an ASCII equals sign '='. Since a variable name must not be
478 // empty, allow variable names starting with an equals sign. Skip all
480 if input.is_empty() {
483 let pos = memchr::memchr(b'=', &input[1..]).map(|p| p + 1);
485 OsStringExt::from_vec(input[..p].to_vec()),
486 OsStringExt::from_vec(input[p+1..].to_vec()),
491 pub fn getenv(k: &OsStr) -> io::Result<Option<OsString>> {
492 // environment variables with a nul byte can't be set, so their value is
493 // always None as well
494 let k = CString::new(k.as_bytes())?;
497 let s = libc::getenv(k.as_ptr()) as *const _;
498 let ret = if s.is_null() {
501 Some(OsStringExt::from_vec(CStr::from_ptr(s).to_bytes().to_vec()))
508 pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> {
509 let k = CString::new(k.as_bytes())?;
510 let v = CString::new(v.as_bytes())?;
514 let ret = cvt(libc::setenv(k.as_ptr(), v.as_ptr(), 1)).map(|_| ());
520 pub fn unsetenv(n: &OsStr) -> io::Result<()> {
521 let nbuf = CString::new(n.as_bytes())?;
525 let ret = cvt(libc::unsetenv(nbuf.as_ptr())).map(|_| ());
531 pub fn page_size() -> usize {
533 libc::sysconf(libc::_SC_PAGESIZE) as usize
537 pub fn temp_dir() -> PathBuf {
538 ::env::var_os("TMPDIR").map(PathBuf::from).unwrap_or_else(|| {
539 if cfg!(target_os = "android") {
540 PathBuf::from("/data/local/tmp")
542 PathBuf::from("/tmp")
547 pub fn home_dir() -> Option<PathBuf> {
548 return ::env::var_os("HOME").or_else(|| unsafe {
550 }).map(PathBuf::from);
552 #[cfg(any(target_os = "android",
554 target_os = "nacl"))]
555 unsafe fn fallback() -> Option<OsString> { None }
556 #[cfg(not(any(target_os = "android",
558 target_os = "nacl")))]
559 unsafe fn fallback() -> Option<OsString> {
560 #[cfg(not(target_os = "solaris"))]
561 unsafe fn getpwduid_r(me: libc::uid_t, passwd: &mut libc::passwd,
562 buf: &mut Vec<c_char>) -> Option<()> {
563 let mut result = ptr::null_mut();
564 match libc::getpwuid_r(me, passwd, buf.as_mut_ptr(),
565 buf.capacity() as libc::size_t,
567 0 if !result.is_null() => Some(()),
572 #[cfg(target_os = "solaris")]
573 unsafe fn getpwduid_r(me: libc::uid_t, passwd: &mut libc::passwd,
574 buf: &mut Vec<c_char>) -> Option<()> {
575 // getpwuid_r semantics is different on Illumos/Solaris:
576 // http://illumos.org/man/3c/getpwuid_r
577 let result = libc::getpwuid_r(me, passwd, buf.as_mut_ptr(),
578 buf.capacity() as libc::size_t);
579 if result.is_null() { None } else { Some(()) }
582 let amt = match libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) {
583 n if n < 0 => 512 as usize,
586 let me = libc::getuid();
588 let mut buf = Vec::with_capacity(amt);
589 let mut passwd: libc::passwd = mem::zeroed();
591 if getpwduid_r(me, &mut passwd, &mut buf).is_some() {
592 let ptr = passwd.pw_dir as *const _;
593 let bytes = CStr::from_ptr(ptr).to_bytes().to_vec();
594 return Some(OsStringExt::from_vec(bytes))
602 pub fn exit(code: i32) -> ! {
603 unsafe { libc::exit(code as c_int) }