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