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.
11 //! Higher-level interfaces to libc::* functions and operating system services.
13 //! In general these take and return rust types, use rust idioms (enums, closures, vectors) rather
14 //! than C idioms, and do more extensive safety checks.
16 //! This module is not meant to only contain 1:1 mappings to libc entries; any os-interface code
17 //! that is reasonably useful and broadly applicable can go here. Including utility routines that
18 //! merely build on other os code.
20 //! We assume the general case is that users do not care, and do not want to be made to care, which
21 //! operating system they are on. While they may want to special case various special cases -- and
22 //! so we will not _hide_ the facts of which OS the user is on -- they should be given the
23 //! opportunity to write OS-ignorant code by default.
27 #![allow(missing_docs)]
28 #![allow(non_snake_case)]
30 pub use self::MemoryMapKind::*;
31 pub use self::MapOption::*;
32 pub use self::MapError::*;
35 use error::{FromError, Error};
37 use io::{IoResult, IoError};
38 use iter::{Iterator, IteratorExt};
40 use libc::{c_void, c_int};
45 use option::Option::{Some, None};
47 use path::{Path, GenericPath, BytesContainer};
49 use sys::os as os_imp;
53 use result::Result::{Err, Ok};
54 use slice::{AsSlice, SlicePrelude, PartialEqSlicePrelude};
55 use slice::CloneSliceAllocPrelude;
56 use str::{Str, StrPrelude, StrAllocating};
57 use string::{String, ToString};
58 use sync::atomic::{AtomicInt, INIT_ATOMIC_INT, SeqCst};
61 #[cfg(unix)] use c_str::ToCStr;
62 #[cfg(unix)] use libc::c_char;
65 pub use sys::ext as unix;
67 pub use sys::ext as windows;
69 /// Get the number of cores available
70 pub fn num_cpus() -> uint {
72 return rust_get_num_cpus() as uint;
76 fn rust_get_num_cpus() -> libc::uintptr_t;
80 pub const TMPBUF_SZ : uint = 1000u;
81 const BUF_BYTES : uint = 2048u;
83 /// Returns the current working directory as a `Path`.
87 /// Returns an `Err` if the current working directory value is invalid.
90 /// * Current directory does not exist.
91 /// * There are insufficient permissions to access the current directory.
92 /// * The internal buffer is not large enough to hold the path.
99 /// // We assume that we are in a valid directory like "/home".
100 /// let current_working_directory = os::getcwd().unwrap();
101 /// println!("The current directory is {}", current_working_directory.display());
105 pub fn getcwd() -> IoResult<Path> {
108 let mut buf = [0 as c_char, ..BUF_BYTES];
110 if libc::getcwd(buf.as_mut_ptr(), buf.len() as libc::size_t).is_null() {
111 Err(IoError::last_error())
113 Ok(Path::new(CString::new(buf.as_ptr(), false)))
118 /// Returns the current working directory as a `Path`.
122 /// Returns an `Err` if the current working directory value is invalid.
125 /// * Current directory does not exist.
126 /// * There are insufficient permissions to access the current directory.
127 /// * The internal buffer is not large enough to hold the path.
134 /// // We assume that we are in a valid directory like "C:\\Windows".
135 /// let current_working_directory = os::getcwd().unwrap();
136 /// println!("The current directory is {}", current_working_directory.display());
140 pub fn getcwd() -> IoResult<Path> {
142 use libc::GetCurrentDirectoryW;
143 use io::OtherIoError;
145 let mut buf = [0 as u16, ..BUF_BYTES];
147 if libc::GetCurrentDirectoryW(buf.len() as DWORD, buf.as_mut_ptr()) == 0 as DWORD {
148 return Err(IoError::last_error());
152 match String::from_utf16(::str::truncate_utf16_at_nul(&buf)) {
153 Some(ref cwd) => Ok(Path::new(cwd)),
154 None => Err(IoError {
156 desc: "GetCurrentDirectoryW returned invalid UTF-16",
164 use libc::types::os::arch::extra::DWORD;
167 use option::Option::None;
170 use slice::{SlicePrelude};
175 pub fn fill_utf16_buf_and_decode(f: |*mut u16, DWORD| -> DWORD)
179 let mut n = TMPBUF_SZ as DWORD;
181 let mut done = false;
183 let mut buf = Vec::from_elem(n as uint, 0u16);
184 let k = f(buf.as_mut_ptr(), n);
185 if k == (0 as DWORD) {
188 libc::GetLastError() ==
189 libc::ERROR_INSUFFICIENT_BUFFER as DWORD {
197 let sub = buf.slice(0, k as uint);
198 // We want to explicitly catch the case when the
199 // closure returned invalid UTF-16, rather than
200 // set `res` to None and continue.
201 let s = String::from_utf16(sub)
202 .expect("fill_utf16_buf_and_decode: closure created invalid UTF-16");
203 res = option::Option::Some(s)
212 Accessing environment variables is not generally threadsafe.
213 Serialize access through a global lock.
215 fn with_env_lock<T>(f: || -> T) -> T {
216 use sync::{StaticMutex, MUTEX_INIT};
218 static LOCK: StaticMutex = MUTEX_INIT;
220 let _guard = LOCK.lock();
224 /// Returns a vector of (variable, value) pairs, for all the environment
225 /// variables of the current process.
227 /// Invalid UTF-8 bytes are replaced with \uFFFD. See `String::from_utf8_lossy()`
235 /// // We will iterate through the references to the element returned by os::env();
236 /// for &(ref key, ref value) in os::env().iter() {
237 /// println!("'{}': '{}'", key, value );
240 pub fn env() -> Vec<(String,String)> {
241 env_as_bytes().into_iter().map(|(k,v)| {
242 let k = String::from_utf8_lossy(k.as_slice()).into_string();
243 let v = String::from_utf8_lossy(v.as_slice()).into_string();
248 /// Returns a vector of (variable, value) byte-vector pairs for all the
249 /// environment variables of the current process.
250 pub fn env_as_bytes() -> Vec<(Vec<u8>,Vec<u8>)> {
253 unsafe fn get_env_pairs() -> Vec<Vec<u8>> {
256 use libc::funcs::extra::kernel32::{
257 GetEnvironmentStringsW,
258 FreeEnvironmentStringsW
260 let ch = GetEnvironmentStringsW();
262 panic!("os::env() failure getting env string from OS: {}",
263 os::last_os_error());
265 // Here, we lossily decode the string as UTF16.
267 // The docs suggest that the result should be in Unicode, but
268 // Windows doesn't guarantee it's actually UTF16 -- it doesn't
269 // validate the environment string passed to CreateProcess nor
270 // SetEnvironmentVariable. Yet, it's unlikely that returning a
271 // raw u16 buffer would be of practical use since the result would
272 // be inherently platform-dependent and introduce additional
273 // complexity to this code.
275 // Using the non-Unicode version of GetEnvironmentStrings is even
276 // worse since the result is in an OEM code page. Characters that
277 // can't be encoded in the code page would be turned into question
279 let mut result = Vec::new();
281 while *ch.offset(i) != 0 {
282 let p = &*ch.offset(i);
284 while *(p as *const _).offset(len) != 0 {
287 let p = p as *const u16;
288 let s = slice::from_raw_buf(&p, len as uint);
289 result.push(String::from_utf16_lossy(s).into_bytes());
292 FreeEnvironmentStringsW(ch);
296 unsafe fn get_env_pairs() -> Vec<Vec<u8>> {
300 fn rust_env_pairs() -> *const *const c_char;
302 let mut environ = rust_env_pairs();
303 if environ as uint == 0 {
304 panic!("os::env() failure getting env string from OS: {}",
305 os::last_os_error());
307 let mut result = Vec::new();
308 while *environ != 0 as *const _ {
310 CString::new(*environ, false).as_bytes_no_nul().to_vec();
311 result.push(env_pair);
312 environ = environ.offset(1);
317 fn env_convert(input: Vec<Vec<u8>>) -> Vec<(Vec<u8>, Vec<u8>)> {
318 let mut pairs = Vec::new();
319 for p in input.iter() {
320 let mut it = p.splitn(1, |b| *b == b'=');
321 let key = it.next().unwrap().to_vec();
322 let default: &[u8] = &[];
323 let val = it.next().unwrap_or(default).to_vec();
324 pairs.push((key, val));
329 let unparsed_environ = get_env_pairs();
330 env_convert(unparsed_environ)
336 /// Fetches the environment variable `n` from the current process, returning
337 /// None if the variable isn't set.
339 /// Any invalid UTF-8 bytes in the value are replaced by \uFFFD. See
340 /// `String::from_utf8_lossy()` for details.
344 /// Panics if `n` has any interior NULs.
351 /// let key = "HOME";
352 /// match os::getenv(key) {
353 /// Some(val) => println!("{}: {}", key, val),
354 /// None => println!("{} is not defined in the environment.", key)
357 pub fn getenv(n: &str) -> Option<String> {
358 getenv_as_bytes(n).map(|v| String::from_utf8_lossy(v.as_slice()).into_string())
362 /// Fetches the environment variable `n` byte vector from the current process,
363 /// returning None if the variable isn't set.
367 /// Panics if `n` has any interior NULs.
368 pub fn getenv_as_bytes(n: &str) -> Option<Vec<u8>> {
373 let s = n.with_c_str(|buf| libc::getenv(buf));
377 Some(CString::new(s as *const i8, false).as_bytes_no_nul().to_vec())
384 /// Fetches the environment variable `n` from the current process, returning
385 /// None if the variable isn't set.
386 pub fn getenv(n: &str) -> Option<String> {
389 use os::windows::{fill_utf16_buf_and_decode};
390 let mut n: Vec<u16> = n.utf16_units().collect();
392 fill_utf16_buf_and_decode(|buf, sz| {
393 libc::GetEnvironmentVariableW(n.as_ptr(), buf, sz)
400 /// Fetches the environment variable `n` byte vector from the current process,
401 /// returning None if the variable isn't set.
402 pub fn getenv_as_bytes(n: &str) -> Option<Vec<u8>> {
403 getenv(n).map(|s| s.into_bytes())
406 /// Sets the environment variable `n` to the value `v` for the currently running
415 /// os::setenv(key, "VALUE");
416 /// match os::getenv(key) {
417 /// Some(ref val) => println!("{}: {}", key, val),
418 /// None => println!("{} is not defined in the environment.", key)
421 pub fn setenv<T: BytesContainer>(n: &str, v: T) {
423 fn _setenv(n: &str, v: &[u8]) {
426 n.with_c_str(|nbuf| {
427 v.with_c_str(|vbuf| {
428 if libc::funcs::posix01::unistd::setenv(nbuf, vbuf, 1) != 0 {
429 panic!(IoError::last_error());
438 fn _setenv(n: &str, v: &[u8]) {
439 let mut n: Vec<u16> = n.utf16_units().collect();
441 let mut v: Vec<u16> = ::str::from_utf8(v).unwrap().utf16_units().collect();
446 if libc::SetEnvironmentVariableW(n.as_ptr(), v.as_ptr()) == 0 {
447 panic!(IoError::last_error());
453 _setenv(n, v.container_as_bytes())
456 /// Remove a variable from the environment entirely.
457 pub fn unsetenv(n: &str) {
459 fn _unsetenv(n: &str) {
462 n.with_c_str(|nbuf| {
463 if libc::funcs::posix01::unistd::unsetenv(nbuf) != 0 {
464 panic!(IoError::last_error());
472 fn _unsetenv(n: &str) {
473 let mut n: Vec<u16> = n.utf16_units().collect();
477 if libc::SetEnvironmentVariableW(n.as_ptr(), ptr::null()) == 0 {
478 panic!(IoError::last_error());
487 /// Parses input according to platform conventions for the `PATH`
488 /// environment variable.
494 /// let key = "PATH";
495 /// match os::getenv_as_bytes(key) {
497 /// for path in os::split_paths(paths).iter() {
498 /// println!("'{}'", path.display());
501 /// None => println!("{} is not defined in the environment.", key)
504 pub fn split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> {
506 fn _split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> {
507 unparsed.container_as_bytes()
508 .split(|b| *b == b':')
514 fn _split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> {
515 // On Windows, the PATH environment variable is semicolon separated. Double
516 // quotes are used as a way of introducing literal semicolons (since
517 // c:\some;dir is a valid Windows path). Double quotes are not themselves
518 // permitted in path names, so there is no way to escape a double quote.
519 // Quoted regions can appear in arbitrary locations, so
521 // c:\foo;c:\som"e;di"r;c:\bar
523 // Should parse as [c:\foo, c:\some;dir, c:\bar].
525 // (The above is based on testing; there is no clear reference available
528 let mut parsed = Vec::new();
529 let mut in_progress = Vec::new();
530 let mut in_quote = false;
532 for b in unparsed.container_as_bytes().iter() {
534 b';' if !in_quote => {
535 parsed.push(Path::new(in_progress.as_slice()));
536 in_progress.truncate(0)
539 in_quote = !in_quote;
542 in_progress.push(*b);
546 parsed.push(Path::new(in_progress));
550 _split_paths(unparsed)
553 /// Joins a collection of `Path`s appropriately for the `PATH`
554 /// environment variable.
556 /// Returns a `Vec<u8>` on success, since `Path`s are not utf-8
557 /// encoded on all platforms.
559 /// Returns an `Err` (containing an error message) if one of the input
560 /// `Path`s contains an invalid character for constructing the `PATH`
561 /// variable (a double quote on Windows or a colon on Unix).
567 /// use std::path::Path;
569 /// let key = "PATH";
570 /// let mut paths = os::getenv_as_bytes(key).map_or(Vec::new(), os::split_paths);
571 /// paths.push(Path::new("/home/xyz/bin"));
572 /// os::setenv(key, os::join_paths(paths.as_slice()).unwrap());
574 pub fn join_paths<T: BytesContainer>(paths: &[T]) -> Result<Vec<u8>, &'static str> {
576 fn _join_paths<T: BytesContainer>(paths: &[T]) -> Result<Vec<u8>, &'static str> {
577 let mut joined = Vec::new();
580 for (i, path) in paths.iter().map(|p| p.container_as_bytes()).enumerate() {
581 if i > 0 { joined.push(sep) }
582 if path.contains(&b'"') {
583 return Err("path segment contains `\"`");
584 } else if path.contains(&sep) {
586 joined.push_all(path);
589 joined.push_all(path);
597 fn _join_paths<T: BytesContainer>(paths: &[T]) -> Result<Vec<u8>, &'static str> {
598 let mut joined = Vec::new();
601 for (i, path) in paths.iter().map(|p| p.container_as_bytes()).enumerate() {
602 if i > 0 { joined.push(sep) }
603 if path.contains(&sep) { return Err("path segment contains separator `:`") }
604 joined.push_all(path);
613 /// A low-level OS in-memory pipe.
615 /// A file descriptor representing the reading end of the pipe. Data written
616 /// on the `out` file descriptor can be read from this file descriptor.
618 /// A file descriptor representing the write end of the pipe. Data written
619 /// to this file descriptor can be read from the `input` file descriptor.
623 impl Copy for Pipe {}
625 /// Creates a new low-level OS in-memory pipe.
627 /// This function can fail to succeed if there are no more resources available
628 /// to allocate a pipe.
630 /// This function is also unsafe as there is no destructor associated with the
631 /// `Pipe` structure will return. If it is not arranged for the returned file
632 /// descriptors to be closed, the file descriptors will leak. For safe handling
633 /// of this scenario, use `std::io::PipeStream` instead.
634 pub unsafe fn pipe() -> IoResult<Pipe> {
635 let (reader, writer) = try!(sys::os::pipe());
637 reader: reader.unwrap(),
638 writer: writer.unwrap(),
642 /// Returns the proper dll filename for the given basename of a file
644 #[cfg(not(target_os="ios"))]
645 pub fn dll_filename(base: &str) -> String {
646 format!("{}{}{}", consts::DLL_PREFIX, base, consts::DLL_SUFFIX)
649 /// Optionally returns the filesystem path to the current executable which is
650 /// running but with the executable name.
657 /// match os::self_exe_name() {
658 /// Some(exe_path) => println!("Path of this executable is: {}", exe_path.display()),
659 /// None => println!("Unable to get the path of this executable!")
662 pub fn self_exe_name() -> Option<Path> {
664 #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))]
665 fn load_self() -> Option<Vec<u8>> {
667 use libc::funcs::bsd44::*;
668 use libc::consts::os::extra::*;
669 let mut mib = vec![CTL_KERN as c_int,
671 KERN_PROC_PATHNAME as c_int,
673 let mut sz: libc::size_t = 0;
674 let err = sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
675 ptr::null_mut(), &mut sz, ptr::null_mut(),
677 if err != 0 { return None; }
678 if sz == 0 { return None; }
679 let mut v: Vec<u8> = Vec::with_capacity(sz as uint);
680 let err = sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
681 v.as_mut_ptr() as *mut c_void, &mut sz,
682 ptr::null_mut(), 0u as libc::size_t);
683 if err != 0 { return None; }
684 if sz == 0 { return None; }
685 v.set_len(sz as uint - 1); // chop off trailing NUL
690 #[cfg(any(target_os = "linux", target_os = "android"))]
691 fn load_self() -> Option<Vec<u8>> {
694 match io::fs::readlink(&Path::new("/proc/self/exe")) {
695 Ok(path) => Some(path.into_vec()),
700 #[cfg(any(target_os = "macos", target_os = "ios"))]
701 fn load_self() -> Option<Vec<u8>> {
703 use libc::funcs::extra::_NSGetExecutablePath;
705 _NSGetExecutablePath(ptr::null_mut(), &mut sz);
706 if sz == 0 { return None; }
707 let mut v: Vec<u8> = Vec::with_capacity(sz as uint);
708 let err = _NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz);
709 if err != 0 { return None; }
710 v.set_len(sz as uint - 1); // chop off trailing NUL
716 fn load_self() -> Option<Vec<u8>> {
718 use os::windows::fill_utf16_buf_and_decode;
719 fill_utf16_buf_and_decode(|buf, sz| {
720 libc::GetModuleFileNameW(0u as libc::DWORD, buf, sz)
721 }).map(|s| s.into_string().into_bytes())
725 load_self().and_then(Path::new_opt)
728 /// Optionally returns the filesystem path to the current executable which is
731 /// Like self_exe_name() but without the binary's name.
738 /// match os::self_exe_path() {
739 /// Some(exe_path) => println!("Executable's Path is: {}", exe_path.display()),
740 /// None => println!("Impossible to fetch the path of this executable.")
743 pub fn self_exe_path() -> Option<Path> {
744 self_exe_name().map(|mut p| { p.pop(); p })
747 /// Optionally returns the path to the current user's home directory if known.
751 /// Returns the value of the 'HOME' environment variable if it is set
752 /// and not equal to the empty string.
756 /// Returns the value of the 'HOME' environment variable if it is
757 /// set and not equal to the empty string. Otherwise, returns the value of the
758 /// 'USERPROFILE' environment variable if it is set and not equal to the empty
766 /// match os::homedir() {
767 /// Some(ref p) => println!("{}", p.display()),
768 /// None => println!("Impossible to get your home dir!")
771 pub fn homedir() -> Option<Path> {
774 fn _homedir() -> Option<Path> {
780 fn _homedir() -> Option<Path> {
781 aux_homedir("HOME").or(aux_homedir("USERPROFILE"))
785 fn aux_homedir(home_name: &str) -> Option<Path> {
786 match getenv_as_bytes(home_name) {
788 if p.is_empty() { None } else { Path::new_opt(p) }
796 /// Returns the path to a temporary directory.
798 /// On Unix, returns the value of the 'TMPDIR' environment variable if it is
799 /// set, otherwise for non-Android it returns '/tmp'. If Android, since there
800 /// is no global temporary folder (it is usually allocated per-app), we return
801 /// '/data/local/tmp'.
803 /// On Windows, returns the value of, in order, the 'TMP', 'TEMP',
804 /// 'USERPROFILE' environment variable if any are set and not the empty
805 /// string. Otherwise, tmpdir returns the path to the Windows directory.
806 pub fn tmpdir() -> Path {
809 fn getenv_nonempty(v: &str) -> Option<Path> {
822 fn lookup() -> Path {
823 let default = if cfg!(target_os = "android") {
824 Path::new("/data/local/tmp")
829 getenv_nonempty("TMPDIR").unwrap_or(default)
833 fn lookup() -> Path {
834 getenv_nonempty("TMP").or(
835 getenv_nonempty("TEMP").or(
836 getenv_nonempty("USERPROFILE").or(
837 getenv_nonempty("WINDIR")))).unwrap_or(Path::new("C:\\Windows"))
842 /// Convert a relative path to an absolute path
844 /// If the given path is relative, return it prepended with the current working
845 /// directory. If the given path is already an absolute path, return it
851 /// use std::path::Path;
853 /// // Assume we're in a path like /home/someuser
854 /// let rel_path = Path::new("..");
855 /// let abs_path = os::make_absolute(&rel_path).unwrap();
856 /// println!("The absolute path is {}", abs_path.display());
857 /// // Prints "The absolute path is /home"
859 // NB: this is here rather than in path because it is a form of environment
860 // querying; what it does depends on the process working directory, not just
862 pub fn make_absolute(p: &Path) -> IoResult<Path> {
866 getcwd().map(|mut cwd| {
873 /// Changes the current working directory to the specified path, returning
874 /// whether the change was completed successfully or not.
879 /// use std::path::Path;
881 /// let root = Path::new("/");
882 /// assert!(os::change_dir(&root).is_ok());
883 /// println!("Successfully changed working directory to {}!", root.display());
885 pub fn change_dir(p: &Path) -> IoResult<()> {
889 fn chdir(p: &Path) -> IoResult<()> {
890 let mut p = p.as_str().unwrap().utf16_units().collect::<Vec<u16>>();
894 match libc::SetCurrentDirectoryW(p.as_ptr()) != (0 as libc::BOOL) {
896 false => Err(IoError::last_error()),
902 fn chdir(p: &Path) -> IoResult<()> {
905 match libc::chdir(buf) == (0 as c_int) {
907 false => Err(IoError::last_error()),
914 /// Returns the platform-specific value of errno
915 pub fn errno() -> uint {
916 os_imp::errno() as uint
919 /// Return the string corresponding to an `errno()` value of `errnum`.
925 /// // Same as println!("{}", last_os_error());
926 /// println!("{}", os::error_string(os::errno() as uint));
928 pub fn error_string(errnum: uint) -> String {
929 return os_imp::error_string(errnum as i32);
932 /// Get a string representing the platform-dependent last error
933 pub fn last_os_error() -> String {
934 error_string(errno() as uint)
937 static EXIT_STATUS: AtomicInt = INIT_ATOMIC_INT;
939 /// Sets the process exit code
941 /// Sets the exit code returned by the process if all supervised tasks
942 /// terminate successfully (without panicking). If the current root task panics
943 /// and is supervised by the scheduler then any user-specified exit status is
944 /// ignored and the process exits with the default panic status.
946 /// Note that this is not synchronized against modifications of other threads.
947 pub fn set_exit_status(code: int) {
948 EXIT_STATUS.store(code, SeqCst)
951 /// Fetches the process's current exit code. This defaults to 0 and can change
952 /// by calling `set_exit_status`.
953 pub fn get_exit_status() -> int {
954 EXIT_STATUS.load(SeqCst)
957 #[cfg(target_os = "macos")]
958 unsafe fn load_argc_and_argv(argc: int,
959 argv: *const *const c_char) -> Vec<Vec<u8>> {
962 Vec::from_fn(argc as uint, |i| {
963 CString::new(*argv.offset(i as int), false).as_bytes_no_nul().to_vec()
967 /// Returns the command line arguments
969 /// Returns a list of the command line arguments.
970 #[cfg(target_os = "macos")]
971 fn real_args_as_bytes() -> Vec<Vec<u8>> {
973 let (argc, argv) = (*_NSGetArgc() as int,
974 *_NSGetArgv() as *const *const c_char);
975 load_argc_and_argv(argc, argv)
979 // As _NSGetArgc and _NSGetArgv aren't mentioned in iOS docs
980 // and use underscores in their names - they're most probably
981 // are considered private and therefore should be avoided
982 // Here is another way to get arguments using Objective C
985 // In general it looks like:
987 // let args = [[NSProcessInfo processInfo] arguments]
988 // for i in range(0, [args count])
989 // res.push([args objectAtIndex:i])
991 #[cfg(target_os = "ios")]
992 fn real_args_as_bytes() -> Vec<Vec<u8>> {
997 #[link(name = "objc")]
999 fn sel_registerName(name: *const libc::c_uchar) -> Sel;
1000 fn objc_msgSend(obj: NsId, sel: Sel, ...) -> NsId;
1001 fn objc_getClass(class_name: *const libc::c_uchar) -> NsId;
1004 #[link(name = "Foundation", kind = "framework")]
1007 type Sel = *const libc::c_void;
1008 type NsId = *const libc::c_void;
1010 let mut res = Vec::new();
1013 let processInfoSel = sel_registerName("processInfo\0".as_ptr());
1014 let argumentsSel = sel_registerName("arguments\0".as_ptr());
1015 let utf8Sel = sel_registerName("UTF8String\0".as_ptr());
1016 let countSel = sel_registerName("count\0".as_ptr());
1017 let objectAtSel = sel_registerName("objectAtIndex:\0".as_ptr());
1019 let klass = objc_getClass("NSProcessInfo\0".as_ptr());
1020 let info = objc_msgSend(klass, processInfoSel);
1021 let args = objc_msgSend(info, argumentsSel);
1023 let cnt: int = mem::transmute(objc_msgSend(args, countSel));
1024 for i in range(0, cnt) {
1025 let tmp = objc_msgSend(args, objectAtSel, i);
1026 let utf_c_str: *const libc::c_char =
1027 mem::transmute(objc_msgSend(tmp, utf8Sel));
1028 let s = CString::new(utf_c_str, false);
1029 res.push(s.as_bytes_no_nul().to_vec())
1036 #[cfg(any(target_os = "linux",
1037 target_os = "android",
1038 target_os = "freebsd",
1039 target_os = "dragonfly"))]
1040 fn real_args_as_bytes() -> Vec<Vec<u8>> {
1043 match rustrt::args::clone() {
1045 None => panic!("process arguments not initialized")
1049 #[cfg(not(windows))]
1050 fn real_args() -> Vec<String> {
1051 real_args_as_bytes().into_iter()
1053 String::from_utf8_lossy(v.as_slice()).into_string()
1058 fn real_args() -> Vec<String> {
1061 let mut nArgs: c_int = 0;
1062 let lpArgCount: *mut c_int = &mut nArgs;
1063 let lpCmdLine = unsafe { GetCommandLineW() };
1064 let szArgList = unsafe { CommandLineToArgvW(lpCmdLine, lpArgCount) };
1066 let args = Vec::from_fn(nArgs as uint, |i| unsafe {
1067 // Determine the length of this argument.
1068 let ptr = *szArgList.offset(i as int);
1070 while *ptr.offset(len as int) != 0 { len += 1; }
1072 // Push it onto the list.
1073 let ptr = ptr as *const u16;
1074 let buf = slice::from_raw_buf(&ptr, len);
1075 let opt_s = String::from_utf16(::str::truncate_utf16_at_nul(buf));
1076 opt_s.expect("CommandLineToArgvW returned invalid UTF-16")
1080 LocalFree(szArgList as *mut c_void);
1087 fn real_args_as_bytes() -> Vec<Vec<u8>> {
1088 real_args().into_iter().map(|s| s.into_bytes()).collect()
1091 type LPCWSTR = *const u16;
1094 #[link_name="kernel32"]
1096 fn GetCommandLineW() -> LPCWSTR;
1097 fn LocalFree(ptr: *mut c_void);
1101 #[link_name="shell32"]
1103 fn CommandLineToArgvW(lpCmdLine: LPCWSTR,
1104 pNumArgs: *mut c_int) -> *mut *mut u16;
1107 /// Returns the arguments which this program was started with (normally passed
1108 /// via the command line).
1110 /// The first element is traditionally the path to the executable, but it can be
1111 /// set to arbitrary text, and it may not even exist, so this property should not
1112 /// be relied upon for security purposes.
1114 /// The arguments are interpreted as utf-8, with invalid bytes replaced with \uFFFD.
1115 /// See `String::from_utf8_lossy` for details.
1121 /// // Prints each argument on a separate line
1122 /// for argument in os::args().iter() {
1123 /// println!("{}", argument);
1126 pub fn args() -> Vec<String> {
1130 /// Returns the arguments which this program was started with (normally passed
1131 /// via the command line) as byte vectors.
1132 pub fn args_as_bytes() -> Vec<Vec<u8>> {
1133 real_args_as_bytes()
1136 #[cfg(target_os = "macos")]
1138 // These functions are in crt_externs.h.
1139 pub fn _NSGetArgc() -> *mut c_int;
1140 pub fn _NSGetArgv() -> *mut *mut *mut c_char;
1143 // Round up `from` to be divisible by `to`
1144 fn round_up(from: uint, to: uint) -> uint {
1145 let r = if from % to == 0 {
1148 from + to - (from % to)
1157 /// Returns the page size of the current architecture in bytes.
1159 pub fn page_size() -> uint {
1161 libc::sysconf(libc::_SC_PAGESIZE) as uint
1165 /// Returns the page size of the current architecture in bytes.
1167 pub fn page_size() -> uint {
1170 let mut info = mem::zeroed();
1171 libc::GetSystemInfo(&mut info);
1173 return info.dwPageSize as uint;
1177 /// A memory mapped file or chunk of memory. This is a very system-specific
1178 /// interface to the OS's memory mapping facilities (`mmap` on POSIX,
1179 /// `VirtualAlloc`/`CreateFileMapping` on Windows). It makes no attempt at
1180 /// abstracting platform differences, besides in error values returned. Consider
1181 /// yourself warned.
1183 /// The memory map is released (unmapped) when the destructor is run, so don't
1184 /// let it leave scope by accident if you want it to stick around.
1185 pub struct MemoryMap {
1188 kind: MemoryMapKind,
1192 impl Copy for MemoryMap {}
1194 /// Type of memory map
1195 pub enum MemoryMapKind {
1196 /// Virtual memory map. Usually used to change the permissions of a given
1197 /// chunk of memory. Corresponds to `VirtualAlloc` on Windows.
1199 /// Virtual memory map. Usually used to change the permissions of a given
1200 /// chunk of memory, or for allocation. Corresponds to `VirtualAlloc` on
1205 impl Copy for MemoryMapKind {}
1207 /// Options the memory map is created with
1208 pub enum MapOption {
1209 /// The memory should be readable
1211 /// The memory should be writable
1213 /// The memory should be executable
1215 /// Create a map for a specific address range. Corresponds to `MAP_FIXED` on
1218 /// Create a memory mapping for a file with a given fd.
1220 /// When using `MapFd`, the start of the map is `uint` bytes from the start
1223 /// On POSIX, this can be used to specify the default flags passed to
1224 /// `mmap`. By default it uses `MAP_PRIVATE` and, if not using `MapFd`,
1225 /// `MAP_ANON`. This will override both of those. This is platform-specific
1226 /// (the exact values used) and ignored on Windows.
1227 MapNonStandardFlags(c_int),
1230 impl Copy for MapOption {}
1232 /// Possible errors when creating a map.
1234 /// ## The following are POSIX-specific
1236 /// fd was not open for reading or, if using `MapWritable`, was not open for
1239 /// fd was not valid
1241 /// Either the address given by `MapAddr` or offset given by `MapOffset` was
1242 /// not a multiple of `MemoryMap::granularity` (unaligned to page size).
1244 /// With `MapFd`, the fd does not support mapping.
1246 /// If using `MapAddr`, the address + `min_len` was outside of the process's
1247 /// address space. If using `MapFd`, the target of the fd didn't have enough
1248 /// resources to fulfill the request.
1250 /// A zero-length map was requested. This is invalid according to
1251 /// [POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/functions/mmap.html).
1252 /// Not all platforms obey this, but this wrapper does.
1254 /// Unrecognized error. The inner value is the unrecognized errno.
1256 /// ## The following are Windows-specific
1258 /// Unsupported combination of protection flags
1259 /// (`MapReadable`/`MapWritable`/`MapExecutable`).
1261 /// When using `MapFd`, `MapOffset` was given (Windows does not support this
1264 /// When using `MapFd`, there was already a mapping to the file.
1266 /// Unrecognized error from `VirtualAlloc`. The inner value is the return
1267 /// value of GetLastError.
1268 ErrVirtualAlloc(uint),
1269 /// Unrecognized error from `CreateFileMapping`. The inner value is the
1270 /// return value of `GetLastError`.
1271 ErrCreateFileMappingW(uint),
1272 /// Unrecognized error from `MapViewOfFile`. The inner value is the return
1273 /// value of `GetLastError`.
1274 ErrMapViewOfFile(uint)
1277 impl Copy for MapError {}
1279 impl fmt::Show for MapError {
1280 fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result {
1281 let str = match *self {
1282 ErrFdNotAvail => "fd not available for reading or writing",
1283 ErrInvalidFd => "Invalid fd",
1285 "Unaligned address, invalid flags, negative length or \
1288 ErrNoMapSupport=> "File doesn't support mapping",
1289 ErrNoMem => "Invalid address, or not enough available memory",
1290 ErrUnsupProt => "Protection mode unsupported",
1291 ErrUnsupOffset => "Offset in virtual memory mode is unsupported",
1292 ErrAlreadyExists => "File mapping for specified file already exists",
1293 ErrZeroLength => "Zero-length mapping not allowed",
1294 ErrUnknown(code) => {
1295 return write!(out, "Unknown error = {}", code)
1297 ErrVirtualAlloc(code) => {
1298 return write!(out, "VirtualAlloc failure = {}", code)
1300 ErrCreateFileMappingW(code) => {
1301 return write!(out, "CreateFileMappingW failure = {}", code)
1303 ErrMapViewOfFile(code) => {
1304 return write!(out, "MapViewOfFile failure = {}", code)
1307 write!(out, "{}", str)
1311 impl Error for MapError {
1312 fn description(&self) -> &str { "memory map error" }
1313 fn detail(&self) -> Option<String> { Some(self.to_string()) }
1316 impl FromError<MapError> for Box<Error> {
1317 fn from_error(err: MapError) -> Box<Error> {
1324 /// Create a new mapping with the given `options`, at least `min_len` bytes
1325 /// long. `min_len` must be greater than zero; see the note on
1326 /// `ErrZeroLength`.
1327 pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
1331 return Err(ErrZeroLength)
1333 let mut addr: *const u8 = ptr::null();
1335 let mut flags = libc::MAP_PRIVATE;
1338 let mut custom_flags = false;
1339 let len = round_up(min_len, page_size());
1341 for &o in options.iter() {
1343 MapReadable => { prot |= libc::PROT_READ; },
1344 MapWritable => { prot |= libc::PROT_WRITE; },
1345 MapExecutable => { prot |= libc::PROT_EXEC; },
1347 flags |= libc::MAP_FIXED;
1351 flags |= libc::MAP_FILE;
1354 MapOffset(offset_) => { offset = offset_ as off_t; },
1355 MapNonStandardFlags(f) => { custom_flags = true; flags = f },
1358 if fd == -1 && !custom_flags { flags |= libc::MAP_ANON; }
1361 libc::mmap(addr as *mut c_void, len as libc::size_t, prot, flags,
1364 if r == libc::MAP_FAILED {
1365 Err(match errno() as c_int {
1366 libc::EACCES => ErrFdNotAvail,
1367 libc::EBADF => ErrInvalidFd,
1368 libc::EINVAL => ErrUnaligned,
1369 libc::ENODEV => ErrNoMapSupport,
1370 libc::ENOMEM => ErrNoMem,
1371 code => ErrUnknown(code as int)
1380 MapFile(ptr::null())
1386 /// Granularity that the offset or address must be for `MapOffset` and
1387 /// `MapAddr` respectively.
1388 pub fn granularity() -> uint {
1394 impl Drop for MemoryMap {
1395 /// Unmap the mapping. Panics the task if `munmap` panics.
1396 fn drop(&mut self) {
1397 if self.len == 0 { /* workaround for dummy_stack */ return; }
1400 // `munmap` only panics due to logic errors
1401 libc::munmap(self.data as *mut c_void, self.len as libc::size_t);
1408 /// Create a new mapping with the given `options`, at least `min_len` bytes long.
1409 pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
1410 use libc::types::os::arch::extra::{LPVOID, DWORD, SIZE_T, HANDLE};
1412 let mut lpAddress: LPVOID = ptr::null_mut();
1413 let mut readable = false;
1414 let mut writable = false;
1415 let mut executable = false;
1416 let mut fd: c_int = -1;
1417 let mut offset: uint = 0;
1418 let len = round_up(min_len, page_size());
1420 for &o in options.iter() {
1422 MapReadable => { readable = true; },
1423 MapWritable => { writable = true; },
1424 MapExecutable => { executable = true; }
1425 MapAddr(addr_) => { lpAddress = addr_ as LPVOID; },
1426 MapFd(fd_) => { fd = fd_; },
1427 MapOffset(offset_) => { offset = offset_; },
1428 MapNonStandardFlags(..) => {}
1432 let flProtect = match (executable, readable, writable) {
1433 (false, false, false) if fd == -1 => libc::PAGE_NOACCESS,
1434 (false, true, false) => libc::PAGE_READONLY,
1435 (false, true, true) => libc::PAGE_READWRITE,
1436 (true, false, false) if fd == -1 => libc::PAGE_EXECUTE,
1437 (true, true, false) => libc::PAGE_EXECUTE_READ,
1438 (true, true, true) => libc::PAGE_EXECUTE_READWRITE,
1439 _ => return Err(ErrUnsupProt)
1444 return Err(ErrUnsupOffset);
1447 libc::VirtualAlloc(lpAddress,
1449 libc::MEM_COMMIT | libc::MEM_RESERVE,
1453 0 => Err(ErrVirtualAlloc(errno())),
1461 let dwDesiredAccess = match (executable, readable, writable) {
1462 (false, true, false) => libc::FILE_MAP_READ,
1463 (false, true, true) => libc::FILE_MAP_WRITE,
1464 (true, true, false) => libc::FILE_MAP_READ | libc::FILE_MAP_EXECUTE,
1465 (true, true, true) => libc::FILE_MAP_WRITE | libc::FILE_MAP_EXECUTE,
1466 _ => return Err(ErrUnsupProt) // Actually, because of the check above,
1467 // we should never get here.
1470 let hFile = libc::get_osfhandle(fd) as HANDLE;
1471 let mapping = libc::CreateFileMappingW(hFile,
1477 if mapping == ptr::null_mut() {
1478 return Err(ErrCreateFileMappingW(errno()));
1480 if errno() as c_int == libc::ERROR_ALREADY_EXISTS {
1481 return Err(ErrAlreadyExists);
1483 let r = libc::MapViewOfFile(mapping,
1485 ((len as u64) >> 32) as DWORD,
1486 (offset & 0xffff_ffff) as DWORD,
1489 0 => Err(ErrMapViewOfFile(errno())),
1493 kind: MapFile(mapping as *const u8)
1500 /// Granularity of MapAddr() and MapOffset() parameter values.
1501 /// This may be greater than the value returned by page_size().
1502 pub fn granularity() -> uint {
1505 let mut info = mem::zeroed();
1506 libc::GetSystemInfo(&mut info);
1508 return info.dwAllocationGranularity as uint;
1514 impl Drop for MemoryMap {
1515 /// Unmap the mapping. Panics the task if any of `VirtualFree`,
1516 /// `UnmapViewOfFile`, or `CloseHandle` fail.
1517 fn drop(&mut self) {
1518 use libc::types::os::arch::extra::{LPCVOID, HANDLE};
1519 use libc::consts::os::extra::FALSE;
1520 if self.len == 0 { return }
1525 if libc::VirtualFree(self.data as *mut c_void, 0,
1526 libc::MEM_RELEASE) == 0 {
1527 println!("VirtualFree failed: {}", errno());
1530 MapFile(mapping) => {
1531 if libc::UnmapViewOfFile(self.data as LPCVOID) == FALSE {
1532 println!("UnmapViewOfFile failed: {}", errno());
1534 if libc::CloseHandle(mapping as HANDLE) == FALSE {
1535 println!("CloseHandle failed: {}", errno());
1544 /// Returns the pointer to the memory created or modified by this map.
1545 pub fn data(&self) -> *mut u8 { self.data }
1546 /// Returns the number of bytes this map applies to.
1547 pub fn len(&self) -> uint { self.len }
1548 /// Returns the type of mapping this represents.
1549 pub fn kind(&self) -> MemoryMapKind { self.kind }
1552 #[cfg(target_os = "linux")]
1554 pub use os::arch_consts::ARCH;
1556 pub const FAMILY: &'static str = "unix";
1558 /// A string describing the specific operating system in use: in this
1560 pub const SYSNAME: &'static str = "linux";
1562 /// Specifies the filename prefix used for shared libraries on this
1563 /// platform: in this case, `lib`.
1564 pub const DLL_PREFIX: &'static str = "lib";
1566 /// Specifies the filename suffix used for shared libraries on this
1567 /// platform: in this case, `.so`.
1568 pub const DLL_SUFFIX: &'static str = ".so";
1570 /// Specifies the file extension used for shared libraries on this
1571 /// platform that goes after the dot: in this case, `so`.
1572 pub const DLL_EXTENSION: &'static str = "so";
1574 /// Specifies the filename suffix used for executable binaries on this
1575 /// platform: in this case, the empty string.
1576 pub const EXE_SUFFIX: &'static str = "";
1578 /// Specifies the file extension, if any, used for executable binaries
1579 /// on this platform: in this case, the empty string.
1580 pub const EXE_EXTENSION: &'static str = "";
1583 #[cfg(target_os = "macos")]
1585 pub use os::arch_consts::ARCH;
1587 pub const FAMILY: &'static str = "unix";
1589 /// A string describing the specific operating system in use: in this
1591 pub const SYSNAME: &'static str = "macos";
1593 /// Specifies the filename prefix used for shared libraries on this
1594 /// platform: in this case, `lib`.
1595 pub const DLL_PREFIX: &'static str = "lib";
1597 /// Specifies the filename suffix used for shared libraries on this
1598 /// platform: in this case, `.dylib`.
1599 pub const DLL_SUFFIX: &'static str = ".dylib";
1601 /// Specifies the file extension used for shared libraries on this
1602 /// platform that goes after the dot: in this case, `dylib`.
1603 pub const DLL_EXTENSION: &'static str = "dylib";
1605 /// Specifies the filename suffix used for executable binaries on this
1606 /// platform: in this case, the empty string.
1607 pub const EXE_SUFFIX: &'static str = "";
1609 /// Specifies the file extension, if any, used for executable binaries
1610 /// on this platform: in this case, the empty string.
1611 pub const EXE_EXTENSION: &'static str = "";
1614 #[cfg(target_os = "ios")]
1616 pub use os::arch_consts::ARCH;
1618 pub const FAMILY: &'static str = "unix";
1620 /// A string describing the specific operating system in use: in this
1622 pub const SYSNAME: &'static str = "ios";
1624 /// Specifies the filename suffix used for executable binaries on this
1625 /// platform: in this case, the empty string.
1626 pub const EXE_SUFFIX: &'static str = "";
1628 /// Specifies the file extension, if any, used for executable binaries
1629 /// on this platform: in this case, the empty string.
1630 pub const EXE_EXTENSION: &'static str = "";
1633 #[cfg(target_os = "freebsd")]
1635 pub use os::arch_consts::ARCH;
1637 pub const FAMILY: &'static str = "unix";
1639 /// A string describing the specific operating system in use: in this
1640 /// case, `freebsd`.
1641 pub const SYSNAME: &'static str = "freebsd";
1643 /// Specifies the filename prefix used for shared libraries on this
1644 /// platform: in this case, `lib`.
1645 pub const DLL_PREFIX: &'static str = "lib";
1647 /// Specifies the filename suffix used for shared libraries on this
1648 /// platform: in this case, `.so`.
1649 pub const DLL_SUFFIX: &'static str = ".so";
1651 /// Specifies the file extension used for shared libraries on this
1652 /// platform that goes after the dot: in this case, `so`.
1653 pub const DLL_EXTENSION: &'static str = "so";
1655 /// Specifies the filename suffix used for executable binaries on this
1656 /// platform: in this case, the empty string.
1657 pub const EXE_SUFFIX: &'static str = "";
1659 /// Specifies the file extension, if any, used for executable binaries
1660 /// on this platform: in this case, the empty string.
1661 pub const EXE_EXTENSION: &'static str = "";
1664 #[cfg(target_os = "dragonfly")]
1666 pub use os::arch_consts::ARCH;
1668 pub const FAMILY: &'static str = "unix";
1670 /// A string describing the specific operating system in use: in this
1671 /// case, `dragonfly`.
1672 pub const SYSNAME: &'static str = "dragonfly";
1674 /// Specifies the filename prefix used for shared libraries on this
1675 /// platform: in this case, `lib`.
1676 pub const DLL_PREFIX: &'static str = "lib";
1678 /// Specifies the filename suffix used for shared libraries on this
1679 /// platform: in this case, `.so`.
1680 pub const DLL_SUFFIX: &'static str = ".so";
1682 /// Specifies the file extension used for shared libraries on this
1683 /// platform that goes after the dot: in this case, `so`.
1684 pub const DLL_EXTENSION: &'static str = "so";
1686 /// Specifies the filename suffix used for executable binaries on this
1687 /// platform: in this case, the empty string.
1688 pub const EXE_SUFFIX: &'static str = "";
1690 /// Specifies the file extension, if any, used for executable binaries
1691 /// on this platform: in this case, the empty string.
1692 pub const EXE_EXTENSION: &'static str = "";
1695 #[cfg(target_os = "android")]
1697 pub use os::arch_consts::ARCH;
1699 pub const FAMILY: &'static str = "unix";
1701 /// A string describing the specific operating system in use: in this
1702 /// case, `android`.
1703 pub const SYSNAME: &'static str = "android";
1705 /// Specifies the filename prefix used for shared libraries on this
1706 /// platform: in this case, `lib`.
1707 pub const DLL_PREFIX: &'static str = "lib";
1709 /// Specifies the filename suffix used for shared libraries on this
1710 /// platform: in this case, `.so`.
1711 pub const DLL_SUFFIX: &'static str = ".so";
1713 /// Specifies the file extension used for shared libraries on this
1714 /// platform that goes after the dot: in this case, `so`.
1715 pub const DLL_EXTENSION: &'static str = "so";
1717 /// Specifies the filename suffix used for executable binaries on this
1718 /// platform: in this case, the empty string.
1719 pub const EXE_SUFFIX: &'static str = "";
1721 /// Specifies the file extension, if any, used for executable binaries
1722 /// on this platform: in this case, the empty string.
1723 pub const EXE_EXTENSION: &'static str = "";
1726 #[cfg(target_os = "windows")]
1728 pub use os::arch_consts::ARCH;
1730 pub const FAMILY: &'static str = "windows";
1732 /// A string describing the specific operating system in use: in this
1733 /// case, `windows`.
1734 pub const SYSNAME: &'static str = "windows";
1736 /// Specifies the filename prefix used for shared libraries on this
1737 /// platform: in this case, the empty string.
1738 pub const DLL_PREFIX: &'static str = "";
1740 /// Specifies the filename suffix used for shared libraries on this
1741 /// platform: in this case, `.dll`.
1742 pub const DLL_SUFFIX: &'static str = ".dll";
1744 /// Specifies the file extension used for shared libraries on this
1745 /// platform that goes after the dot: in this case, `dll`.
1746 pub const DLL_EXTENSION: &'static str = "dll";
1748 /// Specifies the filename suffix used for executable binaries on this
1749 /// platform: in this case, `.exe`.
1750 pub const EXE_SUFFIX: &'static str = ".exe";
1752 /// Specifies the file extension, if any, used for executable binaries
1753 /// on this platform: in this case, `exe`.
1754 pub const EXE_EXTENSION: &'static str = "exe";
1757 #[cfg(target_arch = "x86")]
1759 pub const ARCH: &'static str = "x86";
1762 #[cfg(target_arch = "x86_64")]
1764 pub const ARCH: &'static str = "x86_64";
1767 #[cfg(target_arch = "arm")]
1769 pub const ARCH: &'static str = "arm";
1772 #[cfg(target_arch = "mips")]
1774 pub const ARCH: &'static str = "mips";
1777 #[cfg(target_arch = "mipsel")]
1779 pub const ARCH: &'static str = "mipsel";
1787 use os::{env, getcwd, getenv, make_absolute};
1788 use os::{split_paths, join_paths, setenv, unsetenv};
1794 pub fn last_os_error() {
1795 debug!("{}", os::last_os_error());
1798 fn make_rand_name() -> String {
1799 let mut rng = rand::task_rng();
1800 let n = format!("TEST{}", rng.gen_ascii_chars().take(10u)
1801 .collect::<String>());
1802 assert!(getenv(n.as_slice()).is_none());
1807 fn test_num_cpus() {
1808 assert!(os::num_cpus() > 0);
1813 let n = make_rand_name();
1814 setenv(n.as_slice(), "VALUE");
1815 assert_eq!(getenv(n.as_slice()), option::Option::Some("VALUE".to_string()));
1819 fn test_unsetenv() {
1820 let n = make_rand_name();
1821 setenv(n.as_slice(), "VALUE");
1822 unsetenv(n.as_slice());
1823 assert_eq!(getenv(n.as_slice()), option::Option::None);
1828 fn test_setenv_overwrite() {
1829 let n = make_rand_name();
1830 setenv(n.as_slice(), "1");
1831 setenv(n.as_slice(), "2");
1832 assert_eq!(getenv(n.as_slice()), option::Option::Some("2".to_string()));
1833 setenv(n.as_slice(), "");
1834 assert_eq!(getenv(n.as_slice()), option::Option::Some("".to_string()));
1837 // Windows GetEnvironmentVariable requires some extra work to make sure
1838 // the buffer the variable is copied into is the right size
1841 fn test_getenv_big() {
1842 let mut s = "".to_string();
1845 s.push_str("aaaaaaaaaa");
1848 let n = make_rand_name();
1849 setenv(n.as_slice(), s.as_slice());
1850 debug!("{}", s.clone());
1851 assert_eq!(getenv(n.as_slice()), option::Option::Some(s));
1855 fn test_self_exe_name() {
1856 let path = os::self_exe_name();
1857 assert!(path.is_some());
1858 let path = path.unwrap();
1859 debug!("{}", path.display());
1861 // Hard to test this function
1862 assert!(path.is_absolute());
1866 fn test_self_exe_path() {
1867 let path = os::self_exe_path();
1868 assert!(path.is_some());
1869 let path = path.unwrap();
1870 debug!("{}", path.display());
1872 // Hard to test this function
1873 assert!(path.is_absolute());
1878 fn test_env_getenv() {
1880 assert!(e.len() > 0u);
1882 let (n, v) = (*p).clone();
1884 let v2 = getenv(n.as_slice());
1885 // MingW seems to set some funky environment variables like
1886 // "=C:=C:\MinGW\msys\1.0\bin" and "!::=::\" that are returned
1887 // from env() but not visible from getenv().
1888 assert!(v2.is_none() || v2 == option::Option::Some(v));
1893 fn test_env_set_get_huge() {
1894 let n = make_rand_name();
1895 let s = "x".repeat(10000).to_string();
1896 setenv(n.as_slice(), s.as_slice());
1897 assert_eq!(getenv(n.as_slice()), Some(s));
1898 unsetenv(n.as_slice());
1899 assert_eq!(getenv(n.as_slice()), None);
1903 fn test_env_setenv() {
1904 let n = make_rand_name();
1907 setenv(n.as_slice(), "VALUE");
1908 assert!(!e.contains(&(n.clone(), "VALUE".to_string())));
1911 assert!(e.contains(&(n, "VALUE".to_string())));
1916 assert!((!Path::new("test-path").is_absolute()));
1918 let cwd = getcwd().unwrap();
1919 debug!("Current working directory: {}", cwd.display());
1921 debug!("{}", make_absolute(&Path::new("test-path")).unwrap().display());
1922 debug!("{}", make_absolute(&Path::new("/usr/bin")).unwrap().display());
1928 let oldhome = getenv("HOME");
1930 setenv("HOME", "/home/MountainView");
1931 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1934 assert!(os::homedir().is_none());
1936 for s in oldhome.iter() {
1937 setenv("HOME", s.as_slice());
1945 let oldhome = getenv("HOME");
1946 let olduserprofile = getenv("USERPROFILE");
1949 setenv("USERPROFILE", "");
1951 assert!(os::homedir().is_none());
1953 setenv("HOME", "/home/MountainView");
1954 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1958 setenv("USERPROFILE", "/home/MountainView");
1959 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1961 setenv("HOME", "/home/MountainView");
1962 setenv("USERPROFILE", "/home/PaloAlto");
1963 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1965 for s in oldhome.iter() {
1966 setenv("HOME", s.as_slice());
1968 for s in olduserprofile.iter() {
1969 setenv("USERPROFILE", s.as_slice());
1974 fn memory_map_rw() {
1975 use result::Result::{Ok, Err};
1977 let chunk = match os::MemoryMap::new(16, &[
1982 Err(msg) => panic!("{}", msg)
1984 assert!(chunk.len >= 16);
1988 assert!(*chunk.data == 0xBE);
1993 fn memory_map_file() {
1994 use result::Result::{Ok, Err};
2000 fn lseek_(fd: c_int, size: uint) {
2002 assert!(lseek(fd, size as off_t, SEEK_SET) == size as off_t);
2006 fn lseek_(fd: c_int, size: uint) {
2008 assert!(lseek(fd, size as c_long, SEEK_SET) == size as c_long);
2012 let mut path = tmpdir();
2013 path.push("mmap_file.tmp");
2014 let size = MemoryMap::granularity() * 2;
2017 let fd = path.with_c_str(|path| {
2018 open(path, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR)
2021 "x".with_c_str(|x| assert!(write(fd, x as *const c_void, 1) == 1));
2024 let chunk = match MemoryMap::new(size / 2, &[
2031 Err(msg) => panic!("{}", msg)
2033 assert!(chunk.len > 0);
2037 assert!(*chunk.data == 0xbe);
2042 fs::unlink(&path).unwrap();
2047 fn split_paths_windows() {
2048 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
2049 split_paths(unparsed) ==
2050 parsed.iter().map(|s| Path::new(*s)).collect::<Vec<_>>()
2053 assert!(check_parse("", &mut [""]));
2054 assert!(check_parse(r#""""#, &mut [""]));
2055 assert!(check_parse(";;", &mut ["", "", ""]));
2056 assert!(check_parse(r"c:\", &mut [r"c:\"]));
2057 assert!(check_parse(r"c:\;", &mut [r"c:\", ""]));
2058 assert!(check_parse(r"c:\;c:\Program Files\",
2059 &mut [r"c:\", r"c:\Program Files\"]));
2060 assert!(check_parse(r#"c:\;c:\"foo"\"#, &mut [r"c:\", r"c:\foo\"]));
2061 assert!(check_parse(r#"c:\;c:\"foo;bar"\;c:\baz"#,
2062 &mut [r"c:\", r"c:\foo;bar\", r"c:\baz"]));
2067 fn split_paths_unix() {
2068 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
2069 split_paths(unparsed) ==
2070 parsed.iter().map(|s| Path::new(*s)).collect::<Vec<_>>()
2073 assert!(check_parse("", &mut [""]));
2074 assert!(check_parse("::", &mut ["", "", ""]));
2075 assert!(check_parse("/", &mut ["/"]));
2076 assert!(check_parse("/:", &mut ["/", ""]));
2077 assert!(check_parse("/:/usr/local", &mut ["/", "/usr/local"]));
2082 fn join_paths_unix() {
2083 fn test_eq(input: &[&str], output: &str) -> bool {
2084 join_paths(input).unwrap() == output.as_bytes()
2087 assert!(test_eq(&[], ""));
2088 assert!(test_eq(&["/bin", "/usr/bin", "/usr/local/bin"],
2089 "/bin:/usr/bin:/usr/local/bin"));
2090 assert!(test_eq(&["", "/bin", "", "", "/usr/bin", ""],
2091 ":/bin:::/usr/bin:"));
2092 assert!(join_paths(&["/te:st"]).is_err());
2097 fn join_paths_windows() {
2098 fn test_eq(input: &[&str], output: &str) -> bool {
2099 join_paths(input).unwrap() == output.as_bytes()
2102 assert!(test_eq(&[], ""));
2103 assert!(test_eq(&[r"c:\windows", r"c:\"],
2104 r"c:\windows;c:\"));
2105 assert!(test_eq(&["", r"c:\windows", "", "", r"c:\", ""],
2106 r";c:\windows;;;c:\;"));
2107 assert!(test_eq(&[r"c:\te;st", r"c:\"],
2108 r#""c:\te;st";c:\"#));
2109 assert!(join_paths(&[r#"c:\te"st"#]).is_err());
2112 // More recursive_mkdir tests are in extra::tempfile