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;
35 use io::{IoResult, IoError};
37 use libc::{c_void, c_int};
40 use option::{Some, None, Option};
42 use path::{Path, GenericPath, BytesContainer};
45 use result::{Err, Ok, Result};
46 use slice::{Vector, ImmutableVector, MutableVector};
47 use str::{Str, StrSlice, StrAllocating};
50 use sync::atomics::{AtomicInt, INIT_ATOMIC_INT, SeqCst};
60 /// Get the number of cores available
61 pub fn num_cpus() -> uint {
63 return rust_get_num_cpus();
67 fn rust_get_num_cpus() -> libc::uintptr_t;
71 pub static TMPBUF_SZ : uint = 1000u;
72 static BUF_BYTES : uint = 2048u;
74 /// Returns the current working directory as a Path.
78 /// Fails if the current working directory value is invalid:
81 /// * Current directory does not exist.
82 /// * There are insufficient permissions to access the current directory.
89 /// // We assume that we are in a valid directory like "/home".
90 /// let current_working_directory = os::getcwd();
91 /// println!("The current directory is {}", current_working_directory.display());
95 pub fn getcwd() -> Path {
98 let mut buf = [0 as c_char, ..BUF_BYTES];
100 if libc::getcwd(buf.as_mut_ptr(), buf.len() as libc::size_t).is_null() {
103 Path::new(CString::new(buf.as_ptr(), false))
107 /// Returns the current working directory as a Path.
111 /// Fails if the current working directory value is invalid.
114 /// * Current directory does not exist.
115 /// * There are insufficient permissions to access the current directory.
122 /// // We assume that we are in a valid directory like "C:\\Windows".
123 /// let current_working_directory = os::getcwd();
124 /// println!("The current directory is {}", current_working_directory.display());
128 pub fn getcwd() -> Path {
130 use libc::GetCurrentDirectoryW;
132 let mut buf = [0 as u16, ..BUF_BYTES];
134 if libc::GetCurrentDirectoryW(buf.len() as DWORD, buf.as_mut_ptr()) == 0 as DWORD {
138 Path::new(str::from_utf16(str::truncate_utf16_at_nul(buf))
139 .expect("GetCurrentDirectoryW returned invalid UTF-16"))
144 use libc::types::os::arch::extra::DWORD;
146 use option::{None, Option};
149 use slice::{MutableVector, ImmutableVector};
155 pub fn fill_utf16_buf_and_decode(f: |*mut u16, DWORD| -> DWORD)
159 let mut n = TMPBUF_SZ as DWORD;
161 let mut done = false;
163 let mut buf = Vec::from_elem(n as uint, 0u16);
164 let k = f(buf.as_mut_ptr(), n);
165 if k == (0 as DWORD) {
168 libc::GetLastError() ==
169 libc::ERROR_INSUFFICIENT_BUFFER as DWORD {
177 let sub = buf.slice(0, k as uint);
178 // We want to explicitly catch the case when the
179 // closure returned invalid UTF-16, rather than
180 // set `res` to None and continue.
181 let s = str::from_utf16(sub)
182 .expect("fill_utf16_buf_and_decode: closure created invalid UTF-16");
183 res = option::Some(s)
192 Accessing environment variables is not generally threadsafe.
193 Serialize access through a global lock.
195 fn with_env_lock<T>(f: || -> T) -> T {
196 use rt::mutex::{StaticNativeMutex, NATIVE_MUTEX_INIT};
198 static mut lock: StaticNativeMutex = NATIVE_MUTEX_INIT;
201 let _guard = lock.lock();
206 /// Returns a vector of (variable, value) pairs, for all the environment
207 /// variables of the current process.
209 /// Invalid UTF-8 bytes are replaced with \uFFFD. See `str::from_utf8_lossy()`
217 /// // We will iterate through the references to the element returned by os::env();
218 /// for &(ref key, ref value) in os::env().iter() {
219 /// println!("'{}': '{}'", key, value );
222 pub fn env() -> Vec<(String,String)> {
223 env_as_bytes().move_iter().map(|(k,v)| {
224 let k = str::from_utf8_lossy(k.as_slice()).to_string();
225 let v = str::from_utf8_lossy(v.as_slice()).to_string();
230 /// Returns a vector of (variable, value) byte-vector pairs for all the
231 /// environment variables of the current process.
232 pub fn env_as_bytes() -> Vec<(Vec<u8>,Vec<u8>)> {
235 unsafe fn get_env_pairs() -> Vec<Vec<u8>> {
238 use libc::funcs::extra::kernel32::{
239 GetEnvironmentStringsW,
240 FreeEnvironmentStringsW
242 let ch = GetEnvironmentStringsW();
244 fail!("os::env() failure getting env string from OS: {}",
245 os::last_os_error());
247 // Here, we lossily decode the string as UTF16.
249 // The docs suggest that the result should be in Unicode, but
250 // Windows doesn't guarantee it's actually UTF16 -- it doesn't
251 // validate the environment string passed to CreateProcess nor
252 // SetEnvironmentVariable. Yet, it's unlikely that returning a
253 // raw u16 buffer would be of practical use since the result would
254 // be inherently platform-dependent and introduce additional
255 // complexity to this code.
257 // Using the non-Unicode version of GetEnvironmentStrings is even
258 // worse since the result is in an OEM code page. Characters that
259 // can't be encoded in the code page would be turned into question
261 let mut result = Vec::new();
263 while *ch.offset(i) != 0 {
264 let p = &*ch.offset(i);
265 let len = ptr::position(p, |c| *c == 0);
266 raw::buf_as_slice(p, len, |s| {
267 result.push(str::from_utf16_lossy(s).into_bytes());
271 FreeEnvironmentStringsW(ch);
275 unsafe fn get_env_pairs() -> Vec<Vec<u8>> {
279 fn rust_env_pairs() -> **c_char;
281 let environ = rust_env_pairs();
282 if environ as uint == 0 {
283 fail!("os::env() failure getting env string from OS: {}",
284 os::last_os_error());
286 let mut result = Vec::new();
287 ptr::array_each(environ, |e| {
289 Vec::from_slice(CString::new(e, false).as_bytes_no_nul());
290 result.push(env_pair);
295 fn env_convert(input: Vec<Vec<u8>>) -> Vec<(Vec<u8>, Vec<u8>)> {
296 let mut pairs = Vec::new();
297 for p in input.iter() {
298 let mut it = p.as_slice().splitn(1, |b| *b == '=' as u8);
299 let key = Vec::from_slice(it.next().unwrap());
300 let val = Vec::from_slice(it.next().unwrap_or(&[]));
301 pairs.push((key, val));
306 let unparsed_environ = get_env_pairs();
307 env_convert(unparsed_environ)
313 /// Fetches the environment variable `n` from the current process, returning
314 /// None if the variable isn't set.
316 /// Any invalid UTF-8 bytes in the value are replaced by \uFFFD. See
317 /// `str::from_utf8_lossy()` for details.
321 /// Fails if `n` has any interior NULs.
328 /// let key = "HOME";
329 /// match os::getenv(key) {
330 /// Some(val) => println!("{}: {}", key, val),
331 /// None => println!("{} is not defined in the environment.", key)
334 pub fn getenv(n: &str) -> Option<String> {
335 getenv_as_bytes(n).map(|v| str::from_utf8_lossy(v.as_slice()).to_string())
339 /// Fetches the environment variable `n` byte vector from the current process,
340 /// returning None if the variable isn't set.
344 /// Fails if `n` has any interior NULs.
345 pub fn getenv_as_bytes(n: &str) -> Option<Vec<u8>> {
350 let s = n.with_c_str(|buf| libc::getenv(buf));
354 Some(Vec::from_slice(CString::new(s,
355 false).as_bytes_no_nul()))
362 /// Fetches the environment variable `n` from the current process, returning
363 /// None if the variable isn't set.
364 pub fn getenv(n: &str) -> Option<String> {
367 use os::win32::{fill_utf16_buf_and_decode};
368 let n = n.to_utf16().append_one(0);
369 fill_utf16_buf_and_decode(|buf, sz| {
370 libc::GetEnvironmentVariableW(n.as_ptr(), buf, sz)
377 /// Fetches the environment variable `n` byte vector from the current process,
378 /// returning None if the variable isn't set.
379 pub fn getenv_as_bytes(n: &str) -> Option<Vec<u8>> {
380 getenv(n).map(|s| s.into_bytes())
383 /// Sets the environment variable `n` to the value `v` for the currently running
392 /// os::setenv(key, "VALUE");
393 /// match os::getenv(key) {
394 /// Some(ref val) => println!("{}: {}", key, val),
395 /// None => println!("{} is not defined in the environment.", key)
398 pub fn setenv(n: &str, v: &str) {
400 fn _setenv(n: &str, v: &str) {
403 n.with_c_str(|nbuf| {
404 v.with_c_str(|vbuf| {
405 libc::funcs::posix01::unistd::setenv(nbuf, vbuf, 1);
413 fn _setenv(n: &str, v: &str) {
414 let n = n.to_utf16().append_one(0);
415 let v = v.to_utf16().append_one(0);
418 libc::SetEnvironmentVariableW(n.as_ptr(), v.as_ptr());
425 /// Remove a variable from the environment entirely.
426 pub fn unsetenv(n: &str) {
428 fn _unsetenv(n: &str) {
431 n.with_c_str(|nbuf| {
432 libc::funcs::posix01::unistd::unsetenv(nbuf);
439 fn _unsetenv(n: &str) {
440 let n = n.to_utf16().append_one(0);
443 libc::SetEnvironmentVariableW(n.as_ptr(), ptr::null());
451 /// Parse a string or vector according to the platform's conventions
452 /// for the `PATH` environment variable and return a Vec<Path>.
453 /// Drops empty paths.
459 /// let key = "PATH";
460 /// match os::getenv(key) {
462 /// for path in os::split_paths(paths).iter() {
463 /// println!("'{}'", path.display());
466 /// None => println!("{} is not defined in the environnement.", key)
469 pub fn split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> {
470 unparsed.container_as_bytes()
471 .split(|b| *b == ':' as u8)
472 .filter(|s| s.len() > 0)
478 /// Parse a string or vector according to the platform's conventions
479 /// for the `PATH` environment variable. Drops empty paths.
480 pub fn split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> {
481 // On Windows, the PATH environment variable is semicolon separated. Double
482 // quotes are used as a way of introducing literal semicolons (since
483 // c:\some;dir is a valid Windows path). Double quotes are not themselves
484 // permitted in path names, so there is no way to escape a double quote.
485 // Quoted regions can appear in arbitrary locations, so
487 // c:\foo;c:\som"e;di"r;c:\bar
489 // Should parse as [c:\foo, c:\some;dir, c:\bar].
491 // (The above is based on testing; there is no clear reference available
494 let mut parsed = Vec::new();
495 let mut in_progress = Vec::new();
496 let mut in_quote = false;
498 for b in unparsed.container_as_bytes().iter() {
500 ';' if !in_quote => {
501 // ignore zero-length path strings
502 if in_progress.len() > 0 {
503 parsed.push(Path::new(in_progress.as_slice()));
505 in_progress.truncate(0)
508 in_quote = !in_quote;
511 in_progress.push(*b);
516 if in_progress.len() > 0 {
517 parsed.push(Path::new(in_progress));
523 /// A low-level OS in-memory pipe.
525 /// A file descriptor representing the reading end of the pipe. Data written
526 /// on the `out` file descriptor can be read from this file descriptor.
528 /// A file descriptor representing the write end of the pipe. Data written
529 /// to this file descriptor can be read from the `input` file descriptor.
533 /// Creates a new low-level OS in-memory pipe.
535 /// This function can fail to succeed if there are no more resources available
536 /// to allocate a pipe.
538 /// This function is also unsafe as there is no destructor associated with the
539 /// `Pipe` structure will return. If it is not arranged for the returned file
540 /// descriptors to be closed, the file descriptors will leak. For safe handling
541 /// of this scenario, use `std::io::PipeStream` instead.
542 pub unsafe fn pipe() -> IoResult<Pipe> {
546 unsafe fn _pipe() -> IoResult<Pipe> {
547 let mut fds = [0, ..2];
548 match libc::pipe(fds.as_mut_ptr()) {
549 0 => Ok(Pipe { reader: fds[0], writer: fds[1] }),
550 _ => Err(IoError::last_error()),
555 unsafe fn _pipe() -> IoResult<Pipe> {
556 // Windows pipes work subtly differently than unix pipes, and their
557 // inheritance has to be handled in a different way that I do not
558 // fully understand. Here we explicitly make the pipe non-inheritable,
559 // which means to pass it to a subprocess they need to be duplicated
560 // first, as in std::run.
561 let mut fds = [0, ..2];
562 match libc::pipe(fds.as_mut_ptr(), 1024 as ::libc::c_uint,
563 (libc::O_BINARY | libc::O_NOINHERIT) as c_int) {
565 assert!(fds[0] != -1 && fds[0] != 0);
566 assert!(fds[1] != -1 && fds[1] != 0);
567 Ok(Pipe { reader: fds[0], writer: fds[1] })
569 _ => Err(IoError::last_error()),
574 /// Returns the proper dll filename for the given basename of a file
576 #[cfg(not(target_os="ios"))]
577 pub fn dll_filename(base: &str) -> String {
578 format!("{}{}{}", consts::DLL_PREFIX, base, consts::DLL_SUFFIX)
581 /// Optionally returns the filesystem path to the current executable which is
582 /// running but with the executable name.
589 /// match os::self_exe_name() {
590 /// Some(exe_path) => println!("Path of this executable is: {}", exe_path.display()),
591 /// None => println!("Unable to get the path of this executable!")
594 pub fn self_exe_name() -> Option<Path> {
596 #[cfg(target_os = "freebsd")]
597 fn load_self() -> Option<Vec<u8>> {
599 use libc::funcs::bsd44::*;
600 use libc::consts::os::extra::*;
601 let mib = vec![CTL_KERN as c_int,
603 KERN_PROC_PATHNAME as c_int, -1 as c_int];
604 let mut sz: libc::size_t = 0;
605 let err = sysctl(mib.as_ptr(), mib.len() as ::libc::c_uint,
606 ptr::mut_null(), &mut sz, ptr::null(),
608 if err != 0 { return None; }
609 if sz == 0 { return None; }
610 let mut v: Vec<u8> = Vec::with_capacity(sz as uint);
611 let err = sysctl(mib.as_ptr(), mib.len() as ::libc::c_uint,
612 v.as_mut_ptr() as *mut c_void, &mut sz, ptr::null(),
614 if err != 0 { return None; }
615 if sz == 0 { return None; }
616 v.set_len(sz as uint - 1); // chop off trailing NUL
621 #[cfg(target_os = "linux")]
622 #[cfg(target_os = "android")]
623 fn load_self() -> Option<Vec<u8>> {
626 match io::fs::readlink(&Path::new("/proc/self/exe")) {
627 Ok(path) => Some(path.into_vec()),
632 #[cfg(target_os = "macos")]
633 #[cfg(target_os = "ios")]
634 fn load_self() -> Option<Vec<u8>> {
636 use libc::funcs::extra::_NSGetExecutablePath;
638 _NSGetExecutablePath(ptr::mut_null(), &mut sz);
639 if sz == 0 { return None; }
640 let mut v: Vec<u8> = Vec::with_capacity(sz as uint);
641 let err = _NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz);
642 if err != 0 { return None; }
643 v.set_len(sz as uint - 1); // chop off trailing NUL
649 fn load_self() -> Option<Vec<u8>> {
653 use os::win32::fill_utf16_buf_and_decode;
654 fill_utf16_buf_and_decode(|buf, sz| {
655 libc::GetModuleFileNameW(0u as libc::DWORD, buf, sz)
656 }).map(|s| s.into_string().into_bytes())
660 load_self().and_then(Path::new_opt)
663 /// Optionally returns the filesystem path to the current executable which is
666 /// Like self_exe_name() but without the binary's name.
673 /// match os::self_exe_path() {
674 /// Some(exe_path) => println!("Executable's Path is: {}", exe_path.display()),
675 /// None => println!("Impossible to fetch the path of this executable.")
678 pub fn self_exe_path() -> Option<Path> {
679 self_exe_name().map(|mut p| { p.pop(); p })
682 /// Optionally returns the path to the current user's home directory if known.
686 /// Returns the value of the 'HOME' environment variable if it is set
687 /// and not equal to the empty string.
691 /// Returns the value of the 'HOME' environment variable if it is
692 /// set and not equal to the empty string. Otherwise, returns the value of the
693 /// 'USERPROFILE' environment variable if it is set and not equal to the empty
701 /// match os::homedir() {
702 /// Some(ref p) => println!("{}", p.display()),
703 /// None => println!("Impossible to get your home dir!")
706 pub fn homedir() -> Option<Path> {
709 fn _homedir() -> Option<Path> {
715 fn _homedir() -> Option<Path> {
716 aux_homedir("HOME").or(aux_homedir("USERPROFILE"))
720 fn aux_homedir(home_name: &str) -> Option<Path> {
721 match getenv_as_bytes(home_name) {
723 if p.is_empty() { None } else { Path::new_opt(p) }
732 * Returns the path to a temporary directory.
734 * On Unix, returns the value of the 'TMPDIR' environment variable if it is
735 * set, otherwise for non-Android it returns '/tmp'. If Android, since there
736 * is no global temporary folder (it is usually allocated per-app), we return
739 * On Windows, returns the value of, in order, the 'TMP', 'TEMP',
740 * 'USERPROFILE' environment variable if any are set and not the empty
741 * string. Otherwise, tmpdir returns the path to the Windows directory.
743 pub fn tmpdir() -> Path {
746 fn getenv_nonempty(v: &str) -> Option<Path> {
759 fn lookup() -> Path {
760 let default = if cfg!(target_os = "android") {
761 Path::new("/data/local/tmp")
766 getenv_nonempty("TMPDIR").unwrap_or(default)
770 fn lookup() -> Path {
771 getenv_nonempty("TMP").or(
772 getenv_nonempty("TEMP").or(
773 getenv_nonempty("USERPROFILE").or(
774 getenv_nonempty("WINDIR")))).unwrap_or(Path::new("C:\\Windows"))
779 * Convert a relative path to an absolute path
781 * If the given path is relative, return it prepended with the current working
782 * directory. If the given path is already an absolute path, return it
785 // NB: this is here rather than in path because it is a form of environment
786 // querying; what it does depends on the process working directory, not just
788 pub fn make_absolute(p: &Path) -> Path {
792 let mut ret = getcwd();
798 /// Changes the current working directory to the specified path, returning
799 /// whether the change was completed successfully or not.
800 pub fn change_dir(p: &Path) -> bool {
804 fn chdir(p: &Path) -> bool {
805 let p = match p.as_str() {
806 Some(s) => s.to_utf16().append_one(0),
807 None => return false,
810 libc::SetCurrentDirectoryW(p.as_ptr()) != (0 as libc::BOOL)
815 fn chdir(p: &Path) -> bool {
818 libc::chdir(buf) == (0 as c_int)
825 /// Returns the platform-specific value of errno
826 pub fn errno() -> int {
827 #[cfg(target_os = "macos")]
828 #[cfg(target_os = "ios")]
829 #[cfg(target_os = "freebsd")]
830 fn errno_location() -> *c_int {
832 fn __error() -> *c_int;
839 #[cfg(target_os = "linux")]
840 #[cfg(target_os = "android")]
841 fn errno_location() -> *c_int {
843 fn __errno_location() -> *c_int;
851 (*errno_location()) as int
856 /// Returns the platform-specific value of errno
857 pub fn errno() -> uint {
858 use libc::types::os::arch::extra::DWORD;
860 #[link_name = "kernel32"]
862 fn GetLastError() -> DWORD;
866 GetLastError() as uint
870 /// Return the string corresponding to an `errno()` value of `errnum`.
871 pub fn error_string(errnum: uint) -> String {
872 return strerror(errnum);
875 fn strerror(errnum: uint) -> String {
876 #[cfg(target_os = "macos")]
877 #[cfg(target_os = "ios")]
878 #[cfg(target_os = "android")]
879 #[cfg(target_os = "freebsd")]
880 fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: libc::size_t)
883 fn strerror_r(errnum: c_int, buf: *mut c_char,
884 buflen: libc::size_t) -> c_int;
887 strerror_r(errnum, buf, buflen)
891 // GNU libc provides a non-compliant version of strerror_r by default
892 // and requires macros to instead use the POSIX compliant variant.
893 // So we just use __xpg_strerror_r which is always POSIX compliant
894 #[cfg(target_os = "linux")]
895 fn strerror_r(errnum: c_int, buf: *mut c_char,
896 buflen: libc::size_t) -> c_int {
898 fn __xpg_strerror_r(errnum: c_int,
900 buflen: libc::size_t)
904 __xpg_strerror_r(errnum, buf, buflen)
908 let mut buf = [0 as c_char, ..TMPBUF_SZ];
910 let p = buf.as_mut_ptr();
912 if strerror_r(errnum as c_int, p, buf.len() as libc::size_t) < 0 {
913 fail!("strerror_r failure");
916 str::raw::from_c_str(p as *c_char).into_string()
921 fn strerror(errnum: uint) -> String {
922 use libc::types::os::arch::extra::DWORD;
923 use libc::types::os::arch::extra::LPWSTR;
924 use libc::types::os::arch::extra::LPVOID;
925 use libc::types::os::arch::extra::WCHAR;
927 #[link_name = "kernel32"]
929 fn FormatMessageW(flags: DWORD,
939 static FORMAT_MESSAGE_FROM_SYSTEM: DWORD = 0x00001000;
940 static FORMAT_MESSAGE_IGNORE_INSERTS: DWORD = 0x00000200;
942 // This value is calculated from the macro
943 // MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT)
944 let langId = 0x0800 as DWORD;
946 let mut buf = [0 as WCHAR, ..TMPBUF_SZ];
949 let res = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
950 FORMAT_MESSAGE_IGNORE_INSERTS,
958 // Sometimes FormatMessageW can fail e.g. system doesn't like langId,
959 let fm_err = errno();
960 return format!("OS Error {} (FormatMessageW() returned error {})", errnum, fm_err);
963 let msg = str::from_utf16(str::truncate_utf16_at_nul(buf));
965 Some(msg) => format!("OS Error {}: {}", errnum, msg),
966 None => format!("OS Error {} (FormatMessageW() returned invalid UTF-16)", errnum),
972 /// Get a string representing the platform-dependent last error
973 pub fn last_os_error() -> String {
974 error_string(errno() as uint)
977 static mut EXIT_STATUS: AtomicInt = INIT_ATOMIC_INT;
980 * Sets the process exit code
982 * Sets the exit code returned by the process if all supervised tasks
983 * terminate successfully (without failing). If the current root task fails
984 * and is supervised by the scheduler then any user-specified exit status is
985 * ignored and the process exits with the default failure status.
987 * Note that this is not synchronized against modifications of other threads.
989 pub fn set_exit_status(code: int) {
990 unsafe { EXIT_STATUS.store(code, SeqCst) }
993 /// Fetches the process's current exit code. This defaults to 0 and can change
994 /// by calling `set_exit_status`.
995 pub fn get_exit_status() -> int {
996 unsafe { EXIT_STATUS.load(SeqCst) }
999 #[cfg(target_os = "macos")]
1000 unsafe fn load_argc_and_argv(argc: int, argv: **c_char) -> Vec<Vec<u8>> {
1003 Vec::from_fn(argc as uint, |i| {
1004 Vec::from_slice(CString::new(*argv.offset(i as int),
1005 false).as_bytes_no_nul())
1010 * Returns the command line arguments
1012 * Returns a list of the command line arguments.
1014 #[cfg(target_os = "macos")]
1015 fn real_args_as_bytes() -> Vec<Vec<u8>> {
1017 let (argc, argv) = (*_NSGetArgc() as int,
1018 *_NSGetArgv() as **c_char);
1019 load_argc_and_argv(argc, argv)
1023 // As _NSGetArgc and _NSGetArgv aren't mentioned in iOS docs
1024 // and use underscores in their names - they're most probably
1025 // are considered private and therefore should be avoided
1026 // Here is another way to get arguments using Objective C
1029 // In general it looks like:
1031 // let args = [[NSProcessInfo processInfo] arguments]
1032 // for i in range(0, [args count])
1033 // res.push([args objectAtIndex:i])
1035 #[cfg(target_os = "ios")]
1036 fn real_args_as_bytes() -> Vec<Vec<u8>> {
1041 #[link(name = "objc")]
1043 fn sel_registerName(name: *libc::c_uchar) -> Sel;
1044 fn objc_msgSend(obj: NsId, sel: Sel, ...) -> NsId;
1045 fn objc_getClass(class_name: *libc::c_uchar) -> NsId;
1048 #[link(name = "Foundation", kind = "framework")]
1051 type Sel = *libc::c_void;
1052 type NsId = *libc::c_void;
1054 let mut res = Vec::new();
1057 let processInfoSel = sel_registerName("processInfo\0".as_ptr());
1058 let argumentsSel = sel_registerName("arguments\0".as_ptr());
1059 let utf8Sel = sel_registerName("UTF8String\0".as_ptr());
1060 let countSel = sel_registerName("count\0".as_ptr());
1061 let objectAtSel = sel_registerName("objectAtIndex:\0".as_ptr());
1063 let klass = objc_getClass("NSProcessInfo\0".as_ptr());
1064 let info = objc_msgSend(klass, processInfoSel);
1065 let args = objc_msgSend(info, argumentsSel);
1067 let cnt: int = mem::transmute(objc_msgSend(args, countSel));
1068 for i in range(0, cnt) {
1069 let tmp = objc_msgSend(args, objectAtSel, i);
1070 let utf_c_str: *libc::c_char = mem::transmute(objc_msgSend(tmp, utf8Sel));
1071 let s = CString::new(utf_c_str, false);
1072 if s.is_not_null() {
1073 res.push(Vec::from_slice(s.as_bytes_no_nul()))
1081 #[cfg(target_os = "linux")]
1082 #[cfg(target_os = "android")]
1083 #[cfg(target_os = "freebsd")]
1084 fn real_args_as_bytes() -> Vec<Vec<u8>> {
1087 match rt::args::clone() {
1089 None => fail!("process arguments not initialized")
1093 #[cfg(not(windows))]
1094 fn real_args() -> Vec<String> {
1095 real_args_as_bytes().move_iter()
1097 str::from_utf8_lossy(v.as_slice()).into_string()
1102 fn real_args() -> Vec<String> {
1105 let mut nArgs: c_int = 0;
1106 let lpArgCount: *mut c_int = &mut nArgs;
1107 let lpCmdLine = unsafe { GetCommandLineW() };
1108 let szArgList = unsafe { CommandLineToArgvW(lpCmdLine, lpArgCount) };
1110 let args = Vec::from_fn(nArgs as uint, |i| unsafe {
1111 // Determine the length of this argument.
1112 let ptr = *szArgList.offset(i as int);
1114 while *ptr.offset(len as int) != 0 { len += 1; }
1116 // Push it onto the list.
1117 let opt_s = slice::raw::buf_as_slice(ptr, len, |buf| {
1118 str::from_utf16(str::truncate_utf16_at_nul(buf))
1120 opt_s.expect("CommandLineToArgvW returned invalid UTF-16")
1124 LocalFree(szArgList as *c_void);
1131 fn real_args_as_bytes() -> Vec<Vec<u8>> {
1132 real_args().move_iter().map(|s| s.into_bytes()).collect()
1135 type LPCWSTR = *u16;
1138 #[link_name="kernel32"]
1140 fn GetCommandLineW() -> LPCWSTR;
1141 fn LocalFree(ptr: *c_void);
1145 #[link_name="shell32"]
1147 fn CommandLineToArgvW(lpCmdLine: LPCWSTR, pNumArgs: *mut c_int) -> **u16;
1150 /// Returns the arguments which this program was started with (normally passed
1151 /// via the command line).
1153 /// The arguments are interpreted as utf-8, with invalid bytes replaced with \uFFFD.
1154 /// See `str::from_utf8_lossy` for details.
1155 pub fn args() -> Vec<String> {
1159 /// Returns the arguments which this program was started with (normally passed
1160 /// via the command line) as byte vectors.
1161 pub fn args_as_bytes() -> Vec<Vec<u8>> {
1162 real_args_as_bytes()
1165 #[cfg(target_os = "macos")]
1167 // These functions are in crt_externs.h.
1168 pub fn _NSGetArgc() -> *c_int;
1169 pub fn _NSGetArgv() -> ***c_char;
1172 // Round up `from` to be divisible by `to`
1173 fn round_up(from: uint, to: uint) -> uint {
1174 let r = if from % to == 0 {
1177 from + to - (from % to)
1186 /// Returns the page size of the current architecture in bytes.
1188 pub fn page_size() -> uint {
1190 libc::sysconf(libc::_SC_PAGESIZE) as uint
1194 /// Returns the page size of the current architecture in bytes.
1196 pub fn page_size() -> uint {
1199 let mut info = mem::zeroed();
1200 libc::GetSystemInfo(&mut info);
1202 return info.dwPageSize as uint;
1206 /// A memory mapped file or chunk of memory. This is a very system-specific
1207 /// interface to the OS's memory mapping facilities (`mmap` on POSIX,
1208 /// `VirtualAlloc`/`CreateFileMapping` on win32). It makes no attempt at
1209 /// abstracting platform differences, besides in error values returned. Consider
1210 /// yourself warned.
1212 /// The memory map is released (unmapped) when the destructor is run, so don't
1213 /// let it leave scope by accident if you want it to stick around.
1214 pub struct MemoryMap {
1215 /// Pointer to the memory created or modified by this map.
1217 /// Number of bytes this map applies to
1220 pub kind: MemoryMapKind,
1223 /// Type of memory map
1224 pub enum MemoryMapKind {
1225 /// Virtual memory map. Usually used to change the permissions of a given
1226 /// chunk of memory. Corresponds to `VirtualAlloc` on Windows.
1228 /// Virtual memory map. Usually used to change the permissions of a given
1229 /// chunk of memory, or for allocation. Corresponds to `VirtualAlloc` on
1234 /// Options the memory map is created with
1235 pub enum MapOption {
1236 /// The memory should be readable
1238 /// The memory should be writable
1240 /// The memory should be executable
1242 /// Create a map for a specific address range. Corresponds to `MAP_FIXED` on
1245 /// Create a memory mapping for a file with a given fd.
1247 /// When using `MapFd`, the start of the map is `uint` bytes from the start
1250 /// On POSIX, this can be used to specify the default flags passed to
1251 /// `mmap`. By default it uses `MAP_PRIVATE` and, if not using `MapFd`,
1252 /// `MAP_ANON`. This will override both of those. This is platform-specific
1253 /// (the exact values used) and ignored on Windows.
1254 MapNonStandardFlags(c_int),
1257 /// Possible errors when creating a map.
1259 /// ## The following are POSIX-specific
1261 /// fd was not open for reading or, if using `MapWritable`, was not open for
1264 /// fd was not valid
1266 /// Either the address given by `MapAddr` or offset given by `MapOffset` was
1267 /// not a multiple of `MemoryMap::granularity` (unaligned to page size).
1269 /// With `MapFd`, the fd does not support mapping.
1271 /// If using `MapAddr`, the address + `min_len` was outside of the process's
1272 /// address space. If using `MapFd`, the target of the fd didn't have enough
1273 /// resources to fulfill the request.
1275 /// A zero-length map was requested. This is invalid according to
1276 /// [POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/functions/mmap.html).
1277 /// Not all platforms obey this, but this wrapper does.
1279 /// Unrecognized error. The inner value is the unrecognized errno.
1281 /// ## The following are win32-specific
1283 /// Unsupported combination of protection flags
1284 /// (`MapReadable`/`MapWritable`/`MapExecutable`).
1286 /// When using `MapFd`, `MapOffset` was given (Windows does not support this
1289 /// When using `MapFd`, there was already a mapping to the file.
1291 /// Unrecognized error from `VirtualAlloc`. The inner value is the return
1292 /// value of GetLastError.
1293 ErrVirtualAlloc(uint),
1294 /// Unrecognized error from `CreateFileMapping`. The inner value is the
1295 /// return value of `GetLastError`.
1296 ErrCreateFileMappingW(uint),
1297 /// Unrecognized error from `MapViewOfFile`. The inner value is the return
1298 /// value of `GetLastError`.
1299 ErrMapViewOfFile(uint)
1302 impl fmt::Show for MapError {
1303 fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result {
1304 let str = match *self {
1305 ErrFdNotAvail => "fd not available for reading or writing",
1306 ErrInvalidFd => "Invalid fd",
1308 "Unaligned address, invalid flags, negative length or \
1311 ErrNoMapSupport=> "File doesn't support mapping",
1312 ErrNoMem => "Invalid address, or not enough available memory",
1313 ErrUnsupProt => "Protection mode unsupported",
1314 ErrUnsupOffset => "Offset in virtual memory mode is unsupported",
1315 ErrAlreadyExists => "File mapping for specified file already exists",
1316 ErrZeroLength => "Zero-length mapping not allowed",
1317 ErrUnknown(code) => {
1318 return write!(out, "Unknown error = {}", code)
1320 ErrVirtualAlloc(code) => {
1321 return write!(out, "VirtualAlloc failure = {}", code)
1323 ErrCreateFileMappingW(code) => {
1324 return write!(out, "CreateFileMappingW failure = {}", code)
1326 ErrMapViewOfFile(code) => {
1327 return write!(out, "MapViewOfFile failure = {}", code)
1330 write!(out, "{}", str)
1336 /// Create a new mapping with the given `options`, at least `min_len` bytes
1337 /// long. `min_len` must be greater than zero; see the note on
1338 /// `ErrZeroLength`.
1339 pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
1343 return Err(ErrZeroLength)
1345 let mut addr: *u8 = ptr::null();
1347 let mut flags = libc::MAP_PRIVATE;
1350 let mut custom_flags = false;
1351 let len = round_up(min_len, page_size());
1353 for &o in options.iter() {
1355 MapReadable => { prot |= libc::PROT_READ; },
1356 MapWritable => { prot |= libc::PROT_WRITE; },
1357 MapExecutable => { prot |= libc::PROT_EXEC; },
1359 flags |= libc::MAP_FIXED;
1363 flags |= libc::MAP_FILE;
1366 MapOffset(offset_) => { offset = offset_ as off_t; },
1367 MapNonStandardFlags(f) => { custom_flags = true; flags = f },
1370 if fd == -1 && !custom_flags { flags |= libc::MAP_ANON; }
1373 libc::mmap(addr as *mut c_void, len as libc::size_t, prot, flags,
1376 if r == libc::MAP_FAILED {
1377 Err(match errno() as c_int {
1378 libc::EACCES => ErrFdNotAvail,
1379 libc::EBADF => ErrInvalidFd,
1380 libc::EINVAL => ErrUnaligned,
1381 libc::ENODEV => ErrNoMapSupport,
1382 libc::ENOMEM => ErrNoMem,
1383 code => ErrUnknown(code as int)
1392 MapFile(ptr::null())
1398 /// Granularity that the offset or address must be for `MapOffset` and
1399 /// `MapAddr` respectively.
1400 pub fn granularity() -> uint {
1406 impl Drop for MemoryMap {
1407 /// Unmap the mapping. Fails the task if `munmap` fails.
1408 fn drop(&mut self) {
1409 if self.len == 0 { /* workaround for dummy_stack */ return; }
1412 // `munmap` only fails due to logic errors
1413 libc::munmap(self.data as *mut c_void, self.len as libc::size_t);
1420 /// Create a new mapping with the given `options`, at least `min_len` bytes long.
1421 pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
1422 use libc::types::os::arch::extra::{LPVOID, DWORD, SIZE_T, HANDLE};
1424 let mut lpAddress: LPVOID = ptr::mut_null();
1425 let mut readable = false;
1426 let mut writable = false;
1427 let mut executable = false;
1428 let mut fd: c_int = -1;
1429 let mut offset: uint = 0;
1430 let len = round_up(min_len, page_size());
1432 for &o in options.iter() {
1434 MapReadable => { readable = true; },
1435 MapWritable => { writable = true; },
1436 MapExecutable => { executable = true; }
1437 MapAddr(addr_) => { lpAddress = addr_ as LPVOID; },
1438 MapFd(fd_) => { fd = fd_; },
1439 MapOffset(offset_) => { offset = offset_; },
1440 MapNonStandardFlags(..) => {}
1444 let flProtect = match (executable, readable, writable) {
1445 (false, false, false) if fd == -1 => libc::PAGE_NOACCESS,
1446 (false, true, false) => libc::PAGE_READONLY,
1447 (false, true, true) => libc::PAGE_READWRITE,
1448 (true, false, false) if fd == -1 => libc::PAGE_EXECUTE,
1449 (true, true, false) => libc::PAGE_EXECUTE_READ,
1450 (true, true, true) => libc::PAGE_EXECUTE_READWRITE,
1451 _ => return Err(ErrUnsupProt)
1456 return Err(ErrUnsupOffset);
1459 libc::VirtualAlloc(lpAddress,
1461 libc::MEM_COMMIT | libc::MEM_RESERVE,
1465 0 => Err(ErrVirtualAlloc(errno())),
1473 let dwDesiredAccess = match (executable, readable, writable) {
1474 (false, true, false) => libc::FILE_MAP_READ,
1475 (false, true, true) => libc::FILE_MAP_WRITE,
1476 (true, true, false) => libc::FILE_MAP_READ | libc::FILE_MAP_EXECUTE,
1477 (true, true, true) => libc::FILE_MAP_WRITE | libc::FILE_MAP_EXECUTE,
1478 _ => return Err(ErrUnsupProt) // Actually, because of the check above,
1479 // we should never get here.
1482 let hFile = libc::get_osfhandle(fd) as HANDLE;
1483 let mapping = libc::CreateFileMappingW(hFile,
1489 if mapping == ptr::mut_null() {
1490 return Err(ErrCreateFileMappingW(errno()));
1492 if errno() as c_int == libc::ERROR_ALREADY_EXISTS {
1493 return Err(ErrAlreadyExists);
1495 let r = libc::MapViewOfFile(mapping,
1497 ((len as u64) >> 32) as DWORD,
1498 (offset & 0xffff_ffff) as DWORD,
1501 0 => Err(ErrMapViewOfFile(errno())),
1505 kind: MapFile(mapping as *u8)
1512 /// Granularity of MapAddr() and MapOffset() parameter values.
1513 /// This may be greater than the value returned by page_size().
1514 pub fn granularity() -> uint {
1517 let mut info = mem::zeroed();
1518 libc::GetSystemInfo(&mut info);
1520 return info.dwAllocationGranularity as uint;
1526 impl Drop for MemoryMap {
1527 /// Unmap the mapping. Fails the task if any of `VirtualFree`,
1528 /// `UnmapViewOfFile`, or `CloseHandle` fail.
1529 fn drop(&mut self) {
1530 use libc::types::os::arch::extra::{LPCVOID, HANDLE};
1531 use libc::consts::os::extra::FALSE;
1532 if self.len == 0 { return }
1537 if libc::VirtualFree(self.data as *mut c_void, 0,
1538 libc::MEM_RELEASE) == 0 {
1539 println!("VirtualFree failed: {}", errno());
1542 MapFile(mapping) => {
1543 if libc::UnmapViewOfFile(self.data as LPCVOID) == FALSE {
1544 println!("UnmapViewOfFile failed: {}", errno());
1546 if libc::CloseHandle(mapping as HANDLE) == FALSE {
1547 println!("CloseHandle failed: {}", errno());
1555 #[cfg(target_os = "linux")]
1557 pub use os::arch_consts::ARCH;
1559 pub static FAMILY: &'static str = "unix";
1561 /// A string describing the specific operating system in use: in this
1563 pub static SYSNAME: &'static str = "linux";
1565 /// Specifies the filename prefix used for shared libraries on this
1566 /// platform: in this case, `lib`.
1567 pub static DLL_PREFIX: &'static str = "lib";
1569 /// Specifies the filename suffix used for shared libraries on this
1570 /// platform: in this case, `.so`.
1571 pub static DLL_SUFFIX: &'static str = ".so";
1573 /// Specifies the file extension used for shared libraries on this
1574 /// platform that goes after the dot: in this case, `so`.
1575 pub static DLL_EXTENSION: &'static str = "so";
1577 /// Specifies the filename suffix used for executable binaries on this
1578 /// platform: in this case, the empty string.
1579 pub static EXE_SUFFIX: &'static str = "";
1581 /// Specifies the file extension, if any, used for executable binaries
1582 /// on this platform: in this case, the empty string.
1583 pub static EXE_EXTENSION: &'static str = "";
1586 #[cfg(target_os = "macos")]
1588 pub use os::arch_consts::ARCH;
1590 pub static FAMILY: &'static str = "unix";
1592 /// A string describing the specific operating system in use: in this
1594 pub static SYSNAME: &'static str = "macos";
1596 /// Specifies the filename prefix used for shared libraries on this
1597 /// platform: in this case, `lib`.
1598 pub static DLL_PREFIX: &'static str = "lib";
1600 /// Specifies the filename suffix used for shared libraries on this
1601 /// platform: in this case, `.dylib`.
1602 pub static DLL_SUFFIX: &'static str = ".dylib";
1604 /// Specifies the file extension used for shared libraries on this
1605 /// platform that goes after the dot: in this case, `dylib`.
1606 pub static DLL_EXTENSION: &'static str = "dylib";
1608 /// Specifies the filename suffix used for executable binaries on this
1609 /// platform: in this case, the empty string.
1610 pub static EXE_SUFFIX: &'static str = "";
1612 /// Specifies the file extension, if any, used for executable binaries
1613 /// on this platform: in this case, the empty string.
1614 pub static EXE_EXTENSION: &'static str = "";
1617 #[cfg(target_os = "ios")]
1619 pub use os::arch_consts::ARCH;
1621 pub static FAMILY: &'static str = "unix";
1623 /// A string describing the specific operating system in use: in this
1625 pub static SYSNAME: &'static str = "ios";
1627 /// Specifies the filename suffix used for executable binaries on this
1628 /// platform: in this case, the empty string.
1629 pub static EXE_SUFFIX: &'static str = "";
1631 /// Specifies the file extension, if any, used for executable binaries
1632 /// on this platform: in this case, the empty string.
1633 pub static EXE_EXTENSION: &'static str = "";
1636 #[cfg(target_os = "freebsd")]
1638 pub use os::arch_consts::ARCH;
1640 pub static FAMILY: &'static str = "unix";
1642 /// A string describing the specific operating system in use: in this
1643 /// case, `freebsd`.
1644 pub static SYSNAME: &'static str = "freebsd";
1646 /// Specifies the filename prefix used for shared libraries on this
1647 /// platform: in this case, `lib`.
1648 pub static DLL_PREFIX: &'static str = "lib";
1650 /// Specifies the filename suffix used for shared libraries on this
1651 /// platform: in this case, `.so`.
1652 pub static DLL_SUFFIX: &'static str = ".so";
1654 /// Specifies the file extension used for shared libraries on this
1655 /// platform that goes after the dot: in this case, `so`.
1656 pub static DLL_EXTENSION: &'static str = "so";
1658 /// Specifies the filename suffix used for executable binaries on this
1659 /// platform: in this case, the empty string.
1660 pub static EXE_SUFFIX: &'static str = "";
1662 /// Specifies the file extension, if any, used for executable binaries
1663 /// on this platform: in this case, the empty string.
1664 pub static EXE_EXTENSION: &'static str = "";
1667 #[cfg(target_os = "android")]
1669 pub use os::arch_consts::ARCH;
1671 pub static FAMILY: &'static str = "unix";
1673 /// A string describing the specific operating system in use: in this
1674 /// case, `android`.
1675 pub static SYSNAME: &'static str = "android";
1677 /// Specifies the filename prefix used for shared libraries on this
1678 /// platform: in this case, `lib`.
1679 pub static DLL_PREFIX: &'static str = "lib";
1681 /// Specifies the filename suffix used for shared libraries on this
1682 /// platform: in this case, `.so`.
1683 pub static DLL_SUFFIX: &'static str = ".so";
1685 /// Specifies the file extension used for shared libraries on this
1686 /// platform that goes after the dot: in this case, `so`.
1687 pub static DLL_EXTENSION: &'static str = "so";
1689 /// Specifies the filename suffix used for executable binaries on this
1690 /// platform: in this case, the empty string.
1691 pub static EXE_SUFFIX: &'static str = "";
1693 /// Specifies the file extension, if any, used for executable binaries
1694 /// on this platform: in this case, the empty string.
1695 pub static EXE_EXTENSION: &'static str = "";
1698 #[cfg(target_os = "win32")]
1700 pub use os::arch_consts::ARCH;
1702 pub static FAMILY: &'static str = "windows";
1704 /// A string describing the specific operating system in use: in this
1706 pub static SYSNAME: &'static str = "win32";
1708 /// Specifies the filename prefix used for shared libraries on this
1709 /// platform: in this case, the empty string.
1710 pub static DLL_PREFIX: &'static str = "";
1712 /// Specifies the filename suffix used for shared libraries on this
1713 /// platform: in this case, `.dll`.
1714 pub static DLL_SUFFIX: &'static str = ".dll";
1716 /// Specifies the file extension used for shared libraries on this
1717 /// platform that goes after the dot: in this case, `dll`.
1718 pub static DLL_EXTENSION: &'static str = "dll";
1720 /// Specifies the filename suffix used for executable binaries on this
1721 /// platform: in this case, `.exe`.
1722 pub static EXE_SUFFIX: &'static str = ".exe";
1724 /// Specifies the file extension, if any, used for executable binaries
1725 /// on this platform: in this case, `exe`.
1726 pub static EXE_EXTENSION: &'static str = "exe";
1729 #[cfg(target_arch = "x86")]
1731 pub static ARCH: &'static str = "x86";
1734 #[cfg(target_arch = "x86_64")]
1736 pub static ARCH: &'static str = "x86_64";
1739 #[cfg(target_arch = "arm")]
1741 pub static ARCH: &'static str = "arm";
1744 #[cfg(target_arch = "mips")]
1746 pub static ARCH: &'static str = "mips";
1749 #[cfg(target_arch = "mipsel")]
1751 pub static ARCH: &'static str = "mipsel";
1759 use os::{env, getcwd, getenv, make_absolute};
1760 use os::{split_paths, setenv, unsetenv};
1766 pub fn last_os_error() {
1767 debug!("{}", os::last_os_error());
1770 fn make_rand_name() -> String {
1771 let mut rng = rand::task_rng();
1772 let n = format!("TEST{}", rng.gen_ascii_chars().take(10u)
1773 .collect::<String>());
1774 assert!(getenv(n.as_slice()).is_none());
1779 fn test_num_cpus() {
1780 assert!(os::num_cpus() > 0);
1785 let n = make_rand_name();
1786 setenv(n.as_slice(), "VALUE");
1787 assert_eq!(getenv(n.as_slice()), option::Some("VALUE".to_string()));
1791 fn test_unsetenv() {
1792 let n = make_rand_name();
1793 setenv(n.as_slice(), "VALUE");
1794 unsetenv(n.as_slice());
1795 assert_eq!(getenv(n.as_slice()), option::None);
1800 fn test_setenv_overwrite() {
1801 let n = make_rand_name();
1802 setenv(n.as_slice(), "1");
1803 setenv(n.as_slice(), "2");
1804 assert_eq!(getenv(n.as_slice()), option::Some("2".to_string()));
1805 setenv(n.as_slice(), "");
1806 assert_eq!(getenv(n.as_slice()), option::Some("".to_string()));
1809 // Windows GetEnvironmentVariable requires some extra work to make sure
1810 // the buffer the variable is copied into is the right size
1813 fn test_getenv_big() {
1814 let mut s = "".to_string();
1817 s.push_str("aaaaaaaaaa");
1820 let n = make_rand_name();
1821 setenv(n.as_slice(), s.as_slice());
1822 debug!("{}", s.clone());
1823 assert_eq!(getenv(n.as_slice()), option::Some(s));
1827 fn test_self_exe_name() {
1828 let path = os::self_exe_name();
1829 assert!(path.is_some());
1830 let path = path.unwrap();
1831 debug!("{:?}", path.clone());
1833 // Hard to test this function
1834 assert!(path.is_absolute());
1838 fn test_self_exe_path() {
1839 let path = os::self_exe_path();
1840 assert!(path.is_some());
1841 let path = path.unwrap();
1842 debug!("{:?}", path.clone());
1844 // Hard to test this function
1845 assert!(path.is_absolute());
1850 fn test_env_getenv() {
1852 assert!(e.len() > 0u);
1854 let (n, v) = (*p).clone();
1855 debug!("{:?}", n.clone());
1856 let v2 = getenv(n.as_slice());
1857 // MingW seems to set some funky environment variables like
1858 // "=C:=C:\MinGW\msys\1.0\bin" and "!::=::\" that are returned
1859 // from env() but not visible from getenv().
1860 assert!(v2.is_none() || v2 == option::Some(v));
1865 fn test_env_set_get_huge() {
1866 let n = make_rand_name();
1867 let s = "x".repeat(10000).to_string();
1868 setenv(n.as_slice(), s.as_slice());
1869 assert_eq!(getenv(n.as_slice()), Some(s));
1870 unsetenv(n.as_slice());
1871 assert_eq!(getenv(n.as_slice()), None);
1875 fn test_env_setenv() {
1876 let n = make_rand_name();
1879 setenv(n.as_slice(), "VALUE");
1880 assert!(!e.contains(&(n.clone(), "VALUE".to_string())));
1883 assert!(e.contains(&(n, "VALUE".to_string())));
1888 assert!((!Path::new("test-path").is_absolute()));
1891 debug!("Current working directory: {}", cwd.display());
1893 debug!("{:?}", make_absolute(&Path::new("test-path")));
1894 debug!("{:?}", make_absolute(&Path::new("/usr/bin")));
1900 let oldhome = getenv("HOME");
1902 setenv("HOME", "/home/MountainView");
1903 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1906 assert!(os::homedir().is_none());
1908 for s in oldhome.iter() {
1909 setenv("HOME", s.as_slice());
1917 let oldhome = getenv("HOME");
1918 let olduserprofile = getenv("USERPROFILE");
1921 setenv("USERPROFILE", "");
1923 assert!(os::homedir().is_none());
1925 setenv("HOME", "/home/MountainView");
1926 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1930 setenv("USERPROFILE", "/home/MountainView");
1931 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1933 setenv("HOME", "/home/MountainView");
1934 setenv("USERPROFILE", "/home/PaloAlto");
1935 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1937 for s in oldhome.iter() {
1938 setenv("HOME", s.as_slice());
1940 for s in olduserprofile.iter() {
1941 setenv("USERPROFILE", s.as_slice());
1946 fn memory_map_rw() {
1947 use result::{Ok, Err};
1949 let chunk = match os::MemoryMap::new(16, [
1954 Err(msg) => fail!("{}", msg)
1956 assert!(chunk.len >= 16);
1960 assert!(*chunk.data == 0xBE);
1965 fn memory_map_file() {
1966 use result::{Ok, Err};
1972 fn lseek_(fd: c_int, size: uint) {
1974 assert!(lseek(fd, size as off_t, SEEK_SET) == size as off_t);
1978 fn lseek_(fd: c_int, size: uint) {
1980 assert!(lseek(fd, size as c_long, SEEK_SET) == size as c_long);
1984 let mut path = tmpdir();
1985 path.push("mmap_file.tmp");
1986 let size = MemoryMap::granularity() * 2;
1989 let fd = path.with_c_str(|path| {
1990 open(path, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR)
1993 "x".with_c_str(|x| assert!(write(fd, x as *c_void, 1) == 1));
1996 let chunk = match MemoryMap::new(size / 2, [
2003 Err(msg) => fail!("{}", msg)
2005 assert!(chunk.len > 0);
2009 assert!(*chunk.data == 0xbe);
2014 fs::unlink(&path).unwrap();
2019 fn split_paths_windows() {
2020 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
2021 split_paths(unparsed) ==
2022 parsed.iter().map(|s| Path::new(*s)).collect()
2025 assert!(check_parse("", []));
2026 assert!(check_parse(r#""""#, []));
2027 assert!(check_parse(";;", []));
2028 assert!(check_parse(r"c:\", [r"c:\"]));
2029 assert!(check_parse(r"c:\;", [r"c:\"]));
2030 assert!(check_parse(r"c:\;c:\Program Files\",
2031 [r"c:\", r"c:\Program Files\"]));
2032 assert!(check_parse(r#"c:\;c:\"foo"\"#, [r"c:\", r"c:\foo\"]));
2033 assert!(check_parse(r#"c:\;c:\"foo;bar"\;c:\baz"#,
2034 [r"c:\", r"c:\foo;bar\", r"c:\baz"]));
2039 fn split_paths_unix() {
2040 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
2041 split_paths(unparsed) ==
2042 parsed.iter().map(|s| Path::new(*s)).collect()
2045 assert!(check_parse("", []));
2046 assert!(check_parse("::", []));
2047 assert!(check_parse("/", ["/"]));
2048 assert!(check_parse("/:", ["/"]));
2049 assert!(check_parse("/:/usr/local", ["/", "/usr/local"]));
2052 // More recursive_mkdir tests are in extra::tempfile