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