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.
11 use os::windows::prelude::*;
15 use io::{self, Error, SeekFrom};
17 use path::{Path, PathBuf};
21 use sys::handle::Handle;
22 use sys::time::SystemTime;
24 use sys_common::FromInner;
28 pub struct File { handle: Handle }
33 creation_time: c::FILETIME,
34 last_access_time: c::FILETIME,
35 last_write_time: c::FILETIME,
37 reparse_tag: c::DWORD,
40 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
42 Dir, File, SymlinkFile, SymlinkDir, ReparsePoint, MountPoint,
46 handle: FindNextFileHandle,
48 first: Option<c::WIN32_FIND_DATAW>,
51 struct FindNextFileHandle(c::HANDLE);
53 unsafe impl Send for FindNextFileHandle {}
54 unsafe impl Sync for FindNextFileHandle {}
58 data: c::WIN32_FIND_DATAW,
62 pub struct OpenOptions {
72 access_mode: Option<c::DWORD>,
75 security_qos_flags: c::DWORD,
76 security_attributes: usize, // FIXME: should be a reference
79 #[derive(Clone, PartialEq, Eq, Debug)]
80 pub struct FilePermissions { attrs: c::DWORD }
82 pub struct DirBuilder;
84 impl Iterator for ReadDir {
85 type Item = io::Result<DirEntry>;
86 fn next(&mut self) -> Option<io::Result<DirEntry>> {
87 if let Some(first) = self.first.take() {
88 if let Some(e) = DirEntry::new(&self.root, &first) {
93 let mut wfd = mem::zeroed();
95 if c::FindNextFileW(self.handle.0, &mut wfd) == 0 {
96 if c::GetLastError() == c::ERROR_NO_MORE_FILES {
99 return Some(Err(Error::last_os_error()))
102 if let Some(e) = DirEntry::new(&self.root, &wfd) {
110 impl Drop for FindNextFileHandle {
112 let r = unsafe { c::FindClose(self.0) };
113 debug_assert!(r != 0);
118 fn new(root: &Arc<PathBuf>, wfd: &c::WIN32_FIND_DATAW) -> Option<DirEntry> {
119 match &wfd.cFileName[0..3] {
120 // check for '.' and '..'
122 &[46, 46, 0, ..] => return None,
132 pub fn path(&self) -> PathBuf {
133 self.root.join(&self.file_name())
136 pub fn file_name(&self) -> OsString {
137 let filename = super::truncate_utf16_at_nul(&self.data.cFileName);
138 OsString::from_wide(filename)
141 pub fn file_type(&self) -> io::Result<FileType> {
142 Ok(FileType::new(self.data.dwFileAttributes,
143 /* reparse_tag = */ self.data.dwReserved0))
146 pub fn metadata(&self) -> io::Result<FileAttr> {
148 attributes: self.data.dwFileAttributes,
149 creation_time: self.data.ftCreationTime,
150 last_access_time: self.data.ftLastAccessTime,
151 last_write_time: self.data.ftLastWriteTime,
152 file_size: ((self.data.nFileSizeHigh as u64) << 32) | (self.data.nFileSizeLow as u64),
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 = to_u16s(path)?;
250 let handle = unsafe {
251 c::CreateFileW(path.as_ptr(),
252 opts.get_access_mode()?,
254 opts.security_attributes as *mut _,
255 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 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 cvt(c::GetFileInformationByHandle(self.handle.raw(),
292 let mut attr = FileAttr {
293 attributes: info.dwFileAttributes,
294 creation_time: info.ftCreationTime,
295 last_access_time: info.ftLastAccessTime,
296 last_write_time: info.ftLastWriteTime,
297 file_size: ((info.nFileSizeHigh as u64) << 32) | (info.nFileSizeLow as u64),
300 if attr.is_reparse_point() {
301 let mut b = [0; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
302 if let Ok((_, buf)) = self.reparse_point(&mut b) {
303 attr.reparse_tag = buf.ReparseTag;
310 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
311 self.handle.read(buf)
314 pub fn read_to_end(&self, buf: &mut Vec<u8>) -> io::Result<usize> {
315 self.handle.read_to_end(buf)
318 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
319 self.handle.write(buf)
322 pub fn flush(&self) -> io::Result<()> { Ok(()) }
324 pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
325 let (whence, pos) = match pos {
326 // Casting to `i64` is fine, `SetFilePointerEx` reinterprets this
328 SeekFrom::Start(n) => (c::FILE_BEGIN, n as i64),
329 SeekFrom::End(n) => (c::FILE_END, n),
330 SeekFrom::Current(n) => (c::FILE_CURRENT, n),
332 let pos = pos as c::LARGE_INTEGER;
335 c::SetFilePointerEx(self.handle.raw(), pos,
341 pub fn duplicate(&self) -> io::Result<File> {
343 handle: self.handle.duplicate(0, true, c::DUPLICATE_SAME_ACCESS)?,
347 pub fn handle(&self) -> &Handle { &self.handle }
349 pub fn into_handle(self) -> Handle { self.handle }
351 fn reparse_point<'a>(&self,
352 space: &'a mut [u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE])
353 -> io::Result<(c::DWORD, &'a c::REPARSE_DATA_BUFFER)> {
357 c::DeviceIoControl(self.handle.raw(),
358 c::FSCTL_GET_REPARSE_POINT,
361 space.as_mut_ptr() as *mut _,
362 space.len() as c::DWORD,
366 Ok((bytes, &*(space.as_ptr() as *const c::REPARSE_DATA_BUFFER)))
370 fn readlink(&self) -> io::Result<PathBuf> {
371 let mut space = [0u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
372 let (_bytes, buf) = self.reparse_point(&mut space)?;
374 let (path_buffer, subst_off, subst_len, relative) = match buf.ReparseTag {
375 c::IO_REPARSE_TAG_SYMLINK => {
376 let info: *const c::SYMBOLIC_LINK_REPARSE_BUFFER =
377 &buf.rest as *const _ as *const _;
378 (&(*info).PathBuffer as *const _ as *const u16,
379 (*info).SubstituteNameOffset / 2,
380 (*info).SubstituteNameLength / 2,
381 (*info).Flags & c::SYMLINK_FLAG_RELATIVE != 0)
383 c::IO_REPARSE_TAG_MOUNT_POINT => {
384 let info: *const c::MOUNT_POINT_REPARSE_BUFFER =
385 &buf.rest as *const _ as *const _;
386 (&(*info).PathBuffer as *const _ as *const u16,
387 (*info).SubstituteNameOffset / 2,
388 (*info).SubstituteNameLength / 2,
391 _ => return Err(io::Error::new(io::ErrorKind::Other,
392 "Unsupported reparse point type"))
394 let subst_ptr = path_buffer.offset(subst_off as isize);
395 let mut subst = slice::from_raw_parts(subst_ptr, subst_len as usize);
396 // Absolute paths start with an NT internal namespace prefix `\??\`
397 // We should not let it leak through.
398 if !relative && subst.starts_with(&[92u16, 63u16, 63u16, 92u16]) {
401 Ok(PathBuf::from(OsString::from_wide(subst)))
406 impl FromInner<c::HANDLE> for File {
407 fn from_inner(handle: c::HANDLE) -> File {
408 File { handle: Handle::new(handle) }
412 impl fmt::Debug for File {
413 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
414 // FIXME(#24570): add more info here (e.g. mode)
415 let mut b = f.debug_struct("File");
416 b.field("handle", &self.handle.raw());
417 if let Ok(path) = get_path(&self) {
418 b.field("path", &path);
425 pub fn size(&self) -> u64 {
429 pub fn perm(&self) -> FilePermissions {
430 FilePermissions { attrs: self.attributes }
433 pub fn attrs(&self) -> u32 { self.attributes as u32 }
435 pub fn file_type(&self) -> FileType {
436 FileType::new(self.attributes, self.reparse_tag)
439 pub fn modified(&self) -> io::Result<SystemTime> {
440 Ok(SystemTime::from(self.last_write_time))
443 pub fn accessed(&self) -> io::Result<SystemTime> {
444 Ok(SystemTime::from(self.last_access_time))
447 pub fn created(&self) -> io::Result<SystemTime> {
448 Ok(SystemTime::from(self.creation_time))
451 pub fn modified_u64(&self) -> u64 {
452 to_u64(&self.last_write_time)
455 pub fn accessed_u64(&self) -> u64 {
456 to_u64(&self.last_access_time)
459 pub fn created_u64(&self) -> u64 {
460 to_u64(&self.creation_time)
463 fn is_reparse_point(&self) -> bool {
464 self.attributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0
468 fn to_u64(ft: &c::FILETIME) -> u64 {
469 (ft.dwLowDateTime as u64) | ((ft.dwHighDateTime as u64) << 32)
472 impl FilePermissions {
473 pub fn readonly(&self) -> bool {
474 self.attrs & c::FILE_ATTRIBUTE_READONLY != 0
477 pub fn set_readonly(&mut self, readonly: bool) {
479 self.attrs |= c::FILE_ATTRIBUTE_READONLY;
481 self.attrs &= !c::FILE_ATTRIBUTE_READONLY;
487 fn new(attrs: c::DWORD, reparse_tag: c::DWORD) -> FileType {
488 match (attrs & c::FILE_ATTRIBUTE_DIRECTORY != 0,
489 attrs & c::FILE_ATTRIBUTE_REPARSE_POINT != 0,
491 (false, false, _) => FileType::File,
492 (true, false, _) => FileType::Dir,
493 (false, true, c::IO_REPARSE_TAG_SYMLINK) => FileType::SymlinkFile,
494 (true, true, c::IO_REPARSE_TAG_SYMLINK) => FileType::SymlinkDir,
495 (true, true, c::IO_REPARSE_TAG_MOUNT_POINT) => FileType::MountPoint,
496 (_, true, _) => FileType::ReparsePoint,
497 // Note: if a _file_ has a reparse tag of the type IO_REPARSE_TAG_MOUNT_POINT it is
498 // invalid, as junctions always have to be dirs. We set the filetype to ReparsePoint
499 // to indicate it is something symlink-like, but not something you can follow.
503 pub fn is_dir(&self) -> bool { *self == FileType::Dir }
504 pub fn is_file(&self) -> bool { *self == FileType::File }
505 pub fn is_symlink(&self) -> bool {
506 *self == FileType::SymlinkFile ||
507 *self == FileType::SymlinkDir ||
508 *self == FileType::MountPoint
510 pub fn is_symlink_dir(&self) -> bool {
511 *self == FileType::SymlinkDir || *self == FileType::MountPoint
516 pub fn new() -> DirBuilder { DirBuilder }
518 pub fn mkdir(&self, p: &Path) -> io::Result<()> {
521 c::CreateDirectoryW(p.as_ptr(), ptr::null_mut())
527 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
528 let root = p.to_path_buf();
529 let star = p.join("*");
530 let path = to_u16s(&star)?;
533 let mut wfd = mem::zeroed();
534 let find_handle = c::FindFirstFileW(path.as_ptr(), &mut wfd);
535 if find_handle != c::INVALID_HANDLE_VALUE {
537 handle: FindNextFileHandle(find_handle),
538 root: Arc::new(root),
542 Err(Error::last_os_error())
547 pub fn unlink(p: &Path) -> io::Result<()> {
548 let p_u16s = to_u16s(p)?;
549 cvt(unsafe { c::DeleteFileW(p_u16s.as_ptr()) })?;
553 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
554 let old = to_u16s(old)?;
555 let new = to_u16s(new)?;
557 c::MoveFileExW(old.as_ptr(), new.as_ptr(), c::MOVEFILE_REPLACE_EXISTING)
562 pub fn rmdir(p: &Path) -> io::Result<()> {
564 cvt(unsafe { c::RemoveDirectoryW(p.as_ptr()) })?;
568 pub fn remove_dir_all(path: &Path) -> io::Result<()> {
569 let filetype = lstat(path)?.file_type();
570 if filetype.is_symlink() {
571 // On Windows symlinks to files and directories are removed differently.
572 // rmdir only deletes dir symlinks and junctions, not file symlinks.
575 remove_dir_all_recursive(path)
579 fn remove_dir_all_recursive(path: &Path) -> io::Result<()> {
580 for child in readdir(path)? {
582 let child_type = child.file_type()?;
583 if child_type.is_dir() {
584 remove_dir_all_recursive(&child.path())?;
585 } else if child_type.is_symlink_dir() {
586 rmdir(&child.path())?;
588 unlink(&child.path())?;
594 pub fn readlink(path: &Path) -> io::Result<PathBuf> {
595 // Open the link with no access mode, instead of generic read.
596 // By default FILE_LIST_DIRECTORY is denied for the junction "C:\Documents and Settings", so
597 // this is needed for a common case.
598 let mut opts = OpenOptions::new();
600 opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT |
601 c::FILE_FLAG_BACKUP_SEMANTICS);
602 let file = File::open(&path, &opts)?;
606 pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
607 symlink_inner(src, dst, false)
610 pub fn symlink_inner(src: &Path, dst: &Path, dir: bool) -> io::Result<()> {
611 let src = to_u16s(src)?;
612 let dst = to_u16s(dst)?;
613 let flags = if dir { c::SYMBOLIC_LINK_FLAG_DIRECTORY } else { 0 };
615 c::CreateSymbolicLinkW(dst.as_ptr(), src.as_ptr(), flags) as c::BOOL
620 pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
621 let src = to_u16s(src)?;
622 let dst = to_u16s(dst)?;
624 c::CreateHardLinkW(dst.as_ptr(), src.as_ptr(), ptr::null_mut())
629 pub fn stat(path: &Path) -> io::Result<FileAttr> {
630 let mut opts = OpenOptions::new();
631 // No read or write permissions are necessary
633 // This flag is so we can open directories too
634 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
635 let file = File::open(path, &opts)?;
639 pub fn lstat(path: &Path) -> io::Result<FileAttr> {
640 let mut opts = OpenOptions::new();
641 // No read or write permissions are necessary
643 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS | c::FILE_FLAG_OPEN_REPARSE_POINT);
644 let file = File::open(path, &opts)?;
648 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
651 cvt(c::SetFileAttributesW(p.as_ptr(), perm.attrs))?;
656 fn get_path(f: &File) -> io::Result<PathBuf> {
657 super::fill_utf16_buf(|buf, sz| unsafe {
658 c::GetFinalPathNameByHandleW(f.handle.raw(), buf, sz,
661 PathBuf::from(OsString::from_wide(buf))
665 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
666 let mut opts = OpenOptions::new();
667 // No read or write permissions are necessary
669 // This flag is so we can open directories too
670 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
671 let f = File::open(p, &opts)?;
675 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
676 unsafe extern "system" fn callback(
677 _TotalFileSize: c::LARGE_INTEGER,
678 TotalBytesTransferred: c::LARGE_INTEGER,
679 _StreamSize: c::LARGE_INTEGER,
680 _StreamBytesTransferred: c::LARGE_INTEGER,
681 _dwStreamNumber: c::DWORD,
682 _dwCallbackReason: c::DWORD,
683 _hSourceFile: c::HANDLE,
684 _hDestinationFile: c::HANDLE,
687 *(lpData as *mut i64) = TotalBytesTransferred;
690 let pfrom = to_u16s(from)?;
691 let pto = to_u16s(to)?;
694 c::CopyFileExW(pfrom.as_ptr(), pto.as_ptr(), Some(callback),
695 &mut size as *mut _ as *mut _, ptr::null_mut(), 0)
701 pub fn symlink_junction<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
702 symlink_junction_inner(src.as_ref(), dst.as_ref())
705 // Creating a directory junction on windows involves dealing with reparse
706 // points and the DeviceIoControl function, and this code is a skeleton of
707 // what can be found here:
709 // http://www.flexhex.com/docs/articles/hard-links.phtml
711 fn symlink_junction_inner(target: &Path, junction: &Path) -> io::Result<()> {
712 let d = DirBuilder::new();
715 let mut opts = OpenOptions::new();
717 opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT |
718 c::FILE_FLAG_BACKUP_SEMANTICS);
719 let f = File::open(junction, &opts)?;
720 let h = f.handle().raw();
723 let mut data = [0u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
724 let mut db = data.as_mut_ptr()
725 as *mut c::REPARSE_MOUNTPOINT_DATA_BUFFER;
726 let buf = &mut (*db).ReparseTarget as *mut _;
728 // FIXME: this conversion is very hacky
730 let v = v.iter().map(|x| *x as u16);
731 for c in v.chain(target.as_os_str().encode_wide()) {
737 (*db).ReparseTag = c::IO_REPARSE_TAG_MOUNT_POINT;
738 (*db).ReparseTargetMaximumLength = (i * 2) as c::WORD;
739 (*db).ReparseTargetLength = ((i - 1) * 2) as c::WORD;
740 (*db).ReparseDataLength =
741 (*db).ReparseTargetLength as c::DWORD + 12;
744 cvt(c::DeviceIoControl(h as *mut _,
745 c::FSCTL_SET_REPARSE_POINT,
746 data.as_ptr() as *mut _,
747 (*db).ReparseDataLength + 8,
750 ptr::null_mut())).map(|_| ())