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;
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};
62 /// Get the number of cores available
63 pub fn num_cpus() -> uint {
65 return rust_get_num_cpus();
69 fn rust_get_num_cpus() -> libc::uintptr_t;
73 pub static TMPBUF_SZ : uint = 1000u;
74 static BUF_BYTES : uint = 2048u;
76 /// Returns the current working directory as a Path.
80 /// Fails if the current working directory value is invalid:
83 /// * Current directory does not exist.
84 /// * There are insufficient permissions to access the current directory.
91 /// // We assume that we are in a valid directory like "/home".
92 /// let current_working_directory = os::getcwd();
93 /// println!("The current directory is {}", current_working_directory.display());
97 pub fn getcwd() -> Path {
100 let mut buf = [0 as c_char, ..BUF_BYTES];
102 if libc::getcwd(buf.as_mut_ptr(), buf.len() as libc::size_t).is_null() {
105 Path::new(CString::new(buf.as_ptr(), false))
109 /// Returns the current working directory as a Path.
113 /// Fails if the current working directory value is invalid.
116 /// * Current directory does not exist.
117 /// * There are insufficient permissions to access the current directory.
124 /// // We assume that we are in a valid directory like "C:\\Windows".
125 /// let current_working_directory = os::getcwd();
126 /// println!("The current directory is {}", current_working_directory.display());
130 pub fn getcwd() -> Path {
132 use libc::GetCurrentDirectoryW;
134 let mut buf = [0 as u16, ..BUF_BYTES];
136 if libc::GetCurrentDirectoryW(buf.len() as DWORD, buf.as_mut_ptr()) == 0 as DWORD {
140 Path::new(str::from_utf16(str::truncate_utf16_at_nul(buf))
141 .expect("GetCurrentDirectoryW returned invalid UTF-16"))
146 use libc::types::os::arch::extra::DWORD;
148 use option::{None, Option};
151 use slice::{MutableVector, ImmutableVector};
157 pub fn fill_utf16_buf_and_decode(f: |*mut u16, DWORD| -> DWORD)
161 let mut n = TMPBUF_SZ as DWORD;
163 let mut done = false;
165 let mut buf = Vec::from_elem(n as uint, 0u16);
166 let k = f(buf.as_mut_ptr(), n);
167 if k == (0 as DWORD) {
170 libc::GetLastError() ==
171 libc::ERROR_INSUFFICIENT_BUFFER as DWORD {
179 let sub = buf.slice(0, k as uint);
180 // We want to explicitly catch the case when the
181 // closure returned invalid UTF-16, rather than
182 // set `res` to None and continue.
183 let s = str::from_utf16(sub)
184 .expect("fill_utf16_buf_and_decode: closure created invalid UTF-16");
185 res = option::Some(s)
194 Accessing environment variables is not generally threadsafe.
195 Serialize access through a global lock.
197 fn with_env_lock<T>(f: || -> T) -> T {
198 use rt::mutex::{StaticNativeMutex, NATIVE_MUTEX_INIT};
200 static mut lock: StaticNativeMutex = NATIVE_MUTEX_INIT;
203 let _guard = lock.lock();
208 /// Returns a vector of (variable, value) pairs, for all the environment
209 /// variables of the current process.
211 /// Invalid UTF-8 bytes are replaced with \uFFFD. See `str::from_utf8_lossy()`
219 /// // We will iterate through the references to the element returned by os::env();
220 /// for &(ref key, ref value) in os::env().iter() {
221 /// println!("'{}': '{}'", key, value );
224 pub fn env() -> Vec<(String,String)> {
225 env_as_bytes().move_iter().map(|(k,v)| {
226 let k = str::from_utf8_lossy(k.as_slice()).to_string();
227 let v = str::from_utf8_lossy(v.as_slice()).to_string();
232 /// Returns a vector of (variable, value) byte-vector pairs for all the
233 /// environment variables of the current process.
234 pub fn env_as_bytes() -> Vec<(Vec<u8>,Vec<u8>)> {
237 unsafe fn get_env_pairs() -> Vec<Vec<u8>> {
240 use libc::funcs::extra::kernel32::{
241 GetEnvironmentStringsW,
242 FreeEnvironmentStringsW
244 let ch = GetEnvironmentStringsW();
246 fail!("os::env() failure getting env string from OS: {}",
247 os::last_os_error());
249 // Here, we lossily decode the string as UTF16.
251 // The docs suggest that the result should be in Unicode, but
252 // Windows doesn't guarantee it's actually UTF16 -- it doesn't
253 // validate the environment string passed to CreateProcess nor
254 // SetEnvironmentVariable. Yet, it's unlikely that returning a
255 // raw u16 buffer would be of practical use since the result would
256 // be inherently platform-dependent and introduce additional
257 // complexity to this code.
259 // Using the non-Unicode version of GetEnvironmentStrings is even
260 // worse since the result is in an OEM code page. Characters that
261 // can't be encoded in the code page would be turned into question
263 let mut result = Vec::new();
265 while *ch.offset(i) != 0 {
266 let p = &*ch.offset(i);
267 let len = ptr::position(p, |c| *c == 0);
268 raw::buf_as_slice(p, len, |s| {
269 result.push(str::from_utf16_lossy(s).into_bytes());
273 FreeEnvironmentStringsW(ch);
277 unsafe fn get_env_pairs() -> Vec<Vec<u8>> {
281 fn rust_env_pairs() -> *const *const c_char;
283 let environ = rust_env_pairs();
284 if environ as uint == 0 {
285 fail!("os::env() failure getting env string from OS: {}",
286 os::last_os_error());
288 let mut result = Vec::new();
289 ptr::array_each(environ, |e| {
291 Vec::from_slice(CString::new(e, false).as_bytes_no_nul());
292 result.push(env_pair);
297 fn env_convert(input: Vec<Vec<u8>>) -> Vec<(Vec<u8>, Vec<u8>)> {
298 let mut pairs = Vec::new();
299 for p in input.iter() {
300 let mut it = p.as_slice().splitn(1, |b| *b == '=' as u8);
301 let key = Vec::from_slice(it.next().unwrap());
302 let val = Vec::from_slice(it.next().unwrap_or(&[]));
303 pairs.push((key, val));
308 let unparsed_environ = get_env_pairs();
309 env_convert(unparsed_environ)
315 /// Fetches the environment variable `n` from the current process, returning
316 /// None if the variable isn't set.
318 /// Any invalid UTF-8 bytes in the value are replaced by \uFFFD. See
319 /// `str::from_utf8_lossy()` for details.
323 /// Fails if `n` has any interior NULs.
330 /// let key = "HOME";
331 /// match os::getenv(key) {
332 /// Some(val) => println!("{}: {}", key, val),
333 /// None => println!("{} is not defined in the environment.", key)
336 pub fn getenv(n: &str) -> Option<String> {
337 getenv_as_bytes(n).map(|v| str::from_utf8_lossy(v.as_slice()).to_string())
341 /// Fetches the environment variable `n` byte vector from the current process,
342 /// returning None if the variable isn't set.
346 /// Fails if `n` has any interior NULs.
347 pub fn getenv_as_bytes(n: &str) -> Option<Vec<u8>> {
352 let s = n.with_c_str(|buf| libc::getenv(buf));
356 Some(Vec::from_slice(CString::new(s as *const i8,
357 false).as_bytes_no_nul()))
364 /// Fetches the environment variable `n` from the current process, returning
365 /// None if the variable isn't set.
366 pub fn getenv(n: &str) -> Option<String> {
369 use os::win32::{fill_utf16_buf_and_decode};
370 let n: Vec<u16> = n.utf16_units().collect();
371 let n = n.append_one(0);
372 fill_utf16_buf_and_decode(|buf, sz| {
373 libc::GetEnvironmentVariableW(n.as_ptr(), buf, sz)
380 /// Fetches the environment variable `n` byte vector from the current process,
381 /// returning None if the variable isn't set.
382 pub fn getenv_as_bytes(n: &str) -> Option<Vec<u8>> {
383 getenv(n).map(|s| s.into_bytes())
386 /// Sets the environment variable `n` to the value `v` for the currently running
395 /// os::setenv(key, "VALUE");
396 /// match os::getenv(key) {
397 /// Some(ref val) => println!("{}: {}", key, val),
398 /// None => println!("{} is not defined in the environment.", key)
401 pub fn setenv<T: BytesContainer>(n: &str, v: T) {
403 fn _setenv(n: &str, v: &[u8]) {
406 n.with_c_str(|nbuf| {
407 v.with_c_str(|vbuf| {
408 libc::funcs::posix01::unistd::setenv(nbuf, vbuf, 1);
416 fn _setenv(n: &str, v: &[u8]) {
417 let n: Vec<u16> = n.utf16_units().collect();
418 let n = n.append_one(0);
419 let v: Vec<u16> = str::from_utf8(v).unwrap().utf16_units().collect();
420 let v = v.append_one(0);
424 libc::SetEnvironmentVariableW(n.as_ptr(), v.as_ptr());
429 _setenv(n, v.container_as_bytes())
432 /// Remove a variable from the environment entirely.
433 pub fn unsetenv(n: &str) {
435 fn _unsetenv(n: &str) {
438 n.with_c_str(|nbuf| {
439 libc::funcs::posix01::unistd::unsetenv(nbuf);
446 fn _unsetenv(n: &str) {
447 let n: Vec<u16> = n.utf16_units().collect();
448 let n = n.append_one(0);
451 libc::SetEnvironmentVariableW(n.as_ptr(), ptr::null());
458 /// Parses input according to platform conventions for the `PATH`
459 /// environment variable.
465 /// let key = "PATH";
466 /// match os::getenv_as_bytes(key) {
468 /// for path in os::split_paths(paths).iter() {
469 /// println!("'{}'", path.display());
472 /// None => println!("{} is not defined in the environment.", key)
475 pub fn split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> {
477 fn _split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> {
478 unparsed.container_as_bytes()
479 .split(|b| *b == b':')
485 fn _split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> {
486 // On Windows, the PATH environment variable is semicolon separated. Double
487 // quotes are used as a way of introducing literal semicolons (since
488 // c:\some;dir is a valid Windows path). Double quotes are not themselves
489 // permitted in path names, so there is no way to escape a double quote.
490 // Quoted regions can appear in arbitrary locations, so
492 // c:\foo;c:\som"e;di"r;c:\bar
494 // Should parse as [c:\foo, c:\some;dir, c:\bar].
496 // (The above is based on testing; there is no clear reference available
499 let mut parsed = Vec::new();
500 let mut in_progress = Vec::new();
501 let mut in_quote = false;
503 for b in unparsed.container_as_bytes().iter() {
505 b';' if !in_quote => {
506 parsed.push(Path::new(in_progress.as_slice()));
507 in_progress.truncate(0)
510 in_quote = !in_quote;
513 in_progress.push(*b);
517 parsed.push(Path::new(in_progress));
521 _split_paths(unparsed)
524 /// Joins a collection of `Path`s appropriately for the `PATH`
525 /// environment variable.
527 /// Returns a `Vec<u8>` on success, since `Path`s are not utf-8
528 /// encoded on all platforms.
530 /// Returns an `Err` (containing an error message) if one of the input
531 /// `Path`s contains an invalid character for constructing the `PATH`
532 /// variable (a double quote on Windows or a colon on Unix).
538 /// use std::path::Path;
540 /// let key = "PATH";
541 /// let mut paths = os::getenv_as_bytes(key).map_or(Vec::new(), os::split_paths);
542 /// paths.push(Path::new("/home/xyz/bin"));
543 /// os::setenv(key, os::join_paths(paths.as_slice()).unwrap());
545 pub fn join_paths<T: BytesContainer>(paths: &[T]) -> Result<Vec<u8>, &'static str> {
547 fn _join_paths<T: BytesContainer>(paths: &[T]) -> Result<Vec<u8>, &'static str> {
548 let mut joined = Vec::new();
551 for (i, path) in paths.iter().map(|p| p.container_as_bytes()).enumerate() {
552 if i > 0 { joined.push(sep) }
553 if path.contains(&b'"') {
554 return Err("path segment contains `\"`");
555 } else if path.contains(&sep) {
557 joined.push_all(path);
560 joined.push_all(path);
568 fn _join_paths<T: BytesContainer>(paths: &[T]) -> Result<Vec<u8>, &'static str> {
569 let mut joined = Vec::new();
572 for (i, path) in paths.iter().map(|p| p.container_as_bytes()).enumerate() {
573 if i > 0 { joined.push(sep) }
574 if path.contains(&sep) { return Err("path segment contains separator `:`") }
575 joined.push_all(path);
584 /// A low-level OS in-memory pipe.
586 /// A file descriptor representing the reading end of the pipe. Data written
587 /// on the `out` file descriptor can be read from this file descriptor.
589 /// A file descriptor representing the write end of the pipe. Data written
590 /// to this file descriptor can be read from the `input` file descriptor.
594 /// Creates a new low-level OS in-memory pipe.
596 /// This function can fail to succeed if there are no more resources available
597 /// to allocate a pipe.
599 /// This function is also unsafe as there is no destructor associated with the
600 /// `Pipe` structure will return. If it is not arranged for the returned file
601 /// descriptors to be closed, the file descriptors will leak. For safe handling
602 /// of this scenario, use `std::io::PipeStream` instead.
603 pub unsafe fn pipe() -> IoResult<Pipe> {
607 unsafe fn _pipe() -> IoResult<Pipe> {
608 let mut fds = [0, ..2];
609 match libc::pipe(fds.as_mut_ptr()) {
610 0 => Ok(Pipe { reader: fds[0], writer: fds[1] }),
611 _ => Err(IoError::last_error()),
616 unsafe fn _pipe() -> IoResult<Pipe> {
617 // Windows pipes work subtly differently than unix pipes, and their
618 // inheritance has to be handled in a different way that I do not
619 // fully understand. Here we explicitly make the pipe non-inheritable,
620 // which means to pass it to a subprocess they need to be duplicated
621 // first, as in std::run.
622 let mut fds = [0, ..2];
623 match libc::pipe(fds.as_mut_ptr(), 1024 as ::libc::c_uint,
624 (libc::O_BINARY | libc::O_NOINHERIT) as c_int) {
626 assert!(fds[0] != -1 && fds[0] != 0);
627 assert!(fds[1] != -1 && fds[1] != 0);
628 Ok(Pipe { reader: fds[0], writer: fds[1] })
630 _ => Err(IoError::last_error()),
635 /// Returns the proper dll filename for the given basename of a file
637 #[cfg(not(target_os="ios"))]
638 pub fn dll_filename(base: &str) -> String {
639 format!("{}{}{}", consts::DLL_PREFIX, base, consts::DLL_SUFFIX)
642 /// Optionally returns the filesystem path to the current executable which is
643 /// running but with the executable name.
650 /// match os::self_exe_name() {
651 /// Some(exe_path) => println!("Path of this executable is: {}", exe_path.display()),
652 /// None => println!("Unable to get the path of this executable!")
655 pub fn self_exe_name() -> Option<Path> {
657 #[cfg(target_os = "freebsd")]
658 fn load_self() -> Option<Vec<u8>> {
660 use libc::funcs::bsd44::*;
661 use libc::consts::os::extra::*;
662 let mut mib = vec![CTL_KERN as c_int,
664 KERN_PROC_PATHNAME as c_int,
666 let mut sz: libc::size_t = 0;
667 let err = sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
668 ptr::mut_null(), &mut sz, ptr::mut_null(),
670 if err != 0 { return None; }
671 if sz == 0 { return None; }
672 let mut v: Vec<u8> = Vec::with_capacity(sz as uint);
673 let err = sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
674 v.as_mut_ptr() as *mut c_void, &mut sz,
675 ptr::mut_null(), 0u as libc::size_t);
676 if err != 0 { return None; }
677 if sz == 0 { return None; }
678 v.set_len(sz as uint - 1); // chop off trailing NUL
683 #[cfg(target_os = "linux")]
684 #[cfg(target_os = "android")]
685 fn load_self() -> Option<Vec<u8>> {
688 match io::fs::readlink(&Path::new("/proc/self/exe")) {
689 Ok(path) => Some(path.into_vec()),
694 #[cfg(target_os = "macos")]
695 #[cfg(target_os = "ios")]
696 fn load_self() -> Option<Vec<u8>> {
698 use libc::funcs::extra::_NSGetExecutablePath;
700 _NSGetExecutablePath(ptr::mut_null(), &mut sz);
701 if sz == 0 { return None; }
702 let mut v: Vec<u8> = Vec::with_capacity(sz as uint);
703 let err = _NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz);
704 if err != 0 { return None; }
705 v.set_len(sz as uint - 1); // chop off trailing NUL
711 fn load_self() -> Option<Vec<u8>> {
715 use os::win32::fill_utf16_buf_and_decode;
716 fill_utf16_buf_and_decode(|buf, sz| {
717 libc::GetModuleFileNameW(0u as libc::DWORD, buf, sz)
718 }).map(|s| s.into_string().into_bytes())
722 load_self().and_then(Path::new_opt)
725 /// Optionally returns the filesystem path to the current executable which is
728 /// Like self_exe_name() but without the binary's name.
735 /// match os::self_exe_path() {
736 /// Some(exe_path) => println!("Executable's Path is: {}", exe_path.display()),
737 /// None => println!("Impossible to fetch the path of this executable.")
740 pub fn self_exe_path() -> Option<Path> {
741 self_exe_name().map(|mut p| { p.pop(); p })
744 /// Optionally returns the path to the current user's home directory if known.
748 /// Returns the value of the 'HOME' environment variable if it is set
749 /// and not equal to the empty string.
753 /// Returns the value of the 'HOME' environment variable if it is
754 /// set and not equal to the empty string. Otherwise, returns the value of the
755 /// 'USERPROFILE' environment variable if it is set and not equal to the empty
763 /// match os::homedir() {
764 /// Some(ref p) => println!("{}", p.display()),
765 /// None => println!("Impossible to get your home dir!")
768 pub fn homedir() -> Option<Path> {
771 fn _homedir() -> Option<Path> {
777 fn _homedir() -> Option<Path> {
778 aux_homedir("HOME").or(aux_homedir("USERPROFILE"))
782 fn aux_homedir(home_name: &str) -> Option<Path> {
783 match getenv_as_bytes(home_name) {
785 if p.is_empty() { None } else { Path::new_opt(p) }
794 * Returns the path to a temporary directory.
796 * On Unix, returns the value of the 'TMPDIR' environment variable if it is
797 * set, otherwise for non-Android it returns '/tmp'. If Android, since there
798 * is no global temporary folder (it is usually allocated per-app), we return
801 * On Windows, returns the value of, in order, the 'TMP', 'TEMP',
802 * 'USERPROFILE' environment variable if any are set and not the empty
803 * string. Otherwise, tmpdir returns the path to the Windows directory.
805 pub fn tmpdir() -> Path {
808 fn getenv_nonempty(v: &str) -> Option<Path> {
821 fn lookup() -> Path {
822 let default = if cfg!(target_os = "android") {
823 Path::new("/data/local/tmp")
828 getenv_nonempty("TMPDIR").unwrap_or(default)
832 fn lookup() -> Path {
833 getenv_nonempty("TMP").or(
834 getenv_nonempty("TEMP").or(
835 getenv_nonempty("USERPROFILE").or(
836 getenv_nonempty("WINDIR")))).unwrap_or(Path::new("C:\\Windows"))
841 * Convert a relative path to an absolute path
843 * If the given path is relative, return it prepended with the current working
844 * directory. If the given path is already an absolute path, return it
847 // NB: this is here rather than in path because it is a form of environment
848 // querying; what it does depends on the process working directory, not just
850 pub fn make_absolute(p: &Path) -> Path {
854 let mut ret = getcwd();
860 /// Changes the current working directory to the specified path, returning
861 /// whether the change was completed successfully or not.
862 pub fn change_dir(p: &Path) -> bool {
866 fn chdir(p: &Path) -> bool {
867 let p = match p.as_str() {
868 Some(s) => s.utf16_units().collect::<Vec<u16>>().append_one(0),
869 None => return false,
872 libc::SetCurrentDirectoryW(p.as_ptr()) != (0 as libc::BOOL)
877 fn chdir(p: &Path) -> bool {
880 libc::chdir(buf) == (0 as c_int)
887 /// Returns the platform-specific value of errno
888 pub fn errno() -> int {
889 #[cfg(target_os = "macos")]
890 #[cfg(target_os = "ios")]
891 #[cfg(target_os = "freebsd")]
892 fn errno_location() -> *const c_int {
894 fn __error() -> *const c_int;
901 #[cfg(target_os = "linux")]
902 #[cfg(target_os = "android")]
903 fn errno_location() -> *const c_int {
905 fn __errno_location() -> *const c_int;
913 (*errno_location()) as int
918 /// Returns the platform-specific value of errno
919 pub fn errno() -> uint {
920 use libc::types::os::arch::extra::DWORD;
922 #[link_name = "kernel32"]
924 fn GetLastError() -> DWORD;
928 GetLastError() as uint
932 /// Return the string corresponding to an `errno()` value of `errnum`.
933 pub fn error_string(errnum: uint) -> String {
934 return strerror(errnum);
937 fn strerror(errnum: uint) -> String {
938 #[cfg(target_os = "macos")]
939 #[cfg(target_os = "ios")]
940 #[cfg(target_os = "android")]
941 #[cfg(target_os = "freebsd")]
942 fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: libc::size_t)
945 fn strerror_r(errnum: c_int, buf: *mut c_char,
946 buflen: libc::size_t) -> c_int;
949 strerror_r(errnum, buf, buflen)
953 // GNU libc provides a non-compliant version of strerror_r by default
954 // and requires macros to instead use the POSIX compliant variant.
955 // So we just use __xpg_strerror_r which is always POSIX compliant
956 #[cfg(target_os = "linux")]
957 fn strerror_r(errnum: c_int, buf: *mut c_char,
958 buflen: libc::size_t) -> c_int {
960 fn __xpg_strerror_r(errnum: c_int,
962 buflen: libc::size_t)
966 __xpg_strerror_r(errnum, buf, buflen)
970 let mut buf = [0 as c_char, ..TMPBUF_SZ];
972 let p = buf.as_mut_ptr();
974 if strerror_r(errnum as c_int, p, buf.len() as libc::size_t) < 0 {
975 fail!("strerror_r failure");
978 str::raw::from_c_str(p as *const c_char).into_string()
983 fn strerror(errnum: uint) -> String {
984 use libc::types::os::arch::extra::DWORD;
985 use libc::types::os::arch::extra::LPWSTR;
986 use libc::types::os::arch::extra::LPVOID;
987 use libc::types::os::arch::extra::WCHAR;
989 #[link_name = "kernel32"]
991 fn FormatMessageW(flags: DWORD,
1001 static FORMAT_MESSAGE_FROM_SYSTEM: DWORD = 0x00001000;
1002 static FORMAT_MESSAGE_IGNORE_INSERTS: DWORD = 0x00000200;
1004 // This value is calculated from the macro
1005 // MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT)
1006 let langId = 0x0800 as DWORD;
1008 let mut buf = [0 as WCHAR, ..TMPBUF_SZ];
1011 let res = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
1012 FORMAT_MESSAGE_IGNORE_INSERTS,
1020 // Sometimes FormatMessageW can fail e.g. system doesn't like langId,
1021 let fm_err = errno();
1022 return format!("OS Error {} (FormatMessageW() returned error {})", errnum, fm_err);
1025 let msg = str::from_utf16(str::truncate_utf16_at_nul(buf));
1027 Some(msg) => format!("OS Error {}: {}", errnum, msg),
1028 None => format!("OS Error {} (FormatMessageW() returned invalid UTF-16)", errnum),
1034 /// Get a string representing the platform-dependent last error
1035 pub fn last_os_error() -> String {
1036 error_string(errno() as uint)
1039 static mut EXIT_STATUS: AtomicInt = INIT_ATOMIC_INT;
1042 * Sets the process exit code
1044 * Sets the exit code returned by the process if all supervised tasks
1045 * terminate successfully (without failing). If the current root task fails
1046 * and is supervised by the scheduler then any user-specified exit status is
1047 * ignored and the process exits with the default failure status.
1049 * Note that this is not synchronized against modifications of other threads.
1051 pub fn set_exit_status(code: int) {
1052 unsafe { EXIT_STATUS.store(code, SeqCst) }
1055 /// Fetches the process's current exit code. This defaults to 0 and can change
1056 /// by calling `set_exit_status`.
1057 pub fn get_exit_status() -> int {
1058 unsafe { EXIT_STATUS.load(SeqCst) }
1061 #[cfg(target_os = "macos")]
1062 unsafe fn load_argc_and_argv(argc: int,
1063 argv: *const *const c_char) -> Vec<Vec<u8>> {
1066 Vec::from_fn(argc as uint, |i| {
1067 Vec::from_slice(CString::new(*argv.offset(i as int),
1068 false).as_bytes_no_nul())
1073 * Returns the command line arguments
1075 * Returns a list of the command line arguments.
1077 #[cfg(target_os = "macos")]
1078 fn real_args_as_bytes() -> Vec<Vec<u8>> {
1080 let (argc, argv) = (*_NSGetArgc() as int,
1081 *_NSGetArgv() as *const *const c_char);
1082 load_argc_and_argv(argc, argv)
1086 // As _NSGetArgc and _NSGetArgv aren't mentioned in iOS docs
1087 // and use underscores in their names - they're most probably
1088 // are considered private and therefore should be avoided
1089 // Here is another way to get arguments using Objective C
1092 // In general it looks like:
1094 // let args = [[NSProcessInfo processInfo] arguments]
1095 // for i in range(0, [args count])
1096 // res.push([args objectAtIndex:i])
1098 #[cfg(target_os = "ios")]
1099 fn real_args_as_bytes() -> Vec<Vec<u8>> {
1104 #[link(name = "objc")]
1106 fn sel_registerName(name: *const libc::c_uchar) -> Sel;
1107 fn objc_msgSend(obj: NsId, sel: Sel, ...) -> NsId;
1108 fn objc_getClass(class_name: *const libc::c_uchar) -> NsId;
1111 #[link(name = "Foundation", kind = "framework")]
1114 type Sel = *const libc::c_void;
1115 type NsId = *const libc::c_void;
1117 let mut res = Vec::new();
1120 let processInfoSel = sel_registerName("processInfo\0".as_ptr());
1121 let argumentsSel = sel_registerName("arguments\0".as_ptr());
1122 let utf8Sel = sel_registerName("UTF8String\0".as_ptr());
1123 let countSel = sel_registerName("count\0".as_ptr());
1124 let objectAtSel = sel_registerName("objectAtIndex:\0".as_ptr());
1126 let klass = objc_getClass("NSProcessInfo\0".as_ptr());
1127 let info = objc_msgSend(klass, processInfoSel);
1128 let args = objc_msgSend(info, argumentsSel);
1130 let cnt: int = mem::transmute(objc_msgSend(args, countSel));
1131 for i in range(0, cnt) {
1132 let tmp = objc_msgSend(args, objectAtSel, i);
1133 let utf_c_str: *const libc::c_char =
1134 mem::transmute(objc_msgSend(tmp, utf8Sel));
1135 let s = CString::new(utf_c_str, false);
1136 if s.is_not_null() {
1137 res.push(Vec::from_slice(s.as_bytes_no_nul()))
1145 #[cfg(target_os = "linux")]
1146 #[cfg(target_os = "android")]
1147 #[cfg(target_os = "freebsd")]
1148 fn real_args_as_bytes() -> Vec<Vec<u8>> {
1151 match rt::args::clone() {
1153 None => fail!("process arguments not initialized")
1157 #[cfg(not(windows))]
1158 fn real_args() -> Vec<String> {
1159 real_args_as_bytes().move_iter()
1161 str::from_utf8_lossy(v.as_slice()).into_string()
1166 fn real_args() -> Vec<String> {
1169 let mut nArgs: c_int = 0;
1170 let lpArgCount: *mut c_int = &mut nArgs;
1171 let lpCmdLine = unsafe { GetCommandLineW() };
1172 let szArgList = unsafe { CommandLineToArgvW(lpCmdLine, lpArgCount) };
1174 let args = Vec::from_fn(nArgs as uint, |i| unsafe {
1175 // Determine the length of this argument.
1176 let ptr = *szArgList.offset(i as int);
1178 while *ptr.offset(len as int) != 0 { len += 1; }
1180 // Push it onto the list.
1181 let opt_s = slice::raw::buf_as_slice(ptr as *const _, len, |buf| {
1182 str::from_utf16(str::truncate_utf16_at_nul(buf))
1184 opt_s.expect("CommandLineToArgvW returned invalid UTF-16")
1188 LocalFree(szArgList as *mut c_void);
1195 fn real_args_as_bytes() -> Vec<Vec<u8>> {
1196 real_args().move_iter().map(|s| s.into_bytes()).collect()
1199 type LPCWSTR = *const u16;
1202 #[link_name="kernel32"]
1204 fn GetCommandLineW() -> LPCWSTR;
1205 fn LocalFree(ptr: *mut c_void);
1209 #[link_name="shell32"]
1211 fn CommandLineToArgvW(lpCmdLine: LPCWSTR,
1212 pNumArgs: *mut c_int) -> *mut *mut u16;
1215 /// Returns the arguments which this program was started with (normally passed
1216 /// via the command line).
1218 /// The arguments are interpreted as utf-8, with invalid bytes replaced with \uFFFD.
1219 /// See `str::from_utf8_lossy` for details.
1220 pub fn args() -> Vec<String> {
1224 /// Returns the arguments which this program was started with (normally passed
1225 /// via the command line) as byte vectors.
1226 pub fn args_as_bytes() -> Vec<Vec<u8>> {
1227 real_args_as_bytes()
1230 #[cfg(target_os = "macos")]
1232 // These functions are in crt_externs.h.
1233 pub fn _NSGetArgc() -> *mut c_int;
1234 pub fn _NSGetArgv() -> *mut *mut *mut c_char;
1237 // Round up `from` to be divisible by `to`
1238 fn round_up(from: uint, to: uint) -> uint {
1239 let r = if from % to == 0 {
1242 from + to - (from % to)
1251 /// Returns the page size of the current architecture in bytes.
1253 pub fn page_size() -> uint {
1255 libc::sysconf(libc::_SC_PAGESIZE) as uint
1259 /// Returns the page size of the current architecture in bytes.
1261 pub fn page_size() -> uint {
1264 let mut info = mem::zeroed();
1265 libc::GetSystemInfo(&mut info);
1267 return info.dwPageSize as uint;
1271 /// A memory mapped file or chunk of memory. This is a very system-specific
1272 /// interface to the OS's memory mapping facilities (`mmap` on POSIX,
1273 /// `VirtualAlloc`/`CreateFileMapping` on win32). It makes no attempt at
1274 /// abstracting platform differences, besides in error values returned. Consider
1275 /// yourself warned.
1277 /// The memory map is released (unmapped) when the destructor is run, so don't
1278 /// let it leave scope by accident if you want it to stick around.
1279 pub struct MemoryMap {
1280 /// Pointer to the memory created or modified by this map.
1282 /// Number of bytes this map applies to
1285 pub kind: MemoryMapKind,
1288 /// Type of memory map
1289 pub enum MemoryMapKind {
1290 /// Virtual memory map. Usually used to change the permissions of a given
1291 /// chunk of memory. Corresponds to `VirtualAlloc` on Windows.
1293 /// Virtual memory map. Usually used to change the permissions of a given
1294 /// chunk of memory, or for allocation. Corresponds to `VirtualAlloc` on
1299 /// Options the memory map is created with
1300 pub enum MapOption {
1301 /// The memory should be readable
1303 /// The memory should be writable
1305 /// The memory should be executable
1307 /// Create a map for a specific address range. Corresponds to `MAP_FIXED` on
1310 /// Create a memory mapping for a file with a given fd.
1312 /// When using `MapFd`, the start of the map is `uint` bytes from the start
1315 /// On POSIX, this can be used to specify the default flags passed to
1316 /// `mmap`. By default it uses `MAP_PRIVATE` and, if not using `MapFd`,
1317 /// `MAP_ANON`. This will override both of those. This is platform-specific
1318 /// (the exact values used) and ignored on Windows.
1319 MapNonStandardFlags(c_int),
1322 /// Possible errors when creating a map.
1324 /// ## The following are POSIX-specific
1326 /// fd was not open for reading or, if using `MapWritable`, was not open for
1329 /// fd was not valid
1331 /// Either the address given by `MapAddr` or offset given by `MapOffset` was
1332 /// not a multiple of `MemoryMap::granularity` (unaligned to page size).
1334 /// With `MapFd`, the fd does not support mapping.
1336 /// If using `MapAddr`, the address + `min_len` was outside of the process's
1337 /// address space. If using `MapFd`, the target of the fd didn't have enough
1338 /// resources to fulfill the request.
1340 /// A zero-length map was requested. This is invalid according to
1341 /// [POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/functions/mmap.html).
1342 /// Not all platforms obey this, but this wrapper does.
1344 /// Unrecognized error. The inner value is the unrecognized errno.
1346 /// ## The following are win32-specific
1348 /// Unsupported combination of protection flags
1349 /// (`MapReadable`/`MapWritable`/`MapExecutable`).
1351 /// When using `MapFd`, `MapOffset` was given (Windows does not support this
1354 /// When using `MapFd`, there was already a mapping to the file.
1356 /// Unrecognized error from `VirtualAlloc`. The inner value is the return
1357 /// value of GetLastError.
1358 ErrVirtualAlloc(uint),
1359 /// Unrecognized error from `CreateFileMapping`. The inner value is the
1360 /// return value of `GetLastError`.
1361 ErrCreateFileMappingW(uint),
1362 /// Unrecognized error from `MapViewOfFile`. The inner value is the return
1363 /// value of `GetLastError`.
1364 ErrMapViewOfFile(uint)
1367 impl fmt::Show for MapError {
1368 fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result {
1369 let str = match *self {
1370 ErrFdNotAvail => "fd not available for reading or writing",
1371 ErrInvalidFd => "Invalid fd",
1373 "Unaligned address, invalid flags, negative length or \
1376 ErrNoMapSupport=> "File doesn't support mapping",
1377 ErrNoMem => "Invalid address, or not enough available memory",
1378 ErrUnsupProt => "Protection mode unsupported",
1379 ErrUnsupOffset => "Offset in virtual memory mode is unsupported",
1380 ErrAlreadyExists => "File mapping for specified file already exists",
1381 ErrZeroLength => "Zero-length mapping not allowed",
1382 ErrUnknown(code) => {
1383 return write!(out, "Unknown error = {}", code)
1385 ErrVirtualAlloc(code) => {
1386 return write!(out, "VirtualAlloc failure = {}", code)
1388 ErrCreateFileMappingW(code) => {
1389 return write!(out, "CreateFileMappingW failure = {}", code)
1391 ErrMapViewOfFile(code) => {
1392 return write!(out, "MapViewOfFile failure = {}", code)
1395 write!(out, "{}", str)
1401 /// Create a new mapping with the given `options`, at least `min_len` bytes
1402 /// long. `min_len` must be greater than zero; see the note on
1403 /// `ErrZeroLength`.
1404 pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
1408 return Err(ErrZeroLength)
1410 let mut addr: *const u8 = ptr::null();
1412 let mut flags = libc::MAP_PRIVATE;
1415 let mut custom_flags = false;
1416 let len = round_up(min_len, page_size());
1418 for &o in options.iter() {
1420 MapReadable => { prot |= libc::PROT_READ; },
1421 MapWritable => { prot |= libc::PROT_WRITE; },
1422 MapExecutable => { prot |= libc::PROT_EXEC; },
1424 flags |= libc::MAP_FIXED;
1428 flags |= libc::MAP_FILE;
1431 MapOffset(offset_) => { offset = offset_ as off_t; },
1432 MapNonStandardFlags(f) => { custom_flags = true; flags = f },
1435 if fd == -1 && !custom_flags { flags |= libc::MAP_ANON; }
1438 libc::mmap(addr as *mut c_void, len as libc::size_t, prot, flags,
1441 if r == libc::MAP_FAILED {
1442 Err(match errno() as c_int {
1443 libc::EACCES => ErrFdNotAvail,
1444 libc::EBADF => ErrInvalidFd,
1445 libc::EINVAL => ErrUnaligned,
1446 libc::ENODEV => ErrNoMapSupport,
1447 libc::ENOMEM => ErrNoMem,
1448 code => ErrUnknown(code as int)
1457 MapFile(ptr::null())
1463 /// Granularity that the offset or address must be for `MapOffset` and
1464 /// `MapAddr` respectively.
1465 pub fn granularity() -> uint {
1471 impl Drop for MemoryMap {
1472 /// Unmap the mapping. Fails the task if `munmap` fails.
1473 fn drop(&mut self) {
1474 if self.len == 0 { /* workaround for dummy_stack */ return; }
1477 // `munmap` only fails due to logic errors
1478 libc::munmap(self.data as *mut c_void, self.len as libc::size_t);
1485 /// Create a new mapping with the given `options`, at least `min_len` bytes long.
1486 pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
1487 use libc::types::os::arch::extra::{LPVOID, DWORD, SIZE_T, HANDLE};
1489 let mut lpAddress: LPVOID = ptr::mut_null();
1490 let mut readable = false;
1491 let mut writable = false;
1492 let mut executable = false;
1493 let mut fd: c_int = -1;
1494 let mut offset: uint = 0;
1495 let len = round_up(min_len, page_size());
1497 for &o in options.iter() {
1499 MapReadable => { readable = true; },
1500 MapWritable => { writable = true; },
1501 MapExecutable => { executable = true; }
1502 MapAddr(addr_) => { lpAddress = addr_ as LPVOID; },
1503 MapFd(fd_) => { fd = fd_; },
1504 MapOffset(offset_) => { offset = offset_; },
1505 MapNonStandardFlags(..) => {}
1509 let flProtect = match (executable, readable, writable) {
1510 (false, false, false) if fd == -1 => libc::PAGE_NOACCESS,
1511 (false, true, false) => libc::PAGE_READONLY,
1512 (false, true, true) => libc::PAGE_READWRITE,
1513 (true, false, false) if fd == -1 => libc::PAGE_EXECUTE,
1514 (true, true, false) => libc::PAGE_EXECUTE_READ,
1515 (true, true, true) => libc::PAGE_EXECUTE_READWRITE,
1516 _ => return Err(ErrUnsupProt)
1521 return Err(ErrUnsupOffset);
1524 libc::VirtualAlloc(lpAddress,
1526 libc::MEM_COMMIT | libc::MEM_RESERVE,
1530 0 => Err(ErrVirtualAlloc(errno())),
1538 let dwDesiredAccess = match (executable, readable, writable) {
1539 (false, true, false) => libc::FILE_MAP_READ,
1540 (false, true, true) => libc::FILE_MAP_WRITE,
1541 (true, true, false) => libc::FILE_MAP_READ | libc::FILE_MAP_EXECUTE,
1542 (true, true, true) => libc::FILE_MAP_WRITE | libc::FILE_MAP_EXECUTE,
1543 _ => return Err(ErrUnsupProt) // Actually, because of the check above,
1544 // we should never get here.
1547 let hFile = libc::get_osfhandle(fd) as HANDLE;
1548 let mapping = libc::CreateFileMappingW(hFile,
1554 if mapping == ptr::mut_null() {
1555 return Err(ErrCreateFileMappingW(errno()));
1557 if errno() as c_int == libc::ERROR_ALREADY_EXISTS {
1558 return Err(ErrAlreadyExists);
1560 let r = libc::MapViewOfFile(mapping,
1562 ((len as u64) >> 32) as DWORD,
1563 (offset & 0xffff_ffff) as DWORD,
1566 0 => Err(ErrMapViewOfFile(errno())),
1570 kind: MapFile(mapping as *const u8)
1577 /// Granularity of MapAddr() and MapOffset() parameter values.
1578 /// This may be greater than the value returned by page_size().
1579 pub fn granularity() -> uint {
1582 let mut info = mem::zeroed();
1583 libc::GetSystemInfo(&mut info);
1585 return info.dwAllocationGranularity as uint;
1591 impl Drop for MemoryMap {
1592 /// Unmap the mapping. Fails the task if any of `VirtualFree`,
1593 /// `UnmapViewOfFile`, or `CloseHandle` fail.
1594 fn drop(&mut self) {
1595 use libc::types::os::arch::extra::{LPCVOID, HANDLE};
1596 use libc::consts::os::extra::FALSE;
1597 if self.len == 0 { return }
1602 if libc::VirtualFree(self.data as *mut c_void, 0,
1603 libc::MEM_RELEASE) == 0 {
1604 println!("VirtualFree failed: {}", errno());
1607 MapFile(mapping) => {
1608 if libc::UnmapViewOfFile(self.data as LPCVOID) == FALSE {
1609 println!("UnmapViewOfFile failed: {}", errno());
1611 if libc::CloseHandle(mapping as HANDLE) == FALSE {
1612 println!("CloseHandle failed: {}", errno());
1620 #[cfg(target_os = "linux")]
1622 pub use os::arch_consts::ARCH;
1624 pub static FAMILY: &'static str = "unix";
1626 /// A string describing the specific operating system in use: in this
1628 pub static SYSNAME: &'static str = "linux";
1630 /// Specifies the filename prefix used for shared libraries on this
1631 /// platform: in this case, `lib`.
1632 pub static DLL_PREFIX: &'static str = "lib";
1634 /// Specifies the filename suffix used for shared libraries on this
1635 /// platform: in this case, `.so`.
1636 pub static DLL_SUFFIX: &'static str = ".so";
1638 /// Specifies the file extension used for shared libraries on this
1639 /// platform that goes after the dot: in this case, `so`.
1640 pub static DLL_EXTENSION: &'static str = "so";
1642 /// Specifies the filename suffix used for executable binaries on this
1643 /// platform: in this case, the empty string.
1644 pub static EXE_SUFFIX: &'static str = "";
1646 /// Specifies the file extension, if any, used for executable binaries
1647 /// on this platform: in this case, the empty string.
1648 pub static EXE_EXTENSION: &'static str = "";
1651 #[cfg(target_os = "macos")]
1653 pub use os::arch_consts::ARCH;
1655 pub static FAMILY: &'static str = "unix";
1657 /// A string describing the specific operating system in use: in this
1659 pub static SYSNAME: &'static str = "macos";
1661 /// Specifies the filename prefix used for shared libraries on this
1662 /// platform: in this case, `lib`.
1663 pub static DLL_PREFIX: &'static str = "lib";
1665 /// Specifies the filename suffix used for shared libraries on this
1666 /// platform: in this case, `.dylib`.
1667 pub static DLL_SUFFIX: &'static str = ".dylib";
1669 /// Specifies the file extension used for shared libraries on this
1670 /// platform that goes after the dot: in this case, `dylib`.
1671 pub static DLL_EXTENSION: &'static str = "dylib";
1673 /// Specifies the filename suffix used for executable binaries on this
1674 /// platform: in this case, the empty string.
1675 pub static EXE_SUFFIX: &'static str = "";
1677 /// Specifies the file extension, if any, used for executable binaries
1678 /// on this platform: in this case, the empty string.
1679 pub static EXE_EXTENSION: &'static str = "";
1682 #[cfg(target_os = "ios")]
1684 pub use os::arch_consts::ARCH;
1686 pub static FAMILY: &'static str = "unix";
1688 /// A string describing the specific operating system in use: in this
1690 pub static SYSNAME: &'static str = "ios";
1692 /// Specifies the filename suffix used for executable binaries on this
1693 /// platform: in this case, the empty string.
1694 pub static EXE_SUFFIX: &'static str = "";
1696 /// Specifies the file extension, if any, used for executable binaries
1697 /// on this platform: in this case, the empty string.
1698 pub static EXE_EXTENSION: &'static str = "";
1701 #[cfg(target_os = "freebsd")]
1703 pub use os::arch_consts::ARCH;
1705 pub static FAMILY: &'static str = "unix";
1707 /// A string describing the specific operating system in use: in this
1708 /// case, `freebsd`.
1709 pub static SYSNAME: &'static str = "freebsd";
1711 /// Specifies the filename prefix used for shared libraries on this
1712 /// platform: in this case, `lib`.
1713 pub static DLL_PREFIX: &'static str = "lib";
1715 /// Specifies the filename suffix used for shared libraries on this
1716 /// platform: in this case, `.so`.
1717 pub static DLL_SUFFIX: &'static str = ".so";
1719 /// Specifies the file extension used for shared libraries on this
1720 /// platform that goes after the dot: in this case, `so`.
1721 pub static DLL_EXTENSION: &'static str = "so";
1723 /// Specifies the filename suffix used for executable binaries on this
1724 /// platform: in this case, the empty string.
1725 pub static EXE_SUFFIX: &'static str = "";
1727 /// Specifies the file extension, if any, used for executable binaries
1728 /// on this platform: in this case, the empty string.
1729 pub static EXE_EXTENSION: &'static str = "";
1732 #[cfg(target_os = "android")]
1734 pub use os::arch_consts::ARCH;
1736 pub static FAMILY: &'static str = "unix";
1738 /// A string describing the specific operating system in use: in this
1739 /// case, `android`.
1740 pub static SYSNAME: &'static str = "android";
1742 /// Specifies the filename prefix used for shared libraries on this
1743 /// platform: in this case, `lib`.
1744 pub static DLL_PREFIX: &'static str = "lib";
1746 /// Specifies the filename suffix used for shared libraries on this
1747 /// platform: in this case, `.so`.
1748 pub static DLL_SUFFIX: &'static str = ".so";
1750 /// Specifies the file extension used for shared libraries on this
1751 /// platform that goes after the dot: in this case, `so`.
1752 pub static DLL_EXTENSION: &'static str = "so";
1754 /// Specifies the filename suffix used for executable binaries on this
1755 /// platform: in this case, the empty string.
1756 pub static EXE_SUFFIX: &'static str = "";
1758 /// Specifies the file extension, if any, used for executable binaries
1759 /// on this platform: in this case, the empty string.
1760 pub static EXE_EXTENSION: &'static str = "";
1763 #[cfg(target_os = "win32")]
1765 pub use os::arch_consts::ARCH;
1767 pub static FAMILY: &'static str = "windows";
1769 /// A string describing the specific operating system in use: in this
1771 pub static SYSNAME: &'static str = "win32";
1773 /// Specifies the filename prefix used for shared libraries on this
1774 /// platform: in this case, the empty string.
1775 pub static DLL_PREFIX: &'static str = "";
1777 /// Specifies the filename suffix used for shared libraries on this
1778 /// platform: in this case, `.dll`.
1779 pub static DLL_SUFFIX: &'static str = ".dll";
1781 /// Specifies the file extension used for shared libraries on this
1782 /// platform that goes after the dot: in this case, `dll`.
1783 pub static DLL_EXTENSION: &'static str = "dll";
1785 /// Specifies the filename suffix used for executable binaries on this
1786 /// platform: in this case, `.exe`.
1787 pub static EXE_SUFFIX: &'static str = ".exe";
1789 /// Specifies the file extension, if any, used for executable binaries
1790 /// on this platform: in this case, `exe`.
1791 pub static EXE_EXTENSION: &'static str = "exe";
1794 #[cfg(target_arch = "x86")]
1796 pub static ARCH: &'static str = "x86";
1799 #[cfg(target_arch = "x86_64")]
1801 pub static ARCH: &'static str = "x86_64";
1804 #[cfg(target_arch = "arm")]
1806 pub static ARCH: &'static str = "arm";
1809 #[cfg(target_arch = "mips")]
1811 pub static ARCH: &'static str = "mips";
1814 #[cfg(target_arch = "mipsel")]
1816 pub static ARCH: &'static str = "mipsel";
1824 use os::{env, getcwd, getenv, make_absolute};
1825 use os::{split_paths, join_paths, setenv, unsetenv};
1831 pub fn last_os_error() {
1832 debug!("{}", os::last_os_error());
1835 fn make_rand_name() -> String {
1836 let mut rng = rand::task_rng();
1837 let n = format!("TEST{}", rng.gen_ascii_chars().take(10u)
1838 .collect::<String>());
1839 assert!(getenv(n.as_slice()).is_none());
1844 fn test_num_cpus() {
1845 assert!(os::num_cpus() > 0);
1850 let n = make_rand_name();
1851 setenv(n.as_slice(), "VALUE");
1852 assert_eq!(getenv(n.as_slice()), option::Some("VALUE".to_string()));
1856 fn test_unsetenv() {
1857 let n = make_rand_name();
1858 setenv(n.as_slice(), "VALUE");
1859 unsetenv(n.as_slice());
1860 assert_eq!(getenv(n.as_slice()), option::None);
1865 fn test_setenv_overwrite() {
1866 let n = make_rand_name();
1867 setenv(n.as_slice(), "1");
1868 setenv(n.as_slice(), "2");
1869 assert_eq!(getenv(n.as_slice()), option::Some("2".to_string()));
1870 setenv(n.as_slice(), "");
1871 assert_eq!(getenv(n.as_slice()), option::Some("".to_string()));
1874 // Windows GetEnvironmentVariable requires some extra work to make sure
1875 // the buffer the variable is copied into is the right size
1878 fn test_getenv_big() {
1879 let mut s = "".to_string();
1882 s.push_str("aaaaaaaaaa");
1885 let n = make_rand_name();
1886 setenv(n.as_slice(), s.as_slice());
1887 debug!("{}", s.clone());
1888 assert_eq!(getenv(n.as_slice()), option::Some(s));
1892 fn test_self_exe_name() {
1893 let path = os::self_exe_name();
1894 assert!(path.is_some());
1895 let path = path.unwrap();
1896 debug!("{:?}", path.clone());
1898 // Hard to test this function
1899 assert!(path.is_absolute());
1903 fn test_self_exe_path() {
1904 let path = os::self_exe_path();
1905 assert!(path.is_some());
1906 let path = path.unwrap();
1907 debug!("{:?}", path.clone());
1909 // Hard to test this function
1910 assert!(path.is_absolute());
1915 fn test_env_getenv() {
1917 assert!(e.len() > 0u);
1919 let (n, v) = (*p).clone();
1920 debug!("{:?}", n.clone());
1921 let v2 = getenv(n.as_slice());
1922 // MingW seems to set some funky environment variables like
1923 // "=C:=C:\MinGW\msys\1.0\bin" and "!::=::\" that are returned
1924 // from env() but not visible from getenv().
1925 assert!(v2.is_none() || v2 == option::Some(v));
1930 fn test_env_set_get_huge() {
1931 let n = make_rand_name();
1932 let s = "x".repeat(10000).to_string();
1933 setenv(n.as_slice(), s.as_slice());
1934 assert_eq!(getenv(n.as_slice()), Some(s));
1935 unsetenv(n.as_slice());
1936 assert_eq!(getenv(n.as_slice()), None);
1940 fn test_env_setenv() {
1941 let n = make_rand_name();
1944 setenv(n.as_slice(), "VALUE");
1945 assert!(!e.contains(&(n.clone(), "VALUE".to_string())));
1948 assert!(e.contains(&(n, "VALUE".to_string())));
1953 assert!((!Path::new("test-path").is_absolute()));
1956 debug!("Current working directory: {}", cwd.display());
1958 debug!("{:?}", make_absolute(&Path::new("test-path")));
1959 debug!("{:?}", make_absolute(&Path::new("/usr/bin")));
1965 let oldhome = getenv("HOME");
1967 setenv("HOME", "/home/MountainView");
1968 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1971 assert!(os::homedir().is_none());
1973 for s in oldhome.iter() {
1974 setenv("HOME", s.as_slice());
1982 let oldhome = getenv("HOME");
1983 let olduserprofile = getenv("USERPROFILE");
1986 setenv("USERPROFILE", "");
1988 assert!(os::homedir().is_none());
1990 setenv("HOME", "/home/MountainView");
1991 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1995 setenv("USERPROFILE", "/home/MountainView");
1996 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1998 setenv("HOME", "/home/MountainView");
1999 setenv("USERPROFILE", "/home/PaloAlto");
2000 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
2002 for s in oldhome.iter() {
2003 setenv("HOME", s.as_slice());
2005 for s in olduserprofile.iter() {
2006 setenv("USERPROFILE", s.as_slice());
2011 fn memory_map_rw() {
2012 use result::{Ok, Err};
2014 let chunk = match os::MemoryMap::new(16, [
2019 Err(msg) => fail!("{}", msg)
2021 assert!(chunk.len >= 16);
2025 assert!(*chunk.data == 0xBE);
2030 fn memory_map_file() {
2031 use result::{Ok, Err};
2037 fn lseek_(fd: c_int, size: uint) {
2039 assert!(lseek(fd, size as off_t, SEEK_SET) == size as off_t);
2043 fn lseek_(fd: c_int, size: uint) {
2045 assert!(lseek(fd, size as c_long, SEEK_SET) == size as c_long);
2049 let mut path = tmpdir();
2050 path.push("mmap_file.tmp");
2051 let size = MemoryMap::granularity() * 2;
2054 let fd = path.with_c_str(|path| {
2055 open(path, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR)
2058 "x".with_c_str(|x| assert!(write(fd, x as *const c_void, 1) == 1));
2061 let chunk = match MemoryMap::new(size / 2, [
2068 Err(msg) => fail!("{}", msg)
2070 assert!(chunk.len > 0);
2074 assert!(*chunk.data == 0xbe);
2079 fs::unlink(&path).unwrap();
2084 fn split_paths_windows() {
2085 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
2086 split_paths(unparsed) ==
2087 parsed.iter().map(|s| Path::new(*s)).collect()
2090 assert!(check_parse("", [""]));
2091 assert!(check_parse(r#""""#, [""]));
2092 assert!(check_parse(";;", ["", "", ""]));
2093 assert!(check_parse(r"c:\", [r"c:\"]));
2094 assert!(check_parse(r"c:\;", [r"c:\", ""]));
2095 assert!(check_parse(r"c:\;c:\Program Files\",
2096 [r"c:\", r"c:\Program Files\"]));
2097 assert!(check_parse(r#"c:\;c:\"foo"\"#, [r"c:\", r"c:\foo\"]));
2098 assert!(check_parse(r#"c:\;c:\"foo;bar"\;c:\baz"#,
2099 [r"c:\", r"c:\foo;bar\", r"c:\baz"]));
2104 fn split_paths_unix() {
2105 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
2106 split_paths(unparsed) ==
2107 parsed.iter().map(|s| Path::new(*s)).collect()
2110 assert!(check_parse("", [""]));
2111 assert!(check_parse("::", ["", "", ""]));
2112 assert!(check_parse("/", ["/"]));
2113 assert!(check_parse("/:", ["/", ""]));
2114 assert!(check_parse("/:/usr/local", ["/", "/usr/local"]));
2119 fn join_paths_unix() {
2120 fn test_eq(input: &[&str], output: &str) -> bool {
2121 join_paths(input).unwrap().as_slice() == output.as_bytes()
2124 assert!(test_eq([], ""));
2125 assert!(test_eq(["/bin", "/usr/bin", "/usr/local/bin"],
2126 "/bin:/usr/bin:/usr/local/bin"));
2127 assert!(test_eq(["", "/bin", "", "", "/usr/bin", ""],
2128 ":/bin:::/usr/bin:"));
2129 assert!(join_paths(["/te:st"]).is_err());
2134 fn join_paths_windows() {
2135 fn test_eq(input: &[&str], output: &str) -> bool {
2136 join_paths(input).unwrap().as_slice() == output.as_bytes()
2139 assert!(test_eq([], ""));
2140 assert!(test_eq([r"c:\windows", r"c:\"],
2141 r"c:\windows;c:\"));
2142 assert!(test_eq(["", r"c:\windows", "", "", r"c:\", ""],
2143 r";c:\windows;;;c:\;"));
2144 assert!(test_eq([r"c:\te;st", r"c:\"],
2145 r#""c:\te;st";c:\"#));
2146 assert!(join_paths([r#"c:\te"st"#]).is_err());
2149 // More recursive_mkdir tests are in extra::tempfile