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)];
34 use container::Container;
37 use libc::{c_char, c_void, c_int, size_t};
38 use option::{Some, None};
44 use unstable::finally::Finally;
46 pub use os::consts::*;
48 /// Delegates to the libc close() function, returning the same return value.
49 pub fn close(fd: c_int) -> c_int {
55 pub static TMPBUF_SZ : uint = 1000u;
56 static BUF_BYTES : uint = 2048u;
59 pub fn getcwd() -> Path {
60 let mut buf = [0 as libc::c_char, ..BUF_BYTES];
61 buf.as_mut_buf(|buf, len| {
63 if libc::getcwd(buf, len as size_t).is_null() {
67 Path::new(CString::new(buf as *c_char, false))
73 pub fn getcwd() -> Path {
75 use libc::GetCurrentDirectoryW;
76 let mut buf = [0 as u16, ..BUF_BYTES];
77 buf.as_mut_buf(|buf, len| {
79 if libc::GetCurrentDirectoryW(len as DWORD, buf) == 0 as DWORD {
84 Path::new(str::from_utf16(buf))
92 use option::{None, Option};
95 use libc::types::os::arch::extra::DWORD;
97 pub fn fill_utf16_buf_and_decode(f: |*mut u16, DWORD| -> DWORD)
101 let mut n = TMPBUF_SZ as DWORD;
103 let mut done = false;
105 let mut k: DWORD = 0;
106 let mut buf = vec::from_elem(n as uint, 0u16);
107 buf.as_mut_buf(|b, _sz| {
108 k = f(b, TMPBUF_SZ as DWORD);
109 if k == (0 as DWORD) {
112 libc::GetLastError() ==
113 libc::ERROR_INSUFFICIENT_BUFFER as DWORD) {
120 let sub = buf.slice(0, k as uint);
121 res = option::Some(str::from_utf16(sub));
128 pub fn as_utf16_p<T>(s: &str, f: |*u16| -> T) -> T {
129 let mut t = s.to_utf16();
130 // Null terminate before passing on.
132 t.as_imm_buf(|buf, _len| f(buf))
137 Accessing environment variables is not generally threadsafe.
138 Serialize access through a global lock.
140 fn with_env_lock<T>(f: || -> T) -> T {
141 use unstable::mutex::{Mutex, MUTEX_INIT};
142 use unstable::finally::Finally;
144 static mut lock: Mutex = MUTEX_INIT;
150 }).finally(|| lock.unlock());
154 /// Returns a vector of (variable, value) pairs for all the environment
155 /// variables of the current process.
156 pub fn env() -> ~[(~str,~str)] {
159 unsafe fn get_env_pairs() -> ~[~str] {
163 use libc::funcs::extra::kernel32::{
164 GetEnvironmentStringsA,
165 FreeEnvironmentStringsA
167 let ch = GetEnvironmentStringsA();
168 if (ch as uint == 0) {
169 fail!("os::env() failure getting env string from OS: {}",
170 os::last_os_error());
172 let mut result = ~[];
173 c_str::from_c_multistring(ch as *libc::c_char, None, |cstr| {
174 result.push(cstr.as_str().unwrap().to_owned());
176 FreeEnvironmentStringsA(ch);
180 unsafe fn get_env_pairs() -> ~[~str] {
182 fn rust_env_pairs() -> **libc::c_char;
184 let environ = rust_env_pairs();
185 if (environ as uint == 0) {
186 fail!("os::env() failure getting env string from OS: {}",
187 os::last_os_error());
189 let mut result = ~[];
190 ptr::array_each(environ, |e| {
191 let env_pair = str::raw::from_c_str(e);
192 debug!("get_env_pairs: {}", env_pair);
193 result.push(env_pair);
198 fn env_convert(input: ~[~str]) -> ~[(~str, ~str)] {
200 for p in input.iter() {
201 let vs: ~[&str] = p.splitn('=', 1).collect();
202 debug!("splitting: len: {}", vs.len());
203 assert_eq!(vs.len(), 2);
204 pairs.push((vs[0].to_owned(), vs[1].to_owned()));
209 let unparsed_environ = get_env_pairs();
210 env_convert(unparsed_environ)
216 /// Fetches the environment variable `n` from the current process, returning
217 /// None if the variable isn't set.
218 pub fn getenv(n: &str) -> Option<~str> {
221 let s = n.with_c_str(|buf| libc::getenv(buf));
225 Some(str::raw::from_c_str(s))
232 /// Fetches the environment variable `n` from the current process, returning
233 /// None if the variable isn't set.
234 pub fn getenv(n: &str) -> Option<~str> {
237 use os::win32::{as_utf16_p, fill_utf16_buf_and_decode};
239 fill_utf16_buf_and_decode(|buf, sz| {
240 libc::GetEnvironmentVariableW(u, buf, sz)
249 /// Sets the environment variable `n` to the value `v` for the currently running
251 pub fn setenv(n: &str, v: &str) {
254 n.with_c_str(|nbuf| {
255 v.with_c_str(|vbuf| {
256 libc::funcs::posix01::unistd::setenv(nbuf, vbuf, 1);
265 /// Sets the environment variable `n` to the value `v` for the currently running
267 pub fn setenv(n: &str, v: &str) {
270 use os::win32::as_utf16_p;
271 as_utf16_p(n, |nbuf| {
272 as_utf16_p(v, |vbuf| {
273 libc::SetEnvironmentVariableW(nbuf, vbuf);
280 /// Remove a variable from the environment entirely
281 pub fn unsetenv(n: &str) {
283 fn _unsetenv(n: &str) {
286 n.with_c_str(|nbuf| {
287 libc::funcs::posix01::unistd::unsetenv(nbuf);
293 fn _unsetenv(n: &str) {
296 use os::win32::as_utf16_p;
297 as_utf16_p(n, |nbuf| {
298 libc::SetEnvironmentVariableW(nbuf, ptr::null());
313 pub fn pipe() -> Pipe {
315 let mut fds = Pipe {input: 0 as c_int,
317 assert_eq!(libc::pipe(&mut fds.input), (0 as c_int));
318 return Pipe {input: fds.input, out: fds.out};
323 pub fn pipe() -> Pipe {
325 // Windows pipes work subtly differently than unix pipes, and their
326 // inheritance has to be handled in a different way that I do not
327 // fully understand. Here we explicitly make the pipe non-inheritable,
328 // which means to pass it to a subprocess they need to be duplicated
329 // first, as in std::run.
330 let mut fds = Pipe {input: 0 as c_int,
332 let res = libc::pipe(&mut fds.input, 1024 as ::libc::c_uint,
333 (libc::O_BINARY | libc::O_NOINHERIT) as c_int);
334 assert_eq!(res, 0 as c_int);
335 assert!((fds.input != -1 as c_int && fds.input != 0 as c_int));
336 assert!((fds.out != -1 as c_int && fds.input != 0 as c_int));
337 return Pipe {input: fds.input, out: fds.out};
341 fn dup2(src: c_int, dst: c_int) -> c_int {
347 /// Returns the proper dll filename for the given basename of a file.
348 pub fn dll_filename(base: &str) -> ~str {
349 format!("{}{}{}", DLL_PREFIX, base, DLL_SUFFIX)
352 /// Optionally returns the filesystem path to the current executable which is
353 /// running. If any failure occurs, None is returned.
354 pub fn self_exe_path() -> Option<Path> {
356 #[cfg(target_os = "freebsd")]
357 fn load_self() -> Option<~[u8]> {
359 use libc::funcs::bsd44::*;
360 use libc::consts::os::extra::*;
362 let mib = ~[CTL_KERN as c_int,
364 KERN_PROC_PATHNAME as c_int, -1 as c_int];
365 let mut sz: size_t = 0;
366 let err = sysctl(vec::raw::to_ptr(mib), mib.len() as ::libc::c_uint,
367 ptr::mut_null(), &mut sz, ptr::null(), 0u as size_t);
368 if err != 0 { return None; }
369 if sz == 0 { return None; }
370 let mut v: ~[u8] = vec::with_capacity(sz as uint);
371 let err = v.as_mut_buf(|buf,_| {
372 sysctl(vec::raw::to_ptr(mib), mib.len() as ::libc::c_uint,
373 buf as *mut c_void, &mut sz, ptr::null(), 0u as size_t)
375 if err != 0 { return None; }
376 if sz == 0 { return None; }
377 vec::raw::set_len(&mut v, sz as uint - 1); // chop off trailing NUL
382 #[cfg(target_os = "linux")]
383 #[cfg(target_os = "android")]
384 fn load_self() -> Option<~[u8]> {
387 match io::result(|| io::fs::readlink(&Path::new("/proc/self/exe"))) {
388 Ok(Some(path)) => Some(path.as_vec().to_owned()),
389 Ok(None) | Err(*) => None
393 #[cfg(target_os = "macos")]
394 fn load_self() -> Option<~[u8]> {
396 use libc::funcs::extra::_NSGetExecutablePath;
399 _NSGetExecutablePath(ptr::mut_null(), &mut sz);
400 if sz == 0 { return None; }
401 let mut v: ~[u8] = vec::with_capacity(sz as uint);
402 let err = v.as_mut_buf(|buf, _| {
403 _NSGetExecutablePath(buf as *mut i8, &mut sz)
405 if err != 0 { return None; }
406 vec::raw::set_len(&mut v, sz as uint - 1); // chop off trailing NUL
412 fn load_self() -> Option<~[u8]> {
414 use os::win32::fill_utf16_buf_and_decode;
415 fill_utf16_buf_and_decode(|buf, sz| {
416 libc::GetModuleFileNameW(0u as libc::DWORD, buf, sz)
417 }).map(|s| s.into_bytes())
421 load_self().and_then(|path| Path::new_opt(path).map(|mut p| { p.pop(); p }))
425 * Returns the path to the user's home directory, if known.
427 * On Unix, returns the value of the 'HOME' environment variable if it is set
428 * and not equal to the empty string.
430 * On Windows, returns the value of the 'HOME' environment variable if it is
431 * set and not equal to the empty string. Otherwise, returns the value of the
432 * 'USERPROFILE' environment variable if it is set and not equal to the empty
435 * Otherwise, homedir returns option::none.
437 pub fn homedir() -> Option<Path> {
438 // FIXME (#7188): getenv needs a ~[u8] variant
439 return match getenv("HOME") {
440 Some(ref p) if !p.is_empty() => Path::new_opt(p.as_slice()),
445 fn secondary() -> Option<Path> {
450 fn secondary() -> Option<Path> {
451 getenv("USERPROFILE").and_then(|p| {
462 * Returns the path to a temporary directory.
464 * On Unix, returns the value of the 'TMPDIR' environment variable if it is
465 * set and non-empty and '/tmp' otherwise.
466 * On Android, there is no global temporary folder (it is usually allocated
467 * per-app), hence returns '/data/tmp' which is commonly used.
469 * On Windows, returns the value of, in order, the 'TMP', 'TEMP',
470 * 'USERPROFILE' environment variable if any are set and not the empty
471 * string. Otherwise, tmpdir returns the path to the Windows directory.
473 pub fn tmpdir() -> Path {
476 fn getenv_nonempty(v: &str) -> Option<Path> {
489 fn lookup() -> Path {
490 if cfg!(target_os = "android") {
491 Path::new("/data/tmp")
493 getenv_nonempty("TMPDIR").unwrap_or(Path::new("/tmp"))
498 fn lookup() -> Path {
499 getenv_nonempty("TMP").or(
500 getenv_nonempty("TEMP").or(
501 getenv_nonempty("USERPROFILE").or(
502 getenv_nonempty("WINDIR")))).unwrap_or(Path::new("C:\\Windows"))
507 * Convert a relative path to an absolute path
509 * If the given path is relative, return it prepended with the current working
510 * directory. If the given path is already an absolute path, return it
513 // NB: this is here rather than in path because it is a form of environment
514 // querying; what it does depends on the process working directory, not just
516 pub fn make_absolute(p: &Path) -> Path {
520 let mut ret = getcwd();
526 /// Changes the current working directory to the specified path, returning
527 /// whether the change was completed successfully or not.
528 pub fn change_dir(p: &Path) -> bool {
532 fn chdir(p: &Path) -> bool {
534 use os::win32::as_utf16_p;
535 return as_utf16_p(p.as_str().unwrap(), |buf| {
536 libc::SetCurrentDirectoryW(buf) != (0 as libc::BOOL)
542 fn chdir(p: &Path) -> bool {
545 libc::chdir(buf) == (0 as c_int)
552 /// Returns the platform-specific value of errno
553 pub fn errno() -> int {
554 #[cfg(target_os = "macos")]
555 #[cfg(target_os = "freebsd")]
556 fn errno_location() -> *c_int {
559 fn __error() -> *c_int;
566 #[cfg(target_os = "linux")]
567 #[cfg(target_os = "android")]
568 fn errno_location() -> *c_int {
571 fn __errno_location() -> *c_int;
579 (*errno_location()) as int
584 /// Returns the platform-specific value of errno
585 pub fn errno() -> uint {
586 use libc::types::os::arch::extra::DWORD;
588 #[link_name = "kernel32"]
590 fn GetLastError() -> DWORD;
594 GetLastError() as uint
598 /// Get a string representing the platform-dependent last error
599 pub fn last_os_error() -> ~str {
601 fn strerror() -> ~str {
602 #[cfg(target_os = "macos")]
603 #[cfg(target_os = "android")]
604 #[cfg(target_os = "freebsd")]
605 fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: size_t)
609 fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: size_t)
613 strerror_r(errnum, buf, buflen)
617 // GNU libc provides a non-compliant version of strerror_r by default
618 // and requires macros to instead use the POSIX compliant variant.
619 // So we just use __xpg_strerror_r which is always POSIX compliant
620 #[cfg(target_os = "linux")]
621 fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: size_t) -> c_int {
624 fn __xpg_strerror_r(errnum: c_int,
630 __xpg_strerror_r(errnum, buf, buflen)
634 let mut buf = [0 as c_char, ..TMPBUF_SZ];
636 buf.as_mut_buf(|buf, len| {
638 if strerror_r(errno() as c_int, buf, len as size_t) < 0 {
639 fail!("strerror_r failure");
642 str::raw::from_c_str(buf as *c_char)
648 fn strerror() -> ~str {
649 use libc::types::os::arch::extra::DWORD;
650 use libc::types::os::arch::extra::LPWSTR;
651 use libc::types::os::arch::extra::LPVOID;
652 use libc::types::os::arch::extra::WCHAR;
654 #[link_name = "kernel32"]
656 fn FormatMessageW(flags: DWORD,
666 static FORMAT_MESSAGE_FROM_SYSTEM: DWORD = 0x00001000;
667 static FORMAT_MESSAGE_IGNORE_INSERTS: DWORD = 0x00000200;
669 // This value is calculated from the macro
670 // MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT)
671 let langId = 0x0800 as DWORD;
672 let err = errno() as DWORD;
674 let mut buf = [0 as WCHAR, ..TMPBUF_SZ];
677 buf.as_mut_buf(|buf, len| {
678 let res = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
679 FORMAT_MESSAGE_IGNORE_INSERTS,
687 fail!("[{}] FormatMessage failure", errno());
699 * Sets the process exit code
701 * Sets the exit code returned by the process if all supervised tasks
702 * terminate successfully (without failing). If the current root task fails
703 * and is supervised by the scheduler then any user-specified exit status is
704 * ignored and the process exits with the default failure status
706 pub fn set_exit_status(code: int) {
708 rt::set_exit_status(code);
711 unsafe fn load_argc_and_argv(argc: c_int, argv: **c_char) -> ~[~str] {
713 for i in range(0u, argc as uint) {
714 args.push(str::raw::from_c_str(*argv.offset(i as int)));
720 * Returns the command line arguments
722 * Returns a list of the command line arguments.
724 #[cfg(target_os = "macos")]
725 fn real_args() -> ~[~str] {
727 let (argc, argv) = (*_NSGetArgc() as c_int,
728 *_NSGetArgv() as **c_char);
729 load_argc_and_argv(argc, argv)
733 #[cfg(target_os = "linux")]
734 #[cfg(target_os = "android")]
735 #[cfg(target_os = "freebsd")]
736 fn real_args() -> ~[~str] {
739 match rt::args::clone() {
741 None => fail!("process arguments not initialized")
746 fn real_args() -> ~[~str] {
749 let mut nArgs: c_int = 0;
750 let lpArgCount: *mut c_int = &mut nArgs;
751 let lpCmdLine = unsafe { GetCommandLineW() };
752 let szArgList = unsafe { CommandLineToArgvW(lpCmdLine, lpArgCount) };
755 for i in range(0u, nArgs as uint) {
757 // Determine the length of this argument.
758 let ptr = *szArgList.offset(i as int);
760 while *ptr.offset(len as int) != 0 { len += 1; }
762 // Push it onto the list.
763 args.push(vec::raw::buf_as_slice(ptr, len,
769 LocalFree(szArgList as *c_void);
778 #[link_name="kernel32"]
780 fn GetCommandLineW() -> LPCWSTR;
781 fn LocalFree(ptr: *c_void);
785 #[link_name="shell32"]
787 fn CommandLineToArgvW(lpCmdLine: LPCWSTR, pNumArgs: *mut c_int) -> **u16;
790 struct OverriddenArgs {
794 /// Returns the arguments which this program was started with (normally passed
795 /// via the command line).
796 pub fn args() -> ~[~str] {
800 #[cfg(target_os = "macos")]
802 // These functions are in crt_externs.h.
803 pub fn _NSGetArgc() -> *c_int;
804 pub fn _NSGetArgv() -> ***c_char;
807 // Round up `from` to be divisible by `to`
808 fn round_up(from: uint, to: uint) -> uint {
809 let r = if from % to == 0 {
812 from + to - (from % to)
822 pub fn page_size() -> uint {
824 libc::sysconf(libc::_SC_PAGESIZE) as uint
829 pub fn page_size() -> uint {
831 let mut info = libc::SYSTEM_INFO::new();
832 libc::GetSystemInfo(&mut info);
834 return info.dwPageSize as uint;
838 /// A memory mapped file or chunk of memory. This is a very system-specific interface to the OS's
839 /// memory mapping facilities (`mmap` on POSIX, `VirtualAlloc`/`CreateFileMapping` on win32). It
840 /// makes no attempt at abstracting platform differences, besides in error values returned. Consider
843 /// The memory map is released (unmapped) when the destructor is run, so don't let it leave scope by
844 /// accident if you want it to stick around.
845 pub struct MemoryMap {
846 /// Pointer to the memory created or modified by this map.
848 /// Number of bytes this map applies to
854 /// Type of memory map
855 pub enum MemoryMapKind {
856 /// Memory-mapped file. On Windows, the inner pointer is a handle to the mapping, and
857 /// corresponds to `CreateFileMapping`. Elsewhere, it is null.
859 /// Virtual memory map. Usually used to change the permissions of a given chunk of memory.
860 /// Corresponds to `VirtualAlloc` on Windows.
864 /// Options the memory map is created with
866 /// The memory should be readable
868 /// The memory should be writable
870 /// The memory should be executable
872 /// Create a map for a specific address range. Corresponds to `MAP_FIXED` on POSIX.
874 /// Create a memory mapping for a file with a given fd.
876 /// When using `MapFd`, the start of the map is `uint` bytes from the start of the file.
880 /// Possible errors when creating a map.
882 /// ## The following are POSIX-specific
884 /// fd was not open for reading or, if using `MapWritable`, was not open for writing.
888 /// Either the address given by `MapAddr` or offset given by `MapOffset` was not a multiple of
889 /// `MemoryMap::granularity` (unaligned to page size).
891 /// With `MapFd`, the fd does not support mapping.
893 /// If using `MapAddr`, the address + `min_len` was outside of the process's address space. If
894 /// using `MapFd`, the target of the fd didn't have enough resources to fulfill the request.
896 /// Unrecognized error. The inner value is the unrecognized errno.
897 ErrUnknown(libc::c_int),
898 /// ## The following are win32-specific
900 /// Unsupported combination of protection flags (`MapReadable`/`MapWritable`/`MapExecutable`).
902 /// When using `MapFd`, `MapOffset` was given (Windows does not support this at all)
904 /// When using `MapFd`, there was already a mapping to the file.
906 /// Unrecognized error from `VirtualAlloc`. The inner value is the return value of GetLastError.
907 ErrVirtualAlloc(uint),
908 /// Unrecognized error from `CreateFileMapping`. The inner value is the return value of
910 ErrCreateFileMappingW(uint),
911 /// Unrecognized error from `MapViewOfFile`. The inner value is the return value of
913 ErrMapViewOfFile(uint)
916 impl to_str::ToStr for MapError {
917 fn to_str(&self) -> ~str {
919 ErrFdNotAvail => ~"fd not available for reading or writing",
920 ErrInvalidFd => ~"Invalid fd",
921 ErrUnaligned => ~"Unaligned address, invalid flags, \
922 negative length or unaligned offset",
923 ErrNoMapSupport=> ~"File doesn't support mapping",
924 ErrNoMem => ~"Invalid address, or not enough available memory",
925 ErrUnknown(code) => format!("Unknown error={}", code),
926 ErrUnsupProt => ~"Protection mode unsupported",
927 ErrUnsupOffset => ~"Offset in virtual memory mode is unsupported",
928 ErrAlreadyExists => ~"File mapping for specified file already exists",
929 ErrVirtualAlloc(code) => format!("VirtualAlloc failure={}", code),
930 ErrCreateFileMappingW(code) => format!("CreateFileMappingW failure={}", code),
931 ErrMapViewOfFile(code) => format!("MapViewOfFile failure={}", code)
938 /// Create a new mapping with the given `options`, at least `min_len` bytes long.
939 pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
942 let mut addr: *c_void = ptr::null();
943 let mut prot: c_int = 0;
944 let mut flags: c_int = libc::MAP_PRIVATE;
945 let mut fd: c_int = -1;
946 let mut offset: off_t = 0;
947 let len = round_up(min_len, page_size()) as size_t;
949 for &o in options.iter() {
951 MapReadable => { prot |= libc::PROT_READ; },
952 MapWritable => { prot |= libc::PROT_WRITE; },
953 MapExecutable => { prot |= libc::PROT_EXEC; },
955 flags |= libc::MAP_FIXED;
959 flags |= libc::MAP_FILE;
962 MapOffset(offset_) => { offset = offset_ as off_t; }
965 if fd == -1 { flags |= libc::MAP_ANON; }
968 libc::mmap(addr, len, prot, flags, fd, offset)
970 if r.equiv(&libc::MAP_FAILED) {
971 Err(match errno() as c_int {
972 libc::EACCES => ErrFdNotAvail,
973 libc::EBADF => ErrInvalidFd,
974 libc::EINVAL => ErrUnaligned,
975 libc::ENODEV => ErrNoMapSupport,
976 libc::ENOMEM => ErrNoMem,
977 code => ErrUnknown(code)
992 /// Granularity that the offset or address must be for `MapOffset` and `MapAddr` respectively.
993 pub fn granularity() -> uint {
999 impl Drop for MemoryMap {
1000 /// Unmap the mapping. Fails the task if `munmap` fails.
1001 fn drop(&mut self) {
1003 match libc::munmap(self.data as *c_void, self.len) {
1005 -1 => match errno() as c_int {
1006 libc::EINVAL => error!("invalid addr or len"),
1007 e => error!("unknown errno={}", e)
1009 r => error!("Unexpected result {}", r)
1017 /// Create a new mapping with the given `options`, at least `min_len` bytes long.
1018 pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
1019 use libc::types::os::arch::extra::{LPVOID, DWORD, SIZE_T, HANDLE};
1021 let mut lpAddress: LPVOID = ptr::mut_null();
1022 let mut readable = false;
1023 let mut writable = false;
1024 let mut executable = false;
1025 let mut fd: c_int = -1;
1026 let mut offset: uint = 0;
1027 let len = round_up(min_len, page_size()) as SIZE_T;
1029 for &o in options.iter() {
1031 MapReadable => { readable = true; },
1032 MapWritable => { writable = true; },
1033 MapExecutable => { executable = true; }
1034 MapAddr(addr_) => { lpAddress = addr_ as LPVOID; },
1035 MapFd(fd_) => { fd = fd_; },
1036 MapOffset(offset_) => { offset = offset_; }
1040 let flProtect = match (executable, readable, writable) {
1041 (false, false, false) if fd == -1 => libc::PAGE_NOACCESS,
1042 (false, true, false) => libc::PAGE_READONLY,
1043 (false, true, true) => libc::PAGE_READWRITE,
1044 (true, false, false) if fd == -1 => libc::PAGE_EXECUTE,
1045 (true, true, false) => libc::PAGE_EXECUTE_READ,
1046 (true, true, true) => libc::PAGE_EXECUTE_READWRITE,
1047 _ => return Err(ErrUnsupProt)
1052 return Err(ErrUnsupOffset);
1055 libc::VirtualAlloc(lpAddress,
1057 libc::MEM_COMMIT | libc::MEM_RESERVE,
1061 0 => Err(ErrVirtualAlloc(errno())),
1069 let dwDesiredAccess = match (executable, readable, writable) {
1070 (false, true, false) => libc::FILE_MAP_READ,
1071 (false, true, true) => libc::FILE_MAP_WRITE,
1072 (true, true, false) => libc::FILE_MAP_READ | libc::FILE_MAP_EXECUTE,
1073 (true, true, true) => libc::FILE_MAP_WRITE | libc::FILE_MAP_EXECUTE,
1074 _ => return Err(ErrUnsupProt) // Actually, because of the check above,
1075 // we should never get here.
1078 let hFile = libc::get_osfhandle(fd) as HANDLE;
1079 let mapping = libc::CreateFileMappingW(hFile,
1085 if mapping == ptr::mut_null() {
1086 return Err(ErrCreateFileMappingW(errno()));
1088 if errno() as c_int == libc::ERROR_ALREADY_EXISTS {
1089 return Err(ErrAlreadyExists);
1091 let r = libc::MapViewOfFile(mapping,
1093 ((len as u64) >> 32) as DWORD,
1094 (offset & 0xffff_ffff) as DWORD,
1097 0 => Err(ErrMapViewOfFile(errno())),
1101 kind: MapFile(mapping as *c_void)
1108 /// Granularity of MapAddr() and MapOffset() parameter values.
1109 /// This may be greater than the value returned by page_size().
1110 pub fn granularity() -> uint {
1112 let mut info = libc::SYSTEM_INFO::new();
1113 libc::GetSystemInfo(&mut info);
1115 return info.dwAllocationGranularity as uint;
1121 impl Drop for MemoryMap {
1122 /// Unmap the mapping. Fails the task if any of `VirtualFree`, `UnmapViewOfFile`, or
1123 /// `CloseHandle` fail.
1124 fn drop(&mut self) {
1125 use libc::types::os::arch::extra::{LPCVOID, HANDLE};
1126 use libc::consts::os::extra::FALSE;
1131 if libc::VirtualFree(self.data as *mut c_void,
1133 libc::MEM_RELEASE) == FALSE {
1134 error!("VirtualFree failed: {}", errno());
1137 MapFile(mapping) => {
1138 if libc::UnmapViewOfFile(self.data as LPCVOID) == FALSE {
1139 error!("UnmapViewOfFile failed: {}", errno());
1141 if libc::CloseHandle(mapping as HANDLE) == FALSE {
1142 error!("CloseHandle failed: {}", errno());
1153 pub use os::consts::unix::*;
1156 pub use os::consts::windows::*;
1158 #[cfg(target_os = "macos")]
1159 pub use os::consts::macos::*;
1161 #[cfg(target_os = "freebsd")]
1162 pub use os::consts::freebsd::*;
1164 #[cfg(target_os = "linux")]
1165 pub use os::consts::linux::*;
1167 #[cfg(target_os = "android")]
1168 pub use os::consts::android::*;
1170 #[cfg(target_os = "win32")]
1171 pub use os::consts::win32::*;
1173 #[cfg(target_arch = "x86")]
1174 pub use os::consts::x86::*;
1176 #[cfg(target_arch = "x86_64")]
1177 pub use os::consts::x86_64::*;
1179 #[cfg(target_arch = "arm")]
1180 pub use os::consts::arm::*;
1182 #[cfg(target_arch = "mips")]
1183 pub use os::consts::mips::*;
1186 pub static FAMILY: &'static str = "unix";
1190 pub static FAMILY: &'static str = "windows";
1194 pub static SYSNAME: &'static str = "macos";
1195 pub static DLL_PREFIX: &'static str = "lib";
1196 pub static DLL_SUFFIX: &'static str = ".dylib";
1197 pub static DLL_EXTENSION: &'static str = "dylib";
1198 pub static EXE_SUFFIX: &'static str = "";
1199 pub static EXE_EXTENSION: &'static str = "";
1203 pub static SYSNAME: &'static str = "freebsd";
1204 pub static DLL_PREFIX: &'static str = "lib";
1205 pub static DLL_SUFFIX: &'static str = ".so";
1206 pub static DLL_EXTENSION: &'static str = "so";
1207 pub static EXE_SUFFIX: &'static str = "";
1208 pub static EXE_EXTENSION: &'static str = "";
1212 pub static SYSNAME: &'static str = "linux";
1213 pub static DLL_PREFIX: &'static str = "lib";
1214 pub static DLL_SUFFIX: &'static str = ".so";
1215 pub static DLL_EXTENSION: &'static str = "so";
1216 pub static EXE_SUFFIX: &'static str = "";
1217 pub static EXE_EXTENSION: &'static str = "";
1221 pub static SYSNAME: &'static str = "android";
1222 pub static DLL_PREFIX: &'static str = "lib";
1223 pub static DLL_SUFFIX: &'static str = ".so";
1224 pub static DLL_EXTENSION: &'static str = "so";
1225 pub static EXE_SUFFIX: &'static str = "";
1226 pub static EXE_EXTENSION: &'static str = "";
1230 pub static SYSNAME: &'static str = "win32";
1231 pub static DLL_PREFIX: &'static str = "";
1232 pub static DLL_SUFFIX: &'static str = ".dll";
1233 pub static DLL_EXTENSION: &'static str = "dll";
1234 pub static EXE_SUFFIX: &'static str = ".exe";
1235 pub static EXE_EXTENSION: &'static str = "exe";
1240 pub static ARCH: &'static str = "x86";
1243 pub static ARCH: &'static str = "x86_64";
1246 pub static ARCH: &'static str = "arm";
1249 pub static ARCH: &'static str = "mips";
1258 use os::{env, getcwd, getenv, make_absolute, args};
1259 use os::{setenv, unsetenv};
1268 pub fn last_os_error() {
1269 debug!("{}", os::last_os_error());
1273 pub fn test_args() {
1275 assert!(a.len() >= 1);
1278 fn make_rand_name() -> ~str {
1279 let mut rng = rand::rng();
1280 let n = ~"TEST" + rng.gen_ascii_str(10u);
1281 assert!(getenv(n).is_none());
1287 let n = make_rand_name();
1289 assert_eq!(getenv(n), option::Some(~"VALUE"));
1293 fn test_unsetenv() {
1294 let n = make_rand_name();
1297 assert_eq!(getenv(n), option::None);
1302 fn test_setenv_overwrite() {
1303 let n = make_rand_name();
1306 assert_eq!(getenv(n), option::Some(~"2"));
1308 assert_eq!(getenv(n), option::Some(~""));
1311 // Windows GetEnvironmentVariable requires some extra work to make sure
1312 // the buffer the variable is copied into is the right size
1315 fn test_getenv_big() {
1319 s = s + "aaaaaaaaaa";
1322 let n = make_rand_name();
1324 debug!("{}", s.clone());
1325 assert_eq!(getenv(n), option::Some(s));
1329 fn test_self_exe_path() {
1330 let path = os::self_exe_path();
1331 assert!(path.is_some());
1332 let path = path.unwrap();
1333 debug!("{:?}", path.clone());
1335 // Hard to test this function
1336 assert!(path.is_absolute());
1341 fn test_env_getenv() {
1343 assert!(e.len() > 0u);
1345 let (n, v) = (*p).clone();
1346 debug!("{:?}", n.clone());
1348 // MingW seems to set some funky environment variables like
1349 // "=C:=C:\MinGW\msys\1.0\bin" and "!::=::\" that are returned
1350 // from env() but not visible from getenv().
1351 assert!(v2.is_none() || v2 == option::Some(v));
1356 fn test_env_setenv() {
1357 let n = make_rand_name();
1361 assert!(!e.contains(&(n.clone(), ~"VALUE")));
1364 assert!(e.contains(&(n, ~"VALUE")));
1369 assert!((!Path::new("test-path").is_absolute()));
1372 debug!("Current working directory: {}", cwd.display());
1374 debug!("{:?}", make_absolute(&Path::new("test-path")));
1375 debug!("{:?}", make_absolute(&Path::new("/usr/bin")));
1381 let oldhome = getenv("HOME");
1383 setenv("HOME", "/home/MountainView");
1384 assert_eq!(os::homedir(), Some(Path::new("/home/MountainView")));
1387 assert!(os::homedir().is_none());
1389 for s in oldhome.iter() { setenv("HOME", *s) }
1396 let oldhome = getenv("HOME");
1397 let olduserprofile = getenv("USERPROFILE");
1400 setenv("USERPROFILE", "");
1402 assert!(os::homedir().is_none());
1404 setenv("HOME", "/home/MountainView");
1405 assert_eq!(os::homedir(), Some(Path::new("/home/MountainView")));
1409 setenv("USERPROFILE", "/home/MountainView");
1410 assert_eq!(os::homedir(), Some(Path::new("/home/MountainView")));
1412 setenv("HOME", "/home/MountainView");
1413 setenv("USERPROFILE", "/home/PaloAlto");
1414 assert_eq!(os::homedir(), Some(Path::new("/home/MountainView")));
1416 for s in oldhome.iter() { setenv("HOME", *s) }
1417 for s in olduserprofile.iter() { setenv("USERPROFILE", *s) }
1421 fn memory_map_rw() {
1422 use result::{Ok, Err};
1424 let chunk = match os::MemoryMap::new(16, [
1429 Err(msg) => fail!(msg.to_str())
1431 assert!(chunk.len >= 16);
1435 assert!(*chunk.data == 0xBE);
1440 fn memory_map_file() {
1441 use result::{Ok, Err};
1448 fn lseek_(fd: c_int, size: uint) {
1450 assert!(lseek(fd, size as off_t, SEEK_SET) == size as off_t);
1454 fn lseek_(fd: c_int, size: uint) {
1456 assert!(lseek(fd, size as c_long, SEEK_SET) == size as c_long);
1460 let mut path = tmpdir();
1461 path.push("mmap_file.tmp");
1462 let size = MemoryMap::granularity() * 2;
1465 let fd = path.with_c_str(|path| {
1466 open(path, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR)
1469 "x".with_c_str(|x| assert!(write(fd, x as *c_void, 1) == 1));
1472 let chunk = match MemoryMap::new(size / 2, [
1479 Err(msg) => fail!(msg.to_str())
1481 assert!(chunk.len > 0);
1485 assert!(*chunk.data == 0xbe);
1488 io::ignore_io_error(|| fs::unlink(&path));
1491 // More recursive_mkdir tests are in extra::tempfile