1 use crate::os::windows::prelude::*;
3 use crate::ffi::OsString;
5 use crate::io::{self, Error, IoSlice, IoSliceMut, SeekFrom};
7 use crate::path::{Path, PathBuf};
11 use crate::sys::handle::Handle;
12 use crate::sys::time::SystemTime;
13 use crate::sys::{c, cvt};
14 use crate::sys_common::FromInner;
25 creation_time: c::FILETIME,
26 last_access_time: c::FILETIME,
27 last_write_time: c::FILETIME,
29 reparse_tag: c::DWORD,
30 volume_serial_number: Option<u32>,
31 number_of_links: Option<u32>,
32 file_index: Option<u64>,
35 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
38 reparse_tag: c::DWORD,
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,
57 #[derive(Clone, Debug)]
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 {
81 pub struct DirBuilder;
83 impl fmt::Debug for ReadDir {
84 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85 // This will only be called from std::fs::ReadDir, which will add a "ReadDir()" frame.
86 // Thus the result will be e g 'ReadDir("C:\")'
87 fmt::Debug::fmt(&*self.root, f)
91 impl Iterator for ReadDir {
92 type Item = io::Result<DirEntry>;
93 fn next(&mut self) -> Option<io::Result<DirEntry>> {
94 if let Some(first) = self.first.take() {
95 if let Some(e) = DirEntry::new(&self.root, &first) {
100 let mut wfd = mem::zeroed();
102 if c::FindNextFileW(self.handle.0, &mut wfd) == 0 {
103 if c::GetLastError() == c::ERROR_NO_MORE_FILES {
106 return Some(Err(Error::last_os_error()));
109 if let Some(e) = DirEntry::new(&self.root, &wfd) {
117 impl Drop for FindNextFileHandle {
119 let r = unsafe { c::FindClose(self.0) };
120 debug_assert!(r != 0);
125 fn new(root: &Arc<PathBuf>, wfd: &c::WIN32_FIND_DATAW) -> Option<DirEntry> {
126 match &wfd.cFileName[0..3] {
127 // check for '.' and '..'
128 &[46, 0, ..] | &[46, 46, 0, ..] => return None,
132 Some(DirEntry { root: root.clone(), data: *wfd })
135 pub fn path(&self) -> PathBuf {
136 self.root.join(&self.file_name())
139 pub fn file_name(&self) -> OsString {
140 let filename = super::truncate_utf16_at_nul(&self.data.cFileName);
141 OsString::from_wide(filename)
144 pub fn file_type(&self) -> io::Result<FileType> {
146 self.data.dwFileAttributes,
147 /* reparse_tag = */ self.data.dwReserved0,
151 pub fn metadata(&self) -> io::Result<FileAttr> {
153 attributes: self.data.dwFileAttributes,
154 creation_time: self.data.ftCreationTime,
155 last_access_time: self.data.ftLastAccessTime,
156 last_write_time: self.data.ftLastWriteTime,
157 file_size: ((self.data.nFileSizeHigh as u64) << 32) | (self.data.nFileSizeLow as u64),
158 reparse_tag: if self.data.dwFileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
159 // reserved unless this is a reparse point
160 self.data.dwReserved0
164 volume_serial_number: None,
165 number_of_links: None,
172 pub fn new() -> OpenOptions {
184 share_mode: c::FILE_SHARE_READ | c::FILE_SHARE_WRITE | c::FILE_SHARE_DELETE,
186 security_qos_flags: 0,
187 security_attributes: 0,
191 pub fn read(&mut self, read: bool) {
194 pub fn write(&mut self, write: bool) {
197 pub fn append(&mut self, append: bool) {
198 self.append = append;
200 pub fn truncate(&mut self, truncate: bool) {
201 self.truncate = truncate;
203 pub fn create(&mut self, create: bool) {
204 self.create = create;
206 pub fn create_new(&mut self, create_new: bool) {
207 self.create_new = create_new;
210 pub fn custom_flags(&mut self, flags: u32) {
211 self.custom_flags = flags;
213 pub fn access_mode(&mut self, access_mode: u32) {
214 self.access_mode = Some(access_mode);
216 pub fn share_mode(&mut self, share_mode: u32) {
217 self.share_mode = share_mode;
219 pub fn attributes(&mut self, attrs: u32) {
220 self.attributes = attrs;
222 pub fn security_qos_flags(&mut self, flags: u32) {
223 // We have to set `SECURITY_SQOS_PRESENT` here, because one of the valid flags we can
224 // receive is `SECURITY_ANONYMOUS = 0x0`, which we can't check for later on.
225 self.security_qos_flags = flags | c::SECURITY_SQOS_PRESENT;
227 pub fn security_attributes(&mut self, attrs: c::LPSECURITY_ATTRIBUTES) {
228 self.security_attributes = attrs as usize;
231 fn get_access_mode(&self) -> io::Result<c::DWORD> {
232 const ERROR_INVALID_PARAMETER: i32 = 87;
234 match (self.read, self.write, self.append, self.access_mode) {
235 (.., Some(mode)) => Ok(mode),
236 (true, false, false, None) => Ok(c::GENERIC_READ),
237 (false, true, false, None) => Ok(c::GENERIC_WRITE),
238 (true, true, false, None) => Ok(c::GENERIC_READ | c::GENERIC_WRITE),
239 (false, _, true, None) => Ok(c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA),
240 (true, _, true, None) => {
241 Ok(c::GENERIC_READ | (c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA))
243 (false, false, false, None) => Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER)),
247 fn get_creation_mode(&self) -> io::Result<c::DWORD> {
248 const ERROR_INVALID_PARAMETER: i32 = 87;
250 match (self.write, self.append) {
253 if self.truncate || self.create || self.create_new {
254 return Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER));
258 if self.truncate && !self.create_new {
259 return Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER));
264 Ok(match (self.create, self.truncate, self.create_new) {
265 (false, false, false) => c::OPEN_EXISTING,
266 (true, false, false) => c::OPEN_ALWAYS,
267 (false, true, false) => c::TRUNCATE_EXISTING,
268 (true, true, false) => c::CREATE_ALWAYS,
269 (_, _, true) => c::CREATE_NEW,
273 fn get_flags_and_attributes(&self) -> c::DWORD {
276 | self.security_qos_flags
277 | if self.create_new { c::FILE_FLAG_OPEN_REPARSE_POINT } else { 0 }
282 pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
283 let path = to_u16s(path)?;
284 let handle = unsafe {
287 opts.get_access_mode()?,
289 opts.security_attributes as *mut _,
290 opts.get_creation_mode()?,
291 opts.get_flags_and_attributes(),
295 if handle == c::INVALID_HANDLE_VALUE {
296 Err(Error::last_os_error())
298 Ok(File { handle: Handle::new(handle) })
302 pub fn fsync(&self) -> io::Result<()> {
303 cvt(unsafe { c::FlushFileBuffers(self.handle.raw()) })?;
307 pub fn datasync(&self) -> io::Result<()> {
311 pub fn truncate(&self, size: u64) -> io::Result<()> {
312 let mut info = c::FILE_END_OF_FILE_INFO { EndOfFile: size as c::LARGE_INTEGER };
313 let size = mem::size_of_val(&info);
315 c::SetFileInformationByHandle(
317 c::FileEndOfFileInfo,
318 &mut info as *mut _ as *mut _,
325 #[cfg(not(target_vendor = "uwp"))]
326 pub fn file_attr(&self) -> io::Result<FileAttr> {
328 let mut info: c::BY_HANDLE_FILE_INFORMATION = mem::zeroed();
329 cvt(c::GetFileInformationByHandle(self.handle.raw(), &mut info))?;
330 let mut reparse_tag = 0;
331 if info.dwFileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
332 let mut b = [0; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
333 if let Ok((_, buf)) = self.reparse_point(&mut b) {
334 reparse_tag = buf.ReparseTag;
338 attributes: info.dwFileAttributes,
339 creation_time: info.ftCreationTime,
340 last_access_time: info.ftLastAccessTime,
341 last_write_time: info.ftLastWriteTime,
342 file_size: (info.nFileSizeLow as u64) | ((info.nFileSizeHigh as u64) << 32),
344 volume_serial_number: Some(info.dwVolumeSerialNumber),
345 number_of_links: Some(info.nNumberOfLinks),
347 (info.nFileIndexLow as u64) | ((info.nFileIndexHigh as u64) << 32),
353 #[cfg(target_vendor = "uwp")]
354 pub fn file_attr(&self) -> io::Result<FileAttr> {
356 let mut info: c::FILE_BASIC_INFO = mem::zeroed();
357 let size = mem::size_of_val(&info);
358 cvt(c::GetFileInformationByHandleEx(
361 &mut info as *mut _ as *mut libc::c_void,
364 let mut attr = FileAttr {
365 attributes: info.FileAttributes,
366 creation_time: c::FILETIME {
367 dwLowDateTime: info.CreationTime as c::DWORD,
368 dwHighDateTime: (info.CreationTime >> 32) as c::DWORD,
370 last_access_time: c::FILETIME {
371 dwLowDateTime: info.LastAccessTime as c::DWORD,
372 dwHighDateTime: (info.LastAccessTime >> 32) as c::DWORD,
374 last_write_time: c::FILETIME {
375 dwLowDateTime: info.LastWriteTime as c::DWORD,
376 dwHighDateTime: (info.LastWriteTime >> 32) as c::DWORD,
380 volume_serial_number: None,
381 number_of_links: None,
384 let mut info: c::FILE_STANDARD_INFO = mem::zeroed();
385 let size = mem::size_of_val(&info);
386 cvt(c::GetFileInformationByHandleEx(
389 &mut info as *mut _ as *mut libc::c_void,
392 attr.file_size = info.AllocationSize as u64;
393 attr.number_of_links = Some(info.NumberOfLinks);
394 if attr.file_type().is_reparse_point() {
395 let mut b = [0; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
396 if let Ok((_, buf)) = self.reparse_point(&mut b) {
397 attr.reparse_tag = buf.ReparseTag;
404 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
405 self.handle.read(buf)
408 pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
409 self.handle.read_vectored(bufs)
413 pub fn is_read_vectored(&self) -> bool {
414 self.handle.is_read_vectored()
417 pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
418 self.handle.read_at(buf, offset)
421 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
422 self.handle.write(buf)
425 pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
426 self.handle.write_vectored(bufs)
430 pub fn is_write_vectored(&self) -> bool {
431 self.handle.is_write_vectored()
434 pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
435 self.handle.write_at(buf, offset)
438 pub fn flush(&self) -> io::Result<()> {
442 pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
443 let (whence, pos) = match pos {
444 // Casting to `i64` is fine, `SetFilePointerEx` reinterprets this
446 SeekFrom::Start(n) => (c::FILE_BEGIN, n as i64),
447 SeekFrom::End(n) => (c::FILE_END, n),
448 SeekFrom::Current(n) => (c::FILE_CURRENT, n),
450 let pos = pos as c::LARGE_INTEGER;
452 cvt(unsafe { c::SetFilePointerEx(self.handle.raw(), pos, &mut newpos, whence) })?;
456 pub fn duplicate(&self) -> io::Result<File> {
457 Ok(File { handle: self.handle.duplicate(0, false, c::DUPLICATE_SAME_ACCESS)? })
460 pub fn handle(&self) -> &Handle {
464 pub fn into_handle(self) -> Handle {
468 fn reparse_point<'a>(
470 space: &'a mut [u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE],
471 ) -> io::Result<(c::DWORD, &'a c::REPARSE_DATA_BUFFER)> {
477 c::FSCTL_GET_REPARSE_POINT,
480 space.as_mut_ptr() as *mut _,
481 space.len() as c::DWORD,
486 Ok((bytes, &*(space.as_ptr() as *const c::REPARSE_DATA_BUFFER)))
490 fn readlink(&self) -> io::Result<PathBuf> {
491 let mut space = [0u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
492 let (_bytes, buf) = self.reparse_point(&mut space)?;
494 let (path_buffer, subst_off, subst_len, relative) = match buf.ReparseTag {
495 c::IO_REPARSE_TAG_SYMLINK => {
496 let info: *const c::SYMBOLIC_LINK_REPARSE_BUFFER =
497 &buf.rest as *const _ as *const _;
499 &(*info).PathBuffer as *const _ as *const u16,
500 (*info).SubstituteNameOffset / 2,
501 (*info).SubstituteNameLength / 2,
502 (*info).Flags & c::SYMLINK_FLAG_RELATIVE != 0,
505 c::IO_REPARSE_TAG_MOUNT_POINT => {
506 let info: *const c::MOUNT_POINT_REPARSE_BUFFER =
507 &buf.rest as *const _ as *const _;
509 &(*info).PathBuffer as *const _ as *const u16,
510 (*info).SubstituteNameOffset / 2,
511 (*info).SubstituteNameLength / 2,
516 return Err(io::Error::new_const(
517 io::ErrorKind::Other,
518 &"Unsupported reparse point type",
522 let subst_ptr = path_buffer.offset(subst_off as isize);
523 let mut subst = slice::from_raw_parts(subst_ptr, subst_len as usize);
524 // Absolute paths start with an NT internal namespace prefix `\??\`
525 // We should not let it leak through.
526 if !relative && subst.starts_with(&[92u16, 63u16, 63u16, 92u16]) {
529 Ok(PathBuf::from(OsString::from_wide(subst)))
533 pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
534 let mut info = c::FILE_BASIC_INFO {
539 FileAttributes: perm.attrs,
541 let size = mem::size_of_val(&info);
543 c::SetFileInformationByHandle(
546 &mut info as *mut _ as *mut _,
554 impl FromInner<c::HANDLE> for File {
555 fn from_inner(handle: c::HANDLE) -> File {
556 File { handle: Handle::new(handle) }
560 impl fmt::Debug for File {
561 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
562 // FIXME(#24570): add more info here (e.g., mode)
563 let mut b = f.debug_struct("File");
564 b.field("handle", &self.handle.raw());
565 if let Ok(path) = get_path(&self) {
566 b.field("path", &path);
573 pub fn size(&self) -> u64 {
577 pub fn perm(&self) -> FilePermissions {
578 FilePermissions { attrs: self.attributes }
581 pub fn attrs(&self) -> u32 {
585 pub fn file_type(&self) -> FileType {
586 FileType::new(self.attributes, self.reparse_tag)
589 pub fn modified(&self) -> io::Result<SystemTime> {
590 Ok(SystemTime::from(self.last_write_time))
593 pub fn accessed(&self) -> io::Result<SystemTime> {
594 Ok(SystemTime::from(self.last_access_time))
597 pub fn created(&self) -> io::Result<SystemTime> {
598 Ok(SystemTime::from(self.creation_time))
601 pub fn modified_u64(&self) -> u64 {
602 to_u64(&self.last_write_time)
605 pub fn accessed_u64(&self) -> u64 {
606 to_u64(&self.last_access_time)
609 pub fn created_u64(&self) -> u64 {
610 to_u64(&self.creation_time)
613 pub fn volume_serial_number(&self) -> Option<u32> {
614 self.volume_serial_number
617 pub fn number_of_links(&self) -> Option<u32> {
621 pub fn file_index(&self) -> Option<u64> {
626 fn to_u64(ft: &c::FILETIME) -> u64 {
627 (ft.dwLowDateTime as u64) | ((ft.dwHighDateTime as u64) << 32)
630 impl FilePermissions {
631 pub fn readonly(&self) -> bool {
632 self.attrs & c::FILE_ATTRIBUTE_READONLY != 0
635 pub fn set_readonly(&mut self, readonly: bool) {
637 self.attrs |= c::FILE_ATTRIBUTE_READONLY;
639 self.attrs &= !c::FILE_ATTRIBUTE_READONLY;
645 fn new(attrs: c::DWORD, reparse_tag: c::DWORD) -> FileType {
646 FileType { attributes: attrs, reparse_tag: reparse_tag }
648 pub fn is_dir(&self) -> bool {
649 !self.is_symlink() && self.is_directory()
651 pub fn is_file(&self) -> bool {
652 !self.is_symlink() && !self.is_directory()
654 pub fn is_symlink(&self) -> bool {
655 self.is_reparse_point() && self.is_reparse_tag_name_surrogate()
657 pub fn is_symlink_dir(&self) -> bool {
658 self.is_symlink() && self.is_directory()
660 pub fn is_symlink_file(&self) -> bool {
661 self.is_symlink() && !self.is_directory()
663 fn is_directory(&self) -> bool {
664 self.attributes & c::FILE_ATTRIBUTE_DIRECTORY != 0
666 fn is_reparse_point(&self) -> bool {
667 self.attributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0
669 fn is_reparse_tag_name_surrogate(&self) -> bool {
670 self.reparse_tag & 0x20000000 != 0
675 pub fn new() -> DirBuilder {
679 pub fn mkdir(&self, p: &Path) -> io::Result<()> {
681 cvt(unsafe { c::CreateDirectoryW(p.as_ptr(), ptr::null_mut()) })?;
686 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
687 let root = p.to_path_buf();
688 let star = p.join("*");
689 let path = to_u16s(&star)?;
692 let mut wfd = mem::zeroed();
693 let find_handle = c::FindFirstFileW(path.as_ptr(), &mut wfd);
694 if find_handle != c::INVALID_HANDLE_VALUE {
696 handle: FindNextFileHandle(find_handle),
697 root: Arc::new(root),
701 Err(Error::last_os_error())
706 pub fn unlink(p: &Path) -> io::Result<()> {
707 let p_u16s = to_u16s(p)?;
708 cvt(unsafe { c::DeleteFileW(p_u16s.as_ptr()) })?;
712 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
713 let old = to_u16s(old)?;
714 let new = to_u16s(new)?;
715 cvt(unsafe { c::MoveFileExW(old.as_ptr(), new.as_ptr(), c::MOVEFILE_REPLACE_EXISTING) })?;
719 pub fn rmdir(p: &Path) -> io::Result<()> {
721 cvt(unsafe { c::RemoveDirectoryW(p.as_ptr()) })?;
725 pub fn remove_dir_all(path: &Path) -> io::Result<()> {
726 let filetype = lstat(path)?.file_type();
727 if filetype.is_symlink() {
728 // On Windows symlinks to files and directories are removed differently.
729 // rmdir only deletes dir symlinks and junctions, not file symlinks.
732 remove_dir_all_recursive(path)
736 fn remove_dir_all_recursive(path: &Path) -> io::Result<()> {
737 for child in readdir(path)? {
739 let child_type = child.file_type()?;
740 if child_type.is_dir() {
741 remove_dir_all_recursive(&child.path())?;
742 } else if child_type.is_symlink_dir() {
743 rmdir(&child.path())?;
745 unlink(&child.path())?;
751 pub fn readlink(path: &Path) -> io::Result<PathBuf> {
752 // Open the link with no access mode, instead of generic read.
753 // By default FILE_LIST_DIRECTORY is denied for the junction "C:\Documents and Settings", so
754 // this is needed for a common case.
755 let mut opts = OpenOptions::new();
757 opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT | c::FILE_FLAG_BACKUP_SEMANTICS);
758 let file = File::open(&path, &opts)?;
762 pub fn symlink(original: &Path, link: &Path) -> io::Result<()> {
763 symlink_inner(original, link, false)
766 pub fn symlink_inner(original: &Path, link: &Path, dir: bool) -> io::Result<()> {
767 let original = to_u16s(original)?;
768 let link = to_u16s(link)?;
769 let flags = if dir { c::SYMBOLIC_LINK_FLAG_DIRECTORY } else { 0 };
770 // Formerly, symlink creation required the SeCreateSymbolicLink privilege. For the Windows 10
771 // Creators Update, Microsoft loosened this to allow unprivileged symlink creation if the
772 // computer is in Developer Mode, but SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE must be
773 // added to dwFlags to opt into this behaviour.
774 let result = cvt(unsafe {
775 c::CreateSymbolicLinkW(
778 flags | c::SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE,
781 if let Err(err) = result {
782 if err.raw_os_error() == Some(c::ERROR_INVALID_PARAMETER as i32) {
783 // Older Windows objects to SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE,
784 // so if we encounter ERROR_INVALID_PARAMETER, retry without that flag.
786 c::CreateSymbolicLinkW(link.as_ptr(), original.as_ptr(), flags) as c::BOOL
795 #[cfg(not(target_vendor = "uwp"))]
796 pub fn link(original: &Path, link: &Path) -> io::Result<()> {
797 let original = to_u16s(original)?;
798 let link = to_u16s(link)?;
799 cvt(unsafe { c::CreateHardLinkW(link.as_ptr(), original.as_ptr(), ptr::null_mut()) })?;
803 #[cfg(target_vendor = "uwp")]
804 pub fn link(_original: &Path, _link: &Path) -> io::Result<()> {
805 return Err(io::Error::new_const(
806 io::ErrorKind::Unsupported,
807 &"hard link are not supported on UWP",
811 pub fn stat(path: &Path) -> io::Result<FileAttr> {
812 let mut opts = OpenOptions::new();
813 // No read or write permissions are necessary
815 // This flag is so we can open directories too
816 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
817 let file = File::open(path, &opts)?;
821 pub fn lstat(path: &Path) -> io::Result<FileAttr> {
822 let mut opts = OpenOptions::new();
823 // No read or write permissions are necessary
825 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS | c::FILE_FLAG_OPEN_REPARSE_POINT);
826 let file = File::open(path, &opts)?;
830 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
833 cvt(c::SetFileAttributesW(p.as_ptr(), perm.attrs))?;
838 fn get_path(f: &File) -> io::Result<PathBuf> {
839 super::fill_utf16_buf(
841 c::GetFinalPathNameByHandleW(f.handle.raw(), buf, sz, c::VOLUME_NAME_DOS)
843 |buf| PathBuf::from(OsString::from_wide(buf)),
847 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
848 let mut opts = OpenOptions::new();
849 // No read or write permissions are necessary
851 // This flag is so we can open directories too
852 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
853 let f = File::open(p, &opts)?;
857 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
858 unsafe extern "system" fn callback(
859 _TotalFileSize: c::LARGE_INTEGER,
860 _TotalBytesTransferred: c::LARGE_INTEGER,
861 _StreamSize: c::LARGE_INTEGER,
862 StreamBytesTransferred: c::LARGE_INTEGER,
863 dwStreamNumber: c::DWORD,
864 _dwCallbackReason: c::DWORD,
865 _hSourceFile: c::HANDLE,
866 _hDestinationFile: c::HANDLE,
869 if dwStreamNumber == 1 {
870 *(lpData as *mut i64) = StreamBytesTransferred;
874 let pfrom = to_u16s(from)?;
875 let pto = to_u16s(to)?;
882 &mut size as *mut _ as *mut _,
891 pub fn symlink_junction<P: AsRef<Path>, Q: AsRef<Path>>(
894 ) -> io::Result<()> {
895 symlink_junction_inner(original.as_ref(), junction.as_ref())
898 // Creating a directory junction on windows involves dealing with reparse
899 // points and the DeviceIoControl function, and this code is a skeleton of
900 // what can be found here:
902 // http://www.flexhex.com/docs/articles/hard-links.phtml
904 fn symlink_junction_inner(original: &Path, junction: &Path) -> io::Result<()> {
905 let d = DirBuilder::new();
908 let mut opts = OpenOptions::new();
910 opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT | c::FILE_FLAG_BACKUP_SEMANTICS);
911 let f = File::open(junction, &opts)?;
912 let h = f.handle().raw();
915 let mut data = [0u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
916 let db = data.as_mut_ptr() as *mut c::REPARSE_MOUNTPOINT_DATA_BUFFER;
917 let buf = &mut (*db).ReparseTarget as *mut c::WCHAR;
919 // FIXME: this conversion is very hacky
921 let v = v.iter().map(|x| *x as u16);
922 for c in v.chain(original.as_os_str().encode_wide()) {
928 (*db).ReparseTag = c::IO_REPARSE_TAG_MOUNT_POINT;
929 (*db).ReparseTargetMaximumLength = (i * 2) as c::WORD;
930 (*db).ReparseTargetLength = ((i - 1) * 2) as c::WORD;
931 (*db).ReparseDataLength = (*db).ReparseTargetLength as c::DWORD + 12;
934 cvt(c::DeviceIoControl(
936 c::FSCTL_SET_REPARSE_POINT,
937 data.as_ptr() as *mut _,
938 (*db).ReparseDataLength + 8,