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