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