]> git.lizzy.rs Git - rust.git/blob - src/libstd/os.rs
auto merge of #8350 : dim-an/rust/fix-struct-match, r=pcwalton
[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 use cast;
32 use clone::Clone;
33 use container::Container;
34 use io;
35 use iterator::{IteratorUtil, range};
36 use libc;
37 use libc::{c_char, c_void, c_int, size_t};
38 use libc::FILE;
39 use local_data;
40 use option::{Some, None};
41 use os;
42 use prelude::*;
43 use ptr;
44 use str;
45 use to_str;
46 use unstable::finally::Finally;
47 use vec;
48
49 pub use libc::fclose;
50 pub use os::consts::*;
51
52 /// Delegates to the libc close() function, returning the same return value.
53 pub fn close(fd: c_int) -> c_int {
54     unsafe {
55         libc::close(fd)
56     }
57 }
58
59 pub mod rustrt {
60     use libc::{c_char, c_int};
61     use libc;
62
63     extern {
64         pub fn rust_get_argc() -> c_int;
65         pub fn rust_get_argv() -> **c_char;
66         pub fn rust_path_is_dir(path: *libc::c_char) -> c_int;
67         pub fn rust_path_exists(path: *libc::c_char) -> c_int;
68         pub fn rust_set_exit_status(code: libc::intptr_t);
69     }
70 }
71
72 pub static TMPBUF_SZ : uint = 1000u;
73 static BUF_BYTES : uint = 2048u;
74
75 pub fn getcwd() -> Path {
76     let buf = [0 as libc::c_char, ..BUF_BYTES];
77     unsafe {
78         if(0 as *libc::c_char == libc::getcwd(
79             &buf[0],
80             BUF_BYTES as libc::size_t)) {
81             fail!();
82         }
83         Path(str::raw::from_c_str(&buf[0]))
84     }
85 }
86
87 // FIXME: move these to str perhaps? #2620
88
89 pub fn fill_charp_buf(f: &fn(*mut c_char, size_t) -> bool) -> Option<~str> {
90     let mut buf = [0 as c_char, .. TMPBUF_SZ];
91     do buf.as_mut_buf |b, sz| {
92         if f(b, sz as size_t) {
93             unsafe {
94                 Some(str::raw::from_buf(b as *u8))
95             }
96         } else {
97             None
98         }
99     }
100 }
101
102 #[cfg(windows)]
103 pub mod win32 {
104     use libc;
105     use vec;
106     use str;
107     use option::{None, Option};
108     use option;
109     use os::TMPBUF_SZ;
110     use libc::types::os::arch::extra::DWORD;
111
112     pub fn fill_utf16_buf_and_decode(f: &fn(*mut u16, DWORD) -> DWORD)
113         -> Option<~str> {
114         unsafe {
115             let mut n = TMPBUF_SZ as DWORD;
116             let mut res = None;
117             let mut done = false;
118             while !done {
119                 let mut k: DWORD = 0;
120                 let mut buf = vec::from_elem(n as uint, 0u16);
121                 do buf.as_mut_buf |b, _sz| {
122                     k = f(b, TMPBUF_SZ as DWORD);
123                     if k == (0 as DWORD) {
124                         done = true;
125                     } else if (k == n &&
126                                libc::GetLastError() ==
127                                libc::ERROR_INSUFFICIENT_BUFFER as DWORD) {
128                         n *= (2 as DWORD);
129                     } else {
130                         done = true;
131                     }
132                 }
133                 if k != 0 && done {
134                     let sub = buf.slice(0, k as uint);
135                     res = option::Some(str::from_utf16(sub));
136                 }
137             }
138             return res;
139         }
140     }
141
142     pub fn as_utf16_p<T>(s: &str, f: &fn(*u16) -> T) -> T {
143         let mut t = s.to_utf16();
144         // Null terminate before passing on.
145         t.push(0u16);
146         t.as_imm_buf(|buf, _len| f(buf))
147     }
148 }
149
150 /*
151 Accessing environment variables is not generally threadsafe.
152 Serialize access through a global lock.
153 */
154 fn with_env_lock<T>(f: &fn() -> T) -> T {
155     use unstable::finally::Finally;
156
157     unsafe {
158         return do (|| {
159             rust_take_env_lock();
160             f()
161         }).finally {
162             rust_drop_env_lock();
163         };
164     }
165
166     extern {
167         #[fast_ffi]
168         fn rust_take_env_lock();
169         #[fast_ffi]
170         fn rust_drop_env_lock();
171     }
172 }
173
174 /// Returns a vector of (variable, value) pairs for all the environment
175 /// variables of the current process.
176 pub fn env() -> ~[(~str,~str)] {
177     unsafe {
178         #[cfg(windows)]
179         unsafe fn get_env_pairs() -> ~[~str] {
180             use libc::funcs::extra::kernel32::{
181                 GetEnvironmentStringsA,
182                 FreeEnvironmentStringsA
183             };
184             let ch = GetEnvironmentStringsA();
185             if (ch as uint == 0) {
186                 fail!("os::env() failure getting env string from OS: %s", os::last_os_error());
187             }
188             let mut curr_ptr: uint = ch as uint;
189             let mut result = ~[];
190             while(*(curr_ptr as *libc::c_char) != 0 as libc::c_char) {
191                 let env_pair = str::raw::from_c_str(
192                     curr_ptr as *libc::c_char);
193                 result.push(env_pair);
194                 curr_ptr +=
195                     libc::strlen(curr_ptr as *libc::c_char) as uint
196                     + 1;
197             }
198             FreeEnvironmentStringsA(ch);
199             result
200         }
201         #[cfg(unix)]
202         unsafe fn get_env_pairs() -> ~[~str] {
203             extern {
204                 fn rust_env_pairs() -> **libc::c_char;
205             }
206             let environ = rust_env_pairs();
207             if (environ as uint == 0) {
208                 fail!("os::env() failure getting env string from OS: %s", os::last_os_error());
209             }
210             let mut result = ~[];
211             ptr::array_each(environ, |e| {
212                 let env_pair = str::raw::from_c_str(e);
213                 debug!("get_env_pairs: %s",
214                        env_pair);
215                 result.push(env_pair);
216             });
217             result
218         }
219
220         fn env_convert(input: ~[~str]) -> ~[(~str, ~str)] {
221             let mut pairs = ~[];
222             for p in input.iter() {
223                 let vs: ~[&str] = p.splitn_iter('=', 1).collect();
224                 debug!("splitting: len: %u",
225                     vs.len());
226                 assert_eq!(vs.len(), 2);
227                 pairs.push((vs[0].to_owned(), vs[1].to_owned()));
228             }
229             pairs
230         }
231         do with_env_lock {
232             let unparsed_environ = get_env_pairs();
233             env_convert(unparsed_environ)
234         }
235     }
236 }
237
238 #[cfg(unix)]
239 /// Fetches the environment variable `n` from the current process, returning
240 /// None if the variable isn't set.
241 pub fn getenv(n: &str) -> Option<~str> {
242     unsafe {
243         do with_env_lock {
244             let s = n.as_c_str(|s| libc::getenv(s as *libc::c_char));
245             if ptr::null::<u8>() == cast::transmute(s) {
246                 None
247             } else {
248                 Some(str::raw::from_buf(cast::transmute(s)))
249             }
250         }
251     }
252 }
253
254 #[cfg(windows)]
255 /// Fetches the environment variable `n` from the current process, returning
256 /// None if the variable isn't set.
257 pub fn getenv(n: &str) -> Option<~str> {
258     unsafe {
259         do with_env_lock {
260             use os::win32::{as_utf16_p, fill_utf16_buf_and_decode};
261             do as_utf16_p(n) |u| {
262                 do fill_utf16_buf_and_decode() |buf, sz| {
263                     libc::GetEnvironmentVariableW(u, buf, sz)
264                 }
265             }
266         }
267     }
268 }
269
270
271 #[cfg(unix)]
272 /// Sets the environment variable `n` to the value `v` for the currently running
273 /// process
274 pub fn setenv(n: &str, v: &str) {
275     unsafe {
276         do with_env_lock {
277             do n.to_str().as_c_str |nbuf| {
278                 do v.to_str().as_c_str |vbuf| {
279                     libc::funcs::posix01::unistd::setenv(nbuf, vbuf, 1);
280                 }
281             }
282         }
283     }
284 }
285
286
287 #[cfg(windows)]
288 /// Sets the environment variable `n` to the value `v` for the currently running
289 /// process
290 pub fn setenv(n: &str, v: &str) {
291     unsafe {
292         do with_env_lock {
293             use os::win32::as_utf16_p;
294             do as_utf16_p(n) |nbuf| {
295                 do as_utf16_p(v) |vbuf| {
296                     libc::SetEnvironmentVariableW(nbuf, vbuf);
297                 }
298             }
299         }
300     }
301 }
302
303 /// Remove a variable from the environment entirely
304 pub fn unsetenv(n: &str) {
305     #[cfg(unix)]
306     fn _unsetenv(n: &str) {
307         unsafe {
308             do with_env_lock {
309                 do n.to_str().as_c_str |nbuf| {
310                     libc::funcs::posix01::unistd::unsetenv(nbuf);
311                 }
312             }
313         }
314     }
315     #[cfg(windows)]
316     fn _unsetenv(n: &str) {
317         unsafe {
318             do with_env_lock {
319                 use os::win32::as_utf16_p;
320                 do as_utf16_p(n) |nbuf| {
321                     libc::SetEnvironmentVariableW(nbuf, ptr::null());
322                 }
323             }
324         }
325     }
326
327     _unsetenv(n);
328 }
329
330 pub fn fdopen(fd: c_int) -> *FILE {
331     do "r".as_c_str |modebuf| {
332         unsafe {
333             libc::fdopen(fd, modebuf)
334         }
335     }
336 }
337
338
339 // fsync related
340
341 #[cfg(windows)]
342 pub fn fsync_fd(fd: c_int, _level: io::fsync::Level) -> c_int {
343     unsafe {
344         use libc::funcs::extra::msvcrt::*;
345         return commit(fd);
346     }
347 }
348
349 #[cfg(target_os = "linux")]
350 #[cfg(target_os = "android")]
351 pub fn fsync_fd(fd: c_int, level: io::fsync::Level) -> c_int {
352     unsafe {
353         use libc::funcs::posix01::unistd::*;
354         match level {
355           io::fsync::FSync
356           | io::fsync::FullFSync => return fsync(fd),
357           io::fsync::FDataSync => return fdatasync(fd)
358         }
359     }
360 }
361
362 #[cfg(target_os = "macos")]
363 pub fn fsync_fd(fd: c_int, level: io::fsync::Level) -> c_int {
364     unsafe {
365         use libc::consts::os::extra::*;
366         use libc::funcs::posix88::fcntl::*;
367         use libc::funcs::posix01::unistd::*;
368         match level {
369           io::fsync::FSync => return fsync(fd),
370           _ => {
371             // According to man fnctl, the ok retval is only specified to be
372             // !=-1
373             if (fcntl(F_FULLFSYNC as c_int, fd) == -1 as c_int)
374                 { return -1 as c_int; }
375             else
376                 { return 0 as c_int; }
377           }
378         }
379     }
380 }
381
382 #[cfg(target_os = "freebsd")]
383 pub fn fsync_fd(fd: c_int, _l: io::fsync::Level) -> c_int {
384     unsafe {
385         use libc::funcs::posix01::unistd::*;
386         return fsync(fd);
387     }
388 }
389
390 pub struct Pipe {
391     input: c_int,
392     out: c_int
393 }
394
395 #[cfg(unix)]
396 pub fn pipe() -> Pipe {
397     unsafe {
398         let mut fds = Pipe {input: 0 as c_int,
399                             out: 0 as c_int };
400         assert_eq!(libc::pipe(&mut fds.input), (0 as c_int));
401         return Pipe {input: fds.input, out: fds.out};
402     }
403 }
404
405
406
407 #[cfg(windows)]
408 pub fn pipe() -> Pipe {
409     unsafe {
410         // Windows pipes work subtly differently than unix pipes, and their
411         // inheritance has to be handled in a different way that I do not
412         // fully understand. Here we explicitly make the pipe non-inheritable,
413         // which means to pass it to a subprocess they need to be duplicated
414         // first, as in core::run.
415         let mut fds = Pipe {input: 0 as c_int,
416                     out: 0 as c_int };
417         let res = libc::pipe(&mut fds.input, 1024 as ::libc::c_uint,
418                              (libc::O_BINARY | libc::O_NOINHERIT) as c_int);
419         assert_eq!(res, 0 as c_int);
420         assert!((fds.input != -1 as c_int && fds.input != 0 as c_int));
421         assert!((fds.out != -1 as c_int && fds.input != 0 as c_int));
422         return Pipe {input: fds.input, out: fds.out};
423     }
424 }
425
426 fn dup2(src: c_int, dst: c_int) -> c_int {
427     unsafe {
428         libc::dup2(src, dst)
429     }
430 }
431
432 /// Returns the proper dll filename for the given basename of a file.
433 pub fn dll_filename(base: &str) -> ~str {
434     fmt!("%s%s%s", DLL_PREFIX, base, DLL_SUFFIX)
435 }
436
437 /// Optionally returns the filesystem path to the current executable which is
438 /// running. If any failure occurs, None is returned.
439 pub fn self_exe_path() -> Option<Path> {
440
441     #[cfg(target_os = "freebsd")]
442     fn load_self() -> Option<~str> {
443         unsafe {
444             use libc::funcs::bsd44::*;
445             use libc::consts::os::extra::*;
446             do fill_charp_buf() |buf, sz| {
447                 let mib = ~[CTL_KERN as c_int,
448                            KERN_PROC as c_int,
449                            KERN_PROC_PATHNAME as c_int, -1 as c_int];
450                 let mut sz = sz;
451                 sysctl(vec::raw::to_ptr(mib), mib.len() as ::libc::c_uint,
452                        buf as *mut c_void, &mut sz, ptr::null(),
453                        0u as size_t) == (0 as c_int)
454             }
455         }
456     }
457
458     #[cfg(target_os = "linux")]
459     #[cfg(target_os = "android")]
460     fn load_self() -> Option<~str> {
461         unsafe {
462             use libc::funcs::posix01::unistd::readlink;
463
464             let mut path_str = str::with_capacity(TMPBUF_SZ);
465             let len = do path_str.as_c_str |buf| {
466                 let buf = buf as *mut c_char;
467                 do "/proc/self/exe".as_c_str |proc_self_buf| {
468                     readlink(proc_self_buf, buf, TMPBUF_SZ as size_t)
469                 }
470             };
471             if len == -1 {
472                 None
473             } else {
474                 str::raw::set_len(&mut path_str, len as uint);
475                 Some(path_str)
476             }
477         }
478     }
479
480     #[cfg(target_os = "macos")]
481     fn load_self() -> Option<~str> {
482         unsafe {
483             do fill_charp_buf() |buf, sz| {
484                 let mut sz = sz as u32;
485                 libc::funcs::extra::_NSGetExecutablePath(
486                     buf, &mut sz) == (0 as c_int)
487             }
488         }
489     }
490
491     #[cfg(windows)]
492     fn load_self() -> Option<~str> {
493         unsafe {
494             use os::win32::fill_utf16_buf_and_decode;
495             do fill_utf16_buf_and_decode() |buf, sz| {
496                 libc::GetModuleFileNameW(0u as libc::DWORD, buf, sz)
497             }
498         }
499     }
500
501     load_self().map_move(|path| Path(path).dir_path())
502 }
503
504
505 /**
506  * Returns the path to the user's home directory, if known.
507  *
508  * On Unix, returns the value of the 'HOME' environment variable if it is set
509  * and not equal to the empty string.
510  *
511  * On Windows, returns the value of the 'HOME' environment variable if it is
512  * set and not equal to the empty string. Otherwise, returns the value of the
513  * 'USERPROFILE' environment variable if it is set and not equal to the empty
514  * string.
515  *
516  * Otherwise, homedir returns option::none.
517  */
518 pub fn homedir() -> Option<Path> {
519     return match getenv("HOME") {
520         Some(ref p) => if !p.is_empty() {
521           Some(Path(*p))
522         } else {
523           secondary()
524         },
525         None => secondary()
526     };
527
528     #[cfg(unix)]
529     fn secondary() -> Option<Path> {
530         None
531     }
532
533     #[cfg(windows)]
534     fn secondary() -> Option<Path> {
535         do getenv("USERPROFILE").chain |p| {
536             if !p.is_empty() {
537                 Some(Path(p))
538             } else {
539                 None
540             }
541         }
542     }
543 }
544
545 /**
546  * Returns the path to a temporary directory.
547  *
548  * On Unix, returns the value of the 'TMPDIR' environment variable if it is
549  * set and non-empty and '/tmp' otherwise.
550  *
551  * On Windows, returns the value of, in order, the 'TMP', 'TEMP',
552  * 'USERPROFILE' environment variable  if any are set and not the empty
553  * string. Otherwise, tmpdir returns the path to the Windows directory.
554  */
555 pub fn tmpdir() -> Path {
556     return lookup();
557
558     fn getenv_nonempty(v: &str) -> Option<Path> {
559         match getenv(v) {
560             Some(x) =>
561                 if x.is_empty() {
562                     None
563                 } else {
564                     Some(Path(x))
565                 },
566             _ => None
567         }
568     }
569
570     #[cfg(unix)]
571     fn lookup() -> Path {
572         getenv_nonempty("TMPDIR").unwrap_or_default(Path("/tmp"))
573     }
574
575     #[cfg(windows)]
576     fn lookup() -> Path {
577         getenv_nonempty("TMP").or(
578             getenv_nonempty("TEMP").or(
579                 getenv_nonempty("USERPROFILE").or(
580                    getenv_nonempty("WINDIR")))).unwrap_or_default(Path("C:\\Windows"))
581     }
582 }
583
584 /// Recursively walk a directory structure
585 pub fn walk_dir(p: &Path, f: &fn(&Path) -> bool) -> bool {
586     let r = list_dir(p);
587     r.iter().advance(|q| {
588         let path = &p.push(*q);
589         f(path) && (!path_is_dir(path) || walk_dir(path, |p| f(p)))
590     })
591 }
592
593 /// Indicates whether a path represents a directory
594 pub fn path_is_dir(p: &Path) -> bool {
595     unsafe {
596         do p.to_str().as_c_str |buf| {
597             rustrt::rust_path_is_dir(buf) != 0 as c_int
598         }
599     }
600 }
601
602 /// Indicates whether a path exists
603 pub fn path_exists(p: &Path) -> bool {
604     unsafe {
605         do p.to_str().as_c_str |buf| {
606             rustrt::rust_path_exists(buf) != 0 as c_int
607         }
608     }
609 }
610
611 /**
612  * Convert a relative path to an absolute path
613  *
614  * If the given path is relative, return it prepended with the current working
615  * directory. If the given path is already an absolute path, return it
616  * as is.
617  */
618 // NB: this is here rather than in path because it is a form of environment
619 // querying; what it does depends on the process working directory, not just
620 // the input paths.
621 pub fn make_absolute(p: &Path) -> Path {
622     if p.is_absolute {
623         (*p).clone()
624     } else {
625         getcwd().push_many(p.components)
626     }
627 }
628
629
630 /// Creates a directory at the specified path
631 pub fn make_dir(p: &Path, mode: c_int) -> bool {
632     return mkdir(p, mode);
633
634     #[cfg(windows)]
635     fn mkdir(p: &Path, _mode: c_int) -> bool {
636         unsafe {
637             use os::win32::as_utf16_p;
638             // FIXME: turn mode into something useful? #2623
639             do as_utf16_p(p.to_str()) |buf| {
640                 libc::CreateDirectoryW(buf, cast::transmute(0))
641                     != (0 as libc::BOOL)
642             }
643         }
644     }
645
646     #[cfg(unix)]
647     fn mkdir(p: &Path, mode: c_int) -> bool {
648         do p.to_str().as_c_str |buf| {
649             unsafe {
650                 libc::mkdir(buf, mode as libc::mode_t) == (0 as c_int)
651             }
652         }
653     }
654 }
655
656 /// Creates a directory with a given mode.
657 /// Returns true iff creation
658 /// succeeded. Also creates all intermediate subdirectories
659 /// if they don't already exist, giving all of them the same mode.
660
661 // tjc: if directory exists but with different permissions,
662 // should we return false?
663 pub fn mkdir_recursive(p: &Path, mode: c_int) -> bool {
664     if path_is_dir(p) {
665         return true;
666     }
667     else if p.components.is_empty() {
668         return false;
669     }
670     else if p.components.len() == 1 {
671         // No parent directories to create
672         path_is_dir(p) || make_dir(p, mode)
673     }
674     else {
675         mkdir_recursive(&p.pop(), mode) && make_dir(p, mode)
676     }
677 }
678
679 /// Lists the contents of a directory
680 pub fn list_dir(p: &Path) -> ~[~str] {
681     if p.components.is_empty() && !p.is_absolute() {
682         // Not sure what the right behavior is here, but this
683         // prevents a bounds check failure later
684         return ~[];
685     }
686     unsafe {
687         #[cfg(target_os = "linux")]
688         #[cfg(target_os = "android")]
689         #[cfg(target_os = "freebsd")]
690         #[cfg(target_os = "macos")]
691         unsafe fn get_list(p: &Path) -> ~[~str] {
692             use libc::{dirent_t};
693             use libc::{opendir, readdir, closedir};
694             extern {
695                 fn rust_list_dir_val(ptr: *dirent_t) -> *libc::c_char;
696             }
697             let input = p.to_str();
698             let mut strings = ~[];
699             let input_ptr = ::cast::transmute(&input[0]);
700             debug!("os::list_dir -- BEFORE OPENDIR");
701             let dir_ptr = opendir(input_ptr);
702             if (dir_ptr as uint != 0) {
703         debug!("os::list_dir -- opendir() SUCCESS");
704                 let mut entry_ptr = readdir(dir_ptr);
705                 while (entry_ptr as uint != 0) {
706                     strings.push(str::raw::from_c_str(rust_list_dir_val(
707                         entry_ptr)));
708                     entry_ptr = readdir(dir_ptr);
709                 }
710                 closedir(dir_ptr);
711             }
712             else {
713         debug!("os::list_dir -- opendir() FAILURE");
714             }
715             debug!(
716                 "os::list_dir -- AFTER -- #: %?",
717                      strings.len());
718             strings
719         }
720         #[cfg(windows)]
721         unsafe fn get_list(p: &Path) -> ~[~str] {
722             use libc::consts::os::extra::INVALID_HANDLE_VALUE;
723             use libc::{wcslen, free};
724             use libc::funcs::extra::kernel32::{
725                 FindFirstFileW,
726                 FindNextFileW,
727                 FindClose,
728             };
729             use os::win32::{
730                 as_utf16_p
731             };
732             use rt::global_heap::malloc_raw;
733
734             #[nolink]
735             extern {
736                 fn rust_list_dir_wfd_size() -> libc::size_t;
737                 fn rust_list_dir_wfd_fp_buf(wfd: *libc::c_void) -> *u16;
738             }
739             fn star(p: &Path) -> Path { p.push("*") }
740             do as_utf16_p(star(p).to_str()) |path_ptr| {
741                 let mut strings = ~[];
742                 let wfd_ptr = malloc_raw(rust_list_dir_wfd_size() as uint);
743                 let find_handle =
744                     FindFirstFileW(
745                         path_ptr,
746                         ::cast::transmute(wfd_ptr));
747                 if find_handle as libc::c_int != INVALID_HANDLE_VALUE {
748                     let mut more_files = 1 as libc::c_int;
749                     while more_files != 0 {
750                         let fp_buf = rust_list_dir_wfd_fp_buf(wfd_ptr);
751                         if fp_buf as uint == 0 {
752                             fail!("os::list_dir() failure: got null ptr from wfd");
753                         }
754                         else {
755                             let fp_vec = vec::from_buf(
756                                 fp_buf, wcslen(fp_buf) as uint);
757                             let fp_str = str::from_utf16(fp_vec);
758                             strings.push(fp_str);
759                         }
760                         more_files = FindNextFileW(
761                             find_handle,
762                             ::cast::transmute(wfd_ptr));
763                     }
764                     FindClose(find_handle);
765                     free(wfd_ptr)
766                 }
767                 strings
768             }
769         }
770         do get_list(p).consume_iter().filter |filename| {
771             "." != *filename && ".." != *filename
772         }.collect()
773     }
774 }
775
776 /**
777  * Lists the contents of a directory
778  *
779  * This version prepends each entry with the directory.
780  */
781 pub fn list_dir_path(p: &Path) -> ~[Path] {
782     list_dir(p).map(|f| p.push(*f))
783 }
784
785 /// Removes a directory at the specified path, after removing
786 /// all its contents. Use carefully!
787 pub fn remove_dir_recursive(p: &Path) -> bool {
788     let mut error_happened = false;
789     do walk_dir(p) |inner| {
790         if !error_happened {
791             if path_is_dir(inner) {
792                 if !remove_dir_recursive(inner) {
793                     error_happened = true;
794                 }
795             }
796             else {
797                 if !remove_file(inner) {
798                     error_happened = true;
799                 }
800             }
801         }
802         true
803     };
804     // Directory should now be empty
805     !error_happened && remove_dir(p)
806 }
807
808 /// Removes a directory at the specified path
809 pub fn remove_dir(p: &Path) -> bool {
810    return rmdir(p);
811
812     #[cfg(windows)]
813     fn rmdir(p: &Path) -> bool {
814         unsafe {
815             use os::win32::as_utf16_p;
816             return do as_utf16_p(p.to_str()) |buf| {
817                 libc::RemoveDirectoryW(buf) != (0 as libc::BOOL)
818             };
819         }
820     }
821
822     #[cfg(unix)]
823     fn rmdir(p: &Path) -> bool {
824         do p.to_str().as_c_str |buf| {
825             unsafe {
826                 libc::rmdir(buf) == (0 as c_int)
827             }
828         }
829     }
830 }
831
832 /// Changes the current working directory to the specified path, returning
833 /// whether the change was completed successfully or not.
834 pub fn change_dir(p: &Path) -> bool {
835     return chdir(p);
836
837     #[cfg(windows)]
838     fn chdir(p: &Path) -> bool {
839         unsafe {
840             use os::win32::as_utf16_p;
841             return do as_utf16_p(p.to_str()) |buf| {
842                 libc::SetCurrentDirectoryW(buf) != (0 as libc::BOOL)
843             };
844         }
845     }
846
847     #[cfg(unix)]
848     fn chdir(p: &Path) -> bool {
849         do p.to_str().as_c_str |buf| {
850             unsafe {
851                 libc::chdir(buf) == (0 as c_int)
852             }
853         }
854     }
855 }
856
857 /// Copies a file from one location to another
858 pub fn copy_file(from: &Path, to: &Path) -> bool {
859     return do_copy_file(from, to);
860
861     #[cfg(windows)]
862     fn do_copy_file(from: &Path, to: &Path) -> bool {
863         unsafe {
864             use os::win32::as_utf16_p;
865             return do as_utf16_p(from.to_str()) |fromp| {
866                 do as_utf16_p(to.to_str()) |top| {
867                     libc::CopyFileW(fromp, top, (0 as libc::BOOL)) !=
868                         (0 as libc::BOOL)
869                 }
870             }
871         }
872     }
873
874     #[cfg(unix)]
875     fn do_copy_file(from: &Path, to: &Path) -> bool {
876         unsafe {
877             let istream = do from.to_str().as_c_str |fromp| {
878                 do "rb".as_c_str |modebuf| {
879                     libc::fopen(fromp, modebuf)
880                 }
881             };
882             if istream as uint == 0u {
883                 return false;
884             }
885             // Preserve permissions
886             let from_mode = from.get_mode().expect("copy_file: couldn't get permissions \
887                                                     for source file");
888
889             let ostream = do to.to_str().as_c_str |top| {
890                 do "w+b".as_c_str |modebuf| {
891                     libc::fopen(top, modebuf)
892                 }
893             };
894             if ostream as uint == 0u {
895                 fclose(istream);
896                 return false;
897             }
898             let bufsize = 8192u;
899             let mut buf = vec::with_capacity::<u8>(bufsize);
900             let mut done = false;
901             let mut ok = true;
902             while !done {
903                 do buf.as_mut_buf |b, _sz| {
904                   let nread = libc::fread(b as *mut c_void, 1u as size_t,
905                                           bufsize as size_t,
906                                           istream);
907                   if nread > 0 as size_t {
908                       if libc::fwrite(b as *c_void, 1u as size_t, nread,
909                                       ostream) != nread {
910                           ok = false;
911                           done = true;
912                       }
913                   } else {
914                       done = true;
915                   }
916               }
917             }
918             fclose(istream);
919             fclose(ostream);
920
921             // Give the new file the old file's permissions
922             if do to.to_str().as_c_str |to_buf| {
923                 libc::chmod(to_buf, from_mode as libc::mode_t)
924             } != 0 {
925                 return false; // should be a condition...
926             }
927             return ok;
928         }
929     }
930 }
931
932 /// Deletes an existing file
933 pub fn remove_file(p: &Path) -> bool {
934     return unlink(p);
935
936     #[cfg(windows)]
937     fn unlink(p: &Path) -> bool {
938         unsafe {
939             use os::win32::as_utf16_p;
940             return do as_utf16_p(p.to_str()) |buf| {
941                 libc::DeleteFileW(buf) != (0 as libc::BOOL)
942             };
943         }
944     }
945
946     #[cfg(unix)]
947     fn unlink(p: &Path) -> bool {
948         unsafe {
949             do p.to_str().as_c_str |buf| {
950                 libc::unlink(buf) == (0 as c_int)
951             }
952         }
953     }
954 }
955
956 #[cfg(unix)]
957 /// Returns the platform-specific value of errno
958 pub fn errno() -> int {
959     #[cfg(target_os = "macos")]
960     #[cfg(target_os = "freebsd")]
961     fn errno_location() -> *c_int {
962         #[nolink]
963         extern {
964             fn __error() -> *c_int;
965         }
966         unsafe {
967             __error()
968         }
969     }
970
971     #[cfg(target_os = "linux")]
972     #[cfg(target_os = "android")]
973     fn errno_location() -> *c_int {
974         #[nolink]
975         extern {
976             fn __errno_location() -> *c_int;
977         }
978         unsafe {
979             __errno_location()
980         }
981     }
982
983     unsafe {
984         (*errno_location()) as int
985     }
986 }
987
988 #[cfg(windows)]
989 /// Returns the platform-specific value of errno
990 pub fn errno() -> uint {
991     use libc::types::os::arch::extra::DWORD;
992
993     #[link_name = "kernel32"]
994     #[abi = "stdcall"]
995     extern "stdcall" {
996         fn GetLastError() -> DWORD;
997     }
998
999     unsafe {
1000         GetLastError() as uint
1001     }
1002 }
1003
1004 /// Get a string representing the platform-dependent last error
1005 pub fn last_os_error() -> ~str {
1006     #[cfg(unix)]
1007     fn strerror() -> ~str {
1008         #[cfg(target_os = "macos")]
1009         #[cfg(target_os = "android")]
1010         #[cfg(target_os = "freebsd")]
1011         fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: size_t)
1012                       -> c_int {
1013             #[nolink]
1014             extern {
1015                 fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: size_t)
1016                               -> c_int;
1017             }
1018             unsafe {
1019                 strerror_r(errnum, buf, buflen)
1020             }
1021         }
1022
1023         // GNU libc provides a non-compliant version of strerror_r by default
1024         // and requires macros to instead use the POSIX compliant variant.
1025         // So we just use __xpg_strerror_r which is always POSIX compliant
1026         #[cfg(target_os = "linux")]
1027         fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: size_t) -> c_int {
1028             #[nolink]
1029             extern {
1030                 fn __xpg_strerror_r(errnum: c_int,
1031                                     buf: *mut c_char,
1032                                     buflen: size_t)
1033                                     -> c_int;
1034             }
1035             unsafe {
1036                 __xpg_strerror_r(errnum, buf, buflen)
1037             }
1038         }
1039
1040         let mut buf = [0 as c_char, ..TMPBUF_SZ];
1041         unsafe {
1042             let err = strerror_r(errno() as c_int, &mut buf[0],
1043                                  TMPBUF_SZ as size_t);
1044             if err < 0 {
1045                 fail!("strerror_r failure");
1046             }
1047
1048             str::raw::from_c_str(&buf[0])
1049         }
1050     }
1051
1052     #[cfg(windows)]
1053     fn strerror() -> ~str {
1054         use libc::types::os::arch::extra::DWORD;
1055         use libc::types::os::arch::extra::LPSTR;
1056         use libc::types::os::arch::extra::LPVOID;
1057
1058         #[link_name = "kernel32"]
1059         #[abi = "stdcall"]
1060         extern "stdcall" {
1061             fn FormatMessageA(flags: DWORD,
1062                               lpSrc: LPVOID,
1063                               msgId: DWORD,
1064                               langId: DWORD,
1065                               buf: LPSTR,
1066                               nsize: DWORD,
1067                               args: *c_void)
1068                               -> DWORD;
1069         }
1070
1071         static FORMAT_MESSAGE_FROM_SYSTEM: DWORD = 0x00001000;
1072         static FORMAT_MESSAGE_IGNORE_INSERTS: DWORD = 0x00000200;
1073
1074         let mut buf = [0 as c_char, ..TMPBUF_SZ];
1075
1076         // This value is calculated from the macro
1077         // MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT)
1078         let langId = 0x0800 as DWORD;
1079         let err = errno() as DWORD;
1080         unsafe {
1081             let res = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM |
1082                                      FORMAT_MESSAGE_IGNORE_INSERTS,
1083                                      ptr::mut_null(), err, langId,
1084                                      &mut buf[0], TMPBUF_SZ as DWORD,
1085                                      ptr::null());
1086             if res == 0 {
1087                 fail!("[%?] FormatMessage failure", errno());
1088             }
1089
1090             str::raw::from_c_str(&buf[0])
1091         }
1092     }
1093
1094     strerror()
1095 }
1096
1097 /**
1098  * Sets the process exit code
1099  *
1100  * Sets the exit code returned by the process if all supervised tasks
1101  * terminate successfully (without failing). If the current root task fails
1102  * and is supervised by the scheduler then any user-specified exit status is
1103  * ignored and the process exits with the default failure status
1104  */
1105 pub fn set_exit_status(code: int) {
1106     use rt;
1107     use rt::OldTaskContext;
1108
1109     if rt::context() == OldTaskContext {
1110         unsafe {
1111             rustrt::rust_set_exit_status(code as libc::intptr_t);
1112         }
1113     } else {
1114         rt::util::set_exit_status(code);
1115     }
1116 }
1117
1118 unsafe fn load_argc_and_argv(argc: c_int, argv: **c_char) -> ~[~str] {
1119     let mut args = ~[];
1120     for i in range(0u, argc as uint) {
1121         args.push(str::raw::from_c_str(*argv.offset(i as int)));
1122     }
1123     args
1124 }
1125
1126 /**
1127  * Returns the command line arguments
1128  *
1129  * Returns a list of the command line arguments.
1130  */
1131 #[cfg(target_os = "macos")]
1132 pub fn real_args() -> ~[~str] {
1133     unsafe {
1134         let (argc, argv) = (*_NSGetArgc() as c_int,
1135                             *_NSGetArgv() as **c_char);
1136         load_argc_and_argv(argc, argv)
1137     }
1138 }
1139
1140 #[cfg(target_os = "linux")]
1141 #[cfg(target_os = "android")]
1142 #[cfg(target_os = "freebsd")]
1143 pub fn real_args() -> ~[~str] {
1144     use rt;
1145     use rt::TaskContext;
1146
1147     if rt::context() == TaskContext {
1148         match rt::args::clone() {
1149             Some(args) => args,
1150             None => fail!("process arguments not initialized")
1151         }
1152     } else {
1153         unsafe {
1154             let argc = rustrt::rust_get_argc();
1155             let argv = rustrt::rust_get_argv();
1156             load_argc_and_argv(argc, argv)
1157         }
1158     }
1159 }
1160
1161 #[cfg(windows)]
1162 pub fn real_args() -> ~[~str] {
1163     let mut nArgs: c_int = 0;
1164     let lpArgCount: *mut c_int = &mut nArgs;
1165     let lpCmdLine = unsafe { GetCommandLineW() };
1166     let szArgList = unsafe { CommandLineToArgvW(lpCmdLine, lpArgCount) };
1167
1168     let mut args = ~[];
1169     for i in range(0u, nArgs as uint) {
1170         unsafe {
1171             // Determine the length of this argument.
1172             let ptr = *szArgList.offset(i as int);
1173             let mut len = 0;
1174             while *ptr.offset(len as int) != 0 { len += 1; }
1175
1176             // Push it onto the list.
1177             args.push(vec::raw::buf_as_slice(ptr, len,
1178                                              str::from_utf16));
1179         }
1180     }
1181
1182     unsafe {
1183         LocalFree(cast::transmute(szArgList));
1184     }
1185
1186     return args;
1187 }
1188
1189 type LPCWSTR = *u16;
1190
1191 #[cfg(windows)]
1192 #[link_name="kernel32"]
1193 #[abi="stdcall"]
1194 extern "stdcall" {
1195     fn GetCommandLineW() -> LPCWSTR;
1196     fn LocalFree(ptr: *c_void);
1197 }
1198
1199 #[cfg(windows)]
1200 #[link_name="shell32"]
1201 #[abi="stdcall"]
1202 extern "stdcall" {
1203     fn CommandLineToArgvW(lpCmdLine: LPCWSTR, pNumArgs: *mut c_int) -> **u16;
1204 }
1205
1206 struct OverriddenArgs {
1207     val: ~[~str]
1208 }
1209
1210 static overridden_arg_key: local_data::Key<@OverriddenArgs> = &local_data::Key;
1211
1212 /// Returns the arguments which this program was started with (normally passed
1213 /// via the command line).
1214 ///
1215 /// The return value of the function can be changed by invoking the
1216 /// `os::set_args` function.
1217 pub fn args() -> ~[~str] {
1218     match local_data::get(overridden_arg_key, |k| k.map(|&k| *k)) {
1219         None => real_args(),
1220         Some(args) => args.val.clone()
1221     }
1222 }
1223
1224 /// For the current task, overrides the task-local cache of the arguments this
1225 /// program had when it started. These new arguments are only available to the
1226 /// current task via the `os::args` method.
1227 pub fn set_args(new_args: ~[~str]) {
1228     let overridden_args = @OverriddenArgs {
1229         val: new_args.clone()
1230     };
1231     local_data::set(overridden_arg_key, overridden_args);
1232 }
1233
1234 // FIXME #6100 we should really use an internal implementation of this - using
1235 // the POSIX glob functions isn't portable to windows, probably has slight
1236 // inconsistencies even where it is implemented, and makes extending
1237 // functionality a lot more difficult
1238 // FIXME #6101 also provide a non-allocating version - each_glob or so?
1239 /// Returns a vector of Path objects that match the given glob pattern
1240 #[cfg(target_os = "linux")]
1241 #[cfg(target_os = "android")]
1242 #[cfg(target_os = "freebsd")]
1243 #[cfg(target_os = "macos")]
1244 pub fn glob(pattern: &str) -> ~[Path] {
1245     #[cfg(target_os = "linux")]
1246     #[cfg(target_os = "android")]
1247     fn default_glob_t () -> libc::glob_t {
1248         libc::glob_t {
1249             gl_pathc: 0,
1250             gl_pathv: ptr::null(),
1251             gl_offs: 0,
1252             __unused1: ptr::null(),
1253             __unused2: ptr::null(),
1254             __unused3: ptr::null(),
1255             __unused4: ptr::null(),
1256             __unused5: ptr::null(),
1257         }
1258     }
1259
1260     #[cfg(target_os = "freebsd")]
1261     fn default_glob_t () -> libc::glob_t {
1262         libc::glob_t {
1263             gl_pathc: 0,
1264             __unused1: 0,
1265             gl_offs: 0,
1266             __unused2: 0,
1267             gl_pathv: ptr::null(),
1268             __unused3: ptr::null(),
1269             __unused4: ptr::null(),
1270             __unused5: ptr::null(),
1271             __unused6: ptr::null(),
1272             __unused7: ptr::null(),
1273             __unused8: ptr::null(),
1274         }
1275     }
1276
1277     #[cfg(target_os = "macos")]
1278     fn default_glob_t () -> libc::glob_t {
1279         libc::glob_t {
1280             gl_pathc: 0,
1281             __unused1: 0,
1282             gl_offs: 0,
1283             __unused2: 0,
1284             gl_pathv: ptr::null(),
1285             __unused3: ptr::null(),
1286             __unused4: ptr::null(),
1287             __unused5: ptr::null(),
1288             __unused6: ptr::null(),
1289             __unused7: ptr::null(),
1290             __unused8: ptr::null(),
1291         }
1292     }
1293
1294     let mut g = default_glob_t();
1295     do pattern.as_c_str |c_pattern| {
1296         unsafe { libc::glob(c_pattern, 0, ptr::null(), &mut g) }
1297     };
1298     do(|| {
1299         let paths = unsafe {
1300             vec::raw::from_buf_raw(g.gl_pathv, g.gl_pathc as uint)
1301         };
1302         do paths.map |&c_str| {
1303             Path(unsafe { str::raw::from_c_str(c_str) })
1304         }
1305     }).finally {
1306         unsafe { libc::globfree(&mut g) };
1307     }
1308 }
1309
1310 /// Returns a vector of Path objects that match the given glob pattern
1311 #[cfg(target_os = "win32")]
1312 pub fn glob(_pattern: &str) -> ~[Path] {
1313     fail!("glob() is unimplemented on Windows")
1314 }
1315
1316 #[cfg(target_os = "macos")]
1317 extern {
1318     // These functions are in crt_externs.h.
1319     pub fn _NSGetArgc() -> *c_int;
1320     pub fn _NSGetArgv() -> ***c_char;
1321 }
1322
1323 // Round up `from` to be divisible by `to`
1324 fn round_up(from: uint, to: uint) -> uint {
1325     let r = if from % to == 0 {
1326         from
1327     } else {
1328         from + to - (from % to)
1329     };
1330     if r == 0 {
1331         to
1332     } else {
1333         r
1334     }
1335 }
1336
1337 #[cfg(unix)]
1338 pub fn page_size() -> uint {
1339     unsafe {
1340         libc::sysconf(libc::_SC_PAGESIZE) as uint
1341     }
1342 }
1343
1344 #[cfg(windows)]
1345 pub fn page_size() -> uint {
1346   unsafe {
1347     let mut info = libc::SYSTEM_INFO::new();
1348     libc::GetSystemInfo(&mut info);
1349
1350     return info.dwPageSize as uint;
1351   }
1352 }
1353
1354 pub struct MemoryMap {
1355     data: *mut u8,
1356     len: size_t,
1357     kind: MemoryMapKind
1358 }
1359
1360 pub enum MemoryMapKind {
1361     MapFile(*c_void),
1362     MapVirtual
1363 }
1364
1365 pub enum MapOption {
1366     MapReadable,
1367     MapWritable,
1368     MapExecutable,
1369     MapAddr(*c_void),
1370     MapFd(c_int),
1371     MapOffset(uint)
1372 }
1373
1374 pub enum MapError {
1375     // Linux-specific errors
1376     ErrFdNotAvail,
1377     ErrInvalidFd,
1378     ErrUnaligned,
1379     ErrNoMapSupport,
1380     ErrNoMem,
1381     ErrUnknown(libc::c_int),
1382
1383     // Windows-specific errors
1384     ErrUnsupProt,
1385     ErrUnsupOffset,
1386     ErrNeedRW,
1387     ErrAlreadyExists,
1388     ErrVirtualAlloc(uint),
1389     ErrCreateFileMappingW(uint),
1390     ErrMapViewOfFile(uint)
1391 }
1392
1393 impl to_str::ToStr for MapError {
1394     fn to_str(&self) -> ~str {
1395         match *self {
1396             ErrFdNotAvail => ~"fd not available for reading or writing",
1397             ErrInvalidFd => ~"Invalid fd",
1398             ErrUnaligned => ~"Unaligned address, invalid flags, \
1399                               negative length or unaligned offset",
1400             ErrNoMapSupport=> ~"File doesn't support mapping",
1401             ErrNoMem => ~"Invalid address, or not enough available memory",
1402             ErrUnknown(code) => fmt!("Unknown error=%?", code),
1403             ErrUnsupProt => ~"Protection mode unsupported",
1404             ErrUnsupOffset => ~"Offset in virtual memory mode is unsupported",
1405             ErrNeedRW => ~"File mapping should be at least readable/writable",
1406             ErrAlreadyExists => ~"File mapping for specified file already exists",
1407             ErrVirtualAlloc(code) => fmt!("VirtualAlloc failure=%?", code),
1408             ErrCreateFileMappingW(code) => fmt!("CreateFileMappingW failure=%?", code),
1409             ErrMapViewOfFile(code) => fmt!("MapViewOfFile failure=%?", code)
1410         }
1411     }
1412 }
1413
1414 #[cfg(unix)]
1415 impl MemoryMap {
1416     pub fn new(min_len: uint, options: ~[MapOption]) -> Result<~MemoryMap, MapError> {
1417         use libc::off_t;
1418
1419         let mut addr: *c_void = ptr::null();
1420         let mut prot: c_int = 0;
1421         let mut flags: c_int = libc::MAP_PRIVATE;
1422         let mut fd: c_int = -1;
1423         let mut offset: off_t = 0;
1424         let len = round_up(min_len, page_size()) as size_t;
1425
1426         for &o in options.iter() {
1427             match o {
1428                 MapReadable => { prot |= libc::PROT_READ; },
1429                 MapWritable => { prot |= libc::PROT_WRITE; },
1430                 MapExecutable => { prot |= libc::PROT_EXEC; },
1431                 MapAddr(addr_) => {
1432                     flags |= libc::MAP_FIXED;
1433                     addr = addr_;
1434                 },
1435                 MapFd(fd_) => {
1436                     flags |= libc::MAP_FILE;
1437                     fd = fd_;
1438                 },
1439                 MapOffset(offset_) => { offset = offset_ as off_t; }
1440             }
1441         }
1442         if fd == -1 { flags |= libc::MAP_ANON; }
1443
1444         let r = unsafe {
1445             libc::mmap(addr, len, prot, flags, fd, offset)
1446         };
1447         if r == libc::MAP_FAILED {
1448             Err(match errno() as c_int {
1449                 libc::EACCES => ErrFdNotAvail,
1450                 libc::EBADF => ErrInvalidFd,
1451                 libc::EINVAL => ErrUnaligned,
1452                 libc::ENODEV => ErrNoMapSupport,
1453                 libc::ENOMEM => ErrNoMem,
1454                 code => ErrUnknown(code)
1455             })
1456         } else {
1457             Ok(~MemoryMap {
1458                data: r as *mut u8,
1459                len: len,
1460                kind: if fd == -1 {
1461                    MapVirtual
1462                } else {
1463                    MapFile(ptr::null())
1464                }
1465             })
1466         }
1467     }
1468 }
1469
1470 #[cfg(unix)]
1471 impl Drop for MemoryMap {
1472     fn drop(&self) {
1473         unsafe {
1474             match libc::munmap(self.data as *c_void, self.len) {
1475                 0 => (),
1476                 -1 => error!(match errno() as c_int {
1477                     libc::EINVAL => ~"invalid addr or len",
1478                     e => fmt!("unknown errno=%?", e)
1479                 }),
1480                 r => error!(fmt!("Unexpected result %?", r))
1481             }
1482         }
1483     }
1484 }
1485
1486 #[cfg(windows)]
1487 impl MemoryMap {
1488     pub fn new(min_len: uint, options: ~[MapOption]) -> Result<~MemoryMap, MapError> {
1489         use libc::types::os::arch::extra::{LPVOID, DWORD, SIZE_T, HANDLE};
1490
1491         let mut lpAddress: LPVOID = ptr::mut_null();
1492         let mut readable = false;
1493         let mut writable = false;
1494         let mut executable = false;
1495         let mut fd: c_int = -1;
1496         let mut offset: uint = 0;
1497         let len = round_up(min_len, page_size()) as SIZE_T;
1498
1499         for &o in options.iter() {
1500             match o {
1501                 MapReadable => { readable = true; },
1502                 MapWritable => { writable = true; },
1503                 MapExecutable => { executable = true; }
1504                 MapAddr(addr_) => { lpAddress = addr_ as LPVOID; },
1505                 MapFd(fd_) => { fd = fd_; },
1506                 MapOffset(offset_) => { offset = offset_; }
1507             }
1508         }
1509
1510         let flProtect = match (executable, readable, writable) {
1511             (false, false, false) if fd == -1 => libc::PAGE_NOACCESS,
1512             (false, true, false) => libc::PAGE_READONLY,
1513             (false, true, true) => libc::PAGE_READWRITE,
1514             (true, false, false) if fd == -1 => libc::PAGE_EXECUTE,
1515             (true, true, false) => libc::PAGE_EXECUTE_READ,
1516             (true, true, true) => libc::PAGE_EXECUTE_READWRITE,
1517             _ => return Err(ErrUnsupProt)
1518         };
1519
1520         if fd == -1 {
1521             if offset != 0 {
1522                 return Err(ErrUnsupOffset);
1523             }
1524             let r = unsafe {
1525                 libc::VirtualAlloc(lpAddress,
1526                                    len,
1527                                    libc::MEM_COMMIT | libc::MEM_RESERVE,
1528                                    flProtect)
1529             };
1530             match r as uint {
1531                 0 => Err(ErrVirtualAlloc(errno())),
1532                 _ => Ok(~MemoryMap {
1533                    data: r as *mut u8,
1534                    len: len,
1535                    kind: MapVirtual
1536                 })
1537             }
1538         } else {
1539             let dwDesiredAccess = match (readable, writable) {
1540                 (true, true) => libc::FILE_MAP_ALL_ACCESS,
1541                 (true, false) => libc::FILE_MAP_READ,
1542                 (false, true) => libc::FILE_MAP_WRITE,
1543                 _ => {
1544                     return Err(ErrNeedRW);
1545                 }
1546             };
1547             unsafe {
1548                 let hFile = libc::get_osfhandle(fd) as HANDLE;
1549                 let mapping = libc::CreateFileMappingW(hFile,
1550                                                        ptr::mut_null(),
1551                                                        flProtect,
1552                                                        (len >> 32) as DWORD,
1553                                                        (len & 0xffff_ffff) as DWORD,
1554                                                        ptr::null());
1555                 if mapping == ptr::mut_null() {
1556                     return Err(ErrCreateFileMappingW(errno()));
1557                 }
1558                 if errno() as c_int == libc::ERROR_ALREADY_EXISTS {
1559                     return Err(ErrAlreadyExists);
1560                 }
1561                 let r = libc::MapViewOfFile(mapping,
1562                                             dwDesiredAccess,
1563                                             (offset >> 32) as DWORD,
1564                                             (offset & 0xffff_ffff) as DWORD,
1565                                             0);
1566                 match r as uint {
1567                     0 => Err(ErrMapViewOfFile(errno())),
1568                     _ => Ok(~MemoryMap {
1569                        data: r as *mut u8,
1570                        len: len,
1571                        kind: MapFile(mapping as *c_void)
1572                     })
1573                 }
1574             }
1575         }
1576     }
1577 }
1578
1579 #[cfg(windows)]
1580 impl Drop for MemoryMap {
1581     fn drop(&self) {
1582         use libc::types::os::arch::extra::{LPCVOID, HANDLE};
1583
1584         unsafe {
1585             match self.kind {
1586                 MapVirtual => match libc::VirtualFree(self.data as *mut c_void,
1587                                                       self.len,
1588                                                       libc::MEM_RELEASE) {
1589                     0 => error!(fmt!("VirtualFree failed: %?", errno())),
1590                     _ => ()
1591                 },
1592                 MapFile(mapping) => {
1593                     if libc::UnmapViewOfFile(self.data as LPCVOID) != 0 {
1594                         error!(fmt!("UnmapViewOfFile failed: %?", errno()));
1595                     }
1596                     if libc::CloseHandle(mapping as HANDLE) != 0 {
1597                         error!(fmt!("CloseHandle failed: %?", errno()));
1598                     }
1599                 }
1600             }
1601         }
1602     }
1603 }
1604
1605 pub mod consts {
1606
1607     #[cfg(unix)]
1608     pub use os::consts::unix::*;
1609
1610     #[cfg(windows)]
1611     pub use os::consts::windows::*;
1612
1613     #[cfg(target_os = "macos")]
1614     pub use os::consts::macos::*;
1615
1616     #[cfg(target_os = "freebsd")]
1617     pub use os::consts::freebsd::*;
1618
1619     #[cfg(target_os = "linux")]
1620     pub use os::consts::linux::*;
1621
1622     #[cfg(target_os = "android")]
1623     pub use os::consts::android::*;
1624
1625     #[cfg(target_os = "win32")]
1626     pub use os::consts::win32::*;
1627
1628     #[cfg(target_arch = "x86")]
1629     pub use os::consts::x86::*;
1630
1631     #[cfg(target_arch = "x86_64")]
1632     pub use os::consts::x86_64::*;
1633
1634     #[cfg(target_arch = "arm")]
1635     pub use os::consts::arm::*;
1636
1637     #[cfg(target_arch = "mips")]
1638     use os::consts::mips::*;
1639
1640     pub mod unix {
1641         pub static FAMILY: &'static str = "unix";
1642     }
1643
1644     pub mod windows {
1645         pub static FAMILY: &'static str = "windows";
1646     }
1647
1648     pub mod macos {
1649         pub static SYSNAME: &'static str = "macos";
1650         pub static DLL_PREFIX: &'static str = "lib";
1651         pub static DLL_SUFFIX: &'static str = ".dylib";
1652         pub static EXE_SUFFIX: &'static str = "";
1653     }
1654
1655     pub mod freebsd {
1656         pub static SYSNAME: &'static str = "freebsd";
1657         pub static DLL_PREFIX: &'static str = "lib";
1658         pub static DLL_SUFFIX: &'static str = ".so";
1659         pub static EXE_SUFFIX: &'static str = "";
1660     }
1661
1662     pub mod linux {
1663         pub static SYSNAME: &'static str = "linux";
1664         pub static DLL_PREFIX: &'static str = "lib";
1665         pub static DLL_SUFFIX: &'static str = ".so";
1666         pub static EXE_SUFFIX: &'static str = "";
1667     }
1668
1669     pub mod android {
1670         pub static SYSNAME: &'static str = "android";
1671         pub static DLL_PREFIX: &'static str = "lib";
1672         pub static DLL_SUFFIX: &'static str = ".so";
1673         pub static EXE_SUFFIX: &'static str = "";
1674     }
1675
1676     pub mod win32 {
1677         pub static SYSNAME: &'static str = "win32";
1678         pub static DLL_PREFIX: &'static str = "";
1679         pub static DLL_SUFFIX: &'static str = ".dll";
1680         pub static EXE_SUFFIX: &'static str = ".exe";
1681     }
1682
1683
1684     pub mod x86 {
1685         pub static ARCH: &'static str = "x86";
1686     }
1687     pub mod x86_64 {
1688         pub static ARCH: &'static str = "x86_64";
1689     }
1690     pub mod arm {
1691         pub static ARCH: &'static str = "arm";
1692     }
1693     pub mod mips {
1694         pub static ARCH: &'static str = "mips";
1695     }
1696 }
1697
1698 #[cfg(test)]
1699 mod tests {
1700     use libc::{c_int, c_void, size_t};
1701     use libc;
1702     use option::Some;
1703     use option;
1704     use os::{env, getcwd, getenv, make_absolute, real_args};
1705     use os::{remove_file, setenv, unsetenv};
1706     use os;
1707     use path::Path;
1708     use rand::RngUtil;
1709     use rand;
1710     use run;
1711     use str::StrSlice;
1712     use vec::CopyableVector;
1713     use libc::consts::os::posix88::{S_IRUSR, S_IWUSR, S_IXUSR};
1714
1715
1716     #[test]
1717     pub fn last_os_error() {
1718         debug!(os::last_os_error());
1719     }
1720
1721     #[test]
1722     pub fn test_args() {
1723         let a = real_args();
1724         assert!(a.len() >= 1);
1725     }
1726
1727     fn make_rand_name() -> ~str {
1728         let mut rng = rand::rng();
1729         let n = ~"TEST" + rng.gen_str(10u);
1730         assert!(getenv(n).is_none());
1731         n
1732     }
1733
1734     #[test]
1735     fn test_setenv() {
1736         let n = make_rand_name();
1737         setenv(n, "VALUE");
1738         assert_eq!(getenv(n), option::Some(~"VALUE"));
1739     }
1740
1741     #[test]
1742     fn test_unsetenv() {
1743         let n = make_rand_name();
1744         setenv(n, "VALUE");
1745         unsetenv(n);
1746         assert_eq!(getenv(n), option::None);
1747     }
1748
1749     #[test]
1750     #[ignore(cfg(windows))]
1751     #[ignore]
1752     fn test_setenv_overwrite() {
1753         let n = make_rand_name();
1754         setenv(n, "1");
1755         setenv(n, "2");
1756         assert_eq!(getenv(n), option::Some(~"2"));
1757         setenv(n, "");
1758         assert_eq!(getenv(n), option::Some(~""));
1759     }
1760
1761     // Windows GetEnvironmentVariable requires some extra work to make sure
1762     // the buffer the variable is copied into is the right size
1763     #[test]
1764     #[ignore(cfg(windows))]
1765     #[ignore]
1766     fn test_getenv_big() {
1767         let mut s = ~"";
1768         let mut i = 0;
1769         while i < 100 {
1770             s = s + "aaaaaaaaaa";
1771             i += 1;
1772         }
1773         let n = make_rand_name();
1774         setenv(n, s);
1775         debug!(s.clone());
1776         assert_eq!(getenv(n), option::Some(s));
1777     }
1778
1779     #[test]
1780     fn test_self_exe_path() {
1781         let path = os::self_exe_path();
1782         assert!(path.is_some());
1783         let path = path.unwrap();
1784         debug!(path.clone());
1785
1786         // Hard to test this function
1787         assert!(path.is_absolute);
1788     }
1789
1790     #[test]
1791     #[ignore]
1792     fn test_env_getenv() {
1793         let e = env();
1794         assert!(e.len() > 0u);
1795         for p in e.iter() {
1796             let (n, v) = (*p).clone();
1797             debug!(n.clone());
1798             let v2 = getenv(n);
1799             // MingW seems to set some funky environment variables like
1800             // "=C:=C:\MinGW\msys\1.0\bin" and "!::=::\" that are returned
1801             // from env() but not visible from getenv().
1802             assert!(v2.is_none() || v2 == option::Some(v));
1803         }
1804     }
1805
1806     #[test]
1807     fn test_env_setenv() {
1808         let n = make_rand_name();
1809
1810         let mut e = env();
1811         setenv(n, "VALUE");
1812         assert!(!e.contains(&(n.clone(), ~"VALUE")));
1813
1814         e = env();
1815         assert!(e.contains(&(n, ~"VALUE")));
1816     }
1817
1818     #[test]
1819     fn test() {
1820         assert!((!Path("test-path").is_absolute));
1821
1822         debug!("Current working directory: %s", getcwd().to_str());
1823
1824         debug!(make_absolute(&Path("test-path")));
1825         debug!(make_absolute(&Path("/usr/bin")));
1826     }
1827
1828     #[test]
1829     #[cfg(unix)]
1830     fn homedir() {
1831         let oldhome = getenv("HOME");
1832
1833         setenv("HOME", "/home/MountainView");
1834         assert_eq!(os::homedir(), Some(Path("/home/MountainView")));
1835
1836         setenv("HOME", "");
1837         assert!(os::homedir().is_none());
1838
1839         for s in oldhome.iter() { setenv("HOME", *s) }
1840     }
1841
1842     #[test]
1843     #[cfg(windows)]
1844     fn homedir() {
1845
1846         let oldhome = getenv("HOME");
1847         let olduserprofile = getenv("USERPROFILE");
1848
1849         setenv("HOME", "");
1850         setenv("USERPROFILE", "");
1851
1852         assert!(os::homedir().is_none());
1853
1854         setenv("HOME", "/home/MountainView");
1855         assert_eq!(os::homedir(), Some(Path("/home/MountainView")));
1856
1857         setenv("HOME", "");
1858
1859         setenv("USERPROFILE", "/home/MountainView");
1860         assert_eq!(os::homedir(), Some(Path("/home/MountainView")));
1861
1862         setenv("HOME", "/home/MountainView");
1863         setenv("USERPROFILE", "/home/PaloAlto");
1864         assert_eq!(os::homedir(), Some(Path("/home/MountainView")));
1865
1866         oldhome.iter().advance(|s| { setenv("HOME", *s); true });
1867         olduserprofile.iter().advance(|s| { setenv("USERPROFILE", *s); true });
1868     }
1869
1870     #[test]
1871     fn tmpdir() {
1872         assert!(!os::tmpdir().to_str().is_empty());
1873     }
1874
1875     // Issue #712
1876     #[test]
1877     fn test_list_dir_no_invalid_memory_access() {
1878         os::list_dir(&Path("."));
1879     }
1880
1881     #[test]
1882     fn list_dir() {
1883         let dirs = os::list_dir(&Path("."));
1884         // Just assuming that we've got some contents in the current directory
1885         assert!(dirs.len() > 0u);
1886
1887         for dir in dirs.iter() {
1888             debug!((*dir).clone());
1889         }
1890     }
1891
1892     #[test]
1893     fn list_dir_empty_path() {
1894         let dirs = os::list_dir(&Path(""));
1895         assert!(dirs.is_empty());
1896     }
1897
1898     #[test]
1899     #[cfg(not(windows))]
1900     fn list_dir_root() {
1901         let dirs = os::list_dir(&Path("/"));
1902         assert!(dirs.len() > 1);
1903     }
1904     #[test]
1905     #[cfg(windows)]
1906     fn list_dir_root() {
1907         let dirs = os::list_dir(&Path("C:\\"));
1908         assert!(dirs.len() > 1);
1909     }
1910
1911
1912     #[test]
1913     fn path_is_dir() {
1914         assert!((os::path_is_dir(&Path("."))));
1915         assert!((!os::path_is_dir(&Path("test/stdtest/fs.rs"))));
1916     }
1917
1918     #[test]
1919     fn path_exists() {
1920         assert!((os::path_exists(&Path("."))));
1921         assert!((!os::path_exists(&Path(
1922                      "test/nonexistent-bogus-path"))));
1923     }
1924
1925     #[test]
1926     fn copy_file_does_not_exist() {
1927       assert!(!os::copy_file(&Path("test/nonexistent-bogus-path"),
1928                             &Path("test/other-bogus-path")));
1929       assert!(!os::path_exists(&Path("test/other-bogus-path")));
1930     }
1931
1932     #[test]
1933     fn copy_file_ok() {
1934         unsafe {
1935           let tempdir = getcwd(); // would like to use $TMPDIR,
1936                                   // doesn't seem to work on Linux
1937           assert!((tempdir.to_str().len() > 0u));
1938           let input = tempdir.push("in.txt");
1939           let out = tempdir.push("out.txt");
1940
1941           /* Write the temp input file */
1942             let ostream = do input.to_str().as_c_str |fromp| {
1943                 do "w+b".as_c_str |modebuf| {
1944                     libc::fopen(fromp, modebuf)
1945                 }
1946           };
1947           assert!((ostream as uint != 0u));
1948           let s = ~"hello";
1949           let mut buf = s.as_bytes_with_null().to_owned();
1950           let len = buf.len();
1951           do buf.as_mut_buf |b, _len| {
1952               assert_eq!(libc::fwrite(b as *c_void, 1u as size_t,
1953                                       (s.len() + 1u) as size_t, ostream),
1954                          len as size_t)
1955           }
1956           assert_eq!(libc::fclose(ostream), (0u as c_int));
1957           let in_mode = input.get_mode();
1958           let rs = os::copy_file(&input, &out);
1959           if (!os::path_exists(&input)) {
1960             fail!("%s doesn't exist", input.to_str());
1961           }
1962           assert!((rs));
1963           let rslt = run::process_status("diff", [input.to_str(), out.to_str()]);
1964           assert_eq!(rslt, 0);
1965           assert_eq!(out.get_mode(), in_mode);
1966           assert!((remove_file(&input)));
1967           assert!((remove_file(&out)));
1968         }
1969     }
1970
1971     #[test]
1972     fn recursive_mkdir_slash() {
1973         let path = Path("/");
1974         assert!(os::mkdir_recursive(&path,  (S_IRUSR | S_IWUSR | S_IXUSR) as i32));
1975     }
1976
1977     #[test]
1978     fn recursive_mkdir_empty() {
1979         let path = Path("");
1980         assert!(!os::mkdir_recursive(&path, (S_IRUSR | S_IWUSR | S_IXUSR) as i32));
1981     }
1982
1983     #[test]
1984     fn memory_map_rw() {
1985         use result::{Ok, Err};
1986
1987         let chunk = match os::MemoryMap::new(16, ~[
1988             os::MapReadable,
1989             os::MapWritable
1990         ]) {
1991             Ok(chunk) => chunk,
1992             Err(msg) => fail!(msg.to_str())
1993         };
1994         assert!(chunk.len >= 16);
1995
1996         unsafe {
1997             *chunk.data = 0xBE;
1998             assert!(*chunk.data == 0xBE);
1999         }
2000     }
2001
2002     #[test]
2003     fn memory_map_file() {
2004         use result::{Ok, Err};
2005         use os::*;
2006         use libc::*;
2007
2008         #[cfg(unix)]
2009         fn lseek_(fd: c_int, size: uint) {
2010             unsafe {
2011                 assert!(lseek(fd, size as off_t, SEEK_SET) == size as off_t);
2012             }
2013         }
2014         #[cfg(windows)]
2015         fn lseek_(fd: c_int, size: uint) {
2016            unsafe {
2017                assert!(lseek(fd, size as c_long, SEEK_SET) == size as c_long);
2018            }
2019         }
2020
2021         let path = tmpdir().push("mmap_file.tmp");
2022         let size = page_size() * 2;
2023         remove_file(&path);
2024
2025         let fd = unsafe {
2026             let fd = do path.to_str().as_c_str |path| {
2027                 open(path, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR)
2028             };
2029             lseek_(fd, size);
2030             do "x".as_c_str |x| {
2031                 assert!(write(fd, x as *c_void, 1) == 1);
2032             }
2033             fd
2034         };
2035         let chunk = match MemoryMap::new(size / 2, ~[
2036             MapReadable,
2037             MapWritable,
2038             MapFd(fd),
2039             MapOffset(size / 2)
2040         ]) {
2041             Ok(chunk) => chunk,
2042             Err(msg) => fail!(msg.to_str())
2043         };
2044         assert!(chunk.len > 0);
2045
2046         unsafe {
2047             *chunk.data = 0xbe;
2048             assert!(*chunk.data == 0xbe);
2049             close(fd);
2050         }
2051     }
2052
2053     // More recursive_mkdir tests are in extra::tempfile
2054 }