]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/os.rs
Add support for the Haiku operating system on x86 and x86_64 machines
[rust.git] / src / libstd / sys / unix / os.rs
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.
4 //
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.
10
11 //! Implementation of `std::os` functionality for unix systems
12
13 #![allow(unused_imports)] // lots of cfg code here
14
15 use os::unix::prelude::*;
16
17 use error::Error as StdError;
18 use ffi::{CString, CStr, OsString, OsStr};
19 use fmt;
20 use io;
21 use iter;
22 use libc::{self, c_int, c_char, c_void};
23 use marker::PhantomData;
24 use mem;
25 use memchr;
26 use path::{self, PathBuf};
27 use ptr;
28 use slice;
29 use str;
30 use sys_common::mutex::Mutex;
31 use sys::cvt;
32 use sys::fd;
33 use vec;
34
35 const TMPBUF_SZ: usize = 128;
36 static ENV_LOCK: Mutex = Mutex::new();
37
38
39 extern {
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",
44                    target_os = "netbsd",
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",
51                    target_os = "ios",
52                    target_os = "freebsd"),
53                link_name = "__error")]
54     #[cfg_attr(target_os = "haiku", link_name = "_errnop")]
55     fn errno_location() -> *mut c_int;
56 }
57
58 /// Returns the platform-specific value of errno
59 #[cfg(not(target_os = "dragonfly"))]
60 pub fn errno() -> i32 {
61     unsafe {
62         (*errno_location()) as i32
63     }
64 }
65
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) {
69     unsafe {
70         *errno_location() = e as c_int
71     }
72 }
73
74 #[cfg(target_os = "dragonfly")]
75 pub fn errno() -> i32 {
76     extern {
77         #[thread_local]
78         static errno: c_int;
79     }
80
81     errno as i32
82 }
83
84 /// Gets a detailed string description for the given error number.
85 pub fn error_string(errno: i32) -> String {
86     extern {
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;
91     }
92
93     let mut buf = [0 as c_char; TMPBUF_SZ];
94
95     let p = buf.as_mut_ptr();
96     unsafe {
97         if strerror_r(errno as c_int, p, buf.len() as libc::size_t) < 0 {
98             panic!("strerror_r failure");
99         }
100
101         let p = p as *const _;
102         str::from_utf8(CStr::from_ptr(p).to_bytes()).unwrap().to_owned()
103     }
104 }
105
106 pub fn getcwd() -> io::Result<PathBuf> {
107     let mut buf = Vec::with_capacity(512);
108     loop {
109         unsafe {
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();
113                 buf.set_len(len);
114                 buf.shrink_to_fit();
115                 return Ok(PathBuf::from(OsString::from_vec(buf)));
116             } else {
117                 let error = io::Error::last_os_error();
118                 if error.raw_os_error() != Some(libc::ERANGE) {
119                     return Err(error);
120                 }
121             }
122
123             // Trigger the internal buffer resizing logic of `Vec` by requiring
124             // more space than the current capacity.
125             let cap = buf.capacity();
126             buf.set_len(cap);
127             buf.reserve(1);
128         }
129     }
130 }
131
132 pub fn chdir(p: &path::Path) -> io::Result<()> {
133     let p: &OsStr = p.as_ref();
134     let p = CString::new(p.as_bytes())?;
135     unsafe {
136         match libc::chdir(p.as_ptr()) == (0 as c_int) {
137             true => Ok(()),
138             false => Err(io::Error::last_os_error()),
139         }
140     }
141 }
142
143 pub struct SplitPaths<'a> {
144     iter: iter::Map<slice::Split<'a, u8, fn(&u8) -> bool>,
145                     fn(&'a [u8]) -> PathBuf>,
146 }
147
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))
151     }
152     fn is_colon(b: &u8) -> bool { *b == b':' }
153     let unparsed = unparsed.as_bytes();
154     SplitPaths {
155         iter: unparsed.split(is_colon as fn(&u8) -> bool)
156                       .map(bytes_to_path as fn(&[u8]) -> PathBuf)
157     }
158 }
159
160 impl<'a> Iterator for SplitPaths<'a> {
161     type Item = PathBuf;
162     fn next(&mut self) -> Option<PathBuf> { self.iter.next() }
163     fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
164 }
165
166 #[derive(Debug)]
167 pub struct JoinPathsError;
168
169 pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
170     where I: Iterator<Item=T>, T: AsRef<OsStr>
171 {
172     let mut joined = Vec::new();
173     let sep = b':';
174
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)
180         }
181         joined.extend_from_slice(path);
182     }
183     Ok(OsStringExt::from_vec(joined))
184 }
185
186 impl fmt::Display for JoinPathsError {
187     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
188         "path segment contains separator `:`".fmt(f)
189     }
190 }
191
192 impl StdError for JoinPathsError {
193     fn description(&self) -> &str { "failed to join paths" }
194 }
195
196 #[cfg(target_os = "freebsd")]
197 pub fn current_exe() -> io::Result<PathBuf> {
198     unsafe {
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,
202                        -1 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))?;
207         if sz == 0 {
208             return Err(io::Error::last_os_error())
209         }
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))?;
214         if sz == 0 {
215             return Err(io::Error::last_os_error());
216         }
217         v.set_len(sz as usize - 1); // chop off trailing NUL
218         Ok(PathBuf::from(OsString::from_vec(v)))
219     }
220 }
221
222 #[cfg(target_os = "dragonfly")]
223 pub fn current_exe() -> io::Result<PathBuf> {
224     ::fs::read_link("/proc/curproc/file")
225 }
226
227 #[cfg(target_os = "netbsd")]
228 pub fn current_exe() -> io::Result<PathBuf> {
229     ::fs::read_link("/proc/curproc/exe")
230 }
231
232 #[cfg(any(target_os = "bitrig", target_os = "openbsd"))]
233 pub fn current_exe() -> io::Result<PathBuf> {
234     unsafe {
235         let mut mib = [libc::CTL_KERN,
236                        libc::KERN_PROC_ARGS,
237                        libc::getpid(),
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"))
250         }
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))
254         } else {
255             Ok(PathBuf::from(OsStr::from_bytes(argv0)))
256         }
257     }
258 }
259
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")
263 }
264
265 #[cfg(any(target_os = "macos", target_os = "ios"))]
266 pub fn current_exe() -> io::Result<PathBuf> {
267     extern {
268         fn _NSGetExecutablePath(buf: *mut libc::c_char,
269                                 bufsize: *mut u32) -> libc::c_int;
270     }
271     unsafe {
272         let mut sz: u32 = 0;
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)))
280     }
281 }
282
283 #[cfg(any(target_os = "solaris"))]
284 pub fn current_exe() -> io::Result<PathBuf> {
285     extern {
286         fn getexecname() -> *const c_char;
287     }
288     unsafe {
289         let path = getexecname();
290         if path.is_null() {
291             Err(io::Error::last_os_error())
292         } else {
293             let filename = CStr::from_ptr(path).to_bytes();
294             let path = PathBuf::from(<OsStr as OsStrExt>::from_bytes(filename));
295
296             // Prepend a current working directory to the path if
297             // it doesn't contain an absolute pathname.
298             if filename[0] == b'/' {
299                 Ok(path)
300             } else {
301                 getcwd().map(|cwd| cwd.join(path))
302             }
303         }
304     }
305 }
306
307 #[cfg(target_os = "haiku")]
308 pub fn current_exe() -> io::Result<PathBuf> {
309     // Use Haiku's image info functions
310     #[repr(C)]
311     struct image_info {
312         id: i32,
313         type_: i32,
314         sequence: i32,
315         init_order: i32,
316         init_routine: *mut libc::c_void,    // function pointer
317         term_routine: *mut libc::c_void,    // function pointer
318         device: libc::dev_t,
319         node: libc::ino_t,
320         name: [libc::c_char; 1024],         // MAXPATHLEN
321         text: *mut libc::c_void,
322         data: *mut libc::c_void,
323         text_size: i32,
324         data_size: i32,
325         api_version: i32,
326         abi: i32,
327     }
328
329     unsafe {
330         extern {
331             fn _get_next_image_info(team_id: i32, cookie: *mut i32,
332                 info: *mut image_info, size: i32) -> i32;
333         }
334
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);
340         if result != 0 {
341             use io::ErrorKind;
342             Err(io::Error::new(ErrorKind::Other, "Error getting executable path"))
343         } else {
344             let name = CStr::from_ptr(info.name.as_ptr()).to_bytes();
345             Ok(PathBuf::from(OsStr::from_bytes(name)))
346         }
347     }
348 }
349
350 pub struct Args {
351     iter: vec::IntoIter<OsString>,
352     _dont_send_or_sync_me: PhantomData<*mut ()>,
353 }
354
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() }
359 }
360
361 impl ExactSizeIterator for Args {
362     fn len(&self) -> usize { self.iter.len() }
363 }
364
365 impl DoubleEndedIterator for Args {
366     fn next_back(&mut self) -> Option<OsString> { self.iter.next_back() }
367 }
368
369 /// Returns the command line arguments
370 ///
371 /// Returns a list of the command line arguments.
372 #[cfg(target_os = "macos")]
373 pub fn args() -> Args {
374     extern {
375         // These functions are in crt_externs.h.
376         fn _NSGetArgc() -> *mut c_int;
377         fn _NSGetArgv() -> *mut *mut *mut c_char;
378     }
379
380     let vec = unsafe {
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<_>>()
387     };
388     Args {
389         iter: vec.into_iter(),
390         _dont_send_or_sync_me: PhantomData,
391     }
392 }
393
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
398 // runtime
399 //
400 // In general it looks like:
401 // res = Vec::new()
402 // let args = [[NSProcessInfo processInfo] arguments]
403 // for i in (0..[args count])
404 //      res.push([args objectAtIndex:i])
405 // res
406 #[cfg(target_os = "ios")]
407 pub fn args() -> Args {
408     use mem;
409
410     extern {
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;
414     }
415
416     #[link(name = "Foundation", kind = "framework")]
417     #[link(name = "objc")]
418     #[cfg(not(cargobuild))]
419     extern {}
420
421     type Sel = *const libc::c_void;
422     type NsId = *const libc::c_void;
423
424     let mut res = Vec::new();
425
426     unsafe {
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());
432
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);
436
437         let cnt: usize = mem::transmute(objc_msgSend(args, count_sel));
438         for i in 0..cnt {
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()))
444         }
445     }
446
447     Args { iter: res.into_iter(), _dont_send_or_sync_me: PhantomData }
448 }
449
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",
458           target_os = "nacl",
459           target_os = "emscripten",
460           target_os = "haiku"))]
461 pub fn args() -> Args {
462     use sys_common;
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)
466     }).collect();
467     Args { iter: v.into_iter(), _dont_send_or_sync_me: PhantomData }
468 }
469
470 pub struct Env {
471     iter: vec::IntoIter<(OsString, OsString)>,
472     _dont_send_or_sync_me: PhantomData<*mut ()>,
473 }
474
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() }
479 }
480
481 #[cfg(target_os = "macos")]
482 pub unsafe fn environ() -> *mut *const *const c_char {
483     extern { fn _NSGetEnviron() -> *mut *const *const c_char; }
484     _NSGetEnviron()
485 }
486
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; }
490     &mut environ
491 }
492
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 {
496     unsafe {
497         ENV_LOCK.lock();
498         let mut environ = *environ();
499         if environ == ptr::null() {
500             ENV_LOCK.unlock();
501             panic!("os::env() failure getting env string from OS: {}",
502                    io::Error::last_os_error());
503         }
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);
508             }
509             environ = environ.offset(1);
510         }
511         let ret = Env {
512             iter: result.into_iter(),
513             _dont_send_or_sync_me: PhantomData,
514         };
515         ENV_LOCK.unlock();
516         return ret
517     }
518
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
523         // malformed lines.
524         if input.is_empty() {
525             return None;
526         }
527         let pos = memchr::memchr(b'=', &input[1..]).map(|p| p + 1);
528         pos.map(|p| (
529             OsStringExt::from_vec(input[..p].to_vec()),
530             OsStringExt::from_vec(input[p+1..].to_vec()),
531         ))
532     }
533 }
534
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())?;
539     unsafe {
540         ENV_LOCK.lock();
541         let s = libc::getenv(k.as_ptr()) as *const _;
542         let ret = if s.is_null() {
543             None
544         } else {
545             Some(OsStringExt::from_vec(CStr::from_ptr(s).to_bytes().to_vec()))
546         };
547         ENV_LOCK.unlock();
548         return Ok(ret)
549     }
550 }
551
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())?;
555
556     unsafe {
557         ENV_LOCK.lock();
558         let ret = cvt(libc::setenv(k.as_ptr(), v.as_ptr(), 1)).map(|_| ());
559         ENV_LOCK.unlock();
560         return ret
561     }
562 }
563
564 pub fn unsetenv(n: &OsStr) -> io::Result<()> {
565     let nbuf = CString::new(n.as_bytes())?;
566
567     unsafe {
568         ENV_LOCK.lock();
569         let ret = cvt(libc::unsetenv(nbuf.as_ptr())).map(|_| ());
570         ENV_LOCK.unlock();
571         return ret
572     }
573 }
574
575 pub fn page_size() -> usize {
576     unsafe {
577         libc::sysconf(libc::_SC_PAGESIZE) as usize
578     }
579 }
580
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")
585         } else {
586             PathBuf::from("/tmp")
587         }
588     })
589 }
590
591 pub fn home_dir() -> Option<PathBuf> {
592     return ::env::var_os("HOME").or_else(|| unsafe {
593         fallback()
594     }).map(PathBuf::from);
595
596     #[cfg(any(target_os = "android",
597               target_os = "ios",
598               target_os = "nacl",
599               target_os = "emscripten"))]
600     unsafe fn fallback() -> Option<OsString> { None }
601     #[cfg(not(any(target_os = "android",
602                   target_os = "ios",
603                   target_os = "nacl",
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,
612                                    &mut result) {
613                 0 if !result.is_null() => Some(()),
614                 _ => None
615             }
616         }
617
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(()) }
626         }
627
628         let amt = match libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) {
629             n if n < 0 => 512 as usize,
630             n => n as usize,
631         };
632         let mut buf = Vec::with_capacity(amt);
633         let mut passwd: libc::passwd = mem::zeroed();
634
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))
639         } else {
640             None
641         }
642     }
643 }
644
645 pub fn exit(code: i32) -> ! {
646     unsafe { libc::exit(code as c_int) }
647 }