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)];
31 #[cfg(target_os = "macos")]
36 use container::Container;
38 use libc::{c_char, c_void, c_int};
39 use option::{Some, None, Option};
42 use result::{Err, Ok, Result};
45 use str::{Str, StrSlice};
47 use sync::atomics::{AtomicInt, INIT_ATOMIC_INT, SeqCst};
48 use path::{Path, GenericPath};
50 use slice::{Vector, CloneableVector, ImmutableVector, MutableVector, OwnedVector};
58 /// Delegates to the libc close() function, returning the same return value.
59 pub fn close(fd: int) -> int {
61 libc::close(fd as c_int) as int
65 pub static TMPBUF_SZ : uint = 1000u;
66 static BUF_BYTES : uint = 2048u;
69 pub fn getcwd() -> Path {
72 let mut buf = [0 as c_char, ..BUF_BYTES];
74 if libc::getcwd(buf.as_mut_ptr(), buf.len() as libc::size_t).is_null() {
77 Path::new(CString::new(buf.as_ptr(), false))
82 pub fn getcwd() -> Path {
84 use libc::GetCurrentDirectoryW;
85 let mut buf = [0 as u16, ..BUF_BYTES];
87 if libc::GetCurrentDirectoryW(buf.len() as DWORD, buf.as_mut_ptr()) == 0 as DWORD {
91 Path::new(str::from_utf16(str::truncate_utf16_at_nul(buf))
92 .expect("GetCurrentDirectoryW returned invalid UTF-16"))
97 use libc::types::os::arch::extra::DWORD;
99 use option::{None, Option};
104 use slice::{MutableVector, ImmutableVector, OwnedVector};
107 pub fn fill_utf16_buf_and_decode(f: |*mut u16, DWORD| -> DWORD)
111 let mut n = TMPBUF_SZ as DWORD;
113 let mut done = false;
115 let mut buf = slice::from_elem(n as uint, 0u16);
116 let k = f(buf.as_mut_ptr(), n);
117 if k == (0 as DWORD) {
120 libc::GetLastError() ==
121 libc::ERROR_INSUFFICIENT_BUFFER as DWORD {
129 let sub = buf.slice(0, k as uint);
130 // We want to explicitly catch the case when the
131 // closure returned invalid UTF-16, rather than
132 // set `res` to None and continue.
133 let s = str::from_utf16(sub)
134 .expect("fill_utf16_buf_and_decode: closure created invalid UTF-16");
135 res = option::Some(s)
142 pub fn as_utf16_p<T>(s: &str, f: |*u16| -> T) -> T {
143 let mut t = s.to_utf16();
144 // Null terminate before passing on.
151 Accessing environment variables is not generally threadsafe.
152 Serialize access through a global lock.
154 fn with_env_lock<T>(f: || -> T) -> T {
155 use unstable::mutex::{StaticNativeMutex, NATIVE_MUTEX_INIT};
157 static mut lock: StaticNativeMutex = NATIVE_MUTEX_INIT;
160 let _guard = lock.lock();
165 /// Returns a vector of (variable, value) pairs for all the environment
166 /// variables of the current process.
168 /// Invalid UTF-8 bytes are replaced with \uFFFD. See `str::from_utf8_lossy()`
170 pub fn env() -> ~[(~str,~str)] {
171 env_as_bytes().move_iter().map(|(k,v)| {
172 let k = str::from_utf8_lossy(k).into_owned();
173 let v = str::from_utf8_lossy(v).into_owned();
178 /// Returns a vector of (variable, value) byte-vector pairs for all the
179 /// environment variables of the current process.
180 pub fn env_as_bytes() -> ~[(~[u8],~[u8])] {
183 unsafe fn get_env_pairs() -> ~[~[u8]] {
187 use libc::funcs::extra::kernel32::{
188 GetEnvironmentStringsA,
189 FreeEnvironmentStringsA
191 let ch = GetEnvironmentStringsA();
193 fail!("os::env() failure getting env string from OS: {}",
194 os::last_os_error());
196 let mut result = ~[];
197 c_str::from_c_multistring(ch as *c_char, None, |cstr| {
198 result.push(cstr.as_bytes_no_nul().to_owned());
200 FreeEnvironmentStringsA(ch);
204 unsafe fn get_env_pairs() -> ~[~[u8]] {
208 fn rust_env_pairs() -> **c_char;
210 let environ = rust_env_pairs();
211 if environ as uint == 0 {
212 fail!("os::env() failure getting env string from OS: {}",
213 os::last_os_error());
215 let mut result = ~[];
216 ptr::array_each(environ, |e| {
217 let env_pair = CString::new(e, false).as_bytes_no_nul().to_owned();
218 result.push(env_pair);
223 fn env_convert(input: ~[~[u8]]) -> ~[(~[u8], ~[u8])] {
225 for p in input.iter() {
226 let vs: ~[&[u8]] = p.splitn(1, |b| *b == '=' as u8).collect();
227 let key = vs[0].to_owned();
228 let val = if vs.len() < 2 { ~[] } else { vs[1].to_owned() };
229 pairs.push((key, val));
234 let unparsed_environ = get_env_pairs();
235 env_convert(unparsed_environ)
241 /// Fetches the environment variable `n` from the current process, returning
242 /// None if the variable isn't set.
244 /// Any invalid UTF-8 bytes in the value are replaced by \uFFFD. See
245 /// `str::from_utf8_lossy()` for details.
249 /// Fails if `n` has any interior NULs.
250 pub fn getenv(n: &str) -> Option<~str> {
251 getenv_as_bytes(n).map(|v| str::from_utf8_lossy(v).into_owned())
255 /// Fetches the environment variable `n` byte vector from the current process,
256 /// returning None if the variable isn't set.
260 /// Fails if `n` has any interior NULs.
261 pub fn getenv_as_bytes(n: &str) -> Option<~[u8]> {
266 let s = n.with_c_str(|buf| libc::getenv(buf));
270 Some(CString::new(s, false).as_bytes_no_nul().to_owned())
277 /// Fetches the environment variable `n` from the current process, returning
278 /// None if the variable isn't set.
279 pub fn getenv(n: &str) -> Option<~str> {
282 use os::win32::{as_utf16_p, fill_utf16_buf_and_decode};
284 fill_utf16_buf_and_decode(|buf, sz| {
285 libc::GetEnvironmentVariableW(u, buf, sz)
293 /// Fetches the environment variable `n` byte vector from the current process,
294 /// returning None if the variable isn't set.
295 pub fn getenv_as_bytes(n: &str) -> Option<~[u8]> {
296 getenv(n).map(|s| s.into_bytes())
301 /// Sets the environment variable `n` to the value `v` for the currently running
306 /// Fails if `n` or `v` have any interior NULs.
307 pub fn setenv(n: &str, v: &str) {
310 n.with_c_str(|nbuf| {
311 v.with_c_str(|vbuf| {
312 libc::funcs::posix01::unistd::setenv(nbuf, vbuf, 1);
321 /// Sets the environment variable `n` to the value `v` for the currently running
323 pub fn setenv(n: &str, v: &str) {
326 use os::win32::as_utf16_p;
327 as_utf16_p(n, |nbuf| {
328 as_utf16_p(v, |vbuf| {
329 libc::SetEnvironmentVariableW(nbuf, vbuf);
336 /// Remove a variable from the environment entirely
340 /// Fails (on unix) if `n` has any interior NULs.
341 pub fn unsetenv(n: &str) {
343 fn _unsetenv(n: &str) {
346 n.with_c_str(|nbuf| {
347 libc::funcs::posix01::unistd::unsetenv(nbuf);
353 fn _unsetenv(n: &str) {
356 use os::win32::as_utf16_p;
357 as_utf16_p(n, |nbuf| {
358 libc::SetEnvironmentVariableW(nbuf, ptr::null());
373 pub fn pipe() -> Pipe {
375 let mut fds = Pipe {input: 0,
377 assert_eq!(libc::pipe(&mut fds.input), 0);
378 return Pipe {input: fds.input, out: fds.out};
383 pub fn pipe() -> Pipe {
385 // Windows pipes work subtly differently than unix pipes, and their
386 // inheritance has to be handled in a different way that I do not
387 // fully understand. Here we explicitly make the pipe non-inheritable,
388 // which means to pass it to a subprocess they need to be duplicated
389 // first, as in std::run.
390 let mut fds = Pipe {input: 0,
392 let res = libc::pipe(&mut fds.input, 1024 as ::libc::c_uint,
393 (libc::O_BINARY | libc::O_NOINHERIT) as c_int);
395 assert!((fds.input != -1 && fds.input != 0 ));
396 assert!((fds.out != -1 && fds.input != 0));
397 return Pipe {input: fds.input, out: fds.out};
401 /// Returns the proper dll filename for the given basename of a file.
402 pub fn dll_filename(base: &str) -> ~str {
403 format!("{}{}{}", consts::DLL_PREFIX, base, consts::DLL_SUFFIX)
406 /// Optionally returns the filesystem path of the current executable which is
407 /// running. If any failure occurs, None is returned.
408 pub fn self_exe_name() -> Option<Path> {
410 #[cfg(target_os = "freebsd")]
411 fn load_self() -> Option<~[u8]> {
413 use libc::funcs::bsd44::*;
414 use libc::consts::os::extra::*;
416 let mib = ~[CTL_KERN as c_int,
418 KERN_PROC_PATHNAME as c_int, -1 as c_int];
419 let mut sz: libc::size_t = 0;
420 let err = sysctl(mib.as_ptr(), mib.len() as ::libc::c_uint,
421 ptr::mut_null(), &mut sz, ptr::null(),
423 if err != 0 { return None; }
424 if sz == 0 { return None; }
425 let mut v: ~[u8] = slice::with_capacity(sz as uint);
426 let err = sysctl(mib.as_ptr(), mib.len() as ::libc::c_uint,
427 v.as_mut_ptr() as *mut c_void, &mut sz, ptr::null(),
429 if err != 0 { return None; }
430 if sz == 0 { return None; }
431 v.set_len(sz as uint - 1); // chop off trailing NUL
436 #[cfg(target_os = "linux")]
437 #[cfg(target_os = "android")]
438 fn load_self() -> Option<~[u8]> {
441 match io::fs::readlink(&Path::new("/proc/self/exe")) {
442 Ok(path) => Some(path.as_vec().to_owned()),
447 #[cfg(target_os = "macos")]
448 fn load_self() -> Option<~[u8]> {
450 use libc::funcs::extra::_NSGetExecutablePath;
453 _NSGetExecutablePath(ptr::mut_null(), &mut sz);
454 if sz == 0 { return None; }
455 let mut v: ~[u8] = slice::with_capacity(sz as uint);
456 let err = _NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz);
457 if err != 0 { return None; }
458 v.set_len(sz as uint - 1); // chop off trailing NUL
464 fn load_self() -> Option<~[u8]> {
468 use os::win32::fill_utf16_buf_and_decode;
469 fill_utf16_buf_and_decode(|buf, sz| {
470 libc::GetModuleFileNameW(0u as libc::DWORD, buf, sz)
471 }).map(|s| s.into_bytes())
475 load_self().and_then(Path::new_opt)
478 /// Optionally returns the filesystem path to the current executable which is
479 /// running. Like self_exe_name() but without the binary's name.
480 /// If any failure occurs, None is returned.
481 pub fn self_exe_path() -> Option<Path> {
482 self_exe_name().map(|mut p| { p.pop(); p })
486 * Returns the path to the user's home directory, if known.
488 * On Unix, returns the value of the 'HOME' environment variable if it is set
489 * and not equal to the empty string.
491 * On Windows, returns the value of the 'HOME' environment variable if it is
492 * set and not equal to the empty string. Otherwise, returns the value of the
493 * 'USERPROFILE' environment variable if it is set and not equal to the empty
496 * Otherwise, homedir returns option::none.
498 pub fn homedir() -> Option<Path> {
499 // FIXME (#7188): getenv needs a ~[u8] variant
500 return match getenv("HOME") {
501 Some(ref p) if !p.is_empty() => Path::new_opt(p.as_slice()),
506 fn secondary() -> Option<Path> {
511 fn secondary() -> Option<Path> {
512 getenv("USERPROFILE").and_then(|p| {
523 * Returns the path to a temporary directory.
525 * On Unix, returns the value of the 'TMPDIR' environment variable if it is
526 * set and non-empty and '/tmp' otherwise.
527 * On Android, there is no global temporary folder (it is usually allocated
528 * per-app), hence returns '/data/tmp' which is commonly used.
530 * On Windows, returns the value of, in order, the 'TMP', 'TEMP',
531 * 'USERPROFILE' environment variable if any are set and not the empty
532 * string. Otherwise, tmpdir returns the path to the Windows directory.
534 pub fn tmpdir() -> Path {
537 fn getenv_nonempty(v: &str) -> Option<Path> {
550 fn lookup() -> Path {
551 if cfg!(target_os = "android") {
552 Path::new("/data/tmp")
554 getenv_nonempty("TMPDIR").unwrap_or(Path::new("/tmp"))
559 fn lookup() -> Path {
560 getenv_nonempty("TMP").or(
561 getenv_nonempty("TEMP").or(
562 getenv_nonempty("USERPROFILE").or(
563 getenv_nonempty("WINDIR")))).unwrap_or(Path::new("C:\\Windows"))
568 * Convert a relative path to an absolute path
570 * If the given path is relative, return it prepended with the current working
571 * directory. If the given path is already an absolute path, return it
574 // NB: this is here rather than in path because it is a form of environment
575 // querying; what it does depends on the process working directory, not just
577 pub fn make_absolute(p: &Path) -> Path {
581 let mut ret = getcwd();
587 /// Changes the current working directory to the specified path, returning
588 /// whether the change was completed successfully or not.
589 pub fn change_dir(p: &Path) -> bool {
593 fn chdir(p: &Path) -> bool {
595 use os::win32::as_utf16_p;
596 return as_utf16_p(p.as_str().unwrap(), |buf| {
597 libc::SetCurrentDirectoryW(buf) != (0 as libc::BOOL)
603 fn chdir(p: &Path) -> bool {
606 libc::chdir(buf) == (0 as c_int)
613 /// Returns the platform-specific value of errno
614 pub fn errno() -> int {
615 #[cfg(target_os = "macos")]
616 #[cfg(target_os = "freebsd")]
617 fn errno_location() -> *c_int {
619 fn __error() -> *c_int;
626 #[cfg(target_os = "linux")]
627 #[cfg(target_os = "android")]
628 fn errno_location() -> *c_int {
630 fn __errno_location() -> *c_int;
638 (*errno_location()) as int
643 /// Returns the platform-specific value of errno
644 pub fn errno() -> uint {
645 use libc::types::os::arch::extra::DWORD;
647 #[link_name = "kernel32"]
649 fn GetLastError() -> DWORD;
653 GetLastError() as uint
657 /// Get a string representing the platform-dependent last error
658 pub fn last_os_error() -> ~str {
660 fn strerror() -> ~str {
661 #[cfg(target_os = "macos")]
662 #[cfg(target_os = "android")]
663 #[cfg(target_os = "freebsd")]
664 fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: libc::size_t)
667 fn strerror_r(errnum: c_int, buf: *mut c_char,
668 buflen: libc::size_t) -> c_int;
671 strerror_r(errnum, buf, buflen)
675 // GNU libc provides a non-compliant version of strerror_r by default
676 // and requires macros to instead use the POSIX compliant variant.
677 // So we just use __xpg_strerror_r which is always POSIX compliant
678 #[cfg(target_os = "linux")]
679 fn strerror_r(errnum: c_int, buf: *mut c_char,
680 buflen: libc::size_t) -> c_int {
682 fn __xpg_strerror_r(errnum: c_int,
684 buflen: libc::size_t)
688 __xpg_strerror_r(errnum, buf, buflen)
692 let mut buf = [0 as c_char, ..TMPBUF_SZ];
694 let p = buf.as_mut_ptr();
696 if strerror_r(errno() as c_int, p, buf.len() as libc::size_t) < 0 {
697 fail!("strerror_r failure");
700 str::raw::from_c_str(p as *c_char)
705 fn strerror() -> ~str {
706 use libc::types::os::arch::extra::DWORD;
707 use libc::types::os::arch::extra::LPWSTR;
708 use libc::types::os::arch::extra::LPVOID;
709 use libc::types::os::arch::extra::WCHAR;
711 #[link_name = "kernel32"]
713 fn FormatMessageW(flags: DWORD,
723 static FORMAT_MESSAGE_FROM_SYSTEM: DWORD = 0x00001000;
724 static FORMAT_MESSAGE_IGNORE_INSERTS: DWORD = 0x00000200;
726 // This value is calculated from the macro
727 // MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT)
728 let langId = 0x0800 as DWORD;
729 let err = errno() as DWORD;
731 let mut buf = [0 as WCHAR, ..TMPBUF_SZ];
734 let res = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
735 FORMAT_MESSAGE_IGNORE_INSERTS,
743 // Sometimes FormatMessageW can fail e.g. system doesn't like langId,
744 let fm_err = errno();
745 return format!("OS Error {} (FormatMessageW() returned error {})", err, fm_err);
748 let msg = str::from_utf16(str::truncate_utf16_at_nul(buf));
750 Some(msg) => format!("OS Error {}: {}", err, msg),
751 None => format!("OS Error {} (FormatMessageW() returned invalid UTF-16)", err),
759 static mut EXIT_STATUS: AtomicInt = INIT_ATOMIC_INT;
762 * Sets the process exit code
764 * Sets the exit code returned by the process if all supervised tasks
765 * terminate successfully (without failing). If the current root task fails
766 * and is supervised by the scheduler then any user-specified exit status is
767 * ignored and the process exits with the default failure status.
769 * Note that this is not synchronized against modifications of other threads.
771 pub fn set_exit_status(code: int) {
772 unsafe { EXIT_STATUS.store(code, SeqCst) }
775 /// Fetches the process's current exit code. This defaults to 0 and can change
776 /// by calling `set_exit_status`.
777 pub fn get_exit_status() -> int {
778 unsafe { EXIT_STATUS.load(SeqCst) }
781 #[cfg(target_os = "macos")]
782 unsafe fn load_argc_and_argv(argc: int, argv: **c_char) -> ~[~[u8]] {
786 for i in range(0u, argc as uint) {
787 args.push(CString::new(*argv.offset(i as int), false).as_bytes_no_nul().to_owned())
793 * Returns the command line arguments
795 * Returns a list of the command line arguments.
797 #[cfg(target_os = "macos")]
798 fn real_args_as_bytes() -> ~[~[u8]] {
800 let (argc, argv) = (*_NSGetArgc() as int,
801 *_NSGetArgv() as **c_char);
802 load_argc_and_argv(argc, argv)
806 #[cfg(target_os = "linux")]
807 #[cfg(target_os = "android")]
808 #[cfg(target_os = "freebsd")]
809 fn real_args_as_bytes() -> ~[~[u8]] {
812 match rt::args::clone() {
814 None => fail!("process arguments not initialized")
819 fn real_args() -> ~[~str] {
820 real_args_as_bytes().move_iter().map(|v| str::from_utf8_lossy(v).into_owned()).collect()
824 fn real_args() -> ~[~str] {
827 let mut nArgs: c_int = 0;
828 let lpArgCount: *mut c_int = &mut nArgs;
829 let lpCmdLine = unsafe { GetCommandLineW() };
830 let szArgList = unsafe { CommandLineToArgvW(lpCmdLine, lpArgCount) };
833 for i in range(0u, nArgs as uint) {
835 // Determine the length of this argument.
836 let ptr = *szArgList.offset(i as int);
838 while *ptr.offset(len as int) != 0 { len += 1; }
840 // Push it onto the list.
841 let opt_s = slice::raw::buf_as_slice(ptr, len, |buf| {
842 str::from_utf16(str::truncate_utf16_at_nul(buf))
844 args.push(opt_s.expect("CommandLineToArgvW returned invalid UTF-16"));
849 LocalFree(szArgList as *c_void);
856 fn real_args_as_bytes() -> ~[~[u8]] {
857 real_args().move_iter().map(|s| s.into_bytes()).collect()
863 #[link_name="kernel32"]
865 fn GetCommandLineW() -> LPCWSTR;
866 fn LocalFree(ptr: *c_void);
870 #[link_name="shell32"]
872 fn CommandLineToArgvW(lpCmdLine: LPCWSTR, pNumArgs: *mut c_int) -> **u16;
875 /// Returns the arguments which this program was started with (normally passed
876 /// via the command line).
878 /// The arguments are interpreted as utf-8, with invalid bytes replaced with \uFFFD.
879 /// See `str::from_utf8_lossy` for details.
880 pub fn args() -> ~[~str] {
884 /// Returns the arguments which this program was started with (normally passed
885 /// via the command line) as byte vectors.
886 pub fn args_as_bytes() -> ~[~[u8]] {
890 #[cfg(target_os = "macos")]
892 // These functions are in crt_externs.h.
893 pub fn _NSGetArgc() -> *c_int;
894 pub fn _NSGetArgv() -> ***c_char;
897 // Round up `from` to be divisible by `to`
898 fn round_up(from: uint, to: uint) -> uint {
899 let r = if from % to == 0 {
902 from + to - (from % to)
912 pub fn page_size() -> uint {
914 libc::sysconf(libc::_SC_PAGESIZE) as uint
919 pub fn page_size() -> uint {
921 let mut info = libc::SYSTEM_INFO::new();
922 libc::GetSystemInfo(&mut info);
924 return info.dwPageSize as uint;
928 /// A memory mapped file or chunk of memory. This is a very system-specific
929 /// interface to the OS's memory mapping facilities (`mmap` on POSIX,
930 /// `VirtualAlloc`/`CreateFileMapping` on win32). It makes no attempt at
931 /// abstracting platform differences, besides in error values returned. Consider
934 /// The memory map is released (unmapped) when the destructor is run, so don't
935 /// let it leave scope by accident if you want it to stick around.
936 pub struct MemoryMap {
937 /// Pointer to the memory created or modified by this map.
939 /// Number of bytes this map applies to
945 /// Type of memory map
946 pub enum MemoryMapKind {
947 /// Virtual memory map. Usually used to change the permissions of a given
948 /// chunk of memory. Corresponds to `VirtualAlloc` on Windows.
950 /// Virtual memory map. Usually used to change the permissions of a given
951 /// chunk of memory, or for allocation. Corresponds to `VirtualAlloc` on
956 /// Options the memory map is created with
958 /// The memory should be readable
960 /// The memory should be writable
962 /// The memory should be executable
964 /// Create a map for a specific address range. Corresponds to `MAP_FIXED` on
967 /// Create a memory mapping for a file with a given fd.
969 /// When using `MapFd`, the start of the map is `uint` bytes from the start
972 /// On POSIX, this can be used to specify the default flags passed to
973 /// `mmap`. By default it uses `MAP_PRIVATE` and, if not using `MapFd`,
974 /// `MAP_ANON`. This will override both of those. This is platform-specific
975 /// (the exact values used) and ignored on Windows.
976 MapNonStandardFlags(c_int),
979 /// Possible errors when creating a map.
981 /// ## The following are POSIX-specific
983 /// fd was not open for reading or, if using `MapWritable`, was not open for
988 /// Either the address given by `MapAddr` or offset given by `MapOffset` was
989 /// not a multiple of `MemoryMap::granularity` (unaligned to page size).
991 /// With `MapFd`, the fd does not support mapping.
993 /// If using `MapAddr`, the address + `min_len` was outside of the process's
994 /// address space. If using `MapFd`, the target of the fd didn't have enough
995 /// resources to fulfill the request.
997 /// A zero-length map was requested. This is invalid according to
998 /// [POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/functions/mmap.html).
999 /// Not all platforms obey this, but this wrapper does.
1001 /// Unrecognized error. The inner value is the unrecognized errno.
1003 /// ## The following are win32-specific
1005 /// Unsupported combination of protection flags
1006 /// (`MapReadable`/`MapWritable`/`MapExecutable`).
1008 /// When using `MapFd`, `MapOffset` was given (Windows does not support this
1011 /// When using `MapFd`, there was already a mapping to the file.
1013 /// Unrecognized error from `VirtualAlloc`. The inner value is the return
1014 /// value of GetLastError.
1015 ErrVirtualAlloc(uint),
1016 /// Unrecognized error from `CreateFileMapping`. The inner value is the
1017 /// return value of `GetLastError`.
1018 ErrCreateFileMappingW(uint),
1019 /// Unrecognized error from `MapViewOfFile`. The inner value is the return
1020 /// value of `GetLastError`.
1021 ErrMapViewOfFile(uint)
1024 impl fmt::Show for MapError {
1025 fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result {
1026 let str = match *self {
1027 ErrFdNotAvail => "fd not available for reading or writing",
1028 ErrInvalidFd => "Invalid fd",
1030 "Unaligned address, invalid flags, negative length or \
1033 ErrNoMapSupport=> "File doesn't support mapping",
1034 ErrNoMem => "Invalid address, or not enough available memory",
1035 ErrUnsupProt => "Protection mode unsupported",
1036 ErrUnsupOffset => "Offset in virtual memory mode is unsupported",
1037 ErrAlreadyExists => "File mapping for specified file already exists",
1038 ErrZeroLength => "Zero-length mapping not allowed",
1039 ErrUnknown(code) => {
1040 return write!(out.buf, "Unknown error = {}", code)
1042 ErrVirtualAlloc(code) => {
1043 return write!(out.buf, "VirtualAlloc failure = {}", code)
1045 ErrCreateFileMappingW(code) => {
1046 return write!(out.buf, "CreateFileMappingW failure = {}", code)
1048 ErrMapViewOfFile(code) => {
1049 return write!(out.buf, "MapViewOfFile failure = {}", code)
1052 write!(out.buf, "{}", str)
1058 /// Create a new mapping with the given `options`, at least `min_len` bytes
1059 /// long. `min_len` must be greater than zero; see the note on
1060 /// `ErrZeroLength`.
1061 pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
1066 return Err(ErrZeroLength)
1068 let mut addr: *u8 = ptr::null();
1070 let mut flags = libc::MAP_PRIVATE;
1073 let mut custom_flags = false;
1074 let len = round_up(min_len, page_size());
1076 for &o in options.iter() {
1078 MapReadable => { prot |= libc::PROT_READ; },
1079 MapWritable => { prot |= libc::PROT_WRITE; },
1080 MapExecutable => { prot |= libc::PROT_EXEC; },
1082 flags |= libc::MAP_FIXED;
1086 flags |= libc::MAP_FILE;
1089 MapOffset(offset_) => { offset = offset_ as off_t; },
1090 MapNonStandardFlags(f) => { custom_flags = true; flags = f },
1093 if fd == -1 && !custom_flags { flags |= libc::MAP_ANON; }
1096 libc::mmap(addr as *c_void, len as libc::size_t, prot, flags, fd,
1099 if r.equiv(&libc::MAP_FAILED) {
1100 Err(match errno() as c_int {
1101 libc::EACCES => ErrFdNotAvail,
1102 libc::EBADF => ErrInvalidFd,
1103 libc::EINVAL => ErrUnaligned,
1104 libc::ENODEV => ErrNoMapSupport,
1105 libc::ENOMEM => ErrNoMem,
1106 code => ErrUnknown(code as int)
1115 MapFile(ptr::null())
1121 /// Granularity that the offset or address must be for `MapOffset` and
1122 /// `MapAddr` respectively.
1123 pub fn granularity() -> uint {
1129 impl Drop for MemoryMap {
1130 /// Unmap the mapping. Fails the task if `munmap` fails.
1131 fn drop(&mut self) {
1132 if self.len == 0 { /* workaround for dummy_stack */ return; }
1135 // FIXME: what to do if this fails?
1136 let _ = libc::munmap(self.data as *c_void, self.len as libc::size_t);
1143 /// Create a new mapping with the given `options`, at least `min_len` bytes long.
1144 pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
1145 use libc::types::os::arch::extra::{LPVOID, DWORD, SIZE_T, HANDLE};
1147 let mut lpAddress: LPVOID = ptr::mut_null();
1148 let mut readable = false;
1149 let mut writable = false;
1150 let mut executable = false;
1151 let mut fd: c_int = -1;
1152 let mut offset: uint = 0;
1153 let len = round_up(min_len, page_size());
1155 for &o in options.iter() {
1157 MapReadable => { readable = true; },
1158 MapWritable => { writable = true; },
1159 MapExecutable => { executable = true; }
1160 MapAddr(addr_) => { lpAddress = addr_ as LPVOID; },
1161 MapFd(fd_) => { fd = fd_; },
1162 MapOffset(offset_) => { offset = offset_; },
1163 MapNonStandardFlags(..) => {}
1167 let flProtect = match (executable, readable, writable) {
1168 (false, false, false) if fd == -1 => libc::PAGE_NOACCESS,
1169 (false, true, false) => libc::PAGE_READONLY,
1170 (false, true, true) => libc::PAGE_READWRITE,
1171 (true, false, false) if fd == -1 => libc::PAGE_EXECUTE,
1172 (true, true, false) => libc::PAGE_EXECUTE_READ,
1173 (true, true, true) => libc::PAGE_EXECUTE_READWRITE,
1174 _ => return Err(ErrUnsupProt)
1179 return Err(ErrUnsupOffset);
1182 libc::VirtualAlloc(lpAddress,
1184 libc::MEM_COMMIT | libc::MEM_RESERVE,
1188 0 => Err(ErrVirtualAlloc(errno())),
1196 let dwDesiredAccess = match (executable, readable, writable) {
1197 (false, true, false) => libc::FILE_MAP_READ,
1198 (false, true, true) => libc::FILE_MAP_WRITE,
1199 (true, true, false) => libc::FILE_MAP_READ | libc::FILE_MAP_EXECUTE,
1200 (true, true, true) => libc::FILE_MAP_WRITE | libc::FILE_MAP_EXECUTE,
1201 _ => return Err(ErrUnsupProt) // Actually, because of the check above,
1202 // we should never get here.
1205 let hFile = libc::get_osfhandle(fd) as HANDLE;
1206 let mapping = libc::CreateFileMappingW(hFile,
1212 if mapping == ptr::mut_null() {
1213 return Err(ErrCreateFileMappingW(errno()));
1215 if errno() as c_int == libc::ERROR_ALREADY_EXISTS {
1216 return Err(ErrAlreadyExists);
1218 let r = libc::MapViewOfFile(mapping,
1220 ((len as u64) >> 32) as DWORD,
1221 (offset & 0xffff_ffff) as DWORD,
1224 0 => Err(ErrMapViewOfFile(errno())),
1228 kind: MapFile(mapping as *u8)
1235 /// Granularity of MapAddr() and MapOffset() parameter values.
1236 /// This may be greater than the value returned by page_size().
1237 pub fn granularity() -> uint {
1239 let mut info = libc::SYSTEM_INFO::new();
1240 libc::GetSystemInfo(&mut info);
1242 return info.dwAllocationGranularity as uint;
1248 impl Drop for MemoryMap {
1249 /// Unmap the mapping. Fails the task if any of `VirtualFree`,
1250 /// `UnmapViewOfFile`, or `CloseHandle` fail.
1251 fn drop(&mut self) {
1252 use libc::types::os::arch::extra::{LPCVOID, HANDLE};
1253 use libc::consts::os::extra::FALSE;
1254 if self.len == 0 { return }
1259 if libc::VirtualFree(self.data as *mut c_void, 0,
1260 libc::MEM_RELEASE) == 0 {
1261 println!("VirtualFree failed: {}", errno());
1264 MapFile(mapping) => {
1265 if libc::UnmapViewOfFile(self.data as LPCVOID) == FALSE {
1266 println!("UnmapViewOfFile failed: {}", errno());
1268 if libc::CloseHandle(mapping as HANDLE) == FALSE {
1269 println!("CloseHandle failed: {}", errno());
1280 pub use os::consts::unix::*;
1283 pub use os::consts::windows::*;
1285 #[cfg(target_os = "macos")]
1286 pub use os::consts::macos::*;
1288 #[cfg(target_os = "freebsd")]
1289 pub use os::consts::freebsd::*;
1291 #[cfg(target_os = "linux")]
1292 pub use os::consts::linux::*;
1294 #[cfg(target_os = "android")]
1295 pub use os::consts::android::*;
1297 #[cfg(target_os = "win32")]
1298 pub use os::consts::win32::*;
1300 #[cfg(target_arch = "x86")]
1301 pub use os::consts::x86::*;
1303 #[cfg(target_arch = "x86_64")]
1304 pub use os::consts::x86_64::*;
1306 #[cfg(target_arch = "arm")]
1307 pub use os::consts::arm::*;
1309 #[cfg(target_arch = "mips")]
1310 pub use os::consts::mips::*;
1313 pub static FAMILY: &'static str = "unix";
1317 pub static FAMILY: &'static str = "windows";
1321 pub static SYSNAME: &'static str = "macos";
1322 pub static DLL_PREFIX: &'static str = "lib";
1323 pub static DLL_SUFFIX: &'static str = ".dylib";
1324 pub static DLL_EXTENSION: &'static str = "dylib";
1325 pub static EXE_SUFFIX: &'static str = "";
1326 pub static EXE_EXTENSION: &'static str = "";
1330 pub static SYSNAME: &'static str = "freebsd";
1331 pub static DLL_PREFIX: &'static str = "lib";
1332 pub static DLL_SUFFIX: &'static str = ".so";
1333 pub static DLL_EXTENSION: &'static str = "so";
1334 pub static EXE_SUFFIX: &'static str = "";
1335 pub static EXE_EXTENSION: &'static str = "";
1339 pub static SYSNAME: &'static str = "linux";
1340 pub static DLL_PREFIX: &'static str = "lib";
1341 pub static DLL_SUFFIX: &'static str = ".so";
1342 pub static DLL_EXTENSION: &'static str = "so";
1343 pub static EXE_SUFFIX: &'static str = "";
1344 pub static EXE_EXTENSION: &'static str = "";
1348 pub static SYSNAME: &'static str = "android";
1349 pub static DLL_PREFIX: &'static str = "lib";
1350 pub static DLL_SUFFIX: &'static str = ".so";
1351 pub static DLL_EXTENSION: &'static str = "so";
1352 pub static EXE_SUFFIX: &'static str = "";
1353 pub static EXE_EXTENSION: &'static str = "";
1357 pub static SYSNAME: &'static str = "win32";
1358 pub static DLL_PREFIX: &'static str = "";
1359 pub static DLL_SUFFIX: &'static str = ".dll";
1360 pub static DLL_EXTENSION: &'static str = "dll";
1361 pub static EXE_SUFFIX: &'static str = ".exe";
1362 pub static EXE_EXTENSION: &'static str = "exe";
1367 pub static ARCH: &'static str = "x86";
1370 pub static ARCH: &'static str = "x86_64";
1373 pub static ARCH: &'static str = "arm";
1376 pub static ARCH: &'static str = "mips";
1385 use os::{env, getcwd, getenv, make_absolute, args};
1386 use os::{setenv, unsetenv};
1392 pub fn last_os_error() {
1393 debug!("{}", os::last_os_error());
1397 pub fn test_args() {
1399 assert!(a.len() >= 1);
1402 fn make_rand_name() -> ~str {
1403 let mut rng = rand::task_rng();
1404 let n = ~"TEST" + rng.gen_ascii_str(10u);
1405 assert!(getenv(n).is_none());
1411 let n = make_rand_name();
1413 assert_eq!(getenv(n), option::Some(~"VALUE"));
1417 fn test_unsetenv() {
1418 let n = make_rand_name();
1421 assert_eq!(getenv(n), option::None);
1426 fn test_setenv_overwrite() {
1427 let n = make_rand_name();
1430 assert_eq!(getenv(n), option::Some(~"2"));
1432 assert_eq!(getenv(n), option::Some(~""));
1435 // Windows GetEnvironmentVariable requires some extra work to make sure
1436 // the buffer the variable is copied into is the right size
1439 fn test_getenv_big() {
1443 s = s + "aaaaaaaaaa";
1446 let n = make_rand_name();
1448 debug!("{}", s.clone());
1449 assert_eq!(getenv(n), option::Some(s));
1453 fn test_self_exe_name() {
1454 let path = os::self_exe_name();
1455 assert!(path.is_some());
1456 let path = path.unwrap();
1457 debug!("{:?}", path.clone());
1459 // Hard to test this function
1460 assert!(path.is_absolute());
1464 fn test_self_exe_path() {
1465 let path = os::self_exe_path();
1466 assert!(path.is_some());
1467 let path = path.unwrap();
1468 debug!("{:?}", path.clone());
1470 // Hard to test this function
1471 assert!(path.is_absolute());
1476 fn test_env_getenv() {
1478 assert!(e.len() > 0u);
1480 let (n, v) = (*p).clone();
1481 debug!("{:?}", n.clone());
1483 // MingW seems to set some funky environment variables like
1484 // "=C:=C:\MinGW\msys\1.0\bin" and "!::=::\" that are returned
1485 // from env() but not visible from getenv().
1486 assert!(v2.is_none() || v2 == option::Some(v));
1491 fn test_env_set_get_huge() {
1492 let n = make_rand_name();
1493 let s = "x".repeat(10000);
1495 assert_eq!(getenv(n), Some(s));
1497 assert_eq!(getenv(n), None);
1501 fn test_env_setenv() {
1502 let n = make_rand_name();
1506 assert!(!e.contains(&(n.clone(), ~"VALUE")));
1509 assert!(e.contains(&(n, ~"VALUE")));
1514 assert!((!Path::new("test-path").is_absolute()));
1517 debug!("Current working directory: {}", cwd.display());
1519 debug!("{:?}", make_absolute(&Path::new("test-path")));
1520 debug!("{:?}", make_absolute(&Path::new("/usr/bin")));
1526 let oldhome = getenv("HOME");
1528 setenv("HOME", "/home/MountainView");
1529 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1532 assert!(os::homedir().is_none());
1534 for s in oldhome.iter() { setenv("HOME", *s) }
1541 let oldhome = getenv("HOME");
1542 let olduserprofile = getenv("USERPROFILE");
1545 setenv("USERPROFILE", "");
1547 assert!(os::homedir().is_none());
1549 setenv("HOME", "/home/MountainView");
1550 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1554 setenv("USERPROFILE", "/home/MountainView");
1555 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1557 setenv("HOME", "/home/MountainView");
1558 setenv("USERPROFILE", "/home/PaloAlto");
1559 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1561 for s in oldhome.iter() { setenv("HOME", *s) }
1562 for s in olduserprofile.iter() { setenv("USERPROFILE", *s) }
1566 fn memory_map_rw() {
1567 use result::{Ok, Err};
1569 let chunk = match os::MemoryMap::new(16, [
1574 Err(msg) => fail!("{}", msg)
1576 assert!(chunk.len >= 16);
1580 assert!(*chunk.data == 0xBE);
1585 fn memory_map_file() {
1586 use result::{Ok, Err};
1592 fn lseek_(fd: c_int, size: uint) {
1594 assert!(lseek(fd, size as off_t, SEEK_SET) == size as off_t);
1598 fn lseek_(fd: c_int, size: uint) {
1600 assert!(lseek(fd, size as c_long, SEEK_SET) == size as c_long);
1604 let mut path = tmpdir();
1605 path.push("mmap_file.tmp");
1606 let size = MemoryMap::granularity() * 2;
1609 let fd = path.with_c_str(|path| {
1610 open(path, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR)
1613 "x".with_c_str(|x| assert!(write(fd, x as *c_void, 1) == 1));
1616 let chunk = match MemoryMap::new(size / 2, [
1623 Err(msg) => fail!("{}", msg)
1625 assert!(chunk.len > 0);
1629 assert!(*chunk.data == 0xbe);
1634 fs::unlink(&path).unwrap();
1637 // More recursive_mkdir tests are in extra::tempfile