1 // Copyright 2012-2014 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.
31 #![allow(missing_doc)]
32 #![allow(non_snake_case_functions)]
35 use collections::{Collection, MutableSeq};
37 use io::{IoResult, IoError};
39 use libc::{c_void, c_int};
42 use option::{Some, None, Option};
44 use path::{Path, GenericPath, BytesContainer};
47 use result::{Err, Ok, Result};
48 use slice::{Vector, ImmutableVector, MutableVector, ImmutableEqVector};
49 use str::{Str, StrSlice, StrAllocating};
52 use sync::atomics::{AtomicInt, INIT_ATOMIC_INT, SeqCst};
60 /// Get the number of cores available
61 pub fn num_cpus() -> uint {
63 return rust_get_num_cpus();
67 fn rust_get_num_cpus() -> libc::uintptr_t;
71 pub static TMPBUF_SZ : uint = 1000u;
72 static BUF_BYTES : uint = 2048u;
74 /// Returns the current working directory as a Path.
78 /// Fails if the current working directory value is invalid:
81 /// * Current directory does not exist.
82 /// * There are insufficient permissions to access the current directory.
89 /// // We assume that we are in a valid directory like "/home".
90 /// let current_working_directory = os::getcwd();
91 /// println!("The current directory is {}", current_working_directory.display());
95 pub fn getcwd() -> Path {
98 let mut buf = [0 as c_char, ..BUF_BYTES];
100 if libc::getcwd(buf.as_mut_ptr(), buf.len() as libc::size_t).is_null() {
103 Path::new(CString::new(buf.as_ptr(), false))
107 /// Returns the current working directory as a Path.
111 /// Fails if the current working directory value is invalid.
114 /// * Current directory does not exist.
115 /// * There are insufficient permissions to access the current directory.
122 /// // We assume that we are in a valid directory like "C:\\Windows".
123 /// let current_working_directory = os::getcwd();
124 /// println!("The current directory is {}", current_working_directory.display());
128 pub fn getcwd() -> Path {
130 use libc::GetCurrentDirectoryW;
132 let mut buf = [0 as u16, ..BUF_BYTES];
134 if libc::GetCurrentDirectoryW(buf.len() as DWORD, buf.as_mut_ptr()) == 0 as DWORD {
138 Path::new(String::from_utf16(str::truncate_utf16_at_nul(buf))
139 .expect("GetCurrentDirectoryW returned invalid UTF-16"))
144 use libc::types::os::arch::extra::DWORD;
146 use option::{None, Option};
149 use slice::{MutableVector, ImmutableVector};
154 pub fn fill_utf16_buf_and_decode(f: |*mut u16, DWORD| -> DWORD)
158 let mut n = TMPBUF_SZ as DWORD;
160 let mut done = false;
162 let mut buf = Vec::from_elem(n as uint, 0u16);
163 let k = f(buf.as_mut_ptr(), n);
164 if k == (0 as DWORD) {
167 libc::GetLastError() ==
168 libc::ERROR_INSUFFICIENT_BUFFER as DWORD {
176 let sub = buf.slice(0, k as uint);
177 // We want to explicitly catch the case when the
178 // closure returned invalid UTF-16, rather than
179 // set `res` to None and continue.
180 let s = String::from_utf16(sub)
181 .expect("fill_utf16_buf_and_decode: closure created invalid UTF-16");
182 res = option::Some(s)
191 Accessing environment variables is not generally threadsafe.
192 Serialize access through a global lock.
194 fn with_env_lock<T>(f: || -> T) -> T {
195 use rt::mutex::{StaticNativeMutex, NATIVE_MUTEX_INIT};
197 static mut lock: StaticNativeMutex = NATIVE_MUTEX_INIT;
200 let _guard = lock.lock();
205 /// Returns a vector of (variable, value) pairs, for all the environment
206 /// variables of the current process.
208 /// Invalid UTF-8 bytes are replaced with \uFFFD. See `String::from_utf8_lossy()`
216 /// // We will iterate through the references to the element returned by os::env();
217 /// for &(ref key, ref value) in os::env().iter() {
218 /// println!("'{}': '{}'", key, value );
221 pub fn env() -> Vec<(String,String)> {
222 env_as_bytes().move_iter().map(|(k,v)| {
223 let k = String::from_utf8_lossy(k.as_slice()).into_string();
224 let v = String::from_utf8_lossy(v.as_slice()).into_string();
229 /// Returns a vector of (variable, value) byte-vector pairs for all the
230 /// environment variables of the current process.
231 pub fn env_as_bytes() -> Vec<(Vec<u8>,Vec<u8>)> {
234 unsafe fn get_env_pairs() -> Vec<Vec<u8>> {
237 use libc::funcs::extra::kernel32::{
238 GetEnvironmentStringsW,
239 FreeEnvironmentStringsW
241 let ch = GetEnvironmentStringsW();
243 fail!("os::env() failure getting env string from OS: {}",
244 os::last_os_error());
246 // Here, we lossily decode the string as UTF16.
248 // The docs suggest that the result should be in Unicode, but
249 // Windows doesn't guarantee it's actually UTF16 -- it doesn't
250 // validate the environment string passed to CreateProcess nor
251 // SetEnvironmentVariable. Yet, it's unlikely that returning a
252 // raw u16 buffer would be of practical use since the result would
253 // be inherently platform-dependent and introduce additional
254 // complexity to this code.
256 // Using the non-Unicode version of GetEnvironmentStrings is even
257 // worse since the result is in an OEM code page. Characters that
258 // can't be encoded in the code page would be turned into question
260 let mut result = Vec::new();
262 while *ch.offset(i) != 0 {
263 let p = &*ch.offset(i);
264 let len = ptr::position(p, |c| *c == 0);
265 raw::buf_as_slice(p, len, |s| {
266 result.push(String::from_utf16_lossy(s).into_bytes());
270 FreeEnvironmentStringsW(ch);
274 unsafe fn get_env_pairs() -> Vec<Vec<u8>> {
278 fn rust_env_pairs() -> *const *const c_char;
280 let environ = rust_env_pairs();
281 if environ as uint == 0 {
282 fail!("os::env() failure getting env string from OS: {}",
283 os::last_os_error());
285 let mut result = Vec::new();
286 ptr::array_each(environ, |e| {
288 Vec::from_slice(CString::new(e, false).as_bytes_no_nul());
289 result.push(env_pair);
294 fn env_convert(input: Vec<Vec<u8>>) -> Vec<(Vec<u8>, Vec<u8>)> {
295 let mut pairs = Vec::new();
296 for p in input.iter() {
297 let mut it = p.as_slice().splitn(1, |b| *b == '=' as u8);
298 let key = Vec::from_slice(it.next().unwrap());
299 let val = Vec::from_slice(it.next().unwrap_or(&[]));
300 pairs.push((key, val));
305 let unparsed_environ = get_env_pairs();
306 env_convert(unparsed_environ)
312 /// Fetches the environment variable `n` from the current process, returning
313 /// None if the variable isn't set.
315 /// Any invalid UTF-8 bytes in the value are replaced by \uFFFD. See
316 /// `String::from_utf8_lossy()` for details.
320 /// Fails if `n` has any interior NULs.
327 /// let key = "HOME";
328 /// match os::getenv(key) {
329 /// Some(val) => println!("{}: {}", key, val),
330 /// None => println!("{} is not defined in the environment.", key)
333 pub fn getenv(n: &str) -> Option<String> {
334 getenv_as_bytes(n).map(|v| String::from_utf8_lossy(v.as_slice()).into_string())
338 /// Fetches the environment variable `n` byte vector from the current process,
339 /// returning None if the variable isn't set.
343 /// Fails if `n` has any interior NULs.
344 pub fn getenv_as_bytes(n: &str) -> Option<Vec<u8>> {
349 let s = n.with_c_str(|buf| libc::getenv(buf));
353 Some(Vec::from_slice(CString::new(s as *const i8,
354 false).as_bytes_no_nul()))
361 /// Fetches the environment variable `n` from the current process, returning
362 /// None if the variable isn't set.
363 pub fn getenv(n: &str) -> Option<String> {
366 use os::win32::{fill_utf16_buf_and_decode};
367 let n: Vec<u16> = n.utf16_units().collect();
368 let n = n.append_one(0);
369 fill_utf16_buf_and_decode(|buf, sz| {
370 libc::GetEnvironmentVariableW(n.as_ptr(), buf, sz)
377 /// Fetches the environment variable `n` byte vector from the current process,
378 /// returning None if the variable isn't set.
379 pub fn getenv_as_bytes(n: &str) -> Option<Vec<u8>> {
380 getenv(n).map(|s| s.into_bytes())
383 /// Sets the environment variable `n` to the value `v` for the currently running
392 /// os::setenv(key, "VALUE");
393 /// match os::getenv(key) {
394 /// Some(ref val) => println!("{}: {}", key, val),
395 /// None => println!("{} is not defined in the environment.", key)
398 pub fn setenv<T: BytesContainer>(n: &str, v: T) {
400 fn _setenv(n: &str, v: &[u8]) {
403 n.with_c_str(|nbuf| {
404 v.with_c_str(|vbuf| {
405 libc::funcs::posix01::unistd::setenv(nbuf, vbuf, 1);
413 fn _setenv(n: &str, v: &[u8]) {
414 let n: Vec<u16> = n.utf16_units().collect();
415 let n = n.append_one(0);
416 let v: Vec<u16> = str::from_utf8(v).unwrap().utf16_units().collect();
417 let v = v.append_one(0);
421 libc::SetEnvironmentVariableW(n.as_ptr(), v.as_ptr());
426 _setenv(n, v.container_as_bytes())
429 /// Remove a variable from the environment entirely.
430 pub fn unsetenv(n: &str) {
432 fn _unsetenv(n: &str) {
435 n.with_c_str(|nbuf| {
436 libc::funcs::posix01::unistd::unsetenv(nbuf);
443 fn _unsetenv(n: &str) {
444 let n: Vec<u16> = n.utf16_units().collect();
445 let n = n.append_one(0);
448 libc::SetEnvironmentVariableW(n.as_ptr(), ptr::null());
455 /// Parses input according to platform conventions for the `PATH`
456 /// environment variable.
462 /// let key = "PATH";
463 /// match os::getenv_as_bytes(key) {
465 /// for path in os::split_paths(paths).iter() {
466 /// println!("'{}'", path.display());
469 /// None => println!("{} is not defined in the environment.", key)
472 pub fn split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> {
474 fn _split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> {
475 unparsed.container_as_bytes()
476 .split(|b| *b == b':')
482 fn _split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> {
483 // On Windows, the PATH environment variable is semicolon separated. Double
484 // quotes are used as a way of introducing literal semicolons (since
485 // c:\some;dir is a valid Windows path). Double quotes are not themselves
486 // permitted in path names, so there is no way to escape a double quote.
487 // Quoted regions can appear in arbitrary locations, so
489 // c:\foo;c:\som"e;di"r;c:\bar
491 // Should parse as [c:\foo, c:\some;dir, c:\bar].
493 // (The above is based on testing; there is no clear reference available
496 let mut parsed = Vec::new();
497 let mut in_progress = Vec::new();
498 let mut in_quote = false;
500 for b in unparsed.container_as_bytes().iter() {
502 b';' if !in_quote => {
503 parsed.push(Path::new(in_progress.as_slice()));
504 in_progress.truncate(0)
507 in_quote = !in_quote;
510 in_progress.push(*b);
514 parsed.push(Path::new(in_progress));
518 _split_paths(unparsed)
521 /// Joins a collection of `Path`s appropriately for the `PATH`
522 /// environment variable.
524 /// Returns a `Vec<u8>` on success, since `Path`s are not utf-8
525 /// encoded on all platforms.
527 /// Returns an `Err` (containing an error message) if one of the input
528 /// `Path`s contains an invalid character for constructing the `PATH`
529 /// variable (a double quote on Windows or a colon on Unix).
535 /// use std::path::Path;
537 /// let key = "PATH";
538 /// let mut paths = os::getenv_as_bytes(key).map_or(Vec::new(), os::split_paths);
539 /// paths.push(Path::new("/home/xyz/bin"));
540 /// os::setenv(key, os::join_paths(paths.as_slice()).unwrap());
542 pub fn join_paths<T: BytesContainer>(paths: &[T]) -> Result<Vec<u8>, &'static str> {
544 fn _join_paths<T: BytesContainer>(paths: &[T]) -> Result<Vec<u8>, &'static str> {
545 let mut joined = Vec::new();
548 for (i, path) in paths.iter().map(|p| p.container_as_bytes()).enumerate() {
549 if i > 0 { joined.push(sep) }
550 if path.contains(&b'"') {
551 return Err("path segment contains `\"`");
552 } else if path.contains(&sep) {
554 joined.push_all(path);
557 joined.push_all(path);
565 fn _join_paths<T: BytesContainer>(paths: &[T]) -> Result<Vec<u8>, &'static str> {
566 let mut joined = Vec::new();
569 for (i, path) in paths.iter().map(|p| p.container_as_bytes()).enumerate() {
570 if i > 0 { joined.push(sep) }
571 if path.contains(&sep) { return Err("path segment contains separator `:`") }
572 joined.push_all(path);
581 /// A low-level OS in-memory pipe.
583 /// A file descriptor representing the reading end of the pipe. Data written
584 /// on the `out` file descriptor can be read from this file descriptor.
586 /// A file descriptor representing the write end of the pipe. Data written
587 /// to this file descriptor can be read from the `input` file descriptor.
591 /// Creates a new low-level OS in-memory pipe.
593 /// This function can fail to succeed if there are no more resources available
594 /// to allocate a pipe.
596 /// This function is also unsafe as there is no destructor associated with the
597 /// `Pipe` structure will return. If it is not arranged for the returned file
598 /// descriptors to be closed, the file descriptors will leak. For safe handling
599 /// of this scenario, use `std::io::PipeStream` instead.
600 pub unsafe fn pipe() -> IoResult<Pipe> {
604 unsafe fn _pipe() -> IoResult<Pipe> {
605 let mut fds = [0, ..2];
606 match libc::pipe(fds.as_mut_ptr()) {
607 0 => Ok(Pipe { reader: fds[0], writer: fds[1] }),
608 _ => Err(IoError::last_error()),
613 unsafe fn _pipe() -> IoResult<Pipe> {
614 // Windows pipes work subtly differently than unix pipes, and their
615 // inheritance has to be handled in a different way that I do not
616 // fully understand. Here we explicitly make the pipe non-inheritable,
617 // which means to pass it to a subprocess they need to be duplicated
618 // first, as in std::run.
619 let mut fds = [0, ..2];
620 match libc::pipe(fds.as_mut_ptr(), 1024 as ::libc::c_uint,
621 (libc::O_BINARY | libc::O_NOINHERIT) as c_int) {
623 assert!(fds[0] != -1 && fds[0] != 0);
624 assert!(fds[1] != -1 && fds[1] != 0);
625 Ok(Pipe { reader: fds[0], writer: fds[1] })
627 _ => Err(IoError::last_error()),
632 /// Returns the proper dll filename for the given basename of a file
634 #[cfg(not(target_os="ios"))]
635 pub fn dll_filename(base: &str) -> String {
636 format!("{}{}{}", consts::DLL_PREFIX, base, consts::DLL_SUFFIX)
639 /// Optionally returns the filesystem path to the current executable which is
640 /// running but with the executable name.
647 /// match os::self_exe_name() {
648 /// Some(exe_path) => println!("Path of this executable is: {}", exe_path.display()),
649 /// None => println!("Unable to get the path of this executable!")
652 pub fn self_exe_name() -> Option<Path> {
654 #[cfg(target_os = "freebsd")]
655 fn load_self() -> Option<Vec<u8>> {
657 use libc::funcs::bsd44::*;
658 use libc::consts::os::extra::*;
659 let mut mib = vec![CTL_KERN as c_int,
661 KERN_PROC_PATHNAME as c_int,
663 let mut sz: libc::size_t = 0;
664 let err = sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
665 ptr::mut_null(), &mut sz, ptr::mut_null(),
667 if err != 0 { return None; }
668 if sz == 0 { return None; }
669 let mut v: Vec<u8> = Vec::with_capacity(sz as uint);
670 let err = sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
671 v.as_mut_ptr() as *mut c_void, &mut sz,
672 ptr::mut_null(), 0u as libc::size_t);
673 if err != 0 { return None; }
674 if sz == 0 { return None; }
675 v.set_len(sz as uint - 1); // chop off trailing NUL
680 #[cfg(target_os = "linux")]
681 #[cfg(target_os = "android")]
682 fn load_self() -> Option<Vec<u8>> {
685 match io::fs::readlink(&Path::new("/proc/self/exe")) {
686 Ok(path) => Some(path.into_vec()),
691 #[cfg(target_os = "macos")]
692 #[cfg(target_os = "ios")]
693 fn load_self() -> Option<Vec<u8>> {
695 use libc::funcs::extra::_NSGetExecutablePath;
697 _NSGetExecutablePath(ptr::mut_null(), &mut sz);
698 if sz == 0 { return None; }
699 let mut v: Vec<u8> = Vec::with_capacity(sz as uint);
700 let err = _NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz);
701 if err != 0 { return None; }
702 v.set_len(sz as uint - 1); // chop off trailing NUL
708 fn load_self() -> Option<Vec<u8>> {
710 use os::win32::fill_utf16_buf_and_decode;
711 fill_utf16_buf_and_decode(|buf, sz| {
712 libc::GetModuleFileNameW(0u as libc::DWORD, buf, sz)
713 }).map(|s| s.into_string().into_bytes())
717 load_self().and_then(Path::new_opt)
720 /// Optionally returns the filesystem path to the current executable which is
723 /// Like self_exe_name() but without the binary's name.
730 /// match os::self_exe_path() {
731 /// Some(exe_path) => println!("Executable's Path is: {}", exe_path.display()),
732 /// None => println!("Impossible to fetch the path of this executable.")
735 pub fn self_exe_path() -> Option<Path> {
736 self_exe_name().map(|mut p| { p.pop(); p })
739 /// Optionally returns the path to the current user's home directory if known.
743 /// Returns the value of the 'HOME' environment variable if it is set
744 /// and not equal to the empty string.
748 /// Returns the value of the 'HOME' environment variable if it is
749 /// set and not equal to the empty string. Otherwise, returns the value of the
750 /// 'USERPROFILE' environment variable if it is set and not equal to the empty
758 /// match os::homedir() {
759 /// Some(ref p) => println!("{}", p.display()),
760 /// None => println!("Impossible to get your home dir!")
763 pub fn homedir() -> Option<Path> {
766 fn _homedir() -> Option<Path> {
772 fn _homedir() -> Option<Path> {
773 aux_homedir("HOME").or(aux_homedir("USERPROFILE"))
777 fn aux_homedir(home_name: &str) -> Option<Path> {
778 match getenv_as_bytes(home_name) {
780 if p.is_empty() { None } else { Path::new_opt(p) }
789 * Returns the path to a temporary directory.
791 * On Unix, returns the value of the 'TMPDIR' environment variable if it is
792 * set, otherwise for non-Android it returns '/tmp'. If Android, since there
793 * is no global temporary folder (it is usually allocated per-app), we return
796 * On Windows, returns the value of, in order, the 'TMP', 'TEMP',
797 * 'USERPROFILE' environment variable if any are set and not the empty
798 * string. Otherwise, tmpdir returns the path to the Windows directory.
800 pub fn tmpdir() -> Path {
803 fn getenv_nonempty(v: &str) -> Option<Path> {
816 fn lookup() -> Path {
817 let default = if cfg!(target_os = "android") {
818 Path::new("/data/local/tmp")
823 getenv_nonempty("TMPDIR").unwrap_or(default)
827 fn lookup() -> Path {
828 getenv_nonempty("TMP").or(
829 getenv_nonempty("TEMP").or(
830 getenv_nonempty("USERPROFILE").or(
831 getenv_nonempty("WINDIR")))).unwrap_or(Path::new("C:\\Windows"))
836 /// Convert a relative path to an absolute path
838 /// If the given path is relative, return it prepended with the current working
839 /// directory. If the given path is already an absolute path, return it
845 /// use std::path::Path;
847 /// // Assume we're in a path like /home/someuser
848 /// let rel_path = Path::new("..");
849 /// let abs_path = os::make_absolute(&rel_path);
850 /// println!("The absolute path is {}", abs_path.display());
851 /// // Prints "The absolute path is /home"
853 // NB: this is here rather than in path because it is a form of environment
854 // querying; what it does depends on the process working directory, not just
856 pub fn make_absolute(p: &Path) -> Path {
860 let mut ret = getcwd();
866 /// Changes the current working directory to the specified path, returning
867 /// whether the change was completed successfully or not.
872 /// use std::path::Path;
874 /// let root = Path::new("/");
875 /// assert!(os::change_dir(&root));
876 /// println!("Succesfully changed working directory to {}!", root.display());
878 pub fn change_dir(p: &Path) -> bool {
882 fn chdir(p: &Path) -> bool {
883 let p = match p.as_str() {
884 Some(s) => s.utf16_units().collect::<Vec<u16>>().append_one(0),
885 None => return false,
888 libc::SetCurrentDirectoryW(p.as_ptr()) != (0 as libc::BOOL)
893 fn chdir(p: &Path) -> bool {
896 libc::chdir(buf) == (0 as c_int)
903 /// Returns the platform-specific value of errno
904 pub fn errno() -> int {
905 #[cfg(target_os = "macos")]
906 #[cfg(target_os = "ios")]
907 #[cfg(target_os = "freebsd")]
908 fn errno_location() -> *const c_int {
910 fn __error() -> *const c_int;
917 #[cfg(target_os = "linux")]
918 #[cfg(target_os = "android")]
919 fn errno_location() -> *const c_int {
921 fn __errno_location() -> *const c_int;
929 (*errno_location()) as int
934 /// Returns the platform-specific value of errno
935 pub fn errno() -> uint {
936 use libc::types::os::arch::extra::DWORD;
938 #[link_name = "kernel32"]
940 fn GetLastError() -> DWORD;
944 GetLastError() as uint
948 /// Return the string corresponding to an `errno()` value of `errnum`.
953 /// // Same as println!("{}", last_os_error());
954 /// println!("{}", os::error_string(os::errno() as uint));
956 pub fn error_string(errnum: uint) -> String {
957 return strerror(errnum);
960 fn strerror(errnum: uint) -> String {
961 #[cfg(target_os = "macos")]
962 #[cfg(target_os = "ios")]
963 #[cfg(target_os = "android")]
964 #[cfg(target_os = "freebsd")]
965 fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: libc::size_t)
968 fn strerror_r(errnum: c_int, buf: *mut c_char,
969 buflen: libc::size_t) -> c_int;
972 strerror_r(errnum, buf, buflen)
976 // GNU libc provides a non-compliant version of strerror_r by default
977 // and requires macros to instead use the POSIX compliant variant.
978 // So we just use __xpg_strerror_r which is always POSIX compliant
979 #[cfg(target_os = "linux")]
980 fn strerror_r(errnum: c_int, buf: *mut c_char,
981 buflen: libc::size_t) -> c_int {
983 fn __xpg_strerror_r(errnum: c_int,
985 buflen: libc::size_t)
989 __xpg_strerror_r(errnum, buf, buflen)
993 let mut buf = [0 as c_char, ..TMPBUF_SZ];
995 let p = buf.as_mut_ptr();
997 if strerror_r(errnum as c_int, p, buf.len() as libc::size_t) < 0 {
998 fail!("strerror_r failure");
1001 str::raw::from_c_str(p as *const c_char).into_string()
1006 fn strerror(errnum: uint) -> String {
1007 use libc::types::os::arch::extra::DWORD;
1008 use libc::types::os::arch::extra::LPWSTR;
1009 use libc::types::os::arch::extra::LPVOID;
1010 use libc::types::os::arch::extra::WCHAR;
1012 #[link_name = "kernel32"]
1014 fn FormatMessageW(flags: DWORD,
1020 args: *const c_void)
1024 static FORMAT_MESSAGE_FROM_SYSTEM: DWORD = 0x00001000;
1025 static FORMAT_MESSAGE_IGNORE_INSERTS: DWORD = 0x00000200;
1027 // This value is calculated from the macro
1028 // MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT)
1029 let langId = 0x0800 as DWORD;
1031 let mut buf = [0 as WCHAR, ..TMPBUF_SZ];
1034 let res = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
1035 FORMAT_MESSAGE_IGNORE_INSERTS,
1043 // Sometimes FormatMessageW can fail e.g. system doesn't like langId,
1044 let fm_err = errno();
1045 return format!("OS Error {} (FormatMessageW() returned error {})", errnum, fm_err);
1048 let msg = String::from_utf16(str::truncate_utf16_at_nul(buf));
1050 Some(msg) => format!("OS Error {}: {}", errnum, msg),
1051 None => format!("OS Error {} (FormatMessageW() returned invalid UTF-16)", errnum),
1057 /// Get a string representing the platform-dependent last error
1058 pub fn last_os_error() -> String {
1059 error_string(errno() as uint)
1062 static mut EXIT_STATUS: AtomicInt = INIT_ATOMIC_INT;
1065 * Sets the process exit code
1067 * Sets the exit code returned by the process if all supervised tasks
1068 * terminate successfully (without failing). If the current root task fails
1069 * and is supervised by the scheduler then any user-specified exit status is
1070 * ignored and the process exits with the default failure status.
1072 * Note that this is not synchronized against modifications of other threads.
1074 pub fn set_exit_status(code: int) {
1075 unsafe { EXIT_STATUS.store(code, SeqCst) }
1078 /// Fetches the process's current exit code. This defaults to 0 and can change
1079 /// by calling `set_exit_status`.
1080 pub fn get_exit_status() -> int {
1081 unsafe { EXIT_STATUS.load(SeqCst) }
1084 #[cfg(target_os = "macos")]
1085 unsafe fn load_argc_and_argv(argc: int,
1086 argv: *const *const c_char) -> Vec<Vec<u8>> {
1089 Vec::from_fn(argc as uint, |i| {
1090 Vec::from_slice(CString::new(*argv.offset(i as int),
1091 false).as_bytes_no_nul())
1096 * Returns the command line arguments
1098 * Returns a list of the command line arguments.
1100 #[cfg(target_os = "macos")]
1101 fn real_args_as_bytes() -> Vec<Vec<u8>> {
1103 let (argc, argv) = (*_NSGetArgc() as int,
1104 *_NSGetArgv() as *const *const c_char);
1105 load_argc_and_argv(argc, argv)
1109 // As _NSGetArgc and _NSGetArgv aren't mentioned in iOS docs
1110 // and use underscores in their names - they're most probably
1111 // are considered private and therefore should be avoided
1112 // Here is another way to get arguments using Objective C
1115 // In general it looks like:
1117 // let args = [[NSProcessInfo processInfo] arguments]
1118 // for i in range(0, [args count])
1119 // res.push([args objectAtIndex:i])
1121 #[cfg(target_os = "ios")]
1122 fn real_args_as_bytes() -> Vec<Vec<u8>> {
1127 #[link(name = "objc")]
1129 fn sel_registerName(name: *const libc::c_uchar) -> Sel;
1130 fn objc_msgSend(obj: NsId, sel: Sel, ...) -> NsId;
1131 fn objc_getClass(class_name: *const libc::c_uchar) -> NsId;
1134 #[link(name = "Foundation", kind = "framework")]
1137 type Sel = *const libc::c_void;
1138 type NsId = *const libc::c_void;
1140 let mut res = Vec::new();
1143 let processInfoSel = sel_registerName("processInfo\0".as_ptr());
1144 let argumentsSel = sel_registerName("arguments\0".as_ptr());
1145 let utf8Sel = sel_registerName("UTF8String\0".as_ptr());
1146 let countSel = sel_registerName("count\0".as_ptr());
1147 let objectAtSel = sel_registerName("objectAtIndex:\0".as_ptr());
1149 let klass = objc_getClass("NSProcessInfo\0".as_ptr());
1150 let info = objc_msgSend(klass, processInfoSel);
1151 let args = objc_msgSend(info, argumentsSel);
1153 let cnt: int = mem::transmute(objc_msgSend(args, countSel));
1154 for i in range(0, cnt) {
1155 let tmp = objc_msgSend(args, objectAtSel, i);
1156 let utf_c_str: *const libc::c_char =
1157 mem::transmute(objc_msgSend(tmp, utf8Sel));
1158 let s = CString::new(utf_c_str, false);
1159 if s.is_not_null() {
1160 res.push(Vec::from_slice(s.as_bytes_no_nul()))
1168 #[cfg(target_os = "linux")]
1169 #[cfg(target_os = "android")]
1170 #[cfg(target_os = "freebsd")]
1171 fn real_args_as_bytes() -> Vec<Vec<u8>> {
1174 match rt::args::clone() {
1176 None => fail!("process arguments not initialized")
1180 #[cfg(not(windows))]
1181 fn real_args() -> Vec<String> {
1182 real_args_as_bytes().move_iter()
1184 String::from_utf8_lossy(v.as_slice()).into_string()
1189 fn real_args() -> Vec<String> {
1192 let mut nArgs: c_int = 0;
1193 let lpArgCount: *mut c_int = &mut nArgs;
1194 let lpCmdLine = unsafe { GetCommandLineW() };
1195 let szArgList = unsafe { CommandLineToArgvW(lpCmdLine, lpArgCount) };
1197 let args = Vec::from_fn(nArgs as uint, |i| unsafe {
1198 // Determine the length of this argument.
1199 let ptr = *szArgList.offset(i as int);
1201 while *ptr.offset(len as int) != 0 { len += 1; }
1203 // Push it onto the list.
1204 let opt_s = slice::raw::buf_as_slice(ptr as *const _, len, |buf| {
1205 String::from_utf16(str::truncate_utf16_at_nul(buf))
1207 opt_s.expect("CommandLineToArgvW returned invalid UTF-16")
1211 LocalFree(szArgList as *mut c_void);
1218 fn real_args_as_bytes() -> Vec<Vec<u8>> {
1219 real_args().move_iter().map(|s| s.into_bytes()).collect()
1222 type LPCWSTR = *const u16;
1225 #[link_name="kernel32"]
1227 fn GetCommandLineW() -> LPCWSTR;
1228 fn LocalFree(ptr: *mut c_void);
1232 #[link_name="shell32"]
1234 fn CommandLineToArgvW(lpCmdLine: LPCWSTR,
1235 pNumArgs: *mut c_int) -> *mut *mut u16;
1238 /// Returns the arguments which this program was started with (normally passed
1239 /// via the command line).
1241 /// The arguments are interpreted as utf-8, with invalid bytes replaced with \uFFFD.
1242 /// See `String::from_utf8_lossy` for details.
1248 /// // Prints each argument on a separate line
1249 /// for argument in os::args().iter() {
1250 /// println!("{}", argument);
1253 pub fn args() -> Vec<String> {
1257 /// Returns the arguments which this program was started with (normally passed
1258 /// via the command line) as byte vectors.
1259 pub fn args_as_bytes() -> Vec<Vec<u8>> {
1260 real_args_as_bytes()
1263 #[cfg(target_os = "macos")]
1265 // These functions are in crt_externs.h.
1266 pub fn _NSGetArgc() -> *mut c_int;
1267 pub fn _NSGetArgv() -> *mut *mut *mut c_char;
1270 // Round up `from` to be divisible by `to`
1271 fn round_up(from: uint, to: uint) -> uint {
1272 let r = if from % to == 0 {
1275 from + to - (from % to)
1284 /// Returns the page size of the current architecture in bytes.
1286 pub fn page_size() -> uint {
1288 libc::sysconf(libc::_SC_PAGESIZE) as uint
1292 /// Returns the page size of the current architecture in bytes.
1294 pub fn page_size() -> uint {
1297 let mut info = mem::zeroed();
1298 libc::GetSystemInfo(&mut info);
1300 return info.dwPageSize as uint;
1304 /// A memory mapped file or chunk of memory. This is a very system-specific
1305 /// interface to the OS's memory mapping facilities (`mmap` on POSIX,
1306 /// `VirtualAlloc`/`CreateFileMapping` on win32). It makes no attempt at
1307 /// abstracting platform differences, besides in error values returned. Consider
1308 /// yourself warned.
1310 /// The memory map is released (unmapped) when the destructor is run, so don't
1311 /// let it leave scope by accident if you want it to stick around.
1312 pub struct MemoryMap {
1315 kind: MemoryMapKind,
1318 /// Type of memory map
1319 pub enum MemoryMapKind {
1320 /// Virtual memory map. Usually used to change the permissions of a given
1321 /// chunk of memory. Corresponds to `VirtualAlloc` on Windows.
1323 /// Virtual memory map. Usually used to change the permissions of a given
1324 /// chunk of memory, or for allocation. Corresponds to `VirtualAlloc` on
1329 /// Options the memory map is created with
1330 pub enum MapOption {
1331 /// The memory should be readable
1333 /// The memory should be writable
1335 /// The memory should be executable
1337 /// Create a map for a specific address range. Corresponds to `MAP_FIXED` on
1340 /// Create a memory mapping for a file with a given fd.
1342 /// When using `MapFd`, the start of the map is `uint` bytes from the start
1345 /// On POSIX, this can be used to specify the default flags passed to
1346 /// `mmap`. By default it uses `MAP_PRIVATE` and, if not using `MapFd`,
1347 /// `MAP_ANON`. This will override both of those. This is platform-specific
1348 /// (the exact values used) and ignored on Windows.
1349 MapNonStandardFlags(c_int),
1352 /// Possible errors when creating a map.
1354 /// ## The following are POSIX-specific
1356 /// fd was not open for reading or, if using `MapWritable`, was not open for
1359 /// fd was not valid
1361 /// Either the address given by `MapAddr` or offset given by `MapOffset` was
1362 /// not a multiple of `MemoryMap::granularity` (unaligned to page size).
1364 /// With `MapFd`, the fd does not support mapping.
1366 /// If using `MapAddr`, the address + `min_len` was outside of the process's
1367 /// address space. If using `MapFd`, the target of the fd didn't have enough
1368 /// resources to fulfill the request.
1370 /// A zero-length map was requested. This is invalid according to
1371 /// [POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/functions/mmap.html).
1372 /// Not all platforms obey this, but this wrapper does.
1374 /// Unrecognized error. The inner value is the unrecognized errno.
1376 /// ## The following are win32-specific
1378 /// Unsupported combination of protection flags
1379 /// (`MapReadable`/`MapWritable`/`MapExecutable`).
1381 /// When using `MapFd`, `MapOffset` was given (Windows does not support this
1384 /// When using `MapFd`, there was already a mapping to the file.
1386 /// Unrecognized error from `VirtualAlloc`. The inner value is the return
1387 /// value of GetLastError.
1388 ErrVirtualAlloc(uint),
1389 /// Unrecognized error from `CreateFileMapping`. The inner value is the
1390 /// return value of `GetLastError`.
1391 ErrCreateFileMappingW(uint),
1392 /// Unrecognized error from `MapViewOfFile`. The inner value is the return
1393 /// value of `GetLastError`.
1394 ErrMapViewOfFile(uint)
1397 impl fmt::Show for MapError {
1398 fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result {
1399 let str = match *self {
1400 ErrFdNotAvail => "fd not available for reading or writing",
1401 ErrInvalidFd => "Invalid fd",
1403 "Unaligned address, invalid flags, negative length or \
1406 ErrNoMapSupport=> "File doesn't support mapping",
1407 ErrNoMem => "Invalid address, or not enough available memory",
1408 ErrUnsupProt => "Protection mode unsupported",
1409 ErrUnsupOffset => "Offset in virtual memory mode is unsupported",
1410 ErrAlreadyExists => "File mapping for specified file already exists",
1411 ErrZeroLength => "Zero-length mapping not allowed",
1412 ErrUnknown(code) => {
1413 return write!(out, "Unknown error = {}", code)
1415 ErrVirtualAlloc(code) => {
1416 return write!(out, "VirtualAlloc failure = {}", code)
1418 ErrCreateFileMappingW(code) => {
1419 return write!(out, "CreateFileMappingW failure = {}", code)
1421 ErrMapViewOfFile(code) => {
1422 return write!(out, "MapViewOfFile failure = {}", code)
1425 write!(out, "{}", str)
1431 /// Create a new mapping with the given `options`, at least `min_len` bytes
1432 /// long. `min_len` must be greater than zero; see the note on
1433 /// `ErrZeroLength`.
1434 pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
1438 return Err(ErrZeroLength)
1440 let mut addr: *const u8 = ptr::null();
1442 let mut flags = libc::MAP_PRIVATE;
1445 let mut custom_flags = false;
1446 let len = round_up(min_len, page_size());
1448 for &o in options.iter() {
1450 MapReadable => { prot |= libc::PROT_READ; },
1451 MapWritable => { prot |= libc::PROT_WRITE; },
1452 MapExecutable => { prot |= libc::PROT_EXEC; },
1454 flags |= libc::MAP_FIXED;
1458 flags |= libc::MAP_FILE;
1461 MapOffset(offset_) => { offset = offset_ as off_t; },
1462 MapNonStandardFlags(f) => { custom_flags = true; flags = f },
1465 if fd == -1 && !custom_flags { flags |= libc::MAP_ANON; }
1468 libc::mmap(addr as *mut c_void, len as libc::size_t, prot, flags,
1471 if r == libc::MAP_FAILED {
1472 Err(match errno() as c_int {
1473 libc::EACCES => ErrFdNotAvail,
1474 libc::EBADF => ErrInvalidFd,
1475 libc::EINVAL => ErrUnaligned,
1476 libc::ENODEV => ErrNoMapSupport,
1477 libc::ENOMEM => ErrNoMem,
1478 code => ErrUnknown(code as int)
1487 MapFile(ptr::null())
1493 /// Granularity that the offset or address must be for `MapOffset` and
1494 /// `MapAddr` respectively.
1495 pub fn granularity() -> uint {
1501 impl Drop for MemoryMap {
1502 /// Unmap the mapping. Fails the task if `munmap` fails.
1503 fn drop(&mut self) {
1504 if self.len == 0 { /* workaround for dummy_stack */ return; }
1507 // `munmap` only fails due to logic errors
1508 libc::munmap(self.data as *mut c_void, self.len as libc::size_t);
1515 /// Create a new mapping with the given `options`, at least `min_len` bytes long.
1516 pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
1517 use libc::types::os::arch::extra::{LPVOID, DWORD, SIZE_T, HANDLE};
1519 let mut lpAddress: LPVOID = ptr::mut_null();
1520 let mut readable = false;
1521 let mut writable = false;
1522 let mut executable = false;
1523 let mut fd: c_int = -1;
1524 let mut offset: uint = 0;
1525 let len = round_up(min_len, page_size());
1527 for &o in options.iter() {
1529 MapReadable => { readable = true; },
1530 MapWritable => { writable = true; },
1531 MapExecutable => { executable = true; }
1532 MapAddr(addr_) => { lpAddress = addr_ as LPVOID; },
1533 MapFd(fd_) => { fd = fd_; },
1534 MapOffset(offset_) => { offset = offset_; },
1535 MapNonStandardFlags(..) => {}
1539 let flProtect = match (executable, readable, writable) {
1540 (false, false, false) if fd == -1 => libc::PAGE_NOACCESS,
1541 (false, true, false) => libc::PAGE_READONLY,
1542 (false, true, true) => libc::PAGE_READWRITE,
1543 (true, false, false) if fd == -1 => libc::PAGE_EXECUTE,
1544 (true, true, false) => libc::PAGE_EXECUTE_READ,
1545 (true, true, true) => libc::PAGE_EXECUTE_READWRITE,
1546 _ => return Err(ErrUnsupProt)
1551 return Err(ErrUnsupOffset);
1554 libc::VirtualAlloc(lpAddress,
1556 libc::MEM_COMMIT | libc::MEM_RESERVE,
1560 0 => Err(ErrVirtualAlloc(errno())),
1568 let dwDesiredAccess = match (executable, readable, writable) {
1569 (false, true, false) => libc::FILE_MAP_READ,
1570 (false, true, true) => libc::FILE_MAP_WRITE,
1571 (true, true, false) => libc::FILE_MAP_READ | libc::FILE_MAP_EXECUTE,
1572 (true, true, true) => libc::FILE_MAP_WRITE | libc::FILE_MAP_EXECUTE,
1573 _ => return Err(ErrUnsupProt) // Actually, because of the check above,
1574 // we should never get here.
1577 let hFile = libc::get_osfhandle(fd) as HANDLE;
1578 let mapping = libc::CreateFileMappingW(hFile,
1584 if mapping == ptr::mut_null() {
1585 return Err(ErrCreateFileMappingW(errno()));
1587 if errno() as c_int == libc::ERROR_ALREADY_EXISTS {
1588 return Err(ErrAlreadyExists);
1590 let r = libc::MapViewOfFile(mapping,
1592 ((len as u64) >> 32) as DWORD,
1593 (offset & 0xffff_ffff) as DWORD,
1596 0 => Err(ErrMapViewOfFile(errno())),
1600 kind: MapFile(mapping as *const u8)
1607 /// Granularity of MapAddr() and MapOffset() parameter values.
1608 /// This may be greater than the value returned by page_size().
1609 pub fn granularity() -> uint {
1612 let mut info = mem::zeroed();
1613 libc::GetSystemInfo(&mut info);
1615 return info.dwAllocationGranularity as uint;
1621 impl Drop for MemoryMap {
1622 /// Unmap the mapping. Fails the task if any of `VirtualFree`,
1623 /// `UnmapViewOfFile`, or `CloseHandle` fail.
1624 fn drop(&mut self) {
1625 use libc::types::os::arch::extra::{LPCVOID, HANDLE};
1626 use libc::consts::os::extra::FALSE;
1627 if self.len == 0 { return }
1632 if libc::VirtualFree(self.data as *mut c_void, 0,
1633 libc::MEM_RELEASE) == 0 {
1634 println!("VirtualFree failed: {}", errno());
1637 MapFile(mapping) => {
1638 if libc::UnmapViewOfFile(self.data as LPCVOID) == FALSE {
1639 println!("UnmapViewOfFile failed: {}", errno());
1641 if libc::CloseHandle(mapping as HANDLE) == FALSE {
1642 println!("CloseHandle failed: {}", errno());
1651 /// Returns the pointer to the memory created or modified by this map.
1652 pub fn data(&self) -> *mut u8 { self.data }
1653 /// Returns the number of bytes this map applies to.
1654 pub fn len(&self) -> uint { self.len }
1655 /// Returns the type of mapping this represents.
1656 pub fn kind(&self) -> MemoryMapKind { self.kind }
1659 #[cfg(target_os = "linux")]
1661 pub use os::arch_consts::ARCH;
1663 pub static FAMILY: &'static str = "unix";
1665 /// A string describing the specific operating system in use: in this
1667 pub static SYSNAME: &'static str = "linux";
1669 /// Specifies the filename prefix used for shared libraries on this
1670 /// platform: in this case, `lib`.
1671 pub static DLL_PREFIX: &'static str = "lib";
1673 /// Specifies the filename suffix used for shared libraries on this
1674 /// platform: in this case, `.so`.
1675 pub static DLL_SUFFIX: &'static str = ".so";
1677 /// Specifies the file extension used for shared libraries on this
1678 /// platform that goes after the dot: in this case, `so`.
1679 pub static DLL_EXTENSION: &'static str = "so";
1681 /// Specifies the filename suffix used for executable binaries on this
1682 /// platform: in this case, the empty string.
1683 pub static EXE_SUFFIX: &'static str = "";
1685 /// Specifies the file extension, if any, used for executable binaries
1686 /// on this platform: in this case, the empty string.
1687 pub static EXE_EXTENSION: &'static str = "";
1690 #[cfg(target_os = "macos")]
1692 pub use os::arch_consts::ARCH;
1694 pub static FAMILY: &'static str = "unix";
1696 /// A string describing the specific operating system in use: in this
1698 pub static SYSNAME: &'static str = "macos";
1700 /// Specifies the filename prefix used for shared libraries on this
1701 /// platform: in this case, `lib`.
1702 pub static DLL_PREFIX: &'static str = "lib";
1704 /// Specifies the filename suffix used for shared libraries on this
1705 /// platform: in this case, `.dylib`.
1706 pub static DLL_SUFFIX: &'static str = ".dylib";
1708 /// Specifies the file extension used for shared libraries on this
1709 /// platform that goes after the dot: in this case, `dylib`.
1710 pub static DLL_EXTENSION: &'static str = "dylib";
1712 /// Specifies the filename suffix used for executable binaries on this
1713 /// platform: in this case, the empty string.
1714 pub static EXE_SUFFIX: &'static str = "";
1716 /// Specifies the file extension, if any, used for executable binaries
1717 /// on this platform: in this case, the empty string.
1718 pub static EXE_EXTENSION: &'static str = "";
1721 #[cfg(target_os = "ios")]
1723 pub use os::arch_consts::ARCH;
1725 pub static FAMILY: &'static str = "unix";
1727 /// A string describing the specific operating system in use: in this
1729 pub static SYSNAME: &'static str = "ios";
1731 /// Specifies the filename suffix used for executable binaries on this
1732 /// platform: in this case, the empty string.
1733 pub static EXE_SUFFIX: &'static str = "";
1735 /// Specifies the file extension, if any, used for executable binaries
1736 /// on this platform: in this case, the empty string.
1737 pub static EXE_EXTENSION: &'static str = "";
1740 #[cfg(target_os = "freebsd")]
1742 pub use os::arch_consts::ARCH;
1744 pub static FAMILY: &'static str = "unix";
1746 /// A string describing the specific operating system in use: in this
1747 /// case, `freebsd`.
1748 pub static SYSNAME: &'static str = "freebsd";
1750 /// Specifies the filename prefix used for shared libraries on this
1751 /// platform: in this case, `lib`.
1752 pub static DLL_PREFIX: &'static str = "lib";
1754 /// Specifies the filename suffix used for shared libraries on this
1755 /// platform: in this case, `.so`.
1756 pub static DLL_SUFFIX: &'static str = ".so";
1758 /// Specifies the file extension used for shared libraries on this
1759 /// platform that goes after the dot: in this case, `so`.
1760 pub static DLL_EXTENSION: &'static str = "so";
1762 /// Specifies the filename suffix used for executable binaries on this
1763 /// platform: in this case, the empty string.
1764 pub static EXE_SUFFIX: &'static str = "";
1766 /// Specifies the file extension, if any, used for executable binaries
1767 /// on this platform: in this case, the empty string.
1768 pub static EXE_EXTENSION: &'static str = "";
1771 #[cfg(target_os = "android")]
1773 pub use os::arch_consts::ARCH;
1775 pub static FAMILY: &'static str = "unix";
1777 /// A string describing the specific operating system in use: in this
1778 /// case, `android`.
1779 pub static SYSNAME: &'static str = "android";
1781 /// Specifies the filename prefix used for shared libraries on this
1782 /// platform: in this case, `lib`.
1783 pub static DLL_PREFIX: &'static str = "lib";
1785 /// Specifies the filename suffix used for shared libraries on this
1786 /// platform: in this case, `.so`.
1787 pub static DLL_SUFFIX: &'static str = ".so";
1789 /// Specifies the file extension used for shared libraries on this
1790 /// platform that goes after the dot: in this case, `so`.
1791 pub static DLL_EXTENSION: &'static str = "so";
1793 /// Specifies the filename suffix used for executable binaries on this
1794 /// platform: in this case, the empty string.
1795 pub static EXE_SUFFIX: &'static str = "";
1797 /// Specifies the file extension, if any, used for executable binaries
1798 /// on this platform: in this case, the empty string.
1799 pub static EXE_EXTENSION: &'static str = "";
1802 #[cfg(target_os = "win32")]
1804 pub use os::arch_consts::ARCH;
1806 pub static FAMILY: &'static str = "windows";
1808 /// A string describing the specific operating system in use: in this
1810 pub static SYSNAME: &'static str = "win32";
1812 /// Specifies the filename prefix used for shared libraries on this
1813 /// platform: in this case, the empty string.
1814 pub static DLL_PREFIX: &'static str = "";
1816 /// Specifies the filename suffix used for shared libraries on this
1817 /// platform: in this case, `.dll`.
1818 pub static DLL_SUFFIX: &'static str = ".dll";
1820 /// Specifies the file extension used for shared libraries on this
1821 /// platform that goes after the dot: in this case, `dll`.
1822 pub static DLL_EXTENSION: &'static str = "dll";
1824 /// Specifies the filename suffix used for executable binaries on this
1825 /// platform: in this case, `.exe`.
1826 pub static EXE_SUFFIX: &'static str = ".exe";
1828 /// Specifies the file extension, if any, used for executable binaries
1829 /// on this platform: in this case, `exe`.
1830 pub static EXE_EXTENSION: &'static str = "exe";
1833 #[cfg(target_arch = "x86")]
1835 pub static ARCH: &'static str = "x86";
1838 #[cfg(target_arch = "x86_64")]
1840 pub static ARCH: &'static str = "x86_64";
1843 #[cfg(target_arch = "arm")]
1845 pub static ARCH: &'static str = "arm";
1848 #[cfg(target_arch = "mips")]
1850 pub static ARCH: &'static str = "mips";
1853 #[cfg(target_arch = "mipsel")]
1855 pub static ARCH: &'static str = "mipsel";
1863 use os::{env, getcwd, getenv, make_absolute};
1864 use os::{split_paths, join_paths, setenv, unsetenv};
1870 pub fn last_os_error() {
1871 debug!("{}", os::last_os_error());
1874 fn make_rand_name() -> String {
1875 let mut rng = rand::task_rng();
1876 let n = format!("TEST{}", rng.gen_ascii_chars().take(10u)
1877 .collect::<String>());
1878 assert!(getenv(n.as_slice()).is_none());
1883 fn test_num_cpus() {
1884 assert!(os::num_cpus() > 0);
1889 let n = make_rand_name();
1890 setenv(n.as_slice(), "VALUE");
1891 assert_eq!(getenv(n.as_slice()), option::Some("VALUE".to_string()));
1895 fn test_unsetenv() {
1896 let n = make_rand_name();
1897 setenv(n.as_slice(), "VALUE");
1898 unsetenv(n.as_slice());
1899 assert_eq!(getenv(n.as_slice()), option::None);
1904 fn test_setenv_overwrite() {
1905 let n = make_rand_name();
1906 setenv(n.as_slice(), "1");
1907 setenv(n.as_slice(), "2");
1908 assert_eq!(getenv(n.as_slice()), option::Some("2".to_string()));
1909 setenv(n.as_slice(), "");
1910 assert_eq!(getenv(n.as_slice()), option::Some("".to_string()));
1913 // Windows GetEnvironmentVariable requires some extra work to make sure
1914 // the buffer the variable is copied into is the right size
1917 fn test_getenv_big() {
1918 let mut s = "".to_string();
1921 s.push_str("aaaaaaaaaa");
1924 let n = make_rand_name();
1925 setenv(n.as_slice(), s.as_slice());
1926 debug!("{}", s.clone());
1927 assert_eq!(getenv(n.as_slice()), option::Some(s));
1931 fn test_self_exe_name() {
1932 let path = os::self_exe_name();
1933 assert!(path.is_some());
1934 let path = path.unwrap();
1935 debug!("{:?}", path.clone());
1937 // Hard to test this function
1938 assert!(path.is_absolute());
1942 fn test_self_exe_path() {
1943 let path = os::self_exe_path();
1944 assert!(path.is_some());
1945 let path = path.unwrap();
1946 debug!("{:?}", path.clone());
1948 // Hard to test this function
1949 assert!(path.is_absolute());
1954 fn test_env_getenv() {
1956 assert!(e.len() > 0u);
1958 let (n, v) = (*p).clone();
1959 debug!("{:?}", n.clone());
1960 let v2 = getenv(n.as_slice());
1961 // MingW seems to set some funky environment variables like
1962 // "=C:=C:\MinGW\msys\1.0\bin" and "!::=::\" that are returned
1963 // from env() but not visible from getenv().
1964 assert!(v2.is_none() || v2 == option::Some(v));
1969 fn test_env_set_get_huge() {
1970 let n = make_rand_name();
1971 let s = "x".repeat(10000).to_string();
1972 setenv(n.as_slice(), s.as_slice());
1973 assert_eq!(getenv(n.as_slice()), Some(s));
1974 unsetenv(n.as_slice());
1975 assert_eq!(getenv(n.as_slice()), None);
1979 fn test_env_setenv() {
1980 let n = make_rand_name();
1983 setenv(n.as_slice(), "VALUE");
1984 assert!(!e.contains(&(n.clone(), "VALUE".to_string())));
1987 assert!(e.contains(&(n, "VALUE".to_string())));
1992 assert!((!Path::new("test-path").is_absolute()));
1995 debug!("Current working directory: {}", cwd.display());
1997 debug!("{:?}", make_absolute(&Path::new("test-path")));
1998 debug!("{:?}", make_absolute(&Path::new("/usr/bin")));
2004 let oldhome = getenv("HOME");
2006 setenv("HOME", "/home/MountainView");
2007 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
2010 assert!(os::homedir().is_none());
2012 for s in oldhome.iter() {
2013 setenv("HOME", s.as_slice());
2021 let oldhome = getenv("HOME");
2022 let olduserprofile = getenv("USERPROFILE");
2025 setenv("USERPROFILE", "");
2027 assert!(os::homedir().is_none());
2029 setenv("HOME", "/home/MountainView");
2030 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
2034 setenv("USERPROFILE", "/home/MountainView");
2035 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
2037 setenv("HOME", "/home/MountainView");
2038 setenv("USERPROFILE", "/home/PaloAlto");
2039 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
2041 for s in oldhome.iter() {
2042 setenv("HOME", s.as_slice());
2044 for s in olduserprofile.iter() {
2045 setenv("USERPROFILE", s.as_slice());
2050 fn memory_map_rw() {
2051 use result::{Ok, Err};
2053 let chunk = match os::MemoryMap::new(16, [
2058 Err(msg) => fail!("{}", msg)
2060 assert!(chunk.len >= 16);
2064 assert!(*chunk.data == 0xBE);
2069 fn memory_map_file() {
2070 use result::{Ok, Err};
2076 fn lseek_(fd: c_int, size: uint) {
2078 assert!(lseek(fd, size as off_t, SEEK_SET) == size as off_t);
2082 fn lseek_(fd: c_int, size: uint) {
2084 assert!(lseek(fd, size as c_long, SEEK_SET) == size as c_long);
2088 let mut path = tmpdir();
2089 path.push("mmap_file.tmp");
2090 let size = MemoryMap::granularity() * 2;
2093 let fd = path.with_c_str(|path| {
2094 open(path, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR)
2097 "x".with_c_str(|x| assert!(write(fd, x as *const c_void, 1) == 1));
2100 let chunk = match MemoryMap::new(size / 2, [
2107 Err(msg) => fail!("{}", msg)
2109 assert!(chunk.len > 0);
2113 assert!(*chunk.data == 0xbe);
2118 fs::unlink(&path).unwrap();
2123 fn split_paths_windows() {
2124 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
2125 split_paths(unparsed) ==
2126 parsed.iter().map(|s| Path::new(*s)).collect()
2129 assert!(check_parse("", [""]));
2130 assert!(check_parse(r#""""#, [""]));
2131 assert!(check_parse(";;", ["", "", ""]));
2132 assert!(check_parse(r"c:\", [r"c:\"]));
2133 assert!(check_parse(r"c:\;", [r"c:\", ""]));
2134 assert!(check_parse(r"c:\;c:\Program Files\",
2135 [r"c:\", r"c:\Program Files\"]));
2136 assert!(check_parse(r#"c:\;c:\"foo"\"#, [r"c:\", r"c:\foo\"]));
2137 assert!(check_parse(r#"c:\;c:\"foo;bar"\;c:\baz"#,
2138 [r"c:\", r"c:\foo;bar\", r"c:\baz"]));
2143 fn split_paths_unix() {
2144 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
2145 split_paths(unparsed) ==
2146 parsed.iter().map(|s| Path::new(*s)).collect()
2149 assert!(check_parse("", [""]));
2150 assert!(check_parse("::", ["", "", ""]));
2151 assert!(check_parse("/", ["/"]));
2152 assert!(check_parse("/:", ["/", ""]));
2153 assert!(check_parse("/:/usr/local", ["/", "/usr/local"]));
2158 fn join_paths_unix() {
2159 fn test_eq(input: &[&str], output: &str) -> bool {
2160 join_paths(input).unwrap().as_slice() == output.as_bytes()
2163 assert!(test_eq([], ""));
2164 assert!(test_eq(["/bin", "/usr/bin", "/usr/local/bin"],
2165 "/bin:/usr/bin:/usr/local/bin"));
2166 assert!(test_eq(["", "/bin", "", "", "/usr/bin", ""],
2167 ":/bin:::/usr/bin:"));
2168 assert!(join_paths(["/te:st"]).is_err());
2173 fn join_paths_windows() {
2174 fn test_eq(input: &[&str], output: &str) -> bool {
2175 join_paths(input).unwrap().as_slice() == output.as_bytes()
2178 assert!(test_eq([], ""));
2179 assert!(test_eq([r"c:\windows", r"c:\"],
2180 r"c:\windows;c:\"));
2181 assert!(test_eq(["", r"c:\windows", "", "", r"c:\", ""],
2182 r";c:\windows;;;c:\;"));
2183 assert!(test_eq([r"c:\te;st", r"c:\"],
2184 r#""c:\te;st";c:\"#));
2185 assert!(join_paths([r#"c:\te"st"#]).is_err());
2188 // More recursive_mkdir tests are in extra::tempfile