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;
68 /// Returns the current working directory.
70 pub fn getcwd() -> Path {
73 let mut buf = [0 as c_char, ..BUF_BYTES];
75 if libc::getcwd(buf.as_mut_ptr(), buf.len() as libc::size_t).is_null() {
78 Path::new(CString::new(buf.as_ptr(), false))
82 /// Returns the current working directory.
84 pub fn getcwd() -> Path {
86 use libc::GetCurrentDirectoryW;
87 let mut buf = [0 as u16, ..BUF_BYTES];
89 if libc::GetCurrentDirectoryW(buf.len() as DWORD, buf.as_mut_ptr()) == 0 as DWORD {
93 Path::new(str::from_utf16(str::truncate_utf16_at_nul(buf))
94 .expect("GetCurrentDirectoryW returned invalid UTF-16"))
99 use libc::types::os::arch::extra::DWORD;
101 use option::{None, Option};
106 use slice::{MutableVector, ImmutableVector, OwnedVector};
109 pub fn fill_utf16_buf_and_decode(f: |*mut u16, DWORD| -> DWORD)
113 let mut n = TMPBUF_SZ as DWORD;
115 let mut done = false;
117 let mut buf = slice::from_elem(n as uint, 0u16);
118 let k = f(buf.as_mut_ptr(), n);
119 if k == (0 as DWORD) {
122 libc::GetLastError() ==
123 libc::ERROR_INSUFFICIENT_BUFFER as DWORD {
131 let sub = buf.slice(0, k as uint);
132 // We want to explicitly catch the case when the
133 // closure returned invalid UTF-16, rather than
134 // set `res` to None and continue.
135 let s = str::from_utf16(sub)
136 .expect("fill_utf16_buf_and_decode: closure created invalid UTF-16");
137 res = option::Some(s)
144 pub fn as_utf16_p<T>(s: &str, f: |*u16| -> T) -> T {
145 let mut t = s.to_utf16();
146 // Null terminate before passing on.
153 Accessing environment variables is not generally threadsafe.
154 Serialize access through a global lock.
156 fn with_env_lock<T>(f: || -> T) -> T {
157 use unstable::mutex::{StaticNativeMutex, NATIVE_MUTEX_INIT};
159 static mut lock: StaticNativeMutex = NATIVE_MUTEX_INIT;
162 let _guard = lock.lock();
167 /// Returns a vector of (variable, value) pairs for all the environment
168 /// variables of the current process.
170 /// Invalid UTF-8 bytes are replaced with \uFFFD. See `str::from_utf8_lossy()`
172 pub fn env() -> ~[(~str,~str)] {
173 env_as_bytes().move_iter().map(|(k,v)| {
174 let k = str::from_utf8_lossy(k).into_owned();
175 let v = str::from_utf8_lossy(v).into_owned();
180 /// Returns a vector of (variable, value) byte-vector pairs for all the
181 /// environment variables of the current process.
182 pub fn env_as_bytes() -> ~[(~[u8],~[u8])] {
185 unsafe fn get_env_pairs() -> ~[~[u8]] {
189 use libc::funcs::extra::kernel32::{
190 GetEnvironmentStringsA,
191 FreeEnvironmentStringsA
193 let ch = GetEnvironmentStringsA();
195 fail!("os::env() failure getting env string from OS: {}",
196 os::last_os_error());
198 let mut result = ~[];
199 c_str::from_c_multistring(ch as *c_char, None, |cstr| {
200 result.push(cstr.as_bytes_no_nul().to_owned());
202 FreeEnvironmentStringsA(ch);
206 unsafe fn get_env_pairs() -> ~[~[u8]] {
210 fn rust_env_pairs() -> **c_char;
212 let environ = rust_env_pairs();
213 if environ as uint == 0 {
214 fail!("os::env() failure getting env string from OS: {}",
215 os::last_os_error());
217 let mut result = ~[];
218 ptr::array_each(environ, |e| {
219 let env_pair = CString::new(e, false).as_bytes_no_nul().to_owned();
220 result.push(env_pair);
225 fn env_convert(input: ~[~[u8]]) -> ~[(~[u8], ~[u8])] {
227 for p in input.iter() {
228 let vs: ~[&[u8]] = p.splitn(1, |b| *b == '=' as u8).collect();
229 let key = vs[0].to_owned();
230 let val = if vs.len() < 2 { ~[] } else { vs[1].to_owned() };
231 pairs.push((key, val));
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.
246 /// Any invalid UTF-8 bytes in the value are replaced by \uFFFD. See
247 /// `str::from_utf8_lossy()` for details.
251 /// Fails if `n` has any interior NULs.
252 pub fn getenv(n: &str) -> Option<~str> {
253 getenv_as_bytes(n).map(|v| str::from_utf8_lossy(v).into_owned())
257 /// Fetches the environment variable `n` byte vector from the current process,
258 /// returning None if the variable isn't set.
262 /// Fails if `n` has any interior NULs.
263 pub fn getenv_as_bytes(n: &str) -> Option<~[u8]> {
268 let s = n.with_c_str(|buf| libc::getenv(buf));
272 Some(CString::new(s, false).as_bytes_no_nul().to_owned())
279 /// Fetches the environment variable `n` from the current process, returning
280 /// None if the variable isn't set.
281 pub fn getenv(n: &str) -> Option<~str> {
284 use os::win32::{as_utf16_p, fill_utf16_buf_and_decode};
286 fill_utf16_buf_and_decode(|buf, sz| {
287 libc::GetEnvironmentVariableW(u, buf, sz)
295 /// Fetches the environment variable `n` byte vector from the current process,
296 /// returning None if the variable isn't set.
297 pub fn getenv_as_bytes(n: &str) -> Option<~[u8]> {
298 getenv(n).map(|s| s.into_bytes())
303 /// Sets the environment variable `n` to the value `v` for the currently running
308 /// Fails if `n` or `v` have any interior NULs.
309 pub fn setenv(n: &str, v: &str) {
312 n.with_c_str(|nbuf| {
313 v.with_c_str(|vbuf| {
314 libc::funcs::posix01::unistd::setenv(nbuf, vbuf, 1);
323 /// Sets the environment variable `n` to the value `v` for the currently running
325 pub fn setenv(n: &str, v: &str) {
328 use os::win32::as_utf16_p;
329 as_utf16_p(n, |nbuf| {
330 as_utf16_p(v, |vbuf| {
331 libc::SetEnvironmentVariableW(nbuf, vbuf);
338 /// Remove a variable from the environment entirely
342 /// Fails (on unix) if `n` has any interior NULs.
343 pub fn unsetenv(n: &str) {
345 fn _unsetenv(n: &str) {
348 n.with_c_str(|nbuf| {
349 libc::funcs::posix01::unistd::unsetenv(nbuf);
355 fn _unsetenv(n: &str) {
358 use os::win32::as_utf16_p;
359 as_utf16_p(n, |nbuf| {
360 libc::SetEnvironmentVariableW(nbuf, ptr::null());
369 /// A low-level OS in-memory pipe.
371 /// A file descriptor representing the reading end of the pipe. Data written
372 /// on the `out` file descriptor can be read from this file descriptor.
374 /// A file descriptor representing the write end of the pipe. Data written
375 /// to this file descriptor can be read from the `input` file descriptor.
379 /// Creates a new low-level OS in-memory pipe.
381 pub fn pipe() -> Pipe {
383 let mut fds = Pipe {input: 0,
385 assert_eq!(libc::pipe(&mut fds.input), 0);
386 return Pipe {input: fds.input, out: fds.out};
390 /// Creates a new low-level OS in-memory pipe.
392 pub fn pipe() -> Pipe {
394 // Windows pipes work subtly differently than unix pipes, and their
395 // inheritance has to be handled in a different way that I do not
396 // fully understand. Here we explicitly make the pipe non-inheritable,
397 // which means to pass it to a subprocess they need to be duplicated
398 // first, as in std::run.
399 let mut fds = Pipe {input: 0,
401 let res = libc::pipe(&mut fds.input, 1024 as ::libc::c_uint,
402 (libc::O_BINARY | libc::O_NOINHERIT) as c_int);
404 assert!((fds.input != -1 && fds.input != 0 ));
405 assert!((fds.out != -1 && fds.input != 0));
406 return Pipe {input: fds.input, out: fds.out};
410 /// Returns the proper dll filename for the given basename of a file.
411 pub fn dll_filename(base: &str) -> ~str {
412 format!("{}{}{}", consts::DLL_PREFIX, base, consts::DLL_SUFFIX)
415 /// Optionally returns the filesystem path of the current executable which is
416 /// running. If any failure occurs, None is returned.
417 pub fn self_exe_name() -> Option<Path> {
419 #[cfg(target_os = "freebsd")]
420 fn load_self() -> Option<~[u8]> {
422 use libc::funcs::bsd44::*;
423 use libc::consts::os::extra::*;
425 let mib = ~[CTL_KERN as c_int,
427 KERN_PROC_PATHNAME as c_int, -1 as c_int];
428 let mut sz: libc::size_t = 0;
429 let err = sysctl(mib.as_ptr(), mib.len() as ::libc::c_uint,
430 ptr::mut_null(), &mut sz, ptr::null(),
432 if err != 0 { return None; }
433 if sz == 0 { return None; }
434 let mut v: ~[u8] = slice::with_capacity(sz as uint);
435 let err = sysctl(mib.as_ptr(), mib.len() as ::libc::c_uint,
436 v.as_mut_ptr() as *mut c_void, &mut sz, ptr::null(),
438 if err != 0 { return None; }
439 if sz == 0 { return None; }
440 v.set_len(sz as uint - 1); // chop off trailing NUL
445 #[cfg(target_os = "linux")]
446 #[cfg(target_os = "android")]
447 fn load_self() -> Option<~[u8]> {
450 match io::fs::readlink(&Path::new("/proc/self/exe")) {
451 Ok(path) => Some(path.as_vec().to_owned()),
456 #[cfg(target_os = "macos")]
457 fn load_self() -> Option<~[u8]> {
459 use libc::funcs::extra::_NSGetExecutablePath;
462 _NSGetExecutablePath(ptr::mut_null(), &mut sz);
463 if sz == 0 { return None; }
464 let mut v: ~[u8] = slice::with_capacity(sz as uint);
465 let err = _NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz);
466 if err != 0 { return None; }
467 v.set_len(sz as uint - 1); // chop off trailing NUL
473 fn load_self() -> Option<~[u8]> {
477 use os::win32::fill_utf16_buf_and_decode;
478 fill_utf16_buf_and_decode(|buf, sz| {
479 libc::GetModuleFileNameW(0u as libc::DWORD, buf, sz)
480 }).map(|s| s.into_bytes())
484 load_self().and_then(Path::new_opt)
487 /// Optionally returns the filesystem path to the current executable which is
488 /// running. Like self_exe_name() but without the binary's name.
489 /// If any failure occurs, None is returned.
490 pub fn self_exe_path() -> Option<Path> {
491 self_exe_name().map(|mut p| { p.pop(); p })
495 * Returns the path to the user's home directory, if known.
497 * On Unix, returns the value of the 'HOME' environment variable if it is set
498 * and not equal to the empty string.
500 * On Windows, returns the value of the 'HOME' environment variable if it is
501 * set and not equal to the empty string. Otherwise, returns the value of the
502 * 'USERPROFILE' environment variable if it is set and not equal to the empty
505 * Otherwise, homedir returns option::none.
507 pub fn homedir() -> Option<Path> {
508 // FIXME (#7188): getenv needs a ~[u8] variant
509 return match getenv("HOME") {
510 Some(ref p) if !p.is_empty() => Path::new_opt(p.as_slice()),
515 fn secondary() -> Option<Path> {
520 fn secondary() -> Option<Path> {
521 getenv("USERPROFILE").and_then(|p| {
532 * Returns the path to a temporary directory.
534 * On Unix, returns the value of the 'TMPDIR' environment variable if it is
535 * set and non-empty and '/tmp' otherwise.
536 * On Android, there is no global temporary folder (it is usually allocated
537 * per-app), hence returns '/data/tmp' which is commonly used.
539 * On Windows, returns the value of, in order, the 'TMP', 'TEMP',
540 * 'USERPROFILE' environment variable if any are set and not the empty
541 * string. Otherwise, tmpdir returns the path to the Windows directory.
543 pub fn tmpdir() -> Path {
546 fn getenv_nonempty(v: &str) -> Option<Path> {
559 fn lookup() -> Path {
560 if cfg!(target_os = "android") {
561 Path::new("/data/tmp")
563 getenv_nonempty("TMPDIR").unwrap_or(Path::new("/tmp"))
568 fn lookup() -> Path {
569 getenv_nonempty("TMP").or(
570 getenv_nonempty("TEMP").or(
571 getenv_nonempty("USERPROFILE").or(
572 getenv_nonempty("WINDIR")))).unwrap_or(Path::new("C:\\Windows"))
577 * Convert a relative path to an absolute path
579 * If the given path is relative, return it prepended with the current working
580 * directory. If the given path is already an absolute path, return it
583 // NB: this is here rather than in path because it is a form of environment
584 // querying; what it does depends on the process working directory, not just
586 pub fn make_absolute(p: &Path) -> Path {
590 let mut ret = getcwd();
596 /// Changes the current working directory to the specified path, returning
597 /// whether the change was completed successfully or not.
598 pub fn change_dir(p: &Path) -> bool {
602 fn chdir(p: &Path) -> bool {
604 use os::win32::as_utf16_p;
605 return as_utf16_p(p.as_str().unwrap(), |buf| {
606 libc::SetCurrentDirectoryW(buf) != (0 as libc::BOOL)
612 fn chdir(p: &Path) -> bool {
615 libc::chdir(buf) == (0 as c_int)
622 /// Returns the platform-specific value of errno
623 pub fn errno() -> int {
624 #[cfg(target_os = "macos")]
625 #[cfg(target_os = "freebsd")]
626 fn errno_location() -> *c_int {
628 fn __error() -> *c_int;
635 #[cfg(target_os = "linux")]
636 #[cfg(target_os = "android")]
637 fn errno_location() -> *c_int {
639 fn __errno_location() -> *c_int;
647 (*errno_location()) as int
652 /// Returns the platform-specific value of errno
653 pub fn errno() -> uint {
654 use libc::types::os::arch::extra::DWORD;
656 #[link_name = "kernel32"]
658 fn GetLastError() -> DWORD;
662 GetLastError() as uint
666 /// Get a string representing the platform-dependent last error
667 pub fn last_os_error() -> ~str {
669 fn strerror() -> ~str {
670 #[cfg(target_os = "macos")]
671 #[cfg(target_os = "android")]
672 #[cfg(target_os = "freebsd")]
673 fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: libc::size_t)
676 fn strerror_r(errnum: c_int, buf: *mut c_char,
677 buflen: libc::size_t) -> c_int;
680 strerror_r(errnum, buf, buflen)
684 // GNU libc provides a non-compliant version of strerror_r by default
685 // and requires macros to instead use the POSIX compliant variant.
686 // So we just use __xpg_strerror_r which is always POSIX compliant
687 #[cfg(target_os = "linux")]
688 fn strerror_r(errnum: c_int, buf: *mut c_char,
689 buflen: libc::size_t) -> c_int {
691 fn __xpg_strerror_r(errnum: c_int,
693 buflen: libc::size_t)
697 __xpg_strerror_r(errnum, buf, buflen)
701 let mut buf = [0 as c_char, ..TMPBUF_SZ];
703 let p = buf.as_mut_ptr();
705 if strerror_r(errno() as c_int, p, buf.len() as libc::size_t) < 0 {
706 fail!("strerror_r failure");
709 str::raw::from_c_str(p as *c_char)
714 fn strerror() -> ~str {
715 use libc::types::os::arch::extra::DWORD;
716 use libc::types::os::arch::extra::LPWSTR;
717 use libc::types::os::arch::extra::LPVOID;
718 use libc::types::os::arch::extra::WCHAR;
720 #[link_name = "kernel32"]
722 fn FormatMessageW(flags: DWORD,
732 static FORMAT_MESSAGE_FROM_SYSTEM: DWORD = 0x00001000;
733 static FORMAT_MESSAGE_IGNORE_INSERTS: DWORD = 0x00000200;
735 // This value is calculated from the macro
736 // MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT)
737 let langId = 0x0800 as DWORD;
738 let err = errno() as DWORD;
740 let mut buf = [0 as WCHAR, ..TMPBUF_SZ];
743 let res = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
744 FORMAT_MESSAGE_IGNORE_INSERTS,
752 // Sometimes FormatMessageW can fail e.g. system doesn't like langId,
753 let fm_err = errno();
754 return format!("OS Error {} (FormatMessageW() returned error {})", err, fm_err);
757 let msg = str::from_utf16(str::truncate_utf16_at_nul(buf));
759 Some(msg) => format!("OS Error {}: {}", err, msg),
760 None => format!("OS Error {} (FormatMessageW() returned invalid UTF-16)", err),
768 static mut EXIT_STATUS: AtomicInt = INIT_ATOMIC_INT;
771 * Sets the process exit code
773 * Sets the exit code returned by the process if all supervised tasks
774 * terminate successfully (without failing). If the current root task fails
775 * and is supervised by the scheduler then any user-specified exit status is
776 * ignored and the process exits with the default failure status.
778 * Note that this is not synchronized against modifications of other threads.
780 pub fn set_exit_status(code: int) {
781 unsafe { EXIT_STATUS.store(code, SeqCst) }
784 /// Fetches the process's current exit code. This defaults to 0 and can change
785 /// by calling `set_exit_status`.
786 pub fn get_exit_status() -> int {
787 unsafe { EXIT_STATUS.load(SeqCst) }
790 #[cfg(target_os = "macos")]
791 unsafe fn load_argc_and_argv(argc: int, argv: **c_char) -> ~[~[u8]] {
795 for i in range(0u, argc as uint) {
796 args.push(CString::new(*argv.offset(i as int), false).as_bytes_no_nul().to_owned())
802 * Returns the command line arguments
804 * Returns a list of the command line arguments.
806 #[cfg(target_os = "macos")]
807 fn real_args_as_bytes() -> ~[~[u8]] {
809 let (argc, argv) = (*_NSGetArgc() as int,
810 *_NSGetArgv() as **c_char);
811 load_argc_and_argv(argc, argv)
815 #[cfg(target_os = "linux")]
816 #[cfg(target_os = "android")]
817 #[cfg(target_os = "freebsd")]
818 fn real_args_as_bytes() -> ~[~[u8]] {
821 match rt::args::clone() {
823 None => fail!("process arguments not initialized")
828 fn real_args() -> ~[~str] {
829 real_args_as_bytes().move_iter().map(|v| str::from_utf8_lossy(v).into_owned()).collect()
833 fn real_args() -> ~[~str] {
836 let mut nArgs: c_int = 0;
837 let lpArgCount: *mut c_int = &mut nArgs;
838 let lpCmdLine = unsafe { GetCommandLineW() };
839 let szArgList = unsafe { CommandLineToArgvW(lpCmdLine, lpArgCount) };
842 for i in range(0u, nArgs as uint) {
844 // Determine the length of this argument.
845 let ptr = *szArgList.offset(i as int);
847 while *ptr.offset(len as int) != 0 { len += 1; }
849 // Push it onto the list.
850 let opt_s = slice::raw::buf_as_slice(ptr, len, |buf| {
851 str::from_utf16(str::truncate_utf16_at_nul(buf))
853 args.push(opt_s.expect("CommandLineToArgvW returned invalid UTF-16"));
858 LocalFree(szArgList as *c_void);
865 fn real_args_as_bytes() -> ~[~[u8]] {
866 real_args().move_iter().map(|s| s.into_bytes()).collect()
872 #[link_name="kernel32"]
874 fn GetCommandLineW() -> LPCWSTR;
875 fn LocalFree(ptr: *c_void);
879 #[link_name="shell32"]
881 fn CommandLineToArgvW(lpCmdLine: LPCWSTR, pNumArgs: *mut c_int) -> **u16;
884 /// Returns the arguments which this program was started with (normally passed
885 /// via the command line).
887 /// The arguments are interpreted as utf-8, with invalid bytes replaced with \uFFFD.
888 /// See `str::from_utf8_lossy` for details.
889 pub fn args() -> ~[~str] {
893 /// Returns the arguments which this program was started with (normally passed
894 /// via the command line) as byte vectors.
895 pub fn args_as_bytes() -> ~[~[u8]] {
899 #[cfg(target_os = "macos")]
901 // These functions are in crt_externs.h.
902 pub fn _NSGetArgc() -> *c_int;
903 pub fn _NSGetArgv() -> ***c_char;
906 // Round up `from` to be divisible by `to`
907 fn round_up(from: uint, to: uint) -> uint {
908 let r = if from % to == 0 {
911 from + to - (from % to)
920 /// Returns the page size of the current architecture in bytes.
922 pub fn page_size() -> uint {
924 libc::sysconf(libc::_SC_PAGESIZE) as uint
928 /// Returns the page size of the current architecture in bytes.
930 pub fn page_size() -> uint {
932 let mut info = libc::SYSTEM_INFO::new();
933 libc::GetSystemInfo(&mut info);
935 return info.dwPageSize as uint;
939 /// A memory mapped file or chunk of memory. This is a very system-specific
940 /// interface to the OS's memory mapping facilities (`mmap` on POSIX,
941 /// `VirtualAlloc`/`CreateFileMapping` on win32). It makes no attempt at
942 /// abstracting platform differences, besides in error values returned. Consider
945 /// The memory map is released (unmapped) when the destructor is run, so don't
946 /// let it leave scope by accident if you want it to stick around.
947 pub struct MemoryMap {
948 /// Pointer to the memory created or modified by this map.
950 /// Number of bytes this map applies to
956 /// Type of memory map
957 pub enum MemoryMapKind {
958 /// Virtual memory map. Usually used to change the permissions of a given
959 /// chunk of memory. Corresponds to `VirtualAlloc` on Windows.
961 /// Virtual memory map. Usually used to change the permissions of a given
962 /// chunk of memory, or for allocation. Corresponds to `VirtualAlloc` on
967 /// Options the memory map is created with
969 /// The memory should be readable
971 /// The memory should be writable
973 /// The memory should be executable
975 /// Create a map for a specific address range. Corresponds to `MAP_FIXED` on
978 /// Create a memory mapping for a file with a given fd.
980 /// When using `MapFd`, the start of the map is `uint` bytes from the start
983 /// On POSIX, this can be used to specify the default flags passed to
984 /// `mmap`. By default it uses `MAP_PRIVATE` and, if not using `MapFd`,
985 /// `MAP_ANON`. This will override both of those. This is platform-specific
986 /// (the exact values used) and ignored on Windows.
987 MapNonStandardFlags(c_int),
990 /// Possible errors when creating a map.
992 /// ## The following are POSIX-specific
994 /// fd was not open for reading or, if using `MapWritable`, was not open for
999 /// Either the address given by `MapAddr` or offset given by `MapOffset` was
1000 /// not a multiple of `MemoryMap::granularity` (unaligned to page size).
1002 /// With `MapFd`, the fd does not support mapping.
1004 /// If using `MapAddr`, the address + `min_len` was outside of the process's
1005 /// address space. If using `MapFd`, the target of the fd didn't have enough
1006 /// resources to fulfill the request.
1008 /// A zero-length map was requested. This is invalid according to
1009 /// [POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/functions/mmap.html).
1010 /// Not all platforms obey this, but this wrapper does.
1012 /// Unrecognized error. The inner value is the unrecognized errno.
1014 /// ## The following are win32-specific
1016 /// Unsupported combination of protection flags
1017 /// (`MapReadable`/`MapWritable`/`MapExecutable`).
1019 /// When using `MapFd`, `MapOffset` was given (Windows does not support this
1022 /// When using `MapFd`, there was already a mapping to the file.
1024 /// Unrecognized error from `VirtualAlloc`. The inner value is the return
1025 /// value of GetLastError.
1026 ErrVirtualAlloc(uint),
1027 /// Unrecognized error from `CreateFileMapping`. The inner value is the
1028 /// return value of `GetLastError`.
1029 ErrCreateFileMappingW(uint),
1030 /// Unrecognized error from `MapViewOfFile`. The inner value is the return
1031 /// value of `GetLastError`.
1032 ErrMapViewOfFile(uint)
1035 impl fmt::Show for MapError {
1036 fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result {
1037 let str = match *self {
1038 ErrFdNotAvail => "fd not available for reading or writing",
1039 ErrInvalidFd => "Invalid fd",
1041 "Unaligned address, invalid flags, negative length or \
1044 ErrNoMapSupport=> "File doesn't support mapping",
1045 ErrNoMem => "Invalid address, or not enough available memory",
1046 ErrUnsupProt => "Protection mode unsupported",
1047 ErrUnsupOffset => "Offset in virtual memory mode is unsupported",
1048 ErrAlreadyExists => "File mapping for specified file already exists",
1049 ErrZeroLength => "Zero-length mapping not allowed",
1050 ErrUnknown(code) => {
1051 return write!(out.buf, "Unknown error = {}", code)
1053 ErrVirtualAlloc(code) => {
1054 return write!(out.buf, "VirtualAlloc failure = {}", code)
1056 ErrCreateFileMappingW(code) => {
1057 return write!(out.buf, "CreateFileMappingW failure = {}", code)
1059 ErrMapViewOfFile(code) => {
1060 return write!(out.buf, "MapViewOfFile failure = {}", code)
1063 write!(out.buf, "{}", str)
1069 /// Create a new mapping with the given `options`, at least `min_len` bytes
1070 /// long. `min_len` must be greater than zero; see the note on
1071 /// `ErrZeroLength`.
1072 pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
1077 return Err(ErrZeroLength)
1079 let mut addr: *u8 = ptr::null();
1081 let mut flags = libc::MAP_PRIVATE;
1084 let mut custom_flags = false;
1085 let len = round_up(min_len, page_size());
1087 for &o in options.iter() {
1089 MapReadable => { prot |= libc::PROT_READ; },
1090 MapWritable => { prot |= libc::PROT_WRITE; },
1091 MapExecutable => { prot |= libc::PROT_EXEC; },
1093 flags |= libc::MAP_FIXED;
1097 flags |= libc::MAP_FILE;
1100 MapOffset(offset_) => { offset = offset_ as off_t; },
1101 MapNonStandardFlags(f) => { custom_flags = true; flags = f },
1104 if fd == -1 && !custom_flags { flags |= libc::MAP_ANON; }
1107 libc::mmap(addr as *c_void, len as libc::size_t, prot, flags, fd,
1110 if r.equiv(&libc::MAP_FAILED) {
1111 Err(match errno() as c_int {
1112 libc::EACCES => ErrFdNotAvail,
1113 libc::EBADF => ErrInvalidFd,
1114 libc::EINVAL => ErrUnaligned,
1115 libc::ENODEV => ErrNoMapSupport,
1116 libc::ENOMEM => ErrNoMem,
1117 code => ErrUnknown(code as int)
1126 MapFile(ptr::null())
1132 /// Granularity that the offset or address must be for `MapOffset` and
1133 /// `MapAddr` respectively.
1134 pub fn granularity() -> uint {
1140 impl Drop for MemoryMap {
1141 /// Unmap the mapping. Fails the task if `munmap` fails.
1142 fn drop(&mut self) {
1143 if self.len == 0 { /* workaround for dummy_stack */ return; }
1146 // FIXME: what to do if this fails?
1147 let _ = libc::munmap(self.data as *c_void, self.len as libc::size_t);
1154 /// Create a new mapping with the given `options`, at least `min_len` bytes long.
1155 pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
1156 use libc::types::os::arch::extra::{LPVOID, DWORD, SIZE_T, HANDLE};
1158 let mut lpAddress: LPVOID = ptr::mut_null();
1159 let mut readable = false;
1160 let mut writable = false;
1161 let mut executable = false;
1162 let mut fd: c_int = -1;
1163 let mut offset: uint = 0;
1164 let len = round_up(min_len, page_size());
1166 for &o in options.iter() {
1168 MapReadable => { readable = true; },
1169 MapWritable => { writable = true; },
1170 MapExecutable => { executable = true; }
1171 MapAddr(addr_) => { lpAddress = addr_ as LPVOID; },
1172 MapFd(fd_) => { fd = fd_; },
1173 MapOffset(offset_) => { offset = offset_; },
1174 MapNonStandardFlags(..) => {}
1178 let flProtect = match (executable, readable, writable) {
1179 (false, false, false) if fd == -1 => libc::PAGE_NOACCESS,
1180 (false, true, false) => libc::PAGE_READONLY,
1181 (false, true, true) => libc::PAGE_READWRITE,
1182 (true, false, false) if fd == -1 => libc::PAGE_EXECUTE,
1183 (true, true, false) => libc::PAGE_EXECUTE_READ,
1184 (true, true, true) => libc::PAGE_EXECUTE_READWRITE,
1185 _ => return Err(ErrUnsupProt)
1190 return Err(ErrUnsupOffset);
1193 libc::VirtualAlloc(lpAddress,
1195 libc::MEM_COMMIT | libc::MEM_RESERVE,
1199 0 => Err(ErrVirtualAlloc(errno())),
1207 let dwDesiredAccess = match (executable, readable, writable) {
1208 (false, true, false) => libc::FILE_MAP_READ,
1209 (false, true, true) => libc::FILE_MAP_WRITE,
1210 (true, true, false) => libc::FILE_MAP_READ | libc::FILE_MAP_EXECUTE,
1211 (true, true, true) => libc::FILE_MAP_WRITE | libc::FILE_MAP_EXECUTE,
1212 _ => return Err(ErrUnsupProt) // Actually, because of the check above,
1213 // we should never get here.
1216 let hFile = libc::get_osfhandle(fd) as HANDLE;
1217 let mapping = libc::CreateFileMappingW(hFile,
1223 if mapping == ptr::mut_null() {
1224 return Err(ErrCreateFileMappingW(errno()));
1226 if errno() as c_int == libc::ERROR_ALREADY_EXISTS {
1227 return Err(ErrAlreadyExists);
1229 let r = libc::MapViewOfFile(mapping,
1231 ((len as u64) >> 32) as DWORD,
1232 (offset & 0xffff_ffff) as DWORD,
1235 0 => Err(ErrMapViewOfFile(errno())),
1239 kind: MapFile(mapping as *u8)
1246 /// Granularity of MapAddr() and MapOffset() parameter values.
1247 /// This may be greater than the value returned by page_size().
1248 pub fn granularity() -> uint {
1250 let mut info = libc::SYSTEM_INFO::new();
1251 libc::GetSystemInfo(&mut info);
1253 return info.dwAllocationGranularity as uint;
1259 impl Drop for MemoryMap {
1260 /// Unmap the mapping. Fails the task if any of `VirtualFree`,
1261 /// `UnmapViewOfFile`, or `CloseHandle` fail.
1262 fn drop(&mut self) {
1263 use libc::types::os::arch::extra::{LPCVOID, HANDLE};
1264 use libc::consts::os::extra::FALSE;
1265 if self.len == 0 { return }
1270 if libc::VirtualFree(self.data as *mut c_void, 0,
1271 libc::MEM_RELEASE) == 0 {
1272 println!("VirtualFree failed: {}", errno());
1275 MapFile(mapping) => {
1276 if libc::UnmapViewOfFile(self.data as LPCVOID) == FALSE {
1277 println!("UnmapViewOfFile failed: {}", errno());
1279 if libc::CloseHandle(mapping as HANDLE) == FALSE {
1280 println!("CloseHandle failed: {}", errno());
1288 /// Various useful system-specific constants.
1291 pub use os::consts::unix::*;
1294 pub use os::consts::windows::*;
1296 #[cfg(target_os = "macos")]
1297 pub use os::consts::macos::*;
1299 #[cfg(target_os = "freebsd")]
1300 pub use os::consts::freebsd::*;
1302 #[cfg(target_os = "linux")]
1303 pub use os::consts::linux::*;
1305 #[cfg(target_os = "android")]
1306 pub use os::consts::android::*;
1308 #[cfg(target_os = "win32")]
1309 pub use os::consts::win32::*;
1311 #[cfg(target_arch = "x86")]
1312 pub use os::consts::x86::*;
1314 #[cfg(target_arch = "x86_64")]
1315 pub use os::consts::x86_64::*;
1317 #[cfg(target_arch = "arm")]
1318 pub use os::consts::arm::*;
1320 #[cfg(target_arch = "mips")]
1321 pub use os::consts::mips::*;
1323 /// Constants for Unix systems.
1325 /// A string describing the family that this operating system belongs
1326 /// to: in this case, `unix`.
1327 pub static FAMILY: &'static str = "unix";
1330 /// Constants for Windows systems.
1332 /// A string describing the family that this operating system belongs
1333 /// to: in this case, `windows`.
1334 pub static FAMILY: &'static str = "windows";
1337 /// Constants for Mac OS systems.
1339 /// A string describing the specific operating system in use: in this
1341 pub static SYSNAME: &'static str = "macos";
1343 /// Specifies the filename prefix used for shared libraries on this
1344 /// platform: in this case, `lib`.
1345 pub static DLL_PREFIX: &'static str = "lib";
1347 /// Specifies the filename suffix used for shared libraries on this
1348 /// platform: in this case, `.dylib`.
1349 pub static DLL_SUFFIX: &'static str = ".dylib";
1351 /// Specifies the file extension used for shared libraries on this
1352 /// platform that goes after the dot: in this case, `dylib`.
1353 pub static DLL_EXTENSION: &'static str = "dylib";
1355 /// Specifies the filename suffix used for executable binaries on this
1356 /// platform: in this case, the empty string.
1357 pub static EXE_SUFFIX: &'static str = "";
1359 /// Specifies the file extension, if any, used for executable binaries
1360 /// on this platform: in this case, the empty string.
1361 pub static EXE_EXTENSION: &'static str = "";
1364 /// Constants for FreeBSD systems.
1366 /// A string describing the specific operating system in use: in this
1367 /// case, `freebsd`.
1368 pub static SYSNAME: &'static str = "freebsd";
1370 /// Specifies the filename prefix used for shared libraries on this
1371 /// platform: in this case, `lib`.
1372 pub static DLL_PREFIX: &'static str = "lib";
1374 /// Specifies the filename suffix used for shared libraries on this
1375 /// platform: in this case, `.so`.
1376 pub static DLL_SUFFIX: &'static str = ".so";
1378 /// Specifies the file extension used for shared libraries on this
1379 /// platform that goes after the dot: in this case, `so`.
1380 pub static DLL_EXTENSION: &'static str = "so";
1382 /// Specifies the filename suffix used for executable binaries on this
1383 /// platform: in this case, the empty string.
1384 pub static EXE_SUFFIX: &'static str = "";
1386 /// Specifies the file extension, if any, used for executable binaries
1387 /// on this platform: in this case, the empty string.
1388 pub static EXE_EXTENSION: &'static str = "";
1391 /// Constants for GNU/Linux systems.
1393 /// A string describing the specific operating system in use: in this
1395 pub static SYSNAME: &'static str = "linux";
1397 /// Specifies the filename prefix used for shared libraries on this
1398 /// platform: in this case, `lib`.
1399 pub static DLL_PREFIX: &'static str = "lib";
1401 /// Specifies the filename suffix used for shared libraries on this
1402 /// platform: in this case, `.so`.
1403 pub static DLL_SUFFIX: &'static str = ".so";
1405 /// Specifies the file extension used for shared libraries on this
1406 /// platform that goes after the dot: in this case, `so`.
1407 pub static DLL_EXTENSION: &'static str = "so";
1409 /// Specifies the filename suffix used for executable binaries on this
1410 /// platform: in this case, the empty string.
1411 pub static EXE_SUFFIX: &'static str = "";
1413 /// Specifies the file extension, if any, used for executable binaries
1414 /// on this platform: in this case, the empty string.
1415 pub static EXE_EXTENSION: &'static str = "";
1418 /// Constants for Android systems.
1420 /// A string describing the specific operating system in use: in this
1421 /// case, `android`.
1422 pub static SYSNAME: &'static str = "android";
1424 /// Specifies the filename prefix used for shared libraries on this
1425 /// platform: in this case, `lib`.
1426 pub static DLL_PREFIX: &'static str = "lib";
1428 /// Specifies the filename suffix used for shared libraries on this
1429 /// platform: in this case, `.so`.
1430 pub static DLL_SUFFIX: &'static str = ".so";
1432 /// Specifies the file extension used for shared libraries on this
1433 /// platform that goes after the dot: in this case, `so`.
1434 pub static DLL_EXTENSION: &'static str = "so";
1436 /// Specifies the filename suffix used for executable binaries on this
1437 /// platform: in this case, the empty string.
1438 pub static EXE_SUFFIX: &'static str = "";
1440 /// Specifies the file extension, if any, used for executable binaries
1441 /// on this platform: in this case, the empty string.
1442 pub static EXE_EXTENSION: &'static str = "";
1445 /// Constants for 32-bit or 64-bit Windows systems.
1447 /// A string describing the specific operating system in use: in this
1449 pub static SYSNAME: &'static str = "win32";
1451 /// Specifies the filename prefix used for shared libraries on this
1452 /// platform: in this case, the empty string.
1453 pub static DLL_PREFIX: &'static str = "";
1455 /// Specifies the filename suffix used for shared libraries on this
1456 /// platform: in this case, `.dll`.
1457 pub static DLL_SUFFIX: &'static str = ".dll";
1459 /// Specifies the file extension used for shared libraries on this
1460 /// platform that goes after the dot: in this case, `dll`.
1461 pub static DLL_EXTENSION: &'static str = "dll";
1463 /// Specifies the filename suffix used for executable binaries on this
1464 /// platform: in this case, `.exe`.
1465 pub static EXE_SUFFIX: &'static str = ".exe";
1467 /// Specifies the file extension, if any, used for executable binaries
1468 /// on this platform: in this case, `exe`.
1469 pub static EXE_EXTENSION: &'static str = "exe";
1472 /// Constants for Intel Architecture-32 (x86) architectures.
1474 /// A string describing the architecture in use: in this case, `x86`.
1475 pub static ARCH: &'static str = "x86";
1477 /// Constants for Intel 64/AMD64 (x86-64) architectures.
1479 /// A string describing the architecture in use: in this case,
1481 pub static ARCH: &'static str = "x86_64";
1483 /// Constants for Advanced RISC Machine (ARM) architectures.
1485 /// A string describing the architecture in use: in this case, `ARM`.
1486 pub static ARCH: &'static str = "arm";
1488 /// Constants for Microprocessor without Interlocked Pipeline Stages
1489 /// (MIPS) architectures.
1491 /// A string describing the architecture in use: in this case, `MIPS`.
1492 pub static ARCH: &'static str = "mips";
1501 use os::{env, getcwd, getenv, make_absolute, args};
1502 use os::{setenv, unsetenv};
1508 pub fn last_os_error() {
1509 debug!("{}", os::last_os_error());
1513 pub fn test_args() {
1515 assert!(a.len() >= 1);
1518 fn make_rand_name() -> ~str {
1519 let mut rng = rand::task_rng();
1520 let n = ~"TEST" + rng.gen_ascii_str(10u);
1521 assert!(getenv(n).is_none());
1527 let n = make_rand_name();
1529 assert_eq!(getenv(n), option::Some(~"VALUE"));
1533 fn test_unsetenv() {
1534 let n = make_rand_name();
1537 assert_eq!(getenv(n), option::None);
1542 fn test_setenv_overwrite() {
1543 let n = make_rand_name();
1546 assert_eq!(getenv(n), option::Some(~"2"));
1548 assert_eq!(getenv(n), option::Some(~""));
1551 // Windows GetEnvironmentVariable requires some extra work to make sure
1552 // the buffer the variable is copied into is the right size
1555 fn test_getenv_big() {
1559 s = s + "aaaaaaaaaa";
1562 let n = make_rand_name();
1564 debug!("{}", s.clone());
1565 assert_eq!(getenv(n), option::Some(s));
1569 fn test_self_exe_name() {
1570 let path = os::self_exe_name();
1571 assert!(path.is_some());
1572 let path = path.unwrap();
1573 debug!("{:?}", path.clone());
1575 // Hard to test this function
1576 assert!(path.is_absolute());
1580 fn test_self_exe_path() {
1581 let path = os::self_exe_path();
1582 assert!(path.is_some());
1583 let path = path.unwrap();
1584 debug!("{:?}", path.clone());
1586 // Hard to test this function
1587 assert!(path.is_absolute());
1592 fn test_env_getenv() {
1594 assert!(e.len() > 0u);
1596 let (n, v) = (*p).clone();
1597 debug!("{:?}", n.clone());
1599 // MingW seems to set some funky environment variables like
1600 // "=C:=C:\MinGW\msys\1.0\bin" and "!::=::\" that are returned
1601 // from env() but not visible from getenv().
1602 assert!(v2.is_none() || v2 == option::Some(v));
1607 fn test_env_set_get_huge() {
1608 let n = make_rand_name();
1609 let s = "x".repeat(10000);
1611 assert_eq!(getenv(n), Some(s));
1613 assert_eq!(getenv(n), None);
1617 fn test_env_setenv() {
1618 let n = make_rand_name();
1622 assert!(!e.contains(&(n.clone(), ~"VALUE")));
1625 assert!(e.contains(&(n, ~"VALUE")));
1630 assert!((!Path::new("test-path").is_absolute()));
1633 debug!("Current working directory: {}", cwd.display());
1635 debug!("{:?}", make_absolute(&Path::new("test-path")));
1636 debug!("{:?}", make_absolute(&Path::new("/usr/bin")));
1642 let oldhome = getenv("HOME");
1644 setenv("HOME", "/home/MountainView");
1645 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1648 assert!(os::homedir().is_none());
1650 for s in oldhome.iter() { setenv("HOME", *s) }
1657 let oldhome = getenv("HOME");
1658 let olduserprofile = getenv("USERPROFILE");
1661 setenv("USERPROFILE", "");
1663 assert!(os::homedir().is_none());
1665 setenv("HOME", "/home/MountainView");
1666 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1670 setenv("USERPROFILE", "/home/MountainView");
1671 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1673 setenv("HOME", "/home/MountainView");
1674 setenv("USERPROFILE", "/home/PaloAlto");
1675 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1677 for s in oldhome.iter() { setenv("HOME", *s) }
1678 for s in olduserprofile.iter() { setenv("USERPROFILE", *s) }
1682 fn memory_map_rw() {
1683 use result::{Ok, Err};
1685 let chunk = match os::MemoryMap::new(16, [
1690 Err(msg) => fail!("{}", msg)
1692 assert!(chunk.len >= 16);
1696 assert!(*chunk.data == 0xBE);
1701 fn memory_map_file() {
1702 use result::{Ok, Err};
1708 fn lseek_(fd: c_int, size: uint) {
1710 assert!(lseek(fd, size as off_t, SEEK_SET) == size as off_t);
1714 fn lseek_(fd: c_int, size: uint) {
1716 assert!(lseek(fd, size as c_long, SEEK_SET) == size as c_long);
1720 let mut path = tmpdir();
1721 path.push("mmap_file.tmp");
1722 let size = MemoryMap::granularity() * 2;
1725 let fd = path.with_c_str(|path| {
1726 open(path, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR)
1729 "x".with_c_str(|x| assert!(write(fd, x as *c_void, 1) == 1));
1732 let chunk = match MemoryMap::new(size / 2, [
1739 Err(msg) => fail!("{}", msg)
1741 assert!(chunk.len > 0);
1745 assert!(*chunk.data == 0xbe);
1750 fs::unlink(&path).unwrap();
1753 // More recursive_mkdir tests are in extra::tempfile