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