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 fn errno_location() -> *mut c_int;
57 /// Returns the platform-specific value of errno
58 #[cfg(not(target_os = "dragonfly"))]
59 pub fn errno() -> i32 {
61 (*errno_location()) as i32
65 /// Sets the platform-specific value of errno
66 #[cfg(target_os = "solaris")] // only needed for readdir so far
67 pub fn set_errno(e: i32) {
69 *errno_location() = e as c_int
73 #[cfg(target_os = "dragonfly")]
74 pub fn errno() -> i32 {
83 /// Gets a detailed string description for the given error number.
84 pub fn error_string(errno: i32) -> String {
86 #[cfg_attr(any(target_os = "linux", target_env = "newlib"),
87 link_name = "__xpg_strerror_r")]
88 fn strerror_r(errnum: c_int, buf: *mut c_char,
89 buflen: libc::size_t) -> c_int;
92 let mut buf = [0 as c_char; TMPBUF_SZ];
94 let p = buf.as_mut_ptr();
96 if strerror_r(errno as c_int, p, buf.len() as libc::size_t) < 0 {
97 panic!("strerror_r failure");
100 let p = p as *const _;
101 str::from_utf8(CStr::from_ptr(p).to_bytes()).unwrap().to_owned()
105 pub fn getcwd() -> io::Result<PathBuf> {
106 let mut buf = Vec::with_capacity(512);
109 let ptr = buf.as_mut_ptr() as *mut libc::c_char;
110 if !libc::getcwd(ptr, buf.capacity() as libc::size_t).is_null() {
111 let len = CStr::from_ptr(buf.as_ptr() as *const libc::c_char).to_bytes().len();
114 return Ok(PathBuf::from(OsString::from_vec(buf)));
116 let error = io::Error::last_os_error();
117 if error.raw_os_error() != Some(libc::ERANGE) {
122 // Trigger the internal buffer resizing logic of `Vec` by requiring
123 // more space than the current capacity.
124 let cap = buf.capacity();
131 pub fn chdir(p: &path::Path) -> io::Result<()> {
132 let p: &OsStr = p.as_ref();
133 let p = CString::new(p.as_bytes())?;
135 match libc::chdir(p.as_ptr()) == (0 as c_int) {
137 false => Err(io::Error::last_os_error()),
142 pub struct SplitPaths<'a> {
143 iter: iter::Map<slice::Split<'a, u8, fn(&u8) -> bool>,
144 fn(&'a [u8]) -> PathBuf>,
147 pub fn split_paths(unparsed: &OsStr) -> SplitPaths {
148 fn bytes_to_path(b: &[u8]) -> PathBuf {
149 PathBuf::from(<OsStr as OsStrExt>::from_bytes(b))
151 fn is_colon(b: &u8) -> bool { *b == b':' }
152 let unparsed = unparsed.as_bytes();
154 iter: unparsed.split(is_colon as fn(&u8) -> bool)
155 .map(bytes_to_path as fn(&[u8]) -> PathBuf)
159 impl<'a> Iterator for SplitPaths<'a> {
161 fn next(&mut self) -> Option<PathBuf> { self.iter.next() }
162 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
166 pub struct JoinPathsError;
168 pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
169 where I: Iterator<Item=T>, T: AsRef<OsStr>
171 let mut joined = Vec::new();
174 for (i, path) in paths.enumerate() {
175 let path = path.as_ref().as_bytes();
176 if i > 0 { joined.push(sep) }
177 if path.contains(&sep) {
178 return Err(JoinPathsError)
180 joined.extend_from_slice(path);
182 Ok(OsStringExt::from_vec(joined))
185 impl fmt::Display for JoinPathsError {
186 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
187 "path segment contains separator `:`".fmt(f)
191 impl StdError for JoinPathsError {
192 fn description(&self) -> &str { "failed to join paths" }
195 #[cfg(target_os = "freebsd")]
196 pub fn current_exe() -> io::Result<PathBuf> {
198 let mut mib = [libc::CTL_KERN as c_int,
199 libc::KERN_PROC as c_int,
200 libc::KERN_PROC_PATHNAME as c_int,
202 let mut sz: libc::size_t = 0;
203 cvt(libc::sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
204 ptr::null_mut(), &mut sz, ptr::null_mut(),
205 0 as libc::size_t))?;
207 return Err(io::Error::last_os_error())
209 let mut v: Vec<u8> = Vec::with_capacity(sz as usize);
210 cvt(libc::sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
211 v.as_mut_ptr() as *mut libc::c_void, &mut sz,
212 ptr::null_mut(), 0 as libc::size_t))?;
214 return Err(io::Error::last_os_error());
216 v.set_len(sz as usize - 1); // chop off trailing NUL
217 Ok(PathBuf::from(OsString::from_vec(v)))
221 #[cfg(target_os = "dragonfly")]
222 pub fn current_exe() -> io::Result<PathBuf> {
223 ::fs::read_link("/proc/curproc/file")
226 #[cfg(target_os = "netbsd")]
227 pub fn current_exe() -> io::Result<PathBuf> {
228 ::fs::read_link("/proc/curproc/exe")
231 #[cfg(any(target_os = "bitrig", target_os = "openbsd"))]
232 pub fn current_exe() -> io::Result<PathBuf> {
234 let mut mib = [libc::CTL_KERN,
235 libc::KERN_PROC_ARGS,
237 libc::KERN_PROC_ARGV];
238 let mib = mib.as_mut_ptr();
239 let mut argv_len = 0;
240 cvt(libc::sysctl(mib, 4, ptr::null_mut(), &mut argv_len,
241 ptr::null_mut(), 0))?;
242 let mut argv = Vec::<*const libc::c_char>::with_capacity(argv_len as usize);
243 cvt(libc::sysctl(mib, 4, argv.as_mut_ptr() as *mut _,
244 &mut argv_len, ptr::null_mut(), 0))?;
245 argv.set_len(argv_len as usize);
246 if argv[0].is_null() {
247 return Err(io::Error::new(io::ErrorKind::Other,
248 "no current exe available"))
250 let argv0 = CStr::from_ptr(argv[0]).to_bytes();
251 if argv0[0] == b'.' || argv0.iter().any(|b| *b == b'/') {
252 ::fs::canonicalize(OsStr::from_bytes(argv0))
254 Ok(PathBuf::from(OsStr::from_bytes(argv0)))
259 #[cfg(any(target_os = "linux", target_os = "android", target_os = "emscripten"))]
260 pub fn current_exe() -> io::Result<PathBuf> {
261 ::fs::read_link("/proc/self/exe")
264 #[cfg(any(target_os = "macos", target_os = "ios"))]
265 pub fn current_exe() -> io::Result<PathBuf> {
267 fn _NSGetExecutablePath(buf: *mut libc::c_char,
268 bufsize: *mut u32) -> libc::c_int;
272 _NSGetExecutablePath(ptr::null_mut(), &mut sz);
273 if sz == 0 { return Err(io::Error::last_os_error()); }
274 let mut v: Vec<u8> = Vec::with_capacity(sz as usize);
275 let err = _NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz);
276 if err != 0 { return Err(io::Error::last_os_error()); }
277 v.set_len(sz as usize - 1); // chop off trailing NUL
278 Ok(PathBuf::from(OsString::from_vec(v)))
282 #[cfg(any(target_os = "solaris"))]
283 pub fn current_exe() -> io::Result<PathBuf> {
285 fn getexecname() -> *const c_char;
288 let path = getexecname();
290 Err(io::Error::last_os_error())
292 let filename = CStr::from_ptr(path).to_bytes();
293 let path = PathBuf::from(<OsStr as OsStrExt>::from_bytes(filename));
295 // Prepend a current working directory to the path if
296 // it doesn't contain an absolute pathname.
297 if filename[0] == b'/' {
300 getcwd().map(|cwd| cwd.join(path))
307 iter: vec::IntoIter<OsString>,
308 _dont_send_or_sync_me: PhantomData<*mut ()>,
311 impl Iterator for Args {
312 type Item = OsString;
313 fn next(&mut self) -> Option<OsString> { self.iter.next() }
314 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
317 impl ExactSizeIterator for Args {
318 fn len(&self) -> usize { self.iter.len() }
321 impl DoubleEndedIterator for Args {
322 fn next_back(&mut self) -> Option<OsString> { self.iter.next_back() }
325 /// Returns the command line arguments
327 /// Returns a list of the command line arguments.
328 #[cfg(target_os = "macos")]
329 pub fn args() -> Args {
331 // These functions are in crt_externs.h.
332 fn _NSGetArgc() -> *mut c_int;
333 fn _NSGetArgv() -> *mut *mut *mut c_char;
337 let (argc, argv) = (*_NSGetArgc() as isize,
338 *_NSGetArgv() as *const *const c_char);
339 (0.. argc as isize).map(|i| {
340 let bytes = CStr::from_ptr(*argv.offset(i)).to_bytes().to_vec();
341 OsStringExt::from_vec(bytes)
342 }).collect::<Vec<_>>()
345 iter: vec.into_iter(),
346 _dont_send_or_sync_me: PhantomData,
350 // As _NSGetArgc and _NSGetArgv aren't mentioned in iOS docs
351 // and use underscores in their names - they're most probably
352 // are considered private and therefore should be avoided
353 // Here is another way to get arguments using Objective C
356 // In general it looks like:
358 // let args = [[NSProcessInfo processInfo] arguments]
359 // for i in (0..[args count])
360 // res.push([args objectAtIndex:i])
362 #[cfg(target_os = "ios")]
363 pub fn args() -> Args {
367 fn sel_registerName(name: *const libc::c_uchar) -> Sel;
368 fn objc_msgSend(obj: NsId, sel: Sel, ...) -> NsId;
369 fn objc_getClass(class_name: *const libc::c_uchar) -> NsId;
372 #[link(name = "Foundation", kind = "framework")]
373 #[link(name = "objc")]
374 #[cfg(not(cargobuild))]
377 type Sel = *const libc::c_void;
378 type NsId = *const libc::c_void;
380 let mut res = Vec::new();
383 let process_info_sel = sel_registerName("processInfo\0".as_ptr());
384 let arguments_sel = sel_registerName("arguments\0".as_ptr());
385 let utf8_sel = sel_registerName("UTF8String\0".as_ptr());
386 let count_sel = sel_registerName("count\0".as_ptr());
387 let object_at_sel = sel_registerName("objectAtIndex:\0".as_ptr());
389 let klass = objc_getClass("NSProcessInfo\0".as_ptr());
390 let info = objc_msgSend(klass, process_info_sel);
391 let args = objc_msgSend(info, arguments_sel);
393 let cnt: usize = mem::transmute(objc_msgSend(args, count_sel));
395 let tmp = objc_msgSend(args, object_at_sel, i);
396 let utf_c_str: *const libc::c_char =
397 mem::transmute(objc_msgSend(tmp, utf8_sel));
398 let bytes = CStr::from_ptr(utf_c_str).to_bytes();
399 res.push(OsString::from(str::from_utf8(bytes).unwrap()))
403 Args { iter: res.into_iter(), _dont_send_or_sync_me: PhantomData }
406 #[cfg(any(target_os = "linux",
407 target_os = "android",
408 target_os = "freebsd",
409 target_os = "dragonfly",
410 target_os = "bitrig",
411 target_os = "netbsd",
412 target_os = "openbsd",
413 target_os = "solaris",
415 target_os = "emscripten"))]
416 pub fn args() -> Args {
418 let bytes = sys_common::args::clone().unwrap_or(Vec::new());
419 let v: Vec<OsString> = bytes.into_iter().map(|v| {
420 OsStringExt::from_vec(v)
422 Args { iter: v.into_iter(), _dont_send_or_sync_me: PhantomData }
426 iter: vec::IntoIter<(OsString, OsString)>,
427 _dont_send_or_sync_me: PhantomData<*mut ()>,
430 impl Iterator for Env {
431 type Item = (OsString, OsString);
432 fn next(&mut self) -> Option<(OsString, OsString)> { self.iter.next() }
433 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
436 #[cfg(target_os = "macos")]
437 pub unsafe fn environ() -> *mut *const *const c_char {
438 extern { fn _NSGetEnviron() -> *mut *const *const c_char; }
442 #[cfg(not(target_os = "macos"))]
443 pub unsafe fn environ() -> *mut *const *const c_char {
444 extern { static mut environ: *const *const c_char; }
448 /// Returns a vector of (variable, value) byte-vector pairs for all the
449 /// environment variables of the current process.
450 pub fn env() -> Env {
453 let mut environ = *environ();
454 if environ == ptr::null() {
456 panic!("os::env() failure getting env string from OS: {}",
457 io::Error::last_os_error());
459 let mut result = Vec::new();
460 while *environ != ptr::null() {
461 if let Some(key_value) = parse(CStr::from_ptr(*environ).to_bytes()) {
462 result.push(key_value);
464 environ = environ.offset(1);
467 iter: result.into_iter(),
468 _dont_send_or_sync_me: PhantomData,
474 fn parse(input: &[u8]) -> Option<(OsString, OsString)> {
475 // Strategy (copied from glibc): Variable name and value are separated
476 // by an ASCII equals sign '='. Since a variable name must not be
477 // empty, allow variable names starting with an equals sign. Skip all
479 if input.is_empty() {
482 let pos = memchr::memchr(b'=', &input[1..]).map(|p| p + 1);
484 OsStringExt::from_vec(input[..p].to_vec()),
485 OsStringExt::from_vec(input[p+1..].to_vec()),
490 pub fn getenv(k: &OsStr) -> io::Result<Option<OsString>> {
491 // environment variables with a nul byte can't be set, so their value is
492 // always None as well
493 let k = CString::new(k.as_bytes())?;
496 let s = libc::getenv(k.as_ptr()) as *const _;
497 let ret = if s.is_null() {
500 Some(OsStringExt::from_vec(CStr::from_ptr(s).to_bytes().to_vec()))
507 pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> {
508 let k = CString::new(k.as_bytes())?;
509 let v = CString::new(v.as_bytes())?;
513 let ret = cvt(libc::setenv(k.as_ptr(), v.as_ptr(), 1)).map(|_| ());
519 pub fn unsetenv(n: &OsStr) -> io::Result<()> {
520 let nbuf = CString::new(n.as_bytes())?;
524 let ret = cvt(libc::unsetenv(nbuf.as_ptr())).map(|_| ());
530 pub fn page_size() -> usize {
532 libc::sysconf(libc::_SC_PAGESIZE) as usize
536 pub fn temp_dir() -> PathBuf {
537 ::env::var_os("TMPDIR").map(PathBuf::from).unwrap_or_else(|| {
538 if cfg!(target_os = "android") {
539 PathBuf::from("/data/local/tmp")
541 PathBuf::from("/tmp")
546 pub fn home_dir() -> Option<PathBuf> {
547 return ::env::var_os("HOME").or_else(|| unsafe {
549 }).map(PathBuf::from);
551 #[cfg(any(target_os = "android",
554 target_os = "emscripten"))]
555 unsafe fn fallback() -> Option<OsString> { None }
556 #[cfg(not(any(target_os = "android",
559 target_os = "emscripten")))]
560 unsafe fn fallback() -> Option<OsString> {
561 #[cfg(not(target_os = "solaris"))]
562 unsafe fn getpwduid_r(me: libc::uid_t, passwd: &mut libc::passwd,
563 buf: &mut Vec<c_char>) -> Option<()> {
564 let mut result = ptr::null_mut();
565 match libc::getpwuid_r(me, passwd, buf.as_mut_ptr(),
566 buf.capacity() as libc::size_t,
568 0 if !result.is_null() => Some(()),
573 #[cfg(target_os = "solaris")]
574 unsafe fn getpwduid_r(me: libc::uid_t, passwd: &mut libc::passwd,
575 buf: &mut Vec<c_char>) -> Option<()> {
576 // getpwuid_r semantics is different on Illumos/Solaris:
577 // http://illumos.org/man/3c/getpwuid_r
578 let result = libc::getpwuid_r(me, passwd, buf.as_mut_ptr(),
579 buf.capacity() as libc::size_t);
580 if result.is_null() { None } else { Some(()) }
583 let amt = match libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) {
584 n if n < 0 => 512 as usize,
587 let me = libc::getuid();
589 let mut buf = Vec::with_capacity(amt);
590 let mut passwd: libc::passwd = mem::zeroed();
592 if getpwduid_r(me, &mut passwd, &mut buf).is_some() {
593 let ptr = passwd.pw_dir as *const _;
594 let bytes = CStr::from_ptr(ptr).to_bytes().to_vec();
595 return Some(OsStringExt::from_vec(bytes))
603 pub fn exit(code: i32) -> ! {
604 unsafe { libc::exit(code as c_int) }