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