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.
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.
12 * Higher-level interfaces to libc::* functions and operating system services.
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
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.
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.
29 #[allow(missing_doc)];
33 use container::Container;
37 use libc::{c_char, c_void, c_int, size_t};
39 use option::{Some, None};
45 use unstable::finally::Finally;
49 pub use os::consts::*;
51 /// Delegates to the libc close() function, returning the same return value.
52 pub fn close(fd: c_int) -> c_int {
53 #[fixed_stack_segment]; #[inline(never)];
60 use libc::{c_char, c_int};
64 pub fn rust_path_is_dir(path: *libc::c_char) -> c_int;
65 pub fn rust_path_exists(path: *libc::c_char) -> c_int;
69 pub static TMPBUF_SZ : uint = 1000u;
70 static BUF_BYTES : uint = 2048u;
72 pub fn getcwd() -> Path {
73 #[fixed_stack_segment]; #[inline(never)];
74 let mut buf = [0 as libc::c_char, ..BUF_BYTES];
75 do buf.as_mut_buf |buf, len| {
77 if libc::getcwd(buf, len as size_t).is_null() {
81 Path(str::raw::from_c_str(buf as *c_char))
86 // FIXME: move these to str perhaps? #2620
88 pub fn fill_charp_buf(f: &fn(*mut c_char, size_t) -> bool) -> Option<~str> {
89 let mut buf = [0 as c_char, .. TMPBUF_SZ];
90 do buf.as_mut_buf |b, sz| {
91 if f(b, sz as size_t) {
93 Some(str::raw::from_c_str(b as *c_char))
106 use option::{None, Option};
109 use libc::types::os::arch::extra::DWORD;
111 pub fn fill_utf16_buf_and_decode(f: &fn(*mut u16, DWORD) -> DWORD)
113 #[fixed_stack_segment]; #[inline(never)];
116 let mut n = TMPBUF_SZ as DWORD;
118 let mut done = false;
120 let mut k: DWORD = 0;
121 let mut buf = vec::from_elem(n as uint, 0u16);
122 do buf.as_mut_buf |b, _sz| {
123 k = f(b, TMPBUF_SZ as DWORD);
124 if k == (0 as DWORD) {
127 libc::GetLastError() ==
128 libc::ERROR_INSUFFICIENT_BUFFER as DWORD) {
135 let sub = buf.slice(0, k as uint);
136 res = option::Some(str::from_utf16(sub));
143 pub fn as_utf16_p<T>(s: &str, f: &fn(*u16) -> T) -> T {
144 let mut t = s.to_utf16();
145 // Null terminate before passing on.
147 t.as_imm_buf(|buf, _len| f(buf))
152 Accessing environment variables is not generally threadsafe.
153 Serialize access through a global lock.
155 fn with_env_lock<T>(f: &fn() -> T) -> T {
156 use unstable::finally::Finally;
160 rust_take_env_lock();
163 rust_drop_env_lock();
167 externfn!(fn rust_take_env_lock());
168 externfn!(fn rust_drop_env_lock());
171 /// Returns a vector of (variable, value) pairs for all the environment
172 /// variables of the current process.
173 pub fn env() -> ~[(~str,~str)] {
176 unsafe fn get_env_pairs() -> ~[~str] {
177 #[fixed_stack_segment]; #[inline(never)];
179 use libc::funcs::extra::kernel32::{
180 GetEnvironmentStringsA,
181 FreeEnvironmentStringsA
183 let ch = GetEnvironmentStringsA();
184 if (ch as uint == 0) {
185 fail!("os::env() failure getting env string from OS: %s", os::last_os_error());
187 let result = str::raw::from_c_multistring(ch as *libc::c_char, None);
188 FreeEnvironmentStringsA(ch);
192 unsafe fn get_env_pairs() -> ~[~str] {
193 #[fixed_stack_segment]; #[inline(never)];
196 fn rust_env_pairs() -> **libc::c_char;
198 let environ = rust_env_pairs();
199 if (environ as uint == 0) {
200 fail!("os::env() failure getting env string from OS: %s", os::last_os_error());
202 let mut result = ~[];
203 ptr::array_each(environ, |e| {
204 let env_pair = str::raw::from_c_str(e);
205 debug!("get_env_pairs: %s",
207 result.push(env_pair);
212 fn env_convert(input: ~[~str]) -> ~[(~str, ~str)] {
214 for p in input.iter() {
215 let vs: ~[&str] = p.splitn_iter('=', 1).collect();
216 debug!("splitting: len: %u",
218 assert_eq!(vs.len(), 2);
219 pairs.push((vs[0].to_owned(), vs[1].to_owned()));
224 let unparsed_environ = get_env_pairs();
225 env_convert(unparsed_environ)
231 /// Fetches the environment variable `n` from the current process, returning
232 /// None if the variable isn't set.
233 pub fn getenv(n: &str) -> Option<~str> {
234 #[fixed_stack_segment]; #[inline(never)];
237 let s = do n.with_c_str |buf| {
243 Some(str::raw::from_c_str(s))
250 /// Fetches the environment variable `n` from the current process, returning
251 /// None if the variable isn't set.
252 pub fn getenv(n: &str) -> Option<~str> {
253 #[fixed_stack_segment]; #[inline(never)];
257 use os::win32::{as_utf16_p, fill_utf16_buf_and_decode};
258 do as_utf16_p(n) |u| {
259 do fill_utf16_buf_and_decode() |buf, sz| {
260 libc::GetEnvironmentVariableW(u, buf, sz)
269 /// Sets the environment variable `n` to the value `v` for the currently running
271 pub fn setenv(n: &str, v: &str) {
272 #[fixed_stack_segment]; #[inline(never)];
275 do n.with_c_str |nbuf| {
276 do v.with_c_str |vbuf| {
277 libc::funcs::posix01::unistd::setenv(nbuf, vbuf, 1);
286 /// Sets the environment variable `n` to the value `v` for the currently running
288 pub fn setenv(n: &str, v: &str) {
289 #[fixed_stack_segment]; #[inline(never)];
293 use os::win32::as_utf16_p;
294 do as_utf16_p(n) |nbuf| {
295 do as_utf16_p(v) |vbuf| {
296 libc::SetEnvironmentVariableW(nbuf, vbuf);
303 /// Remove a variable from the environment entirely
304 pub fn unsetenv(n: &str) {
306 fn _unsetenv(n: &str) {
307 #[fixed_stack_segment]; #[inline(never)];
310 do n.with_c_str |nbuf| {
311 libc::funcs::posix01::unistd::unsetenv(nbuf);
317 fn _unsetenv(n: &str) {
318 #[fixed_stack_segment]; #[inline(never)];
321 use os::win32::as_utf16_p;
322 do as_utf16_p(n) |nbuf| {
323 libc::SetEnvironmentVariableW(nbuf, ptr::null());
332 pub fn fdopen(fd: c_int) -> *FILE {
333 #[fixed_stack_segment]; #[inline(never)];
334 do "r".with_c_str |modebuf| {
336 libc::fdopen(fd, modebuf)
345 pub fn fsync_fd(fd: c_int, _level: io::fsync::Level) -> c_int {
346 #[fixed_stack_segment]; #[inline(never)];
348 use libc::funcs::extra::msvcrt::*;
353 #[cfg(target_os = "linux")]
354 #[cfg(target_os = "android")]
355 pub fn fsync_fd(fd: c_int, level: io::fsync::Level) -> c_int {
356 #[fixed_stack_segment]; #[inline(never)];
358 use libc::funcs::posix01::unistd::*;
361 | io::fsync::FullFSync => return fsync(fd),
362 io::fsync::FDataSync => return fdatasync(fd)
367 #[cfg(target_os = "macos")]
368 pub fn fsync_fd(fd: c_int, level: io::fsync::Level) -> c_int {
369 #[fixed_stack_segment]; #[inline(never)];
372 use libc::consts::os::extra::*;
373 use libc::funcs::posix88::fcntl::*;
374 use libc::funcs::posix01::unistd::*;
376 io::fsync::FSync => return fsync(fd),
378 // According to man fnctl, the ok retval is only specified to be
380 if (fcntl(F_FULLFSYNC as c_int, fd) == -1 as c_int)
381 { return -1 as c_int; }
383 { return 0 as c_int; }
389 #[cfg(target_os = "freebsd")]
390 pub fn fsync_fd(fd: c_int, _l: io::fsync::Level) -> c_int {
391 #[fixed_stack_segment]; #[inline(never)];
394 use libc::funcs::posix01::unistd::*;
405 pub fn pipe() -> Pipe {
406 #[fixed_stack_segment]; #[inline(never)];
408 let mut fds = Pipe {input: 0 as c_int,
410 assert_eq!(libc::pipe(&mut fds.input), (0 as c_int));
411 return Pipe {input: fds.input, out: fds.out};
418 pub fn pipe() -> Pipe {
419 #[fixed_stack_segment]; #[inline(never)];
421 // Windows pipes work subtly differently than unix pipes, and their
422 // inheritance has to be handled in a different way that I do not
423 // fully understand. Here we explicitly make the pipe non-inheritable,
424 // which means to pass it to a subprocess they need to be duplicated
425 // first, as in std::run.
426 let mut fds = Pipe {input: 0 as c_int,
428 let res = libc::pipe(&mut fds.input, 1024 as ::libc::c_uint,
429 (libc::O_BINARY | libc::O_NOINHERIT) as c_int);
430 assert_eq!(res, 0 as c_int);
431 assert!((fds.input != -1 as c_int && fds.input != 0 as c_int));
432 assert!((fds.out != -1 as c_int && fds.input != 0 as c_int));
433 return Pipe {input: fds.input, out: fds.out};
437 fn dup2(src: c_int, dst: c_int) -> c_int {
438 #[fixed_stack_segment]; #[inline(never)];
444 /// Returns the proper dll filename for the given basename of a file.
445 pub fn dll_filename(base: &str) -> ~str {
446 fmt!("%s%s%s", DLL_PREFIX, base, DLL_SUFFIX)
449 /// Optionally returns the filesystem path to the current executable which is
450 /// running. If any failure occurs, None is returned.
451 pub fn self_exe_path() -> Option<Path> {
453 #[cfg(target_os = "freebsd")]
454 fn load_self() -> Option<~str> {
455 #[fixed_stack_segment]; #[inline(never)];
457 use libc::funcs::bsd44::*;
458 use libc::consts::os::extra::*;
459 do fill_charp_buf() |buf, sz| {
460 let mib = ~[CTL_KERN as c_int,
462 KERN_PROC_PATHNAME as c_int, -1 as c_int];
464 sysctl(vec::raw::to_ptr(mib), mib.len() as ::libc::c_uint,
465 buf as *mut c_void, &mut sz, ptr::null(),
466 0u as size_t) == (0 as c_int)
471 #[cfg(target_os = "linux")]
472 #[cfg(target_os = "android")]
473 fn load_self() -> Option<~str> {
474 #[fixed_stack_segment]; #[inline(never)];
476 use libc::funcs::posix01::unistd::readlink;
478 let mut path = [0 as c_char, .. TMPBUF_SZ];
480 do path.as_mut_buf |buf, len| {
481 let len = do "/proc/self/exe".with_c_str |proc_self_buf| {
482 readlink(proc_self_buf, buf, len as size_t) as uint
488 Some(str::raw::from_buf_len(buf as *u8, len))
494 #[cfg(target_os = "macos")]
495 fn load_self() -> Option<~str> {
496 #[fixed_stack_segment]; #[inline(never)];
498 do fill_charp_buf() |buf, sz| {
499 let mut sz = sz as u32;
500 libc::funcs::extra::_NSGetExecutablePath(
501 buf, &mut sz) == (0 as c_int)
507 fn load_self() -> Option<~str> {
508 #[fixed_stack_segment]; #[inline(never)];
510 use os::win32::fill_utf16_buf_and_decode;
511 do fill_utf16_buf_and_decode() |buf, sz| {
512 libc::GetModuleFileNameW(0u as libc::DWORD, buf, sz)
517 load_self().map_move(|path| Path(path).dir_path())
522 * Returns the path to the user's home directory, if known.
524 * On Unix, returns the value of the 'HOME' environment variable if it is set
525 * and not equal to the empty string.
527 * On Windows, returns the value of the 'HOME' environment variable if it is
528 * set and not equal to the empty string. Otherwise, returns the value of the
529 * 'USERPROFILE' environment variable if it is set and not equal to the empty
532 * Otherwise, homedir returns option::none.
534 pub fn homedir() -> Option<Path> {
535 return match getenv("HOME") {
536 Some(ref p) => if !p.is_empty() {
545 fn secondary() -> Option<Path> {
550 fn secondary() -> Option<Path> {
551 do getenv("USERPROFILE").and_then |p| {
562 * Returns the path to a temporary directory.
564 * On Unix, returns the value of the 'TMPDIR' environment variable if it is
565 * set and non-empty and '/tmp' otherwise.
566 * On Android, there is no global temporary folder (it is usually allocated
567 * per-app), hence returns '/data/tmp' which is commonly used.
569 * On Windows, returns the value of, in order, the 'TMP', 'TEMP',
570 * 'USERPROFILE' environment variable if any are set and not the empty
571 * string. Otherwise, tmpdir returns the path to the Windows directory.
573 pub fn tmpdir() -> Path {
576 fn getenv_nonempty(v: &str) -> Option<Path> {
589 fn lookup() -> Path {
590 if cfg!(target_os = "android") {
593 getenv_nonempty("TMPDIR").unwrap_or(Path("/tmp"))
598 fn lookup() -> Path {
599 getenv_nonempty("TMP").or(
600 getenv_nonempty("TEMP").or(
601 getenv_nonempty("USERPROFILE").or(
602 getenv_nonempty("WINDIR")))).unwrap_or(Path("C:\\Windows"))
606 /// Recursively walk a directory structure
607 pub fn walk_dir(p: &Path, f: &fn(&Path) -> bool) -> bool {
609 r.iter().advance(|q| {
610 let path = &p.push(*q);
611 f(path) && (!path_is_dir(path) || walk_dir(path, |p| f(p)))
615 /// Indicates whether a path represents a directory
616 pub fn path_is_dir(p: &Path) -> bool {
617 #[fixed_stack_segment]; #[inline(never)];
619 do p.with_c_str |buf| {
620 rustrt::rust_path_is_dir(buf) != 0 as c_int
625 /// Indicates whether a path exists
626 pub fn path_exists(p: &Path) -> bool {
627 #[fixed_stack_segment]; #[inline(never)];
629 do p.with_c_str |buf| {
630 rustrt::rust_path_exists(buf) != 0 as c_int
636 * Convert a relative path to an absolute path
638 * If the given path is relative, return it prepended with the current working
639 * directory. If the given path is already an absolute path, return it
642 // NB: this is here rather than in path because it is a form of environment
643 // querying; what it does depends on the process working directory, not just
645 pub fn make_absolute(p: &Path) -> Path {
649 getcwd().push_many(p.components)
654 /// Creates a directory at the specified path
655 pub fn make_dir(p: &Path, mode: c_int) -> bool {
656 return mkdir(p, mode);
659 fn mkdir(p: &Path, _mode: c_int) -> bool {
660 #[fixed_stack_segment]; #[inline(never)];
662 use os::win32::as_utf16_p;
663 // FIXME: turn mode into something useful? #2623
664 do as_utf16_p(p.to_str()) |buf| {
665 libc::CreateDirectoryW(buf, ptr::mut_null())
672 fn mkdir(p: &Path, mode: c_int) -> bool {
673 #[fixed_stack_segment]; #[inline(never)];
674 do p.with_c_str |buf| {
676 libc::mkdir(buf, mode as libc::mode_t) == (0 as c_int)
682 /// Creates a directory with a given mode.
683 /// Returns true iff creation
684 /// succeeded. Also creates all intermediate subdirectories
685 /// if they don't already exist, giving all of them the same mode.
687 // tjc: if directory exists but with different permissions,
688 // should we return false?
689 pub fn mkdir_recursive(p: &Path, mode: c_int) -> bool {
693 else if p.components.is_empty() {
696 else if p.components.len() == 1 {
697 // No parent directories to create
698 path_is_dir(p) || make_dir(p, mode)
701 mkdir_recursive(&p.pop(), mode) && make_dir(p, mode)
705 /// Lists the contents of a directory
706 pub fn list_dir(p: &Path) -> ~[~str] {
707 if p.components.is_empty() && !p.is_absolute() {
708 // Not sure what the right behavior is here, but this
709 // prevents a bounds check failure later
713 #[cfg(target_os = "linux")]
714 #[cfg(target_os = "android")]
715 #[cfg(target_os = "freebsd")]
716 #[cfg(target_os = "macos")]
717 unsafe fn get_list(p: &Path) -> ~[~str] {
718 #[fixed_stack_segment]; #[inline(never)];
719 use libc::{dirent_t};
720 use libc::{opendir, readdir, closedir};
722 fn rust_list_dir_val(ptr: *dirent_t) -> *libc::c_char;
724 let mut strings = ~[];
725 debug!("os::list_dir -- BEFORE OPENDIR");
727 let dir_ptr = do p.with_c_str |buf| {
731 if (dir_ptr as uint != 0) {
732 debug!("os::list_dir -- opendir() SUCCESS");
733 let mut entry_ptr = readdir(dir_ptr);
734 while (entry_ptr as uint != 0) {
735 strings.push(str::raw::from_c_str(rust_list_dir_val(
737 entry_ptr = readdir(dir_ptr);
742 debug!("os::list_dir -- opendir() FAILURE");
745 "os::list_dir -- AFTER -- #: %?",
750 unsafe fn get_list(p: &Path) -> ~[~str] {
751 #[fixed_stack_segment]; #[inline(never)];
752 use libc::consts::os::extra::INVALID_HANDLE_VALUE;
753 use libc::{wcslen, free};
754 use libc::funcs::extra::kernel32::{
759 use libc::types::os::arch::extra::HANDLE;
763 use rt::global_heap::malloc_raw;
767 fn rust_list_dir_wfd_size() -> libc::size_t;
768 fn rust_list_dir_wfd_fp_buf(wfd: *libc::c_void) -> *u16;
770 fn star(p: &Path) -> Path { p.push("*") }
771 do as_utf16_p(star(p).to_str()) |path_ptr| {
772 let mut strings = ~[];
773 let wfd_ptr = malloc_raw(rust_list_dir_wfd_size() as uint);
774 let find_handle = FindFirstFileW(path_ptr, wfd_ptr as HANDLE);
775 if find_handle as libc::c_int != INVALID_HANDLE_VALUE {
776 let mut more_files = 1 as libc::c_int;
777 while more_files != 0 {
778 let fp_buf = rust_list_dir_wfd_fp_buf(wfd_ptr);
779 if fp_buf as uint == 0 {
780 fail!("os::list_dir() failure: got null ptr from wfd");
783 let fp_vec = vec::from_buf(
784 fp_buf, wcslen(fp_buf) as uint);
785 let fp_str = str::from_utf16(fp_vec);
786 strings.push(fp_str);
788 more_files = FindNextFileW(find_handle, wfd_ptr as HANDLE);
790 FindClose(find_handle);
796 do get_list(p).move_iter().filter |filename| {
797 "." != *filename && ".." != *filename
803 * Lists the contents of a directory
805 * This version prepends each entry with the directory.
807 pub fn list_dir_path(p: &Path) -> ~[Path] {
808 list_dir(p).map(|f| p.push(*f))
811 /// Removes a directory at the specified path, after removing
812 /// all its contents. Use carefully!
813 pub fn remove_dir_recursive(p: &Path) -> bool {
814 let mut error_happened = false;
815 do walk_dir(p) |inner| {
817 if path_is_dir(inner) {
818 if !remove_dir_recursive(inner) {
819 error_happened = true;
823 if !remove_file(inner) {
824 error_happened = true;
830 // Directory should now be empty
831 !error_happened && remove_dir(p)
834 /// Removes a directory at the specified path
835 pub fn remove_dir(p: &Path) -> bool {
839 fn rmdir(p: &Path) -> bool {
840 #[fixed_stack_segment]; #[inline(never)];
842 use os::win32::as_utf16_p;
843 return do as_utf16_p(p.to_str()) |buf| {
844 libc::RemoveDirectoryW(buf) != (0 as libc::BOOL)
850 fn rmdir(p: &Path) -> bool {
851 #[fixed_stack_segment]; #[inline(never)];
852 do p.with_c_str |buf| {
854 libc::rmdir(buf) == (0 as c_int)
860 /// Changes the current working directory to the specified path, returning
861 /// whether the change was completed successfully or not.
862 pub fn change_dir(p: &Path) -> bool {
866 fn chdir(p: &Path) -> bool {
867 #[fixed_stack_segment]; #[inline(never)];
869 use os::win32::as_utf16_p;
870 return do as_utf16_p(p.to_str()) |buf| {
871 libc::SetCurrentDirectoryW(buf) != (0 as libc::BOOL)
877 fn chdir(p: &Path) -> bool {
878 #[fixed_stack_segment]; #[inline(never)];
879 do p.with_c_str |buf| {
881 libc::chdir(buf) == (0 as c_int)
887 /// Copies a file from one location to another
888 pub fn copy_file(from: &Path, to: &Path) -> bool {
889 return do_copy_file(from, to);
892 fn do_copy_file(from: &Path, to: &Path) -> bool {
893 #[fixed_stack_segment]; #[inline(never)];
895 use os::win32::as_utf16_p;
896 return do as_utf16_p(from.to_str()) |fromp| {
897 do as_utf16_p(to.to_str()) |top| {
898 libc::CopyFileW(fromp, top, (0 as libc::BOOL)) !=
906 fn do_copy_file(from: &Path, to: &Path) -> bool {
907 #[fixed_stack_segment]; #[inline(never)];
909 let istream = do from.with_c_str |fromp| {
910 do "rb".with_c_str |modebuf| {
911 libc::fopen(fromp, modebuf)
914 if istream as uint == 0u {
917 // Preserve permissions
918 let from_mode = from.get_mode().expect("copy_file: couldn't get permissions \
921 let ostream = do to.with_c_str |top| {
922 do "w+b".with_c_str |modebuf| {
923 libc::fopen(top, modebuf)
926 if ostream as uint == 0u {
931 let mut buf = vec::with_capacity::<u8>(bufsize);
932 let mut done = false;
935 do buf.as_mut_buf |b, _sz| {
936 let nread = libc::fread(b as *mut c_void, 1u as size_t,
939 if nread > 0 as size_t {
940 if libc::fwrite(b as *c_void, 1u as size_t, nread,
953 // Give the new file the old file's permissions
954 if do to.with_c_str |to_buf| {
955 libc::chmod(to_buf, from_mode as libc::mode_t)
957 return false; // should be a condition...
964 /// Deletes an existing file
965 pub fn remove_file(p: &Path) -> bool {
969 fn unlink(p: &Path) -> bool {
970 #[fixed_stack_segment]; #[inline(never)];
972 use os::win32::as_utf16_p;
973 return do as_utf16_p(p.to_str()) |buf| {
974 libc::DeleteFileW(buf) != (0 as libc::BOOL)
980 fn unlink(p: &Path) -> bool {
981 #[fixed_stack_segment]; #[inline(never)];
983 do p.with_c_str |buf| {
984 libc::unlink(buf) == (0 as c_int)
990 /// Renames an existing file or directory
991 pub fn rename_file(old: &Path, new: &Path) -> bool {
992 #[fixed_stack_segment]; #[inline(never)];
994 do old.with_c_str |old_buf| {
995 do new.with_c_str |new_buf| {
996 libc::rename(old_buf, new_buf) == (0 as c_int)
1003 /// Returns the platform-specific value of errno
1004 pub fn errno() -> int {
1005 #[cfg(target_os = "macos")]
1006 #[cfg(target_os = "freebsd")]
1007 fn errno_location() -> *c_int {
1008 #[fixed_stack_segment]; #[inline(never)];
1011 fn __error() -> *c_int;
1018 #[cfg(target_os = "linux")]
1019 #[cfg(target_os = "android")]
1020 fn errno_location() -> *c_int {
1021 #[fixed_stack_segment]; #[inline(never)];
1024 fn __errno_location() -> *c_int;
1032 (*errno_location()) as int
1037 /// Returns the platform-specific value of errno
1038 pub fn errno() -> uint {
1039 #[fixed_stack_segment]; #[inline(never)];
1040 use libc::types::os::arch::extra::DWORD;
1042 #[cfg(target_arch = "x86")]
1043 #[link_name = "kernel32"]
1046 fn GetLastError() -> DWORD;
1049 #[cfg(target_arch = "x86_64")]
1050 #[link_name = "kernel32"]
1052 fn GetLastError() -> DWORD;
1056 GetLastError() as uint
1060 /// Get a string representing the platform-dependent last error
1061 pub fn last_os_error() -> ~str {
1063 fn strerror() -> ~str {
1064 #[cfg(target_os = "macos")]
1065 #[cfg(target_os = "android")]
1066 #[cfg(target_os = "freebsd")]
1067 fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: size_t)
1069 #[fixed_stack_segment]; #[inline(never)];
1073 fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: size_t)
1077 strerror_r(errnum, buf, buflen)
1081 // GNU libc provides a non-compliant version of strerror_r by default
1082 // and requires macros to instead use the POSIX compliant variant.
1083 // So we just use __xpg_strerror_r which is always POSIX compliant
1084 #[cfg(target_os = "linux")]
1085 fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: size_t) -> c_int {
1086 #[fixed_stack_segment]; #[inline(never)];
1089 fn __xpg_strerror_r(errnum: c_int,
1095 __xpg_strerror_r(errnum, buf, buflen)
1099 let mut buf = [0 as c_char, ..TMPBUF_SZ];
1101 do buf.as_mut_buf |buf, len| {
1103 if strerror_r(errno() as c_int, buf, len as size_t) < 0 {
1104 fail!("strerror_r failure");
1107 str::raw::from_c_str(buf as *c_char)
1113 fn strerror() -> ~str {
1114 #[fixed_stack_segment]; #[inline(never)];
1116 use libc::types::os::arch::extra::DWORD;
1117 use libc::types::os::arch::extra::LPWSTR;
1118 use libc::types::os::arch::extra::LPVOID;
1119 use libc::types::os::arch::extra::WCHAR;
1121 #[cfg(target_arch = "x86")]
1122 #[link_name = "kernel32"]
1125 fn FormatMessageW(flags: DWORD,
1135 #[cfg(target_arch = "x86_64")]
1136 #[link_name = "kernel32"]
1138 fn FormatMessageW(flags: DWORD,
1148 static FORMAT_MESSAGE_FROM_SYSTEM: DWORD = 0x00001000;
1149 static FORMAT_MESSAGE_IGNORE_INSERTS: DWORD = 0x00000200;
1151 // This value is calculated from the macro
1152 // MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT)
1153 let langId = 0x0800 as DWORD;
1154 let err = errno() as DWORD;
1156 let mut buf = [0 as WCHAR, ..TMPBUF_SZ];
1159 do buf.as_mut_buf |buf, len| {
1160 let res = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
1161 FORMAT_MESSAGE_IGNORE_INSERTS,
1169 fail!("[%?] FormatMessage failure", errno());
1173 str::from_utf16(buf)
1181 * Sets the process exit code
1183 * Sets the exit code returned by the process if all supervised tasks
1184 * terminate successfully (without failing). If the current root task fails
1185 * and is supervised by the scheduler then any user-specified exit status is
1186 * ignored and the process exits with the default failure status
1188 pub fn set_exit_status(code: int) {
1190 rt::util::set_exit_status(code);
1193 unsafe fn load_argc_and_argv(argc: c_int, argv: **c_char) -> ~[~str] {
1195 for i in range(0u, argc as uint) {
1196 args.push(str::raw::from_c_str(*argv.offset(i as int)));
1202 * Returns the command line arguments
1204 * Returns a list of the command line arguments.
1206 #[cfg(target_os = "macos")]
1207 fn real_args() -> ~[~str] {
1208 #[fixed_stack_segment]; #[inline(never)];
1211 let (argc, argv) = (*_NSGetArgc() as c_int,
1212 *_NSGetArgv() as **c_char);
1213 load_argc_and_argv(argc, argv)
1217 #[cfg(target_os = "linux")]
1218 #[cfg(target_os = "android")]
1219 #[cfg(target_os = "freebsd")]
1220 fn real_args() -> ~[~str] {
1223 match rt::args::clone() {
1225 None => fail!("process arguments not initialized")
1230 fn real_args() -> ~[~str] {
1231 #[fixed_stack_segment]; #[inline(never)];
1233 let mut nArgs: c_int = 0;
1234 let lpArgCount: *mut c_int = &mut nArgs;
1235 let lpCmdLine = unsafe { GetCommandLineW() };
1236 let szArgList = unsafe { CommandLineToArgvW(lpCmdLine, lpArgCount) };
1239 for i in range(0u, nArgs as uint) {
1241 // Determine the length of this argument.
1242 let ptr = *szArgList.offset(i as int);
1244 while *ptr.offset(len as int) != 0 { len += 1; }
1246 // Push it onto the list.
1247 args.push(vec::raw::buf_as_slice(ptr, len,
1253 LocalFree(szArgList as *c_void);
1259 type LPCWSTR = *u16;
1261 #[cfg(windows, target_arch = "x86")]
1262 #[link_name="kernel32"]
1265 fn GetCommandLineW() -> LPCWSTR;
1266 fn LocalFree(ptr: *c_void);
1269 #[cfg(windows, target_arch = "x86_64")]
1270 #[link_name="kernel32"]
1272 fn GetCommandLineW() -> LPCWSTR;
1273 fn LocalFree(ptr: *c_void);
1276 #[cfg(windows, target_arch = "x86")]
1277 #[link_name="shell32"]
1280 fn CommandLineToArgvW(lpCmdLine: LPCWSTR, pNumArgs: *mut c_int) -> **u16;
1283 #[cfg(windows, target_arch = "x86_64")]
1284 #[link_name="shell32"]
1286 fn CommandLineToArgvW(lpCmdLine: LPCWSTR, pNumArgs: *mut c_int) -> **u16;
1289 struct OverriddenArgs {
1293 /// Returns the arguments which this program was started with (normally passed
1294 /// via the command line).
1295 pub fn args() -> ~[~str] {
1299 #[cfg(target_os = "macos")]
1301 // These functions are in crt_externs.h.
1302 pub fn _NSGetArgc() -> *c_int;
1303 pub fn _NSGetArgv() -> ***c_char;
1306 // Round up `from` to be divisible by `to`
1307 fn round_up(from: uint, to: uint) -> uint {
1308 let r = if from % to == 0 {
1311 from + to - (from % to)
1321 pub fn page_size() -> uint {
1322 #[fixed_stack_segment]; #[inline(never)];
1325 libc::sysconf(libc::_SC_PAGESIZE) as uint
1330 pub fn page_size() -> uint {
1331 #[fixed_stack_segment]; #[inline(never)];
1334 let mut info = libc::SYSTEM_INFO::new();
1335 libc::GetSystemInfo(&mut info);
1337 return info.dwPageSize as uint;
1341 pub struct MemoryMap {
1347 pub enum MemoryMapKind {
1352 pub enum MapOption {
1362 // Linux-specific errors
1368 ErrUnknown(libc::c_int),
1370 // Windows-specific errors
1374 ErrVirtualAlloc(uint),
1375 ErrCreateFileMappingW(uint),
1376 ErrMapViewOfFile(uint)
1379 impl to_str::ToStr for MapError {
1380 fn to_str(&self) -> ~str {
1382 ErrFdNotAvail => ~"fd not available for reading or writing",
1383 ErrInvalidFd => ~"Invalid fd",
1384 ErrUnaligned => ~"Unaligned address, invalid flags, \
1385 negative length or unaligned offset",
1386 ErrNoMapSupport=> ~"File doesn't support mapping",
1387 ErrNoMem => ~"Invalid address, or not enough available memory",
1388 ErrUnknown(code) => fmt!("Unknown error=%?", code),
1389 ErrUnsupProt => ~"Protection mode unsupported",
1390 ErrUnsupOffset => ~"Offset in virtual memory mode is unsupported",
1391 ErrAlreadyExists => ~"File mapping for specified file already exists",
1392 ErrVirtualAlloc(code) => fmt!("VirtualAlloc failure=%?", code),
1393 ErrCreateFileMappingW(code) => fmt!("CreateFileMappingW failure=%?", code),
1394 ErrMapViewOfFile(code) => fmt!("MapViewOfFile failure=%?", code)
1401 pub fn new(min_len: uint, options: ~[MapOption]) -> Result<~MemoryMap, MapError> {
1402 #[fixed_stack_segment]; #[inline(never)];
1406 let mut addr: *c_void = ptr::null();
1407 let mut prot: c_int = 0;
1408 let mut flags: c_int = libc::MAP_PRIVATE;
1409 let mut fd: c_int = -1;
1410 let mut offset: off_t = 0;
1411 let len = round_up(min_len, page_size()) as size_t;
1413 for &o in options.iter() {
1415 MapReadable => { prot |= libc::PROT_READ; },
1416 MapWritable => { prot |= libc::PROT_WRITE; },
1417 MapExecutable => { prot |= libc::PROT_EXEC; },
1419 flags |= libc::MAP_FIXED;
1423 flags |= libc::MAP_FILE;
1426 MapOffset(offset_) => { offset = offset_ as off_t; }
1429 if fd == -1 { flags |= libc::MAP_ANON; }
1432 libc::mmap(addr, len, prot, flags, fd, offset)
1434 if r.equiv(&libc::MAP_FAILED) {
1435 Err(match errno() as c_int {
1436 libc::EACCES => ErrFdNotAvail,
1437 libc::EBADF => ErrInvalidFd,
1438 libc::EINVAL => ErrUnaligned,
1439 libc::ENODEV => ErrNoMapSupport,
1440 libc::ENOMEM => ErrNoMem,
1441 code => ErrUnknown(code)
1450 MapFile(ptr::null())
1456 pub fn granularity() -> uint {
1462 impl Drop for MemoryMap {
1463 fn drop(&mut self) {
1464 #[fixed_stack_segment]; #[inline(never)];
1467 match libc::munmap(self.data as *c_void, self.len) {
1469 -1 => error!(match errno() as c_int {
1470 libc::EINVAL => ~"invalid addr or len",
1471 e => fmt!("unknown errno=%?", e)
1473 r => error!(fmt!("Unexpected result %?", r))
1481 pub fn new(min_len: uint, options: ~[MapOption]) -> Result<~MemoryMap, MapError> {
1482 #[fixed_stack_segment]; #[inline(never)];
1484 use libc::types::os::arch::extra::{LPVOID, DWORD, SIZE_T, HANDLE};
1486 let mut lpAddress: LPVOID = ptr::mut_null();
1487 let mut readable = false;
1488 let mut writable = false;
1489 let mut executable = false;
1490 let mut fd: c_int = -1;
1491 let mut offset: uint = 0;
1492 let len = round_up(min_len, page_size()) as SIZE_T;
1494 for &o in options.iter() {
1496 MapReadable => { readable = true; },
1497 MapWritable => { writable = true; },
1498 MapExecutable => { executable = true; }
1499 MapAddr(addr_) => { lpAddress = addr_ as LPVOID; },
1500 MapFd(fd_) => { fd = fd_; },
1501 MapOffset(offset_) => { offset = offset_; }
1505 let flProtect = match (executable, readable, writable) {
1506 (false, false, false) if fd == -1 => libc::PAGE_NOACCESS,
1507 (false, true, false) => libc::PAGE_READONLY,
1508 (false, true, true) => libc::PAGE_READWRITE,
1509 (true, false, false) if fd == -1 => libc::PAGE_EXECUTE,
1510 (true, true, false) => libc::PAGE_EXECUTE_READ,
1511 (true, true, true) => libc::PAGE_EXECUTE_READWRITE,
1512 _ => return Err(ErrUnsupProt)
1517 return Err(ErrUnsupOffset);
1520 libc::VirtualAlloc(lpAddress,
1522 libc::MEM_COMMIT | libc::MEM_RESERVE,
1526 0 => Err(ErrVirtualAlloc(errno())),
1527 _ => Ok(~MemoryMap {
1534 let dwDesiredAccess = match (executable, readable, writable) {
1535 (false, true, false) => libc::FILE_MAP_READ,
1536 (false, true, true) => libc::FILE_MAP_WRITE,
1537 (true, true, false) => libc::FILE_MAP_READ | libc::FILE_MAP_EXECUTE,
1538 (true, true, true) => libc::FILE_MAP_WRITE | libc::FILE_MAP_EXECUTE,
1539 _ => return Err(ErrUnsupProt) // Actually, because of the check above,
1540 // we should never get here.
1543 let hFile = libc::get_osfhandle(fd) as HANDLE;
1544 let mapping = libc::CreateFileMappingW(hFile,
1550 if mapping == ptr::mut_null() {
1551 return Err(ErrCreateFileMappingW(errno()));
1553 if errno() as c_int == libc::ERROR_ALREADY_EXISTS {
1554 return Err(ErrAlreadyExists);
1556 let r = libc::MapViewOfFile(mapping,
1558 ((len as u64) >> 32) as DWORD,
1559 (offset & 0xffff_ffff) as DWORD,
1562 0 => Err(ErrMapViewOfFile(errno())),
1563 _ => Ok(~MemoryMap {
1566 kind: MapFile(mapping as *c_void)
1573 /// Granularity of MapAddr() and MapOffset() parameter values.
1574 /// This may be greater than the value returned by page_size().
1575 pub fn granularity() -> uint {
1576 #[fixed_stack_segment]; #[inline(never)];
1579 let mut info = libc::SYSTEM_INFO::new();
1580 libc::GetSystemInfo(&mut info);
1582 return info.dwAllocationGranularity as uint;
1588 impl Drop for MemoryMap {
1589 fn drop(&mut self) {
1590 #[fixed_stack_segment]; #[inline(never)];
1592 use libc::types::os::arch::extra::{LPCVOID, HANDLE};
1593 use libc::consts::os::extra::FALSE;
1598 if libc::VirtualFree(self.data as *mut c_void,
1600 libc::MEM_RELEASE) == FALSE {
1601 error!(fmt!("VirtualFree failed: %?", errno()));
1604 MapFile(mapping) => {
1605 if libc::UnmapViewOfFile(self.data as LPCVOID) == FALSE {
1606 error!(fmt!("UnmapViewOfFile failed: %?", errno()));
1608 if libc::CloseHandle(mapping as HANDLE) == FALSE {
1609 error!(fmt!("CloseHandle failed: %?", errno()));
1620 pub use os::consts::unix::*;
1623 pub use os::consts::windows::*;
1625 #[cfg(target_os = "macos")]
1626 pub use os::consts::macos::*;
1628 #[cfg(target_os = "freebsd")]
1629 pub use os::consts::freebsd::*;
1631 #[cfg(target_os = "linux")]
1632 pub use os::consts::linux::*;
1634 #[cfg(target_os = "android")]
1635 pub use os::consts::android::*;
1637 #[cfg(target_os = "win32")]
1638 pub use os::consts::win32::*;
1640 #[cfg(target_arch = "x86")]
1641 pub use os::consts::x86::*;
1643 #[cfg(target_arch = "x86_64")]
1644 pub use os::consts::x86_64::*;
1646 #[cfg(target_arch = "arm")]
1647 pub use os::consts::arm::*;
1649 #[cfg(target_arch = "mips")]
1650 pub use os::consts::mips::*;
1653 pub static FAMILY: &'static str = "unix";
1657 pub static FAMILY: &'static str = "windows";
1661 pub static SYSNAME: &'static str = "macos";
1662 pub static DLL_PREFIX: &'static str = "lib";
1663 pub static DLL_SUFFIX: &'static str = ".dylib";
1664 pub static EXE_SUFFIX: &'static str = "";
1668 pub static SYSNAME: &'static str = "freebsd";
1669 pub static DLL_PREFIX: &'static str = "lib";
1670 pub static DLL_SUFFIX: &'static str = ".so";
1671 pub static EXE_SUFFIX: &'static str = "";
1675 pub static SYSNAME: &'static str = "linux";
1676 pub static DLL_PREFIX: &'static str = "lib";
1677 pub static DLL_SUFFIX: &'static str = ".so";
1678 pub static EXE_SUFFIX: &'static str = "";
1682 pub static SYSNAME: &'static str = "android";
1683 pub static DLL_PREFIX: &'static str = "lib";
1684 pub static DLL_SUFFIX: &'static str = ".so";
1685 pub static EXE_SUFFIX: &'static str = "";
1689 pub static SYSNAME: &'static str = "win32";
1690 pub static DLL_PREFIX: &'static str = "";
1691 pub static DLL_SUFFIX: &'static str = ".dll";
1692 pub static EXE_SUFFIX: &'static str = ".exe";
1697 pub static ARCH: &'static str = "x86";
1700 pub static ARCH: &'static str = "x86_64";
1703 pub static ARCH: &'static str = "arm";
1706 pub static ARCH: &'static str = "mips";
1713 use libc::{c_int, c_void, size_t};
1717 use os::{env, getcwd, getenv, make_absolute, args};
1718 use os::{remove_file, setenv, unsetenv};
1725 use libc::consts::os::posix88::{S_IRUSR, S_IWUSR, S_IXUSR};
1729 pub fn last_os_error() {
1730 debug!(os::last_os_error());
1734 pub fn test_args() {
1736 assert!(a.len() >= 1);
1739 fn make_rand_name() -> ~str {
1740 let mut rng = rand::rng();
1741 let n = ~"TEST" + rng.gen_str(10u);
1742 assert!(getenv(n).is_none());
1748 let n = make_rand_name();
1750 assert_eq!(getenv(n), option::Some(~"VALUE"));
1754 fn test_unsetenv() {
1755 let n = make_rand_name();
1758 assert_eq!(getenv(n), option::None);
1763 fn test_setenv_overwrite() {
1764 let n = make_rand_name();
1767 assert_eq!(getenv(n), option::Some(~"2"));
1769 assert_eq!(getenv(n), option::Some(~""));
1772 // Windows GetEnvironmentVariable requires some extra work to make sure
1773 // the buffer the variable is copied into is the right size
1776 fn test_getenv_big() {
1780 s = s + "aaaaaaaaaa";
1783 let n = make_rand_name();
1786 assert_eq!(getenv(n), option::Some(s));
1790 fn test_self_exe_path() {
1791 let path = os::self_exe_path();
1792 assert!(path.is_some());
1793 let path = path.unwrap();
1794 debug!(path.clone());
1796 // Hard to test this function
1797 assert!(path.is_absolute);
1802 fn test_env_getenv() {
1804 assert!(e.len() > 0u);
1806 let (n, v) = (*p).clone();
1809 // MingW seems to set some funky environment variables like
1810 // "=C:=C:\MinGW\msys\1.0\bin" and "!::=::\" that are returned
1811 // from env() but not visible from getenv().
1812 assert!(v2.is_none() || v2 == option::Some(v));
1817 fn test_env_setenv() {
1818 let n = make_rand_name();
1822 assert!(!e.contains(&(n.clone(), ~"VALUE")));
1825 assert!(e.contains(&(n, ~"VALUE")));
1830 assert!((!Path("test-path").is_absolute));
1832 debug!("Current working directory: %s", getcwd().to_str());
1834 debug!(make_absolute(&Path("test-path")));
1835 debug!(make_absolute(&Path("/usr/bin")));
1841 let oldhome = getenv("HOME");
1843 setenv("HOME", "/home/MountainView");
1844 assert_eq!(os::homedir(), Some(Path("/home/MountainView")));
1847 assert!(os::homedir().is_none());
1849 for s in oldhome.iter() { setenv("HOME", *s) }
1856 let oldhome = getenv("HOME");
1857 let olduserprofile = getenv("USERPROFILE");
1860 setenv("USERPROFILE", "");
1862 assert!(os::homedir().is_none());
1864 setenv("HOME", "/home/MountainView");
1865 assert_eq!(os::homedir(), Some(Path("/home/MountainView")));
1869 setenv("USERPROFILE", "/home/MountainView");
1870 assert_eq!(os::homedir(), Some(Path("/home/MountainView")));
1872 setenv("HOME", "/home/MountainView");
1873 setenv("USERPROFILE", "/home/PaloAlto");
1874 assert_eq!(os::homedir(), Some(Path("/home/MountainView")));
1876 for s in oldhome.iter() { setenv("HOME", *s) }
1877 for s in olduserprofile.iter() { setenv("USERPROFILE", *s) }
1882 assert!(!os::tmpdir().to_str().is_empty());
1887 fn test_list_dir_no_invalid_memory_access() {
1888 os::list_dir(&Path("."));
1893 let dirs = os::list_dir(&Path("."));
1894 // Just assuming that we've got some contents in the current directory
1895 assert!(dirs.len() > 0u);
1897 for dir in dirs.iter() {
1898 debug!((*dir).clone());
1903 fn list_dir_empty_path() {
1904 let dirs = os::list_dir(&Path(""));
1905 assert!(dirs.is_empty());
1909 #[cfg(not(windows))]
1910 fn list_dir_root() {
1911 let dirs = os::list_dir(&Path("/"));
1912 assert!(dirs.len() > 1);
1916 fn list_dir_root() {
1917 let dirs = os::list_dir(&Path("C:\\"));
1918 assert!(dirs.len() > 1);
1924 assert!((os::path_is_dir(&Path("."))));
1925 assert!((!os::path_is_dir(&Path("test/stdtest/fs.rs"))));
1930 assert!((os::path_exists(&Path("."))));
1931 assert!((!os::path_exists(&Path(
1932 "test/nonexistent-bogus-path"))));
1936 fn copy_file_does_not_exist() {
1937 assert!(!os::copy_file(&Path("test/nonexistent-bogus-path"),
1938 &Path("test/other-bogus-path")));
1939 assert!(!os::path_exists(&Path("test/other-bogus-path")));
1944 #[fixed_stack_segment]; #[inline(never)];
1947 let tempdir = getcwd(); // would like to use $TMPDIR,
1948 // doesn't seem to work on Linux
1949 assert!((tempdir.to_str().len() > 0u));
1950 let input = tempdir.push("in.txt");
1951 let out = tempdir.push("out.txt");
1953 /* Write the temp input file */
1954 let ostream = do input.with_c_str |fromp| {
1955 do "w+b".with_c_str |modebuf| {
1956 libc::fopen(fromp, modebuf)
1959 assert!((ostream as uint != 0u));
1961 do "hello".with_c_str |buf| {
1962 let write_len = libc::fwrite(buf as *c_void,
1964 (s.len() + 1u) as size_t,
1966 assert_eq!(write_len, (s.len() + 1) as size_t)
1968 assert_eq!(libc::fclose(ostream), (0u as c_int));
1969 let in_mode = input.get_mode();
1970 let rs = os::copy_file(&input, &out);
1971 if (!os::path_exists(&input)) {
1972 fail!("%s doesn't exist", input.to_str());
1975 let rslt = run::process_status("diff", [input.to_str(), out.to_str()]);
1976 assert_eq!(rslt, 0);
1977 assert_eq!(out.get_mode(), in_mode);
1978 assert!((remove_file(&input)));
1979 assert!((remove_file(&out)));
1984 fn recursive_mkdir_slash() {
1985 let path = Path("/");
1986 assert!(os::mkdir_recursive(&path, (S_IRUSR | S_IWUSR | S_IXUSR) as i32));
1990 fn recursive_mkdir_empty() {
1991 let path = Path("");
1992 assert!(!os::mkdir_recursive(&path, (S_IRUSR | S_IWUSR | S_IXUSR) as i32));
1996 fn memory_map_rw() {
1997 use result::{Ok, Err};
1999 let chunk = match os::MemoryMap::new(16, ~[
2004 Err(msg) => fail!(msg.to_str())
2006 assert!(chunk.len >= 16);
2010 assert!(*chunk.data == 0xBE);
2015 fn memory_map_file() {
2016 #[fixed_stack_segment]; #[inline(never)];
2018 use result::{Ok, Err};
2023 #[fixed_stack_segment]
2025 fn lseek_(fd: c_int, size: uint) {
2027 assert!(lseek(fd, size as off_t, SEEK_SET) == size as off_t);
2031 #[fixed_stack_segment]
2033 fn lseek_(fd: c_int, size: uint) {
2035 assert!(lseek(fd, size as c_long, SEEK_SET) == size as c_long);
2039 let path = tmpdir().push("mmap_file.tmp");
2040 let size = MemoryMap::granularity() * 2;
2044 let fd = do path.with_c_str |path| {
2045 open(path, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR)
2048 do "x".with_c_str |x| {
2049 assert!(write(fd, x as *c_void, 1) == 1);
2053 let chunk = match MemoryMap::new(size / 2, ~[
2060 Err(msg) => fail!(msg.to_str())
2062 assert!(chunk.len > 0);
2066 assert!(*chunk.data == 0xbe);
2071 // More recursive_mkdir tests are in extra::tempfile