1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Higher-level interfaces to libc::* functions and operating system services.
13 //! In general these take and return rust types, use rust idioms (enums,
14 //! closures, vectors) rather than C idioms, and do more extensive safety
17 //! This module is not meant to only contain 1:1 mappings to libc entries; any
18 //! os-interface code that is reasonably useful and broadly applicable can go
19 //! here. Including utility routines that merely build on other os code.
21 //! We assume the general case is that users do not care, and do not want to be
22 //! made to care, which operating system they are on. While they may want to
23 //! special case various special cases -- and so we will not _hide_ the facts of
24 //! which OS the user is on -- they should be given the opportunity to write
25 //! OS-ignorant code by default.
27 #![unstable(feature = "os")]
29 #![allow(missing_docs)]
30 #![allow(non_snake_case)]
31 #![allow(unused_imports)]
33 use self::MemoryMapKind::*;
34 use self::MapOption::*;
35 use self::MapError::*;
38 use error::{FromError, Error};
40 use old_io::{IoResult, IoError};
41 use iter::{Iterator, IteratorExt};
42 use marker::{Copy, Send};
43 use libc::{c_void, c_int, c_char};
46 use ops::{Drop, FnOnce};
48 use option::Option::{Some, None};
49 use path::{Path, GenericPath, BytesContainer};
51 use sys::os as os_imp;
55 use result::Result::{Err, Ok};
56 use slice::{AsSlice, SliceExt};
57 use str::{Str, StrExt};
58 use string::{String, ToString};
59 use sync::atomic::{AtomicIsize, ATOMIC_ISIZE_INIT, Ordering};
62 #[cfg(unix)] use ffi::{self, CString};
64 #[cfg(unix)] pub use sys::ext as unix;
65 #[cfg(windows)] pub use sys::ext as windows;
67 /// Get the number of cores available
68 pub fn num_cpus() -> uint {
70 return rust_get_num_cpus() as uint;
74 fn rust_get_num_cpus() -> libc::uintptr_t;
78 pub const TMPBUF_SZ : uint = 1000u;
80 /// Returns the current working directory as a `Path`.
84 /// Returns an `Err` if the current working directory value is invalid.
87 /// * Current directory does not exist.
88 /// * There are insufficient permissions to access the current directory.
89 /// * The internal buffer is not large enough to hold the path.
96 /// // We assume that we are in a valid directory.
97 /// let current_working_directory = os::getcwd().unwrap();
98 /// println!("The current directory is {:?}", current_working_directory.display());
100 pub fn getcwd() -> IoResult<Path> {
105 Accessing environment variables is not generally threadsafe.
106 Serialize access through a global lock.
108 fn with_env_lock<T, F>(f: F) -> T where
111 use sync::{StaticMutex, MUTEX_INIT};
113 static LOCK: StaticMutex = MUTEX_INIT;
115 let _guard = LOCK.lock();
119 /// Returns a vector of (variable, value) pairs, for all the environment
120 /// variables of the current process.
122 /// Invalid UTF-8 bytes are replaced with \uFFFD. See `String::from_utf8_lossy()`
130 /// // We will iterate through the references to the element returned by os::env();
131 /// for &(ref key, ref value) in os::env().iter() {
132 /// println!("'{}': '{}'", key, value );
135 pub fn env() -> Vec<(String,String)> {
136 env_as_bytes().into_iter().map(|(k,v)| {
137 let k = String::from_utf8_lossy(k.as_slice()).into_owned();
138 let v = String::from_utf8_lossy(v.as_slice()).into_owned();
143 /// Returns a vector of (variable, value) byte-vector pairs for all the
144 /// environment variables of the current process.
145 pub fn env_as_bytes() -> Vec<(Vec<u8>,Vec<u8>)> {
147 fn env_convert(input: Vec<Vec<u8>>) -> Vec<(Vec<u8>, Vec<u8>)> {
148 let mut pairs = Vec::new();
149 for p in input.iter() {
150 let mut it = p.splitn(1, |b| *b == b'=');
151 let key = it.next().unwrap().to_vec();
152 let default: &[u8] = &[];
153 let val = it.next().unwrap_or(default).to_vec();
154 pairs.push((key, val));
159 let unparsed_environ = sys::os::get_env_pairs();
160 env_convert(unparsed_environ)
166 /// Fetches the environment variable `n` from the current process, returning
167 /// None if the variable isn't set.
169 /// Any invalid UTF-8 bytes in the value are replaced by \uFFFD. See
170 /// `String::from_utf8_lossy()` for details.
174 /// Panics if `n` has any interior NULs.
181 /// let key = "HOME";
182 /// match os::getenv(key) {
183 /// Some(val) => println!("{}: {}", key, val),
184 /// None => println!("{} is not defined in the environment.", key)
187 pub fn getenv(n: &str) -> Option<String> {
188 getenv_as_bytes(n).map(|v| String::from_utf8_lossy(v.as_slice()).into_owned())
192 /// Fetches the environment variable `n` byte vector from the current process,
193 /// returning None if the variable isn't set.
197 /// Panics if `n` has any interior NULs.
198 pub fn getenv_as_bytes(n: &str) -> Option<Vec<u8>> {
201 let s = CString::from_slice(n.as_bytes());
202 let s = libc::getenv(s.as_ptr()) as *const _;
206 Some(ffi::c_str_to_bytes(&s).to_vec())
213 /// Fetches the environment variable `n` from the current process, returning
214 /// None if the variable isn't set.
215 pub fn getenv(n: &str) -> Option<String> {
218 use sys::os::fill_utf16_buf_and_decode;
219 let mut n: Vec<u16> = n.utf16_units().collect();
221 fill_utf16_buf_and_decode(|buf, sz| {
222 libc::GetEnvironmentVariableW(n.as_ptr(), buf, sz)
229 /// Fetches the environment variable `n` byte vector from the current process,
230 /// returning None if the variable isn't set.
231 pub fn getenv_as_bytes(n: &str) -> Option<Vec<u8>> {
232 getenv(n).map(|s| s.into_bytes())
235 /// Sets the environment variable `n` to the value `v` for the currently running
244 /// os::setenv(key, "VALUE");
245 /// match os::getenv(key) {
246 /// Some(ref val) => println!("{}: {}", key, val),
247 /// None => println!("{} is not defined in the environment.", key)
250 pub fn setenv<T: BytesContainer>(n: &str, v: T) {
252 fn _setenv(n: &str, v: &[u8]) {
255 let k = CString::from_slice(n.as_bytes());
256 let v = CString::from_slice(v);
257 if libc::funcs::posix01::unistd::setenv(k.as_ptr(),
258 v.as_ptr(), 1) != 0 {
259 panic!(IoError::last_error());
266 fn _setenv(n: &str, v: &[u8]) {
267 let mut n: Vec<u16> = n.utf16_units().collect();
269 let mut v: Vec<u16> = ::str::from_utf8(v).unwrap().utf16_units().collect();
274 if libc::SetEnvironmentVariableW(n.as_ptr(), v.as_ptr()) == 0 {
275 panic!(IoError::last_error());
281 _setenv(n, v.container_as_bytes())
284 /// Remove a variable from the environment entirely.
285 pub fn unsetenv(n: &str) {
287 fn _unsetenv(n: &str) {
290 let nbuf = CString::from_slice(n.as_bytes());
291 if libc::funcs::posix01::unistd::unsetenv(nbuf.as_ptr()) != 0 {
292 panic!(IoError::last_error());
299 fn _unsetenv(n: &str) {
300 let mut n: Vec<u16> = n.utf16_units().collect();
304 if libc::SetEnvironmentVariableW(n.as_ptr(), ptr::null()) == 0 {
305 panic!(IoError::last_error());
314 /// Parses input according to platform conventions for the `PATH`
315 /// environment variable.
321 /// let key = "PATH";
322 /// match os::getenv_as_bytes(key) {
324 /// for path in os::split_paths(paths).iter() {
325 /// println!("'{}'", path.display());
328 /// None => println!("{} is not defined in the environment.", key)
331 pub fn split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> {
332 sys::os::split_paths(unparsed.container_as_bytes())
335 /// Joins a collection of `Path`s appropriately for the `PATH`
336 /// environment variable.
338 /// Returns a `Vec<u8>` on success, since `Path`s are not utf-8
339 /// encoded on all platforms.
341 /// Returns an `Err` (containing an error message) if one of the input
342 /// `Path`s contains an invalid character for constructing the `PATH`
343 /// variable (a double quote on Windows or a colon on Unix).
349 /// use std::path::Path;
351 /// let key = "PATH";
352 /// let mut paths = os::getenv_as_bytes(key).map_or(Vec::new(), os::split_paths);
353 /// paths.push(Path::new("/home/xyz/bin"));
354 /// os::setenv(key, os::join_paths(paths.as_slice()).unwrap());
356 pub fn join_paths<T: BytesContainer>(paths: &[T]) -> Result<Vec<u8>, &'static str> {
357 sys::os::join_paths(paths)
360 /// A low-level OS in-memory pipe.
363 /// A file descriptor representing the reading end of the pipe. Data written
364 /// on the `out` file descriptor can be read from this file descriptor.
366 /// A file descriptor representing the write end of the pipe. Data written
367 /// to this file descriptor can be read from the `input` file descriptor.
371 /// Creates a new low-level OS in-memory pipe.
373 /// This function can fail to succeed if there are no more resources available
374 /// to allocate a pipe.
376 /// This function is also unsafe as there is no destructor associated with the
377 /// `Pipe` structure will return. If it is not arranged for the returned file
378 /// descriptors to be closed, the file descriptors will leak. For safe handling
379 /// of this scenario, use `std::old_io::PipeStream` instead.
380 pub unsafe fn pipe() -> IoResult<Pipe> {
381 let (reader, writer) = try!(sys::os::pipe());
383 reader: reader.unwrap(),
384 writer: writer.unwrap(),
388 /// Returns the proper dll filename for the given basename of a file
390 #[cfg(not(target_os="ios"))]
391 pub fn dll_filename(base: &str) -> String {
392 format!("{}{}{}", consts::DLL_PREFIX, base, consts::DLL_SUFFIX)
395 /// Optionally returns the filesystem path to the current executable which is
396 /// running but with the executable name.
403 /// match os::self_exe_name() {
404 /// Some(exe_path) => println!("Path of this executable is: {}", exe_path.display()),
405 /// None => println!("Unable to get the path of this executable!")
408 pub fn self_exe_name() -> Option<Path> {
409 sys::os::load_self().and_then(Path::new_opt)
412 /// Optionally returns the filesystem path to the current executable which is
415 /// Like self_exe_name() but without the binary's name.
422 /// match os::self_exe_path() {
423 /// Some(exe_path) => println!("Executable's Path is: {}", exe_path.display()),
424 /// None => println!("Impossible to fetch the path of this executable.")
427 pub fn self_exe_path() -> Option<Path> {
428 self_exe_name().map(|mut p| { p.pop(); p })
431 /// Optionally returns the path to the current user's home directory if known.
435 /// Returns the value of the 'HOME' environment variable if it is set
436 /// and not equal to the empty string.
440 /// Returns the value of the 'HOME' environment variable if it is
441 /// set and not equal to the empty string. Otherwise, returns the value of the
442 /// 'USERPROFILE' environment variable if it is set and not equal to the empty
450 /// match os::homedir() {
451 /// Some(ref p) => println!("{}", p.display()),
452 /// None => println!("Impossible to get your home dir!")
455 pub fn homedir() -> Option<Path> {
458 fn _homedir() -> Option<Path> {
464 fn _homedir() -> Option<Path> {
465 aux_homedir("HOME").or(aux_homedir("USERPROFILE"))
469 fn aux_homedir(home_name: &str) -> Option<Path> {
470 match getenv_as_bytes(home_name) {
472 if p.is_empty() { None } else { Path::new_opt(p) }
480 /// Returns the path to a temporary directory.
482 /// On Unix, returns the value of the 'TMPDIR' environment variable if it is
483 /// set, otherwise for non-Android it returns '/tmp'. If Android, since there
484 /// is no global temporary folder (it is usually allocated per-app), we return
485 /// '/data/local/tmp'.
487 /// On Windows, returns the value of, in order, the 'TMP', 'TEMP',
488 /// 'USERPROFILE' environment variable if any are set and not the empty
489 /// string. Otherwise, tmpdir returns the path to the Windows directory.
490 pub fn tmpdir() -> Path {
493 fn getenv_nonempty(v: &str) -> Option<Path> {
506 fn lookup() -> Path {
507 let default = if cfg!(target_os = "android") {
508 Path::new("/data/local/tmp")
513 getenv_nonempty("TMPDIR").unwrap_or(default)
517 fn lookup() -> Path {
518 getenv_nonempty("TMP").or(
519 getenv_nonempty("TEMP").or(
520 getenv_nonempty("USERPROFILE").or(
521 getenv_nonempty("WINDIR")))).unwrap_or(Path::new("C:\\Windows"))
525 /// Convert a relative path to an absolute path
527 /// If the given path is relative, return it prepended with the current working
528 /// directory. If the given path is already an absolute path, return it
534 /// use std::path::Path;
536 /// // Assume we're in a path like /home/someuser
537 /// let rel_path = Path::new("..");
538 /// let abs_path = os::make_absolute(&rel_path).unwrap();
539 /// println!("The absolute path is {}", abs_path.display());
540 /// // Prints "The absolute path is /home"
542 // NB: this is here rather than in path because it is a form of environment
543 // querying; what it does depends on the process working directory, not just
545 pub fn make_absolute(p: &Path) -> IoResult<Path> {
549 getcwd().map(|mut cwd| {
556 /// Changes the current working directory to the specified path, returning
557 /// whether the change was completed successfully or not.
562 /// use std::path::Path;
564 /// let root = Path::new("/");
565 /// assert!(os::change_dir(&root).is_ok());
566 /// println!("Successfully changed working directory to {}!", root.display());
568 pub fn change_dir(p: &Path) -> IoResult<()> {
569 return sys::os::chdir(p);
572 /// Returns the platform-specific value of errno
573 pub fn errno() -> uint {
574 sys::os::errno() as uint
577 /// Return the string corresponding to an `errno()` value of `errnum`.
583 /// // Same as println!("{}", last_os_error());
584 /// println!("{}", os::error_string(os::errno() as uint));
586 pub fn error_string(errnum: uint) -> String {
587 return sys::os::error_string(errnum as i32);
590 /// Get a string representing the platform-dependent last error
591 pub fn last_os_error() -> String {
592 error_string(errno() as uint)
595 static EXIT_STATUS: AtomicIsize = ATOMIC_ISIZE_INIT;
597 /// Sets the process exit code
599 /// Sets the exit code returned by the process if all supervised tasks
600 /// terminate successfully (without panicking). If the current root task panics
601 /// and is supervised by the scheduler then any user-specified exit status is
602 /// ignored and the process exits with the default panic status.
604 /// Note that this is not synchronized against modifications of other threads.
605 pub fn set_exit_status(code: int) {
606 EXIT_STATUS.store(code, Ordering::SeqCst)
609 /// Fetches the process's current exit code. This defaults to 0 and can change
610 /// by calling `set_exit_status`.
611 pub fn get_exit_status() -> int {
612 EXIT_STATUS.load(Ordering::SeqCst)
615 #[cfg(target_os = "macos")]
616 unsafe fn load_argc_and_argv(argc: int,
617 argv: *const *const c_char) -> Vec<Vec<u8>> {
620 (0..argc as uint).map(|i| {
621 ffi::c_str_to_bytes(&*argv.offset(i as int)).to_vec()
625 /// Returns the command line arguments
627 /// Returns a list of the command line arguments.
628 #[cfg(target_os = "macos")]
629 fn real_args_as_bytes() -> Vec<Vec<u8>> {
631 let (argc, argv) = (*_NSGetArgc() as int,
632 *_NSGetArgv() as *const *const c_char);
633 load_argc_and_argv(argc, argv)
637 // As _NSGetArgc and _NSGetArgv aren't mentioned in iOS docs
638 // and use underscores in their names - they're most probably
639 // are considered private and therefore should be avoided
640 // Here is another way to get arguments using Objective C
643 // In general it looks like:
645 // let args = [[NSProcessInfo processInfo] arguments]
646 // for i in 0..[args count]
647 // res.push([args objectAtIndex:i])
649 #[cfg(target_os = "ios")]
650 fn real_args_as_bytes() -> Vec<Vec<u8>> {
651 use ffi::c_str_to_bytes;
655 #[link(name = "objc")]
657 fn sel_registerName(name: *const libc::c_uchar) -> Sel;
658 fn objc_msgSend(obj: NsId, sel: Sel, ...) -> NsId;
659 fn objc_getClass(class_name: *const libc::c_uchar) -> NsId;
662 #[link(name = "Foundation", kind = "framework")]
665 type Sel = *const libc::c_void;
666 type NsId = *const libc::c_void;
668 let mut res = Vec::new();
671 let processInfoSel = sel_registerName("processInfo\0".as_ptr());
672 let argumentsSel = sel_registerName("arguments\0".as_ptr());
673 let utf8Sel = sel_registerName("UTF8String\0".as_ptr());
674 let countSel = sel_registerName("count\0".as_ptr());
675 let objectAtSel = sel_registerName("objectAtIndex:\0".as_ptr());
677 let klass = objc_getClass("NSProcessInfo\0".as_ptr());
678 let info = objc_msgSend(klass, processInfoSel);
679 let args = objc_msgSend(info, argumentsSel);
681 let cnt: int = mem::transmute(objc_msgSend(args, countSel));
683 let tmp = objc_msgSend(args, objectAtSel, i);
684 let utf_c_str: *const libc::c_char =
685 mem::transmute(objc_msgSend(tmp, utf8Sel));
686 res.push(c_str_to_bytes(&utf_c_str).to_vec());
693 #[cfg(any(target_os = "linux",
694 target_os = "android",
695 target_os = "freebsd",
696 target_os = "dragonfly"))]
697 fn real_args_as_bytes() -> Vec<Vec<u8>> {
699 rt::args::clone().unwrap_or_else(|| vec![])
703 fn real_args() -> Vec<String> {
704 real_args_as_bytes().into_iter()
706 String::from_utf8_lossy(v.as_slice()).into_owned()
711 fn real_args() -> Vec<String> {
715 let mut nArgs: c_int = 0;
716 let lpArgCount: *mut c_int = &mut nArgs;
717 let lpCmdLine = unsafe { GetCommandLineW() };
718 let szArgList = unsafe { CommandLineToArgvW(lpCmdLine, lpArgCount) };
720 let args: Vec<_> = (0..nArgs as uint).map(|i| unsafe {
721 // Determine the length of this argument.
722 let ptr = *szArgList.offset(i as int);
724 while *ptr.offset(len as int) != 0 { len += 1; }
726 // Push it onto the list.
727 let ptr = ptr as *const u16;
728 let buf = slice::from_raw_buf(&ptr, len);
729 let opt_s = String::from_utf16(sys::os::truncate_utf16_at_nul(buf));
730 opt_s.ok().expect("CommandLineToArgvW returned invalid UTF-16")
734 LocalFree(szArgList as *mut c_void);
741 fn real_args_as_bytes() -> Vec<Vec<u8>> {
742 real_args().into_iter().map(|s| s.into_bytes()).collect()
745 type LPCWSTR = *const u16;
748 #[link_name="kernel32"]
750 fn GetCommandLineW() -> LPCWSTR;
751 fn LocalFree(ptr: *mut c_void);
755 #[link_name="shell32"]
757 fn CommandLineToArgvW(lpCmdLine: LPCWSTR,
758 pNumArgs: *mut c_int) -> *mut *mut u16;
761 /// Returns the arguments which this program was started with (normally passed
762 /// via the command line).
764 /// The first element is traditionally the path to the executable, but it can be
765 /// set to arbitrary text, and it may not even exist, so this property should not
766 /// be relied upon for security purposes.
768 /// The arguments are interpreted as utf-8, with invalid bytes replaced with \uFFFD.
769 /// See `String::from_utf8_lossy` for details.
775 /// // Prints each argument on a separate line
776 /// for argument in os::args().iter() {
777 /// println!("{}", argument);
780 pub fn args() -> Vec<String> {
784 /// Returns the arguments which this program was started with (normally passed
785 /// via the command line) as byte vectors.
786 pub fn args_as_bytes() -> Vec<Vec<u8>> {
790 #[cfg(target_os = "macos")]
792 // These functions are in crt_externs.h.
793 pub fn _NSGetArgc() -> *mut c_int;
794 pub fn _NSGetArgv() -> *mut *mut *mut c_char;
797 /// Returns the page size of the current architecture in bytes.
798 pub fn page_size() -> uint {
802 /// A memory mapped file or chunk of memory. This is a very system-specific
803 /// interface to the OS's memory mapping facilities (`mmap` on POSIX,
804 /// `VirtualAlloc`/`CreateFileMapping` on Windows). It makes no attempt at
805 /// abstracting platform differences, besides in error values returned. Consider
808 /// The memory map is released (unmapped) when the destructor is run, so don't
809 /// let it leave scope by accident if you want it to stick around.
810 #[allow(missing_copy_implementations)]
811 pub struct MemoryMap {
817 /// Type of memory map
818 #[allow(raw_pointer_derive)]
820 pub enum MemoryMapKind {
821 /// Virtual memory map. Usually used to change the permissions of a given
822 /// chunk of memory. Corresponds to `VirtualAlloc` on Windows.
824 /// Virtual memory map. Usually used to change the permissions of a given
825 /// chunk of memory, or for allocation. Corresponds to `VirtualAlloc` on
830 /// Options the memory map is created with
831 #[allow(raw_pointer_derive)]
834 /// The memory should be readable
836 /// The memory should be writable
838 /// The memory should be executable
840 /// Create a map for a specific address range. Corresponds to `MAP_FIXED` on
843 /// Create a memory mapping for a file with a given HANDLE.
846 /// Create a memory mapping for a file with a given fd.
849 /// When using `MapFd`, the start of the map is `uint` bytes from the start
852 /// On POSIX, this can be used to specify the default flags passed to
853 /// `mmap`. By default it uses `MAP_PRIVATE` and, if not using `MapFd`,
854 /// `MAP_ANON`. This will override both of those. This is platform-specific
855 /// (the exact values used) and ignored on Windows.
856 MapNonStandardFlags(c_int),
859 /// Possible errors when creating a map.
860 #[derive(Copy, Debug)]
862 /// # The following are POSIX-specific
864 /// fd was not open for reading or, if using `MapWritable`, was not open for
869 /// Either the address given by `MapAddr` or offset given by `MapOffset` was
870 /// not a multiple of `MemoryMap::granularity` (unaligned to page size).
872 /// With `MapFd`, the fd does not support mapping.
874 /// If using `MapAddr`, the address + `min_len` was outside of the process's
875 /// address space. If using `MapFd`, the target of the fd didn't have enough
876 /// resources to fulfill the request.
878 /// A zero-length map was requested. This is invalid according to
879 /// [POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/functions/mmap.html).
880 /// Not all platforms obey this, but this wrapper does.
882 /// Unrecognized error. The inner value is the unrecognized errno.
884 /// # The following are Windows-specific
886 /// Unsupported combination of protection flags
887 /// (`MapReadable`/`MapWritable`/`MapExecutable`).
889 /// When using `MapFd`, `MapOffset` was given (Windows does not support this
892 /// When using `MapFd`, there was already a mapping to the file.
894 /// Unrecognized error from `VirtualAlloc`. The inner value is the return
895 /// value of GetLastError.
896 ErrVirtualAlloc(uint),
897 /// Unrecognized error from `CreateFileMapping`. The inner value is the
898 /// return value of `GetLastError`.
899 ErrCreateFileMappingW(uint),
900 /// Unrecognized error from `MapViewOfFile`. The inner value is the return
901 /// value of `GetLastError`.
902 ErrMapViewOfFile(uint)
905 #[stable(feature = "rust1", since = "1.0.0")]
906 impl fmt::Display for MapError {
907 fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result {
908 let str = match *self {
909 ErrFdNotAvail => "fd not available for reading or writing",
910 ErrInvalidFd => "Invalid fd",
912 "Unaligned address, invalid flags, negative length or \
915 ErrNoMapSupport=> "File doesn't support mapping",
916 ErrNoMem => "Invalid address, or not enough available memory",
917 ErrUnsupProt => "Protection mode unsupported",
918 ErrUnsupOffset => "Offset in virtual memory mode is unsupported",
919 ErrAlreadyExists => "File mapping for specified file already exists",
920 ErrZeroLength => "Zero-length mapping not allowed",
921 ErrUnknown(code) => {
922 return write!(out, "Unknown error = {}", code)
924 ErrVirtualAlloc(code) => {
925 return write!(out, "VirtualAlloc failure = {}", code)
927 ErrCreateFileMappingW(code) => {
928 return write!(out, "CreateFileMappingW failure = {}", code)
930 ErrMapViewOfFile(code) => {
931 return write!(out, "MapViewOfFile failure = {}", code)
934 write!(out, "{}", str)
938 impl Error for MapError {
939 fn description(&self) -> &str { "memory map error" }
942 // Round up `from` to be divisible by `to`
943 fn round_up(from: uint, to: uint) -> uint {
944 let r = if from % to == 0 {
947 from + to - (from % to)
958 /// Create a new mapping with the given `options`, at least `min_len` bytes
959 /// long. `min_len` must be greater than zero; see the note on
961 pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
965 return Err(ErrZeroLength)
967 let mut addr: *const u8 = ptr::null();
969 let mut flags = libc::MAP_PRIVATE;
972 let mut custom_flags = false;
973 let len = round_up(min_len, page_size());
975 for &o in options.iter() {
977 MapReadable => { prot |= libc::PROT_READ; },
978 MapWritable => { prot |= libc::PROT_WRITE; },
979 MapExecutable => { prot |= libc::PROT_EXEC; },
981 flags |= libc::MAP_FIXED;
985 flags |= libc::MAP_FILE;
988 MapOffset(offset_) => { offset = offset_ as off_t; },
989 MapNonStandardFlags(f) => { custom_flags = true; flags = f },
992 if fd == -1 && !custom_flags { flags |= libc::MAP_ANON; }
995 libc::mmap(addr as *mut c_void, len as libc::size_t, prot, flags,
998 if r == libc::MAP_FAILED {
999 Err(match errno() as c_int {
1000 libc::EACCES => ErrFdNotAvail,
1001 libc::EBADF => ErrInvalidFd,
1002 libc::EINVAL => ErrUnaligned,
1003 libc::ENODEV => ErrNoMapSupport,
1004 libc::ENOMEM => ErrNoMem,
1005 code => ErrUnknown(code as int)
1014 MapFile(ptr::null())
1020 /// Granularity that the offset or address must be for `MapOffset` and
1021 /// `MapAddr` respectively.
1022 pub fn granularity() -> uint {
1028 impl Drop for MemoryMap {
1029 /// Unmap the mapping. Panics the task if `munmap` panics.
1030 fn drop(&mut self) {
1031 if self.len == 0 { /* workaround for dummy_stack */ return; }
1034 // `munmap` only panics due to logic errors
1035 libc::munmap(self.data as *mut c_void, self.len as libc::size_t);
1042 /// Create a new mapping with the given `options`, at least `min_len` bytes long.
1043 pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
1044 use libc::types::os::arch::extra::{LPVOID, DWORD, SIZE_T, HANDLE};
1046 let mut lpAddress: LPVOID = ptr::null_mut();
1047 let mut readable = false;
1048 let mut writable = false;
1049 let mut executable = false;
1050 let mut handle: HANDLE = libc::INVALID_HANDLE_VALUE;
1051 let mut offset: uint = 0;
1052 let len = round_up(min_len, page_size());
1054 for &o in options.iter() {
1056 MapReadable => { readable = true; },
1057 MapWritable => { writable = true; },
1058 MapExecutable => { executable = true; }
1059 MapAddr(addr_) => { lpAddress = addr_ as LPVOID; },
1060 MapFd(handle_) => { handle = handle_; },
1061 MapOffset(offset_) => { offset = offset_; },
1062 MapNonStandardFlags(..) => {}
1066 let flProtect = match (executable, readable, writable) {
1067 (false, false, false) if handle == libc::INVALID_HANDLE_VALUE => libc::PAGE_NOACCESS,
1068 (false, true, false) => libc::PAGE_READONLY,
1069 (false, true, true) => libc::PAGE_READWRITE,
1070 (true, false, false) if handle == libc::INVALID_HANDLE_VALUE => libc::PAGE_EXECUTE,
1071 (true, true, false) => libc::PAGE_EXECUTE_READ,
1072 (true, true, true) => libc::PAGE_EXECUTE_READWRITE,
1073 _ => return Err(ErrUnsupProt)
1076 if handle == libc::INVALID_HANDLE_VALUE {
1078 return Err(ErrUnsupOffset);
1081 libc::VirtualAlloc(lpAddress,
1083 libc::MEM_COMMIT | libc::MEM_RESERVE,
1087 0 => Err(ErrVirtualAlloc(errno())),
1095 let dwDesiredAccess = match (executable, readable, writable) {
1096 (false, true, false) => libc::FILE_MAP_READ,
1097 (false, true, true) => libc::FILE_MAP_WRITE,
1098 (true, true, false) => libc::FILE_MAP_READ | libc::FILE_MAP_EXECUTE,
1099 (true, true, true) => libc::FILE_MAP_WRITE | libc::FILE_MAP_EXECUTE,
1100 _ => return Err(ErrUnsupProt) // Actually, because of the check above,
1101 // we should never get here.
1105 let mapping = libc::CreateFileMappingW(hFile,
1111 if mapping == ptr::null_mut() {
1112 return Err(ErrCreateFileMappingW(errno()));
1114 if errno() as c_int == libc::ERROR_ALREADY_EXISTS {
1115 return Err(ErrAlreadyExists);
1117 let r = libc::MapViewOfFile(mapping,
1119 ((len as u64) >> 32) as DWORD,
1120 (offset & 0xffff_ffff) as DWORD,
1123 0 => Err(ErrMapViewOfFile(errno())),
1127 kind: MapFile(mapping as *const u8)
1134 /// Granularity of MapAddr() and MapOffset() parameter values.
1135 /// This may be greater than the value returned by page_size().
1136 pub fn granularity() -> uint {
1139 let mut info = mem::zeroed();
1140 libc::GetSystemInfo(&mut info);
1142 return info.dwAllocationGranularity as uint;
1148 impl Drop for MemoryMap {
1149 /// Unmap the mapping. Panics the task if any of `VirtualFree`,
1150 /// `UnmapViewOfFile`, or `CloseHandle` fail.
1151 fn drop(&mut self) {
1152 use libc::types::os::arch::extra::{LPCVOID, HANDLE};
1153 use libc::consts::os::extra::FALSE;
1154 if self.len == 0 { return }
1159 if libc::VirtualFree(self.data as *mut c_void, 0,
1160 libc::MEM_RELEASE) == 0 {
1161 println!("VirtualFree failed: {}", errno());
1164 MapFile(mapping) => {
1165 if libc::UnmapViewOfFile(self.data as LPCVOID) == FALSE {
1166 println!("UnmapViewOfFile failed: {}", errno());
1168 if libc::CloseHandle(mapping as HANDLE) == FALSE {
1169 println!("CloseHandle failed: {}", errno());
1178 /// Returns the pointer to the memory created or modified by this map.
1179 pub fn data(&self) -> *mut u8 { self.data }
1180 /// Returns the number of bytes this map applies to.
1181 pub fn len(&self) -> uint { self.len }
1182 /// Returns the type of mapping this represents.
1183 pub fn kind(&self) -> MemoryMapKind { self.kind }
1186 #[cfg(target_os = "linux")]
1188 pub use os::arch_consts::ARCH;
1190 pub const FAMILY: &'static str = "unix";
1192 /// A string describing the specific operating system in use: in this
1194 pub const SYSNAME: &'static str = "linux";
1196 /// Specifies the filename prefix used for shared libraries on this
1197 /// platform: in this case, `lib`.
1198 pub const DLL_PREFIX: &'static str = "lib";
1200 /// Specifies the filename suffix used for shared libraries on this
1201 /// platform: in this case, `.so`.
1202 pub const DLL_SUFFIX: &'static str = ".so";
1204 /// Specifies the file extension used for shared libraries on this
1205 /// platform that goes after the dot: in this case, `so`.
1206 pub const DLL_EXTENSION: &'static str = "so";
1208 /// Specifies the filename suffix used for executable binaries on this
1209 /// platform: in this case, the empty string.
1210 pub const EXE_SUFFIX: &'static str = "";
1212 /// Specifies the file extension, if any, used for executable binaries
1213 /// on this platform: in this case, the empty string.
1214 pub const EXE_EXTENSION: &'static str = "";
1217 #[cfg(target_os = "macos")]
1219 pub use os::arch_consts::ARCH;
1221 pub const FAMILY: &'static str = "unix";
1223 /// A string describing the specific operating system in use: in this
1225 pub const SYSNAME: &'static str = "macos";
1227 /// Specifies the filename prefix used for shared libraries on this
1228 /// platform: in this case, `lib`.
1229 pub const DLL_PREFIX: &'static str = "lib";
1231 /// Specifies the filename suffix used for shared libraries on this
1232 /// platform: in this case, `.dylib`.
1233 pub const DLL_SUFFIX: &'static str = ".dylib";
1235 /// Specifies the file extension used for shared libraries on this
1236 /// platform that goes after the dot: in this case, `dylib`.
1237 pub const DLL_EXTENSION: &'static str = "dylib";
1239 /// Specifies the filename suffix used for executable binaries on this
1240 /// platform: in this case, the empty string.
1241 pub const EXE_SUFFIX: &'static str = "";
1243 /// Specifies the file extension, if any, used for executable binaries
1244 /// on this platform: in this case, the empty string.
1245 pub const EXE_EXTENSION: &'static str = "";
1248 #[cfg(target_os = "ios")]
1250 pub use os::arch_consts::ARCH;
1252 pub const FAMILY: &'static str = "unix";
1254 /// A string describing the specific operating system in use: in this
1256 pub const SYSNAME: &'static str = "ios";
1258 /// Specifies the filename suffix used for executable binaries on this
1259 /// platform: in this case, the empty string.
1260 pub const EXE_SUFFIX: &'static str = "";
1262 /// Specifies the file extension, if any, used for executable binaries
1263 /// on this platform: in this case, the empty string.
1264 pub const EXE_EXTENSION: &'static str = "";
1267 #[cfg(target_os = "freebsd")]
1269 pub use os::arch_consts::ARCH;
1271 pub const FAMILY: &'static str = "unix";
1273 /// A string describing the specific operating system in use: in this
1274 /// case, `freebsd`.
1275 pub const SYSNAME: &'static str = "freebsd";
1277 /// Specifies the filename prefix used for shared libraries on this
1278 /// platform: in this case, `lib`.
1279 pub const DLL_PREFIX: &'static str = "lib";
1281 /// Specifies the filename suffix used for shared libraries on this
1282 /// platform: in this case, `.so`.
1283 pub const DLL_SUFFIX: &'static str = ".so";
1285 /// Specifies the file extension used for shared libraries on this
1286 /// platform that goes after the dot: in this case, `so`.
1287 pub const DLL_EXTENSION: &'static str = "so";
1289 /// Specifies the filename suffix used for executable binaries on this
1290 /// platform: in this case, the empty string.
1291 pub const EXE_SUFFIX: &'static str = "";
1293 /// Specifies the file extension, if any, used for executable binaries
1294 /// on this platform: in this case, the empty string.
1295 pub const EXE_EXTENSION: &'static str = "";
1298 #[cfg(target_os = "dragonfly")]
1300 pub use os::arch_consts::ARCH;
1302 pub const FAMILY: &'static str = "unix";
1304 /// A string describing the specific operating system in use: in this
1305 /// case, `dragonfly`.
1306 pub const SYSNAME: &'static str = "dragonfly";
1308 /// Specifies the filename prefix used for shared libraries on this
1309 /// platform: in this case, `lib`.
1310 pub const DLL_PREFIX: &'static str = "lib";
1312 /// Specifies the filename suffix used for shared libraries on this
1313 /// platform: in this case, `.so`.
1314 pub const DLL_SUFFIX: &'static str = ".so";
1316 /// Specifies the file extension used for shared libraries on this
1317 /// platform that goes after the dot: in this case, `so`.
1318 pub const DLL_EXTENSION: &'static str = "so";
1320 /// Specifies the filename suffix used for executable binaries on this
1321 /// platform: in this case, the empty string.
1322 pub const EXE_SUFFIX: &'static str = "";
1324 /// Specifies the file extension, if any, used for executable binaries
1325 /// on this platform: in this case, the empty string.
1326 pub const EXE_EXTENSION: &'static str = "";
1329 #[cfg(target_os = "android")]
1331 pub use os::arch_consts::ARCH;
1333 pub const FAMILY: &'static str = "unix";
1335 /// A string describing the specific operating system in use: in this
1336 /// case, `android`.
1337 pub const SYSNAME: &'static str = "android";
1339 /// Specifies the filename prefix used for shared libraries on this
1340 /// platform: in this case, `lib`.
1341 pub const DLL_PREFIX: &'static str = "lib";
1343 /// Specifies the filename suffix used for shared libraries on this
1344 /// platform: in this case, `.so`.
1345 pub const DLL_SUFFIX: &'static str = ".so";
1347 /// Specifies the file extension used for shared libraries on this
1348 /// platform that goes after the dot: in this case, `so`.
1349 pub const DLL_EXTENSION: &'static str = "so";
1351 /// Specifies the filename suffix used for executable binaries on this
1352 /// platform: in this case, the empty string.
1353 pub const EXE_SUFFIX: &'static str = "";
1355 /// Specifies the file extension, if any, used for executable binaries
1356 /// on this platform: in this case, the empty string.
1357 pub const EXE_EXTENSION: &'static str = "";
1360 #[cfg(target_os = "windows")]
1362 pub use os::arch_consts::ARCH;
1364 pub const FAMILY: &'static str = "windows";
1366 /// A string describing the specific operating system in use: in this
1367 /// case, `windows`.
1368 pub const SYSNAME: &'static str = "windows";
1370 /// Specifies the filename prefix used for shared libraries on this
1371 /// platform: in this case, the empty string.
1372 pub const DLL_PREFIX: &'static str = "";
1374 /// Specifies the filename suffix used for shared libraries on this
1375 /// platform: in this case, `.dll`.
1376 pub const DLL_SUFFIX: &'static str = ".dll";
1378 /// Specifies the file extension used for shared libraries on this
1379 /// platform that goes after the dot: in this case, `dll`.
1380 pub const DLL_EXTENSION: &'static str = "dll";
1382 /// Specifies the filename suffix used for executable binaries on this
1383 /// platform: in this case, `.exe`.
1384 pub const EXE_SUFFIX: &'static str = ".exe";
1386 /// Specifies the file extension, if any, used for executable binaries
1387 /// on this platform: in this case, `exe`.
1388 pub const EXE_EXTENSION: &'static str = "exe";
1391 #[cfg(target_arch = "x86")]
1393 pub const ARCH: &'static str = "x86";
1396 #[cfg(target_arch = "x86_64")]
1398 pub const ARCH: &'static str = "x86_64";
1401 #[cfg(target_arch = "arm")]
1403 pub const ARCH: &'static str = "arm";
1406 #[cfg(target_arch = "aarch64")]
1408 pub const ARCH: &'static str = "aarch64";
1411 #[cfg(target_arch = "mips")]
1413 pub const ARCH: &'static str = "mips";
1416 #[cfg(target_arch = "mipsel")]
1418 pub const ARCH: &'static str = "mipsel";
1421 #[cfg(target_arch = "powerpc")]
1423 pub const ARCH: &'static str = "powerpc";
1431 use os::{env, getcwd, getenv, make_absolute};
1432 use os::{split_paths, join_paths, setenv, unsetenv};
1438 pub fn last_os_error() {
1439 debug!("{}", os::last_os_error());
1442 fn make_rand_name() -> String {
1443 let mut rng = rand::thread_rng();
1444 let n = format!("TEST{}", rng.gen_ascii_chars().take(10u)
1445 .collect::<String>());
1446 assert!(getenv(n.as_slice()).is_none());
1451 fn test_num_cpus() {
1452 assert!(os::num_cpus() > 0);
1457 let n = make_rand_name();
1458 setenv(n.as_slice(), "VALUE");
1459 assert_eq!(getenv(n.as_slice()), Some("VALUE".to_string()));
1463 fn test_unsetenv() {
1464 let n = make_rand_name();
1465 setenv(n.as_slice(), "VALUE");
1466 unsetenv(n.as_slice());
1467 assert_eq!(getenv(n.as_slice()), None);
1472 fn test_setenv_overwrite() {
1473 let n = make_rand_name();
1474 setenv(n.as_slice(), "1");
1475 setenv(n.as_slice(), "2");
1476 assert_eq!(getenv(n.as_slice()), Some("2".to_string()));
1477 setenv(n.as_slice(), "");
1478 assert_eq!(getenv(n.as_slice()), Some("".to_string()));
1481 // Windows GetEnvironmentVariable requires some extra work to make sure
1482 // the buffer the variable is copied into is the right size
1485 fn test_getenv_big() {
1486 let mut s = "".to_string();
1489 s.push_str("aaaaaaaaaa");
1492 let n = make_rand_name();
1493 setenv(n.as_slice(), s.as_slice());
1494 debug!("{}", s.clone());
1495 assert_eq!(getenv(n.as_slice()), Some(s));
1499 fn test_self_exe_name() {
1500 let path = os::self_exe_name();
1501 assert!(path.is_some());
1502 let path = path.unwrap();
1503 debug!("{}", path.display());
1505 // Hard to test this function
1506 assert!(path.is_absolute());
1510 fn test_self_exe_path() {
1511 let path = os::self_exe_path();
1512 assert!(path.is_some());
1513 let path = path.unwrap();
1514 debug!("{}", path.display());
1516 // Hard to test this function
1517 assert!(path.is_absolute());
1522 fn test_env_getenv() {
1524 assert!(e.len() > 0u);
1526 let (n, v) = (*p).clone();
1528 let v2 = getenv(n.as_slice());
1529 // MingW seems to set some funky environment variables like
1530 // "=C:=C:\MinGW\msys\1.0\bin" and "!::=::\" that are returned
1531 // from env() but not visible from getenv().
1532 assert!(v2.is_none() || v2 == Some(v));
1537 fn test_env_set_get_huge() {
1538 let n = make_rand_name();
1539 let s = repeat("x").take(10000).collect::<String>();
1540 setenv(n.as_slice(), s.as_slice());
1541 assert_eq!(getenv(n.as_slice()), Some(s));
1542 unsetenv(n.as_slice());
1543 assert_eq!(getenv(n.as_slice()), None);
1547 fn test_env_setenv() {
1548 let n = make_rand_name();
1551 setenv(n.as_slice(), "VALUE");
1552 assert!(!e.contains(&(n.clone(), "VALUE".to_string())));
1555 assert!(e.contains(&(n, "VALUE".to_string())));
1560 assert!((!Path::new("test-path").is_absolute()));
1562 let cwd = getcwd().unwrap();
1563 debug!("Current working directory: {}", cwd.display());
1565 debug!("{}", make_absolute(&Path::new("test-path")).unwrap().display());
1566 debug!("{}", make_absolute(&Path::new("/usr/bin")).unwrap().display());
1572 let oldhome = getenv("HOME");
1574 setenv("HOME", "/home/MountainView");
1575 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1578 assert!(os::homedir().is_none());
1580 for s in oldhome.iter() {
1581 setenv("HOME", s.as_slice());
1589 let oldhome = getenv("HOME");
1590 let olduserprofile = getenv("USERPROFILE");
1593 setenv("USERPROFILE", "");
1595 assert!(os::homedir().is_none());
1597 setenv("HOME", "/home/MountainView");
1598 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1602 setenv("USERPROFILE", "/home/MountainView");
1603 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1605 setenv("HOME", "/home/MountainView");
1606 setenv("USERPROFILE", "/home/PaloAlto");
1607 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1609 for s in oldhome.iter() {
1610 setenv("HOME", s.as_slice());
1612 for s in olduserprofile.iter() {
1613 setenv("USERPROFILE", s.as_slice());
1618 fn memory_map_rw() {
1619 use result::Result::{Ok, Err};
1621 let chunk = match os::MemoryMap::new(16, &[
1622 os::MapOption::MapReadable,
1623 os::MapOption::MapWritable
1626 Err(msg) => panic!("{:?}", msg)
1628 assert!(chunk.len >= 16);
1632 assert!(*chunk.data == 0xBE);
1637 fn memory_map_file() {
1640 use old_io::fs::{File, unlink};
1641 use old_io::SeekStyle::SeekSet;
1642 use old_io::FileMode::Open;
1643 use old_io::FileAccess::ReadWrite;
1645 #[cfg(not(windows))]
1646 fn get_fd(file: &File) -> libc::c_int {
1647 use os::unix::AsRawFd;
1652 fn get_fd(file: &File) -> libc::HANDLE {
1653 use os::windows::AsRawHandle;
1654 file.as_raw_handle()
1657 let mut path = tmpdir();
1658 path.push("mmap_file.tmp");
1659 let size = MemoryMap::granularity() * 2;
1660 let mut file = File::open_mode(&path, Open, ReadWrite).unwrap();
1661 file.seek(size as i64, SeekSet).unwrap();
1662 file.write_u8(0).unwrap();
1664 let chunk = MemoryMap::new(size / 2, &[
1665 MapOption::MapReadable,
1666 MapOption::MapWritable,
1667 MapOption::MapFd(get_fd(&file)),
1668 MapOption::MapOffset(size / 2)
1670 assert!(chunk.len > 0);
1674 assert!(*chunk.data == 0xbe);
1678 unlink(&path).unwrap();
1683 fn split_paths_windows() {
1684 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
1685 split_paths(unparsed) ==
1686 parsed.iter().map(|s| Path::new(*s)).collect::<Vec<_>>()
1689 assert!(check_parse("", &mut [""]));
1690 assert!(check_parse(r#""""#, &mut [""]));
1691 assert!(check_parse(";;", &mut ["", "", ""]));
1692 assert!(check_parse(r"c:\", &mut [r"c:\"]));
1693 assert!(check_parse(r"c:\;", &mut [r"c:\", ""]));
1694 assert!(check_parse(r"c:\;c:\Program Files\",
1695 &mut [r"c:\", r"c:\Program Files\"]));
1696 assert!(check_parse(r#"c:\;c:\"foo"\"#, &mut [r"c:\", r"c:\foo\"]));
1697 assert!(check_parse(r#"c:\;c:\"foo;bar"\;c:\baz"#,
1698 &mut [r"c:\", r"c:\foo;bar\", r"c:\baz"]));
1703 fn split_paths_unix() {
1704 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
1705 split_paths(unparsed) ==
1706 parsed.iter().map(|s| Path::new(*s)).collect::<Vec<_>>()
1709 assert!(check_parse("", &mut [""]));
1710 assert!(check_parse("::", &mut ["", "", ""]));
1711 assert!(check_parse("/", &mut ["/"]));
1712 assert!(check_parse("/:", &mut ["/", ""]));
1713 assert!(check_parse("/:/usr/local", &mut ["/", "/usr/local"]));
1718 fn join_paths_unix() {
1719 fn test_eq(input: &[&str], output: &str) -> bool {
1720 join_paths(input).unwrap() == output.as_bytes()
1723 assert!(test_eq(&[], ""));
1724 assert!(test_eq(&["/bin", "/usr/bin", "/usr/local/bin"],
1725 "/bin:/usr/bin:/usr/local/bin"));
1726 assert!(test_eq(&["", "/bin", "", "", "/usr/bin", ""],
1727 ":/bin:::/usr/bin:"));
1728 assert!(join_paths(&["/te:st"]).is_err());
1733 fn join_paths_windows() {
1734 fn test_eq(input: &[&str], output: &str) -> bool {
1735 join_paths(input).unwrap() == output.as_bytes()
1738 assert!(test_eq(&[], ""));
1739 assert!(test_eq(&[r"c:\windows", r"c:\"],
1740 r"c:\windows;c:\"));
1741 assert!(test_eq(&["", r"c:\windows", "", "", r"c:\", ""],
1742 r";c:\windows;;;c:\;"));
1743 assert!(test_eq(&[r"c:\te;st", r"c:\"],
1744 r#""c:\te;st";c:\"#));
1745 assert!(join_paths(&[r#"c:\te"st"#]).is_err());
1748 // More recursive_mkdir tests are in extra::tempfile