]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/windows/fs.rs
Auto merge of #30865 - alexcrichton:mtime-system-time, r=aturon
[rust.git] / src / libstd / sys / windows / fs.rs
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.
4 //
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.
10
11 use io::prelude::*;
12 use os::windows::prelude::*;
13
14 use ffi::OsString;
15 use fmt;
16 use io::{self, Error, SeekFrom};
17 use mem;
18 use path::{Path, PathBuf};
19 use ptr;
20 use slice;
21 use sync::Arc;
22 use sys::handle::Handle;
23 use sys::time::SystemTime;
24 use sys::{c, cvt};
25 use sys_common::FromInner;
26
27 use super::to_u16s;
28
29 pub struct File { handle: Handle }
30
31 #[derive(Clone)]
32 pub struct FileAttr {
33     data: c::WIN32_FILE_ATTRIBUTE_DATA,
34     reparse_tag: c::DWORD,
35 }
36
37 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
38 pub enum FileType {
39     Dir, File, SymlinkFile, SymlinkDir, ReparsePoint, MountPoint,
40 }
41
42 pub struct ReadDir {
43     handle: FindNextFileHandle,
44     root: Arc<PathBuf>,
45     first: Option<c::WIN32_FIND_DATAW>,
46 }
47
48 struct FindNextFileHandle(c::HANDLE);
49
50 unsafe impl Send for FindNextFileHandle {}
51 unsafe impl Sync for FindNextFileHandle {}
52
53 pub struct DirEntry {
54     root: Arc<PathBuf>,
55     data: c::WIN32_FIND_DATAW,
56 }
57
58 #[derive(Clone)]
59 pub struct OpenOptions {
60     // generic
61     read: bool,
62     write: bool,
63     append: bool,
64     truncate: bool,
65     create: bool,
66     create_new: bool,
67     // system-specific
68     custom_flags: u32,
69     access_mode: Option<c::DWORD>,
70     attributes: c::DWORD,
71     share_mode: c::DWORD,
72     security_qos_flags: c::DWORD,
73     security_attributes: usize, // FIXME: should be a reference
74 }
75
76 #[derive(Clone, PartialEq, Eq, Debug)]
77 pub struct FilePermissions { attrs: c::DWORD }
78
79 pub struct DirBuilder;
80
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) {
86                 return Some(Ok(e));
87             }
88         }
89         unsafe {
90             let mut wfd = mem::zeroed();
91             loop {
92                 if c::FindNextFileW(self.handle.0, &mut wfd) == 0 {
93                     if c::GetLastError() == c::ERROR_NO_MORE_FILES {
94                         return None
95                     } else {
96                         return Some(Err(Error::last_os_error()))
97                     }
98                 }
99                 if let Some(e) = DirEntry::new(&self.root, &wfd) {
100                     return Some(Ok(e))
101                 }
102             }
103         }
104     }
105 }
106
107 impl Drop for FindNextFileHandle {
108     fn drop(&mut self) {
109         let r = unsafe { c::FindClose(self.0) };
110         debug_assert!(r != 0);
111     }
112 }
113
114 impl DirEntry {
115     fn new(root: &Arc<PathBuf>, wfd: &c::WIN32_FIND_DATAW) -> Option<DirEntry> {
116         match &wfd.cFileName[0..3] {
117             // check for '.' and '..'
118             [46, 0, ..] |
119             [46, 46, 0, ..] => return None,
120             _ => {}
121         }
122
123         Some(DirEntry {
124             root: root.clone(),
125             data: *wfd,
126         })
127     }
128
129     pub fn path(&self) -> PathBuf {
130         self.root.join(&self.file_name())
131     }
132
133     pub fn file_name(&self) -> OsString {
134         let filename = super::truncate_utf16_at_nul(&self.data.cFileName);
135         OsString::from_wide(filename)
136     }
137
138     pub fn file_type(&self) -> io::Result<FileType> {
139         Ok(FileType::new(self.data.dwFileAttributes,
140                          /* reparse_tag = */ self.data.dwReserved0))
141     }
142
143     pub fn metadata(&self) -> io::Result<FileAttr> {
144         Ok(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,
152             },
153             reparse_tag: self.data.dwReserved0,
154         })
155     }
156 }
157
158 impl OpenOptions {
159     pub fn new() -> OpenOptions {
160         OpenOptions {
161             // generic
162             read: false,
163             write: false,
164             append: false,
165             truncate: false,
166             create: false,
167             create_new: false,
168             // system-specific
169             custom_flags: 0,
170             access_mode: None,
171             share_mode: c::FILE_SHARE_READ | c::FILE_SHARE_WRITE | c::FILE_SHARE_DELETE,
172             attributes: 0,
173             security_qos_flags: 0,
174             security_attributes: 0,
175         }
176     }
177
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; }
184
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;
192     }
193
194     fn get_access_mode(&self) -> io::Result<c::DWORD> {
195         const ERROR_INVALID_PARAMETER: i32 = 87;
196
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)),
206         }
207     }
208
209     fn get_creation_mode(&self) -> io::Result<c::DWORD> {
210         const ERROR_INVALID_PARAMETER: i32 = 87;
211
212         match (self.write, self.append) {
213             (true, false) => {}
214             (false, false) =>
215                 if self.truncate || self.create || self.create_new {
216                     return Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER));
217                 },
218             (_, true) =>
219                 if self.truncate && !self.create_new {
220                     return Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER));
221                 },
222         }
223
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,
230            })
231     }
232
233     fn get_flags_and_attributes(&self) -> c::DWORD {
234         self.custom_flags |
235         self.attributes |
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 }
239     }
240 }
241
242 impl File {
243     fn open_reparse_point(path: &Path, write: bool) -> io::Result<File> {
244         let mut opts = OpenOptions::new();
245         opts.read(!write);
246         opts.write(write);
247         opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT |
248                           c::FILE_FLAG_BACKUP_SEMANTICS);
249         File::open(path, &opts)
250     }
251
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()),
257                            opts.share_mode,
258                            opts.security_attributes as *mut _,
259                            try!(opts.get_creation_mode()),
260                            opts.get_flags_and_attributes(),
261                            ptr::null_mut())
262         };
263         if handle == c::INVALID_HANDLE_VALUE {
264             Err(Error::last_os_error())
265         } else {
266             Ok(File { handle: Handle::new(handle) })
267         }
268     }
269
270     pub fn fsync(&self) -> io::Result<()> {
271         try!(cvt(unsafe { c::FlushFileBuffers(self.handle.raw()) }));
272         Ok(())
273     }
274
275     pub fn datasync(&self) -> io::Result<()> { self.fsync() }
276
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,
280         };
281         let size = mem::size_of_val(&info);
282         try!(cvt(unsafe {
283             c::SetFileInformationByHandle(self.handle.raw(),
284                                           c::FileEndOfFileInfo,
285                                           &mut info as *mut _ as *mut _,
286                                           size as c::DWORD)
287         }));
288         Ok(())
289     }
290
291     pub fn file_attr(&self) -> io::Result<FileAttr> {
292         unsafe {
293             let mut info: c::BY_HANDLE_FILE_INFORMATION = mem::zeroed();
294             try!(cvt(c::GetFileInformationByHandle(self.handle.raw(),
295                                                    &mut info)));
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,
304                 },
305                 reparse_tag: 0,
306             };
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;
311                 }
312             }
313             Ok(attr)
314         }
315     }
316
317     pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
318         self.handle.read(buf)
319     }
320
321     pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
322         self.handle.write(buf)
323     }
324
325     pub fn flush(&self) -> io::Result<()> { Ok(()) }
326
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),
332         };
333         let pos = pos as c::LARGE_INTEGER;
334         let mut newpos = 0;
335         try!(cvt(unsafe {
336             c::SetFilePointerEx(self.handle.raw(), pos,
337                                 &mut newpos, whence)
338         }));
339         Ok(newpos as u64)
340     }
341
342     pub fn duplicate(&self) -> io::Result<File> {
343         Ok(File {
344             handle: try!(self.handle.duplicate(0, true, c::DUPLICATE_SAME_ACCESS)),
345         })
346     }
347
348     pub fn handle(&self) -> &Handle { &self.handle }
349
350     pub fn into_handle(self) -> Handle { self.handle }
351
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)> {
355         unsafe {
356             let mut bytes = 0;
357             try!(cvt({
358                 c::DeviceIoControl(self.handle.raw(),
359                                    c::FSCTL_GET_REPARSE_POINT,
360                                    ptr::null_mut(),
361                                    0,
362                                    space.as_mut_ptr() as *mut _,
363                                    space.len() as c::DWORD,
364                                    &mut bytes,
365                                    ptr::null_mut())
366             }));
367             Ok((bytes, &*(space.as_ptr() as *const c::REPARSE_DATA_BUFFER)))
368         }
369     }
370
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"))
376         }
377
378         unsafe {
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);
386
387             Ok(PathBuf::from(OsString::from_wide(subst)))
388         }
389     }
390 }
391
392 impl FromInner<c::HANDLE> for File {
393     fn from_inner(handle: c::HANDLE) -> File {
394         File { handle: Handle::new(handle) }
395     }
396 }
397
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);
405         }
406         b.finish()
407     }
408 }
409
410 impl FileAttr {
411     pub fn size(&self) -> u64 {
412         ((self.data.nFileSizeHigh as u64) << 32) | (self.data.nFileSizeLow as u64)
413     }
414
415     pub fn perm(&self) -> FilePermissions {
416         FilePermissions { attrs: self.data.dwFileAttributes }
417     }
418
419     pub fn attrs(&self) -> u32 { self.data.dwFileAttributes as u32 }
420
421     pub fn file_type(&self) -> FileType {
422         FileType::new(self.data.dwFileAttributes, self.reparse_tag)
423     }
424
425     pub fn modified(&self) -> io::Result<SystemTime> {
426         Ok(SystemTime::from(self.data.ftLastWriteTime))
427     }
428
429     pub fn accessed(&self) -> io::Result<SystemTime> {
430         Ok(SystemTime::from(self.data.ftLastAccessTime))
431     }
432
433     pub fn created(&self) -> io::Result<SystemTime> {
434         Ok(SystemTime::from(self.data.ftCreationTime))
435     }
436
437     pub fn modified_u64(&self) -> u64 {
438         to_u64(&self.data.ftLastWriteTime)
439     }
440
441     pub fn accessed_u64(&self) -> u64 {
442         to_u64(&self.data.ftLastAccessTime)
443     }
444
445     pub fn created_u64(&self) -> u64 {
446         to_u64(&self.data.ftCreationTime)
447     }
448
449     fn is_reparse_point(&self) -> bool {
450         self.data.dwFileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0
451     }
452 }
453
454 fn to_u64(ft: &c::FILETIME) -> u64 {
455     (ft.dwLowDateTime as u64) | ((ft.dwHighDateTime as u64) << 32)
456 }
457
458 impl FilePermissions {
459     pub fn readonly(&self) -> bool {
460         self.attrs & c::FILE_ATTRIBUTE_READONLY != 0
461     }
462
463     pub fn set_readonly(&mut self, readonly: bool) {
464         if readonly {
465             self.attrs |= c::FILE_ATTRIBUTE_READONLY;
466         } else {
467             self.attrs &= !c::FILE_ATTRIBUTE_READONLY;
468         }
469     }
470 }
471
472 impl FileType {
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,
476                reparse_tag) {
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.
486         }
487     }
488
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
495     }
496     pub fn is_symlink_dir(&self) -> bool {
497         *self == FileType::SymlinkDir || *self == FileType::MountPoint
498     }
499 }
500
501 impl DirBuilder {
502     pub fn new() -> DirBuilder { DirBuilder }
503
504     pub fn mkdir(&self, p: &Path) -> io::Result<()> {
505         let p = try!(to_u16s(p));
506         try!(cvt(unsafe {
507             c::CreateDirectoryW(p.as_ptr(), ptr::null_mut())
508         }));
509         Ok(())
510     }
511 }
512
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));
517
518     unsafe {
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 {
522             Ok(ReadDir {
523                 handle: FindNextFileHandle(find_handle),
524                 root: Arc::new(root),
525                 first: Some(wfd),
526             })
527         } else {
528             Err(Error::last_os_error())
529         }
530     }
531 }
532
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()) }));
536     Ok(())
537 }
538
539 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
540     let old = try!(to_u16s(old));
541     let new = try!(to_u16s(new));
542     try!(cvt(unsafe {
543         c::MoveFileExW(old.as_ptr(), new.as_ptr(), c::MOVEFILE_REPLACE_EXISTING)
544     }));
545     Ok(())
546 }
547
548 pub fn rmdir(p: &Path) -> io::Result<()> {
549     let p = try!(to_u16s(p));
550     try!(cvt(unsafe { c::RemoveDirectoryW(p.as_ptr()) }));
551     Ok(())
552 }
553
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()));
562         } else {
563             try!(unlink(&child.path()));
564         }
565     }
566     rmdir(path)
567 }
568
569 pub fn readlink(p: &Path) -> io::Result<PathBuf> {
570     let file = try!(File::open_reparse_point(p, false));
571     file.readlink()
572 }
573
574 pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
575     symlink_inner(src, dst, false)
576 }
577
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 };
582     try!(cvt(unsafe {
583         c::CreateSymbolicLinkW(dst.as_ptr(), src.as_ptr(), flags) as c::BOOL
584     }));
585     Ok(())
586 }
587
588 pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
589     let src = try!(to_u16s(src));
590     let dst = try!(to_u16s(dst));
591     try!(cvt(unsafe {
592         c::CreateHardLinkW(dst.as_ptr(), src.as_ptr(), ptr::null_mut())
593     }));
594     Ok(())
595 }
596
597 pub fn stat(p: &Path) -> io::Result<FileAttr> {
598     let attr = try!(lstat(p));
599
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
608         opts.access_mode(0);
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));
612         file.file_attr()
613     } else {
614         Ok(attr)
615     }
616 }
617
618 pub fn lstat(p: &Path) -> io::Result<FileAttr> {
619     let u16s = try!(to_u16s(p));
620     unsafe {
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)
629             }).unwrap_or(0);
630         }
631         Ok(attr)
632     }
633 }
634
635 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
636     let p = try!(to_u16s(p));
637     unsafe {
638         try!(cvt(c::SetFileAttributesW(p.as_ptr(), perm.attrs)));
639         Ok(())
640     }
641 }
642
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,
646                                      c::VOLUME_NAME_DOS)
647     }, |buf| {
648         PathBuf::from(OsString::from_wide(buf))
649     })
650 }
651
652 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
653     let mut opts = OpenOptions::new();
654     // No read or write permissions are necessary
655     opts.access_mode(0);
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));
659     get_path(&f)
660 }
661
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,
672         lpData: c::LPVOID,
673     ) -> c::DWORD {
674         *(lpData as *mut i64) = TotalBytesTransferred;
675         c::PROGRESS_CONTINUE
676     }
677     let pfrom = try!(to_u16s(from));
678     let pto = try!(to_u16s(to));
679     let mut size = 0i64;
680     try!(cvt(unsafe {
681         c::CopyFileExW(pfrom.as_ptr(), pto.as_ptr(), Some(callback),
682                        &mut size as *mut _ as *mut _, ptr::null_mut(), 0)
683     }));
684     Ok(size as u64)
685 }
686
687 #[allow(dead_code)]
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())
690 }
691
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:
695 //
696 // http://www.flexhex.com/docs/articles/hard-links.phtml
697 #[allow(dead_code)]
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();
703
704     unsafe {
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 _;
709         let mut i = 0;
710         // FIXME: this conversion is very hacky
711         let v = br"\??\";
712         let v = v.iter().map(|x| *x as u16);
713         for c in v.chain(target.as_os_str().encode_wide()) {
714             *buf.offset(i) = c;
715             i += 1;
716         }
717         *buf.offset(i) = 0;
718         i += 1;
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;
724
725         let mut ret = 0;
726         cvt(c::DeviceIoControl(h as *mut _,
727                                c::FSCTL_SET_REPARSE_POINT,
728                                data.as_ptr() as *mut _,
729                                (*db).ReparseDataLength + 8,
730                                ptr::null_mut(), 0,
731                                &mut ret,
732                                ptr::null_mut())).map(|_| ())
733     }
734 }