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 }
34 creation_time: c::FILETIME,
35 last_access_time: c::FILETIME,
36 last_write_time: c::FILETIME,
38 reparse_tag: c::DWORD,
41 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
43 Dir, File, SymlinkFile, SymlinkDir, ReparsePoint, MountPoint,
47 handle: FindNextFileHandle,
49 first: Option<c::WIN32_FIND_DATAW>,
52 struct FindNextFileHandle(c::HANDLE);
54 unsafe impl Send for FindNextFileHandle {}
55 unsafe impl Sync for FindNextFileHandle {}
59 data: c::WIN32_FIND_DATAW,
63 pub struct OpenOptions {
73 access_mode: Option<c::DWORD>,
76 security_qos_flags: c::DWORD,
77 security_attributes: usize, // FIXME: should be a reference
80 #[derive(Clone, PartialEq, Eq, Debug)]
81 pub struct FilePermissions { attrs: c::DWORD }
83 pub struct DirBuilder;
85 impl Iterator for ReadDir {
86 type Item = io::Result<DirEntry>;
87 fn next(&mut self) -> Option<io::Result<DirEntry>> {
88 if let Some(first) = self.first.take() {
89 if let Some(e) = DirEntry::new(&self.root, &first) {
94 let mut wfd = mem::zeroed();
96 if c::FindNextFileW(self.handle.0, &mut wfd) == 0 {
97 if c::GetLastError() == c::ERROR_NO_MORE_FILES {
100 return Some(Err(Error::last_os_error()))
103 if let Some(e) = DirEntry::new(&self.root, &wfd) {
111 impl Drop for FindNextFileHandle {
113 let r = unsafe { c::FindClose(self.0) };
114 debug_assert!(r != 0);
119 fn new(root: &Arc<PathBuf>, wfd: &c::WIN32_FIND_DATAW) -> Option<DirEntry> {
120 match &wfd.cFileName[0..3] {
121 // check for '.' and '..'
123 [46, 46, 0, ..] => return None,
133 pub fn path(&self) -> PathBuf {
134 self.root.join(&self.file_name())
137 pub fn file_name(&self) -> OsString {
138 let filename = super::truncate_utf16_at_nul(&self.data.cFileName);
139 OsString::from_wide(filename)
142 pub fn file_type(&self) -> io::Result<FileType> {
143 Ok(FileType::new(self.data.dwFileAttributes,
144 /* reparse_tag = */ self.data.dwReserved0))
147 pub fn metadata(&self) -> io::Result<FileAttr> {
149 attributes: self.data.dwFileAttributes,
150 creation_time: self.data.ftCreationTime,
151 last_access_time: self.data.ftLastAccessTime,
152 last_write_time: self.data.ftLastWriteTime,
153 file_size: ((self.data.nFileSizeHigh as u64) << 32) | (self.data.nFileSizeLow as u64),
154 reparse_tag: if self.data.dwFileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
155 // reserved unless this is a reparse point
156 self.data.dwReserved0
165 pub fn new() -> OpenOptions {
177 share_mode: c::FILE_SHARE_READ | c::FILE_SHARE_WRITE | c::FILE_SHARE_DELETE,
179 security_qos_flags: 0,
180 security_attributes: 0,
184 pub fn read(&mut self, read: bool) { self.read = read; }
185 pub fn write(&mut self, write: bool) { self.write = write; }
186 pub fn append(&mut self, append: bool) { self.append = append; }
187 pub fn truncate(&mut self, truncate: bool) { self.truncate = truncate; }
188 pub fn create(&mut self, create: bool) { self.create = create; }
189 pub fn create_new(&mut self, create_new: bool) { self.create_new = create_new; }
191 pub fn custom_flags(&mut self, flags: u32) { self.custom_flags = flags; }
192 pub fn access_mode(&mut self, access_mode: u32) { self.access_mode = Some(access_mode); }
193 pub fn share_mode(&mut self, share_mode: u32) { self.share_mode = share_mode; }
194 pub fn attributes(&mut self, attrs: u32) { self.attributes = attrs; }
195 pub fn security_qos_flags(&mut self, flags: u32) { self.security_qos_flags = flags; }
196 pub fn security_attributes(&mut self, attrs: c::LPSECURITY_ATTRIBUTES) {
197 self.security_attributes = attrs as usize;
200 fn get_access_mode(&self) -> io::Result<c::DWORD> {
201 const ERROR_INVALID_PARAMETER: i32 = 87;
203 match (self.read, self.write, self.append, self.access_mode) {
204 (_, _, _, Some(mode)) => Ok(mode),
205 (true, false, false, None) => Ok(c::GENERIC_READ),
206 (false, true, false, None) => Ok(c::GENERIC_WRITE),
207 (true, true, false, None) => Ok(c::GENERIC_READ | c::GENERIC_WRITE),
208 (false, _, true, None) => Ok(c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA),
209 (true, _, true, None) => Ok(c::GENERIC_READ |
210 (c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA)),
211 (false, false, false, None) => Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER)),
215 fn get_creation_mode(&self) -> io::Result<c::DWORD> {
216 const ERROR_INVALID_PARAMETER: i32 = 87;
218 match (self.write, self.append) {
221 if self.truncate || self.create || self.create_new {
222 return Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER));
225 if self.truncate && !self.create_new {
226 return Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER));
230 Ok(match (self.create, self.truncate, self.create_new) {
231 (false, false, false) => c::OPEN_EXISTING,
232 (true, false, false) => c::OPEN_ALWAYS,
233 (false, true, false) => c::TRUNCATE_EXISTING,
234 (true, true, false) => c::CREATE_ALWAYS,
235 (_, _, true) => c::CREATE_NEW,
239 fn get_flags_and_attributes(&self) -> c::DWORD {
242 self.security_qos_flags |
243 if self.security_qos_flags != 0 { c::SECURITY_SQOS_PRESENT } else { 0 } |
244 if self.create_new { c::FILE_FLAG_OPEN_REPARSE_POINT } else { 0 }
249 pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
250 let path = try!(to_u16s(path));
251 let handle = unsafe {
252 c::CreateFileW(path.as_ptr(),
253 try!(opts.get_access_mode()),
255 opts.security_attributes as *mut _,
256 try!(opts.get_creation_mode()),
257 opts.get_flags_and_attributes(),
260 if handle == c::INVALID_HANDLE_VALUE {
261 Err(Error::last_os_error())
263 Ok(File { handle: Handle::new(handle) })
267 pub fn fsync(&self) -> io::Result<()> {
268 try!(cvt(unsafe { c::FlushFileBuffers(self.handle.raw()) }));
272 pub fn datasync(&self) -> io::Result<()> { self.fsync() }
274 pub fn truncate(&self, size: u64) -> io::Result<()> {
275 let mut info = c::FILE_END_OF_FILE_INFO {
276 EndOfFile: size as c::LARGE_INTEGER,
278 let size = mem::size_of_val(&info);
280 c::SetFileInformationByHandle(self.handle.raw(),
281 c::FileEndOfFileInfo,
282 &mut info as *mut _ as *mut _,
288 pub fn file_attr(&self) -> io::Result<FileAttr> {
290 let mut info: c::BY_HANDLE_FILE_INFORMATION = mem::zeroed();
291 try!(cvt(c::GetFileInformationByHandle(self.handle.raw(),
293 let mut attr = FileAttr {
294 attributes: info.dwFileAttributes,
295 creation_time: info.ftCreationTime,
296 last_access_time: info.ftLastAccessTime,
297 last_write_time: info.ftLastWriteTime,
298 file_size: ((info.nFileSizeHigh as u64) << 32) | (info.nFileSizeLow as u64),
301 if attr.is_reparse_point() {
302 let mut b = [0; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
303 if let Ok((_, buf)) = self.reparse_point(&mut b) {
304 attr.reparse_tag = buf.ReparseTag;
311 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
312 self.handle.read(buf)
315 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
316 self.handle.write(buf)
319 pub fn flush(&self) -> io::Result<()> { Ok(()) }
321 pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
322 let (whence, pos) = match pos {
323 SeekFrom::Start(n) => (c::FILE_BEGIN, n as i64),
324 SeekFrom::End(n) => (c::FILE_END, n),
325 SeekFrom::Current(n) => (c::FILE_CURRENT, n),
327 let pos = pos as c::LARGE_INTEGER;
330 c::SetFilePointerEx(self.handle.raw(), pos,
336 pub fn duplicate(&self) -> io::Result<File> {
338 handle: try!(self.handle.duplicate(0, true, c::DUPLICATE_SAME_ACCESS)),
342 pub fn handle(&self) -> &Handle { &self.handle }
344 pub fn into_handle(self) -> Handle { self.handle }
346 fn reparse_point<'a>(&self,
347 space: &'a mut [u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE])
348 -> io::Result<(c::DWORD, &'a c::REPARSE_DATA_BUFFER)> {
352 c::DeviceIoControl(self.handle.raw(),
353 c::FSCTL_GET_REPARSE_POINT,
356 space.as_mut_ptr() as *mut _,
357 space.len() as c::DWORD,
361 Ok((bytes, &*(space.as_ptr() as *const c::REPARSE_DATA_BUFFER)))
365 fn readlink(&self) -> io::Result<PathBuf> {
366 let mut space = [0u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
367 let (_bytes, buf) = try!(self.reparse_point(&mut space));
369 let (path_buffer, subst_off, subst_len, relative) = match buf.ReparseTag {
370 c::IO_REPARSE_TAG_SYMLINK => {
371 let info: *const c::SYMBOLIC_LINK_REPARSE_BUFFER =
372 &buf.rest as *const _ as *const _;
373 (&(*info).PathBuffer as *const _ as *const u16,
374 (*info).SubstituteNameOffset / 2,
375 (*info).SubstituteNameLength / 2,
376 (*info).Flags & c::SYMLINK_FLAG_RELATIVE != 0)
378 c::IO_REPARSE_TAG_MOUNT_POINT => {
379 let info: *const c::MOUNT_POINT_REPARSE_BUFFER =
380 &buf.rest as *const _ as *const _;
381 (&(*info).PathBuffer as *const _ as *const u16,
382 (*info).SubstituteNameOffset / 2,
383 (*info).SubstituteNameLength / 2,
386 _ => return Err(io::Error::new(io::ErrorKind::Other,
387 "Unsupported reparse point type"))
389 let subst_ptr = path_buffer.offset(subst_off as isize);
390 let mut subst = slice::from_raw_parts(subst_ptr, subst_len as usize);
391 // Absolute paths start with an NT internal namespace prefix `\??\`
392 // We should not let it leak through.
393 if !relative && subst.starts_with(&[92u16, 63u16, 63u16, 92u16]) {
396 Ok(PathBuf::from(OsString::from_wide(subst)))
401 impl FromInner<c::HANDLE> for File {
402 fn from_inner(handle: c::HANDLE) -> File {
403 File { handle: Handle::new(handle) }
407 impl fmt::Debug for File {
408 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
409 // FIXME(#24570): add more info here (e.g. mode)
410 let mut b = f.debug_struct("File");
411 b.field("handle", &self.handle.raw());
412 if let Ok(path) = get_path(&self) {
413 b.field("path", &path);
420 pub fn size(&self) -> u64 {
424 pub fn perm(&self) -> FilePermissions {
425 FilePermissions { attrs: self.attributes }
428 pub fn attrs(&self) -> u32 { self.attributes as u32 }
430 pub fn file_type(&self) -> FileType {
431 FileType::new(self.attributes, self.reparse_tag)
434 pub fn modified(&self) -> io::Result<SystemTime> {
435 Ok(SystemTime::from(self.last_write_time))
438 pub fn accessed(&self) -> io::Result<SystemTime> {
439 Ok(SystemTime::from(self.last_access_time))
442 pub fn created(&self) -> io::Result<SystemTime> {
443 Ok(SystemTime::from(self.creation_time))
446 pub fn modified_u64(&self) -> u64 {
447 to_u64(&self.last_write_time)
450 pub fn accessed_u64(&self) -> u64 {
451 to_u64(&self.last_access_time)
454 pub fn created_u64(&self) -> u64 {
455 to_u64(&self.creation_time)
458 fn is_reparse_point(&self) -> bool {
459 self.attributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0
463 fn to_u64(ft: &c::FILETIME) -> u64 {
464 (ft.dwLowDateTime as u64) | ((ft.dwHighDateTime as u64) << 32)
467 impl FilePermissions {
468 pub fn readonly(&self) -> bool {
469 self.attrs & c::FILE_ATTRIBUTE_READONLY != 0
472 pub fn set_readonly(&mut self, readonly: bool) {
474 self.attrs |= c::FILE_ATTRIBUTE_READONLY;
476 self.attrs &= !c::FILE_ATTRIBUTE_READONLY;
482 fn new(attrs: c::DWORD, reparse_tag: c::DWORD) -> FileType {
483 match (attrs & c::FILE_ATTRIBUTE_DIRECTORY != 0,
484 attrs & c::FILE_ATTRIBUTE_REPARSE_POINT != 0,
486 (false, false, _) => FileType::File,
487 (true, false, _) => FileType::Dir,
488 (false, true, c::IO_REPARSE_TAG_SYMLINK) => FileType::SymlinkFile,
489 (true, true, c::IO_REPARSE_TAG_SYMLINK) => FileType::SymlinkDir,
490 (true, true, c::IO_REPARSE_TAG_MOUNT_POINT) => FileType::MountPoint,
491 (_, true, _) => FileType::ReparsePoint,
492 // Note: if a _file_ has a reparse tag of the type IO_REPARSE_TAG_MOUNT_POINT it is
493 // invalid, as junctions always have to be dirs. We set the filetype to ReparsePoint
494 // to indicate it is something symlink-like, but not something you can follow.
498 pub fn is_dir(&self) -> bool { *self == FileType::Dir }
499 pub fn is_file(&self) -> bool { *self == FileType::File }
500 pub fn is_symlink(&self) -> bool {
501 *self == FileType::SymlinkFile ||
502 *self == FileType::SymlinkDir ||
503 *self == FileType::MountPoint
505 pub fn is_symlink_dir(&self) -> bool {
506 *self == FileType::SymlinkDir || *self == FileType::MountPoint
511 pub fn new() -> DirBuilder { DirBuilder }
513 pub fn mkdir(&self, p: &Path) -> io::Result<()> {
514 let p = try!(to_u16s(p));
516 c::CreateDirectoryW(p.as_ptr(), ptr::null_mut())
522 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
523 let root = p.to_path_buf();
524 let star = p.join("*");
525 let path = try!(to_u16s(&star));
528 let mut wfd = mem::zeroed();
529 let find_handle = c::FindFirstFileW(path.as_ptr(), &mut wfd);
530 if find_handle != c::INVALID_HANDLE_VALUE {
532 handle: FindNextFileHandle(find_handle),
533 root: Arc::new(root),
537 Err(Error::last_os_error())
542 pub fn unlink(p: &Path) -> io::Result<()> {
543 let p_u16s = try!(to_u16s(p));
544 try!(cvt(unsafe { c::DeleteFileW(p_u16s.as_ptr()) }));
548 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
549 let old = try!(to_u16s(old));
550 let new = try!(to_u16s(new));
552 c::MoveFileExW(old.as_ptr(), new.as_ptr(), c::MOVEFILE_REPLACE_EXISTING)
557 pub fn rmdir(p: &Path) -> io::Result<()> {
558 let p = try!(to_u16s(p));
559 try!(cvt(unsafe { c::RemoveDirectoryW(p.as_ptr()) }));
563 pub fn remove_dir_all(path: &Path) -> io::Result<()> {
564 let filetype = try!(lstat(path)).file_type();
565 if filetype.is_symlink() {
566 // On Windows symlinks to files and directories are removed differently.
567 // rmdir only deletes dir symlinks and junctions, not file symlinks.
570 remove_dir_all_recursive(path)
574 fn remove_dir_all_recursive(path: &Path) -> io::Result<()> {
575 for child in try!(readdir(path)) {
576 let child = try!(child);
577 let child_type = try!(child.file_type());
578 if child_type.is_dir() {
579 try!(remove_dir_all_recursive(&child.path()));
580 } else if child_type.is_symlink_dir() {
581 try!(rmdir(&child.path()));
583 try!(unlink(&child.path()));
589 pub fn readlink(path: &Path) -> io::Result<PathBuf> {
590 // Open the link with no access mode, instead of generic read.
591 // By default FILE_LIST_DIRECTORY is denied for the junction "C:\Documents and Settings", so
592 // this is needed for a common case.
593 let mut opts = OpenOptions::new();
595 opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT |
596 c::FILE_FLAG_BACKUP_SEMANTICS);
597 let file = try!(File::open(&path, &opts));
601 pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
602 symlink_inner(src, dst, false)
605 pub fn symlink_inner(src: &Path, dst: &Path, dir: bool) -> io::Result<()> {
606 let src = try!(to_u16s(src));
607 let dst = try!(to_u16s(dst));
608 let flags = if dir { c::SYMBOLIC_LINK_FLAG_DIRECTORY } else { 0 };
610 c::CreateSymbolicLinkW(dst.as_ptr(), src.as_ptr(), flags) as c::BOOL
615 pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
616 let src = try!(to_u16s(src));
617 let dst = try!(to_u16s(dst));
619 c::CreateHardLinkW(dst.as_ptr(), src.as_ptr(), ptr::null_mut())
624 pub fn stat(path: &Path) -> io::Result<FileAttr> {
625 let mut opts = OpenOptions::new();
626 // No read or write permissions are necessary
628 // This flag is so we can open directories too
629 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
630 let file = try!(File::open(path, &opts));
634 pub fn lstat(path: &Path) -> io::Result<FileAttr> {
635 let mut opts = OpenOptions::new();
636 // No read or write permissions are necessary
638 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS | c::FILE_FLAG_OPEN_REPARSE_POINT);
639 let file = try!(File::open(path, &opts));
643 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
644 let p = try!(to_u16s(p));
646 try!(cvt(c::SetFileAttributesW(p.as_ptr(), perm.attrs)));
651 fn get_path(f: &File) -> io::Result<PathBuf> {
652 super::fill_utf16_buf(|buf, sz| unsafe {
653 c::GetFinalPathNameByHandleW(f.handle.raw(), buf, sz,
656 PathBuf::from(OsString::from_wide(buf))
660 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
661 let mut opts = OpenOptions::new();
662 // No read or write permissions are necessary
664 // This flag is so we can open directories too
665 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
666 let f = try!(File::open(p, &opts));
670 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
671 unsafe extern "system" fn callback(
672 _TotalFileSize: c::LARGE_INTEGER,
673 TotalBytesTransferred: c::LARGE_INTEGER,
674 _StreamSize: c::LARGE_INTEGER,
675 _StreamBytesTransferred: c::LARGE_INTEGER,
676 _dwStreamNumber: c::DWORD,
677 _dwCallbackReason: c::DWORD,
678 _hSourceFile: c::HANDLE,
679 _hDestinationFile: c::HANDLE,
682 *(lpData as *mut i64) = TotalBytesTransferred;
685 let pfrom = try!(to_u16s(from));
686 let pto = try!(to_u16s(to));
689 c::CopyFileExW(pfrom.as_ptr(), pto.as_ptr(), Some(callback),
690 &mut size as *mut _ as *mut _, ptr::null_mut(), 0)
696 pub fn symlink_junction<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
697 symlink_junction_inner(src.as_ref(), dst.as_ref())
700 // Creating a directory junction on windows involves dealing with reparse
701 // points and the DeviceIoControl function, and this code is a skeleton of
702 // what can be found here:
704 // http://www.flexhex.com/docs/articles/hard-links.phtml
706 fn symlink_junction_inner(target: &Path, junction: &Path) -> io::Result<()> {
707 let d = DirBuilder::new();
708 try!(d.mkdir(&junction));
710 let mut opts = OpenOptions::new();
712 opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT |
713 c::FILE_FLAG_BACKUP_SEMANTICS);
714 let f = try!(File::open(junction, &opts));
715 let h = f.handle().raw();
718 let mut data = [0u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
719 let mut db = data.as_mut_ptr()
720 as *mut c::REPARSE_MOUNTPOINT_DATA_BUFFER;
721 let buf = &mut (*db).ReparseTarget as *mut _;
723 // FIXME: this conversion is very hacky
725 let v = v.iter().map(|x| *x as u16);
726 for c in v.chain(target.as_os_str().encode_wide()) {
732 (*db).ReparseTag = c::IO_REPARSE_TAG_MOUNT_POINT;
733 (*db).ReparseTargetMaximumLength = (i * 2) as c::WORD;
734 (*db).ReparseTargetLength = ((i - 1) * 2) as c::WORD;
735 (*db).ReparseDataLength =
736 (*db).ReparseTargetLength as c::DWORD + 12;
739 cvt(c::DeviceIoControl(h as *mut _,
740 c::FSCTL_SET_REPARSE_POINT,
741 data.as_ptr() as *mut _,
742 (*db).ReparseDataLength + 8,
745 ptr::null_mut())).map(|_| ())