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