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_docs)]
32 #![allow(non_snake_case)]
34 pub use self::MemoryMapKind::*;
35 pub use self::MapOption::*;
36 pub use self::MapError::*;
39 use error::{FromError, Error};
41 use io::{IoResult, IoError};
42 use iter::{Iterator, IteratorExt};
43 use libc::{c_void, c_int};
47 use option::{Some, None, Option};
49 use path::{Path, GenericPath, BytesContainer};
51 use sys::os as os_imp;
54 use result::{Err, Ok, Result};
55 use slice::{AsSlice, SlicePrelude, PartialEqSlicePrelude};
56 use slice::CloneSliceAllocPrelude;
57 use str::{Str, StrPrelude, StrAllocating};
58 use string::{String, ToString};
59 use sync::atomic::{AtomicInt, INIT_ATOMIC_INT, SeqCst};
62 #[cfg(unix)] use c_str::ToCStr;
63 #[cfg(unix)] use libc::c_char;
66 pub use sys::ext as unix;
68 pub use sys::ext as windows;
70 /// Get the number of cores available
71 pub fn num_cpus() -> uint {
73 return rust_get_num_cpus() as uint;
77 fn rust_get_num_cpus() -> libc::uintptr_t;
81 pub const TMPBUF_SZ : uint = 1000u;
82 const BUF_BYTES : uint = 2048u;
84 /// Returns the current working directory as a `Path`.
88 /// Returns an `Err` if the current working directory value is invalid.
91 /// * Current directory does not exist.
92 /// * There are insufficient permissions to access the current directory.
93 /// * The internal buffer is not large enough to hold the path.
100 /// // We assume that we are in a valid directory like "/home".
101 /// let current_working_directory = os::getcwd().unwrap();
102 /// println!("The current directory is {}", current_working_directory.display());
106 pub fn getcwd() -> IoResult<Path> {
109 let mut buf = [0 as c_char, ..BUF_BYTES];
111 if libc::getcwd(buf.as_mut_ptr(), buf.len() as libc::size_t).is_null() {
112 Err(IoError::last_error())
114 Ok(Path::new(CString::new(buf.as_ptr(), false)))
119 /// Returns the current working directory as a `Path`.
123 /// Returns an `Err` if the current working directory value is invalid.
126 /// * Current directory does not exist.
127 /// * There are insufficient permissions to access the current directory.
128 /// * The internal buffer is not large enough to hold the path.
135 /// // We assume that we are in a valid directory like "C:\\Windows".
136 /// let current_working_directory = os::getcwd().unwrap();
137 /// println!("The current directory is {}", current_working_directory.display());
141 pub fn getcwd() -> IoResult<Path> {
143 use libc::GetCurrentDirectoryW;
144 use io::OtherIoError;
146 let mut buf = [0 as u16, ..BUF_BYTES];
148 if libc::GetCurrentDirectoryW(buf.len() as DWORD, buf.as_mut_ptr()) == 0 as DWORD {
149 return Err(IoError::last_error());
153 match String::from_utf16(::str::truncate_utf16_at_nul(&buf)) {
154 Some(ref cwd) => Ok(Path::new(cwd)),
155 None => Err(IoError {
157 desc: "GetCurrentDirectoryW returned invalid UTF-16",
165 use libc::types::os::arch::extra::DWORD;
167 use option::{None, Option};
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::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 rustrt::mutex::{StaticNativeMutex, NATIVE_MUTEX_INIT};
218 static LOCK: StaticNativeMutex = NATIVE_MUTEX_INIT;
221 let _guard = LOCK.lock();
226 /// Returns a vector of (variable, value) pairs, for all the environment
227 /// variables of the current process.
229 /// Invalid UTF-8 bytes are replaced with \uFFFD. See `String::from_utf8_lossy()`
237 /// // We will iterate through the references to the element returned by os::env();
238 /// for &(ref key, ref value) in os::env().iter() {
239 /// println!("'{}': '{}'", key, value );
242 pub fn env() -> Vec<(String,String)> {
243 env_as_bytes().into_iter().map(|(k,v)| {
244 let k = String::from_utf8_lossy(k.as_slice()).into_string();
245 let v = String::from_utf8_lossy(v.as_slice()).into_string();
250 /// Returns a vector of (variable, value) byte-vector pairs for all the
251 /// environment variables of the current process.
252 pub fn env_as_bytes() -> Vec<(Vec<u8>,Vec<u8>)> {
255 unsafe fn get_env_pairs() -> Vec<Vec<u8>> {
258 use libc::funcs::extra::kernel32::{
259 GetEnvironmentStringsW,
260 FreeEnvironmentStringsW
262 let ch = GetEnvironmentStringsW();
264 panic!("os::env() failure getting env string from OS: {}",
265 os::last_os_error());
267 // Here, we lossily decode the string as UTF16.
269 // The docs suggest that the result should be in Unicode, but
270 // Windows doesn't guarantee it's actually UTF16 -- it doesn't
271 // validate the environment string passed to CreateProcess nor
272 // SetEnvironmentVariable. Yet, it's unlikely that returning a
273 // raw u16 buffer would be of practical use since the result would
274 // be inherently platform-dependent and introduce additional
275 // complexity to this code.
277 // Using the non-Unicode version of GetEnvironmentStrings is even
278 // worse since the result is in an OEM code page. Characters that
279 // can't be encoded in the code page would be turned into question
281 let mut result = Vec::new();
283 while *ch.offset(i) != 0 {
284 let p = &*ch.offset(i);
286 while *(p as *const _).offset(len) != 0 {
289 let p = p as *const u16;
290 let s = slice::from_raw_buf(&p, len as uint);
291 result.push(String::from_utf16_lossy(s).into_bytes());
294 FreeEnvironmentStringsW(ch);
298 unsafe fn get_env_pairs() -> Vec<Vec<u8>> {
302 fn rust_env_pairs() -> *const *const c_char;
304 let mut environ = rust_env_pairs();
305 if environ as uint == 0 {
306 panic!("os::env() failure getting env string from OS: {}",
307 os::last_os_error());
309 let mut result = Vec::new();
310 while *environ != 0 as *const _ {
312 CString::new(*environ, false).as_bytes_no_nul().to_vec();
313 result.push(env_pair);
314 environ = environ.offset(1);
319 fn env_convert(input: Vec<Vec<u8>>) -> Vec<(Vec<u8>, Vec<u8>)> {
320 let mut pairs = Vec::new();
321 for p in input.iter() {
322 let mut it = p.as_slice().splitn(1, |b| *b == b'=');
323 let key = it.next().unwrap().to_vec();
324 let default: &[u8] = &[];
325 let val = it.next().unwrap_or(default).to_vec();
326 pairs.push((key, val));
331 let unparsed_environ = get_env_pairs();
332 env_convert(unparsed_environ)
338 /// Fetches the environment variable `n` from the current process, returning
339 /// None if the variable isn't set.
341 /// Any invalid UTF-8 bytes in the value are replaced by \uFFFD. See
342 /// `String::from_utf8_lossy()` for details.
346 /// Panics if `n` has any interior NULs.
353 /// let key = "HOME";
354 /// match os::getenv(key) {
355 /// Some(val) => println!("{}: {}", key, val),
356 /// None => println!("{} is not defined in the environment.", key)
359 pub fn getenv(n: &str) -> Option<String> {
360 getenv_as_bytes(n).map(|v| String::from_utf8_lossy(v.as_slice()).into_string())
364 /// Fetches the environment variable `n` byte vector from the current process,
365 /// returning None if the variable isn't set.
369 /// Panics if `n` has any interior NULs.
370 pub fn getenv_as_bytes(n: &str) -> Option<Vec<u8>> {
375 let s = n.with_c_str(|buf| libc::getenv(buf));
379 Some(CString::new(s as *const i8, false).as_bytes_no_nul().to_vec())
386 /// Fetches the environment variable `n` from the current process, returning
387 /// None if the variable isn't set.
388 pub fn getenv(n: &str) -> Option<String> {
391 use os::windows::{fill_utf16_buf_and_decode};
392 let mut n: Vec<u16> = n.utf16_units().collect();
394 fill_utf16_buf_and_decode(|buf, sz| {
395 libc::GetEnvironmentVariableW(n.as_ptr(), buf, sz)
402 /// Fetches the environment variable `n` byte vector from the current process,
403 /// returning None if the variable isn't set.
404 pub fn getenv_as_bytes(n: &str) -> Option<Vec<u8>> {
405 getenv(n).map(|s| s.into_bytes())
408 /// Sets the environment variable `n` to the value `v` for the currently running
417 /// os::setenv(key, "VALUE");
418 /// match os::getenv(key) {
419 /// Some(ref val) => println!("{}: {}", key, val),
420 /// None => println!("{} is not defined in the environment.", key)
423 pub fn setenv<T: BytesContainer>(n: &str, v: T) {
425 fn _setenv(n: &str, v: &[u8]) {
428 n.with_c_str(|nbuf| {
429 v.with_c_str(|vbuf| {
430 if libc::funcs::posix01::unistd::setenv(nbuf, vbuf, 1) != 0 {
431 panic!(IoError::last_error());
440 fn _setenv(n: &str, v: &[u8]) {
441 let mut n: Vec<u16> = n.utf16_units().collect();
443 let mut v: Vec<u16> = ::str::from_utf8(v).unwrap().utf16_units().collect();
448 if libc::SetEnvironmentVariableW(n.as_ptr(), v.as_ptr()) == 0 {
449 panic!(IoError::last_error());
455 _setenv(n, v.container_as_bytes())
458 /// Remove a variable from the environment entirely.
459 pub fn unsetenv(n: &str) {
461 fn _unsetenv(n: &str) {
464 n.with_c_str(|nbuf| {
465 if libc::funcs::posix01::unistd::unsetenv(nbuf) != 0 {
466 panic!(IoError::last_error());
474 fn _unsetenv(n: &str) {
475 let mut n: Vec<u16> = n.utf16_units().collect();
479 if libc::SetEnvironmentVariableW(n.as_ptr(), ptr::null()) == 0 {
480 panic!(IoError::last_error());
489 /// Parses input according to platform conventions for the `PATH`
490 /// environment variable.
496 /// let key = "PATH";
497 /// match os::getenv_as_bytes(key) {
499 /// for path in os::split_paths(paths).iter() {
500 /// println!("'{}'", path.display());
503 /// None => println!("{} is not defined in the environment.", key)
506 pub fn split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> {
508 fn _split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> {
509 unparsed.container_as_bytes()
510 .split(|b| *b == b':')
516 fn _split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> {
517 // On Windows, the PATH environment variable is semicolon separated. Double
518 // quotes are used as a way of introducing literal semicolons (since
519 // c:\some;dir is a valid Windows path). Double quotes are not themselves
520 // permitted in path names, so there is no way to escape a double quote.
521 // Quoted regions can appear in arbitrary locations, so
523 // c:\foo;c:\som"e;di"r;c:\bar
525 // Should parse as [c:\foo, c:\some;dir, c:\bar].
527 // (The above is based on testing; there is no clear reference available
530 let mut parsed = Vec::new();
531 let mut in_progress = Vec::new();
532 let mut in_quote = false;
534 for b in unparsed.container_as_bytes().iter() {
536 b';' if !in_quote => {
537 parsed.push(Path::new(in_progress.as_slice()));
538 in_progress.truncate(0)
541 in_quote = !in_quote;
544 in_progress.push(*b);
548 parsed.push(Path::new(in_progress));
552 _split_paths(unparsed)
555 /// Joins a collection of `Path`s appropriately for the `PATH`
556 /// environment variable.
558 /// Returns a `Vec<u8>` on success, since `Path`s are not utf-8
559 /// encoded on all platforms.
561 /// Returns an `Err` (containing an error message) if one of the input
562 /// `Path`s contains an invalid character for constructing the `PATH`
563 /// variable (a double quote on Windows or a colon on Unix).
569 /// use std::path::Path;
571 /// let key = "PATH";
572 /// let mut paths = os::getenv_as_bytes(key).map_or(Vec::new(), os::split_paths);
573 /// paths.push(Path::new("/home/xyz/bin"));
574 /// os::setenv(key, os::join_paths(paths.as_slice()).unwrap());
576 pub fn join_paths<T: BytesContainer>(paths: &[T]) -> Result<Vec<u8>, &'static str> {
578 fn _join_paths<T: BytesContainer>(paths: &[T]) -> Result<Vec<u8>, &'static str> {
579 let mut joined = Vec::new();
582 for (i, path) in paths.iter().map(|p| p.container_as_bytes()).enumerate() {
583 if i > 0 { joined.push(sep) }
584 if path.contains(&b'"') {
585 return Err("path segment contains `\"`");
586 } else if path.contains(&sep) {
588 joined.push_all(path);
591 joined.push_all(path);
599 fn _join_paths<T: BytesContainer>(paths: &[T]) -> Result<Vec<u8>, &'static str> {
600 let mut joined = Vec::new();
603 for (i, path) in paths.iter().map(|p| p.container_as_bytes()).enumerate() {
604 if i > 0 { joined.push(sep) }
605 if path.contains(&sep) { return Err("path segment contains separator `:`") }
606 joined.push_all(path);
615 /// A low-level OS in-memory pipe.
617 /// A file descriptor representing the reading end of the pipe. Data written
618 /// on the `out` file descriptor can be read from this file descriptor.
620 /// A file descriptor representing the write end of the pipe. Data written
621 /// to this file descriptor can be read from the `input` file descriptor.
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,
1191 /// Type of memory map
1192 pub enum MemoryMapKind {
1193 /// Virtual memory map. Usually used to change the permissions of a given
1194 /// chunk of memory. Corresponds to `VirtualAlloc` on Windows.
1196 /// Virtual memory map. Usually used to change the permissions of a given
1197 /// chunk of memory, or for allocation. Corresponds to `VirtualAlloc` on
1202 /// Options the memory map is created with
1203 pub enum MapOption {
1204 /// The memory should be readable
1206 /// The memory should be writable
1208 /// The memory should be executable
1210 /// Create a map for a specific address range. Corresponds to `MAP_FIXED` on
1213 /// Create a memory mapping for a file with a given fd.
1215 /// When using `MapFd`, the start of the map is `uint` bytes from the start
1218 /// On POSIX, this can be used to specify the default flags passed to
1219 /// `mmap`. By default it uses `MAP_PRIVATE` and, if not using `MapFd`,
1220 /// `MAP_ANON`. This will override both of those. This is platform-specific
1221 /// (the exact values used) and ignored on Windows.
1222 MapNonStandardFlags(c_int),
1225 /// Possible errors when creating a map.
1227 /// ## The following are POSIX-specific
1229 /// fd was not open for reading or, if using `MapWritable`, was not open for
1232 /// fd was not valid
1234 /// Either the address given by `MapAddr` or offset given by `MapOffset` was
1235 /// not a multiple of `MemoryMap::granularity` (unaligned to page size).
1237 /// With `MapFd`, the fd does not support mapping.
1239 /// If using `MapAddr`, the address + `min_len` was outside of the process's
1240 /// address space. If using `MapFd`, the target of the fd didn't have enough
1241 /// resources to fulfill the request.
1243 /// A zero-length map was requested. This is invalid according to
1244 /// [POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/functions/mmap.html).
1245 /// Not all platforms obey this, but this wrapper does.
1247 /// Unrecognized error. The inner value is the unrecognized errno.
1249 /// ## The following are Windows-specific
1251 /// Unsupported combination of protection flags
1252 /// (`MapReadable`/`MapWritable`/`MapExecutable`).
1254 /// When using `MapFd`, `MapOffset` was given (Windows does not support this
1257 /// When using `MapFd`, there was already a mapping to the file.
1259 /// Unrecognized error from `VirtualAlloc`. The inner value is the return
1260 /// value of GetLastError.
1261 ErrVirtualAlloc(uint),
1262 /// Unrecognized error from `CreateFileMapping`. The inner value is the
1263 /// return value of `GetLastError`.
1264 ErrCreateFileMappingW(uint),
1265 /// Unrecognized error from `MapViewOfFile`. The inner value is the return
1266 /// value of `GetLastError`.
1267 ErrMapViewOfFile(uint)
1270 impl fmt::Show for MapError {
1271 fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result {
1272 let str = match *self {
1273 ErrFdNotAvail => "fd not available for reading or writing",
1274 ErrInvalidFd => "Invalid fd",
1276 "Unaligned address, invalid flags, negative length or \
1279 ErrNoMapSupport=> "File doesn't support mapping",
1280 ErrNoMem => "Invalid address, or not enough available memory",
1281 ErrUnsupProt => "Protection mode unsupported",
1282 ErrUnsupOffset => "Offset in virtual memory mode is unsupported",
1283 ErrAlreadyExists => "File mapping for specified file already exists",
1284 ErrZeroLength => "Zero-length mapping not allowed",
1285 ErrUnknown(code) => {
1286 return write!(out, "Unknown error = {}", code)
1288 ErrVirtualAlloc(code) => {
1289 return write!(out, "VirtualAlloc failure = {}", code)
1291 ErrCreateFileMappingW(code) => {
1292 return write!(out, "CreateFileMappingW failure = {}", code)
1294 ErrMapViewOfFile(code) => {
1295 return write!(out, "MapViewOfFile failure = {}", code)
1298 write!(out, "{}", str)
1302 impl Error for MapError {
1303 fn description(&self) -> &str { "memory map error" }
1304 fn detail(&self) -> Option<String> { Some(self.to_string()) }
1307 impl FromError<MapError> for Box<Error> {
1308 fn from_error(err: MapError) -> Box<Error> {
1315 /// Create a new mapping with the given `options`, at least `min_len` bytes
1316 /// long. `min_len` must be greater than zero; see the note on
1317 /// `ErrZeroLength`.
1318 pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
1322 return Err(ErrZeroLength)
1324 let mut addr: *const u8 = ptr::null();
1326 let mut flags = libc::MAP_PRIVATE;
1329 let mut custom_flags = false;
1330 let len = round_up(min_len, page_size());
1332 for &o in options.iter() {
1334 MapReadable => { prot |= libc::PROT_READ; },
1335 MapWritable => { prot |= libc::PROT_WRITE; },
1336 MapExecutable => { prot |= libc::PROT_EXEC; },
1338 flags |= libc::MAP_FIXED;
1342 flags |= libc::MAP_FILE;
1345 MapOffset(offset_) => { offset = offset_ as off_t; },
1346 MapNonStandardFlags(f) => { custom_flags = true; flags = f },
1349 if fd == -1 && !custom_flags { flags |= libc::MAP_ANON; }
1352 libc::mmap(addr as *mut c_void, len as libc::size_t, prot, flags,
1355 if r == libc::MAP_FAILED {
1356 Err(match errno() as c_int {
1357 libc::EACCES => ErrFdNotAvail,
1358 libc::EBADF => ErrInvalidFd,
1359 libc::EINVAL => ErrUnaligned,
1360 libc::ENODEV => ErrNoMapSupport,
1361 libc::ENOMEM => ErrNoMem,
1362 code => ErrUnknown(code as int)
1371 MapFile(ptr::null())
1377 /// Granularity that the offset or address must be for `MapOffset` and
1378 /// `MapAddr` respectively.
1379 pub fn granularity() -> uint {
1385 impl Drop for MemoryMap {
1386 /// Unmap the mapping. Panics the task if `munmap` panics.
1387 fn drop(&mut self) {
1388 if self.len == 0 { /* workaround for dummy_stack */ return; }
1391 // `munmap` only panics due to logic errors
1392 libc::munmap(self.data as *mut c_void, self.len as libc::size_t);
1399 /// Create a new mapping with the given `options`, at least `min_len` bytes long.
1400 pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
1401 use libc::types::os::arch::extra::{LPVOID, DWORD, SIZE_T, HANDLE};
1403 let mut lpAddress: LPVOID = ptr::null_mut();
1404 let mut readable = false;
1405 let mut writable = false;
1406 let mut executable = false;
1407 let mut fd: c_int = -1;
1408 let mut offset: uint = 0;
1409 let len = round_up(min_len, page_size());
1411 for &o in options.iter() {
1413 MapReadable => { readable = true; },
1414 MapWritable => { writable = true; },
1415 MapExecutable => { executable = true; }
1416 MapAddr(addr_) => { lpAddress = addr_ as LPVOID; },
1417 MapFd(fd_) => { fd = fd_; },
1418 MapOffset(offset_) => { offset = offset_; },
1419 MapNonStandardFlags(..) => {}
1423 let flProtect = match (executable, readable, writable) {
1424 (false, false, false) if fd == -1 => libc::PAGE_NOACCESS,
1425 (false, true, false) => libc::PAGE_READONLY,
1426 (false, true, true) => libc::PAGE_READWRITE,
1427 (true, false, false) if fd == -1 => libc::PAGE_EXECUTE,
1428 (true, true, false) => libc::PAGE_EXECUTE_READ,
1429 (true, true, true) => libc::PAGE_EXECUTE_READWRITE,
1430 _ => return Err(ErrUnsupProt)
1435 return Err(ErrUnsupOffset);
1438 libc::VirtualAlloc(lpAddress,
1440 libc::MEM_COMMIT | libc::MEM_RESERVE,
1444 0 => Err(ErrVirtualAlloc(errno())),
1452 let dwDesiredAccess = match (executable, readable, writable) {
1453 (false, true, false) => libc::FILE_MAP_READ,
1454 (false, true, true) => libc::FILE_MAP_WRITE,
1455 (true, true, false) => libc::FILE_MAP_READ | libc::FILE_MAP_EXECUTE,
1456 (true, true, true) => libc::FILE_MAP_WRITE | libc::FILE_MAP_EXECUTE,
1457 _ => return Err(ErrUnsupProt) // Actually, because of the check above,
1458 // we should never get here.
1461 let hFile = libc::get_osfhandle(fd) as HANDLE;
1462 let mapping = libc::CreateFileMappingW(hFile,
1468 if mapping == ptr::null_mut() {
1469 return Err(ErrCreateFileMappingW(errno()));
1471 if errno() as c_int == libc::ERROR_ALREADY_EXISTS {
1472 return Err(ErrAlreadyExists);
1474 let r = libc::MapViewOfFile(mapping,
1476 ((len as u64) >> 32) as DWORD,
1477 (offset & 0xffff_ffff) as DWORD,
1480 0 => Err(ErrMapViewOfFile(errno())),
1484 kind: MapFile(mapping as *const u8)
1491 /// Granularity of MapAddr() and MapOffset() parameter values.
1492 /// This may be greater than the value returned by page_size().
1493 pub fn granularity() -> uint {
1496 let mut info = mem::zeroed();
1497 libc::GetSystemInfo(&mut info);
1499 return info.dwAllocationGranularity as uint;
1505 impl Drop for MemoryMap {
1506 /// Unmap the mapping. Panics the task if any of `VirtualFree`,
1507 /// `UnmapViewOfFile`, or `CloseHandle` fail.
1508 fn drop(&mut self) {
1509 use libc::types::os::arch::extra::{LPCVOID, HANDLE};
1510 use libc::consts::os::extra::FALSE;
1511 if self.len == 0 { return }
1516 if libc::VirtualFree(self.data as *mut c_void, 0,
1517 libc::MEM_RELEASE) == 0 {
1518 println!("VirtualFree failed: {}", errno());
1521 MapFile(mapping) => {
1522 if libc::UnmapViewOfFile(self.data as LPCVOID) == FALSE {
1523 println!("UnmapViewOfFile failed: {}", errno());
1525 if libc::CloseHandle(mapping as HANDLE) == FALSE {
1526 println!("CloseHandle failed: {}", errno());
1535 /// Returns the pointer to the memory created or modified by this map.
1536 pub fn data(&self) -> *mut u8 { self.data }
1537 /// Returns the number of bytes this map applies to.
1538 pub fn len(&self) -> uint { self.len }
1539 /// Returns the type of mapping this represents.
1540 pub fn kind(&self) -> MemoryMapKind { self.kind }
1543 #[cfg(target_os = "linux")]
1545 pub use os::arch_consts::ARCH;
1547 pub const FAMILY: &'static str = "unix";
1549 /// A string describing the specific operating system in use: in this
1551 pub const SYSNAME: &'static str = "linux";
1553 /// Specifies the filename prefix used for shared libraries on this
1554 /// platform: in this case, `lib`.
1555 pub const DLL_PREFIX: &'static str = "lib";
1557 /// Specifies the filename suffix used for shared libraries on this
1558 /// platform: in this case, `.so`.
1559 pub const DLL_SUFFIX: &'static str = ".so";
1561 /// Specifies the file extension used for shared libraries on this
1562 /// platform that goes after the dot: in this case, `so`.
1563 pub const DLL_EXTENSION: &'static str = "so";
1565 /// Specifies the filename suffix used for executable binaries on this
1566 /// platform: in this case, the empty string.
1567 pub const EXE_SUFFIX: &'static str = "";
1569 /// Specifies the file extension, if any, used for executable binaries
1570 /// on this platform: in this case, the empty string.
1571 pub const EXE_EXTENSION: &'static str = "";
1574 #[cfg(target_os = "macos")]
1576 pub use os::arch_consts::ARCH;
1578 pub const FAMILY: &'static str = "unix";
1580 /// A string describing the specific operating system in use: in this
1582 pub const SYSNAME: &'static str = "macos";
1584 /// Specifies the filename prefix used for shared libraries on this
1585 /// platform: in this case, `lib`.
1586 pub const DLL_PREFIX: &'static str = "lib";
1588 /// Specifies the filename suffix used for shared libraries on this
1589 /// platform: in this case, `.dylib`.
1590 pub const DLL_SUFFIX: &'static str = ".dylib";
1592 /// Specifies the file extension used for shared libraries on this
1593 /// platform that goes after the dot: in this case, `dylib`.
1594 pub const DLL_EXTENSION: &'static str = "dylib";
1596 /// Specifies the filename suffix used for executable binaries on this
1597 /// platform: in this case, the empty string.
1598 pub const EXE_SUFFIX: &'static str = "";
1600 /// Specifies the file extension, if any, used for executable binaries
1601 /// on this platform: in this case, the empty string.
1602 pub const EXE_EXTENSION: &'static str = "";
1605 #[cfg(target_os = "ios")]
1607 pub use os::arch_consts::ARCH;
1609 pub const FAMILY: &'static str = "unix";
1611 /// A string describing the specific operating system in use: in this
1613 pub const SYSNAME: &'static str = "ios";
1615 /// Specifies the filename suffix used for executable binaries on this
1616 /// platform: in this case, the empty string.
1617 pub const EXE_SUFFIX: &'static str = "";
1619 /// Specifies the file extension, if any, used for executable binaries
1620 /// on this platform: in this case, the empty string.
1621 pub const EXE_EXTENSION: &'static str = "";
1624 #[cfg(target_os = "freebsd")]
1626 pub use os::arch_consts::ARCH;
1628 pub const FAMILY: &'static str = "unix";
1630 /// A string describing the specific operating system in use: in this
1631 /// case, `freebsd`.
1632 pub const SYSNAME: &'static str = "freebsd";
1634 /// Specifies the filename prefix used for shared libraries on this
1635 /// platform: in this case, `lib`.
1636 pub const DLL_PREFIX: &'static str = "lib";
1638 /// Specifies the filename suffix used for shared libraries on this
1639 /// platform: in this case, `.so`.
1640 pub const DLL_SUFFIX: &'static str = ".so";
1642 /// Specifies the file extension used for shared libraries on this
1643 /// platform that goes after the dot: in this case, `so`.
1644 pub const DLL_EXTENSION: &'static str = "so";
1646 /// Specifies the filename suffix used for executable binaries on this
1647 /// platform: in this case, the empty string.
1648 pub const EXE_SUFFIX: &'static str = "";
1650 /// Specifies the file extension, if any, used for executable binaries
1651 /// on this platform: in this case, the empty string.
1652 pub const EXE_EXTENSION: &'static str = "";
1655 #[cfg(target_os = "dragonfly")]
1657 pub use os::arch_consts::ARCH;
1659 pub const FAMILY: &'static str = "unix";
1661 /// A string describing the specific operating system in use: in this
1662 /// case, `dragonfly`.
1663 pub const SYSNAME: &'static str = "dragonfly";
1665 /// Specifies the filename prefix used for shared libraries on this
1666 /// platform: in this case, `lib`.
1667 pub const DLL_PREFIX: &'static str = "lib";
1669 /// Specifies the filename suffix used for shared libraries on this
1670 /// platform: in this case, `.so`.
1671 pub const DLL_SUFFIX: &'static str = ".so";
1673 /// Specifies the file extension used for shared libraries on this
1674 /// platform that goes after the dot: in this case, `so`.
1675 pub const DLL_EXTENSION: &'static str = "so";
1677 /// Specifies the filename suffix used for executable binaries on this
1678 /// platform: in this case, the empty string.
1679 pub const EXE_SUFFIX: &'static str = "";
1681 /// Specifies the file extension, if any, used for executable binaries
1682 /// on this platform: in this case, the empty string.
1683 pub const EXE_EXTENSION: &'static str = "";
1686 #[cfg(target_os = "android")]
1688 pub use os::arch_consts::ARCH;
1690 pub const FAMILY: &'static str = "unix";
1692 /// A string describing the specific operating system in use: in this
1693 /// case, `android`.
1694 pub const SYSNAME: &'static str = "android";
1696 /// Specifies the filename prefix used for shared libraries on this
1697 /// platform: in this case, `lib`.
1698 pub const DLL_PREFIX: &'static str = "lib";
1700 /// Specifies the filename suffix used for shared libraries on this
1701 /// platform: in this case, `.so`.
1702 pub const DLL_SUFFIX: &'static str = ".so";
1704 /// Specifies the file extension used for shared libraries on this
1705 /// platform that goes after the dot: in this case, `so`.
1706 pub const DLL_EXTENSION: &'static str = "so";
1708 /// Specifies the filename suffix used for executable binaries on this
1709 /// platform: in this case, the empty string.
1710 pub const EXE_SUFFIX: &'static str = "";
1712 /// Specifies the file extension, if any, used for executable binaries
1713 /// on this platform: in this case, the empty string.
1714 pub const EXE_EXTENSION: &'static str = "";
1717 #[cfg(target_os = "windows")]
1719 pub use os::arch_consts::ARCH;
1721 pub const FAMILY: &'static str = "windows";
1723 /// A string describing the specific operating system in use: in this
1724 /// case, `windows`.
1725 pub const SYSNAME: &'static str = "windows";
1727 /// Specifies the filename prefix used for shared libraries on this
1728 /// platform: in this case, the empty string.
1729 pub const DLL_PREFIX: &'static str = "";
1731 /// Specifies the filename suffix used for shared libraries on this
1732 /// platform: in this case, `.dll`.
1733 pub const DLL_SUFFIX: &'static str = ".dll";
1735 /// Specifies the file extension used for shared libraries on this
1736 /// platform that goes after the dot: in this case, `dll`.
1737 pub const DLL_EXTENSION: &'static str = "dll";
1739 /// Specifies the filename suffix used for executable binaries on this
1740 /// platform: in this case, `.exe`.
1741 pub const EXE_SUFFIX: &'static str = ".exe";
1743 /// Specifies the file extension, if any, used for executable binaries
1744 /// on this platform: in this case, `exe`.
1745 pub const EXE_EXTENSION: &'static str = "exe";
1748 #[cfg(target_arch = "x86")]
1750 pub const ARCH: &'static str = "x86";
1753 #[cfg(target_arch = "x86_64")]
1755 pub const ARCH: &'static str = "x86_64";
1758 #[cfg(target_arch = "arm")]
1760 pub const ARCH: &'static str = "arm";
1763 #[cfg(target_arch = "mips")]
1765 pub const ARCH: &'static str = "mips";
1768 #[cfg(target_arch = "mipsel")]
1770 pub const ARCH: &'static str = "mipsel";
1778 use os::{env, getcwd, getenv, make_absolute};
1779 use os::{split_paths, join_paths, setenv, unsetenv};
1785 pub fn last_os_error() {
1786 debug!("{}", os::last_os_error());
1789 fn make_rand_name() -> String {
1790 let mut rng = rand::task_rng();
1791 let n = format!("TEST{}", rng.gen_ascii_chars().take(10u)
1792 .collect::<String>());
1793 assert!(getenv(n.as_slice()).is_none());
1798 fn test_num_cpus() {
1799 assert!(os::num_cpus() > 0);
1804 let n = make_rand_name();
1805 setenv(n.as_slice(), "VALUE");
1806 assert_eq!(getenv(n.as_slice()), option::Some("VALUE".to_string()));
1810 fn test_unsetenv() {
1811 let n = make_rand_name();
1812 setenv(n.as_slice(), "VALUE");
1813 unsetenv(n.as_slice());
1814 assert_eq!(getenv(n.as_slice()), option::None);
1819 fn test_setenv_overwrite() {
1820 let n = make_rand_name();
1821 setenv(n.as_slice(), "1");
1822 setenv(n.as_slice(), "2");
1823 assert_eq!(getenv(n.as_slice()), option::Some("2".to_string()));
1824 setenv(n.as_slice(), "");
1825 assert_eq!(getenv(n.as_slice()), option::Some("".to_string()));
1828 // Windows GetEnvironmentVariable requires some extra work to make sure
1829 // the buffer the variable is copied into is the right size
1832 fn test_getenv_big() {
1833 let mut s = "".to_string();
1836 s.push_str("aaaaaaaaaa");
1839 let n = make_rand_name();
1840 setenv(n.as_slice(), s.as_slice());
1841 debug!("{}", s.clone());
1842 assert_eq!(getenv(n.as_slice()), option::Some(s));
1846 fn test_self_exe_name() {
1847 let path = os::self_exe_name();
1848 assert!(path.is_some());
1849 let path = path.unwrap();
1850 debug!("{}", path.display());
1852 // Hard to test this function
1853 assert!(path.is_absolute());
1857 fn test_self_exe_path() {
1858 let path = os::self_exe_path();
1859 assert!(path.is_some());
1860 let path = path.unwrap();
1861 debug!("{}", path.display());
1863 // Hard to test this function
1864 assert!(path.is_absolute());
1869 fn test_env_getenv() {
1871 assert!(e.len() > 0u);
1873 let (n, v) = (*p).clone();
1875 let v2 = getenv(n.as_slice());
1876 // MingW seems to set some funky environment variables like
1877 // "=C:=C:\MinGW\msys\1.0\bin" and "!::=::\" that are returned
1878 // from env() but not visible from getenv().
1879 assert!(v2.is_none() || v2 == option::Some(v));
1884 fn test_env_set_get_huge() {
1885 let n = make_rand_name();
1886 let s = "x".repeat(10000).to_string();
1887 setenv(n.as_slice(), s.as_slice());
1888 assert_eq!(getenv(n.as_slice()), Some(s));
1889 unsetenv(n.as_slice());
1890 assert_eq!(getenv(n.as_slice()), None);
1894 fn test_env_setenv() {
1895 let n = make_rand_name();
1898 setenv(n.as_slice(), "VALUE");
1899 assert!(!e.contains(&(n.clone(), "VALUE".to_string())));
1902 assert!(e.contains(&(n, "VALUE".to_string())));
1907 assert!((!Path::new("test-path").is_absolute()));
1909 let cwd = getcwd().unwrap();
1910 debug!("Current working directory: {}", cwd.display());
1912 debug!("{}", make_absolute(&Path::new("test-path")).unwrap().display());
1913 debug!("{}", make_absolute(&Path::new("/usr/bin")).unwrap().display());
1919 let oldhome = getenv("HOME");
1921 setenv("HOME", "/home/MountainView");
1922 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1925 assert!(os::homedir().is_none());
1927 for s in oldhome.iter() {
1928 setenv("HOME", s.as_slice());
1936 let oldhome = getenv("HOME");
1937 let olduserprofile = getenv("USERPROFILE");
1940 setenv("USERPROFILE", "");
1942 assert!(os::homedir().is_none());
1944 setenv("HOME", "/home/MountainView");
1945 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1949 setenv("USERPROFILE", "/home/MountainView");
1950 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1952 setenv("HOME", "/home/MountainView");
1953 setenv("USERPROFILE", "/home/PaloAlto");
1954 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1956 for s in oldhome.iter() {
1957 setenv("HOME", s.as_slice());
1959 for s in olduserprofile.iter() {
1960 setenv("USERPROFILE", s.as_slice());
1965 fn memory_map_rw() {
1966 use result::{Ok, Err};
1968 let chunk = match os::MemoryMap::new(16, &[
1973 Err(msg) => panic!("{}", msg)
1975 assert!(chunk.len >= 16);
1979 assert!(*chunk.data == 0xBE);
1984 fn memory_map_file() {
1985 use result::{Ok, Err};
1991 fn lseek_(fd: c_int, size: uint) {
1993 assert!(lseek(fd, size as off_t, SEEK_SET) == size as off_t);
1997 fn lseek_(fd: c_int, size: uint) {
1999 assert!(lseek(fd, size as c_long, SEEK_SET) == size as c_long);
2003 let mut path = tmpdir();
2004 path.push("mmap_file.tmp");
2005 let size = MemoryMap::granularity() * 2;
2008 let fd = path.with_c_str(|path| {
2009 open(path, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR)
2012 "x".with_c_str(|x| assert!(write(fd, x as *const c_void, 1) == 1));
2015 let chunk = match MemoryMap::new(size / 2, &[
2022 Err(msg) => panic!("{}", msg)
2024 assert!(chunk.len > 0);
2028 assert!(*chunk.data == 0xbe);
2033 fs::unlink(&path).unwrap();
2038 fn split_paths_windows() {
2039 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
2040 split_paths(unparsed) ==
2041 parsed.iter().map(|s| Path::new(*s)).collect()
2044 assert!(check_parse("", &mut [""]));
2045 assert!(check_parse(r#""""#, &mut [""]));
2046 assert!(check_parse(";;", &mut ["", "", ""]));
2047 assert!(check_parse(r"c:\", &mut [r"c:\"]));
2048 assert!(check_parse(r"c:\;", &mut [r"c:\", ""]));
2049 assert!(check_parse(r"c:\;c:\Program Files\",
2050 &mut [r"c:\", r"c:\Program Files\"]));
2051 assert!(check_parse(r#"c:\;c:\"foo"\"#, &mut [r"c:\", r"c:\foo\"]));
2052 assert!(check_parse(r#"c:\;c:\"foo;bar"\;c:\baz"#,
2053 &mut [r"c:\", r"c:\foo;bar\", r"c:\baz"]));
2058 fn split_paths_unix() {
2059 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
2060 split_paths(unparsed) ==
2061 parsed.iter().map(|s| Path::new(*s)).collect()
2064 assert!(check_parse("", &mut [""]));
2065 assert!(check_parse("::", &mut ["", "", ""]));
2066 assert!(check_parse("/", &mut ["/"]));
2067 assert!(check_parse("/:", &mut ["/", ""]));
2068 assert!(check_parse("/:/usr/local", &mut ["/", "/usr/local"]));
2073 fn join_paths_unix() {
2074 fn test_eq(input: &[&str], output: &str) -> bool {
2075 join_paths(input).unwrap().as_slice() == output.as_bytes()
2078 assert!(test_eq(&[], ""));
2079 assert!(test_eq(&["/bin", "/usr/bin", "/usr/local/bin"],
2080 "/bin:/usr/bin:/usr/local/bin"));
2081 assert!(test_eq(&["", "/bin", "", "", "/usr/bin", ""],
2082 ":/bin:::/usr/bin:"));
2083 assert!(join_paths(&["/te:st"]).is_err());
2088 fn join_paths_windows() {
2089 fn test_eq(input: &[&str], output: &str) -> bool {
2090 join_paths(input).unwrap().as_slice() == output.as_bytes()
2093 assert!(test_eq(&[], ""));
2094 assert!(test_eq(&[r"c:\windows", r"c:\"],
2095 r"c:\windows;c:\"));
2096 assert!(test_eq(&["", r"c:\windows", "", "", r"c:\", ""],
2097 r";c:\windows;;;c:\;"));
2098 assert!(test_eq(&[r"c:\te;st", r"c:\"],
2099 r#""c:\te;st";c:\"#));
2100 assert!(join_paths(&[r#"c:\te"st"#]).is_err());
2103 // More recursive_mkdir tests are in extra::tempfile