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.
29 #![allow(missing_doc)]
30 #![allow(non_snake_case_functions)]
33 use collections::Collection;
36 use libc::{c_void, c_int};
39 use option::{Some, None, Option};
41 use path::{Path, GenericPath, BytesContainer};
44 use result::{Err, Ok, Result};
45 use slice::{Vector, ImmutableVector, MutableVector};
46 use str::{Str, StrSlice, StrAllocating};
49 use sync::atomics::{AtomicInt, INIT_ATOMIC_INT, SeqCst};
60 pub static TMPBUF_SZ : uint = 1000u;
61 static BUF_BYTES : uint = 2048u;
63 /// Returns the current working directory as a Path.
67 /// Fails if the current working directory value is invalid:
70 /// * Current directory does not exist.
71 /// * There are insufficient permissions to access the current directory.
78 /// // We assume that we are in a valid directory like "/home".
79 /// let current_working_directory = os::getcwd();
80 /// println!("The current directory is {}", current_working_directory.display());
84 pub fn getcwd() -> Path {
87 let mut buf = [0 as c_char, ..BUF_BYTES];
89 if libc::getcwd(buf.as_mut_ptr(), buf.len() as libc::size_t).is_null() {
92 Path::new(CString::new(buf.as_ptr(), false))
96 /// Returns the current working directory as a Path.
100 /// Fails if the current working directory value is invalid.
103 /// * Current directory does not exist.
104 /// * There are insufficient permissions to access the current directory.
111 /// // We assume that we are in a valid directory like "C:\\Windows".
112 /// let current_working_directory = os::getcwd();
113 /// println!("The current directory is {}", current_working_directory.display());
117 pub fn getcwd() -> Path {
119 use libc::GetCurrentDirectoryW;
121 let mut buf = [0 as u16, ..BUF_BYTES];
123 if libc::GetCurrentDirectoryW(buf.len() as DWORD, buf.as_mut_ptr()) == 0 as DWORD {
127 Path::new(str::from_utf16(str::truncate_utf16_at_nul(buf))
128 .expect("GetCurrentDirectoryW returned invalid UTF-16"))
133 use libc::types::os::arch::extra::DWORD;
135 use option::{None, Option};
138 use slice::{MutableVector, ImmutableVector};
144 pub fn fill_utf16_buf_and_decode(f: |*mut u16, DWORD| -> DWORD)
148 let mut n = TMPBUF_SZ as DWORD;
150 let mut done = false;
152 let mut buf = Vec::from_elem(n as uint, 0u16);
153 let k = f(buf.as_mut_ptr(), n);
154 if k == (0 as DWORD) {
157 libc::GetLastError() ==
158 libc::ERROR_INSUFFICIENT_BUFFER as DWORD {
166 let sub = buf.slice(0, k as uint);
167 // We want to explicitly catch the case when the
168 // closure returned invalid UTF-16, rather than
169 // set `res` to None and continue.
170 let s = str::from_utf16(sub)
171 .expect("fill_utf16_buf_and_decode: closure created invalid UTF-16");
172 res = option::Some(s)
181 Accessing environment variables is not generally threadsafe.
182 Serialize access through a global lock.
184 fn with_env_lock<T>(f: || -> T) -> T {
185 use rt::mutex::{StaticNativeMutex, NATIVE_MUTEX_INIT};
187 static mut lock: StaticNativeMutex = NATIVE_MUTEX_INIT;
190 let _guard = lock.lock();
195 /// Returns a vector of (variable, value) pairs, for all the environment
196 /// variables of the current process.
198 /// Invalid UTF-8 bytes are replaced with \uFFFD. See `str::from_utf8_lossy()`
206 /// // We will iterate through the references to the element returned by os::env();
207 /// for &(ref key, ref value) in os::env().iter() {
208 /// println!("'{}': '{}'", key, value );
211 pub fn env() -> Vec<(String,String)> {
212 env_as_bytes().move_iter().map(|(k,v)| {
213 let k = str::from_utf8_lossy(k.as_slice()).to_string();
214 let v = str::from_utf8_lossy(v.as_slice()).to_string();
219 /// Returns a vector of (variable, value) byte-vector pairs for all the
220 /// environment variables of the current process.
221 pub fn env_as_bytes() -> Vec<(Vec<u8>,Vec<u8>)> {
224 unsafe fn get_env_pairs() -> Vec<Vec<u8>> {
227 use libc::funcs::extra::kernel32::{
228 GetEnvironmentStringsW,
229 FreeEnvironmentStringsW
231 let ch = GetEnvironmentStringsW();
233 fail!("os::env() failure getting env string from OS: {}",
234 os::last_os_error());
236 // Here, we lossily decode the string as UTF16.
238 // The docs suggest that the result should be in Unicode, but
239 // Windows doesn't guarantee it's actually UTF16 -- it doesn't
240 // validate the environment string passed to CreateProcess nor
241 // SetEnvironmentVariable. Yet, it's unlikely that returning a
242 // raw u16 buffer would be of practical use since the result would
243 // be inherently platform-dependent and introduce additional
244 // complexity to this code.
246 // Using the non-Unicode version of GetEnvironmentStrings is even
247 // worse since the result is in an OEM code page. Characters that
248 // can't be encoded in the code page would be turned into question
250 let mut result = Vec::new();
252 while *ch.offset(i) != 0 {
253 let p = &*ch.offset(i);
254 let len = ptr::position(p, |c| *c == 0);
255 raw::buf_as_slice(p, len, |s| {
256 result.push(str::from_utf16_lossy(s).into_bytes());
260 FreeEnvironmentStringsW(ch);
264 unsafe fn get_env_pairs() -> Vec<Vec<u8>> {
268 fn rust_env_pairs() -> **c_char;
270 let environ = rust_env_pairs();
271 if environ as uint == 0 {
272 fail!("os::env() failure getting env string from OS: {}",
273 os::last_os_error());
275 let mut result = Vec::new();
276 ptr::array_each(environ, |e| {
278 Vec::from_slice(CString::new(e, false).as_bytes_no_nul());
279 result.push(env_pair);
284 fn env_convert(input: Vec<Vec<u8>>) -> Vec<(Vec<u8>, Vec<u8>)> {
285 let mut pairs = Vec::new();
286 for p in input.iter() {
287 let mut it = p.as_slice().splitn(1, |b| *b == '=' as u8);
288 let key = Vec::from_slice(it.next().unwrap());
289 let val = Vec::from_slice(it.next().unwrap_or(&[]));
290 pairs.push((key, val));
295 let unparsed_environ = get_env_pairs();
296 env_convert(unparsed_environ)
302 /// Fetches the environment variable `n` from the current process, returning
303 /// None if the variable isn't set.
305 /// Any invalid UTF-8 bytes in the value are replaced by \uFFFD. See
306 /// `str::from_utf8_lossy()` for details.
310 /// Fails if `n` has any interior NULs.
317 /// let key = "HOME";
318 /// match os::getenv(key) {
319 /// Some(val) => println!("{}: {}", key, val),
320 /// None => println!("{} is not defined in the environment.", key)
323 pub fn getenv(n: &str) -> Option<String> {
324 getenv_as_bytes(n).map(|v| str::from_utf8_lossy(v.as_slice()).to_string())
328 /// Fetches the environment variable `n` byte vector from the current process,
329 /// returning None if the variable isn't set.
333 /// Fails if `n` has any interior NULs.
334 pub fn getenv_as_bytes(n: &str) -> Option<Vec<u8>> {
339 let s = n.with_c_str(|buf| libc::getenv(buf));
343 Some(Vec::from_slice(CString::new(s,
344 false).as_bytes_no_nul()))
351 /// Fetches the environment variable `n` from the current process, returning
352 /// None if the variable isn't set.
353 pub fn getenv(n: &str) -> Option<String> {
356 use os::win32::{fill_utf16_buf_and_decode};
357 let n = n.to_utf16().append_one(0);
358 fill_utf16_buf_and_decode(|buf, sz| {
359 libc::GetEnvironmentVariableW(n.as_ptr(), buf, sz)
366 /// Fetches the environment variable `n` byte vector from the current process,
367 /// returning None if the variable isn't set.
368 pub fn getenv_as_bytes(n: &str) -> Option<Vec<u8>> {
369 getenv(n).map(|s| s.into_bytes())
372 /// Sets the environment variable `n` to the value `v` for the currently running
381 /// os::setenv(key, "VALUE");
382 /// match os::getenv(key) {
383 /// Some(ref val) => println!("{}: {}", key, val),
384 /// None => println!("{} is not defined in the environment.", key)
387 pub fn setenv(n: &str, v: &str) {
389 fn _setenv(n: &str, v: &str) {
392 n.with_c_str(|nbuf| {
393 v.with_c_str(|vbuf| {
394 libc::funcs::posix01::unistd::setenv(nbuf, vbuf, 1);
402 fn _setenv(n: &str, v: &str) {
403 let n = n.to_utf16().append_one(0);
404 let v = v.to_utf16().append_one(0);
407 libc::SetEnvironmentVariableW(n.as_ptr(), v.as_ptr());
414 /// Remove a variable from the environment entirely.
415 pub fn unsetenv(n: &str) {
417 fn _unsetenv(n: &str) {
420 n.with_c_str(|nbuf| {
421 libc::funcs::posix01::unistd::unsetenv(nbuf);
428 fn _unsetenv(n: &str) {
429 let n = n.to_utf16().append_one(0);
432 libc::SetEnvironmentVariableW(n.as_ptr(), ptr::null());
440 /// Parse a string or vector according to the platform's conventions
441 /// for the `PATH` environment variable and return a Vec<Path>.
442 /// Drops empty paths.
448 /// let key = "PATH";
449 /// match os::getenv(key) {
451 /// for path in os::split_paths(paths).iter() {
452 /// println!("'{}'", path.display());
455 /// None => println!("{} is not defined in the environnement.", key)
458 pub fn split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> {
459 unparsed.container_as_bytes()
460 .split(|b| *b == ':' as u8)
461 .filter(|s| s.len() > 0)
467 /// Parse a string or vector according to the platform's conventions
468 /// for the `PATH` environment variable. Drops empty paths.
469 pub fn split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> {
470 // On Windows, the PATH environment variable is semicolon separated. Double
471 // quotes are used as a way of introducing literal semicolons (since
472 // c:\some;dir is a valid Windows path). Double quotes are not themselves
473 // permitted in path names, so there is no way to escape a double quote.
474 // Quoted regions can appear in arbitrary locations, so
476 // c:\foo;c:\som"e;di"r;c:\bar
478 // Should parse as [c:\foo, c:\some;dir, c:\bar].
480 // (The above is based on testing; there is no clear reference available
483 let mut parsed = Vec::new();
484 let mut in_progress = Vec::new();
485 let mut in_quote = false;
487 for b in unparsed.container_as_bytes().iter() {
489 ';' if !in_quote => {
490 // ignore zero-length path strings
491 if in_progress.len() > 0 {
492 parsed.push(Path::new(in_progress.as_slice()));
494 in_progress.truncate(0)
497 in_quote = !in_quote;
500 in_progress.push(*b);
505 if in_progress.len() > 0 {
506 parsed.push(Path::new(in_progress));
512 /// A low-level OS in-memory pipe.
514 /// A file descriptor representing the reading end of the pipe. Data written
515 /// on the `out` file descriptor can be read from this file descriptor.
517 /// A file descriptor representing the write end of the pipe. Data written
518 /// to this file descriptor can be read from the `input` file descriptor.
522 /// Creates a new low-level OS in-memory pipe represented as a Pipe struct.
524 pub fn pipe() -> Pipe {
526 let mut fds = Pipe {input: 0,
528 assert_eq!(libc::pipe(&mut fds.input), 0);
529 return Pipe {input: fds.input, out: fds.out};
533 /// Creates a new low-level OS in-memory pipe represented as a Pipe struct.
535 pub fn pipe() -> Pipe {
537 // Windows pipes work subtly differently than unix pipes, and their
538 // inheritance has to be handled in a different way that I do not
539 // fully understand. Here we explicitly make the pipe non-inheritable,
540 // which means to pass it to a subprocess they need to be duplicated
541 // first, as in std::run.
542 let mut fds = Pipe {input: 0,
544 let res = libc::pipe(&mut fds.input, 1024 as ::libc::c_uint,
545 (libc::O_BINARY | libc::O_NOINHERIT) as c_int);
547 assert!((fds.input != -1 && fds.input != 0 ));
548 assert!((fds.out != -1 && fds.input != 0));
549 return Pipe {input: fds.input, out: fds.out};
553 /// Returns the proper dll filename for the given basename of a file
555 #[cfg(not(target_os="ios"))]
556 pub fn dll_filename(base: &str) -> String {
557 format!("{}{}{}", consts::DLL_PREFIX, base, consts::DLL_SUFFIX)
560 /// Optionally returns the filesystem path to the current executable which is
561 /// running but with the executable name.
568 /// match os::self_exe_name() {
569 /// Some(exe_path) => println!("Path of this executable is: {}", exe_path.display()),
570 /// None => println!("Unable to get the path of this executable!")
573 pub fn self_exe_name() -> Option<Path> {
575 #[cfg(target_os = "freebsd")]
576 fn load_self() -> Option<Vec<u8>> {
578 use libc::funcs::bsd44::*;
579 use libc::consts::os::extra::*;
580 let mib = vec![CTL_KERN as c_int,
582 KERN_PROC_PATHNAME as c_int, -1 as c_int];
583 let mut sz: libc::size_t = 0;
584 let err = sysctl(mib.as_ptr(), mib.len() as ::libc::c_uint,
585 ptr::mut_null(), &mut sz, ptr::null(),
587 if err != 0 { return None; }
588 if sz == 0 { return None; }
589 let mut v: Vec<u8> = Vec::with_capacity(sz as uint);
590 let err = sysctl(mib.as_ptr(), mib.len() as ::libc::c_uint,
591 v.as_mut_ptr() as *mut c_void, &mut sz, ptr::null(),
593 if err != 0 { return None; }
594 if sz == 0 { return None; }
595 v.set_len(sz as uint - 1); // chop off trailing NUL
600 #[cfg(target_os = "linux")]
601 #[cfg(target_os = "android")]
602 fn load_self() -> Option<Vec<u8>> {
605 match io::fs::readlink(&Path::new("/proc/self/exe")) {
606 Ok(path) => Some(path.into_vec()),
611 #[cfg(target_os = "macos")]
612 #[cfg(target_os = "ios")]
613 fn load_self() -> Option<Vec<u8>> {
615 use libc::funcs::extra::_NSGetExecutablePath;
617 _NSGetExecutablePath(ptr::mut_null(), &mut sz);
618 if sz == 0 { return None; }
619 let mut v: Vec<u8> = Vec::with_capacity(sz as uint);
620 let err = _NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz);
621 if err != 0 { return None; }
622 v.set_len(sz as uint - 1); // chop off trailing NUL
628 fn load_self() -> Option<Vec<u8>> {
632 use os::win32::fill_utf16_buf_and_decode;
633 fill_utf16_buf_and_decode(|buf, sz| {
634 libc::GetModuleFileNameW(0u as libc::DWORD, buf, sz)
635 }).map(|s| s.into_string().into_bytes())
639 load_self().and_then(Path::new_opt)
642 /// Optionally returns the filesystem path to the current executable which is
645 /// Like self_exe_name() but without the binary's name.
652 /// match os::self_exe_path() {
653 /// Some(exe_path) => println!("Executable's Path is: {}", exe_path.display()),
654 /// None => println!("Impossible to fetch the path of this executable.")
657 pub fn self_exe_path() -> Option<Path> {
658 self_exe_name().map(|mut p| { p.pop(); p })
661 /// Optionally returns the path to the current user's home directory if known.
665 /// Returns the value of the 'HOME' environment variable if it is set
666 /// and not equal to the empty string.
670 /// Returns the value of the 'HOME' environment variable if it is
671 /// set and not equal to the empty string. Otherwise, returns the value of the
672 /// 'USERPROFILE' environment variable if it is set and not equal to the empty
680 /// match os::homedir() {
681 /// Some(ref p) => println!("{}", p.display()),
682 /// None => println!("Impossible to get your home dir!")
685 pub fn homedir() -> Option<Path> {
688 fn _homedir() -> Option<Path> {
694 fn _homedir() -> Option<Path> {
695 aux_homedir("HOME").or(aux_homedir("USERPROFILE"))
699 fn aux_homedir(home_name: &str) -> Option<Path> {
700 match getenv_as_bytes(home_name) {
702 if p.is_empty() { None } else { Path::new_opt(p) }
711 * Returns the path to a temporary directory.
713 * On Unix, returns the value of the 'TMPDIR' environment variable if it is
714 * set, otherwise for non-Android it returns '/tmp'. If Android, since there
715 * is no global temporary folder (it is usually allocated per-app), we return
718 * On Windows, returns the value of, in order, the 'TMP', 'TEMP',
719 * 'USERPROFILE' environment variable if any are set and not the empty
720 * string. Otherwise, tmpdir returns the path to the Windows directory.
722 pub fn tmpdir() -> Path {
725 fn getenv_nonempty(v: &str) -> Option<Path> {
738 fn lookup() -> Path {
739 let default = if cfg!(target_os = "android") {
740 Path::new("/data/local/tmp")
745 getenv_nonempty("TMPDIR").unwrap_or(default)
749 fn lookup() -> Path {
750 getenv_nonempty("TMP").or(
751 getenv_nonempty("TEMP").or(
752 getenv_nonempty("USERPROFILE").or(
753 getenv_nonempty("WINDIR")))).unwrap_or(Path::new("C:\\Windows"))
758 * Convert a relative path to an absolute path
760 * If the given path is relative, return it prepended with the current working
761 * directory. If the given path is already an absolute path, return it
764 // NB: this is here rather than in path because it is a form of environment
765 // querying; what it does depends on the process working directory, not just
767 pub fn make_absolute(p: &Path) -> Path {
771 let mut ret = getcwd();
777 /// Changes the current working directory to the specified path, returning
778 /// whether the change was completed successfully or not.
779 pub fn change_dir(p: &Path) -> bool {
783 fn chdir(p: &Path) -> bool {
784 let p = match p.as_str() {
785 Some(s) => s.to_utf16().append_one(0),
786 None => return false,
789 libc::SetCurrentDirectoryW(p.as_ptr()) != (0 as libc::BOOL)
794 fn chdir(p: &Path) -> bool {
797 libc::chdir(buf) == (0 as c_int)
804 /// Returns the platform-specific value of errno
805 pub fn errno() -> int {
806 #[cfg(target_os = "macos")]
807 #[cfg(target_os = "ios")]
808 #[cfg(target_os = "freebsd")]
809 fn errno_location() -> *c_int {
811 fn __error() -> *c_int;
818 #[cfg(target_os = "linux")]
819 #[cfg(target_os = "android")]
820 fn errno_location() -> *c_int {
822 fn __errno_location() -> *c_int;
830 (*errno_location()) as int
835 /// Returns the platform-specific value of errno
836 pub fn errno() -> uint {
837 use libc::types::os::arch::extra::DWORD;
839 #[link_name = "kernel32"]
841 fn GetLastError() -> DWORD;
845 GetLastError() as uint
849 /// Return the string corresponding to an `errno()` value of `errnum`.
850 pub fn error_string(errnum: uint) -> String {
851 return strerror(errnum);
854 fn strerror(errnum: uint) -> String {
855 #[cfg(target_os = "macos")]
856 #[cfg(target_os = "ios")]
857 #[cfg(target_os = "android")]
858 #[cfg(target_os = "freebsd")]
859 fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: libc::size_t)
862 fn strerror_r(errnum: c_int, buf: *mut c_char,
863 buflen: libc::size_t) -> c_int;
866 strerror_r(errnum, buf, buflen)
870 // GNU libc provides a non-compliant version of strerror_r by default
871 // and requires macros to instead use the POSIX compliant variant.
872 // So we just use __xpg_strerror_r which is always POSIX compliant
873 #[cfg(target_os = "linux")]
874 fn strerror_r(errnum: c_int, buf: *mut c_char,
875 buflen: libc::size_t) -> c_int {
877 fn __xpg_strerror_r(errnum: c_int,
879 buflen: libc::size_t)
883 __xpg_strerror_r(errnum, buf, buflen)
887 let mut buf = [0 as c_char, ..TMPBUF_SZ];
889 let p = buf.as_mut_ptr();
891 if strerror_r(errnum as c_int, p, buf.len() as libc::size_t) < 0 {
892 fail!("strerror_r failure");
895 str::raw::from_c_str(p as *c_char).into_string()
900 fn strerror(errnum: uint) -> String {
901 use libc::types::os::arch::extra::DWORD;
902 use libc::types::os::arch::extra::LPWSTR;
903 use libc::types::os::arch::extra::LPVOID;
904 use libc::types::os::arch::extra::WCHAR;
906 #[link_name = "kernel32"]
908 fn FormatMessageW(flags: DWORD,
918 static FORMAT_MESSAGE_FROM_SYSTEM: DWORD = 0x00001000;
919 static FORMAT_MESSAGE_IGNORE_INSERTS: DWORD = 0x00000200;
921 // This value is calculated from the macro
922 // MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT)
923 let langId = 0x0800 as DWORD;
925 let mut buf = [0 as WCHAR, ..TMPBUF_SZ];
928 let res = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
929 FORMAT_MESSAGE_IGNORE_INSERTS,
937 // Sometimes FormatMessageW can fail e.g. system doesn't like langId,
938 let fm_err = errno();
939 return format!("OS Error {} (FormatMessageW() returned error {})", errnum, fm_err);
942 let msg = str::from_utf16(str::truncate_utf16_at_nul(buf));
944 Some(msg) => format!("OS Error {}: {}", errnum, msg),
945 None => format!("OS Error {} (FormatMessageW() returned invalid UTF-16)", errnum),
951 /// Get a string representing the platform-dependent last error
952 pub fn last_os_error() -> String {
953 error_string(errno() as uint)
956 static mut EXIT_STATUS: AtomicInt = INIT_ATOMIC_INT;
959 * Sets the process exit code
961 * Sets the exit code returned by the process if all supervised tasks
962 * terminate successfully (without failing). If the current root task fails
963 * and is supervised by the scheduler then any user-specified exit status is
964 * ignored and the process exits with the default failure status.
966 * Note that this is not synchronized against modifications of other threads.
968 pub fn set_exit_status(code: int) {
969 unsafe { EXIT_STATUS.store(code, SeqCst) }
972 /// Fetches the process's current exit code. This defaults to 0 and can change
973 /// by calling `set_exit_status`.
974 pub fn get_exit_status() -> int {
975 unsafe { EXIT_STATUS.load(SeqCst) }
978 #[cfg(target_os = "macos")]
979 unsafe fn load_argc_and_argv(argc: int, argv: **c_char) -> Vec<Vec<u8>> {
982 Vec::from_fn(argc as uint, |i| {
983 Vec::from_slice(CString::new(*argv.offset(i as int),
984 false).as_bytes_no_nul())
989 * Returns the command line arguments
991 * Returns a list of the command line arguments.
993 #[cfg(target_os = "macos")]
994 fn real_args_as_bytes() -> Vec<Vec<u8>> {
996 let (argc, argv) = (*_NSGetArgc() as int,
997 *_NSGetArgv() as **c_char);
998 load_argc_and_argv(argc, argv)
1002 // As _NSGetArgc and _NSGetArgv aren't mentioned in iOS docs
1003 // and use underscores in their names - they're most probably
1004 // are considered private and therefore should be avoided
1005 // Here is another way to get arguments using Objective C
1008 // In general it looks like:
1010 // let args = [[NSProcessInfo processInfo] arguments]
1011 // for i in range(0, [args count])
1012 // res.push([args objectAtIndex:i])
1014 #[cfg(target_os = "ios")]
1015 fn real_args_as_bytes() -> Vec<Vec<u8>> {
1020 #[link(name = "objc")]
1022 fn sel_registerName(name: *libc::c_uchar) -> Sel;
1023 fn objc_msgSend(obj: NsId, sel: Sel, ...) -> NsId;
1024 fn objc_getClass(class_name: *libc::c_uchar) -> NsId;
1027 #[link(name = "Foundation", kind = "framework")]
1030 type Sel = *libc::c_void;
1031 type NsId = *libc::c_void;
1033 let mut res = Vec::new();
1036 let processInfoSel = sel_registerName("processInfo\0".as_ptr());
1037 let argumentsSel = sel_registerName("arguments\0".as_ptr());
1038 let utf8Sel = sel_registerName("UTF8String\0".as_ptr());
1039 let countSel = sel_registerName("count\0".as_ptr());
1040 let objectAtSel = sel_registerName("objectAtIndex:\0".as_ptr());
1042 let klass = objc_getClass("NSProcessInfo\0".as_ptr());
1043 let info = objc_msgSend(klass, processInfoSel);
1044 let args = objc_msgSend(info, argumentsSel);
1046 let cnt: int = mem::transmute(objc_msgSend(args, countSel));
1047 for i in range(0, cnt) {
1048 let tmp = objc_msgSend(args, objectAtSel, i);
1049 let utf_c_str: *libc::c_char = mem::transmute(objc_msgSend(tmp, utf8Sel));
1050 let s = CString::new(utf_c_str, false);
1051 if s.is_not_null() {
1052 res.push(Vec::from_slice(s.as_bytes_no_nul()))
1060 #[cfg(target_os = "linux")]
1061 #[cfg(target_os = "android")]
1062 #[cfg(target_os = "freebsd")]
1063 fn real_args_as_bytes() -> Vec<Vec<u8>> {
1066 match rt::args::clone() {
1068 None => fail!("process arguments not initialized")
1072 #[cfg(not(windows))]
1073 fn real_args() -> Vec<String> {
1074 real_args_as_bytes().move_iter()
1076 str::from_utf8_lossy(v.as_slice()).into_string()
1081 fn real_args() -> Vec<String> {
1084 let mut nArgs: c_int = 0;
1085 let lpArgCount: *mut c_int = &mut nArgs;
1086 let lpCmdLine = unsafe { GetCommandLineW() };
1087 let szArgList = unsafe { CommandLineToArgvW(lpCmdLine, lpArgCount) };
1089 let args = Vec::from_fn(nArgs as uint, |i| unsafe {
1090 // Determine the length of this argument.
1091 let ptr = *szArgList.offset(i as int);
1093 while *ptr.offset(len as int) != 0 { len += 1; }
1095 // Push it onto the list.
1096 let opt_s = slice::raw::buf_as_slice(ptr, len, |buf| {
1097 str::from_utf16(str::truncate_utf16_at_nul(buf))
1099 opt_s.expect("CommandLineToArgvW returned invalid UTF-16")
1103 LocalFree(szArgList as *c_void);
1110 fn real_args_as_bytes() -> Vec<Vec<u8>> {
1111 real_args().move_iter().map(|s| s.into_bytes()).collect()
1114 type LPCWSTR = *u16;
1117 #[link_name="kernel32"]
1119 fn GetCommandLineW() -> LPCWSTR;
1120 fn LocalFree(ptr: *c_void);
1124 #[link_name="shell32"]
1126 fn CommandLineToArgvW(lpCmdLine: LPCWSTR, pNumArgs: *mut c_int) -> **u16;
1129 /// Returns the arguments which this program was started with (normally passed
1130 /// via the command line).
1132 /// The arguments are interpreted as utf-8, with invalid bytes replaced with \uFFFD.
1133 /// See `str::from_utf8_lossy` for details.
1134 pub fn args() -> Vec<String> {
1138 /// Returns the arguments which this program was started with (normally passed
1139 /// via the command line) as byte vectors.
1140 pub fn args_as_bytes() -> Vec<Vec<u8>> {
1141 real_args_as_bytes()
1144 #[cfg(target_os = "macos")]
1146 // These functions are in crt_externs.h.
1147 pub fn _NSGetArgc() -> *c_int;
1148 pub fn _NSGetArgv() -> ***c_char;
1151 // Round up `from` to be divisible by `to`
1152 fn round_up(from: uint, to: uint) -> uint {
1153 let r = if from % to == 0 {
1156 from + to - (from % to)
1165 /// Returns the page size of the current architecture in bytes.
1167 pub fn page_size() -> uint {
1169 libc::sysconf(libc::_SC_PAGESIZE) as uint
1173 /// Returns the page size of the current architecture in bytes.
1175 pub fn page_size() -> uint {
1178 let mut info = mem::zeroed();
1179 libc::GetSystemInfo(&mut info);
1181 return info.dwPageSize as uint;
1185 /// A memory mapped file or chunk of memory. This is a very system-specific
1186 /// interface to the OS's memory mapping facilities (`mmap` on POSIX,
1187 /// `VirtualAlloc`/`CreateFileMapping` on win32). It makes no attempt at
1188 /// abstracting platform differences, besides in error values returned. Consider
1189 /// yourself warned.
1191 /// The memory map is released (unmapped) when the destructor is run, so don't
1192 /// let it leave scope by accident if you want it to stick around.
1193 pub struct MemoryMap {
1194 /// Pointer to the memory created or modified by this map.
1196 /// Number of bytes this map applies to
1199 pub kind: MemoryMapKind,
1202 /// Type of memory map
1203 pub enum MemoryMapKind {
1204 /// Virtual memory map. Usually used to change the permissions of a given
1205 /// chunk of memory. Corresponds to `VirtualAlloc` on Windows.
1207 /// Virtual memory map. Usually used to change the permissions of a given
1208 /// chunk of memory, or for allocation. Corresponds to `VirtualAlloc` on
1213 /// Options the memory map is created with
1214 pub enum MapOption {
1215 /// The memory should be readable
1217 /// The memory should be writable
1219 /// The memory should be executable
1221 /// Create a map for a specific address range. Corresponds to `MAP_FIXED` on
1224 /// Create a memory mapping for a file with a given fd.
1226 /// When using `MapFd`, the start of the map is `uint` bytes from the start
1229 /// On POSIX, this can be used to specify the default flags passed to
1230 /// `mmap`. By default it uses `MAP_PRIVATE` and, if not using `MapFd`,
1231 /// `MAP_ANON`. This will override both of those. This is platform-specific
1232 /// (the exact values used) and ignored on Windows.
1233 MapNonStandardFlags(c_int),
1236 /// Possible errors when creating a map.
1238 /// ## The following are POSIX-specific
1240 /// fd was not open for reading or, if using `MapWritable`, was not open for
1243 /// fd was not valid
1245 /// Either the address given by `MapAddr` or offset given by `MapOffset` was
1246 /// not a multiple of `MemoryMap::granularity` (unaligned to page size).
1248 /// With `MapFd`, the fd does not support mapping.
1250 /// If using `MapAddr`, the address + `min_len` was outside of the process's
1251 /// address space. If using `MapFd`, the target of the fd didn't have enough
1252 /// resources to fulfill the request.
1254 /// A zero-length map was requested. This is invalid according to
1255 /// [POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/functions/mmap.html).
1256 /// Not all platforms obey this, but this wrapper does.
1258 /// Unrecognized error. The inner value is the unrecognized errno.
1260 /// ## The following are win32-specific
1262 /// Unsupported combination of protection flags
1263 /// (`MapReadable`/`MapWritable`/`MapExecutable`).
1265 /// When using `MapFd`, `MapOffset` was given (Windows does not support this
1268 /// When using `MapFd`, there was already a mapping to the file.
1270 /// Unrecognized error from `VirtualAlloc`. The inner value is the return
1271 /// value of GetLastError.
1272 ErrVirtualAlloc(uint),
1273 /// Unrecognized error from `CreateFileMapping`. The inner value is the
1274 /// return value of `GetLastError`.
1275 ErrCreateFileMappingW(uint),
1276 /// Unrecognized error from `MapViewOfFile`. The inner value is the return
1277 /// value of `GetLastError`.
1278 ErrMapViewOfFile(uint)
1281 impl fmt::Show for MapError {
1282 fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result {
1283 let str = match *self {
1284 ErrFdNotAvail => "fd not available for reading or writing",
1285 ErrInvalidFd => "Invalid fd",
1287 "Unaligned address, invalid flags, negative length or \
1290 ErrNoMapSupport=> "File doesn't support mapping",
1291 ErrNoMem => "Invalid address, or not enough available memory",
1292 ErrUnsupProt => "Protection mode unsupported",
1293 ErrUnsupOffset => "Offset in virtual memory mode is unsupported",
1294 ErrAlreadyExists => "File mapping for specified file already exists",
1295 ErrZeroLength => "Zero-length mapping not allowed",
1296 ErrUnknown(code) => {
1297 return write!(out, "Unknown error = {}", code)
1299 ErrVirtualAlloc(code) => {
1300 return write!(out, "VirtualAlloc failure = {}", code)
1302 ErrCreateFileMappingW(code) => {
1303 return write!(out, "CreateFileMappingW failure = {}", code)
1305 ErrMapViewOfFile(code) => {
1306 return write!(out, "MapViewOfFile failure = {}", code)
1309 write!(out, "{}", str)
1315 /// Create a new mapping with the given `options`, at least `min_len` bytes
1316 /// long. `min_len` must be greater than zero; see the note on
1317 /// `ErrZeroLength`.
1318 pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
1323 return Err(ErrZeroLength)
1325 let mut addr: *u8 = ptr::null();
1327 let mut flags = libc::MAP_PRIVATE;
1330 let mut custom_flags = false;
1331 let len = round_up(min_len, page_size());
1333 for &o in options.iter() {
1335 MapReadable => { prot |= libc::PROT_READ; },
1336 MapWritable => { prot |= libc::PROT_WRITE; },
1337 MapExecutable => { prot |= libc::PROT_EXEC; },
1339 flags |= libc::MAP_FIXED;
1343 flags |= libc::MAP_FILE;
1346 MapOffset(offset_) => { offset = offset_ as off_t; },
1347 MapNonStandardFlags(f) => { custom_flags = true; flags = f },
1350 if fd == -1 && !custom_flags { flags |= libc::MAP_ANON; }
1353 libc::mmap(addr as *c_void, len as libc::size_t, prot, flags, fd,
1356 if r.equiv(&libc::MAP_FAILED) {
1357 Err(match errno() as c_int {
1358 libc::EACCES => ErrFdNotAvail,
1359 libc::EBADF => ErrInvalidFd,
1360 libc::EINVAL => ErrUnaligned,
1361 libc::ENODEV => ErrNoMapSupport,
1362 libc::ENOMEM => ErrNoMem,
1363 code => ErrUnknown(code as int)
1372 MapFile(ptr::null())
1378 /// Granularity that the offset or address must be for `MapOffset` and
1379 /// `MapAddr` respectively.
1380 pub fn granularity() -> uint {
1386 impl Drop for MemoryMap {
1387 /// Unmap the mapping. Fails the task if `munmap` fails.
1388 fn drop(&mut self) {
1389 if self.len == 0 { /* workaround for dummy_stack */ return; }
1392 // FIXME: what to do if this fails?
1393 let _ = libc::munmap(self.data as *c_void, self.len as libc::size_t);
1400 /// Create a new mapping with the given `options`, at least `min_len` bytes long.
1401 pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
1402 use libc::types::os::arch::extra::{LPVOID, DWORD, SIZE_T, HANDLE};
1404 let mut lpAddress: LPVOID = ptr::mut_null();
1405 let mut readable = false;
1406 let mut writable = false;
1407 let mut executable = false;
1408 let mut fd: c_int = -1;
1409 let mut offset: uint = 0;
1410 let len = round_up(min_len, page_size());
1412 for &o in options.iter() {
1414 MapReadable => { readable = true; },
1415 MapWritable => { writable = true; },
1416 MapExecutable => { executable = true; }
1417 MapAddr(addr_) => { lpAddress = addr_ as LPVOID; },
1418 MapFd(fd_) => { fd = fd_; },
1419 MapOffset(offset_) => { offset = offset_; },
1420 MapNonStandardFlags(..) => {}
1424 let flProtect = match (executable, readable, writable) {
1425 (false, false, false) if fd == -1 => libc::PAGE_NOACCESS,
1426 (false, true, false) => libc::PAGE_READONLY,
1427 (false, true, true) => libc::PAGE_READWRITE,
1428 (true, false, false) if fd == -1 => libc::PAGE_EXECUTE,
1429 (true, true, false) => libc::PAGE_EXECUTE_READ,
1430 (true, true, true) => libc::PAGE_EXECUTE_READWRITE,
1431 _ => return Err(ErrUnsupProt)
1436 return Err(ErrUnsupOffset);
1439 libc::VirtualAlloc(lpAddress,
1441 libc::MEM_COMMIT | libc::MEM_RESERVE,
1445 0 => Err(ErrVirtualAlloc(errno())),
1453 let dwDesiredAccess = match (executable, readable, writable) {
1454 (false, true, false) => libc::FILE_MAP_READ,
1455 (false, true, true) => libc::FILE_MAP_WRITE,
1456 (true, true, false) => libc::FILE_MAP_READ | libc::FILE_MAP_EXECUTE,
1457 (true, true, true) => libc::FILE_MAP_WRITE | libc::FILE_MAP_EXECUTE,
1458 _ => return Err(ErrUnsupProt) // Actually, because of the check above,
1459 // we should never get here.
1462 let hFile = libc::get_osfhandle(fd) as HANDLE;
1463 let mapping = libc::CreateFileMappingW(hFile,
1469 if mapping == ptr::mut_null() {
1470 return Err(ErrCreateFileMappingW(errno()));
1472 if errno() as c_int == libc::ERROR_ALREADY_EXISTS {
1473 return Err(ErrAlreadyExists);
1475 let r = libc::MapViewOfFile(mapping,
1477 ((len as u64) >> 32) as DWORD,
1478 (offset & 0xffff_ffff) as DWORD,
1481 0 => Err(ErrMapViewOfFile(errno())),
1485 kind: MapFile(mapping as *u8)
1492 /// Granularity of MapAddr() and MapOffset() parameter values.
1493 /// This may be greater than the value returned by page_size().
1494 pub fn granularity() -> uint {
1497 let mut info = mem::zeroed();
1498 libc::GetSystemInfo(&mut info);
1500 return info.dwAllocationGranularity as uint;
1506 impl Drop for MemoryMap {
1507 /// Unmap the mapping. Fails the task if any of `VirtualFree`,
1508 /// `UnmapViewOfFile`, or `CloseHandle` fail.
1509 fn drop(&mut self) {
1510 use libc::types::os::arch::extra::{LPCVOID, HANDLE};
1511 use libc::consts::os::extra::FALSE;
1512 if self.len == 0 { return }
1517 if libc::VirtualFree(self.data as *mut c_void, 0,
1518 libc::MEM_RELEASE) == 0 {
1519 println!("VirtualFree failed: {}", errno());
1522 MapFile(mapping) => {
1523 if libc::UnmapViewOfFile(self.data as LPCVOID) == FALSE {
1524 println!("UnmapViewOfFile failed: {}", errno());
1526 if libc::CloseHandle(mapping as HANDLE) == FALSE {
1527 println!("CloseHandle failed: {}", errno());
1535 #[cfg(target_os = "linux")]
1537 pub use os::arch_consts::ARCH;
1539 pub static FAMILY: &'static str = "unix";
1541 /// A string describing the specific operating system in use: in this
1543 pub static SYSNAME: &'static str = "linux";
1545 /// Specifies the filename prefix used for shared libraries on this
1546 /// platform: in this case, `lib`.
1547 pub static DLL_PREFIX: &'static str = "lib";
1549 /// Specifies the filename suffix used for shared libraries on this
1550 /// platform: in this case, `.so`.
1551 pub static DLL_SUFFIX: &'static str = ".so";
1553 /// Specifies the file extension used for shared libraries on this
1554 /// platform that goes after the dot: in this case, `so`.
1555 pub static DLL_EXTENSION: &'static str = "so";
1557 /// Specifies the filename suffix used for executable binaries on this
1558 /// platform: in this case, the empty string.
1559 pub static EXE_SUFFIX: &'static str = "";
1561 /// Specifies the file extension, if any, used for executable binaries
1562 /// on this platform: in this case, the empty string.
1563 pub static EXE_EXTENSION: &'static str = "";
1566 #[cfg(target_os = "macos")]
1568 pub use os::arch_consts::ARCH;
1570 pub static FAMILY: &'static str = "unix";
1572 /// A string describing the specific operating system in use: in this
1574 pub static SYSNAME: &'static str = "macos";
1576 /// Specifies the filename prefix used for shared libraries on this
1577 /// platform: in this case, `lib`.
1578 pub static DLL_PREFIX: &'static str = "lib";
1580 /// Specifies the filename suffix used for shared libraries on this
1581 /// platform: in this case, `.dylib`.
1582 pub static DLL_SUFFIX: &'static str = ".dylib";
1584 /// Specifies the file extension used for shared libraries on this
1585 /// platform that goes after the dot: in this case, `dylib`.
1586 pub static DLL_EXTENSION: &'static str = "dylib";
1588 /// Specifies the filename suffix used for executable binaries on this
1589 /// platform: in this case, the empty string.
1590 pub static EXE_SUFFIX: &'static str = "";
1592 /// Specifies the file extension, if any, used for executable binaries
1593 /// on this platform: in this case, the empty string.
1594 pub static EXE_EXTENSION: &'static str = "";
1597 #[cfg(target_os = "ios")]
1599 pub use os::arch_consts::ARCH;
1601 pub static FAMILY: &'static str = "unix";
1603 /// A string describing the specific operating system in use: in this
1605 pub static SYSNAME: &'static str = "ios";
1607 /// Specifies the filename suffix used for executable binaries on this
1608 /// platform: in this case, the empty string.
1609 pub static EXE_SUFFIX: &'static str = "";
1611 /// Specifies the file extension, if any, used for executable binaries
1612 /// on this platform: in this case, the empty string.
1613 pub static EXE_EXTENSION: &'static str = "";
1616 #[cfg(target_os = "freebsd")]
1618 pub use os::arch_consts::ARCH;
1620 pub static FAMILY: &'static str = "unix";
1622 /// A string describing the specific operating system in use: in this
1623 /// case, `freebsd`.
1624 pub static SYSNAME: &'static str = "freebsd";
1626 /// Specifies the filename prefix used for shared libraries on this
1627 /// platform: in this case, `lib`.
1628 pub static DLL_PREFIX: &'static str = "lib";
1630 /// Specifies the filename suffix used for shared libraries on this
1631 /// platform: in this case, `.so`.
1632 pub static DLL_SUFFIX: &'static str = ".so";
1634 /// Specifies the file extension used for shared libraries on this
1635 /// platform that goes after the dot: in this case, `so`.
1636 pub static DLL_EXTENSION: &'static str = "so";
1638 /// Specifies the filename suffix used for executable binaries on this
1639 /// platform: in this case, the empty string.
1640 pub static EXE_SUFFIX: &'static str = "";
1642 /// Specifies the file extension, if any, used for executable binaries
1643 /// on this platform: in this case, the empty string.
1644 pub static EXE_EXTENSION: &'static str = "";
1647 #[cfg(target_os = "android")]
1649 pub use os::arch_consts::ARCH;
1651 pub static FAMILY: &'static str = "unix";
1653 /// A string describing the specific operating system in use: in this
1654 /// case, `android`.
1655 pub static SYSNAME: &'static str = "android";
1657 /// Specifies the filename prefix used for shared libraries on this
1658 /// platform: in this case, `lib`.
1659 pub static DLL_PREFIX: &'static str = "lib";
1661 /// Specifies the filename suffix used for shared libraries on this
1662 /// platform: in this case, `.so`.
1663 pub static DLL_SUFFIX: &'static str = ".so";
1665 /// Specifies the file extension used for shared libraries on this
1666 /// platform that goes after the dot: in this case, `so`.
1667 pub static DLL_EXTENSION: &'static str = "so";
1669 /// Specifies the filename suffix used for executable binaries on this
1670 /// platform: in this case, the empty string.
1671 pub static EXE_SUFFIX: &'static str = "";
1673 /// Specifies the file extension, if any, used for executable binaries
1674 /// on this platform: in this case, the empty string.
1675 pub static EXE_EXTENSION: &'static str = "";
1678 #[cfg(target_os = "win32")]
1680 pub use os::arch_consts::ARCH;
1682 pub static FAMILY: &'static str = "windows";
1684 /// A string describing the specific operating system in use: in this
1686 pub static SYSNAME: &'static str = "win32";
1688 /// Specifies the filename prefix used for shared libraries on this
1689 /// platform: in this case, the empty string.
1690 pub static DLL_PREFIX: &'static str = "";
1692 /// Specifies the filename suffix used for shared libraries on this
1693 /// platform: in this case, `.dll`.
1694 pub static DLL_SUFFIX: &'static str = ".dll";
1696 /// Specifies the file extension used for shared libraries on this
1697 /// platform that goes after the dot: in this case, `dll`.
1698 pub static DLL_EXTENSION: &'static str = "dll";
1700 /// Specifies the filename suffix used for executable binaries on this
1701 /// platform: in this case, `.exe`.
1702 pub static EXE_SUFFIX: &'static str = ".exe";
1704 /// Specifies the file extension, if any, used for executable binaries
1705 /// on this platform: in this case, `exe`.
1706 pub static EXE_EXTENSION: &'static str = "exe";
1709 #[cfg(target_arch = "x86")]
1711 pub static ARCH: &'static str = "x86";
1714 #[cfg(target_arch = "x86_64")]
1716 pub static ARCH: &'static str = "x86_64";
1719 #[cfg(target_arch = "arm")]
1721 pub static ARCH: &'static str = "arm";
1724 #[cfg(target_arch = "mips")]
1726 pub static ARCH: &'static str = "mips";
1735 use os::{env, getcwd, getenv, make_absolute};
1736 use os::{split_paths, setenv, unsetenv};
1742 pub fn last_os_error() {
1743 debug!("{}", os::last_os_error());
1746 fn make_rand_name() -> String {
1747 let mut rng = rand::task_rng();
1748 let n = format!("TEST{}", rng.gen_ascii_chars().take(10u)
1749 .collect::<String>());
1750 assert!(getenv(n.as_slice()).is_none());
1756 let n = make_rand_name();
1757 setenv(n.as_slice(), "VALUE");
1758 assert_eq!(getenv(n.as_slice()), option::Some("VALUE".to_string()));
1762 fn test_unsetenv() {
1763 let n = make_rand_name();
1764 setenv(n.as_slice(), "VALUE");
1765 unsetenv(n.as_slice());
1766 assert_eq!(getenv(n.as_slice()), option::None);
1771 fn test_setenv_overwrite() {
1772 let n = make_rand_name();
1773 setenv(n.as_slice(), "1");
1774 setenv(n.as_slice(), "2");
1775 assert_eq!(getenv(n.as_slice()), option::Some("2".to_string()));
1776 setenv(n.as_slice(), "");
1777 assert_eq!(getenv(n.as_slice()), option::Some("".to_string()));
1780 // Windows GetEnvironmentVariable requires some extra work to make sure
1781 // the buffer the variable is copied into is the right size
1784 fn test_getenv_big() {
1785 let mut s = "".to_string();
1788 s.push_str("aaaaaaaaaa");
1791 let n = make_rand_name();
1792 setenv(n.as_slice(), s.as_slice());
1793 debug!("{}", s.clone());
1794 assert_eq!(getenv(n.as_slice()), option::Some(s));
1798 fn test_self_exe_name() {
1799 let path = os::self_exe_name();
1800 assert!(path.is_some());
1801 let path = path.unwrap();
1802 debug!("{:?}", path.clone());
1804 // Hard to test this function
1805 assert!(path.is_absolute());
1809 fn test_self_exe_path() {
1810 let path = os::self_exe_path();
1811 assert!(path.is_some());
1812 let path = path.unwrap();
1813 debug!("{:?}", path.clone());
1815 // Hard to test this function
1816 assert!(path.is_absolute());
1821 fn test_env_getenv() {
1823 assert!(e.len() > 0u);
1825 let (n, v) = (*p).clone();
1826 debug!("{:?}", n.clone());
1827 let v2 = getenv(n.as_slice());
1828 // MingW seems to set some funky environment variables like
1829 // "=C:=C:\MinGW\msys\1.0\bin" and "!::=::\" that are returned
1830 // from env() but not visible from getenv().
1831 assert!(v2.is_none() || v2 == option::Some(v));
1836 fn test_env_set_get_huge() {
1837 let n = make_rand_name();
1838 let s = "x".repeat(10000).to_string();
1839 setenv(n.as_slice(), s.as_slice());
1840 assert_eq!(getenv(n.as_slice()), Some(s));
1841 unsetenv(n.as_slice());
1842 assert_eq!(getenv(n.as_slice()), None);
1846 fn test_env_setenv() {
1847 let n = make_rand_name();
1850 setenv(n.as_slice(), "VALUE");
1851 assert!(!e.contains(&(n.clone(), "VALUE".to_string())));
1854 assert!(e.contains(&(n, "VALUE".to_string())));
1859 assert!((!Path::new("test-path").is_absolute()));
1862 debug!("Current working directory: {}", cwd.display());
1864 debug!("{:?}", make_absolute(&Path::new("test-path")));
1865 debug!("{:?}", make_absolute(&Path::new("/usr/bin")));
1871 let oldhome = getenv("HOME");
1873 setenv("HOME", "/home/MountainView");
1874 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1877 assert!(os::homedir().is_none());
1879 for s in oldhome.iter() {
1880 setenv("HOME", s.as_slice());
1888 let oldhome = getenv("HOME");
1889 let olduserprofile = getenv("USERPROFILE");
1892 setenv("USERPROFILE", "");
1894 assert!(os::homedir().is_none());
1896 setenv("HOME", "/home/MountainView");
1897 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1901 setenv("USERPROFILE", "/home/MountainView");
1902 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1904 setenv("HOME", "/home/MountainView");
1905 setenv("USERPROFILE", "/home/PaloAlto");
1906 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1908 for s in oldhome.iter() {
1909 setenv("HOME", s.as_slice());
1911 for s in olduserprofile.iter() {
1912 setenv("USERPROFILE", s.as_slice());
1917 fn memory_map_rw() {
1918 use result::{Ok, Err};
1920 let chunk = match os::MemoryMap::new(16, [
1925 Err(msg) => fail!("{}", msg)
1927 assert!(chunk.len >= 16);
1931 assert!(*chunk.data == 0xBE);
1936 fn memory_map_file() {
1937 use result::{Ok, Err};
1943 fn lseek_(fd: c_int, size: uint) {
1945 assert!(lseek(fd, size as off_t, SEEK_SET) == size as off_t);
1949 fn lseek_(fd: c_int, size: uint) {
1951 assert!(lseek(fd, size as c_long, SEEK_SET) == size as c_long);
1955 let mut path = tmpdir();
1956 path.push("mmap_file.tmp");
1957 let size = MemoryMap::granularity() * 2;
1960 let fd = path.with_c_str(|path| {
1961 open(path, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR)
1964 "x".with_c_str(|x| assert!(write(fd, x as *c_void, 1) == 1));
1967 let chunk = match MemoryMap::new(size / 2, [
1974 Err(msg) => fail!("{}", msg)
1976 assert!(chunk.len > 0);
1980 assert!(*chunk.data == 0xbe);
1985 fs::unlink(&path).unwrap();
1990 fn split_paths_windows() {
1991 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
1992 split_paths(unparsed) ==
1993 parsed.iter().map(|s| Path::new(*s)).collect()
1996 assert!(check_parse("", []));
1997 assert!(check_parse(r#""""#, []));
1998 assert!(check_parse(";;", []));
1999 assert!(check_parse(r"c:\", [r"c:\"]));
2000 assert!(check_parse(r"c:\;", [r"c:\"]));
2001 assert!(check_parse(r"c:\;c:\Program Files\",
2002 [r"c:\", r"c:\Program Files\"]));
2003 assert!(check_parse(r#"c:\;c:\"foo"\"#, [r"c:\", r"c:\foo\"]));
2004 assert!(check_parse(r#"c:\;c:\"foo;bar"\;c:\baz"#,
2005 [r"c:\", r"c:\foo;bar\", r"c:\baz"]));
2010 fn split_paths_unix() {
2011 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
2012 split_paths(unparsed) ==
2013 parsed.iter().map(|s| Path::new(*s)).collect()
2016 assert!(check_parse("", []));
2017 assert!(check_parse("::", []));
2018 assert!(check_parse("/", ["/"]));
2019 assert!(check_parse("/:", ["/"]));
2020 assert!(check_parse("/:/usr/local", ["/", "/usr/local"]));
2023 // More recursive_mkdir tests are in extra::tempfile