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