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