1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 use os::windows::prelude::*;
16 use io::{self, Error, SeekFrom};
18 use path::{Path, PathBuf};
22 use sys::handle::Handle;
23 use sys::time::SystemTime;
25 use sys_common::FromInner;
29 pub struct File { handle: Handle }
33 data: c::WIN32_FILE_ATTRIBUTE_DATA,
34 reparse_tag: c::DWORD,
37 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
39 Dir, File, SymlinkFile, SymlinkDir, ReparsePoint, MountPoint,
43 handle: FindNextFileHandle,
45 first: Option<c::WIN32_FIND_DATAW>,
48 struct FindNextFileHandle(c::HANDLE);
50 unsafe impl Send for FindNextFileHandle {}
51 unsafe impl Sync for FindNextFileHandle {}
55 data: c::WIN32_FIND_DATAW,
59 pub struct OpenOptions {
69 access_mode: Option<c::DWORD>,
72 security_qos_flags: c::DWORD,
73 security_attributes: usize, // FIXME: should be a reference
76 #[derive(Clone, PartialEq, Eq, Debug)]
77 pub struct FilePermissions { attrs: c::DWORD }
79 pub struct DirBuilder;
81 impl Iterator for ReadDir {
82 type Item = io::Result<DirEntry>;
83 fn next(&mut self) -> Option<io::Result<DirEntry>> {
84 if let Some(first) = self.first.take() {
85 if let Some(e) = DirEntry::new(&self.root, &first) {
90 let mut wfd = mem::zeroed();
92 if c::FindNextFileW(self.handle.0, &mut wfd) == 0 {
93 if c::GetLastError() == c::ERROR_NO_MORE_FILES {
96 return Some(Err(Error::last_os_error()))
99 if let Some(e) = DirEntry::new(&self.root, &wfd) {
107 impl Drop for FindNextFileHandle {
109 let r = unsafe { c::FindClose(self.0) };
110 debug_assert!(r != 0);
115 fn new(root: &Arc<PathBuf>, wfd: &c::WIN32_FIND_DATAW) -> Option<DirEntry> {
116 match &wfd.cFileName[0..3] {
117 // check for '.' and '..'
119 [46, 46, 0, ..] => return None,
129 pub fn path(&self) -> PathBuf {
130 self.root.join(&self.file_name())
133 pub fn file_name(&self) -> OsString {
134 let filename = super::truncate_utf16_at_nul(&self.data.cFileName);
135 OsString::from_wide(filename)
138 pub fn file_type(&self) -> io::Result<FileType> {
139 Ok(FileType::new(self.data.dwFileAttributes,
140 /* reparse_tag = */ self.data.dwReserved0))
143 pub fn metadata(&self) -> io::Result<FileAttr> {
145 data: c::WIN32_FILE_ATTRIBUTE_DATA {
146 dwFileAttributes: self.data.dwFileAttributes,
147 ftCreationTime: self.data.ftCreationTime,
148 ftLastAccessTime: self.data.ftLastAccessTime,
149 ftLastWriteTime: self.data.ftLastWriteTime,
150 nFileSizeHigh: self.data.nFileSizeHigh,
151 nFileSizeLow: self.data.nFileSizeLow,
153 reparse_tag: if self.data.dwFileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
154 // reserved unless this is a reparse point
155 self.data.dwReserved0
164 pub fn new() -> OpenOptions {
176 share_mode: c::FILE_SHARE_READ | c::FILE_SHARE_WRITE | c::FILE_SHARE_DELETE,
178 security_qos_flags: 0,
179 security_attributes: 0,
183 pub fn read(&mut self, read: bool) { self.read = read; }
184 pub fn write(&mut self, write: bool) { self.write = write; }
185 pub fn append(&mut self, append: bool) { self.append = append; }
186 pub fn truncate(&mut self, truncate: bool) { self.truncate = truncate; }
187 pub fn create(&mut self, create: bool) { self.create = create; }
188 pub fn create_new(&mut self, create_new: bool) { self.create_new = create_new; }
190 pub fn custom_flags(&mut self, flags: u32) { self.custom_flags = flags; }
191 pub fn access_mode(&mut self, access_mode: u32) { self.access_mode = Some(access_mode); }
192 pub fn share_mode(&mut self, share_mode: u32) { self.share_mode = share_mode; }
193 pub fn attributes(&mut self, attrs: u32) { self.attributes = attrs; }
194 pub fn security_qos_flags(&mut self, flags: u32) { self.security_qos_flags = flags; }
195 pub fn security_attributes(&mut self, attrs: c::LPSECURITY_ATTRIBUTES) {
196 self.security_attributes = attrs as usize;
199 fn get_access_mode(&self) -> io::Result<c::DWORD> {
200 const ERROR_INVALID_PARAMETER: i32 = 87;
202 match (self.read, self.write, self.append, self.access_mode) {
203 (_, _, _, Some(mode)) => Ok(mode),
204 (true, false, false, None) => Ok(c::GENERIC_READ),
205 (false, true, false, None) => Ok(c::GENERIC_WRITE),
206 (true, true, false, None) => Ok(c::GENERIC_READ | c::GENERIC_WRITE),
207 (false, _, true, None) => Ok(c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA),
208 (true, _, true, None) => Ok(c::GENERIC_READ |
209 (c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA)),
210 (false, false, false, None) => Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER)),
214 fn get_creation_mode(&self) -> io::Result<c::DWORD> {
215 const ERROR_INVALID_PARAMETER: i32 = 87;
217 match (self.write, self.append) {
220 if self.truncate || self.create || self.create_new {
221 return Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER));
224 if self.truncate && !self.create_new {
225 return Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER));
229 Ok(match (self.create, self.truncate, self.create_new) {
230 (false, false, false) => c::OPEN_EXISTING,
231 (true, false, false) => c::OPEN_ALWAYS,
232 (false, true, false) => c::TRUNCATE_EXISTING,
233 (true, true, false) => c::CREATE_ALWAYS,
234 (_, _, true) => c::CREATE_NEW,
238 fn get_flags_and_attributes(&self) -> c::DWORD {
241 self.security_qos_flags |
242 if self.security_qos_flags != 0 { c::SECURITY_SQOS_PRESENT } else { 0 } |
243 if self.create_new { c::FILE_FLAG_OPEN_REPARSE_POINT } else { 0 }
248 pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
249 let path = try!(to_u16s(path));
250 let handle = unsafe {
251 c::CreateFileW(path.as_ptr(),
252 try!(opts.get_access_mode()),
254 opts.security_attributes as *mut _,
255 try!(opts.get_creation_mode()),
256 opts.get_flags_and_attributes(),
259 if handle == c::INVALID_HANDLE_VALUE {
260 Err(Error::last_os_error())
262 Ok(File { handle: Handle::new(handle) })
266 pub fn fsync(&self) -> io::Result<()> {
267 try!(cvt(unsafe { c::FlushFileBuffers(self.handle.raw()) }));
271 pub fn datasync(&self) -> io::Result<()> { self.fsync() }
273 pub fn truncate(&self, size: u64) -> io::Result<()> {
274 let mut info = c::FILE_END_OF_FILE_INFO {
275 EndOfFile: size as c::LARGE_INTEGER,
277 let size = mem::size_of_val(&info);
279 c::SetFileInformationByHandle(self.handle.raw(),
280 c::FileEndOfFileInfo,
281 &mut info as *mut _ as *mut _,
287 pub fn file_attr(&self) -> io::Result<FileAttr> {
289 let mut info: c::BY_HANDLE_FILE_INFORMATION = mem::zeroed();
290 try!(cvt(c::GetFileInformationByHandle(self.handle.raw(),
292 let mut attr = FileAttr {
293 data: c::WIN32_FILE_ATTRIBUTE_DATA {
294 dwFileAttributes: info.dwFileAttributes,
295 ftCreationTime: info.ftCreationTime,
296 ftLastAccessTime: info.ftLastAccessTime,
297 ftLastWriteTime: info.ftLastWriteTime,
298 nFileSizeHigh: info.nFileSizeHigh,
299 nFileSizeLow: info.nFileSizeLow,
303 if attr.is_reparse_point() {
304 let mut b = [0; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
305 if let Ok((_, buf)) = self.reparse_point(&mut b) {
306 attr.reparse_tag = buf.ReparseTag;
313 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
314 self.handle.read(buf)
317 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
318 self.handle.write(buf)
321 pub fn flush(&self) -> io::Result<()> { Ok(()) }
323 pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
324 let (whence, pos) = match pos {
325 SeekFrom::Start(n) => (c::FILE_BEGIN, n as i64),
326 SeekFrom::End(n) => (c::FILE_END, n),
327 SeekFrom::Current(n) => (c::FILE_CURRENT, n),
329 let pos = pos as c::LARGE_INTEGER;
332 c::SetFilePointerEx(self.handle.raw(), pos,
338 pub fn duplicate(&self) -> io::Result<File> {
340 handle: try!(self.handle.duplicate(0, true, c::DUPLICATE_SAME_ACCESS)),
344 pub fn handle(&self) -> &Handle { &self.handle }
346 pub fn into_handle(self) -> Handle { self.handle }
348 fn reparse_point<'a>(&self,
349 space: &'a mut [u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE])
350 -> io::Result<(c::DWORD, &'a c::REPARSE_DATA_BUFFER)> {
354 c::DeviceIoControl(self.handle.raw(),
355 c::FSCTL_GET_REPARSE_POINT,
358 space.as_mut_ptr() as *mut _,
359 space.len() as c::DWORD,
363 Ok((bytes, &*(space.as_ptr() as *const c::REPARSE_DATA_BUFFER)))
367 fn readlink(&self) -> io::Result<PathBuf> {
368 let mut space = [0u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
369 let (_bytes, buf) = try!(self.reparse_point(&mut space));
371 let (path_buffer, subst_off, subst_len, relative) = match buf.ReparseTag {
372 c::IO_REPARSE_TAG_SYMLINK => {
373 let info: *const c::SYMBOLIC_LINK_REPARSE_BUFFER =
374 &buf.rest as *const _ as *const _;
375 (&(*info).PathBuffer as *const _ as *const u16,
376 (*info).SubstituteNameOffset / 2,
377 (*info).SubstituteNameLength / 2,
378 (*info).Flags & c::SYMLINK_FLAG_RELATIVE != 0)
380 c::IO_REPARSE_TAG_MOUNT_POINT => {
381 let info: *const c::MOUNT_POINT_REPARSE_BUFFER =
382 &buf.rest as *const _ as *const _;
383 (&(*info).PathBuffer as *const _ as *const u16,
384 (*info).SubstituteNameOffset / 2,
385 (*info).SubstituteNameLength / 2,
388 _ => return Err(io::Error::new(io::ErrorKind::Other,
389 "Unsupported reparse point type"))
391 let subst_ptr = path_buffer.offset(subst_off as isize);
392 let mut subst = slice::from_raw_parts(subst_ptr, subst_len as usize);
393 // Absolute paths start with an NT internal namespace prefix `\??\`
394 // We should not let it leak through.
395 if !relative && subst.starts_with(&[92u16, 63u16, 63u16, 92u16]) {
398 Ok(PathBuf::from(OsString::from_wide(subst)))
403 impl FromInner<c::HANDLE> for File {
404 fn from_inner(handle: c::HANDLE) -> File {
405 File { handle: Handle::new(handle) }
409 impl fmt::Debug for File {
410 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
411 // FIXME(#24570): add more info here (e.g. mode)
412 let mut b = f.debug_struct("File");
413 b.field("handle", &self.handle.raw());
414 if let Ok(path) = get_path(&self) {
415 b.field("path", &path);
422 pub fn size(&self) -> u64 {
423 ((self.data.nFileSizeHigh as u64) << 32) | (self.data.nFileSizeLow as u64)
426 pub fn perm(&self) -> FilePermissions {
427 FilePermissions { attrs: self.data.dwFileAttributes }
430 pub fn attrs(&self) -> u32 { self.data.dwFileAttributes as u32 }
432 pub fn file_type(&self) -> FileType {
433 FileType::new(self.data.dwFileAttributes, self.reparse_tag)
436 pub fn modified(&self) -> io::Result<SystemTime> {
437 Ok(SystemTime::from(self.data.ftLastWriteTime))
440 pub fn accessed(&self) -> io::Result<SystemTime> {
441 Ok(SystemTime::from(self.data.ftLastAccessTime))
444 pub fn created(&self) -> io::Result<SystemTime> {
445 Ok(SystemTime::from(self.data.ftCreationTime))
448 pub fn modified_u64(&self) -> u64 {
449 to_u64(&self.data.ftLastWriteTime)
452 pub fn accessed_u64(&self) -> u64 {
453 to_u64(&self.data.ftLastAccessTime)
456 pub fn created_u64(&self) -> u64 {
457 to_u64(&self.data.ftCreationTime)
460 fn is_reparse_point(&self) -> bool {
461 self.data.dwFileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0
465 fn to_u64(ft: &c::FILETIME) -> u64 {
466 (ft.dwLowDateTime as u64) | ((ft.dwHighDateTime as u64) << 32)
469 impl FilePermissions {
470 pub fn readonly(&self) -> bool {
471 self.attrs & c::FILE_ATTRIBUTE_READONLY != 0
474 pub fn set_readonly(&mut self, readonly: bool) {
476 self.attrs |= c::FILE_ATTRIBUTE_READONLY;
478 self.attrs &= !c::FILE_ATTRIBUTE_READONLY;
484 fn new(attrs: c::DWORD, reparse_tag: c::DWORD) -> FileType {
485 match (attrs & c::FILE_ATTRIBUTE_DIRECTORY != 0,
486 attrs & c::FILE_ATTRIBUTE_REPARSE_POINT != 0,
488 (false, false, _) => FileType::File,
489 (true, false, _) => FileType::Dir,
490 (false, true, c::IO_REPARSE_TAG_SYMLINK) => FileType::SymlinkFile,
491 (true, true, c::IO_REPARSE_TAG_SYMLINK) => FileType::SymlinkDir,
492 (true, true, c::IO_REPARSE_TAG_MOUNT_POINT) => FileType::MountPoint,
493 (_, true, _) => FileType::ReparsePoint,
494 // Note: if a _file_ has a reparse tag of the type IO_REPARSE_TAG_MOUNT_POINT it is
495 // invalid, as junctions always have to be dirs. We set the filetype to ReparsePoint
496 // to indicate it is something symlink-like, but not something you can follow.
500 pub fn is_dir(&self) -> bool { *self == FileType::Dir }
501 pub fn is_file(&self) -> bool { *self == FileType::File }
502 pub fn is_symlink(&self) -> bool {
503 *self == FileType::SymlinkFile ||
504 *self == FileType::SymlinkDir ||
505 *self == FileType::MountPoint
507 pub fn is_symlink_dir(&self) -> bool {
508 *self == FileType::SymlinkDir || *self == FileType::MountPoint
513 pub fn new() -> DirBuilder { DirBuilder }
515 pub fn mkdir(&self, p: &Path) -> io::Result<()> {
516 let p = try!(to_u16s(p));
518 c::CreateDirectoryW(p.as_ptr(), ptr::null_mut())
524 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
525 let root = p.to_path_buf();
526 let star = p.join("*");
527 let path = try!(to_u16s(&star));
530 let mut wfd = mem::zeroed();
531 let find_handle = c::FindFirstFileW(path.as_ptr(), &mut wfd);
532 if find_handle != c::INVALID_HANDLE_VALUE {
534 handle: FindNextFileHandle(find_handle),
535 root: Arc::new(root),
539 Err(Error::last_os_error())
544 pub fn unlink(p: &Path) -> io::Result<()> {
545 let p_u16s = try!(to_u16s(p));
546 try!(cvt(unsafe { c::DeleteFileW(p_u16s.as_ptr()) }));
550 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
551 let old = try!(to_u16s(old));
552 let new = try!(to_u16s(new));
554 c::MoveFileExW(old.as_ptr(), new.as_ptr(), c::MOVEFILE_REPLACE_EXISTING)
559 pub fn rmdir(p: &Path) -> io::Result<()> {
560 let p = try!(to_u16s(p));
561 try!(cvt(unsafe { c::RemoveDirectoryW(p.as_ptr()) }));
565 pub fn remove_dir_all(path: &Path) -> io::Result<()> {
566 let filetype = try!(lstat(path)).file_type();
567 if filetype.is_symlink() {
568 // On Windows symlinks to files and directories are removed differently.
569 // rmdir only deletes dir symlinks and junctions, not file symlinks.
572 remove_dir_all_recursive(path)
576 fn remove_dir_all_recursive(path: &Path) -> io::Result<()> {
577 for child in try!(readdir(path)) {
578 let child = try!(child);
579 let child_type = try!(child.file_type());
580 if child_type.is_dir() {
581 try!(remove_dir_all_recursive(&child.path()));
582 } else if child_type.is_symlink_dir() {
583 try!(rmdir(&child.path()));
585 try!(unlink(&child.path()));
591 pub fn readlink(path: &Path) -> io::Result<PathBuf> {
592 // Open the link with no access mode, instead of generic read.
593 // By default FILE_LIST_DIRECTORY is denied for the junction "C:\Documents and Settings", so
594 // this is needed for a common case.
595 let mut opts = OpenOptions::new();
597 opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT |
598 c::FILE_FLAG_BACKUP_SEMANTICS);
599 let file = try!(File::open(&path, &opts));
603 pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
604 symlink_inner(src, dst, false)
607 pub fn symlink_inner(src: &Path, dst: &Path, dir: bool) -> io::Result<()> {
608 let src = try!(to_u16s(src));
609 let dst = try!(to_u16s(dst));
610 let flags = if dir { c::SYMBOLIC_LINK_FLAG_DIRECTORY } else { 0 };
612 c::CreateSymbolicLinkW(dst.as_ptr(), src.as_ptr(), flags) as c::BOOL
617 pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
618 let src = try!(to_u16s(src));
619 let dst = try!(to_u16s(dst));
621 c::CreateHardLinkW(dst.as_ptr(), src.as_ptr(), ptr::null_mut())
626 pub fn stat(path: &Path) -> io::Result<FileAttr> {
627 let mut opts = OpenOptions::new();
628 // No read or write permissions are necessary
630 // This flag is so we can open directories too
631 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
632 let file = try!(File::open(path, &opts));
636 pub fn lstat(path: &Path) -> io::Result<FileAttr> {
637 let mut opts = OpenOptions::new();
638 // No read or write permissions are necessary
640 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS | c::FILE_FLAG_OPEN_REPARSE_POINT);
641 let file = try!(File::open(path, &opts));
645 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
646 let p = try!(to_u16s(p));
648 try!(cvt(c::SetFileAttributesW(p.as_ptr(), perm.attrs)));
653 fn get_path(f: &File) -> io::Result<PathBuf> {
654 super::fill_utf16_buf(|buf, sz| unsafe {
655 c::GetFinalPathNameByHandleW(f.handle.raw(), buf, sz,
658 PathBuf::from(OsString::from_wide(buf))
662 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
663 let mut opts = OpenOptions::new();
664 // No read or write permissions are necessary
666 // This flag is so we can open directories too
667 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
668 let f = try!(File::open(p, &opts));
672 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
673 unsafe extern "system" fn callback(
674 _TotalFileSize: c::LARGE_INTEGER,
675 TotalBytesTransferred: c::LARGE_INTEGER,
676 _StreamSize: c::LARGE_INTEGER,
677 _StreamBytesTransferred: c::LARGE_INTEGER,
678 _dwStreamNumber: c::DWORD,
679 _dwCallbackReason: c::DWORD,
680 _hSourceFile: c::HANDLE,
681 _hDestinationFile: c::HANDLE,
684 *(lpData as *mut i64) = TotalBytesTransferred;
687 let pfrom = try!(to_u16s(from));
688 let pto = try!(to_u16s(to));
691 c::CopyFileExW(pfrom.as_ptr(), pto.as_ptr(), Some(callback),
692 &mut size as *mut _ as *mut _, ptr::null_mut(), 0)
698 pub fn symlink_junction<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
699 symlink_junction_inner(src.as_ref(), dst.as_ref())
702 // Creating a directory junction on windows involves dealing with reparse
703 // points and the DeviceIoControl function, and this code is a skeleton of
704 // what can be found here:
706 // http://www.flexhex.com/docs/articles/hard-links.phtml
708 fn symlink_junction_inner(target: &Path, junction: &Path) -> io::Result<()> {
709 let d = DirBuilder::new();
710 try!(d.mkdir(&junction));
712 let mut opts = OpenOptions::new();
714 opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT |
715 c::FILE_FLAG_BACKUP_SEMANTICS);
716 let f = try!(File::open(junction, &opts));
717 let h = f.handle().raw();
720 let mut data = [0u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
721 let mut db = data.as_mut_ptr()
722 as *mut c::REPARSE_MOUNTPOINT_DATA_BUFFER;
723 let buf = &mut (*db).ReparseTarget as *mut _;
725 // FIXME: this conversion is very hacky
727 let v = v.iter().map(|x| *x as u16);
728 for c in v.chain(target.as_os_str().encode_wide()) {
734 (*db).ReparseTag = c::IO_REPARSE_TAG_MOUNT_POINT;
735 (*db).ReparseTargetMaximumLength = (i * 2) as c::WORD;
736 (*db).ReparseTargetLength = ((i - 1) * 2) as c::WORD;
737 (*db).ReparseDataLength =
738 (*db).ReparseTargetLength as c::DWORD + 12;
741 cvt(c::DeviceIoControl(h as *mut _,
742 c::FSCTL_SET_REPARSE_POINT,
743 data.as_ptr() as *mut _,
744 (*db).ReparseDataLength + 8,
747 ptr::null_mut())).map(|_| ())