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