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};
51 use sync::atomics::{AtomicInt, INIT_ATOMIC_INT, SeqCst};
59 /// Get the number of cores available
60 pub fn num_cpus() -> uint {
62 return rust_get_num_cpus();
66 fn rust_get_num_cpus() -> libc::uintptr_t;
70 pub static TMPBUF_SZ : uint = 1000u;
71 static BUF_BYTES : uint = 2048u;
73 /// Returns the current working directory as a Path.
77 /// Fails if the current working directory value is invalid:
80 /// * Current directory does not exist.
81 /// * There are insufficient permissions to access the current directory.
88 /// // We assume that we are in a valid directory like "/home".
89 /// let current_working_directory = os::getcwd();
90 /// println!("The current directory is {}", current_working_directory.display());
94 pub fn getcwd() -> Path {
97 let mut buf = [0 as c_char, ..BUF_BYTES];
99 if libc::getcwd(buf.as_mut_ptr(), buf.len() as libc::size_t).is_null() {
102 Path::new(CString::new(buf.as_ptr(), false))
106 /// Returns the current working directory as a Path.
110 /// Fails if the current working directory value is invalid.
113 /// * Current directory does not exist.
114 /// * There are insufficient permissions to access the current directory.
121 /// // We assume that we are in a valid directory like "C:\\Windows".
122 /// let current_working_directory = os::getcwd();
123 /// println!("The current directory is {}", current_working_directory.display());
127 pub fn getcwd() -> Path {
129 use libc::GetCurrentDirectoryW;
131 let mut buf = [0 as u16, ..BUF_BYTES];
133 if libc::GetCurrentDirectoryW(buf.len() as DWORD, buf.as_mut_ptr()) == 0 as DWORD {
137 Path::new(String::from_utf16(::str::truncate_utf16_at_nul(buf))
138 .expect("GetCurrentDirectoryW returned invalid UTF-16"))
143 use libc::types::os::arch::extra::DWORD;
145 use option::{None, Option};
148 use slice::{MutableVector, ImmutableVector};
153 pub fn fill_utf16_buf_and_decode(f: |*mut u16, DWORD| -> DWORD)
157 let mut n = TMPBUF_SZ as DWORD;
159 let mut done = false;
161 let mut buf = Vec::from_elem(n as uint, 0u16);
162 let k = f(buf.as_mut_ptr(), n);
163 if k == (0 as DWORD) {
166 libc::GetLastError() ==
167 libc::ERROR_INSUFFICIENT_BUFFER as DWORD {
175 let sub = buf.slice(0, k as uint);
176 // We want to explicitly catch the case when the
177 // closure returned invalid UTF-16, rather than
178 // set `res` to None and continue.
179 let s = String::from_utf16(sub)
180 .expect("fill_utf16_buf_and_decode: closure created invalid UTF-16");
181 res = option::Some(s)
190 Accessing environment variables is not generally threadsafe.
191 Serialize access through a global lock.
193 fn with_env_lock<T>(f: || -> T) -> T {
194 use rt::mutex::{StaticNativeMutex, NATIVE_MUTEX_INIT};
196 static mut lock: StaticNativeMutex = NATIVE_MUTEX_INIT;
199 let _guard = lock.lock();
204 /// Returns a vector of (variable, value) pairs, for all the environment
205 /// variables of the current process.
207 /// Invalid UTF-8 bytes are replaced with \uFFFD. See `String::from_utf8_lossy()`
215 /// // We will iterate through the references to the element returned by os::env();
216 /// for &(ref key, ref value) in os::env().iter() {
217 /// println!("'{}': '{}'", key, value );
220 pub fn env() -> Vec<(String,String)> {
221 env_as_bytes().move_iter().map(|(k,v)| {
222 let k = String::from_utf8_lossy(k.as_slice()).into_string();
223 let v = String::from_utf8_lossy(v.as_slice()).into_string();
228 /// Returns a vector of (variable, value) byte-vector pairs for all the
229 /// environment variables of the current process.
230 pub fn env_as_bytes() -> Vec<(Vec<u8>,Vec<u8>)> {
233 unsafe fn get_env_pairs() -> Vec<Vec<u8>> {
236 use libc::funcs::extra::kernel32::{
237 GetEnvironmentStringsW,
238 FreeEnvironmentStringsW
240 let ch = GetEnvironmentStringsW();
242 fail!("os::env() failure getting env string from OS: {}",
243 os::last_os_error());
245 // Here, we lossily decode the string as UTF16.
247 // The docs suggest that the result should be in Unicode, but
248 // Windows doesn't guarantee it's actually UTF16 -- it doesn't
249 // validate the environment string passed to CreateProcess nor
250 // SetEnvironmentVariable. Yet, it's unlikely that returning a
251 // raw u16 buffer would be of practical use since the result would
252 // be inherently platform-dependent and introduce additional
253 // complexity to this code.
255 // Using the non-Unicode version of GetEnvironmentStrings is even
256 // worse since the result is in an OEM code page. Characters that
257 // can't be encoded in the code page would be turned into question
259 let mut result = Vec::new();
261 while *ch.offset(i) != 0 {
262 let p = &*ch.offset(i);
263 let len = ptr::position(p, |c| *c == 0);
264 raw::buf_as_slice(p, len, |s| {
265 result.push(String::from_utf16_lossy(s).into_bytes());
269 FreeEnvironmentStringsW(ch);
273 unsafe fn get_env_pairs() -> Vec<Vec<u8>> {
277 fn rust_env_pairs() -> *const *const c_char;
279 let environ = rust_env_pairs();
280 if environ as uint == 0 {
281 fail!("os::env() failure getting env string from OS: {}",
282 os::last_os_error());
284 let mut result = Vec::new();
285 ptr::array_each(environ, |e| {
287 Vec::from_slice(CString::new(e, false).as_bytes_no_nul());
288 result.push(env_pair);
293 fn env_convert(input: Vec<Vec<u8>>) -> Vec<(Vec<u8>, Vec<u8>)> {
294 let mut pairs = Vec::new();
295 for p in input.iter() {
296 let mut it = p.as_slice().splitn(1, |b| *b == '=' as u8);
297 let key = Vec::from_slice(it.next().unwrap());
298 let val = Vec::from_slice(it.next().unwrap_or(&[]));
299 pairs.push((key, val));
304 let unparsed_environ = get_env_pairs();
305 env_convert(unparsed_environ)
311 /// Fetches the environment variable `n` from the current process, returning
312 /// None if the variable isn't set.
314 /// Any invalid UTF-8 bytes in the value are replaced by \uFFFD. See
315 /// `String::from_utf8_lossy()` for details.
319 /// Fails if `n` has any interior NULs.
326 /// let key = "HOME";
327 /// match os::getenv(key) {
328 /// Some(val) => println!("{}: {}", key, val),
329 /// None => println!("{} is not defined in the environment.", key)
332 pub fn getenv(n: &str) -> Option<String> {
333 getenv_as_bytes(n).map(|v| String::from_utf8_lossy(v.as_slice()).into_string())
337 /// Fetches the environment variable `n` byte vector from the current process,
338 /// returning None if the variable isn't set.
342 /// Fails if `n` has any interior NULs.
343 pub fn getenv_as_bytes(n: &str) -> Option<Vec<u8>> {
348 let s = n.with_c_str(|buf| libc::getenv(buf));
352 Some(Vec::from_slice(CString::new(s as *const i8,
353 false).as_bytes_no_nul()))
360 /// Fetches the environment variable `n` from the current process, returning
361 /// None if the variable isn't set.
362 pub fn getenv(n: &str) -> Option<String> {
365 use os::win32::{fill_utf16_buf_and_decode};
366 let n: Vec<u16> = n.utf16_units().collect();
367 let n = n.append_one(0);
368 fill_utf16_buf_and_decode(|buf, sz| {
369 libc::GetEnvironmentVariableW(n.as_ptr(), buf, sz)
376 /// Fetches the environment variable `n` byte vector from the current process,
377 /// returning None if the variable isn't set.
378 pub fn getenv_as_bytes(n: &str) -> Option<Vec<u8>> {
379 getenv(n).map(|s| s.into_bytes())
382 /// Sets the environment variable `n` to the value `v` for the currently running
391 /// os::setenv(key, "VALUE");
392 /// match os::getenv(key) {
393 /// Some(ref val) => println!("{}: {}", key, val),
394 /// None => println!("{} is not defined in the environment.", key)
397 pub fn setenv<T: BytesContainer>(n: &str, v: T) {
399 fn _setenv(n: &str, v: &[u8]) {
402 n.with_c_str(|nbuf| {
403 v.with_c_str(|vbuf| {
404 libc::funcs::posix01::unistd::setenv(nbuf, vbuf, 1);
412 fn _setenv(n: &str, v: &[u8]) {
413 let n: Vec<u16> = n.utf16_units().collect();
414 let n = n.append_one(0);
415 let v: Vec<u16> = ::str::from_utf8(v).unwrap().utf16_units().collect();
416 let v = v.append_one(0);
420 libc::SetEnvironmentVariableW(n.as_ptr(), v.as_ptr());
425 _setenv(n, v.container_as_bytes())
428 /// Remove a variable from the environment entirely.
429 pub fn unsetenv(n: &str) {
431 fn _unsetenv(n: &str) {
434 n.with_c_str(|nbuf| {
435 libc::funcs::posix01::unistd::unsetenv(nbuf);
442 fn _unsetenv(n: &str) {
443 let n: Vec<u16> = n.utf16_units().collect();
444 let n = n.append_one(0);
447 libc::SetEnvironmentVariableW(n.as_ptr(), ptr::null());
454 /// Parses input according to platform conventions for the `PATH`
455 /// environment variable.
461 /// let key = "PATH";
462 /// match os::getenv_as_bytes(key) {
464 /// for path in os::split_paths(paths).iter() {
465 /// println!("'{}'", path.display());
468 /// None => println!("{} is not defined in the environment.", key)
471 pub fn split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> {
473 fn _split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> {
474 unparsed.container_as_bytes()
475 .split(|b| *b == b':')
481 fn _split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> {
482 // On Windows, the PATH environment variable is semicolon separated. Double
483 // quotes are used as a way of introducing literal semicolons (since
484 // c:\some;dir is a valid Windows path). Double quotes are not themselves
485 // permitted in path names, so there is no way to escape a double quote.
486 // Quoted regions can appear in arbitrary locations, so
488 // c:\foo;c:\som"e;di"r;c:\bar
490 // Should parse as [c:\foo, c:\some;dir, c:\bar].
492 // (The above is based on testing; there is no clear reference available
495 let mut parsed = Vec::new();
496 let mut in_progress = Vec::new();
497 let mut in_quote = false;
499 for b in unparsed.container_as_bytes().iter() {
501 b';' if !in_quote => {
502 parsed.push(Path::new(in_progress.as_slice()));
503 in_progress.truncate(0)
506 in_quote = !in_quote;
509 in_progress.push(*b);
513 parsed.push(Path::new(in_progress));
517 _split_paths(unparsed)
520 /// Joins a collection of `Path`s appropriately for the `PATH`
521 /// environment variable.
523 /// Returns a `Vec<u8>` on success, since `Path`s are not utf-8
524 /// encoded on all platforms.
526 /// Returns an `Err` (containing an error message) if one of the input
527 /// `Path`s contains an invalid character for constructing the `PATH`
528 /// variable (a double quote on Windows or a colon on Unix).
534 /// use std::path::Path;
536 /// let key = "PATH";
537 /// let mut paths = os::getenv_as_bytes(key).map_or(Vec::new(), os::split_paths);
538 /// paths.push(Path::new("/home/xyz/bin"));
539 /// os::setenv(key, os::join_paths(paths.as_slice()).unwrap());
541 pub fn join_paths<T: BytesContainer>(paths: &[T]) -> Result<Vec<u8>, &'static str> {
543 fn _join_paths<T: BytesContainer>(paths: &[T]) -> Result<Vec<u8>, &'static str> {
544 let mut joined = Vec::new();
547 for (i, path) in paths.iter().map(|p| p.container_as_bytes()).enumerate() {
548 if i > 0 { joined.push(sep) }
549 if path.contains(&b'"') {
550 return Err("path segment contains `\"`");
551 } else if path.contains(&sep) {
553 joined.push_all(path);
556 joined.push_all(path);
564 fn _join_paths<T: BytesContainer>(paths: &[T]) -> Result<Vec<u8>, &'static str> {
565 let mut joined = Vec::new();
568 for (i, path) in paths.iter().map(|p| p.container_as_bytes()).enumerate() {
569 if i > 0 { joined.push(sep) }
570 if path.contains(&sep) { return Err("path segment contains separator `:`") }
571 joined.push_all(path);
580 /// A low-level OS in-memory pipe.
582 /// A file descriptor representing the reading end of the pipe. Data written
583 /// on the `out` file descriptor can be read from this file descriptor.
585 /// A file descriptor representing the write end of the pipe. Data written
586 /// to this file descriptor can be read from the `input` file descriptor.
590 /// Creates a new low-level OS in-memory pipe.
592 /// This function can fail to succeed if there are no more resources available
593 /// to allocate a pipe.
595 /// This function is also unsafe as there is no destructor associated with the
596 /// `Pipe` structure will return. If it is not arranged for the returned file
597 /// descriptors to be closed, the file descriptors will leak. For safe handling
598 /// of this scenario, use `std::io::PipeStream` instead.
599 pub unsafe fn pipe() -> IoResult<Pipe> {
603 unsafe fn _pipe() -> IoResult<Pipe> {
604 let mut fds = [0, ..2];
605 match libc::pipe(fds.as_mut_ptr()) {
606 0 => Ok(Pipe { reader: fds[0], writer: fds[1] }),
607 _ => Err(IoError::last_error()),
612 unsafe fn _pipe() -> IoResult<Pipe> {
613 // Windows pipes work subtly differently than unix pipes, and their
614 // inheritance has to be handled in a different way that I do not
615 // fully understand. Here we explicitly make the pipe non-inheritable,
616 // which means to pass it to a subprocess they need to be duplicated
617 // first, as in std::run.
618 let mut fds = [0, ..2];
619 match libc::pipe(fds.as_mut_ptr(), 1024 as ::libc::c_uint,
620 (libc::O_BINARY | libc::O_NOINHERIT) as c_int) {
622 assert!(fds[0] != -1 && fds[0] != 0);
623 assert!(fds[1] != -1 && fds[1] != 0);
624 Ok(Pipe { reader: fds[0], writer: fds[1] })
626 _ => Err(IoError::last_error()),
631 /// Returns the proper dll filename for the given basename of a file
633 #[cfg(not(target_os="ios"))]
634 pub fn dll_filename(base: &str) -> String {
635 format!("{}{}{}", consts::DLL_PREFIX, base, consts::DLL_SUFFIX)
638 /// Optionally returns the filesystem path to the current executable which is
639 /// running but with the executable name.
646 /// match os::self_exe_name() {
647 /// Some(exe_path) => println!("Path of this executable is: {}", exe_path.display()),
648 /// None => println!("Unable to get the path of this executable!")
651 pub fn self_exe_name() -> Option<Path> {
653 #[cfg(target_os = "freebsd")]
654 fn load_self() -> Option<Vec<u8>> {
656 use libc::funcs::bsd44::*;
657 use libc::consts::os::extra::*;
658 let mut mib = vec![CTL_KERN as c_int,
660 KERN_PROC_PATHNAME as c_int,
662 let mut sz: libc::size_t = 0;
663 let err = sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
664 ptr::mut_null(), &mut sz, ptr::mut_null(),
666 if err != 0 { return None; }
667 if sz == 0 { return None; }
668 let mut v: Vec<u8> = Vec::with_capacity(sz as uint);
669 let err = sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
670 v.as_mut_ptr() as *mut c_void, &mut sz,
671 ptr::mut_null(), 0u as libc::size_t);
672 if err != 0 { return None; }
673 if sz == 0 { return None; }
674 v.set_len(sz as uint - 1); // chop off trailing NUL
679 #[cfg(target_os = "linux")]
680 #[cfg(target_os = "android")]
681 fn load_self() -> Option<Vec<u8>> {
684 match io::fs::readlink(&Path::new("/proc/self/exe")) {
685 Ok(path) => Some(path.into_vec()),
690 #[cfg(target_os = "macos")]
691 #[cfg(target_os = "ios")]
692 fn load_self() -> Option<Vec<u8>> {
694 use libc::funcs::extra::_NSGetExecutablePath;
696 _NSGetExecutablePath(ptr::mut_null(), &mut sz);
697 if sz == 0 { return None; }
698 let mut v: Vec<u8> = Vec::with_capacity(sz as uint);
699 let err = _NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz);
700 if err != 0 { return None; }
701 v.set_len(sz as uint - 1); // chop off trailing NUL
707 fn load_self() -> Option<Vec<u8>> {
709 use os::win32::fill_utf16_buf_and_decode;
710 fill_utf16_buf_and_decode(|buf, sz| {
711 libc::GetModuleFileNameW(0u as libc::DWORD, buf, sz)
712 }).map(|s| s.into_string().into_bytes())
716 load_self().and_then(Path::new_opt)
719 /// Optionally returns the filesystem path to the current executable which is
722 /// Like self_exe_name() but without the binary's name.
729 /// match os::self_exe_path() {
730 /// Some(exe_path) => println!("Executable's Path is: {}", exe_path.display()),
731 /// None => println!("Impossible to fetch the path of this executable.")
734 pub fn self_exe_path() -> Option<Path> {
735 self_exe_name().map(|mut p| { p.pop(); p })
738 /// Optionally returns the path to the current user's home directory if known.
742 /// Returns the value of the 'HOME' environment variable if it is set
743 /// and not equal to the empty string.
747 /// Returns the value of the 'HOME' environment variable if it is
748 /// set and not equal to the empty string. Otherwise, returns the value of the
749 /// 'USERPROFILE' environment variable if it is set and not equal to the empty
757 /// match os::homedir() {
758 /// Some(ref p) => println!("{}", p.display()),
759 /// None => println!("Impossible to get your home dir!")
762 pub fn homedir() -> Option<Path> {
765 fn _homedir() -> Option<Path> {
771 fn _homedir() -> Option<Path> {
772 aux_homedir("HOME").or(aux_homedir("USERPROFILE"))
776 fn aux_homedir(home_name: &str) -> Option<Path> {
777 match getenv_as_bytes(home_name) {
779 if p.is_empty() { None } else { Path::new_opt(p) }
788 * Returns the path to a temporary directory.
790 * On Unix, returns the value of the 'TMPDIR' environment variable if it is
791 * set, otherwise for non-Android it returns '/tmp'. If Android, since there
792 * is no global temporary folder (it is usually allocated per-app), we return
795 * On Windows, returns the value of, in order, the 'TMP', 'TEMP',
796 * 'USERPROFILE' environment variable if any are set and not the empty
797 * string. Otherwise, tmpdir returns the path to the Windows directory.
799 pub fn tmpdir() -> Path {
802 fn getenv_nonempty(v: &str) -> Option<Path> {
815 fn lookup() -> Path {
816 let default = if cfg!(target_os = "android") {
817 Path::new("/data/local/tmp")
822 getenv_nonempty("TMPDIR").unwrap_or(default)
826 fn lookup() -> Path {
827 getenv_nonempty("TMP").or(
828 getenv_nonempty("TEMP").or(
829 getenv_nonempty("USERPROFILE").or(
830 getenv_nonempty("WINDIR")))).unwrap_or(Path::new("C:\\Windows"))
835 /// Convert a relative path to an absolute path
837 /// If the given path is relative, return it prepended with the current working
838 /// directory. If the given path is already an absolute path, return it
844 /// use std::path::Path;
846 /// // Assume we're in a path like /home/someuser
847 /// let rel_path = Path::new("..");
848 /// let abs_path = os::make_absolute(&rel_path);
849 /// println!("The absolute path is {}", abs_path.display());
850 /// // Prints "The absolute path is /home"
852 // NB: this is here rather than in path because it is a form of environment
853 // querying; what it does depends on the process working directory, not just
855 pub fn make_absolute(p: &Path) -> Path {
859 let mut ret = getcwd();
865 /// Changes the current working directory to the specified path, returning
866 /// whether the change was completed successfully or not.
871 /// use std::path::Path;
873 /// let root = Path::new("/");
874 /// assert!(os::change_dir(&root));
875 /// println!("Succesfully changed working directory to {}!", root.display());
877 pub fn change_dir(p: &Path) -> bool {
881 fn chdir(p: &Path) -> bool {
882 let p = match p.as_str() {
883 Some(s) => s.utf16_units().collect::<Vec<u16>>().append_one(0),
884 None => return false,
887 libc::SetCurrentDirectoryW(p.as_ptr()) != (0 as libc::BOOL)
892 fn chdir(p: &Path) -> bool {
895 libc::chdir(buf) == (0 as c_int)
902 /// Returns the platform-specific value of errno
903 pub fn errno() -> int {
904 #[cfg(target_os = "macos")]
905 #[cfg(target_os = "ios")]
906 #[cfg(target_os = "freebsd")]
907 fn errno_location() -> *const c_int {
909 fn __error() -> *const c_int;
916 #[cfg(target_os = "linux")]
917 #[cfg(target_os = "android")]
918 fn errno_location() -> *const c_int {
920 fn __errno_location() -> *const c_int;
928 (*errno_location()) as int
933 /// Returns the platform-specific value of errno
934 pub fn errno() -> uint {
935 use libc::types::os::arch::extra::DWORD;
937 #[link_name = "kernel32"]
939 fn GetLastError() -> DWORD;
943 GetLastError() as uint
947 /// Return the string corresponding to an `errno()` value of `errnum`.
952 /// // Same as println!("{}", last_os_error());
953 /// println!("{}", os::error_string(os::errno() as uint));
955 pub fn error_string(errnum: uint) -> String {
956 return strerror(errnum);
959 fn strerror(errnum: uint) -> String {
960 #[cfg(target_os = "macos")]
961 #[cfg(target_os = "ios")]
962 #[cfg(target_os = "android")]
963 #[cfg(target_os = "freebsd")]
964 fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: libc::size_t)
967 fn strerror_r(errnum: c_int, buf: *mut c_char,
968 buflen: libc::size_t) -> c_int;
971 strerror_r(errnum, buf, buflen)
975 // GNU libc provides a non-compliant version of strerror_r by default
976 // and requires macros to instead use the POSIX compliant variant.
977 // So we just use __xpg_strerror_r which is always POSIX compliant
978 #[cfg(target_os = "linux")]
979 fn strerror_r(errnum: c_int, buf: *mut c_char,
980 buflen: libc::size_t) -> c_int {
982 fn __xpg_strerror_r(errnum: c_int,
984 buflen: libc::size_t)
988 __xpg_strerror_r(errnum, buf, buflen)
992 let mut buf = [0 as c_char, ..TMPBUF_SZ];
994 let p = buf.as_mut_ptr();
996 if strerror_r(errnum as c_int, p, buf.len() as libc::size_t) < 0 {
997 fail!("strerror_r failure");
1000 ::string::raw::from_buf(p as *const u8)
1005 fn strerror(errnum: uint) -> String {
1006 use libc::types::os::arch::extra::DWORD;
1007 use libc::types::os::arch::extra::LPWSTR;
1008 use libc::types::os::arch::extra::LPVOID;
1009 use libc::types::os::arch::extra::WCHAR;
1011 #[link_name = "kernel32"]
1013 fn FormatMessageW(flags: DWORD,
1019 args: *const c_void)
1023 static FORMAT_MESSAGE_FROM_SYSTEM: DWORD = 0x00001000;
1024 static FORMAT_MESSAGE_IGNORE_INSERTS: DWORD = 0x00000200;
1026 // This value is calculated from the macro
1027 // MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT)
1028 let langId = 0x0800 as DWORD;
1030 let mut buf = [0 as WCHAR, ..TMPBUF_SZ];
1033 let res = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
1034 FORMAT_MESSAGE_IGNORE_INSERTS,
1042 // Sometimes FormatMessageW can fail e.g. system doesn't like langId,
1043 let fm_err = errno();
1044 return format!("OS Error {} (FormatMessageW() returned error {})", errnum, fm_err);
1047 let msg = String::from_utf16(::str::truncate_utf16_at_nul(buf));
1049 Some(msg) => format!("OS Error {}: {}", errnum, msg),
1050 None => format!("OS Error {} (FormatMessageW() returned invalid UTF-16)", errnum),
1056 /// Get a string representing the platform-dependent last error
1057 pub fn last_os_error() -> String {
1058 error_string(errno() as uint)
1061 static mut EXIT_STATUS: AtomicInt = INIT_ATOMIC_INT;
1064 * Sets the process exit code
1066 * Sets the exit code returned by the process if all supervised tasks
1067 * terminate successfully (without failing). If the current root task fails
1068 * and is supervised by the scheduler then any user-specified exit status is
1069 * ignored and the process exits with the default failure status.
1071 * Note that this is not synchronized against modifications of other threads.
1073 pub fn set_exit_status(code: int) {
1074 unsafe { EXIT_STATUS.store(code, SeqCst) }
1077 /// Fetches the process's current exit code. This defaults to 0 and can change
1078 /// by calling `set_exit_status`.
1079 pub fn get_exit_status() -> int {
1080 unsafe { EXIT_STATUS.load(SeqCst) }
1083 #[cfg(target_os = "macos")]
1084 unsafe fn load_argc_and_argv(argc: int,
1085 argv: *const *const c_char) -> Vec<Vec<u8>> {
1088 Vec::from_fn(argc as uint, |i| {
1089 Vec::from_slice(CString::new(*argv.offset(i as int),
1090 false).as_bytes_no_nul())
1095 * Returns the command line arguments
1097 * Returns a list of the command line arguments.
1099 #[cfg(target_os = "macos")]
1100 fn real_args_as_bytes() -> Vec<Vec<u8>> {
1102 let (argc, argv) = (*_NSGetArgc() as int,
1103 *_NSGetArgv() as *const *const c_char);
1104 load_argc_and_argv(argc, argv)
1108 // As _NSGetArgc and _NSGetArgv aren't mentioned in iOS docs
1109 // and use underscores in their names - they're most probably
1110 // are considered private and therefore should be avoided
1111 // Here is another way to get arguments using Objective C
1114 // In general it looks like:
1116 // let args = [[NSProcessInfo processInfo] arguments]
1117 // for i in range(0, [args count])
1118 // res.push([args objectAtIndex:i])
1120 #[cfg(target_os = "ios")]
1121 fn real_args_as_bytes() -> Vec<Vec<u8>> {
1126 #[link(name = "objc")]
1128 fn sel_registerName(name: *const libc::c_uchar) -> Sel;
1129 fn objc_msgSend(obj: NsId, sel: Sel, ...) -> NsId;
1130 fn objc_getClass(class_name: *const libc::c_uchar) -> NsId;
1133 #[link(name = "Foundation", kind = "framework")]
1136 type Sel = *const libc::c_void;
1137 type NsId = *const libc::c_void;
1139 let mut res = Vec::new();
1142 let processInfoSel = sel_registerName("processInfo\0".as_ptr());
1143 let argumentsSel = sel_registerName("arguments\0".as_ptr());
1144 let utf8Sel = sel_registerName("UTF8String\0".as_ptr());
1145 let countSel = sel_registerName("count\0".as_ptr());
1146 let objectAtSel = sel_registerName("objectAtIndex:\0".as_ptr());
1148 let klass = objc_getClass("NSProcessInfo\0".as_ptr());
1149 let info = objc_msgSend(klass, processInfoSel);
1150 let args = objc_msgSend(info, argumentsSel);
1152 let cnt: int = mem::transmute(objc_msgSend(args, countSel));
1153 for i in range(0, cnt) {
1154 let tmp = objc_msgSend(args, objectAtSel, i);
1155 let utf_c_str: *const libc::c_char =
1156 mem::transmute(objc_msgSend(tmp, utf8Sel));
1157 let s = CString::new(utf_c_str, false);
1158 if s.is_not_null() {
1159 res.push(Vec::from_slice(s.as_bytes_no_nul()))
1167 #[cfg(target_os = "linux")]
1168 #[cfg(target_os = "android")]
1169 #[cfg(target_os = "freebsd")]
1170 fn real_args_as_bytes() -> Vec<Vec<u8>> {
1173 match rt::args::clone() {
1175 None => fail!("process arguments not initialized")
1179 #[cfg(not(windows))]
1180 fn real_args() -> Vec<String> {
1181 real_args_as_bytes().move_iter()
1183 String::from_utf8_lossy(v.as_slice()).into_string()
1188 fn real_args() -> Vec<String> {
1191 let mut nArgs: c_int = 0;
1192 let lpArgCount: *mut c_int = &mut nArgs;
1193 let lpCmdLine = unsafe { GetCommandLineW() };
1194 let szArgList = unsafe { CommandLineToArgvW(lpCmdLine, lpArgCount) };
1196 let args = Vec::from_fn(nArgs as uint, |i| unsafe {
1197 // Determine the length of this argument.
1198 let ptr = *szArgList.offset(i as int);
1200 while *ptr.offset(len as int) != 0 { len += 1; }
1202 // Push it onto the list.
1203 let opt_s = slice::raw::buf_as_slice(ptr as *const _, len, |buf| {
1204 String::from_utf16(::str::truncate_utf16_at_nul(buf))
1206 opt_s.expect("CommandLineToArgvW returned invalid UTF-16")
1210 LocalFree(szArgList as *mut c_void);
1217 fn real_args_as_bytes() -> Vec<Vec<u8>> {
1218 real_args().move_iter().map(|s| s.into_bytes()).collect()
1221 type LPCWSTR = *const u16;
1224 #[link_name="kernel32"]
1226 fn GetCommandLineW() -> LPCWSTR;
1227 fn LocalFree(ptr: *mut c_void);
1231 #[link_name="shell32"]
1233 fn CommandLineToArgvW(lpCmdLine: LPCWSTR,
1234 pNumArgs: *mut c_int) -> *mut *mut u16;
1237 /// Returns the arguments which this program was started with (normally passed
1238 /// via the command line).
1240 /// The arguments are interpreted as utf-8, with invalid bytes replaced with \uFFFD.
1241 /// See `String::from_utf8_lossy` for details.
1247 /// // Prints each argument on a separate line
1248 /// for argument in os::args().iter() {
1249 /// println!("{}", argument);
1252 pub fn args() -> Vec<String> {
1256 /// Returns the arguments which this program was started with (normally passed
1257 /// via the command line) as byte vectors.
1258 pub fn args_as_bytes() -> Vec<Vec<u8>> {
1259 real_args_as_bytes()
1262 #[cfg(target_os = "macos")]
1264 // These functions are in crt_externs.h.
1265 pub fn _NSGetArgc() -> *mut c_int;
1266 pub fn _NSGetArgv() -> *mut *mut *mut c_char;
1269 // Round up `from` to be divisible by `to`
1270 fn round_up(from: uint, to: uint) -> uint {
1271 let r = if from % to == 0 {
1274 from + to - (from % to)
1283 /// Returns the page size of the current architecture in bytes.
1285 pub fn page_size() -> uint {
1287 libc::sysconf(libc::_SC_PAGESIZE) as uint
1291 /// Returns the page size of the current architecture in bytes.
1293 pub fn page_size() -> uint {
1296 let mut info = mem::zeroed();
1297 libc::GetSystemInfo(&mut info);
1299 return info.dwPageSize as uint;
1303 /// A memory mapped file or chunk of memory. This is a very system-specific
1304 /// interface to the OS's memory mapping facilities (`mmap` on POSIX,
1305 /// `VirtualAlloc`/`CreateFileMapping` on win32). It makes no attempt at
1306 /// abstracting platform differences, besides in error values returned. Consider
1307 /// yourself warned.
1309 /// The memory map is released (unmapped) when the destructor is run, so don't
1310 /// let it leave scope by accident if you want it to stick around.
1311 pub struct MemoryMap {
1314 kind: MemoryMapKind,
1317 /// Type of memory map
1318 pub enum MemoryMapKind {
1319 /// Virtual memory map. Usually used to change the permissions of a given
1320 /// chunk of memory. Corresponds to `VirtualAlloc` on Windows.
1322 /// Virtual memory map. Usually used to change the permissions of a given
1323 /// chunk of memory, or for allocation. Corresponds to `VirtualAlloc` on
1328 /// Options the memory map is created with
1329 pub enum MapOption {
1330 /// The memory should be readable
1332 /// The memory should be writable
1334 /// The memory should be executable
1336 /// Create a map for a specific address range. Corresponds to `MAP_FIXED` on
1339 /// Create a memory mapping for a file with a given fd.
1341 /// When using `MapFd`, the start of the map is `uint` bytes from the start
1344 /// On POSIX, this can be used to specify the default flags passed to
1345 /// `mmap`. By default it uses `MAP_PRIVATE` and, if not using `MapFd`,
1346 /// `MAP_ANON`. This will override both of those. This is platform-specific
1347 /// (the exact values used) and ignored on Windows.
1348 MapNonStandardFlags(c_int),
1351 /// Possible errors when creating a map.
1353 /// ## The following are POSIX-specific
1355 /// fd was not open for reading or, if using `MapWritable`, was not open for
1358 /// fd was not valid
1360 /// Either the address given by `MapAddr` or offset given by `MapOffset` was
1361 /// not a multiple of `MemoryMap::granularity` (unaligned to page size).
1363 /// With `MapFd`, the fd does not support mapping.
1365 /// If using `MapAddr`, the address + `min_len` was outside of the process's
1366 /// address space. If using `MapFd`, the target of the fd didn't have enough
1367 /// resources to fulfill the request.
1369 /// A zero-length map was requested. This is invalid according to
1370 /// [POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/functions/mmap.html).
1371 /// Not all platforms obey this, but this wrapper does.
1373 /// Unrecognized error. The inner value is the unrecognized errno.
1375 /// ## The following are win32-specific
1377 /// Unsupported combination of protection flags
1378 /// (`MapReadable`/`MapWritable`/`MapExecutable`).
1380 /// When using `MapFd`, `MapOffset` was given (Windows does not support this
1383 /// When using `MapFd`, there was already a mapping to the file.
1385 /// Unrecognized error from `VirtualAlloc`. The inner value is the return
1386 /// value of GetLastError.
1387 ErrVirtualAlloc(uint),
1388 /// Unrecognized error from `CreateFileMapping`. The inner value is the
1389 /// return value of `GetLastError`.
1390 ErrCreateFileMappingW(uint),
1391 /// Unrecognized error from `MapViewOfFile`. The inner value is the return
1392 /// value of `GetLastError`.
1393 ErrMapViewOfFile(uint)
1396 impl fmt::Show for MapError {
1397 fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result {
1398 let str = match *self {
1399 ErrFdNotAvail => "fd not available for reading or writing",
1400 ErrInvalidFd => "Invalid fd",
1402 "Unaligned address, invalid flags, negative length or \
1405 ErrNoMapSupport=> "File doesn't support mapping",
1406 ErrNoMem => "Invalid address, or not enough available memory",
1407 ErrUnsupProt => "Protection mode unsupported",
1408 ErrUnsupOffset => "Offset in virtual memory mode is unsupported",
1409 ErrAlreadyExists => "File mapping for specified file already exists",
1410 ErrZeroLength => "Zero-length mapping not allowed",
1411 ErrUnknown(code) => {
1412 return write!(out, "Unknown error = {}", code)
1414 ErrVirtualAlloc(code) => {
1415 return write!(out, "VirtualAlloc failure = {}", code)
1417 ErrCreateFileMappingW(code) => {
1418 return write!(out, "CreateFileMappingW failure = {}", code)
1420 ErrMapViewOfFile(code) => {
1421 return write!(out, "MapViewOfFile failure = {}", code)
1424 write!(out, "{}", str)
1430 /// Create a new mapping with the given `options`, at least `min_len` bytes
1431 /// long. `min_len` must be greater than zero; see the note on
1432 /// `ErrZeroLength`.
1433 pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
1437 return Err(ErrZeroLength)
1439 let mut addr: *const u8 = ptr::null();
1441 let mut flags = libc::MAP_PRIVATE;
1444 let mut custom_flags = false;
1445 let len = round_up(min_len, page_size());
1447 for &o in options.iter() {
1449 MapReadable => { prot |= libc::PROT_READ; },
1450 MapWritable => { prot |= libc::PROT_WRITE; },
1451 MapExecutable => { prot |= libc::PROT_EXEC; },
1453 flags |= libc::MAP_FIXED;
1457 flags |= libc::MAP_FILE;
1460 MapOffset(offset_) => { offset = offset_ as off_t; },
1461 MapNonStandardFlags(f) => { custom_flags = true; flags = f },
1464 if fd == -1 && !custom_flags { flags |= libc::MAP_ANON; }
1467 libc::mmap(addr as *mut c_void, len as libc::size_t, prot, flags,
1470 if r == libc::MAP_FAILED {
1471 Err(match errno() as c_int {
1472 libc::EACCES => ErrFdNotAvail,
1473 libc::EBADF => ErrInvalidFd,
1474 libc::EINVAL => ErrUnaligned,
1475 libc::ENODEV => ErrNoMapSupport,
1476 libc::ENOMEM => ErrNoMem,
1477 code => ErrUnknown(code as int)
1486 MapFile(ptr::null())
1492 /// Granularity that the offset or address must be for `MapOffset` and
1493 /// `MapAddr` respectively.
1494 pub fn granularity() -> uint {
1500 impl Drop for MemoryMap {
1501 /// Unmap the mapping. Fails the task if `munmap` fails.
1502 fn drop(&mut self) {
1503 if self.len == 0 { /* workaround for dummy_stack */ return; }
1506 // `munmap` only fails due to logic errors
1507 libc::munmap(self.data as *mut c_void, self.len as libc::size_t);
1514 /// Create a new mapping with the given `options`, at least `min_len` bytes long.
1515 pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
1516 use libc::types::os::arch::extra::{LPVOID, DWORD, SIZE_T, HANDLE};
1518 let mut lpAddress: LPVOID = ptr::mut_null();
1519 let mut readable = false;
1520 let mut writable = false;
1521 let mut executable = false;
1522 let mut fd: c_int = -1;
1523 let mut offset: uint = 0;
1524 let len = round_up(min_len, page_size());
1526 for &o in options.iter() {
1528 MapReadable => { readable = true; },
1529 MapWritable => { writable = true; },
1530 MapExecutable => { executable = true; }
1531 MapAddr(addr_) => { lpAddress = addr_ as LPVOID; },
1532 MapFd(fd_) => { fd = fd_; },
1533 MapOffset(offset_) => { offset = offset_; },
1534 MapNonStandardFlags(..) => {}
1538 let flProtect = match (executable, readable, writable) {
1539 (false, false, false) if fd == -1 => libc::PAGE_NOACCESS,
1540 (false, true, false) => libc::PAGE_READONLY,
1541 (false, true, true) => libc::PAGE_READWRITE,
1542 (true, false, false) if fd == -1 => libc::PAGE_EXECUTE,
1543 (true, true, false) => libc::PAGE_EXECUTE_READ,
1544 (true, true, true) => libc::PAGE_EXECUTE_READWRITE,
1545 _ => return Err(ErrUnsupProt)
1550 return Err(ErrUnsupOffset);
1553 libc::VirtualAlloc(lpAddress,
1555 libc::MEM_COMMIT | libc::MEM_RESERVE,
1559 0 => Err(ErrVirtualAlloc(errno())),
1567 let dwDesiredAccess = match (executable, readable, writable) {
1568 (false, true, false) => libc::FILE_MAP_READ,
1569 (false, true, true) => libc::FILE_MAP_WRITE,
1570 (true, true, false) => libc::FILE_MAP_READ | libc::FILE_MAP_EXECUTE,
1571 (true, true, true) => libc::FILE_MAP_WRITE | libc::FILE_MAP_EXECUTE,
1572 _ => return Err(ErrUnsupProt) // Actually, because of the check above,
1573 // we should never get here.
1576 let hFile = libc::get_osfhandle(fd) as HANDLE;
1577 let mapping = libc::CreateFileMappingW(hFile,
1583 if mapping == ptr::mut_null() {
1584 return Err(ErrCreateFileMappingW(errno()));
1586 if errno() as c_int == libc::ERROR_ALREADY_EXISTS {
1587 return Err(ErrAlreadyExists);
1589 let r = libc::MapViewOfFile(mapping,
1591 ((len as u64) >> 32) as DWORD,
1592 (offset & 0xffff_ffff) as DWORD,
1595 0 => Err(ErrMapViewOfFile(errno())),
1599 kind: MapFile(mapping as *const u8)
1606 /// Granularity of MapAddr() and MapOffset() parameter values.
1607 /// This may be greater than the value returned by page_size().
1608 pub fn granularity() -> uint {
1611 let mut info = mem::zeroed();
1612 libc::GetSystemInfo(&mut info);
1614 return info.dwAllocationGranularity as uint;
1620 impl Drop for MemoryMap {
1621 /// Unmap the mapping. Fails the task if any of `VirtualFree`,
1622 /// `UnmapViewOfFile`, or `CloseHandle` fail.
1623 fn drop(&mut self) {
1624 use libc::types::os::arch::extra::{LPCVOID, HANDLE};
1625 use libc::consts::os::extra::FALSE;
1626 if self.len == 0 { return }
1631 if libc::VirtualFree(self.data as *mut c_void, 0,
1632 libc::MEM_RELEASE) == 0 {
1633 println!("VirtualFree failed: {}", errno());
1636 MapFile(mapping) => {
1637 if libc::UnmapViewOfFile(self.data as LPCVOID) == FALSE {
1638 println!("UnmapViewOfFile failed: {}", errno());
1640 if libc::CloseHandle(mapping as HANDLE) == FALSE {
1641 println!("CloseHandle failed: {}", errno());
1650 /// Returns the pointer to the memory created or modified by this map.
1651 pub fn data(&self) -> *mut u8 { self.data }
1652 /// Returns the number of bytes this map applies to.
1653 pub fn len(&self) -> uint { self.len }
1654 /// Returns the type of mapping this represents.
1655 pub fn kind(&self) -> MemoryMapKind { self.kind }
1658 #[cfg(target_os = "linux")]
1660 pub use os::arch_consts::ARCH;
1662 pub static FAMILY: &'static str = "unix";
1664 /// A string describing the specific operating system in use: in this
1666 pub static SYSNAME: &'static str = "linux";
1668 /// Specifies the filename prefix used for shared libraries on this
1669 /// platform: in this case, `lib`.
1670 pub static DLL_PREFIX: &'static str = "lib";
1672 /// Specifies the filename suffix used for shared libraries on this
1673 /// platform: in this case, `.so`.
1674 pub static DLL_SUFFIX: &'static str = ".so";
1676 /// Specifies the file extension used for shared libraries on this
1677 /// platform that goes after the dot: in this case, `so`.
1678 pub static DLL_EXTENSION: &'static str = "so";
1680 /// Specifies the filename suffix used for executable binaries on this
1681 /// platform: in this case, the empty string.
1682 pub static EXE_SUFFIX: &'static str = "";
1684 /// Specifies the file extension, if any, used for executable binaries
1685 /// on this platform: in this case, the empty string.
1686 pub static EXE_EXTENSION: &'static str = "";
1689 #[cfg(target_os = "macos")]
1691 pub use os::arch_consts::ARCH;
1693 pub static FAMILY: &'static str = "unix";
1695 /// A string describing the specific operating system in use: in this
1697 pub static SYSNAME: &'static str = "macos";
1699 /// Specifies the filename prefix used for shared libraries on this
1700 /// platform: in this case, `lib`.
1701 pub static DLL_PREFIX: &'static str = "lib";
1703 /// Specifies the filename suffix used for shared libraries on this
1704 /// platform: in this case, `.dylib`.
1705 pub static DLL_SUFFIX: &'static str = ".dylib";
1707 /// Specifies the file extension used for shared libraries on this
1708 /// platform that goes after the dot: in this case, `dylib`.
1709 pub static DLL_EXTENSION: &'static str = "dylib";
1711 /// Specifies the filename suffix used for executable binaries on this
1712 /// platform: in this case, the empty string.
1713 pub static EXE_SUFFIX: &'static str = "";
1715 /// Specifies the file extension, if any, used for executable binaries
1716 /// on this platform: in this case, the empty string.
1717 pub static EXE_EXTENSION: &'static str = "";
1720 #[cfg(target_os = "ios")]
1722 pub use os::arch_consts::ARCH;
1724 pub static FAMILY: &'static str = "unix";
1726 /// A string describing the specific operating system in use: in this
1728 pub static SYSNAME: &'static str = "ios";
1730 /// Specifies the filename suffix used for executable binaries on this
1731 /// platform: in this case, the empty string.
1732 pub static EXE_SUFFIX: &'static str = "";
1734 /// Specifies the file extension, if any, used for executable binaries
1735 /// on this platform: in this case, the empty string.
1736 pub static EXE_EXTENSION: &'static str = "";
1739 #[cfg(target_os = "freebsd")]
1741 pub use os::arch_consts::ARCH;
1743 pub static FAMILY: &'static str = "unix";
1745 /// A string describing the specific operating system in use: in this
1746 /// case, `freebsd`.
1747 pub static SYSNAME: &'static str = "freebsd";
1749 /// Specifies the filename prefix used for shared libraries on this
1750 /// platform: in this case, `lib`.
1751 pub static DLL_PREFIX: &'static str = "lib";
1753 /// Specifies the filename suffix used for shared libraries on this
1754 /// platform: in this case, `.so`.
1755 pub static DLL_SUFFIX: &'static str = ".so";
1757 /// Specifies the file extension used for shared libraries on this
1758 /// platform that goes after the dot: in this case, `so`.
1759 pub static DLL_EXTENSION: &'static str = "so";
1761 /// Specifies the filename suffix used for executable binaries on this
1762 /// platform: in this case, the empty string.
1763 pub static EXE_SUFFIX: &'static str = "";
1765 /// Specifies the file extension, if any, used for executable binaries
1766 /// on this platform: in this case, the empty string.
1767 pub static EXE_EXTENSION: &'static str = "";
1770 #[cfg(target_os = "android")]
1772 pub use os::arch_consts::ARCH;
1774 pub static FAMILY: &'static str = "unix";
1776 /// A string describing the specific operating system in use: in this
1777 /// case, `android`.
1778 pub static SYSNAME: &'static str = "android";
1780 /// Specifies the filename prefix used for shared libraries on this
1781 /// platform: in this case, `lib`.
1782 pub static DLL_PREFIX: &'static str = "lib";
1784 /// Specifies the filename suffix used for shared libraries on this
1785 /// platform: in this case, `.so`.
1786 pub static DLL_SUFFIX: &'static str = ".so";
1788 /// Specifies the file extension used for shared libraries on this
1789 /// platform that goes after the dot: in this case, `so`.
1790 pub static DLL_EXTENSION: &'static str = "so";
1792 /// Specifies the filename suffix used for executable binaries on this
1793 /// platform: in this case, the empty string.
1794 pub static EXE_SUFFIX: &'static str = "";
1796 /// Specifies the file extension, if any, used for executable binaries
1797 /// on this platform: in this case, the empty string.
1798 pub static EXE_EXTENSION: &'static str = "";
1801 #[cfg(target_os = "win32")]
1803 pub use os::arch_consts::ARCH;
1805 pub static FAMILY: &'static str = "windows";
1807 /// A string describing the specific operating system in use: in this
1809 pub static SYSNAME: &'static str = "win32";
1811 /// Specifies the filename prefix used for shared libraries on this
1812 /// platform: in this case, the empty string.
1813 pub static DLL_PREFIX: &'static str = "";
1815 /// Specifies the filename suffix used for shared libraries on this
1816 /// platform: in this case, `.dll`.
1817 pub static DLL_SUFFIX: &'static str = ".dll";
1819 /// Specifies the file extension used for shared libraries on this
1820 /// platform that goes after the dot: in this case, `dll`.
1821 pub static DLL_EXTENSION: &'static str = "dll";
1823 /// Specifies the filename suffix used for executable binaries on this
1824 /// platform: in this case, `.exe`.
1825 pub static EXE_SUFFIX: &'static str = ".exe";
1827 /// Specifies the file extension, if any, used for executable binaries
1828 /// on this platform: in this case, `exe`.
1829 pub static EXE_EXTENSION: &'static str = "exe";
1832 #[cfg(target_arch = "x86")]
1834 pub static ARCH: &'static str = "x86";
1837 #[cfg(target_arch = "x86_64")]
1839 pub static ARCH: &'static str = "x86_64";
1842 #[cfg(target_arch = "arm")]
1844 pub static ARCH: &'static str = "arm";
1847 #[cfg(target_arch = "mips")]
1849 pub static ARCH: &'static str = "mips";
1852 #[cfg(target_arch = "mipsel")]
1854 pub static ARCH: &'static str = "mipsel";
1862 use os::{env, getcwd, getenv, make_absolute};
1863 use os::{split_paths, join_paths, setenv, unsetenv};
1869 pub fn last_os_error() {
1870 debug!("{}", os::last_os_error());
1873 fn make_rand_name() -> String {
1874 let mut rng = rand::task_rng();
1875 let n = format!("TEST{}", rng.gen_ascii_chars().take(10u)
1876 .collect::<String>());
1877 assert!(getenv(n.as_slice()).is_none());
1882 fn test_num_cpus() {
1883 assert!(os::num_cpus() > 0);
1888 let n = make_rand_name();
1889 setenv(n.as_slice(), "VALUE");
1890 assert_eq!(getenv(n.as_slice()), option::Some("VALUE".to_string()));
1894 fn test_unsetenv() {
1895 let n = make_rand_name();
1896 setenv(n.as_slice(), "VALUE");
1897 unsetenv(n.as_slice());
1898 assert_eq!(getenv(n.as_slice()), option::None);
1903 fn test_setenv_overwrite() {
1904 let n = make_rand_name();
1905 setenv(n.as_slice(), "1");
1906 setenv(n.as_slice(), "2");
1907 assert_eq!(getenv(n.as_slice()), option::Some("2".to_string()));
1908 setenv(n.as_slice(), "");
1909 assert_eq!(getenv(n.as_slice()), option::Some("".to_string()));
1912 // Windows GetEnvironmentVariable requires some extra work to make sure
1913 // the buffer the variable is copied into is the right size
1916 fn test_getenv_big() {
1917 let mut s = "".to_string();
1920 s.push_str("aaaaaaaaaa");
1923 let n = make_rand_name();
1924 setenv(n.as_slice(), s.as_slice());
1925 debug!("{}", s.clone());
1926 assert_eq!(getenv(n.as_slice()), option::Some(s));
1930 fn test_self_exe_name() {
1931 let path = os::self_exe_name();
1932 assert!(path.is_some());
1933 let path = path.unwrap();
1934 debug!("{:?}", path.clone());
1936 // Hard to test this function
1937 assert!(path.is_absolute());
1941 fn test_self_exe_path() {
1942 let path = os::self_exe_path();
1943 assert!(path.is_some());
1944 let path = path.unwrap();
1945 debug!("{:?}", path.clone());
1947 // Hard to test this function
1948 assert!(path.is_absolute());
1953 fn test_env_getenv() {
1955 assert!(e.len() > 0u);
1957 let (n, v) = (*p).clone();
1958 debug!("{:?}", n.clone());
1959 let v2 = getenv(n.as_slice());
1960 // MingW seems to set some funky environment variables like
1961 // "=C:=C:\MinGW\msys\1.0\bin" and "!::=::\" that are returned
1962 // from env() but not visible from getenv().
1963 assert!(v2.is_none() || v2 == option::Some(v));
1968 fn test_env_set_get_huge() {
1969 let n = make_rand_name();
1970 let s = "x".repeat(10000).to_string();
1971 setenv(n.as_slice(), s.as_slice());
1972 assert_eq!(getenv(n.as_slice()), Some(s));
1973 unsetenv(n.as_slice());
1974 assert_eq!(getenv(n.as_slice()), None);
1978 fn test_env_setenv() {
1979 let n = make_rand_name();
1982 setenv(n.as_slice(), "VALUE");
1983 assert!(!e.contains(&(n.clone(), "VALUE".to_string())));
1986 assert!(e.contains(&(n, "VALUE".to_string())));
1991 assert!((!Path::new("test-path").is_absolute()));
1994 debug!("Current working directory: {}", cwd.display());
1996 debug!("{:?}", make_absolute(&Path::new("test-path")));
1997 debug!("{:?}", make_absolute(&Path::new("/usr/bin")));
2003 let oldhome = getenv("HOME");
2005 setenv("HOME", "/home/MountainView");
2006 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
2009 assert!(os::homedir().is_none());
2011 for s in oldhome.iter() {
2012 setenv("HOME", s.as_slice());
2020 let oldhome = getenv("HOME");
2021 let olduserprofile = getenv("USERPROFILE");
2024 setenv("USERPROFILE", "");
2026 assert!(os::homedir().is_none());
2028 setenv("HOME", "/home/MountainView");
2029 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
2033 setenv("USERPROFILE", "/home/MountainView");
2034 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
2036 setenv("HOME", "/home/MountainView");
2037 setenv("USERPROFILE", "/home/PaloAlto");
2038 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
2040 for s in oldhome.iter() {
2041 setenv("HOME", s.as_slice());
2043 for s in olduserprofile.iter() {
2044 setenv("USERPROFILE", s.as_slice());
2049 fn memory_map_rw() {
2050 use result::{Ok, Err};
2052 let chunk = match os::MemoryMap::new(16, [
2057 Err(msg) => fail!("{}", msg)
2059 assert!(chunk.len >= 16);
2063 assert!(*chunk.data == 0xBE);
2068 fn memory_map_file() {
2069 use result::{Ok, Err};
2075 fn lseek_(fd: c_int, size: uint) {
2077 assert!(lseek(fd, size as off_t, SEEK_SET) == size as off_t);
2081 fn lseek_(fd: c_int, size: uint) {
2083 assert!(lseek(fd, size as c_long, SEEK_SET) == size as c_long);
2087 let mut path = tmpdir();
2088 path.push("mmap_file.tmp");
2089 let size = MemoryMap::granularity() * 2;
2092 let fd = path.with_c_str(|path| {
2093 open(path, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR)
2096 "x".with_c_str(|x| assert!(write(fd, x as *const c_void, 1) == 1));
2099 let chunk = match MemoryMap::new(size / 2, [
2106 Err(msg) => fail!("{}", msg)
2108 assert!(chunk.len > 0);
2112 assert!(*chunk.data == 0xbe);
2117 fs::unlink(&path).unwrap();
2122 fn split_paths_windows() {
2123 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
2124 split_paths(unparsed) ==
2125 parsed.iter().map(|s| Path::new(*s)).collect()
2128 assert!(check_parse("", [""]));
2129 assert!(check_parse(r#""""#, [""]));
2130 assert!(check_parse(";;", ["", "", ""]));
2131 assert!(check_parse(r"c:\", [r"c:\"]));
2132 assert!(check_parse(r"c:\;", [r"c:\", ""]));
2133 assert!(check_parse(r"c:\;c:\Program Files\",
2134 [r"c:\", r"c:\Program Files\"]));
2135 assert!(check_parse(r#"c:\;c:\"foo"\"#, [r"c:\", r"c:\foo\"]));
2136 assert!(check_parse(r#"c:\;c:\"foo;bar"\;c:\baz"#,
2137 [r"c:\", r"c:\foo;bar\", r"c:\baz"]));
2142 fn split_paths_unix() {
2143 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
2144 split_paths(unparsed) ==
2145 parsed.iter().map(|s| Path::new(*s)).collect()
2148 assert!(check_parse("", [""]));
2149 assert!(check_parse("::", ["", "", ""]));
2150 assert!(check_parse("/", ["/"]));
2151 assert!(check_parse("/:", ["/", ""]));
2152 assert!(check_parse("/:/usr/local", ["/", "/usr/local"]));
2157 fn join_paths_unix() {
2158 fn test_eq(input: &[&str], output: &str) -> bool {
2159 join_paths(input).unwrap().as_slice() == output.as_bytes()
2162 assert!(test_eq([], ""));
2163 assert!(test_eq(["/bin", "/usr/bin", "/usr/local/bin"],
2164 "/bin:/usr/bin:/usr/local/bin"));
2165 assert!(test_eq(["", "/bin", "", "", "/usr/bin", ""],
2166 ":/bin:::/usr/bin:"));
2167 assert!(join_paths(["/te:st"]).is_err());
2172 fn join_paths_windows() {
2173 fn test_eq(input: &[&str], output: &str) -> bool {
2174 join_paths(input).unwrap().as_slice() == output.as_bytes()
2177 assert!(test_eq([], ""));
2178 assert!(test_eq([r"c:\windows", r"c:\"],
2179 r"c:\windows;c:\"));
2180 assert!(test_eq(["", r"c:\windows", "", "", r"c:\", ""],
2181 r";c:\windows;;;c:\;"));
2182 assert!(test_eq([r"c:\te;st", r"c:\"],
2183 r#""c:\te;st";c:\"#));
2184 assert!(join_paths([r#"c:\te"st"#]).is_err());
2187 // More recursive_mkdir tests are in extra::tempfile