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