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