]> git.lizzy.rs Git - rust.git/blob - src/libstd/os.rs
rollup merge of #19620: retep998/memorymap
[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 windoze {
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::windoze::{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::windoze::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 HANDLE.
1219     #[cfg(windows)]
1220     MapFd(libc::HANDLE),
1221     /// Create a memory mapping for a file with a given fd.
1222     #[cfg(not(windows))]
1223     MapFd(c_int),
1224     /// When using `MapFd`, the start of the map is `uint` bytes from the start
1225     /// of the file.
1226     MapOffset(uint),
1227     /// On POSIX, this can be used to specify the default flags passed to
1228     /// `mmap`. By default it uses `MAP_PRIVATE` and, if not using `MapFd`,
1229     /// `MAP_ANON`. This will override both of those. This is platform-specific
1230     /// (the exact values used) and ignored on Windows.
1231     MapNonStandardFlags(c_int),
1232 }
1233
1234 impl Copy for MapOption {}
1235
1236 /// Possible errors when creating a map.
1237 pub enum MapError {
1238     /// ## The following are POSIX-specific
1239     ///
1240     /// fd was not open for reading or, if using `MapWritable`, was not open for
1241     /// writing.
1242     ErrFdNotAvail,
1243     /// fd was not valid
1244     ErrInvalidFd,
1245     /// Either the address given by `MapAddr` or offset given by `MapOffset` was
1246     /// not a multiple of `MemoryMap::granularity` (unaligned to page size).
1247     ErrUnaligned,
1248     /// With `MapFd`, the fd does not support mapping.
1249     ErrNoMapSupport,
1250     /// If using `MapAddr`, the address + `min_len` was outside of the process's
1251     /// address space. If using `MapFd`, the target of the fd didn't have enough
1252     /// resources to fulfill the request.
1253     ErrNoMem,
1254     /// A zero-length map was requested. This is invalid according to
1255     /// [POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/functions/mmap.html).
1256     /// Not all platforms obey this, but this wrapper does.
1257     ErrZeroLength,
1258     /// Unrecognized error. The inner value is the unrecognized errno.
1259     ErrUnknown(int),
1260     /// ## The following are Windows-specific
1261     ///
1262     /// Unsupported combination of protection flags
1263     /// (`MapReadable`/`MapWritable`/`MapExecutable`).
1264     ErrUnsupProt,
1265     /// When using `MapFd`, `MapOffset` was given (Windows does not support this
1266     /// at all)
1267     ErrUnsupOffset,
1268     /// When using `MapFd`, there was already a mapping to the file.
1269     ErrAlreadyExists,
1270     /// Unrecognized error from `VirtualAlloc`. The inner value is the return
1271     /// value of GetLastError.
1272     ErrVirtualAlloc(uint),
1273     /// Unrecognized error from `CreateFileMapping`. The inner value is the
1274     /// return value of `GetLastError`.
1275     ErrCreateFileMappingW(uint),
1276     /// Unrecognized error from `MapViewOfFile`. The inner value is the return
1277     /// value of `GetLastError`.
1278     ErrMapViewOfFile(uint)
1279 }
1280
1281 impl Copy for MapError {}
1282
1283 impl fmt::Show for MapError {
1284     fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result {
1285         let str = match *self {
1286             ErrFdNotAvail => "fd not available for reading or writing",
1287             ErrInvalidFd => "Invalid fd",
1288             ErrUnaligned => {
1289                 "Unaligned address, invalid flags, negative length or \
1290                  unaligned offset"
1291             }
1292             ErrNoMapSupport=> "File doesn't support mapping",
1293             ErrNoMem => "Invalid address, or not enough available memory",
1294             ErrUnsupProt => "Protection mode unsupported",
1295             ErrUnsupOffset => "Offset in virtual memory mode is unsupported",
1296             ErrAlreadyExists => "File mapping for specified file already exists",
1297             ErrZeroLength => "Zero-length mapping not allowed",
1298             ErrUnknown(code) => {
1299                 return write!(out, "Unknown error = {}", code)
1300             },
1301             ErrVirtualAlloc(code) => {
1302                 return write!(out, "VirtualAlloc failure = {}", code)
1303             },
1304             ErrCreateFileMappingW(code) => {
1305                 return write!(out, "CreateFileMappingW failure = {}", code)
1306             },
1307             ErrMapViewOfFile(code) => {
1308                 return write!(out, "MapViewOfFile failure = {}", code)
1309             }
1310         };
1311         write!(out, "{}", str)
1312     }
1313 }
1314
1315 impl Error for MapError {
1316     fn description(&self) -> &str { "memory map error" }
1317     fn detail(&self) -> Option<String> { Some(self.to_string()) }
1318 }
1319
1320 impl FromError<MapError> for Box<Error> {
1321     fn from_error(err: MapError) -> Box<Error> {
1322         box err
1323     }
1324 }
1325
1326 #[cfg(unix)]
1327 impl MemoryMap {
1328     /// Create a new mapping with the given `options`, at least `min_len` bytes
1329     /// long. `min_len` must be greater than zero; see the note on
1330     /// `ErrZeroLength`.
1331     pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
1332         use libc::off_t;
1333
1334         if min_len == 0 {
1335             return Err(ErrZeroLength)
1336         }
1337         let mut addr: *const u8 = ptr::null();
1338         let mut prot = 0;
1339         let mut flags = libc::MAP_PRIVATE;
1340         let mut fd = -1;
1341         let mut offset = 0;
1342         let mut custom_flags = false;
1343         let len = round_up(min_len, page_size());
1344
1345         for &o in options.iter() {
1346             match o {
1347                 MapReadable => { prot |= libc::PROT_READ; },
1348                 MapWritable => { prot |= libc::PROT_WRITE; },
1349                 MapExecutable => { prot |= libc::PROT_EXEC; },
1350                 MapAddr(addr_) => {
1351                     flags |= libc::MAP_FIXED;
1352                     addr = addr_;
1353                 },
1354                 MapFd(fd_) => {
1355                     flags |= libc::MAP_FILE;
1356                     fd = fd_;
1357                 },
1358                 MapOffset(offset_) => { offset = offset_ as off_t; },
1359                 MapNonStandardFlags(f) => { custom_flags = true; flags = f },
1360             }
1361         }
1362         if fd == -1 && !custom_flags { flags |= libc::MAP_ANON; }
1363
1364         let r = unsafe {
1365             libc::mmap(addr as *mut c_void, len as libc::size_t, prot, flags,
1366                        fd, offset)
1367         };
1368         if r == libc::MAP_FAILED {
1369             Err(match errno() as c_int {
1370                 libc::EACCES => ErrFdNotAvail,
1371                 libc::EBADF => ErrInvalidFd,
1372                 libc::EINVAL => ErrUnaligned,
1373                 libc::ENODEV => ErrNoMapSupport,
1374                 libc::ENOMEM => ErrNoMem,
1375                 code => ErrUnknown(code as int)
1376             })
1377         } else {
1378             Ok(MemoryMap {
1379                data: r as *mut u8,
1380                len: len,
1381                kind: if fd == -1 {
1382                    MapVirtual
1383                } else {
1384                    MapFile(ptr::null())
1385                }
1386             })
1387         }
1388     }
1389
1390     /// Granularity that the offset or address must be for `MapOffset` and
1391     /// `MapAddr` respectively.
1392     pub fn granularity() -> uint {
1393         page_size()
1394     }
1395 }
1396
1397 #[cfg(unix)]
1398 impl Drop for MemoryMap {
1399     /// Unmap the mapping. Panics the task if `munmap` panics.
1400     fn drop(&mut self) {
1401         if self.len == 0 { /* workaround for dummy_stack */ return; }
1402
1403         unsafe {
1404             // `munmap` only panics due to logic errors
1405             libc::munmap(self.data as *mut c_void, self.len as libc::size_t);
1406         }
1407     }
1408 }
1409
1410 #[cfg(windows)]
1411 impl MemoryMap {
1412     /// Create a new mapping with the given `options`, at least `min_len` bytes long.
1413     pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
1414         use libc::types::os::arch::extra::{LPVOID, DWORD, SIZE_T, HANDLE};
1415
1416         let mut lpAddress: LPVOID = ptr::null_mut();
1417         let mut readable = false;
1418         let mut writable = false;
1419         let mut executable = false;
1420         let mut handle: HANDLE = libc::INVALID_HANDLE_VALUE;
1421         let mut offset: uint = 0;
1422         let len = round_up(min_len, page_size());
1423
1424         for &o in options.iter() {
1425             match o {
1426                 MapReadable => { readable = true; },
1427                 MapWritable => { writable = true; },
1428                 MapExecutable => { executable = true; }
1429                 MapAddr(addr_) => { lpAddress = addr_ as LPVOID; },
1430                 MapFd(handle_) => { handle = handle_; },
1431                 MapOffset(offset_) => { offset = offset_; },
1432                 MapNonStandardFlags(..) => {}
1433             }
1434         }
1435
1436         let flProtect = match (executable, readable, writable) {
1437             (false, false, false) if handle == libc::INVALID_HANDLE_VALUE => libc::PAGE_NOACCESS,
1438             (false, true, false) => libc::PAGE_READONLY,
1439             (false, true, true) => libc::PAGE_READWRITE,
1440             (true, false, false) if handle == libc::INVALID_HANDLE_VALUE => libc::PAGE_EXECUTE,
1441             (true, true, false) => libc::PAGE_EXECUTE_READ,
1442             (true, true, true) => libc::PAGE_EXECUTE_READWRITE,
1443             _ => return Err(ErrUnsupProt)
1444         };
1445
1446         if handle == libc::INVALID_HANDLE_VALUE {
1447             if offset != 0 {
1448                 return Err(ErrUnsupOffset);
1449             }
1450             let r = unsafe {
1451                 libc::VirtualAlloc(lpAddress,
1452                                    len as SIZE_T,
1453                                    libc::MEM_COMMIT | libc::MEM_RESERVE,
1454                                    flProtect)
1455             };
1456             match r as uint {
1457                 0 => Err(ErrVirtualAlloc(errno())),
1458                 _ => Ok(MemoryMap {
1459                    data: r as *mut u8,
1460                    len: len,
1461                    kind: MapVirtual
1462                 })
1463             }
1464         } else {
1465             let dwDesiredAccess = match (executable, readable, writable) {
1466                 (false, true, false) => libc::FILE_MAP_READ,
1467                 (false, true, true) => libc::FILE_MAP_WRITE,
1468                 (true, true, false) => libc::FILE_MAP_READ | libc::FILE_MAP_EXECUTE,
1469                 (true, true, true) => libc::FILE_MAP_WRITE | libc::FILE_MAP_EXECUTE,
1470                 _ => return Err(ErrUnsupProt) // Actually, because of the check above,
1471                                               // we should never get here.
1472             };
1473             unsafe {
1474                 let hFile = handle;
1475                 let mapping = libc::CreateFileMappingW(hFile,
1476                                                        ptr::null_mut(),
1477                                                        flProtect,
1478                                                        0,
1479                                                        0,
1480                                                        ptr::null());
1481                 if mapping == ptr::null_mut() {
1482                     return Err(ErrCreateFileMappingW(errno()));
1483                 }
1484                 if errno() as c_int == libc::ERROR_ALREADY_EXISTS {
1485                     return Err(ErrAlreadyExists);
1486                 }
1487                 let r = libc::MapViewOfFile(mapping,
1488                                             dwDesiredAccess,
1489                                             ((len as u64) >> 32) as DWORD,
1490                                             (offset & 0xffff_ffff) as DWORD,
1491                                             0);
1492                 match r as uint {
1493                     0 => Err(ErrMapViewOfFile(errno())),
1494                     _ => Ok(MemoryMap {
1495                        data: r as *mut u8,
1496                        len: len,
1497                        kind: MapFile(mapping as *const u8)
1498                     })
1499                 }
1500             }
1501         }
1502     }
1503
1504     /// Granularity of MapAddr() and MapOffset() parameter values.
1505     /// This may be greater than the value returned by page_size().
1506     pub fn granularity() -> uint {
1507         use mem;
1508         unsafe {
1509             let mut info = mem::zeroed();
1510             libc::GetSystemInfo(&mut info);
1511
1512             return info.dwAllocationGranularity as uint;
1513         }
1514     }
1515 }
1516
1517 #[cfg(windows)]
1518 impl Drop for MemoryMap {
1519     /// Unmap the mapping. Panics the task if any of `VirtualFree`,
1520     /// `UnmapViewOfFile`, or `CloseHandle` fail.
1521     fn drop(&mut self) {
1522         use libc::types::os::arch::extra::{LPCVOID, HANDLE};
1523         use libc::consts::os::extra::FALSE;
1524         if self.len == 0 { return }
1525
1526         unsafe {
1527             match self.kind {
1528                 MapVirtual => {
1529                     if libc::VirtualFree(self.data as *mut c_void, 0,
1530                                          libc::MEM_RELEASE) == 0 {
1531                         println!("VirtualFree failed: {}", errno());
1532                     }
1533                 },
1534                 MapFile(mapping) => {
1535                     if libc::UnmapViewOfFile(self.data as LPCVOID) == FALSE {
1536                         println!("UnmapViewOfFile failed: {}", errno());
1537                     }
1538                     if libc::CloseHandle(mapping as HANDLE) == FALSE {
1539                         println!("CloseHandle failed: {}", errno());
1540                     }
1541                 }
1542             }
1543         }
1544     }
1545 }
1546
1547 impl MemoryMap {
1548     /// Returns the pointer to the memory created or modified by this map.
1549     pub fn data(&self) -> *mut u8 { self.data }
1550     /// Returns the number of bytes this map applies to.
1551     pub fn len(&self) -> uint { self.len }
1552     /// Returns the type of mapping this represents.
1553     pub fn kind(&self) -> MemoryMapKind { self.kind }
1554 }
1555
1556 #[cfg(target_os = "linux")]
1557 pub mod consts {
1558     pub use os::arch_consts::ARCH;
1559
1560     pub const FAMILY: &'static str = "unix";
1561
1562     /// A string describing the specific operating system in use: in this
1563     /// case, `linux`.
1564     pub const SYSNAME: &'static str = "linux";
1565
1566     /// Specifies the filename prefix used for shared libraries on this
1567     /// platform: in this case, `lib`.
1568     pub const DLL_PREFIX: &'static str = "lib";
1569
1570     /// Specifies the filename suffix used for shared libraries on this
1571     /// platform: in this case, `.so`.
1572     pub const DLL_SUFFIX: &'static str = ".so";
1573
1574     /// Specifies the file extension used for shared libraries on this
1575     /// platform that goes after the dot: in this case, `so`.
1576     pub const DLL_EXTENSION: &'static str = "so";
1577
1578     /// Specifies the filename suffix used for executable binaries on this
1579     /// platform: in this case, the empty string.
1580     pub const EXE_SUFFIX: &'static str = "";
1581
1582     /// Specifies the file extension, if any, used for executable binaries
1583     /// on this platform: in this case, the empty string.
1584     pub const EXE_EXTENSION: &'static str = "";
1585 }
1586
1587 #[cfg(target_os = "macos")]
1588 pub mod consts {
1589     pub use os::arch_consts::ARCH;
1590
1591     pub const FAMILY: &'static str = "unix";
1592
1593     /// A string describing the specific operating system in use: in this
1594     /// case, `macos`.
1595     pub const SYSNAME: &'static str = "macos";
1596
1597     /// Specifies the filename prefix used for shared libraries on this
1598     /// platform: in this case, `lib`.
1599     pub const DLL_PREFIX: &'static str = "lib";
1600
1601     /// Specifies the filename suffix used for shared libraries on this
1602     /// platform: in this case, `.dylib`.
1603     pub const DLL_SUFFIX: &'static str = ".dylib";
1604
1605     /// Specifies the file extension used for shared libraries on this
1606     /// platform that goes after the dot: in this case, `dylib`.
1607     pub const DLL_EXTENSION: &'static str = "dylib";
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 = "ios")]
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, `ios`.
1626     pub const SYSNAME: &'static str = "ios";
1627
1628     /// Specifies the filename suffix used for executable binaries on this
1629     /// platform: in this case, the empty string.
1630     pub const EXE_SUFFIX: &'static str = "";
1631
1632     /// Specifies the file extension, if any, used for executable binaries
1633     /// on this platform: in this case, the empty string.
1634     pub const EXE_EXTENSION: &'static str = "";
1635 }
1636
1637 #[cfg(target_os = "freebsd")]
1638 pub mod consts {
1639     pub use os::arch_consts::ARCH;
1640
1641     pub const FAMILY: &'static str = "unix";
1642
1643     /// A string describing the specific operating system in use: in this
1644     /// case, `freebsd`.
1645     pub const SYSNAME: &'static str = "freebsd";
1646
1647     /// Specifies the filename prefix used for shared libraries on this
1648     /// platform: in this case, `lib`.
1649     pub const DLL_PREFIX: &'static str = "lib";
1650
1651     /// Specifies the filename suffix used for shared libraries on this
1652     /// platform: in this case, `.so`.
1653     pub const DLL_SUFFIX: &'static str = ".so";
1654
1655     /// Specifies the file extension used for shared libraries on this
1656     /// platform that goes after the dot: in this case, `so`.
1657     pub const DLL_EXTENSION: &'static str = "so";
1658
1659     /// Specifies the filename suffix used for executable binaries on this
1660     /// platform: in this case, the empty string.
1661     pub const EXE_SUFFIX: &'static str = "";
1662
1663     /// Specifies the file extension, if any, used for executable binaries
1664     /// on this platform: in this case, the empty string.
1665     pub const EXE_EXTENSION: &'static str = "";
1666 }
1667
1668 #[cfg(target_os = "dragonfly")]
1669 pub mod consts {
1670     pub use os::arch_consts::ARCH;
1671
1672     pub const FAMILY: &'static str = "unix";
1673
1674     /// A string describing the specific operating system in use: in this
1675     /// case, `dragonfly`.
1676     pub const SYSNAME: &'static str = "dragonfly";
1677
1678     /// Specifies the filename prefix used for shared libraries on this
1679     /// platform: in this case, `lib`.
1680     pub const DLL_PREFIX: &'static str = "lib";
1681
1682     /// Specifies the filename suffix used for shared libraries on this
1683     /// platform: in this case, `.so`.
1684     pub const DLL_SUFFIX: &'static str = ".so";
1685
1686     /// Specifies the file extension used for shared libraries on this
1687     /// platform that goes after the dot: in this case, `so`.
1688     pub const DLL_EXTENSION: &'static str = "so";
1689
1690     /// Specifies the filename suffix used for executable binaries on this
1691     /// platform: in this case, the empty string.
1692     pub const EXE_SUFFIX: &'static str = "";
1693
1694     /// Specifies the file extension, if any, used for executable binaries
1695     /// on this platform: in this case, the empty string.
1696     pub const EXE_EXTENSION: &'static str = "";
1697 }
1698
1699 #[cfg(target_os = "android")]
1700 pub mod consts {
1701     pub use os::arch_consts::ARCH;
1702
1703     pub const FAMILY: &'static str = "unix";
1704
1705     /// A string describing the specific operating system in use: in this
1706     /// case, `android`.
1707     pub const SYSNAME: &'static str = "android";
1708
1709     /// Specifies the filename prefix used for shared libraries on this
1710     /// platform: in this case, `lib`.
1711     pub const DLL_PREFIX: &'static str = "lib";
1712
1713     /// Specifies the filename suffix used for shared libraries on this
1714     /// platform: in this case, `.so`.
1715     pub const DLL_SUFFIX: &'static str = ".so";
1716
1717     /// Specifies the file extension used for shared libraries on this
1718     /// platform that goes after the dot: in this case, `so`.
1719     pub const DLL_EXTENSION: &'static str = "so";
1720
1721     /// Specifies the filename suffix used for executable binaries on this
1722     /// platform: in this case, the empty string.
1723     pub const EXE_SUFFIX: &'static str = "";
1724
1725     /// Specifies the file extension, if any, used for executable binaries
1726     /// on this platform: in this case, the empty string.
1727     pub const EXE_EXTENSION: &'static str = "";
1728 }
1729
1730 #[cfg(target_os = "windows")]
1731 pub mod consts {
1732     pub use os::arch_consts::ARCH;
1733
1734     pub const FAMILY: &'static str = "windows";
1735
1736     /// A string describing the specific operating system in use: in this
1737     /// case, `windows`.
1738     pub const SYSNAME: &'static str = "windows";
1739
1740     /// Specifies the filename prefix used for shared libraries on this
1741     /// platform: in this case, the empty string.
1742     pub const DLL_PREFIX: &'static str = "";
1743
1744     /// Specifies the filename suffix used for shared libraries on this
1745     /// platform: in this case, `.dll`.
1746     pub const DLL_SUFFIX: &'static str = ".dll";
1747
1748     /// Specifies the file extension used for shared libraries on this
1749     /// platform that goes after the dot: in this case, `dll`.
1750     pub const DLL_EXTENSION: &'static str = "dll";
1751
1752     /// Specifies the filename suffix used for executable binaries on this
1753     /// platform: in this case, `.exe`.
1754     pub const EXE_SUFFIX: &'static str = ".exe";
1755
1756     /// Specifies the file extension, if any, used for executable binaries
1757     /// on this platform: in this case, `exe`.
1758     pub const EXE_EXTENSION: &'static str = "exe";
1759 }
1760
1761 #[cfg(target_arch = "x86")]
1762 mod arch_consts {
1763     pub const ARCH: &'static str = "x86";
1764 }
1765
1766 #[cfg(target_arch = "x86_64")]
1767 mod arch_consts {
1768     pub const ARCH: &'static str = "x86_64";
1769 }
1770
1771 #[cfg(target_arch = "arm")]
1772 mod arch_consts {
1773     pub const ARCH: &'static str = "arm";
1774 }
1775
1776 #[cfg(target_arch = "mips")]
1777 mod arch_consts {
1778     pub const ARCH: &'static str = "mips";
1779 }
1780
1781 #[cfg(target_arch = "mipsel")]
1782 mod arch_consts {
1783     pub const ARCH: &'static str = "mipsel";
1784 }
1785
1786 #[cfg(test)]
1787 mod tests {
1788     use prelude::*;
1789     use c_str::ToCStr;
1790     use option;
1791     use os::{env, getcwd, getenv, make_absolute};
1792     use os::{split_paths, join_paths, setenv, unsetenv};
1793     use os;
1794     use rand::Rng;
1795     use rand;
1796
1797     #[test]
1798     pub fn last_os_error() {
1799         debug!("{}", os::last_os_error());
1800     }
1801
1802     fn make_rand_name() -> String {
1803         let mut rng = rand::task_rng();
1804         let n = format!("TEST{}", rng.gen_ascii_chars().take(10u)
1805                                      .collect::<String>());
1806         assert!(getenv(n.as_slice()).is_none());
1807         n
1808     }
1809
1810     #[test]
1811     fn test_num_cpus() {
1812         assert!(os::num_cpus() > 0);
1813     }
1814
1815     #[test]
1816     fn test_setenv() {
1817         let n = make_rand_name();
1818         setenv(n.as_slice(), "VALUE");
1819         assert_eq!(getenv(n.as_slice()), option::Option::Some("VALUE".to_string()));
1820     }
1821
1822     #[test]
1823     fn test_unsetenv() {
1824         let n = make_rand_name();
1825         setenv(n.as_slice(), "VALUE");
1826         unsetenv(n.as_slice());
1827         assert_eq!(getenv(n.as_slice()), option::Option::None);
1828     }
1829
1830     #[test]
1831     #[ignore]
1832     fn test_setenv_overwrite() {
1833         let n = make_rand_name();
1834         setenv(n.as_slice(), "1");
1835         setenv(n.as_slice(), "2");
1836         assert_eq!(getenv(n.as_slice()), option::Option::Some("2".to_string()));
1837         setenv(n.as_slice(), "");
1838         assert_eq!(getenv(n.as_slice()), option::Option::Some("".to_string()));
1839     }
1840
1841     // Windows GetEnvironmentVariable requires some extra work to make sure
1842     // the buffer the variable is copied into is the right size
1843     #[test]
1844     #[ignore]
1845     fn test_getenv_big() {
1846         let mut s = "".to_string();
1847         let mut i = 0i;
1848         while i < 100 {
1849             s.push_str("aaaaaaaaaa");
1850             i += 1;
1851         }
1852         let n = make_rand_name();
1853         setenv(n.as_slice(), s.as_slice());
1854         debug!("{}", s.clone());
1855         assert_eq!(getenv(n.as_slice()), option::Option::Some(s));
1856     }
1857
1858     #[test]
1859     fn test_self_exe_name() {
1860         let path = os::self_exe_name();
1861         assert!(path.is_some());
1862         let path = path.unwrap();
1863         debug!("{}", path.display());
1864
1865         // Hard to test this function
1866         assert!(path.is_absolute());
1867     }
1868
1869     #[test]
1870     fn test_self_exe_path() {
1871         let path = os::self_exe_path();
1872         assert!(path.is_some());
1873         let path = path.unwrap();
1874         debug!("{}", path.display());
1875
1876         // Hard to test this function
1877         assert!(path.is_absolute());
1878     }
1879
1880     #[test]
1881     #[ignore]
1882     fn test_env_getenv() {
1883         let e = env();
1884         assert!(e.len() > 0u);
1885         for p in e.iter() {
1886             let (n, v) = (*p).clone();
1887             debug!("{}", n);
1888             let v2 = getenv(n.as_slice());
1889             // MingW seems to set some funky environment variables like
1890             // "=C:=C:\MinGW\msys\1.0\bin" and "!::=::\" that are returned
1891             // from env() but not visible from getenv().
1892             assert!(v2.is_none() || v2 == option::Option::Some(v));
1893         }
1894     }
1895
1896     #[test]
1897     fn test_env_set_get_huge() {
1898         let n = make_rand_name();
1899         let s = "x".repeat(10000).to_string();
1900         setenv(n.as_slice(), s.as_slice());
1901         assert_eq!(getenv(n.as_slice()), Some(s));
1902         unsetenv(n.as_slice());
1903         assert_eq!(getenv(n.as_slice()), None);
1904     }
1905
1906     #[test]
1907     fn test_env_setenv() {
1908         let n = make_rand_name();
1909
1910         let mut e = env();
1911         setenv(n.as_slice(), "VALUE");
1912         assert!(!e.contains(&(n.clone(), "VALUE".to_string())));
1913
1914         e = env();
1915         assert!(e.contains(&(n, "VALUE".to_string())));
1916     }
1917
1918     #[test]
1919     fn test() {
1920         assert!((!Path::new("test-path").is_absolute()));
1921
1922         let cwd = getcwd().unwrap();
1923         debug!("Current working directory: {}", cwd.display());
1924
1925         debug!("{}", make_absolute(&Path::new("test-path")).unwrap().display());
1926         debug!("{}", make_absolute(&Path::new("/usr/bin")).unwrap().display());
1927     }
1928
1929     #[test]
1930     #[cfg(unix)]
1931     fn homedir() {
1932         let oldhome = getenv("HOME");
1933
1934         setenv("HOME", "/home/MountainView");
1935         assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1936
1937         setenv("HOME", "");
1938         assert!(os::homedir().is_none());
1939
1940         for s in oldhome.iter() {
1941             setenv("HOME", s.as_slice());
1942         }
1943     }
1944
1945     #[test]
1946     #[cfg(windows)]
1947     fn homedir() {
1948
1949         let oldhome = getenv("HOME");
1950         let olduserprofile = getenv("USERPROFILE");
1951
1952         setenv("HOME", "");
1953         setenv("USERPROFILE", "");
1954
1955         assert!(os::homedir().is_none());
1956
1957         setenv("HOME", "/home/MountainView");
1958         assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1959
1960         setenv("HOME", "");
1961
1962         setenv("USERPROFILE", "/home/MountainView");
1963         assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1964
1965         setenv("HOME", "/home/MountainView");
1966         setenv("USERPROFILE", "/home/PaloAlto");
1967         assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1968
1969         for s in oldhome.iter() {
1970             setenv("HOME", s.as_slice());
1971         }
1972         for s in olduserprofile.iter() {
1973             setenv("USERPROFILE", s.as_slice());
1974         }
1975     }
1976
1977     #[test]
1978     fn memory_map_rw() {
1979         use result::Result::{Ok, Err};
1980
1981         let chunk = match os::MemoryMap::new(16, &[
1982             os::MapReadable,
1983             os::MapWritable
1984         ]) {
1985             Ok(chunk) => chunk,
1986             Err(msg) => panic!("{}", msg)
1987         };
1988         assert!(chunk.len >= 16);
1989
1990         unsafe {
1991             *chunk.data = 0xBE;
1992             assert!(*chunk.data == 0xBE);
1993         }
1994     }
1995
1996     #[test]
1997     fn memory_map_file() {
1998         use os::*;
1999         use io::fs::{File, unlink};
2000         use io::SeekStyle::SeekSet;
2001         use io::FileMode::Open;
2002         use io::FileAccess::ReadWrite;
2003         use libc::HANDLE;
2004
2005         #[cfg(not(windows))]
2006         fn get_fd(file: &File) -> c_int {
2007             use os::unix::AsRawFd;
2008             file.as_raw_fd()
2009         }
2010
2011         #[cfg(windows)]
2012         fn get_fd(file: &File) -> HANDLE {
2013             use os::windows::AsRawHandle;
2014             file.as_raw_handle()
2015         }
2016
2017         let mut path = tmpdir();
2018         path.push("mmap_file.tmp");
2019         let size = MemoryMap::granularity() * 2;
2020         let mut file = File::open_mode(&path, Open, ReadWrite).unwrap();
2021         file.seek(size as i64, SeekSet);
2022         file.write_u8(0);
2023
2024         let chunk = MemoryMap::new(size / 2, &[
2025             MapReadable,
2026             MapWritable,
2027             MapFd(get_fd(&file)),
2028             MapOffset(size / 2)
2029         ]).unwrap();
2030         assert!(chunk.len > 0);
2031
2032         unsafe {
2033             *chunk.data = 0xbe;
2034             assert!(*chunk.data == 0xbe);
2035         }
2036         drop(chunk);
2037
2038         unlink(&path).unwrap();
2039     }
2040
2041     #[test]
2042     #[cfg(windows)]
2043     fn split_paths_windows() {
2044         fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
2045             split_paths(unparsed) ==
2046                 parsed.iter().map(|s| Path::new(*s)).collect::<Vec<_>>()
2047         }
2048
2049         assert!(check_parse("", &mut [""]));
2050         assert!(check_parse(r#""""#, &mut [""]));
2051         assert!(check_parse(";;", &mut ["", "", ""]));
2052         assert!(check_parse(r"c:\", &mut [r"c:\"]));
2053         assert!(check_parse(r"c:\;", &mut [r"c:\", ""]));
2054         assert!(check_parse(r"c:\;c:\Program Files\",
2055                             &mut [r"c:\", r"c:\Program Files\"]));
2056         assert!(check_parse(r#"c:\;c:\"foo"\"#, &mut [r"c:\", r"c:\foo\"]));
2057         assert!(check_parse(r#"c:\;c:\"foo;bar"\;c:\baz"#,
2058                             &mut [r"c:\", r"c:\foo;bar\", r"c:\baz"]));
2059     }
2060
2061     #[test]
2062     #[cfg(unix)]
2063     fn split_paths_unix() {
2064         fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
2065             split_paths(unparsed) ==
2066                 parsed.iter().map(|s| Path::new(*s)).collect::<Vec<_>>()
2067         }
2068
2069         assert!(check_parse("", &mut [""]));
2070         assert!(check_parse("::", &mut ["", "", ""]));
2071         assert!(check_parse("/", &mut ["/"]));
2072         assert!(check_parse("/:", &mut ["/", ""]));
2073         assert!(check_parse("/:/usr/local", &mut ["/", "/usr/local"]));
2074     }
2075
2076     #[test]
2077     #[cfg(unix)]
2078     fn join_paths_unix() {
2079         fn test_eq(input: &[&str], output: &str) -> bool {
2080             join_paths(input).unwrap() == output.as_bytes()
2081         }
2082
2083         assert!(test_eq(&[], ""));
2084         assert!(test_eq(&["/bin", "/usr/bin", "/usr/local/bin"],
2085                          "/bin:/usr/bin:/usr/local/bin"));
2086         assert!(test_eq(&["", "/bin", "", "", "/usr/bin", ""],
2087                          ":/bin:::/usr/bin:"));
2088         assert!(join_paths(&["/te:st"]).is_err());
2089     }
2090
2091     #[test]
2092     #[cfg(windows)]
2093     fn join_paths_windows() {
2094         fn test_eq(input: &[&str], output: &str) -> bool {
2095             join_paths(input).unwrap() == output.as_bytes()
2096         }
2097
2098         assert!(test_eq(&[], ""));
2099         assert!(test_eq(&[r"c:\windows", r"c:\"],
2100                         r"c:\windows;c:\"));
2101         assert!(test_eq(&["", r"c:\windows", "", "", r"c:\", ""],
2102                         r";c:\windows;;;c:\;"));
2103         assert!(test_eq(&[r"c:\te;st", r"c:\"],
2104                         r#""c:\te;st";c:\"#));
2105         assert!(join_paths(&[r#"c:\te"st"#]).is_err());
2106     }
2107
2108     // More recursive_mkdir tests are in extra::tempfile
2109 }