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};
43 use option::{Some, None, Option};
45 use path::{Path, GenericPath, BytesContainer};
47 use sys::os as os_imp;
50 use result::{Err, Ok, Result};
51 use slice::{AsSlice, SlicePrelude, PartialEqSlicePrelude};
52 use slice::CloneSliceAllocPrelude;
53 use str::{Str, StrPrelude, StrAllocating};
54 use string::{String, ToString};
55 use sync::atomic::{AtomicInt, INIT_ATOMIC_INT, SeqCst};
58 #[cfg(unix)] use c_str::ToCStr;
59 #[cfg(unix)] use libc::c_char;
62 pub use sys::ext as unix;
64 pub use sys::ext as windows;
66 /// Get the number of cores available
67 pub fn num_cpus() -> uint {
69 return rust_get_num_cpus() as uint;
73 fn rust_get_num_cpus() -> libc::uintptr_t;
77 pub const TMPBUF_SZ : uint = 1000u;
78 const BUF_BYTES : uint = 2048u;
80 /// Returns the current working directory as a `Path`.
84 /// Returns an `Err` if the current working directory value is invalid.
87 /// * Current directory does not exist.
88 /// * There are insufficient permissions to access the current directory.
89 /// * The internal buffer is not large enough to hold the path.
96 /// // We assume that we are in a valid directory like "/home".
97 /// let current_working_directory = os::getcwd().unwrap();
98 /// println!("The current directory is {}", current_working_directory.display());
102 pub fn getcwd() -> IoResult<Path> {
105 let mut buf = [0 as c_char, ..BUF_BYTES];
107 if libc::getcwd(buf.as_mut_ptr(), buf.len() as libc::size_t).is_null() {
108 Err(IoError::last_error())
110 Ok(Path::new(CString::new(buf.as_ptr(), false)))
115 /// Returns the current working directory as a `Path`.
119 /// Returns an `Err` if the current working directory value is invalid.
122 /// * Current directory does not exist.
123 /// * There are insufficient permissions to access the current directory.
124 /// * The internal buffer is not large enough to hold the path.
131 /// // We assume that we are in a valid directory like "C:\\Windows".
132 /// let current_working_directory = os::getcwd().unwrap();
133 /// println!("The current directory is {}", current_working_directory.display());
137 pub fn getcwd() -> IoResult<Path> {
139 use libc::GetCurrentDirectoryW;
140 use io::OtherIoError;
142 let mut buf = [0 as u16, ..BUF_BYTES];
144 if libc::GetCurrentDirectoryW(buf.len() as DWORD, buf.as_mut_ptr()) == 0 as DWORD {
145 return Err(IoError::last_error());
149 match String::from_utf16(::str::truncate_utf16_at_nul(&buf)) {
150 Some(ref cwd) => Ok(Path::new(cwd)),
151 None => Err(IoError {
153 desc: "GetCurrentDirectoryW returned invalid UTF-16",
161 use libc::types::os::arch::extra::DWORD;
163 use option::{None, Option};
166 use slice::{SlicePrelude};
171 pub fn fill_utf16_buf_and_decode(f: |*mut u16, DWORD| -> DWORD)
175 let mut n = TMPBUF_SZ as DWORD;
177 let mut done = false;
179 let mut buf = Vec::from_elem(n as uint, 0u16);
180 let k = f(buf.as_mut_ptr(), n);
181 if k == (0 as DWORD) {
184 libc::GetLastError() ==
185 libc::ERROR_INSUFFICIENT_BUFFER as DWORD {
193 let sub = buf.slice(0, k as uint);
194 // We want to explicitly catch the case when the
195 // closure returned invalid UTF-16, rather than
196 // set `res` to None and continue.
197 let s = String::from_utf16(sub)
198 .expect("fill_utf16_buf_and_decode: closure created invalid UTF-16");
199 res = option::Some(s)
208 Accessing environment variables is not generally threadsafe.
209 Serialize access through a global lock.
211 fn with_env_lock<T>(f: || -> T) -> T {
212 use rustrt::mutex::{StaticNativeMutex, NATIVE_MUTEX_INIT};
214 static LOCK: StaticNativeMutex = NATIVE_MUTEX_INIT;
217 let _guard = LOCK.lock();
222 /// Returns a vector of (variable, value) pairs, for all the environment
223 /// variables of the current process.
225 /// Invalid UTF-8 bytes are replaced with \uFFFD. See `String::from_utf8_lossy()`
233 /// // We will iterate through the references to the element returned by os::env();
234 /// for &(ref key, ref value) in os::env().iter() {
235 /// println!("'{}': '{}'", key, value );
238 pub fn env() -> Vec<(String,String)> {
239 env_as_bytes().into_iter().map(|(k,v)| {
240 let k = String::from_utf8_lossy(k.as_slice()).into_string();
241 let v = String::from_utf8_lossy(v.as_slice()).into_string();
246 /// Returns a vector of (variable, value) byte-vector pairs for all the
247 /// environment variables of the current process.
248 pub fn env_as_bytes() -> Vec<(Vec<u8>,Vec<u8>)> {
251 unsafe fn get_env_pairs() -> Vec<Vec<u8>> {
254 use libc::funcs::extra::kernel32::{
255 GetEnvironmentStringsW,
256 FreeEnvironmentStringsW
258 let ch = GetEnvironmentStringsW();
260 panic!("os::env() failure getting env string from OS: {}",
261 os::last_os_error());
263 // Here, we lossily decode the string as UTF16.
265 // The docs suggest that the result should be in Unicode, but
266 // Windows doesn't guarantee it's actually UTF16 -- it doesn't
267 // validate the environment string passed to CreateProcess nor
268 // SetEnvironmentVariable. Yet, it's unlikely that returning a
269 // raw u16 buffer would be of practical use since the result would
270 // be inherently platform-dependent and introduce additional
271 // complexity to this code.
273 // Using the non-Unicode version of GetEnvironmentStrings is even
274 // worse since the result is in an OEM code page. Characters that
275 // can't be encoded in the code page would be turned into question
277 let mut result = Vec::new();
279 while *ch.offset(i) != 0 {
280 let p = &*ch.offset(i);
282 while *(p as *const _).offset(len) != 0 {
285 let p = p as *const u16;
286 let s = slice::from_raw_buf(&p, len as uint);
287 result.push(String::from_utf16_lossy(s).into_bytes());
290 FreeEnvironmentStringsW(ch);
294 unsafe fn get_env_pairs() -> Vec<Vec<u8>> {
298 fn rust_env_pairs() -> *const *const c_char;
300 let mut environ = rust_env_pairs();
301 if environ as uint == 0 {
302 panic!("os::env() failure getting env string from OS: {}",
303 os::last_os_error());
305 let mut result = Vec::new();
306 while *environ != 0 as *const _ {
308 CString::new(*environ, false).as_bytes_no_nul().to_vec();
309 result.push(env_pair);
310 environ = environ.offset(1);
315 fn env_convert(input: Vec<Vec<u8>>) -> Vec<(Vec<u8>, Vec<u8>)> {
316 let mut pairs = Vec::new();
317 for p in input.iter() {
318 let mut it = p.as_slice().splitn(1, |b| *b == b'=');
319 let key = it.next().unwrap().to_vec();
320 let default: &[u8] = &[];
321 let val = it.next().unwrap_or(default).to_vec();
322 pairs.push((key, val));
327 let unparsed_environ = get_env_pairs();
328 env_convert(unparsed_environ)
334 /// Fetches the environment variable `n` from the current process, returning
335 /// None if the variable isn't set.
337 /// Any invalid UTF-8 bytes in the value are replaced by \uFFFD. See
338 /// `String::from_utf8_lossy()` for details.
342 /// Panics if `n` has any interior NULs.
349 /// let key = "HOME";
350 /// match os::getenv(key) {
351 /// Some(val) => println!("{}: {}", key, val),
352 /// None => println!("{} is not defined in the environment.", key)
355 pub fn getenv(n: &str) -> Option<String> {
356 getenv_as_bytes(n).map(|v| String::from_utf8_lossy(v.as_slice()).into_string())
360 /// Fetches the environment variable `n` byte vector from the current process,
361 /// returning None if the variable isn't set.
365 /// Panics if `n` has any interior NULs.
366 pub fn getenv_as_bytes(n: &str) -> Option<Vec<u8>> {
371 let s = n.with_c_str(|buf| libc::getenv(buf));
375 Some(CString::new(s as *const i8, false).as_bytes_no_nul().to_vec())
382 /// Fetches the environment variable `n` from the current process, returning
383 /// None if the variable isn't set.
384 pub fn getenv(n: &str) -> Option<String> {
387 use os::windows::{fill_utf16_buf_and_decode};
388 let mut n: Vec<u16> = n.utf16_units().collect();
390 fill_utf16_buf_and_decode(|buf, sz| {
391 libc::GetEnvironmentVariableW(n.as_ptr(), buf, sz)
398 /// Fetches the environment variable `n` byte vector from the current process,
399 /// returning None if the variable isn't set.
400 pub fn getenv_as_bytes(n: &str) -> Option<Vec<u8>> {
401 getenv(n).map(|s| s.into_bytes())
404 /// Sets the environment variable `n` to the value `v` for the currently running
413 /// os::setenv(key, "VALUE");
414 /// match os::getenv(key) {
415 /// Some(ref val) => println!("{}: {}", key, val),
416 /// None => println!("{} is not defined in the environment.", key)
419 pub fn setenv<T: BytesContainer>(n: &str, v: T) {
421 fn _setenv(n: &str, v: &[u8]) {
424 n.with_c_str(|nbuf| {
425 v.with_c_str(|vbuf| {
426 if libc::funcs::posix01::unistd::setenv(nbuf, vbuf, 1) != 0 {
427 panic!(IoError::last_error());
436 fn _setenv(n: &str, v: &[u8]) {
437 let mut n: Vec<u16> = n.utf16_units().collect();
439 let mut v: Vec<u16> = ::str::from_utf8(v).unwrap().utf16_units().collect();
444 if libc::SetEnvironmentVariableW(n.as_ptr(), v.as_ptr()) == 0 {
445 panic!(IoError::last_error());
451 _setenv(n, v.container_as_bytes())
454 /// Remove a variable from the environment entirely.
455 pub fn unsetenv(n: &str) {
457 fn _unsetenv(n: &str) {
460 n.with_c_str(|nbuf| {
461 if libc::funcs::posix01::unistd::unsetenv(nbuf) != 0 {
462 panic!(IoError::last_error());
470 fn _unsetenv(n: &str) {
471 let mut n: Vec<u16> = n.utf16_units().collect();
475 if libc::SetEnvironmentVariableW(n.as_ptr(), ptr::null()) == 0 {
476 panic!(IoError::last_error());
485 /// Parses input according to platform conventions for the `PATH`
486 /// environment variable.
492 /// let key = "PATH";
493 /// match os::getenv_as_bytes(key) {
495 /// for path in os::split_paths(paths).iter() {
496 /// println!("'{}'", path.display());
499 /// None => println!("{} is not defined in the environment.", key)
502 pub fn split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> {
504 fn _split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> {
505 unparsed.container_as_bytes()
506 .split(|b| *b == b':')
512 fn _split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> {
513 // On Windows, the PATH environment variable is semicolon separated. Double
514 // quotes are used as a way of introducing literal semicolons (since
515 // c:\some;dir is a valid Windows path). Double quotes are not themselves
516 // permitted in path names, so there is no way to escape a double quote.
517 // Quoted regions can appear in arbitrary locations, so
519 // c:\foo;c:\som"e;di"r;c:\bar
521 // Should parse as [c:\foo, c:\some;dir, c:\bar].
523 // (The above is based on testing; there is no clear reference available
526 let mut parsed = Vec::new();
527 let mut in_progress = Vec::new();
528 let mut in_quote = false;
530 for b in unparsed.container_as_bytes().iter() {
532 b';' if !in_quote => {
533 parsed.push(Path::new(in_progress.as_slice()));
534 in_progress.truncate(0)
537 in_quote = !in_quote;
540 in_progress.push(*b);
544 parsed.push(Path::new(in_progress));
548 _split_paths(unparsed)
551 /// Joins a collection of `Path`s appropriately for the `PATH`
552 /// environment variable.
554 /// Returns a `Vec<u8>` on success, since `Path`s are not utf-8
555 /// encoded on all platforms.
557 /// Returns an `Err` (containing an error message) if one of the input
558 /// `Path`s contains an invalid character for constructing the `PATH`
559 /// variable (a double quote on Windows or a colon on Unix).
565 /// use std::path::Path;
567 /// let key = "PATH";
568 /// let mut paths = os::getenv_as_bytes(key).map_or(Vec::new(), os::split_paths);
569 /// paths.push(Path::new("/home/xyz/bin"));
570 /// os::setenv(key, os::join_paths(paths.as_slice()).unwrap());
572 pub fn join_paths<T: BytesContainer>(paths: &[T]) -> Result<Vec<u8>, &'static str> {
574 fn _join_paths<T: BytesContainer>(paths: &[T]) -> Result<Vec<u8>, &'static str> {
575 let mut joined = Vec::new();
578 for (i, path) in paths.iter().map(|p| p.container_as_bytes()).enumerate() {
579 if i > 0 { joined.push(sep) }
580 if path.contains(&b'"') {
581 return Err("path segment contains `\"`");
582 } else if path.contains(&sep) {
584 joined.push_all(path);
587 joined.push_all(path);
595 fn _join_paths<T: BytesContainer>(paths: &[T]) -> Result<Vec<u8>, &'static str> {
596 let mut joined = Vec::new();
599 for (i, path) in paths.iter().map(|p| p.container_as_bytes()).enumerate() {
600 if i > 0 { joined.push(sep) }
601 if path.contains(&sep) { return Err("path segment contains separator `:`") }
602 joined.push_all(path);
611 /// A low-level OS in-memory pipe.
613 /// A file descriptor representing the reading end of the pipe. Data written
614 /// on the `out` file descriptor can be read from this file descriptor.
616 /// A file descriptor representing the write end of the pipe. Data written
617 /// to this file descriptor can be read from the `input` file descriptor.
621 /// Creates a new low-level OS in-memory pipe.
623 /// This function can fail to succeed if there are no more resources available
624 /// to allocate a pipe.
626 /// This function is also unsafe as there is no destructor associated with the
627 /// `Pipe` structure will return. If it is not arranged for the returned file
628 /// descriptors to be closed, the file descriptors will leak. For safe handling
629 /// of this scenario, use `std::io::PipeStream` instead.
630 pub unsafe fn pipe() -> IoResult<Pipe> {
631 let (reader, writer) = try!(sys::os::pipe());
633 reader: reader.unwrap(),
634 writer: writer.unwrap(),
638 /// Returns the proper dll filename for the given basename of a file
640 #[cfg(not(target_os="ios"))]
641 pub fn dll_filename(base: &str) -> String {
642 format!("{}{}{}", consts::DLL_PREFIX, base, consts::DLL_SUFFIX)
645 /// Optionally returns the filesystem path to the current executable which is
646 /// running but with the executable name.
653 /// match os::self_exe_name() {
654 /// Some(exe_path) => println!("Path of this executable is: {}", exe_path.display()),
655 /// None => println!("Unable to get the path of this executable!")
658 pub fn self_exe_name() -> Option<Path> {
660 #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))]
661 fn load_self() -> Option<Vec<u8>> {
663 use libc::funcs::bsd44::*;
664 use libc::consts::os::extra::*;
665 let mut mib = vec![CTL_KERN as c_int,
667 KERN_PROC_PATHNAME as c_int,
669 let mut sz: libc::size_t = 0;
670 let err = sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
671 ptr::null_mut(), &mut sz, ptr::null_mut(),
673 if err != 0 { return None; }
674 if sz == 0 { return None; }
675 let mut v: Vec<u8> = Vec::with_capacity(sz as uint);
676 let err = sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
677 v.as_mut_ptr() as *mut c_void, &mut sz,
678 ptr::null_mut(), 0u as libc::size_t);
679 if err != 0 { return None; }
680 if sz == 0 { return None; }
681 v.set_len(sz as uint - 1); // chop off trailing NUL
686 #[cfg(any(target_os = "linux", target_os = "android"))]
687 fn load_self() -> Option<Vec<u8>> {
690 match io::fs::readlink(&Path::new("/proc/self/exe")) {
691 Ok(path) => Some(path.into_vec()),
696 #[cfg(any(target_os = "macos", target_os = "ios"))]
697 fn load_self() -> Option<Vec<u8>> {
699 use libc::funcs::extra::_NSGetExecutablePath;
701 _NSGetExecutablePath(ptr::null_mut(), &mut sz);
702 if sz == 0 { return None; }
703 let mut v: Vec<u8> = Vec::with_capacity(sz as uint);
704 let err = _NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz);
705 if err != 0 { return None; }
706 v.set_len(sz as uint - 1); // chop off trailing NUL
712 fn load_self() -> Option<Vec<u8>> {
714 use os::windows::fill_utf16_buf_and_decode;
715 fill_utf16_buf_and_decode(|buf, sz| {
716 libc::GetModuleFileNameW(0u as libc::DWORD, buf, sz)
717 }).map(|s| s.into_string().into_bytes())
721 load_self().and_then(Path::new_opt)
724 /// Optionally returns the filesystem path to the current executable which is
727 /// Like self_exe_name() but without the binary's name.
734 /// match os::self_exe_path() {
735 /// Some(exe_path) => println!("Executable's Path is: {}", exe_path.display()),
736 /// None => println!("Impossible to fetch the path of this executable.")
739 pub fn self_exe_path() -> Option<Path> {
740 self_exe_name().map(|mut p| { p.pop(); p })
743 /// Optionally returns the path to the current user's home directory if known.
747 /// Returns the value of the 'HOME' environment variable if it is set
748 /// and not equal to the empty string.
752 /// Returns the value of the 'HOME' environment variable if it is
753 /// set and not equal to the empty string. Otherwise, returns the value of the
754 /// 'USERPROFILE' environment variable if it is set and not equal to the empty
762 /// match os::homedir() {
763 /// Some(ref p) => println!("{}", p.display()),
764 /// None => println!("Impossible to get your home dir!")
767 pub fn homedir() -> Option<Path> {
770 fn _homedir() -> Option<Path> {
776 fn _homedir() -> Option<Path> {
777 aux_homedir("HOME").or(aux_homedir("USERPROFILE"))
781 fn aux_homedir(home_name: &str) -> Option<Path> {
782 match getenv_as_bytes(home_name) {
784 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
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.
804 pub fn tmpdir() -> Path {
807 fn getenv_nonempty(v: &str) -> Option<Path> {
820 fn lookup() -> Path {
821 let default = if cfg!(target_os = "android") {
822 Path::new("/data/local/tmp")
827 getenv_nonempty("TMPDIR").unwrap_or(default)
831 fn lookup() -> Path {
832 getenv_nonempty("TMP").or(
833 getenv_nonempty("TEMP").or(
834 getenv_nonempty("USERPROFILE").or(
835 getenv_nonempty("WINDIR")))).unwrap_or(Path::new("C:\\Windows"))
840 /// Convert a relative path to an absolute path
842 /// If the given path is relative, return it prepended with the current working
843 /// directory. If the given path is already an absolute path, return it
849 /// use std::path::Path;
851 /// // Assume we're in a path like /home/someuser
852 /// let rel_path = Path::new("..");
853 /// let abs_path = os::make_absolute(&rel_path).unwrap();
854 /// println!("The absolute path is {}", abs_path.display());
855 /// // Prints "The absolute path is /home"
857 // NB: this is here rather than in path because it is a form of environment
858 // querying; what it does depends on the process working directory, not just
860 pub fn make_absolute(p: &Path) -> IoResult<Path> {
864 getcwd().map(|mut cwd| {
871 /// Changes the current working directory to the specified path, returning
872 /// whether the change was completed successfully or not.
877 /// use std::path::Path;
879 /// let root = Path::new("/");
880 /// assert!(os::change_dir(&root).is_ok());
881 /// println!("Successfully changed working directory to {}!", root.display());
883 pub fn change_dir(p: &Path) -> IoResult<()> {
887 fn chdir(p: &Path) -> IoResult<()> {
888 let mut p = p.as_str().unwrap().utf16_units().collect::<Vec<u16>>();
892 match libc::SetCurrentDirectoryW(p.as_ptr()) != (0 as libc::BOOL) {
894 false => Err(IoError::last_error()),
900 fn chdir(p: &Path) -> IoResult<()> {
903 match libc::chdir(buf) == (0 as c_int) {
905 false => Err(IoError::last_error()),
912 /// Returns the platform-specific value of errno
913 pub fn errno() -> uint {
914 os_imp::errno() as uint
917 /// Return the string corresponding to an `errno()` value of `errnum`.
923 /// // Same as println!("{}", last_os_error());
924 /// println!("{}", os::error_string(os::errno() as uint));
926 pub fn error_string(errnum: uint) -> String {
927 return os_imp::error_string(errnum as i32);
930 /// Get a string representing the platform-dependent last error
931 pub fn last_os_error() -> String {
932 error_string(errno() as uint)
935 static EXIT_STATUS: AtomicInt = INIT_ATOMIC_INT;
938 * Sets the process exit code
940 * Sets the exit code returned by the process if all supervised tasks
941 * terminate successfully (without panicking). If the current root task panics
942 * and is supervised by the scheduler then any user-specified exit status is
943 * ignored and the process exits with the default panic status.
945 * 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()
968 * Returns the command line arguments
970 * Returns a list of the command line arguments.
972 #[cfg(target_os = "macos")]
973 fn real_args_as_bytes() -> Vec<Vec<u8>> {
975 let (argc, argv) = (*_NSGetArgc() as int,
976 *_NSGetArgv() as *const *const c_char);
977 load_argc_and_argv(argc, argv)
981 // As _NSGetArgc and _NSGetArgv aren't mentioned in iOS docs
982 // and use underscores in their names - they're most probably
983 // are considered private and therefore should be avoided
984 // Here is another way to get arguments using Objective C
987 // In general it looks like:
989 // let args = [[NSProcessInfo processInfo] arguments]
990 // for i in range(0, [args count])
991 // res.push([args objectAtIndex:i])
993 #[cfg(target_os = "ios")]
994 fn real_args_as_bytes() -> Vec<Vec<u8>> {
999 #[link(name = "objc")]
1001 fn sel_registerName(name: *const libc::c_uchar) -> Sel;
1002 fn objc_msgSend(obj: NsId, sel: Sel, ...) -> NsId;
1003 fn objc_getClass(class_name: *const libc::c_uchar) -> NsId;
1006 #[link(name = "Foundation", kind = "framework")]
1009 type Sel = *const libc::c_void;
1010 type NsId = *const libc::c_void;
1012 let mut res = Vec::new();
1015 let processInfoSel = sel_registerName("processInfo\0".as_ptr());
1016 let argumentsSel = sel_registerName("arguments\0".as_ptr());
1017 let utf8Sel = sel_registerName("UTF8String\0".as_ptr());
1018 let countSel = sel_registerName("count\0".as_ptr());
1019 let objectAtSel = sel_registerName("objectAtIndex:\0".as_ptr());
1021 let klass = objc_getClass("NSProcessInfo\0".as_ptr());
1022 let info = objc_msgSend(klass, processInfoSel);
1023 let args = objc_msgSend(info, argumentsSel);
1025 let cnt: int = mem::transmute(objc_msgSend(args, countSel));
1026 for i in range(0, cnt) {
1027 let tmp = objc_msgSend(args, objectAtSel, i);
1028 let utf_c_str: *const libc::c_char =
1029 mem::transmute(objc_msgSend(tmp, utf8Sel));
1030 let s = CString::new(utf_c_str, false);
1031 res.push(s.as_bytes_no_nul().to_vec())
1038 #[cfg(any(target_os = "linux",
1039 target_os = "android",
1040 target_os = "freebsd",
1041 target_os = "dragonfly"))]
1042 fn real_args_as_bytes() -> Vec<Vec<u8>> {
1045 match rustrt::args::clone() {
1047 None => panic!("process arguments not initialized")
1051 #[cfg(not(windows))]
1052 fn real_args() -> Vec<String> {
1053 real_args_as_bytes().into_iter()
1055 String::from_utf8_lossy(v.as_slice()).into_string()
1060 fn real_args() -> Vec<String> {
1063 let mut nArgs: c_int = 0;
1064 let lpArgCount: *mut c_int = &mut nArgs;
1065 let lpCmdLine = unsafe { GetCommandLineW() };
1066 let szArgList = unsafe { CommandLineToArgvW(lpCmdLine, lpArgCount) };
1068 let args = Vec::from_fn(nArgs as uint, |i| unsafe {
1069 // Determine the length of this argument.
1070 let ptr = *szArgList.offset(i as int);
1072 while *ptr.offset(len as int) != 0 { len += 1; }
1074 // Push it onto the list.
1075 let ptr = ptr as *const u16;
1076 let buf = slice::from_raw_buf(&ptr, len);
1077 let opt_s = String::from_utf16(::str::truncate_utf16_at_nul(buf));
1078 opt_s.expect("CommandLineToArgvW returned invalid UTF-16")
1082 LocalFree(szArgList as *mut c_void);
1089 fn real_args_as_bytes() -> Vec<Vec<u8>> {
1090 real_args().into_iter().map(|s| s.into_bytes()).collect()
1093 type LPCWSTR = *const u16;
1096 #[link_name="kernel32"]
1098 fn GetCommandLineW() -> LPCWSTR;
1099 fn LocalFree(ptr: *mut c_void);
1103 #[link_name="shell32"]
1105 fn CommandLineToArgvW(lpCmdLine: LPCWSTR,
1106 pNumArgs: *mut c_int) -> *mut *mut u16;
1109 /// Returns the arguments which this program was started with (normally passed
1110 /// via the command line).
1112 /// The first element is traditionally the path to the executable, but it can be
1113 /// set to arbitrary text, and it may not even exist, so this property should not
1114 /// be relied upon for security purposes.
1116 /// The arguments are interpreted as utf-8, with invalid bytes replaced with \uFFFD.
1117 /// See `String::from_utf8_lossy` for details.
1123 /// // Prints each argument on a separate line
1124 /// for argument in os::args().iter() {
1125 /// println!("{}", argument);
1128 pub fn args() -> Vec<String> {
1132 /// Returns the arguments which this program was started with (normally passed
1133 /// via the command line) as byte vectors.
1134 pub fn args_as_bytes() -> Vec<Vec<u8>> {
1135 real_args_as_bytes()
1138 #[cfg(target_os = "macos")]
1140 // These functions are in crt_externs.h.
1141 pub fn _NSGetArgc() -> *mut c_int;
1142 pub fn _NSGetArgv() -> *mut *mut *mut c_char;
1145 // Round up `from` to be divisible by `to`
1146 fn round_up(from: uint, to: uint) -> uint {
1147 let r = if from % to == 0 {
1150 from + to - (from % to)
1159 /// Returns the page size of the current architecture in bytes.
1161 pub fn page_size() -> uint {
1163 libc::sysconf(libc::_SC_PAGESIZE) as uint
1167 /// Returns the page size of the current architecture in bytes.
1169 pub fn page_size() -> uint {
1172 let mut info = mem::zeroed();
1173 libc::GetSystemInfo(&mut info);
1175 return info.dwPageSize as uint;
1179 /// A memory mapped file or chunk of memory. This is a very system-specific
1180 /// interface to the OS's memory mapping facilities (`mmap` on POSIX,
1181 /// `VirtualAlloc`/`CreateFileMapping` on Windows). It makes no attempt at
1182 /// abstracting platform differences, besides in error values returned. Consider
1183 /// yourself warned.
1185 /// The memory map is released (unmapped) when the destructor is run, so don't
1186 /// let it leave scope by accident if you want it to stick around.
1187 pub struct MemoryMap {
1190 kind: MemoryMapKind,
1193 /// Type of memory map
1194 pub enum MemoryMapKind {
1195 /// Virtual memory map. Usually used to change the permissions of a given
1196 /// chunk of memory. Corresponds to `VirtualAlloc` on Windows.
1198 /// Virtual memory map. Usually used to change the permissions of a given
1199 /// chunk of memory, or for allocation. Corresponds to `VirtualAlloc` on
1204 /// Options the memory map is created with
1205 pub enum MapOption {
1206 /// The memory should be readable
1208 /// The memory should be writable
1210 /// The memory should be executable
1212 /// Create a map for a specific address range. Corresponds to `MAP_FIXED` on
1215 /// Create a memory mapping for a file with a given fd.
1217 /// When using `MapFd`, the start of the map is `uint` bytes from the start
1220 /// On POSIX, this can be used to specify the default flags passed to
1221 /// `mmap`. By default it uses `MAP_PRIVATE` and, if not using `MapFd`,
1222 /// `MAP_ANON`. This will override both of those. This is platform-specific
1223 /// (the exact values used) and ignored on Windows.
1224 MapNonStandardFlags(c_int),
1227 /// Possible errors when creating a map.
1229 /// ## The following are POSIX-specific
1231 /// fd was not open for reading or, if using `MapWritable`, was not open for
1234 /// fd was not valid
1236 /// Either the address given by `MapAddr` or offset given by `MapOffset` was
1237 /// not a multiple of `MemoryMap::granularity` (unaligned to page size).
1239 /// With `MapFd`, the fd does not support mapping.
1241 /// If using `MapAddr`, the address + `min_len` was outside of the process's
1242 /// address space. If using `MapFd`, the target of the fd didn't have enough
1243 /// resources to fulfill the request.
1245 /// A zero-length map was requested. This is invalid according to
1246 /// [POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/functions/mmap.html).
1247 /// Not all platforms obey this, but this wrapper does.
1249 /// Unrecognized error. The inner value is the unrecognized errno.
1251 /// ## The following are Windows-specific
1253 /// Unsupported combination of protection flags
1254 /// (`MapReadable`/`MapWritable`/`MapExecutable`).
1256 /// When using `MapFd`, `MapOffset` was given (Windows does not support this
1259 /// When using `MapFd`, there was already a mapping to the file.
1261 /// Unrecognized error from `VirtualAlloc`. The inner value is the return
1262 /// value of GetLastError.
1263 ErrVirtualAlloc(uint),
1264 /// Unrecognized error from `CreateFileMapping`. The inner value is the
1265 /// return value of `GetLastError`.
1266 ErrCreateFileMappingW(uint),
1267 /// Unrecognized error from `MapViewOfFile`. The inner value is the return
1268 /// value of `GetLastError`.
1269 ErrMapViewOfFile(uint)
1272 impl fmt::Show for MapError {
1273 fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result {
1274 let str = match *self {
1275 ErrFdNotAvail => "fd not available for reading or writing",
1276 ErrInvalidFd => "Invalid fd",
1278 "Unaligned address, invalid flags, negative length or \
1281 ErrNoMapSupport=> "File doesn't support mapping",
1282 ErrNoMem => "Invalid address, or not enough available memory",
1283 ErrUnsupProt => "Protection mode unsupported",
1284 ErrUnsupOffset => "Offset in virtual memory mode is unsupported",
1285 ErrAlreadyExists => "File mapping for specified file already exists",
1286 ErrZeroLength => "Zero-length mapping not allowed",
1287 ErrUnknown(code) => {
1288 return write!(out, "Unknown error = {}", code)
1290 ErrVirtualAlloc(code) => {
1291 return write!(out, "VirtualAlloc failure = {}", code)
1293 ErrCreateFileMappingW(code) => {
1294 return write!(out, "CreateFileMappingW failure = {}", code)
1296 ErrMapViewOfFile(code) => {
1297 return write!(out, "MapViewOfFile failure = {}", code)
1300 write!(out, "{}", str)
1304 impl Error for MapError {
1305 fn description(&self) -> &str { "memory map error" }
1306 fn detail(&self) -> Option<String> { Some(self.to_string()) }
1309 impl FromError<MapError> for Box<Error> {
1310 fn from_error(err: MapError) -> Box<Error> {
1317 /// Create a new mapping with the given `options`, at least `min_len` bytes
1318 /// long. `min_len` must be greater than zero; see the note on
1319 /// `ErrZeroLength`.
1320 pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
1324 return Err(ErrZeroLength)
1326 let mut addr: *const u8 = ptr::null();
1328 let mut flags = libc::MAP_PRIVATE;
1331 let mut custom_flags = false;
1332 let len = round_up(min_len, page_size());
1334 for &o in options.iter() {
1336 MapReadable => { prot |= libc::PROT_READ; },
1337 MapWritable => { prot |= libc::PROT_WRITE; },
1338 MapExecutable => { prot |= libc::PROT_EXEC; },
1340 flags |= libc::MAP_FIXED;
1344 flags |= libc::MAP_FILE;
1347 MapOffset(offset_) => { offset = offset_ as off_t; },
1348 MapNonStandardFlags(f) => { custom_flags = true; flags = f },
1351 if fd == -1 && !custom_flags { flags |= libc::MAP_ANON; }
1354 libc::mmap(addr as *mut c_void, len as libc::size_t, prot, flags,
1357 if r == libc::MAP_FAILED {
1358 Err(match errno() as c_int {
1359 libc::EACCES => ErrFdNotAvail,
1360 libc::EBADF => ErrInvalidFd,
1361 libc::EINVAL => ErrUnaligned,
1362 libc::ENODEV => ErrNoMapSupport,
1363 libc::ENOMEM => ErrNoMem,
1364 code => ErrUnknown(code as int)
1373 MapFile(ptr::null())
1379 /// Granularity that the offset or address must be for `MapOffset` and
1380 /// `MapAddr` respectively.
1381 pub fn granularity() -> uint {
1387 impl Drop for MemoryMap {
1388 /// Unmap the mapping. Panics the task if `munmap` panics.
1389 fn drop(&mut self) {
1390 if self.len == 0 { /* workaround for dummy_stack */ return; }
1393 // `munmap` only panics due to logic errors
1394 libc::munmap(self.data as *mut c_void, self.len as libc::size_t);
1401 /// Create a new mapping with the given `options`, at least `min_len` bytes long.
1402 pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
1403 use libc::types::os::arch::extra::{LPVOID, DWORD, SIZE_T, HANDLE};
1405 let mut lpAddress: LPVOID = ptr::null_mut();
1406 let mut readable = false;
1407 let mut writable = false;
1408 let mut executable = false;
1409 let mut fd: c_int = -1;
1410 let mut offset: uint = 0;
1411 let len = round_up(min_len, page_size());
1413 for &o in options.iter() {
1415 MapReadable => { readable = true; },
1416 MapWritable => { writable = true; },
1417 MapExecutable => { executable = true; }
1418 MapAddr(addr_) => { lpAddress = addr_ as LPVOID; },
1419 MapFd(fd_) => { fd = fd_; },
1420 MapOffset(offset_) => { offset = offset_; },
1421 MapNonStandardFlags(..) => {}
1425 let flProtect = match (executable, readable, writable) {
1426 (false, false, false) if fd == -1 => libc::PAGE_NOACCESS,
1427 (false, true, false) => libc::PAGE_READONLY,
1428 (false, true, true) => libc::PAGE_READWRITE,
1429 (true, false, false) if fd == -1 => libc::PAGE_EXECUTE,
1430 (true, true, false) => libc::PAGE_EXECUTE_READ,
1431 (true, true, true) => libc::PAGE_EXECUTE_READWRITE,
1432 _ => return Err(ErrUnsupProt)
1437 return Err(ErrUnsupOffset);
1440 libc::VirtualAlloc(lpAddress,
1442 libc::MEM_COMMIT | libc::MEM_RESERVE,
1446 0 => Err(ErrVirtualAlloc(errno())),
1454 let dwDesiredAccess = match (executable, readable, writable) {
1455 (false, true, false) => libc::FILE_MAP_READ,
1456 (false, true, true) => libc::FILE_MAP_WRITE,
1457 (true, true, false) => libc::FILE_MAP_READ | libc::FILE_MAP_EXECUTE,
1458 (true, true, true) => libc::FILE_MAP_WRITE | libc::FILE_MAP_EXECUTE,
1459 _ => return Err(ErrUnsupProt) // Actually, because of the check above,
1460 // we should never get here.
1463 let hFile = libc::get_osfhandle(fd) as HANDLE;
1464 let mapping = libc::CreateFileMappingW(hFile,
1470 if mapping == ptr::null_mut() {
1471 return Err(ErrCreateFileMappingW(errno()));
1473 if errno() as c_int == libc::ERROR_ALREADY_EXISTS {
1474 return Err(ErrAlreadyExists);
1476 let r = libc::MapViewOfFile(mapping,
1478 ((len as u64) >> 32) as DWORD,
1479 (offset & 0xffff_ffff) as DWORD,
1482 0 => Err(ErrMapViewOfFile(errno())),
1486 kind: MapFile(mapping as *const u8)
1493 /// Granularity of MapAddr() and MapOffset() parameter values.
1494 /// This may be greater than the value returned by page_size().
1495 pub fn granularity() -> uint {
1498 let mut info = mem::zeroed();
1499 libc::GetSystemInfo(&mut info);
1501 return info.dwAllocationGranularity as uint;
1507 impl Drop for MemoryMap {
1508 /// Unmap the mapping. Panics the task if any of `VirtualFree`,
1509 /// `UnmapViewOfFile`, or `CloseHandle` fail.
1510 fn drop(&mut self) {
1511 use libc::types::os::arch::extra::{LPCVOID, HANDLE};
1512 use libc::consts::os::extra::FALSE;
1513 if self.len == 0 { return }
1518 if libc::VirtualFree(self.data as *mut c_void, 0,
1519 libc::MEM_RELEASE) == 0 {
1520 println!("VirtualFree failed: {}", errno());
1523 MapFile(mapping) => {
1524 if libc::UnmapViewOfFile(self.data as LPCVOID) == FALSE {
1525 println!("UnmapViewOfFile failed: {}", errno());
1527 if libc::CloseHandle(mapping as HANDLE) == FALSE {
1528 println!("CloseHandle failed: {}", errno());
1537 /// Returns the pointer to the memory created or modified by this map.
1538 pub fn data(&self) -> *mut u8 { self.data }
1539 /// Returns the number of bytes this map applies to.
1540 pub fn len(&self) -> uint { self.len }
1541 /// Returns the type of mapping this represents.
1542 pub fn kind(&self) -> MemoryMapKind { self.kind }
1545 #[cfg(target_os = "linux")]
1547 pub use os::arch_consts::ARCH;
1549 pub const FAMILY: &'static str = "unix";
1551 /// A string describing the specific operating system in use: in this
1553 pub const SYSNAME: &'static str = "linux";
1555 /// Specifies the filename prefix used for shared libraries on this
1556 /// platform: in this case, `lib`.
1557 pub const DLL_PREFIX: &'static str = "lib";
1559 /// Specifies the filename suffix used for shared libraries on this
1560 /// platform: in this case, `.so`.
1561 pub const DLL_SUFFIX: &'static str = ".so";
1563 /// Specifies the file extension used for shared libraries on this
1564 /// platform that goes after the dot: in this case, `so`.
1565 pub const DLL_EXTENSION: &'static str = "so";
1567 /// Specifies the filename suffix used for executable binaries on this
1568 /// platform: in this case, the empty string.
1569 pub const EXE_SUFFIX: &'static str = "";
1571 /// Specifies the file extension, if any, used for executable binaries
1572 /// on this platform: in this case, the empty string.
1573 pub const EXE_EXTENSION: &'static str = "";
1576 #[cfg(target_os = "macos")]
1578 pub use os::arch_consts::ARCH;
1580 pub const FAMILY: &'static str = "unix";
1582 /// A string describing the specific operating system in use: in this
1584 pub const SYSNAME: &'static str = "macos";
1586 /// Specifies the filename prefix used for shared libraries on this
1587 /// platform: in this case, `lib`.
1588 pub const DLL_PREFIX: &'static str = "lib";
1590 /// Specifies the filename suffix used for shared libraries on this
1591 /// platform: in this case, `.dylib`.
1592 pub const DLL_SUFFIX: &'static str = ".dylib";
1594 /// Specifies the file extension used for shared libraries on this
1595 /// platform that goes after the dot: in this case, `dylib`.
1596 pub const DLL_EXTENSION: &'static str = "dylib";
1598 /// Specifies the filename suffix used for executable binaries on this
1599 /// platform: in this case, the empty string.
1600 pub const EXE_SUFFIX: &'static str = "";
1602 /// Specifies the file extension, if any, used for executable binaries
1603 /// on this platform: in this case, the empty string.
1604 pub const EXE_EXTENSION: &'static str = "";
1607 #[cfg(target_os = "ios")]
1609 pub use os::arch_consts::ARCH;
1611 pub const FAMILY: &'static str = "unix";
1613 /// A string describing the specific operating system in use: in this
1615 pub const SYSNAME: &'static str = "ios";
1617 /// Specifies the filename suffix used for executable binaries on this
1618 /// platform: in this case, the empty string.
1619 pub const EXE_SUFFIX: &'static str = "";
1621 /// Specifies the file extension, if any, used for executable binaries
1622 /// on this platform: in this case, the empty string.
1623 pub const EXE_EXTENSION: &'static str = "";
1626 #[cfg(target_os = "freebsd")]
1628 pub use os::arch_consts::ARCH;
1630 pub const FAMILY: &'static str = "unix";
1632 /// A string describing the specific operating system in use: in this
1633 /// case, `freebsd`.
1634 pub const SYSNAME: &'static str = "freebsd";
1636 /// Specifies the filename prefix used for shared libraries on this
1637 /// platform: in this case, `lib`.
1638 pub const DLL_PREFIX: &'static str = "lib";
1640 /// Specifies the filename suffix used for shared libraries on this
1641 /// platform: in this case, `.so`.
1642 pub const DLL_SUFFIX: &'static str = ".so";
1644 /// Specifies the file extension used for shared libraries on this
1645 /// platform that goes after the dot: in this case, `so`.
1646 pub const DLL_EXTENSION: &'static str = "so";
1648 /// Specifies the filename suffix used for executable binaries on this
1649 /// platform: in this case, the empty string.
1650 pub const EXE_SUFFIX: &'static str = "";
1652 /// Specifies the file extension, if any, used for executable binaries
1653 /// on this platform: in this case, the empty string.
1654 pub const EXE_EXTENSION: &'static str = "";
1657 #[cfg(target_os = "dragonfly")]
1659 pub use os::arch_consts::ARCH;
1661 pub const FAMILY: &'static str = "unix";
1663 /// A string describing the specific operating system in use: in this
1664 /// case, `dragonfly`.
1665 pub const SYSNAME: &'static str = "dragonfly";
1667 /// Specifies the filename prefix used for shared libraries on this
1668 /// platform: in this case, `lib`.
1669 pub const DLL_PREFIX: &'static str = "lib";
1671 /// Specifies the filename suffix used for shared libraries on this
1672 /// platform: in this case, `.so`.
1673 pub const DLL_SUFFIX: &'static str = ".so";
1675 /// Specifies the file extension used for shared libraries on this
1676 /// platform that goes after the dot: in this case, `so`.
1677 pub const DLL_EXTENSION: &'static str = "so";
1679 /// Specifies the filename suffix used for executable binaries on this
1680 /// platform: in this case, the empty string.
1681 pub const EXE_SUFFIX: &'static str = "";
1683 /// Specifies the file extension, if any, used for executable binaries
1684 /// on this platform: in this case, the empty string.
1685 pub const EXE_EXTENSION: &'static str = "";
1688 #[cfg(target_os = "android")]
1690 pub use os::arch_consts::ARCH;
1692 pub const FAMILY: &'static str = "unix";
1694 /// A string describing the specific operating system in use: in this
1695 /// case, `android`.
1696 pub const SYSNAME: &'static str = "android";
1698 /// Specifies the filename prefix used for shared libraries on this
1699 /// platform: in this case, `lib`.
1700 pub const DLL_PREFIX: &'static str = "lib";
1702 /// Specifies the filename suffix used for shared libraries on this
1703 /// platform: in this case, `.so`.
1704 pub const DLL_SUFFIX: &'static str = ".so";
1706 /// Specifies the file extension used for shared libraries on this
1707 /// platform that goes after the dot: in this case, `so`.
1708 pub const DLL_EXTENSION: &'static str = "so";
1710 /// Specifies the filename suffix used for executable binaries on this
1711 /// platform: in this case, the empty string.
1712 pub const EXE_SUFFIX: &'static str = "";
1714 /// Specifies the file extension, if any, used for executable binaries
1715 /// on this platform: in this case, the empty string.
1716 pub const EXE_EXTENSION: &'static str = "";
1719 #[cfg(target_os = "windows")]
1721 pub use os::arch_consts::ARCH;
1723 pub const FAMILY: &'static str = "windows";
1725 /// A string describing the specific operating system in use: in this
1726 /// case, `windows`.
1727 pub const SYSNAME: &'static str = "windows";
1729 /// Specifies the filename prefix used for shared libraries on this
1730 /// platform: in this case, the empty string.
1731 pub const DLL_PREFIX: &'static str = "";
1733 /// Specifies the filename suffix used for shared libraries on this
1734 /// platform: in this case, `.dll`.
1735 pub const DLL_SUFFIX: &'static str = ".dll";
1737 /// Specifies the file extension used for shared libraries on this
1738 /// platform that goes after the dot: in this case, `dll`.
1739 pub const DLL_EXTENSION: &'static str = "dll";
1741 /// Specifies the filename suffix used for executable binaries on this
1742 /// platform: in this case, `.exe`.
1743 pub const EXE_SUFFIX: &'static str = ".exe";
1745 /// Specifies the file extension, if any, used for executable binaries
1746 /// on this platform: in this case, `exe`.
1747 pub const EXE_EXTENSION: &'static str = "exe";
1750 #[cfg(target_arch = "x86")]
1752 pub const ARCH: &'static str = "x86";
1755 #[cfg(target_arch = "x86_64")]
1757 pub const ARCH: &'static str = "x86_64";
1760 #[cfg(target_arch = "arm")]
1762 pub const ARCH: &'static str = "arm";
1765 #[cfg(target_arch = "mips")]
1767 pub const ARCH: &'static str = "mips";
1770 #[cfg(target_arch = "mipsel")]
1772 pub const ARCH: &'static str = "mipsel";
1780 use os::{env, getcwd, getenv, make_absolute};
1781 use os::{split_paths, join_paths, setenv, unsetenv};
1787 pub fn last_os_error() {
1788 debug!("{}", os::last_os_error());
1791 fn make_rand_name() -> String {
1792 let mut rng = rand::task_rng();
1793 let n = format!("TEST{}", rng.gen_ascii_chars().take(10u)
1794 .collect::<String>());
1795 assert!(getenv(n.as_slice()).is_none());
1800 fn test_num_cpus() {
1801 assert!(os::num_cpus() > 0);
1806 let n = make_rand_name();
1807 setenv(n.as_slice(), "VALUE");
1808 assert_eq!(getenv(n.as_slice()), option::Some("VALUE".to_string()));
1812 fn test_unsetenv() {
1813 let n = make_rand_name();
1814 setenv(n.as_slice(), "VALUE");
1815 unsetenv(n.as_slice());
1816 assert_eq!(getenv(n.as_slice()), option::None);
1821 fn test_setenv_overwrite() {
1822 let n = make_rand_name();
1823 setenv(n.as_slice(), "1");
1824 setenv(n.as_slice(), "2");
1825 assert_eq!(getenv(n.as_slice()), option::Some("2".to_string()));
1826 setenv(n.as_slice(), "");
1827 assert_eq!(getenv(n.as_slice()), option::Some("".to_string()));
1830 // Windows GetEnvironmentVariable requires some extra work to make sure
1831 // the buffer the variable is copied into is the right size
1834 fn test_getenv_big() {
1835 let mut s = "".to_string();
1838 s.push_str("aaaaaaaaaa");
1841 let n = make_rand_name();
1842 setenv(n.as_slice(), s.as_slice());
1843 debug!("{}", s.clone());
1844 assert_eq!(getenv(n.as_slice()), option::Some(s));
1848 fn test_self_exe_name() {
1849 let path = os::self_exe_name();
1850 assert!(path.is_some());
1851 let path = path.unwrap();
1852 debug!("{}", path.display());
1854 // Hard to test this function
1855 assert!(path.is_absolute());
1859 fn test_self_exe_path() {
1860 let path = os::self_exe_path();
1861 assert!(path.is_some());
1862 let path = path.unwrap();
1863 debug!("{}", path.display());
1865 // Hard to test this function
1866 assert!(path.is_absolute());
1871 fn test_env_getenv() {
1873 assert!(e.len() > 0u);
1875 let (n, v) = (*p).clone();
1877 let v2 = getenv(n.as_slice());
1878 // MingW seems to set some funky environment variables like
1879 // "=C:=C:\MinGW\msys\1.0\bin" and "!::=::\" that are returned
1880 // from env() but not visible from getenv().
1881 assert!(v2.is_none() || v2 == option::Some(v));
1886 fn test_env_set_get_huge() {
1887 let n = make_rand_name();
1888 let s = "x".repeat(10000).to_string();
1889 setenv(n.as_slice(), s.as_slice());
1890 assert_eq!(getenv(n.as_slice()), Some(s));
1891 unsetenv(n.as_slice());
1892 assert_eq!(getenv(n.as_slice()), None);
1896 fn test_env_setenv() {
1897 let n = make_rand_name();
1900 setenv(n.as_slice(), "VALUE");
1901 assert!(!e.contains(&(n.clone(), "VALUE".to_string())));
1904 assert!(e.contains(&(n, "VALUE".to_string())));
1909 assert!((!Path::new("test-path").is_absolute()));
1911 let cwd = getcwd().unwrap();
1912 debug!("Current working directory: {}", cwd.display());
1914 debug!("{}", make_absolute(&Path::new("test-path")).unwrap().display());
1915 debug!("{}", make_absolute(&Path::new("/usr/bin")).unwrap().display());
1921 let oldhome = getenv("HOME");
1923 setenv("HOME", "/home/MountainView");
1924 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1927 assert!(os::homedir().is_none());
1929 for s in oldhome.iter() {
1930 setenv("HOME", s.as_slice());
1938 let oldhome = getenv("HOME");
1939 let olduserprofile = getenv("USERPROFILE");
1942 setenv("USERPROFILE", "");
1944 assert!(os::homedir().is_none());
1946 setenv("HOME", "/home/MountainView");
1947 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1951 setenv("USERPROFILE", "/home/MountainView");
1952 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1954 setenv("HOME", "/home/MountainView");
1955 setenv("USERPROFILE", "/home/PaloAlto");
1956 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1958 for s in oldhome.iter() {
1959 setenv("HOME", s.as_slice());
1961 for s in olduserprofile.iter() {
1962 setenv("USERPROFILE", s.as_slice());
1967 fn memory_map_rw() {
1968 use result::{Ok, Err};
1970 let chunk = match os::MemoryMap::new(16, &[
1975 Err(msg) => panic!("{}", msg)
1977 assert!(chunk.len >= 16);
1981 assert!(*chunk.data == 0xBE);
1986 fn memory_map_file() {
1987 use result::{Ok, Err};
1993 fn lseek_(fd: c_int, size: uint) {
1995 assert!(lseek(fd, size as off_t, SEEK_SET) == size as off_t);
1999 fn lseek_(fd: c_int, size: uint) {
2001 assert!(lseek(fd, size as c_long, SEEK_SET) == size as c_long);
2005 let mut path = tmpdir();
2006 path.push("mmap_file.tmp");
2007 let size = MemoryMap::granularity() * 2;
2010 let fd = path.with_c_str(|path| {
2011 open(path, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR)
2014 "x".with_c_str(|x| assert!(write(fd, x as *const c_void, 1) == 1));
2017 let chunk = match MemoryMap::new(size / 2, &[
2024 Err(msg) => panic!("{}", msg)
2026 assert!(chunk.len > 0);
2030 assert!(*chunk.data == 0xbe);
2035 fs::unlink(&path).unwrap();
2040 fn split_paths_windows() {
2041 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
2042 split_paths(unparsed) ==
2043 parsed.iter().map(|s| Path::new(*s)).collect()
2046 assert!(check_parse("", &mut [""]));
2047 assert!(check_parse(r#""""#, &mut [""]));
2048 assert!(check_parse(";;", &mut ["", "", ""]));
2049 assert!(check_parse(r"c:\", &mut [r"c:\"]));
2050 assert!(check_parse(r"c:\;", &mut [r"c:\", ""]));
2051 assert!(check_parse(r"c:\;c:\Program Files\",
2052 &mut [r"c:\", r"c:\Program Files\"]));
2053 assert!(check_parse(r#"c:\;c:\"foo"\"#, &mut [r"c:\", r"c:\foo\"]));
2054 assert!(check_parse(r#"c:\;c:\"foo;bar"\;c:\baz"#,
2055 &mut [r"c:\", r"c:\foo;bar\", r"c:\baz"]));
2060 fn split_paths_unix() {
2061 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
2062 split_paths(unparsed) ==
2063 parsed.iter().map(|s| Path::new(*s)).collect()
2066 assert!(check_parse("", &mut [""]));
2067 assert!(check_parse("::", &mut ["", "", ""]));
2068 assert!(check_parse("/", &mut ["/"]));
2069 assert!(check_parse("/:", &mut ["/", ""]));
2070 assert!(check_parse("/:/usr/local", &mut ["/", "/usr/local"]));
2075 fn join_paths_unix() {
2076 fn test_eq(input: &[&str], output: &str) -> bool {
2077 join_paths(input).unwrap().as_slice() == output.as_bytes()
2080 assert!(test_eq(&[], ""));
2081 assert!(test_eq(&["/bin", "/usr/bin", "/usr/local/bin"],
2082 "/bin:/usr/bin:/usr/local/bin"));
2083 assert!(test_eq(&["", "/bin", "", "", "/usr/bin", ""],
2084 ":/bin:::/usr/bin:"));
2085 assert!(join_paths(&["/te:st"]).is_err());
2090 fn join_paths_windows() {
2091 fn test_eq(input: &[&str], output: &str) -> bool {
2092 join_paths(input).unwrap().as_slice() == output.as_bytes()
2095 assert!(test_eq(&[], ""));
2096 assert!(test_eq(&[r"c:\windows", r"c:\"],
2097 r"c:\windows;c:\"));
2098 assert!(test_eq(&["", r"c:\windows", "", "", r"c:\", ""],
2099 r";c:\windows;;;c:\;"));
2100 assert!(test_eq(&[r"c:\te;st", r"c:\"],
2101 r#""c:\te;st";c:\"#));
2102 assert!(join_paths(&[r#"c:\te"st"#]).is_err());
2105 // More recursive_mkdir tests are in extra::tempfile