1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 * Higher-level interfaces to libc::* functions and operating system services.
14 * In general these take and return rust types, use rust idioms (enums,
15 * closures, vectors) rather than C idioms, and do more extensive safety
18 * This module is not meant to only contain 1:1 mappings to libc entries; any
19 * os-interface code that is reasonably useful and broadly applicable can go
20 * here. Including utility routines that merely build on other os code.
22 * We assume the general case is that users do not care, and do not want to
23 * be made to care, which operating system they are on. While they may want
24 * to special case various special cases -- and so we will not _hide_ the
25 * facts of which OS the user is on -- they should be given the opportunity
26 * to write OS-ignorant code by default.
31 #![allow(missing_docs)]
32 #![allow(non_snake_case)]
34 pub use self::MemoryMapKind::*;
35 pub use self::MapOption::*;
36 pub use self::MapError::*;
39 use error::{FromError, Error};
41 use io::{IoResult, IoError};
43 use libc::{c_void, c_int};
47 use option::{Some, None, Option};
49 use path::{Path, GenericPath, BytesContainer};
51 use sys::os as os_imp;
54 use result::{Err, Ok, Result};
55 use slice::{AsSlice, SlicePrelude, PartialEqSlicePrelude};
56 use slice::CloneSliceAllocPrelude;
57 use str::{Str, StrPrelude, StrAllocating};
58 use string::{String, ToString};
59 use sync::atomic::{AtomicInt, INIT_ATOMIC_INT, SeqCst};
62 #[cfg(unix)] use c_str::ToCStr;
63 #[cfg(unix)] use libc::c_char;
65 /// Get the number of cores available
66 pub fn num_cpus() -> uint {
68 return rust_get_num_cpus() as uint;
72 fn rust_get_num_cpus() -> libc::uintptr_t;
76 pub const TMPBUF_SZ : uint = 1000u;
77 const BUF_BYTES : uint = 2048u;
79 /// Returns the current working directory as a `Path`.
83 /// Returns an `Err` if the current working directory value is invalid.
86 /// * Current directory does not exist.
87 /// * There are insufficient permissions to access the current directory.
88 /// * The internal buffer is not large enough to hold the path.
95 /// // We assume that we are in a valid directory like "/home".
96 /// let current_working_directory = os::getcwd().unwrap();
97 /// println!("The current directory is {}", current_working_directory.display());
101 pub fn getcwd() -> IoResult<Path> {
104 let mut buf = [0 as c_char, ..BUF_BYTES];
106 if libc::getcwd(buf.as_mut_ptr(), buf.len() as libc::size_t).is_null() {
107 Err(IoError::last_error())
109 Ok(Path::new(CString::new(buf.as_ptr(), false)))
114 /// Returns the current working directory as a `Path`.
118 /// Returns an `Err` if the current working directory value is invalid.
121 /// * Current directory does not exist.
122 /// * There are insufficient permissions to access the current directory.
123 /// * The internal buffer is not large enough to hold the path.
130 /// // We assume that we are in a valid directory like "C:\\Windows".
131 /// let current_working_directory = os::getcwd().unwrap();
132 /// println!("The current directory is {}", current_working_directory.display());
136 pub fn getcwd() -> IoResult<Path> {
138 use libc::GetCurrentDirectoryW;
139 use io::OtherIoError;
141 let mut buf = [0 as u16, ..BUF_BYTES];
143 if libc::GetCurrentDirectoryW(buf.len() as DWORD, buf.as_mut_ptr()) == 0 as DWORD {
144 return Err(IoError::last_error());
148 match String::from_utf16(::str::truncate_utf16_at_nul(&buf)) {
149 Some(ref cwd) => Ok(Path::new(cwd)),
150 None => Err(IoError {
152 desc: "GetCurrentDirectoryW returned invalid UTF-16",
160 use libc::types::os::arch::extra::DWORD;
162 use option::{None, Option};
165 use slice::{SlicePrelude};
170 pub fn fill_utf16_buf_and_decode(f: |*mut u16, DWORD| -> DWORD)
174 let mut n = TMPBUF_SZ as DWORD;
176 let mut done = false;
178 let mut buf = Vec::from_elem(n as uint, 0u16);
179 let k = f(buf.as_mut_ptr(), n);
180 if k == (0 as DWORD) {
183 libc::GetLastError() ==
184 libc::ERROR_INSUFFICIENT_BUFFER as DWORD {
192 let sub = buf.slice(0, k as uint);
193 // We want to explicitly catch the case when the
194 // closure returned invalid UTF-16, rather than
195 // set `res` to None and continue.
196 let s = String::from_utf16(sub)
197 .expect("fill_utf16_buf_and_decode: closure created invalid UTF-16");
198 res = option::Some(s)
207 Accessing environment variables is not generally threadsafe.
208 Serialize access through a global lock.
210 fn with_env_lock<T>(f: || -> T) -> T {
211 use rt::mutex::{StaticNativeMutex, NATIVE_MUTEX_INIT};
213 static LOCK: StaticNativeMutex = NATIVE_MUTEX_INIT;
216 let _guard = LOCK.lock();
221 /// Returns a vector of (variable, value) pairs, for all the environment
222 /// variables of the current process.
224 /// Invalid UTF-8 bytes are replaced with \uFFFD. See `String::from_utf8_lossy()`
232 /// // We will iterate through the references to the element returned by os::env();
233 /// for &(ref key, ref value) in os::env().iter() {
234 /// println!("'{}': '{}'", key, value );
237 pub fn env() -> Vec<(String,String)> {
238 env_as_bytes().into_iter().map(|(k,v)| {
239 let k = String::from_utf8_lossy(k.as_slice()).into_string();
240 let v = String::from_utf8_lossy(v.as_slice()).into_string();
245 /// Returns a vector of (variable, value) byte-vector pairs for all the
246 /// environment variables of the current process.
247 pub fn env_as_bytes() -> Vec<(Vec<u8>,Vec<u8>)> {
250 unsafe fn get_env_pairs() -> Vec<Vec<u8>> {
253 use libc::funcs::extra::kernel32::{
254 GetEnvironmentStringsW,
255 FreeEnvironmentStringsW
257 let ch = GetEnvironmentStringsW();
259 panic!("os::env() failure getting env string from OS: {}",
260 os::last_os_error());
262 // Here, we lossily decode the string as UTF16.
264 // The docs suggest that the result should be in Unicode, but
265 // Windows doesn't guarantee it's actually UTF16 -- it doesn't
266 // validate the environment string passed to CreateProcess nor
267 // SetEnvironmentVariable. Yet, it's unlikely that returning a
268 // raw u16 buffer would be of practical use since the result would
269 // be inherently platform-dependent and introduce additional
270 // complexity to this code.
272 // Using the non-Unicode version of GetEnvironmentStrings is even
273 // worse since the result is in an OEM code page. Characters that
274 // can't be encoded in the code page would be turned into question
276 let mut result = Vec::new();
278 while *ch.offset(i) != 0 {
279 let p = &*ch.offset(i);
281 while *(p as *const _).offset(len) != 0 {
284 raw::buf_as_slice(p, len as uint, |s| {
285 result.push(String::from_utf16_lossy(s).into_bytes());
289 FreeEnvironmentStringsW(ch);
293 unsafe fn get_env_pairs() -> Vec<Vec<u8>> {
297 fn rust_env_pairs() -> *const *const c_char;
299 let mut environ = rust_env_pairs();
300 if environ as uint == 0 {
301 panic!("os::env() failure getting env string from OS: {}",
302 os::last_os_error());
304 let mut result = Vec::new();
305 while *environ != 0 as *const _ {
307 CString::new(*environ, false).as_bytes_no_nul().to_vec();
308 result.push(env_pair);
309 environ = environ.offset(1);
314 fn env_convert(input: Vec<Vec<u8>>) -> Vec<(Vec<u8>, Vec<u8>)> {
315 let mut pairs = Vec::new();
316 for p in input.iter() {
317 let mut it = p.as_slice().splitn(1, |b| *b == b'=');
318 let key = it.next().unwrap().to_vec();
319 let default: &[u8] = &[];
320 let val = it.next().unwrap_or(default).to_vec();
321 pairs.push((key, val));
326 let unparsed_environ = get_env_pairs();
327 env_convert(unparsed_environ)
333 /// Fetches the environment variable `n` from the current process, returning
334 /// None if the variable isn't set.
336 /// Any invalid UTF-8 bytes in the value are replaced by \uFFFD. See
337 /// `String::from_utf8_lossy()` for details.
341 /// Panics if `n` has any interior NULs.
348 /// let key = "HOME";
349 /// match os::getenv(key) {
350 /// Some(val) => println!("{}: {}", key, val),
351 /// None => println!("{} is not defined in the environment.", key)
354 pub fn getenv(n: &str) -> Option<String> {
355 getenv_as_bytes(n).map(|v| String::from_utf8_lossy(v.as_slice()).into_string())
359 /// Fetches the environment variable `n` byte vector from the current process,
360 /// returning None if the variable isn't set.
364 /// Panics if `n` has any interior NULs.
365 pub fn getenv_as_bytes(n: &str) -> Option<Vec<u8>> {
370 let s = n.with_c_str(|buf| libc::getenv(buf));
374 Some(CString::new(s as *const i8, false).as_bytes_no_nul().to_vec())
381 /// Fetches the environment variable `n` from the current process, returning
382 /// None if the variable isn't set.
383 pub fn getenv(n: &str) -> Option<String> {
386 use os::windows::{fill_utf16_buf_and_decode};
387 let mut n: Vec<u16> = n.utf16_units().collect();
389 fill_utf16_buf_and_decode(|buf, sz| {
390 libc::GetEnvironmentVariableW(n.as_ptr(), buf, sz)
397 /// Fetches the environment variable `n` byte vector from the current process,
398 /// returning None if the variable isn't set.
399 pub fn getenv_as_bytes(n: &str) -> Option<Vec<u8>> {
400 getenv(n).map(|s| s.into_bytes())
403 /// Sets the environment variable `n` to the value `v` for the currently running
412 /// os::setenv(key, "VALUE");
413 /// match os::getenv(key) {
414 /// Some(ref val) => println!("{}: {}", key, val),
415 /// None => println!("{} is not defined in the environment.", key)
418 pub fn setenv<T: BytesContainer>(n: &str, v: T) {
420 fn _setenv(n: &str, v: &[u8]) {
423 n.with_c_str(|nbuf| {
424 v.with_c_str(|vbuf| {
425 libc::funcs::posix01::unistd::setenv(nbuf, vbuf, 1);
433 fn _setenv(n: &str, v: &[u8]) {
434 let mut n: Vec<u16> = n.utf16_units().collect();
436 let mut v: Vec<u16> = ::str::from_utf8(v).unwrap().utf16_units().collect();
441 libc::SetEnvironmentVariableW(n.as_ptr(), v.as_ptr());
446 _setenv(n, v.container_as_bytes())
449 /// Remove a variable from the environment entirely.
450 pub fn unsetenv(n: &str) {
452 fn _unsetenv(n: &str) {
455 n.with_c_str(|nbuf| {
456 libc::funcs::posix01::unistd::unsetenv(nbuf);
463 fn _unsetenv(n: &str) {
464 let mut n: Vec<u16> = n.utf16_units().collect();
468 libc::SetEnvironmentVariableW(n.as_ptr(), ptr::null());
475 /// Parses input according to platform conventions for the `PATH`
476 /// environment variable.
482 /// let key = "PATH";
483 /// match os::getenv_as_bytes(key) {
485 /// for path in os::split_paths(paths).iter() {
486 /// println!("'{}'", path.display());
489 /// None => println!("{} is not defined in the environment.", key)
492 pub fn split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> {
494 fn _split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> {
495 unparsed.container_as_bytes()
496 .split(|b| *b == b':')
502 fn _split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> {
503 // On Windows, the PATH environment variable is semicolon separated. Double
504 // quotes are used as a way of introducing literal semicolons (since
505 // c:\some;dir is a valid Windows path). Double quotes are not themselves
506 // permitted in path names, so there is no way to escape a double quote.
507 // Quoted regions can appear in arbitrary locations, so
509 // c:\foo;c:\som"e;di"r;c:\bar
511 // Should parse as [c:\foo, c:\some;dir, c:\bar].
513 // (The above is based on testing; there is no clear reference available
516 let mut parsed = Vec::new();
517 let mut in_progress = Vec::new();
518 let mut in_quote = false;
520 for b in unparsed.container_as_bytes().iter() {
522 b';' if !in_quote => {
523 parsed.push(Path::new(in_progress.as_slice()));
524 in_progress.truncate(0)
527 in_quote = !in_quote;
530 in_progress.push(*b);
534 parsed.push(Path::new(in_progress));
538 _split_paths(unparsed)
541 /// Joins a collection of `Path`s appropriately for the `PATH`
542 /// environment variable.
544 /// Returns a `Vec<u8>` on success, since `Path`s are not utf-8
545 /// encoded on all platforms.
547 /// Returns an `Err` (containing an error message) if one of the input
548 /// `Path`s contains an invalid character for constructing the `PATH`
549 /// variable (a double quote on Windows or a colon on Unix).
555 /// use std::path::Path;
557 /// let key = "PATH";
558 /// let mut paths = os::getenv_as_bytes(key).map_or(Vec::new(), os::split_paths);
559 /// paths.push(Path::new("/home/xyz/bin"));
560 /// os::setenv(key, os::join_paths(paths.as_slice()).unwrap());
562 pub fn join_paths<T: BytesContainer>(paths: &[T]) -> Result<Vec<u8>, &'static str> {
564 fn _join_paths<T: BytesContainer>(paths: &[T]) -> Result<Vec<u8>, &'static str> {
565 let mut joined = Vec::new();
568 for (i, path) in paths.iter().map(|p| p.container_as_bytes()).enumerate() {
569 if i > 0 { joined.push(sep) }
570 if path.contains(&b'"') {
571 return Err("path segment contains `\"`");
572 } else if path.contains(&sep) {
574 joined.push_all(path);
577 joined.push_all(path);
585 fn _join_paths<T: BytesContainer>(paths: &[T]) -> Result<Vec<u8>, &'static str> {
586 let mut joined = Vec::new();
589 for (i, path) in paths.iter().map(|p| p.container_as_bytes()).enumerate() {
590 if i > 0 { joined.push(sep) }
591 if path.contains(&sep) { return Err("path segment contains separator `:`") }
592 joined.push_all(path);
601 /// A low-level OS in-memory pipe.
603 /// A file descriptor representing the reading end of the pipe. Data written
604 /// on the `out` file descriptor can be read from this file descriptor.
606 /// A file descriptor representing the write end of the pipe. Data written
607 /// to this file descriptor can be read from the `input` file descriptor.
611 /// Creates a new low-level OS in-memory pipe.
613 /// This function can fail to succeed if there are no more resources available
614 /// to allocate a pipe.
616 /// This function is also unsafe as there is no destructor associated with the
617 /// `Pipe` structure will return. If it is not arranged for the returned file
618 /// descriptors to be closed, the file descriptors will leak. For safe handling
619 /// of this scenario, use `std::io::PipeStream` instead.
620 pub unsafe fn pipe() -> IoResult<Pipe> {
621 let (reader, writer) = try!(sys::os::pipe());
623 reader: reader.unwrap(),
624 writer: writer.unwrap(),
628 /// Returns the proper dll filename for the given basename of a file
630 #[cfg(not(target_os="ios"))]
631 pub fn dll_filename(base: &str) -> String {
632 format!("{}{}{}", consts::DLL_PREFIX, base, consts::DLL_SUFFIX)
635 /// Optionally returns the filesystem path to the current executable which is
636 /// running but with the executable name.
643 /// match os::self_exe_name() {
644 /// Some(exe_path) => println!("Path of this executable is: {}", exe_path.display()),
645 /// None => println!("Unable to get the path of this executable!")
648 pub fn self_exe_name() -> Option<Path> {
650 #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))]
651 fn load_self() -> Option<Vec<u8>> {
653 use libc::funcs::bsd44::*;
654 use libc::consts::os::extra::*;
655 let mut mib = vec![CTL_KERN as c_int,
657 KERN_PROC_PATHNAME as c_int,
659 let mut sz: libc::size_t = 0;
660 let err = sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
661 ptr::null_mut(), &mut sz, ptr::null_mut(),
663 if err != 0 { return None; }
664 if sz == 0 { return None; }
665 let mut v: Vec<u8> = Vec::with_capacity(sz as uint);
666 let err = sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
667 v.as_mut_ptr() as *mut c_void, &mut sz,
668 ptr::null_mut(), 0u as libc::size_t);
669 if err != 0 { return None; }
670 if sz == 0 { return None; }
671 v.set_len(sz as uint - 1); // chop off trailing NUL
676 #[cfg(any(target_os = "linux", target_os = "android"))]
677 fn load_self() -> Option<Vec<u8>> {
680 match io::fs::readlink(&Path::new("/proc/self/exe")) {
681 Ok(path) => Some(path.into_vec()),
686 #[cfg(any(target_os = "macos", target_os = "ios"))]
687 fn load_self() -> Option<Vec<u8>> {
689 use libc::funcs::extra::_NSGetExecutablePath;
691 _NSGetExecutablePath(ptr::null_mut(), &mut sz);
692 if sz == 0 { return None; }
693 let mut v: Vec<u8> = Vec::with_capacity(sz as uint);
694 let err = _NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz);
695 if err != 0 { return None; }
696 v.set_len(sz as uint - 1); // chop off trailing NUL
702 fn load_self() -> Option<Vec<u8>> {
704 use os::windows::fill_utf16_buf_and_decode;
705 fill_utf16_buf_and_decode(|buf, sz| {
706 libc::GetModuleFileNameW(0u as libc::DWORD, buf, sz)
707 }).map(|s| s.into_string().into_bytes())
711 load_self().and_then(Path::new_opt)
714 /// Optionally returns the filesystem path to the current executable which is
717 /// Like self_exe_name() but without the binary's name.
724 /// match os::self_exe_path() {
725 /// Some(exe_path) => println!("Executable's Path is: {}", exe_path.display()),
726 /// None => println!("Impossible to fetch the path of this executable.")
729 pub fn self_exe_path() -> Option<Path> {
730 self_exe_name().map(|mut p| { p.pop(); p })
733 /// Optionally returns the path to the current user's home directory if known.
737 /// Returns the value of the 'HOME' environment variable if it is set
738 /// and not equal to the empty string.
742 /// Returns the value of the 'HOME' environment variable if it is
743 /// set and not equal to the empty string. Otherwise, returns the value of the
744 /// 'USERPROFILE' environment variable if it is set and not equal to the empty
752 /// match os::homedir() {
753 /// Some(ref p) => println!("{}", p.display()),
754 /// None => println!("Impossible to get your home dir!")
757 pub fn homedir() -> Option<Path> {
760 fn _homedir() -> Option<Path> {
766 fn _homedir() -> Option<Path> {
767 aux_homedir("HOME").or(aux_homedir("USERPROFILE"))
771 fn aux_homedir(home_name: &str) -> Option<Path> {
772 match getenv_as_bytes(home_name) {
774 if p.is_empty() { None } else { Path::new_opt(p) }
783 * Returns the path to a temporary directory.
785 * On Unix, returns the value of the 'TMPDIR' environment variable if it is
786 * set, otherwise for non-Android it returns '/tmp'. If Android, since there
787 * is no global temporary folder (it is usually allocated per-app), we return
790 * On Windows, returns the value of, in order, the 'TMP', 'TEMP',
791 * 'USERPROFILE' environment variable if any are set and not the empty
792 * string. Otherwise, tmpdir returns the path to the Windows directory.
794 pub fn tmpdir() -> Path {
797 fn getenv_nonempty(v: &str) -> Option<Path> {
810 fn lookup() -> Path {
811 let default = if cfg!(target_os = "android") {
812 Path::new("/data/local/tmp")
817 getenv_nonempty("TMPDIR").unwrap_or(default)
821 fn lookup() -> Path {
822 getenv_nonempty("TMP").or(
823 getenv_nonempty("TEMP").or(
824 getenv_nonempty("USERPROFILE").or(
825 getenv_nonempty("WINDIR")))).unwrap_or(Path::new("C:\\Windows"))
830 /// Convert a relative path to an absolute path
832 /// If the given path is relative, return it prepended with the current working
833 /// directory. If the given path is already an absolute path, return it
839 /// use std::path::Path;
841 /// // Assume we're in a path like /home/someuser
842 /// let rel_path = Path::new("..");
843 /// let abs_path = os::make_absolute(&rel_path).unwrap();
844 /// println!("The absolute path is {}", abs_path.display());
845 /// // Prints "The absolute path is /home"
847 // NB: this is here rather than in path because it is a form of environment
848 // querying; what it does depends on the process working directory, not just
850 pub fn make_absolute(p: &Path) -> IoResult<Path> {
854 getcwd().map(|mut cwd| {
861 /// Changes the current working directory to the specified path, returning
862 /// whether the change was completed successfully or not.
867 /// use std::path::Path;
869 /// let root = Path::new("/");
870 /// assert!(os::change_dir(&root).is_ok());
871 /// println!("Successfully changed working directory to {}!", root.display());
873 pub fn change_dir(p: &Path) -> IoResult<()> {
877 fn chdir(p: &Path) -> IoResult<()> {
878 let mut p = p.as_str().unwrap().utf16_units().collect::<Vec<u16>>();
882 match libc::SetCurrentDirectoryW(p.as_ptr()) != (0 as libc::BOOL) {
884 false => Err(IoError::last_error()),
890 fn chdir(p: &Path) -> IoResult<()> {
893 match libc::chdir(buf) == (0 as c_int) {
895 false => Err(IoError::last_error()),
902 /// Returns the platform-specific value of errno
903 pub fn errno() -> uint {
904 os_imp::errno() as uint
907 /// Return the string corresponding to an `errno()` value of `errnum`.
913 /// // Same as println!("{}", last_os_error());
914 /// println!("{}", os::error_string(os::errno() as uint));
916 pub fn error_string(errnum: uint) -> String {
917 return os_imp::error_string(errnum as i32);
920 /// Get a string representing the platform-dependent last error
921 pub fn last_os_error() -> String {
922 error_string(errno() as uint)
925 static EXIT_STATUS: AtomicInt = INIT_ATOMIC_INT;
928 * Sets the process exit code
930 * Sets the exit code returned by the process if all supervised tasks
931 * terminate successfully (without panicking). If the current root task panics
932 * and is supervised by the scheduler then any user-specified exit status is
933 * ignored and the process exits with the default panic status.
935 * Note that this is not synchronized against modifications of other threads.
937 pub fn set_exit_status(code: int) {
938 EXIT_STATUS.store(code, SeqCst)
941 /// Fetches the process's current exit code. This defaults to 0 and can change
942 /// by calling `set_exit_status`.
943 pub fn get_exit_status() -> int {
944 EXIT_STATUS.load(SeqCst)
947 #[cfg(target_os = "macos")]
948 unsafe fn load_argc_and_argv(argc: int,
949 argv: *const *const c_char) -> Vec<Vec<u8>> {
952 Vec::from_fn(argc as uint, |i| {
953 CString::new(*argv.offset(i as int), false).as_bytes_no_nul().to_vec()
958 * Returns the command line arguments
960 * Returns a list of the command line arguments.
962 #[cfg(target_os = "macos")]
963 fn real_args_as_bytes() -> Vec<Vec<u8>> {
965 let (argc, argv) = (*_NSGetArgc() as int,
966 *_NSGetArgv() as *const *const c_char);
967 load_argc_and_argv(argc, argv)
971 // As _NSGetArgc and _NSGetArgv aren't mentioned in iOS docs
972 // and use underscores in their names - they're most probably
973 // are considered private and therefore should be avoided
974 // Here is another way to get arguments using Objective C
977 // In general it looks like:
979 // let args = [[NSProcessInfo processInfo] arguments]
980 // for i in range(0, [args count])
981 // res.push([args objectAtIndex:i])
983 #[cfg(target_os = "ios")]
984 fn real_args_as_bytes() -> Vec<Vec<u8>> {
989 #[link(name = "objc")]
991 fn sel_registerName(name: *const libc::c_uchar) -> Sel;
992 fn objc_msgSend(obj: NsId, sel: Sel, ...) -> NsId;
993 fn objc_getClass(class_name: *const libc::c_uchar) -> NsId;
996 #[link(name = "Foundation", kind = "framework")]
999 type Sel = *const libc::c_void;
1000 type NsId = *const libc::c_void;
1002 let mut res = Vec::new();
1005 let processInfoSel = sel_registerName("processInfo\0".as_ptr());
1006 let argumentsSel = sel_registerName("arguments\0".as_ptr());
1007 let utf8Sel = sel_registerName("UTF8String\0".as_ptr());
1008 let countSel = sel_registerName("count\0".as_ptr());
1009 let objectAtSel = sel_registerName("objectAtIndex:\0".as_ptr());
1011 let klass = objc_getClass("NSProcessInfo\0".as_ptr());
1012 let info = objc_msgSend(klass, processInfoSel);
1013 let args = objc_msgSend(info, argumentsSel);
1015 let cnt: int = mem::transmute(objc_msgSend(args, countSel));
1016 for i in range(0, cnt) {
1017 let tmp = objc_msgSend(args, objectAtSel, i);
1018 let utf_c_str: *const libc::c_char =
1019 mem::transmute(objc_msgSend(tmp, utf8Sel));
1020 let s = CString::new(utf_c_str, false);
1021 res.push(s.as_bytes_no_nul().to_vec())
1028 #[cfg(any(target_os = "linux",
1029 target_os = "android",
1030 target_os = "freebsd",
1031 target_os = "dragonfly"))]
1032 fn real_args_as_bytes() -> Vec<Vec<u8>> {
1035 match rt::args::clone() {
1037 None => panic!("process arguments not initialized")
1041 #[cfg(not(windows))]
1042 fn real_args() -> Vec<String> {
1043 real_args_as_bytes().into_iter()
1045 String::from_utf8_lossy(v.as_slice()).into_string()
1050 fn real_args() -> Vec<String> {
1053 let mut nArgs: c_int = 0;
1054 let lpArgCount: *mut c_int = &mut nArgs;
1055 let lpCmdLine = unsafe { GetCommandLineW() };
1056 let szArgList = unsafe { CommandLineToArgvW(lpCmdLine, lpArgCount) };
1058 let args = Vec::from_fn(nArgs as uint, |i| unsafe {
1059 // Determine the length of this argument.
1060 let ptr = *szArgList.offset(i as int);
1062 while *ptr.offset(len as int) != 0 { len += 1; }
1064 // Push it onto the list.
1065 let opt_s = slice::raw::buf_as_slice(ptr as *const _, len, |buf| {
1066 String::from_utf16(::str::truncate_utf16_at_nul(buf))
1068 opt_s.expect("CommandLineToArgvW returned invalid UTF-16")
1072 LocalFree(szArgList as *mut c_void);
1079 fn real_args_as_bytes() -> Vec<Vec<u8>> {
1080 real_args().into_iter().map(|s| s.into_bytes()).collect()
1083 type LPCWSTR = *const u16;
1086 #[link_name="kernel32"]
1088 fn GetCommandLineW() -> LPCWSTR;
1089 fn LocalFree(ptr: *mut c_void);
1093 #[link_name="shell32"]
1095 fn CommandLineToArgvW(lpCmdLine: LPCWSTR,
1096 pNumArgs: *mut c_int) -> *mut *mut u16;
1099 /// Returns the arguments which this program was started with (normally passed
1100 /// via the command line).
1102 /// The arguments are interpreted as utf-8, with invalid bytes replaced with \uFFFD.
1103 /// See `String::from_utf8_lossy` for details.
1109 /// // Prints each argument on a separate line
1110 /// for argument in os::args().iter() {
1111 /// println!("{}", argument);
1114 pub fn args() -> Vec<String> {
1118 /// Returns the arguments which this program was started with (normally passed
1119 /// via the command line) as byte vectors.
1120 pub fn args_as_bytes() -> Vec<Vec<u8>> {
1121 real_args_as_bytes()
1124 #[cfg(target_os = "macos")]
1126 // These functions are in crt_externs.h.
1127 pub fn _NSGetArgc() -> *mut c_int;
1128 pub fn _NSGetArgv() -> *mut *mut *mut c_char;
1131 // Round up `from` to be divisible by `to`
1132 fn round_up(from: uint, to: uint) -> uint {
1133 let r = if from % to == 0 {
1136 from + to - (from % to)
1145 /// Returns the page size of the current architecture in bytes.
1147 pub fn page_size() -> uint {
1149 libc::sysconf(libc::_SC_PAGESIZE) as uint
1153 /// Returns the page size of the current architecture in bytes.
1155 pub fn page_size() -> uint {
1158 let mut info = mem::zeroed();
1159 libc::GetSystemInfo(&mut info);
1161 return info.dwPageSize as uint;
1165 /// A memory mapped file or chunk of memory. This is a very system-specific
1166 /// interface to the OS's memory mapping facilities (`mmap` on POSIX,
1167 /// `VirtualAlloc`/`CreateFileMapping` on Windows). It makes no attempt at
1168 /// abstracting platform differences, besides in error values returned. Consider
1169 /// yourself warned.
1171 /// The memory map is released (unmapped) when the destructor is run, so don't
1172 /// let it leave scope by accident if you want it to stick around.
1173 pub struct MemoryMap {
1176 kind: MemoryMapKind,
1179 /// Type of memory map
1180 pub enum MemoryMapKind {
1181 /// Virtual memory map. Usually used to change the permissions of a given
1182 /// chunk of memory. Corresponds to `VirtualAlloc` on Windows.
1184 /// Virtual memory map. Usually used to change the permissions of a given
1185 /// chunk of memory, or for allocation. Corresponds to `VirtualAlloc` on
1190 /// Options the memory map is created with
1191 pub enum MapOption {
1192 /// The memory should be readable
1194 /// The memory should be writable
1196 /// The memory should be executable
1198 /// Create a map for a specific address range. Corresponds to `MAP_FIXED` on
1201 /// Create a memory mapping for a file with a given fd.
1203 /// When using `MapFd`, the start of the map is `uint` bytes from the start
1206 /// On POSIX, this can be used to specify the default flags passed to
1207 /// `mmap`. By default it uses `MAP_PRIVATE` and, if not using `MapFd`,
1208 /// `MAP_ANON`. This will override both of those. This is platform-specific
1209 /// (the exact values used) and ignored on Windows.
1210 MapNonStandardFlags(c_int),
1213 /// Possible errors when creating a map.
1215 /// ## The following are POSIX-specific
1217 /// fd was not open for reading or, if using `MapWritable`, was not open for
1220 /// fd was not valid
1222 /// Either the address given by `MapAddr` or offset given by `MapOffset` was
1223 /// not a multiple of `MemoryMap::granularity` (unaligned to page size).
1225 /// With `MapFd`, the fd does not support mapping.
1227 /// If using `MapAddr`, the address + `min_len` was outside of the process's
1228 /// address space. If using `MapFd`, the target of the fd didn't have enough
1229 /// resources to fulfill the request.
1231 /// A zero-length map was requested. This is invalid according to
1232 /// [POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/functions/mmap.html).
1233 /// Not all platforms obey this, but this wrapper does.
1235 /// Unrecognized error. The inner value is the unrecognized errno.
1237 /// ## The following are Windows-specific
1239 /// Unsupported combination of protection flags
1240 /// (`MapReadable`/`MapWritable`/`MapExecutable`).
1242 /// When using `MapFd`, `MapOffset` was given (Windows does not support this
1245 /// When using `MapFd`, there was already a mapping to the file.
1247 /// Unrecognized error from `VirtualAlloc`. The inner value is the return
1248 /// value of GetLastError.
1249 ErrVirtualAlloc(uint),
1250 /// Unrecognized error from `CreateFileMapping`. The inner value is the
1251 /// return value of `GetLastError`.
1252 ErrCreateFileMappingW(uint),
1253 /// Unrecognized error from `MapViewOfFile`. The inner value is the return
1254 /// value of `GetLastError`.
1255 ErrMapViewOfFile(uint)
1258 impl fmt::Show for MapError {
1259 fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result {
1260 let str = match *self {
1261 ErrFdNotAvail => "fd not available for reading or writing",
1262 ErrInvalidFd => "Invalid fd",
1264 "Unaligned address, invalid flags, negative length or \
1267 ErrNoMapSupport=> "File doesn't support mapping",
1268 ErrNoMem => "Invalid address, or not enough available memory",
1269 ErrUnsupProt => "Protection mode unsupported",
1270 ErrUnsupOffset => "Offset in virtual memory mode is unsupported",
1271 ErrAlreadyExists => "File mapping for specified file already exists",
1272 ErrZeroLength => "Zero-length mapping not allowed",
1273 ErrUnknown(code) => {
1274 return write!(out, "Unknown error = {}", code)
1276 ErrVirtualAlloc(code) => {
1277 return write!(out, "VirtualAlloc failure = {}", code)
1279 ErrCreateFileMappingW(code) => {
1280 return write!(out, "CreateFileMappingW failure = {}", code)
1282 ErrMapViewOfFile(code) => {
1283 return write!(out, "MapViewOfFile failure = {}", code)
1286 write!(out, "{}", str)
1290 impl Error for MapError {
1291 fn description(&self) -> &str { "memory map error" }
1292 fn detail(&self) -> Option<String> { Some(self.to_string()) }
1295 impl FromError<MapError> for Box<Error> {
1296 fn from_error(err: MapError) -> Box<Error> {
1303 /// Create a new mapping with the given `options`, at least `min_len` bytes
1304 /// long. `min_len` must be greater than zero; see the note on
1305 /// `ErrZeroLength`.
1306 pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
1310 return Err(ErrZeroLength)
1312 let mut addr: *const u8 = ptr::null();
1314 let mut flags = libc::MAP_PRIVATE;
1317 let mut custom_flags = false;
1318 let len = round_up(min_len, page_size());
1320 for &o in options.iter() {
1322 MapReadable => { prot |= libc::PROT_READ; },
1323 MapWritable => { prot |= libc::PROT_WRITE; },
1324 MapExecutable => { prot |= libc::PROT_EXEC; },
1326 flags |= libc::MAP_FIXED;
1330 flags |= libc::MAP_FILE;
1333 MapOffset(offset_) => { offset = offset_ as off_t; },
1334 MapNonStandardFlags(f) => { custom_flags = true; flags = f },
1337 if fd == -1 && !custom_flags { flags |= libc::MAP_ANON; }
1340 libc::mmap(addr as *mut c_void, len as libc::size_t, prot, flags,
1343 if r == libc::MAP_FAILED {
1344 Err(match errno() as c_int {
1345 libc::EACCES => ErrFdNotAvail,
1346 libc::EBADF => ErrInvalidFd,
1347 libc::EINVAL => ErrUnaligned,
1348 libc::ENODEV => ErrNoMapSupport,
1349 libc::ENOMEM => ErrNoMem,
1350 code => ErrUnknown(code as int)
1359 MapFile(ptr::null())
1365 /// Granularity that the offset or address must be for `MapOffset` and
1366 /// `MapAddr` respectively.
1367 pub fn granularity() -> uint {
1373 impl Drop for MemoryMap {
1374 /// Unmap the mapping. Panics the task if `munmap` panics.
1375 fn drop(&mut self) {
1376 if self.len == 0 { /* workaround for dummy_stack */ return; }
1379 // `munmap` only panics due to logic errors
1380 libc::munmap(self.data as *mut c_void, self.len as libc::size_t);
1387 /// Create a new mapping with the given `options`, at least `min_len` bytes long.
1388 pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
1389 use libc::types::os::arch::extra::{LPVOID, DWORD, SIZE_T, HANDLE};
1391 let mut lpAddress: LPVOID = ptr::null_mut();
1392 let mut readable = false;
1393 let mut writable = false;
1394 let mut executable = false;
1395 let mut fd: c_int = -1;
1396 let mut offset: uint = 0;
1397 let len = round_up(min_len, page_size());
1399 for &o in options.iter() {
1401 MapReadable => { readable = true; },
1402 MapWritable => { writable = true; },
1403 MapExecutable => { executable = true; }
1404 MapAddr(addr_) => { lpAddress = addr_ as LPVOID; },
1405 MapFd(fd_) => { fd = fd_; },
1406 MapOffset(offset_) => { offset = offset_; },
1407 MapNonStandardFlags(..) => {}
1411 let flProtect = match (executable, readable, writable) {
1412 (false, false, false) if fd == -1 => libc::PAGE_NOACCESS,
1413 (false, true, false) => libc::PAGE_READONLY,
1414 (false, true, true) => libc::PAGE_READWRITE,
1415 (true, false, false) if fd == -1 => libc::PAGE_EXECUTE,
1416 (true, true, false) => libc::PAGE_EXECUTE_READ,
1417 (true, true, true) => libc::PAGE_EXECUTE_READWRITE,
1418 _ => return Err(ErrUnsupProt)
1423 return Err(ErrUnsupOffset);
1426 libc::VirtualAlloc(lpAddress,
1428 libc::MEM_COMMIT | libc::MEM_RESERVE,
1432 0 => Err(ErrVirtualAlloc(errno())),
1440 let dwDesiredAccess = match (executable, readable, writable) {
1441 (false, true, false) => libc::FILE_MAP_READ,
1442 (false, true, true) => libc::FILE_MAP_WRITE,
1443 (true, true, false) => libc::FILE_MAP_READ | libc::FILE_MAP_EXECUTE,
1444 (true, true, true) => libc::FILE_MAP_WRITE | libc::FILE_MAP_EXECUTE,
1445 _ => return Err(ErrUnsupProt) // Actually, because of the check above,
1446 // we should never get here.
1449 let hFile = libc::get_osfhandle(fd) as HANDLE;
1450 let mapping = libc::CreateFileMappingW(hFile,
1456 if mapping == ptr::null_mut() {
1457 return Err(ErrCreateFileMappingW(errno()));
1459 if errno() as c_int == libc::ERROR_ALREADY_EXISTS {
1460 return Err(ErrAlreadyExists);
1462 let r = libc::MapViewOfFile(mapping,
1464 ((len as u64) >> 32) as DWORD,
1465 (offset & 0xffff_ffff) as DWORD,
1468 0 => Err(ErrMapViewOfFile(errno())),
1472 kind: MapFile(mapping as *const u8)
1479 /// Granularity of MapAddr() and MapOffset() parameter values.
1480 /// This may be greater than the value returned by page_size().
1481 pub fn granularity() -> uint {
1484 let mut info = mem::zeroed();
1485 libc::GetSystemInfo(&mut info);
1487 return info.dwAllocationGranularity as uint;
1493 impl Drop for MemoryMap {
1494 /// Unmap the mapping. Panics the task if any of `VirtualFree`,
1495 /// `UnmapViewOfFile`, or `CloseHandle` fail.
1496 fn drop(&mut self) {
1497 use libc::types::os::arch::extra::{LPCVOID, HANDLE};
1498 use libc::consts::os::extra::FALSE;
1499 if self.len == 0 { return }
1504 if libc::VirtualFree(self.data as *mut c_void, 0,
1505 libc::MEM_RELEASE) == 0 {
1506 println!("VirtualFree failed: {}", errno());
1509 MapFile(mapping) => {
1510 if libc::UnmapViewOfFile(self.data as LPCVOID) == FALSE {
1511 println!("UnmapViewOfFile failed: {}", errno());
1513 if libc::CloseHandle(mapping as HANDLE) == FALSE {
1514 println!("CloseHandle failed: {}", errno());
1523 /// Returns the pointer to the memory created or modified by this map.
1524 pub fn data(&self) -> *mut u8 { self.data }
1525 /// Returns the number of bytes this map applies to.
1526 pub fn len(&self) -> uint { self.len }
1527 /// Returns the type of mapping this represents.
1528 pub fn kind(&self) -> MemoryMapKind { self.kind }
1531 #[cfg(target_os = "linux")]
1533 pub use os::arch_consts::ARCH;
1535 pub const FAMILY: &'static str = "unix";
1537 /// A string describing the specific operating system in use: in this
1539 pub const SYSNAME: &'static str = "linux";
1541 /// Specifies the filename prefix used for shared libraries on this
1542 /// platform: in this case, `lib`.
1543 pub const DLL_PREFIX: &'static str = "lib";
1545 /// Specifies the filename suffix used for shared libraries on this
1546 /// platform: in this case, `.so`.
1547 pub const DLL_SUFFIX: &'static str = ".so";
1549 /// Specifies the file extension used for shared libraries on this
1550 /// platform that goes after the dot: in this case, `so`.
1551 pub const DLL_EXTENSION: &'static str = "so";
1553 /// Specifies the filename suffix used for executable binaries on this
1554 /// platform: in this case, the empty string.
1555 pub const EXE_SUFFIX: &'static str = "";
1557 /// Specifies the file extension, if any, used for executable binaries
1558 /// on this platform: in this case, the empty string.
1559 pub const EXE_EXTENSION: &'static str = "";
1562 #[cfg(target_os = "macos")]
1564 pub use os::arch_consts::ARCH;
1566 pub const FAMILY: &'static str = "unix";
1568 /// A string describing the specific operating system in use: in this
1570 pub const SYSNAME: &'static str = "macos";
1572 /// Specifies the filename prefix used for shared libraries on this
1573 /// platform: in this case, `lib`.
1574 pub const DLL_PREFIX: &'static str = "lib";
1576 /// Specifies the filename suffix used for shared libraries on this
1577 /// platform: in this case, `.dylib`.
1578 pub const DLL_SUFFIX: &'static str = ".dylib";
1580 /// Specifies the file extension used for shared libraries on this
1581 /// platform that goes after the dot: in this case, `dylib`.
1582 pub const DLL_EXTENSION: &'static str = "dylib";
1584 /// Specifies the filename suffix used for executable binaries on this
1585 /// platform: in this case, the empty string.
1586 pub const EXE_SUFFIX: &'static str = "";
1588 /// Specifies the file extension, if any, used for executable binaries
1589 /// on this platform: in this case, the empty string.
1590 pub const EXE_EXTENSION: &'static str = "";
1593 #[cfg(target_os = "ios")]
1595 pub use os::arch_consts::ARCH;
1597 pub const FAMILY: &'static str = "unix";
1599 /// A string describing the specific operating system in use: in this
1601 pub const SYSNAME: &'static str = "ios";
1603 /// Specifies the filename suffix used for executable binaries on this
1604 /// platform: in this case, the empty string.
1605 pub const EXE_SUFFIX: &'static str = "";
1607 /// Specifies the file extension, if any, used for executable binaries
1608 /// on this platform: in this case, the empty string.
1609 pub const EXE_EXTENSION: &'static str = "";
1612 #[cfg(target_os = "freebsd")]
1614 pub use os::arch_consts::ARCH;
1616 pub const FAMILY: &'static str = "unix";
1618 /// A string describing the specific operating system in use: in this
1619 /// case, `freebsd`.
1620 pub const SYSNAME: &'static str = "freebsd";
1622 /// Specifies the filename prefix used for shared libraries on this
1623 /// platform: in this case, `lib`.
1624 pub const DLL_PREFIX: &'static str = "lib";
1626 /// Specifies the filename suffix used for shared libraries on this
1627 /// platform: in this case, `.so`.
1628 pub const DLL_SUFFIX: &'static str = ".so";
1630 /// Specifies the file extension used for shared libraries on this
1631 /// platform that goes after the dot: in this case, `so`.
1632 pub const DLL_EXTENSION: &'static str = "so";
1634 /// Specifies the filename suffix used for executable binaries on this
1635 /// platform: in this case, the empty string.
1636 pub const EXE_SUFFIX: &'static str = "";
1638 /// Specifies the file extension, if any, used for executable binaries
1639 /// on this platform: in this case, the empty string.
1640 pub const EXE_EXTENSION: &'static str = "";
1643 #[cfg(target_os = "dragonfly")]
1645 pub use os::arch_consts::ARCH;
1647 pub const FAMILY: &'static str = "unix";
1649 /// A string describing the specific operating system in use: in this
1650 /// case, `dragonfly`.
1651 pub const SYSNAME: &'static str = "dragonfly";
1653 /// Specifies the filename prefix used for shared libraries on this
1654 /// platform: in this case, `lib`.
1655 pub const DLL_PREFIX: &'static str = "lib";
1657 /// Specifies the filename suffix used for shared libraries on this
1658 /// platform: in this case, `.so`.
1659 pub const DLL_SUFFIX: &'static str = ".so";
1661 /// Specifies the file extension used for shared libraries on this
1662 /// platform that goes after the dot: in this case, `so`.
1663 pub const DLL_EXTENSION: &'static str = "so";
1665 /// Specifies the filename suffix used for executable binaries on this
1666 /// platform: in this case, the empty string.
1667 pub const EXE_SUFFIX: &'static str = "";
1669 /// Specifies the file extension, if any, used for executable binaries
1670 /// on this platform: in this case, the empty string.
1671 pub const EXE_EXTENSION: &'static str = "";
1674 #[cfg(target_os = "android")]
1676 pub use os::arch_consts::ARCH;
1678 pub const FAMILY: &'static str = "unix";
1680 /// A string describing the specific operating system in use: in this
1681 /// case, `android`.
1682 pub const SYSNAME: &'static str = "android";
1684 /// Specifies the filename prefix used for shared libraries on this
1685 /// platform: in this case, `lib`.
1686 pub const DLL_PREFIX: &'static str = "lib";
1688 /// Specifies the filename suffix used for shared libraries on this
1689 /// platform: in this case, `.so`.
1690 pub const DLL_SUFFIX: &'static str = ".so";
1692 /// Specifies the file extension used for shared libraries on this
1693 /// platform that goes after the dot: in this case, `so`.
1694 pub const DLL_EXTENSION: &'static str = "so";
1696 /// Specifies the filename suffix used for executable binaries on this
1697 /// platform: in this case, the empty string.
1698 pub const EXE_SUFFIX: &'static str = "";
1700 /// Specifies the file extension, if any, used for executable binaries
1701 /// on this platform: in this case, the empty string.
1702 pub const EXE_EXTENSION: &'static str = "";
1705 #[cfg(target_os = "windows")]
1707 pub use os::arch_consts::ARCH;
1709 pub const FAMILY: &'static str = "windows";
1711 /// A string describing the specific operating system in use: in this
1712 /// case, `windows`.
1713 pub const SYSNAME: &'static str = "windows";
1715 /// Specifies the filename prefix used for shared libraries on this
1716 /// platform: in this case, the empty string.
1717 pub const DLL_PREFIX: &'static str = "";
1719 /// Specifies the filename suffix used for shared libraries on this
1720 /// platform: in this case, `.dll`.
1721 pub const DLL_SUFFIX: &'static str = ".dll";
1723 /// Specifies the file extension used for shared libraries on this
1724 /// platform that goes after the dot: in this case, `dll`.
1725 pub const DLL_EXTENSION: &'static str = "dll";
1727 /// Specifies the filename suffix used for executable binaries on this
1728 /// platform: in this case, `.exe`.
1729 pub const EXE_SUFFIX: &'static str = ".exe";
1731 /// Specifies the file extension, if any, used for executable binaries
1732 /// on this platform: in this case, `exe`.
1733 pub const EXE_EXTENSION: &'static str = "exe";
1736 #[cfg(target_arch = "x86")]
1738 pub const ARCH: &'static str = "x86";
1741 #[cfg(target_arch = "x86_64")]
1743 pub const ARCH: &'static str = "x86_64";
1746 #[cfg(target_arch = "arm")]
1748 pub const ARCH: &'static str = "arm";
1751 #[cfg(target_arch = "mips")]
1753 pub const ARCH: &'static str = "mips";
1756 #[cfg(target_arch = "mipsel")]
1758 pub const ARCH: &'static str = "mipsel";
1766 use os::{env, getcwd, getenv, make_absolute};
1767 use os::{split_paths, join_paths, setenv, unsetenv};
1773 pub fn last_os_error() {
1774 debug!("{}", os::last_os_error());
1777 fn make_rand_name() -> String {
1778 let mut rng = rand::task_rng();
1779 let n = format!("TEST{}", rng.gen_ascii_chars().take(10u)
1780 .collect::<String>());
1781 assert!(getenv(n.as_slice()).is_none());
1786 fn test_num_cpus() {
1787 assert!(os::num_cpus() > 0);
1792 let n = make_rand_name();
1793 setenv(n.as_slice(), "VALUE");
1794 assert_eq!(getenv(n.as_slice()), option::Some("VALUE".to_string()));
1798 fn test_unsetenv() {
1799 let n = make_rand_name();
1800 setenv(n.as_slice(), "VALUE");
1801 unsetenv(n.as_slice());
1802 assert_eq!(getenv(n.as_slice()), option::None);
1807 fn test_setenv_overwrite() {
1808 let n = make_rand_name();
1809 setenv(n.as_slice(), "1");
1810 setenv(n.as_slice(), "2");
1811 assert_eq!(getenv(n.as_slice()), option::Some("2".to_string()));
1812 setenv(n.as_slice(), "");
1813 assert_eq!(getenv(n.as_slice()), option::Some("".to_string()));
1816 // Windows GetEnvironmentVariable requires some extra work to make sure
1817 // the buffer the variable is copied into is the right size
1820 fn test_getenv_big() {
1821 let mut s = "".to_string();
1824 s.push_str("aaaaaaaaaa");
1827 let n = make_rand_name();
1828 setenv(n.as_slice(), s.as_slice());
1829 debug!("{}", s.clone());
1830 assert_eq!(getenv(n.as_slice()), option::Some(s));
1834 fn test_self_exe_name() {
1835 let path = os::self_exe_name();
1836 assert!(path.is_some());
1837 let path = path.unwrap();
1838 debug!("{}", path.display());
1840 // Hard to test this function
1841 assert!(path.is_absolute());
1845 fn test_self_exe_path() {
1846 let path = os::self_exe_path();
1847 assert!(path.is_some());
1848 let path = path.unwrap();
1849 debug!("{}", path.display());
1851 // Hard to test this function
1852 assert!(path.is_absolute());
1857 fn test_env_getenv() {
1859 assert!(e.len() > 0u);
1861 let (n, v) = (*p).clone();
1863 let v2 = getenv(n.as_slice());
1864 // MingW seems to set some funky environment variables like
1865 // "=C:=C:\MinGW\msys\1.0\bin" and "!::=::\" that are returned
1866 // from env() but not visible from getenv().
1867 assert!(v2.is_none() || v2 == option::Some(v));
1872 fn test_env_set_get_huge() {
1873 let n = make_rand_name();
1874 let s = "x".repeat(10000).to_string();
1875 setenv(n.as_slice(), s.as_slice());
1876 assert_eq!(getenv(n.as_slice()), Some(s));
1877 unsetenv(n.as_slice());
1878 assert_eq!(getenv(n.as_slice()), None);
1882 fn test_env_setenv() {
1883 let n = make_rand_name();
1886 setenv(n.as_slice(), "VALUE");
1887 assert!(!e.contains(&(n.clone(), "VALUE".to_string())));
1890 assert!(e.contains(&(n, "VALUE".to_string())));
1895 assert!((!Path::new("test-path").is_absolute()));
1897 let cwd = getcwd().unwrap();
1898 debug!("Current working directory: {}", cwd.display());
1900 debug!("{}", make_absolute(&Path::new("test-path")).unwrap().display());
1901 debug!("{}", make_absolute(&Path::new("/usr/bin")).unwrap().display());
1907 let oldhome = getenv("HOME");
1909 setenv("HOME", "/home/MountainView");
1910 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1913 assert!(os::homedir().is_none());
1915 for s in oldhome.iter() {
1916 setenv("HOME", s.as_slice());
1924 let oldhome = getenv("HOME");
1925 let olduserprofile = getenv("USERPROFILE");
1928 setenv("USERPROFILE", "");
1930 assert!(os::homedir().is_none());
1932 setenv("HOME", "/home/MountainView");
1933 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1937 setenv("USERPROFILE", "/home/MountainView");
1938 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1940 setenv("HOME", "/home/MountainView");
1941 setenv("USERPROFILE", "/home/PaloAlto");
1942 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1944 for s in oldhome.iter() {
1945 setenv("HOME", s.as_slice());
1947 for s in olduserprofile.iter() {
1948 setenv("USERPROFILE", s.as_slice());
1953 fn memory_map_rw() {
1954 use result::{Ok, Err};
1956 let chunk = match os::MemoryMap::new(16, &[
1961 Err(msg) => panic!("{}", msg)
1963 assert!(chunk.len >= 16);
1967 assert!(*chunk.data == 0xBE);
1972 fn memory_map_file() {
1973 use result::{Ok, Err};
1979 fn lseek_(fd: c_int, size: uint) {
1981 assert!(lseek(fd, size as off_t, SEEK_SET) == size as off_t);
1985 fn lseek_(fd: c_int, size: uint) {
1987 assert!(lseek(fd, size as c_long, SEEK_SET) == size as c_long);
1991 let mut path = tmpdir();
1992 path.push("mmap_file.tmp");
1993 let size = MemoryMap::granularity() * 2;
1996 let fd = path.with_c_str(|path| {
1997 open(path, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR)
2000 "x".with_c_str(|x| assert!(write(fd, x as *const c_void, 1) == 1));
2003 let chunk = match MemoryMap::new(size / 2, &[
2010 Err(msg) => panic!("{}", msg)
2012 assert!(chunk.len > 0);
2016 assert!(*chunk.data == 0xbe);
2021 fs::unlink(&path).unwrap();
2026 fn split_paths_windows() {
2027 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
2028 split_paths(unparsed) ==
2029 parsed.iter().map(|s| Path::new(*s)).collect()
2032 assert!(check_parse("", &mut [""]));
2033 assert!(check_parse(r#""""#, &mut [""]));
2034 assert!(check_parse(";;", &mut ["", "", ""]));
2035 assert!(check_parse(r"c:\", &mut [r"c:\"]));
2036 assert!(check_parse(r"c:\;", &mut [r"c:\", ""]));
2037 assert!(check_parse(r"c:\;c:\Program Files\",
2038 &mut [r"c:\", r"c:\Program Files\"]));
2039 assert!(check_parse(r#"c:\;c:\"foo"\"#, &mut [r"c:\", r"c:\foo\"]));
2040 assert!(check_parse(r#"c:\;c:\"foo;bar"\;c:\baz"#,
2041 &mut [r"c:\", r"c:\foo;bar\", r"c:\baz"]));
2046 fn split_paths_unix() {
2047 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
2048 split_paths(unparsed) ==
2049 parsed.iter().map(|s| Path::new(*s)).collect()
2052 assert!(check_parse("", &mut [""]));
2053 assert!(check_parse("::", &mut ["", "", ""]));
2054 assert!(check_parse("/", &mut ["/"]));
2055 assert!(check_parse("/:", &mut ["/", ""]));
2056 assert!(check_parse("/:/usr/local", &mut ["/", "/usr/local"]));
2061 fn join_paths_unix() {
2062 fn test_eq(input: &[&str], output: &str) -> bool {
2063 join_paths(input).unwrap().as_slice() == output.as_bytes()
2066 assert!(test_eq(&[], ""));
2067 assert!(test_eq(&["/bin", "/usr/bin", "/usr/local/bin"],
2068 "/bin:/usr/bin:/usr/local/bin"));
2069 assert!(test_eq(&["", "/bin", "", "", "/usr/bin", ""],
2070 ":/bin:::/usr/bin:"));
2071 assert!(join_paths(&["/te:st"]).is_err());
2076 fn join_paths_windows() {
2077 fn test_eq(input: &[&str], output: &str) -> bool {
2078 join_paths(input).unwrap().as_slice() == output.as_bytes()
2081 assert!(test_eq(&[], ""));
2082 assert!(test_eq(&[r"c:\windows", r"c:\"],
2083 r"c:\windows;c:\"));
2084 assert!(test_eq(&["", r"c:\windows", "", "", r"c:\", ""],
2085 r";c:\windows;;;c:\;"));
2086 assert!(test_eq(&[r"c:\te;st", r"c:\"],
2087 r#""c:\te;st";c:\"#));
2088 assert!(join_paths(&[r#"c:\te"st"#]).is_err());
2091 // More recursive_mkdir tests are in extra::tempfile