about summary refs log tree commit diff
path: root/src/libstd/sys
diff options
context:
space:
mode:
authorbors <bors@rust-lang.org>2015-02-10 04:07:03 +0000
committerbors <bors@rust-lang.org>2015-02-10 04:07:03 +0000
commit0bfe358e0fe3b35f0434e81e7c53ea844e95cc13 (patch)
tree091fc970b94cf86a68fd62febef1c5648f5b0d9d /src/libstd/sys
parent134e00be7751a9fdc820981962e4fd7ea97bfff6 (diff)
parent6bfbad937bdf578e35777d079f8dcfab49758041 (diff)
downloadrust-0bfe358e0fe3b35f0434e81e7c53ea844e95cc13.tar.gz
rust-0bfe358e0fe3b35f0434e81e7c53ea844e95cc13.zip
Auto merge of #21936 - alexcrichton:fsv2, r=aturon
This commit is an implementation of [RFC 739][rfc] which adds a new `std::fs`
module to the standard library. This module provides much of the same
functionality as `std::old_io::fs` but it has many tweaked APIs as well as uses
the new `std::path` module.

[rfc]: https://github.com/rust-lang/rfcs/pull/739
Diffstat (limited to 'src/libstd/sys')
-rw-r--r--src/libstd/sys/common/mod.rs10
-rw-r--r--src/libstd/sys/unix/c.rs3
-rw-r--r--src/libstd/sys/unix/ext.rs48
-rw-r--r--src/libstd/sys/unix/fd.rs70
-rw-r--r--src/libstd/sys/unix/fs2.rs378
-rw-r--r--src/libstd/sys/unix/mod.rs27
-rw-r--r--src/libstd/sys/windows/ext.rs61
-rw-r--r--src/libstd/sys/windows/fs2.rs428
-rw-r--r--src/libstd/sys/windows/handle.rs1
-rw-r--r--src/libstd/sys/windows/mod.rs40
-rw-r--r--src/libstd/sys/windows/os.rs2
11 files changed, 1055 insertions, 13 deletions
diff --git a/src/libstd/sys/common/mod.rs b/src/libstd/sys/common/mod.rs
index 6f6b4c58717..80fa5f64597 100644
--- a/src/libstd/sys/common/mod.rs
+++ b/src/libstd/sys/common/mod.rs
@@ -95,20 +95,30 @@ pub fn keep_going<F>(data: &[u8], mut f: F) -> i64 where
 }
 
 /// A trait for viewing representations from std types
+#[doc(hidden)]
 pub trait AsInner<Inner: ?Sized> {
     fn as_inner(&self) -> &Inner;
 }
 
+/// A trait for viewing representations from std types
+#[doc(hidden)]
+pub trait AsInnerMut<Inner: ?Sized> {
+    fn as_inner_mut(&mut self) -> &mut Inner;
+}
+
 /// A trait for extracting representations from std types
+#[doc(hidden)]
 pub trait IntoInner<Inner> {
     fn into_inner(self) -> Inner;
 }
 
 /// A trait for creating std types from internal representations
+#[doc(hidden)]
 pub trait FromInner<Inner> {
     fn from_inner(inner: Inner) -> Self;
 }
 
+#[doc(hidden)]
 pub trait ProcessConfig<K: BytesContainer, V: BytesContainer> {
     fn program(&self) -> &CString;
     fn args(&self) -> &[CString];
diff --git a/src/libstd/sys/unix/c.rs b/src/libstd/sys/unix/c.rs
index c27dbf6734a..cf05733cc18 100644
--- a/src/libstd/sys/unix/c.rs
+++ b/src/libstd/sys/unix/c.rs
@@ -154,6 +154,9 @@ extern {
                       buf: *mut libc::c_char,
                       buflen: libc::size_t,
                       result: *mut *mut passwd) -> libc::c_int;
+
+    pub fn utimes(filename: *const libc::c_char,
+                  times: *const libc::timeval) -> libc::c_int;
 }
 
 #[cfg(any(target_os = "macos", target_os = "ios"))]
diff --git a/src/libstd/sys/unix/ext.rs b/src/libstd/sys/unix/ext.rs
index 4a82b2807e7..689bbda8322 100644
--- a/src/libstd/sys/unix/ext.rs
+++ b/src/libstd/sys/unix/ext.rs
@@ -31,11 +31,14 @@
 
 #![unstable(feature = "std_misc")]
 
-use vec::Vec;
-use sys::os_str::Buf;
-use sys_common::{AsInner, IntoInner, FromInner};
 use ffi::{OsStr, OsString};
+use fs::{Permissions, OpenOptions};
+use fs;
 use libc;
+use mem;
+use sys::os_str::Buf;
+use sys_common::{AsInner, AsInnerMut, IntoInner, FromInner};
+use vec::Vec;
 
 use old_io;
 
@@ -54,6 +57,12 @@ impl AsRawFd for old_io::fs::File {
     }
 }
 
+impl AsRawFd for fs::File {
+    fn as_raw_fd(&self) -> Fd {
+        self.as_inner().fd().raw()
+    }
+}
+
 impl AsRawFd for old_io::pipe::PipeStream {
     fn as_raw_fd(&self) -> Fd {
         self.as_inner().fd()
@@ -123,18 +132,49 @@ impl OsStringExt for OsString {
 
 // Unix-specific extensions to `OsStr`.
 pub trait OsStrExt {
+    fn from_byte_slice(slice: &[u8]) -> &OsStr;
     fn as_byte_slice(&self) -> &[u8];
 }
 
 impl OsStrExt for OsStr {
+    fn from_byte_slice(slice: &[u8]) -> &OsStr {
+        unsafe { mem::transmute(slice) }
+    }
     fn as_byte_slice(&self) -> &[u8] {
         &self.as_inner().inner
     }
 }
 
+// Unix-specific extensions to `Permissions`
+pub trait PermissionsExt {
+    fn set_mode(&mut self, mode: i32);
+}
+
+impl PermissionsExt for Permissions {
+    fn set_mode(&mut self, mode: i32) {
+        *self = FromInner::from_inner(FromInner::from_inner(mode));
+    }
+}
+
+// Unix-specific extensions to `OpenOptions`
+pub trait OpenOptionsExt {
+    /// Set the mode bits that a new file will be created with.
+    ///
+    /// If a new file is created as part of a `File::open_opts` call then this
+    /// specified `mode` will be used as the permission bits for the new file.
+    fn mode(&mut self, mode: i32) -> &mut Self;
+}
+
+impl OpenOptionsExt for OpenOptions {
+    fn mode(&mut self, mode: i32) -> &mut OpenOptions {
+        self.as_inner_mut().mode(mode); self
+    }
+}
+
 /// A prelude for conveniently writing platform-specific code.
 ///
 /// Includes all extension traits, and some important type definitions.
 pub mod prelude {
-    pub use super::{Fd, AsRawFd};
+    #[doc(no_inline)]
+    pub use super::{Fd, AsRawFd, OsStrExt, OsStringExt, PermissionsExt};
 }
diff --git a/src/libstd/sys/unix/fd.rs b/src/libstd/sys/unix/fd.rs
new file mode 100644
index 00000000000..f0943de5378
--- /dev/null
+++ b/src/libstd/sys/unix/fd.rs
@@ -0,0 +1,70 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+use core::prelude::*;
+use io::prelude::*;
+
+use io;
+use libc::{self, c_int, size_t, c_void};
+use mem;
+use sys::cvt;
+
+pub type fd_t = c_int;
+
+pub struct FileDesc {
+    fd: c_int,
+}
+
+impl FileDesc {
+    pub fn new(fd: c_int) -> FileDesc {
+        FileDesc { fd: fd }
+    }
+
+    pub fn raw(&self) -> c_int { self.fd }
+
+    /// Extract the actual filedescriptor without closing it.
+    pub fn into_raw(self) -> c_int {
+        let fd = self.fd;
+        unsafe { mem::forget(self) };
+        fd
+    }
+
+    pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
+        let ret = try!(cvt(unsafe {
+            libc::read(self.fd,
+                       buf.as_mut_ptr() as *mut c_void,
+                       buf.len() as size_t)
+        }));
+        Ok(ret as usize)
+    }
+
+    pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
+        let ret = try!(cvt(unsafe {
+            libc::write(self.fd,
+                        buf.as_ptr() as *const c_void,
+                        buf.len() as size_t)
+        }));
+        Ok(ret as usize)
+    }
+}
+
+impl Drop for FileDesc {
+    fn drop(&mut self) {
+        // closing stdio file handles makes no sense, so never do it. Also, note
+        // that errors are ignored when closing a file descriptor. The reason
+        // for this is that if an error occurs we don't actually know if the
+        // file descriptor was closed or not, and if we retried (for something
+        // like EINTR), we might close another valid file descriptor (opened
+        // after we closed ours.
+        if self.fd > libc::STDERR_FILENO {
+            let _ = unsafe { libc::close(self.fd) };
+        }
+    }
+}
diff --git a/src/libstd/sys/unix/fs2.rs b/src/libstd/sys/unix/fs2.rs
new file mode 100644
index 00000000000..070b3248349
--- /dev/null
+++ b/src/libstd/sys/unix/fs2.rs
@@ -0,0 +1,378 @@
+// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+use core::prelude::*;
+use io::prelude::*;
+use os::unix::prelude::*;
+
+use ffi::{self, CString, OsString, AsOsStr, OsStr};
+use io::{self, Error, Seek, SeekFrom};
+use libc::{self, c_int, c_void, size_t, off_t, c_char, mode_t};
+use mem;
+use path::{Path, PathBuf};
+use ptr;
+use rc::Rc;
+use sys::fd::FileDesc;
+use sys::{c, cvt, cvt_r};
+use sys_common::FromInner;
+use vec::Vec;
+
+pub struct File(FileDesc);
+
+pub struct FileAttr {
+    stat: libc::stat,
+}
+
+pub struct ReadDir {
+    dirp: *mut libc::DIR,
+    root: Rc<PathBuf>,
+}
+
+pub struct DirEntry {
+    buf: Vec<u8>,
+    dirent: *mut libc::dirent_t,
+    root: Rc<PathBuf>,
+}
+
+#[derive(Clone)]
+pub struct OpenOptions {
+    flags: c_int,
+    read: bool,
+    write: bool,
+    mode: mode_t,
+}
+
+#[derive(Clone, PartialEq, Eq, Debug)]
+pub struct FilePermissions { mode: mode_t }
+
+impl FileAttr {
+    pub fn is_dir(&self) -> bool {
+        (self.stat.st_mode as mode_t) & libc::S_IFMT == libc::S_IFDIR
+    }
+    pub fn is_file(&self) -> bool {
+        (self.stat.st_mode as mode_t) & libc::S_IFMT == libc::S_IFREG
+    }
+    pub fn size(&self) -> u64 { self.stat.st_size as u64 }
+    pub fn perm(&self) -> FilePermissions {
+        FilePermissions { mode: (self.stat.st_mode as mode_t) & 0o777 }
+    }
+
+    pub fn accessed(&self) -> u64 {
+        self.mktime(self.stat.st_atime as u64, self.stat.st_atime_nsec as u64)
+    }
+    pub fn modified(&self) -> u64 {
+        self.mktime(self.stat.st_mtime as u64, self.stat.st_mtime_nsec as u64)
+    }
+
+    // times are in milliseconds (currently)
+    fn mktime(&self, secs: u64, nsecs: u64) -> u64 {
+        secs * 1000 + nsecs / 1000000
+    }
+}
+
+impl FilePermissions {
+    pub fn readonly(&self) -> bool { self.mode & 0o222 == 0 }
+    pub fn set_readonly(&mut self, readonly: bool) {
+        if readonly {
+            self.mode &= !0o222;
+        } else {
+            self.mode |= 0o222;
+        }
+    }
+}
+
+impl FromInner<i32> for FilePermissions {
+    fn from_inner(mode: i32) -> FilePermissions {
+        FilePermissions { mode: mode as mode_t }
+    }
+}
+
+impl Iterator for ReadDir {
+    type Item = io::Result<DirEntry>;
+
+    fn next(&mut self) -> Option<io::Result<DirEntry>> {
+        extern {
+            fn rust_dirent_t_size() -> c_int;
+        }
+
+        let mut buf: Vec<u8> = Vec::with_capacity(unsafe {
+            rust_dirent_t_size() as usize
+        });
+        let ptr = buf.as_mut_ptr() as *mut libc::dirent_t;
+
+        let mut entry_ptr = ptr::null_mut();
+        loop {
+            if unsafe { libc::readdir_r(self.dirp, ptr, &mut entry_ptr) != 0 } {
+                return Some(Err(Error::last_os_error()))
+            }
+            if entry_ptr.is_null() {
+                return None
+            }
+
+            let entry = DirEntry {
+                buf: buf,
+                dirent: entry_ptr,
+                root: self.root.clone()
+            };
+            if entry.name_bytes() == b"." || entry.name_bytes() == b".." {
+                buf = entry.buf;
+            } else {
+                return Some(Ok(entry))
+            }
+        }
+    }
+}
+
+impl Drop for ReadDir {
+    fn drop(&mut self) {
+        let r = unsafe { libc::closedir(self.dirp) };
+        debug_assert_eq!(r, 0);
+    }
+}
+
+impl DirEntry {
+    pub fn path(&self) -> PathBuf {
+        self.root.join(<OsStr as OsStrExt>::from_byte_slice(self.name_bytes()))
+    }
+
+    fn name_bytes(&self) -> &[u8] {
+        extern {
+            fn rust_list_dir_val(ptr: *mut libc::dirent_t) -> *const c_char;
+        }
+        unsafe {
+            let ptr = rust_list_dir_val(self.dirent);
+            ffi::c_str_to_bytes(mem::copy_lifetime(self, &ptr))
+        }
+    }
+}
+
+impl OpenOptions {
+    pub fn new() -> OpenOptions {
+        OpenOptions {
+            flags: 0,
+            read: false,
+            write: false,
+            mode: libc::S_IRUSR | libc::S_IWUSR,
+        }
+    }
+
+    pub fn read(&mut self, read: bool) {
+        self.read = read;
+    }
+
+    pub fn write(&mut self, write: bool) {
+        self.write = write;
+    }
+
+    pub fn append(&mut self, append: bool) {
+        self.flag(libc::O_APPEND, append);
+    }
+
+    pub fn truncate(&mut self, truncate: bool) {
+        self.flag(libc::O_TRUNC, truncate);
+    }
+
+    pub fn create(&mut self, create: bool) {
+        self.flag(libc::O_CREAT, create);
+    }
+
+    pub fn mode(&mut self, mode: i32) {
+        self.mode = mode as mode_t;
+    }
+
+    fn flag(&mut self, bit: c_int, on: bool) {
+        if on {
+            self.flags |= bit;
+        } else {
+            self.flags &= !bit;
+        }
+    }
+}
+
+impl File {
+    pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
+        let flags = opts.flags | match (opts.read, opts.write) {
+            (true, true) => libc::O_RDWR,
+            (false, true) => libc::O_WRONLY,
+            (true, false) |
+            (false, false) => libc::O_RDONLY,
+        };
+        let path = cstr(path);
+        let fd = try!(cvt_r(|| unsafe {
+            libc::open(path.as_ptr(), flags, opts.mode)
+        }));
+        Ok(File(FileDesc::new(fd)))
+    }
+
+    pub fn file_attr(&self) -> io::Result<FileAttr> {
+        let mut stat: libc::stat = unsafe { mem::zeroed() };
+        try!(cvt(unsafe { libc::fstat(self.0.raw(), &mut stat) }));
+        Ok(FileAttr { stat: stat })
+    }
+
+    pub fn fsync(&self) -> io::Result<()> {
+        try!(cvt_r(|| unsafe { libc::fsync(self.0.raw()) }));
+        Ok(())
+    }
+
+    pub fn datasync(&self) -> io::Result<()> {
+        try!(cvt_r(|| unsafe { os_datasync(self.0.raw()) }));
+        return Ok(());
+
+        #[cfg(any(target_os = "macos", target_os = "ios"))]
+        unsafe fn os_datasync(fd: c_int) -> c_int {
+            libc::fcntl(fd, libc::F_FULLFSYNC)
+        }
+        #[cfg(target_os = "linux")]
+        unsafe fn os_datasync(fd: c_int) -> c_int { libc::fdatasync(fd) }
+        #[cfg(not(any(target_os = "macos",
+                      target_os = "ios",
+                      target_os = "linux")))]
+        unsafe fn os_datasync(fd: c_int) -> c_int { libc::fsync(fd) }
+    }
+
+    pub fn truncate(&self, size: u64) -> io::Result<()> {
+        try!(cvt_r(|| unsafe {
+            libc::ftruncate(self.0.raw(), size as libc::off_t)
+        }));
+        Ok(())
+    }
+
+    pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
+        self.0.read(buf)
+    }
+
+    pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
+        self.0.write(buf)
+    }
+
+    pub fn flush(&self) -> io::Result<()> { Ok(()) }
+
+    pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
+        let (whence, pos) = match pos {
+            SeekFrom::Start(off) => (libc::SEEK_SET, off as off_t),
+            SeekFrom::End(off) => (libc::SEEK_END, off as off_t),
+            SeekFrom::Current(off) => (libc::SEEK_CUR, off as off_t),
+        };
+        let n = try!(cvt(unsafe { libc::lseek(self.0.raw(), pos, whence) }));
+        Ok(n as u64)
+    }
+
+    pub fn fd(&self) -> &FileDesc { &self.0 }
+}
+
+fn cstr(path: &Path) -> CString {
+    CString::from_slice(path.as_os_str().as_byte_slice())
+}
+
+pub fn mkdir(p: &Path) -> io::Result<()> {
+    let p = cstr(p);
+    try!(cvt(unsafe { libc::mkdir(p.as_ptr(), 0o777) }));
+    Ok(())
+}
+
+pub fn readdir(p: &Path) -> io::Result<ReadDir> {
+    let root = Rc::new(p.to_path_buf());
+    let p = cstr(p);
+    unsafe {
+        let ptr = libc::opendir(p.as_ptr());
+        if ptr.is_null() {
+            Err(Error::last_os_error())
+        } else {
+            Ok(ReadDir { dirp: ptr, root: root })
+        }
+    }
+}
+
+pub fn unlink(p: &Path) -> io::Result<()> {
+    let p = cstr(p);
+    try!(cvt(unsafe { libc::unlink(p.as_ptr()) }));
+    Ok(())
+}
+
+pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
+    let old = cstr(old);
+    let new = cstr(new);
+    try!(cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) }));
+    Ok(())
+}
+
+pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
+    let p = cstr(p);
+    try!(cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) }));
+    Ok(())
+}
+
+pub fn rmdir(p: &Path) -> io::Result<()> {
+    let p = cstr(p);
+    try!(cvt(unsafe { libc::rmdir(p.as_ptr()) }));
+    Ok(())
+}
+
+pub fn chown(p: &Path, uid: isize, gid: isize) -> io::Result<()> {
+    let p = cstr(p);
+    try!(cvt_r(|| unsafe {
+        libc::chown(p.as_ptr(), uid as libc::uid_t, gid as libc::gid_t)
+    }));
+    Ok(())
+}
+
+pub fn readlink(p: &Path) -> io::Result<PathBuf> {
+    let c_path = cstr(p);
+    let p = c_path.as_ptr();
+    let mut len = unsafe { libc::pathconf(p as *mut _, libc::_PC_NAME_MAX) };
+    if len < 0 {
+        len = 1024; // FIXME: read PATH_MAX from C ffi?
+    }
+    let mut buf: Vec<u8> = Vec::with_capacity(len as usize);
+    unsafe {
+        let n = try!(cvt({
+            libc::readlink(p, buf.as_ptr() as *mut c_char, len as size_t)
+        }));
+        buf.set_len(n as usize);
+    }
+    let s: OsString = OsStringExt::from_vec(buf);
+    Ok(PathBuf::new(&s))
+}
+
+pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
+    let src = cstr(src);
+    let dst = cstr(dst);
+    try!(cvt(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) }));
+    Ok(())
+}
+
+pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
+    let src = cstr(src);
+    let dst = cstr(dst);
+    try!(cvt(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) }));
+    Ok(())
+}
+
+pub fn stat(p: &Path) -> io::Result<FileAttr> {
+    let p = cstr(p);
+    let mut stat: libc::stat = unsafe { mem::zeroed() };
+    try!(cvt(unsafe { libc::stat(p.as_ptr(), &mut stat) }));
+    Ok(FileAttr { stat: stat })
+}
+
+pub fn lstat(p: &Path) -> io::Result<FileAttr> {
+    let p = cstr(p);
+    let mut stat: libc::stat = unsafe { mem::zeroed() };
+    try!(cvt(unsafe { libc::lstat(p.as_ptr(), &mut stat) }));
+    Ok(FileAttr { stat: stat })
+}
+
+pub fn utimes(p: &Path, atime: u64, mtime: u64) -> io::Result<()> {
+    let p = cstr(p);
+    let buf = [super::ms_to_timeval(atime), super::ms_to_timeval(mtime)];
+    try!(cvt(unsafe { c::utimes(p.as_ptr(), buf.as_ptr()) }));
+    Ok(())
+}
diff --git a/src/libstd/sys/unix/mod.rs b/src/libstd/sys/unix/mod.rs
index 427cf21ac70..b5a24278a20 100644
--- a/src/libstd/sys/unix/mod.rs
+++ b/src/libstd/sys/unix/mod.rs
@@ -23,6 +23,7 @@ use libc;
 use num::{Int, SignedInt};
 use num;
 use old_io::{self, IoResult, IoError};
+use io;
 use str;
 use sys_common::mkerr_libc;
 
@@ -39,9 +40,11 @@ macro_rules! helper_init { (static $name:ident: Helper<$m:ty>) => (
 
 pub mod backtrace;
 pub mod c;
-pub mod ext;
 pub mod condvar;
-pub mod fs;
+pub mod ext;
+pub mod fd;
+pub mod fs;  // support for std::old_io
+pub mod fs2; // support for std::fs
 pub mod helper_signal;
 pub mod mutex;
 pub mod os;
@@ -176,6 +179,26 @@ pub fn retry<T, F> (mut f: F) -> T where
     }
 }
 
+pub fn cvt<T: SignedInt>(t: T) -> io::Result<T> {
+    let one: T = Int::one();
+    if t == -one {
+        Err(io::Error::last_os_error())
+    } else {
+        Ok(t)
+    }
+}
+
+pub fn cvt_r<T, F>(mut f: F) -> io::Result<T>
+    where T: SignedInt, F: FnMut() -> T
+{
+    loop {
+        match cvt(f()) {
+            Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
+            other => return other,
+        }
+    }
+}
+
 pub fn ms_to_timeval(ms: u64) -> libc::timeval {
     libc::timeval {
         tv_sec: (ms / 1000) as libc::time_t,
diff --git a/src/libstd/sys/windows/ext.rs b/src/libstd/sys/windows/ext.rs
index a3bbf5c5fe7..dc874c2c791 100644
--- a/src/libstd/sys/windows/ext.rs
+++ b/src/libstd/sys/windows/ext.rs
@@ -18,10 +18,11 @@
 
 pub use sys_common::wtf8::{Wtf8Buf, EncodeWide};
 
-use sys::os_str::Buf;
-use sys_common::{AsInner, FromInner};
 use ffi::{OsStr, OsString};
+use fs::{self, OpenOptions};
 use libc;
+use sys::os_str::Buf;
+use sys_common::{AsInner, FromInner, AsInnerMut};
 
 use old_io;
 
@@ -43,6 +44,12 @@ impl AsRawHandle for old_io::fs::File {
     }
 }
 
+impl AsRawHandle for fs::File {
+    fn as_raw_handle(&self) -> Handle {
+        self.as_inner().handle().raw()
+    }
+}
+
 impl AsRawHandle for old_io::pipe::PipeStream {
     fn as_raw_handle(&self) -> Handle {
         self.as_inner().handle()
@@ -122,9 +129,57 @@ impl OsStrExt for OsStr {
     }
 }
 
+// Windows-specific extensions to `OpenOptions`
+pub trait OpenOptionsExt {
+    /// Override the `dwDesiredAccess` argument to the call to `CreateFile` with
+    /// the specified value.
+    fn desired_access(&mut self, access: i32) -> &mut Self;
+
+    /// Override the `dwCreationDisposition` argument to the call to
+    /// `CreateFile` with the specified value.
+    ///
+    /// This will override any values of the standard `create` flags, for
+    /// example.
+    fn creation_disposition(&mut self, val: i32) -> &mut Self;
+
+    /// Override the `dwFlagsAndAttributes` argument to the call to
+    /// `CreateFile` with the specified value.
+    ///
+    /// This will override any values of the standard flags on the `OpenOptions`
+    /// structure.
+    fn flags_and_attributes(&mut self, val: i32) -> &mut Self;
+
+    /// Override the `dwShareMode` argument to the call to `CreateFile` with the
+    /// specified value.
+    ///
+    /// This will override any values of the standard flags on the `OpenOptions`
+    /// structure.
+    fn share_mode(&mut self, val: i32) -> &mut Self;
+}
+
+impl OpenOptionsExt for OpenOptions {
+    fn desired_access(&mut self, access: i32) -> &mut OpenOptions {
+        self.as_inner_mut().desired_access(access); self
+    }
+    fn creation_disposition(&mut self, access: i32) -> &mut OpenOptions {
+        self.as_inner_mut().creation_disposition(access); self
+    }
+    fn flags_and_attributes(&mut self, access: i32) -> &mut OpenOptions {
+        self.as_inner_mut().flags_and_attributes(access); self
+    }
+    fn share_mode(&mut self, access: i32) -> &mut OpenOptions {
+        self.as_inner_mut().share_mode(access); self
+    }
+}
+
 /// A prelude for conveniently writing platform-specific code.
 ///
 /// Includes all extension traits, and some important type definitions.
 pub mod prelude {
-    pub use super::{Socket, Handle, AsRawSocket, AsRawHandle, OsStrExt, OsStringExt};
+    #[doc(no_inline)]
+    pub use super::{Socket, Handle, AsRawSocket, AsRawHandle};
+    #[doc(no_inline)]
+    pub use super::{OsStrExt, OsStringExt};
+    #[doc(no_inline)]
+    pub use super::OpenOptionsExt;
 }
diff --git a/src/libstd/sys/windows/fs2.rs b/src/libstd/sys/windows/fs2.rs
new file mode 100644
index 00000000000..74bb509789b
--- /dev/null
+++ b/src/libstd/sys/windows/fs2.rs
@@ -0,0 +1,428 @@
+// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+use core::prelude::*;
+use io::prelude::*;
+use os::windows::prelude::*;
+
+use default::Default;
+use ffi::{OsString, AsOsStr};
+use io::{self, Error, SeekFrom};
+use libc::{self, HANDLE};
+use mem;
+use path::{Path, PathBuf};
+use ptr;
+use sys::handle::Handle as RawHandle;
+use sys::{c, cvt};
+use vec::Vec;
+
+pub struct File { handle: RawHandle }
+pub struct FileAttr { data: c::WIN32_FILE_ATTRIBUTE_DATA }
+
+pub struct ReadDir {
+    handle: libc::HANDLE,
+    root: PathBuf,
+    first: Option<libc::WIN32_FIND_DATAW>,
+}
+
+pub struct DirEntry { path: PathBuf }
+
+#[derive(Clone, Default)]
+pub struct OpenOptions {
+    create: bool,
+    append: bool,
+    read: bool,
+    write: bool,
+    truncate: bool,
+    desired_access: Option<libc::DWORD>,
+    share_mode: Option<libc::DWORD>,
+    creation_disposition: Option<libc::DWORD>,
+    flags_and_attributes: Option<libc::DWORD>,
+}
+
+#[derive(Clone, PartialEq, Eq, Debug)]
+pub struct FilePermissions { attrs: libc::DWORD }
+
+impl Iterator for ReadDir {
+    type Item = io::Result<DirEntry>;
+    fn next(&mut self) -> Option<io::Result<DirEntry>> {
+        if let Some(first) = self.first.take() {
+            if let Some(e) = DirEntry::new(&self.root, &first) {
+                return Some(Ok(e));
+            }
+        }
+        unsafe {
+            let mut wfd = mem::zeroed();
+            loop {
+                if libc::FindNextFileW(self.handle, &mut wfd) == 0 {
+                    if libc::GetLastError() ==
+                        c::ERROR_NO_MORE_FILES as libc::DWORD {
+                        return None
+                    } else {
+                        return Some(Err(Error::last_os_error()))
+                    }
+                }
+                if let Some(e) = DirEntry::new(&self.root, &wfd) {
+                    return Some(Ok(e))
+                }
+            }
+        }
+    }
+}
+
+impl Drop for ReadDir {
+    fn drop(&mut self) {
+        let r = unsafe { libc::FindClose(self.handle) };
+        debug_assert!(r != 0);
+    }
+}
+
+impl DirEntry {
+    fn new(root: &Path, wfd: &libc::WIN32_FIND_DATAW) -> Option<DirEntry> {
+        match &wfd.cFileName[0..3] {
+            // check for '.' and '..'
+            [46, 0, ..] |
+            [46, 46, 0, ..] => return None,
+            _ => {}
+        }
+
+        let filename = super::truncate_utf16_at_nul(&wfd.cFileName);
+        let filename: OsString = OsStringExt::from_wide(filename);
+        Some(DirEntry { path: root.join(&filename) })
+    }
+
+    pub fn path(&self) -> PathBuf {
+        self.path.clone()
+    }
+}
+
+impl OpenOptions {
+    pub fn new() -> OpenOptions { Default::default() }
+    pub fn read(&mut self, read: bool) { self.read = read; }
+    pub fn write(&mut self, write: bool) { self.write = write; }
+    pub fn append(&mut self, append: bool) { self.append = append; }
+    pub fn create(&mut self, create: bool) { self.create = create; }
+    pub fn truncate(&mut self, truncate: bool) { self.truncate = truncate; }
+    pub fn creation_disposition(&mut self, val: i32) {
+        self.creation_disposition = Some(val as libc::DWORD);
+    }
+    pub fn flags_and_attributes(&mut self, val: i32) {
+        self.flags_and_attributes = Some(val as libc::DWORD);
+    }
+    pub fn desired_access(&mut self, val: i32) {
+        self.desired_access = Some(val as libc::DWORD);
+    }
+    pub fn share_mode(&mut self, val: i32) {
+        self.share_mode = Some(val as libc::DWORD);
+    }
+
+    fn get_desired_access(&self) -> libc::DWORD {
+        self.desired_access.unwrap_or({
+            let mut base = if self.read {libc::FILE_GENERIC_READ} else {0} |
+                           if self.write {libc::FILE_GENERIC_WRITE} else {0};
+            if self.append {
+                base &= !libc::FILE_WRITE_DATA;
+                base |= libc::FILE_APPEND_DATA;
+            }
+            base
+        })
+    }
+
+    fn get_share_mode(&self) -> libc::DWORD {
+        // libuv has a good comment about this, but the basic idea is that
+        // we try to emulate unix semantics by enabling all sharing by
+        // allowing things such as deleting a file while it's still open.
+        self.share_mode.unwrap_or(libc::FILE_SHARE_READ |
+                                  libc::FILE_SHARE_WRITE |
+                                  libc::FILE_SHARE_DELETE)
+    }
+
+    fn get_creation_disposition(&self) -> libc::DWORD {
+        self.creation_disposition.unwrap_or({
+            match (self.create, self.truncate) {
+                (true, true) => libc::CREATE_ALWAYS,
+                (true, false) => libc::OPEN_ALWAYS,
+                (false, false) => libc::OPEN_EXISTING,
+                (false, true) => {
+                    if self.write && !self.append {
+                        libc::CREATE_ALWAYS
+                    } else {
+                        libc::TRUNCATE_EXISTING
+                    }
+                }
+            }
+        })
+    }
+
+    fn get_flags_and_attributes(&self) -> libc::DWORD {
+        self.flags_and_attributes.unwrap_or(libc::FILE_ATTRIBUTE_NORMAL)
+    }
+}
+
+impl File {
+    pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
+        let path = to_utf16(path);
+        let handle = unsafe {
+            libc::CreateFileW(path.as_ptr(),
+                              opts.get_desired_access(),
+                              opts.get_share_mode(),
+                              ptr::null_mut(),
+                              opts.get_creation_disposition(),
+                              opts.get_flags_and_attributes(),
+                              ptr::null_mut())
+        };
+        if handle == libc::INVALID_HANDLE_VALUE {
+            Err(Error::last_os_error())
+        } else {
+            Ok(File { handle: RawHandle::new(handle) })
+        }
+    }
+
+    pub fn fsync(&self) -> io::Result<()> {
+        try!(cvt(unsafe { libc::FlushFileBuffers(self.handle.raw()) }));
+        Ok(())
+    }
+
+    pub fn datasync(&self) -> io::Result<()> { self.fsync() }
+
+    pub fn truncate(&self, size: u64) -> io::Result<()> {
+        let mut info = c::FILE_END_OF_FILE_INFO {
+            EndOfFile: size as libc::LARGE_INTEGER,
+        };
+        let size = mem::size_of_val(&info);
+        try!(cvt(unsafe {
+            c::SetFileInformationByHandle(self.handle.raw(),
+                                          c::FileEndOfFileInfo,
+                                          &mut info as *mut _ as *mut _,
+                                          size as libc::DWORD)
+        }));
+        Ok(())
+    }
+
+    pub fn file_attr(&self) -> io::Result<FileAttr> {
+        unsafe {
+            let mut info: c::BY_HANDLE_FILE_INFORMATION = mem::zeroed();
+            try!(cvt(c::GetFileInformationByHandle(self.handle.raw(),
+                                                   &mut info)));
+            Ok(FileAttr {
+                data: c::WIN32_FILE_ATTRIBUTE_DATA {
+                    dwFileAttributes: info.dwFileAttributes,
+                    ftCreationTime: info.ftCreationTime,
+                    ftLastAccessTime: info.ftLastAccessTime,
+                    ftLastWriteTime: info.ftLastWriteTime,
+                    nFileSizeHigh: info.nFileSizeHigh,
+                    nFileSizeLow: info.nFileSizeLow,
+                }
+            })
+        }
+    }
+
+    pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
+        let mut read = 0;
+        try!(cvt(unsafe {
+            libc::ReadFile(self.handle.raw(),
+                           buf.as_ptr() as libc::LPVOID,
+                           buf.len() as libc::DWORD,
+                           &mut read,
+                           ptr::null_mut())
+        }));
+        Ok(read as usize)
+    }
+
+    pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
+        let mut amt = 0;
+        try!(cvt(unsafe {
+            libc::WriteFile(self.handle.raw(),
+                            buf.as_ptr() as libc::LPVOID,
+                            buf.len() as libc::DWORD,
+                            &mut amt,
+                            ptr::null_mut())
+        }));
+        Ok(amt as usize)
+    }
+
+    pub fn flush(&self) -> io::Result<()> { Ok(()) }
+
+    pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
+        let (whence, pos) = match pos {
+            SeekFrom::Start(n) => (libc::FILE_BEGIN, n as i64),
+            SeekFrom::End(n) => (libc::FILE_END, n),
+            SeekFrom::Current(n) => (libc::FILE_CURRENT, n),
+        };
+        let pos = pos as libc::LARGE_INTEGER;
+        let mut newpos = 0;
+        try!(cvt(unsafe {
+            libc::SetFilePointerEx(self.handle.raw(), pos,
+                                   &mut newpos, whence)
+        }));
+        Ok(newpos as u64)
+    }
+
+    pub fn handle(&self) -> &RawHandle { &self.handle }
+}
+
+pub fn to_utf16(s: &Path) -> Vec<u16> {
+    s.as_os_str().encode_wide().chain(Some(0).into_iter()).collect()
+}
+
+impl FileAttr {
+    pub fn is_dir(&self) -> bool {
+        self.data.dwFileAttributes & c::FILE_ATTRIBUTE_DIRECTORY != 0
+    }
+    pub fn is_file(&self) -> bool {
+        !self.is_dir()
+    }
+    pub fn size(&self) -> u64 {
+        ((self.data.nFileSizeHigh as u64) << 32) | (self.data.nFileSizeLow as u64)
+    }
+    pub fn perm(&self) -> FilePermissions {
+        FilePermissions { attrs: self.data.dwFileAttributes }
+    }
+
+    pub fn accessed(&self) -> u64 { self.to_ms(&self.data.ftLastAccessTime) }
+    pub fn modified(&self) -> u64 { self.to_ms(&self.data.ftLastWriteTime) }
+
+    fn to_ms(&self, ft: &libc::FILETIME) -> u64 {
+        // FILETIME is in 100ns intervals and there are 10000 intervals in a
+        // millisecond.
+        let bits = (ft.dwLowDateTime as u64) | ((ft.dwHighDateTime as u64) << 32);
+        bits / 10000
+    }
+}
+
+impl FilePermissions {
+    pub fn readonly(&self) -> bool {
+        self.attrs & c::FILE_ATTRIBUTE_READONLY != 0
+    }
+
+    pub fn set_readonly(&mut self, readonly: bool) {
+        if readonly {
+            self.attrs |= c::FILE_ATTRIBUTE_READONLY;
+        } else {
+            self.attrs &= !c::FILE_ATTRIBUTE_READONLY;
+        }
+    }
+}
+
+pub fn mkdir(p: &Path) -> io::Result<()> {
+    let p = to_utf16(p);
+    try!(cvt(unsafe {
+        libc::CreateDirectoryW(p.as_ptr(), ptr::null_mut())
+    }));
+    Ok(())
+}
+
+pub fn readdir(p: &Path) -> io::Result<ReadDir> {
+    let root = p.to_path_buf();
+    let star = p.join("*");
+    let path = to_utf16(&star);
+
+    unsafe {
+        let mut wfd = mem::zeroed();
+        let find_handle = libc::FindFirstFileW(path.as_ptr(), &mut wfd);
+        if find_handle != libc::INVALID_HANDLE_VALUE {
+            Ok(ReadDir { handle: find_handle, root: root, first: Some(wfd) })
+        } else {
+            Err(Error::last_os_error())
+        }
+    }
+}
+
+pub fn unlink(p: &Path) -> io::Result<()> {
+    let p_utf16 = to_utf16(p);
+    try!(cvt(unsafe { libc::DeleteFileW(p_utf16.as_ptr()) }));
+    Ok(())
+}
+
+pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
+    let old = to_utf16(old);
+    let new = to_utf16(new);
+    try!(cvt(unsafe {
+        libc::MoveFileExW(old.as_ptr(), new.as_ptr(),
+                          libc::MOVEFILE_REPLACE_EXISTING)
+    }));
+    Ok(())
+}
+
+pub fn rmdir(p: &Path) -> io::Result<()> {
+    let p = to_utf16(p);
+    try!(cvt(unsafe { c::RemoveDirectoryW(p.as_ptr()) }));
+    Ok(())
+}
+
+pub fn readlink(p: &Path) -> io::Result<PathBuf> {
+    use sys::c::compat::kernel32::GetFinalPathNameByHandleW;
+    let mut opts = OpenOptions::new();
+    opts.read(true);
+    let file = try!(File::open(p, &opts));;
+
+    // Specify (sz - 1) because the documentation states that it's the size
+    // without the null pointer
+    //
+    // FIXME: I have a feeling that this reads intermediate symlinks as well.
+    let ret: OsString = try!(super::fill_utf16_buf_new(|buf, sz| unsafe {
+        GetFinalPathNameByHandleW(file.handle.raw(),
+                                  buf as *const u16,
+                                  sz - 1,
+                                  libc::VOLUME_NAME_DOS)
+    }, |s| OsStringExt::from_wide(s)));
+    Ok(PathBuf::new(&ret))
+}
+
+pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
+    use sys::c::compat::kernel32::CreateSymbolicLinkW;
+    let src = to_utf16(src);
+    let dst = to_utf16(dst);
+    try!(cvt(unsafe {
+        CreateSymbolicLinkW(dst.as_ptr(), src.as_ptr(), 0) as libc::BOOL
+    }));
+    Ok(())
+}
+
+pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
+    let src = to_utf16(src);
+    let dst = to_utf16(dst);
+    try!(cvt(unsafe {
+        libc::CreateHardLinkW(dst.as_ptr(), src.as_ptr(), ptr::null_mut())
+    }));
+    Ok(())
+}
+
+pub fn stat(p: &Path) -> io::Result<FileAttr> {
+    let p = to_utf16(p);
+    unsafe {
+        let mut attr: FileAttr = mem::zeroed();
+        try!(cvt(c::GetFileAttributesExW(p.as_ptr(),
+                                         c::GetFileExInfoStandard,
+                                         &mut attr.data as *mut _ as *mut _)));
+        Ok(attr)
+    }
+}
+
+pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
+    let p = to_utf16(p);
+    unsafe {
+        try!(cvt(c::SetFileAttributesW(p.as_ptr(), perm.attrs)));
+        Ok(())
+    }
+}
+
+pub fn utimes(p: &Path, atime: u64, mtime: u64) -> io::Result<()> {
+    let atime = super::ms_to_filetime(atime);
+    let mtime = super::ms_to_filetime(mtime);
+
+    let mut o = OpenOptions::new();
+    o.write(true);
+    let f = try!(File::open(p, &o));
+    try!(cvt(unsafe {
+        c::SetFileTime(f.handle.raw(), 0 as *const _, &atime, &mtime)
+    }));
+    Ok(())
+}
diff --git a/src/libstd/sys/windows/handle.rs b/src/libstd/sys/windows/handle.rs
index 6737eeef125..52aa5fb036a 100644
--- a/src/libstd/sys/windows/handle.rs
+++ b/src/libstd/sys/windows/handle.rs
@@ -21,6 +21,7 @@ impl Handle {
     pub fn new(handle: HANDLE) -> Handle {
         Handle(handle)
     }
+    pub fn raw(&self) -> HANDLE { self.0 }
 }
 
 impl Drop for Handle {
diff --git a/src/libstd/sys/windows/mod.rs b/src/libstd/sys/windows/mod.rs
index f1af70e2cf7..140bdb14501 100644
--- a/src/libstd/sys/windows/mod.rs
+++ b/src/libstd/sys/windows/mod.rs
@@ -15,10 +15,11 @@
 use prelude::v1::*;
 
 use ffi::OsStr;
-use io::ErrorKind;
+use io::{self, ErrorKind};
 use libc;
 use mem;
 use old_io::{self, IoResult, IoError};
+use num::Int;
 use os::windows::OsStrExt;
 use sync::{Once, ONCE_INIT};
 
@@ -38,6 +39,7 @@ pub mod c;
 pub mod condvar;
 pub mod ext;
 pub mod fs;
+pub mod fs2;
 pub mod handle;
 pub mod helper_signal;
 pub mod mutex;
@@ -248,7 +250,7 @@ fn to_utf16_os(s: &OsStr) -> Vec<u16> {
 // Once the syscall has completed (errors bail out early) the second closure is
 // yielded the data which has been read from the syscall. The return value
 // from this closure is then the return value of the function.
-fn fill_utf16_buf<F1, F2, T>(mut f1: F1, f2: F2) -> IoResult<T>
+fn fill_utf16_buf_base<F1, F2, T>(mut f1: F1, f2: F2) -> Result<T, ()>
     where F1: FnMut(*mut u16, libc::DWORD) -> libc::DWORD,
           F2: FnOnce(&[u16]) -> T
 {
@@ -280,7 +282,7 @@ fn fill_utf16_buf<F1, F2, T>(mut f1: F1, f2: F2) -> IoResult<T>
             c::SetLastError(0);
             let k = match f1(buf.as_mut_ptr(), n as libc::DWORD) {
                 0 if libc::GetLastError() == 0 => 0,
-                0 => return Err(IoError::last_error()),
+                0 => return Err(()),
                 n => n,
             } as usize;
             if k == n && libc::GetLastError() ==
@@ -295,6 +297,20 @@ fn fill_utf16_buf<F1, F2, T>(mut f1: F1, f2: F2) -> IoResult<T>
     }
 }
 
+fn fill_utf16_buf<F1, F2, T>(f1: F1, f2: F2) -> IoResult<T>
+    where F1: FnMut(*mut u16, libc::DWORD) -> libc::DWORD,
+          F2: FnOnce(&[u16]) -> T
+{
+    fill_utf16_buf_base(f1, f2).map_err(|()| IoError::last_error())
+}
+
+fn fill_utf16_buf_new<F1, F2, T>(f1: F1, f2: F2) -> io::Result<T>
+    where F1: FnMut(*mut u16, libc::DWORD) -> libc::DWORD,
+          F2: FnOnce(&[u16]) -> T
+{
+    fill_utf16_buf_base(f1, f2).map_err(|()| io::Error::last_os_error())
+}
+
 fn os2path(s: &[u16]) -> Path {
     // FIXME: this should not be a panicking conversion (aka path reform)
     Path::new(String::from_utf16(s).unwrap())
@@ -307,3 +323,21 @@ pub fn truncate_utf16_at_nul<'a>(v: &'a [u16]) -> &'a [u16] {
         None => v
     }
 }
+
+fn cvt<I: Int>(i: I) -> io::Result<I> {
+    if i == Int::zero() {
+        Err(io::Error::last_os_error())
+    } else {
+        Ok(i)
+    }
+}
+
+fn ms_to_filetime(ms: u64) -> libc::FILETIME {
+    // A FILETIME is a count of 100 nanosecond intervals, so we multiply by
+    // 10000 b/c there are 10000 intervals in 1 ms
+    let ms = ms * 10000;
+    libc::FILETIME {
+        dwLowDateTime: ms as u32,
+        dwHighDateTime: (ms >> 32) as u32,
+    }
+}
diff --git a/src/libstd/sys/windows/os.rs b/src/libstd/sys/windows/os.rs
index d8e3e6981df..7e684c52341 100644
--- a/src/libstd/sys/windows/os.rs
+++ b/src/libstd/sys/windows/os.rs
@@ -191,7 +191,7 @@ impl<'a> Iterator for SplitPaths<'a> {
     }
 }
 
-#[derive(Show)]
+#[derive(Debug)]
 pub struct JoinPathsError;
 
 pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>