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, Debug)]
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 = to_u16s(path)?;
251 let handle = unsafe {
252 c::CreateFileW(path.as_ptr(),
253 opts.get_access_mode()?,
255 opts.security_attributes as *mut _,
256 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 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 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 read_to_end(&self, buf: &mut Vec<u8>) -> io::Result<usize> {
316 self.handle.read_to_end(buf)
319 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
320 self.handle.write(buf)
323 pub fn flush(&self) -> io::Result<()> { Ok(()) }
325 pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
326 let (whence, pos) = match pos {
327 SeekFrom::Start(n) => (c::FILE_BEGIN, n as i64),
328 SeekFrom::End(n) => (c::FILE_END, n),
329 SeekFrom::Current(n) => (c::FILE_CURRENT, n),
331 let pos = pos as c::LARGE_INTEGER;
334 c::SetFilePointerEx(self.handle.raw(), pos,
340 pub fn duplicate(&self) -> io::Result<File> {
342 handle: self.handle.duplicate(0, true, c::DUPLICATE_SAME_ACCESS)?,
346 pub fn handle(&self) -> &Handle { &self.handle }
348 pub fn into_handle(self) -> Handle { self.handle }
350 fn reparse_point<'a>(&self,
351 space: &'a mut [u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE])
352 -> io::Result<(c::DWORD, &'a c::REPARSE_DATA_BUFFER)> {
356 c::DeviceIoControl(self.handle.raw(),
357 c::FSCTL_GET_REPARSE_POINT,
360 space.as_mut_ptr() as *mut _,
361 space.len() as c::DWORD,
365 Ok((bytes, &*(space.as_ptr() as *const c::REPARSE_DATA_BUFFER)))
369 fn readlink(&self) -> io::Result<PathBuf> {
370 let mut space = [0u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
371 let (_bytes, buf) = self.reparse_point(&mut space)?;
373 let (path_buffer, subst_off, subst_len, relative) = match buf.ReparseTag {
374 c::IO_REPARSE_TAG_SYMLINK => {
375 let info: *const c::SYMBOLIC_LINK_REPARSE_BUFFER =
376 &buf.rest as *const _ as *const _;
377 (&(*info).PathBuffer as *const _ as *const u16,
378 (*info).SubstituteNameOffset / 2,
379 (*info).SubstituteNameLength / 2,
380 (*info).Flags & c::SYMLINK_FLAG_RELATIVE != 0)
382 c::IO_REPARSE_TAG_MOUNT_POINT => {
383 let info: *const c::MOUNT_POINT_REPARSE_BUFFER =
384 &buf.rest as *const _ as *const _;
385 (&(*info).PathBuffer as *const _ as *const u16,
386 (*info).SubstituteNameOffset / 2,
387 (*info).SubstituteNameLength / 2,
390 _ => return Err(io::Error::new(io::ErrorKind::Other,
391 "Unsupported reparse point type"))
393 let subst_ptr = path_buffer.offset(subst_off as isize);
394 let mut subst = slice::from_raw_parts(subst_ptr, subst_len as usize);
395 // Absolute paths start with an NT internal namespace prefix `\??\`
396 // We should not let it leak through.
397 if !relative && subst.starts_with(&[92u16, 63u16, 63u16, 92u16]) {
400 Ok(PathBuf::from(OsString::from_wide(subst)))
405 impl FromInner<c::HANDLE> for File {
406 fn from_inner(handle: c::HANDLE) -> File {
407 File { handle: Handle::new(handle) }
411 impl fmt::Debug for File {
412 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
413 // FIXME(#24570): add more info here (e.g. mode)
414 let mut b = f.debug_struct("File");
415 b.field("handle", &self.handle.raw());
416 if let Ok(path) = get_path(&self) {
417 b.field("path", &path);
424 pub fn size(&self) -> u64 {
428 pub fn perm(&self) -> FilePermissions {
429 FilePermissions { attrs: self.attributes }
432 pub fn attrs(&self) -> u32 { self.attributes as u32 }
434 pub fn file_type(&self) -> FileType {
435 FileType::new(self.attributes, self.reparse_tag)
438 pub fn modified(&self) -> io::Result<SystemTime> {
439 Ok(SystemTime::from(self.last_write_time))
442 pub fn accessed(&self) -> io::Result<SystemTime> {
443 Ok(SystemTime::from(self.last_access_time))
446 pub fn created(&self) -> io::Result<SystemTime> {
447 Ok(SystemTime::from(self.creation_time))
450 pub fn modified_u64(&self) -> u64 {
451 to_u64(&self.last_write_time)
454 pub fn accessed_u64(&self) -> u64 {
455 to_u64(&self.last_access_time)
458 pub fn created_u64(&self) -> u64 {
459 to_u64(&self.creation_time)
462 fn is_reparse_point(&self) -> bool {
463 self.attributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0
467 fn to_u64(ft: &c::FILETIME) -> u64 {
468 (ft.dwLowDateTime as u64) | ((ft.dwHighDateTime as u64) << 32)
471 impl FilePermissions {
472 pub fn readonly(&self) -> bool {
473 self.attrs & c::FILE_ATTRIBUTE_READONLY != 0
476 pub fn set_readonly(&mut self, readonly: bool) {
478 self.attrs |= c::FILE_ATTRIBUTE_READONLY;
480 self.attrs &= !c::FILE_ATTRIBUTE_READONLY;
486 fn new(attrs: c::DWORD, reparse_tag: c::DWORD) -> FileType {
487 match (attrs & c::FILE_ATTRIBUTE_DIRECTORY != 0,
488 attrs & c::FILE_ATTRIBUTE_REPARSE_POINT != 0,
490 (false, false, _) => FileType::File,
491 (true, false, _) => FileType::Dir,
492 (false, true, c::IO_REPARSE_TAG_SYMLINK) => FileType::SymlinkFile,
493 (true, true, c::IO_REPARSE_TAG_SYMLINK) => FileType::SymlinkDir,
494 (true, true, c::IO_REPARSE_TAG_MOUNT_POINT) => FileType::MountPoint,
495 (_, true, _) => FileType::ReparsePoint,
496 // Note: if a _file_ has a reparse tag of the type IO_REPARSE_TAG_MOUNT_POINT it is
497 // invalid, as junctions always have to be dirs. We set the filetype to ReparsePoint
498 // to indicate it is something symlink-like, but not something you can follow.
502 pub fn is_dir(&self) -> bool { *self == FileType::Dir }
503 pub fn is_file(&self) -> bool { *self == FileType::File }
504 pub fn is_symlink(&self) -> bool {
505 *self == FileType::SymlinkFile ||
506 *self == FileType::SymlinkDir ||
507 *self == FileType::MountPoint
509 pub fn is_symlink_dir(&self) -> bool {
510 *self == FileType::SymlinkDir || *self == FileType::MountPoint
515 pub fn new() -> DirBuilder { DirBuilder }
517 pub fn mkdir(&self, p: &Path) -> io::Result<()> {
520 c::CreateDirectoryW(p.as_ptr(), ptr::null_mut())
526 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
527 let root = p.to_path_buf();
528 let star = p.join("*");
529 let path = to_u16s(&star)?;
532 let mut wfd = mem::zeroed();
533 let find_handle = c::FindFirstFileW(path.as_ptr(), &mut wfd);
534 if find_handle != c::INVALID_HANDLE_VALUE {
536 handle: FindNextFileHandle(find_handle),
537 root: Arc::new(root),
541 Err(Error::last_os_error())
546 pub fn unlink(p: &Path) -> io::Result<()> {
547 let p_u16s = to_u16s(p)?;
548 cvt(unsafe { c::DeleteFileW(p_u16s.as_ptr()) })?;
552 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
553 let old = to_u16s(old)?;
554 let new = to_u16s(new)?;
556 c::MoveFileExW(old.as_ptr(), new.as_ptr(), c::MOVEFILE_REPLACE_EXISTING)
561 pub fn rmdir(p: &Path) -> io::Result<()> {
563 cvt(unsafe { c::RemoveDirectoryW(p.as_ptr()) })?;
567 pub fn remove_dir_all(path: &Path) -> io::Result<()> {
568 let filetype = lstat(path)?.file_type();
569 if filetype.is_symlink() {
570 // On Windows symlinks to files and directories are removed differently.
571 // rmdir only deletes dir symlinks and junctions, not file symlinks.
574 remove_dir_all_recursive(path)
578 fn remove_dir_all_recursive(path: &Path) -> io::Result<()> {
579 for child in readdir(path)? {
581 let child_type = child.file_type()?;
582 if child_type.is_dir() {
583 remove_dir_all_recursive(&child.path())?;
584 } else if child_type.is_symlink_dir() {
585 rmdir(&child.path())?;
587 unlink(&child.path())?;
593 pub fn readlink(path: &Path) -> io::Result<PathBuf> {
594 // Open the link with no access mode, instead of generic read.
595 // By default FILE_LIST_DIRECTORY is denied for the junction "C:\Documents and Settings", so
596 // this is needed for a common case.
597 let mut opts = OpenOptions::new();
599 opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT |
600 c::FILE_FLAG_BACKUP_SEMANTICS);
601 let file = File::open(&path, &opts)?;
605 pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
606 symlink_inner(src, dst, false)
609 pub fn symlink_inner(src: &Path, dst: &Path, dir: bool) -> io::Result<()> {
610 let src = to_u16s(src)?;
611 let dst = to_u16s(dst)?;
612 let flags = if dir { c::SYMBOLIC_LINK_FLAG_DIRECTORY } else { 0 };
614 c::CreateSymbolicLinkW(dst.as_ptr(), src.as_ptr(), flags) as c::BOOL
619 pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
620 let src = to_u16s(src)?;
621 let dst = to_u16s(dst)?;
623 c::CreateHardLinkW(dst.as_ptr(), src.as_ptr(), ptr::null_mut())
628 pub fn stat(path: &Path) -> io::Result<FileAttr> {
629 let mut opts = OpenOptions::new();
630 // No read or write permissions are necessary
632 // This flag is so we can open directories too
633 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
634 let file = File::open(path, &opts)?;
638 pub fn lstat(path: &Path) -> io::Result<FileAttr> {
639 let mut opts = OpenOptions::new();
640 // No read or write permissions are necessary
642 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS | c::FILE_FLAG_OPEN_REPARSE_POINT);
643 let file = File::open(path, &opts)?;
647 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
650 cvt(c::SetFileAttributesW(p.as_ptr(), perm.attrs))?;
655 fn get_path(f: &File) -> io::Result<PathBuf> {
656 super::fill_utf16_buf(|buf, sz| unsafe {
657 c::GetFinalPathNameByHandleW(f.handle.raw(), buf, sz,
660 PathBuf::from(OsString::from_wide(buf))
664 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
665 let mut opts = OpenOptions::new();
666 // No read or write permissions are necessary
668 // This flag is so we can open directories too
669 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
670 let f = File::open(p, &opts)?;
674 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
675 unsafe extern "system" fn callback(
676 _TotalFileSize: c::LARGE_INTEGER,
677 TotalBytesTransferred: c::LARGE_INTEGER,
678 _StreamSize: c::LARGE_INTEGER,
679 _StreamBytesTransferred: c::LARGE_INTEGER,
680 _dwStreamNumber: c::DWORD,
681 _dwCallbackReason: c::DWORD,
682 _hSourceFile: c::HANDLE,
683 _hDestinationFile: c::HANDLE,
686 *(lpData as *mut i64) = TotalBytesTransferred;
689 let pfrom = to_u16s(from)?;
690 let pto = to_u16s(to)?;
693 c::CopyFileExW(pfrom.as_ptr(), pto.as_ptr(), Some(callback),
694 &mut size as *mut _ as *mut _, ptr::null_mut(), 0)
700 pub fn symlink_junction<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
701 symlink_junction_inner(src.as_ref(), dst.as_ref())
704 // Creating a directory junction on windows involves dealing with reparse
705 // points and the DeviceIoControl function, and this code is a skeleton of
706 // what can be found here:
708 // http://www.flexhex.com/docs/articles/hard-links.phtml
710 fn symlink_junction_inner(target: &Path, junction: &Path) -> io::Result<()> {
711 let d = DirBuilder::new();
714 let mut opts = OpenOptions::new();
716 opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT |
717 c::FILE_FLAG_BACKUP_SEMANTICS);
718 let f = File::open(junction, &opts)?;
719 let h = f.handle().raw();
722 let mut data = [0u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
723 let mut db = data.as_mut_ptr()
724 as *mut c::REPARSE_MOUNTPOINT_DATA_BUFFER;
725 let buf = &mut (*db).ReparseTarget as *mut _;
727 // FIXME: this conversion is very hacky
729 let v = v.iter().map(|x| *x as u16);
730 for c in v.chain(target.as_os_str().encode_wide()) {
736 (*db).ReparseTag = c::IO_REPARSE_TAG_MOUNT_POINT;
737 (*db).ReparseTargetMaximumLength = (i * 2) as c::WORD;
738 (*db).ReparseTargetLength = ((i - 1) * 2) as c::WORD;
739 (*db).ReparseDataLength =
740 (*db).ReparseTargetLength as c::DWORD + 12;
743 cvt(c::DeviceIoControl(h as *mut _,
744 c::FSCTL_SET_REPARSE_POINT,
745 data.as_ptr() as *mut _,
746 (*db).ReparseDataLength + 8,
749 ptr::null_mut())).map(|_| ())