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