]> git.lizzy.rs Git - rust.git/blob - src/libstd/os.rs
Convert most code to new inner attribute syntax.
[rust.git] / src / libstd / os.rs
1 // Copyright 2012-2013 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 #![allow(missing_doc)]
30
31 #[cfg(target_os = "macos")]
32 #[cfg(windows)]
33 use iter::range;
34
35 use clone::Clone;
36 use container::Container;
37 use libc;
38 use libc::{c_char, c_void, c_int};
39 use option::{Some, None, Option};
40 use os;
41 use ops::Drop;
42 use result::{Err, Ok, Result};
43 use ptr;
44 use str;
45 use str::{Str, StrSlice};
46 use fmt;
47 use sync::atomics::{AtomicInt, INIT_ATOMIC_INT, SeqCst};
48 use path::{Path, GenericPath};
49 use iter::Iterator;
50 use slice::{Vector, CloneableVector, ImmutableVector, MutableVector, OwnedVector};
51 use ptr::RawPtr;
52
53 #[cfg(unix)]
54 use c_str::ToCStr;
55 #[cfg(windows)]
56 use str::OwnedStr;
57
58 /// Delegates to the libc close() function, returning the same return value.
59 pub fn close(fd: int) -> int {
60     unsafe {
61         libc::close(fd as c_int) as int
62     }
63 }
64
65 pub static TMPBUF_SZ : uint = 1000u;
66 static BUF_BYTES : uint = 2048u;
67
68 /// Returns the current working directory.
69 #[cfg(unix)]
70 pub fn getcwd() -> Path {
71     use c_str::CString;
72
73     let mut buf = [0 as c_char, ..BUF_BYTES];
74     unsafe {
75         if libc::getcwd(buf.as_mut_ptr(), buf.len() as libc::size_t).is_null() {
76             fail!()
77         }
78         Path::new(CString::new(buf.as_ptr(), false))
79     }
80 }
81
82 /// Returns the current working directory.
83 #[cfg(windows)]
84 pub fn getcwd() -> Path {
85     use libc::DWORD;
86     use libc::GetCurrentDirectoryW;
87     let mut buf = [0 as u16, ..BUF_BYTES];
88     unsafe {
89         if libc::GetCurrentDirectoryW(buf.len() as DWORD, buf.as_mut_ptr()) == 0 as DWORD {
90             fail!();
91         }
92     }
93     Path::new(str::from_utf16(str::truncate_utf16_at_nul(buf))
94               .expect("GetCurrentDirectoryW returned invalid UTF-16"))
95 }
96
97 #[cfg(windows)]
98 pub mod win32 {
99     use libc::types::os::arch::extra::DWORD;
100     use libc;
101     use option::{None, Option};
102     use option;
103     use os::TMPBUF_SZ;
104     use str::StrSlice;
105     use str;
106     use slice::{MutableVector, ImmutableVector, OwnedVector};
107     use slice;
108
109     pub fn fill_utf16_buf_and_decode(f: |*mut u16, DWORD| -> DWORD)
110         -> Option<~str> {
111
112         unsafe {
113             let mut n = TMPBUF_SZ as DWORD;
114             let mut res = None;
115             let mut done = false;
116             while !done {
117                 let mut buf = slice::from_elem(n as uint, 0u16);
118                 let k = f(buf.as_mut_ptr(), n);
119                 if k == (0 as DWORD) {
120                     done = true;
121                 } else if k == n &&
122                           libc::GetLastError() ==
123                           libc::ERROR_INSUFFICIENT_BUFFER as DWORD {
124                     n *= 2 as DWORD;
125                 } else if k >= n {
126                     n = k;
127                 } else {
128                     done = true;
129                 }
130                 if k != 0 && done {
131                     let sub = buf.slice(0, k as uint);
132                     // We want to explicitly catch the case when the
133                     // closure returned invalid UTF-16, rather than
134                     // set `res` to None and continue.
135                     let s = str::from_utf16(sub)
136                         .expect("fill_utf16_buf_and_decode: closure created invalid UTF-16");
137                     res = option::Some(s)
138                 }
139             }
140             return res;
141         }
142     }
143
144     pub fn as_utf16_p<T>(s: &str, f: |*u16| -> T) -> T {
145         let mut t = s.to_utf16();
146         // Null terminate before passing on.
147         t.push(0u16);
148         f(t.as_ptr())
149     }
150 }
151
152 /*
153 Accessing environment variables is not generally threadsafe.
154 Serialize access through a global lock.
155 */
156 fn with_env_lock<T>(f: || -> T) -> T {
157     use unstable::mutex::{StaticNativeMutex, NATIVE_MUTEX_INIT};
158
159     static mut lock: StaticNativeMutex = NATIVE_MUTEX_INIT;
160
161     unsafe {
162         let _guard = lock.lock();
163         f()
164     }
165 }
166
167 /// Returns a vector of (variable, value) pairs for all the environment
168 /// variables of the current process.
169 ///
170 /// Invalid UTF-8 bytes are replaced with \uFFFD. See `str::from_utf8_lossy()`
171 /// for details.
172 pub fn env() -> ~[(~str,~str)] {
173     env_as_bytes().move_iter().map(|(k,v)| {
174         let k = str::from_utf8_lossy(k).into_owned();
175         let v = str::from_utf8_lossy(v).into_owned();
176         (k,v)
177     }).collect()
178 }
179
180 /// Returns a vector of (variable, value) byte-vector pairs for all the
181 /// environment variables of the current process.
182 pub fn env_as_bytes() -> ~[(~[u8],~[u8])] {
183     unsafe {
184         #[cfg(windows)]
185         unsafe fn get_env_pairs() -> ~[~[u8]] {
186             use c_str;
187             use str::StrSlice;
188
189             use libc::funcs::extra::kernel32::{
190                 GetEnvironmentStringsA,
191                 FreeEnvironmentStringsA
192             };
193             let ch = GetEnvironmentStringsA();
194             if ch as uint == 0 {
195                 fail!("os::env() failure getting env string from OS: {}",
196                        os::last_os_error());
197             }
198             let mut result = ~[];
199             c_str::from_c_multistring(ch as *c_char, None, |cstr| {
200                 result.push(cstr.as_bytes_no_nul().to_owned());
201             });
202             FreeEnvironmentStringsA(ch);
203             result
204         }
205         #[cfg(unix)]
206         unsafe fn get_env_pairs() -> ~[~[u8]] {
207             use c_str::CString;
208
209             extern {
210                 fn rust_env_pairs() -> **c_char;
211             }
212             let environ = rust_env_pairs();
213             if environ as uint == 0 {
214                 fail!("os::env() failure getting env string from OS: {}",
215                        os::last_os_error());
216             }
217             let mut result = ~[];
218             ptr::array_each(environ, |e| {
219                 let env_pair = CString::new(e, false).as_bytes_no_nul().to_owned();
220                 result.push(env_pair);
221             });
222             result
223         }
224
225         fn env_convert(input: ~[~[u8]]) -> ~[(~[u8], ~[u8])] {
226             let mut pairs = ~[];
227             for p in input.iter() {
228                 let vs: ~[&[u8]] = p.splitn(1, |b| *b == '=' as u8).collect();
229                 let key = vs[0].to_owned();
230                 let val = if vs.len() < 2 { ~[] } else { vs[1].to_owned() };
231                 pairs.push((key, val));
232             }
233             pairs
234         }
235         with_env_lock(|| {
236             let unparsed_environ = get_env_pairs();
237             env_convert(unparsed_environ)
238         })
239     }
240 }
241
242 #[cfg(unix)]
243 /// Fetches the environment variable `n` from the current process, returning
244 /// None if the variable isn't set.
245 ///
246 /// Any invalid UTF-8 bytes in the value are replaced by \uFFFD. See
247 /// `str::from_utf8_lossy()` for details.
248 ///
249 /// # Failure
250 ///
251 /// Fails if `n` has any interior NULs.
252 pub fn getenv(n: &str) -> Option<~str> {
253     getenv_as_bytes(n).map(|v| str::from_utf8_lossy(v).into_owned())
254 }
255
256 #[cfg(unix)]
257 /// Fetches the environment variable `n` byte vector from the current process,
258 /// returning None if the variable isn't set.
259 ///
260 /// # Failure
261 ///
262 /// Fails if `n` has any interior NULs.
263 pub fn getenv_as_bytes(n: &str) -> Option<~[u8]> {
264     use c_str::CString;
265
266     unsafe {
267         with_env_lock(|| {
268             let s = n.with_c_str(|buf| libc::getenv(buf));
269             if s.is_null() {
270                 None
271             } else {
272                 Some(CString::new(s, false).as_bytes_no_nul().to_owned())
273             }
274         })
275     }
276 }
277
278 #[cfg(windows)]
279 /// Fetches the environment variable `n` from the current process, returning
280 /// None if the variable isn't set.
281 pub fn getenv(n: &str) -> Option<~str> {
282     unsafe {
283         with_env_lock(|| {
284             use os::win32::{as_utf16_p, fill_utf16_buf_and_decode};
285             as_utf16_p(n, |u| {
286                 fill_utf16_buf_and_decode(|buf, sz| {
287                     libc::GetEnvironmentVariableW(u, buf, sz)
288                 })
289             })
290         })
291     }
292 }
293
294 #[cfg(windows)]
295 /// Fetches the environment variable `n` byte vector from the current process,
296 /// returning None if the variable isn't set.
297 pub fn getenv_as_bytes(n: &str) -> Option<~[u8]> {
298     getenv(n).map(|s| s.into_bytes())
299 }
300
301
302 #[cfg(unix)]
303 /// Sets the environment variable `n` to the value `v` for the currently running
304 /// process
305 ///
306 /// # Failure
307 ///
308 /// Fails if `n` or `v` have any interior NULs.
309 pub fn setenv(n: &str, v: &str) {
310     unsafe {
311         with_env_lock(|| {
312             n.with_c_str(|nbuf| {
313                 v.with_c_str(|vbuf| {
314                     libc::funcs::posix01::unistd::setenv(nbuf, vbuf, 1);
315                 })
316             })
317         })
318     }
319 }
320
321
322 #[cfg(windows)]
323 /// Sets the environment variable `n` to the value `v` for the currently running
324 /// process
325 pub fn setenv(n: &str, v: &str) {
326     unsafe {
327         with_env_lock(|| {
328             use os::win32::as_utf16_p;
329             as_utf16_p(n, |nbuf| {
330                 as_utf16_p(v, |vbuf| {
331                     libc::SetEnvironmentVariableW(nbuf, vbuf);
332                 })
333             })
334         })
335     }
336 }
337
338 /// Remove a variable from the environment entirely
339 ///
340 /// # Failure
341 ///
342 /// Fails (on unix) if `n` has any interior NULs.
343 pub fn unsetenv(n: &str) {
344     #[cfg(unix)]
345     fn _unsetenv(n: &str) {
346         unsafe {
347             with_env_lock(|| {
348                 n.with_c_str(|nbuf| {
349                     libc::funcs::posix01::unistd::unsetenv(nbuf);
350                 })
351             })
352         }
353     }
354     #[cfg(windows)]
355     fn _unsetenv(n: &str) {
356         unsafe {
357             with_env_lock(|| {
358                 use os::win32::as_utf16_p;
359                 as_utf16_p(n, |nbuf| {
360                     libc::SetEnvironmentVariableW(nbuf, ptr::null());
361                 })
362             })
363         }
364     }
365
366     _unsetenv(n);
367 }
368
369 /// A low-level OS in-memory pipe.
370 pub struct Pipe {
371     /// A file descriptor representing the reading end of the pipe. Data written
372     /// on the `out` file descriptor can be read from this file descriptor.
373     input: c_int,
374     /// A file descriptor representing the write end of the pipe. Data written
375     /// to this file descriptor can be read from the `input` file descriptor.
376     out: c_int,
377 }
378
379 /// Creates a new low-level OS in-memory pipe.
380 #[cfg(unix)]
381 pub fn pipe() -> Pipe {
382     unsafe {
383         let mut fds = Pipe {input: 0,
384                             out: 0};
385         assert_eq!(libc::pipe(&mut fds.input), 0);
386         return Pipe {input: fds.input, out: fds.out};
387     }
388 }
389
390 /// Creates a new low-level OS in-memory pipe.
391 #[cfg(windows)]
392 pub fn pipe() -> Pipe {
393     unsafe {
394         // Windows pipes work subtly differently than unix pipes, and their
395         // inheritance has to be handled in a different way that I do not
396         // fully understand. Here we explicitly make the pipe non-inheritable,
397         // which means to pass it to a subprocess they need to be duplicated
398         // first, as in std::run.
399         let mut fds = Pipe {input: 0,
400                     out: 0};
401         let res = libc::pipe(&mut fds.input, 1024 as ::libc::c_uint,
402                              (libc::O_BINARY | libc::O_NOINHERIT) as c_int);
403         assert_eq!(res, 0);
404         assert!((fds.input != -1 && fds.input != 0 ));
405         assert!((fds.out != -1 && fds.input != 0));
406         return Pipe {input: fds.input, out: fds.out};
407     }
408 }
409
410 /// Returns the proper dll filename for the given basename of a file.
411 pub fn dll_filename(base: &str) -> ~str {
412     format!("{}{}{}", consts::DLL_PREFIX, base, consts::DLL_SUFFIX)
413 }
414
415 /// Optionally returns the filesystem path of the current executable which is
416 /// running. If any failure occurs, None is returned.
417 pub fn self_exe_name() -> Option<Path> {
418
419     #[cfg(target_os = "freebsd")]
420     fn load_self() -> Option<~[u8]> {
421         unsafe {
422             use libc::funcs::bsd44::*;
423             use libc::consts::os::extra::*;
424             use slice;
425             let mib = ~[CTL_KERN as c_int,
426                         KERN_PROC as c_int,
427                         KERN_PROC_PATHNAME as c_int, -1 as c_int];
428             let mut sz: libc::size_t = 0;
429             let err = sysctl(mib.as_ptr(), mib.len() as ::libc::c_uint,
430                              ptr::mut_null(), &mut sz, ptr::null(),
431                              0u as libc::size_t);
432             if err != 0 { return None; }
433             if sz == 0 { return None; }
434             let mut v: ~[u8] = slice::with_capacity(sz as uint);
435             let err = sysctl(mib.as_ptr(), mib.len() as ::libc::c_uint,
436                              v.as_mut_ptr() as *mut c_void, &mut sz, ptr::null(),
437                              0u as libc::size_t);
438             if err != 0 { return None; }
439             if sz == 0 { return None; }
440             v.set_len(sz as uint - 1); // chop off trailing NUL
441             Some(v)
442         }
443     }
444
445     #[cfg(target_os = "linux")]
446     #[cfg(target_os = "android")]
447     fn load_self() -> Option<~[u8]> {
448         use std::io;
449
450         match io::fs::readlink(&Path::new("/proc/self/exe")) {
451             Ok(path) => Some(path.as_vec().to_owned()),
452             Err(..) => None
453         }
454     }
455
456     #[cfg(target_os = "macos")]
457     fn load_self() -> Option<~[u8]> {
458         unsafe {
459             use libc::funcs::extra::_NSGetExecutablePath;
460             use slice;
461             let mut sz: u32 = 0;
462             _NSGetExecutablePath(ptr::mut_null(), &mut sz);
463             if sz == 0 { return None; }
464             let mut v: ~[u8] = slice::with_capacity(sz as uint);
465             let err = _NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz);
466             if err != 0 { return None; }
467             v.set_len(sz as uint - 1); // chop off trailing NUL
468             Some(v)
469         }
470     }
471
472     #[cfg(windows)]
473     fn load_self() -> Option<~[u8]> {
474         use str::OwnedStr;
475
476         unsafe {
477             use os::win32::fill_utf16_buf_and_decode;
478             fill_utf16_buf_and_decode(|buf, sz| {
479                 libc::GetModuleFileNameW(0u as libc::DWORD, buf, sz)
480             }).map(|s| s.into_bytes())
481         }
482     }
483
484     load_self().and_then(Path::new_opt)
485 }
486
487 /// Optionally returns the filesystem path to the current executable which is
488 /// running. Like self_exe_name() but without the binary's name.
489 /// If any failure occurs, None is returned.
490 pub fn self_exe_path() -> Option<Path> {
491     self_exe_name().map(|mut p| { p.pop(); p })
492 }
493
494 /**
495  * Returns the path to the user's home directory, if known.
496  *
497  * On Unix, returns the value of the 'HOME' environment variable if it is set
498  * and not equal to the empty string.
499  *
500  * On Windows, returns the value of the 'HOME' environment variable if it is
501  * set and not equal to the empty string. Otherwise, returns the value of the
502  * 'USERPROFILE' environment variable if it is set and not equal to the empty
503  * string.
504  *
505  * Otherwise, homedir returns option::none.
506  */
507 pub fn homedir() -> Option<Path> {
508     // FIXME (#7188): getenv needs a ~[u8] variant
509     return match getenv("HOME") {
510         Some(ref p) if !p.is_empty() => Path::new_opt(p.as_slice()),
511         _ => secondary()
512     };
513
514     #[cfg(unix)]
515     fn secondary() -> Option<Path> {
516         None
517     }
518
519     #[cfg(windows)]
520     fn secondary() -> Option<Path> {
521         getenv("USERPROFILE").and_then(|p| {
522             if !p.is_empty() {
523                 Path::new_opt(p)
524             } else {
525                 None
526             }
527         })
528     }
529 }
530
531 /**
532  * Returns the path to a temporary directory.
533  *
534  * On Unix, returns the value of the 'TMPDIR' environment variable if it is
535  * set and non-empty and '/tmp' otherwise.
536  * On Android, there is no global temporary folder (it is usually allocated
537  * per-app), hence returns '/data/tmp' which is commonly used.
538  *
539  * On Windows, returns the value of, in order, the 'TMP', 'TEMP',
540  * 'USERPROFILE' environment variable  if any are set and not the empty
541  * string. Otherwise, tmpdir returns the path to the Windows directory.
542  */
543 pub fn tmpdir() -> Path {
544     return lookup();
545
546     fn getenv_nonempty(v: &str) -> Option<Path> {
547         match getenv(v) {
548             Some(x) =>
549                 if x.is_empty() {
550                     None
551                 } else {
552                     Path::new_opt(x)
553                 },
554             _ => None
555         }
556     }
557
558     #[cfg(unix)]
559     fn lookup() -> Path {
560         if cfg!(target_os = "android") {
561             Path::new("/data/tmp")
562         } else {
563             getenv_nonempty("TMPDIR").unwrap_or(Path::new("/tmp"))
564         }
565     }
566
567     #[cfg(windows)]
568     fn lookup() -> Path {
569         getenv_nonempty("TMP").or(
570             getenv_nonempty("TEMP").or(
571                 getenv_nonempty("USERPROFILE").or(
572                    getenv_nonempty("WINDIR")))).unwrap_or(Path::new("C:\\Windows"))
573     }
574 }
575
576 /**
577  * Convert a relative path to an absolute path
578  *
579  * If the given path is relative, return it prepended with the current working
580  * directory. If the given path is already an absolute path, return it
581  * as is.
582  */
583 // NB: this is here rather than in path because it is a form of environment
584 // querying; what it does depends on the process working directory, not just
585 // the input paths.
586 pub fn make_absolute(p: &Path) -> Path {
587     if p.is_absolute() {
588         p.clone()
589     } else {
590         let mut ret = getcwd();
591         ret.push(p);
592         ret
593     }
594 }
595
596 /// Changes the current working directory to the specified path, returning
597 /// whether the change was completed successfully or not.
598 pub fn change_dir(p: &Path) -> bool {
599     return chdir(p);
600
601     #[cfg(windows)]
602     fn chdir(p: &Path) -> bool {
603         unsafe {
604             use os::win32::as_utf16_p;
605             return as_utf16_p(p.as_str().unwrap(), |buf| {
606                 libc::SetCurrentDirectoryW(buf) != (0 as libc::BOOL)
607             });
608         }
609     }
610
611     #[cfg(unix)]
612     fn chdir(p: &Path) -> bool {
613         p.with_c_str(|buf| {
614             unsafe {
615                 libc::chdir(buf) == (0 as c_int)
616             }
617         })
618     }
619 }
620
621 #[cfg(unix)]
622 /// Returns the platform-specific value of errno
623 pub fn errno() -> int {
624     #[cfg(target_os = "macos")]
625     #[cfg(target_os = "freebsd")]
626     fn errno_location() -> *c_int {
627         extern {
628             fn __error() -> *c_int;
629         }
630         unsafe {
631             __error()
632         }
633     }
634
635     #[cfg(target_os = "linux")]
636     #[cfg(target_os = "android")]
637     fn errno_location() -> *c_int {
638         extern {
639             fn __errno_location() -> *c_int;
640         }
641         unsafe {
642             __errno_location()
643         }
644     }
645
646     unsafe {
647         (*errno_location()) as int
648     }
649 }
650
651 #[cfg(windows)]
652 /// Returns the platform-specific value of errno
653 pub fn errno() -> uint {
654     use libc::types::os::arch::extra::DWORD;
655
656     #[link_name = "kernel32"]
657     extern "system" {
658         fn GetLastError() -> DWORD;
659     }
660
661     unsafe {
662         GetLastError() as uint
663     }
664 }
665
666 /// Get a string representing the platform-dependent last error
667 pub fn last_os_error() -> ~str {
668     #[cfg(unix)]
669     fn strerror() -> ~str {
670         #[cfg(target_os = "macos")]
671         #[cfg(target_os = "android")]
672         #[cfg(target_os = "freebsd")]
673         fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: libc::size_t)
674                       -> c_int {
675             extern {
676                 fn strerror_r(errnum: c_int, buf: *mut c_char,
677                               buflen: libc::size_t) -> c_int;
678             }
679             unsafe {
680                 strerror_r(errnum, buf, buflen)
681             }
682         }
683
684         // GNU libc provides a non-compliant version of strerror_r by default
685         // and requires macros to instead use the POSIX compliant variant.
686         // So we just use __xpg_strerror_r which is always POSIX compliant
687         #[cfg(target_os = "linux")]
688         fn strerror_r(errnum: c_int, buf: *mut c_char,
689                       buflen: libc::size_t) -> c_int {
690             extern {
691                 fn __xpg_strerror_r(errnum: c_int,
692                                     buf: *mut c_char,
693                                     buflen: libc::size_t)
694                                     -> c_int;
695             }
696             unsafe {
697                 __xpg_strerror_r(errnum, buf, buflen)
698             }
699         }
700
701         let mut buf = [0 as c_char, ..TMPBUF_SZ];
702
703         let p = buf.as_mut_ptr();
704         unsafe {
705             if strerror_r(errno() as c_int, p, buf.len() as libc::size_t) < 0 {
706                 fail!("strerror_r failure");
707             }
708
709             str::raw::from_c_str(p as *c_char)
710         }
711     }
712
713     #[cfg(windows)]
714     fn strerror() -> ~str {
715         use libc::types::os::arch::extra::DWORD;
716         use libc::types::os::arch::extra::LPWSTR;
717         use libc::types::os::arch::extra::LPVOID;
718         use libc::types::os::arch::extra::WCHAR;
719
720         #[link_name = "kernel32"]
721         extern "system" {
722             fn FormatMessageW(flags: DWORD,
723                               lpSrc: LPVOID,
724                               msgId: DWORD,
725                               langId: DWORD,
726                               buf: LPWSTR,
727                               nsize: DWORD,
728                               args: *c_void)
729                               -> DWORD;
730         }
731
732         static FORMAT_MESSAGE_FROM_SYSTEM: DWORD = 0x00001000;
733         static FORMAT_MESSAGE_IGNORE_INSERTS: DWORD = 0x00000200;
734
735         // This value is calculated from the macro
736         // MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT)
737         let langId = 0x0800 as DWORD;
738         let err = errno() as DWORD;
739
740         let mut buf = [0 as WCHAR, ..TMPBUF_SZ];
741
742         unsafe {
743             let res = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
744                                      FORMAT_MESSAGE_IGNORE_INSERTS,
745                                      ptr::mut_null(),
746                                      err,
747                                      langId,
748                                      buf.as_mut_ptr(),
749                                      buf.len() as DWORD,
750                                      ptr::null());
751             if res == 0 {
752                 // Sometimes FormatMessageW can fail e.g. system doesn't like langId,
753                 let fm_err = errno();
754                 return format!("OS Error {} (FormatMessageW() returned error {})", err, fm_err);
755             }
756
757             let msg = str::from_utf16(str::truncate_utf16_at_nul(buf));
758             match msg {
759                 Some(msg) => format!("OS Error {}: {}", err, msg),
760                 None => format!("OS Error {} (FormatMessageW() returned invalid UTF-16)", err),
761             }
762         }
763     }
764
765     strerror()
766 }
767
768 static mut EXIT_STATUS: AtomicInt = INIT_ATOMIC_INT;
769
770 /**
771  * Sets the process exit code
772  *
773  * Sets the exit code returned by the process if all supervised tasks
774  * terminate successfully (without failing). If the current root task fails
775  * and is supervised by the scheduler then any user-specified exit status is
776  * ignored and the process exits with the default failure status.
777  *
778  * Note that this is not synchronized against modifications of other threads.
779  */
780 pub fn set_exit_status(code: int) {
781     unsafe { EXIT_STATUS.store(code, SeqCst) }
782 }
783
784 /// Fetches the process's current exit code. This defaults to 0 and can change
785 /// by calling `set_exit_status`.
786 pub fn get_exit_status() -> int {
787     unsafe { EXIT_STATUS.load(SeqCst) }
788 }
789
790 #[cfg(target_os = "macos")]
791 unsafe fn load_argc_and_argv(argc: int, argv: **c_char) -> ~[~[u8]] {
792     use c_str::CString;
793
794     let mut args = ~[];
795     for i in range(0u, argc as uint) {
796         args.push(CString::new(*argv.offset(i as int), false).as_bytes_no_nul().to_owned())
797     }
798     args
799 }
800
801 /**
802  * Returns the command line arguments
803  *
804  * Returns a list of the command line arguments.
805  */
806 #[cfg(target_os = "macos")]
807 fn real_args_as_bytes() -> ~[~[u8]] {
808     unsafe {
809         let (argc, argv) = (*_NSGetArgc() as int,
810                             *_NSGetArgv() as **c_char);
811         load_argc_and_argv(argc, argv)
812     }
813 }
814
815 #[cfg(target_os = "linux")]
816 #[cfg(target_os = "android")]
817 #[cfg(target_os = "freebsd")]
818 fn real_args_as_bytes() -> ~[~[u8]] {
819     use rt;
820
821     match rt::args::clone() {
822         Some(args) => args,
823         None => fail!("process arguments not initialized")
824     }
825 }
826
827 #[cfg(not(windows))]
828 fn real_args() -> ~[~str] {
829     real_args_as_bytes().move_iter().map(|v| str::from_utf8_lossy(v).into_owned()).collect()
830 }
831
832 #[cfg(windows)]
833 fn real_args() -> ~[~str] {
834     use slice;
835
836     let mut nArgs: c_int = 0;
837     let lpArgCount: *mut c_int = &mut nArgs;
838     let lpCmdLine = unsafe { GetCommandLineW() };
839     let szArgList = unsafe { CommandLineToArgvW(lpCmdLine, lpArgCount) };
840
841     let mut args = ~[];
842     for i in range(0u, nArgs as uint) {
843         unsafe {
844             // Determine the length of this argument.
845             let ptr = *szArgList.offset(i as int);
846             let mut len = 0;
847             while *ptr.offset(len as int) != 0 { len += 1; }
848
849             // Push it onto the list.
850             let opt_s = slice::raw::buf_as_slice(ptr, len, |buf| {
851                     str::from_utf16(str::truncate_utf16_at_nul(buf))
852                 });
853             args.push(opt_s.expect("CommandLineToArgvW returned invalid UTF-16"));
854         }
855     }
856
857     unsafe {
858         LocalFree(szArgList as *c_void);
859     }
860
861     return args;
862 }
863
864 #[cfg(windows)]
865 fn real_args_as_bytes() -> ~[~[u8]] {
866     real_args().move_iter().map(|s| s.into_bytes()).collect()
867 }
868
869 type LPCWSTR = *u16;
870
871 #[cfg(windows)]
872 #[link_name="kernel32"]
873 extern "system" {
874     fn GetCommandLineW() -> LPCWSTR;
875     fn LocalFree(ptr: *c_void);
876 }
877
878 #[cfg(windows)]
879 #[link_name="shell32"]
880 extern "system" {
881     fn CommandLineToArgvW(lpCmdLine: LPCWSTR, pNumArgs: *mut c_int) -> **u16;
882 }
883
884 /// Returns the arguments which this program was started with (normally passed
885 /// via the command line).
886 ///
887 /// The arguments are interpreted as utf-8, with invalid bytes replaced with \uFFFD.
888 /// See `str::from_utf8_lossy` for details.
889 pub fn args() -> ~[~str] {
890     real_args()
891 }
892
893 /// Returns the arguments which this program was started with (normally passed
894 /// via the command line) as byte vectors.
895 pub fn args_as_bytes() -> ~[~[u8]] {
896     real_args_as_bytes()
897 }
898
899 #[cfg(target_os = "macos")]
900 extern {
901     // These functions are in crt_externs.h.
902     pub fn _NSGetArgc() -> *c_int;
903     pub fn _NSGetArgv() -> ***c_char;
904 }
905
906 // Round up `from` to be divisible by `to`
907 fn round_up(from: uint, to: uint) -> uint {
908     let r = if from % to == 0 {
909         from
910     } else {
911         from + to - (from % to)
912     };
913     if r == 0 {
914         to
915     } else {
916         r
917     }
918 }
919
920 /// Returns the page size of the current architecture in bytes.
921 #[cfg(unix)]
922 pub fn page_size() -> uint {
923     unsafe {
924         libc::sysconf(libc::_SC_PAGESIZE) as uint
925     }
926 }
927
928 /// Returns the page size of the current architecture in bytes.
929 #[cfg(windows)]
930 pub fn page_size() -> uint {
931     unsafe {
932         let mut info = libc::SYSTEM_INFO::new();
933         libc::GetSystemInfo(&mut info);
934
935         return info.dwPageSize as uint;
936     }
937 }
938
939 /// A memory mapped file or chunk of memory. This is a very system-specific
940 /// interface to the OS's memory mapping facilities (`mmap` on POSIX,
941 /// `VirtualAlloc`/`CreateFileMapping` on win32). It makes no attempt at
942 /// abstracting platform differences, besides in error values returned. Consider
943 /// yourself warned.
944 ///
945 /// The memory map is released (unmapped) when the destructor is run, so don't
946 /// let it leave scope by accident if you want it to stick around.
947 pub struct MemoryMap {
948     /// Pointer to the memory created or modified by this map.
949     data: *mut u8,
950     /// Number of bytes this map applies to
951     len: uint,
952     /// Type of mapping
953     kind: MemoryMapKind
954 }
955
956 /// Type of memory map
957 pub enum MemoryMapKind {
958     /// Virtual memory map. Usually used to change the permissions of a given
959     /// chunk of memory.  Corresponds to `VirtualAlloc` on Windows.
960     MapFile(*u8),
961     /// Virtual memory map. Usually used to change the permissions of a given
962     /// chunk of memory, or for allocation. Corresponds to `VirtualAlloc` on
963     /// Windows.
964     MapVirtual
965 }
966
967 /// Options the memory map is created with
968 pub enum MapOption {
969     /// The memory should be readable
970     MapReadable,
971     /// The memory should be writable
972     MapWritable,
973     /// The memory should be executable
974     MapExecutable,
975     /// Create a map for a specific address range. Corresponds to `MAP_FIXED` on
976     /// POSIX.
977     MapAddr(*u8),
978     /// Create a memory mapping for a file with a given fd.
979     MapFd(c_int),
980     /// When using `MapFd`, the start of the map is `uint` bytes from the start
981     /// of the file.
982     MapOffset(uint),
983     /// On POSIX, this can be used to specify the default flags passed to
984     /// `mmap`. By default it uses `MAP_PRIVATE` and, if not using `MapFd`,
985     /// `MAP_ANON`. This will override both of those. This is platform-specific
986     /// (the exact values used) and ignored on Windows.
987     MapNonStandardFlags(c_int),
988 }
989
990 /// Possible errors when creating a map.
991 pub enum MapError {
992     /// ## The following are POSIX-specific
993     ///
994     /// fd was not open for reading or, if using `MapWritable`, was not open for
995     /// writing.
996     ErrFdNotAvail,
997     /// fd was not valid
998     ErrInvalidFd,
999     /// Either the address given by `MapAddr` or offset given by `MapOffset` was
1000     /// not a multiple of `MemoryMap::granularity` (unaligned to page size).
1001     ErrUnaligned,
1002     /// With `MapFd`, the fd does not support mapping.
1003     ErrNoMapSupport,
1004     /// If using `MapAddr`, the address + `min_len` was outside of the process's
1005     /// address space. If using `MapFd`, the target of the fd didn't have enough
1006     /// resources to fulfill the request.
1007     ErrNoMem,
1008     /// A zero-length map was requested. This is invalid according to
1009     /// [POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/functions/mmap.html).
1010     /// Not all platforms obey this, but this wrapper does.
1011     ErrZeroLength,
1012     /// Unrecognized error. The inner value is the unrecognized errno.
1013     ErrUnknown(int),
1014     /// ## The following are win32-specific
1015     ///
1016     /// Unsupported combination of protection flags
1017     /// (`MapReadable`/`MapWritable`/`MapExecutable`).
1018     ErrUnsupProt,
1019     /// When using `MapFd`, `MapOffset` was given (Windows does not support this
1020     /// at all)
1021     ErrUnsupOffset,
1022     /// When using `MapFd`, there was already a mapping to the file.
1023     ErrAlreadyExists,
1024     /// Unrecognized error from `VirtualAlloc`. The inner value is the return
1025     /// value of GetLastError.
1026     ErrVirtualAlloc(uint),
1027     /// Unrecognized error from `CreateFileMapping`. The inner value is the
1028     /// return value of `GetLastError`.
1029     ErrCreateFileMappingW(uint),
1030     /// Unrecognized error from `MapViewOfFile`. The inner value is the return
1031     /// value of `GetLastError`.
1032     ErrMapViewOfFile(uint)
1033 }
1034
1035 impl fmt::Show for MapError {
1036     fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result {
1037         let str = match *self {
1038             ErrFdNotAvail => "fd not available for reading or writing",
1039             ErrInvalidFd => "Invalid fd",
1040             ErrUnaligned => {
1041                 "Unaligned address, invalid flags, negative length or \
1042                  unaligned offset"
1043             }
1044             ErrNoMapSupport=> "File doesn't support mapping",
1045             ErrNoMem => "Invalid address, or not enough available memory",
1046             ErrUnsupProt => "Protection mode unsupported",
1047             ErrUnsupOffset => "Offset in virtual memory mode is unsupported",
1048             ErrAlreadyExists => "File mapping for specified file already exists",
1049             ErrZeroLength => "Zero-length mapping not allowed",
1050             ErrUnknown(code) => {
1051                 return write!(out.buf, "Unknown error = {}", code)
1052             },
1053             ErrVirtualAlloc(code) => {
1054                 return write!(out.buf, "VirtualAlloc failure = {}", code)
1055             },
1056             ErrCreateFileMappingW(code) => {
1057                 return write!(out.buf, "CreateFileMappingW failure = {}", code)
1058             },
1059             ErrMapViewOfFile(code) => {
1060                 return write!(out.buf, "MapViewOfFile failure = {}", code)
1061             }
1062         };
1063         write!(out.buf, "{}", str)
1064     }
1065 }
1066
1067 #[cfg(unix)]
1068 impl MemoryMap {
1069     /// Create a new mapping with the given `options`, at least `min_len` bytes
1070     /// long. `min_len` must be greater than zero; see the note on
1071     /// `ErrZeroLength`.
1072     pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
1073         use libc::off_t;
1074         use cmp::Equiv;
1075
1076         if min_len == 0 {
1077             return Err(ErrZeroLength)
1078         }
1079         let mut addr: *u8 = ptr::null();
1080         let mut prot = 0;
1081         let mut flags = libc::MAP_PRIVATE;
1082         let mut fd = -1;
1083         let mut offset = 0;
1084         let mut custom_flags = false;
1085         let len = round_up(min_len, page_size());
1086
1087         for &o in options.iter() {
1088             match o {
1089                 MapReadable => { prot |= libc::PROT_READ; },
1090                 MapWritable => { prot |= libc::PROT_WRITE; },
1091                 MapExecutable => { prot |= libc::PROT_EXEC; },
1092                 MapAddr(addr_) => {
1093                     flags |= libc::MAP_FIXED;
1094                     addr = addr_;
1095                 },
1096                 MapFd(fd_) => {
1097                     flags |= libc::MAP_FILE;
1098                     fd = fd_;
1099                 },
1100                 MapOffset(offset_) => { offset = offset_ as off_t; },
1101                 MapNonStandardFlags(f) => { custom_flags = true; flags = f },
1102             }
1103         }
1104         if fd == -1 && !custom_flags { flags |= libc::MAP_ANON; }
1105
1106         let r = unsafe {
1107             libc::mmap(addr as *c_void, len as libc::size_t, prot, flags, fd,
1108                        offset)
1109         };
1110         if r.equiv(&libc::MAP_FAILED) {
1111             Err(match errno() as c_int {
1112                 libc::EACCES => ErrFdNotAvail,
1113                 libc::EBADF => ErrInvalidFd,
1114                 libc::EINVAL => ErrUnaligned,
1115                 libc::ENODEV => ErrNoMapSupport,
1116                 libc::ENOMEM => ErrNoMem,
1117                 code => ErrUnknown(code as int)
1118             })
1119         } else {
1120             Ok(MemoryMap {
1121                data: r as *mut u8,
1122                len: len,
1123                kind: if fd == -1 {
1124                    MapVirtual
1125                } else {
1126                    MapFile(ptr::null())
1127                }
1128             })
1129         }
1130     }
1131
1132     /// Granularity that the offset or address must be for `MapOffset` and
1133     /// `MapAddr` respectively.
1134     pub fn granularity() -> uint {
1135         page_size()
1136     }
1137 }
1138
1139 #[cfg(unix)]
1140 impl Drop for MemoryMap {
1141     /// Unmap the mapping. Fails the task if `munmap` fails.
1142     fn drop(&mut self) {
1143         if self.len == 0 { /* workaround for dummy_stack */ return; }
1144
1145         unsafe {
1146             // FIXME: what to do if this fails?
1147             let _ = libc::munmap(self.data as *c_void, self.len as libc::size_t);
1148         }
1149     }
1150 }
1151
1152 #[cfg(windows)]
1153 impl MemoryMap {
1154     /// Create a new mapping with the given `options`, at least `min_len` bytes long.
1155     pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
1156         use libc::types::os::arch::extra::{LPVOID, DWORD, SIZE_T, HANDLE};
1157
1158         let mut lpAddress: LPVOID = ptr::mut_null();
1159         let mut readable = false;
1160         let mut writable = false;
1161         let mut executable = false;
1162         let mut fd: c_int = -1;
1163         let mut offset: uint = 0;
1164         let len = round_up(min_len, page_size());
1165
1166         for &o in options.iter() {
1167             match o {
1168                 MapReadable => { readable = true; },
1169                 MapWritable => { writable = true; },
1170                 MapExecutable => { executable = true; }
1171                 MapAddr(addr_) => { lpAddress = addr_ as LPVOID; },
1172                 MapFd(fd_) => { fd = fd_; },
1173                 MapOffset(offset_) => { offset = offset_; },
1174                 MapNonStandardFlags(..) => {}
1175             }
1176         }
1177
1178         let flProtect = match (executable, readable, writable) {
1179             (false, false, false) if fd == -1 => libc::PAGE_NOACCESS,
1180             (false, true, false) => libc::PAGE_READONLY,
1181             (false, true, true) => libc::PAGE_READWRITE,
1182             (true, false, false) if fd == -1 => libc::PAGE_EXECUTE,
1183             (true, true, false) => libc::PAGE_EXECUTE_READ,
1184             (true, true, true) => libc::PAGE_EXECUTE_READWRITE,
1185             _ => return Err(ErrUnsupProt)
1186         };
1187
1188         if fd == -1 {
1189             if offset != 0 {
1190                 return Err(ErrUnsupOffset);
1191             }
1192             let r = unsafe {
1193                 libc::VirtualAlloc(lpAddress,
1194                                    len as SIZE_T,
1195                                    libc::MEM_COMMIT | libc::MEM_RESERVE,
1196                                    flProtect)
1197             };
1198             match r as uint {
1199                 0 => Err(ErrVirtualAlloc(errno())),
1200                 _ => Ok(MemoryMap {
1201                    data: r as *mut u8,
1202                    len: len,
1203                    kind: MapVirtual
1204                 })
1205             }
1206         } else {
1207             let dwDesiredAccess = match (executable, readable, writable) {
1208                 (false, true, false) => libc::FILE_MAP_READ,
1209                 (false, true, true) => libc::FILE_MAP_WRITE,
1210                 (true, true, false) => libc::FILE_MAP_READ | libc::FILE_MAP_EXECUTE,
1211                 (true, true, true) => libc::FILE_MAP_WRITE | libc::FILE_MAP_EXECUTE,
1212                 _ => return Err(ErrUnsupProt) // Actually, because of the check above,
1213                                               // we should never get here.
1214             };
1215             unsafe {
1216                 let hFile = libc::get_osfhandle(fd) as HANDLE;
1217                 let mapping = libc::CreateFileMappingW(hFile,
1218                                                        ptr::mut_null(),
1219                                                        flProtect,
1220                                                        0,
1221                                                        0,
1222                                                        ptr::null());
1223                 if mapping == ptr::mut_null() {
1224                     return Err(ErrCreateFileMappingW(errno()));
1225                 }
1226                 if errno() as c_int == libc::ERROR_ALREADY_EXISTS {
1227                     return Err(ErrAlreadyExists);
1228                 }
1229                 let r = libc::MapViewOfFile(mapping,
1230                                             dwDesiredAccess,
1231                                             ((len as u64) >> 32) as DWORD,
1232                                             (offset & 0xffff_ffff) as DWORD,
1233                                             0);
1234                 match r as uint {
1235                     0 => Err(ErrMapViewOfFile(errno())),
1236                     _ => Ok(MemoryMap {
1237                        data: r as *mut u8,
1238                        len: len,
1239                        kind: MapFile(mapping as *u8)
1240                     })
1241                 }
1242             }
1243         }
1244     }
1245
1246     /// Granularity of MapAddr() and MapOffset() parameter values.
1247     /// This may be greater than the value returned by page_size().
1248     pub fn granularity() -> uint {
1249         unsafe {
1250             let mut info = libc::SYSTEM_INFO::new();
1251             libc::GetSystemInfo(&mut info);
1252
1253             return info.dwAllocationGranularity as uint;
1254         }
1255     }
1256 }
1257
1258 #[cfg(windows)]
1259 impl Drop for MemoryMap {
1260     /// Unmap the mapping. Fails the task if any of `VirtualFree`,
1261     /// `UnmapViewOfFile`, or `CloseHandle` fail.
1262     fn drop(&mut self) {
1263         use libc::types::os::arch::extra::{LPCVOID, HANDLE};
1264         use libc::consts::os::extra::FALSE;
1265         if self.len == 0 { return }
1266
1267         unsafe {
1268             match self.kind {
1269                 MapVirtual => {
1270                     if libc::VirtualFree(self.data as *mut c_void, 0,
1271                                          libc::MEM_RELEASE) == 0 {
1272                         println!("VirtualFree failed: {}", errno());
1273                     }
1274                 },
1275                 MapFile(mapping) => {
1276                     if libc::UnmapViewOfFile(self.data as LPCVOID) == FALSE {
1277                         println!("UnmapViewOfFile failed: {}", errno());
1278                     }
1279                     if libc::CloseHandle(mapping as HANDLE) == FALSE {
1280                         println!("CloseHandle failed: {}", errno());
1281                     }
1282                 }
1283             }
1284         }
1285     }
1286 }
1287
1288 /// Various useful system-specific constants.
1289 pub mod consts {
1290     #[cfg(unix)]
1291     pub use os::consts::unix::*;
1292
1293     #[cfg(windows)]
1294     pub use os::consts::windows::*;
1295
1296     #[cfg(target_os = "macos")]
1297     pub use os::consts::macos::*;
1298
1299     #[cfg(target_os = "freebsd")]
1300     pub use os::consts::freebsd::*;
1301
1302     #[cfg(target_os = "linux")]
1303     pub use os::consts::linux::*;
1304
1305     #[cfg(target_os = "android")]
1306     pub use os::consts::android::*;
1307
1308     #[cfg(target_os = "win32")]
1309     pub use os::consts::win32::*;
1310
1311     #[cfg(target_arch = "x86")]
1312     pub use os::consts::x86::*;
1313
1314     #[cfg(target_arch = "x86_64")]
1315     pub use os::consts::x86_64::*;
1316
1317     #[cfg(target_arch = "arm")]
1318     pub use os::consts::arm::*;
1319
1320     #[cfg(target_arch = "mips")]
1321     pub use os::consts::mips::*;
1322
1323     /// Constants for Unix systems.
1324     pub mod unix {
1325         /// A string describing the family that this operating system belongs
1326         /// to: in this case, `unix`.
1327         pub static FAMILY: &'static str = "unix";
1328     }
1329
1330     /// Constants for Windows systems.
1331     pub mod windows {
1332         /// A string describing the family that this operating system belongs
1333         /// to: in this case, `windows`.
1334         pub static FAMILY: &'static str = "windows";
1335     }
1336
1337     /// Constants for Mac OS systems.
1338     pub mod macos {
1339         /// A string describing the specific operating system in use: in this
1340         /// case, `macos`.
1341         pub static SYSNAME: &'static str = "macos";
1342
1343         /// Specifies the filename prefix used for shared libraries on this
1344         /// platform: in this case, `lib`.
1345         pub static DLL_PREFIX: &'static str = "lib";
1346
1347         /// Specifies the filename suffix used for shared libraries on this
1348         /// platform: in this case, `.dylib`.
1349         pub static DLL_SUFFIX: &'static str = ".dylib";
1350
1351         /// Specifies the file extension used for shared libraries on this
1352         /// platform that goes after the dot: in this case, `dylib`.
1353         pub static DLL_EXTENSION: &'static str = "dylib";
1354
1355         /// Specifies the filename suffix used for executable binaries on this
1356         /// platform: in this case, the empty string.
1357         pub static EXE_SUFFIX: &'static str = "";
1358
1359         /// Specifies the file extension, if any, used for executable binaries
1360         /// on this platform: in this case, the empty string.
1361         pub static EXE_EXTENSION: &'static str = "";
1362     }
1363
1364     /// Constants for FreeBSD systems.
1365     pub mod freebsd {
1366         /// A string describing the specific operating system in use: in this
1367         /// case, `freebsd`.
1368         pub static SYSNAME: &'static str = "freebsd";
1369
1370         /// Specifies the filename prefix used for shared libraries on this
1371         /// platform: in this case, `lib`.
1372         pub static DLL_PREFIX: &'static str = "lib";
1373
1374         /// Specifies the filename suffix used for shared libraries on this
1375         /// platform: in this case, `.so`.
1376         pub static DLL_SUFFIX: &'static str = ".so";
1377
1378         /// Specifies the file extension used for shared libraries on this
1379         /// platform that goes after the dot: in this case, `so`.
1380         pub static DLL_EXTENSION: &'static str = "so";
1381
1382         /// Specifies the filename suffix used for executable binaries on this
1383         /// platform: in this case, the empty string.
1384         pub static EXE_SUFFIX: &'static str = "";
1385
1386         /// Specifies the file extension, if any, used for executable binaries
1387         /// on this platform: in this case, the empty string.
1388         pub static EXE_EXTENSION: &'static str = "";
1389     }
1390
1391     /// Constants for GNU/Linux systems.
1392     pub mod linux {
1393         /// A string describing the specific operating system in use: in this
1394         /// case, `linux`.
1395         pub static SYSNAME: &'static str = "linux";
1396
1397         /// Specifies the filename prefix used for shared libraries on this
1398         /// platform: in this case, `lib`.
1399         pub static DLL_PREFIX: &'static str = "lib";
1400
1401         /// Specifies the filename suffix used for shared libraries on this
1402         /// platform: in this case, `.so`.
1403         pub static DLL_SUFFIX: &'static str = ".so";
1404
1405         /// Specifies the file extension used for shared libraries on this
1406         /// platform that goes after the dot: in this case, `so`.
1407         pub static DLL_EXTENSION: &'static str = "so";
1408
1409         /// Specifies the filename suffix used for executable binaries on this
1410         /// platform: in this case, the empty string.
1411         pub static EXE_SUFFIX: &'static str = "";
1412
1413         /// Specifies the file extension, if any, used for executable binaries
1414         /// on this platform: in this case, the empty string.
1415         pub static EXE_EXTENSION: &'static str = "";
1416     }
1417
1418     /// Constants for Android systems.
1419     pub mod android {
1420         /// A string describing the specific operating system in use: in this
1421         /// case, `android`.
1422         pub static SYSNAME: &'static str = "android";
1423
1424         /// Specifies the filename prefix used for shared libraries on this
1425         /// platform: in this case, `lib`.
1426         pub static DLL_PREFIX: &'static str = "lib";
1427
1428         /// Specifies the filename suffix used for shared libraries on this
1429         /// platform: in this case, `.so`.
1430         pub static DLL_SUFFIX: &'static str = ".so";
1431
1432         /// Specifies the file extension used for shared libraries on this
1433         /// platform that goes after the dot: in this case, `so`.
1434         pub static DLL_EXTENSION: &'static str = "so";
1435
1436         /// Specifies the filename suffix used for executable binaries on this
1437         /// platform: in this case, the empty string.
1438         pub static EXE_SUFFIX: &'static str = "";
1439
1440         /// Specifies the file extension, if any, used for executable binaries
1441         /// on this platform: in this case, the empty string.
1442         pub static EXE_EXTENSION: &'static str = "";
1443     }
1444
1445     /// Constants for 32-bit or 64-bit Windows systems.
1446     pub mod win32 {
1447         /// A string describing the specific operating system in use: in this
1448         /// case, `win32`.
1449         pub static SYSNAME: &'static str = "win32";
1450
1451         /// Specifies the filename prefix used for shared libraries on this
1452         /// platform: in this case, the empty string.
1453         pub static DLL_PREFIX: &'static str = "";
1454
1455         /// Specifies the filename suffix used for shared libraries on this
1456         /// platform: in this case, `.dll`.
1457         pub static DLL_SUFFIX: &'static str = ".dll";
1458
1459         /// Specifies the file extension used for shared libraries on this
1460         /// platform that goes after the dot: in this case, `dll`.
1461         pub static DLL_EXTENSION: &'static str = "dll";
1462
1463         /// Specifies the filename suffix used for executable binaries on this
1464         /// platform: in this case, `.exe`.
1465         pub static EXE_SUFFIX: &'static str = ".exe";
1466
1467         /// Specifies the file extension, if any, used for executable binaries
1468         /// on this platform: in this case, `exe`.
1469         pub static EXE_EXTENSION: &'static str = "exe";
1470     }
1471
1472     /// Constants for Intel Architecture-32 (x86) architectures.
1473     pub mod x86 {
1474         /// A string describing the architecture in use: in this case, `x86`.
1475         pub static ARCH: &'static str = "x86";
1476     }
1477     /// Constants for Intel 64/AMD64 (x86-64) architectures.
1478     pub mod x86_64 {
1479         /// A string describing the architecture in use: in this case,
1480         /// `x86_64`.
1481         pub static ARCH: &'static str = "x86_64";
1482     }
1483     /// Constants for Advanced RISC Machine (ARM) architectures.
1484     pub mod arm {
1485         /// A string describing the architecture in use: in this case, `ARM`.
1486         pub static ARCH: &'static str = "arm";
1487     }
1488     /// Constants for Microprocessor without Interlocked Pipeline Stages
1489     /// (MIPS) architectures.
1490     pub mod mips {
1491         /// A string describing the architecture in use: in this case, `MIPS`.
1492         pub static ARCH: &'static str = "mips";
1493     }
1494 }
1495
1496 #[cfg(test)]
1497 mod tests {
1498     use prelude::*;
1499     use c_str::ToCStr;
1500     use option;
1501     use os::{env, getcwd, getenv, make_absolute, args};
1502     use os::{setenv, unsetenv};
1503     use os;
1504     use rand::Rng;
1505     use rand;
1506
1507     #[test]
1508     pub fn last_os_error() {
1509         debug!("{}", os::last_os_error());
1510     }
1511
1512     #[test]
1513     pub fn test_args() {
1514         let a = args();
1515         assert!(a.len() >= 1);
1516     }
1517
1518     fn make_rand_name() -> ~str {
1519         let mut rng = rand::task_rng();
1520         let n = ~"TEST" + rng.gen_ascii_str(10u);
1521         assert!(getenv(n).is_none());
1522         n
1523     }
1524
1525     #[test]
1526     fn test_setenv() {
1527         let n = make_rand_name();
1528         setenv(n, "VALUE");
1529         assert_eq!(getenv(n), option::Some(~"VALUE"));
1530     }
1531
1532     #[test]
1533     fn test_unsetenv() {
1534         let n = make_rand_name();
1535         setenv(n, "VALUE");
1536         unsetenv(n);
1537         assert_eq!(getenv(n), option::None);
1538     }
1539
1540     #[test]
1541     #[ignore]
1542     fn test_setenv_overwrite() {
1543         let n = make_rand_name();
1544         setenv(n, "1");
1545         setenv(n, "2");
1546         assert_eq!(getenv(n), option::Some(~"2"));
1547         setenv(n, "");
1548         assert_eq!(getenv(n), option::Some(~""));
1549     }
1550
1551     // Windows GetEnvironmentVariable requires some extra work to make sure
1552     // the buffer the variable is copied into is the right size
1553     #[test]
1554     #[ignore]
1555     fn test_getenv_big() {
1556         let mut s = ~"";
1557         let mut i = 0;
1558         while i < 100 {
1559             s = s + "aaaaaaaaaa";
1560             i += 1;
1561         }
1562         let n = make_rand_name();
1563         setenv(n, s);
1564         debug!("{}", s.clone());
1565         assert_eq!(getenv(n), option::Some(s));
1566     }
1567
1568     #[test]
1569     fn test_self_exe_name() {
1570         let path = os::self_exe_name();
1571         assert!(path.is_some());
1572         let path = path.unwrap();
1573         debug!("{:?}", path.clone());
1574
1575         // Hard to test this function
1576         assert!(path.is_absolute());
1577     }
1578
1579     #[test]
1580     fn test_self_exe_path() {
1581         let path = os::self_exe_path();
1582         assert!(path.is_some());
1583         let path = path.unwrap();
1584         debug!("{:?}", path.clone());
1585
1586         // Hard to test this function
1587         assert!(path.is_absolute());
1588     }
1589
1590     #[test]
1591     #[ignore]
1592     fn test_env_getenv() {
1593         let e = env();
1594         assert!(e.len() > 0u);
1595         for p in e.iter() {
1596             let (n, v) = (*p).clone();
1597             debug!("{:?}", n.clone());
1598             let v2 = getenv(n);
1599             // MingW seems to set some funky environment variables like
1600             // "=C:=C:\MinGW\msys\1.0\bin" and "!::=::\" that are returned
1601             // from env() but not visible from getenv().
1602             assert!(v2.is_none() || v2 == option::Some(v));
1603         }
1604     }
1605
1606     #[test]
1607     fn test_env_set_get_huge() {
1608         let n = make_rand_name();
1609         let s = "x".repeat(10000);
1610         setenv(n, s);
1611         assert_eq!(getenv(n), Some(s));
1612         unsetenv(n);
1613         assert_eq!(getenv(n), None);
1614     }
1615
1616     #[test]
1617     fn test_env_setenv() {
1618         let n = make_rand_name();
1619
1620         let mut e = env();
1621         setenv(n, "VALUE");
1622         assert!(!e.contains(&(n.clone(), ~"VALUE")));
1623
1624         e = env();
1625         assert!(e.contains(&(n, ~"VALUE")));
1626     }
1627
1628     #[test]
1629     fn test() {
1630         assert!((!Path::new("test-path").is_absolute()));
1631
1632         let cwd = getcwd();
1633         debug!("Current working directory: {}", cwd.display());
1634
1635         debug!("{:?}", make_absolute(&Path::new("test-path")));
1636         debug!("{:?}", make_absolute(&Path::new("/usr/bin")));
1637     }
1638
1639     #[test]
1640     #[cfg(unix)]
1641     fn homedir() {
1642         let oldhome = getenv("HOME");
1643
1644         setenv("HOME", "/home/MountainView");
1645         assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1646
1647         setenv("HOME", "");
1648         assert!(os::homedir().is_none());
1649
1650         for s in oldhome.iter() { setenv("HOME", *s) }
1651     }
1652
1653     #[test]
1654     #[cfg(windows)]
1655     fn homedir() {
1656
1657         let oldhome = getenv("HOME");
1658         let olduserprofile = getenv("USERPROFILE");
1659
1660         setenv("HOME", "");
1661         setenv("USERPROFILE", "");
1662
1663         assert!(os::homedir().is_none());
1664
1665         setenv("HOME", "/home/MountainView");
1666         assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1667
1668         setenv("HOME", "");
1669
1670         setenv("USERPROFILE", "/home/MountainView");
1671         assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1672
1673         setenv("HOME", "/home/MountainView");
1674         setenv("USERPROFILE", "/home/PaloAlto");
1675         assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1676
1677         for s in oldhome.iter() { setenv("HOME", *s) }
1678         for s in olduserprofile.iter() { setenv("USERPROFILE", *s) }
1679     }
1680
1681     #[test]
1682     fn memory_map_rw() {
1683         use result::{Ok, Err};
1684
1685         let chunk = match os::MemoryMap::new(16, [
1686             os::MapReadable,
1687             os::MapWritable
1688         ]) {
1689             Ok(chunk) => chunk,
1690             Err(msg) => fail!("{}", msg)
1691         };
1692         assert!(chunk.len >= 16);
1693
1694         unsafe {
1695             *chunk.data = 0xBE;
1696             assert!(*chunk.data == 0xBE);
1697         }
1698     }
1699
1700     #[test]
1701     fn memory_map_file() {
1702         use result::{Ok, Err};
1703         use os::*;
1704         use libc::*;
1705         use io::fs;
1706
1707         #[cfg(unix)]
1708         fn lseek_(fd: c_int, size: uint) {
1709             unsafe {
1710                 assert!(lseek(fd, size as off_t, SEEK_SET) == size as off_t);
1711             }
1712         }
1713         #[cfg(windows)]
1714         fn lseek_(fd: c_int, size: uint) {
1715            unsafe {
1716                assert!(lseek(fd, size as c_long, SEEK_SET) == size as c_long);
1717            }
1718         }
1719
1720         let mut path = tmpdir();
1721         path.push("mmap_file.tmp");
1722         let size = MemoryMap::granularity() * 2;
1723
1724         let fd = unsafe {
1725             let fd = path.with_c_str(|path| {
1726                 open(path, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR)
1727             });
1728             lseek_(fd, size);
1729             "x".with_c_str(|x| assert!(write(fd, x as *c_void, 1) == 1));
1730             fd
1731         };
1732         let chunk = match MemoryMap::new(size / 2, [
1733             MapReadable,
1734             MapWritable,
1735             MapFd(fd),
1736             MapOffset(size / 2)
1737         ]) {
1738             Ok(chunk) => chunk,
1739             Err(msg) => fail!("{}", msg)
1740         };
1741         assert!(chunk.len > 0);
1742
1743         unsafe {
1744             *chunk.data = 0xbe;
1745             assert!(*chunk.data == 0xbe);
1746             close(fd);
1747         }
1748         drop(chunk);
1749
1750         fs::unlink(&path).unwrap();
1751     }
1752
1753     // More recursive_mkdir tests are in extra::tempfile
1754 }