]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/os.rs
unbreak openbsd build after 1860ee52
[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 use prelude::v1::*;
14 use os::unix::*;
15
16 use error::Error as StdError;
17 use ffi::{CString, CStr, OsString, OsStr, AsOsStr};
18 use fmt;
19 use iter;
20 use libc::{self, c_int, c_char, c_void};
21 use mem;
22 use io;
23 use old_io::{IoResult, IoError, fs};
24 use ptr;
25 use slice;
26 use str;
27 use sys::c;
28 use sys::fd;
29 use sys::fs::FileDesc;
30 use vec;
31
32 const BUF_BYTES: usize = 2048;
33 const TMPBUF_SZ: usize = 128;
34
35 /// Returns the platform-specific value of errno
36 pub fn errno() -> i32 {
37     #[cfg(any(target_os = "macos",
38               target_os = "ios",
39               target_os = "freebsd"))]
40     unsafe fn errno_location() -> *const c_int {
41         extern { fn __error() -> *const c_int; }
42         __error()
43     }
44
45     #[cfg(target_os = "dragonfly")]
46     unsafe fn errno_location() -> *const c_int {
47         extern { fn __dfly_error() -> *const c_int; }
48         __dfly_error()
49     }
50
51     #[cfg(target_os = "openbsd")]
52     unsafe fn errno_location() -> *const c_int {
53         extern { fn __errno() -> *const c_int; }
54         __errno()
55     }
56
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; }
60         __errno_location()
61     }
62
63     unsafe {
64         (*errno_location()) as i32
65     }
66 }
67
68 /// Get a detailed string description for the given error number
69 pub fn error_string(errno: i32) -> String {
70     #[cfg(target_os = "linux")]
71     extern {
72         #[link_name = "__xpg_strerror_r"]
73         fn strerror_r(errnum: c_int, buf: *mut c_char,
74                       buflen: libc::size_t) -> c_int;
75     }
76     #[cfg(not(target_os = "linux"))]
77     extern {
78         fn strerror_r(errnum: c_int, buf: *mut c_char,
79                       buflen: libc::size_t) -> c_int;
80     }
81
82     let mut buf = [0 as c_char; TMPBUF_SZ];
83
84     let p = buf.as_mut_ptr();
85     unsafe {
86         if strerror_r(errno as c_int, p, buf.len() as libc::size_t) < 0 {
87             panic!("strerror_r failure");
88         }
89
90         let p = p as *const _;
91         str::from_utf8(CStr::from_ptr(p).to_bytes()).unwrap().to_string()
92     }
93 }
94
95 pub fn getcwd() -> IoResult<Path> {
96     let mut buf = [0 as c_char; BUF_BYTES];
97     unsafe {
98         if libc::getcwd(buf.as_mut_ptr(), buf.len() as libc::size_t).is_null() {
99             Err(IoError::last_error())
100         } else {
101             Ok(Path::new(CStr::from_ptr(buf.as_ptr()).to_bytes()))
102         }
103     }
104 }
105
106 pub fn chdir(p: &Path) -> IoResult<()> {
107     let p = CString::new(p.as_vec()).unwrap();
108     unsafe {
109         match libc::chdir(p.as_ptr()) == (0 as c_int) {
110             true => Ok(()),
111             false => Err(IoError::last_error()),
112         }
113     }
114 }
115
116 pub struct SplitPaths<'a> {
117     iter: iter::Map<slice::Split<'a, u8, fn(&u8) -> bool>,
118                     fn(&'a [u8]) -> Path>,
119 }
120
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();
124     SplitPaths {
125         iter: unparsed.split(is_colon as fn(&u8) -> bool)
126                       .map(Path::new as fn(&'a [u8]) ->  Path)
127     }
128 }
129
130 impl<'a> Iterator for SplitPaths<'a> {
131     type Item = Path;
132     fn next(&mut self) -> Option<Path> { self.iter.next() }
133     fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
134 }
135
136 #[derive(Debug)]
137 pub struct JoinPathsError;
138
139 pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
140     where I: Iterator<Item=T>, T: AsOsStr
141 {
142     let mut joined = Vec::new();
143     let sep = b':';
144
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)
150         }
151         joined.push_all(path);
152     }
153     Ok(OsStringExt::from_vec(joined))
154 }
155
156 impl fmt::Display for JoinPathsError {
157     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
158         "path segment contains separator `:`".fmt(f)
159     }
160 }
161
162 impl StdError for JoinPathsError {
163     fn description(&self) -> &str { "failed to join paths" }
164 }
165
166 #[cfg(target_os = "freebsd")]
167 pub fn current_exe() -> IoResult<Path> {
168     unsafe {
169         use libc::funcs::bsd44::*;
170         use libc::consts::os::extra::*;
171         let mut mib = vec![CTL_KERN as c_int,
172                            KERN_PROC as c_int,
173                            KERN_PROC_PATHNAME as c_int,
174                            -1 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(),
178                          0 as libc::size_t);
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
188         Ok(Path::new(v))
189     }
190 }
191
192 #[cfg(target_os = "dragonfly")]
193 pub fn current_exe() -> IoResult<Path> {
194     fs::readlink(&Path::new("/proc/curproc/file"))
195 }
196
197 #[cfg(target_os = "openbsd")]
198 pub fn current_exe() -> IoResult<Path> {
199     use sync::{StaticMutex, MUTEX_INIT};
200
201     static LOCK: StaticMutex = MUTEX_INIT;
202
203     extern {
204         fn rust_current_exe() -> *const c_char;
205     }
206
207     let _guard = LOCK.lock();
208
209     unsafe {
210         let v = rust_current_exe();
211         if v.is_null() {
212             Err(IoError::last_error())
213         } else {
214             Ok(Path::new(CStr::from_ptr(v).to_bytes().to_vec()))
215         }
216     }
217 }
218
219 #[cfg(any(target_os = "linux", target_os = "android"))]
220 pub fn current_exe() -> IoResult<Path> {
221     fs::readlink(&Path::new("/proc/self/exe"))
222 }
223
224 #[cfg(any(target_os = "macos", target_os = "ios"))]
225 pub fn current_exe() -> IoResult<Path> {
226     unsafe {
227         use libc::funcs::extra::_NSGetExecutablePath;
228         let mut sz: u32 = 0;
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
235         Ok(Path::new(v))
236     }
237 }
238
239 pub struct Args {
240     iter: vec::IntoIter<OsString>,
241     _dont_send_or_sync_me: *mut (),
242 }
243
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() }
248 }
249
250 impl ExactSizeIterator for Args {
251     fn len(&self) -> usize { self.iter.len() }
252 }
253
254 /// Returns the command line arguments
255 ///
256 /// Returns a list of the command line arguments.
257 #[cfg(target_os = "macos")]
258 pub fn args() -> Args {
259     extern {
260         // These functions are in crt_externs.h.
261         fn _NSGetArgc() -> *mut c_int;
262         fn _NSGetArgv() -> *mut *mut *mut c_char;
263     }
264
265     let vec = unsafe {
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<_>>()
272     };
273     Args {
274         iter: vec.into_iter(),
275         _dont_send_or_sync_me: 0 as *mut (),
276     }
277 }
278
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
283 // runtime
284 //
285 // In general it looks like:
286 // res = Vec::new()
287 // let args = [[NSProcessInfo processInfo] arguments]
288 // for i in range(0, [args count])
289 //      res.push([args objectAtIndex:i])
290 // res
291 #[cfg(target_os = "ios")]
292 pub fn args() -> Args {
293     use iter::range;
294     use mem;
295
296     #[link(name = "objc")]
297     extern {
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;
301     }
302
303     #[link(name = "Foundation", kind = "framework")]
304     extern {}
305
306     type Sel = *const libc::c_void;
307     type NsId = *const libc::c_void;
308
309     let mut res = Vec::new();
310
311     unsafe {
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());
317
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);
321
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()))
329         }
330     }
331
332     Args { iter: res.into_iter(), _dont_send_or_sync_me: 0 as *mut _ }
333 }
334
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 {
341     use rt;
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)
345     }).collect();
346     Args { iter: v.into_iter(), _dont_send_or_sync_me: 0 as *mut _ }
347 }
348
349 pub struct Env {
350     iter: vec::IntoIter<(OsString, OsString)>,
351     _dont_send_or_sync_me: *mut (),
352 }
353
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() }
358 }
359
360 #[cfg(target_os = "macos")]
361 pub unsafe fn environ() -> *mut *const *const c_char {
362     extern { fn _NSGetEnviron() -> *mut *const *const c_char; }
363     _NSGetEnviron()
364 }
365
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; }
369     &mut environ
370 }
371
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 {
375     return unsafe {
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());
380         }
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);
385         }
386         Env { iter: result.into_iter(), _dont_send_or_sync_me: 0 as *mut _ }
387     };
388
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))
395     }
396 }
397
398 pub fn getenv(k: &OsStr) -> Option<OsString> {
399     unsafe {
400         let s = k.to_cstring().unwrap();
401         let s = libc::getenv(s.as_ptr()) as *const _;
402         if s.is_null() {
403             None
404         } else {
405             Some(OsStringExt::from_vec(CStr::from_ptr(s).to_bytes().to_vec()))
406         }
407     }
408 }
409
410 pub fn setenv(k: &OsStr, v: &OsStr) {
411     unsafe {
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());
416         }
417     }
418 }
419
420 pub fn unsetenv(n: &OsStr) {
421     unsafe {
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());
425         }
426     }
427 }
428
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)))
433     } else {
434         Err(IoError::last_error())
435     }
436 }
437
438 pub fn page_size() -> usize {
439     unsafe {
440         libc::sysconf(libc::_SC_PAGESIZE) as usize
441     }
442 }
443
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")
448         } else {
449             Path::new("/tmp")
450         }
451     })
452 }
453
454 pub fn home_dir() -> Option<Path> {
455     return getenv("HOME".as_os_str()).or_else(|| unsafe {
456         fallback()
457     }).map(|os| {
458         Path::new(os.into_vec())
459     });
460
461     #[cfg(any(target_os = "android",
462               target_os = "ios"))]
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,
469             n => n as usize,
470         };
471         let me = libc::getuid();
472         loop {
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,
478                                 &mut result) {
479                 0 if !result.is_null() => {}
480                 _ => return None
481             }
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))
485         }
486     }
487 }