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: self.data.dwReserved0,
159 pub fn new() -> OpenOptions {
171 share_mode: c::FILE_SHARE_READ | c::FILE_SHARE_WRITE | c::FILE_SHARE_DELETE,
173 security_qos_flags: 0,
174 security_attributes: 0,
178 pub fn read(&mut self, read: bool) { self.read = read; }
179 pub fn write(&mut self, write: bool) { self.write = write; }
180 pub fn append(&mut self, append: bool) { self.append = append; }
181 pub fn truncate(&mut self, truncate: bool) { self.truncate = truncate; }
182 pub fn create(&mut self, create: bool) { self.create = create; }
183 pub fn create_new(&mut self, create_new: bool) { self.create_new = create_new; }
185 pub fn custom_flags(&mut self, flags: u32) { self.custom_flags = flags; }
186 pub fn access_mode(&mut self, access_mode: u32) { self.access_mode = Some(access_mode); }
187 pub fn share_mode(&mut self, share_mode: u32) { self.share_mode = share_mode; }
188 pub fn attributes(&mut self, attrs: u32) { self.attributes = attrs; }
189 pub fn security_qos_flags(&mut self, flags: u32) { self.security_qos_flags = flags; }
190 pub fn security_attributes(&mut self, attrs: c::LPSECURITY_ATTRIBUTES) {
191 self.security_attributes = attrs as usize;
194 fn get_access_mode(&self) -> io::Result<c::DWORD> {
195 const ERROR_INVALID_PARAMETER: i32 = 87;
197 match (self.read, self.write, self.append, self.access_mode) {
198 (_, _, _, Some(mode)) => Ok(mode),
199 (true, false, false, None) => Ok(c::GENERIC_READ),
200 (false, true, false, None) => Ok(c::GENERIC_WRITE),
201 (true, true, false, None) => Ok(c::GENERIC_READ | c::GENERIC_WRITE),
202 (false, _, true, None) => Ok(c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA),
203 (true, _, true, None) => Ok(c::GENERIC_READ |
204 (c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA)),
205 (false, false, false, None) => Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER)),
209 fn get_creation_mode(&self) -> io::Result<c::DWORD> {
210 const ERROR_INVALID_PARAMETER: i32 = 87;
212 match (self.write, self.append) {
215 if self.truncate || self.create || self.create_new {
216 return Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER));
219 if self.truncate && !self.create_new {
220 return Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER));
224 Ok(match (self.create, self.truncate, self.create_new) {
225 (false, false, false) => c::OPEN_EXISTING,
226 (true, false, false) => c::OPEN_ALWAYS,
227 (false, true, false) => c::TRUNCATE_EXISTING,
228 (true, true, false) => c::CREATE_ALWAYS,
229 (_, _, true) => c::CREATE_NEW,
233 fn get_flags_and_attributes(&self) -> c::DWORD {
236 self.security_qos_flags |
237 if self.security_qos_flags != 0 { c::SECURITY_SQOS_PRESENT } else { 0 } |
238 if self.create_new { c::FILE_FLAG_OPEN_REPARSE_POINT } else { 0 }
243 fn open_reparse_point(path: &Path, write: bool) -> io::Result<File> {
244 let mut opts = OpenOptions::new();
247 opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT |
248 c::FILE_FLAG_BACKUP_SEMANTICS);
249 File::open(path, &opts)
252 pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
253 let path = try!(to_u16s(path));
254 let handle = unsafe {
255 c::CreateFileW(path.as_ptr(),
256 try!(opts.get_access_mode()),
258 opts.security_attributes as *mut _,
259 try!(opts.get_creation_mode()),
260 opts.get_flags_and_attributes(),
263 if handle == c::INVALID_HANDLE_VALUE {
264 Err(Error::last_os_error())
266 Ok(File { handle: Handle::new(handle) })
270 pub fn fsync(&self) -> io::Result<()> {
271 try!(cvt(unsafe { c::FlushFileBuffers(self.handle.raw()) }));
275 pub fn datasync(&self) -> io::Result<()> { self.fsync() }
277 pub fn truncate(&self, size: u64) -> io::Result<()> {
278 let mut info = c::FILE_END_OF_FILE_INFO {
279 EndOfFile: size as c::LARGE_INTEGER,
281 let size = mem::size_of_val(&info);
283 c::SetFileInformationByHandle(self.handle.raw(),
284 c::FileEndOfFileInfo,
285 &mut info as *mut _ as *mut _,
291 pub fn file_attr(&self) -> io::Result<FileAttr> {
293 let mut info: c::BY_HANDLE_FILE_INFORMATION = mem::zeroed();
294 try!(cvt(c::GetFileInformationByHandle(self.handle.raw(),
296 let mut attr = FileAttr {
297 data: c::WIN32_FILE_ATTRIBUTE_DATA {
298 dwFileAttributes: info.dwFileAttributes,
299 ftCreationTime: info.ftCreationTime,
300 ftLastAccessTime: info.ftLastAccessTime,
301 ftLastWriteTime: info.ftLastWriteTime,
302 nFileSizeHigh: info.nFileSizeHigh,
303 nFileSizeLow: info.nFileSizeLow,
307 if attr.is_reparse_point() {
308 let mut b = [0; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
309 if let Ok((_, buf)) = self.reparse_point(&mut b) {
310 attr.reparse_tag = buf.ReparseTag;
317 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
318 self.handle.read(buf)
321 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
322 self.handle.write(buf)
325 pub fn flush(&self) -> io::Result<()> { Ok(()) }
327 pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
328 let (whence, pos) = match pos {
329 SeekFrom::Start(n) => (c::FILE_BEGIN, n as i64),
330 SeekFrom::End(n) => (c::FILE_END, n),
331 SeekFrom::Current(n) => (c::FILE_CURRENT, n),
333 let pos = pos as c::LARGE_INTEGER;
336 c::SetFilePointerEx(self.handle.raw(), pos,
342 pub fn duplicate(&self) -> io::Result<File> {
344 handle: try!(self.handle.duplicate(0, true, c::DUPLICATE_SAME_ACCESS)),
348 pub fn handle(&self) -> &Handle { &self.handle }
350 pub fn into_handle(self) -> Handle { self.handle }
352 fn reparse_point<'a>(&self,
353 space: &'a mut [u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE])
354 -> io::Result<(c::DWORD, &'a c::REPARSE_DATA_BUFFER)> {
358 c::DeviceIoControl(self.handle.raw(),
359 c::FSCTL_GET_REPARSE_POINT,
362 space.as_mut_ptr() as *mut _,
363 space.len() as c::DWORD,
367 Ok((bytes, &*(space.as_ptr() as *const c::REPARSE_DATA_BUFFER)))
371 fn readlink(&self) -> io::Result<PathBuf> {
372 let mut space = [0u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
373 let (_bytes, buf) = try!(self.reparse_point(&mut space));
374 if buf.ReparseTag != c::IO_REPARSE_TAG_SYMLINK {
375 return Err(io::Error::new(io::ErrorKind::Other, "not a symlink"))
379 let info: *const c::SYMBOLIC_LINK_REPARSE_BUFFER =
380 &buf.rest as *const _ as *const _;
381 let path_buffer = &(*info).PathBuffer as *const _ as *const u16;
382 let subst_off = (*info).SubstituteNameOffset / 2;
383 let subst_ptr = path_buffer.offset(subst_off as isize);
384 let subst_len = (*info).SubstituteNameLength / 2;
385 let subst = slice::from_raw_parts(subst_ptr, subst_len as usize);
387 Ok(PathBuf::from(OsString::from_wide(subst)))
392 impl FromInner<c::HANDLE> for File {
393 fn from_inner(handle: c::HANDLE) -> File {
394 File { handle: Handle::new(handle) }
398 impl fmt::Debug for File {
399 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
400 // FIXME(#24570): add more info here (e.g. mode)
401 let mut b = f.debug_struct("File");
402 b.field("handle", &self.handle.raw());
403 if let Ok(path) = get_path(&self) {
404 b.field("path", &path);
411 pub fn size(&self) -> u64 {
412 ((self.data.nFileSizeHigh as u64) << 32) | (self.data.nFileSizeLow as u64)
415 pub fn perm(&self) -> FilePermissions {
416 FilePermissions { attrs: self.data.dwFileAttributes }
419 pub fn attrs(&self) -> u32 { self.data.dwFileAttributes as u32 }
421 pub fn file_type(&self) -> FileType {
422 FileType::new(self.data.dwFileAttributes, self.reparse_tag)
425 pub fn modified(&self) -> io::Result<SystemTime> {
426 Ok(SystemTime::from(self.data.ftLastWriteTime))
429 pub fn accessed(&self) -> io::Result<SystemTime> {
430 Ok(SystemTime::from(self.data.ftLastAccessTime))
433 pub fn created(&self) -> io::Result<SystemTime> {
434 Ok(SystemTime::from(self.data.ftCreationTime))
437 pub fn modified_u64(&self) -> u64 {
438 to_u64(&self.data.ftLastWriteTime)
441 pub fn accessed_u64(&self) -> u64 {
442 to_u64(&self.data.ftLastAccessTime)
445 pub fn created_u64(&self) -> u64 {
446 to_u64(&self.data.ftCreationTime)
449 fn is_reparse_point(&self) -> bool {
450 self.data.dwFileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0
454 fn to_u64(ft: &c::FILETIME) -> u64 {
455 (ft.dwLowDateTime as u64) | ((ft.dwHighDateTime as u64) << 32)
458 impl FilePermissions {
459 pub fn readonly(&self) -> bool {
460 self.attrs & c::FILE_ATTRIBUTE_READONLY != 0
463 pub fn set_readonly(&mut self, readonly: bool) {
465 self.attrs |= c::FILE_ATTRIBUTE_READONLY;
467 self.attrs &= !c::FILE_ATTRIBUTE_READONLY;
473 fn new(attrs: c::DWORD, reparse_tag: c::DWORD) -> FileType {
474 match (attrs & c::FILE_ATTRIBUTE_DIRECTORY != 0,
475 attrs & c::FILE_ATTRIBUTE_REPARSE_POINT != 0,
477 (false, false, _) => FileType::File,
478 (true, false, _) => FileType::Dir,
479 (false, true, c::IO_REPARSE_TAG_SYMLINK) => FileType::SymlinkFile,
480 (true, true, c::IO_REPARSE_TAG_SYMLINK) => FileType::SymlinkDir,
481 (true, true, c::IO_REPARSE_TAG_MOUNT_POINT) => FileType::MountPoint,
482 (_, true, _) => FileType::ReparsePoint,
483 // Note: if a _file_ has a reparse tag of the type IO_REPARSE_TAG_MOUNT_POINT it is
484 // invalid, as junctions always have to be dirs. We set the filetype to ReparsePoint
485 // to indicate it is something symlink-like, but not something you can follow.
489 pub fn is_dir(&self) -> bool { *self == FileType::Dir }
490 pub fn is_file(&self) -> bool { *self == FileType::File }
491 pub fn is_symlink(&self) -> bool {
492 *self == FileType::SymlinkFile ||
493 *self == FileType::SymlinkDir ||
494 *self == FileType::MountPoint
496 pub fn is_symlink_dir(&self) -> bool {
497 *self == FileType::SymlinkDir || *self == FileType::MountPoint
502 pub fn new() -> DirBuilder { DirBuilder }
504 pub fn mkdir(&self, p: &Path) -> io::Result<()> {
505 let p = try!(to_u16s(p));
507 c::CreateDirectoryW(p.as_ptr(), ptr::null_mut())
513 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
514 let root = p.to_path_buf();
515 let star = p.join("*");
516 let path = try!(to_u16s(&star));
519 let mut wfd = mem::zeroed();
520 let find_handle = c::FindFirstFileW(path.as_ptr(), &mut wfd);
521 if find_handle != c::INVALID_HANDLE_VALUE {
523 handle: FindNextFileHandle(find_handle),
524 root: Arc::new(root),
528 Err(Error::last_os_error())
533 pub fn unlink(p: &Path) -> io::Result<()> {
534 let p_u16s = try!(to_u16s(p));
535 try!(cvt(unsafe { c::DeleteFileW(p_u16s.as_ptr()) }));
539 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
540 let old = try!(to_u16s(old));
541 let new = try!(to_u16s(new));
543 c::MoveFileExW(old.as_ptr(), new.as_ptr(), c::MOVEFILE_REPLACE_EXISTING)
548 pub fn rmdir(p: &Path) -> io::Result<()> {
549 let p = try!(to_u16s(p));
550 try!(cvt(unsafe { c::RemoveDirectoryW(p.as_ptr()) }));
554 pub fn remove_dir_all(path: &Path) -> io::Result<()> {
555 for child in try!(readdir(path)) {
556 let child = try!(child);
557 let child_type = try!(child.file_type());
558 if child_type.is_dir() {
559 try!(remove_dir_all(&child.path()));
560 } else if child_type.is_symlink_dir() {
561 try!(rmdir(&child.path()));
563 try!(unlink(&child.path()));
569 pub fn readlink(p: &Path) -> io::Result<PathBuf> {
570 let file = try!(File::open_reparse_point(p, false));
574 pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
575 symlink_inner(src, dst, false)
578 pub fn symlink_inner(src: &Path, dst: &Path, dir: bool) -> io::Result<()> {
579 let src = try!(to_u16s(src));
580 let dst = try!(to_u16s(dst));
581 let flags = if dir { c::SYMBOLIC_LINK_FLAG_DIRECTORY } else { 0 };
583 c::CreateSymbolicLinkW(dst.as_ptr(), src.as_ptr(), flags) as c::BOOL
588 pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
589 let src = try!(to_u16s(src));
590 let dst = try!(to_u16s(dst));
592 c::CreateHardLinkW(dst.as_ptr(), src.as_ptr(), ptr::null_mut())
597 pub fn stat(p: &Path) -> io::Result<FileAttr> {
598 let attr = try!(lstat(p));
600 // If this is a reparse point, then we need to reopen the file to get the
601 // actual destination. We also pass the FILE_FLAG_BACKUP_SEMANTICS flag to
602 // ensure that we can open directories (this path may be a directory
603 // junction). Once the file is opened we ask the opened handle what its
604 // metadata information is.
605 if attr.is_reparse_point() {
606 let mut opts = OpenOptions::new();
607 // No read or write permissions are necessary
609 // This flag is so we can open directories too
610 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
611 let file = try!(File::open(p, &opts));
618 pub fn lstat(p: &Path) -> io::Result<FileAttr> {
619 let u16s = try!(to_u16s(p));
621 let mut attr: FileAttr = mem::zeroed();
622 try!(cvt(c::GetFileAttributesExW(u16s.as_ptr(),
623 c::GetFileExInfoStandard,
624 &mut attr.data as *mut _ as *mut _)));
625 if attr.is_reparse_point() {
626 attr.reparse_tag = File::open_reparse_point(p, false).and_then(|f| {
627 let mut b = [0; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
628 f.reparse_point(&mut b).map(|(_, b)| b.ReparseTag)
635 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
636 let p = try!(to_u16s(p));
638 try!(cvt(c::SetFileAttributesW(p.as_ptr(), perm.attrs)));
643 fn get_path(f: &File) -> io::Result<PathBuf> {
644 super::fill_utf16_buf(|buf, sz| unsafe {
645 c::GetFinalPathNameByHandleW(f.handle.raw(), buf, sz,
648 PathBuf::from(OsString::from_wide(buf))
652 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
653 let mut opts = OpenOptions::new();
654 // No read or write permissions are necessary
656 // This flag is so we can open directories too
657 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
658 let f = try!(File::open(p, &opts));
662 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
663 unsafe extern "system" fn callback(
664 _TotalFileSize: c::LARGE_INTEGER,
665 TotalBytesTransferred: c::LARGE_INTEGER,
666 _StreamSize: c::LARGE_INTEGER,
667 _StreamBytesTransferred: c::LARGE_INTEGER,
668 _dwStreamNumber: c::DWORD,
669 _dwCallbackReason: c::DWORD,
670 _hSourceFile: c::HANDLE,
671 _hDestinationFile: c::HANDLE,
674 *(lpData as *mut i64) = TotalBytesTransferred;
677 let pfrom = try!(to_u16s(from));
678 let pto = try!(to_u16s(to));
681 c::CopyFileExW(pfrom.as_ptr(), pto.as_ptr(), Some(callback),
682 &mut size as *mut _ as *mut _, ptr::null_mut(), 0)
688 pub fn symlink_junction<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
689 symlink_junction_inner(src.as_ref(), dst.as_ref())
692 // Creating a directory junction on windows involves dealing with reparse
693 // points and the DeviceIoControl function, and this code is a skeleton of
694 // what can be found here:
696 // http://www.flexhex.com/docs/articles/hard-links.phtml
698 fn symlink_junction_inner(target: &Path, junction: &Path) -> io::Result<()> {
699 let d = DirBuilder::new();
700 try!(d.mkdir(&junction));
701 let f = try!(File::open_reparse_point(junction, true));
702 let h = f.handle().raw();
705 let mut data = [0u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
706 let mut db = data.as_mut_ptr()
707 as *mut c::REPARSE_MOUNTPOINT_DATA_BUFFER;
708 let buf = &mut (*db).ReparseTarget as *mut _;
710 // FIXME: this conversion is very hacky
712 let v = v.iter().map(|x| *x as u16);
713 for c in v.chain(target.as_os_str().encode_wide()) {
719 (*db).ReparseTag = c::IO_REPARSE_TAG_MOUNT_POINT;
720 (*db).ReparseTargetMaximumLength = (i * 2) as c::WORD;
721 (*db).ReparseTargetLength = ((i - 1) * 2) as c::WORD;
722 (*db).ReparseDataLength =
723 (*db).ReparseTargetLength as c::DWORD + 12;
726 cvt(c::DeviceIoControl(h as *mut _,
727 c::FSCTL_SET_REPARSE_POINT,
728 data.as_ptr() as *mut _,
729 (*db).ReparseDataLength + 8,
732 ptr::null_mut())).map(|_| ())