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};
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 /// Fails if the current working directory value is invalid:
86 /// * Current directory does not exist.
87 /// * There are insufficient permissions to access the current directory.
94 /// // We assume that we are in a valid directory like "/home".
95 /// let current_working_directory = os::getcwd();
96 /// println!("The current directory is {}", current_working_directory.display());
100 pub fn getcwd() -> Path {
103 let mut buf = [0 as c_char, ..BUF_BYTES];
105 if libc::getcwd(buf.as_mut_ptr(), buf.len() as libc::size_t).is_null() {
108 Path::new(CString::new(buf.as_ptr(), false))
112 /// Returns the current working directory as a Path.
116 /// Fails if the current working directory value is invalid.
119 /// * Current directory does not exist.
120 /// * There are insufficient permissions to access the current directory.
127 /// // We assume that we are in a valid directory like "C:\\Windows".
128 /// let current_working_directory = os::getcwd();
129 /// println!("The current directory is {}", current_working_directory.display());
133 pub fn getcwd() -> Path {
135 use libc::GetCurrentDirectoryW;
137 let mut buf = [0 as u16, ..BUF_BYTES];
139 if libc::GetCurrentDirectoryW(buf.len() as DWORD, buf.as_mut_ptr()) == 0 as DWORD {
143 Path::new(String::from_utf16(::str::truncate_utf16_at_nul(&buf))
144 .expect("GetCurrentDirectoryW returned invalid UTF-16"))
149 use libc::types::os::arch::extra::DWORD;
151 use option::{None, Option};
154 use slice::{SlicePrelude};
159 pub fn fill_utf16_buf_and_decode(f: |*mut u16, DWORD| -> DWORD)
163 let mut n = TMPBUF_SZ as DWORD;
165 let mut done = false;
167 let mut buf = Vec::from_elem(n as uint, 0u16);
168 let k = f(buf.as_mut_ptr(), n);
169 if k == (0 as DWORD) {
172 libc::GetLastError() ==
173 libc::ERROR_INSUFFICIENT_BUFFER as DWORD {
181 let sub = buf.slice(0, k as uint);
182 // We want to explicitly catch the case when the
183 // closure returned invalid UTF-16, rather than
184 // set `res` to None and continue.
185 let s = String::from_utf16(sub)
186 .expect("fill_utf16_buf_and_decode: closure created invalid UTF-16");
187 res = option::Some(s)
196 Accessing environment variables is not generally threadsafe.
197 Serialize access through a global lock.
199 fn with_env_lock<T>(f: || -> T) -> T {
200 use rt::mutex::{StaticNativeMutex, NATIVE_MUTEX_INIT};
202 static LOCK: StaticNativeMutex = NATIVE_MUTEX_INIT;
205 let _guard = LOCK.lock();
210 /// Returns a vector of (variable, value) pairs, for all the environment
211 /// variables of the current process.
213 /// Invalid UTF-8 bytes are replaced with \uFFFD. See `String::from_utf8_lossy()`
221 /// // We will iterate through the references to the element returned by os::env();
222 /// for &(ref key, ref value) in os::env().iter() {
223 /// println!("'{}': '{}'", key, value );
226 pub fn env() -> Vec<(String,String)> {
227 env_as_bytes().into_iter().map(|(k,v)| {
228 let k = String::from_utf8_lossy(k.as_slice()).into_string();
229 let v = String::from_utf8_lossy(v.as_slice()).into_string();
234 /// Returns a vector of (variable, value) byte-vector pairs for all the
235 /// environment variables of the current process.
236 pub fn env_as_bytes() -> Vec<(Vec<u8>,Vec<u8>)> {
239 unsafe fn get_env_pairs() -> Vec<Vec<u8>> {
242 use libc::funcs::extra::kernel32::{
243 GetEnvironmentStringsW,
244 FreeEnvironmentStringsW
246 let ch = GetEnvironmentStringsW();
248 panic!("os::env() failure getting env string from OS: {}",
249 os::last_os_error());
251 // Here, we lossily decode the string as UTF16.
253 // The docs suggest that the result should be in Unicode, but
254 // Windows doesn't guarantee it's actually UTF16 -- it doesn't
255 // validate the environment string passed to CreateProcess nor
256 // SetEnvironmentVariable. Yet, it's unlikely that returning a
257 // raw u16 buffer would be of practical use since the result would
258 // be inherently platform-dependent and introduce additional
259 // complexity to this code.
261 // Using the non-Unicode version of GetEnvironmentStrings is even
262 // worse since the result is in an OEM code page. Characters that
263 // can't be encoded in the code page would be turned into question
265 let mut result = Vec::new();
267 while *ch.offset(i) != 0 {
268 let p = &*ch.offset(i);
270 while *(p as *const _).offset(len) != 0 {
273 raw::buf_as_slice(p, len as uint, |s| {
274 result.push(String::from_utf16_lossy(s).into_bytes());
278 FreeEnvironmentStringsW(ch);
282 unsafe fn get_env_pairs() -> Vec<Vec<u8>> {
286 fn rust_env_pairs() -> *const *const c_char;
288 let mut environ = rust_env_pairs();
289 if environ as uint == 0 {
290 panic!("os::env() failure getting env string from OS: {}",
291 os::last_os_error());
293 let mut result = Vec::new();
294 while *environ != 0 as *const _ {
296 CString::new(*environ, false).as_bytes_no_nul().to_vec();
297 result.push(env_pair);
298 environ = environ.offset(1);
303 fn env_convert(input: Vec<Vec<u8>>) -> Vec<(Vec<u8>, Vec<u8>)> {
304 let mut pairs = Vec::new();
305 for p in input.iter() {
306 let mut it = p.as_slice().splitn(1, |b| *b == b'=');
307 let key = it.next().unwrap().to_vec();
308 let default: &[u8] = &[];
309 let val = it.next().unwrap_or(default).to_vec();
310 pairs.push((key, val));
315 let unparsed_environ = get_env_pairs();
316 env_convert(unparsed_environ)
322 /// Fetches the environment variable `n` from the current process, returning
323 /// None if the variable isn't set.
325 /// Any invalid UTF-8 bytes in the value are replaced by \uFFFD. See
326 /// `String::from_utf8_lossy()` for details.
330 /// Panics if `n` has any interior NULs.
337 /// let key = "HOME";
338 /// match os::getenv(key) {
339 /// Some(val) => println!("{}: {}", key, val),
340 /// None => println!("{} is not defined in the environment.", key)
343 pub fn getenv(n: &str) -> Option<String> {
344 getenv_as_bytes(n).map(|v| String::from_utf8_lossy(v.as_slice()).into_string())
348 /// Fetches the environment variable `n` byte vector from the current process,
349 /// returning None if the variable isn't set.
353 /// Panics if `n` has any interior NULs.
354 pub fn getenv_as_bytes(n: &str) -> Option<Vec<u8>> {
359 let s = n.with_c_str(|buf| libc::getenv(buf));
363 Some(CString::new(s as *const i8, false).as_bytes_no_nul().to_vec())
370 /// Fetches the environment variable `n` from the current process, returning
371 /// None if the variable isn't set.
372 pub fn getenv(n: &str) -> Option<String> {
375 use os::windows::{fill_utf16_buf_and_decode};
376 let mut n: Vec<u16> = n.utf16_units().collect();
378 fill_utf16_buf_and_decode(|buf, sz| {
379 libc::GetEnvironmentVariableW(n.as_ptr(), buf, sz)
386 /// Fetches the environment variable `n` byte vector from the current process,
387 /// returning None if the variable isn't set.
388 pub fn getenv_as_bytes(n: &str) -> Option<Vec<u8>> {
389 getenv(n).map(|s| s.into_bytes())
392 /// Sets the environment variable `n` to the value `v` for the currently running
401 /// os::setenv(key, "VALUE");
402 /// match os::getenv(key) {
403 /// Some(ref val) => println!("{}: {}", key, val),
404 /// None => println!("{} is not defined in the environment.", key)
407 pub fn setenv<T: BytesContainer>(n: &str, v: T) {
409 fn _setenv(n: &str, v: &[u8]) {
412 n.with_c_str(|nbuf| {
413 v.with_c_str(|vbuf| {
414 libc::funcs::posix01::unistd::setenv(nbuf, vbuf, 1);
422 fn _setenv(n: &str, v: &[u8]) {
423 let mut n: Vec<u16> = n.utf16_units().collect();
425 let mut v: Vec<u16> = ::str::from_utf8(v).unwrap().utf16_units().collect();
430 libc::SetEnvironmentVariableW(n.as_ptr(), v.as_ptr());
435 _setenv(n, v.container_as_bytes())
438 /// Remove a variable from the environment entirely.
439 pub fn unsetenv(n: &str) {
441 fn _unsetenv(n: &str) {
444 n.with_c_str(|nbuf| {
445 libc::funcs::posix01::unistd::unsetenv(nbuf);
452 fn _unsetenv(n: &str) {
453 let mut n: Vec<u16> = n.utf16_units().collect();
457 libc::SetEnvironmentVariableW(n.as_ptr(), ptr::null());
464 /// Parses input according to platform conventions for the `PATH`
465 /// environment variable.
471 /// let key = "PATH";
472 /// match os::getenv_as_bytes(key) {
474 /// for path in os::split_paths(paths).iter() {
475 /// println!("'{}'", path.display());
478 /// None => println!("{} is not defined in the environment.", key)
481 pub fn split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> {
483 fn _split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> {
484 unparsed.container_as_bytes()
485 .split(|b| *b == b':')
491 fn _split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> {
492 // On Windows, the PATH environment variable is semicolon separated. Double
493 // quotes are used as a way of introducing literal semicolons (since
494 // c:\some;dir is a valid Windows path). Double quotes are not themselves
495 // permitted in path names, so there is no way to escape a double quote.
496 // Quoted regions can appear in arbitrary locations, so
498 // c:\foo;c:\som"e;di"r;c:\bar
500 // Should parse as [c:\foo, c:\some;dir, c:\bar].
502 // (The above is based on testing; there is no clear reference available
505 let mut parsed = Vec::new();
506 let mut in_progress = Vec::new();
507 let mut in_quote = false;
509 for b in unparsed.container_as_bytes().iter() {
511 b';' if !in_quote => {
512 parsed.push(Path::new(in_progress.as_slice()));
513 in_progress.truncate(0)
516 in_quote = !in_quote;
519 in_progress.push(*b);
523 parsed.push(Path::new(in_progress));
527 _split_paths(unparsed)
530 /// Joins a collection of `Path`s appropriately for the `PATH`
531 /// environment variable.
533 /// Returns a `Vec<u8>` on success, since `Path`s are not utf-8
534 /// encoded on all platforms.
536 /// Returns an `Err` (containing an error message) if one of the input
537 /// `Path`s contains an invalid character for constructing the `PATH`
538 /// variable (a double quote on Windows or a colon on Unix).
544 /// use std::path::Path;
546 /// let key = "PATH";
547 /// let mut paths = os::getenv_as_bytes(key).map_or(Vec::new(), os::split_paths);
548 /// paths.push(Path::new("/home/xyz/bin"));
549 /// os::setenv(key, os::join_paths(paths.as_slice()).unwrap());
551 pub fn join_paths<T: BytesContainer>(paths: &[T]) -> Result<Vec<u8>, &'static str> {
553 fn _join_paths<T: BytesContainer>(paths: &[T]) -> Result<Vec<u8>, &'static str> {
554 let mut joined = Vec::new();
557 for (i, path) in paths.iter().map(|p| p.container_as_bytes()).enumerate() {
558 if i > 0 { joined.push(sep) }
559 if path.contains(&b'"') {
560 return Err("path segment contains `\"`");
561 } else if path.contains(&sep) {
563 joined.push_all(path);
566 joined.push_all(path);
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(&sep) { return Err("path segment contains separator `:`") }
581 joined.push_all(path);
590 /// A low-level OS in-memory pipe.
592 /// A file descriptor representing the reading end of the pipe. Data written
593 /// on the `out` file descriptor can be read from this file descriptor.
595 /// A file descriptor representing the write end of the pipe. Data written
596 /// to this file descriptor can be read from the `input` file descriptor.
600 /// Creates a new low-level OS in-memory pipe.
602 /// This function can fail to succeed if there are no more resources available
603 /// to allocate a pipe.
605 /// This function is also unsafe as there is no destructor associated with the
606 /// `Pipe` structure will return. If it is not arranged for the returned file
607 /// descriptors to be closed, the file descriptors will leak. For safe handling
608 /// of this scenario, use `std::io::PipeStream` instead.
609 pub unsafe fn pipe() -> IoResult<Pipe> {
610 let (reader, writer) = try!(sys::os::pipe());
612 reader: reader.unwrap(),
613 writer: writer.unwrap(),
617 /// Returns the proper dll filename for the given basename of a file
619 #[cfg(not(target_os="ios"))]
620 pub fn dll_filename(base: &str) -> String {
621 format!("{}{}{}", consts::DLL_PREFIX, base, consts::DLL_SUFFIX)
624 /// Optionally returns the filesystem path to the current executable which is
625 /// running but with the executable name.
632 /// match os::self_exe_name() {
633 /// Some(exe_path) => println!("Path of this executable is: {}", exe_path.display()),
634 /// None => println!("Unable to get the path of this executable!")
637 pub fn self_exe_name() -> Option<Path> {
639 #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))]
640 fn load_self() -> Option<Vec<u8>> {
642 use libc::funcs::bsd44::*;
643 use libc::consts::os::extra::*;
644 let mut mib = vec![CTL_KERN as c_int,
646 KERN_PROC_PATHNAME as c_int,
648 let mut sz: libc::size_t = 0;
649 let err = sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
650 ptr::null_mut(), &mut sz, ptr::null_mut(),
652 if err != 0 { return None; }
653 if sz == 0 { return None; }
654 let mut v: Vec<u8> = Vec::with_capacity(sz as uint);
655 let err = sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint,
656 v.as_mut_ptr() as *mut c_void, &mut sz,
657 ptr::null_mut(), 0u as libc::size_t);
658 if err != 0 { return None; }
659 if sz == 0 { return None; }
660 v.set_len(sz as uint - 1); // chop off trailing NUL
665 #[cfg(any(target_os = "linux", target_os = "android"))]
666 fn load_self() -> Option<Vec<u8>> {
669 match io::fs::readlink(&Path::new("/proc/self/exe")) {
670 Ok(path) => Some(path.into_vec()),
675 #[cfg(any(target_os = "macos", target_os = "ios"))]
676 fn load_self() -> Option<Vec<u8>> {
678 use libc::funcs::extra::_NSGetExecutablePath;
680 _NSGetExecutablePath(ptr::null_mut(), &mut sz);
681 if sz == 0 { return None; }
682 let mut v: Vec<u8> = Vec::with_capacity(sz as uint);
683 let err = _NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz);
684 if err != 0 { return None; }
685 v.set_len(sz as uint - 1); // chop off trailing NUL
691 fn load_self() -> Option<Vec<u8>> {
693 use os::windows::fill_utf16_buf_and_decode;
694 fill_utf16_buf_and_decode(|buf, sz| {
695 libc::GetModuleFileNameW(0u as libc::DWORD, buf, sz)
696 }).map(|s| s.into_string().into_bytes())
700 load_self().and_then(Path::new_opt)
703 /// Optionally returns the filesystem path to the current executable which is
706 /// Like self_exe_name() but without the binary's name.
713 /// match os::self_exe_path() {
714 /// Some(exe_path) => println!("Executable's Path is: {}", exe_path.display()),
715 /// None => println!("Impossible to fetch the path of this executable.")
718 pub fn self_exe_path() -> Option<Path> {
719 self_exe_name().map(|mut p| { p.pop(); p })
722 /// Optionally returns the path to the current user's home directory if known.
726 /// Returns the value of the 'HOME' environment variable if it is set
727 /// and not equal to the empty string.
731 /// Returns the value of the 'HOME' environment variable if it is
732 /// set and not equal to the empty string. Otherwise, returns the value of the
733 /// 'USERPROFILE' environment variable if it is set and not equal to the empty
741 /// match os::homedir() {
742 /// Some(ref p) => println!("{}", p.display()),
743 /// None => println!("Impossible to get your home dir!")
746 pub fn homedir() -> Option<Path> {
749 fn _homedir() -> Option<Path> {
755 fn _homedir() -> Option<Path> {
756 aux_homedir("HOME").or(aux_homedir("USERPROFILE"))
760 fn aux_homedir(home_name: &str) -> Option<Path> {
761 match getenv_as_bytes(home_name) {
763 if p.is_empty() { None } else { Path::new_opt(p) }
772 * Returns the path to a temporary directory.
774 * On Unix, returns the value of the 'TMPDIR' environment variable if it is
775 * set, otherwise for non-Android it returns '/tmp'. If Android, since there
776 * is no global temporary folder (it is usually allocated per-app), we return
779 * On Windows, returns the value of, in order, the 'TMP', 'TEMP',
780 * 'USERPROFILE' environment variable if any are set and not the empty
781 * string. Otherwise, tmpdir returns the path to the Windows directory.
783 pub fn tmpdir() -> Path {
786 fn getenv_nonempty(v: &str) -> Option<Path> {
799 fn lookup() -> Path {
800 let default = if cfg!(target_os = "android") {
801 Path::new("/data/local/tmp")
806 getenv_nonempty("TMPDIR").unwrap_or(default)
810 fn lookup() -> Path {
811 getenv_nonempty("TMP").or(
812 getenv_nonempty("TEMP").or(
813 getenv_nonempty("USERPROFILE").or(
814 getenv_nonempty("WINDIR")))).unwrap_or(Path::new("C:\\Windows"))
819 /// Convert a relative path to an absolute path
821 /// If the given path is relative, return it prepended with the current working
822 /// directory. If the given path is already an absolute path, return it
828 /// use std::path::Path;
830 /// // Assume we're in a path like /home/someuser
831 /// let rel_path = Path::new("..");
832 /// let abs_path = os::make_absolute(&rel_path);
833 /// println!("The absolute path is {}", abs_path.display());
834 /// // Prints "The absolute path is /home"
836 // NB: this is here rather than in path because it is a form of environment
837 // querying; what it does depends on the process working directory, not just
839 pub fn make_absolute(p: &Path) -> Path {
843 let mut ret = getcwd();
849 /// Changes the current working directory to the specified path, returning
850 /// whether the change was completed successfully or not.
855 /// use std::path::Path;
857 /// let root = Path::new("/");
858 /// assert!(os::change_dir(&root));
859 /// println!("Successfully changed working directory to {}!", root.display());
861 pub fn change_dir(p: &Path) -> bool {
865 fn chdir(p: &Path) -> bool {
866 let p = match p.as_str() {
868 let mut p = s.utf16_units().collect::<Vec<u16>>();
872 None => return false,
875 libc::SetCurrentDirectoryW(p.as_ptr()) != (0 as libc::BOOL)
880 fn chdir(p: &Path) -> bool {
883 libc::chdir(buf) == (0 as c_int)
889 /// Returns the platform-specific value of errno
890 pub fn errno() -> uint {
891 os_imp::errno() as uint
894 /// Return the string corresponding to an `errno()` value of `errnum`.
900 /// // Same as println!("{}", last_os_error());
901 /// println!("{}", os::error_string(os::errno() as uint));
903 pub fn error_string(errnum: uint) -> String {
904 return os_imp::error_string(errnum as i32);
907 /// Get a string representing the platform-dependent last error
908 pub fn last_os_error() -> String {
909 error_string(errno() as uint)
912 static EXIT_STATUS: AtomicInt = INIT_ATOMIC_INT;
915 * Sets the process exit code
917 * Sets the exit code returned by the process if all supervised tasks
918 * terminate successfully (without panicking). If the current root task panics
919 * and is supervised by the scheduler then any user-specified exit status is
920 * ignored and the process exits with the default panic status.
922 * Note that this is not synchronized against modifications of other threads.
924 pub fn set_exit_status(code: int) {
925 EXIT_STATUS.store(code, SeqCst)
928 /// Fetches the process's current exit code. This defaults to 0 and can change
929 /// by calling `set_exit_status`.
930 pub fn get_exit_status() -> int {
931 EXIT_STATUS.load(SeqCst)
934 #[cfg(target_os = "macos")]
935 unsafe fn load_argc_and_argv(argc: int,
936 argv: *const *const c_char) -> Vec<Vec<u8>> {
939 Vec::from_fn(argc as uint, |i| {
940 CString::new(*argv.offset(i as int), false).as_bytes_no_nul().to_vec()
945 * Returns the command line arguments
947 * Returns a list of the command line arguments.
949 #[cfg(target_os = "macos")]
950 fn real_args_as_bytes() -> Vec<Vec<u8>> {
952 let (argc, argv) = (*_NSGetArgc() as int,
953 *_NSGetArgv() as *const *const c_char);
954 load_argc_and_argv(argc, argv)
958 // As _NSGetArgc and _NSGetArgv aren't mentioned in iOS docs
959 // and use underscores in their names - they're most probably
960 // are considered private and therefore should be avoided
961 // Here is another way to get arguments using Objective C
964 // In general it looks like:
966 // let args = [[NSProcessInfo processInfo] arguments]
967 // for i in range(0, [args count])
968 // res.push([args objectAtIndex:i])
970 #[cfg(target_os = "ios")]
971 fn real_args_as_bytes() -> Vec<Vec<u8>> {
976 #[link(name = "objc")]
978 fn sel_registerName(name: *const libc::c_uchar) -> Sel;
979 fn objc_msgSend(obj: NsId, sel: Sel, ...) -> NsId;
980 fn objc_getClass(class_name: *const libc::c_uchar) -> NsId;
983 #[link(name = "Foundation", kind = "framework")]
986 type Sel = *const libc::c_void;
987 type NsId = *const libc::c_void;
989 let mut res = Vec::new();
992 let processInfoSel = sel_registerName("processInfo\0".as_ptr());
993 let argumentsSel = sel_registerName("arguments\0".as_ptr());
994 let utf8Sel = sel_registerName("UTF8String\0".as_ptr());
995 let countSel = sel_registerName("count\0".as_ptr());
996 let objectAtSel = sel_registerName("objectAtIndex:\0".as_ptr());
998 let klass = objc_getClass("NSProcessInfo\0".as_ptr());
999 let info = objc_msgSend(klass, processInfoSel);
1000 let args = objc_msgSend(info, argumentsSel);
1002 let cnt: int = mem::transmute(objc_msgSend(args, countSel));
1003 for i in range(0, cnt) {
1004 let tmp = objc_msgSend(args, objectAtSel, i);
1005 let utf_c_str: *const libc::c_char =
1006 mem::transmute(objc_msgSend(tmp, utf8Sel));
1007 let s = CString::new(utf_c_str, false);
1008 res.push(s.as_bytes_no_nul().to_vec())
1015 #[cfg(any(target_os = "linux",
1016 target_os = "android",
1017 target_os = "freebsd",
1018 target_os = "dragonfly"))]
1019 fn real_args_as_bytes() -> Vec<Vec<u8>> {
1022 match rt::args::clone() {
1024 None => panic!("process arguments not initialized")
1028 #[cfg(not(windows))]
1029 fn real_args() -> Vec<String> {
1030 real_args_as_bytes().into_iter()
1032 String::from_utf8_lossy(v.as_slice()).into_string()
1037 fn real_args() -> Vec<String> {
1040 let mut nArgs: c_int = 0;
1041 let lpArgCount: *mut c_int = &mut nArgs;
1042 let lpCmdLine = unsafe { GetCommandLineW() };
1043 let szArgList = unsafe { CommandLineToArgvW(lpCmdLine, lpArgCount) };
1045 let args = Vec::from_fn(nArgs as uint, |i| unsafe {
1046 // Determine the length of this argument.
1047 let ptr = *szArgList.offset(i as int);
1049 while *ptr.offset(len as int) != 0 { len += 1; }
1051 // Push it onto the list.
1052 let opt_s = slice::raw::buf_as_slice(ptr as *const _, len, |buf| {
1053 String::from_utf16(::str::truncate_utf16_at_nul(buf))
1055 opt_s.expect("CommandLineToArgvW returned invalid UTF-16")
1059 LocalFree(szArgList as *mut c_void);
1066 fn real_args_as_bytes() -> Vec<Vec<u8>> {
1067 real_args().into_iter().map(|s| s.into_bytes()).collect()
1070 type LPCWSTR = *const u16;
1073 #[link_name="kernel32"]
1075 fn GetCommandLineW() -> LPCWSTR;
1076 fn LocalFree(ptr: *mut c_void);
1080 #[link_name="shell32"]
1082 fn CommandLineToArgvW(lpCmdLine: LPCWSTR,
1083 pNumArgs: *mut c_int) -> *mut *mut u16;
1086 /// Returns the arguments which this program was started with (normally passed
1087 /// via the command line).
1089 /// The arguments are interpreted as utf-8, with invalid bytes replaced with \uFFFD.
1090 /// See `String::from_utf8_lossy` for details.
1096 /// // Prints each argument on a separate line
1097 /// for argument in os::args().iter() {
1098 /// println!("{}", argument);
1101 pub fn args() -> Vec<String> {
1105 /// Returns the arguments which this program was started with (normally passed
1106 /// via the command line) as byte vectors.
1107 pub fn args_as_bytes() -> Vec<Vec<u8>> {
1108 real_args_as_bytes()
1111 #[cfg(target_os = "macos")]
1113 // These functions are in crt_externs.h.
1114 pub fn _NSGetArgc() -> *mut c_int;
1115 pub fn _NSGetArgv() -> *mut *mut *mut c_char;
1118 // Round up `from` to be divisible by `to`
1119 fn round_up(from: uint, to: uint) -> uint {
1120 let r = if from % to == 0 {
1123 from + to - (from % to)
1132 /// Returns the page size of the current architecture in bytes.
1134 pub fn page_size() -> uint {
1136 libc::sysconf(libc::_SC_PAGESIZE) as uint
1140 /// Returns the page size of the current architecture in bytes.
1142 pub fn page_size() -> uint {
1145 let mut info = mem::zeroed();
1146 libc::GetSystemInfo(&mut info);
1148 return info.dwPageSize as uint;
1152 /// A memory mapped file or chunk of memory. This is a very system-specific
1153 /// interface to the OS's memory mapping facilities (`mmap` on POSIX,
1154 /// `VirtualAlloc`/`CreateFileMapping` on Windows). It makes no attempt at
1155 /// abstracting platform differences, besides in error values returned. Consider
1156 /// yourself warned.
1158 /// The memory map is released (unmapped) when the destructor is run, so don't
1159 /// let it leave scope by accident if you want it to stick around.
1160 pub struct MemoryMap {
1163 kind: MemoryMapKind,
1166 /// Type of memory map
1167 pub enum MemoryMapKind {
1168 /// Virtual memory map. Usually used to change the permissions of a given
1169 /// chunk of memory. Corresponds to `VirtualAlloc` on Windows.
1171 /// Virtual memory map. Usually used to change the permissions of a given
1172 /// chunk of memory, or for allocation. Corresponds to `VirtualAlloc` on
1177 /// Options the memory map is created with
1178 pub enum MapOption {
1179 /// The memory should be readable
1181 /// The memory should be writable
1183 /// The memory should be executable
1185 /// Create a map for a specific address range. Corresponds to `MAP_FIXED` on
1188 /// Create a memory mapping for a file with a given fd.
1190 /// When using `MapFd`, the start of the map is `uint` bytes from the start
1193 /// On POSIX, this can be used to specify the default flags passed to
1194 /// `mmap`. By default it uses `MAP_PRIVATE` and, if not using `MapFd`,
1195 /// `MAP_ANON`. This will override both of those. This is platform-specific
1196 /// (the exact values used) and ignored on Windows.
1197 MapNonStandardFlags(c_int),
1200 /// Possible errors when creating a map.
1202 /// ## The following are POSIX-specific
1204 /// fd was not open for reading or, if using `MapWritable`, was not open for
1207 /// fd was not valid
1209 /// Either the address given by `MapAddr` or offset given by `MapOffset` was
1210 /// not a multiple of `MemoryMap::granularity` (unaligned to page size).
1212 /// With `MapFd`, the fd does not support mapping.
1214 /// If using `MapAddr`, the address + `min_len` was outside of the process's
1215 /// address space. If using `MapFd`, the target of the fd didn't have enough
1216 /// resources to fulfill the request.
1218 /// A zero-length map was requested. This is invalid according to
1219 /// [POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/functions/mmap.html).
1220 /// Not all platforms obey this, but this wrapper does.
1222 /// Unrecognized error. The inner value is the unrecognized errno.
1224 /// ## The following are Windows-specific
1226 /// Unsupported combination of protection flags
1227 /// (`MapReadable`/`MapWritable`/`MapExecutable`).
1229 /// When using `MapFd`, `MapOffset` was given (Windows does not support this
1232 /// When using `MapFd`, there was already a mapping to the file.
1234 /// Unrecognized error from `VirtualAlloc`. The inner value is the return
1235 /// value of GetLastError.
1236 ErrVirtualAlloc(uint),
1237 /// Unrecognized error from `CreateFileMapping`. The inner value is the
1238 /// return value of `GetLastError`.
1239 ErrCreateFileMappingW(uint),
1240 /// Unrecognized error from `MapViewOfFile`. The inner value is the return
1241 /// value of `GetLastError`.
1242 ErrMapViewOfFile(uint)
1245 impl fmt::Show for MapError {
1246 fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result {
1247 let str = match *self {
1248 ErrFdNotAvail => "fd not available for reading or writing",
1249 ErrInvalidFd => "Invalid fd",
1251 "Unaligned address, invalid flags, negative length or \
1254 ErrNoMapSupport=> "File doesn't support mapping",
1255 ErrNoMem => "Invalid address, or not enough available memory",
1256 ErrUnsupProt => "Protection mode unsupported",
1257 ErrUnsupOffset => "Offset in virtual memory mode is unsupported",
1258 ErrAlreadyExists => "File mapping for specified file already exists",
1259 ErrZeroLength => "Zero-length mapping not allowed",
1260 ErrUnknown(code) => {
1261 return write!(out, "Unknown error = {}", code)
1263 ErrVirtualAlloc(code) => {
1264 return write!(out, "VirtualAlloc failure = {}", code)
1266 ErrCreateFileMappingW(code) => {
1267 return write!(out, "CreateFileMappingW failure = {}", code)
1269 ErrMapViewOfFile(code) => {
1270 return write!(out, "MapViewOfFile failure = {}", code)
1273 write!(out, "{}", str)
1277 impl Error for MapError {
1278 fn description(&self) -> &str { "memory map error" }
1279 fn detail(&self) -> Option<String> { Some(self.to_string()) }
1282 impl FromError<MapError> for Box<Error> {
1283 fn from_error(err: MapError) -> Box<Error> {
1290 /// Create a new mapping with the given `options`, at least `min_len` bytes
1291 /// long. `min_len` must be greater than zero; see the note on
1292 /// `ErrZeroLength`.
1293 pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
1297 return Err(ErrZeroLength)
1299 let mut addr: *const u8 = ptr::null();
1301 let mut flags = libc::MAP_PRIVATE;
1304 let mut custom_flags = false;
1305 let len = round_up(min_len, page_size());
1307 for &o in options.iter() {
1309 MapReadable => { prot |= libc::PROT_READ; },
1310 MapWritable => { prot |= libc::PROT_WRITE; },
1311 MapExecutable => { prot |= libc::PROT_EXEC; },
1313 flags |= libc::MAP_FIXED;
1317 flags |= libc::MAP_FILE;
1320 MapOffset(offset_) => { offset = offset_ as off_t; },
1321 MapNonStandardFlags(f) => { custom_flags = true; flags = f },
1324 if fd == -1 && !custom_flags { flags |= libc::MAP_ANON; }
1327 libc::mmap(addr as *mut c_void, len as libc::size_t, prot, flags,
1330 if r == libc::MAP_FAILED {
1331 Err(match errno() as c_int {
1332 libc::EACCES => ErrFdNotAvail,
1333 libc::EBADF => ErrInvalidFd,
1334 libc::EINVAL => ErrUnaligned,
1335 libc::ENODEV => ErrNoMapSupport,
1336 libc::ENOMEM => ErrNoMem,
1337 code => ErrUnknown(code as int)
1346 MapFile(ptr::null())
1352 /// Granularity that the offset or address must be for `MapOffset` and
1353 /// `MapAddr` respectively.
1354 pub fn granularity() -> uint {
1360 impl Drop for MemoryMap {
1361 /// Unmap the mapping. Panics the task if `munmap` panics.
1362 fn drop(&mut self) {
1363 if self.len == 0 { /* workaround for dummy_stack */ return; }
1366 // `munmap` only panics due to logic errors
1367 libc::munmap(self.data as *mut c_void, self.len as libc::size_t);
1374 /// Create a new mapping with the given `options`, at least `min_len` bytes long.
1375 pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
1376 use libc::types::os::arch::extra::{LPVOID, DWORD, SIZE_T, HANDLE};
1378 let mut lpAddress: LPVOID = ptr::null_mut();
1379 let mut readable = false;
1380 let mut writable = false;
1381 let mut executable = false;
1382 let mut fd: c_int = -1;
1383 let mut offset: uint = 0;
1384 let len = round_up(min_len, page_size());
1386 for &o in options.iter() {
1388 MapReadable => { readable = true; },
1389 MapWritable => { writable = true; },
1390 MapExecutable => { executable = true; }
1391 MapAddr(addr_) => { lpAddress = addr_ as LPVOID; },
1392 MapFd(fd_) => { fd = fd_; },
1393 MapOffset(offset_) => { offset = offset_; },
1394 MapNonStandardFlags(..) => {}
1398 let flProtect = match (executable, readable, writable) {
1399 (false, false, false) if fd == -1 => libc::PAGE_NOACCESS,
1400 (false, true, false) => libc::PAGE_READONLY,
1401 (false, true, true) => libc::PAGE_READWRITE,
1402 (true, false, false) if fd == -1 => libc::PAGE_EXECUTE,
1403 (true, true, false) => libc::PAGE_EXECUTE_READ,
1404 (true, true, true) => libc::PAGE_EXECUTE_READWRITE,
1405 _ => return Err(ErrUnsupProt)
1410 return Err(ErrUnsupOffset);
1413 libc::VirtualAlloc(lpAddress,
1415 libc::MEM_COMMIT | libc::MEM_RESERVE,
1419 0 => Err(ErrVirtualAlloc(errno())),
1427 let dwDesiredAccess = match (executable, readable, writable) {
1428 (false, true, false) => libc::FILE_MAP_READ,
1429 (false, true, true) => libc::FILE_MAP_WRITE,
1430 (true, true, false) => libc::FILE_MAP_READ | libc::FILE_MAP_EXECUTE,
1431 (true, true, true) => libc::FILE_MAP_WRITE | libc::FILE_MAP_EXECUTE,
1432 _ => return Err(ErrUnsupProt) // Actually, because of the check above,
1433 // we should never get here.
1436 let hFile = libc::get_osfhandle(fd) as HANDLE;
1437 let mapping = libc::CreateFileMappingW(hFile,
1443 if mapping == ptr::null_mut() {
1444 return Err(ErrCreateFileMappingW(errno()));
1446 if errno() as c_int == libc::ERROR_ALREADY_EXISTS {
1447 return Err(ErrAlreadyExists);
1449 let r = libc::MapViewOfFile(mapping,
1451 ((len as u64) >> 32) as DWORD,
1452 (offset & 0xffff_ffff) as DWORD,
1455 0 => Err(ErrMapViewOfFile(errno())),
1459 kind: MapFile(mapping as *const u8)
1466 /// Granularity of MapAddr() and MapOffset() parameter values.
1467 /// This may be greater than the value returned by page_size().
1468 pub fn granularity() -> uint {
1471 let mut info = mem::zeroed();
1472 libc::GetSystemInfo(&mut info);
1474 return info.dwAllocationGranularity as uint;
1480 impl Drop for MemoryMap {
1481 /// Unmap the mapping. Panics the task if any of `VirtualFree`,
1482 /// `UnmapViewOfFile`, or `CloseHandle` fail.
1483 fn drop(&mut self) {
1484 use libc::types::os::arch::extra::{LPCVOID, HANDLE};
1485 use libc::consts::os::extra::FALSE;
1486 if self.len == 0 { return }
1491 if libc::VirtualFree(self.data as *mut c_void, 0,
1492 libc::MEM_RELEASE) == 0 {
1493 println!("VirtualFree failed: {}", errno());
1496 MapFile(mapping) => {
1497 if libc::UnmapViewOfFile(self.data as LPCVOID) == FALSE {
1498 println!("UnmapViewOfFile failed: {}", errno());
1500 if libc::CloseHandle(mapping as HANDLE) == FALSE {
1501 println!("CloseHandle failed: {}", errno());
1510 /// Returns the pointer to the memory created or modified by this map.
1511 pub fn data(&self) -> *mut u8 { self.data }
1512 /// Returns the number of bytes this map applies to.
1513 pub fn len(&self) -> uint { self.len }
1514 /// Returns the type of mapping this represents.
1515 pub fn kind(&self) -> MemoryMapKind { self.kind }
1518 #[cfg(target_os = "linux")]
1520 pub use os::arch_consts::ARCH;
1522 pub const FAMILY: &'static str = "unix";
1524 /// A string describing the specific operating system in use: in this
1526 pub const SYSNAME: &'static str = "linux";
1528 /// Specifies the filename prefix used for shared libraries on this
1529 /// platform: in this case, `lib`.
1530 pub const DLL_PREFIX: &'static str = "lib";
1532 /// Specifies the filename suffix used for shared libraries on this
1533 /// platform: in this case, `.so`.
1534 pub const DLL_SUFFIX: &'static str = ".so";
1536 /// Specifies the file extension used for shared libraries on this
1537 /// platform that goes after the dot: in this case, `so`.
1538 pub const DLL_EXTENSION: &'static str = "so";
1540 /// Specifies the filename suffix used for executable binaries on this
1541 /// platform: in this case, the empty string.
1542 pub const EXE_SUFFIX: &'static str = "";
1544 /// Specifies the file extension, if any, used for executable binaries
1545 /// on this platform: in this case, the empty string.
1546 pub const EXE_EXTENSION: &'static str = "";
1549 #[cfg(target_os = "macos")]
1551 pub use os::arch_consts::ARCH;
1553 pub const FAMILY: &'static str = "unix";
1555 /// A string describing the specific operating system in use: in this
1557 pub const SYSNAME: &'static str = "macos";
1559 /// Specifies the filename prefix used for shared libraries on this
1560 /// platform: in this case, `lib`.
1561 pub const DLL_PREFIX: &'static str = "lib";
1563 /// Specifies the filename suffix used for shared libraries on this
1564 /// platform: in this case, `.dylib`.
1565 pub const DLL_SUFFIX: &'static str = ".dylib";
1567 /// Specifies the file extension used for shared libraries on this
1568 /// platform that goes after the dot: in this case, `dylib`.
1569 pub const DLL_EXTENSION: &'static str = "dylib";
1571 /// Specifies the filename suffix used for executable binaries on this
1572 /// platform: in this case, the empty string.
1573 pub const EXE_SUFFIX: &'static str = "";
1575 /// Specifies the file extension, if any, used for executable binaries
1576 /// on this platform: in this case, the empty string.
1577 pub const EXE_EXTENSION: &'static str = "";
1580 #[cfg(target_os = "ios")]
1582 pub use os::arch_consts::ARCH;
1584 pub const FAMILY: &'static str = "unix";
1586 /// A string describing the specific operating system in use: in this
1588 pub const SYSNAME: &'static str = "ios";
1590 /// Specifies the filename suffix used for executable binaries on this
1591 /// platform: in this case, the empty string.
1592 pub const EXE_SUFFIX: &'static str = "";
1594 /// Specifies the file extension, if any, used for executable binaries
1595 /// on this platform: in this case, the empty string.
1596 pub const EXE_EXTENSION: &'static str = "";
1599 #[cfg(target_os = "freebsd")]
1601 pub use os::arch_consts::ARCH;
1603 pub const FAMILY: &'static str = "unix";
1605 /// A string describing the specific operating system in use: in this
1606 /// case, `freebsd`.
1607 pub const SYSNAME: &'static str = "freebsd";
1609 /// Specifies the filename prefix used for shared libraries on this
1610 /// platform: in this case, `lib`.
1611 pub const DLL_PREFIX: &'static str = "lib";
1613 /// Specifies the filename suffix used for shared libraries on this
1614 /// platform: in this case, `.so`.
1615 pub const DLL_SUFFIX: &'static str = ".so";
1617 /// Specifies the file extension used for shared libraries on this
1618 /// platform that goes after the dot: in this case, `so`.
1619 pub const DLL_EXTENSION: &'static str = "so";
1621 /// Specifies the filename suffix used for executable binaries on this
1622 /// platform: in this case, the empty string.
1623 pub const EXE_SUFFIX: &'static str = "";
1625 /// Specifies the file extension, if any, used for executable binaries
1626 /// on this platform: in this case, the empty string.
1627 pub const EXE_EXTENSION: &'static str = "";
1630 #[cfg(target_os = "dragonfly")]
1632 pub use os::arch_consts::ARCH;
1634 pub const FAMILY: &'static str = "unix";
1636 /// A string describing the specific operating system in use: in this
1637 /// case, `dragonfly`.
1638 pub const SYSNAME: &'static str = "dragonfly";
1640 /// Specifies the filename prefix used for shared libraries on this
1641 /// platform: in this case, `lib`.
1642 pub const DLL_PREFIX: &'static str = "lib";
1644 /// Specifies the filename suffix used for shared libraries on this
1645 /// platform: in this case, `.so`.
1646 pub const DLL_SUFFIX: &'static str = ".so";
1648 /// Specifies the file extension used for shared libraries on this
1649 /// platform that goes after the dot: in this case, `so`.
1650 pub const DLL_EXTENSION: &'static str = "so";
1652 /// Specifies the filename suffix used for executable binaries on this
1653 /// platform: in this case, the empty string.
1654 pub const EXE_SUFFIX: &'static str = "";
1656 /// Specifies the file extension, if any, used for executable binaries
1657 /// on this platform: in this case, the empty string.
1658 pub const EXE_EXTENSION: &'static str = "";
1661 #[cfg(target_os = "android")]
1663 pub use os::arch_consts::ARCH;
1665 pub const FAMILY: &'static str = "unix";
1667 /// A string describing the specific operating system in use: in this
1668 /// case, `android`.
1669 pub const SYSNAME: &'static str = "android";
1671 /// Specifies the filename prefix used for shared libraries on this
1672 /// platform: in this case, `lib`.
1673 pub const DLL_PREFIX: &'static str = "lib";
1675 /// Specifies the filename suffix used for shared libraries on this
1676 /// platform: in this case, `.so`.
1677 pub const DLL_SUFFIX: &'static str = ".so";
1679 /// Specifies the file extension used for shared libraries on this
1680 /// platform that goes after the dot: in this case, `so`.
1681 pub const DLL_EXTENSION: &'static str = "so";
1683 /// Specifies the filename suffix used for executable binaries on this
1684 /// platform: in this case, the empty string.
1685 pub const EXE_SUFFIX: &'static str = "";
1687 /// Specifies the file extension, if any, used for executable binaries
1688 /// on this platform: in this case, the empty string.
1689 pub const EXE_EXTENSION: &'static str = "";
1692 #[cfg(target_os = "windows")]
1694 pub use os::arch_consts::ARCH;
1696 pub const FAMILY: &'static str = "windows";
1698 /// A string describing the specific operating system in use: in this
1699 /// case, `windows`.
1700 pub const SYSNAME: &'static str = "windows";
1702 /// Specifies the filename prefix used for shared libraries on this
1703 /// platform: in this case, the empty string.
1704 pub const DLL_PREFIX: &'static str = "";
1706 /// Specifies the filename suffix used for shared libraries on this
1707 /// platform: in this case, `.dll`.
1708 pub const DLL_SUFFIX: &'static str = ".dll";
1710 /// Specifies the file extension used for shared libraries on this
1711 /// platform that goes after the dot: in this case, `dll`.
1712 pub const DLL_EXTENSION: &'static str = "dll";
1714 /// Specifies the filename suffix used for executable binaries on this
1715 /// platform: in this case, `.exe`.
1716 pub const EXE_SUFFIX: &'static str = ".exe";
1718 /// Specifies the file extension, if any, used for executable binaries
1719 /// on this platform: in this case, `exe`.
1720 pub const EXE_EXTENSION: &'static str = "exe";
1723 #[cfg(target_arch = "x86")]
1725 pub const ARCH: &'static str = "x86";
1728 #[cfg(target_arch = "x86_64")]
1730 pub const ARCH: &'static str = "x86_64";
1733 #[cfg(target_arch = "arm")]
1735 pub const ARCH: &'static str = "arm";
1738 #[cfg(target_arch = "mips")]
1740 pub const ARCH: &'static str = "mips";
1743 #[cfg(target_arch = "mipsel")]
1745 pub const ARCH: &'static str = "mipsel";
1753 use os::{env, getcwd, getenv, make_absolute};
1754 use os::{split_paths, join_paths, setenv, unsetenv};
1760 pub fn last_os_error() {
1761 debug!("{}", os::last_os_error());
1764 fn make_rand_name() -> String {
1765 let mut rng = rand::task_rng();
1766 let n = format!("TEST{}", rng.gen_ascii_chars().take(10u)
1767 .collect::<String>());
1768 assert!(getenv(n.as_slice()).is_none());
1773 fn test_num_cpus() {
1774 assert!(os::num_cpus() > 0);
1779 let n = make_rand_name();
1780 setenv(n.as_slice(), "VALUE");
1781 assert_eq!(getenv(n.as_slice()), option::Some("VALUE".to_string()));
1785 fn test_unsetenv() {
1786 let n = make_rand_name();
1787 setenv(n.as_slice(), "VALUE");
1788 unsetenv(n.as_slice());
1789 assert_eq!(getenv(n.as_slice()), option::None);
1794 fn test_setenv_overwrite() {
1795 let n = make_rand_name();
1796 setenv(n.as_slice(), "1");
1797 setenv(n.as_slice(), "2");
1798 assert_eq!(getenv(n.as_slice()), option::Some("2".to_string()));
1799 setenv(n.as_slice(), "");
1800 assert_eq!(getenv(n.as_slice()), option::Some("".to_string()));
1803 // Windows GetEnvironmentVariable requires some extra work to make sure
1804 // the buffer the variable is copied into is the right size
1807 fn test_getenv_big() {
1808 let mut s = "".to_string();
1811 s.push_str("aaaaaaaaaa");
1814 let n = make_rand_name();
1815 setenv(n.as_slice(), s.as_slice());
1816 debug!("{}", s.clone());
1817 assert_eq!(getenv(n.as_slice()), option::Some(s));
1821 fn test_self_exe_name() {
1822 let path = os::self_exe_name();
1823 assert!(path.is_some());
1824 let path = path.unwrap();
1825 debug!("{}", path.display());
1827 // Hard to test this function
1828 assert!(path.is_absolute());
1832 fn test_self_exe_path() {
1833 let path = os::self_exe_path();
1834 assert!(path.is_some());
1835 let path = path.unwrap();
1836 debug!("{}", path.display());
1838 // Hard to test this function
1839 assert!(path.is_absolute());
1844 fn test_env_getenv() {
1846 assert!(e.len() > 0u);
1848 let (n, v) = (*p).clone();
1850 let v2 = getenv(n.as_slice());
1851 // MingW seems to set some funky environment variables like
1852 // "=C:=C:\MinGW\msys\1.0\bin" and "!::=::\" that are returned
1853 // from env() but not visible from getenv().
1854 assert!(v2.is_none() || v2 == option::Some(v));
1859 fn test_env_set_get_huge() {
1860 let n = make_rand_name();
1861 let s = "x".repeat(10000).to_string();
1862 setenv(n.as_slice(), s.as_slice());
1863 assert_eq!(getenv(n.as_slice()), Some(s));
1864 unsetenv(n.as_slice());
1865 assert_eq!(getenv(n.as_slice()), None);
1869 fn test_env_setenv() {
1870 let n = make_rand_name();
1873 setenv(n.as_slice(), "VALUE");
1874 assert!(!e.contains(&(n.clone(), "VALUE".to_string())));
1877 assert!(e.contains(&(n, "VALUE".to_string())));
1882 assert!((!Path::new("test-path").is_absolute()));
1885 debug!("Current working directory: {}", cwd.display());
1887 debug!("{}", make_absolute(&Path::new("test-path")).display());
1888 debug!("{}", make_absolute(&Path::new("/usr/bin")).display());
1894 let oldhome = getenv("HOME");
1896 setenv("HOME", "/home/MountainView");
1897 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1900 assert!(os::homedir().is_none());
1902 for s in oldhome.iter() {
1903 setenv("HOME", s.as_slice());
1911 let oldhome = getenv("HOME");
1912 let olduserprofile = getenv("USERPROFILE");
1915 setenv("USERPROFILE", "");
1917 assert!(os::homedir().is_none());
1919 setenv("HOME", "/home/MountainView");
1920 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1924 setenv("USERPROFILE", "/home/MountainView");
1925 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1927 setenv("HOME", "/home/MountainView");
1928 setenv("USERPROFILE", "/home/PaloAlto");
1929 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1931 for s in oldhome.iter() {
1932 setenv("HOME", s.as_slice());
1934 for s in olduserprofile.iter() {
1935 setenv("USERPROFILE", s.as_slice());
1940 fn memory_map_rw() {
1941 use result::{Ok, Err};
1943 let chunk = match os::MemoryMap::new(16, &[
1948 Err(msg) => panic!("{}", msg)
1950 assert!(chunk.len >= 16);
1954 assert!(*chunk.data == 0xBE);
1959 fn memory_map_file() {
1960 use result::{Ok, Err};
1966 fn lseek_(fd: c_int, size: uint) {
1968 assert!(lseek(fd, size as off_t, SEEK_SET) == size as off_t);
1972 fn lseek_(fd: c_int, size: uint) {
1974 assert!(lseek(fd, size as c_long, SEEK_SET) == size as c_long);
1978 let mut path = tmpdir();
1979 path.push("mmap_file.tmp");
1980 let size = MemoryMap::granularity() * 2;
1983 let fd = path.with_c_str(|path| {
1984 open(path, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR)
1987 "x".with_c_str(|x| assert!(write(fd, x as *const c_void, 1) == 1));
1990 let chunk = match MemoryMap::new(size / 2, &[
1997 Err(msg) => panic!("{}", msg)
1999 assert!(chunk.len > 0);
2003 assert!(*chunk.data == 0xbe);
2008 fs::unlink(&path).unwrap();
2013 fn split_paths_windows() {
2014 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
2015 split_paths(unparsed) ==
2016 parsed.iter().map(|s| Path::new(*s)).collect()
2019 assert!(check_parse("", &mut [""]));
2020 assert!(check_parse(r#""""#, &mut [""]));
2021 assert!(check_parse(";;", &mut ["", "", ""]));
2022 assert!(check_parse(r"c:\", &mut [r"c:\"]));
2023 assert!(check_parse(r"c:\;", &mut [r"c:\", ""]));
2024 assert!(check_parse(r"c:\;c:\Program Files\",
2025 &mut [r"c:\", r"c:\Program Files\"]));
2026 assert!(check_parse(r#"c:\;c:\"foo"\"#, &mut [r"c:\", r"c:\foo\"]));
2027 assert!(check_parse(r#"c:\;c:\"foo;bar"\;c:\baz"#,
2028 &mut [r"c:\", r"c:\foo;bar\", r"c:\baz"]));
2033 fn split_paths_unix() {
2034 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
2035 split_paths(unparsed) ==
2036 parsed.iter().map(|s| Path::new(*s)).collect()
2039 assert!(check_parse("", &mut [""]));
2040 assert!(check_parse("::", &mut ["", "", ""]));
2041 assert!(check_parse("/", &mut ["/"]));
2042 assert!(check_parse("/:", &mut ["/", ""]));
2043 assert!(check_parse("/:/usr/local", &mut ["/", "/usr/local"]));
2048 fn join_paths_unix() {
2049 fn test_eq(input: &[&str], output: &str) -> bool {
2050 join_paths(input).unwrap().as_slice() == output.as_bytes()
2053 assert!(test_eq(&[], ""));
2054 assert!(test_eq(&["/bin", "/usr/bin", "/usr/local/bin"],
2055 "/bin:/usr/bin:/usr/local/bin"));
2056 assert!(test_eq(&["", "/bin", "", "", "/usr/bin", ""],
2057 ":/bin:::/usr/bin:"));
2058 assert!(join_paths(&["/te:st"]).is_err());
2063 fn join_paths_windows() {
2064 fn test_eq(input: &[&str], output: &str) -> bool {
2065 join_paths(input).unwrap().as_slice() == output.as_bytes()
2068 assert!(test_eq(&[], ""));
2069 assert!(test_eq(&[r"c:\windows", r"c:\"],
2070 r"c:\windows;c:\"));
2071 assert!(test_eq(&["", r"c:\windows", "", "", r"c:\", ""],
2072 r";c:\windows;;;c:\;"));
2073 assert!(test_eq(&[r"c:\te;st", r"c:\"],
2074 r#""c:\te;st";c:\"#));
2075 assert!(join_paths(&[r#"c:\te"st"#]).is_err());
2078 // More recursive_mkdir tests are in extra::tempfile