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