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;
24 use sys_common::FromInner;
28 pub struct File { handle: Handle }
32 data: c::WIN32_FILE_ATTRIBUTE_DATA,
33 reparse_tag: c::DWORD,
36 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
38 Dir, File, SymlinkFile, SymlinkDir, ReparsePoint, MountPoint,
42 handle: FindNextFileHandle,
44 first: Option<c::WIN32_FIND_DATAW>,
47 struct FindNextFileHandle(c::HANDLE);
49 unsafe impl Send for FindNextFileHandle {}
50 unsafe impl Sync for FindNextFileHandle {}
54 data: c::WIN32_FIND_DATAW,
58 pub struct OpenOptions {
68 access_mode: Option<c::DWORD>,
71 security_qos_flags: c::DWORD,
72 security_attributes: usize, // FIXME: should be a reference
75 #[derive(Clone, PartialEq, Eq, Debug)]
76 pub struct FilePermissions { attrs: c::DWORD }
78 pub struct DirBuilder;
80 impl Iterator for ReadDir {
81 type Item = io::Result<DirEntry>;
82 fn next(&mut self) -> Option<io::Result<DirEntry>> {
83 if let Some(first) = self.first.take() {
84 if let Some(e) = DirEntry::new(&self.root, &first) {
89 let mut wfd = mem::zeroed();
91 if c::FindNextFileW(self.handle.0, &mut wfd) == 0 {
92 if c::GetLastError() == c::ERROR_NO_MORE_FILES {
95 return Some(Err(Error::last_os_error()))
98 if let Some(e) = DirEntry::new(&self.root, &wfd) {
106 impl Drop for FindNextFileHandle {
108 let r = unsafe { c::FindClose(self.0) };
109 debug_assert!(r != 0);
114 fn new(root: &Arc<PathBuf>, wfd: &c::WIN32_FIND_DATAW) -> Option<DirEntry> {
115 match &wfd.cFileName[0..3] {
116 // check for '.' and '..'
118 [46, 46, 0, ..] => return None,
128 pub fn path(&self) -> PathBuf {
129 self.root.join(&self.file_name())
132 pub fn file_name(&self) -> OsString {
133 let filename = super::truncate_utf16_at_nul(&self.data.cFileName);
134 OsString::from_wide(filename)
137 pub fn file_type(&self) -> io::Result<FileType> {
138 Ok(FileType::new(self.data.dwFileAttributes,
139 /* reparse_tag = */ self.data.dwReserved0))
142 pub fn metadata(&self) -> io::Result<FileAttr> {
144 data: c::WIN32_FILE_ATTRIBUTE_DATA {
145 dwFileAttributes: self.data.dwFileAttributes,
146 ftCreationTime: self.data.ftCreationTime,
147 ftLastAccessTime: self.data.ftLastAccessTime,
148 ftLastWriteTime: self.data.ftLastWriteTime,
149 nFileSizeHigh: self.data.nFileSizeHigh,
150 nFileSizeLow: self.data.nFileSizeLow,
152 reparse_tag: self.data.dwReserved0,
158 pub fn new() -> OpenOptions {
170 share_mode: c::FILE_SHARE_READ | c::FILE_SHARE_WRITE | c::FILE_SHARE_DELETE,
172 security_qos_flags: 0,
173 security_attributes: 0,
177 pub fn read(&mut self, read: bool) { self.read = read; }
178 pub fn write(&mut self, write: bool) { self.write = write; }
179 pub fn append(&mut self, append: bool) { self.append = append; }
180 pub fn truncate(&mut self, truncate: bool) { self.truncate = truncate; }
181 pub fn create(&mut self, create: bool) { self.create = create; }
182 pub fn create_new(&mut self, create_new: bool) { self.create_new = create_new; }
184 pub fn custom_flags(&mut self, flags: u32) { self.custom_flags = flags; }
185 pub fn access_mode(&mut self, access_mode: u32) { self.access_mode = Some(access_mode); }
186 pub fn share_mode(&mut self, share_mode: u32) { self.share_mode = share_mode; }
187 pub fn attributes(&mut self, attrs: u32) { self.attributes = attrs; }
188 pub fn security_qos_flags(&mut self, flags: u32) { self.security_qos_flags = flags; }
189 pub fn security_attributes(&mut self, attrs: c::LPSECURITY_ATTRIBUTES) {
190 self.security_attributes = attrs as usize;
193 fn get_access_mode(&self) -> io::Result<c::DWORD> {
194 const ERROR_INVALID_PARAMETER: i32 = 87;
196 match (self.read, self.write, self.append, self.access_mode) {
197 (_, _, _, Some(mode)) => Ok(mode),
198 (true, false, false, None) => Ok(c::GENERIC_READ),
199 (false, true, false, None) => Ok(c::GENERIC_WRITE),
200 (true, true, false, None) => Ok(c::GENERIC_READ | c::GENERIC_WRITE),
201 (false, _, true, None) => Ok(c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA),
202 (true, _, true, None) => Ok(c::GENERIC_READ |
203 (c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA)),
204 (false, false, false, None) => Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER)),
208 fn get_creation_mode(&self) -> io::Result<c::DWORD> {
209 const ERROR_INVALID_PARAMETER: i32 = 87;
211 match (self.write, self.append) {
214 if self.truncate || self.create || self.create_new {
215 return Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER));
218 if self.truncate && !self.create_new {
219 return Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER));
223 Ok(match (self.create, self.truncate, self.create_new) {
224 (false, false, false) => c::OPEN_EXISTING,
225 (true, false, false) => c::OPEN_ALWAYS,
226 (false, true, false) => c::TRUNCATE_EXISTING,
227 (true, true, false) => c::CREATE_ALWAYS,
228 (_, _, true) => c::CREATE_NEW,
232 fn get_flags_and_attributes(&self) -> c::DWORD {
235 self.security_qos_flags |
236 if self.security_qos_flags != 0 { c::SECURITY_SQOS_PRESENT } else { 0 } |
237 if self.create_new { c::FILE_FLAG_OPEN_REPARSE_POINT } else { 0 }
242 fn open_reparse_point(path: &Path, write: bool) -> io::Result<File> {
243 let mut opts = OpenOptions::new();
246 opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT |
247 c::FILE_FLAG_BACKUP_SEMANTICS);
248 File::open(path, &opts)
251 pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
252 let path = try!(to_u16s(path));
253 let handle = unsafe {
254 c::CreateFileW(path.as_ptr(),
255 try!(opts.get_access_mode()),
257 opts.security_attributes as *mut _,
258 try!(opts.get_creation_mode()),
259 opts.get_flags_and_attributes(),
262 if handle == c::INVALID_HANDLE_VALUE {
263 Err(Error::last_os_error())
265 Ok(File { handle: Handle::new(handle) })
269 pub fn fsync(&self) -> io::Result<()> {
270 try!(cvt(unsafe { c::FlushFileBuffers(self.handle.raw()) }));
274 pub fn datasync(&self) -> io::Result<()> { self.fsync() }
276 pub fn truncate(&self, size: u64) -> io::Result<()> {
277 let mut info = c::FILE_END_OF_FILE_INFO {
278 EndOfFile: size as c::LARGE_INTEGER,
280 let size = mem::size_of_val(&info);
282 c::SetFileInformationByHandle(self.handle.raw(),
283 c::FileEndOfFileInfo,
284 &mut info as *mut _ as *mut _,
290 pub fn file_attr(&self) -> io::Result<FileAttr> {
292 let mut info: c::BY_HANDLE_FILE_INFORMATION = mem::zeroed();
293 try!(cvt(c::GetFileInformationByHandle(self.handle.raw(),
295 let mut attr = FileAttr {
296 data: c::WIN32_FILE_ATTRIBUTE_DATA {
297 dwFileAttributes: info.dwFileAttributes,
298 ftCreationTime: info.ftCreationTime,
299 ftLastAccessTime: info.ftLastAccessTime,
300 ftLastWriteTime: info.ftLastWriteTime,
301 nFileSizeHigh: info.nFileSizeHigh,
302 nFileSizeLow: info.nFileSizeLow,
306 if attr.is_reparse_point() {
307 let mut b = [0; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
308 if let Ok((_, buf)) = self.reparse_point(&mut b) {
309 attr.reparse_tag = buf.ReparseTag;
316 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
317 self.handle.read(buf)
320 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
321 self.handle.write(buf)
324 pub fn flush(&self) -> io::Result<()> { Ok(()) }
326 pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
327 let (whence, pos) = match pos {
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 handle(&self) -> &Handle { &self.handle }
343 pub fn into_handle(self) -> Handle { self.handle }
345 fn reparse_point<'a>(&self,
346 space: &'a mut [u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE])
347 -> io::Result<(c::DWORD, &'a c::REPARSE_DATA_BUFFER)> {
351 c::DeviceIoControl(self.handle.raw(),
352 c::FSCTL_GET_REPARSE_POINT,
355 space.as_mut_ptr() as *mut _,
356 space.len() as c::DWORD,
360 Ok((bytes, &*(space.as_ptr() as *const c::REPARSE_DATA_BUFFER)))
364 fn readlink(&self) -> io::Result<PathBuf> {
365 let mut space = [0u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
366 let (_bytes, buf) = try!(self.reparse_point(&mut space));
367 if buf.ReparseTag != c::IO_REPARSE_TAG_SYMLINK {
368 return Err(io::Error::new(io::ErrorKind::Other, "not a symlink"))
372 let info: *const c::SYMBOLIC_LINK_REPARSE_BUFFER =
373 &buf.rest as *const _ as *const _;
374 let path_buffer = &(*info).PathBuffer as *const _ as *const u16;
375 let subst_off = (*info).SubstituteNameOffset / 2;
376 let subst_ptr = path_buffer.offset(subst_off as isize);
377 let subst_len = (*info).SubstituteNameLength / 2;
378 let subst = slice::from_raw_parts(subst_ptr, subst_len as usize);
380 Ok(PathBuf::from(OsString::from_wide(subst)))
385 impl FromInner<c::HANDLE> for File {
386 fn from_inner(handle: c::HANDLE) -> File {
387 File { handle: Handle::new(handle) }
391 impl fmt::Debug for File {
392 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
393 // FIXME(#24570): add more info here (e.g. mode)
394 let mut b = f.debug_struct("File");
395 b.field("handle", &self.handle.raw());
396 if let Ok(path) = get_path(&self) {
397 b.field("path", &path);
404 pub fn size(&self) -> u64 {
405 ((self.data.nFileSizeHigh as u64) << 32) | (self.data.nFileSizeLow as u64)
408 pub fn perm(&self) -> FilePermissions {
409 FilePermissions { attrs: self.data.dwFileAttributes }
412 pub fn attrs(&self) -> u32 { self.data.dwFileAttributes as u32 }
414 pub fn file_type(&self) -> FileType {
415 FileType::new(self.data.dwFileAttributes, self.reparse_tag)
418 pub fn created(&self) -> u64 { self.to_u64(&self.data.ftCreationTime) }
419 pub fn accessed(&self) -> u64 { self.to_u64(&self.data.ftLastAccessTime) }
420 pub fn modified(&self) -> u64 { self.to_u64(&self.data.ftLastWriteTime) }
422 fn to_u64(&self, ft: &c::FILETIME) -> u64 {
423 (ft.dwLowDateTime as u64) | ((ft.dwHighDateTime as u64) << 32)
426 fn is_reparse_point(&self) -> bool {
427 self.data.dwFileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0
431 impl FilePermissions {
432 pub fn readonly(&self) -> bool {
433 self.attrs & c::FILE_ATTRIBUTE_READONLY != 0
436 pub fn set_readonly(&mut self, readonly: bool) {
438 self.attrs |= c::FILE_ATTRIBUTE_READONLY;
440 self.attrs &= !c::FILE_ATTRIBUTE_READONLY;
446 fn new(attrs: c::DWORD, reparse_tag: c::DWORD) -> FileType {
447 match (attrs & c::FILE_ATTRIBUTE_DIRECTORY != 0,
448 attrs & c::FILE_ATTRIBUTE_REPARSE_POINT != 0,
450 (false, false, _) => FileType::File,
451 (true, false, _) => FileType::Dir,
452 (false, true, c::IO_REPARSE_TAG_SYMLINK) => FileType::SymlinkFile,
453 (true, true, c::IO_REPARSE_TAG_SYMLINK) => FileType::SymlinkDir,
454 (true, true, c::IO_REPARSE_TAG_MOUNT_POINT) => FileType::MountPoint,
455 (_, true, _) => FileType::ReparsePoint,
456 // Note: if a _file_ has a reparse tag of the type IO_REPARSE_TAG_MOUNT_POINT it is
457 // invalid, as junctions always have to be dirs. We set the filetype to ReparsePoint
458 // to indicate it is something symlink-like, but not something you can follow.
462 pub fn is_dir(&self) -> bool { *self == FileType::Dir }
463 pub fn is_file(&self) -> bool { *self == FileType::File }
464 pub fn is_symlink(&self) -> bool {
465 *self == FileType::SymlinkFile ||
466 *self == FileType::SymlinkDir ||
467 *self == FileType::MountPoint
469 pub fn is_symlink_dir(&self) -> bool {
470 *self == FileType::SymlinkDir || *self == FileType::MountPoint
475 pub fn new() -> DirBuilder { DirBuilder }
477 pub fn mkdir(&self, p: &Path) -> io::Result<()> {
478 let p = try!(to_u16s(p));
480 c::CreateDirectoryW(p.as_ptr(), ptr::null_mut())
486 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
487 let root = p.to_path_buf();
488 let star = p.join("*");
489 let path = try!(to_u16s(&star));
492 let mut wfd = mem::zeroed();
493 let find_handle = c::FindFirstFileW(path.as_ptr(), &mut wfd);
494 if find_handle != c::INVALID_HANDLE_VALUE {
496 handle: FindNextFileHandle(find_handle),
497 root: Arc::new(root),
501 Err(Error::last_os_error())
506 pub fn unlink(p: &Path) -> io::Result<()> {
507 let p_u16s = try!(to_u16s(p));
508 try!(cvt(unsafe { c::DeleteFileW(p_u16s.as_ptr()) }));
512 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
513 let old = try!(to_u16s(old));
514 let new = try!(to_u16s(new));
516 c::MoveFileExW(old.as_ptr(), new.as_ptr(), c::MOVEFILE_REPLACE_EXISTING)
521 pub fn rmdir(p: &Path) -> io::Result<()> {
522 let p = try!(to_u16s(p));
523 try!(cvt(unsafe { c::RemoveDirectoryW(p.as_ptr()) }));
527 pub fn remove_dir_all(path: &Path) -> io::Result<()> {
528 let filetype = try!(lstat(path)).file_type();
529 if filetype.is_symlink() {
530 // On Windows symlinks to files and directories are removed differently.
531 // rmdir only deletes dir symlinks and junctions, not file symlinks.
534 remove_dir_all_recursive(path)
538 fn remove_dir_all_recursive(path: &Path) -> io::Result<()> {
539 for child in try!(readdir(path)) {
540 let child = try!(child);
541 let child_type = try!(child.file_type());
542 if child_type.is_dir() {
543 try!(remove_dir_all_recursive(&child.path()));
544 } else if child_type.is_symlink_dir() {
545 try!(rmdir(&child.path()));
547 try!(unlink(&child.path()));
553 pub fn readlink(p: &Path) -> io::Result<PathBuf> {
554 let file = try!(File::open_reparse_point(p, false));
558 pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
559 symlink_inner(src, dst, false)
562 pub fn symlink_inner(src: &Path, dst: &Path, dir: bool) -> io::Result<()> {
563 let src = try!(to_u16s(src));
564 let dst = try!(to_u16s(dst));
565 let flags = if dir { c::SYMBOLIC_LINK_FLAG_DIRECTORY } else { 0 };
567 c::CreateSymbolicLinkW(dst.as_ptr(), src.as_ptr(), flags) as c::BOOL
572 pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
573 let src = try!(to_u16s(src));
574 let dst = try!(to_u16s(dst));
576 c::CreateHardLinkW(dst.as_ptr(), src.as_ptr(), ptr::null_mut())
581 pub fn stat(p: &Path) -> io::Result<FileAttr> {
582 let attr = try!(lstat(p));
584 // If this is a reparse point, then we need to reopen the file to get the
585 // actual destination. We also pass the FILE_FLAG_BACKUP_SEMANTICS flag to
586 // ensure that we can open directories (this path may be a directory
587 // junction). Once the file is opened we ask the opened handle what its
588 // metadata information is.
589 if attr.is_reparse_point() {
590 let mut opts = OpenOptions::new();
591 // No read or write permissions are necessary
593 // This flag is so we can open directories too
594 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
595 let file = try!(File::open(p, &opts));
602 pub fn lstat(p: &Path) -> io::Result<FileAttr> {
603 let u16s = try!(to_u16s(p));
605 let mut attr: FileAttr = mem::zeroed();
606 try!(cvt(c::GetFileAttributesExW(u16s.as_ptr(),
607 c::GetFileExInfoStandard,
608 &mut attr.data as *mut _ as *mut _)));
609 if attr.is_reparse_point() {
610 attr.reparse_tag = File::open_reparse_point(p, false).and_then(|f| {
611 let mut b = [0; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
612 f.reparse_point(&mut b).map(|(_, b)| b.ReparseTag)
619 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
620 let p = try!(to_u16s(p));
622 try!(cvt(c::SetFileAttributesW(p.as_ptr(), perm.attrs)));
627 fn get_path(f: &File) -> io::Result<PathBuf> {
628 super::fill_utf16_buf(|buf, sz| unsafe {
629 c::GetFinalPathNameByHandleW(f.handle.raw(), buf, sz,
632 PathBuf::from(OsString::from_wide(buf))
636 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
637 let mut opts = OpenOptions::new();
638 // No read or write permissions are necessary
640 // This flag is so we can open directories too
641 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
642 let f = try!(File::open(p, &opts));
646 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
647 unsafe extern "system" fn callback(
648 _TotalFileSize: c::LARGE_INTEGER,
649 TotalBytesTransferred: c::LARGE_INTEGER,
650 _StreamSize: c::LARGE_INTEGER,
651 _StreamBytesTransferred: c::LARGE_INTEGER,
652 _dwStreamNumber: c::DWORD,
653 _dwCallbackReason: c::DWORD,
654 _hSourceFile: c::HANDLE,
655 _hDestinationFile: c::HANDLE,
658 *(lpData as *mut i64) = TotalBytesTransferred;
661 let pfrom = try!(to_u16s(from));
662 let pto = try!(to_u16s(to));
665 c::CopyFileExW(pfrom.as_ptr(), pto.as_ptr(), Some(callback),
666 &mut size as *mut _ as *mut _, ptr::null_mut(), 0)
672 pub fn symlink_junction<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
673 symlink_junction_inner(src.as_ref(), dst.as_ref())
676 // Creating a directory junction on windows involves dealing with reparse
677 // points and the DeviceIoControl function, and this code is a skeleton of
678 // what can be found here:
680 // http://www.flexhex.com/docs/articles/hard-links.phtml
682 fn symlink_junction_inner(target: &Path, junction: &Path) -> io::Result<()> {
683 let d = DirBuilder::new();
684 try!(d.mkdir(&junction));
685 let f = try!(File::open_reparse_point(junction, true));
686 let h = f.handle().raw();
689 let mut data = [0u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
690 let mut db = data.as_mut_ptr()
691 as *mut c::REPARSE_MOUNTPOINT_DATA_BUFFER;
692 let buf = &mut (*db).ReparseTarget as *mut _;
694 // FIXME: this conversion is very hacky
696 let v = v.iter().map(|x| *x as u16);
697 for c in v.chain(target.as_os_str().encode_wide()) {
703 (*db).ReparseTag = c::IO_REPARSE_TAG_MOUNT_POINT;
704 (*db).ReparseTargetMaximumLength = (i * 2) as c::WORD;
705 (*db).ReparseTargetLength = ((i - 1) * 2) as c::WORD;
706 (*db).ReparseDataLength =
707 (*db).ReparseTargetLength as c::DWORD + 12;
710 cvt(c::DeviceIoControl(h as *mut _,
711 c::FSCTL_SET_REPARSE_POINT,
712 data.as_ptr() as *mut _,
713 (*db).ReparseDataLength + 8,
716 ptr::null_mut())).map(|_| ())