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