]> git.proxmox.com Git - rustc.git/blob - src/libstd/sys/unix/os.rs
Imported Upstream version 1.5.0+dfsg1
[rustc.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 path::{self, PathBuf};
26 use ptr;
27 use slice;
28 use str;
29 use sys::c;
30 use sys::fd;
31 use vec;
32
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(any(target_os = "bitrig", target_os = "netbsd", 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 /// Gets 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_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 = try!(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.push_all(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 use libc::funcs::bsd44::*;
189 use libc::consts::os::extra::*;
190 let mut mib = [CTL_KERN as c_int,
191 KERN_PROC as c_int,
192 KERN_PROC_PATHNAME as c_int,
193 -1 as c_int];
194 let mut sz: libc::size_t = 0;
195 let err = sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
196 ptr::null_mut(), &mut sz, ptr::null_mut(),
197 0 as libc::size_t);
198 if err != 0 { return Err(io::Error::last_os_error()); }
199 if sz == 0 { return Err(io::Error::last_os_error()); }
200 let mut v: Vec<u8> = Vec::with_capacity(sz as usize);
201 let err = sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
202 v.as_mut_ptr() as *mut libc::c_void, &mut sz,
203 ptr::null_mut(), 0 as libc::size_t);
204 if err != 0 { return Err(io::Error::last_os_error()); }
205 if sz == 0 { return Err(io::Error::last_os_error()); }
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 use sync::StaticMutex;
224 static LOCK: StaticMutex = StaticMutex::new();
225
226 extern {
227 fn rust_current_exe() -> *const c_char;
228 }
229
230 let _guard = LOCK.lock();
231
232 unsafe {
233 let v = rust_current_exe();
234 if v.is_null() {
235 Err(io::Error::last_os_error())
236 } else {
237 let vec = CStr::from_ptr(v).to_bytes().to_vec();
238 Ok(PathBuf::from(OsString::from_vec(vec)))
239 }
240 }
241 }
242
243 #[cfg(any(target_os = "linux", target_os = "android"))]
244 pub fn current_exe() -> io::Result<PathBuf> {
245 ::fs::read_link("/proc/self/exe")
246 }
247
248 #[cfg(any(target_os = "macos", target_os = "ios"))]
249 pub fn current_exe() -> io::Result<PathBuf> {
250 unsafe {
251 use libc::funcs::extra::_NSGetExecutablePath;
252 let mut sz: u32 = 0;
253 _NSGetExecutablePath(ptr::null_mut(), &mut sz);
254 if sz == 0 { return Err(io::Error::last_os_error()); }
255 let mut v: Vec<u8> = Vec::with_capacity(sz as usize);
256 let err = _NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz);
257 if err != 0 { return Err(io::Error::last_os_error()); }
258 v.set_len(sz as usize - 1); // chop off trailing NUL
259 Ok(PathBuf::from(OsString::from_vec(v)))
260 }
261 }
262
263 pub struct Args {
264 iter: vec::IntoIter<OsString>,
265 _dont_send_or_sync_me: *mut (),
266 }
267
268 impl Iterator for Args {
269 type Item = OsString;
270 fn next(&mut self) -> Option<OsString> { self.iter.next() }
271 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
272 }
273
274 impl ExactSizeIterator for Args {
275 fn len(&self) -> usize { self.iter.len() }
276 }
277
278 /// Returns the command line arguments
279 ///
280 /// Returns a list of the command line arguments.
281 #[cfg(target_os = "macos")]
282 pub fn args() -> Args {
283 extern {
284 // These functions are in crt_externs.h.
285 fn _NSGetArgc() -> *mut c_int;
286 fn _NSGetArgv() -> *mut *mut *mut c_char;
287 }
288
289 let vec = unsafe {
290 let (argc, argv) = (*_NSGetArgc() as isize,
291 *_NSGetArgv() as *const *const c_char);
292 (0.. argc as isize).map(|i| {
293 let bytes = CStr::from_ptr(*argv.offset(i)).to_bytes().to_vec();
294 OsStringExt::from_vec(bytes)
295 }).collect::<Vec<_>>()
296 };
297 Args {
298 iter: vec.into_iter(),
299 _dont_send_or_sync_me: ptr::null_mut(),
300 }
301 }
302
303 // As _NSGetArgc and _NSGetArgv aren't mentioned in iOS docs
304 // and use underscores in their names - they're most probably
305 // are considered private and therefore should be avoided
306 // Here is another way to get arguments using Objective C
307 // runtime
308 //
309 // In general it looks like:
310 // res = Vec::new()
311 // let args = [[NSProcessInfo processInfo] arguments]
312 // for i in (0..[args count])
313 // res.push([args objectAtIndex:i])
314 // res
315 #[cfg(target_os = "ios")]
316 pub fn args() -> Args {
317 use mem;
318
319 #[link(name = "objc")]
320 extern {
321 fn sel_registerName(name: *const libc::c_uchar) -> Sel;
322 fn objc_msgSend(obj: NsId, sel: Sel, ...) -> NsId;
323 fn objc_getClass(class_name: *const libc::c_uchar) -> NsId;
324 }
325
326 #[link(name = "Foundation", kind = "framework")]
327 extern {}
328
329 type Sel = *const libc::c_void;
330 type NsId = *const libc::c_void;
331
332 let mut res = Vec::new();
333
334 unsafe {
335 let process_info_sel = sel_registerName("processInfo\0".as_ptr());
336 let arguments_sel = sel_registerName("arguments\0".as_ptr());
337 let utf8_sel = sel_registerName("UTF8String\0".as_ptr());
338 let count_sel = sel_registerName("count\0".as_ptr());
339 let object_at_sel = sel_registerName("objectAtIndex:\0".as_ptr());
340
341 let klass = objc_getClass("NSProcessInfo\0".as_ptr());
342 let info = objc_msgSend(klass, process_info_sel);
343 let args = objc_msgSend(info, arguments_sel);
344
345 let cnt: usize = mem::transmute(objc_msgSend(args, count_sel));
346 for i in 0..cnt {
347 let tmp = objc_msgSend(args, object_at_sel, i);
348 let utf_c_str: *const libc::c_char =
349 mem::transmute(objc_msgSend(tmp, utf8_sel));
350 let bytes = CStr::from_ptr(utf_c_str).to_bytes();
351 res.push(OsString::from(str::from_utf8(bytes).unwrap()))
352 }
353 }
354
355 Args { iter: res.into_iter(), _dont_send_or_sync_me: ptr::null_mut() }
356 }
357
358 #[cfg(any(target_os = "linux",
359 target_os = "android",
360 target_os = "freebsd",
361 target_os = "dragonfly",
362 target_os = "bitrig",
363 target_os = "netbsd",
364 target_os = "openbsd"))]
365 pub fn args() -> Args {
366 use sys_common;
367 let bytes = sys_common::args::clone().unwrap_or(Vec::new());
368 let v: Vec<OsString> = bytes.into_iter().map(|v| {
369 OsStringExt::from_vec(v)
370 }).collect();
371 Args { iter: v.into_iter(), _dont_send_or_sync_me: ptr::null_mut() }
372 }
373
374 pub struct Env {
375 iter: vec::IntoIter<(OsString, OsString)>,
376 _dont_send_or_sync_me: *mut (),
377 }
378
379 impl Iterator for Env {
380 type Item = (OsString, OsString);
381 fn next(&mut self) -> Option<(OsString, OsString)> { self.iter.next() }
382 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
383 }
384
385 #[cfg(target_os = "macos")]
386 pub unsafe fn environ() -> *mut *const *const c_char {
387 extern { fn _NSGetEnviron() -> *mut *const *const c_char; }
388 _NSGetEnviron()
389 }
390
391 #[cfg(not(target_os = "macos"))]
392 pub unsafe fn environ() -> *mut *const *const c_char {
393 extern { static mut environ: *const *const c_char; }
394 &mut environ
395 }
396
397 /// Returns a vector of (variable, value) byte-vector pairs for all the
398 /// environment variables of the current process.
399 pub fn env() -> Env {
400 return unsafe {
401 let mut environ = *environ();
402 if environ as usize == 0 {
403 panic!("os::env() failure getting env string from OS: {}",
404 io::Error::last_os_error());
405 }
406 let mut result = Vec::new();
407 while *environ != ptr::null() {
408 result.push(parse(CStr::from_ptr(*environ).to_bytes()));
409 environ = environ.offset(1);
410 }
411 Env { iter: result.into_iter(), _dont_send_or_sync_me: ptr::null_mut() }
412 };
413
414 fn parse(input: &[u8]) -> (OsString, OsString) {
415 let mut it = input.splitn(2, |b| *b == b'=');
416 let key = it.next().unwrap().to_vec();
417 let default: &[u8] = &[];
418 let val = it.next().unwrap_or(default).to_vec();
419 (OsStringExt::from_vec(key), OsStringExt::from_vec(val))
420 }
421 }
422
423 pub fn getenv(k: &OsStr) -> Option<OsString> {
424 unsafe {
425 let s = k.to_cstring().unwrap();
426 let s = libc::getenv(s.as_ptr()) as *const _;
427 if s.is_null() {
428 None
429 } else {
430 Some(OsStringExt::from_vec(CStr::from_ptr(s).to_bytes().to_vec()))
431 }
432 }
433 }
434
435 pub fn setenv(k: &OsStr, v: &OsStr) {
436 unsafe {
437 let k = k.to_cstring().unwrap();
438 let v = v.to_cstring().unwrap();
439 if libc::funcs::posix01::unistd::setenv(k.as_ptr(), v.as_ptr(), 1) != 0 {
440 panic!("failed setenv: {}", io::Error::last_os_error());
441 }
442 }
443 }
444
445 pub fn unsetenv(n: &OsStr) {
446 unsafe {
447 let nbuf = n.to_cstring().unwrap();
448 if libc::funcs::posix01::unistd::unsetenv(nbuf.as_ptr()) != 0 {
449 panic!("failed unsetenv: {}", io::Error::last_os_error());
450 }
451 }
452 }
453
454 pub fn page_size() -> usize {
455 unsafe {
456 libc::sysconf(libc::_SC_PAGESIZE) as usize
457 }
458 }
459
460 pub fn temp_dir() -> PathBuf {
461 getenv("TMPDIR".as_ref()).map(PathBuf::from).unwrap_or_else(|| {
462 if cfg!(target_os = "android") {
463 PathBuf::from("/data/local/tmp")
464 } else {
465 PathBuf::from("/tmp")
466 }
467 })
468 }
469
470 pub fn home_dir() -> Option<PathBuf> {
471 return getenv("HOME".as_ref()).or_else(|| unsafe {
472 fallback()
473 }).map(PathBuf::from);
474
475 #[cfg(any(target_os = "android",
476 target_os = "ios"))]
477 unsafe fn fallback() -> Option<OsString> { None }
478 #[cfg(not(any(target_os = "android",
479 target_os = "ios")))]
480 unsafe fn fallback() -> Option<OsString> {
481 let amt = match libc::sysconf(c::_SC_GETPW_R_SIZE_MAX) {
482 n if n < 0 => 512 as usize,
483 n => n as usize,
484 };
485 let me = libc::getuid();
486 loop {
487 let mut buf = Vec::with_capacity(amt);
488 let mut passwd: c::passwd = mem::zeroed();
489 let mut result = ptr::null_mut();
490 match c::getpwuid_r(me, &mut passwd, buf.as_mut_ptr(),
491 buf.capacity() as libc::size_t,
492 &mut result) {
493 0 if !result.is_null() => {}
494 _ => return None
495 }
496 let ptr = passwd.pw_dir as *const _;
497 let bytes = CStr::from_ptr(ptr).to_bytes().to_vec();
498 return Some(OsStringExt::from_vec(bytes))
499 }
500 }
501 }
502
503 pub fn exit(code: i32) -> ! {
504 unsafe { libc::exit(code as c_int) }
505 }