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;
35 #[cfg(target_os = "macos")]
38 use libc::{c_char, c_void, c_int, size_t};
39 use option::{Some, None};
45 use unstable::finally::Finally;
47 pub use os::consts::*;
49 /// Delegates to the libc close() function, returning the same return value.
50 pub fn close(fd: c_int) -> c_int {
56 pub static TMPBUF_SZ : uint = 1000u;
57 static BUF_BYTES : uint = 2048u;
60 pub fn getcwd() -> Path {
61 let mut buf = [0 as libc::c_char, ..BUF_BYTES];
63 if libc::getcwd(buf.as_mut_ptr(), buf.len() as size_t).is_null() {
66 Path::new(CString::new(buf.as_ptr(), false))
71 pub fn getcwd() -> Path {
73 use libc::GetCurrentDirectoryW;
74 let mut buf = [0 as u16, ..BUF_BYTES];
76 if libc::GetCurrentDirectoryW(buf.len() as DWORD, buf.as_mut_ptr()) == 0 as DWORD {
80 Path::new(str::from_utf16(buf))
88 use option::{None, Option};
91 use libc::types::os::arch::extra::DWORD;
93 pub fn fill_utf16_buf_and_decode(f: |*mut u16, DWORD| -> DWORD)
97 let mut n = TMPBUF_SZ as DWORD;
101 let mut buf = vec::from_elem(n as uint, 0u16);
102 let k = f(buf.as_mut_ptr(), TMPBUF_SZ as DWORD);
103 if k == (0 as DWORD) {
106 libc::GetLastError() ==
107 libc::ERROR_INSUFFICIENT_BUFFER as DWORD) {
113 let sub = buf.slice(0, k as uint);
114 res = option::Some(str::from_utf16(sub));
121 pub fn as_utf16_p<T>(s: &str, f: |*u16| -> T) -> T {
122 let mut t = s.to_utf16();
123 // Null terminate before passing on.
130 Accessing environment variables is not generally threadsafe.
131 Serialize access through a global lock.
133 fn with_env_lock<T>(f: || -> T) -> T {
134 use unstable::mutex::{Mutex, MUTEX_INIT};
135 use unstable::finally::Finally;
137 static mut lock: Mutex = MUTEX_INIT;
143 }).finally(|| lock.unlock());
147 /// Returns a vector of (variable, value) pairs for all the environment
148 /// variables of the current process.
149 pub fn env() -> ~[(~str,~str)] {
152 unsafe fn get_env_pairs() -> ~[~str] {
156 use libc::funcs::extra::kernel32::{
157 GetEnvironmentStringsA,
158 FreeEnvironmentStringsA
160 let ch = GetEnvironmentStringsA();
161 if (ch as uint == 0) {
162 fail!("os::env() failure getting env string from OS: {}",
163 os::last_os_error());
165 let mut result = ~[];
166 c_str::from_c_multistring(ch as *libc::c_char, None, |cstr| {
167 result.push(cstr.as_str().unwrap().to_owned());
169 FreeEnvironmentStringsA(ch);
173 unsafe fn get_env_pairs() -> ~[~str] {
175 fn rust_env_pairs() -> **libc::c_char;
177 let environ = rust_env_pairs();
178 if (environ as uint == 0) {
179 fail!("os::env() failure getting env string from OS: {}",
180 os::last_os_error());
182 let mut result = ~[];
183 ptr::array_each(environ, |e| {
184 let env_pair = str::raw::from_c_str(e);
185 debug!("get_env_pairs: {}", env_pair);
186 result.push(env_pair);
191 fn env_convert(input: ~[~str]) -> ~[(~str, ~str)] {
193 for p in input.iter() {
194 let vs: ~[&str] = p.splitn('=', 1).collect();
195 debug!("splitting: len: {}", vs.len());
196 assert_eq!(vs.len(), 2);
197 pairs.push((vs[0].to_owned(), vs[1].to_owned()));
202 let unparsed_environ = get_env_pairs();
203 env_convert(unparsed_environ)
209 /// Fetches the environment variable `n` from the current process, returning
210 /// None if the variable isn't set.
211 pub fn getenv(n: &str) -> Option<~str> {
214 let s = n.with_c_str(|buf| libc::getenv(buf));
218 Some(str::raw::from_c_str(s))
225 /// Fetches the environment variable `n` from the current process, returning
226 /// None if the variable isn't set.
227 pub fn getenv(n: &str) -> Option<~str> {
230 use os::win32::{as_utf16_p, fill_utf16_buf_and_decode};
232 fill_utf16_buf_and_decode(|buf, sz| {
233 libc::GetEnvironmentVariableW(u, buf, sz)
242 /// Sets the environment variable `n` to the value `v` for the currently running
244 pub fn setenv(n: &str, v: &str) {
247 n.with_c_str(|nbuf| {
248 v.with_c_str(|vbuf| {
249 libc::funcs::posix01::unistd::setenv(nbuf, vbuf, 1);
258 /// Sets the environment variable `n` to the value `v` for the currently running
260 pub fn setenv(n: &str, v: &str) {
263 use os::win32::as_utf16_p;
264 as_utf16_p(n, |nbuf| {
265 as_utf16_p(v, |vbuf| {
266 libc::SetEnvironmentVariableW(nbuf, vbuf);
273 /// Remove a variable from the environment entirely
274 pub fn unsetenv(n: &str) {
276 fn _unsetenv(n: &str) {
279 n.with_c_str(|nbuf| {
280 libc::funcs::posix01::unistd::unsetenv(nbuf);
286 fn _unsetenv(n: &str) {
289 use os::win32::as_utf16_p;
290 as_utf16_p(n, |nbuf| {
291 libc::SetEnvironmentVariableW(nbuf, ptr::null());
306 pub fn pipe() -> Pipe {
308 let mut fds = Pipe {input: 0 as c_int,
310 assert_eq!(libc::pipe(&mut fds.input), (0 as c_int));
311 return Pipe {input: fds.input, out: fds.out};
316 pub fn pipe() -> Pipe {
318 // Windows pipes work subtly differently than unix pipes, and their
319 // inheritance has to be handled in a different way that I do not
320 // fully understand. Here we explicitly make the pipe non-inheritable,
321 // which means to pass it to a subprocess they need to be duplicated
322 // first, as in std::run.
323 let mut fds = Pipe {input: 0 as c_int,
325 let res = libc::pipe(&mut fds.input, 1024 as ::libc::c_uint,
326 (libc::O_BINARY | libc::O_NOINHERIT) as c_int);
327 assert_eq!(res, 0 as c_int);
328 assert!((fds.input != -1 as c_int && fds.input != 0 as c_int));
329 assert!((fds.out != -1 as c_int && fds.input != 0 as c_int));
330 return Pipe {input: fds.input, out: fds.out};
334 /// Returns the proper dll filename for the given basename of a file.
335 pub fn dll_filename(base: &str) -> ~str {
336 format!("{}{}{}", DLL_PREFIX, base, DLL_SUFFIX)
339 /// Optionally returns the filesystem path to the current executable which is
340 /// running. If any failure occurs, None is returned.
341 pub fn self_exe_path() -> Option<Path> {
343 #[cfg(target_os = "freebsd")]
344 fn load_self() -> Option<~[u8]> {
346 use libc::funcs::bsd44::*;
347 use libc::consts::os::extra::*;
349 let mib = ~[CTL_KERN as c_int,
351 KERN_PROC_PATHNAME as c_int, -1 as c_int];
352 let mut sz: size_t = 0;
353 let err = sysctl(mib.as_ptr(), mib.len() as ::libc::c_uint,
354 ptr::mut_null(), &mut sz, ptr::null(), 0u as size_t);
355 if err != 0 { return None; }
356 if sz == 0 { return None; }
357 let mut v: ~[u8] = vec::with_capacity(sz as uint);
358 let err = sysctl(mib.as_ptr(), mib.len() as ::libc::c_uint,
359 v.as_mut_ptr() as *mut c_void, &mut sz, ptr::null(), 0u as size_t);
360 if err != 0 { return None; }
361 if sz == 0 { return None; }
362 v.set_len(sz as uint - 1); // chop off trailing NUL
367 #[cfg(target_os = "linux")]
368 #[cfg(target_os = "android")]
369 fn load_self() -> Option<~[u8]> {
372 match io::result(|| io::fs::readlink(&Path::new("/proc/self/exe"))) {
373 Ok(Some(path)) => Some(path.as_vec().to_owned()),
374 Ok(None) | Err(..) => None
378 #[cfg(target_os = "macos")]
379 fn load_self() -> Option<~[u8]> {
381 use libc::funcs::extra::_NSGetExecutablePath;
384 _NSGetExecutablePath(ptr::mut_null(), &mut sz);
385 if sz == 0 { return None; }
386 let mut v: ~[u8] = vec::with_capacity(sz as uint);
387 let err = _NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz);
388 if err != 0 { return None; }
389 v.set_len(sz as uint - 1); // chop off trailing NUL
395 fn load_self() -> Option<~[u8]> {
397 use os::win32::fill_utf16_buf_and_decode;
398 fill_utf16_buf_and_decode(|buf, sz| {
399 libc::GetModuleFileNameW(0u as libc::DWORD, buf, sz)
400 }).map(|s| s.into_bytes())
404 load_self().and_then(|path| Path::new_opt(path).map(|mut p| { p.pop(); p }))
408 * Returns the path to the user's home directory, if known.
410 * On Unix, returns the value of the 'HOME' environment variable if it is set
411 * and not equal to the empty string.
413 * On Windows, returns the value of the 'HOME' environment variable if it is
414 * set and not equal to the empty string. Otherwise, returns the value of the
415 * 'USERPROFILE' environment variable if it is set and not equal to the empty
418 * Otherwise, homedir returns option::none.
420 pub fn homedir() -> Option<Path> {
421 // FIXME (#7188): getenv needs a ~[u8] variant
422 return match getenv("HOME") {
423 Some(ref p) if !p.is_empty() => Path::new_opt(p.as_slice()),
428 fn secondary() -> Option<Path> {
433 fn secondary() -> Option<Path> {
434 getenv("USERPROFILE").and_then(|p| {
445 * Returns the path to a temporary directory.
447 * On Unix, returns the value of the 'TMPDIR' environment variable if it is
448 * set and non-empty and '/tmp' otherwise.
449 * On Android, there is no global temporary folder (it is usually allocated
450 * per-app), hence returns '/data/tmp' which is commonly used.
452 * On Windows, returns the value of, in order, the 'TMP', 'TEMP',
453 * 'USERPROFILE' environment variable if any are set and not the empty
454 * string. Otherwise, tmpdir returns the path to the Windows directory.
456 pub fn tmpdir() -> Path {
459 fn getenv_nonempty(v: &str) -> Option<Path> {
472 fn lookup() -> Path {
473 if cfg!(target_os = "android") {
474 Path::new("/data/tmp")
476 getenv_nonempty("TMPDIR").unwrap_or(Path::new("/tmp"))
481 fn lookup() -> Path {
482 getenv_nonempty("TMP").or(
483 getenv_nonempty("TEMP").or(
484 getenv_nonempty("USERPROFILE").or(
485 getenv_nonempty("WINDIR")))).unwrap_or(Path::new("C:\\Windows"))
490 * Convert a relative path to an absolute path
492 * If the given path is relative, return it prepended with the current working
493 * directory. If the given path is already an absolute path, return it
496 // NB: this is here rather than in path because it is a form of environment
497 // querying; what it does depends on the process working directory, not just
499 pub fn make_absolute(p: &Path) -> Path {
503 let mut ret = getcwd();
509 /// Changes the current working directory to the specified path, returning
510 /// whether the change was completed successfully or not.
511 pub fn change_dir(p: &Path) -> bool {
515 fn chdir(p: &Path) -> bool {
517 use os::win32::as_utf16_p;
518 return as_utf16_p(p.as_str().unwrap(), |buf| {
519 libc::SetCurrentDirectoryW(buf) != (0 as libc::BOOL)
525 fn chdir(p: &Path) -> bool {
528 libc::chdir(buf) == (0 as c_int)
535 /// Returns the platform-specific value of errno
536 pub fn errno() -> int {
537 #[cfg(target_os = "macos")]
538 #[cfg(target_os = "freebsd")]
539 fn errno_location() -> *c_int {
542 fn __error() -> *c_int;
549 #[cfg(target_os = "linux")]
550 #[cfg(target_os = "android")]
551 fn errno_location() -> *c_int {
554 fn __errno_location() -> *c_int;
562 (*errno_location()) as int
567 /// Returns the platform-specific value of errno
568 pub fn errno() -> uint {
569 use libc::types::os::arch::extra::DWORD;
571 #[link_name = "kernel32"]
573 fn GetLastError() -> DWORD;
577 GetLastError() as uint
581 /// Get a string representing the platform-dependent last error
582 pub fn last_os_error() -> ~str {
584 fn strerror() -> ~str {
585 #[cfg(target_os = "macos")]
586 #[cfg(target_os = "android")]
587 #[cfg(target_os = "freebsd")]
588 fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: size_t)
592 fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: size_t)
596 strerror_r(errnum, buf, buflen)
600 // GNU libc provides a non-compliant version of strerror_r by default
601 // and requires macros to instead use the POSIX compliant variant.
602 // So we just use __xpg_strerror_r which is always POSIX compliant
603 #[cfg(target_os = "linux")]
604 fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: size_t) -> c_int {
607 fn __xpg_strerror_r(errnum: c_int,
613 __xpg_strerror_r(errnum, buf, buflen)
617 let mut buf = [0 as c_char, ..TMPBUF_SZ];
619 let p = buf.as_mut_ptr();
621 if strerror_r(errno() as c_int, p, buf.len() as size_t) < 0 {
622 fail!("strerror_r failure");
625 str::raw::from_c_str(p as *c_char)
630 fn strerror() -> ~str {
631 use libc::types::os::arch::extra::DWORD;
632 use libc::types::os::arch::extra::LPWSTR;
633 use libc::types::os::arch::extra::LPVOID;
634 use libc::types::os::arch::extra::WCHAR;
636 #[link_name = "kernel32"]
638 fn FormatMessageW(flags: DWORD,
648 static FORMAT_MESSAGE_FROM_SYSTEM: DWORD = 0x00001000;
649 static FORMAT_MESSAGE_IGNORE_INSERTS: DWORD = 0x00000200;
651 // This value is calculated from the macro
652 // MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT)
653 let langId = 0x0800 as DWORD;
654 let err = errno() as DWORD;
656 let mut buf = [0 as WCHAR, ..TMPBUF_SZ];
659 let res = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
660 FORMAT_MESSAGE_IGNORE_INSERTS,
668 fail!("[{}] FormatMessage failure", errno());
679 * Sets the process exit code
681 * Sets the exit code returned by the process if all supervised tasks
682 * terminate successfully (without failing). If the current root task fails
683 * and is supervised by the scheduler then any user-specified exit status is
684 * ignored and the process exits with the default failure status
686 pub fn set_exit_status(code: int) {
688 rt::set_exit_status(code);
691 #[cfg(target_os = "macos")]
692 unsafe fn load_argc_and_argv(argc: c_int, argv: **c_char) -> ~[~str] {
694 for i in range(0u, argc as uint) {
695 args.push(str::raw::from_c_str(*argv.offset(i as int)));
701 * Returns the command line arguments
703 * Returns a list of the command line arguments.
705 #[cfg(target_os = "macos")]
706 fn real_args() -> ~[~str] {
708 let (argc, argv) = (*_NSGetArgc() as c_int,
709 *_NSGetArgv() as **c_char);
710 load_argc_and_argv(argc, argv)
714 #[cfg(target_os = "linux")]
715 #[cfg(target_os = "android")]
716 #[cfg(target_os = "freebsd")]
717 fn real_args() -> ~[~str] {
720 match rt::args::clone() {
722 None => fail!("process arguments not initialized")
727 fn real_args() -> ~[~str] {
730 let mut nArgs: c_int = 0;
731 let lpArgCount: *mut c_int = &mut nArgs;
732 let lpCmdLine = unsafe { GetCommandLineW() };
733 let szArgList = unsafe { CommandLineToArgvW(lpCmdLine, lpArgCount) };
736 for i in range(0u, nArgs as uint) {
738 // Determine the length of this argument.
739 let ptr = *szArgList.offset(i as int);
741 while *ptr.offset(len as int) != 0 { len += 1; }
743 // Push it onto the list.
744 args.push(vec::raw::buf_as_slice(ptr, len,
750 LocalFree(szArgList as *c_void);
759 #[link_name="kernel32"]
761 fn GetCommandLineW() -> LPCWSTR;
762 fn LocalFree(ptr: *c_void);
766 #[link_name="shell32"]
768 fn CommandLineToArgvW(lpCmdLine: LPCWSTR, pNumArgs: *mut c_int) -> **u16;
771 /// Returns the arguments which this program was started with (normally passed
772 /// via the command line).
773 pub fn args() -> ~[~str] {
777 #[cfg(target_os = "macos")]
779 // These functions are in crt_externs.h.
780 pub fn _NSGetArgc() -> *c_int;
781 pub fn _NSGetArgv() -> ***c_char;
784 // Round up `from` to be divisible by `to`
785 fn round_up(from: uint, to: uint) -> uint {
786 let r = if from % to == 0 {
789 from + to - (from % to)
799 pub fn page_size() -> uint {
801 libc::sysconf(libc::_SC_PAGESIZE) as uint
806 pub fn page_size() -> uint {
808 let mut info = libc::SYSTEM_INFO::new();
809 libc::GetSystemInfo(&mut info);
811 return info.dwPageSize as uint;
815 /// A memory mapped file or chunk of memory. This is a very system-specific interface to the OS's
816 /// memory mapping facilities (`mmap` on POSIX, `VirtualAlloc`/`CreateFileMapping` on win32). It
817 /// makes no attempt at abstracting platform differences, besides in error values returned. Consider
820 /// The memory map is released (unmapped) when the destructor is run, so don't let it leave scope by
821 /// accident if you want it to stick around.
822 pub struct MemoryMap {
823 /// Pointer to the memory created or modified by this map.
825 /// Number of bytes this map applies to
831 /// Type of memory map
832 pub enum MemoryMapKind {
833 /// Memory-mapped file. On Windows, the inner pointer is a handle to the mapping, and
834 /// corresponds to `CreateFileMapping`. Elsewhere, it is null.
836 /// Virtual memory map. Usually used to change the permissions of a given chunk of memory.
837 /// Corresponds to `VirtualAlloc` on Windows.
841 /// Options the memory map is created with
843 /// The memory should be readable
845 /// The memory should be writable
847 /// The memory should be executable
849 /// Create a map for a specific address range. Corresponds to `MAP_FIXED` on POSIX.
851 /// Create a memory mapping for a file with a given fd.
853 /// When using `MapFd`, the start of the map is `uint` bytes from the start of the file.
857 /// Possible errors when creating a map.
859 /// ## The following are POSIX-specific
861 /// fd was not open for reading or, if using `MapWritable`, was not open for writing.
865 /// Either the address given by `MapAddr` or offset given by `MapOffset` was not a multiple of
866 /// `MemoryMap::granularity` (unaligned to page size).
868 /// With `MapFd`, the fd does not support mapping.
870 /// If using `MapAddr`, the address + `min_len` was outside of the process's address space. If
871 /// using `MapFd`, the target of the fd didn't have enough resources to fulfill the request.
873 /// Unrecognized error. The inner value is the unrecognized errno.
874 ErrUnknown(libc::c_int),
875 /// ## The following are win32-specific
877 /// Unsupported combination of protection flags (`MapReadable`/`MapWritable`/`MapExecutable`).
879 /// When using `MapFd`, `MapOffset` was given (Windows does not support this at all)
881 /// When using `MapFd`, there was already a mapping to the file.
883 /// Unrecognized error from `VirtualAlloc`. The inner value is the return value of GetLastError.
884 ErrVirtualAlloc(uint),
885 /// Unrecognized error from `CreateFileMapping`. The inner value is the return value of
887 ErrCreateFileMappingW(uint),
888 /// Unrecognized error from `MapViewOfFile`. The inner value is the return value of
890 ErrMapViewOfFile(uint)
893 impl to_str::ToStr for MapError {
894 fn to_str(&self) -> ~str {
896 ErrFdNotAvail => ~"fd not available for reading or writing",
897 ErrInvalidFd => ~"Invalid fd",
898 ErrUnaligned => ~"Unaligned address, invalid flags, \
899 negative length or unaligned offset",
900 ErrNoMapSupport=> ~"File doesn't support mapping",
901 ErrNoMem => ~"Invalid address, or not enough available memory",
902 ErrUnknown(code) => format!("Unknown error={}", code),
903 ErrUnsupProt => ~"Protection mode unsupported",
904 ErrUnsupOffset => ~"Offset in virtual memory mode is unsupported",
905 ErrAlreadyExists => ~"File mapping for specified file already exists",
906 ErrVirtualAlloc(code) => format!("VirtualAlloc failure={}", code),
907 ErrCreateFileMappingW(code) => format!("CreateFileMappingW failure={}", code),
908 ErrMapViewOfFile(code) => format!("MapViewOfFile failure={}", code)
915 /// Create a new mapping with the given `options`, at least `min_len` bytes long.
916 pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
919 let mut addr: *c_void = ptr::null();
920 let mut prot: c_int = 0;
921 let mut flags: c_int = libc::MAP_PRIVATE;
922 let mut fd: c_int = -1;
923 let mut offset: off_t = 0;
924 let len = round_up(min_len, page_size()) as size_t;
926 for &o in options.iter() {
928 MapReadable => { prot |= libc::PROT_READ; },
929 MapWritable => { prot |= libc::PROT_WRITE; },
930 MapExecutable => { prot |= libc::PROT_EXEC; },
932 flags |= libc::MAP_FIXED;
936 flags |= libc::MAP_FILE;
939 MapOffset(offset_) => { offset = offset_ as off_t; }
942 if fd == -1 { flags |= libc::MAP_ANON; }
945 libc::mmap(addr, len, prot, flags, fd, offset)
947 if r.equiv(&libc::MAP_FAILED) {
948 Err(match errno() as c_int {
949 libc::EACCES => ErrFdNotAvail,
950 libc::EBADF => ErrInvalidFd,
951 libc::EINVAL => ErrUnaligned,
952 libc::ENODEV => ErrNoMapSupport,
953 libc::ENOMEM => ErrNoMem,
954 code => ErrUnknown(code)
969 /// Granularity that the offset or address must be for `MapOffset` and `MapAddr` respectively.
970 pub fn granularity() -> uint {
976 impl Drop for MemoryMap {
977 /// Unmap the mapping. Fails the task if `munmap` fails.
980 match libc::munmap(self.data as *c_void, self.len) {
982 -1 => match errno() as c_int {
983 libc::EINVAL => error!("invalid addr or len"),
984 e => error!("unknown errno={}", e)
986 r => error!("Unexpected result {}", r)
994 /// Create a new mapping with the given `options`, at least `min_len` bytes long.
995 pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
996 use libc::types::os::arch::extra::{LPVOID, DWORD, SIZE_T, HANDLE};
998 let mut lpAddress: LPVOID = ptr::mut_null();
999 let mut readable = false;
1000 let mut writable = false;
1001 let mut executable = false;
1002 let mut fd: c_int = -1;
1003 let mut offset: uint = 0;
1004 let len = round_up(min_len, page_size()) as SIZE_T;
1006 for &o in options.iter() {
1008 MapReadable => { readable = true; },
1009 MapWritable => { writable = true; },
1010 MapExecutable => { executable = true; }
1011 MapAddr(addr_) => { lpAddress = addr_ as LPVOID; },
1012 MapFd(fd_) => { fd = fd_; },
1013 MapOffset(offset_) => { offset = offset_; }
1017 let flProtect = match (executable, readable, writable) {
1018 (false, false, false) if fd == -1 => libc::PAGE_NOACCESS,
1019 (false, true, false) => libc::PAGE_READONLY,
1020 (false, true, true) => libc::PAGE_READWRITE,
1021 (true, false, false) if fd == -1 => libc::PAGE_EXECUTE,
1022 (true, true, false) => libc::PAGE_EXECUTE_READ,
1023 (true, true, true) => libc::PAGE_EXECUTE_READWRITE,
1024 _ => return Err(ErrUnsupProt)
1029 return Err(ErrUnsupOffset);
1032 libc::VirtualAlloc(lpAddress,
1034 libc::MEM_COMMIT | libc::MEM_RESERVE,
1038 0 => Err(ErrVirtualAlloc(errno())),
1046 let dwDesiredAccess = match (executable, readable, writable) {
1047 (false, true, false) => libc::FILE_MAP_READ,
1048 (false, true, true) => libc::FILE_MAP_WRITE,
1049 (true, true, false) => libc::FILE_MAP_READ | libc::FILE_MAP_EXECUTE,
1050 (true, true, true) => libc::FILE_MAP_WRITE | libc::FILE_MAP_EXECUTE,
1051 _ => return Err(ErrUnsupProt) // Actually, because of the check above,
1052 // we should never get here.
1055 let hFile = libc::get_osfhandle(fd) as HANDLE;
1056 let mapping = libc::CreateFileMappingW(hFile,
1062 if mapping == ptr::mut_null() {
1063 return Err(ErrCreateFileMappingW(errno()));
1065 if errno() as c_int == libc::ERROR_ALREADY_EXISTS {
1066 return Err(ErrAlreadyExists);
1068 let r = libc::MapViewOfFile(mapping,
1070 ((len as u64) >> 32) as DWORD,
1071 (offset & 0xffff_ffff) as DWORD,
1074 0 => Err(ErrMapViewOfFile(errno())),
1078 kind: MapFile(mapping as *c_void)
1085 /// Granularity of MapAddr() and MapOffset() parameter values.
1086 /// This may be greater than the value returned by page_size().
1087 pub fn granularity() -> uint {
1089 let mut info = libc::SYSTEM_INFO::new();
1090 libc::GetSystemInfo(&mut info);
1092 return info.dwAllocationGranularity as uint;
1098 impl Drop for MemoryMap {
1099 /// Unmap the mapping. Fails the task if any of `VirtualFree`, `UnmapViewOfFile`, or
1100 /// `CloseHandle` fail.
1101 fn drop(&mut self) {
1102 use libc::types::os::arch::extra::{LPCVOID, HANDLE};
1103 use libc::consts::os::extra::FALSE;
1108 if libc::VirtualFree(self.data as *mut c_void,
1110 libc::MEM_RELEASE) == FALSE {
1111 error!("VirtualFree failed: {}", errno());
1114 MapFile(mapping) => {
1115 if libc::UnmapViewOfFile(self.data as LPCVOID) == FALSE {
1116 error!("UnmapViewOfFile failed: {}", errno());
1118 if libc::CloseHandle(mapping as HANDLE) == FALSE {
1119 error!("CloseHandle failed: {}", errno());
1130 pub use os::consts::unix::*;
1133 pub use os::consts::windows::*;
1135 #[cfg(target_os = "macos")]
1136 pub use os::consts::macos::*;
1138 #[cfg(target_os = "freebsd")]
1139 pub use os::consts::freebsd::*;
1141 #[cfg(target_os = "linux")]
1142 pub use os::consts::linux::*;
1144 #[cfg(target_os = "android")]
1145 pub use os::consts::android::*;
1147 #[cfg(target_os = "win32")]
1148 pub use os::consts::win32::*;
1150 #[cfg(target_arch = "x86")]
1151 pub use os::consts::x86::*;
1153 #[cfg(target_arch = "x86_64")]
1154 pub use os::consts::x86_64::*;
1156 #[cfg(target_arch = "arm")]
1157 pub use os::consts::arm::*;
1159 #[cfg(target_arch = "mips")]
1160 pub use os::consts::mips::*;
1163 pub static FAMILY: &'static str = "unix";
1167 pub static FAMILY: &'static str = "windows";
1171 pub static SYSNAME: &'static str = "macos";
1172 pub static DLL_PREFIX: &'static str = "lib";
1173 pub static DLL_SUFFIX: &'static str = ".dylib";
1174 pub static DLL_EXTENSION: &'static str = "dylib";
1175 pub static EXE_SUFFIX: &'static str = "";
1176 pub static EXE_EXTENSION: &'static str = "";
1180 pub static SYSNAME: &'static str = "freebsd";
1181 pub static DLL_PREFIX: &'static str = "lib";
1182 pub static DLL_SUFFIX: &'static str = ".so";
1183 pub static DLL_EXTENSION: &'static str = "so";
1184 pub static EXE_SUFFIX: &'static str = "";
1185 pub static EXE_EXTENSION: &'static str = "";
1189 pub static SYSNAME: &'static str = "linux";
1190 pub static DLL_PREFIX: &'static str = "lib";
1191 pub static DLL_SUFFIX: &'static str = ".so";
1192 pub static DLL_EXTENSION: &'static str = "so";
1193 pub static EXE_SUFFIX: &'static str = "";
1194 pub static EXE_EXTENSION: &'static str = "";
1198 pub static SYSNAME: &'static str = "android";
1199 pub static DLL_PREFIX: &'static str = "lib";
1200 pub static DLL_SUFFIX: &'static str = ".so";
1201 pub static DLL_EXTENSION: &'static str = "so";
1202 pub static EXE_SUFFIX: &'static str = "";
1203 pub static EXE_EXTENSION: &'static str = "";
1207 pub static SYSNAME: &'static str = "win32";
1208 pub static DLL_PREFIX: &'static str = "";
1209 pub static DLL_SUFFIX: &'static str = ".dll";
1210 pub static DLL_EXTENSION: &'static str = "dll";
1211 pub static EXE_SUFFIX: &'static str = ".exe";
1212 pub static EXE_EXTENSION: &'static str = "exe";
1217 pub static ARCH: &'static str = "x86";
1220 pub static ARCH: &'static str = "x86_64";
1223 pub static ARCH: &'static str = "arm";
1226 pub static ARCH: &'static str = "mips";
1235 use os::{env, getcwd, getenv, make_absolute, args};
1236 use os::{setenv, unsetenv};
1245 pub fn last_os_error() {
1246 debug!("{}", os::last_os_error());
1250 pub fn test_args() {
1252 assert!(a.len() >= 1);
1255 fn make_rand_name() -> ~str {
1256 let mut rng = rand::rng();
1257 let n = ~"TEST" + rng.gen_ascii_str(10u);
1258 assert!(getenv(n).is_none());
1264 let n = make_rand_name();
1266 assert_eq!(getenv(n), option::Some(~"VALUE"));
1270 fn test_unsetenv() {
1271 let n = make_rand_name();
1274 assert_eq!(getenv(n), option::None);
1279 fn test_setenv_overwrite() {
1280 let n = make_rand_name();
1283 assert_eq!(getenv(n), option::Some(~"2"));
1285 assert_eq!(getenv(n), option::Some(~""));
1288 // Windows GetEnvironmentVariable requires some extra work to make sure
1289 // the buffer the variable is copied into is the right size
1292 fn test_getenv_big() {
1296 s = s + "aaaaaaaaaa";
1299 let n = make_rand_name();
1301 debug!("{}", s.clone());
1302 assert_eq!(getenv(n), option::Some(s));
1306 fn test_self_exe_path() {
1307 let path = os::self_exe_path();
1308 assert!(path.is_some());
1309 let path = path.unwrap();
1310 debug!("{:?}", path.clone());
1312 // Hard to test this function
1313 assert!(path.is_absolute());
1318 fn test_env_getenv() {
1320 assert!(e.len() > 0u);
1322 let (n, v) = (*p).clone();
1323 debug!("{:?}", n.clone());
1325 // MingW seems to set some funky environment variables like
1326 // "=C:=C:\MinGW\msys\1.0\bin" and "!::=::\" that are returned
1327 // from env() but not visible from getenv().
1328 assert!(v2.is_none() || v2 == option::Some(v));
1333 fn test_env_setenv() {
1334 let n = make_rand_name();
1338 assert!(!e.contains(&(n.clone(), ~"VALUE")));
1341 assert!(e.contains(&(n, ~"VALUE")));
1346 assert!((!Path::new("test-path").is_absolute()));
1349 debug!("Current working directory: {}", cwd.display());
1351 debug!("{:?}", make_absolute(&Path::new("test-path")));
1352 debug!("{:?}", make_absolute(&Path::new("/usr/bin")));
1358 let oldhome = getenv("HOME");
1360 setenv("HOME", "/home/MountainView");
1361 assert_eq!(os::homedir(), Some(Path::new("/home/MountainView")));
1364 assert!(os::homedir().is_none());
1366 for s in oldhome.iter() { setenv("HOME", *s) }
1373 let oldhome = getenv("HOME");
1374 let olduserprofile = getenv("USERPROFILE");
1377 setenv("USERPROFILE", "");
1379 assert!(os::homedir().is_none());
1381 setenv("HOME", "/home/MountainView");
1382 assert_eq!(os::homedir(), Some(Path::new("/home/MountainView")));
1386 setenv("USERPROFILE", "/home/MountainView");
1387 assert_eq!(os::homedir(), Some(Path::new("/home/MountainView")));
1389 setenv("HOME", "/home/MountainView");
1390 setenv("USERPROFILE", "/home/PaloAlto");
1391 assert_eq!(os::homedir(), Some(Path::new("/home/MountainView")));
1393 for s in oldhome.iter() { setenv("HOME", *s) }
1394 for s in olduserprofile.iter() { setenv("USERPROFILE", *s) }
1398 fn memory_map_rw() {
1399 use result::{Ok, Err};
1401 let chunk = match os::MemoryMap::new(16, [
1406 Err(msg) => fail!(msg.to_str())
1408 assert!(chunk.len >= 16);
1412 assert!(*chunk.data == 0xBE);
1417 fn memory_map_file() {
1418 use result::{Ok, Err};
1425 fn lseek_(fd: c_int, size: uint) {
1427 assert!(lseek(fd, size as off_t, SEEK_SET) == size as off_t);
1431 fn lseek_(fd: c_int, size: uint) {
1433 assert!(lseek(fd, size as c_long, SEEK_SET) == size as c_long);
1437 let mut path = tmpdir();
1438 path.push("mmap_file.tmp");
1439 let size = MemoryMap::granularity() * 2;
1442 let fd = path.with_c_str(|path| {
1443 open(path, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR)
1446 "x".with_c_str(|x| assert!(write(fd, x as *c_void, 1) == 1));
1449 let chunk = match MemoryMap::new(size / 2, [
1456 Err(msg) => fail!(msg.to_str())
1458 assert!(chunk.len > 0);
1462 assert!(*chunk.data == 0xbe);
1466 let _guard = io::ignore_io_error();
1470 // More recursive_mkdir tests are in extra::tempfile