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")]
28 #![deprecated(since = "1.0.0", reason = "replaced with std::env APIs")]
30 #![allow(missing_docs)]
31 #![allow(non_snake_case)]
32 #![allow(unused_imports)]
35 use self::MemoryMapKind::*;
36 use self::MapOption::*;
37 use self::MapError::*;
42 use error::{FromError, Error};
43 use ffi::{OsString, OsStr};
45 use iter::{Iterator, IteratorExt};
46 use libc::{c_void, c_int, c_char};
48 use marker::{Copy, Send};
49 use old_io::{IoResult, IoError};
50 use ops::{Drop, FnOnce};
51 use option::Option::{Some, None};
53 use old_path::{Path, GenericPath, BytesContainer};
54 use path::{self, PathBuf};
57 use result::Result::{Err, Ok};
59 use slice::{AsSlice, SliceExt};
60 use str::{Str, StrExt};
62 use string::{String, ToString};
63 use sync::atomic::{AtomicIsize, ATOMIC_ISIZE_INIT, Ordering};
64 use sys::os as os_imp;
68 #[cfg(unix)] use ffi::{self, CString};
70 #[cfg(unix)] pub use sys::ext as unix;
71 #[cfg(windows)] pub use sys::ext as windows;
73 fn err2old(new: ::io::Error) -> IoError {
75 kind: ::old_io::OtherIoError,
77 detail: Some(new.to_string()),
82 fn path2new(path: &Path) -> PathBuf {
83 PathBuf::new(path.as_str().unwrap())
86 fn path2new(path: &Path) -> PathBuf {
87 use os::unix::prelude::*;
88 PathBuf::new(<OsStr as OsStrExt>::from_bytes(path.as_vec()))
92 fn path2old(path: &path::Path) -> Path {
93 use os::unix::prelude::*;
95 Path::new(path.as_os_str().as_bytes())
98 fn path2old(path: &path::Path) -> Path {
99 Path::new(path.to_str().unwrap())
102 /// Get the number of cores available
103 pub fn num_cpus() -> uint {
105 return rust_get_num_cpus() as uint;
109 fn rust_get_num_cpus() -> libc::uintptr_t;
113 pub const TMPBUF_SZ : uint = 1000;
115 /// Returns the current working directory as a `Path`.
119 /// Returns an `Err` if the current working directory value is invalid.
122 /// * Current directory does not exist.
123 /// * There are insufficient permissions to access the current directory.
124 /// * The internal buffer is not large enough to hold the path.
131 /// // We assume that we are in a valid directory.
132 /// let current_working_directory = os::getcwd().unwrap();
133 /// println!("The current directory is {:?}", current_working_directory.display());
135 #[unstable(feature = "os")]
136 pub fn getcwd() -> IoResult<Path> {
137 env::current_dir().map_err(err2old).map(|s| path2old(&s))
140 /// Returns a vector of (variable, value) pairs, for all the environment
141 /// variables of the current process.
143 /// Invalid UTF-8 bytes are replaced with \uFFFD. See `String::from_utf8_lossy()`
151 /// // We will iterate through the references to the element returned by os::env();
152 /// for &(ref key, ref value) in os::env().iter() {
153 /// println!("'{}': '{}'", key, value );
156 #[deprecated(since = "1.0.0", reason = "use env::vars instead")]
157 #[unstable(feature = "os")]
158 pub fn env() -> Vec<(String,String)> {
159 env::vars_os().map(|(k, v)| {
160 (k.to_string_lossy().into_owned(), v.to_string_lossy().into_owned())
164 /// Returns a vector of (variable, value) byte-vector pairs for all the
165 /// environment variables of the current process.
166 #[deprecated(since = "1.0.0", reason = "use env::vars_os instead")]
167 #[unstable(feature = "os")]
168 pub fn env_as_bytes() -> Vec<(Vec<u8>, Vec<u8>)> {
169 env::vars_os().map(|(k, v)| (byteify(k), byteify(v))).collect()
172 /// Fetches the environment variable `n` from the current process, returning
173 /// None if the variable isn't set.
175 /// Any invalid UTF-8 bytes in the value are replaced by \uFFFD. See
176 /// `String::from_utf8_lossy()` for details.
180 /// Panics if `n` has any interior NULs.
187 /// let key = "HOME";
188 /// match os::getenv(key) {
189 /// Some(val) => println!("{}: {}", key, val),
190 /// None => println!("{} is not defined in the environment.", key)
193 #[deprecated(since = "1.0.0", reason = "use env::var instead")]
194 #[unstable(feature = "os")]
195 pub fn getenv(n: &str) -> Option<String> {
199 /// Fetches the environment variable `n` byte vector from the current process,
200 /// returning None if the variable isn't set.
204 /// Panics if `n` has any interior NULs.
205 #[deprecated(since = "1.0.0", reason = "use env::var_os instead")]
206 #[unstable(feature = "os")]
207 pub fn getenv_as_bytes(n: &str) -> Option<Vec<u8>> {
208 env::var_os(n).map(byteify)
212 fn byteify(s: OsString) -> Vec<u8> {
217 fn byteify(s: OsString) -> Vec<u8> {
218 s.to_string_lossy().as_bytes().to_vec()
221 /// Sets the environment variable `n` to the value `v` for the currently running
230 /// os::setenv(key, "VALUE");
231 /// match os::getenv(key) {
232 /// Some(ref val) => println!("{}: {}", key, val),
233 /// None => println!("{} is not defined in the environment.", key)
236 #[deprecated(since = "1.0.0", reason = "renamed to env::set_var")]
237 #[unstable(feature = "os")]
238 pub fn setenv<T: BytesContainer>(n: &str, v: T) {
240 fn _setenv(n: &str, v: &[u8]) {
242 let v: OsString = OsStringExt::from_vec(v.to_vec());
247 fn _setenv(n: &str, v: &[u8]) {
248 let v = str::from_utf8(v).unwrap();
252 _setenv(n, v.container_as_bytes())
255 /// Remove a variable from the environment entirely.
256 #[deprecated(since = "1.0.0", reason = "renamed to env::remove_var")]
257 #[unstable(feature = "os")]
258 pub fn unsetenv(n: &str) {
262 /// Parses input according to platform conventions for the `PATH`
263 /// environment variable.
269 /// let key = "PATH";
270 /// match os::getenv_as_bytes(key) {
272 /// for path in os::split_paths(paths).iter() {
273 /// println!("'{}'", path.display());
276 /// None => println!("{} is not defined in the environment.", key)
279 #[unstable(feature = "os")]
280 pub fn split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> {
281 let b = unparsed.container_as_bytes();
282 let s = str::from_utf8(b).unwrap();
283 env::split_paths(s).map(|s| path2old(&s)).collect()
286 /// Joins a collection of `Path`s appropriately for the `PATH`
287 /// environment variable.
289 /// Returns a `Vec<u8>` on success, since `Path`s are not utf-8
290 /// encoded on all platforms.
292 /// Returns an `Err` (containing an error message) if one of the input
293 /// `Path`s contains an invalid character for constructing the `PATH`
294 /// variable (a double quote on Windows or a colon on Unix).
300 /// use std::old_path::Path;
302 /// let key = "PATH";
303 /// let mut paths = os::getenv_as_bytes(key).map_or(Vec::new(), os::split_paths);
304 /// paths.push(Path::new("/home/xyz/bin"));
305 /// os::setenv(key, os::join_paths(paths.as_slice()).unwrap());
307 #[unstable(feature = "os")]
308 pub fn join_paths<T: BytesContainer>(paths: &[T]) -> Result<Vec<u8>, &'static str> {
309 env::join_paths(paths.iter().map(|s| {
310 str::from_utf8(s.container_as_bytes()).unwrap()
312 s.to_string_lossy().into_owned().into_bytes()
313 }).map_err(|_| "failed to join paths")
316 /// A low-level OS in-memory pipe.
319 /// A file descriptor representing the reading end of the pipe. Data written
320 /// on the `out` file descriptor can be read from this file descriptor.
322 /// A file descriptor representing the write end of the pipe. Data written
323 /// to this file descriptor can be read from the `input` file descriptor.
327 /// Creates a new low-level OS in-memory pipe.
329 /// This function can fail to succeed if there are no more resources available
330 /// to allocate a pipe.
332 /// This function is also unsafe as there is no destructor associated with the
333 /// `Pipe` structure will return. If it is not arranged for the returned file
334 /// descriptors to be closed, the file descriptors will leak. For safe handling
335 /// of this scenario, use `std::old_io::PipeStream` instead.
336 pub unsafe fn pipe() -> IoResult<Pipe> {
337 let (reader, writer) = try!(sys::os::pipe());
339 reader: reader.unwrap(),
340 writer: writer.unwrap(),
344 /// Returns the proper dll filename for the given basename of a file
346 #[cfg(not(target_os="ios"))]
347 #[deprecated(since = "1.0.0", reason = "this function will be removed, use the constants directly")]
348 #[unstable(feature = "os")]
350 pub fn dll_filename(base: &str) -> String {
351 format!("{}{}{}", consts::DLL_PREFIX, base, consts::DLL_SUFFIX)
354 /// Optionally returns the filesystem path to the current executable which is
355 /// running but with the executable name.
362 /// match os::self_exe_name() {
363 /// Some(exe_path) => println!("Path of this executable is: {}", exe_path.display()),
364 /// None => println!("Unable to get the path of this executable!")
367 #[unstable(feature = "os")]
368 pub fn self_exe_name() -> Option<Path> {
369 env::current_exe().ok().map(|p| path2old(&p))
372 /// Optionally returns the filesystem path to the current executable which is
375 /// Like self_exe_name() but without the binary's name.
382 /// match os::self_exe_path() {
383 /// Some(exe_path) => println!("Executable's Path is: {}", exe_path.display()),
384 /// None => println!("Impossible to fetch the path of this executable.")
387 #[unstable(feature = "os")]
388 pub fn self_exe_path() -> Option<Path> {
389 env::current_exe().ok().map(|p| { let mut p = path2old(&p); p.pop(); p })
392 /// Optionally returns the path to the current user's home directory if known.
396 /// Returns the value of the 'HOME' environment variable if it is set
397 /// and not equal to the empty string.
401 /// Returns the value of the 'HOME' environment variable if it is
402 /// set and not equal to the empty string. Otherwise, returns the value of the
403 /// 'USERPROFILE' environment variable if it is set and not equal to the empty
411 /// match os::homedir() {
412 /// Some(ref p) => println!("{}", p.display()),
413 /// None => println!("Impossible to get your home dir!")
416 #[unstable(feature = "os")]
418 pub fn homedir() -> Option<Path> {
421 fn _homedir() -> Option<Path> {
427 fn _homedir() -> Option<Path> {
428 aux_homedir("HOME").or(aux_homedir("USERPROFILE"))
432 fn aux_homedir(home_name: &str) -> Option<Path> {
433 match getenv_as_bytes(home_name) {
435 if p.is_empty() { None } else { Path::new_opt(p) }
443 /// Returns the path to a temporary directory.
445 /// On Unix, returns the value of the 'TMPDIR' environment variable if it is
446 /// set, otherwise for non-Android it returns '/tmp'. If Android, since there
447 /// is no global temporary folder (it is usually allocated per-app), we return
448 /// '/data/local/tmp'.
450 /// On Windows, returns the value of, in order, the 'TMP', 'TEMP',
451 /// 'USERPROFILE' environment variable if any are set and not the empty
452 /// string. Otherwise, tmpdir returns the path to the Windows directory.
453 #[unstable(feature = "os")]
455 pub fn tmpdir() -> Path {
458 fn getenv_nonempty(v: &str) -> Option<Path> {
471 fn lookup() -> Path {
472 let default = if cfg!(target_os = "android") {
473 Path::new("/data/local/tmp")
478 getenv_nonempty("TMPDIR").unwrap_or(default)
482 fn lookup() -> Path {
483 getenv_nonempty("TMP").or(
484 getenv_nonempty("TEMP").or(
485 getenv_nonempty("USERPROFILE").or(
486 getenv_nonempty("WINDIR")))).unwrap_or(Path::new("C:\\Windows"))
490 /// Convert a relative path to an absolute path
492 /// If the given path is relative, return it prepended with the current working
493 /// directory. If the given path is already an absolute path, return it
499 /// use std::old_path::Path;
501 /// // Assume we're in a path like /home/someuser
502 /// let rel_path = Path::new("..");
503 /// let abs_path = os::make_absolute(&rel_path).unwrap();
504 /// println!("The absolute path is {}", abs_path.display());
505 /// // Prints "The absolute path is /home"
507 // NB: this is here rather than in path because it is a form of environment
508 // querying; what it does depends on the process working directory, not just
510 #[deprecated(since = "1.0.0", reason = "use env::current_dir + .join directly")]
511 #[unstable(feature = "os")]
512 pub fn make_absolute(p: &Path) -> IoResult<Path> {
516 env::current_dir().map_err(err2old).map(|cwd| {
517 let mut cwd = path2old(&cwd);
524 /// Changes the current working directory to the specified path, returning
525 /// whether the change was completed successfully or not.
530 /// use std::old_path::Path;
532 /// let root = Path::new("/");
533 /// assert!(os::change_dir(&root).is_ok());
534 /// println!("Successfully changed working directory to {}!", root.display());
536 #[unstable(feature = "os")]
537 pub fn change_dir(p: &Path) -> IoResult<()> {
538 sys::os::chdir(&path2new(p)).map_err(err2old)
541 /// Returns the platform-specific value of errno
542 pub fn errno() -> i32 {
543 sys::os::errno() as i32
546 /// Return the string corresponding to an `errno()` value of `errnum`.
552 /// // Same as println!("{}", last_os_error());
553 /// println!("{}", os::error_string(os::errno() as i32));
555 pub fn error_string(errnum: i32) -> String {
556 return sys::os::error_string(errnum);
559 /// Get a string representing the platform-dependent last error
560 pub fn last_os_error() -> String {
561 error_string(errno())
564 /// Sets the process exit code
566 /// Sets the exit code returned by the process if all supervised tasks
567 /// terminate successfully (without panicking). If the current root task panics
568 /// and is supervised by the scheduler then any user-specified exit status is
569 /// ignored and the process exits with the default panic status.
571 /// Note that this is not synchronized against modifications of other threads.
572 #[deprecated(since = "1.0.0", reason = "renamed to env::set_exit_status")]
573 #[unstable(feature = "os")]
574 pub fn set_exit_status(code: int) {
575 env::set_exit_status(code as i32)
578 /// Fetches the process's current exit code. This defaults to 0 and can change
579 /// by calling `set_exit_status`.
580 #[deprecated(since = "1.0.0", reason = "renamed to env::get_exit_status")]
581 #[unstable(feature = "os")]
582 pub fn get_exit_status() -> int {
583 env::get_exit_status() as isize
586 #[cfg(target_os = "macos")]
587 unsafe fn load_argc_and_argv(argc: int,
588 argv: *const *const c_char) -> Vec<Vec<u8>> {
593 CStr::from_ptr(*argv.offset(i)).to_bytes().to_vec()
597 /// Returns the command line arguments
599 /// Returns a list of the command line arguments.
600 #[cfg(target_os = "macos")]
601 fn real_args_as_bytes() -> Vec<Vec<u8>> {
603 let (argc, argv) = (*_NSGetArgc() as int,
604 *_NSGetArgv() as *const *const c_char);
605 load_argc_and_argv(argc, argv)
609 // As _NSGetArgc and _NSGetArgv aren't mentioned in iOS docs
610 // and use underscores in their names - they're most probably
611 // are considered private and therefore should be avoided
612 // Here is another way to get arguments using Objective C
615 // In general it looks like:
617 // let args = [[NSProcessInfo processInfo] arguments]
618 // for i in 0..[args count]
619 // res.push([args objectAtIndex:i])
621 #[cfg(target_os = "ios")]
622 fn real_args_as_bytes() -> Vec<Vec<u8>> {
627 #[link(name = "objc")]
629 fn sel_registerName(name: *const libc::c_uchar) -> Sel;
630 fn objc_msgSend(obj: NsId, sel: Sel, ...) -> NsId;
631 fn objc_getClass(class_name: *const libc::c_uchar) -> NsId;
634 #[link(name = "Foundation", kind = "framework")]
637 type Sel = *const libc::c_void;
638 type NsId = *const libc::c_void;
640 let mut res = Vec::new();
643 let processInfoSel = sel_registerName("processInfo\0".as_ptr());
644 let argumentsSel = sel_registerName("arguments\0".as_ptr());
645 let utf8Sel = sel_registerName("UTF8String\0".as_ptr());
646 let countSel = sel_registerName("count\0".as_ptr());
647 let objectAtSel = sel_registerName("objectAtIndex:\0".as_ptr());
649 let klass = objc_getClass("NSProcessInfo\0".as_ptr());
650 let info = objc_msgSend(klass, processInfoSel);
651 let args = objc_msgSend(info, argumentsSel);
653 let cnt: int = mem::transmute(objc_msgSend(args, countSel));
655 let tmp = objc_msgSend(args, objectAtSel, i);
656 let utf_c_str: *const libc::c_char =
657 mem::transmute(objc_msgSend(tmp, utf8Sel));
658 res.push(CStr::from_ptr(utf_c_str).to_bytes().to_vec());
665 #[cfg(any(target_os = "linux",
666 target_os = "android",
667 target_os = "freebsd",
668 target_os = "dragonfly",
669 target_os = "bitrig",
670 target_os = "openbsd"))]
671 fn real_args_as_bytes() -> Vec<Vec<u8>> {
673 rt::args::clone().unwrap_or_else(|| vec![])
677 fn real_args() -> Vec<String> {
678 real_args_as_bytes().into_iter()
680 String::from_utf8_lossy(&v).into_owned()
685 fn real_args() -> Vec<String> {
689 let mut nArgs: c_int = 0;
690 let lpArgCount: *mut c_int = &mut nArgs;
691 let lpCmdLine = unsafe { GetCommandLineW() };
692 let szArgList = unsafe { CommandLineToArgvW(lpCmdLine, lpArgCount) };
694 let args: Vec<_> = (0..nArgs as uint).map(|i| unsafe {
695 // Determine the length of this argument.
696 let ptr = *szArgList.offset(i as int);
698 while *ptr.offset(len as int) != 0 { len += 1; }
700 // Push it onto the list.
701 let ptr = ptr as *const u16;
702 let buf = slice::from_raw_parts(ptr, len);
703 let opt_s = String::from_utf16(sys::truncate_utf16_at_nul(buf));
704 opt_s.ok().expect("CommandLineToArgvW returned invalid UTF-16")
708 LocalFree(szArgList as *mut c_void);
715 fn real_args_as_bytes() -> Vec<Vec<u8>> {
716 real_args().into_iter().map(|s| s.into_bytes()).collect()
719 type LPCWSTR = *const u16;
722 #[link_name="kernel32"]
724 fn GetCommandLineW() -> LPCWSTR;
725 fn LocalFree(ptr: *mut c_void);
729 #[link_name="shell32"]
731 fn CommandLineToArgvW(lpCmdLine: LPCWSTR,
732 pNumArgs: *mut c_int) -> *mut *mut u16;
735 /// Returns the arguments which this program was started with (normally passed
736 /// via the command line).
738 /// The first element is traditionally the path to the executable, but it can be
739 /// set to arbitrary text, and it may not even exist, so this property should not
740 /// be relied upon for security purposes.
742 /// The arguments are interpreted as utf-8, with invalid bytes replaced with \uFFFD.
743 /// See `String::from_utf8_lossy` for details.
749 /// // Prints each argument on a separate line
750 /// for argument in os::args().iter() {
751 /// println!("{}", argument);
754 #[deprecated(since = "1.0.0", reason = "use std::env::args() instead")]
755 #[unstable(feature = "os")]
756 pub fn args() -> Vec<String> {
760 /// Returns the arguments which this program was started with (normally passed
761 /// via the command line) as byte vectors.
762 #[deprecated(since = "1.0.0", reason = "use env::args_os instead")]
763 #[unstable(feature = "os")]
764 pub fn args_as_bytes() -> Vec<Vec<u8>> {
768 #[cfg(target_os = "macos")]
770 // These functions are in crt_externs.h.
771 fn _NSGetArgc() -> *mut c_int;
772 fn _NSGetArgv() -> *mut *mut *mut c_char;
775 /// Returns the page size of the current architecture in bytes.
776 #[deprecated(since = "1.0.0", reason = "renamed to env::page_size")]
777 #[unstable(feature = "os")]
778 pub fn page_size() -> uint {
782 /// A memory mapped file or chunk of memory. This is a very system-specific
783 /// interface to the OS's memory mapping facilities (`mmap` on POSIX,
784 /// `VirtualAlloc`/`CreateFileMapping` on Windows). It makes no attempt at
785 /// abstracting platform differences, besides in error values returned. Consider
788 /// The memory map is released (unmapped) when the destructor is run, so don't
789 /// let it leave scope by accident if you want it to stick around.
790 pub struct MemoryMap {
796 /// Type of memory map
797 #[allow(raw_pointer_derive)]
799 pub enum MemoryMapKind {
800 /// Virtual memory map. Usually used to change the permissions of a given
801 /// chunk of memory. Corresponds to `VirtualAlloc` on Windows.
803 /// Virtual memory map. Usually used to change the permissions of a given
804 /// chunk of memory, or for allocation. Corresponds to `VirtualAlloc` on
809 /// Options the memory map is created with
810 #[allow(raw_pointer_derive)]
813 /// The memory should be readable
815 /// The memory should be writable
817 /// The memory should be executable
819 /// Create a map for a specific address range. Corresponds to `MAP_FIXED` on
822 /// Create a memory mapping for a file with a given HANDLE.
825 /// Create a memory mapping for a file with a given fd.
828 /// When using `MapFd`, the start of the map is `uint` bytes from the start
831 /// On POSIX, this can be used to specify the default flags passed to
832 /// `mmap`. By default it uses `MAP_PRIVATE` and, if not using `MapFd`,
833 /// `MAP_ANON`. This will override both of those. This is platform-specific
834 /// (the exact values used) and ignored on Windows.
835 MapNonStandardFlags(c_int),
838 /// Possible errors when creating a map.
839 #[derive(Copy, Debug)]
841 /// # The following are POSIX-specific
843 /// fd was not open for reading or, if using `MapWritable`, was not open for
848 /// Either the address given by `MapAddr` or offset given by `MapOffset` was
849 /// not a multiple of `MemoryMap::granularity` (unaligned to page size).
851 /// With `MapFd`, the fd does not support mapping.
853 /// If using `MapAddr`, the address + `min_len` was outside of the process's
854 /// address space. If using `MapFd`, the target of the fd didn't have enough
855 /// resources to fulfill the request.
857 /// A zero-length map was requested. This is invalid according to
858 /// [POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/functions/mmap.html).
859 /// Not all platforms obey this, but this wrapper does.
861 /// Unrecognized error. The inner value is the unrecognized errno.
863 /// # The following are Windows-specific
865 /// Unsupported combination of protection flags
866 /// (`MapReadable`/`MapWritable`/`MapExecutable`).
868 /// When using `MapFd`, `MapOffset` was given (Windows does not support this
871 /// When using `MapFd`, there was already a mapping to the file.
873 /// Unrecognized error from `VirtualAlloc`. The inner value is the return
874 /// value of GetLastError.
875 ErrVirtualAlloc(i32),
876 /// Unrecognized error from `CreateFileMapping`. The inner value is the
877 /// return value of `GetLastError`.
878 ErrCreateFileMappingW(i32),
879 /// Unrecognized error from `MapViewOfFile`. The inner value is the return
880 /// value of `GetLastError`.
881 ErrMapViewOfFile(i32)
884 #[stable(feature = "rust1", since = "1.0.0")]
885 impl fmt::Display for MapError {
886 fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result {
887 let str = match *self {
888 ErrFdNotAvail => "fd not available for reading or writing",
889 ErrInvalidFd => "Invalid fd",
891 "Unaligned address, invalid flags, negative length or \
894 ErrNoMapSupport=> "File doesn't support mapping",
895 ErrNoMem => "Invalid address, or not enough available memory",
896 ErrUnsupProt => "Protection mode unsupported",
897 ErrUnsupOffset => "Offset in virtual memory mode is unsupported",
898 ErrAlreadyExists => "File mapping for specified file already exists",
899 ErrZeroLength => "Zero-length mapping not allowed",
900 ErrUnknown(code) => {
901 return write!(out, "Unknown error = {}", code)
903 ErrVirtualAlloc(code) => {
904 return write!(out, "VirtualAlloc failure = {}", code)
906 ErrCreateFileMappingW(code) => {
907 return write!(out, "CreateFileMappingW failure = {}", code)
909 ErrMapViewOfFile(code) => {
910 return write!(out, "MapViewOfFile failure = {}", code)
913 write!(out, "{}", str)
917 impl Error for MapError {
918 fn description(&self) -> &str { "memory map error" }
921 // Round up `from` to be divisible by `to`
922 fn round_up(from: uint, to: uint) -> uint {
923 let r = if from % to == 0 {
926 from + to - (from % to)
937 /// Create a new mapping with the given `options`, at least `min_len` bytes
938 /// long. `min_len` must be greater than zero; see the note on
940 pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
944 return Err(ErrZeroLength)
946 let mut addr: *const u8 = ptr::null();
948 let mut flags = libc::MAP_PRIVATE;
951 let mut custom_flags = false;
952 let len = round_up(min_len, env::page_size());
956 MapReadable => { prot |= libc::PROT_READ; },
957 MapWritable => { prot |= libc::PROT_WRITE; },
958 MapExecutable => { prot |= libc::PROT_EXEC; },
960 flags |= libc::MAP_FIXED;
964 flags |= libc::MAP_FILE;
967 MapOffset(offset_) => { offset = offset_ as off_t; },
968 MapNonStandardFlags(f) => { custom_flags = true; flags = f },
971 if fd == -1 && !custom_flags { flags |= libc::MAP_ANON; }
974 libc::mmap(addr as *mut c_void, len as libc::size_t, prot, flags,
977 if r == libc::MAP_FAILED {
978 Err(match errno() as c_int {
979 libc::EACCES => ErrFdNotAvail,
980 libc::EBADF => ErrInvalidFd,
981 libc::EINVAL => ErrUnaligned,
982 libc::ENODEV => ErrNoMapSupport,
983 libc::ENOMEM => ErrNoMem,
984 code => ErrUnknown(code as int)
999 /// Granularity that the offset or address must be for `MapOffset` and
1000 /// `MapAddr` respectively.
1001 pub fn granularity() -> uint {
1007 impl Drop for MemoryMap {
1008 /// Unmap the mapping. Panics the task if `munmap` panics.
1009 fn drop(&mut self) {
1010 if self.len == 0 { /* workaround for dummy_stack */ return; }
1013 // `munmap` only panics due to logic errors
1014 libc::munmap(self.data as *mut c_void, self.len as libc::size_t);
1021 /// Create a new mapping with the given `options`, at least `min_len` bytes long.
1022 pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
1023 use libc::types::os::arch::extra::{LPVOID, DWORD, SIZE_T, HANDLE};
1025 let mut lpAddress: LPVOID = ptr::null_mut();
1026 let mut readable = false;
1027 let mut writable = false;
1028 let mut executable = false;
1029 let mut handle: HANDLE = libc::INVALID_HANDLE_VALUE;
1030 let mut offset: uint = 0;
1031 let len = round_up(min_len, env::page_size());
1035 MapReadable => { readable = true; },
1036 MapWritable => { writable = true; },
1037 MapExecutable => { executable = true; }
1038 MapAddr(addr_) => { lpAddress = addr_ as LPVOID; },
1039 MapFd(handle_) => { handle = handle_; },
1040 MapOffset(offset_) => { offset = offset_; },
1041 MapNonStandardFlags(..) => {}
1045 let flProtect = match (executable, readable, writable) {
1046 (false, false, false) if handle == libc::INVALID_HANDLE_VALUE => libc::PAGE_NOACCESS,
1047 (false, true, false) => libc::PAGE_READONLY,
1048 (false, true, true) => libc::PAGE_READWRITE,
1049 (true, false, false) if handle == libc::INVALID_HANDLE_VALUE => libc::PAGE_EXECUTE,
1050 (true, true, false) => libc::PAGE_EXECUTE_READ,
1051 (true, true, true) => libc::PAGE_EXECUTE_READWRITE,
1052 _ => return Err(ErrUnsupProt)
1055 if handle == libc::INVALID_HANDLE_VALUE {
1057 return Err(ErrUnsupOffset);
1060 libc::VirtualAlloc(lpAddress,
1062 libc::MEM_COMMIT | libc::MEM_RESERVE,
1066 0 => Err(ErrVirtualAlloc(errno())),
1074 let dwDesiredAccess = match (executable, readable, writable) {
1075 (false, true, false) => libc::FILE_MAP_READ,
1076 (false, true, true) => libc::FILE_MAP_WRITE,
1077 (true, true, false) => libc::FILE_MAP_READ | libc::FILE_MAP_EXECUTE,
1078 (true, true, true) => libc::FILE_MAP_WRITE | libc::FILE_MAP_EXECUTE,
1079 _ => return Err(ErrUnsupProt) // Actually, because of the check above,
1080 // we should never get here.
1084 let mapping = libc::CreateFileMappingW(hFile,
1090 if mapping == ptr::null_mut() {
1091 return Err(ErrCreateFileMappingW(errno()));
1093 if errno() as c_int == libc::ERROR_ALREADY_EXISTS {
1094 return Err(ErrAlreadyExists);
1096 let r = libc::MapViewOfFile(mapping,
1098 ((len as u64) >> 32) as DWORD,
1099 (offset & 0xffff_ffff) as DWORD,
1102 0 => Err(ErrMapViewOfFile(errno())),
1106 kind: MapFile(mapping as *const u8)
1113 /// Granularity of MapAddr() and MapOffset() parameter values.
1114 /// This may be greater than the value returned by page_size().
1115 pub fn granularity() -> uint {
1118 let mut info = mem::zeroed();
1119 libc::GetSystemInfo(&mut info);
1121 return info.dwAllocationGranularity as uint;
1127 impl Drop for MemoryMap {
1128 /// Unmap the mapping. Panics the task if any of `VirtualFree`,
1129 /// `UnmapViewOfFile`, or `CloseHandle` fail.
1130 fn drop(&mut self) {
1131 use libc::types::os::arch::extra::{LPCVOID, HANDLE};
1132 use libc::consts::os::extra::FALSE;
1133 if self.len == 0 { return }
1138 if libc::VirtualFree(self.data as *mut c_void, 0,
1139 libc::MEM_RELEASE) == 0 {
1140 println!("VirtualFree failed: {}", errno());
1143 MapFile(mapping) => {
1144 if libc::UnmapViewOfFile(self.data as LPCVOID) == FALSE {
1145 println!("UnmapViewOfFile failed: {}", errno());
1147 if libc::CloseHandle(mapping as HANDLE) == FALSE {
1148 println!("CloseHandle failed: {}", errno());
1157 /// Returns the pointer to the memory created or modified by this map.
1158 pub fn data(&self) -> *mut u8 { self.data }
1159 /// Returns the number of bytes this map applies to.
1160 pub fn len(&self) -> uint { self.len }
1161 /// Returns the type of mapping this represents.
1162 pub fn kind(&self) -> MemoryMapKind { self.kind }
1165 #[cfg(target_os = "linux")]
1166 #[deprecated(since = "1.0.0", reason = "renamed to env::consts")]
1167 #[unstable(feature = "os")]
1169 pub use os::arch_consts::ARCH;
1171 pub const FAMILY: &'static str = "unix";
1173 /// A string describing the specific operating system in use: in this
1175 pub const SYSNAME: &'static str = "linux";
1177 /// Specifies the filename prefix used for shared libraries on this
1178 /// platform: in this case, `lib`.
1179 pub const DLL_PREFIX: &'static str = "lib";
1181 /// Specifies the filename suffix used for shared libraries on this
1182 /// platform: in this case, `.so`.
1183 pub const DLL_SUFFIX: &'static str = ".so";
1185 /// Specifies the file extension used for shared libraries on this
1186 /// platform that goes after the dot: in this case, `so`.
1187 pub const DLL_EXTENSION: &'static str = "so";
1189 /// Specifies the filename suffix used for executable binaries on this
1190 /// platform: in this case, the empty string.
1191 pub const EXE_SUFFIX: &'static str = "";
1193 /// Specifies the file extension, if any, used for executable binaries
1194 /// on this platform: in this case, the empty string.
1195 pub const EXE_EXTENSION: &'static str = "";
1198 #[cfg(target_os = "macos")]
1199 #[deprecated(since = "1.0.0", reason = "renamed to env::consts")]
1200 #[unstable(feature = "os")]
1202 pub use os::arch_consts::ARCH;
1204 pub const FAMILY: &'static str = "unix";
1206 /// A string describing the specific operating system in use: in this
1208 pub const SYSNAME: &'static str = "macos";
1210 /// Specifies the filename prefix used for shared libraries on this
1211 /// platform: in this case, `lib`.
1212 pub const DLL_PREFIX: &'static str = "lib";
1214 /// Specifies the filename suffix used for shared libraries on this
1215 /// platform: in this case, `.dylib`.
1216 pub const DLL_SUFFIX: &'static str = ".dylib";
1218 /// Specifies the file extension used for shared libraries on this
1219 /// platform that goes after the dot: in this case, `dylib`.
1220 pub const DLL_EXTENSION: &'static str = "dylib";
1222 /// Specifies the filename suffix used for executable binaries on this
1223 /// platform: in this case, the empty string.
1224 pub const EXE_SUFFIX: &'static str = "";
1226 /// Specifies the file extension, if any, used for executable binaries
1227 /// on this platform: in this case, the empty string.
1228 pub const EXE_EXTENSION: &'static str = "";
1231 #[cfg(target_os = "ios")]
1232 #[deprecated(since = "1.0.0", reason = "renamed to env::consts")]
1233 #[unstable(feature = "os")]
1235 pub use os::arch_consts::ARCH;
1237 pub const FAMILY: &'static str = "unix";
1239 /// A string describing the specific operating system in use: in this
1241 pub const SYSNAME: &'static str = "ios";
1243 /// Specifies the filename suffix used for executable binaries on this
1244 /// platform: in this case, the empty string.
1245 pub const EXE_SUFFIX: &'static str = "";
1247 /// Specifies the file extension, if any, used for executable binaries
1248 /// on this platform: in this case, the empty string.
1249 pub const EXE_EXTENSION: &'static str = "";
1252 #[cfg(target_os = "freebsd")]
1253 #[deprecated(since = "1.0.0", reason = "renamed to env::consts")]
1254 #[unstable(feature = "os")]
1256 pub use os::arch_consts::ARCH;
1258 pub const FAMILY: &'static str = "unix";
1260 /// A string describing the specific operating system in use: in this
1261 /// case, `freebsd`.
1262 pub const SYSNAME: &'static str = "freebsd";
1264 /// Specifies the filename prefix used for shared libraries on this
1265 /// platform: in this case, `lib`.
1266 pub const DLL_PREFIX: &'static str = "lib";
1268 /// Specifies the filename suffix used for shared libraries on this
1269 /// platform: in this case, `.so`.
1270 pub const DLL_SUFFIX: &'static str = ".so";
1272 /// Specifies the file extension used for shared libraries on this
1273 /// platform that goes after the dot: in this case, `so`.
1274 pub const DLL_EXTENSION: &'static str = "so";
1276 /// Specifies the filename suffix used for executable binaries on this
1277 /// platform: in this case, the empty string.
1278 pub const EXE_SUFFIX: &'static str = "";
1280 /// Specifies the file extension, if any, used for executable binaries
1281 /// on this platform: in this case, the empty string.
1282 pub const EXE_EXTENSION: &'static str = "";
1285 #[cfg(target_os = "dragonfly")]
1286 #[deprecated(since = "1.0.0", reason = "renamed to env::consts")]
1287 #[unstable(feature = "os")]
1289 pub use os::arch_consts::ARCH;
1291 pub const FAMILY: &'static str = "unix";
1293 /// A string describing the specific operating system in use: in this
1294 /// case, `dragonfly`.
1295 pub const SYSNAME: &'static str = "dragonfly";
1297 /// Specifies the filename prefix used for shared libraries on this
1298 /// platform: in this case, `lib`.
1299 pub const DLL_PREFIX: &'static str = "lib";
1301 /// Specifies the filename suffix used for shared libraries on this
1302 /// platform: in this case, `.so`.
1303 pub const DLL_SUFFIX: &'static str = ".so";
1305 /// Specifies the file extension used for shared libraries on this
1306 /// platform that goes after the dot: in this case, `so`.
1307 pub const DLL_EXTENSION: &'static str = "so";
1309 /// Specifies the filename suffix used for executable binaries on this
1310 /// platform: in this case, the empty string.
1311 pub const EXE_SUFFIX: &'static str = "";
1313 /// Specifies the file extension, if any, used for executable binaries
1314 /// on this platform: in this case, the empty string.
1315 pub const EXE_EXTENSION: &'static str = "";
1318 #[cfg(target_os = "bitrig")]
1319 #[deprecated(since = "1.0.0", reason = "renamed to env::consts")]
1320 #[unstable(feature = "os")]
1322 pub use os::arch_consts::ARCH;
1324 pub const FAMILY: &'static str = "unix";
1326 /// A string describing the specific operating system in use: in this
1328 pub const SYSNAME: &'static str = "bitrig";
1330 /// Specifies the filename prefix used for shared libraries on this
1331 /// platform: in this case, `lib`.
1332 pub const DLL_PREFIX: &'static str = "lib";
1334 /// Specifies the filename suffix used for shared libraries on this
1335 /// platform: in this case, `.so`.
1336 pub const DLL_SUFFIX: &'static str = ".so";
1338 /// Specifies the file extension used for shared libraries on this
1339 /// platform that goes after the dot: in this case, `so`.
1340 pub const DLL_EXTENSION: &'static str = "so";
1342 /// Specifies the filename suffix used for executable binaries on this
1343 /// platform: in this case, the empty string.
1344 pub const EXE_SUFFIX: &'static str = "";
1346 /// Specifies the file extension, if any, used for executable binaries
1347 /// on this platform: in this case, the empty string.
1348 pub const EXE_EXTENSION: &'static str = "";
1351 #[cfg(target_os = "openbsd")]
1352 #[deprecated(since = "1.0.0", reason = "renamed to env::consts")]
1353 #[unstable(feature = "os")]
1355 pub use os::arch_consts::ARCH;
1357 pub const FAMILY: &'static str = "unix";
1359 /// A string describing the specific operating system in use: in this
1360 /// case, `openbsd`.
1361 pub const SYSNAME: &'static str = "openbsd";
1363 /// Specifies the filename prefix used for shared libraries on this
1364 /// platform: in this case, `lib`.
1365 pub const DLL_PREFIX: &'static str = "lib";
1367 /// Specifies the filename suffix used for shared libraries on this
1368 /// platform: in this case, `.so`.
1369 pub const DLL_SUFFIX: &'static str = ".so";
1371 /// Specifies the file extension used for shared libraries on this
1372 /// platform that goes after the dot: in this case, `so`.
1373 pub const DLL_EXTENSION: &'static str = "so";
1375 /// Specifies the filename suffix used for executable binaries on this
1376 /// platform: in this case, the empty string.
1377 pub const EXE_SUFFIX: &'static str = "";
1379 /// Specifies the file extension, if any, used for executable binaries
1380 /// on this platform: in this case, the empty string.
1381 pub const EXE_EXTENSION: &'static str = "";
1384 #[cfg(target_os = "android")]
1385 #[deprecated(since = "1.0.0", reason = "renamed to env::consts")]
1386 #[unstable(feature = "os")]
1388 pub use os::arch_consts::ARCH;
1390 pub const FAMILY: &'static str = "unix";
1392 /// A string describing the specific operating system in use: in this
1393 /// case, `android`.
1394 pub const SYSNAME: &'static str = "android";
1396 /// Specifies the filename prefix used for shared libraries on this
1397 /// platform: in this case, `lib`.
1398 pub const DLL_PREFIX: &'static str = "lib";
1400 /// Specifies the filename suffix used for shared libraries on this
1401 /// platform: in this case, `.so`.
1402 pub const DLL_SUFFIX: &'static str = ".so";
1404 /// Specifies the file extension used for shared libraries on this
1405 /// platform that goes after the dot: in this case, `so`.
1406 pub const DLL_EXTENSION: &'static str = "so";
1408 /// Specifies the filename suffix used for executable binaries on this
1409 /// platform: in this case, the empty string.
1410 pub const EXE_SUFFIX: &'static str = "";
1412 /// Specifies the file extension, if any, used for executable binaries
1413 /// on this platform: in this case, the empty string.
1414 pub const EXE_EXTENSION: &'static str = "";
1417 #[cfg(target_os = "windows")]
1418 #[deprecated(since = "1.0.0", reason = "renamed to env::consts")]
1419 #[unstable(feature = "os")]
1421 pub use os::arch_consts::ARCH;
1423 pub const FAMILY: &'static str = "windows";
1425 /// A string describing the specific operating system in use: in this
1426 /// case, `windows`.
1427 pub const SYSNAME: &'static str = "windows";
1429 /// Specifies the filename prefix used for shared libraries on this
1430 /// platform: in this case, the empty string.
1431 pub const DLL_PREFIX: &'static str = "";
1433 /// Specifies the filename suffix used for shared libraries on this
1434 /// platform: in this case, `.dll`.
1435 pub const DLL_SUFFIX: &'static str = ".dll";
1437 /// Specifies the file extension used for shared libraries on this
1438 /// platform that goes after the dot: in this case, `dll`.
1439 pub const DLL_EXTENSION: &'static str = "dll";
1441 /// Specifies the filename suffix used for executable binaries on this
1442 /// platform: in this case, `.exe`.
1443 pub const EXE_SUFFIX: &'static str = ".exe";
1445 /// Specifies the file extension, if any, used for executable binaries
1446 /// on this platform: in this case, `exe`.
1447 pub const EXE_EXTENSION: &'static str = "exe";
1450 #[cfg(target_arch = "x86")]
1452 pub const ARCH: &'static str = "x86";
1455 #[cfg(target_arch = "x86_64")]
1457 pub const ARCH: &'static str = "x86_64";
1460 #[cfg(target_arch = "arm")]
1462 pub const ARCH: &'static str = "arm";
1465 #[cfg(target_arch = "aarch64")]
1467 pub const ARCH: &'static str = "aarch64";
1470 #[cfg(target_arch = "mips")]
1472 pub const ARCH: &'static str = "mips";
1475 #[cfg(target_arch = "mipsel")]
1477 pub const ARCH: &'static str = "mipsel";
1480 #[cfg(target_arch = "powerpc")]
1482 pub const ARCH: &'static str = "powerpc";
1487 #![allow(deprecated)] // rand
1492 use os::{env, getcwd, getenv, make_absolute};
1493 use os::{split_paths, join_paths, setenv, unsetenv};
1499 pub fn last_os_error() {
1500 debug!("{}", os::last_os_error());
1503 fn make_rand_name() -> String {
1504 let mut rng = rand::thread_rng();
1505 let n = format!("TEST{}", rng.gen_ascii_chars().take(10)
1506 .collect::<String>());
1507 assert!(getenv(&n).is_none());
1512 fn test_num_cpus() {
1513 assert!(os::num_cpus() > 0);
1518 let n = make_rand_name();
1519 setenv(&n, "VALUE");
1520 assert_eq!(getenv(&n), Some("VALUE".to_string()));
1524 fn test_unsetenv() {
1525 let n = make_rand_name();
1526 setenv(&n, "VALUE");
1528 assert_eq!(getenv(&n), None);
1533 fn test_setenv_overwrite() {
1534 let n = make_rand_name();
1537 assert_eq!(getenv(&n), Some("2".to_string()));
1539 assert_eq!(getenv(&n), Some("".to_string()));
1542 // Windows GetEnvironmentVariable requires some extra work to make sure
1543 // the buffer the variable is copied into is the right size
1546 fn test_getenv_big() {
1547 let mut s = "".to_string();
1550 s.push_str("aaaaaaaaaa");
1553 let n = make_rand_name();
1555 debug!("{}", s.clone());
1556 assert_eq!(getenv(&n), Some(s));
1560 fn test_self_exe_name() {
1561 let path = os::self_exe_name();
1562 assert!(path.is_some());
1563 let path = path.unwrap();
1564 debug!("{}", path.display());
1566 // Hard to test this function
1567 assert!(path.is_absolute());
1571 fn test_self_exe_path() {
1572 let path = os::self_exe_path();
1573 assert!(path.is_some());
1574 let path = path.unwrap();
1575 debug!("{}", path.display());
1577 // Hard to test this function
1578 assert!(path.is_absolute());
1583 fn test_env_getenv() {
1585 assert!(e.len() > 0);
1587 let (n, v) = (*p).clone();
1589 let v2 = getenv(&n);
1590 // MingW seems to set some funky environment variables like
1591 // "=C:=C:\MinGW\msys\1.0\bin" and "!::=::\" that are returned
1592 // from env() but not visible from getenv().
1593 assert!(v2.is_none() || v2 == Some(v));
1598 fn test_env_set_get_huge() {
1599 let n = make_rand_name();
1600 let s = repeat("x").take(10000).collect::<String>();
1602 assert_eq!(getenv(&n), Some(s));
1604 assert_eq!(getenv(&n), None);
1608 fn test_env_setenv() {
1609 let n = make_rand_name();
1612 setenv(&n, "VALUE");
1613 assert!(!e.contains(&(n.clone(), "VALUE".to_string())));
1616 assert!(e.contains(&(n, "VALUE".to_string())));
1621 assert!((!Path::new("test-path").is_absolute()));
1623 let cwd = getcwd().unwrap();
1624 debug!("Current working directory: {}", cwd.display());
1626 debug!("{}", make_absolute(&Path::new("test-path")).unwrap().display());
1627 debug!("{}", make_absolute(&Path::new("/usr/bin")).unwrap().display());
1633 let oldhome = getenv("HOME");
1635 setenv("HOME", "/home/MountainView");
1636 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1639 assert!(os::homedir().is_none());
1641 if let Some(s) = oldhome {
1650 let oldhome = getenv("HOME");
1651 let olduserprofile = getenv("USERPROFILE");
1654 setenv("USERPROFILE", "");
1656 assert!(os::homedir().is_none());
1658 setenv("HOME", "/home/MountainView");
1659 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1663 setenv("USERPROFILE", "/home/MountainView");
1664 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1666 setenv("HOME", "/home/MountainView");
1667 setenv("USERPROFILE", "/home/PaloAlto");
1668 assert!(os::homedir() == Some(Path::new("/home/MountainView")));
1670 if let Some(s) = oldhome {
1673 if let Some(s) = olduserprofile {
1674 setenv("USERPROFILE", &s);
1679 fn memory_map_rw() {
1680 use result::Result::{Ok, Err};
1682 let chunk = match os::MemoryMap::new(16, &[
1683 os::MapOption::MapReadable,
1684 os::MapOption::MapWritable
1687 Err(msg) => panic!("{:?}", msg)
1689 assert!(chunk.len >= 16);
1693 assert!(*chunk.data == 0xBE);
1698 fn memory_map_file() {
1701 use old_io::fs::{File, unlink};
1702 use old_io::SeekStyle::SeekSet;
1703 use old_io::FileMode::Open;
1704 use old_io::FileAccess::ReadWrite;
1706 #[cfg(not(windows))]
1707 fn get_fd(file: &File) -> libc::c_int {
1708 use os::unix::AsRawFd;
1713 fn get_fd(file: &File) -> libc::HANDLE {
1714 use os::windows::AsRawHandle;
1715 file.as_raw_handle()
1718 let mut path = tmpdir();
1719 path.push("mmap_file.tmp");
1720 let size = MemoryMap::granularity() * 2;
1721 let mut file = File::open_mode(&path, Open, ReadWrite).unwrap();
1722 file.seek(size as i64, SeekSet).unwrap();
1723 file.write_u8(0).unwrap();
1725 let chunk = MemoryMap::new(size / 2, &[
1726 MapOption::MapReadable,
1727 MapOption::MapWritable,
1728 MapOption::MapFd(get_fd(&file)),
1729 MapOption::MapOffset(size / 2)
1731 assert!(chunk.len > 0);
1735 assert!(*chunk.data == 0xbe);
1739 unlink(&path).unwrap();
1744 fn split_paths_windows() {
1745 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
1746 split_paths(unparsed) ==
1747 parsed.iter().map(|s| Path::new(*s)).collect::<Vec<_>>()
1750 assert!(check_parse("", &mut [""]));
1751 assert!(check_parse(r#""""#, &mut [""]));
1752 assert!(check_parse(";;", &mut ["", "", ""]));
1753 assert!(check_parse(r"c:\", &mut [r"c:\"]));
1754 assert!(check_parse(r"c:\;", &mut [r"c:\", ""]));
1755 assert!(check_parse(r"c:\;c:\Program Files\",
1756 &mut [r"c:\", r"c:\Program Files\"]));
1757 assert!(check_parse(r#"c:\;c:\"foo"\"#, &mut [r"c:\", r"c:\foo\"]));
1758 assert!(check_parse(r#"c:\;c:\"foo;bar"\;c:\baz"#,
1759 &mut [r"c:\", r"c:\foo;bar\", r"c:\baz"]));
1764 fn split_paths_unix() {
1765 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
1766 split_paths(unparsed) ==
1767 parsed.iter().map(|s| Path::new(*s)).collect::<Vec<_>>()
1770 assert!(check_parse("", &mut [""]));
1771 assert!(check_parse("::", &mut ["", "", ""]));
1772 assert!(check_parse("/", &mut ["/"]));
1773 assert!(check_parse("/:", &mut ["/", ""]));
1774 assert!(check_parse("/:/usr/local", &mut ["/", "/usr/local"]));
1779 fn join_paths_unix() {
1780 fn test_eq(input: &[&str], output: &str) -> bool {
1781 join_paths(input).unwrap() == output.as_bytes()
1784 assert!(test_eq(&[], ""));
1785 assert!(test_eq(&["/bin", "/usr/bin", "/usr/local/bin"],
1786 "/bin:/usr/bin:/usr/local/bin"));
1787 assert!(test_eq(&["", "/bin", "", "", "/usr/bin", ""],
1788 ":/bin:::/usr/bin:"));
1789 assert!(join_paths(&["/te:st"]).is_err());
1794 fn join_paths_windows() {
1795 fn test_eq(input: &[&str], output: &str) -> bool {
1796 join_paths(input).unwrap() == output.as_bytes()
1799 assert!(test_eq(&[], ""));
1800 assert!(test_eq(&[r"c:\windows", r"c:\"],
1801 r"c:\windows;c:\"));
1802 assert!(test_eq(&["", r"c:\windows", "", "", r"c:\", ""],
1803 r";c:\windows;;;c:\;"));
1804 assert!(test_eq(&[r"c:\te;st", r"c:\"],
1805 r#""c:\te;st";c:\"#));
1806 assert!(join_paths(&[r#"c:\te"st"#]).is_err());
1809 // More recursive_mkdir tests are in extra::tempfile