]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/os.rs
unbreak bitrig/openbsd build after 8389253d
[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 prelude::v1::*;
16 use os::unix::prelude::*;
17
18 use error::Error as StdError;
19 use ffi::{CString, CStr, OsString, OsStr, AsOsStr};
20 use fmt;
21 use io;
22 use iter;
23 use libc::{self, c_int, c_char, c_void};
24 use mem;
25 #[allow(deprecated)] use old_io::{IoError, IoResult};
26 use ptr;
27 use path::{self, PathBuf};
28 use slice;
29 use str;
30 use sys::c;
31 use sys::fd;
32 use sys::fs::FileDesc;
33 use vec;
34
35 const BUF_BYTES: usize = 2048;
36 const TMPBUF_SZ: usize = 128;
37
38 fn bytes2path(b: &[u8]) -> PathBuf {
39     PathBuf::from(<OsStr as OsStrExt>::from_bytes(b))
40 }
41
42 fn os2path(os: OsString) -> PathBuf {
43     bytes2path(os.as_bytes())
44 }
45
46 /// Returns the platform-specific value of errno
47 pub fn errno() -> i32 {
48     #[cfg(any(target_os = "macos",
49               target_os = "ios",
50               target_os = "freebsd"))]
51     unsafe fn errno_location() -> *const c_int {
52         extern { fn __error() -> *const c_int; }
53         __error()
54     }
55
56     #[cfg(target_os = "bitrig")]
57     fn errno_location() -> *const c_int {
58         extern {
59             fn __errno() -> *const c_int;
60         }
61         unsafe {
62             __errno()
63         }
64     }
65
66     #[cfg(target_os = "dragonfly")]
67     unsafe fn errno_location() -> *const c_int {
68         extern { fn __dfly_error() -> *const c_int; }
69         __dfly_error()
70     }
71
72     #[cfg(target_os = "openbsd")]
73     unsafe fn errno_location() -> *const c_int {
74         extern { fn __errno() -> *const c_int; }
75         __errno()
76     }
77
78     #[cfg(any(target_os = "linux", target_os = "android"))]
79     unsafe fn errno_location() -> *const c_int {
80         extern { fn __errno_location() -> *const c_int; }
81         __errno_location()
82     }
83
84     unsafe {
85         (*errno_location()) as i32
86     }
87 }
88
89 /// Get a detailed string description for the given error number
90 pub fn error_string(errno: i32) -> String {
91     #[cfg(target_os = "linux")]
92     extern {
93         #[link_name = "__xpg_strerror_r"]
94         fn strerror_r(errnum: c_int, buf: *mut c_char,
95                       buflen: libc::size_t) -> c_int;
96     }
97     #[cfg(not(target_os = "linux"))]
98     extern {
99         fn strerror_r(errnum: c_int, buf: *mut c_char,
100                       buflen: libc::size_t) -> c_int;
101     }
102
103     let mut buf = [0 as c_char; TMPBUF_SZ];
104
105     let p = buf.as_mut_ptr();
106     unsafe {
107         if strerror_r(errno as c_int, p, buf.len() as libc::size_t) < 0 {
108             panic!("strerror_r failure");
109         }
110
111         let p = p as *const _;
112         str::from_utf8(CStr::from_ptr(p).to_bytes()).unwrap().to_string()
113     }
114 }
115
116 pub fn getcwd() -> io::Result<PathBuf> {
117     let mut buf = [0 as c_char; BUF_BYTES];
118     unsafe {
119         if libc::getcwd(buf.as_mut_ptr(), buf.len() as libc::size_t).is_null() {
120             Err(io::Error::last_os_error())
121         } else {
122             Ok(bytes2path(CStr::from_ptr(buf.as_ptr()).to_bytes()))
123         }
124     }
125 }
126
127 pub fn chdir(p: &path::Path) -> io::Result<()> {
128     let p = try!(CString::new(p.as_os_str().as_bytes()));
129     unsafe {
130         match libc::chdir(p.as_ptr()) == (0 as c_int) {
131             true => Ok(()),
132             false => Err(io::Error::last_os_error()),
133         }
134     }
135 }
136
137 pub struct SplitPaths<'a> {
138     iter: iter::Map<slice::Split<'a, u8, fn(&u8) -> bool>,
139                     fn(&'a [u8]) -> PathBuf>,
140 }
141
142 pub fn split_paths<'a>(unparsed: &'a OsStr) -> SplitPaths<'a> {
143     fn is_colon(b: &u8) -> bool { *b == b':' }
144     let unparsed = unparsed.as_bytes();
145     SplitPaths {
146         iter: unparsed.split(is_colon as fn(&u8) -> bool)
147                       .map(bytes2path as fn(&'a [u8]) -> PathBuf)
148     }
149 }
150
151 impl<'a> Iterator for SplitPaths<'a> {
152     type Item = PathBuf;
153     fn next(&mut self) -> Option<PathBuf> { self.iter.next() }
154     fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
155 }
156
157 #[derive(Debug)]
158 pub struct JoinPathsError;
159
160 pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
161     where I: Iterator<Item=T>, T: AsOsStr
162 {
163     let mut joined = Vec::new();
164     let sep = b':';
165
166     for (i, path) in paths.enumerate() {
167         let path = path.as_os_str().as_bytes();
168         if i > 0 { joined.push(sep) }
169         if path.contains(&sep) {
170             return Err(JoinPathsError)
171         }
172         joined.push_all(path);
173     }
174     Ok(OsStringExt::from_vec(joined))
175 }
176
177 impl fmt::Display for JoinPathsError {
178     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
179         "path segment contains separator `:`".fmt(f)
180     }
181 }
182
183 impl StdError for JoinPathsError {
184     fn description(&self) -> &str { "failed to join paths" }
185 }
186
187 #[cfg(target_os = "freebsd")]
188 pub fn current_exe() -> io::Result<PathBuf> {
189     unsafe {
190         use libc::funcs::bsd44::*;
191         use libc::consts::os::extra::*;
192         let mut mib = vec![CTL_KERN as c_int,
193                            KERN_PROC as c_int,
194                            KERN_PROC_PATHNAME as c_int,
195                            -1 as c_int];
196         let mut sz: libc::size_t = 0;
197         let err = sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
198                          ptr::null_mut(), &mut sz, ptr::null_mut(),
199                          0 as libc::size_t);
200         if err != 0 { return Err(io::Error::last_os_error()); }
201         if sz == 0 { return Err(io::Error::last_os_error()); }
202         let mut v: Vec<u8> = Vec::with_capacity(sz as uint);
203         let err = sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
204                          v.as_mut_ptr() as *mut libc::c_void, &mut sz,
205                          ptr::null_mut(), 0 as libc::size_t);
206         if err != 0 { return Err(io::Error::last_os_error()); }
207         if sz == 0 { return Err(io::Error::last_os_error()); }
208         v.set_len(sz as uint - 1); // chop off trailing NUL
209         Ok(PathBuf::from(OsString::from_vec(v)))
210     }
211 }
212
213 #[cfg(target_os = "dragonfly")]
214 pub fn current_exe() -> io::Result<PathBuf> {
215     ::fs::read_link("/proc/curproc/file")
216 }
217
218 #[cfg(any(target_os = "bitrig", target_os = "openbsd"))]
219 pub fn current_exe() -> io::Result<PathBuf> {
220     use sync::{StaticMutex, MUTEX_INIT};
221     static LOCK: StaticMutex = MUTEX_INIT;
222
223     extern {
224         fn rust_current_exe() -> *const c_char;
225     }
226
227     let _guard = LOCK.lock();
228
229     unsafe {
230         let v = rust_current_exe();
231         if v.is_null() {
232             Err(io::Error::last_os_error())
233         } else {
234             let vec = CStr::from_ptr(v).to_bytes().to_vec();
235             Ok(PathBuf::from(OsString::from_vec(vec)))
236         }
237     }
238 }
239
240 #[cfg(any(target_os = "linux", target_os = "android"))]
241 pub fn current_exe() -> io::Result<PathBuf> {
242     ::fs::read_link("/proc/self/exe")
243 }
244
245 #[cfg(any(target_os = "macos", target_os = "ios"))]
246 pub fn current_exe() -> io::Result<PathBuf> {
247     unsafe {
248         use libc::funcs::extra::_NSGetExecutablePath;
249         let mut sz: u32 = 0;
250         _NSGetExecutablePath(ptr::null_mut(), &mut sz);
251         if sz == 0 { return Err(io::Error::last_os_error()); }
252         let mut v: Vec<u8> = Vec::with_capacity(sz as uint);
253         let err = _NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz);
254         if err != 0 { return Err(io::Error::last_os_error()); }
255         v.set_len(sz as uint - 1); // chop off trailing NUL
256         Ok(PathBuf::from(OsString::from_vec(v)))
257     }
258 }
259
260 pub struct Args {
261     iter: vec::IntoIter<OsString>,
262     _dont_send_or_sync_me: *mut (),
263 }
264
265 impl Iterator for Args {
266     type Item = OsString;
267     fn next(&mut self) -> Option<OsString> { self.iter.next() }
268     fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
269 }
270
271 impl ExactSizeIterator for Args {
272     fn len(&self) -> usize { self.iter.len() }
273 }
274
275 /// Returns the command line arguments
276 ///
277 /// Returns a list of the command line arguments.
278 #[cfg(target_os = "macos")]
279 pub fn args() -> Args {
280     extern {
281         // These functions are in crt_externs.h.
282         fn _NSGetArgc() -> *mut c_int;
283         fn _NSGetArgv() -> *mut *mut *mut c_char;
284     }
285
286     let vec = unsafe {
287         let (argc, argv) = (*_NSGetArgc() as isize,
288                             *_NSGetArgv() as *const *const c_char);
289         (0.. argc as isize).map(|i| {
290             let bytes = CStr::from_ptr(*argv.offset(i)).to_bytes().to_vec();
291             OsStringExt::from_vec(bytes)
292         }).collect::<Vec<_>>()
293     };
294     Args {
295         iter: vec.into_iter(),
296         _dont_send_or_sync_me: 0 as *mut (),
297     }
298 }
299
300 // As _NSGetArgc and _NSGetArgv aren't mentioned in iOS docs
301 // and use underscores in their names - they're most probably
302 // are considered private and therefore should be avoided
303 // Here is another way to get arguments using Objective C
304 // runtime
305 //
306 // In general it looks like:
307 // res = Vec::new()
308 // let args = [[NSProcessInfo processInfo] arguments]
309 // for i in (0..[args count])
310 //      res.push([args objectAtIndex:i])
311 // res
312 #[cfg(target_os = "ios")]
313 pub fn args() -> Args {
314     use mem;
315
316     #[link(name = "objc")]
317     extern {
318         fn sel_registerName(name: *const libc::c_uchar) -> Sel;
319         fn objc_msgSend(obj: NsId, sel: Sel, ...) -> NsId;
320         fn objc_getClass(class_name: *const libc::c_uchar) -> NsId;
321     }
322
323     #[link(name = "Foundation", kind = "framework")]
324     extern {}
325
326     type Sel = *const libc::c_void;
327     type NsId = *const libc::c_void;
328
329     let mut res = Vec::new();
330
331     unsafe {
332         let process_info_sel = sel_registerName("processInfo\0".as_ptr());
333         let arguments_sel = sel_registerName("arguments\0".as_ptr());
334         let utf8_sel = sel_registerName("UTF8String\0".as_ptr());
335         let count_sel = sel_registerName("count\0".as_ptr());
336         let object_at_sel = sel_registerName("objectAtIndex:\0".as_ptr());
337
338         let klass = objc_getClass("NSProcessInfo\0".as_ptr());
339         let info = objc_msgSend(klass, process_info_sel);
340         let args = objc_msgSend(info, arguments_sel);
341
342         let cnt: int = mem::transmute(objc_msgSend(args, count_sel));
343         for i in (0..cnt) {
344             let tmp = objc_msgSend(args, object_at_sel, i);
345             let utf_c_str: *const libc::c_char =
346                 mem::transmute(objc_msgSend(tmp, utf8_sel));
347             let bytes = CStr::from_ptr(utf_c_str).to_bytes();
348             res.push(OsString::from_str(str::from_utf8(bytes).unwrap()))
349         }
350     }
351
352     Args { iter: res.into_iter(), _dont_send_or_sync_me: 0 as *mut _ }
353 }
354
355 #[cfg(any(target_os = "linux",
356           target_os = "android",
357           target_os = "freebsd",
358           target_os = "dragonfly",
359           target_os = "bitrig",
360           target_os = "openbsd"))]
361 pub fn args() -> Args {
362     use rt;
363     let bytes = rt::args::clone().unwrap_or(Vec::new());
364     let v: Vec<OsString> = bytes.into_iter().map(|v| {
365         OsStringExt::from_vec(v)
366     }).collect();
367     Args { iter: v.into_iter(), _dont_send_or_sync_me: 0 as *mut _ }
368 }
369
370 pub struct Env {
371     iter: vec::IntoIter<(OsString, OsString)>,
372     _dont_send_or_sync_me: *mut (),
373 }
374
375 impl Iterator for Env {
376     type Item = (OsString, OsString);
377     fn next(&mut self) -> Option<(OsString, OsString)> { self.iter.next() }
378     fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
379 }
380
381 #[cfg(target_os = "macos")]
382 pub unsafe fn environ() -> *mut *const *const c_char {
383     extern { fn _NSGetEnviron() -> *mut *const *const c_char; }
384     _NSGetEnviron()
385 }
386
387 #[cfg(not(target_os = "macos"))]
388 pub unsafe fn environ() -> *mut *const *const c_char {
389     extern { static mut environ: *const *const c_char; }
390     &mut environ
391 }
392
393 /// Returns a vector of (variable, value) byte-vector pairs for all the
394 /// environment variables of the current process.
395 pub fn env() -> Env {
396     return unsafe {
397         let mut environ = *environ();
398         if environ as usize == 0 {
399             panic!("os::env() failure getting env string from OS: {}",
400                    io::Error::last_os_error());
401         }
402         let mut result = Vec::new();
403         while *environ != ptr::null() {
404             result.push(parse(CStr::from_ptr(*environ).to_bytes()));
405             environ = environ.offset(1);
406         }
407         Env { iter: result.into_iter(), _dont_send_or_sync_me: 0 as *mut _ }
408     };
409
410     fn parse(input: &[u8]) -> (OsString, OsString) {
411         let mut it = input.splitn(1, |b| *b == b'=');
412         let key = it.next().unwrap().to_vec();
413         let default: &[u8] = &[];
414         let val = it.next().unwrap_or(default).to_vec();
415         (OsStringExt::from_vec(key), OsStringExt::from_vec(val))
416     }
417 }
418
419 pub fn getenv(k: &OsStr) -> Option<OsString> {
420     unsafe {
421         let s = k.to_cstring().unwrap();
422         let s = libc::getenv(s.as_ptr()) as *const _;
423         if s.is_null() {
424             None
425         } else {
426             Some(OsStringExt::from_vec(CStr::from_ptr(s).to_bytes().to_vec()))
427         }
428     }
429 }
430
431 pub fn setenv(k: &OsStr, v: &OsStr) {
432     unsafe {
433         let k = k.to_cstring().unwrap();
434         let v = v.to_cstring().unwrap();
435         if libc::funcs::posix01::unistd::setenv(k.as_ptr(), v.as_ptr(), 1) != 0 {
436             panic!("failed setenv: {}", io::Error::last_os_error());
437         }
438     }
439 }
440
441 pub fn unsetenv(n: &OsStr) {
442     unsafe {
443         let nbuf = n.to_cstring().unwrap();
444         if libc::funcs::posix01::unistd::unsetenv(nbuf.as_ptr()) != 0 {
445             panic!("failed unsetenv: {}", io::Error::last_os_error());
446         }
447     }
448 }
449
450 #[allow(deprecated)]
451 pub unsafe fn pipe() -> IoResult<(FileDesc, FileDesc)> {
452     let mut fds = [0; 2];
453     if libc::pipe(fds.as_mut_ptr()) == 0 {
454         Ok((FileDesc::new(fds[0], true), FileDesc::new(fds[1], true)))
455     } else {
456         Err(IoError::last_error())
457     }
458 }
459
460 pub fn page_size() -> usize {
461     unsafe {
462         libc::sysconf(libc::_SC_PAGESIZE) as usize
463     }
464 }
465
466 pub fn temp_dir() -> PathBuf {
467     getenv("TMPDIR".as_os_str()).map(os2path).unwrap_or_else(|| {
468         if cfg!(target_os = "android") {
469             PathBuf::from("/data/local/tmp")
470         } else {
471             PathBuf::from("/tmp")
472         }
473     })
474 }
475
476 pub fn home_dir() -> Option<PathBuf> {
477     return getenv("HOME".as_os_str()).or_else(|| unsafe {
478         fallback()
479     }).map(os2path);
480
481     #[cfg(any(target_os = "android",
482               target_os = "ios"))]
483     unsafe fn fallback() -> Option<OsString> { None }
484     #[cfg(not(any(target_os = "android",
485                   target_os = "ios")))]
486     unsafe fn fallback() -> Option<OsString> {
487         let amt = match libc::sysconf(c::_SC_GETPW_R_SIZE_MAX) {
488             n if n < 0 => 512 as usize,
489             n => n as usize,
490         };
491         let me = libc::getuid();
492         loop {
493             let mut buf = Vec::with_capacity(amt);
494             let mut passwd: c::passwd = mem::zeroed();
495             let mut result = 0 as *mut _;
496             match c::getpwuid_r(me, &mut passwd, buf.as_mut_ptr(),
497                                 buf.capacity() as libc::size_t,
498                                 &mut result) {
499                 0 if !result.is_null() => {}
500                 _ => return None
501             }
502             let ptr = passwd.pw_dir as *const _;
503             let bytes = CStr::from_ptr(ptr).to_bytes().to_vec();
504             return Some(OsStringExt::from_vec(bytes))
505         }
506     }
507 }