]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/os.rs
DoubleEndedIterator for Args
[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};
20 use fmt;
21 use io;
22 use iter;
23 use libc::{self, c_int, c_char, c_void};
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 /// Returns the platform-specific value of errno
39 #[cfg(not(target_os = "dragonfly"))]
40 pub fn errno() -> i32 {
41     extern {
42         #[cfg_attr(any(target_os = "linux", target_os = "emscripten"),
43                    link_name = "__errno_location")]
44         #[cfg_attr(any(target_os = "bitrig",
45                        target_os = "netbsd",
46                        target_os = "openbsd",
47                        target_os = "android",
48                        target_env = "newlib"),
49                    link_name = "__errno")]
50         #[cfg_attr(target_os = "solaris", link_name = "___errno")]
51         #[cfg_attr(any(target_os = "macos",
52                        target_os = "ios",
53                        target_os = "freebsd"),
54                    link_name = "__error")]
55         fn errno_location() -> *const c_int;
56     }
57
58     unsafe {
59         (*errno_location()) as i32
60     }
61 }
62
63 #[cfg(target_os = "dragonfly")]
64 pub fn errno() -> i32 {
65     extern {
66         #[thread_local]
67         static errno: c_int;
68     }
69
70     errno as i32
71 }
72
73 /// Gets a detailed string description for the given error number.
74 pub fn error_string(errno: i32) -> String {
75     extern {
76         #[cfg_attr(any(target_os = "linux", target_env = "newlib"),
77                    link_name = "__xpg_strerror_r")]
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_owned()
92     }
93 }
94
95 pub fn getcwd() -> io::Result<PathBuf> {
96     let mut buf = Vec::with_capacity(512);
97     loop {
98         unsafe {
99             let ptr = buf.as_mut_ptr() as *mut libc::c_char;
100             if !libc::getcwd(ptr, buf.capacity() as libc::size_t).is_null() {
101                 let len = CStr::from_ptr(buf.as_ptr() as *const libc::c_char).to_bytes().len();
102                 buf.set_len(len);
103                 buf.shrink_to_fit();
104                 return Ok(PathBuf::from(OsString::from_vec(buf)));
105             } else {
106                 let error = io::Error::last_os_error();
107                 if error.raw_os_error() != Some(libc::ERANGE) {
108                     return Err(error);
109                 }
110             }
111
112             // Trigger the internal buffer resizing logic of `Vec` by requiring
113             // more space than the current capacity.
114             let cap = buf.capacity();
115             buf.set_len(cap);
116             buf.reserve(1);
117         }
118     }
119 }
120
121 pub fn chdir(p: &path::Path) -> io::Result<()> {
122     let p: &OsStr = p.as_ref();
123     let p = CString::new(p.as_bytes())?;
124     unsafe {
125         match libc::chdir(p.as_ptr()) == (0 as c_int) {
126             true => Ok(()),
127             false => Err(io::Error::last_os_error()),
128         }
129     }
130 }
131
132 pub struct SplitPaths<'a> {
133     iter: iter::Map<slice::Split<'a, u8, fn(&u8) -> bool>,
134                     fn(&'a [u8]) -> PathBuf>,
135 }
136
137 pub fn split_paths(unparsed: &OsStr) -> SplitPaths {
138     fn bytes_to_path(b: &[u8]) -> PathBuf {
139         PathBuf::from(<OsStr as OsStrExt>::from_bytes(b))
140     }
141     fn is_colon(b: &u8) -> bool { *b == b':' }
142     let unparsed = unparsed.as_bytes();
143     SplitPaths {
144         iter: unparsed.split(is_colon as fn(&u8) -> bool)
145                       .map(bytes_to_path as fn(&[u8]) -> PathBuf)
146     }
147 }
148
149 impl<'a> Iterator for SplitPaths<'a> {
150     type Item = PathBuf;
151     fn next(&mut self) -> Option<PathBuf> { self.iter.next() }
152     fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
153 }
154
155 #[derive(Debug)]
156 pub struct JoinPathsError;
157
158 pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
159     where I: Iterator<Item=T>, T: AsRef<OsStr>
160 {
161     let mut joined = Vec::new();
162     let sep = b':';
163
164     for (i, path) in paths.enumerate() {
165         let path = path.as_ref().as_bytes();
166         if i > 0 { joined.push(sep) }
167         if path.contains(&sep) {
168             return Err(JoinPathsError)
169         }
170         joined.extend_from_slice(path);
171     }
172     Ok(OsStringExt::from_vec(joined))
173 }
174
175 impl fmt::Display for JoinPathsError {
176     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
177         "path segment contains separator `:`".fmt(f)
178     }
179 }
180
181 impl StdError for JoinPathsError {
182     fn description(&self) -> &str { "failed to join paths" }
183 }
184
185 #[cfg(target_os = "freebsd")]
186 pub fn current_exe() -> io::Result<PathBuf> {
187     unsafe {
188         let mut mib = [libc::CTL_KERN as c_int,
189                        libc::KERN_PROC as c_int,
190                        libc::KERN_PROC_PATHNAME as c_int,
191                        -1 as c_int];
192         let mut sz: libc::size_t = 0;
193         cvt(libc::sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
194                          ptr::null_mut(), &mut sz, ptr::null_mut(),
195                          0 as libc::size_t))?;
196         if sz == 0 {
197             return Err(io::Error::last_os_error())
198         }
199         let mut v: Vec<u8> = Vec::with_capacity(sz as usize);
200         cvt(libc::sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
201                          v.as_mut_ptr() as *mut libc::c_void, &mut sz,
202                          ptr::null_mut(), 0 as libc::size_t))?;
203         if sz == 0 {
204             return Err(io::Error::last_os_error());
205         }
206         v.set_len(sz as usize - 1); // chop off trailing NUL
207         Ok(PathBuf::from(OsString::from_vec(v)))
208     }
209 }
210
211 #[cfg(target_os = "dragonfly")]
212 pub fn current_exe() -> io::Result<PathBuf> {
213     ::fs::read_link("/proc/curproc/file")
214 }
215
216 #[cfg(target_os = "netbsd")]
217 pub fn current_exe() -> io::Result<PathBuf> {
218     ::fs::read_link("/proc/curproc/exe")
219 }
220
221 #[cfg(any(target_os = "bitrig", target_os = "openbsd"))]
222 pub fn current_exe() -> io::Result<PathBuf> {
223     unsafe {
224         let mut mib = [libc::CTL_KERN,
225                        libc::KERN_PROC_ARGS,
226                        libc::getpid(),
227                        libc::KERN_PROC_ARGV];
228         let mib = mib.as_mut_ptr();
229         let mut argv_len = 0;
230         cvt(libc::sysctl(mib, 4, 0 as *mut _, &mut argv_len,
231                          0 as *mut _, 0))?;
232         let mut argv = Vec::<*const libc::c_char>::with_capacity(argv_len as usize);
233         cvt(libc::sysctl(mib, 4, argv.as_mut_ptr() as *mut _,
234                          &mut argv_len, 0 as *mut _, 0))?;
235         argv.set_len(argv_len as usize);
236         if argv[0].is_null() {
237             return Err(io::Error::new(io::ErrorKind::Other,
238                                       "no current exe available"))
239         }
240         let argv0 = CStr::from_ptr(argv[0]).to_bytes();
241         if argv0[0] == b'.' || argv0.iter().any(|b| *b == b'/') {
242             ::fs::canonicalize(OsStr::from_bytes(argv0))
243         } else {
244             Ok(PathBuf::from(OsStr::from_bytes(argv0)))
245         }
246     }
247 }
248
249 #[cfg(any(target_os = "linux", target_os = "android", target_os = "emscripten"))]
250 pub fn current_exe() -> io::Result<PathBuf> {
251     ::fs::read_link("/proc/self/exe")
252 }
253
254 #[cfg(any(target_os = "macos", target_os = "ios"))]
255 pub fn current_exe() -> io::Result<PathBuf> {
256     extern {
257         fn _NSGetExecutablePath(buf: *mut libc::c_char,
258                                 bufsize: *mut u32) -> libc::c_int;
259     }
260     unsafe {
261         let mut sz: u32 = 0;
262         _NSGetExecutablePath(ptr::null_mut(), &mut sz);
263         if sz == 0 { return Err(io::Error::last_os_error()); }
264         let mut v: Vec<u8> = Vec::with_capacity(sz as usize);
265         let err = _NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz);
266         if err != 0 { return Err(io::Error::last_os_error()); }
267         v.set_len(sz as usize - 1); // chop off trailing NUL
268         Ok(PathBuf::from(OsString::from_vec(v)))
269     }
270 }
271
272 #[cfg(any(target_os = "solaris"))]
273 pub fn current_exe() -> io::Result<PathBuf> {
274     extern {
275         fn getexecname() -> *const c_char;
276     }
277     unsafe {
278         let path = getexecname();
279         if path.is_null() {
280             Err(io::Error::last_os_error())
281         } else {
282             let filename = CStr::from_ptr(path).to_bytes();
283             let path = PathBuf::from(<OsStr as OsStrExt>::from_bytes(filename));
284
285             // Prepend a current working directory to the path if
286             // it doesn't contain an absolute pathname.
287             if filename[0] == b'/' {
288                 Ok(path)
289             } else {
290                 getcwd().map(|cwd| cwd.join(path))
291             }
292         }
293     }
294 }
295
296 pub struct Args {
297     iter: vec::IntoIter<OsString>,
298     _dont_send_or_sync_me: *mut (),
299 }
300
301 impl Iterator for Args {
302     type Item = OsString;
303     fn next(&mut self) -> Option<OsString> { self.iter.next() }
304     fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
305 }
306
307 impl ExactSizeIterator for Args {
308     fn len(&self) -> usize { self.iter.len() }
309 }
310
311 impl DoubleEndedIterator for Args {
312     fn next_back(&mut self) -> Option<OsString> { self.iter.next_back() }
313 }
314
315 /// Returns the command line arguments
316 ///
317 /// Returns a list of the command line arguments.
318 #[cfg(target_os = "macos")]
319 pub fn args() -> Args {
320     extern {
321         // These functions are in crt_externs.h.
322         fn _NSGetArgc() -> *mut c_int;
323         fn _NSGetArgv() -> *mut *mut *mut c_char;
324     }
325
326     let vec = unsafe {
327         let (argc, argv) = (*_NSGetArgc() as isize,
328                             *_NSGetArgv() as *const *const c_char);
329         (0.. argc as isize).map(|i| {
330             let bytes = CStr::from_ptr(*argv.offset(i)).to_bytes().to_vec();
331             OsStringExt::from_vec(bytes)
332         }).collect::<Vec<_>>()
333     };
334     Args {
335         iter: vec.into_iter(),
336         _dont_send_or_sync_me: ptr::null_mut(),
337     }
338 }
339
340 // As _NSGetArgc and _NSGetArgv aren't mentioned in iOS docs
341 // and use underscores in their names - they're most probably
342 // are considered private and therefore should be avoided
343 // Here is another way to get arguments using Objective C
344 // runtime
345 //
346 // In general it looks like:
347 // res = Vec::new()
348 // let args = [[NSProcessInfo processInfo] arguments]
349 // for i in (0..[args count])
350 //      res.push([args objectAtIndex:i])
351 // res
352 #[cfg(target_os = "ios")]
353 pub fn args() -> Args {
354     use mem;
355
356     extern {
357         fn sel_registerName(name: *const libc::c_uchar) -> Sel;
358         fn objc_msgSend(obj: NsId, sel: Sel, ...) -> NsId;
359         fn objc_getClass(class_name: *const libc::c_uchar) -> NsId;
360     }
361
362     #[link(name = "Foundation", kind = "framework")]
363     #[link(name = "objc")]
364     #[cfg(not(cargobuild))]
365     extern {}
366
367     type Sel = *const libc::c_void;
368     type NsId = *const libc::c_void;
369
370     let mut res = Vec::new();
371
372     unsafe {
373         let process_info_sel = sel_registerName("processInfo\0".as_ptr());
374         let arguments_sel = sel_registerName("arguments\0".as_ptr());
375         let utf8_sel = sel_registerName("UTF8String\0".as_ptr());
376         let count_sel = sel_registerName("count\0".as_ptr());
377         let object_at_sel = sel_registerName("objectAtIndex:\0".as_ptr());
378
379         let klass = objc_getClass("NSProcessInfo\0".as_ptr());
380         let info = objc_msgSend(klass, process_info_sel);
381         let args = objc_msgSend(info, arguments_sel);
382
383         let cnt: usize = mem::transmute(objc_msgSend(args, count_sel));
384         for i in 0..cnt {
385             let tmp = objc_msgSend(args, object_at_sel, i);
386             let utf_c_str: *const libc::c_char =
387                 mem::transmute(objc_msgSend(tmp, utf8_sel));
388             let bytes = CStr::from_ptr(utf_c_str).to_bytes();
389             res.push(OsString::from(str::from_utf8(bytes).unwrap()))
390         }
391     }
392
393     Args { iter: res.into_iter(), _dont_send_or_sync_me: ptr::null_mut() }
394 }
395
396 #[cfg(any(target_os = "linux",
397           target_os = "android",
398           target_os = "freebsd",
399           target_os = "dragonfly",
400           target_os = "bitrig",
401           target_os = "netbsd",
402           target_os = "openbsd",
403           target_os = "solaris",
404           target_os = "nacl",
405           target_os = "emscripten"))]
406 pub fn args() -> Args {
407     use sys_common;
408     let bytes = sys_common::args::clone().unwrap_or(Vec::new());
409     let v: Vec<OsString> = bytes.into_iter().map(|v| {
410         OsStringExt::from_vec(v)
411     }).collect();
412     Args { iter: v.into_iter(), _dont_send_or_sync_me: ptr::null_mut() }
413 }
414
415 pub struct Env {
416     iter: vec::IntoIter<(OsString, OsString)>,
417     _dont_send_or_sync_me: *mut (),
418 }
419
420 impl Iterator for Env {
421     type Item = (OsString, OsString);
422     fn next(&mut self) -> Option<(OsString, OsString)> { self.iter.next() }
423     fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
424 }
425
426 #[cfg(target_os = "macos")]
427 pub unsafe fn environ() -> *mut *const *const c_char {
428     extern { fn _NSGetEnviron() -> *mut *const *const c_char; }
429     _NSGetEnviron()
430 }
431
432 #[cfg(not(target_os = "macos"))]
433 pub unsafe fn environ() -> *mut *const *const c_char {
434     extern { static mut environ: *const *const c_char; }
435     &mut environ
436 }
437
438 /// Returns a vector of (variable, value) byte-vector pairs for all the
439 /// environment variables of the current process.
440 pub fn env() -> Env {
441     unsafe {
442         ENV_LOCK.lock();
443         let mut environ = *environ();
444         if environ == ptr::null() {
445             ENV_LOCK.unlock();
446             panic!("os::env() failure getting env string from OS: {}",
447                    io::Error::last_os_error());
448         }
449         let mut result = Vec::new();
450         while *environ != ptr::null() {
451             if let Some(key_value) = parse(CStr::from_ptr(*environ).to_bytes()) {
452                 result.push(key_value);
453             }
454             environ = environ.offset(1);
455         }
456         let ret = Env {
457             iter: result.into_iter(),
458             _dont_send_or_sync_me: ptr::null_mut(),
459         };
460         ENV_LOCK.unlock();
461         return ret
462     }
463
464     fn parse(input: &[u8]) -> Option<(OsString, OsString)> {
465         // Strategy (copied from glibc): Variable name and value are separated
466         // by an ASCII equals sign '='. Since a variable name must not be
467         // empty, allow variable names starting with an equals sign. Skip all
468         // malformed lines.
469         if input.is_empty() {
470             return None;
471         }
472         let pos = memchr::memchr(b'=', &input[1..]).map(|p| p + 1);
473         pos.map(|p| (
474             OsStringExt::from_vec(input[..p].to_vec()),
475             OsStringExt::from_vec(input[p+1..].to_vec()),
476         ))
477     }
478 }
479
480 pub fn getenv(k: &OsStr) -> io::Result<Option<OsString>> {
481     // environment variables with a nul byte can't be set, so their value is
482     // always None as well
483     let k = CString::new(k.as_bytes())?;
484     unsafe {
485         ENV_LOCK.lock();
486         let s = libc::getenv(k.as_ptr()) as *const _;
487         let ret = if s.is_null() {
488             None
489         } else {
490             Some(OsStringExt::from_vec(CStr::from_ptr(s).to_bytes().to_vec()))
491         };
492         ENV_LOCK.unlock();
493         return Ok(ret)
494     }
495 }
496
497 pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> {
498     let k = CString::new(k.as_bytes())?;
499     let v = CString::new(v.as_bytes())?;
500
501     unsafe {
502         ENV_LOCK.lock();
503         let ret = cvt(libc::setenv(k.as_ptr(), v.as_ptr(), 1)).map(|_| ());
504         ENV_LOCK.unlock();
505         return ret
506     }
507 }
508
509 pub fn unsetenv(n: &OsStr) -> io::Result<()> {
510     let nbuf = CString::new(n.as_bytes())?;
511
512     unsafe {
513         ENV_LOCK.lock();
514         let ret = cvt(libc::unsetenv(nbuf.as_ptr())).map(|_| ());
515         ENV_LOCK.unlock();
516         return ret
517     }
518 }
519
520 pub fn page_size() -> usize {
521     unsafe {
522         libc::sysconf(libc::_SC_PAGESIZE) as usize
523     }
524 }
525
526 pub fn temp_dir() -> PathBuf {
527     ::env::var_os("TMPDIR").map(PathBuf::from).unwrap_or_else(|| {
528         if cfg!(target_os = "android") {
529             PathBuf::from("/data/local/tmp")
530         } else {
531             PathBuf::from("/tmp")
532         }
533     })
534 }
535
536 pub fn home_dir() -> Option<PathBuf> {
537     return ::env::var_os("HOME").or_else(|| unsafe {
538         fallback()
539     }).map(PathBuf::from);
540
541     #[cfg(any(target_os = "android",
542               target_os = "ios",
543               target_os = "nacl"))]
544     unsafe fn fallback() -> Option<OsString> { None }
545     #[cfg(not(any(target_os = "android",
546                   target_os = "ios",
547                   target_os = "nacl")))]
548     unsafe fn fallback() -> Option<OsString> {
549         #[cfg(not(target_os = "solaris"))]
550         unsafe fn getpwduid_r(me: libc::uid_t, passwd: &mut libc::passwd,
551                               buf: &mut Vec<c_char>) -> Option<()> {
552             let mut result = ptr::null_mut();
553             match libc::getpwuid_r(me, passwd, buf.as_mut_ptr(),
554                                    buf.capacity() as libc::size_t,
555                                    &mut result) {
556                 0 if !result.is_null() => Some(()),
557                 _ => None
558             }
559         }
560
561         #[cfg(target_os = "solaris")]
562         unsafe fn getpwduid_r(me: libc::uid_t, passwd: &mut libc::passwd,
563                               buf: &mut Vec<c_char>) -> Option<()> {
564             // getpwuid_r semantics is different on Illumos/Solaris:
565             // http://illumos.org/man/3c/getpwuid_r
566             let result = libc::getpwuid_r(me, passwd, buf.as_mut_ptr(),
567                                           buf.capacity() as libc::size_t);
568             if result.is_null() { None } else { Some(()) }
569         }
570
571         let amt = match libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) {
572             n if n < 0 => 512 as usize,
573             n => n as usize,
574         };
575         let me = libc::getuid();
576         loop {
577             let mut buf = Vec::with_capacity(amt);
578             let mut passwd: libc::passwd = mem::zeroed();
579
580             if getpwduid_r(me, &mut passwd, &mut buf).is_some() {
581                 let ptr = passwd.pw_dir as *const _;
582                 let bytes = CStr::from_ptr(ptr).to_bytes().to_vec();
583                 return Some(OsStringExt::from_vec(bytes))
584             } else {
585                 return None;
586             }
587         }
588     }
589 }
590
591 pub fn exit(code: i32) -> ! {
592     unsafe { libc::exit(code as c_int) }
593 }