]> git.lizzy.rs Git - rust.git/blob - src/libstd/os.rs
Merge remote-tracking branch 'origin/master' into 0.11.0-release
[rust.git] / src / libstd / os.rs
1 // Copyright 2012-2014 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 /*!
12  * Higher-level interfaces to libc::* functions and operating system services.
13  *
14  * In general these take and return rust types, use rust idioms (enums,
15  * closures, vectors) rather than C idioms, and do more extensive safety
16  * checks.
17  *
18  * This module is not meant to only contain 1:1 mappings to libc entries; any
19  * os-interface code that is reasonably useful and broadly applicable can go
20  * here. Including utility routines that merely build on other os code.
21  *
22  * We assume the general case is that users do not care, and do not want to
23  * be made to care, which operating system they are on. While they may want
24  * to special case various special cases -- and so we will not _hide_ the
25  * facts of which OS the user is on -- they should be given the opportunity
26  * to write OS-ignorant code by default.
27  */
28
29 #![experimental]
30
31 #![allow(missing_doc)]
32 #![allow(non_snake_case_functions)]
33
34 use clone::Clone;
35 use collections::Collection;
36 use fmt;
37 use io::{IoResult, IoError};
38 use iter::Iterator;
39 use libc::{c_void, c_int};
40 use libc;
41 use ops::Drop;
42 use option::{Some, None, Option};
43 use os;
44 use path::{Path, GenericPath, BytesContainer};
45 use ptr::RawPtr;
46 use ptr;
47 use result::{Err, Ok, Result};
48 use slice::{Vector, ImmutableVector, MutableVector};
49 use str::{Str, StrSlice, StrAllocating};
50 use str;
51 use string::String;
52 use sync::atomics::{AtomicInt, INIT_ATOMIC_INT, SeqCst};
53 use vec::Vec;
54
55 #[cfg(unix)]
56 use c_str::ToCStr;
57 #[cfg(unix)]
58 use libc::c_char;
59 #[cfg(windows)]
60 use str::OwnedStr;
61
62 /// Get the number of cores available
63 pub fn num_cpus() -> uint {
64     unsafe {
65         return rust_get_num_cpus();
66     }
67
68     extern {
69         fn rust_get_num_cpus() -> libc::uintptr_t;
70     }
71 }
72
73 pub static TMPBUF_SZ : uint = 1000u;
74 static BUF_BYTES : uint = 2048u;
75
76 /// Returns the current working directory as a Path.
77 ///
78 /// # Failure
79 ///
80 /// Fails if the current working directory value is invalid:
81 /// Possibles cases:
82 ///
83 /// * Current directory does not exist.
84 /// * There are insufficient permissions to access the current directory.
85 ///
86 /// # Example
87 ///
88 /// ```rust
89 /// use std::os;
90 ///
91 /// // We assume that we are in a valid directory like "/home".
92 /// let current_working_directory = os::getcwd();
93 /// println!("The current directory is {}", current_working_directory.display());
94 /// // /home
95 /// ```
96 #[cfg(unix)]
97 pub fn getcwd() -> Path {
98     use c_str::CString;
99
100     let mut buf = [0 as c_char, ..BUF_BYTES];
101     unsafe {
102         if libc::getcwd(buf.as_mut_ptr(), buf.len() as libc::size_t).is_null() {
103             fail!()
104         }
105         Path::new(CString::new(buf.as_ptr(), false))
106     }
107 }
108
109 /// Returns the current working directory as a Path.
110 ///
111 /// # Failure
112 ///
113 /// Fails if the current working directory value is invalid.
114 /// Possibles cases:
115 ///
116 /// * Current directory does not exist.
117 /// * There are insufficient permissions to access the current directory.
118 ///
119 /// # Example
120 ///
121 /// ```rust
122 /// use std::os;
123 ///
124 /// // We assume that we are in a valid directory like "C:\\Windows".
125 /// let current_working_directory = os::getcwd();
126 /// println!("The current directory is {}", current_working_directory.display());
127 /// // C:\\Windows
128 /// ```
129 #[cfg(windows)]
130 pub fn getcwd() -> Path {
131     use libc::DWORD;
132     use libc::GetCurrentDirectoryW;
133
134     let mut buf = [0 as u16, ..BUF_BYTES];
135     unsafe {
136         if libc::GetCurrentDirectoryW(buf.len() as DWORD, buf.as_mut_ptr()) == 0 as DWORD {
137             fail!();
138         }
139     }
140     Path::new(str::from_utf16(str::truncate_utf16_at_nul(buf))
141               .expect("GetCurrentDirectoryW returned invalid UTF-16"))
142 }
143
144 #[cfg(windows)]
145 pub mod win32 {
146     use libc::types::os::arch::extra::DWORD;
147     use libc;
148     use option::{None, Option};
149     use option;
150     use os::TMPBUF_SZ;
151     use slice::{MutableVector, ImmutableVector};
152     use string::String;
153     use str::StrSlice;
154     use str;
155     use vec::Vec;
156
157     pub fn fill_utf16_buf_and_decode(f: |*mut u16, DWORD| -> DWORD)
158         -> Option<String> {
159
160         unsafe {
161             let mut n = TMPBUF_SZ as DWORD;
162             let mut res = None;
163             let mut done = false;
164             while !done {
165                 let mut buf = Vec::from_elem(n as uint, 0u16);
166                 let k = f(buf.as_mut_ptr(), n);
167                 if k == (0 as DWORD) {
168                     done = true;
169                 } else if k == n &&
170                           libc::GetLastError() ==
171                           libc::ERROR_INSUFFICIENT_BUFFER as DWORD {
172                     n *= 2 as DWORD;
173                 } else if k >= n {
174                     n = k;
175                 } else {
176                     done = true;
177                 }
178                 if k != 0 && done {
179                     let sub = buf.slice(0, k as uint);
180                     // We want to explicitly catch the case when the
181                     // closure returned invalid UTF-16, rather than
182                     // set `res` to None and continue.
183                     let s = str::from_utf16(sub)
184                         .expect("fill_utf16_buf_and_decode: closure created invalid UTF-16");
185                     res = option::Some(s)
186                 }
187             }
188             return res;
189         }
190     }
191 }
192
193 /*
194 Accessing environment variables is not generally threadsafe.
195 Serialize access through a global lock.
196 */
197 fn with_env_lock<T>(f: || -> T) -> T {
198     use rt::mutex::{StaticNativeMutex, NATIVE_MUTEX_INIT};
199
200     static mut lock: StaticNativeMutex = NATIVE_MUTEX_INIT;
201
202     unsafe {
203         let _guard = lock.lock();
204         f()
205     }
206 }
207
208 /// Returns a vector of (variable, value) pairs, for all the environment
209 /// variables of the current process.
210 ///
211 /// Invalid UTF-8 bytes are replaced with \uFFFD. See `str::from_utf8_lossy()`
212 /// for details.
213 ///
214 /// # Example
215 ///
216 /// ```rust
217 /// use std::os;
218 ///
219 /// // We will iterate through the references to the element returned by os::env();
220 /// for &(ref key, ref value) in os::env().iter() {
221 ///     println!("'{}': '{}'", key, value );
222 /// }
223 /// ```
224 pub fn env() -> Vec<(String,String)> {
225     env_as_bytes().move_iter().map(|(k,v)| {
226         let k = str::from_utf8_lossy(k.as_slice()).to_string();
227         let v = str::from_utf8_lossy(v.as_slice()).to_string();
228         (k,v)
229     }).collect()
230 }
231
232 /// Returns a vector of (variable, value) byte-vector pairs for all the
233 /// environment variables of the current process.
234 pub fn env_as_bytes() -> Vec<(Vec<u8>,Vec<u8>)> {
235     unsafe {
236         #[cfg(windows)]
237         unsafe fn get_env_pairs() -> Vec<Vec<u8>> {
238             use slice::raw;
239
240             use libc::funcs::extra::kernel32::{
241                 GetEnvironmentStringsW,
242                 FreeEnvironmentStringsW
243             };
244             let ch = GetEnvironmentStringsW();
245             if ch as uint == 0 {
246                 fail!("os::env() failure getting env string from OS: {}",
247                        os::last_os_error());
248             }
249             // Here, we lossily decode the string as UTF16.
250             //
251             // The docs suggest that the result should be in Unicode, but
252             // Windows doesn't guarantee it's actually UTF16 -- it doesn't
253             // validate the environment string passed to CreateProcess nor
254             // SetEnvironmentVariable.  Yet, it's unlikely that returning a
255             // raw u16 buffer would be of practical use since the result would
256             // be inherently platform-dependent and introduce additional
257             // complexity to this code.
258             //
259             // Using the non-Unicode version of GetEnvironmentStrings is even
260             // worse since the result is in an OEM code page.  Characters that
261             // can't be encoded in the code page would be turned into question
262             // marks.
263             let mut result = Vec::new();
264             let mut i = 0;
265             while *ch.offset(i) != 0 {
266                 let p = &*ch.offset(i);
267                 let len = ptr::position(p, |c| *c == 0);
268                 raw::buf_as_slice(p, len, |s| {
269                     result.push(str::from_utf16_lossy(s).into_bytes());
270                 });
271                 i += len as int + 1;
272             }
273             FreeEnvironmentStringsW(ch);
274             result
275         }
276         #[cfg(unix)]
277         unsafe fn get_env_pairs() -> Vec<Vec<u8>> {
278             use c_str::CString;
279
280             extern {
281                 fn rust_env_pairs() -> *const *const c_char;
282             }
283             let environ = rust_env_pairs();
284             if environ as uint == 0 {
285                 fail!("os::env() failure getting env string from OS: {}",
286                        os::last_os_error());
287             }
288             let mut result = Vec::new();
289             ptr::array_each(environ, |e| {
290                 let env_pair =
291                     Vec::from_slice(CString::new(e, false).as_bytes_no_nul());
292                 result.push(env_pair);
293             });
294             result
295         }
296
297         fn env_convert(input: Vec<Vec<u8>>) -> Vec<(Vec<u8>, Vec<u8>)> {
298             let mut pairs = Vec::new();
299             for p in input.iter() {
300                 let mut it = p.as_slice().splitn(1, |b| *b == '=' as u8);
301                 let key = Vec::from_slice(it.next().unwrap());
302                 let val = Vec::from_slice(it.next().unwrap_or(&[]));
303                 pairs.push((key, val));
304             }
305             pairs
306         }
307         with_env_lock(|| {
308             let unparsed_environ = get_env_pairs();
309             env_convert(unparsed_environ)
310         })
311     }
312 }
313
314 #[cfg(unix)]
315 /// Fetches the environment variable `n` from the current process, returning
316 /// None if the variable isn't set.
317 ///
318 /// Any invalid UTF-8 bytes in the value are replaced by \uFFFD. See
319 /// `str::from_utf8_lossy()` for details.
320 ///
321 /// # Failure
322 ///
323 /// Fails if `n` has any interior NULs.
324 ///
325 /// # Example
326 ///
327 /// ```rust
328 /// use std::os;
329 ///
330 /// let key = "HOME";
331 /// match os::getenv(key) {
332 ///     Some(val) => println!("{}: {}", key, val),
333 ///     None => println!("{} is not defined in the environment.", key)
334 /// }
335 /// ```
336 pub fn getenv(n: &str) -> Option<String> {
337     getenv_as_bytes(n).map(|v| str::from_utf8_lossy(v.as_slice()).to_string())
338 }
339
340 #[cfg(unix)]
341 /// Fetches the environment variable `n` byte vector from the current process,
342 /// returning None if the variable isn't set.
343 ///
344 /// # Failure
345 ///
346 /// Fails if `n` has any interior NULs.
347 pub fn getenv_as_bytes(n: &str) -> Option<Vec<u8>> {
348     use c_str::CString;
349
350     unsafe {
351         with_env_lock(|| {
352             let s = n.with_c_str(|buf| libc::getenv(buf));
353             if s.is_null() {
354                 None
355             } else {
356                 Some(Vec::from_slice(CString::new(s as *const i8,
357                                                   false).as_bytes_no_nul()))
358             }
359         })
360     }
361 }
362
363 #[cfg(windows)]
364 /// Fetches the environment variable `n` from the current process, returning
365 /// None if the variable isn't set.
366 pub fn getenv(n: &str) -> Option<String> {
367     unsafe {
368         with_env_lock(|| {
369             use os::win32::{fill_utf16_buf_and_decode};
370             let n: Vec<u16> = n.utf16_units().collect();
371             let n = n.append_one(0);
372             fill_utf16_buf_and_decode(|buf, sz| {
373                 libc::GetEnvironmentVariableW(n.as_ptr(), buf, sz)
374             })
375         })
376     }
377 }
378
379 #[cfg(windows)]
380 /// Fetches the environment variable `n` byte vector from the current process,
381 /// returning None if the variable isn't set.
382 pub fn getenv_as_bytes(n: &str) -> Option<Vec<u8>> {
383     getenv(n).map(|s| s.into_bytes())
384 }
385
386 /// Sets the environment variable `n` to the value `v` for the currently running
387 /// process.
388 ///
389 /// # Example
390 ///
391 /// ```rust
392 /// use std::os;
393 ///
394 /// let key = "KEY";
395 /// os::setenv(key, "VALUE");
396 /// match os::getenv(key) {
397 ///     Some(ref val) => println!("{}: {}", key, val),
398 ///     None => println!("{} is not defined in the environment.", key)
399 /// }
400 /// ```
401 pub fn setenv(n: &str, v: &str) {
402     #[cfg(unix)]
403     fn _setenv(n: &str, v: &str) {
404         unsafe {
405             with_env_lock(|| {
406                 n.with_c_str(|nbuf| {
407                     v.with_c_str(|vbuf| {
408                         libc::funcs::posix01::unistd::setenv(nbuf, vbuf, 1);
409                     })
410                 })
411             })
412         }
413     }
414
415     #[cfg(windows)]
416     fn _setenv(n: &str, v: &str) {
417         let n: Vec<u16> = n.utf16_units().collect();
418         let n = n.append_one(0);
419         let v: Vec<u16> = v.utf16_units().collect();
420         let v = v.append_one(0);
421         unsafe {
422             with_env_lock(|| {
423                 libc::SetEnvironmentVariableW(n.as_ptr(), v.as_ptr());
424             })
425         }
426     }
427     _setenv(n, v)
428 }
429
430 /// Remove a variable from the environment entirely.
431 pub fn unsetenv(n: &str) {
432     #[cfg(unix)]
433     fn _unsetenv(n: &str) {
434         unsafe {
435             with_env_lock(|| {
436                 n.with_c_str(|nbuf| {
437                     libc::funcs::posix01::unistd::unsetenv(nbuf);
438                 })
439             })
440         }
441     }
442
443     #[cfg(windows)]
444     fn _unsetenv(n: &str) {
445         let n: Vec<u16> = n.utf16_units().collect();
446         let n = n.append_one(0);
447         unsafe {
448             with_env_lock(|| {
449                 libc::SetEnvironmentVariableW(n.as_ptr(), ptr::null());
450             })
451         }
452     }
453     _unsetenv(n);
454 }
455
456 #[cfg(unix)]
457 /// Parse a string or vector according to the platform's conventions
458 /// for the `PATH` environment variable and return a Vec<Path>.
459 /// Drops empty paths.
460 ///
461 /// # Example
462 /// ```rust
463 /// use std::os;
464 ///
465 /// let key = "PATH";
466 /// match os::getenv(key) {
467 ///     Some(paths) => {
468 ///         for path in os::split_paths(paths).iter() {
469 ///             println!("'{}'", path.display());
470 ///         }
471 ///     }
472 ///     None => println!("{} is not defined in the environnement.", key)
473 /// }
474 /// ```
475 pub fn split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> {
476     unparsed.container_as_bytes()
477             .split(|b| *b == ':' as u8)
478             .filter(|s| s.len() > 0)
479             .map(Path::new)
480             .collect()
481 }
482
483 #[cfg(windows)]
484 /// Parse a string or vector according to the platform's conventions
485 /// for the `PATH` environment variable. Drops empty paths.
486 pub fn split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> {
487     // On Windows, the PATH environment variable is semicolon separated.  Double
488     // quotes are used as a way of introducing literal semicolons (since
489     // c:\some;dir is a valid Windows path). Double quotes are not themselves
490     // permitted in path names, so there is no way to escape a double quote.
491     // Quoted regions can appear in arbitrary locations, so
492     //
493     //   c:\foo;c:\som"e;di"r;c:\bar
494     //
495     // Should parse as [c:\foo, c:\some;dir, c:\bar].
496     //
497     // (The above is based on testing; there is no clear reference available
498     // for the grammar.)
499
500     let mut parsed = Vec::new();
501     let mut in_progress = Vec::new();
502     let mut in_quote = false;
503
504     for b in unparsed.container_as_bytes().iter() {
505         match *b as char {
506             ';' if !in_quote => {
507                 // ignore zero-length path strings
508                 if in_progress.len() > 0 {
509                     parsed.push(Path::new(in_progress.as_slice()));
510                 }
511                 in_progress.truncate(0)
512             }
513             '\"' => {
514                 in_quote = !in_quote;
515             }
516             _  => {
517                 in_progress.push(*b);
518             }
519         }
520     }
521
522     if in_progress.len() > 0 {
523         parsed.push(Path::new(in_progress));
524     }
525
526     parsed
527 }
528
529 /// A low-level OS in-memory pipe.
530 pub struct Pipe {
531     /// A file descriptor representing the reading end of the pipe. Data written
532     /// on the `out` file descriptor can be read from this file descriptor.
533     pub reader: c_int,
534     /// A file descriptor representing the write end of the pipe. Data written
535     /// to this file descriptor can be read from the `input` file descriptor.
536     pub writer: c_int,
537 }
538
539 /// Creates a new low-level OS in-memory pipe.
540 ///
541 /// This function can fail to succeed if there are no more resources available
542 /// to allocate a pipe.
543 ///
544 /// This function is also unsafe as there is no destructor associated with the
545 /// `Pipe` structure will return. If it is not arranged for the returned file
546 /// descriptors to be closed, the file descriptors will leak. For safe handling
547 /// of this scenario, use `std::io::PipeStream` instead.
548 pub unsafe fn pipe() -> IoResult<Pipe> {
549     return _pipe();
550
551     #[cfg(unix)]
552     unsafe fn _pipe() -> IoResult<Pipe> {
553         let mut fds = [0, ..2];
554         match libc::pipe(fds.as_mut_ptr()) {
555             0 => Ok(Pipe { reader: fds[0], writer: fds[1] }),
556             _ => Err(IoError::last_error()),
557         }
558     }
559
560     #[cfg(windows)]
561     unsafe fn _pipe() -> IoResult<Pipe> {
562         // Windows pipes work subtly differently than unix pipes, and their
563         // inheritance has to be handled in a different way that I do not
564         // fully understand. Here we explicitly make the pipe non-inheritable,
565         // which means to pass it to a subprocess they need to be duplicated
566         // first, as in std::run.
567         let mut fds = [0, ..2];
568         match libc::pipe(fds.as_mut_ptr(), 1024 as ::libc::c_uint,
569                          (libc::O_BINARY | libc::O_NOINHERIT) as c_int) {
570             0 => {
571                 assert!(fds[0] != -1 && fds[0] != 0);
572                 assert!(fds[1] != -1 && fds[1] != 0);
573                 Ok(Pipe { reader: fds[0], writer: fds[1] })
574             }
575             _ => Err(IoError::last_error()),
576         }
577     }
578 }
579
580 /// Returns the proper dll filename for the given basename of a file
581 /// as a String.
582 #[cfg(not(target_os="ios"))]
583 pub fn dll_filename(base: &str) -> String {
584     format!("{}{}{}", consts::DLL_PREFIX, base, consts::DLL_SUFFIX)
585 }
586
587 /// Optionally returns the filesystem path to the current executable which is
588 /// running but with the executable name.
589 ///
590 /// # Examples
591 ///
592 /// ```rust
593 /// use std::os;
594 ///
595 /// match os::self_exe_name() {
596 ///     Some(exe_path) => println!("Path of this executable is: {}", exe_path.display()),
597 ///     None => println!("Unable to get the path of this executable!")
598 /// };
599 /// ```
600 pub fn self_exe_name() -> Option<Path> {
601
602     #[cfg(target_os = "freebsd")]
603     fn load_self() -> Option<Vec<u8>> {
604         unsafe {
605             use libc::funcs::bsd44::*;
606             use libc::consts::os::extra::*;
607             let mut mib = vec![CTL_KERN as c_int,
608                                KERN_PROC as c_int,
609                                KERN_PROC_PATHNAME as c_int,
610                                -1 as c_int];
611             let mut sz: libc::size_t = 0;
612             let err = sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
613                              ptr::mut_null(), &mut sz, ptr::mut_null(),
614                              0u as libc::size_t);
615             if err != 0 { return None; }
616             if sz == 0 { return None; }
617             let mut v: Vec<u8> = Vec::with_capacity(sz as uint);
618             let err = sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
619                              v.as_mut_ptr() as *mut c_void, &mut sz,
620                              ptr::mut_null(), 0u as libc::size_t);
621             if err != 0 { return None; }
622             if sz == 0 { return None; }
623             v.set_len(sz as uint - 1); // chop off trailing NUL
624             Some(v)
625         }
626     }
627
628     #[cfg(target_os = "linux")]
629     #[cfg(target_os = "android")]
630     fn load_self() -> Option<Vec<u8>> {
631         use std::io;
632
633         match io::fs::readlink(&Path::new("/proc/self/exe")) {
634             Ok(path) => Some(path.into_vec()),
635             Err(..) => None
636         }
637     }
638
639     #[cfg(target_os = "macos")]
640     #[cfg(target_os = "ios")]
641     fn load_self() -> Option<Vec<u8>> {
642         unsafe {
643             use libc::funcs::extra::_NSGetExecutablePath;
644             let mut sz: u32 = 0;
645             _NSGetExecutablePath(ptr::mut_null(), &mut sz);
646             if sz == 0 { return None; }
647             let mut v: Vec<u8> = Vec::with_capacity(sz as uint);
648             let err = _NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz);
649             if err != 0 { return None; }
650             v.set_len(sz as uint - 1); // chop off trailing NUL
651             Some(v)
652         }
653     }
654
655     #[cfg(windows)]
656     fn load_self() -> Option<Vec<u8>> {
657         use str::OwnedStr;
658
659         unsafe {
660             use os::win32::fill_utf16_buf_and_decode;
661             fill_utf16_buf_and_decode(|buf, sz| {
662                 libc::GetModuleFileNameW(0u as libc::DWORD, buf, sz)
663             }).map(|s| s.into_string().into_bytes())
664         }
665     }
666
667     load_self().and_then(Path::new_opt)
668 }
669
670 /// Optionally returns the filesystem path to the current executable which is
671 /// running.
672 ///
673 /// Like self_exe_name() but without the binary's name.
674 ///
675 /// # Example
676 ///
677 /// ```rust
678 /// use std::os;
679 ///
680 /// match os::self_exe_path() {
681 ///     Some(exe_path) => println!("Executable's Path is: {}", exe_path.display()),
682 ///     None => println!("Impossible to fetch the path of this executable.")
683 /// };
684 /// ```
685 pub fn self_exe_path() -> Option<Path> {
686     self_exe_name().map(|mut p| { p.pop(); p })
687 }
688
689 /// Optionally returns the path to the current user's home directory if known.
690 ///
691 /// # Unix
692 ///
693 /// Returns the value of the 'HOME' environment variable if it is set
694 /// and not equal to the empty string.
695 ///
696 /// # Windows
697 ///
698 /// Returns the value of the 'HOME' environment variable if it is
699 /// set and not equal to the empty string. Otherwise, returns the value of the
700 /// 'USERPROFILE' environment variable if it is set and not equal to the empty
701 /// string.
702 ///
703 /// # Example
704 ///
705 /// ```rust
706 /// use std::os;
707 ///
708 /// match os::homedir() {
709 ///     Some(ref p) => println!("{}", p.display()),
710 ///     None => println!("Impossible to get your home dir!")
711 /// }
712 /// ```
713 pub fn homedir() -> Option<Path> {
714     #[inline]
715     #[cfg(unix)]
716     fn _homedir() -> Option<Path> {
717         aux_homedir("HOME")
718     }
719
720     #[inline]
721     #[cfg(windows)]
722     fn _homedir() -> Option<Path> {
723         aux_homedir("HOME").or(aux_homedir("USERPROFILE"))
724     }
725
726     #[inline]
727     fn aux_homedir(home_name: &str) -> Option<Path> {
728         match getenv_as_bytes(home_name) {
729             Some(p)  => {
730                 if p.is_empty() { None } else { Path::new_opt(p) }
731             },
732             _ => None
733         }
734     }
735     _homedir()
736 }
737
738 /**
739  * Returns the path to a temporary directory.
740  *
741  * On Unix, returns the value of the 'TMPDIR' environment variable if it is
742  * set, otherwise for non-Android it returns '/tmp'. If Android, since there
743  * is no global temporary folder (it is usually allocated per-app), we return
744  * '/data/local/tmp'.
745  *
746  * On Windows, returns the value of, in order, the 'TMP', 'TEMP',
747  * 'USERPROFILE' environment variable  if any are set and not the empty
748  * string. Otherwise, tmpdir returns the path to the Windows directory.
749  */
750 pub fn tmpdir() -> Path {
751     return lookup();
752
753     fn getenv_nonempty(v: &str) -> Option<Path> {
754         match getenv(v) {
755             Some(x) =>
756                 if x.is_empty() {
757                     None
758                 } else {
759                     Path::new_opt(x)
760                 },
761             _ => None
762         }
763     }
764
765     #[cfg(unix)]
766     fn lookup() -> Path {
767         let default = if cfg!(target_os = "android") {
768             Path::new("/data/local/tmp")
769         } else {
770             Path::new("/tmp")
771         };
772
773         getenv_nonempty("TMPDIR").unwrap_or(default)
774     }
775
776     #[cfg(windows)]
777     fn lookup() -> Path {
778         getenv_nonempty("TMP").or(
779             getenv_nonempty("TEMP").or(
780                 getenv_nonempty("USERPROFILE").or(
781                    getenv_nonempty("WINDIR")))).unwrap_or(Path::new("C:\\Windows"))
782     }
783 }
784
785 /**
786  * Convert a relative path to an absolute path
787  *
788  * If the given path is relative, return it prepended with the current working
789  * directory. If the given path is already an absolute path, return it
790  * as is.
791  */
792 // NB: this is here rather than in path because it is a form of environment
793 // querying; what it does depends on the process working directory, not just
794 // the input paths.
795 pub fn make_absolute(p: &Path) -> Path {
796     if p.is_absolute() {
797         p.clone()
798     } else {
799         let mut ret = getcwd();
800         ret.push(p);
801         ret
802     }
803 }
804
805 /// Changes the current working directory to the specified path, returning
806 /// whether the change was completed successfully or not.
807 pub fn change_dir(p: &Path) -> bool {
808     return chdir(p);
809
810     #[cfg(windows)]
811     fn chdir(p: &Path) -> bool {
812         let p = match p.as_str() {
813             Some(s) => s.utf16_units().collect::<Vec<u16>>().append_one(0),
814             None => return false,
815         };
816         unsafe {
817             libc::SetCurrentDirectoryW(p.as_ptr()) != (0 as libc::BOOL)
818         }
819     }
820
821     #[cfg(unix)]
822     fn chdir(p: &Path) -> bool {
823         p.with_c_str(|buf| {
824             unsafe {
825                 libc::chdir(buf) == (0 as c_int)
826             }
827         })
828     }
829 }
830
831 #[cfg(unix)]
832 /// Returns the platform-specific value of errno
833 pub fn errno() -> int {
834     #[cfg(target_os = "macos")]
835     #[cfg(target_os = "ios")]
836     #[cfg(target_os = "freebsd")]
837     fn errno_location() -> *const c_int {
838         extern {
839             fn __error() -> *const c_int;
840         }
841         unsafe {
842             __error()
843         }
844     }
845
846     #[cfg(target_os = "linux")]
847     #[cfg(target_os = "android")]
848     fn errno_location() -> *const c_int {
849         extern {
850             fn __errno_location() -> *const c_int;
851         }
852         unsafe {
853             __errno_location()
854         }
855     }
856
857     unsafe {
858         (*errno_location()) as int
859     }
860 }
861
862 #[cfg(windows)]
863 /// Returns the platform-specific value of errno
864 pub fn errno() -> uint {
865     use libc::types::os::arch::extra::DWORD;
866
867     #[link_name = "kernel32"]
868     extern "system" {
869         fn GetLastError() -> DWORD;
870     }
871
872     unsafe {
873         GetLastError() as uint
874     }
875 }
876
877 /// Return the string corresponding to an `errno()` value of `errnum`.
878 pub fn error_string(errnum: uint) -> String {
879     return strerror(errnum);
880
881     #[cfg(unix)]
882     fn strerror(errnum: uint) -> String {
883         #[cfg(target_os = "macos")]
884         #[cfg(target_os = "ios")]
885         #[cfg(target_os = "android")]
886         #[cfg(target_os = "freebsd")]
887         fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: libc::size_t)
888                       -> c_int {
889             extern {
890                 fn strerror_r(errnum: c_int, buf: *mut c_char,
891                               buflen: libc::size_t) -> c_int;
892             }
893             unsafe {
894                 strerror_r(errnum, buf, buflen)
895             }
896         }
897
898         // GNU libc provides a non-compliant version of strerror_r by default
899         // and requires macros to instead use the POSIX compliant variant.
900         // So we just use __xpg_strerror_r which is always POSIX compliant
901         #[cfg(target_os = "linux")]
902         fn strerror_r(errnum: c_int, buf: *mut c_char,
903                       buflen: libc::size_t) -> c_int {
904             extern {
905                 fn __xpg_strerror_r(errnum: c_int,
906                                     buf: *mut c_char,
907                                     buflen: libc::size_t)
908                                     -> c_int;
909             }
910             unsafe {
911                 __xpg_strerror_r(errnum, buf, buflen)
912             }
913         }
914
915         let mut buf = [0 as c_char, ..TMPBUF_SZ];
916
917         let p = buf.as_mut_ptr();
918         unsafe {
919             if strerror_r(errnum as c_int, p, buf.len() as libc::size_t) < 0 {
920                 fail!("strerror_r failure");
921             }
922
923             str::raw::from_c_str(p as *const c_char).into_string()
924         }
925     }
926
927     #[cfg(windows)]
928     fn strerror(errnum: uint) -> String {
929         use libc::types::os::arch::extra::DWORD;
930         use libc::types::os::arch::extra::LPWSTR;
931         use libc::types::os::arch::extra::LPVOID;
932         use libc::types::os::arch::extra::WCHAR;
933
934         #[link_name = "kernel32"]
935         extern "system" {
936             fn FormatMessageW(flags: DWORD,
937                               lpSrc: LPVOID,
938                               msgId: DWORD,
939                               langId: DWORD,
940                               buf: LPWSTR,
941                               nsize: DWORD,
942                               args: *const c_void)
943                               -> DWORD;
944         }
945
946         static FORMAT_MESSAGE_FROM_SYSTEM: DWORD = 0x00001000;
947         static FORMAT_MESSAGE_IGNORE_INSERTS: DWORD = 0x00000200;
948
949         // This value is calculated from the macro
950         // MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT)
951         let langId = 0x0800 as DWORD;
952
953         let mut buf = [0 as WCHAR, ..TMPBUF_SZ];
954
955         unsafe {
956             let res = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
957                                      FORMAT_MESSAGE_IGNORE_INSERTS,
958                                      ptr::mut_null(),
959                                      errnum as DWORD,
960                                      langId,
961                                      buf.as_mut_ptr(),
962                                      buf.len() as DWORD,
963                                      ptr::null());
964             if res == 0 {
965                 // Sometimes FormatMessageW can fail e.g. system doesn't like langId,
966                 let fm_err = errno();
967                 return format!("OS Error {} (FormatMessageW() returned error {})", errnum, fm_err);
968             }
969
970             let msg = str::from_utf16(str::truncate_utf16_at_nul(buf));
971             match msg {
972                 Some(msg) => format!("OS Error {}: {}", errnum, msg),
973                 None => format!("OS Error {} (FormatMessageW() returned invalid UTF-16)", errnum),
974             }
975         }
976     }
977 }
978
979 /// Get a string representing the platform-dependent last error
980 pub fn last_os_error() -> String {
981     error_string(errno() as uint)
982 }
983
984 static mut EXIT_STATUS: AtomicInt = INIT_ATOMIC_INT;
985
986 /**
987  * Sets the process exit code
988  *
989  * Sets the exit code returned by the process if all supervised tasks
990  * terminate successfully (without failing). If the current root task fails
991  * and is supervised by the scheduler then any user-specified exit status is
992  * ignored and the process exits with the default failure status.
993  *
994  * Note that this is not synchronized against modifications of other threads.
995  */
996 pub fn set_exit_status(code: int) {
997     unsafe { EXIT_STATUS.store(code, SeqCst) }
998 }
999
1000 /// Fetches the process's current exit code. This defaults to 0 and can change
1001 /// by calling `set_exit_status`.
1002 pub fn get_exit_status() -> int {
1003     unsafe { EXIT_STATUS.load(SeqCst) }
1004 }
1005
1006 #[cfg(target_os = "macos")]
1007 unsafe fn load_argc_and_argv(argc: int,
1008                              argv: *const *const c_char) -> Vec<Vec<u8>> {
1009     use c_str::CString;
1010
1011     Vec::from_fn(argc as uint, |i| {
1012         Vec::from_slice(CString::new(*argv.offset(i as int),
1013                                      false).as_bytes_no_nul())
1014     })
1015 }
1016
1017 /**
1018  * Returns the command line arguments
1019  *
1020  * Returns a list of the command line arguments.
1021  */
1022 #[cfg(target_os = "macos")]
1023 fn real_args_as_bytes() -> Vec<Vec<u8>> {
1024     unsafe {
1025         let (argc, argv) = (*_NSGetArgc() as int,
1026                             *_NSGetArgv() as *const *const c_char);
1027         load_argc_and_argv(argc, argv)
1028     }
1029 }
1030
1031 // As _NSGetArgc and _NSGetArgv aren't mentioned in iOS docs
1032 // and use underscores in their names - they're most probably
1033 // are considered private and therefore should be avoided
1034 // Here is another way to get arguments using Objective C
1035 // runtime
1036 //
1037 // In general it looks like:
1038 // res = Vec::new()
1039 // let args = [[NSProcessInfo processInfo] arguments]
1040 // for i in range(0, [args count])
1041 //      res.push([args objectAtIndex:i])
1042 // res
1043 #[cfg(target_os = "ios")]
1044 fn real_args_as_bytes() -> Vec<Vec<u8>> {
1045     use c_str::CString;
1046     use iter::range;
1047     use mem;
1048
1049     #[link(name = "objc")]
1050     extern {
1051         fn sel_registerName(name: *const libc::c_uchar) -> Sel;
1052         fn objc_msgSend(obj: NsId, sel: Sel, ...) -> NsId;
1053         fn objc_getClass(class_name: *const libc::c_uchar) -> NsId;
1054     }
1055
1056     #[link(name = "Foundation", kind = "framework")]
1057     extern {}
1058
1059     type Sel = *const libc::c_void;
1060     type NsId = *const libc::c_void;
1061
1062     let mut res = Vec::new();
1063
1064     unsafe {
1065         let processInfoSel = sel_registerName("processInfo\0".as_ptr());
1066         let argumentsSel = sel_registerName("arguments\0".as_ptr());
1067         let utf8Sel = sel_registerName("UTF8String\0".as_ptr());
1068         let countSel = sel_registerName("count\0".as_ptr());
1069         let objectAtSel = sel_registerName("objectAtIndex:\0".as_ptr());
1070
1071         let klass = objc_getClass("NSProcessInfo\0".as_ptr());
1072         let info = objc_msgSend(klass, processInfoSel);
1073         let args = objc_msgSend(info, argumentsSel);
1074
1075         let cnt: int = mem::transmute(objc_msgSend(args, countSel));
1076         for i in range(0, cnt) {
1077             let tmp = objc_msgSend(args, objectAtSel, i);
1078             let utf_c_str: *const libc::c_char =
1079                 mem::transmute(objc_msgSend(tmp, utf8Sel));
1080             let s = CString::new(utf_c_str, false);
1081             if s.is_not_null() {
1082                 res.push(Vec::from_slice(s.as_bytes_no_nul()))
1083             }
1084         }
1085     }
1086
1087     res
1088 }
1089
1090 #[cfg(target_os = "linux")]
1091 #[cfg(target_os = "android")]
1092 #[cfg(target_os = "freebsd")]
1093 fn real_args_as_bytes() -> Vec<Vec<u8>> {
1094     use rt;
1095
1096     match rt::args::clone() {
1097         Some(args) => args,
1098         None => fail!("process arguments not initialized")
1099     }
1100 }
1101
1102 #[cfg(not(windows))]
1103 fn real_args() -> Vec<String> {
1104     real_args_as_bytes().move_iter()
1105                         .map(|v| {
1106                             str::from_utf8_lossy(v.as_slice()).into_string()
1107                         }).collect()
1108 }
1109
1110 #[cfg(windows)]
1111 fn real_args() -> Vec<String> {
1112     use slice;
1113
1114     let mut nArgs: c_int = 0;
1115     let lpArgCount: *mut c_int = &mut nArgs;
1116     let lpCmdLine = unsafe { GetCommandLineW() };
1117     let szArgList = unsafe { CommandLineToArgvW(lpCmdLine, lpArgCount) };
1118
1119     let args = Vec::from_fn(nArgs as uint, |i| unsafe {
1120         // Determine the length of this argument.
1121         let ptr = *szArgList.offset(i as int);
1122         let mut len = 0;
1123         while *ptr.offset(len as int) != 0 { len += 1; }
1124
1125         // Push it onto the list.
1126         let opt_s = slice::raw::buf_as_slice(ptr as *const _, len, |buf| {
1127             str::from_utf16(str::truncate_utf16_at_nul(buf))
1128         });
1129         opt_s.expect("CommandLineToArgvW returned invalid UTF-16")
1130     });
1131
1132     unsafe {
1133         LocalFree(szArgList as *mut c_void);
1134     }
1135
1136     return args
1137 }
1138
1139 #[cfg(windows)]
1140 fn real_args_as_bytes() -> Vec<Vec<u8>> {
1141     real_args().move_iter().map(|s| s.into_bytes()).collect()
1142 }
1143
1144 type LPCWSTR = *const u16;
1145
1146 #[cfg(windows)]
1147 #[link_name="kernel32"]
1148 extern "system" {
1149     fn GetCommandLineW() -> LPCWSTR;
1150     fn LocalFree(ptr: *mut c_void);
1151 }
1152
1153 #[cfg(windows)]
1154 #[link_name="shell32"]
1155 extern "system" {
1156     fn CommandLineToArgvW(lpCmdLine: LPCWSTR,
1157                           pNumArgs: *mut c_int) -> *mut *mut u16;
1158 }
1159
1160 /// Returns the arguments which this program was started with (normally passed
1161 /// via the command line).
1162 ///
1163 /// The arguments are interpreted as utf-8, with invalid bytes replaced with \uFFFD.
1164 /// See `str::from_utf8_lossy` for details.
1165 pub fn args() -> Vec<String> {
1166     real_args()
1167 }
1168
1169 /// Returns the arguments which this program was started with (normally passed
1170 /// via the command line) as byte vectors.
1171 pub fn args_as_bytes() -> Vec<Vec<u8>> {
1172     real_args_as_bytes()
1173 }
1174
1175 #[cfg(target_os = "macos")]
1176 extern {
1177     // These functions are in crt_externs.h.
1178     pub fn _NSGetArgc() -> *mut c_int;
1179     pub fn _NSGetArgv() -> *mut *mut *mut c_char;
1180 }
1181
1182 // Round up `from` to be divisible by `to`
1183 fn round_up(from: uint, to: uint) -> uint {
1184     let r = if from % to == 0 {
1185         from
1186     } else {
1187         from + to - (from % to)
1188     };
1189     if r == 0 {
1190         to
1191     } else {
1192         r
1193     }
1194 }
1195
1196 /// Returns the page size of the current architecture in bytes.
1197 #[cfg(unix)]
1198 pub fn page_size() -> uint {
1199     unsafe {
1200         libc::sysconf(libc::_SC_PAGESIZE) as uint
1201     }
1202 }
1203
1204 /// Returns the page size of the current architecture in bytes.
1205 #[cfg(windows)]
1206 pub fn page_size() -> uint {
1207     use mem;
1208     unsafe {
1209         let mut info = mem::zeroed();
1210         libc::GetSystemInfo(&mut info);
1211
1212         return info.dwPageSize as uint;
1213     }
1214 }
1215
1216 /// A memory mapped file or chunk of memory. This is a very system-specific
1217 /// interface to the OS's memory mapping facilities (`mmap` on POSIX,
1218 /// `VirtualAlloc`/`CreateFileMapping` on win32). It makes no attempt at
1219 /// abstracting platform differences, besides in error values returned. Consider
1220 /// yourself warned.
1221 ///
1222 /// The memory map is released (unmapped) when the destructor is run, so don't
1223 /// let it leave scope by accident if you want it to stick around.
1224 pub struct MemoryMap {
1225     /// Pointer to the memory created or modified by this map.
1226     pub data: *mut u8,
1227     /// Number of bytes this map applies to
1228     pub len: uint,
1229     /// Type of mapping
1230     pub kind: MemoryMapKind,
1231 }
1232
1233 /// Type of memory map
1234 pub enum MemoryMapKind {
1235     /// Virtual memory map. Usually used to change the permissions of a given
1236     /// chunk of memory.  Corresponds to `VirtualAlloc` on Windows.
1237     MapFile(*const u8),
1238     /// Virtual memory map. Usually used to change the permissions of a given
1239     /// chunk of memory, or for allocation. Corresponds to `VirtualAlloc` on
1240     /// Windows.
1241     MapVirtual
1242 }
1243
1244 /// Options the memory map is created with
1245 pub enum MapOption {
1246     /// The memory should be readable
1247     MapReadable,
1248     /// The memory should be writable
1249     MapWritable,
1250     /// The memory should be executable
1251     MapExecutable,
1252     /// Create a map for a specific address range. Corresponds to `MAP_FIXED` on
1253     /// POSIX.
1254     MapAddr(*const u8),
1255     /// Create a memory mapping for a file with a given fd.
1256     MapFd(c_int),
1257     /// When using `MapFd`, the start of the map is `uint` bytes from the start
1258     /// of the file.
1259     MapOffset(uint),
1260     /// On POSIX, this can be used to specify the default flags passed to
1261     /// `mmap`. By default it uses `MAP_PRIVATE` and, if not using `MapFd`,
1262     /// `MAP_ANON`. This will override both of those. This is platform-specific
1263     /// (the exact values used) and ignored on Windows.
1264     MapNonStandardFlags(c_int),
1265 }
1266
1267 /// Possible errors when creating a map.
1268 pub enum MapError {
1269     /// ## The following are POSIX-specific
1270     ///
1271     /// fd was not open for reading or, if using `MapWritable`, was not open for
1272     /// writing.
1273     ErrFdNotAvail,
1274     /// fd was not valid
1275     ErrInvalidFd,
1276     /// Either the address given by `MapAddr` or offset given by `MapOffset` was
1277     /// not a multiple of `MemoryMap::granularity` (unaligned to page size).
1278     ErrUnaligned,
1279     /// With `MapFd`, the fd does not support mapping.
1280     ErrNoMapSupport,
1281     /// If using `MapAddr`, the address + `min_len` was outside of the process's
1282     /// address space. If using `MapFd`, the target of the fd didn't have enough
1283     /// resources to fulfill the request.
1284     ErrNoMem,
1285     /// A zero-length map was requested. This is invalid according to
1286     /// [POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/functions/mmap.html).
1287     /// Not all platforms obey this, but this wrapper does.
1288     ErrZeroLength,
1289     /// Unrecognized error. The inner value is the unrecognized errno.
1290     ErrUnknown(int),
1291     /// ## The following are win32-specific
1292     ///
1293     /// Unsupported combination of protection flags
1294     /// (`MapReadable`/`MapWritable`/`MapExecutable`).
1295     ErrUnsupProt,
1296     /// When using `MapFd`, `MapOffset` was given (Windows does not support this
1297     /// at all)
1298     ErrUnsupOffset,
1299     /// When using `MapFd`, there was already a mapping to the file.
1300     ErrAlreadyExists,
1301     /// Unrecognized error from `VirtualAlloc`. The inner value is the return
1302     /// value of GetLastError.
1303     ErrVirtualAlloc(uint),
1304     /// Unrecognized error from `CreateFileMapping`. The inner value is the
1305     /// return value of `GetLastError`.
1306     ErrCreateFileMappingW(uint),
1307     /// Unrecognized error from `MapViewOfFile`. The inner value is the return
1308     /// value of `GetLastError`.
1309     ErrMapViewOfFile(uint)
1310 }
1311
1312 impl fmt::Show for MapError {
1313     fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result {
1314         let str = match *self {
1315             ErrFdNotAvail => "fd not available for reading or writing",
1316             ErrInvalidFd => "Invalid fd",
1317             ErrUnaligned => {
1318                 "Unaligned address, invalid flags, negative length or \
1319                  unaligned offset"
1320             }
1321             ErrNoMapSupport=> "File doesn't support mapping",
1322             ErrNoMem => "Invalid address, or not enough available memory",
1323             ErrUnsupProt => "Protection mode unsupported",
1324             ErrUnsupOffset => "Offset in virtual memory mode is unsupported",
1325             ErrAlreadyExists => "File mapping for specified file already exists",
1326             ErrZeroLength => "Zero-length mapping not allowed",
1327             ErrUnknown(code) => {
1328                 return write!(out, "Unknown error = {}", code)
1329             },
1330             ErrVirtualAlloc(code) => {
1331                 return write!(out, "VirtualAlloc failure = {}", code)
1332             },
1333             ErrCreateFileMappingW(code) => {
1334                 return write!(out, "CreateFileMappingW failure = {}", code)
1335             },
1336             ErrMapViewOfFile(code) => {
1337                 return write!(out, "MapViewOfFile failure = {}", code)
1338             }
1339         };
1340         write!(out, "{}", str)
1341     }
1342 }
1343
1344 #[cfg(unix)]
1345 impl MemoryMap {
1346     /// Create a new mapping with the given `options`, at least `min_len` bytes
1347     /// long. `min_len` must be greater than zero; see the note on
1348     /// `ErrZeroLength`.
1349     pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
1350         use libc::off_t;
1351
1352         if min_len == 0 {
1353             return Err(ErrZeroLength)
1354         }
1355         let mut addr: *const u8 = ptr::null();
1356         let mut prot = 0;
1357         let mut flags = libc::MAP_PRIVATE;
1358         let mut fd = -1;
1359         let mut offset = 0;
1360         let mut custom_flags = false;
1361         let len = round_up(min_len, page_size());
1362
1363         for &o in options.iter() {
1364             match o {
1365                 MapReadable => { prot |= libc::PROT_READ; },
1366                 MapWritable => { prot |= libc::PROT_WRITE; },
1367                 MapExecutable => { prot |= libc::PROT_EXEC; },
1368                 MapAddr(addr_) => {
1369                     flags |= libc::MAP_FIXED;
1370                     addr = addr_;
1371                 },
1372                 MapFd(fd_) => {
1373                     flags |= libc::MAP_FILE;
1374                     fd = fd_;
1375                 },
1376                 MapOffset(offset_) => { offset = offset_ as off_t; },
1377                 MapNonStandardFlags(f) => { custom_flags = true; flags = f },
1378             }
1379         }
1380         if fd == -1 && !custom_flags { flags |= libc::MAP_ANON; }
1381
1382         let r = unsafe {
1383             libc::mmap(addr as *mut c_void, len as libc::size_t, prot, flags,
1384                        fd, offset)
1385         };
1386         if r == libc::MAP_FAILED {
1387             Err(match errno() as c_int {
1388                 libc::EACCES => ErrFdNotAvail,
1389                 libc::EBADF => ErrInvalidFd,
1390                 libc::EINVAL => ErrUnaligned,
1391                 libc::ENODEV => ErrNoMapSupport,
1392                 libc::ENOMEM => ErrNoMem,
1393                 code => ErrUnknown(code as int)
1394             })
1395         } else {
1396             Ok(MemoryMap {
1397                data: r as *mut u8,
1398                len: len,
1399                kind: if fd == -1 {
1400                    MapVirtual
1401                } else {
1402                    MapFile(ptr::null())
1403                }
1404             })
1405         }
1406     }
1407
1408     /// Granularity that the offset or address must be for `MapOffset` and
1409     /// `MapAddr` respectively.
1410     pub fn granularity() -> uint {
1411         page_size()
1412     }
1413 }
1414
1415 #[cfg(unix)]
1416 impl Drop for MemoryMap {
1417     /// Unmap the mapping. Fails the task if `munmap` fails.
1418     fn drop(&mut self) {
1419         if self.len == 0 { /* workaround for dummy_stack */ return; }
1420
1421         unsafe {
1422             // `munmap` only fails due to logic errors
1423             libc::munmap(self.data as *mut c_void, self.len as libc::size_t);
1424         }
1425     }
1426 }
1427
1428 #[cfg(windows)]
1429 impl MemoryMap {
1430     /// Create a new mapping with the given `options`, at least `min_len` bytes long.
1431     pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
1432         use libc::types::os::arch::extra::{LPVOID, DWORD, SIZE_T, HANDLE};
1433
1434         let mut lpAddress: LPVOID = ptr::mut_null();
1435         let mut readable = false;
1436         let mut writable = false;
1437         let mut executable = false;
1438         let mut fd: c_int = -1;
1439         let mut offset: uint = 0;
1440         let len = round_up(min_len, page_size());
1441
1442         for &o in options.iter() {
1443             match o {
1444                 MapReadable => { readable = true; },
1445                 MapWritable => { writable = true; },
1446                 MapExecutable => { executable = true; }
1447                 MapAddr(addr_) => { lpAddress = addr_ as LPVOID; },
1448                 MapFd(fd_) => { fd = fd_; },
1449                 MapOffset(offset_) => { offset = offset_; },
1450                 MapNonStandardFlags(..) => {}
1451             }
1452         }
1453
1454         let flProtect = match (executable, readable, writable) {
1455             (false, false, false) if fd == -1 => libc::PAGE_NOACCESS,
1456             (false, true, false) => libc::PAGE_READONLY,
1457             (false, true, true) => libc::PAGE_READWRITE,
1458             (true, false, false) if fd == -1 => libc::PAGE_EXECUTE,
1459             (true, true, false) => libc::PAGE_EXECUTE_READ,
1460             (true, true, true) => libc::PAGE_EXECUTE_READWRITE,
1461             _ => return Err(ErrUnsupProt)
1462         };
1463
1464         if fd == -1 {
1465             if offset != 0 {
1466                 return Err(ErrUnsupOffset);
1467             }
1468             let r = unsafe {
1469                 libc::VirtualAlloc(lpAddress,
1470                                    len as SIZE_T,
1471                                    libc::MEM_COMMIT | libc::MEM_RESERVE,
1472                                    flProtect)
1473             };
1474             match r as uint {
1475                 0 => Err(ErrVirtualAlloc(errno())),
1476                 _ => Ok(MemoryMap {
1477                    data: r as *mut u8,
1478                    len: len,
1479                    kind: MapVirtual
1480                 })
1481             }
1482         } else {
1483             let dwDesiredAccess = match (executable, readable, writable) {
1484                 (false, true, false) => libc::FILE_MAP_READ,
1485                 (false, true, true) => libc::FILE_MAP_WRITE,
1486                 (true, true, false) => libc::FILE_MAP_READ | libc::FILE_MAP_EXECUTE,
1487                 (true, true, true) => libc::FILE_MAP_WRITE | libc::FILE_MAP_EXECUTE,
1488                 _ => return Err(ErrUnsupProt) // Actually, because of the check above,
1489                                               // we should never get here.
1490             };
1491             unsafe {
1492                 let hFile = libc::get_osfhandle(fd) as HANDLE;
1493                 let mapping = libc::CreateFileMappingW(hFile,
1494                                                        ptr::mut_null(),
1495                                                        flProtect,
1496                                                        0,
1497                                                        0,
1498                                                        ptr::null());
1499                 if mapping == ptr::mut_null() {
1500                     return Err(ErrCreateFileMappingW(errno()));
1501                 }
1502                 if errno() as c_int == libc::ERROR_ALREADY_EXISTS {
1503                     return Err(ErrAlreadyExists);
1504                 }
1505                 let r = libc::MapViewOfFile(mapping,
1506                                             dwDesiredAccess,
1507                                             ((len as u64) >> 32) as DWORD,
1508                                             (offset & 0xffff_ffff) as DWORD,
1509                                             0);
1510                 match r as uint {
1511                     0 => Err(ErrMapViewOfFile(errno())),
1512                     _ => Ok(MemoryMap {
1513                        data: r as *mut u8,
1514                        len: len,
1515                        kind: MapFile(mapping as *const u8)
1516                     })
1517                 }
1518             }
1519         }
1520     }
1521
1522     /// Granularity of MapAddr() and MapOffset() parameter values.
1523     /// This may be greater than the value returned by page_size().
1524     pub fn granularity() -> uint {
1525         use mem;
1526         unsafe {
1527             let mut info = mem::zeroed();
1528             libc::GetSystemInfo(&mut info);
1529
1530             return info.dwAllocationGranularity as uint;
1531         }
1532     }
1533 }
1534
1535 #[cfg(windows)]
1536 impl Drop for MemoryMap {
1537     /// Unmap the mapping. Fails the task if any of `VirtualFree`,
1538     /// `UnmapViewOfFile`, or `CloseHandle` fail.
1539     fn drop(&mut self) {
1540         use libc::types::os::arch::extra::{LPCVOID, HANDLE};
1541         use libc::consts::os::extra::FALSE;
1542         if self.len == 0 { return }
1543
1544         unsafe {
1545             match self.kind {
1546                 MapVirtual => {
1547                     if libc::VirtualFree(self.data as *mut c_void, 0,
1548                                          libc::MEM_RELEASE) == 0 {
1549                         println!("VirtualFree failed: {}", errno());
1550                     }
1551                 },
1552                 MapFile(mapping) => {
1553                     if libc::UnmapViewOfFile(self.data as LPCVOID) == FALSE {
1554                         println!("UnmapViewOfFile failed: {}", errno());
1555                     }
1556                     if libc::CloseHandle(mapping as HANDLE) == FALSE {
1557                         println!("CloseHandle failed: {}", errno());
1558                     }
1559                 }
1560             }
1561         }
1562     }
1563 }
1564
1565 #[cfg(target_os = "linux")]
1566 pub mod consts {
1567     pub use os::arch_consts::ARCH;
1568
1569     pub static FAMILY: &'static str = "unix";
1570
1571     /// A string describing the specific operating system in use: in this
1572     /// case, `linux`.
1573     pub static SYSNAME: &'static str = "linux";
1574
1575     /// Specifies the filename prefix used for shared libraries on this
1576     /// platform: in this case, `lib`.
1577     pub static DLL_PREFIX: &'static str = "lib";
1578
1579     /// Specifies the filename suffix used for shared libraries on this
1580     /// platform: in this case, `.so`.
1581     pub static DLL_SUFFIX: &'static str = ".so";
1582
1583     /// Specifies the file extension used for shared libraries on this
1584     /// platform that goes after the dot: in this case, `so`.
1585     pub static DLL_EXTENSION: &'static str = "so";
1586
1587     /// Specifies the filename suffix used for executable binaries on this
1588     /// platform: in this case, the empty string.
1589     pub static EXE_SUFFIX: &'static str = "";
1590
1591     /// Specifies the file extension, if any, used for executable binaries
1592     /// on this platform: in this case, the empty string.
1593     pub static EXE_EXTENSION: &'static str = "";
1594 }
1595
1596 #[cfg(target_os = "macos")]
1597 pub mod consts {
1598     pub use os::arch_consts::ARCH;
1599
1600     pub static FAMILY: &'static str = "unix";
1601
1602     /// A string describing the specific operating system in use: in this
1603     /// case, `macos`.
1604     pub static SYSNAME: &'static str = "macos";
1605
1606     /// Specifies the filename prefix used for shared libraries on this
1607     /// platform: in this case, `lib`.
1608     pub static DLL_PREFIX: &'static str = "lib";
1609
1610     /// Specifies the filename suffix used for shared libraries on this
1611     /// platform: in this case, `.dylib`.
1612     pub static DLL_SUFFIX: &'static str = ".dylib";
1613
1614     /// Specifies the file extension used for shared libraries on this
1615     /// platform that goes after the dot: in this case, `dylib`.
1616     pub static DLL_EXTENSION: &'static str = "dylib";
1617
1618     /// Specifies the filename suffix used for executable binaries on this
1619     /// platform: in this case, the empty string.
1620     pub static EXE_SUFFIX: &'static str = "";
1621
1622     /// Specifies the file extension, if any, used for executable binaries
1623     /// on this platform: in this case, the empty string.
1624     pub static EXE_EXTENSION: &'static str = "";
1625 }
1626
1627 #[cfg(target_os = "ios")]
1628 pub mod consts {
1629     pub use os::arch_consts::ARCH;
1630
1631     pub static FAMILY: &'static str = "unix";
1632
1633     /// A string describing the specific operating system in use: in this
1634     /// case, `ios`.
1635     pub static SYSNAME: &'static str = "ios";
1636
1637     /// Specifies the filename suffix used for executable binaries on this
1638     /// platform: in this case, the empty string.
1639     pub static EXE_SUFFIX: &'static str = "";
1640
1641     /// Specifies the file extension, if any, used for executable binaries
1642     /// on this platform: in this case, the empty string.
1643     pub static EXE_EXTENSION: &'static str = "";
1644 }
1645
1646 #[cfg(target_os = "freebsd")]
1647 pub mod consts {
1648     pub use os::arch_consts::ARCH;
1649
1650     pub static FAMILY: &'static str = "unix";
1651
1652     /// A string describing the specific operating system in use: in this
1653     /// case, `freebsd`.
1654     pub static SYSNAME: &'static str = "freebsd";
1655
1656     /// Specifies the filename prefix used for shared libraries on this
1657     /// platform: in this case, `lib`.
1658     pub static DLL_PREFIX: &'static str = "lib";
1659
1660     /// Specifies the filename suffix used for shared libraries on this
1661     /// platform: in this case, `.so`.
1662     pub static DLL_SUFFIX: &'static str = ".so";
1663
1664     /// Specifies the file extension used for shared libraries on this
1665     /// platform that goes after the dot: in this case, `so`.
1666     pub static DLL_EXTENSION: &'static str = "so";
1667
1668     /// Specifies the filename suffix used for executable binaries on this
1669     /// platform: in this case, the empty string.
1670     pub static EXE_SUFFIX: &'static str = "";
1671
1672     /// Specifies the file extension, if any, used for executable binaries
1673     /// on this platform: in this case, the empty string.
1674     pub static EXE_EXTENSION: &'static str = "";
1675 }
1676
1677 #[cfg(target_os = "android")]
1678 pub mod consts {
1679     pub use os::arch_consts::ARCH;
1680
1681     pub static FAMILY: &'static str = "unix";
1682
1683     /// A string describing the specific operating system in use: in this
1684     /// case, `android`.
1685     pub static SYSNAME: &'static str = "android";
1686
1687     /// Specifies the filename prefix used for shared libraries on this
1688     /// platform: in this case, `lib`.
1689     pub static DLL_PREFIX: &'static str = "lib";
1690
1691     /// Specifies the filename suffix used for shared libraries on this
1692     /// platform: in this case, `.so`.
1693     pub static DLL_SUFFIX: &'static str = ".so";
1694
1695     /// Specifies the file extension used for shared libraries on this
1696     /// platform that goes after the dot: in this case, `so`.
1697     pub static DLL_EXTENSION: &'static str = "so";
1698
1699     /// Specifies the filename suffix used for executable binaries on this
1700     /// platform: in this case, the empty string.
1701     pub static EXE_SUFFIX: &'static str = "";
1702
1703     /// Specifies the file extension, if any, used for executable binaries
1704     /// on this platform: in this case, the empty string.
1705     pub static EXE_EXTENSION: &'static str = "";
1706 }
1707
1708 #[cfg(target_os = "win32")]
1709 pub mod consts {
1710     pub use os::arch_consts::ARCH;
1711
1712     pub static FAMILY: &'static str = "windows";
1713
1714     /// A string describing the specific operating system in use: in this
1715     /// case, `win32`.
1716     pub static SYSNAME: &'static str = "win32";
1717
1718     /// Specifies the filename prefix used for shared libraries on this
1719     /// platform: in this case, the empty string.
1720     pub static DLL_PREFIX: &'static str = "";
1721
1722     /// Specifies the filename suffix used for shared libraries on this
1723     /// platform: in this case, `.dll`.
1724     pub static DLL_SUFFIX: &'static str = ".dll";
1725
1726     /// Specifies the file extension used for shared libraries on this
1727     /// platform that goes after the dot: in this case, `dll`.
1728     pub static DLL_EXTENSION: &'static str = "dll";
1729
1730     /// Specifies the filename suffix used for executable binaries on this
1731     /// platform: in this case, `.exe`.
1732     pub static EXE_SUFFIX: &'static str = ".exe";
1733
1734     /// Specifies the file extension, if any, used for executable binaries
1735     /// on this platform: in this case, `exe`.
1736     pub static EXE_EXTENSION: &'static str = "exe";
1737 }
1738
1739 #[cfg(target_arch = "x86")]
1740 mod arch_consts {
1741     pub static ARCH: &'static str = "x86";
1742 }
1743
1744 #[cfg(target_arch = "x86_64")]
1745 mod arch_consts {
1746     pub static ARCH: &'static str = "x86_64";
1747 }
1748
1749 #[cfg(target_arch = "arm")]
1750 mod arch_consts {
1751     pub static ARCH: &'static str = "arm";
1752 }
1753
1754 #[cfg(target_arch = "mips")]
1755 mod arch_consts {
1756     pub static ARCH: &'static str = "mips";
1757 }
1758
1759 #[cfg(target_arch = "mipsel")]
1760 mod arch_consts {
1761     pub static ARCH: &'static str = "mipsel";
1762 }
1763
1764 #[cfg(test)]
1765 mod tests {
1766     use prelude::*;
1767     use c_str::ToCStr;
1768     use option;
1769     use os::{env, getcwd, getenv, make_absolute};
1770     use os::{split_paths, setenv, unsetenv};
1771     use os;
1772     use rand::Rng;
1773     use rand;
1774
1775     #[test]
1776     pub fn last_os_error() {
1777         debug!("{}", os::last_os_error());
1778     }
1779
1780     fn make_rand_name() -> String {
1781         let mut rng = rand::task_rng();
1782         let n = format!("TEST{}", rng.gen_ascii_chars().take(10u)
1783                                      .collect::<String>());
1784         assert!(getenv(n.as_slice()).is_none());
1785         n
1786     }
1787
1788     #[test]
1789     fn test_num_cpus() {
1790         assert!(os::num_cpus() > 0);
1791     }
1792
1793     #[test]
1794     fn test_setenv() {
1795         let n = make_rand_name();
1796         setenv(n.as_slice(), "VALUE");
1797         assert_eq!(getenv(n.as_slice()), option::Some("VALUE".to_string()));
1798     }
1799
1800     #[test]
1801     fn test_unsetenv() {
1802         let n = make_rand_name();
1803         setenv(n.as_slice(), "VALUE");
1804         unsetenv(n.as_slice());
1805         assert_eq!(getenv(n.as_slice()), option::None);
1806     }
1807
1808     #[test]
1809     #[ignore]
1810     fn test_setenv_overwrite() {
1811         let n = make_rand_name();
1812         setenv(n.as_slice(), "1");
1813         setenv(n.as_slice(), "2");
1814         assert_eq!(getenv(n.as_slice()), option::Some("2".to_string()));
1815         setenv(n.as_slice(), "");
1816         assert_eq!(getenv(n.as_slice()), option::Some("".to_string()));
1817     }
1818
1819     // Windows GetEnvironmentVariable requires some extra work to make sure
1820     // the buffer the variable is copied into is the right size
1821     #[test]
1822     #[ignore]
1823     fn test_getenv_big() {
1824         let mut s = "".to_string();
1825         let mut i = 0i;
1826         while i < 100 {
1827             s.push_str("aaaaaaaaaa");
1828             i += 1;
1829         }
1830         let n = make_rand_name();
1831         setenv(n.as_slice(), s.as_slice());
1832         debug!("{}", s.clone());
1833         assert_eq!(getenv(n.as_slice()), option::Some(s));
1834     }
1835
1836     #[test]
1837     fn test_self_exe_name() {
1838         let path = os::self_exe_name();
1839         assert!(path.is_some());
1840         let path = path.unwrap();
1841         debug!("{:?}", path.clone());
1842
1843         // Hard to test this function
1844         assert!(path.is_absolute());
1845     }
1846
1847     #[test]
1848     fn test_self_exe_path() {
1849         let path = os::self_exe_path();
1850         assert!(path.is_some());
1851         let path = path.unwrap();
1852         debug!("{:?}", path.clone());
1853
1854         // Hard to test this function
1855         assert!(path.is_absolute());
1856     }
1857
1858     #[test]
1859     #[ignore]
1860     fn test_env_getenv() {
1861         let e = env();
1862         assert!(e.len() > 0u);
1863         for p in e.iter() {
1864             let (n, v) = (*p).clone();
1865             debug!("{:?}", n.clone());
1866             let v2 = getenv(n.as_slice());
1867             // MingW seems to set some funky environment variables like
1868             // "=C:=C:\MinGW\msys\1.0\bin" and "!::=::\" that are returned
1869             // from env() but not visible from getenv().
1870             assert!(v2.is_none() || v2 == option::Some(v));
1871         }
1872     }
1873
1874     #[test]
1875     fn test_env_set_get_huge() {
1876         let n = make_rand_name();
1877         let s = "x".repeat(10000).to_string();
1878         setenv(n.as_slice(), s.as_slice());
1879         assert_eq!(getenv(n.as_slice()), Some(s));
1880         unsetenv(n.as_slice());
1881         assert_eq!(getenv(n.as_slice()), None);
1882     }
1883
1884     #[test]
1885     fn test_env_setenv() {
1886         let n = make_rand_name();
1887
1888         let mut e = env();
1889         setenv(n.as_slice(), "VALUE");
1890         assert!(!e.contains(&(n.clone(), "VALUE".to_string())));
1891
1892         e = env();
1893         assert!(e.contains(&(n, "VALUE".to_string())));
1894     }
1895
1896     #[test]
1897     fn test() {
1898         assert!((!Path::new("test-path").is_absolute()));
1899
1900         let cwd = getcwd();
1901         debug!("Current working directory: {}", cwd.display());
1902
1903         debug!("{:?}", make_absolute(&Path::new("test-path")));
1904         debug!("{:?}", make_absolute(&Path::new("/usr/bin")));
1905     }
1906
1907     #[test]
1908     #[cfg(unix)]
1909     fn homedir() {
1910         let oldhome = getenv("HOME");
1911
1912         setenv("HOME", "/home/MountainView");
1913         assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1914
1915         setenv("HOME", "");
1916         assert!(os::homedir().is_none());
1917
1918         for s in oldhome.iter() {
1919             setenv("HOME", s.as_slice());
1920         }
1921     }
1922
1923     #[test]
1924     #[cfg(windows)]
1925     fn homedir() {
1926
1927         let oldhome = getenv("HOME");
1928         let olduserprofile = getenv("USERPROFILE");
1929
1930         setenv("HOME", "");
1931         setenv("USERPROFILE", "");
1932
1933         assert!(os::homedir().is_none());
1934
1935         setenv("HOME", "/home/MountainView");
1936         assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1937
1938         setenv("HOME", "");
1939
1940         setenv("USERPROFILE", "/home/MountainView");
1941         assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1942
1943         setenv("HOME", "/home/MountainView");
1944         setenv("USERPROFILE", "/home/PaloAlto");
1945         assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1946
1947         for s in oldhome.iter() {
1948             setenv("HOME", s.as_slice());
1949         }
1950         for s in olduserprofile.iter() {
1951             setenv("USERPROFILE", s.as_slice());
1952         }
1953     }
1954
1955     #[test]
1956     fn memory_map_rw() {
1957         use result::{Ok, Err};
1958
1959         let chunk = match os::MemoryMap::new(16, [
1960             os::MapReadable,
1961             os::MapWritable
1962         ]) {
1963             Ok(chunk) => chunk,
1964             Err(msg) => fail!("{}", msg)
1965         };
1966         assert!(chunk.len >= 16);
1967
1968         unsafe {
1969             *chunk.data = 0xBE;
1970             assert!(*chunk.data == 0xBE);
1971         }
1972     }
1973
1974     #[test]
1975     fn memory_map_file() {
1976         use result::{Ok, Err};
1977         use os::*;
1978         use libc::*;
1979         use io::fs;
1980
1981         #[cfg(unix)]
1982         fn lseek_(fd: c_int, size: uint) {
1983             unsafe {
1984                 assert!(lseek(fd, size as off_t, SEEK_SET) == size as off_t);
1985             }
1986         }
1987         #[cfg(windows)]
1988         fn lseek_(fd: c_int, size: uint) {
1989            unsafe {
1990                assert!(lseek(fd, size as c_long, SEEK_SET) == size as c_long);
1991            }
1992         }
1993
1994         let mut path = tmpdir();
1995         path.push("mmap_file.tmp");
1996         let size = MemoryMap::granularity() * 2;
1997
1998         let fd = unsafe {
1999             let fd = path.with_c_str(|path| {
2000                 open(path, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR)
2001             });
2002             lseek_(fd, size);
2003             "x".with_c_str(|x| assert!(write(fd, x as *const c_void, 1) == 1));
2004             fd
2005         };
2006         let chunk = match MemoryMap::new(size / 2, [
2007             MapReadable,
2008             MapWritable,
2009             MapFd(fd),
2010             MapOffset(size / 2)
2011         ]) {
2012             Ok(chunk) => chunk,
2013             Err(msg) => fail!("{}", msg)
2014         };
2015         assert!(chunk.len > 0);
2016
2017         unsafe {
2018             *chunk.data = 0xbe;
2019             assert!(*chunk.data == 0xbe);
2020             close(fd);
2021         }
2022         drop(chunk);
2023
2024         fs::unlink(&path).unwrap();
2025     }
2026
2027     #[test]
2028     #[cfg(windows)]
2029     fn split_paths_windows() {
2030         fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
2031             split_paths(unparsed) ==
2032                 parsed.iter().map(|s| Path::new(*s)).collect()
2033         }
2034
2035         assert!(check_parse("", []));
2036         assert!(check_parse(r#""""#, []));
2037         assert!(check_parse(";;", []));
2038         assert!(check_parse(r"c:\", [r"c:\"]));
2039         assert!(check_parse(r"c:\;", [r"c:\"]));
2040         assert!(check_parse(r"c:\;c:\Program Files\",
2041                             [r"c:\", r"c:\Program Files\"]));
2042         assert!(check_parse(r#"c:\;c:\"foo"\"#, [r"c:\", r"c:\foo\"]));
2043         assert!(check_parse(r#"c:\;c:\"foo;bar"\;c:\baz"#,
2044                             [r"c:\", r"c:\foo;bar\", r"c:\baz"]));
2045     }
2046
2047     #[test]
2048     #[cfg(unix)]
2049     fn split_paths_unix() {
2050         fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
2051             split_paths(unparsed) ==
2052                 parsed.iter().map(|s| Path::new(*s)).collect()
2053         }
2054
2055         assert!(check_parse("", []));
2056         assert!(check_parse("::", []));
2057         assert!(check_parse("/", ["/"]));
2058         assert!(check_parse("/:", ["/"]));
2059         assert!(check_parse("/:/usr/local", ["/", "/usr/local"]));
2060     }
2061
2062     // More recursive_mkdir tests are in extra::tempfile
2063 }