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