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