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))
154 macro_rules! externfn(
155 (fn $name:ident ()) => (
164 Accessing environment variables is not generally threadsafe.
165 Serialize access through a global lock.
167 fn with_env_lock<T>(f: &fn() -> T) -> T {
168 use unstable::finally::Finally;
172 rust_take_env_lock();
175 rust_drop_env_lock();
179 externfn!(fn rust_take_env_lock());
180 externfn!(fn rust_drop_env_lock());
183 /// Returns a vector of (variable, value) pairs for all the environment
184 /// variables of the current process.
185 pub fn env() -> ~[(~str,~str)] {
188 unsafe fn get_env_pairs() -> ~[~str] {
189 #[fixed_stack_segment]; #[inline(never)];
191 use libc::funcs::extra::kernel32::{
192 GetEnvironmentStringsA,
193 FreeEnvironmentStringsA
195 let ch = GetEnvironmentStringsA();
196 if (ch as uint == 0) {
197 fail!("os::env() failure getting env string from OS: %s", os::last_os_error());
199 let result = str::raw::from_c_multistring(ch as *libc::c_char, None);
200 FreeEnvironmentStringsA(ch);
204 unsafe fn get_env_pairs() -> ~[~str] {
205 #[fixed_stack_segment]; #[inline(never)];
208 fn rust_env_pairs() -> **libc::c_char;
210 let environ = rust_env_pairs();
211 if (environ as uint == 0) {
212 fail!("os::env() failure getting env string from OS: %s", os::last_os_error());
214 let mut result = ~[];
215 ptr::array_each(environ, |e| {
216 let env_pair = str::raw::from_c_str(e);
217 debug!("get_env_pairs: %s",
219 result.push(env_pair);
224 fn env_convert(input: ~[~str]) -> ~[(~str, ~str)] {
226 for p in input.iter() {
227 let vs: ~[&str] = p.splitn_iter('=', 1).collect();
228 debug!("splitting: len: %u",
230 assert_eq!(vs.len(), 2);
231 pairs.push((vs[0].to_owned(), vs[1].to_owned()));
236 let unparsed_environ = get_env_pairs();
237 env_convert(unparsed_environ)
243 /// Fetches the environment variable `n` from the current process, returning
244 /// None if the variable isn't set.
245 pub fn getenv(n: &str) -> Option<~str> {
246 #[fixed_stack_segment]; #[inline(never)];
249 let s = do n.with_c_str |buf| {
255 Some(str::raw::from_c_str(s))
262 /// Fetches the environment variable `n` from the current process, returning
263 /// None if the variable isn't set.
264 pub fn getenv(n: &str) -> Option<~str> {
265 #[fixed_stack_segment]; #[inline(never)];
269 use os::win32::{as_utf16_p, fill_utf16_buf_and_decode};
270 do as_utf16_p(n) |u| {
271 do fill_utf16_buf_and_decode() |buf, sz| {
272 libc::GetEnvironmentVariableW(u, buf, sz)
281 /// Sets the environment variable `n` to the value `v` for the currently running
283 pub fn setenv(n: &str, v: &str) {
284 #[fixed_stack_segment]; #[inline(never)];
287 do n.with_c_str |nbuf| {
288 do v.with_c_str |vbuf| {
289 libc::funcs::posix01::unistd::setenv(nbuf, vbuf, 1);
298 /// Sets the environment variable `n` to the value `v` for the currently running
300 pub fn setenv(n: &str, v: &str) {
301 #[fixed_stack_segment]; #[inline(never)];
305 use os::win32::as_utf16_p;
306 do as_utf16_p(n) |nbuf| {
307 do as_utf16_p(v) |vbuf| {
308 libc::SetEnvironmentVariableW(nbuf, vbuf);
315 /// Remove a variable from the environment entirely
316 pub fn unsetenv(n: &str) {
318 fn _unsetenv(n: &str) {
319 #[fixed_stack_segment]; #[inline(never)];
322 do n.with_c_str |nbuf| {
323 libc::funcs::posix01::unistd::unsetenv(nbuf);
329 fn _unsetenv(n: &str) {
330 #[fixed_stack_segment]; #[inline(never)];
333 use os::win32::as_utf16_p;
334 do as_utf16_p(n) |nbuf| {
335 libc::SetEnvironmentVariableW(nbuf, ptr::null());
344 pub fn fdopen(fd: c_int) -> *FILE {
345 #[fixed_stack_segment]; #[inline(never)];
346 do "r".with_c_str |modebuf| {
348 libc::fdopen(fd, modebuf)
357 pub fn fsync_fd(fd: c_int, _level: io::fsync::Level) -> c_int {
358 #[fixed_stack_segment]; #[inline(never)];
360 use libc::funcs::extra::msvcrt::*;
365 #[cfg(target_os = "linux")]
366 #[cfg(target_os = "android")]
367 pub fn fsync_fd(fd: c_int, level: io::fsync::Level) -> c_int {
368 #[fixed_stack_segment]; #[inline(never)];
370 use libc::funcs::posix01::unistd::*;
373 | io::fsync::FullFSync => return fsync(fd),
374 io::fsync::FDataSync => return fdatasync(fd)
379 #[cfg(target_os = "macos")]
380 pub fn fsync_fd(fd: c_int, level: io::fsync::Level) -> c_int {
381 #[fixed_stack_segment]; #[inline(never)];
384 use libc::consts::os::extra::*;
385 use libc::funcs::posix88::fcntl::*;
386 use libc::funcs::posix01::unistd::*;
388 io::fsync::FSync => return fsync(fd),
390 // According to man fnctl, the ok retval is only specified to be
392 if (fcntl(F_FULLFSYNC as c_int, fd) == -1 as c_int)
393 { return -1 as c_int; }
395 { return 0 as c_int; }
401 #[cfg(target_os = "freebsd")]
402 pub fn fsync_fd(fd: c_int, _l: io::fsync::Level) -> c_int {
403 #[fixed_stack_segment]; #[inline(never)];
406 use libc::funcs::posix01::unistd::*;
417 pub fn pipe() -> Pipe {
418 #[fixed_stack_segment]; #[inline(never)];
420 let mut fds = Pipe {input: 0 as c_int,
422 assert_eq!(libc::pipe(&mut fds.input), (0 as c_int));
423 return Pipe {input: fds.input, out: fds.out};
430 pub fn pipe() -> Pipe {
431 #[fixed_stack_segment]; #[inline(never)];
433 // Windows pipes work subtly differently than unix pipes, and their
434 // inheritance has to be handled in a different way that I do not
435 // fully understand. Here we explicitly make the pipe non-inheritable,
436 // which means to pass it to a subprocess they need to be duplicated
437 // first, as in std::run.
438 let mut fds = Pipe {input: 0 as c_int,
440 let res = libc::pipe(&mut fds.input, 1024 as ::libc::c_uint,
441 (libc::O_BINARY | libc::O_NOINHERIT) as c_int);
442 assert_eq!(res, 0 as c_int);
443 assert!((fds.input != -1 as c_int && fds.input != 0 as c_int));
444 assert!((fds.out != -1 as c_int && fds.input != 0 as c_int));
445 return Pipe {input: fds.input, out: fds.out};
449 fn dup2(src: c_int, dst: c_int) -> c_int {
450 #[fixed_stack_segment]; #[inline(never)];
456 /// Returns the proper dll filename for the given basename of a file.
457 pub fn dll_filename(base: &str) -> ~str {
458 fmt!("%s%s%s", DLL_PREFIX, base, DLL_SUFFIX)
461 /// Optionally returns the filesystem path to the current executable which is
462 /// running. If any failure occurs, None is returned.
463 pub fn self_exe_path() -> Option<Path> {
465 #[cfg(target_os = "freebsd")]
466 fn load_self() -> Option<~str> {
467 #[fixed_stack_segment]; #[inline(never)];
469 use libc::funcs::bsd44::*;
470 use libc::consts::os::extra::*;
471 do fill_charp_buf() |buf, sz| {
472 let mib = ~[CTL_KERN as c_int,
474 KERN_PROC_PATHNAME as c_int, -1 as c_int];
476 sysctl(vec::raw::to_ptr(mib), mib.len() as ::libc::c_uint,
477 buf as *mut c_void, &mut sz, ptr::null(),
478 0u as size_t) == (0 as c_int)
483 #[cfg(target_os = "linux")]
484 #[cfg(target_os = "android")]
485 fn load_self() -> Option<~str> {
486 #[fixed_stack_segment]; #[inline(never)];
488 use libc::funcs::posix01::unistd::readlink;
490 let mut path = [0 as c_char, .. TMPBUF_SZ];
492 do path.as_mut_buf |buf, len| {
493 let len = do "/proc/self/exe".with_c_str |proc_self_buf| {
494 readlink(proc_self_buf, buf, len as size_t) as uint
500 Some(str::raw::from_buf_len(buf as *u8, len))
506 #[cfg(target_os = "macos")]
507 fn load_self() -> Option<~str> {
508 #[fixed_stack_segment]; #[inline(never)];
510 do fill_charp_buf() |buf, sz| {
511 let mut sz = sz as u32;
512 libc::funcs::extra::_NSGetExecutablePath(
513 buf, &mut sz) == (0 as c_int)
519 fn load_self() -> Option<~str> {
520 #[fixed_stack_segment]; #[inline(never)];
522 use os::win32::fill_utf16_buf_and_decode;
523 do fill_utf16_buf_and_decode() |buf, sz| {
524 libc::GetModuleFileNameW(0u as libc::DWORD, buf, sz)
529 load_self().map_move(|path| Path(path).dir_path())
534 * Returns the path to the user's home directory, if known.
536 * On Unix, returns the value of the 'HOME' environment variable if it is set
537 * and not equal to the empty string.
539 * On Windows, returns the value of the 'HOME' environment variable if it is
540 * set and not equal to the empty string. Otherwise, returns the value of the
541 * 'USERPROFILE' environment variable if it is set and not equal to the empty
544 * Otherwise, homedir returns option::none.
546 pub fn homedir() -> Option<Path> {
547 return match getenv("HOME") {
548 Some(ref p) => if !p.is_empty() {
557 fn secondary() -> Option<Path> {
562 fn secondary() -> Option<Path> {
563 do getenv("USERPROFILE").and_then |p| {
574 * Returns the path to a temporary directory.
576 * On Unix, returns the value of the 'TMPDIR' environment variable if it is
577 * set and non-empty and '/tmp' otherwise.
578 * On Android, there is no global temporary folder (it is usually allocated
579 * per-app), hence returns '/data/tmp' which is commonly used.
581 * On Windows, returns the value of, in order, the 'TMP', 'TEMP',
582 * 'USERPROFILE' environment variable if any are set and not the empty
583 * string. Otherwise, tmpdir returns the path to the Windows directory.
585 pub fn tmpdir() -> Path {
588 fn getenv_nonempty(v: &str) -> Option<Path> {
601 fn lookup() -> Path {
602 if cfg!(target_os = "android") {
605 getenv_nonempty("TMPDIR").unwrap_or(Path("/tmp"))
610 fn lookup() -> Path {
611 getenv_nonempty("TMP").or(
612 getenv_nonempty("TEMP").or(
613 getenv_nonempty("USERPROFILE").or(
614 getenv_nonempty("WINDIR")))).unwrap_or(Path("C:\\Windows"))
618 /// Recursively walk a directory structure
619 pub fn walk_dir(p: &Path, f: &fn(&Path) -> bool) -> bool {
621 r.iter().advance(|q| {
622 let path = &p.push(*q);
623 f(path) && (!path_is_dir(path) || walk_dir(path, |p| f(p)))
627 /// Indicates whether a path represents a directory
628 pub fn path_is_dir(p: &Path) -> bool {
629 #[fixed_stack_segment]; #[inline(never)];
631 do p.with_c_str |buf| {
632 rustrt::rust_path_is_dir(buf) != 0 as c_int
637 /// Indicates whether a path exists
638 pub fn path_exists(p: &Path) -> bool {
639 #[fixed_stack_segment]; #[inline(never)];
641 do p.with_c_str |buf| {
642 rustrt::rust_path_exists(buf) != 0 as c_int
648 * Convert a relative path to an absolute path
650 * If the given path is relative, return it prepended with the current working
651 * directory. If the given path is already an absolute path, return it
654 // NB: this is here rather than in path because it is a form of environment
655 // querying; what it does depends on the process working directory, not just
657 pub fn make_absolute(p: &Path) -> Path {
661 getcwd().push_many(p.components)
666 /// Creates a directory at the specified path
667 pub fn make_dir(p: &Path, mode: c_int) -> bool {
668 return mkdir(p, mode);
671 fn mkdir(p: &Path, _mode: c_int) -> bool {
672 #[fixed_stack_segment]; #[inline(never)];
674 use os::win32::as_utf16_p;
675 // FIXME: turn mode into something useful? #2623
676 do as_utf16_p(p.to_str()) |buf| {
677 libc::CreateDirectoryW(buf, ptr::mut_null())
684 fn mkdir(p: &Path, mode: c_int) -> bool {
685 #[fixed_stack_segment]; #[inline(never)];
686 do p.with_c_str |buf| {
688 libc::mkdir(buf, mode as libc::mode_t) == (0 as c_int)
694 /// Creates a directory with a given mode.
695 /// Returns true iff creation
696 /// succeeded. Also creates all intermediate subdirectories
697 /// if they don't already exist, giving all of them the same mode.
699 // tjc: if directory exists but with different permissions,
700 // should we return false?
701 pub fn mkdir_recursive(p: &Path, mode: c_int) -> bool {
705 else if p.components.is_empty() {
708 else if p.components.len() == 1 {
709 // No parent directories to create
710 path_is_dir(p) || make_dir(p, mode)
713 mkdir_recursive(&p.pop(), mode) && make_dir(p, mode)
717 /// Lists the contents of a directory
718 pub fn list_dir(p: &Path) -> ~[~str] {
719 if p.components.is_empty() && !p.is_absolute() {
720 // Not sure what the right behavior is here, but this
721 // prevents a bounds check failure later
725 #[cfg(target_os = "linux")]
726 #[cfg(target_os = "android")]
727 #[cfg(target_os = "freebsd")]
728 #[cfg(target_os = "macos")]
729 unsafe fn get_list(p: &Path) -> ~[~str] {
730 #[fixed_stack_segment]; #[inline(never)];
731 use libc::{dirent_t};
732 use libc::{opendir, readdir, closedir};
734 fn rust_list_dir_val(ptr: *dirent_t) -> *libc::c_char;
736 let mut strings = ~[];
737 debug!("os::list_dir -- BEFORE OPENDIR");
739 let dir_ptr = do p.with_c_str |buf| {
743 if (dir_ptr as uint != 0) {
744 debug!("os::list_dir -- opendir() SUCCESS");
745 let mut entry_ptr = readdir(dir_ptr);
746 while (entry_ptr as uint != 0) {
747 strings.push(str::raw::from_c_str(rust_list_dir_val(
749 entry_ptr = readdir(dir_ptr);
754 debug!("os::list_dir -- opendir() FAILURE");
757 "os::list_dir -- AFTER -- #: %?",
762 unsafe fn get_list(p: &Path) -> ~[~str] {
763 #[fixed_stack_segment]; #[inline(never)];
764 use libc::consts::os::extra::INVALID_HANDLE_VALUE;
765 use libc::{wcslen, free};
766 use libc::funcs::extra::kernel32::{
771 use libc::types::os::arch::extra::HANDLE;
775 use rt::global_heap::malloc_raw;
779 fn rust_list_dir_wfd_size() -> libc::size_t;
780 fn rust_list_dir_wfd_fp_buf(wfd: *libc::c_void) -> *u16;
782 fn star(p: &Path) -> Path { p.push("*") }
783 do as_utf16_p(star(p).to_str()) |path_ptr| {
784 let mut strings = ~[];
785 let wfd_ptr = malloc_raw(rust_list_dir_wfd_size() as uint);
786 let find_handle = FindFirstFileW(path_ptr, wfd_ptr as HANDLE);
787 if find_handle as libc::c_int != INVALID_HANDLE_VALUE {
788 let mut more_files = 1 as libc::c_int;
789 while more_files != 0 {
790 let fp_buf = rust_list_dir_wfd_fp_buf(wfd_ptr);
791 if fp_buf as uint == 0 {
792 fail!("os::list_dir() failure: got null ptr from wfd");
795 let fp_vec = vec::from_buf(
796 fp_buf, wcslen(fp_buf) as uint);
797 let fp_str = str::from_utf16(fp_vec);
798 strings.push(fp_str);
800 more_files = FindNextFileW(find_handle, wfd_ptr as HANDLE);
802 FindClose(find_handle);
808 do get_list(p).move_iter().filter |filename| {
809 "." != *filename && ".." != *filename
815 * Lists the contents of a directory
817 * This version prepends each entry with the directory.
819 pub fn list_dir_path(p: &Path) -> ~[Path] {
820 list_dir(p).map(|f| p.push(*f))
823 /// Removes a directory at the specified path, after removing
824 /// all its contents. Use carefully!
825 pub fn remove_dir_recursive(p: &Path) -> bool {
826 let mut error_happened = false;
827 do walk_dir(p) |inner| {
829 if path_is_dir(inner) {
830 if !remove_dir_recursive(inner) {
831 error_happened = true;
835 if !remove_file(inner) {
836 error_happened = true;
842 // Directory should now be empty
843 !error_happened && remove_dir(p)
846 /// Removes a directory at the specified path
847 pub fn remove_dir(p: &Path) -> bool {
851 fn rmdir(p: &Path) -> bool {
852 #[fixed_stack_segment]; #[inline(never)];
854 use os::win32::as_utf16_p;
855 return do as_utf16_p(p.to_str()) |buf| {
856 libc::RemoveDirectoryW(buf) != (0 as libc::BOOL)
862 fn rmdir(p: &Path) -> bool {
863 #[fixed_stack_segment]; #[inline(never)];
864 do p.with_c_str |buf| {
866 libc::rmdir(buf) == (0 as c_int)
872 /// Changes the current working directory to the specified path, returning
873 /// whether the change was completed successfully or not.
874 pub fn change_dir(p: &Path) -> bool {
878 fn chdir(p: &Path) -> bool {
879 #[fixed_stack_segment]; #[inline(never)];
881 use os::win32::as_utf16_p;
882 return do as_utf16_p(p.to_str()) |buf| {
883 libc::SetCurrentDirectoryW(buf) != (0 as libc::BOOL)
889 fn chdir(p: &Path) -> bool {
890 #[fixed_stack_segment]; #[inline(never)];
891 do p.with_c_str |buf| {
893 libc::chdir(buf) == (0 as c_int)
899 /// Copies a file from one location to another
900 pub fn copy_file(from: &Path, to: &Path) -> bool {
901 return do_copy_file(from, to);
904 fn do_copy_file(from: &Path, to: &Path) -> bool {
905 #[fixed_stack_segment]; #[inline(never)];
907 use os::win32::as_utf16_p;
908 return do as_utf16_p(from.to_str()) |fromp| {
909 do as_utf16_p(to.to_str()) |top| {
910 libc::CopyFileW(fromp, top, (0 as libc::BOOL)) !=
918 fn do_copy_file(from: &Path, to: &Path) -> bool {
919 #[fixed_stack_segment]; #[inline(never)];
921 let istream = do from.with_c_str |fromp| {
922 do "rb".with_c_str |modebuf| {
923 libc::fopen(fromp, modebuf)
926 if istream as uint == 0u {
929 // Preserve permissions
930 let from_mode = from.get_mode().expect("copy_file: couldn't get permissions \
933 let ostream = do to.with_c_str |top| {
934 do "w+b".with_c_str |modebuf| {
935 libc::fopen(top, modebuf)
938 if ostream as uint == 0u {
943 let mut buf = vec::with_capacity::<u8>(bufsize);
944 let mut done = false;
947 do buf.as_mut_buf |b, _sz| {
948 let nread = libc::fread(b as *mut c_void, 1u as size_t,
951 if nread > 0 as size_t {
952 if libc::fwrite(b as *c_void, 1u as size_t, nread,
965 // Give the new file the old file's permissions
966 if do to.with_c_str |to_buf| {
967 libc::chmod(to_buf, from_mode as libc::mode_t)
969 return false; // should be a condition...
976 /// Deletes an existing file
977 pub fn remove_file(p: &Path) -> bool {
981 fn unlink(p: &Path) -> bool {
982 #[fixed_stack_segment]; #[inline(never)];
984 use os::win32::as_utf16_p;
985 return do as_utf16_p(p.to_str()) |buf| {
986 libc::DeleteFileW(buf) != (0 as libc::BOOL)
992 fn unlink(p: &Path) -> bool {
993 #[fixed_stack_segment]; #[inline(never)];
995 do p.with_c_str |buf| {
996 libc::unlink(buf) == (0 as c_int)
1002 /// Renames an existing file or directory
1003 pub fn rename_file(old: &Path, new: &Path) -> bool {
1004 #[fixed_stack_segment]; #[inline(never)];
1006 do old.with_c_str |old_buf| {
1007 do new.with_c_str |new_buf| {
1008 libc::rename(old_buf, new_buf) == (0 as c_int)
1015 /// Returns the platform-specific value of errno
1016 pub fn errno() -> int {
1017 #[cfg(target_os = "macos")]
1018 #[cfg(target_os = "freebsd")]
1019 fn errno_location() -> *c_int {
1020 #[fixed_stack_segment]; #[inline(never)];
1023 fn __error() -> *c_int;
1030 #[cfg(target_os = "linux")]
1031 #[cfg(target_os = "android")]
1032 fn errno_location() -> *c_int {
1033 #[fixed_stack_segment]; #[inline(never)];
1036 fn __errno_location() -> *c_int;
1044 (*errno_location()) as int
1049 /// Returns the platform-specific value of errno
1050 pub fn errno() -> uint {
1051 #[fixed_stack_segment]; #[inline(never)];
1052 use libc::types::os::arch::extra::DWORD;
1054 #[cfg(target_arch = "x86")]
1055 #[link_name = "kernel32"]
1058 fn GetLastError() -> DWORD;
1061 #[cfg(target_arch = "x86_64")]
1062 #[link_name = "kernel32"]
1064 fn GetLastError() -> DWORD;
1068 GetLastError() as uint
1072 /// Get a string representing the platform-dependent last error
1073 pub fn last_os_error() -> ~str {
1075 fn strerror() -> ~str {
1076 #[cfg(target_os = "macos")]
1077 #[cfg(target_os = "android")]
1078 #[cfg(target_os = "freebsd")]
1079 fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: size_t)
1081 #[fixed_stack_segment]; #[inline(never)];
1085 fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: size_t)
1089 strerror_r(errnum, buf, buflen)
1093 // GNU libc provides a non-compliant version of strerror_r by default
1094 // and requires macros to instead use the POSIX compliant variant.
1095 // So we just use __xpg_strerror_r which is always POSIX compliant
1096 #[cfg(target_os = "linux")]
1097 fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: size_t) -> c_int {
1098 #[fixed_stack_segment]; #[inline(never)];
1101 fn __xpg_strerror_r(errnum: c_int,
1107 __xpg_strerror_r(errnum, buf, buflen)
1111 let mut buf = [0 as c_char, ..TMPBUF_SZ];
1113 do buf.as_mut_buf |buf, len| {
1115 if strerror_r(errno() as c_int, buf, len as size_t) < 0 {
1116 fail!("strerror_r failure");
1119 str::raw::from_c_str(buf as *c_char)
1125 fn strerror() -> ~str {
1126 #[fixed_stack_segment]; #[inline(never)];
1128 use libc::types::os::arch::extra::DWORD;
1129 use libc::types::os::arch::extra::LPWSTR;
1130 use libc::types::os::arch::extra::LPVOID;
1131 use libc::types::os::arch::extra::WCHAR;
1133 #[cfg(target_arch = "x86")]
1134 #[link_name = "kernel32"]
1137 fn FormatMessageW(flags: DWORD,
1147 #[cfg(target_arch = "x86_64")]
1148 #[link_name = "kernel32"]
1150 fn FormatMessageW(flags: DWORD,
1160 static FORMAT_MESSAGE_FROM_SYSTEM: DWORD = 0x00001000;
1161 static FORMAT_MESSAGE_IGNORE_INSERTS: DWORD = 0x00000200;
1163 // This value is calculated from the macro
1164 // MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT)
1165 let langId = 0x0800 as DWORD;
1166 let err = errno() as DWORD;
1168 let mut buf = [0 as WCHAR, ..TMPBUF_SZ];
1171 do buf.as_mut_buf |buf, len| {
1172 let res = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
1173 FORMAT_MESSAGE_IGNORE_INSERTS,
1181 fail!("[%?] FormatMessage failure", errno());
1185 str::from_utf16(buf)
1193 * Sets the process exit code
1195 * Sets the exit code returned by the process if all supervised tasks
1196 * terminate successfully (without failing). If the current root task fails
1197 * and is supervised by the scheduler then any user-specified exit status is
1198 * ignored and the process exits with the default failure status
1200 pub fn set_exit_status(code: int) {
1202 rt::util::set_exit_status(code);
1205 unsafe fn load_argc_and_argv(argc: c_int, argv: **c_char) -> ~[~str] {
1207 for i in range(0u, argc as uint) {
1208 args.push(str::raw::from_c_str(*argv.offset(i as int)));
1214 * Returns the command line arguments
1216 * Returns a list of the command line arguments.
1218 #[cfg(target_os = "macos")]
1219 fn real_args() -> ~[~str] {
1220 #[fixed_stack_segment]; #[inline(never)];
1223 let (argc, argv) = (*_NSGetArgc() as c_int,
1224 *_NSGetArgv() as **c_char);
1225 load_argc_and_argv(argc, argv)
1229 #[cfg(target_os = "linux")]
1230 #[cfg(target_os = "android")]
1231 #[cfg(target_os = "freebsd")]
1232 fn real_args() -> ~[~str] {
1235 match rt::args::clone() {
1237 None => fail!("process arguments not initialized")
1242 fn real_args() -> ~[~str] {
1243 #[fixed_stack_segment]; #[inline(never)];
1245 let mut nArgs: c_int = 0;
1246 let lpArgCount: *mut c_int = &mut nArgs;
1247 let lpCmdLine = unsafe { GetCommandLineW() };
1248 let szArgList = unsafe { CommandLineToArgvW(lpCmdLine, lpArgCount) };
1251 for i in range(0u, nArgs as uint) {
1253 // Determine the length of this argument.
1254 let ptr = *szArgList.offset(i as int);
1256 while *ptr.offset(len as int) != 0 { len += 1; }
1258 // Push it onto the list.
1259 args.push(vec::raw::buf_as_slice(ptr, len,
1265 LocalFree(szArgList as *c_void);
1271 type LPCWSTR = *u16;
1273 #[cfg(windows, target_arch = "x86")]
1274 #[link_name="kernel32"]
1277 fn GetCommandLineW() -> LPCWSTR;
1278 fn LocalFree(ptr: *c_void);
1281 #[cfg(windows, target_arch = "x86_64")]
1282 #[link_name="kernel32"]
1284 fn GetCommandLineW() -> LPCWSTR;
1285 fn LocalFree(ptr: *c_void);
1288 #[cfg(windows, target_arch = "x86")]
1289 #[link_name="shell32"]
1292 fn CommandLineToArgvW(lpCmdLine: LPCWSTR, pNumArgs: *mut c_int) -> **u16;
1295 #[cfg(windows, target_arch = "x86_64")]
1296 #[link_name="shell32"]
1298 fn CommandLineToArgvW(lpCmdLine: LPCWSTR, pNumArgs: *mut c_int) -> **u16;
1301 struct OverriddenArgs {
1305 /// Returns the arguments which this program was started with (normally passed
1306 /// via the command line).
1307 pub fn args() -> ~[~str] {
1311 #[cfg(target_os = "macos")]
1313 // These functions are in crt_externs.h.
1314 pub fn _NSGetArgc() -> *c_int;
1315 pub fn _NSGetArgv() -> ***c_char;
1318 // Round up `from` to be divisible by `to`
1319 fn round_up(from: uint, to: uint) -> uint {
1320 let r = if from % to == 0 {
1323 from + to - (from % to)
1333 pub fn page_size() -> uint {
1334 #[fixed_stack_segment]; #[inline(never)];
1337 libc::sysconf(libc::_SC_PAGESIZE) as uint
1342 pub fn page_size() -> uint {
1343 #[fixed_stack_segment]; #[inline(never)];
1346 let mut info = libc::SYSTEM_INFO::new();
1347 libc::GetSystemInfo(&mut info);
1349 return info.dwPageSize as uint;
1353 pub struct MemoryMap {
1359 pub enum MemoryMapKind {
1364 pub enum MapOption {
1374 // Linux-specific errors
1380 ErrUnknown(libc::c_int),
1382 // Windows-specific errors
1386 ErrVirtualAlloc(uint),
1387 ErrCreateFileMappingW(uint),
1388 ErrMapViewOfFile(uint)
1391 impl to_str::ToStr for MapError {
1392 fn to_str(&self) -> ~str {
1394 ErrFdNotAvail => ~"fd not available for reading or writing",
1395 ErrInvalidFd => ~"Invalid fd",
1396 ErrUnaligned => ~"Unaligned address, invalid flags, \
1397 negative length or unaligned offset",
1398 ErrNoMapSupport=> ~"File doesn't support mapping",
1399 ErrNoMem => ~"Invalid address, or not enough available memory",
1400 ErrUnknown(code) => fmt!("Unknown error=%?", code),
1401 ErrUnsupProt => ~"Protection mode unsupported",
1402 ErrUnsupOffset => ~"Offset in virtual memory mode is unsupported",
1403 ErrAlreadyExists => ~"File mapping for specified file already exists",
1404 ErrVirtualAlloc(code) => fmt!("VirtualAlloc failure=%?", code),
1405 ErrCreateFileMappingW(code) => fmt!("CreateFileMappingW failure=%?", code),
1406 ErrMapViewOfFile(code) => fmt!("MapViewOfFile failure=%?", code)
1413 pub fn new(min_len: uint, options: ~[MapOption]) -> Result<~MemoryMap, MapError> {
1414 #[fixed_stack_segment]; #[inline(never)];
1418 let mut addr: *c_void = ptr::null();
1419 let mut prot: c_int = 0;
1420 let mut flags: c_int = libc::MAP_PRIVATE;
1421 let mut fd: c_int = -1;
1422 let mut offset: off_t = 0;
1423 let len = round_up(min_len, page_size()) as size_t;
1425 for &o in options.iter() {
1427 MapReadable => { prot |= libc::PROT_READ; },
1428 MapWritable => { prot |= libc::PROT_WRITE; },
1429 MapExecutable => { prot |= libc::PROT_EXEC; },
1431 flags |= libc::MAP_FIXED;
1435 flags |= libc::MAP_FILE;
1438 MapOffset(offset_) => { offset = offset_ as off_t; }
1441 if fd == -1 { flags |= libc::MAP_ANON; }
1444 libc::mmap(addr, len, prot, flags, fd, offset)
1446 if r.equiv(&libc::MAP_FAILED) {
1447 Err(match errno() as c_int {
1448 libc::EACCES => ErrFdNotAvail,
1449 libc::EBADF => ErrInvalidFd,
1450 libc::EINVAL => ErrUnaligned,
1451 libc::ENODEV => ErrNoMapSupport,
1452 libc::ENOMEM => ErrNoMem,
1453 code => ErrUnknown(code)
1462 MapFile(ptr::null())
1468 pub fn granularity() -> uint {
1474 impl Drop for MemoryMap {
1475 fn drop(&mut self) {
1476 #[fixed_stack_segment]; #[inline(never)];
1479 match libc::munmap(self.data as *c_void, self.len) {
1481 -1 => error!(match errno() as c_int {
1482 libc::EINVAL => ~"invalid addr or len",
1483 e => fmt!("unknown errno=%?", e)
1485 r => error!(fmt!("Unexpected result %?", r))
1493 pub fn new(min_len: uint, options: ~[MapOption]) -> Result<~MemoryMap, MapError> {
1494 #[fixed_stack_segment]; #[inline(never)];
1496 use libc::types::os::arch::extra::{LPVOID, DWORD, SIZE_T, HANDLE};
1498 let mut lpAddress: LPVOID = ptr::mut_null();
1499 let mut readable = false;
1500 let mut writable = false;
1501 let mut executable = false;
1502 let mut fd: c_int = -1;
1503 let mut offset: uint = 0;
1504 let len = round_up(min_len, page_size()) as SIZE_T;
1506 for &o in options.iter() {
1508 MapReadable => { readable = true; },
1509 MapWritable => { writable = true; },
1510 MapExecutable => { executable = true; }
1511 MapAddr(addr_) => { lpAddress = addr_ as LPVOID; },
1512 MapFd(fd_) => { fd = fd_; },
1513 MapOffset(offset_) => { offset = offset_; }
1517 let flProtect = match (executable, readable, writable) {
1518 (false, false, false) if fd == -1 => libc::PAGE_NOACCESS,
1519 (false, true, false) => libc::PAGE_READONLY,
1520 (false, true, true) => libc::PAGE_READWRITE,
1521 (true, false, false) if fd == -1 => libc::PAGE_EXECUTE,
1522 (true, true, false) => libc::PAGE_EXECUTE_READ,
1523 (true, true, true) => libc::PAGE_EXECUTE_READWRITE,
1524 _ => return Err(ErrUnsupProt)
1529 return Err(ErrUnsupOffset);
1532 libc::VirtualAlloc(lpAddress,
1534 libc::MEM_COMMIT | libc::MEM_RESERVE,
1538 0 => Err(ErrVirtualAlloc(errno())),
1539 _ => Ok(~MemoryMap {
1546 let dwDesiredAccess = match (executable, readable, writable) {
1547 (false, true, false) => libc::FILE_MAP_READ,
1548 (false, true, true) => libc::FILE_MAP_WRITE,
1549 (true, true, false) => libc::FILE_MAP_READ | libc::FILE_MAP_EXECUTE,
1550 (true, true, true) => libc::FILE_MAP_WRITE | libc::FILE_MAP_EXECUTE,
1551 _ => return Err(ErrUnsupProt) // Actually, because of the check above,
1552 // we should never get here.
1555 let hFile = libc::get_osfhandle(fd) as HANDLE;
1556 let mapping = libc::CreateFileMappingW(hFile,
1562 if mapping == ptr::mut_null() {
1563 return Err(ErrCreateFileMappingW(errno()));
1565 if errno() as c_int == libc::ERROR_ALREADY_EXISTS {
1566 return Err(ErrAlreadyExists);
1568 let r = libc::MapViewOfFile(mapping,
1570 ((len as u64) >> 32) as DWORD,
1571 (offset & 0xffff_ffff) as DWORD,
1574 0 => Err(ErrMapViewOfFile(errno())),
1575 _ => Ok(~MemoryMap {
1578 kind: MapFile(mapping as *c_void)
1585 /// Granularity of MapAddr() and MapOffset() parameter values.
1586 /// This may be greater than the value returned by page_size().
1587 pub fn granularity() -> uint {
1588 #[fixed_stack_segment]; #[inline(never)];
1591 let mut info = libc::SYSTEM_INFO::new();
1592 libc::GetSystemInfo(&mut info);
1594 return info.dwAllocationGranularity as uint;
1600 impl Drop for MemoryMap {
1601 fn drop(&mut self) {
1602 #[fixed_stack_segment]; #[inline(never)];
1604 use libc::types::os::arch::extra::{LPCVOID, HANDLE};
1605 use libc::consts::os::extra::FALSE;
1610 if libc::VirtualFree(self.data as *mut c_void,
1612 libc::MEM_RELEASE) == FALSE {
1613 error!(fmt!("VirtualFree failed: %?", errno()));
1616 MapFile(mapping) => {
1617 if libc::UnmapViewOfFile(self.data as LPCVOID) == FALSE {
1618 error!(fmt!("UnmapViewOfFile failed: %?", errno()));
1620 if libc::CloseHandle(mapping as HANDLE) == FALSE {
1621 error!(fmt!("CloseHandle failed: %?", errno()));
1632 pub use os::consts::unix::*;
1635 pub use os::consts::windows::*;
1637 #[cfg(target_os = "macos")]
1638 pub use os::consts::macos::*;
1640 #[cfg(target_os = "freebsd")]
1641 pub use os::consts::freebsd::*;
1643 #[cfg(target_os = "linux")]
1644 pub use os::consts::linux::*;
1646 #[cfg(target_os = "android")]
1647 pub use os::consts::android::*;
1649 #[cfg(target_os = "win32")]
1650 pub use os::consts::win32::*;
1652 #[cfg(target_arch = "x86")]
1653 pub use os::consts::x86::*;
1655 #[cfg(target_arch = "x86_64")]
1656 pub use os::consts::x86_64::*;
1658 #[cfg(target_arch = "arm")]
1659 pub use os::consts::arm::*;
1661 #[cfg(target_arch = "mips")]
1662 use os::consts::mips::*;
1665 pub static FAMILY: &'static str = "unix";
1669 pub static FAMILY: &'static str = "windows";
1673 pub static SYSNAME: &'static str = "macos";
1674 pub static DLL_PREFIX: &'static str = "lib";
1675 pub static DLL_SUFFIX: &'static str = ".dylib";
1676 pub static EXE_SUFFIX: &'static str = "";
1680 pub static SYSNAME: &'static str = "freebsd";
1681 pub static DLL_PREFIX: &'static str = "lib";
1682 pub static DLL_SUFFIX: &'static str = ".so";
1683 pub static EXE_SUFFIX: &'static str = "";
1687 pub static SYSNAME: &'static str = "linux";
1688 pub static DLL_PREFIX: &'static str = "lib";
1689 pub static DLL_SUFFIX: &'static str = ".so";
1690 pub static EXE_SUFFIX: &'static str = "";
1694 pub static SYSNAME: &'static str = "android";
1695 pub static DLL_PREFIX: &'static str = "lib";
1696 pub static DLL_SUFFIX: &'static str = ".so";
1697 pub static EXE_SUFFIX: &'static str = "";
1701 pub static SYSNAME: &'static str = "win32";
1702 pub static DLL_PREFIX: &'static str = "";
1703 pub static DLL_SUFFIX: &'static str = ".dll";
1704 pub static EXE_SUFFIX: &'static str = ".exe";
1709 pub static ARCH: &'static str = "x86";
1712 pub static ARCH: &'static str = "x86_64";
1715 pub static ARCH: &'static str = "arm";
1718 pub static ARCH: &'static str = "mips";
1725 use libc::{c_int, c_void, size_t};
1729 use os::{env, getcwd, getenv, make_absolute, args};
1730 use os::{remove_file, setenv, unsetenv};
1737 use libc::consts::os::posix88::{S_IRUSR, S_IWUSR, S_IXUSR};
1741 pub fn last_os_error() {
1742 debug!(os::last_os_error());
1746 pub fn test_args() {
1748 assert!(a.len() >= 1);
1751 fn make_rand_name() -> ~str {
1752 let mut rng = rand::rng();
1753 let n = ~"TEST" + rng.gen_str(10u);
1754 assert!(getenv(n).is_none());
1760 let n = make_rand_name();
1762 assert_eq!(getenv(n), option::Some(~"VALUE"));
1766 fn test_unsetenv() {
1767 let n = make_rand_name();
1770 assert_eq!(getenv(n), option::None);
1775 fn test_setenv_overwrite() {
1776 let n = make_rand_name();
1779 assert_eq!(getenv(n), option::Some(~"2"));
1781 assert_eq!(getenv(n), option::Some(~""));
1784 // Windows GetEnvironmentVariable requires some extra work to make sure
1785 // the buffer the variable is copied into is the right size
1788 fn test_getenv_big() {
1792 s = s + "aaaaaaaaaa";
1795 let n = make_rand_name();
1798 assert_eq!(getenv(n), option::Some(s));
1802 fn test_self_exe_path() {
1803 let path = os::self_exe_path();
1804 assert!(path.is_some());
1805 let path = path.unwrap();
1806 debug!(path.clone());
1808 // Hard to test this function
1809 assert!(path.is_absolute);
1814 fn test_env_getenv() {
1816 assert!(e.len() > 0u);
1818 let (n, v) = (*p).clone();
1821 // MingW seems to set some funky environment variables like
1822 // "=C:=C:\MinGW\msys\1.0\bin" and "!::=::\" that are returned
1823 // from env() but not visible from getenv().
1824 assert!(v2.is_none() || v2 == option::Some(v));
1829 fn test_env_setenv() {
1830 let n = make_rand_name();
1834 assert!(!e.contains(&(n.clone(), ~"VALUE")));
1837 assert!(e.contains(&(n, ~"VALUE")));
1842 assert!((!Path("test-path").is_absolute));
1844 debug!("Current working directory: %s", getcwd().to_str());
1846 debug!(make_absolute(&Path("test-path")));
1847 debug!(make_absolute(&Path("/usr/bin")));
1853 let oldhome = getenv("HOME");
1855 setenv("HOME", "/home/MountainView");
1856 assert_eq!(os::homedir(), Some(Path("/home/MountainView")));
1859 assert!(os::homedir().is_none());
1861 for s in oldhome.iter() { setenv("HOME", *s) }
1868 let oldhome = getenv("HOME");
1869 let olduserprofile = getenv("USERPROFILE");
1872 setenv("USERPROFILE", "");
1874 assert!(os::homedir().is_none());
1876 setenv("HOME", "/home/MountainView");
1877 assert_eq!(os::homedir(), Some(Path("/home/MountainView")));
1881 setenv("USERPROFILE", "/home/MountainView");
1882 assert_eq!(os::homedir(), Some(Path("/home/MountainView")));
1884 setenv("HOME", "/home/MountainView");
1885 setenv("USERPROFILE", "/home/PaloAlto");
1886 assert_eq!(os::homedir(), Some(Path("/home/MountainView")));
1888 for s in oldhome.iter() { setenv("HOME", *s) }
1889 for s in olduserprofile.iter() { setenv("USERPROFILE", *s) }
1894 assert!(!os::tmpdir().to_str().is_empty());
1899 fn test_list_dir_no_invalid_memory_access() {
1900 os::list_dir(&Path("."));
1905 let dirs = os::list_dir(&Path("."));
1906 // Just assuming that we've got some contents in the current directory
1907 assert!(dirs.len() > 0u);
1909 for dir in dirs.iter() {
1910 debug!((*dir).clone());
1915 fn list_dir_empty_path() {
1916 let dirs = os::list_dir(&Path(""));
1917 assert!(dirs.is_empty());
1921 #[cfg(not(windows))]
1922 fn list_dir_root() {
1923 let dirs = os::list_dir(&Path("/"));
1924 assert!(dirs.len() > 1);
1928 fn list_dir_root() {
1929 let dirs = os::list_dir(&Path("C:\\"));
1930 assert!(dirs.len() > 1);
1936 assert!((os::path_is_dir(&Path("."))));
1937 assert!((!os::path_is_dir(&Path("test/stdtest/fs.rs"))));
1942 assert!((os::path_exists(&Path("."))));
1943 assert!((!os::path_exists(&Path(
1944 "test/nonexistent-bogus-path"))));
1948 fn copy_file_does_not_exist() {
1949 assert!(!os::copy_file(&Path("test/nonexistent-bogus-path"),
1950 &Path("test/other-bogus-path")));
1951 assert!(!os::path_exists(&Path("test/other-bogus-path")));
1956 #[fixed_stack_segment]; #[inline(never)];
1959 let tempdir = getcwd(); // would like to use $TMPDIR,
1960 // doesn't seem to work on Linux
1961 assert!((tempdir.to_str().len() > 0u));
1962 let input = tempdir.push("in.txt");
1963 let out = tempdir.push("out.txt");
1965 /* Write the temp input file */
1966 let ostream = do input.with_c_str |fromp| {
1967 do "w+b".with_c_str |modebuf| {
1968 libc::fopen(fromp, modebuf)
1971 assert!((ostream as uint != 0u));
1973 do "hello".with_c_str |buf| {
1974 let write_len = libc::fwrite(buf as *c_void,
1976 (s.len() + 1u) as size_t,
1978 assert_eq!(write_len, (s.len() + 1) as size_t)
1980 assert_eq!(libc::fclose(ostream), (0u as c_int));
1981 let in_mode = input.get_mode();
1982 let rs = os::copy_file(&input, &out);
1983 if (!os::path_exists(&input)) {
1984 fail!("%s doesn't exist", input.to_str());
1987 let rslt = run::process_status("diff", [input.to_str(), out.to_str()]);
1988 assert_eq!(rslt, 0);
1989 assert_eq!(out.get_mode(), in_mode);
1990 assert!((remove_file(&input)));
1991 assert!((remove_file(&out)));
1996 fn recursive_mkdir_slash() {
1997 let path = Path("/");
1998 assert!(os::mkdir_recursive(&path, (S_IRUSR | S_IWUSR | S_IXUSR) as i32));
2002 fn recursive_mkdir_empty() {
2003 let path = Path("");
2004 assert!(!os::mkdir_recursive(&path, (S_IRUSR | S_IWUSR | S_IXUSR) as i32));
2008 fn memory_map_rw() {
2009 use result::{Ok, Err};
2011 let chunk = match os::MemoryMap::new(16, ~[
2016 Err(msg) => fail!(msg.to_str())
2018 assert!(chunk.len >= 16);
2022 assert!(*chunk.data == 0xBE);
2027 fn memory_map_file() {
2028 #[fixed_stack_segment]; #[inline(never)];
2030 use result::{Ok, Err};
2035 #[fixed_stack_segment]
2037 fn lseek_(fd: c_int, size: uint) {
2039 assert!(lseek(fd, size as off_t, SEEK_SET) == size as off_t);
2043 #[fixed_stack_segment]
2045 fn lseek_(fd: c_int, size: uint) {
2047 assert!(lseek(fd, size as c_long, SEEK_SET) == size as c_long);
2051 let path = tmpdir().push("mmap_file.tmp");
2052 let size = MemoryMap::granularity() * 2;
2056 let fd = do path.with_c_str |path| {
2057 open(path, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR)
2060 do "x".with_c_str |x| {
2061 assert!(write(fd, x as *c_void, 1) == 1);
2065 let chunk = match MemoryMap::new(size / 2, ~[
2072 Err(msg) => fail!(msg.to_str())
2074 assert!(chunk.len > 0);
2078 assert!(*chunk.data == 0xbe);
2083 // More recursive_mkdir tests are in extra::tempfile