]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/os.rs
Auto merge of #35426 - frewsxcv:os-sys-env-args-phantoms, r=alexcrichton
[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 marker::PhantomData;
25 use mem;
26 use memchr;
27 use path::{self, PathBuf};
28 use ptr;
29 use slice;
30 use str;
31 use sys_common::mutex::Mutex;
32 use sys::cvt;
33 use sys::fd;
34 use vec;
35
36 const TMPBUF_SZ: usize = 128;
37 static ENV_LOCK: Mutex = Mutex::new();
38
39
40 extern {
41     #[cfg(not(target_os = "dragonfly"))]
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() -> *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 pub struct Args {
308     iter: vec::IntoIter<OsString>,
309     _dont_send_or_sync_me: PhantomData<*mut ()>,
310 }
311
312 impl Iterator for Args {
313     type Item = OsString;
314     fn next(&mut self) -> Option<OsString> { self.iter.next() }
315     fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
316 }
317
318 impl ExactSizeIterator for Args {
319     fn len(&self) -> usize { self.iter.len() }
320 }
321
322 impl DoubleEndedIterator for Args {
323     fn next_back(&mut self) -> Option<OsString> { self.iter.next_back() }
324 }
325
326 /// Returns the command line arguments
327 ///
328 /// Returns a list of the command line arguments.
329 #[cfg(target_os = "macos")]
330 pub fn args() -> Args {
331     extern {
332         // These functions are in crt_externs.h.
333         fn _NSGetArgc() -> *mut c_int;
334         fn _NSGetArgv() -> *mut *mut *mut c_char;
335     }
336
337     let vec = unsafe {
338         let (argc, argv) = (*_NSGetArgc() as isize,
339                             *_NSGetArgv() as *const *const c_char);
340         (0.. argc as isize).map(|i| {
341             let bytes = CStr::from_ptr(*argv.offset(i)).to_bytes().to_vec();
342             OsStringExt::from_vec(bytes)
343         }).collect::<Vec<_>>()
344     };
345     Args {
346         iter: vec.into_iter(),
347         _dont_send_or_sync_me: PhantomData,
348     }
349 }
350
351 // As _NSGetArgc and _NSGetArgv aren't mentioned in iOS docs
352 // and use underscores in their names - they're most probably
353 // are considered private and therefore should be avoided
354 // Here is another way to get arguments using Objective C
355 // runtime
356 //
357 // In general it looks like:
358 // res = Vec::new()
359 // let args = [[NSProcessInfo processInfo] arguments]
360 // for i in (0..[args count])
361 //      res.push([args objectAtIndex:i])
362 // res
363 #[cfg(target_os = "ios")]
364 pub fn args() -> Args {
365     use mem;
366
367     extern {
368         fn sel_registerName(name: *const libc::c_uchar) -> Sel;
369         fn objc_msgSend(obj: NsId, sel: Sel, ...) -> NsId;
370         fn objc_getClass(class_name: *const libc::c_uchar) -> NsId;
371     }
372
373     #[link(name = "Foundation", kind = "framework")]
374     #[link(name = "objc")]
375     #[cfg(not(cargobuild))]
376     extern {}
377
378     type Sel = *const libc::c_void;
379     type NsId = *const libc::c_void;
380
381     let mut res = Vec::new();
382
383     unsafe {
384         let process_info_sel = sel_registerName("processInfo\0".as_ptr());
385         let arguments_sel = sel_registerName("arguments\0".as_ptr());
386         let utf8_sel = sel_registerName("UTF8String\0".as_ptr());
387         let count_sel = sel_registerName("count\0".as_ptr());
388         let object_at_sel = sel_registerName("objectAtIndex:\0".as_ptr());
389
390         let klass = objc_getClass("NSProcessInfo\0".as_ptr());
391         let info = objc_msgSend(klass, process_info_sel);
392         let args = objc_msgSend(info, arguments_sel);
393
394         let cnt: usize = mem::transmute(objc_msgSend(args, count_sel));
395         for i in 0..cnt {
396             let tmp = objc_msgSend(args, object_at_sel, i);
397             let utf_c_str: *const libc::c_char =
398                 mem::transmute(objc_msgSend(tmp, utf8_sel));
399             let bytes = CStr::from_ptr(utf_c_str).to_bytes();
400             res.push(OsString::from(str::from_utf8(bytes).unwrap()))
401         }
402     }
403
404     Args { iter: res.into_iter(), _dont_send_or_sync_me: PhantomData }
405 }
406
407 #[cfg(any(target_os = "linux",
408           target_os = "android",
409           target_os = "freebsd",
410           target_os = "dragonfly",
411           target_os = "bitrig",
412           target_os = "netbsd",
413           target_os = "openbsd",
414           target_os = "solaris",
415           target_os = "nacl",
416           target_os = "emscripten"))]
417 pub fn args() -> Args {
418     use sys_common;
419     let bytes = sys_common::args::clone().unwrap_or(Vec::new());
420     let v: Vec<OsString> = bytes.into_iter().map(|v| {
421         OsStringExt::from_vec(v)
422     }).collect();
423     Args { iter: v.into_iter(), _dont_send_or_sync_me: PhantomData }
424 }
425
426 pub struct Env {
427     iter: vec::IntoIter<(OsString, OsString)>,
428     _dont_send_or_sync_me: PhantomData<*mut ()>,
429 }
430
431 impl Iterator for Env {
432     type Item = (OsString, OsString);
433     fn next(&mut self) -> Option<(OsString, OsString)> { self.iter.next() }
434     fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
435 }
436
437 #[cfg(target_os = "macos")]
438 pub unsafe fn environ() -> *mut *const *const c_char {
439     extern { fn _NSGetEnviron() -> *mut *const *const c_char; }
440     _NSGetEnviron()
441 }
442
443 #[cfg(not(target_os = "macos"))]
444 pub unsafe fn environ() -> *mut *const *const c_char {
445     extern { static mut environ: *const *const c_char; }
446     &mut environ
447 }
448
449 /// Returns a vector of (variable, value) byte-vector pairs for all the
450 /// environment variables of the current process.
451 pub fn env() -> Env {
452     unsafe {
453         ENV_LOCK.lock();
454         let mut environ = *environ();
455         if environ == ptr::null() {
456             ENV_LOCK.unlock();
457             panic!("os::env() failure getting env string from OS: {}",
458                    io::Error::last_os_error());
459         }
460         let mut result = Vec::new();
461         while *environ != ptr::null() {
462             if let Some(key_value) = parse(CStr::from_ptr(*environ).to_bytes()) {
463                 result.push(key_value);
464             }
465             environ = environ.offset(1);
466         }
467         let ret = Env {
468             iter: result.into_iter(),
469             _dont_send_or_sync_me: PhantomData,
470         };
471         ENV_LOCK.unlock();
472         return ret
473     }
474
475     fn parse(input: &[u8]) -> Option<(OsString, OsString)> {
476         // Strategy (copied from glibc): Variable name and value are separated
477         // by an ASCII equals sign '='. Since a variable name must not be
478         // empty, allow variable names starting with an equals sign. Skip all
479         // malformed lines.
480         if input.is_empty() {
481             return None;
482         }
483         let pos = memchr::memchr(b'=', &input[1..]).map(|p| p + 1);
484         pos.map(|p| (
485             OsStringExt::from_vec(input[..p].to_vec()),
486             OsStringExt::from_vec(input[p+1..].to_vec()),
487         ))
488     }
489 }
490
491 pub fn getenv(k: &OsStr) -> io::Result<Option<OsString>> {
492     // environment variables with a nul byte can't be set, so their value is
493     // always None as well
494     let k = CString::new(k.as_bytes())?;
495     unsafe {
496         ENV_LOCK.lock();
497         let s = libc::getenv(k.as_ptr()) as *const _;
498         let ret = if s.is_null() {
499             None
500         } else {
501             Some(OsStringExt::from_vec(CStr::from_ptr(s).to_bytes().to_vec()))
502         };
503         ENV_LOCK.unlock();
504         return Ok(ret)
505     }
506 }
507
508 pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> {
509     let k = CString::new(k.as_bytes())?;
510     let v = CString::new(v.as_bytes())?;
511
512     unsafe {
513         ENV_LOCK.lock();
514         let ret = cvt(libc::setenv(k.as_ptr(), v.as_ptr(), 1)).map(|_| ());
515         ENV_LOCK.unlock();
516         return ret
517     }
518 }
519
520 pub fn unsetenv(n: &OsStr) -> io::Result<()> {
521     let nbuf = CString::new(n.as_bytes())?;
522
523     unsafe {
524         ENV_LOCK.lock();
525         let ret = cvt(libc::unsetenv(nbuf.as_ptr())).map(|_| ());
526         ENV_LOCK.unlock();
527         return ret
528     }
529 }
530
531 pub fn page_size() -> usize {
532     unsafe {
533         libc::sysconf(libc::_SC_PAGESIZE) as usize
534     }
535 }
536
537 pub fn temp_dir() -> PathBuf {
538     ::env::var_os("TMPDIR").map(PathBuf::from).unwrap_or_else(|| {
539         if cfg!(target_os = "android") {
540             PathBuf::from("/data/local/tmp")
541         } else {
542             PathBuf::from("/tmp")
543         }
544     })
545 }
546
547 pub fn home_dir() -> Option<PathBuf> {
548     return ::env::var_os("HOME").or_else(|| unsafe {
549         fallback()
550     }).map(PathBuf::from);
551
552     #[cfg(any(target_os = "android",
553               target_os = "ios",
554               target_os = "nacl"))]
555     unsafe fn fallback() -> Option<OsString> { None }
556     #[cfg(not(any(target_os = "android",
557                   target_os = "ios",
558                   target_os = "nacl")))]
559     unsafe fn fallback() -> Option<OsString> {
560         #[cfg(not(target_os = "solaris"))]
561         unsafe fn getpwduid_r(me: libc::uid_t, passwd: &mut libc::passwd,
562                               buf: &mut Vec<c_char>) -> Option<()> {
563             let mut result = ptr::null_mut();
564             match libc::getpwuid_r(me, passwd, buf.as_mut_ptr(),
565                                    buf.capacity() as libc::size_t,
566                                    &mut result) {
567                 0 if !result.is_null() => Some(()),
568                 _ => None
569             }
570         }
571
572         #[cfg(target_os = "solaris")]
573         unsafe fn getpwduid_r(me: libc::uid_t, passwd: &mut libc::passwd,
574                               buf: &mut Vec<c_char>) -> Option<()> {
575             // getpwuid_r semantics is different on Illumos/Solaris:
576             // http://illumos.org/man/3c/getpwuid_r
577             let result = libc::getpwuid_r(me, passwd, buf.as_mut_ptr(),
578                                           buf.capacity() as libc::size_t);
579             if result.is_null() { None } else { Some(()) }
580         }
581
582         let amt = match libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) {
583             n if n < 0 => 512 as usize,
584             n => n as usize,
585         };
586         let me = libc::getuid();
587         loop {
588             let mut buf = Vec::with_capacity(amt);
589             let mut passwd: libc::passwd = mem::zeroed();
590
591             if getpwduid_r(me, &mut passwd, &mut buf).is_some() {
592                 let ptr = passwd.pw_dir as *const _;
593                 let bytes = CStr::from_ptr(ptr).to_bytes().to_vec();
594                 return Some(OsStringExt::from_vec(bytes))
595             } else {
596                 return None;
597             }
598         }
599     }
600 }
601
602 pub fn exit(code: i32) -> ! {
603     unsafe { libc::exit(code as c_int) }
604 }