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};
39 use libc::{c_void, c_int};
44 use option::Option::{Some, None};
46 use path::{Path, GenericPath, BytesContainer};
48 use sys::os as os_imp;
52 use result::Result::{Err, Ok};
53 use slice::{AsSlice, SlicePrelude, PartialEqSlicePrelude};
54 use slice::CloneSliceAllocPrelude;
55 use str::{Str, StrPrelude, StrAllocating};
56 use string::{String, ToString};
57 use sync::atomic::{AtomicInt, INIT_ATOMIC_INT, SeqCst};
60 #[cfg(unix)] use c_str::ToCStr;
61 #[cfg(unix)] use libc::c_char;
64 pub use sys::ext as unix;
66 pub use sys::ext as windows;
68 /// Get the number of cores available
69 pub fn num_cpus() -> uint {
71 return rust_get_num_cpus() as uint;
75 fn rust_get_num_cpus() -> libc::uintptr_t;
79 pub const TMPBUF_SZ : uint = 1000u;
80 const BUF_BYTES : uint = 2048u;
82 /// Returns the current working directory as a `Path`.
86 /// Returns an `Err` if the current working directory value is invalid.
89 /// * Current directory does not exist.
90 /// * There are insufficient permissions to access the current directory.
91 /// * The internal buffer is not large enough to hold the path.
98 /// // We assume that we are in a valid directory like "/home".
99 /// let current_working_directory = os::getcwd().unwrap();
100 /// println!("The current directory is {}", current_working_directory.display());
104 pub fn getcwd() -> IoResult<Path> {
107 let mut buf = [0 as c_char, ..BUF_BYTES];
109 if libc::getcwd(buf.as_mut_ptr(), buf.len() as libc::size_t).is_null() {
110 Err(IoError::last_error())
112 Ok(Path::new(CString::new(buf.as_ptr(), false)))
117 /// Returns the current working directory as a `Path`.
121 /// Returns an `Err` if the current working directory value is invalid.
124 /// * Current directory does not exist.
125 /// * There are insufficient permissions to access the current directory.
126 /// * The internal buffer is not large enough to hold the path.
133 /// // We assume that we are in a valid directory like "C:\\Windows".
134 /// let current_working_directory = os::getcwd().unwrap();
135 /// println!("The current directory is {}", current_working_directory.display());
139 pub fn getcwd() -> IoResult<Path> {
141 use libc::GetCurrentDirectoryW;
142 use io::OtherIoError;
144 let mut buf = [0 as u16, ..BUF_BYTES];
146 if libc::GetCurrentDirectoryW(buf.len() as DWORD, buf.as_mut_ptr()) == 0 as DWORD {
147 return Err(IoError::last_error());
151 match String::from_utf16(::str::truncate_utf16_at_nul(&buf)) {
152 Some(ref cwd) => Ok(Path::new(cwd)),
153 None => Err(IoError {
155 desc: "GetCurrentDirectoryW returned invalid UTF-16",
163 use libc::types::os::arch::extra::DWORD;
166 use option::Option::None;
169 use slice::{SlicePrelude};
174 pub fn fill_utf16_buf_and_decode(f: |*mut u16, DWORD| -> DWORD)
178 let mut n = TMPBUF_SZ as DWORD;
180 let mut done = false;
182 let mut buf = Vec::from_elem(n as uint, 0u16);
183 let k = f(buf.as_mut_ptr(), n);
184 if k == (0 as DWORD) {
187 libc::GetLastError() ==
188 libc::ERROR_INSUFFICIENT_BUFFER as DWORD {
196 let sub = buf.slice(0, k as uint);
197 // We want to explicitly catch the case when the
198 // closure returned invalid UTF-16, rather than
199 // set `res` to None and continue.
200 let s = String::from_utf16(sub)
201 .expect("fill_utf16_buf_and_decode: closure created invalid UTF-16");
202 res = option::Option::Some(s)
211 Accessing environment variables is not generally threadsafe.
212 Serialize access through a global lock.
214 fn with_env_lock<T>(f: || -> T) -> T {
215 use sync::{StaticMutex, MUTEX_INIT};
217 static LOCK: StaticMutex = MUTEX_INIT;
219 let _guard = LOCK.lock();
223 /// Returns a vector of (variable, value) pairs, for all the environment
224 /// variables of the current process.
226 /// Invalid UTF-8 bytes are replaced with \uFFFD. See `String::from_utf8_lossy()`
234 /// // We will iterate through the references to the element returned by os::env();
235 /// for &(ref key, ref value) in os::env().iter() {
236 /// println!("'{}': '{}'", key, value );
239 pub fn env() -> Vec<(String,String)> {
240 env_as_bytes().into_iter().map(|(k,v)| {
241 let k = String::from_utf8_lossy(k.as_slice()).into_string();
242 let v = String::from_utf8_lossy(v.as_slice()).into_string();
247 /// Returns a vector of (variable, value) byte-vector pairs for all the
248 /// environment variables of the current process.
249 pub fn env_as_bytes() -> Vec<(Vec<u8>,Vec<u8>)> {
252 unsafe fn get_env_pairs() -> Vec<Vec<u8>> {
255 use libc::funcs::extra::kernel32::{
256 GetEnvironmentStringsW,
257 FreeEnvironmentStringsW
259 let ch = GetEnvironmentStringsW();
261 panic!("os::env() failure getting env string from OS: {}",
262 os::last_os_error());
264 // Here, we lossily decode the string as UTF16.
266 // The docs suggest that the result should be in Unicode, but
267 // Windows doesn't guarantee it's actually UTF16 -- it doesn't
268 // validate the environment string passed to CreateProcess nor
269 // SetEnvironmentVariable. Yet, it's unlikely that returning a
270 // raw u16 buffer would be of practical use since the result would
271 // be inherently platform-dependent and introduce additional
272 // complexity to this code.
274 // Using the non-Unicode version of GetEnvironmentStrings is even
275 // worse since the result is in an OEM code page. Characters that
276 // can't be encoded in the code page would be turned into question
278 let mut result = Vec::new();
280 while *ch.offset(i) != 0 {
281 let p = &*ch.offset(i);
283 while *(p as *const _).offset(len) != 0 {
286 let p = p as *const u16;
287 let s = slice::from_raw_buf(&p, len as uint);
288 result.push(String::from_utf16_lossy(s).into_bytes());
291 FreeEnvironmentStringsW(ch);
295 unsafe fn get_env_pairs() -> Vec<Vec<u8>> {
299 fn rust_env_pairs() -> *const *const c_char;
301 let mut environ = rust_env_pairs();
302 if environ as uint == 0 {
303 panic!("os::env() failure getting env string from OS: {}",
304 os::last_os_error());
306 let mut result = Vec::new();
307 while *environ != 0 as *const _ {
309 CString::new(*environ, false).as_bytes_no_nul().to_vec();
310 result.push(env_pair);
311 environ = environ.offset(1);
316 fn env_convert(input: Vec<Vec<u8>>) -> Vec<(Vec<u8>, Vec<u8>)> {
317 let mut pairs = Vec::new();
318 for p in input.iter() {
319 let mut it = p.as_slice().splitn(1, |b| *b == b'=');
320 let key = it.next().unwrap().to_vec();
321 let default: &[u8] = &[];
322 let val = it.next().unwrap_or(default).to_vec();
323 pairs.push((key, val));
328 let unparsed_environ = get_env_pairs();
329 env_convert(unparsed_environ)
335 /// Fetches the environment variable `n` from the current process, returning
336 /// None if the variable isn't set.
338 /// Any invalid UTF-8 bytes in the value are replaced by \uFFFD. See
339 /// `String::from_utf8_lossy()` for details.
343 /// Panics if `n` has any interior NULs.
350 /// let key = "HOME";
351 /// match os::getenv(key) {
352 /// Some(val) => println!("{}: {}", key, val),
353 /// None => println!("{} is not defined in the environment.", key)
356 pub fn getenv(n: &str) -> Option<String> {
357 getenv_as_bytes(n).map(|v| String::from_utf8_lossy(v.as_slice()).into_string())
361 /// Fetches the environment variable `n` byte vector from the current process,
362 /// returning None if the variable isn't set.
366 /// Panics if `n` has any interior NULs.
367 pub fn getenv_as_bytes(n: &str) -> Option<Vec<u8>> {
372 let s = n.with_c_str(|buf| libc::getenv(buf));
376 Some(CString::new(s as *const i8, false).as_bytes_no_nul().to_vec())
383 /// Fetches the environment variable `n` from the current process, returning
384 /// None if the variable isn't set.
385 pub fn getenv(n: &str) -> Option<String> {
388 use os::windows::{fill_utf16_buf_and_decode};
389 let mut n: Vec<u16> = n.utf16_units().collect();
391 fill_utf16_buf_and_decode(|buf, sz| {
392 libc::GetEnvironmentVariableW(n.as_ptr(), buf, sz)
399 /// Fetches the environment variable `n` byte vector from the current process,
400 /// returning None if the variable isn't set.
401 pub fn getenv_as_bytes(n: &str) -> Option<Vec<u8>> {
402 getenv(n).map(|s| s.into_bytes())
405 /// Sets the environment variable `n` to the value `v` for the currently running
414 /// os::setenv(key, "VALUE");
415 /// match os::getenv(key) {
416 /// Some(ref val) => println!("{}: {}", key, val),
417 /// None => println!("{} is not defined in the environment.", key)
420 pub fn setenv<T: BytesContainer>(n: &str, v: T) {
422 fn _setenv(n: &str, v: &[u8]) {
425 n.with_c_str(|nbuf| {
426 v.with_c_str(|vbuf| {
427 if libc::funcs::posix01::unistd::setenv(nbuf, vbuf, 1) != 0 {
428 panic!(IoError::last_error());
437 fn _setenv(n: &str, v: &[u8]) {
438 let mut n: Vec<u16> = n.utf16_units().collect();
440 let mut v: Vec<u16> = ::str::from_utf8(v).unwrap().utf16_units().collect();
445 if libc::SetEnvironmentVariableW(n.as_ptr(), v.as_ptr()) == 0 {
446 panic!(IoError::last_error());
452 _setenv(n, v.container_as_bytes())
455 /// Remove a variable from the environment entirely.
456 pub fn unsetenv(n: &str) {
458 fn _unsetenv(n: &str) {
461 n.with_c_str(|nbuf| {
462 if libc::funcs::posix01::unistd::unsetenv(nbuf) != 0 {
463 panic!(IoError::last_error());
471 fn _unsetenv(n: &str) {
472 let mut n: Vec<u16> = n.utf16_units().collect();
476 if libc::SetEnvironmentVariableW(n.as_ptr(), ptr::null()) == 0 {
477 panic!(IoError::last_error());
486 /// Parses input according to platform conventions for the `PATH`
487 /// environment variable.
493 /// let key = "PATH";
494 /// match os::getenv_as_bytes(key) {
496 /// for path in os::split_paths(paths).iter() {
497 /// println!("'{}'", path.display());
500 /// None => println!("{} is not defined in the environment.", key)
503 pub fn split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> {
505 fn _split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> {
506 unparsed.container_as_bytes()
507 .split(|b| *b == b':')
513 fn _split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> {
514 // On Windows, the PATH environment variable is semicolon separated. Double
515 // quotes are used as a way of introducing literal semicolons (since
516 // c:\some;dir is a valid Windows path). Double quotes are not themselves
517 // permitted in path names, so there is no way to escape a double quote.
518 // Quoted regions can appear in arbitrary locations, so
520 // c:\foo;c:\som"e;di"r;c:\bar
522 // Should parse as [c:\foo, c:\some;dir, c:\bar].
524 // (The above is based on testing; there is no clear reference available
527 let mut parsed = Vec::new();
528 let mut in_progress = Vec::new();
529 let mut in_quote = false;
531 for b in unparsed.container_as_bytes().iter() {
533 b';' if !in_quote => {
534 parsed.push(Path::new(in_progress.as_slice()));
535 in_progress.truncate(0)
538 in_quote = !in_quote;
541 in_progress.push(*b);
545 parsed.push(Path::new(in_progress));
549 _split_paths(unparsed)
552 /// Joins a collection of `Path`s appropriately for the `PATH`
553 /// environment variable.
555 /// Returns a `Vec<u8>` on success, since `Path`s are not utf-8
556 /// encoded on all platforms.
558 /// Returns an `Err` (containing an error message) if one of the input
559 /// `Path`s contains an invalid character for constructing the `PATH`
560 /// variable (a double quote on Windows or a colon on Unix).
566 /// use std::path::Path;
568 /// let key = "PATH";
569 /// let mut paths = os::getenv_as_bytes(key).map_or(Vec::new(), os::split_paths);
570 /// paths.push(Path::new("/home/xyz/bin"));
571 /// os::setenv(key, os::join_paths(paths.as_slice()).unwrap());
573 pub fn join_paths<T: BytesContainer>(paths: &[T]) -> Result<Vec<u8>, &'static str> {
575 fn _join_paths<T: BytesContainer>(paths: &[T]) -> Result<Vec<u8>, &'static str> {
576 let mut joined = Vec::new();
579 for (i, path) in paths.iter().map(|p| p.container_as_bytes()).enumerate() {
580 if i > 0 { joined.push(sep) }
581 if path.contains(&b'"') {
582 return Err("path segment contains `\"`");
583 } else if path.contains(&sep) {
585 joined.push_all(path);
588 joined.push_all(path);
596 fn _join_paths<T: BytesContainer>(paths: &[T]) -> Result<Vec<u8>, &'static str> {
597 let mut joined = Vec::new();
600 for (i, path) in paths.iter().map(|p| p.container_as_bytes()).enumerate() {
601 if i > 0 { joined.push(sep) }
602 if path.contains(&sep) { return Err("path segment contains separator `:`") }
603 joined.push_all(path);
612 /// A low-level OS in-memory pipe.
614 /// A file descriptor representing the reading end of the pipe. Data written
615 /// on the `out` file descriptor can be read from this file descriptor.
617 /// A file descriptor representing the write end of the pipe. Data written
618 /// to this file descriptor can be read from the `input` file descriptor.
622 /// Creates a new low-level OS in-memory pipe.
624 /// This function can fail to succeed if there are no more resources available
625 /// to allocate a pipe.
627 /// This function is also unsafe as there is no destructor associated with the
628 /// `Pipe` structure will return. If it is not arranged for the returned file
629 /// descriptors to be closed, the file descriptors will leak. For safe handling
630 /// of this scenario, use `std::io::PipeStream` instead.
631 pub unsafe fn pipe() -> IoResult<Pipe> {
632 let (reader, writer) = try!(sys::os::pipe());
634 reader: reader.unwrap(),
635 writer: writer.unwrap(),
639 /// Returns the proper dll filename for the given basename of a file
641 #[cfg(not(target_os="ios"))]
642 pub fn dll_filename(base: &str) -> String {
643 format!("{}{}{}", consts::DLL_PREFIX, base, consts::DLL_SUFFIX)
646 /// Optionally returns the filesystem path to the current executable which is
647 /// running but with the executable name.
654 /// match os::self_exe_name() {
655 /// Some(exe_path) => println!("Path of this executable is: {}", exe_path.display()),
656 /// None => println!("Unable to get the path of this executable!")
659 pub fn self_exe_name() -> Option<Path> {
661 #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))]
662 fn load_self() -> Option<Vec<u8>> {
664 use libc::funcs::bsd44::*;
665 use libc::consts::os::extra::*;
666 let mut mib = vec![CTL_KERN as c_int,
668 KERN_PROC_PATHNAME as c_int,
670 let mut sz: libc::size_t = 0;
671 let err = sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
672 ptr::null_mut(), &mut sz, ptr::null_mut(),
674 if err != 0 { return None; }
675 if sz == 0 { return None; }
676 let mut v: Vec<u8> = Vec::with_capacity(sz as uint);
677 let err = sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
678 v.as_mut_ptr() as *mut c_void, &mut sz,
679 ptr::null_mut(), 0u as libc::size_t);
680 if err != 0 { return None; }
681 if sz == 0 { return None; }
682 v.set_len(sz as uint - 1); // chop off trailing NUL
687 #[cfg(any(target_os = "linux", target_os = "android"))]
688 fn load_self() -> Option<Vec<u8>> {
691 match io::fs::readlink(&Path::new("/proc/self/exe")) {
692 Ok(path) => Some(path.into_vec()),
697 #[cfg(any(target_os = "macos", target_os = "ios"))]
698 fn load_self() -> Option<Vec<u8>> {
700 use libc::funcs::extra::_NSGetExecutablePath;
702 _NSGetExecutablePath(ptr::null_mut(), &mut sz);
703 if sz == 0 { return None; }
704 let mut v: Vec<u8> = Vec::with_capacity(sz as uint);
705 let err = _NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz);
706 if err != 0 { return None; }
707 v.set_len(sz as uint - 1); // chop off trailing NUL
713 fn load_self() -> Option<Vec<u8>> {
715 use os::windows::fill_utf16_buf_and_decode;
716 fill_utf16_buf_and_decode(|buf, sz| {
717 libc::GetModuleFileNameW(0u as libc::DWORD, buf, sz)
718 }).map(|s| s.into_string().into_bytes())
722 load_self().and_then(Path::new_opt)
725 /// Optionally returns the filesystem path to the current executable which is
728 /// Like self_exe_name() but without the binary's name.
735 /// match os::self_exe_path() {
736 /// Some(exe_path) => println!("Executable's Path is: {}", exe_path.display()),
737 /// None => println!("Impossible to fetch the path of this executable.")
740 pub fn self_exe_path() -> Option<Path> {
741 self_exe_name().map(|mut p| { p.pop(); p })
744 /// Optionally returns the path to the current user's home directory if known.
748 /// Returns the value of the 'HOME' environment variable if it is set
749 /// and not equal to the empty string.
753 /// Returns the value of the 'HOME' environment variable if it is
754 /// set and not equal to the empty string. Otherwise, returns the value of the
755 /// 'USERPROFILE' environment variable if it is set and not equal to the empty
763 /// match os::homedir() {
764 /// Some(ref p) => println!("{}", p.display()),
765 /// None => println!("Impossible to get your home dir!")
768 pub fn homedir() -> Option<Path> {
771 fn _homedir() -> Option<Path> {
777 fn _homedir() -> Option<Path> {
778 aux_homedir("HOME").or(aux_homedir("USERPROFILE"))
782 fn aux_homedir(home_name: &str) -> Option<Path> {
783 match getenv_as_bytes(home_name) {
785 if p.is_empty() { None } else { Path::new_opt(p) }
793 /// Returns the path to a temporary directory.
795 /// On Unix, returns the value of the 'TMPDIR' environment variable if it is
796 /// set, otherwise for non-Android it returns '/tmp'. If Android, since there
797 /// is no global temporary folder (it is usually allocated per-app), we return
798 /// '/data/local/tmp'.
800 /// On Windows, returns the value of, in order, the 'TMP', 'TEMP',
801 /// 'USERPROFILE' environment variable if any are set and not the empty
802 /// string. Otherwise, tmpdir returns the path to the Windows directory.
803 pub fn tmpdir() -> Path {
806 fn getenv_nonempty(v: &str) -> Option<Path> {
819 fn lookup() -> Path {
820 let default = if cfg!(target_os = "android") {
821 Path::new("/data/local/tmp")
826 getenv_nonempty("TMPDIR").unwrap_or(default)
830 fn lookup() -> Path {
831 getenv_nonempty("TMP").or(
832 getenv_nonempty("TEMP").or(
833 getenv_nonempty("USERPROFILE").or(
834 getenv_nonempty("WINDIR")))).unwrap_or(Path::new("C:\\Windows"))
839 /// Convert a relative path to an absolute path
841 /// If the given path is relative, return it prepended with the current working
842 /// directory. If the given path is already an absolute path, return it
848 /// use std::path::Path;
850 /// // Assume we're in a path like /home/someuser
851 /// let rel_path = Path::new("..");
852 /// let abs_path = os::make_absolute(&rel_path).unwrap();
853 /// println!("The absolute path is {}", abs_path.display());
854 /// // Prints "The absolute path is /home"
856 // NB: this is here rather than in path because it is a form of environment
857 // querying; what it does depends on the process working directory, not just
859 pub fn make_absolute(p: &Path) -> IoResult<Path> {
863 getcwd().map(|mut cwd| {
870 /// Changes the current working directory to the specified path, returning
871 /// whether the change was completed successfully or not.
876 /// use std::path::Path;
878 /// let root = Path::new("/");
879 /// assert!(os::change_dir(&root).is_ok());
880 /// println!("Successfully changed working directory to {}!", root.display());
882 pub fn change_dir(p: &Path) -> IoResult<()> {
886 fn chdir(p: &Path) -> IoResult<()> {
887 let mut p = p.as_str().unwrap().utf16_units().collect::<Vec<u16>>();
891 match libc::SetCurrentDirectoryW(p.as_ptr()) != (0 as libc::BOOL) {
893 false => Err(IoError::last_error()),
899 fn chdir(p: &Path) -> IoResult<()> {
902 match libc::chdir(buf) == (0 as c_int) {
904 false => Err(IoError::last_error()),
911 /// Returns the platform-specific value of errno
912 pub fn errno() -> uint {
913 os_imp::errno() as uint
916 /// Return the string corresponding to an `errno()` value of `errnum`.
922 /// // Same as println!("{}", last_os_error());
923 /// println!("{}", os::error_string(os::errno() as uint));
925 pub fn error_string(errnum: uint) -> String {
926 return os_imp::error_string(errnum as i32);
929 /// Get a string representing the platform-dependent last error
930 pub fn last_os_error() -> String {
931 error_string(errno() as uint)
934 static EXIT_STATUS: AtomicInt = INIT_ATOMIC_INT;
936 /// Sets the process exit code
938 /// Sets the exit code returned by the process if all supervised tasks
939 /// terminate successfully (without panicking). If the current root task panics
940 /// and is supervised by the scheduler then any user-specified exit status is
941 /// ignored and the process exits with the default panic status.
943 /// Note that this is not synchronized against modifications of other threads.
944 pub fn set_exit_status(code: int) {
945 EXIT_STATUS.store(code, SeqCst)
948 /// Fetches the process's current exit code. This defaults to 0 and can change
949 /// by calling `set_exit_status`.
950 pub fn get_exit_status() -> int {
951 EXIT_STATUS.load(SeqCst)
954 #[cfg(target_os = "macos")]
955 unsafe fn load_argc_and_argv(argc: int,
956 argv: *const *const c_char) -> Vec<Vec<u8>> {
959 Vec::from_fn(argc as uint, |i| {
960 CString::new(*argv.offset(i as int), false).as_bytes_no_nul().to_vec()
964 /// Returns the command line arguments
966 /// Returns a list of the command line arguments.
967 #[cfg(target_os = "macos")]
968 fn real_args_as_bytes() -> Vec<Vec<u8>> {
970 let (argc, argv) = (*_NSGetArgc() as int,
971 *_NSGetArgv() as *const *const c_char);
972 load_argc_and_argv(argc, argv)
976 // As _NSGetArgc and _NSGetArgv aren't mentioned in iOS docs
977 // and use underscores in their names - they're most probably
978 // are considered private and therefore should be avoided
979 // Here is another way to get arguments using Objective C
982 // In general it looks like:
984 // let args = [[NSProcessInfo processInfo] arguments]
985 // for i in range(0, [args count])
986 // res.push([args objectAtIndex:i])
988 #[cfg(target_os = "ios")]
989 fn real_args_as_bytes() -> Vec<Vec<u8>> {
994 #[link(name = "objc")]
996 fn sel_registerName(name: *const libc::c_uchar) -> Sel;
997 fn objc_msgSend(obj: NsId, sel: Sel, ...) -> NsId;
998 fn objc_getClass(class_name: *const libc::c_uchar) -> NsId;
1001 #[link(name = "Foundation", kind = "framework")]
1004 type Sel = *const libc::c_void;
1005 type NsId = *const libc::c_void;
1007 let mut res = Vec::new();
1010 let processInfoSel = sel_registerName("processInfo\0".as_ptr());
1011 let argumentsSel = sel_registerName("arguments\0".as_ptr());
1012 let utf8Sel = sel_registerName("UTF8String\0".as_ptr());
1013 let countSel = sel_registerName("count\0".as_ptr());
1014 let objectAtSel = sel_registerName("objectAtIndex:\0".as_ptr());
1016 let klass = objc_getClass("NSProcessInfo\0".as_ptr());
1017 let info = objc_msgSend(klass, processInfoSel);
1018 let args = objc_msgSend(info, argumentsSel);
1020 let cnt: int = mem::transmute(objc_msgSend(args, countSel));
1021 for i in range(0, cnt) {
1022 let tmp = objc_msgSend(args, objectAtSel, i);
1023 let utf_c_str: *const libc::c_char =
1024 mem::transmute(objc_msgSend(tmp, utf8Sel));
1025 let s = CString::new(utf_c_str, false);
1026 res.push(s.as_bytes_no_nul().to_vec())
1033 #[cfg(any(target_os = "linux",
1034 target_os = "android",
1035 target_os = "freebsd",
1036 target_os = "dragonfly"))]
1037 fn real_args_as_bytes() -> Vec<Vec<u8>> {
1040 match rustrt::args::clone() {
1042 None => panic!("process arguments not initialized")
1046 #[cfg(not(windows))]
1047 fn real_args() -> Vec<String> {
1048 real_args_as_bytes().into_iter()
1050 String::from_utf8_lossy(v.as_slice()).into_string()
1055 fn real_args() -> Vec<String> {
1058 let mut nArgs: c_int = 0;
1059 let lpArgCount: *mut c_int = &mut nArgs;
1060 let lpCmdLine = unsafe { GetCommandLineW() };
1061 let szArgList = unsafe { CommandLineToArgvW(lpCmdLine, lpArgCount) };
1063 let args = Vec::from_fn(nArgs as uint, |i| unsafe {
1064 // Determine the length of this argument.
1065 let ptr = *szArgList.offset(i as int);
1067 while *ptr.offset(len as int) != 0 { len += 1; }
1069 // Push it onto the list.
1070 let ptr = ptr as *const u16;
1071 let buf = slice::from_raw_buf(&ptr, len);
1072 let opt_s = String::from_utf16(::str::truncate_utf16_at_nul(buf));
1073 opt_s.expect("CommandLineToArgvW returned invalid UTF-16")
1077 LocalFree(szArgList as *mut c_void);
1084 fn real_args_as_bytes() -> Vec<Vec<u8>> {
1085 real_args().into_iter().map(|s| s.into_bytes()).collect()
1088 type LPCWSTR = *const u16;
1091 #[link_name="kernel32"]
1093 fn GetCommandLineW() -> LPCWSTR;
1094 fn LocalFree(ptr: *mut c_void);
1098 #[link_name="shell32"]
1100 fn CommandLineToArgvW(lpCmdLine: LPCWSTR,
1101 pNumArgs: *mut c_int) -> *mut *mut u16;
1104 /// Returns the arguments which this program was started with (normally passed
1105 /// via the command line).
1107 /// The first element is traditionally the path to the executable, but it can be
1108 /// set to arbitrary text, and it may not even exist, so this property should not
1109 /// be relied upon for security purposes.
1111 /// The arguments are interpreted as utf-8, with invalid bytes replaced with \uFFFD.
1112 /// See `String::from_utf8_lossy` for details.
1118 /// // Prints each argument on a separate line
1119 /// for argument in os::args().iter() {
1120 /// println!("{}", argument);
1123 pub fn args() -> Vec<String> {
1127 /// Returns the arguments which this program was started with (normally passed
1128 /// via the command line) as byte vectors.
1129 pub fn args_as_bytes() -> Vec<Vec<u8>> {
1130 real_args_as_bytes()
1133 #[cfg(target_os = "macos")]
1135 // These functions are in crt_externs.h.
1136 pub fn _NSGetArgc() -> *mut c_int;
1137 pub fn _NSGetArgv() -> *mut *mut *mut c_char;
1140 // Round up `from` to be divisible by `to`
1141 fn round_up(from: uint, to: uint) -> uint {
1142 let r = if from % to == 0 {
1145 from + to - (from % to)
1154 /// Returns the page size of the current architecture in bytes.
1156 pub fn page_size() -> uint {
1158 libc::sysconf(libc::_SC_PAGESIZE) as uint
1162 /// Returns the page size of the current architecture in bytes.
1164 pub fn page_size() -> uint {
1167 let mut info = mem::zeroed();
1168 libc::GetSystemInfo(&mut info);
1170 return info.dwPageSize as uint;
1174 /// A memory mapped file or chunk of memory. This is a very system-specific
1175 /// interface to the OS's memory mapping facilities (`mmap` on POSIX,
1176 /// `VirtualAlloc`/`CreateFileMapping` on Windows). It makes no attempt at
1177 /// abstracting platform differences, besides in error values returned. Consider
1178 /// yourself warned.
1180 /// The memory map is released (unmapped) when the destructor is run, so don't
1181 /// let it leave scope by accident if you want it to stick around.
1182 pub struct MemoryMap {
1185 kind: MemoryMapKind,
1188 /// Type of memory map
1189 pub enum MemoryMapKind {
1190 /// Virtual memory map. Usually used to change the permissions of a given
1191 /// chunk of memory. Corresponds to `VirtualAlloc` on Windows.
1193 /// Virtual memory map. Usually used to change the permissions of a given
1194 /// chunk of memory, or for allocation. Corresponds to `VirtualAlloc` on
1199 /// Options the memory map is created with
1200 pub enum MapOption {
1201 /// The memory should be readable
1203 /// The memory should be writable
1205 /// The memory should be executable
1207 /// Create a map for a specific address range. Corresponds to `MAP_FIXED` on
1210 /// Create a memory mapping for a file with a given fd.
1212 /// When using `MapFd`, the start of the map is `uint` bytes from the start
1215 /// On POSIX, this can be used to specify the default flags passed to
1216 /// `mmap`. By default it uses `MAP_PRIVATE` and, if not using `MapFd`,
1217 /// `MAP_ANON`. This will override both of those. This is platform-specific
1218 /// (the exact values used) and ignored on Windows.
1219 MapNonStandardFlags(c_int),
1222 /// Possible errors when creating a map.
1224 /// ## The following are POSIX-specific
1226 /// fd was not open for reading or, if using `MapWritable`, was not open for
1229 /// fd was not valid
1231 /// Either the address given by `MapAddr` or offset given by `MapOffset` was
1232 /// not a multiple of `MemoryMap::granularity` (unaligned to page size).
1234 /// With `MapFd`, the fd does not support mapping.
1236 /// If using `MapAddr`, the address + `min_len` was outside of the process's
1237 /// address space. If using `MapFd`, the target of the fd didn't have enough
1238 /// resources to fulfill the request.
1240 /// A zero-length map was requested. This is invalid according to
1241 /// [POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/functions/mmap.html).
1242 /// Not all platforms obey this, but this wrapper does.
1244 /// Unrecognized error. The inner value is the unrecognized errno.
1246 /// ## The following are Windows-specific
1248 /// Unsupported combination of protection flags
1249 /// (`MapReadable`/`MapWritable`/`MapExecutable`).
1251 /// When using `MapFd`, `MapOffset` was given (Windows does not support this
1254 /// When using `MapFd`, there was already a mapping to the file.
1256 /// Unrecognized error from `VirtualAlloc`. The inner value is the return
1257 /// value of GetLastError.
1258 ErrVirtualAlloc(uint),
1259 /// Unrecognized error from `CreateFileMapping`. The inner value is the
1260 /// return value of `GetLastError`.
1261 ErrCreateFileMappingW(uint),
1262 /// Unrecognized error from `MapViewOfFile`. The inner value is the return
1263 /// value of `GetLastError`.
1264 ErrMapViewOfFile(uint)
1267 impl fmt::Show for MapError {
1268 fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result {
1269 let str = match *self {
1270 ErrFdNotAvail => "fd not available for reading or writing",
1271 ErrInvalidFd => "Invalid fd",
1273 "Unaligned address, invalid flags, negative length or \
1276 ErrNoMapSupport=> "File doesn't support mapping",
1277 ErrNoMem => "Invalid address, or not enough available memory",
1278 ErrUnsupProt => "Protection mode unsupported",
1279 ErrUnsupOffset => "Offset in virtual memory mode is unsupported",
1280 ErrAlreadyExists => "File mapping for specified file already exists",
1281 ErrZeroLength => "Zero-length mapping not allowed",
1282 ErrUnknown(code) => {
1283 return write!(out, "Unknown error = {}", code)
1285 ErrVirtualAlloc(code) => {
1286 return write!(out, "VirtualAlloc failure = {}", code)
1288 ErrCreateFileMappingW(code) => {
1289 return write!(out, "CreateFileMappingW failure = {}", code)
1291 ErrMapViewOfFile(code) => {
1292 return write!(out, "MapViewOfFile failure = {}", code)
1295 write!(out, "{}", str)
1299 impl Error for MapError {
1300 fn description(&self) -> &str { "memory map error" }
1301 fn detail(&self) -> Option<String> { Some(self.to_string()) }
1304 impl FromError<MapError> for Box<Error> {
1305 fn from_error(err: MapError) -> Box<Error> {
1312 /// Create a new mapping with the given `options`, at least `min_len` bytes
1313 /// long. `min_len` must be greater than zero; see the note on
1314 /// `ErrZeroLength`.
1315 pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
1319 return Err(ErrZeroLength)
1321 let mut addr: *const u8 = ptr::null();
1323 let mut flags = libc::MAP_PRIVATE;
1326 let mut custom_flags = false;
1327 let len = round_up(min_len, page_size());
1329 for &o in options.iter() {
1331 MapReadable => { prot |= libc::PROT_READ; },
1332 MapWritable => { prot |= libc::PROT_WRITE; },
1333 MapExecutable => { prot |= libc::PROT_EXEC; },
1335 flags |= libc::MAP_FIXED;
1339 flags |= libc::MAP_FILE;
1342 MapOffset(offset_) => { offset = offset_ as off_t; },
1343 MapNonStandardFlags(f) => { custom_flags = true; flags = f },
1346 if fd == -1 && !custom_flags { flags |= libc::MAP_ANON; }
1349 libc::mmap(addr as *mut c_void, len as libc::size_t, prot, flags,
1352 if r == libc::MAP_FAILED {
1353 Err(match errno() as c_int {
1354 libc::EACCES => ErrFdNotAvail,
1355 libc::EBADF => ErrInvalidFd,
1356 libc::EINVAL => ErrUnaligned,
1357 libc::ENODEV => ErrNoMapSupport,
1358 libc::ENOMEM => ErrNoMem,
1359 code => ErrUnknown(code as int)
1368 MapFile(ptr::null())
1374 /// Granularity that the offset or address must be for `MapOffset` and
1375 /// `MapAddr` respectively.
1376 pub fn granularity() -> uint {
1382 impl Drop for MemoryMap {
1383 /// Unmap the mapping. Panics the task if `munmap` panics.
1384 fn drop(&mut self) {
1385 if self.len == 0 { /* workaround for dummy_stack */ return; }
1388 // `munmap` only panics due to logic errors
1389 libc::munmap(self.data as *mut c_void, self.len as libc::size_t);
1396 /// Create a new mapping with the given `options`, at least `min_len` bytes long.
1397 pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
1398 use libc::types::os::arch::extra::{LPVOID, DWORD, SIZE_T, HANDLE};
1400 let mut lpAddress: LPVOID = ptr::null_mut();
1401 let mut readable = false;
1402 let mut writable = false;
1403 let mut executable = false;
1404 let mut fd: c_int = -1;
1405 let mut offset: uint = 0;
1406 let len = round_up(min_len, page_size());
1408 for &o in options.iter() {
1410 MapReadable => { readable = true; },
1411 MapWritable => { writable = true; },
1412 MapExecutable => { executable = true; }
1413 MapAddr(addr_) => { lpAddress = addr_ as LPVOID; },
1414 MapFd(fd_) => { fd = fd_; },
1415 MapOffset(offset_) => { offset = offset_; },
1416 MapNonStandardFlags(..) => {}
1420 let flProtect = match (executable, readable, writable) {
1421 (false, false, false) if fd == -1 => libc::PAGE_NOACCESS,
1422 (false, true, false) => libc::PAGE_READONLY,
1423 (false, true, true) => libc::PAGE_READWRITE,
1424 (true, false, false) if fd == -1 => libc::PAGE_EXECUTE,
1425 (true, true, false) => libc::PAGE_EXECUTE_READ,
1426 (true, true, true) => libc::PAGE_EXECUTE_READWRITE,
1427 _ => return Err(ErrUnsupProt)
1432 return Err(ErrUnsupOffset);
1435 libc::VirtualAlloc(lpAddress,
1437 libc::MEM_COMMIT | libc::MEM_RESERVE,
1441 0 => Err(ErrVirtualAlloc(errno())),
1449 let dwDesiredAccess = match (executable, readable, writable) {
1450 (false, true, false) => libc::FILE_MAP_READ,
1451 (false, true, true) => libc::FILE_MAP_WRITE,
1452 (true, true, false) => libc::FILE_MAP_READ | libc::FILE_MAP_EXECUTE,
1453 (true, true, true) => libc::FILE_MAP_WRITE | libc::FILE_MAP_EXECUTE,
1454 _ => return Err(ErrUnsupProt) // Actually, because of the check above,
1455 // we should never get here.
1458 let hFile = libc::get_osfhandle(fd) as HANDLE;
1459 let mapping = libc::CreateFileMappingW(hFile,
1465 if mapping == ptr::null_mut() {
1466 return Err(ErrCreateFileMappingW(errno()));
1468 if errno() as c_int == libc::ERROR_ALREADY_EXISTS {
1469 return Err(ErrAlreadyExists);
1471 let r = libc::MapViewOfFile(mapping,
1473 ((len as u64) >> 32) as DWORD,
1474 (offset & 0xffff_ffff) as DWORD,
1477 0 => Err(ErrMapViewOfFile(errno())),
1481 kind: MapFile(mapping as *const u8)
1488 /// Granularity of MapAddr() and MapOffset() parameter values.
1489 /// This may be greater than the value returned by page_size().
1490 pub fn granularity() -> uint {
1493 let mut info = mem::zeroed();
1494 libc::GetSystemInfo(&mut info);
1496 return info.dwAllocationGranularity as uint;
1502 impl Drop for MemoryMap {
1503 /// Unmap the mapping. Panics the task if any of `VirtualFree`,
1504 /// `UnmapViewOfFile`, or `CloseHandle` fail.
1505 fn drop(&mut self) {
1506 use libc::types::os::arch::extra::{LPCVOID, HANDLE};
1507 use libc::consts::os::extra::FALSE;
1508 if self.len == 0 { return }
1513 if libc::VirtualFree(self.data as *mut c_void, 0,
1514 libc::MEM_RELEASE) == 0 {
1515 println!("VirtualFree failed: {}", errno());
1518 MapFile(mapping) => {
1519 if libc::UnmapViewOfFile(self.data as LPCVOID) == FALSE {
1520 println!("UnmapViewOfFile failed: {}", errno());
1522 if libc::CloseHandle(mapping as HANDLE) == FALSE {
1523 println!("CloseHandle failed: {}", errno());
1532 /// Returns the pointer to the memory created or modified by this map.
1533 pub fn data(&self) -> *mut u8 { self.data }
1534 /// Returns the number of bytes this map applies to.
1535 pub fn len(&self) -> uint { self.len }
1536 /// Returns the type of mapping this represents.
1537 pub fn kind(&self) -> MemoryMapKind { self.kind }
1540 #[cfg(target_os = "linux")]
1542 pub use os::arch_consts::ARCH;
1544 pub const FAMILY: &'static str = "unix";
1546 /// A string describing the specific operating system in use: in this
1548 pub const SYSNAME: &'static str = "linux";
1550 /// Specifies the filename prefix used for shared libraries on this
1551 /// platform: in this case, `lib`.
1552 pub const DLL_PREFIX: &'static str = "lib";
1554 /// Specifies the filename suffix used for shared libraries on this
1555 /// platform: in this case, `.so`.
1556 pub const DLL_SUFFIX: &'static str = ".so";
1558 /// Specifies the file extension used for shared libraries on this
1559 /// platform that goes after the dot: in this case, `so`.
1560 pub const DLL_EXTENSION: &'static str = "so";
1562 /// Specifies the filename suffix used for executable binaries on this
1563 /// platform: in this case, the empty string.
1564 pub const EXE_SUFFIX: &'static str = "";
1566 /// Specifies the file extension, if any, used for executable binaries
1567 /// on this platform: in this case, the empty string.
1568 pub const EXE_EXTENSION: &'static str = "";
1571 #[cfg(target_os = "macos")]
1573 pub use os::arch_consts::ARCH;
1575 pub const FAMILY: &'static str = "unix";
1577 /// A string describing the specific operating system in use: in this
1579 pub const SYSNAME: &'static str = "macos";
1581 /// Specifies the filename prefix used for shared libraries on this
1582 /// platform: in this case, `lib`.
1583 pub const DLL_PREFIX: &'static str = "lib";
1585 /// Specifies the filename suffix used for shared libraries on this
1586 /// platform: in this case, `.dylib`.
1587 pub const DLL_SUFFIX: &'static str = ".dylib";
1589 /// Specifies the file extension used for shared libraries on this
1590 /// platform that goes after the dot: in this case, `dylib`.
1591 pub const DLL_EXTENSION: &'static str = "dylib";
1593 /// Specifies the filename suffix used for executable binaries on this
1594 /// platform: in this case, the empty string.
1595 pub const EXE_SUFFIX: &'static str = "";
1597 /// Specifies the file extension, if any, used for executable binaries
1598 /// on this platform: in this case, the empty string.
1599 pub const EXE_EXTENSION: &'static str = "";
1602 #[cfg(target_os = "ios")]
1604 pub use os::arch_consts::ARCH;
1606 pub const FAMILY: &'static str = "unix";
1608 /// A string describing the specific operating system in use: in this
1610 pub const SYSNAME: &'static str = "ios";
1612 /// Specifies the filename suffix used for executable binaries on this
1613 /// platform: in this case, the empty string.
1614 pub const EXE_SUFFIX: &'static str = "";
1616 /// Specifies the file extension, if any, used for executable binaries
1617 /// on this platform: in this case, the empty string.
1618 pub const EXE_EXTENSION: &'static str = "";
1621 #[cfg(target_os = "freebsd")]
1623 pub use os::arch_consts::ARCH;
1625 pub const FAMILY: &'static str = "unix";
1627 /// A string describing the specific operating system in use: in this
1628 /// case, `freebsd`.
1629 pub const SYSNAME: &'static str = "freebsd";
1631 /// Specifies the filename prefix used for shared libraries on this
1632 /// platform: in this case, `lib`.
1633 pub const DLL_PREFIX: &'static str = "lib";
1635 /// Specifies the filename suffix used for shared libraries on this
1636 /// platform: in this case, `.so`.
1637 pub const DLL_SUFFIX: &'static str = ".so";
1639 /// Specifies the file extension used for shared libraries on this
1640 /// platform that goes after the dot: in this case, `so`.
1641 pub const DLL_EXTENSION: &'static str = "so";
1643 /// Specifies the filename suffix used for executable binaries on this
1644 /// platform: in this case, the empty string.
1645 pub const EXE_SUFFIX: &'static str = "";
1647 /// Specifies the file extension, if any, used for executable binaries
1648 /// on this platform: in this case, the empty string.
1649 pub const EXE_EXTENSION: &'static str = "";
1652 #[cfg(target_os = "dragonfly")]
1654 pub use os::arch_consts::ARCH;
1656 pub const FAMILY: &'static str = "unix";
1658 /// A string describing the specific operating system in use: in this
1659 /// case, `dragonfly`.
1660 pub const SYSNAME: &'static str = "dragonfly";
1662 /// Specifies the filename prefix used for shared libraries on this
1663 /// platform: in this case, `lib`.
1664 pub const DLL_PREFIX: &'static str = "lib";
1666 /// Specifies the filename suffix used for shared libraries on this
1667 /// platform: in this case, `.so`.
1668 pub const DLL_SUFFIX: &'static str = ".so";
1670 /// Specifies the file extension used for shared libraries on this
1671 /// platform that goes after the dot: in this case, `so`.
1672 pub const DLL_EXTENSION: &'static str = "so";
1674 /// Specifies the filename suffix used for executable binaries on this
1675 /// platform: in this case, the empty string.
1676 pub const EXE_SUFFIX: &'static str = "";
1678 /// Specifies the file extension, if any, used for executable binaries
1679 /// on this platform: in this case, the empty string.
1680 pub const EXE_EXTENSION: &'static str = "";
1683 #[cfg(target_os = "android")]
1685 pub use os::arch_consts::ARCH;
1687 pub const FAMILY: &'static str = "unix";
1689 /// A string describing the specific operating system in use: in this
1690 /// case, `android`.
1691 pub const SYSNAME: &'static str = "android";
1693 /// Specifies the filename prefix used for shared libraries on this
1694 /// platform: in this case, `lib`.
1695 pub const DLL_PREFIX: &'static str = "lib";
1697 /// Specifies the filename suffix used for shared libraries on this
1698 /// platform: in this case, `.so`.
1699 pub const DLL_SUFFIX: &'static str = ".so";
1701 /// Specifies the file extension used for shared libraries on this
1702 /// platform that goes after the dot: in this case, `so`.
1703 pub const DLL_EXTENSION: &'static str = "so";
1705 /// Specifies the filename suffix used for executable binaries on this
1706 /// platform: in this case, the empty string.
1707 pub const EXE_SUFFIX: &'static str = "";
1709 /// Specifies the file extension, if any, used for executable binaries
1710 /// on this platform: in this case, the empty string.
1711 pub const EXE_EXTENSION: &'static str = "";
1714 #[cfg(target_os = "windows")]
1716 pub use os::arch_consts::ARCH;
1718 pub const FAMILY: &'static str = "windows";
1720 /// A string describing the specific operating system in use: in this
1721 /// case, `windows`.
1722 pub const SYSNAME: &'static str = "windows";
1724 /// Specifies the filename prefix used for shared libraries on this
1725 /// platform: in this case, the empty string.
1726 pub const DLL_PREFIX: &'static str = "";
1728 /// Specifies the filename suffix used for shared libraries on this
1729 /// platform: in this case, `.dll`.
1730 pub const DLL_SUFFIX: &'static str = ".dll";
1732 /// Specifies the file extension used for shared libraries on this
1733 /// platform that goes after the dot: in this case, `dll`.
1734 pub const DLL_EXTENSION: &'static str = "dll";
1736 /// Specifies the filename suffix used for executable binaries on this
1737 /// platform: in this case, `.exe`.
1738 pub const EXE_SUFFIX: &'static str = ".exe";
1740 /// Specifies the file extension, if any, used for executable binaries
1741 /// on this platform: in this case, `exe`.
1742 pub const EXE_EXTENSION: &'static str = "exe";
1745 #[cfg(target_arch = "x86")]
1747 pub const ARCH: &'static str = "x86";
1750 #[cfg(target_arch = "x86_64")]
1752 pub const ARCH: &'static str = "x86_64";
1755 #[cfg(target_arch = "arm")]
1757 pub const ARCH: &'static str = "arm";
1760 #[cfg(target_arch = "mips")]
1762 pub const ARCH: &'static str = "mips";
1765 #[cfg(target_arch = "mipsel")]
1767 pub const ARCH: &'static str = "mipsel";
1775 use os::{env, getcwd, getenv, make_absolute};
1776 use os::{split_paths, join_paths, setenv, unsetenv};
1782 pub fn last_os_error() {
1783 debug!("{}", os::last_os_error());
1786 fn make_rand_name() -> String {
1787 let mut rng = rand::task_rng();
1788 let n = format!("TEST{}", rng.gen_ascii_chars().take(10u)
1789 .collect::<String>());
1790 assert!(getenv(n.as_slice()).is_none());
1795 fn test_num_cpus() {
1796 assert!(os::num_cpus() > 0);
1801 let n = make_rand_name();
1802 setenv(n.as_slice(), "VALUE");
1803 assert_eq!(getenv(n.as_slice()), option::Option::Some("VALUE".to_string()));
1807 fn test_unsetenv() {
1808 let n = make_rand_name();
1809 setenv(n.as_slice(), "VALUE");
1810 unsetenv(n.as_slice());
1811 assert_eq!(getenv(n.as_slice()), option::Option::None);
1816 fn test_setenv_overwrite() {
1817 let n = make_rand_name();
1818 setenv(n.as_slice(), "1");
1819 setenv(n.as_slice(), "2");
1820 assert_eq!(getenv(n.as_slice()), option::Option::Some("2".to_string()));
1821 setenv(n.as_slice(), "");
1822 assert_eq!(getenv(n.as_slice()), option::Option::Some("".to_string()));
1825 // Windows GetEnvironmentVariable requires some extra work to make sure
1826 // the buffer the variable is copied into is the right size
1829 fn test_getenv_big() {
1830 let mut s = "".to_string();
1833 s.push_str("aaaaaaaaaa");
1836 let n = make_rand_name();
1837 setenv(n.as_slice(), s.as_slice());
1838 debug!("{}", s.clone());
1839 assert_eq!(getenv(n.as_slice()), option::Option::Some(s));
1843 fn test_self_exe_name() {
1844 let path = os::self_exe_name();
1845 assert!(path.is_some());
1846 let path = path.unwrap();
1847 debug!("{}", path.display());
1849 // Hard to test this function
1850 assert!(path.is_absolute());
1854 fn test_self_exe_path() {
1855 let path = os::self_exe_path();
1856 assert!(path.is_some());
1857 let path = path.unwrap();
1858 debug!("{}", path.display());
1860 // Hard to test this function
1861 assert!(path.is_absolute());
1866 fn test_env_getenv() {
1868 assert!(e.len() > 0u);
1870 let (n, v) = (*p).clone();
1872 let v2 = getenv(n.as_slice());
1873 // MingW seems to set some funky environment variables like
1874 // "=C:=C:\MinGW\msys\1.0\bin" and "!::=::\" that are returned
1875 // from env() but not visible from getenv().
1876 assert!(v2.is_none() || v2 == option::Option::Some(v));
1881 fn test_env_set_get_huge() {
1882 let n = make_rand_name();
1883 let s = "x".repeat(10000).to_string();
1884 setenv(n.as_slice(), s.as_slice());
1885 assert_eq!(getenv(n.as_slice()), Some(s));
1886 unsetenv(n.as_slice());
1887 assert_eq!(getenv(n.as_slice()), None);
1891 fn test_env_setenv() {
1892 let n = make_rand_name();
1895 setenv(n.as_slice(), "VALUE");
1896 assert!(!e.contains(&(n.clone(), "VALUE".to_string())));
1899 assert!(e.contains(&(n, "VALUE".to_string())));
1904 assert!((!Path::new("test-path").is_absolute()));
1906 let cwd = getcwd().unwrap();
1907 debug!("Current working directory: {}", cwd.display());
1909 debug!("{}", make_absolute(&Path::new("test-path")).unwrap().display());
1910 debug!("{}", make_absolute(&Path::new("/usr/bin")).unwrap().display());
1916 let oldhome = getenv("HOME");
1918 setenv("HOME", "/home/MountainView");
1919 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1922 assert!(os::homedir().is_none());
1924 for s in oldhome.iter() {
1925 setenv("HOME", s.as_slice());
1933 let oldhome = getenv("HOME");
1934 let olduserprofile = getenv("USERPROFILE");
1937 setenv("USERPROFILE", "");
1939 assert!(os::homedir().is_none());
1941 setenv("HOME", "/home/MountainView");
1942 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1946 setenv("USERPROFILE", "/home/MountainView");
1947 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1949 setenv("HOME", "/home/MountainView");
1950 setenv("USERPROFILE", "/home/PaloAlto");
1951 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1953 for s in oldhome.iter() {
1954 setenv("HOME", s.as_slice());
1956 for s in olduserprofile.iter() {
1957 setenv("USERPROFILE", s.as_slice());
1962 fn memory_map_rw() {
1963 use result::Result::{Ok, Err};
1965 let chunk = match os::MemoryMap::new(16, &[
1970 Err(msg) => panic!("{}", msg)
1972 assert!(chunk.len >= 16);
1976 assert!(*chunk.data == 0xBE);
1981 fn memory_map_file() {
1982 use result::Result::{Ok, Err};
1988 fn lseek_(fd: c_int, size: uint) {
1990 assert!(lseek(fd, size as off_t, SEEK_SET) == size as off_t);
1994 fn lseek_(fd: c_int, size: uint) {
1996 assert!(lseek(fd, size as c_long, SEEK_SET) == size as c_long);
2000 let mut path = tmpdir();
2001 path.push("mmap_file.tmp");
2002 let size = MemoryMap::granularity() * 2;
2005 let fd = path.with_c_str(|path| {
2006 open(path, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR)
2009 "x".with_c_str(|x| assert!(write(fd, x as *const c_void, 1) == 1));
2012 let chunk = match MemoryMap::new(size / 2, &[
2019 Err(msg) => panic!("{}", msg)
2021 assert!(chunk.len > 0);
2025 assert!(*chunk.data == 0xbe);
2030 fs::unlink(&path).unwrap();
2035 fn split_paths_windows() {
2036 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
2037 split_paths(unparsed) ==
2038 parsed.iter().map(|s| Path::new(*s)).collect::<Vec<_>>()
2041 assert!(check_parse("", &mut [""]));
2042 assert!(check_parse(r#""""#, &mut [""]));
2043 assert!(check_parse(";;", &mut ["", "", ""]));
2044 assert!(check_parse(r"c:\", &mut [r"c:\"]));
2045 assert!(check_parse(r"c:\;", &mut [r"c:\", ""]));
2046 assert!(check_parse(r"c:\;c:\Program Files\",
2047 &mut [r"c:\", r"c:\Program Files\"]));
2048 assert!(check_parse(r#"c:\;c:\"foo"\"#, &mut [r"c:\", r"c:\foo\"]));
2049 assert!(check_parse(r#"c:\;c:\"foo;bar"\;c:\baz"#,
2050 &mut [r"c:\", r"c:\foo;bar\", r"c:\baz"]));
2055 fn split_paths_unix() {
2056 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
2057 split_paths(unparsed) ==
2058 parsed.iter().map(|s| Path::new(*s)).collect::<Vec<_>>()
2061 assert!(check_parse("", &mut [""]));
2062 assert!(check_parse("::", &mut ["", "", ""]));
2063 assert!(check_parse("/", &mut ["/"]));
2064 assert!(check_parse("/:", &mut ["/", ""]));
2065 assert!(check_parse("/:/usr/local", &mut ["/", "/usr/local"]));
2070 fn join_paths_unix() {
2071 fn test_eq(input: &[&str], output: &str) -> bool {
2072 join_paths(input).unwrap().as_slice() == output.as_bytes()
2075 assert!(test_eq(&[], ""));
2076 assert!(test_eq(&["/bin", "/usr/bin", "/usr/local/bin"],
2077 "/bin:/usr/bin:/usr/local/bin"));
2078 assert!(test_eq(&["", "/bin", "", "", "/usr/bin", ""],
2079 ":/bin:::/usr/bin:"));
2080 assert!(join_paths(&["/te:st"]).is_err());
2085 fn join_paths_windows() {
2086 fn test_eq(input: &[&str], output: &str) -> bool {
2087 join_paths(input).unwrap().as_slice() == output.as_bytes()
2090 assert!(test_eq(&[], ""));
2091 assert!(test_eq(&[r"c:\windows", r"c:\"],
2092 r"c:\windows;c:\"));
2093 assert!(test_eq(&["", r"c:\windows", "", "", r"c:\", ""],
2094 r";c:\windows;;;c:\;"));
2095 assert!(test_eq(&[r"c:\te;st", r"c:\"],
2096 r#""c:\te;st";c:\"#));
2097 assert!(join_paths(&[r#"c:\te"st"#]).is_err());
2100 // More recursive_mkdir tests are in extra::tempfile