This repository has been archived by the owner on Apr 23, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathPath.inc
1498 lines (1268 loc) · 50.1 KB
/
Path.inc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===- llvm/Support/Windows/Path.inc - Windows Path Impl --------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements the Windows specific implementation of the Path API.
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
//=== WARNING: Implementation here must contain only generic Windows code that
//=== is guaranteed to work on *all* Windows variants.
//===----------------------------------------------------------------------===//
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/ConvertUTF.h"
#include "llvm/Support/WindowsError.h"
#include <fcntl.h>
#include <io.h>
#include <sys/stat.h>
#include <sys/types.h>
// These two headers must be included last, and make sure shlobj is required
// after Windows.h to make sure it picks up our definition of _WIN32_WINNT
#include "WindowsSupport.h"
#include <shellapi.h>
#include <shlobj.h>
#undef max
// MinGW doesn't define this.
#ifndef _ERRNO_T_DEFINED
#define _ERRNO_T_DEFINED
typedef int errno_t;
#endif
#ifdef _MSC_VER
# pragma comment(lib, "advapi32.lib") // This provides CryptAcquireContextW.
# pragma comment(lib, "ole32.lib") // This provides CoTaskMemFree
#endif
using namespace llvm;
using llvm::sys::windows::UTF8ToUTF16;
using llvm::sys::windows::CurCPToUTF16;
using llvm::sys::windows::UTF16ToUTF8;
using llvm::sys::path::widenPath;
static bool is_separator(const wchar_t value) {
switch (value) {
case L'\\':
case L'/':
return true;
default:
return false;
}
}
namespace llvm {
namespace sys {
namespace path {
// Convert a UTF-8 path to UTF-16. Also, if the absolute equivalent of the
// path is longer than CreateDirectory can tolerate, make it absolute and
// prefixed by '\\?\'.
std::error_code widenPath(const Twine &Path8,
SmallVectorImpl<wchar_t> &Path16) {
const size_t MaxDirLen = MAX_PATH - 12; // Must leave room for 8.3 filename.
// Several operations would convert Path8 to SmallString; more efficient to
// do it once up front.
SmallString<128> Path8Str;
Path8.toVector(Path8Str);
// If we made this path absolute, how much longer would it get?
size_t CurPathLen;
if (llvm::sys::path::is_absolute(Twine(Path8Str)))
CurPathLen = 0; // No contribution from current_path needed.
else {
CurPathLen = ::GetCurrentDirectoryW(0, NULL);
if (CurPathLen == 0)
return mapWindowsError(::GetLastError());
}
// Would the absolute path be longer than our limit?
if ((Path8Str.size() + CurPathLen) >= MaxDirLen &&
!Path8Str.startswith("\\\\?\\")) {
SmallString<2*MAX_PATH> FullPath("\\\\?\\");
if (CurPathLen) {
SmallString<80> CurPath;
if (std::error_code EC = llvm::sys::fs::current_path(CurPath))
return EC;
FullPath.append(CurPath);
}
// Traverse the requested path, canonicalizing . and .. (because the \\?\
// prefix is documented to treat them as real components). Ignore
// separators, which can be returned from the iterator if the path has a
// drive name. We don't need to call native() on the result since append()
// always attaches preferred_separator.
for (llvm::sys::path::const_iterator I = llvm::sys::path::begin(Path8Str),
E = llvm::sys::path::end(Path8Str);
I != E; ++I) {
if (I->size() == 1 && is_separator((*I)[0]))
continue;
if (I->size() == 1 && *I == ".")
continue;
if (I->size() == 2 && *I == "..")
llvm::sys::path::remove_filename(FullPath);
else
llvm::sys::path::append(FullPath, *I);
}
return UTF8ToUTF16(FullPath, Path16);
}
// Just use the caller's original path.
return UTF8ToUTF16(Path8Str, Path16);
}
} // end namespace path
namespace fs {
const file_t kInvalidFile = INVALID_HANDLE_VALUE;
std::string getMainExecutable(const char *argv0, void *MainExecAddr) {
SmallVector<wchar_t, MAX_PATH> PathName;
DWORD Size = ::GetModuleFileNameW(NULL, PathName.data(), PathName.capacity());
// A zero return value indicates a failure other than insufficient space.
if (Size == 0)
return "";
// Insufficient space is determined by a return value equal to the size of
// the buffer passed in.
if (Size == PathName.capacity())
return "";
// On success, GetModuleFileNameW returns the number of characters written to
// the buffer not including the NULL terminator.
PathName.set_size(Size);
// Convert the result from UTF-16 to UTF-8.
SmallVector<char, MAX_PATH> PathNameUTF8;
if (UTF16ToUTF8(PathName.data(), PathName.size(), PathNameUTF8))
return "";
return std::string(PathNameUTF8.data());
}
UniqueID file_status::getUniqueID() const {
// The file is uniquely identified by the volume serial number along
// with the 64-bit file identifier.
uint64_t FileID = (static_cast<uint64_t>(FileIndexHigh) << 32ULL) |
static_cast<uint64_t>(FileIndexLow);
return UniqueID(VolumeSerialNumber, FileID);
}
ErrorOr<space_info> disk_space(const Twine &Path) {
ULARGE_INTEGER Avail, Total, Free;
if (!::GetDiskFreeSpaceExA(Path.str().c_str(), &Avail, &Total, &Free))
return mapWindowsError(::GetLastError());
space_info SpaceInfo;
SpaceInfo.capacity =
(static_cast<uint64_t>(Total.HighPart) << 32) + Total.LowPart;
SpaceInfo.free = (static_cast<uint64_t>(Free.HighPart) << 32) + Free.LowPart;
SpaceInfo.available =
(static_cast<uint64_t>(Avail.HighPart) << 32) + Avail.LowPart;
return SpaceInfo;
}
TimePoint<> basic_file_status::getLastAccessedTime() const {
FILETIME Time;
Time.dwLowDateTime = LastAccessedTimeLow;
Time.dwHighDateTime = LastAccessedTimeHigh;
return toTimePoint(Time);
}
TimePoint<> basic_file_status::getLastModificationTime() const {
FILETIME Time;
Time.dwLowDateTime = LastWriteTimeLow;
Time.dwHighDateTime = LastWriteTimeHigh;
return toTimePoint(Time);
}
uint32_t file_status::getLinkCount() const {
return NumLinks;
}
std::error_code current_path(SmallVectorImpl<char> &result) {
SmallVector<wchar_t, MAX_PATH> cur_path;
DWORD len = MAX_PATH;
do {
cur_path.reserve(len);
len = ::GetCurrentDirectoryW(cur_path.capacity(), cur_path.data());
// A zero return value indicates a failure other than insufficient space.
if (len == 0)
return mapWindowsError(::GetLastError());
// If there's insufficient space, the len returned is larger than the len
// given.
} while (len > cur_path.capacity());
// On success, GetCurrentDirectoryW returns the number of characters not
// including the null-terminator.
cur_path.set_size(len);
return UTF16ToUTF8(cur_path.begin(), cur_path.size(), result);
}
std::error_code set_current_path(const Twine &path) {
// Convert to utf-16.
SmallVector<wchar_t, 128> wide_path;
if (std::error_code ec = widenPath(path, wide_path))
return ec;
if (!::SetCurrentDirectoryW(wide_path.begin()))
return mapWindowsError(::GetLastError());
return std::error_code();
}
std::error_code create_directory(const Twine &path, bool IgnoreExisting,
perms Perms) {
SmallVector<wchar_t, 128> path_utf16;
if (std::error_code ec = widenPath(path, path_utf16))
return ec;
if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {
DWORD LastError = ::GetLastError();
if (LastError != ERROR_ALREADY_EXISTS || !IgnoreExisting)
return mapWindowsError(LastError);
}
return std::error_code();
}
// We can't use symbolic links for windows.
std::error_code create_link(const Twine &to, const Twine &from) {
// Convert to utf-16.
SmallVector<wchar_t, 128> wide_from;
SmallVector<wchar_t, 128> wide_to;
if (std::error_code ec = widenPath(from, wide_from))
return ec;
if (std::error_code ec = widenPath(to, wide_to))
return ec;
if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
return mapWindowsError(::GetLastError());
return std::error_code();
}
std::error_code create_hard_link(const Twine &to, const Twine &from) {
return create_link(to, from);
}
std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
SmallVector<wchar_t, 128> path_utf16;
if (std::error_code ec = widenPath(path, path_utf16))
return ec;
// We don't know whether this is a file or a directory, and remove() can
// accept both. The usual way to delete a file or directory is to use one of
// the DeleteFile or RemoveDirectory functions, but that requires you to know
// which one it is. We could stat() the file to determine that, but that would
// cost us additional system calls, which can be slow in a directory
// containing a large number of files. So instead we call CreateFile directly.
// The important part is the FILE_FLAG_DELETE_ON_CLOSE flag, which causes the
// file to be deleted once it is closed. We also use the flags
// FILE_FLAG_BACKUP_SEMANTICS (which allows us to open directories), and
// FILE_FLAG_OPEN_REPARSE_POINT (don't follow symlinks).
ScopedFileHandle h(::CreateFileW(
c_str(path_utf16), DELETE,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS |
FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_DELETE_ON_CLOSE,
NULL));
if (!h) {
std::error_code EC = mapWindowsError(::GetLastError());
if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
return EC;
}
return std::error_code();
}
static std::error_code is_local_internal(SmallVectorImpl<wchar_t> &Path,
bool &Result) {
SmallVector<wchar_t, 128> VolumePath;
size_t Len = 128;
while (true) {
VolumePath.resize(Len);
BOOL Success =
::GetVolumePathNameW(Path.data(), VolumePath.data(), VolumePath.size());
if (Success)
break;
DWORD Err = ::GetLastError();
if (Err != ERROR_INSUFFICIENT_BUFFER)
return mapWindowsError(Err);
Len *= 2;
}
// If the output buffer has exactly enough space for the path name, but not
// the null terminator, it will leave the output unterminated. Push a null
// terminator onto the end to ensure that this never happens.
VolumePath.push_back(L'\0');
VolumePath.set_size(wcslen(VolumePath.data()));
const wchar_t *P = VolumePath.data();
UINT Type = ::GetDriveTypeW(P);
switch (Type) {
case DRIVE_FIXED:
Result = true;
return std::error_code();
case DRIVE_REMOTE:
case DRIVE_CDROM:
case DRIVE_RAMDISK:
case DRIVE_REMOVABLE:
Result = false;
return std::error_code();
default:
return make_error_code(errc::no_such_file_or_directory);
}
llvm_unreachable("Unreachable!");
}
std::error_code is_local(const Twine &path, bool &result) {
if (!llvm::sys::fs::exists(path) || !llvm::sys::path::has_root_path(path))
return make_error_code(errc::no_such_file_or_directory);
SmallString<128> Storage;
StringRef P = path.toStringRef(Storage);
// Convert to utf-16.
SmallVector<wchar_t, 128> WidePath;
if (std::error_code ec = widenPath(P, WidePath))
return ec;
return is_local_internal(WidePath, result);
}
static std::error_code realPathFromHandle(HANDLE H,
SmallVectorImpl<wchar_t> &Buffer) {
DWORD CountChars = ::GetFinalPathNameByHandleW(
H, Buffer.begin(), Buffer.capacity() - 1, FILE_NAME_NORMALIZED);
if (CountChars > Buffer.capacity()) {
// The buffer wasn't big enough, try again. In this case the return value
// *does* indicate the size of the null terminator.
Buffer.reserve(CountChars);
CountChars = ::GetFinalPathNameByHandleW(
H, Buffer.data(), Buffer.capacity() - 1, FILE_NAME_NORMALIZED);
}
if (CountChars == 0)
return mapWindowsError(GetLastError());
Buffer.set_size(CountChars);
return std::error_code();
}
static std::error_code realPathFromHandle(HANDLE H,
SmallVectorImpl<char> &RealPath) {
RealPath.clear();
SmallVector<wchar_t, MAX_PATH> Buffer;
if (std::error_code EC = realPathFromHandle(H, Buffer))
return EC;
// Strip the \\?\ prefix. We don't want it ending up in output, and such
// paths don't get canonicalized by file APIs.
wchar_t *Data = Buffer.data();
DWORD CountChars = Buffer.size();
if (CountChars >= 8 && ::memcmp(Data, L"\\\\?\\UNC\\", 16) == 0) {
// Convert \\?\UNC\foo\bar to \\foo\bar
CountChars -= 6;
Data += 6;
Data[0] = '\\';
} else if (CountChars >= 4 && ::memcmp(Data, L"\\\\?\\", 8) == 0) {
// Convert \\?\c:\foo to c:\foo
CountChars -= 4;
Data += 4;
}
// Convert the result from UTF-16 to UTF-8.
return UTF16ToUTF8(Data, CountChars, RealPath);
}
std::error_code is_local(int FD, bool &Result) {
SmallVector<wchar_t, 128> FinalPath;
HANDLE Handle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
if (std::error_code EC = realPathFromHandle(Handle, FinalPath))
return EC;
return is_local_internal(FinalPath, Result);
}
static std::error_code setDeleteDisposition(HANDLE Handle, bool Delete) {
FILE_DISPOSITION_INFO Disposition;
Disposition.DeleteFile = Delete;
if (!SetFileInformationByHandle(Handle, FileDispositionInfo, &Disposition,
sizeof(Disposition)))
return mapWindowsError(::GetLastError());
return std::error_code();
}
static std::error_code rename_internal(HANDLE FromHandle, const Twine &To,
bool ReplaceIfExists) {
SmallVector<wchar_t, 0> ToWide;
if (auto EC = widenPath(To, ToWide))
return EC;
std::vector<char> RenameInfoBuf(sizeof(FILE_RENAME_INFO) - sizeof(wchar_t) +
(ToWide.size() * sizeof(wchar_t)));
FILE_RENAME_INFO &RenameInfo =
*reinterpret_cast<FILE_RENAME_INFO *>(RenameInfoBuf.data());
RenameInfo.ReplaceIfExists = ReplaceIfExists;
RenameInfo.RootDirectory = 0;
RenameInfo.FileNameLength = ToWide.size() * sizeof(wchar_t);
std::copy(ToWide.begin(), ToWide.end(), &RenameInfo.FileName[0]);
SetLastError(ERROR_SUCCESS);
if (!SetFileInformationByHandle(FromHandle, FileRenameInfo, &RenameInfo,
RenameInfoBuf.size())) {
unsigned Error = GetLastError();
if (Error == ERROR_SUCCESS)
Error = ERROR_CALL_NOT_IMPLEMENTED; // Wine doesn't always set error code.
return mapWindowsError(Error);
}
return std::error_code();
}
static std::error_code rename_handle(HANDLE FromHandle, const Twine &To) {
SmallVector<wchar_t, 128> WideTo;
if (std::error_code EC = widenPath(To, WideTo))
return EC;
// We normally expect this loop to succeed after a few iterations. If it
// requires more than 200 tries, it's more likely that the failures are due to
// a true error, so stop trying.
for (unsigned Retry = 0; Retry != 200; ++Retry) {
auto EC = rename_internal(FromHandle, To, true);
if (EC ==
std::error_code(ERROR_CALL_NOT_IMPLEMENTED, std::system_category())) {
// Wine doesn't support SetFileInformationByHandle in rename_internal.
// Fall back to MoveFileEx.
SmallVector<wchar_t, MAX_PATH> WideFrom;
if (std::error_code EC2 = realPathFromHandle(FromHandle, WideFrom))
return EC2;
if (::MoveFileExW(WideFrom.begin(), WideTo.begin(),
MOVEFILE_REPLACE_EXISTING))
return std::error_code();
return mapWindowsError(GetLastError());
}
if (!EC || EC != errc::permission_denied)
return EC;
// The destination file probably exists and is currently open in another
// process, either because the file was opened without FILE_SHARE_DELETE or
// it is mapped into memory (e.g. using MemoryBuffer). Rename it in order to
// move it out of the way of the source file. Use FILE_FLAG_DELETE_ON_CLOSE
// to arrange for the destination file to be deleted when the other process
// closes it.
ScopedFileHandle ToHandle(
::CreateFileW(WideTo.begin(), GENERIC_READ | DELETE,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, NULL));
if (!ToHandle) {
auto EC = mapWindowsError(GetLastError());
// Another process might have raced with us and moved the existing file
// out of the way before we had a chance to open it. If that happens, try
// to rename the source file again.
if (EC == errc::no_such_file_or_directory)
continue;
return EC;
}
BY_HANDLE_FILE_INFORMATION FI;
if (!GetFileInformationByHandle(ToHandle, &FI))
return mapWindowsError(GetLastError());
// Try to find a unique new name for the destination file.
for (unsigned UniqueId = 0; UniqueId != 200; ++UniqueId) {
std::string TmpFilename = (To + ".tmp" + utostr(UniqueId)).str();
if (auto EC = rename_internal(ToHandle, TmpFilename, false)) {
if (EC == errc::file_exists || EC == errc::permission_denied) {
// Again, another process might have raced with us and moved the file
// before we could move it. Check whether this is the case, as it
// might have caused the permission denied error. If that was the
// case, we don't need to move it ourselves.
ScopedFileHandle ToHandle2(::CreateFileW(
WideTo.begin(), 0,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL));
if (!ToHandle2) {
auto EC = mapWindowsError(GetLastError());
if (EC == errc::no_such_file_or_directory)
break;
return EC;
}
BY_HANDLE_FILE_INFORMATION FI2;
if (!GetFileInformationByHandle(ToHandle2, &FI2))
return mapWindowsError(GetLastError());
if (FI.nFileIndexHigh != FI2.nFileIndexHigh ||
FI.nFileIndexLow != FI2.nFileIndexLow ||
FI.dwVolumeSerialNumber != FI2.dwVolumeSerialNumber)
break;
continue;
}
return EC;
}
break;
}
// Okay, the old destination file has probably been moved out of the way at
// this point, so try to rename the source file again. Still, another
// process might have raced with us to create and open the destination
// file, so we need to keep doing this until we succeed.
}
// The most likely root cause.
return errc::permission_denied;
}
static std::error_code rename_fd(int FromFD, const Twine &To) {
HANDLE FromHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FromFD));
return rename_handle(FromHandle, To);
}
std::error_code rename(const Twine &From, const Twine &To) {
// Convert to utf-16.
SmallVector<wchar_t, 128> WideFrom;
if (std::error_code EC = widenPath(From, WideFrom))
return EC;
ScopedFileHandle FromHandle;
// Retry this a few times to defeat badly behaved file system scanners.
for (unsigned Retry = 0; Retry != 200; ++Retry) {
if (Retry != 0)
::Sleep(10);
FromHandle =
::CreateFileW(WideFrom.begin(), GENERIC_READ | DELETE,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (FromHandle)
break;
}
if (!FromHandle)
return mapWindowsError(GetLastError());
return rename_handle(FromHandle, To);
}
std::error_code resize_file(int FD, uint64_t Size) {
#ifdef HAVE__CHSIZE_S
errno_t error = ::_chsize_s(FD, Size);
#else
errno_t error = ::_chsize(FD, Size);
#endif
return std::error_code(error, std::generic_category());
}
std::error_code access(const Twine &Path, AccessMode Mode) {
SmallVector<wchar_t, 128> PathUtf16;
if (std::error_code EC = widenPath(Path, PathUtf16))
return EC;
DWORD Attributes = ::GetFileAttributesW(PathUtf16.begin());
if (Attributes == INVALID_FILE_ATTRIBUTES) {
// See if the file didn't actually exist.
DWORD LastError = ::GetLastError();
if (LastError != ERROR_FILE_NOT_FOUND &&
LastError != ERROR_PATH_NOT_FOUND)
return mapWindowsError(LastError);
return errc::no_such_file_or_directory;
}
if (Mode == AccessMode::Write && (Attributes & FILE_ATTRIBUTE_READONLY))
return errc::permission_denied;
return std::error_code();
}
bool can_execute(const Twine &Path) {
return !access(Path, AccessMode::Execute) ||
!access(Path + ".exe", AccessMode::Execute);
}
bool equivalent(file_status A, file_status B) {
assert(status_known(A) && status_known(B));
return A.FileIndexHigh == B.FileIndexHigh &&
A.FileIndexLow == B.FileIndexLow &&
A.FileSizeHigh == B.FileSizeHigh &&
A.FileSizeLow == B.FileSizeLow &&
A.LastAccessedTimeHigh == B.LastAccessedTimeHigh &&
A.LastAccessedTimeLow == B.LastAccessedTimeLow &&
A.LastWriteTimeHigh == B.LastWriteTimeHigh &&
A.LastWriteTimeLow == B.LastWriteTimeLow &&
A.VolumeSerialNumber == B.VolumeSerialNumber;
}
std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
file_status fsA, fsB;
if (std::error_code ec = status(A, fsA))
return ec;
if (std::error_code ec = status(B, fsB))
return ec;
result = equivalent(fsA, fsB);
return std::error_code();
}
static bool isReservedName(StringRef path) {
// This list of reserved names comes from MSDN, at:
// http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
static const char *const sReservedNames[] = { "nul", "con", "prn", "aux",
"com1", "com2", "com3", "com4",
"com5", "com6", "com7", "com8",
"com9", "lpt1", "lpt2", "lpt3",
"lpt4", "lpt5", "lpt6", "lpt7",
"lpt8", "lpt9" };
// First, check to see if this is a device namespace, which always
// starts with \\.\, since device namespaces are not legal file paths.
if (path.startswith("\\\\.\\"))
return true;
// Then compare against the list of ancient reserved names.
for (size_t i = 0; i < array_lengthof(sReservedNames); ++i) {
if (path.equals_lower(sReservedNames[i]))
return true;
}
// The path isn't what we consider reserved.
return false;
}
static file_type file_type_from_attrs(DWORD Attrs) {
return (Attrs & FILE_ATTRIBUTE_DIRECTORY) ? file_type::directory_file
: file_type::regular_file;
}
static perms perms_from_attrs(DWORD Attrs) {
return (Attrs & FILE_ATTRIBUTE_READONLY) ? (all_read | all_exe) : all_all;
}
static std::error_code getStatus(HANDLE FileHandle, file_status &Result) {
if (FileHandle == INVALID_HANDLE_VALUE)
goto handle_status_error;
switch (::GetFileType(FileHandle)) {
default:
llvm_unreachable("Don't know anything about this file type");
case FILE_TYPE_UNKNOWN: {
DWORD Err = ::GetLastError();
if (Err != NO_ERROR)
return mapWindowsError(Err);
Result = file_status(file_type::type_unknown);
return std::error_code();
}
case FILE_TYPE_DISK:
break;
case FILE_TYPE_CHAR:
Result = file_status(file_type::character_file);
return std::error_code();
case FILE_TYPE_PIPE:
Result = file_status(file_type::fifo_file);
return std::error_code();
}
BY_HANDLE_FILE_INFORMATION Info;
if (!::GetFileInformationByHandle(FileHandle, &Info))
goto handle_status_error;
Result = file_status(
file_type_from_attrs(Info.dwFileAttributes),
perms_from_attrs(Info.dwFileAttributes), Info.nNumberOfLinks,
Info.ftLastAccessTime.dwHighDateTime, Info.ftLastAccessTime.dwLowDateTime,
Info.ftLastWriteTime.dwHighDateTime, Info.ftLastWriteTime.dwLowDateTime,
Info.dwVolumeSerialNumber, Info.nFileSizeHigh, Info.nFileSizeLow,
Info.nFileIndexHigh, Info.nFileIndexLow);
return std::error_code();
handle_status_error:
DWORD LastError = ::GetLastError();
if (LastError == ERROR_FILE_NOT_FOUND ||
LastError == ERROR_PATH_NOT_FOUND)
Result = file_status(file_type::file_not_found);
else if (LastError == ERROR_SHARING_VIOLATION)
Result = file_status(file_type::type_unknown);
else
Result = file_status(file_type::status_error);
return mapWindowsError(LastError);
}
std::error_code status(const Twine &path, file_status &result, bool Follow) {
SmallString<128> path_storage;
SmallVector<wchar_t, 128> path_utf16;
StringRef path8 = path.toStringRef(path_storage);
if (isReservedName(path8)) {
result = file_status(file_type::character_file);
return std::error_code();
}
if (std::error_code ec = widenPath(path8, path_utf16))
return ec;
DWORD attr = ::GetFileAttributesW(path_utf16.begin());
if (attr == INVALID_FILE_ATTRIBUTES)
return getStatus(INVALID_HANDLE_VALUE, result);
DWORD Flags = FILE_FLAG_BACKUP_SEMANTICS;
// Handle reparse points.
if (!Follow && (attr & FILE_ATTRIBUTE_REPARSE_POINT))
Flags |= FILE_FLAG_OPEN_REPARSE_POINT;
ScopedFileHandle h(
::CreateFileW(path_utf16.begin(), 0, // Attributes only.
FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, Flags, 0));
if (!h)
return getStatus(INVALID_HANDLE_VALUE, result);
return getStatus(h, result);
}
std::error_code status(int FD, file_status &Result) {
HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
return getStatus(FileHandle, Result);
}
std::error_code status(file_t FileHandle, file_status &Result) {
return getStatus(FileHandle, Result);
}
unsigned getUmask() {
return 0;
}
std::error_code setPermissions(const Twine &Path, perms Permissions) {
SmallVector<wchar_t, 128> PathUTF16;
if (std::error_code EC = widenPath(Path, PathUTF16))
return EC;
DWORD Attributes = ::GetFileAttributesW(PathUTF16.begin());
if (Attributes == INVALID_FILE_ATTRIBUTES)
return mapWindowsError(GetLastError());
// There are many Windows file attributes that are not to do with the file
// permissions (e.g. FILE_ATTRIBUTE_HIDDEN). We need to be careful to preserve
// them.
if (Permissions & all_write) {
Attributes &= ~FILE_ATTRIBUTE_READONLY;
if (Attributes == 0)
// FILE_ATTRIBUTE_NORMAL indicates no other attributes are set.
Attributes |= FILE_ATTRIBUTE_NORMAL;
}
else {
Attributes |= FILE_ATTRIBUTE_READONLY;
// FILE_ATTRIBUTE_NORMAL is not compatible with any other attributes, so
// remove it, if it is present.
Attributes &= ~FILE_ATTRIBUTE_NORMAL;
}
if (!::SetFileAttributesW(PathUTF16.begin(), Attributes))
return mapWindowsError(GetLastError());
return std::error_code();
}
std::error_code setPermissions(int FD, perms Permissions) {
// FIXME Not implemented.
return std::make_error_code(std::errc::not_supported);
}
std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime,
TimePoint<> ModificationTime) {
FILETIME AccessFT = toFILETIME(AccessTime);
FILETIME ModifyFT = toFILETIME(ModificationTime);
HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
if (!SetFileTime(FileHandle, NULL, &AccessFT, &ModifyFT))
return mapWindowsError(::GetLastError());
return std::error_code();
}
std::error_code mapped_file_region::init(sys::fs::file_t OrigFileHandle,
uint64_t Offset, mapmode Mode) {
this->Mode = Mode;
if (OrigFileHandle == INVALID_HANDLE_VALUE)
return make_error_code(errc::bad_file_descriptor);
DWORD flprotect;
switch (Mode) {
case readonly: flprotect = PAGE_READONLY; break;
case readwrite: flprotect = PAGE_READWRITE; break;
case priv: flprotect = PAGE_WRITECOPY; break;
}
HANDLE FileMappingHandle =
::CreateFileMappingW(OrigFileHandle, 0, flprotect,
Hi_32(Size),
Lo_32(Size),
0);
if (FileMappingHandle == NULL) {
std::error_code ec = mapWindowsError(GetLastError());
return ec;
}
DWORD dwDesiredAccess;
switch (Mode) {
case readonly: dwDesiredAccess = FILE_MAP_READ; break;
case readwrite: dwDesiredAccess = FILE_MAP_WRITE; break;
case priv: dwDesiredAccess = FILE_MAP_COPY; break;
}
Mapping = ::MapViewOfFile(FileMappingHandle,
dwDesiredAccess,
Offset >> 32,
Offset & 0xffffffff,
Size);
if (Mapping == NULL) {
std::error_code ec = mapWindowsError(GetLastError());
::CloseHandle(FileMappingHandle);
return ec;
}
if (Size == 0) {
MEMORY_BASIC_INFORMATION mbi;
SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));
if (Result == 0) {
std::error_code ec = mapWindowsError(GetLastError());
::UnmapViewOfFile(Mapping);
::CloseHandle(FileMappingHandle);
return ec;
}
Size = mbi.RegionSize;
}
// Close the file mapping handle, as it's kept alive by the file mapping. But
// neither the file mapping nor the file mapping handle keep the file handle
// alive, so we need to keep a reference to the file in case all other handles
// are closed and the file is deleted, which may cause invalid data to be read
// from the file.
::CloseHandle(FileMappingHandle);
if (!::DuplicateHandle(::GetCurrentProcess(), OrigFileHandle,
::GetCurrentProcess(), &FileHandle, 0, 0,
DUPLICATE_SAME_ACCESS)) {
std::error_code ec = mapWindowsError(GetLastError());
::UnmapViewOfFile(Mapping);
return ec;
}
return std::error_code();
}
mapped_file_region::mapped_file_region(sys::fs::file_t fd, mapmode mode,
size_t length, uint64_t offset,
std::error_code &ec)
: Size(length), Mapping() {
ec = init(fd, offset, mode);
if (ec)
Mapping = 0;
}
static bool hasFlushBufferKernelBug() {
static bool Ret{GetWindowsOSVersion() < llvm::VersionTuple(10, 0, 0, 17763)};
return Ret;
}
static bool isEXE(StringRef Magic) {
static const char PEMagic[] = {'P', 'E', '\0', '\0'};
if (Magic.startswith(StringRef("MZ")) && Magic.size() >= 0x3c + 4) {
uint32_t off = read32le(Magic.data() + 0x3c);
// PE/COFF file, either EXE or DLL.
if (Magic.substr(off).startswith(StringRef(PEMagic, sizeof(PEMagic))))
return true;
}
return false;
}
mapped_file_region::~mapped_file_region() {
if (Mapping) {
bool Exe = isEXE(StringRef((char *)Mapping, Size));
::UnmapViewOfFile(Mapping);
if (Mode == mapmode::readwrite && Exe && hasFlushBufferKernelBug()) {
// There is a Windows kernel bug, the exact trigger conditions of which
// are not well understood. When triggered, dirty pages are not properly
// flushed and subsequent process's attempts to read a file can return
// invalid data. Calling FlushFileBuffers on the write handle is
// sufficient to ensure that this bug is not triggered.
// The bug only occurs when writing an executable and executing it right
// after, under high I/O pressure.
::FlushFileBuffers(FileHandle);
}
::CloseHandle(FileHandle);
}
}
size_t mapped_file_region::size() const {
assert(Mapping && "Mapping failed but used anyway!");
return Size;
}
char *mapped_file_region::data() const {
assert(Mapping && "Mapping failed but used anyway!");
return reinterpret_cast<char*>(Mapping);
}
const char *mapped_file_region::const_data() const {
assert(Mapping && "Mapping failed but used anyway!");
return reinterpret_cast<const char*>(Mapping);
}
int mapped_file_region::alignment() {
SYSTEM_INFO SysInfo;
::GetSystemInfo(&SysInfo);
return SysInfo.dwAllocationGranularity;
}
static basic_file_status status_from_find_data(WIN32_FIND_DATAW *FindData) {
return basic_file_status(file_type_from_attrs(FindData->dwFileAttributes),
perms_from_attrs(FindData->dwFileAttributes),
FindData->ftLastAccessTime.dwHighDateTime,
FindData->ftLastAccessTime.dwLowDateTime,
FindData->ftLastWriteTime.dwHighDateTime,
FindData->ftLastWriteTime.dwLowDateTime,
FindData->nFileSizeHigh, FindData->nFileSizeLow);
}
std::error_code detail::directory_iterator_construct(detail::DirIterState &IT,
StringRef Path,
bool FollowSymlinks) {
SmallVector<wchar_t, 128> PathUTF16;
if (std::error_code EC = widenPath(Path, PathUTF16))
return EC;
// Convert path to the format that Windows is happy with.
if (PathUTF16.size() > 0 &&
!is_separator(PathUTF16[Path.size() - 1]) &&
PathUTF16[Path.size() - 1] != L':') {
PathUTF16.push_back(L'\\');
PathUTF16.push_back(L'*');
} else {
PathUTF16.push_back(L'*');
}
// Get the first directory entry.
WIN32_FIND_DATAW FirstFind;
ScopedFindHandle FindHandle(::FindFirstFileExW(
c_str(PathUTF16), FindExInfoBasic, &FirstFind, FindExSearchNameMatch,
NULL, FIND_FIRST_EX_LARGE_FETCH));
if (!FindHandle)
return mapWindowsError(::GetLastError());
size_t FilenameLen = ::wcslen(FirstFind.cFileName);
while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
(FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
FirstFind.cFileName[1] == L'.'))
if (!::FindNextFileW(FindHandle, &FirstFind)) {
DWORD LastError = ::GetLastError();
// Check for end.
if (LastError == ERROR_NO_MORE_FILES)
return detail::directory_iterator_destruct(IT);
return mapWindowsError(LastError);
} else
FilenameLen = ::wcslen(FirstFind.cFileName);
// Construct the current directory entry.
SmallString<128> DirectoryEntryNameUTF8;
if (std::error_code EC =
UTF16ToUTF8(FirstFind.cFileName, ::wcslen(FirstFind.cFileName),
DirectoryEntryNameUTF8))
return EC;
IT.IterationHandle = intptr_t(FindHandle.take());
SmallString<128> DirectoryEntryPath(Path);
path::append(DirectoryEntryPath, DirectoryEntryNameUTF8);
IT.CurrentEntry =
directory_entry(DirectoryEntryPath, FollowSymlinks,
file_type_from_attrs(FirstFind.dwFileAttributes),
status_from_find_data(&FirstFind));
return std::error_code();
}