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