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
16 use error::Error as StdError;
17 use ffi::{CString, CStr, OsString, OsStr, AsOsStr};
20 use libc::{self, c_int, c_char, c_void};
23 use old_io::{IoResult, IoError, fs};
29 use sys::fs::FileDesc;
32 const BUF_BYTES: usize = 2048;
33 const TMPBUF_SZ: usize = 128;
35 /// Returns the platform-specific value of errno
36 pub fn errno() -> i32 {
37 #[cfg(any(target_os = "macos",
39 target_os = "freebsd"))]
40 unsafe fn errno_location() -> *const c_int {
41 extern { fn __error() -> *const c_int; }
45 #[cfg(target_os = "dragonfly")]
46 unsafe fn errno_location() -> *const c_int {
47 extern { fn __dfly_error() -> *const c_int; }
51 #[cfg(target_os = "openbsd")]
52 unsafe fn errno_location() -> *const c_int {
53 extern { fn __errno() -> *const c_int; }
57 #[cfg(any(target_os = "linux", target_os = "android"))]
58 unsafe fn errno_location() -> *const c_int {
59 extern { fn __errno_location() -> *const c_int; }
64 (*errno_location()) as i32
68 /// Get a detailed string description for the given error number
69 pub fn error_string(errno: i32) -> String {
70 #[cfg(target_os = "linux")]
72 #[link_name = "__xpg_strerror_r"]
73 fn strerror_r(errnum: c_int, buf: *mut c_char,
74 buflen: libc::size_t) -> c_int;
76 #[cfg(not(target_os = "linux"))]
78 fn strerror_r(errnum: c_int, buf: *mut c_char,
79 buflen: libc::size_t) -> c_int;
82 let mut buf = [0 as c_char; TMPBUF_SZ];
84 let p = buf.as_mut_ptr();
86 if strerror_r(errno as c_int, p, buf.len() as libc::size_t) < 0 {
87 panic!("strerror_r failure");
90 let p = p as *const _;
91 str::from_utf8(CStr::from_ptr(p).to_bytes()).unwrap().to_string()
95 pub fn getcwd() -> IoResult<Path> {
96 let mut buf = [0 as c_char; BUF_BYTES];
98 if libc::getcwd(buf.as_mut_ptr(), buf.len() as libc::size_t).is_null() {
99 Err(IoError::last_error())
101 Ok(Path::new(CStr::from_ptr(buf.as_ptr()).to_bytes()))
106 pub fn chdir(p: &Path) -> IoResult<()> {
107 let p = CString::new(p.as_vec()).unwrap();
109 match libc::chdir(p.as_ptr()) == (0 as c_int) {
111 false => Err(IoError::last_error()),
116 pub struct SplitPaths<'a> {
117 iter: iter::Map<slice::Split<'a, u8, fn(&u8) -> bool>,
118 fn(&'a [u8]) -> Path>,
121 pub fn split_paths<'a>(unparsed: &'a OsStr) -> SplitPaths<'a> {
122 fn is_colon(b: &u8) -> bool { *b == b':' }
123 let unparsed = unparsed.as_bytes();
125 iter: unparsed.split(is_colon as fn(&u8) -> bool)
126 .map(Path::new as fn(&'a [u8]) -> Path)
130 impl<'a> Iterator for SplitPaths<'a> {
132 fn next(&mut self) -> Option<Path> { self.iter.next() }
133 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
137 pub struct JoinPathsError;
139 pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
140 where I: Iterator<Item=T>, T: AsOsStr
142 let mut joined = Vec::new();
145 for (i, path) in paths.enumerate() {
146 let path = path.as_os_str().as_bytes();
147 if i > 0 { joined.push(sep) }
148 if path.contains(&sep) {
149 return Err(JoinPathsError)
151 joined.push_all(path);
153 Ok(OsStringExt::from_vec(joined))
156 impl fmt::Display for JoinPathsError {
157 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
158 "path segment contains separator `:`".fmt(f)
162 impl StdError for JoinPathsError {
163 fn description(&self) -> &str { "failed to join paths" }
166 #[cfg(target_os = "freebsd")]
167 pub fn current_exe() -> IoResult<Path> {
169 use libc::funcs::bsd44::*;
170 use libc::consts::os::extra::*;
171 let mut mib = vec![CTL_KERN as c_int,
173 KERN_PROC_PATHNAME as c_int,
175 let mut sz: libc::size_t = 0;
176 let err = sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
177 ptr::null_mut(), &mut sz, ptr::null_mut(),
179 if err != 0 { return Err(IoError::last_error()); }
180 if sz == 0 { return Err(IoError::last_error()); }
181 let mut v: Vec<u8> = Vec::with_capacity(sz as uint);
182 let err = sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
183 v.as_mut_ptr() as *mut libc::c_void, &mut sz,
184 ptr::null_mut(), 0 as libc::size_t);
185 if err != 0 { return Err(IoError::last_error()); }
186 if sz == 0 { return Err(IoError::last_error()); }
187 v.set_len(sz as uint - 1); // chop off trailing NUL
192 #[cfg(target_os = "dragonfly")]
193 pub fn current_exe() -> IoResult<Path> {
194 fs::readlink(&Path::new("/proc/curproc/file"))
197 #[cfg(target_os = "openbsd")]
198 pub fn current_exe() -> IoResult<Path> {
199 use sync::{StaticMutex, MUTEX_INIT};
201 static LOCK: StaticMutex = MUTEX_INIT;
204 fn rust_current_exe() -> *const c_char;
207 let _guard = LOCK.lock();
210 let v = rust_current_exe();
212 Err(IoError::last_error())
214 Ok(Path::new(CStr::from_ptr(&v).to_bytes().to_vec()))
219 #[cfg(any(target_os = "linux", target_os = "android"))]
220 pub fn current_exe() -> IoResult<Path> {
221 fs::readlink(&Path::new("/proc/self/exe"))
224 #[cfg(any(target_os = "macos", target_os = "ios"))]
225 pub fn current_exe() -> IoResult<Path> {
227 use libc::funcs::extra::_NSGetExecutablePath;
229 _NSGetExecutablePath(ptr::null_mut(), &mut sz);
230 if sz == 0 { return Err(IoError::last_error()); }
231 let mut v: Vec<u8> = Vec::with_capacity(sz as uint);
232 let err = _NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz);
233 if err != 0 { return Err(IoError::last_error()); }
234 v.set_len(sz as uint - 1); // chop off trailing NUL
240 iter: vec::IntoIter<OsString>,
241 _dont_send_or_sync_me: *mut (),
244 impl Iterator for Args {
245 type Item = OsString;
246 fn next(&mut self) -> Option<OsString> { self.iter.next() }
247 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
250 impl ExactSizeIterator for Args {
251 fn len(&self) -> usize { self.iter.len() }
254 /// Returns the command line arguments
256 /// Returns a list of the command line arguments.
257 #[cfg(target_os = "macos")]
258 pub fn args() -> Args {
260 // These functions are in crt_externs.h.
261 fn _NSGetArgc() -> *mut c_int;
262 fn _NSGetArgv() -> *mut *mut *mut c_char;
266 let (argc, argv) = (*_NSGetArgc() as isize,
267 *_NSGetArgv() as *const *const c_char);
268 range(0, argc as isize).map(|i| {
269 let bytes = CStr::from_ptr(*argv.offset(i)).to_bytes().to_vec();
270 OsStringExt::from_vec(bytes)
271 }).collect::<Vec<_>>()
274 iter: vec.into_iter(),
275 _dont_send_or_sync_me: 0 as *mut (),
279 // As _NSGetArgc and _NSGetArgv aren't mentioned in iOS docs
280 // and use underscores in their names - they're most probably
281 // are considered private and therefore should be avoided
282 // Here is another way to get arguments using Objective C
285 // In general it looks like:
287 // let args = [[NSProcessInfo processInfo] arguments]
288 // for i in range(0, [args count])
289 // res.push([args objectAtIndex:i])
291 #[cfg(target_os = "ios")]
292 pub fn args() -> Args {
296 #[link(name = "objc")]
298 fn sel_registerName(name: *const libc::c_uchar) -> Sel;
299 fn objc_msgSend(obj: NsId, sel: Sel, ...) -> NsId;
300 fn objc_getClass(class_name: *const libc::c_uchar) -> NsId;
303 #[link(name = "Foundation", kind = "framework")]
306 type Sel = *const libc::c_void;
307 type NsId = *const libc::c_void;
309 let mut res = Vec::new();
312 let process_info_sel = sel_registerName("processInfo\0".as_ptr());
313 let arguments_sel = sel_registerName("arguments\0".as_ptr());
314 let utf8_sel = sel_registerName("UTF8String\0".as_ptr());
315 let count_sel = sel_registerName("count\0".as_ptr());
316 let object_at_sel = sel_registerName("objectAtIndex:\0".as_ptr());
318 let klass = objc_getClass("NSProcessInfo\0".as_ptr());
319 let info = objc_msgSend(klass, process_info_sel);
320 let args = objc_msgSend(info, arguments_sel);
322 let cnt: int = mem::transmute(objc_msgSend(args, count_sel));
323 for i in range(0, cnt) {
324 let tmp = objc_msgSend(args, object_at_sel, i);
325 let utf_c_str: *const libc::c_char =
326 mem::transmute(objc_msgSend(tmp, utf8_sel));
327 let bytes = CStr::from_ptr(utf_c_str).to_bytes();
328 res.push(OsString::from_str(str::from_utf8(bytes).unwrap()))
332 Args { iter: res.into_iter(), _dont_send_or_sync_me: 0 as *mut _ }
335 #[cfg(any(target_os = "linux",
336 target_os = "android",
337 target_os = "freebsd",
338 target_os = "dragonfly",
339 target_os = "openbsd"))]
340 pub fn args() -> Args {
342 let bytes = rt::args::clone().unwrap_or(Vec::new());
343 let v: Vec<OsString> = bytes.into_iter().map(|v| {
344 OsStringExt::from_vec(v)
346 Args { iter: v.into_iter(), _dont_send_or_sync_me: 0 as *mut _ }
350 iter: vec::IntoIter<(OsString, OsString)>,
351 _dont_send_or_sync_me: *mut (),
354 impl Iterator for Env {
355 type Item = (OsString, OsString);
356 fn next(&mut self) -> Option<(OsString, OsString)> { self.iter.next() }
357 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
360 #[cfg(target_os = "macos")]
361 pub unsafe fn environ() -> *mut *const *const c_char {
362 extern { fn _NSGetEnviron() -> *mut *const *const c_char; }
366 #[cfg(not(target_os = "macos"))]
367 pub unsafe fn environ() -> *mut *const *const c_char {
368 extern { static mut environ: *const *const c_char; }
372 /// Returns a vector of (variable, value) byte-vector pairs for all the
373 /// environment variables of the current process.
374 pub fn env() -> Env {
376 let mut environ = *environ();
377 if environ as usize == 0 {
378 panic!("os::env() failure getting env string from OS: {}",
379 IoError::last_error());
381 let mut result = Vec::new();
382 while *environ != ptr::null() {
383 result.push(parse(CStr::from_ptr(*environ).to_bytes()));
384 environ = environ.offset(1);
386 Env { iter: result.into_iter(), _dont_send_or_sync_me: 0 as *mut _ }
389 fn parse(input: &[u8]) -> (OsString, OsString) {
390 let mut it = input.splitn(1, |b| *b == b'=');
391 let key = it.next().unwrap().to_vec();
392 let default: &[u8] = &[];
393 let val = it.next().unwrap_or(default).to_vec();
394 (OsStringExt::from_vec(key), OsStringExt::from_vec(val))
398 pub fn getenv(k: &OsStr) -> Option<OsString> {
400 let s = k.to_cstring().unwrap();
401 let s = libc::getenv(s.as_ptr()) as *const _;
405 Some(OsStringExt::from_vec(CStr::from_ptr(s).to_bytes().to_vec()))
410 pub fn setenv(k: &OsStr, v: &OsStr) {
412 let k = k.to_cstring().unwrap();
413 let v = v.to_cstring().unwrap();
414 if libc::funcs::posix01::unistd::setenv(k.as_ptr(), v.as_ptr(), 1) != 0 {
415 panic!("failed setenv: {}", IoError::last_error());
420 pub fn unsetenv(n: &OsStr) {
422 let nbuf = n.to_cstring().unwrap();
423 if libc::funcs::posix01::unistd::unsetenv(nbuf.as_ptr()) != 0 {
424 panic!("failed unsetenv: {}", IoError::last_error());
429 pub unsafe fn pipe() -> IoResult<(FileDesc, FileDesc)> {
430 let mut fds = [0; 2];
431 if libc::pipe(fds.as_mut_ptr()) == 0 {
432 Ok((FileDesc::new(fds[0], true), FileDesc::new(fds[1], true)))
434 Err(IoError::last_error())
438 pub fn page_size() -> usize {
440 libc::sysconf(libc::_SC_PAGESIZE) as usize
444 pub fn temp_dir() -> Path {
445 getenv("TMPDIR".as_os_str()).map(|p| Path::new(p.into_vec())).unwrap_or_else(|| {
446 if cfg!(target_os = "android") {
447 Path::new("/data/local/tmp")
454 pub fn home_dir() -> Option<Path> {
455 return getenv("HOME".as_os_str()).or_else(|| unsafe {
458 Path::new(os.into_vec())
461 #[cfg(any(target_os = "android",
463 unsafe fn fallback() -> Option<OsString> { None }
464 #[cfg(not(any(target_os = "android",
465 target_os = "ios")))]
466 unsafe fn fallback() -> Option<OsString> {
467 let mut amt = match libc::sysconf(c::_SC_GETPW_R_SIZE_MAX) {
468 n if n < 0 => 512 as usize,
471 let me = libc::getuid();
473 let mut buf = Vec::with_capacity(amt);
474 let mut passwd: c::passwd = mem::zeroed();
475 let mut result = 0 as *mut _;
476 match c::getpwuid_r(me, &mut passwd, buf.as_mut_ptr(),
477 buf.capacity() as libc::size_t,
479 0 if !result.is_null() => {}
482 let ptr = passwd.pw_dir as *const _;
483 let bytes = CStr::from_ptr(ptr).to_bytes().to_vec();
484 return Some(OsStringExt::from_vec(bytes))