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