]> git.proxmox.com Git - rustc.git/blob - src/libstd/sys/unix/os.rs
New upstream version 1.14.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 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", target_os = "fuchsia"),
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 #[cfg_attr(target_os = "haiku", link_name = "_errnop")]
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()) < 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()).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 = 0;
204 cvt(libc::sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
205 ptr::null_mut(), &mut sz, ptr::null_mut(), 0))?;
206 if sz == 0 {
207 return Err(io::Error::last_os_error())
208 }
209 let mut v: Vec<u8> = Vec::with_capacity(sz);
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))?;
213 if sz == 0 {
214 return Err(io::Error::last_os_error());
215 }
216 v.set_len(sz - 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 #[cfg(target_os = "haiku")]
307 pub fn current_exe() -> io::Result<PathBuf> {
308 // Use Haiku's image info functions
309 #[repr(C)]
310 struct image_info {
311 id: i32,
312 type_: i32,
313 sequence: i32,
314 init_order: i32,
315 init_routine: *mut libc::c_void, // function pointer
316 term_routine: *mut libc::c_void, // function pointer
317 device: libc::dev_t,
318 node: libc::ino_t,
319 name: [libc::c_char; 1024], // MAXPATHLEN
320 text: *mut libc::c_void,
321 data: *mut libc::c_void,
322 text_size: i32,
323 data_size: i32,
324 api_version: i32,
325 abi: i32,
326 }
327
328 unsafe {
329 extern {
330 fn _get_next_image_info(team_id: i32, cookie: *mut i32,
331 info: *mut image_info, size: i32) -> i32;
332 }
333
334 let mut info: image_info = mem::zeroed();
335 let mut cookie: i32 = 0;
336 // the executable can be found at team id 0
337 let result = _get_next_image_info(0, &mut cookie, &mut info,
338 mem::size_of::<image_info>() as i32);
339 if result != 0 {
340 use io::ErrorKind;
341 Err(io::Error::new(ErrorKind::Other, "Error getting executable path"))
342 } else {
343 let name = CStr::from_ptr(info.name.as_ptr()).to_bytes();
344 Ok(PathBuf::from(OsStr::from_bytes(name)))
345 }
346 }
347 }
348
349 #[cfg(target_os = "fuchsia")]
350 pub fn current_exe() -> io::Result<PathBuf> {
351 use io::ErrorKind;
352 Err(io::Error::new(ErrorKind::Other, "Not yet implemented on fuchsia"))
353 }
354
355 pub struct Env {
356 iter: vec::IntoIter<(OsString, OsString)>,
357 _dont_send_or_sync_me: PhantomData<*mut ()>,
358 }
359
360 impl Iterator for Env {
361 type Item = (OsString, OsString);
362 fn next(&mut self) -> Option<(OsString, OsString)> { self.iter.next() }
363 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
364 }
365
366 #[cfg(target_os = "macos")]
367 pub unsafe fn environ() -> *mut *const *const c_char {
368 extern { fn _NSGetEnviron() -> *mut *const *const c_char; }
369 _NSGetEnviron()
370 }
371
372 #[cfg(not(target_os = "macos"))]
373 pub unsafe fn environ() -> *mut *const *const c_char {
374 extern { static mut environ: *const *const c_char; }
375 &mut environ
376 }
377
378 /// Returns a vector of (variable, value) byte-vector pairs for all the
379 /// environment variables of the current process.
380 pub fn env() -> Env {
381 unsafe {
382 ENV_LOCK.lock();
383 let mut environ = *environ();
384 if environ == ptr::null() {
385 ENV_LOCK.unlock();
386 panic!("os::env() failure getting env string from OS: {}",
387 io::Error::last_os_error());
388 }
389 let mut result = Vec::new();
390 while *environ != ptr::null() {
391 if let Some(key_value) = parse(CStr::from_ptr(*environ).to_bytes()) {
392 result.push(key_value);
393 }
394 environ = environ.offset(1);
395 }
396 let ret = Env {
397 iter: result.into_iter(),
398 _dont_send_or_sync_me: PhantomData,
399 };
400 ENV_LOCK.unlock();
401 return ret
402 }
403
404 fn parse(input: &[u8]) -> Option<(OsString, OsString)> {
405 // Strategy (copied from glibc): Variable name and value are separated
406 // by an ASCII equals sign '='. Since a variable name must not be
407 // empty, allow variable names starting with an equals sign. Skip all
408 // malformed lines.
409 if input.is_empty() {
410 return None;
411 }
412 let pos = memchr::memchr(b'=', &input[1..]).map(|p| p + 1);
413 pos.map(|p| (
414 OsStringExt::from_vec(input[..p].to_vec()),
415 OsStringExt::from_vec(input[p+1..].to_vec()),
416 ))
417 }
418 }
419
420 pub fn getenv(k: &OsStr) -> io::Result<Option<OsString>> {
421 // environment variables with a nul byte can't be set, so their value is
422 // always None as well
423 let k = CString::new(k.as_bytes())?;
424 unsafe {
425 ENV_LOCK.lock();
426 let s = libc::getenv(k.as_ptr()) as *const _;
427 let ret = if s.is_null() {
428 None
429 } else {
430 Some(OsStringExt::from_vec(CStr::from_ptr(s).to_bytes().to_vec()))
431 };
432 ENV_LOCK.unlock();
433 return Ok(ret)
434 }
435 }
436
437 pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> {
438 let k = CString::new(k.as_bytes())?;
439 let v = CString::new(v.as_bytes())?;
440
441 unsafe {
442 ENV_LOCK.lock();
443 let ret = cvt(libc::setenv(k.as_ptr(), v.as_ptr(), 1)).map(|_| ());
444 ENV_LOCK.unlock();
445 return ret
446 }
447 }
448
449 pub fn unsetenv(n: &OsStr) -> io::Result<()> {
450 let nbuf = CString::new(n.as_bytes())?;
451
452 unsafe {
453 ENV_LOCK.lock();
454 let ret = cvt(libc::unsetenv(nbuf.as_ptr())).map(|_| ());
455 ENV_LOCK.unlock();
456 return ret
457 }
458 }
459
460 pub fn page_size() -> usize {
461 unsafe {
462 libc::sysconf(libc::_SC_PAGESIZE) as usize
463 }
464 }
465
466 pub fn temp_dir() -> PathBuf {
467 ::env::var_os("TMPDIR").map(PathBuf::from).unwrap_or_else(|| {
468 if cfg!(target_os = "android") {
469 PathBuf::from("/data/local/tmp")
470 } else {
471 PathBuf::from("/tmp")
472 }
473 })
474 }
475
476 pub fn home_dir() -> Option<PathBuf> {
477 return ::env::var_os("HOME").or_else(|| unsafe {
478 fallback()
479 }).map(PathBuf::from);
480
481 #[cfg(any(target_os = "android",
482 target_os = "ios",
483 target_os = "nacl",
484 target_os = "emscripten"))]
485 unsafe fn fallback() -> Option<OsString> { None }
486 #[cfg(not(any(target_os = "android",
487 target_os = "ios",
488 target_os = "nacl",
489 target_os = "emscripten")))]
490 unsafe fn fallback() -> Option<OsString> {
491 #[cfg(not(target_os = "solaris"))]
492 unsafe fn getpwduid_r(me: libc::uid_t, passwd: &mut libc::passwd,
493 buf: &mut Vec<c_char>) -> Option<()> {
494 let mut result = ptr::null_mut();
495 match libc::getpwuid_r(me, passwd, buf.as_mut_ptr(),
496 buf.capacity(),
497 &mut result) {
498 0 if !result.is_null() => Some(()),
499 _ => None
500 }
501 }
502
503 #[cfg(target_os = "solaris")]
504 unsafe fn getpwduid_r(me: libc::uid_t, passwd: &mut libc::passwd,
505 buf: &mut Vec<c_char>) -> Option<()> {
506 // getpwuid_r semantics is different on Illumos/Solaris:
507 // http://illumos.org/man/3c/getpwuid_r
508 let result = libc::getpwuid_r(me, passwd, buf.as_mut_ptr(),
509 buf.capacity());
510 if result.is_null() { None } else { Some(()) }
511 }
512
513 let amt = match libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) {
514 n if n < 0 => 512 as usize,
515 n => n as usize,
516 };
517 let mut buf = Vec::with_capacity(amt);
518 let mut passwd: libc::passwd = mem::zeroed();
519
520 if getpwduid_r(libc::getuid(), &mut passwd, &mut buf).is_some() {
521 let ptr = passwd.pw_dir as *const _;
522 let bytes = CStr::from_ptr(ptr).to_bytes().to_vec();
523 Some(OsStringExt::from_vec(bytes))
524 } else {
525 None
526 }
527 }
528 }
529
530 pub fn exit(code: i32) -> ! {
531 unsafe { libc::exit(code as c_int) }
532 }