]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/os.rs
Rollup merge of #36045 - ollie27:rustdoc_titles3, r=steveklabnik
[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     fn errno_location() -> *mut c_int;
55 }
56
57 /// Returns the platform-specific value of errno
58 #[cfg(not(target_os = "dragonfly"))]
59 pub fn errno() -> i32 {
60     unsafe {
61         (*errno_location()) as i32
62     }
63 }
64
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) {
68     unsafe {
69         *errno_location() = e as c_int
70     }
71 }
72
73 #[cfg(target_os = "dragonfly")]
74 pub fn errno() -> i32 {
75     extern {
76         #[thread_local]
77         static errno: c_int;
78     }
79
80     errno as i32
81 }
82
83 /// Gets a detailed string description for the given error number.
84 pub fn error_string(errno: i32) -> String {
85     extern {
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;
90     }
91
92     let mut buf = [0 as c_char; TMPBUF_SZ];
93
94     let p = buf.as_mut_ptr();
95     unsafe {
96         if strerror_r(errno as c_int, p, buf.len() as libc::size_t) < 0 {
97             panic!("strerror_r failure");
98         }
99
100         let p = p as *const _;
101         str::from_utf8(CStr::from_ptr(p).to_bytes()).unwrap().to_owned()
102     }
103 }
104
105 pub fn getcwd() -> io::Result<PathBuf> {
106     let mut buf = Vec::with_capacity(512);
107     loop {
108         unsafe {
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();
112                 buf.set_len(len);
113                 buf.shrink_to_fit();
114                 return Ok(PathBuf::from(OsString::from_vec(buf)));
115             } else {
116                 let error = io::Error::last_os_error();
117                 if error.raw_os_error() != Some(libc::ERANGE) {
118                     return Err(error);
119                 }
120             }
121
122             // Trigger the internal buffer resizing logic of `Vec` by requiring
123             // more space than the current capacity.
124             let cap = buf.capacity();
125             buf.set_len(cap);
126             buf.reserve(1);
127         }
128     }
129 }
130
131 pub fn chdir(p: &path::Path) -> io::Result<()> {
132     let p: &OsStr = p.as_ref();
133     let p = CString::new(p.as_bytes())?;
134     unsafe {
135         match libc::chdir(p.as_ptr()) == (0 as c_int) {
136             true => Ok(()),
137             false => Err(io::Error::last_os_error()),
138         }
139     }
140 }
141
142 pub struct SplitPaths<'a> {
143     iter: iter::Map<slice::Split<'a, u8, fn(&u8) -> bool>,
144                     fn(&'a [u8]) -> PathBuf>,
145 }
146
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))
150     }
151     fn is_colon(b: &u8) -> bool { *b == b':' }
152     let unparsed = unparsed.as_bytes();
153     SplitPaths {
154         iter: unparsed.split(is_colon as fn(&u8) -> bool)
155                       .map(bytes_to_path as fn(&[u8]) -> PathBuf)
156     }
157 }
158
159 impl<'a> Iterator for SplitPaths<'a> {
160     type Item = PathBuf;
161     fn next(&mut self) -> Option<PathBuf> { self.iter.next() }
162     fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
163 }
164
165 #[derive(Debug)]
166 pub struct JoinPathsError;
167
168 pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
169     where I: Iterator<Item=T>, T: AsRef<OsStr>
170 {
171     let mut joined = Vec::new();
172     let sep = b':';
173
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)
179         }
180         joined.extend_from_slice(path);
181     }
182     Ok(OsStringExt::from_vec(joined))
183 }
184
185 impl fmt::Display for JoinPathsError {
186     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
187         "path segment contains separator `:`".fmt(f)
188     }
189 }
190
191 impl StdError for JoinPathsError {
192     fn description(&self) -> &str { "failed to join paths" }
193 }
194
195 #[cfg(target_os = "freebsd")]
196 pub fn current_exe() -> io::Result<PathBuf> {
197     unsafe {
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,
201                        -1 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))?;
206         if sz == 0 {
207             return Err(io::Error::last_os_error())
208         }
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))?;
213         if sz == 0 {
214             return Err(io::Error::last_os_error());
215         }
216         v.set_len(sz as usize - 1); // chop off trailing NUL
217         Ok(PathBuf::from(OsString::from_vec(v)))
218     }
219 }
220
221 #[cfg(target_os = "dragonfly")]
222 pub fn current_exe() -> io::Result<PathBuf> {
223     ::fs::read_link("/proc/curproc/file")
224 }
225
226 #[cfg(target_os = "netbsd")]
227 pub fn current_exe() -> io::Result<PathBuf> {
228     ::fs::read_link("/proc/curproc/exe")
229 }
230
231 #[cfg(any(target_os = "bitrig", target_os = "openbsd"))]
232 pub fn current_exe() -> io::Result<PathBuf> {
233     unsafe {
234         let mut mib = [libc::CTL_KERN,
235                        libc::KERN_PROC_ARGS,
236                        libc::getpid(),
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"))
249         }
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))
253         } else {
254             Ok(PathBuf::from(OsStr::from_bytes(argv0)))
255         }
256     }
257 }
258
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")
262 }
263
264 #[cfg(any(target_os = "macos", target_os = "ios"))]
265 pub fn current_exe() -> io::Result<PathBuf> {
266     extern {
267         fn _NSGetExecutablePath(buf: *mut libc::c_char,
268                                 bufsize: *mut u32) -> libc::c_int;
269     }
270     unsafe {
271         let mut sz: u32 = 0;
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)))
279     }
280 }
281
282 #[cfg(any(target_os = "solaris"))]
283 pub fn current_exe() -> io::Result<PathBuf> {
284     extern {
285         fn getexecname() -> *const c_char;
286     }
287     unsafe {
288         let path = getexecname();
289         if path.is_null() {
290             Err(io::Error::last_os_error())
291         } else {
292             let filename = CStr::from_ptr(path).to_bytes();
293             let path = PathBuf::from(<OsStr as OsStrExt>::from_bytes(filename));
294
295             // Prepend a current working directory to the path if
296             // it doesn't contain an absolute pathname.
297             if filename[0] == b'/' {
298                 Ok(path)
299             } else {
300                 getcwd().map(|cwd| cwd.join(path))
301             }
302         }
303     }
304 }
305
306 pub struct Args {
307     iter: vec::IntoIter<OsString>,
308     _dont_send_or_sync_me: PhantomData<*mut ()>,
309 }
310
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() }
315 }
316
317 impl ExactSizeIterator for Args {
318     fn len(&self) -> usize { self.iter.len() }
319 }
320
321 impl DoubleEndedIterator for Args {
322     fn next_back(&mut self) -> Option<OsString> { self.iter.next_back() }
323 }
324
325 /// Returns the command line arguments
326 ///
327 /// Returns a list of the command line arguments.
328 #[cfg(target_os = "macos")]
329 pub fn args() -> Args {
330     extern {
331         // These functions are in crt_externs.h.
332         fn _NSGetArgc() -> *mut c_int;
333         fn _NSGetArgv() -> *mut *mut *mut c_char;
334     }
335
336     let vec = unsafe {
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<_>>()
343     };
344     Args {
345         iter: vec.into_iter(),
346         _dont_send_or_sync_me: PhantomData,
347     }
348 }
349
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
354 // runtime
355 //
356 // In general it looks like:
357 // res = Vec::new()
358 // let args = [[NSProcessInfo processInfo] arguments]
359 // for i in (0..[args count])
360 //      res.push([args objectAtIndex:i])
361 // res
362 #[cfg(target_os = "ios")]
363 pub fn args() -> Args {
364     use mem;
365
366     extern {
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;
370     }
371
372     #[link(name = "Foundation", kind = "framework")]
373     #[link(name = "objc")]
374     #[cfg(not(cargobuild))]
375     extern {}
376
377     type Sel = *const libc::c_void;
378     type NsId = *const libc::c_void;
379
380     let mut res = Vec::new();
381
382     unsafe {
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());
388
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);
392
393         let cnt: usize = mem::transmute(objc_msgSend(args, count_sel));
394         for i in 0..cnt {
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()))
400         }
401     }
402
403     Args { iter: res.into_iter(), _dont_send_or_sync_me: PhantomData }
404 }
405
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",
414           target_os = "nacl",
415           target_os = "emscripten"))]
416 pub fn args() -> Args {
417     use sys_common;
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)
421     }).collect();
422     Args { iter: v.into_iter(), _dont_send_or_sync_me: PhantomData }
423 }
424
425 pub struct Env {
426     iter: vec::IntoIter<(OsString, OsString)>,
427     _dont_send_or_sync_me: PhantomData<*mut ()>,
428 }
429
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() }
434 }
435
436 #[cfg(target_os = "macos")]
437 pub unsafe fn environ() -> *mut *const *const c_char {
438     extern { fn _NSGetEnviron() -> *mut *const *const c_char; }
439     _NSGetEnviron()
440 }
441
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; }
445     &mut environ
446 }
447
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 {
451     unsafe {
452         ENV_LOCK.lock();
453         let mut environ = *environ();
454         if environ == ptr::null() {
455             ENV_LOCK.unlock();
456             panic!("os::env() failure getting env string from OS: {}",
457                    io::Error::last_os_error());
458         }
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);
463             }
464             environ = environ.offset(1);
465         }
466         let ret = Env {
467             iter: result.into_iter(),
468             _dont_send_or_sync_me: PhantomData,
469         };
470         ENV_LOCK.unlock();
471         return ret
472     }
473
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
478         // malformed lines.
479         if input.is_empty() {
480             return None;
481         }
482         let pos = memchr::memchr(b'=', &input[1..]).map(|p| p + 1);
483         pos.map(|p| (
484             OsStringExt::from_vec(input[..p].to_vec()),
485             OsStringExt::from_vec(input[p+1..].to_vec()),
486         ))
487     }
488 }
489
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())?;
494     unsafe {
495         ENV_LOCK.lock();
496         let s = libc::getenv(k.as_ptr()) as *const _;
497         let ret = if s.is_null() {
498             None
499         } else {
500             Some(OsStringExt::from_vec(CStr::from_ptr(s).to_bytes().to_vec()))
501         };
502         ENV_LOCK.unlock();
503         return Ok(ret)
504     }
505 }
506
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())?;
510
511     unsafe {
512         ENV_LOCK.lock();
513         let ret = cvt(libc::setenv(k.as_ptr(), v.as_ptr(), 1)).map(|_| ());
514         ENV_LOCK.unlock();
515         return ret
516     }
517 }
518
519 pub fn unsetenv(n: &OsStr) -> io::Result<()> {
520     let nbuf = CString::new(n.as_bytes())?;
521
522     unsafe {
523         ENV_LOCK.lock();
524         let ret = cvt(libc::unsetenv(nbuf.as_ptr())).map(|_| ());
525         ENV_LOCK.unlock();
526         return ret
527     }
528 }
529
530 pub fn page_size() -> usize {
531     unsafe {
532         libc::sysconf(libc::_SC_PAGESIZE) as usize
533     }
534 }
535
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")
540         } else {
541             PathBuf::from("/tmp")
542         }
543     })
544 }
545
546 pub fn home_dir() -> Option<PathBuf> {
547     return ::env::var_os("HOME").or_else(|| unsafe {
548         fallback()
549     }).map(PathBuf::from);
550
551     #[cfg(any(target_os = "android",
552               target_os = "ios",
553               target_os = "nacl",
554               target_os = "emscripten"))]
555     unsafe fn fallback() -> Option<OsString> { None }
556     #[cfg(not(any(target_os = "android",
557                   target_os = "ios",
558                   target_os = "nacl",
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,
567                                    &mut result) {
568                 0 if !result.is_null() => Some(()),
569                 _ => None
570             }
571         }
572
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(()) }
581         }
582
583         let amt = match libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) {
584             n if n < 0 => 512 as usize,
585             n => n as usize,
586         };
587         let mut buf = Vec::with_capacity(amt);
588         let mut passwd: libc::passwd = mem::zeroed();
589
590         if getpwduid_r(libc::getuid(), &mut passwd, &mut buf).is_some() {
591             let ptr = passwd.pw_dir as *const _;
592             let bytes = CStr::from_ptr(ptr).to_bytes().to_vec();
593             Some(OsStringExt::from_vec(bytes))
594         } else {
595             None
596         }
597     }
598 }
599
600 pub fn exit(code: i32) -> ! {
601     unsafe { libc::exit(code as c_int) }
602 }