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