LLVM 23.0.0git
Path.inc
Go to the documentation of this file.
1//===- llvm/Support/Windows/Path.inc - Windows Path Impl --------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Windows specific implementation of the Path API.
10//
11//===----------------------------------------------------------------------===//
12
13//===----------------------------------------------------------------------===//
14//=== WARNING: Implementation here must contain only generic Windows code that
15//=== is guaranteed to work on *all* Windows variants.
16//===----------------------------------------------------------------------===//
17
18#include "llvm/ADT/STLExtras.h"
22#include <fcntl.h>
23#include <sys/stat.h>
24#include <sys/types.h>
25
26// These two headers must be included last, and make sure shlobj is required
27// after Windows.h to make sure it picks up our definition of _WIN32_WINNT
29#include <shellapi.h>
30#include <shlobj.h>
31#include <winioctl.h>
32
33#undef max
34
35// MinGW doesn't define this.
36#ifndef _ERRNO_T_DEFINED
37#define _ERRNO_T_DEFINED
38typedef int errno_t;
39#endif
40
41#ifdef _MSC_VER
42#pragma comment(lib, "advapi32.lib") // This provides CryptAcquireContextW.
43#pragma comment(lib, "ole32.lib") // This provides CoTaskMemFree
44#endif
45
46using namespace llvm;
47
48using llvm::sys::windows::CurCPToUTF16;
49using llvm::sys::windows::UTF16ToUTF8;
50using llvm::sys::windows::UTF8ToUTF16;
52
53static bool is_separator(const wchar_t value) {
54 switch (value) {
55 case L'\\':
56 case L'/':
57 return true;
58 default:
59 return false;
60 }
61}
62
63// Long path path prefix constants (UTF-8).
64static constexpr llvm::StringLiteral LongPathPrefix8 = R"(\\?\)";
65static constexpr llvm::StringLiteral LongPathUNCPrefix8 = R"(\\?\UNC\)";
66
67// Long path prefix constants (UTF-16).
68static constexpr wchar_t LongPathPrefix16[] = LR"(\\?\)";
69static constexpr wchar_t LongPathUNCPrefix16[] = LR"(\\?\UNC\)";
70
71static constexpr DWORD LongPathPrefix16Len =
72 static_cast<DWORD>(std::size(LongPathPrefix16) - 1);
73static constexpr DWORD LongPathUNCPrefix16Len =
74 static_cast<DWORD>(std::size(LongPathUNCPrefix16) - 1);
75
76static void stripLongPathPrefix(wchar_t *&Data, DWORD &CountChars) {
77 if (CountChars >= LongPathUNCPrefix16Len &&
78 ::wmemcmp(Data, LongPathUNCPrefix16, LongPathUNCPrefix16Len) == 0) {
79 // Convert \\?\UNC\foo\bar to \\foo\bar
80 CountChars -= 6;
81 Data += 6;
82 Data[0] = L'\\';
83 } else if (CountChars >= LongPathPrefix16Len &&
84 ::wmemcmp(Data, LongPathPrefix16, LongPathPrefix16Len) == 0) {
85 // Convert \\?\C:\foo to C:\foo
86 CountChars -= 4;
87 Data += 4;
88 }
89}
90
91namespace llvm {
92namespace sys {
93namespace windows {
94
95// Convert a UTF-8 path to UTF-16. Also, if the absolute equivalent of the path
96// is longer than the limit that the Win32 Unicode File API can tolerate, make
97// it an absolute normalized path prefixed by '\\?\'.
98std::error_code widenPath(const Twine &Path8, SmallVectorImpl<wchar_t> &Path16,
99 size_t MaxPathLen) {
100 assert(MaxPathLen <= MAX_PATH);
101
102 // Several operations would convert Path8 to SmallString; more efficient to do
103 // it once up front.
104 SmallString<MAX_PATH> Path8Str;
105 Path8.toVector(Path8Str);
106
107 // If the path is a long path, mangled into forward slashes, normalize
108 // back to backslashes here.
109 if (Path8Str.starts_with("//?/"))
111
112 if (std::error_code EC = UTF8ToUTF16(Path8Str, Path16))
113 return EC;
114
115 const bool IsAbsolute = llvm::sys::path::is_absolute(Path8);
116 size_t CurPathLen;
117 if (IsAbsolute)
118 CurPathLen = 0; // No contribution from current_path needed.
119 else {
120 CurPathLen = ::GetCurrentDirectoryW(
121 0, NULL); // Returns the size including the null terminator.
122 if (CurPathLen == 0)
123 return mapWindowsError(::GetLastError());
124 }
125
126 if ((Path16.size() + CurPathLen) < MaxPathLen ||
127 Path8Str.starts_with(LongPathPrefix8))
128 return std::error_code();
129
130 if (!IsAbsolute) {
131 if (std::error_code EC = llvm::sys::fs::make_absolute(Path8Str))
132 return EC;
133 }
134
135 // Remove '.' and '..' because long paths treat these as real path components.
136 // Explicitly use the backslash form here, as we're prepending the \\?\
137 // prefix.
140
141 const StringRef RootName = llvm::sys::path::root_name(Path8Str);
142 assert(!RootName.empty() &&
143 "Root name cannot be empty for an absolute path!");
144
145 SmallString<2 * MAX_PATH> FullPath;
146 if (RootName[1] != ':') { // Check if UNC.
147 FullPath.append(LongPathUNCPrefix8);
148 FullPath.append(Path8Str.begin() + 2, Path8Str.end());
149 } else {
150 FullPath.append(LongPathPrefix8);
151 FullPath.append(Path8Str);
152 }
153
154 return UTF8ToUTF16(FullPath, Path16);
155}
156
157std::error_code makeLongFormPath(const Twine &Path8,
158 llvm::SmallVectorImpl<char> &Result8) {
159 SmallString<128> PathStorage;
160 StringRef PathStr = Path8.toStringRef(PathStorage);
161 bool HadPrefix = PathStr.starts_with(LongPathPrefix8);
162
164 if (std::error_code EC = widenPath(PathStr, Path16))
165 return EC;
166
167 // Start with a buffer equal to input.
169 DWORD Len = static_cast<DWORD>(Path16.size());
170
171 // Loop instead of a double call to be defensive against TOCTOU races.
172 do {
173 Long16.resize_for_overwrite(Len);
174
175 Len = ::GetLongPathNameW(Path16.data(), Long16.data(), Len);
176
177 // A zero return value indicates a failure other than insufficient space.
178 if (Len == 0)
179 return mapWindowsError(::GetLastError());
180
181 // If there's insufficient space, the return value is the required size in
182 // characters *including* the null terminator, and therefore greater than
183 // the buffer size we provided. Equality would imply success with no room
184 // for the terminator and should not occur for this API.
185 assert(Len != Long16.size());
186 } while (Len > Long16.size());
187
188 // On success, GetLongPathNameW returns the number of characters not
189 // including the null-terminator.
190 Long16.truncate(Len);
191
192 // Strip \\?\ or \\?\UNC\ long length prefix if it wasn't part of the
193 // original path.
194 wchar_t *Data = Long16.data();
195 if (!HadPrefix)
196 stripLongPathPrefix(Data, Len);
197
198 return sys::windows::UTF16ToUTF8(Data, Len, Result8);
199}
200
201} // end namespace windows
202
203namespace fs {
204
205const file_t kInvalidFile = INVALID_HANDLE_VALUE;
206
207std::string getMainExecutable(const char *argv0, void *MainExecAddr) {
208 auto BypassSandbox = sandbox::scopedDisable();
209
211 PathName.resize_for_overwrite(PathName.capacity());
212 DWORD Size = ::GetModuleFileNameW(NULL, PathName.data(), PathName.size());
213
214 // A zero return value indicates a failure other than insufficient space.
215 if (Size == 0)
216 return "";
217
218 // Insufficient space is determined by a return value equal to the size of
219 // the buffer passed in.
220 if (Size == PathName.capacity())
221 return "";
222
223 // On success, GetModuleFileNameW returns the number of characters written to
224 // the buffer not including the NULL terminator.
225 PathName.truncate(Size);
226
227 // Convert the result from UTF-16 to UTF-8.
228 SmallVector<char, MAX_PATH> PathNameUTF8;
229 if (UTF16ToUTF8(PathName.data(), PathName.size(), PathNameUTF8))
230 return "";
231
233
234 SmallString<256> RealPath;
235 sys::fs::real_path(PathNameUTF8, RealPath);
236 if (RealPath.size())
237 return std::string(RealPath);
238 return std::string(PathNameUTF8.data());
239}
240
242 return UniqueID(VolumeSerialNumber, PathHash);
243}
244
245ErrorOr<space_info> disk_space(const Twine &Path) {
246 ULARGE_INTEGER Avail, Total, Free;
248
249 if (std::error_code EC = widenPath(Path, PathUTF16))
250 return EC;
251
252 if (!::GetDiskFreeSpaceExW(PathUTF16.data(), &Avail, &Total, &Free))
253 return mapWindowsError(::GetLastError());
254
255 space_info SpaceInfo;
256 SpaceInfo.capacity = Total.QuadPart;
257 SpaceInfo.free = Free.QuadPart;
258 SpaceInfo.available = Avail.QuadPart;
259
260 return SpaceInfo;
261}
262
264 FILETIME Time;
265 Time.dwLowDateTime = LastAccessedTimeLow;
266 Time.dwHighDateTime = LastAccessedTimeHigh;
267 return toTimePoint(Time);
268}
269
271 FILETIME Time;
272 Time.dwLowDateTime = LastWriteTimeLow;
273 Time.dwHighDateTime = LastWriteTimeHigh;
274 return toTimePoint(Time);
275}
276
277uint32_t file_status::getLinkCount() const { return NumLinks; }
278
279std::error_code current_path(SmallVectorImpl<char> &result) {
281
283 DWORD len = MAX_PATH;
284
285 do {
286 cur_path.resize_for_overwrite(len);
287 len = ::GetCurrentDirectoryW(cur_path.size(), cur_path.data());
288
289 // A zero return value indicates a failure other than insufficient space.
290 if (len == 0)
291 return mapWindowsError(::GetLastError());
292
293 // If there's insufficient space, the len returned is larger than the len
294 // given.
295 } while (len > cur_path.size());
296
297 // On success, GetCurrentDirectoryW returns the number of characters not
298 // including the null-terminator.
299 cur_path.truncate(len);
300
301 if (std::error_code EC =
302 UTF16ToUTF8(cur_path.begin(), cur_path.size(), result))
303 return EC;
304
306 return std::error_code();
307}
308
309std::error_code set_current_path(const Twine &path) {
311
312 // Convert to utf-16.
314 if (std::error_code ec = widenPath(path, wide_path))
315 return ec;
316
317 if (!::SetCurrentDirectoryW(wide_path.begin()))
318 return mapWindowsError(::GetLastError());
319
320 return std::error_code();
321}
322
323std::error_code create_directory(const Twine &path, bool IgnoreExisting,
324 perms Perms) {
325 SmallVector<wchar_t, 128> path_utf16;
326
327 // CreateDirectoryW has a lower maximum path length as it must leave room for
328 // an 8.3 filename.
329 if (std::error_code ec = widenPath(path, path_utf16, MAX_PATH - 12))
330 return ec;
331
332 if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {
333 DWORD LastError = ::GetLastError();
334 if (LastError != ERROR_ALREADY_EXISTS || !IgnoreExisting)
335 return mapWindowsError(LastError);
336 }
337
338 return std::error_code();
339}
340
341// We can't use symbolic links for windows.
342std::error_code create_link(const Twine &to, const Twine &from) {
343 // Convert to utf-16.
346 if (std::error_code ec = widenPath(from, wide_from))
347 return ec;
348 if (std::error_code ec = widenPath(to, wide_to))
349 return ec;
350
351 if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
352 return mapWindowsError(::GetLastError());
353
354 return std::error_code();
355}
356
357std::error_code create_hard_link(const Twine &to, const Twine &from) {
358 return create_link(to, from);
359}
360
361std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
362 SmallVector<wchar_t, 128> path_utf16;
363
364 if (std::error_code ec = widenPath(path, path_utf16))
365 return ec;
366
367 // We don't know whether this is a file or a directory, and remove() can
368 // accept both. The usual way to delete a file or directory is to use one of
369 // the DeleteFile or RemoveDirectory functions, but that requires you to know
370 // which one it is. We could stat() the file to determine that, but that would
371 // cost us additional system calls, which can be slow in a directory
372 // containing a large number of files. So instead we call CreateFile directly.
373 // The important part is the FILE_FLAG_DELETE_ON_CLOSE flag, which causes the
374 // file to be deleted once it is closed. We also use the flags
375 // FILE_FLAG_BACKUP_SEMANTICS (which allows us to open directories), and
376 // FILE_FLAG_OPEN_REPARSE_POINT (don't follow symlinks).
377 ScopedFileHandle h(::CreateFileW(
378 c_str(path_utf16), DELETE,
379 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
380 OPEN_EXISTING,
381 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS |
382 FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_DELETE_ON_CLOSE,
383 NULL));
384 if (!h) {
385 std::error_code EC = mapWindowsError(::GetLastError());
386 if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
387 return EC;
388 }
389
390 return std::error_code();
391}
392
393static std::error_code is_local_internal(SmallVectorImpl<wchar_t> &Path,
394 bool &Result) {
395 SmallVector<wchar_t, 128> VolumePath;
396 size_t Len = 128;
397 while (true) {
398 VolumePath.resize(Len);
399 BOOL Success =
400 ::GetVolumePathNameW(Path.data(), VolumePath.data(), VolumePath.size());
401
402 if (Success)
403 break;
404
405 DWORD Err = ::GetLastError();
406 if (Err != ERROR_INSUFFICIENT_BUFFER)
407 return mapWindowsError(Err);
408
409 Len *= 2;
410 }
411 // If the output buffer has exactly enough space for the path name, but not
412 // the null terminator, it will leave the output unterminated. Push a null
413 // terminator onto the end to ensure that this never happens.
414 VolumePath.push_back(L'\0');
415 VolumePath.truncate(wcslen(VolumePath.data()));
416 const wchar_t *P = VolumePath.data();
417
418 UINT Type = ::GetDriveTypeW(P);
419 switch (Type) {
420 case DRIVE_FIXED:
421 Result = true;
422 return std::error_code();
423 case DRIVE_REMOTE:
424 case DRIVE_CDROM:
425 case DRIVE_RAMDISK:
426 case DRIVE_REMOVABLE:
427 Result = false;
428 return std::error_code();
429 default:
431 }
432 llvm_unreachable("Unreachable!");
433}
434
435std::error_code is_local(const Twine &path, bool &result) {
437
440
441 SmallString<128> Storage;
442 StringRef P = path.toStringRef(Storage);
443
444 // Convert to utf-16.
446 if (std::error_code ec = widenPath(P, WidePath))
447 return ec;
448 return is_local_internal(WidePath, result);
449}
450
451static std::error_code realPathFromHandle(HANDLE H,
452 SmallVectorImpl<wchar_t> &Buffer,
453 DWORD flags = VOLUME_NAME_DOS) {
454 Buffer.resize_for_overwrite(Buffer.capacity());
455 DWORD CountChars = ::GetFinalPathNameByHandleW(
456 H, Buffer.begin(), Buffer.capacity(), FILE_NAME_NORMALIZED | flags);
457 if (CountChars && CountChars >= Buffer.capacity()) {
458 // The buffer wasn't big enough, try again. In this case the return value
459 // *does* indicate the size of the null terminator.
460 Buffer.resize_for_overwrite(CountChars);
461 CountChars = ::GetFinalPathNameByHandleW(H, Buffer.begin(), Buffer.size(),
462 FILE_NAME_NORMALIZED | flags);
463 }
464 Buffer.truncate(CountChars);
465 if (CountChars == 0)
466 return mapWindowsError(GetLastError());
467 return std::error_code();
468}
469
470static std::error_code realPathFromHandle(HANDLE H,
471 SmallVectorImpl<char> &RealPath) {
472 RealPath.clear();
474 if (std::error_code EC = realPathFromHandle(H, Buffer))
475 return EC;
476
477 // Strip the \\?\ prefix. We don't want it ending up in output, and such
478 // paths don't get canonicalized by file APIs.
479 wchar_t *Data = Buffer.data();
480 DWORD CountChars = Buffer.size();
481 stripLongPathPrefix(Data, CountChars);
482
483 // Convert the result from UTF-16 to UTF-8.
484 if (std::error_code EC = UTF16ToUTF8(Data, CountChars, RealPath))
485 return EC;
486
488 return std::error_code();
489}
490
491std::error_code is_local(int FD, bool &Result) {
493
495 HANDLE Handle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
496
497 if (std::error_code EC = realPathFromHandle(Handle, FinalPath))
498 return EC;
499
500 return is_local_internal(FinalPath, Result);
501}
502
503static std::error_code setDeleteDisposition(HANDLE Handle, bool Delete) {
504 // Clear the FILE_DISPOSITION_INFO flag first, before checking if it's a
505 // network file. On Windows 7 the function realPathFromHandle() below fails
506 // if the FILE_DISPOSITION_INFO flag was already set to 'DeleteFile = true' by
507 // a prior call.
508 FILE_DISPOSITION_INFO Disposition;
509 Disposition.DeleteFile = false;
510 if (!SetFileInformationByHandle(Handle, FileDispositionInfo, &Disposition,
511 sizeof(Disposition)))
512 return mapWindowsError(::GetLastError());
513 if (!Delete)
514 return std::error_code();
515
516 // Check if the file is on a network (non-local) drive. If so, don't
517 // continue when DeleteFile is true, since it prevents opening the file for
518 // writes.
520 if (std::error_code EC = realPathFromHandle(Handle, FinalPath))
521 return EC;
522
523 bool IsLocal;
524 if (std::error_code EC = is_local_internal(FinalPath, IsLocal))
525 return EC;
526
527 if (!IsLocal)
528 return errc::not_supported;
529
530 // The file is on a local drive, we can safely set FILE_DISPOSITION_INFO's
531 // flag.
532 Disposition.DeleteFile = true;
533 if (!SetFileInformationByHandle(Handle, FileDispositionInfo, &Disposition,
534 sizeof(Disposition)))
535 return mapWindowsError(::GetLastError());
536 return std::error_code();
537}
538
539static std::error_code rename_internal(HANDLE FromHandle, const Twine &To,
540 bool ReplaceIfExists) {
542 if (auto EC = widenPath(To, ToWide))
543 return EC;
544
545 std::vector<char> RenameInfoBuf(sizeof(FILE_RENAME_INFO) - sizeof(wchar_t) +
546 (ToWide.size() * sizeof(wchar_t)));
547 FILE_RENAME_INFO &RenameInfo =
548 *reinterpret_cast<FILE_RENAME_INFO *>(RenameInfoBuf.data());
549 RenameInfo.ReplaceIfExists = ReplaceIfExists;
550 RenameInfo.RootDirectory = 0;
551 RenameInfo.FileNameLength = ToWide.size() * sizeof(wchar_t);
552 std::copy(ToWide.begin(), ToWide.end(), &RenameInfo.FileName[0]);
553
554 SetLastError(ERROR_SUCCESS);
555 if (!SetFileInformationByHandle(FromHandle, FileRenameInfo, &RenameInfo,
556 RenameInfoBuf.size())) {
557 unsigned Error = GetLastError();
558 if (Error == ERROR_SUCCESS)
559 Error = ERROR_CALL_NOT_IMPLEMENTED; // Wine doesn't always set error code.
560 return mapWindowsError(Error);
561 }
562
563 return std::error_code();
564}
565
566static std::error_code rename_handle(HANDLE FromHandle, const Twine &To) {
568 if (std::error_code EC = widenPath(To, WideTo))
569 return EC;
570
571 // We normally expect this loop to succeed after a few iterations. If it
572 // requires more than 200 tries, it's more likely that the failures are due to
573 // a true error, so stop trying.
574 for (unsigned Retry = 0; Retry != 200; ++Retry) {
575 auto EC = rename_internal(FromHandle, To, true);
576
577 if (EC ==
578 std::error_code(ERROR_CALL_NOT_IMPLEMENTED, std::system_category())) {
579 // Wine doesn't support SetFileInformationByHandle in rename_internal.
580 // Fall back to MoveFileEx.
582 if (std::error_code EC2 = realPathFromHandle(FromHandle, WideFrom))
583 return EC2;
584 if (::MoveFileExW(WideFrom.begin(), WideTo.begin(),
585 MOVEFILE_REPLACE_EXISTING))
586 return std::error_code();
587 return mapWindowsError(GetLastError());
588 }
589
590 if (!EC || EC != errc::permission_denied)
591 return EC;
592
593 // The destination file probably exists and is currently open in another
594 // process, either because the file was opened without FILE_SHARE_DELETE or
595 // it is mapped into memory (e.g. using MemoryBuffer). Rename it in order to
596 // move it out of the way of the source file. Use FILE_FLAG_DELETE_ON_CLOSE
597 // to arrange for the destination file to be deleted when the other process
598 // closes it.
599 ScopedFileHandle ToHandle(
600 ::CreateFileW(WideTo.begin(), GENERIC_READ | DELETE,
601 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
602 NULL, OPEN_EXISTING,
603 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, NULL));
604 if (!ToHandle) {
605 auto EC = mapWindowsError(GetLastError());
606 // Another process might have raced with us and moved the existing file
607 // out of the way before we had a chance to open it. If that happens, try
608 // to rename the source file again.
610 continue;
611 return EC;
612 }
613
614 BY_HANDLE_FILE_INFORMATION FI;
615 if (!GetFileInformationByHandle(ToHandle, &FI))
616 return mapWindowsError(GetLastError());
617
618 // Try to find a unique new name for the destination file.
619 for (unsigned UniqueId = 0; UniqueId != 200; ++UniqueId) {
620 std::string TmpFilename = (To + ".tmp" + utostr(UniqueId)).str();
621 if (auto EC = rename_internal(ToHandle, TmpFilename, false)) {
622 if (EC == errc::file_exists || EC == errc::permission_denied) {
623 // Again, another process might have raced with us and moved the file
624 // before we could move it. Check whether this is the case, as it
625 // might have caused the permission denied error. If that was the
626 // case, we don't need to move it ourselves.
627 ScopedFileHandle ToHandle2(::CreateFileW(
628 WideTo.begin(), 0,
629 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
630 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL));
631 if (!ToHandle2) {
632 auto EC = mapWindowsError(GetLastError());
634 break;
635 return EC;
636 }
637 BY_HANDLE_FILE_INFORMATION FI2;
638 if (!GetFileInformationByHandle(ToHandle2, &FI2))
639 return mapWindowsError(GetLastError());
640 if (FI.nFileIndexHigh != FI2.nFileIndexHigh ||
641 FI.nFileIndexLow != FI2.nFileIndexLow ||
642 FI.dwVolumeSerialNumber != FI2.dwVolumeSerialNumber)
643 break;
644 continue;
645 }
646 return EC;
647 }
648 break;
649 }
650
651 // Okay, the old destination file has probably been moved out of the way at
652 // this point, so try to rename the source file again. Still, another
653 // process might have raced with us to create and open the destination
654 // file, so we need to keep doing this until we succeed.
655 }
656
657 // The most likely root cause.
659}
660
661std::error_code rename(const Twine &From, const Twine &To) {
662 // Convert to utf-16.
664 if (std::error_code EC = widenPath(From, WideFrom))
665 return EC;
666
667 ScopedFileHandle FromHandle;
668 // Retry this a few times to defeat badly behaved file system scanners.
669 for (unsigned Retry = 0; Retry != 200; ++Retry) {
670 if (Retry != 0)
671 ::Sleep(10);
672 // `FILE_FLAG_BACKUP_SEMANTICS` must be used to create a handle to a
673 // directory.
674 FromHandle =
675 ::CreateFileW(WideFrom.begin(), GENERIC_READ | DELETE,
676 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
677 NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
678 if (FromHandle)
679 break;
680
681 // We don't want to loop if the file doesn't exist.
682 auto EC = mapWindowsError(GetLastError());
684 return EC;
685 }
686 if (!FromHandle)
687 return mapWindowsError(GetLastError());
688
689 return rename_handle(FromHandle, To);
690}
691
692std::error_code resize_file(int FD, uint64_t Size) {
693#ifdef HAVE__CHSIZE_S
694 errno_t error = ::_chsize_s(FD, Size);
695#else
696 errno_t error = ::_chsize(FD, Size);
697#endif
698 return std::error_code(error, std::generic_category());
699}
700
701std::error_code resize_file_sparse(int FD, uint64_t Size) {
702 HANDLE hFile = reinterpret_cast<HANDLE>(::_get_osfhandle(FD));
703 DWORD temp;
704 if (!DeviceIoControl(hFile, FSCTL_SET_SPARSE, NULL, 0, NULL, 0, &temp,
705 NULL)) {
706 return mapWindowsError(GetLastError());
707 }
708 LARGE_INTEGER liSize;
709 liSize.QuadPart = Size;
710 if (!SetFilePointerEx(hFile, liSize, NULL, FILE_BEGIN) ||
711 !SetEndOfFile(hFile)) {
712 return mapWindowsError(GetLastError());
713 }
714 return std::error_code();
715}
716
717std::error_code access(const Twine &Path, AccessMode Mode) {
719
721
722 if (std::error_code EC = widenPath(Path, PathUtf16))
723 return EC;
724
725 DWORD Attributes = ::GetFileAttributesW(PathUtf16.begin());
726
727 if (Attributes == INVALID_FILE_ATTRIBUTES) {
728 // Avoid returning unexpected error codes when querying for existence.
729 if (Mode == AccessMode::Exist)
731
732 // See if the file didn't actually exist.
733 DWORD LastError = ::GetLastError();
734 if (LastError != ERROR_FILE_NOT_FOUND && LastError != ERROR_PATH_NOT_FOUND)
735 return mapWindowsError(LastError);
737 }
738
739 if (Mode == AccessMode::Write && (Attributes & FILE_ATTRIBUTE_READONLY))
741
742 if (Mode == AccessMode::Execute && (Attributes & FILE_ATTRIBUTE_DIRECTORY))
744
745 return std::error_code();
746}
747
748bool can_execute(const Twine &Path) {
749 return !access(Path, AccessMode::Execute) ||
750 !access(Path + ".exe", AccessMode::Execute);
751}
752
755 return A.getUniqueID() == B.getUniqueID();
756}
757
758std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
760
761 file_status fsA, fsB;
762 if (std::error_code ec = status(A, fsA))
763 return ec;
764 if (std::error_code ec = status(B, fsB))
765 return ec;
766 result = equivalent(fsA, fsB);
767 return std::error_code();
768}
769
770static bool isReservedName(StringRef path) {
771 // This list of reserved names comes from MSDN, at:
772 // http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
773 static const char *const sReservedNames[] = {
774 "nul", "con", "prn", "aux", "com1", "com2", "com3", "com4",
775 "com5", "com6", "com7", "com8", "com9", "lpt1", "lpt2", "lpt3",
776 "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9"};
777
778 // First, check to see if this is a device namespace, which always
779 // starts with \\.\, since device namespaces are not legal file paths.
780 if (path.starts_with("\\\\.\\"))
781 return true;
782
783 // Then compare against the list of ancient reserved names.
784 for (size_t i = 0; i < std::size(sReservedNames); ++i) {
785 if (path.equals_insensitive(sReservedNames[i]))
786 return true;
787 }
788
789 // The path isn't what we consider reserved.
790 return false;
791}
792
793static file_type file_type_from_attrs(DWORD Attrs) {
794 return (Attrs & FILE_ATTRIBUTE_DIRECTORY) ? file_type::directory_file
796}
797
798static perms perms_from_attrs(DWORD Attrs) {
799 return (Attrs & FILE_ATTRIBUTE_READONLY) ? (all_read | all_exe) : all_all;
800}
801
802static std::error_code getStatus(HANDLE FileHandle, file_status &Result) {
804 if (FileHandle == INVALID_HANDLE_VALUE)
805 goto handle_status_error;
806
807 switch (::GetFileType(FileHandle)) {
808 default:
809 llvm_unreachable("Don't know anything about this file type");
810 case FILE_TYPE_UNKNOWN: {
811 DWORD Err = ::GetLastError();
812 if (Err != NO_ERROR)
813 return mapWindowsError(Err);
815 return std::error_code();
816 }
817 case FILE_TYPE_DISK:
818 break;
819 case FILE_TYPE_CHAR:
821 return std::error_code();
822 case FILE_TYPE_PIPE:
824 return std::error_code();
825 }
826
827 BY_HANDLE_FILE_INFORMATION Info;
828 if (!::GetFileInformationByHandle(FileHandle, &Info))
829 goto handle_status_error;
830
831 // File indices aren't necessarily stable after closing the file handle;
832 // instead hash a canonicalized path.
833 //
834 // For getting a canonical path to the file, call GetFinalPathNameByHandleW
835 // with VOLUME_NAME_NT. We don't really care exactly what the path looks
836 // like here, as long as it is canonical (e.g. doesn't differentiate between
837 // whether a file was referred to with upper/lower case names originally).
838 // The default format with VOLUME_NAME_DOS doesn't work with all file system
839 // drivers, such as ImDisk. (See
840 // https://github.com/rust-lang/rust/pull/86447.)
841 uint64_t PathHash;
842 if (std::error_code EC =
843 realPathFromHandle(FileHandle, ntPath, VOLUME_NAME_NT)) {
844 // If realPathFromHandle failed, fall back on the fields
845 // nFileIndex{High,Low} instead. They're not necessarily stable on all file
846 // systems as they're only documented as being unique/stable as long as the
847 // file handle is open - but they're a decent fallback if we couldn't get
848 // the canonical path.
849 PathHash = (static_cast<uint64_t>(Info.nFileIndexHigh) << 32ULL) |
850 static_cast<uint64_t>(Info.nFileIndexLow);
851 } else {
852 PathHash = hash_combine_range(ntPath);
853 }
854
856 file_type_from_attrs(Info.dwFileAttributes),
857 perms_from_attrs(Info.dwFileAttributes), Info.nNumberOfLinks,
858 Info.ftLastAccessTime.dwHighDateTime, Info.ftLastAccessTime.dwLowDateTime,
859 Info.ftLastWriteTime.dwHighDateTime, Info.ftLastWriteTime.dwLowDateTime,
860 Info.dwVolumeSerialNumber, Info.nFileSizeHigh, Info.nFileSizeLow,
861 PathHash);
862 return std::error_code();
863
864handle_status_error:
865 std::error_code Err = mapLastWindowsError();
866 if (Err == std::errc::no_such_file_or_directory)
868 else if (Err == std::errc::permission_denied)
870 else
872 return Err;
873}
874
875std::error_code status(const Twine &path, file_status &result, bool Follow) {
877
878 SmallString<128> path_storage;
879 SmallVector<wchar_t, 128> path_utf16;
880
881 StringRef path8 = path.toStringRef(path_storage);
882 if (isReservedName(path8)) {
884 return std::error_code();
885 }
886
887 if (std::error_code ec = widenPath(path8, path_utf16))
888 return ec;
889
890 DWORD Flags = FILE_FLAG_BACKUP_SEMANTICS;
891 if (!Follow) {
892 DWORD attr = ::GetFileAttributesW(path_utf16.begin());
893 if (attr == INVALID_FILE_ATTRIBUTES)
894 return getStatus(INVALID_HANDLE_VALUE, result);
895
896 // Handle reparse points.
897 if (attr & FILE_ATTRIBUTE_REPARSE_POINT)
898 Flags |= FILE_FLAG_OPEN_REPARSE_POINT;
899 }
900
902 ::CreateFileW(path_utf16.begin(), 0, // Attributes only.
903 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
904 NULL, OPEN_EXISTING, Flags, 0));
905 if (!h)
906 return getStatus(INVALID_HANDLE_VALUE, result);
907
908 return getStatus(h, result);
909}
910
911std::error_code status(int FD, file_status &Result) {
913
914 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
915 return getStatus(FileHandle, Result);
916}
917
918std::error_code status(file_t FileHandle, file_status &Result) {
920
921 return getStatus(FileHandle, Result);
922}
923
924unsigned getUmask() { return 0; }
925
926std::error_code setPermissions(const Twine &Path, perms Permissions) {
928 if (std::error_code EC = widenPath(Path, PathUTF16))
929 return EC;
930
931 DWORD Attributes = ::GetFileAttributesW(PathUTF16.begin());
932 if (Attributes == INVALID_FILE_ATTRIBUTES)
933 return mapWindowsError(GetLastError());
934
935 // There are many Windows file attributes that are not to do with the file
936 // permissions (e.g. FILE_ATTRIBUTE_HIDDEN). We need to be careful to preserve
937 // them.
938 if (Permissions & all_write) {
939 Attributes &= ~FILE_ATTRIBUTE_READONLY;
940 if (Attributes == 0)
941 // FILE_ATTRIBUTE_NORMAL indicates no other attributes are set.
942 Attributes |= FILE_ATTRIBUTE_NORMAL;
943 } else {
944 Attributes |= FILE_ATTRIBUTE_READONLY;
945 // FILE_ATTRIBUTE_NORMAL is not compatible with any other attributes, so
946 // remove it, if it is present.
947 Attributes &= ~FILE_ATTRIBUTE_NORMAL;
948 }
949
950 if (!::SetFileAttributesW(PathUTF16.begin(), Attributes))
951 return mapWindowsError(GetLastError());
952
953 return std::error_code();
954}
955
956std::error_code setPermissions(int FD, perms Permissions) {
957 // FIXME Not implemented.
958 return std::make_error_code(std::errc::not_supported);
959}
960
961std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime,
962 TimePoint<> ModificationTime) {
963 FILETIME AccessFT = toFILETIME(AccessTime);
964 FILETIME ModifyFT = toFILETIME(ModificationTime);
965 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
966 if (!SetFileTime(FileHandle, NULL, &AccessFT, &ModifyFT))
967 return mapWindowsError(::GetLastError());
968 return std::error_code();
969}
970
971std::error_code mapped_file_region::init(sys::fs::file_t OrigFileHandle,
972 uint64_t Offset, mapmode Mode) {
973 this->Mode = Mode;
974 if (OrigFileHandle == INVALID_HANDLE_VALUE)
976
977 DWORD flprotect;
978 switch (Mode) {
979 case readonly:
980 flprotect = PAGE_READONLY;
981 break;
982 case readwrite:
983 flprotect = PAGE_READWRITE;
984 break;
985 case priv:
986 flprotect = PAGE_WRITECOPY;
987 break;
988 }
989
990 HANDLE FileMappingHandle = ::CreateFileMappingW(OrigFileHandle, 0, flprotect,
991 Hi_32(Size), Lo_32(Size), 0);
992 if (FileMappingHandle == NULL) {
993 std::error_code ec = mapWindowsError(GetLastError());
994 return ec;
995 }
996
997 DWORD dwDesiredAccess;
998 switch (Mode) {
999 case readonly:
1000 dwDesiredAccess = FILE_MAP_READ;
1001 break;
1002 case readwrite:
1003 dwDesiredAccess = FILE_MAP_WRITE;
1004 break;
1005 case priv:
1006 dwDesiredAccess = FILE_MAP_COPY;
1007 break;
1008 }
1009 Mapping = ::MapViewOfFile(FileMappingHandle, dwDesiredAccess, Offset >> 32,
1010 Offset & 0xffffffff, Size);
1011 if (Mapping == NULL) {
1012 std::error_code ec = mapWindowsError(GetLastError());
1013 ::CloseHandle(FileMappingHandle);
1014 return ec;
1015 }
1016
1017 if (Size == 0) {
1018 MEMORY_BASIC_INFORMATION mbi;
1019 SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));
1020 if (Result == 0) {
1021 std::error_code ec = mapWindowsError(GetLastError());
1022 ::UnmapViewOfFile(Mapping);
1023 ::CloseHandle(FileMappingHandle);
1024 return ec;
1025 }
1026 Size = mbi.RegionSize;
1027 }
1028
1029 // Close the file mapping handle, as it's kept alive by the file mapping. But
1030 // neither the file mapping nor the file mapping handle keep the file handle
1031 // alive, so we need to keep a reference to the file in case all other handles
1032 // are closed and the file is deleted, which may cause invalid data to be read
1033 // from the file.
1034 ::CloseHandle(FileMappingHandle);
1035 if (!::DuplicateHandle(::GetCurrentProcess(), OrigFileHandle,
1036 ::GetCurrentProcess(), &FileHandle, 0, 0,
1037 DUPLICATE_SAME_ACCESS)) {
1038 std::error_code ec = mapWindowsError(GetLastError());
1039 ::UnmapViewOfFile(Mapping);
1040 return ec;
1041 }
1042
1043 return std::error_code();
1044}
1045
1047 size_t length, uint64_t offset,
1048 std::error_code &ec)
1049 : Size(length) {
1051
1052 ec = init(fd, offset, mode);
1053 if (ec)
1054 copyFrom(mapped_file_region());
1055}
1056
1057static bool hasFlushBufferKernelBug() {
1058 static bool Ret{GetWindowsOSVersion() < llvm::VersionTuple(10, 0, 0, 17763)};
1059 return Ret;
1060}
1061
1062static bool isEXE(StringRef Magic) {
1063 static const char PEMagic[] = {'P', 'E', '\0', '\0'};
1064 if (Magic.starts_with(StringRef("MZ")) && Magic.size() >= 0x3c + 4) {
1065 uint32_t off = read32le(Magic.data() + 0x3c);
1066 // PE/COFF file, either EXE or DLL.
1067 if (Magic.substr(off).starts_with(StringRef(PEMagic, sizeof(PEMagic))))
1068 return true;
1069 }
1070 return false;
1071}
1072
1073void mapped_file_region::unmapImpl() {
1074 if (Mapping) {
1075
1076 bool Exe = isEXE(StringRef((char *)Mapping, Size));
1077
1078 ::UnmapViewOfFile(Mapping);
1079
1080 if (Mode == mapmode::readwrite) {
1081 bool DoFlush = Exe && hasFlushBufferKernelBug();
1082 // There is a Windows kernel bug, the exact trigger conditions of which
1083 // are not well understood. When triggered, dirty pages are not properly
1084 // flushed and subsequent process's attempts to read a file can return
1085 // invalid data. Calling FlushFileBuffers on the write handle is
1086 // sufficient to ensure that this bug is not triggered.
1087 // The bug only occurs when writing an executable and executing it right
1088 // after, under high I/O pressure.
1089 if (!DoFlush) {
1090 // Separately, on VirtualBox Shared Folder mounts, writes via memory
1091 // maps always end up unflushed (regardless of version of Windows),
1092 // unless flushed with this explicit call, if they are renamed with
1093 // SetFileInformationByHandle(FileRenameInfo) before closing the output
1094 // handle.
1095 //
1096 // As the flushing is quite expensive, use a heuristic to limit the
1097 // cases where we do the flushing. Only do the flushing if we aren't
1098 // sure we are on a local file system.
1099 bool IsLocal = false;
1100 SmallVector<wchar_t, 128> FinalPath;
1101 if (!realPathFromHandle(FileHandle, FinalPath)) {
1102 // Not checking the return value here - if the check fails, assume the
1103 // file isn't local.
1104 is_local_internal(FinalPath, IsLocal);
1105 }
1106 DoFlush = !IsLocal;
1107 }
1108 if (DoFlush)
1109 ::FlushFileBuffers(FileHandle);
1110 }
1111
1112 ::CloseHandle(FileHandle);
1113 }
1114}
1115
1116void mapped_file_region::dontNeedImpl() {}
1117
1118void mapped_file_region::willNeedImpl() {
1119 struct MEMORY_RANGE_ENTRY {
1120 PVOID VirtualAddress;
1121 SIZE_T NumberOfBytes;
1122 };
1123 // PrefetchVirtualMemory is only available on Windows 8 and later. Since we
1124 // still support compilation on Windows 7, we load the function dynamically.
1125 typedef BOOL(WINAPI * PrefetchVirtualMemory_t)(
1126 HANDLE hProcess, ULONG_PTR NumberOfEntries,
1127 MEMORY_RANGE_ENTRY * VirtualAddresses, ULONG Flags);
1128
1129 static auto pfnPrefetchVirtualMemory = []() -> PrefetchVirtualMemory_t {
1130 HMODULE kernelM =
1132 if (!kernelM)
1133 return nullptr;
1134 return (PrefetchVirtualMemory_t)::GetProcAddress(kernelM,
1135 "PrefetchVirtualMemory");
1136 }();
1137 if (pfnPrefetchVirtualMemory) {
1138 MEMORY_RANGE_ENTRY Range{Mapping, Size};
1139 pfnPrefetchVirtualMemory(::GetCurrentProcess(), 1, &Range, 0);
1140 }
1141}
1142
1143std::error_code mapped_file_region::sync() const {
1144 if (!::FlushViewOfFile(Mapping, Size))
1145 return mapWindowsError(GetLastError());
1146 if (!::FlushFileBuffers(FileHandle))
1147 return mapWindowsError(GetLastError());
1148 return std::error_code();
1149}
1150
1151int mapped_file_region::alignment() {
1152 SYSTEM_INFO SysInfo;
1153 ::GetSystemInfo(&SysInfo);
1154 return SysInfo.dwAllocationGranularity;
1155}
1156
1157static basic_file_status status_from_find_data(WIN32_FIND_DATAW *FindData) {
1158 return basic_file_status(file_type_from_attrs(FindData->dwFileAttributes),
1159 perms_from_attrs(FindData->dwFileAttributes),
1160 FindData->ftLastAccessTime.dwHighDateTime,
1161 FindData->ftLastAccessTime.dwLowDateTime,
1162 FindData->ftLastWriteTime.dwHighDateTime,
1163 FindData->ftLastWriteTime.dwLowDateTime,
1164 FindData->nFileSizeHigh, FindData->nFileSizeLow);
1165}
1166
1167std::error_code detail::directory_iterator_construct(detail::DirIterState &IT,
1168 StringRef Path,
1169 bool FollowSymlinks) {
1171
1172 SmallVector<wchar_t, 128> PathUTF16;
1173
1174 if (std::error_code EC = widenPath(Path, PathUTF16))
1175 return EC;
1176
1177 // Convert path to the format that Windows is happy with.
1178 size_t PathUTF16Len = PathUTF16.size();
1179 if (PathUTF16Len > 0 && !is_separator(PathUTF16[PathUTF16Len - 1]) &&
1180 PathUTF16[PathUTF16Len - 1] != L':') {
1181 PathUTF16.push_back(L'\\');
1182 PathUTF16.push_back(L'*');
1183 } else {
1184 PathUTF16.push_back(L'*');
1185 }
1186
1187 // Get the first directory entry.
1188 WIN32_FIND_DATAW FirstFind;
1189 ScopedFindHandle FindHandle(::FindFirstFileExW(
1190 c_str(PathUTF16), FindExInfoBasic, &FirstFind, FindExSearchNameMatch,
1191 NULL, FIND_FIRST_EX_LARGE_FETCH));
1192 if (!FindHandle)
1193 return mapWindowsError(::GetLastError());
1194
1195 size_t FilenameLen = ::wcslen(FirstFind.cFileName);
1196 while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
1197 (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
1198 FirstFind.cFileName[1] == L'.'))
1199 if (!::FindNextFileW(FindHandle, &FirstFind)) {
1200 DWORD LastError = ::GetLastError();
1201 // Check for end.
1202 if (LastError == ERROR_NO_MORE_FILES)
1203 return detail::directory_iterator_destruct(IT);
1204 return mapWindowsError(LastError);
1205 } else {
1206 FilenameLen = ::wcslen(FirstFind.cFileName);
1207 }
1208
1209 // Construct the current directory entry.
1210 SmallString<128> DirectoryEntryNameUTF8;
1211 if (std::error_code EC =
1212 UTF16ToUTF8(FirstFind.cFileName, ::wcslen(FirstFind.cFileName),
1213 DirectoryEntryNameUTF8))
1214 return EC;
1215
1216 IT.IterationHandle = intptr_t(FindHandle.take());
1217 SmallString<128> DirectoryEntryPath(Path);
1218 path::append(DirectoryEntryPath, DirectoryEntryNameUTF8);
1219 IT.CurrentEntry =
1220 directory_entry(DirectoryEntryPath, FollowSymlinks,
1221 file_type_from_attrs(FirstFind.dwFileAttributes),
1222 status_from_find_data(&FirstFind));
1223
1224 return std::error_code();
1225}
1226
1227std::error_code detail::directory_iterator_destruct(detail::DirIterState &IT) {
1228 if (IT.IterationHandle != 0)
1229 // Closes the handle if it's valid.
1230 ScopedFindHandle close(HANDLE(IT.IterationHandle));
1231 IT.IterationHandle = 0;
1232 IT.CurrentEntry = directory_entry();
1233 return std::error_code();
1234}
1235
1236std::error_code detail::directory_iterator_increment(detail::DirIterState &IT) {
1238
1239 WIN32_FIND_DATAW FindData;
1240 if (!::FindNextFileW(HANDLE(IT.IterationHandle), &FindData)) {
1241 DWORD LastError = ::GetLastError();
1242 // Check for end.
1243 if (LastError == ERROR_NO_MORE_FILES)
1244 return detail::directory_iterator_destruct(IT);
1245 return mapWindowsError(LastError);
1246 }
1247
1248 size_t FilenameLen = ::wcslen(FindData.cFileName);
1249 if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
1250 (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
1251 FindData.cFileName[1] == L'.'))
1253
1254 SmallString<128> DirectoryEntryPathUTF8;
1255 if (std::error_code EC =
1256 UTF16ToUTF8(FindData.cFileName, ::wcslen(FindData.cFileName),
1257 DirectoryEntryPathUTF8))
1258 return EC;
1259
1260 IT.CurrentEntry.replace_filename(
1261 Twine(DirectoryEntryPathUTF8),
1262 file_type_from_attrs(FindData.dwFileAttributes),
1263 status_from_find_data(&FindData));
1264 return std::error_code();
1265}
1266
1267ErrorOr<basic_file_status> directory_entry::status() const { return Status; }
1268
1269static std::error_code nativeFileToFd(Expected<HANDLE> H, int &ResultFD,
1270 OpenFlags Flags) {
1271 int CrtOpenFlags = 0;
1272 if (Flags & OF_Append)
1273 CrtOpenFlags |= _O_APPEND;
1274
1275 if (Flags & OF_CRLF) {
1276 assert(Flags & OF_Text && "Flags set OF_CRLF without OF_Text");
1277 CrtOpenFlags |= _O_TEXT;
1278 }
1279
1280 ResultFD = -1;
1281 if (!H)
1282 return errorToErrorCode(H.takeError());
1283
1284 ResultFD = ::_open_osfhandle(intptr_t(*H), CrtOpenFlags);
1285 if (ResultFD == -1) {
1286 ::CloseHandle(*H);
1287 return mapWindowsError(ERROR_INVALID_HANDLE);
1288 }
1289 return std::error_code();
1290}
1291
1292static DWORD nativeDisposition(CreationDisposition Disp, OpenFlags Flags) {
1293 // This is a compatibility hack. Really we should respect the creation
1294 // disposition, but a lot of old code relied on the implicit assumption that
1295 // OF_Append implied it would open an existing file. Since the disposition is
1296 // now explicit and defaults to CD_CreateAlways, this assumption would cause
1297 // any usage of OF_Append to append to a new file, even if the file already
1298 // existed. A better solution might have two new creation dispositions:
1299 // CD_AppendAlways and CD_AppendNew. This would also address the problem of
1300 // OF_Append being used on a read-only descriptor, which doesn't make sense.
1301 if (Flags & OF_Append)
1302 return OPEN_ALWAYS;
1303
1304 switch (Disp) {
1305 case CD_CreateAlways:
1306 return CREATE_ALWAYS;
1307 case CD_CreateNew:
1308 return CREATE_NEW;
1309 case CD_OpenAlways:
1310 return OPEN_ALWAYS;
1311 case CD_OpenExisting:
1312 return OPEN_EXISTING;
1313 }
1314 llvm_unreachable("unreachable!");
1315}
1316
1317static DWORD nativeAccess(FileAccess Access, OpenFlags Flags) {
1318 DWORD Result = 0;
1319 if (Access & FA_Read)
1320 Result |= GENERIC_READ;
1321 if (Access & FA_Write)
1322 Result |= GENERIC_WRITE;
1323 if (Flags & OF_Delete)
1324 Result |= DELETE;
1325 if (Flags & OF_UpdateAtime)
1326 Result |= FILE_WRITE_ATTRIBUTES;
1327 return Result;
1328}
1329
1330static std::error_code openNativeFileInternal(const Twine &Name,
1331 file_t &ResultFile, DWORD Disp,
1332 DWORD Access, DWORD Flags,
1333 bool Inherit = false) {
1334 SmallVector<wchar_t, 128> PathUTF16;
1335 if (std::error_code EC = widenPath(Name, PathUTF16))
1336 return EC;
1337
1338 SECURITY_ATTRIBUTES SA;
1339 SA.nLength = sizeof(SA);
1340 SA.lpSecurityDescriptor = nullptr;
1341 SA.bInheritHandle = Inherit;
1342
1343 HANDLE H =
1344 ::CreateFileW(PathUTF16.begin(), Access,
1345 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &SA,
1346 Disp, Flags, NULL);
1347 if (H == INVALID_HANDLE_VALUE) {
1348 DWORD LastError = ::GetLastError();
1349 std::error_code EC = mapWindowsError(LastError);
1350 // Provide a better error message when trying to open directories.
1351 // This only runs if we failed to open the file, so there is probably
1352 // no performances issues.
1353 if (LastError != ERROR_ACCESS_DENIED)
1354 return EC;
1355 if (is_directory(Name))
1357 return EC;
1358 }
1359 ResultFile = H;
1360 return std::error_code();
1361}
1362
1363Expected<file_t> openNativeFile(const Twine &Name, CreationDisposition Disp,
1364 FileAccess Access, OpenFlags Flags,
1365 unsigned Mode) {
1367
1368 // Verify that we don't have both "append" and "excl".
1369 assert((!(Disp == CD_CreateNew) || !(Flags & OF_Append)) &&
1370 "Cannot specify both 'CreateNew' and 'Append' file creation flags!");
1371
1372 DWORD NativeDisp = nativeDisposition(Disp, Flags);
1373 DWORD NativeAccess = nativeAccess(Access, Flags);
1374
1375 bool Inherit = false;
1376 if (Flags & OF_ChildInherit)
1377 Inherit = true;
1378
1379 file_t Result;
1380 std::error_code EC = openNativeFileInternal(
1381 Name, Result, NativeDisp, NativeAccess, FILE_ATTRIBUTE_NORMAL, Inherit);
1382 if (EC)
1383 return errorCodeToError(EC);
1384
1385 if (Flags & OF_UpdateAtime) {
1386 FILETIME FileTime;
1387 SYSTEMTIME SystemTime;
1388 GetSystemTime(&SystemTime);
1389 if (SystemTimeToFileTime(&SystemTime, &FileTime) == 0 ||
1390 SetFileTime(Result, NULL, &FileTime, NULL) == 0) {
1391 DWORD LastError = ::GetLastError();
1392 ::CloseHandle(Result);
1393 return errorCodeToError(mapWindowsError(LastError));
1394 }
1395 }
1396
1397 return Result;
1398}
1399
1400std::error_code openFile(const Twine &Name, int &ResultFD,
1401 CreationDisposition Disp, FileAccess Access,
1402 OpenFlags Flags, unsigned int Mode) {
1404
1405 Expected<file_t> Result = openNativeFile(Name, Disp, Access, Flags);
1406 if (!Result)
1407 return errorToErrorCode(Result.takeError());
1408
1409 return nativeFileToFd(*Result, ResultFD, Flags);
1410}
1411
1412static std::error_code directoryRealPath(const Twine &Name,
1413 SmallVectorImpl<char> &RealPath) {
1414 file_t File;
1415 std::error_code EC = openNativeFileInternal(
1416 Name, File, OPEN_EXISTING, GENERIC_READ, FILE_FLAG_BACKUP_SEMANTICS);
1417 if (EC)
1418 return EC;
1419
1420 EC = realPathFromHandle(File, RealPath);
1421 ::CloseHandle(File);
1422 return EC;
1423}
1424
1425std::error_code openFileForRead(const Twine &Name, int &ResultFD,
1426 OpenFlags Flags,
1427 SmallVectorImpl<char> *RealPath) {
1429
1430 Expected<HANDLE> NativeFile = openNativeFileForRead(Name, Flags, RealPath);
1431 return nativeFileToFd(std::move(NativeFile), ResultFD, OF_None);
1432}
1433
1434Expected<file_t> openNativeFileForRead(const Twine &Name, OpenFlags Flags,
1435 SmallVectorImpl<char> *RealPath) {
1437
1438 Expected<file_t> Result =
1439 openNativeFile(Name, CD_OpenExisting, FA_Read, Flags);
1440
1441 // Fetch the real name of the file, if the user asked
1442 if (Result && RealPath)
1443 realPathFromHandle(*Result, *RealPath);
1444
1445 return Result;
1446}
1447
1449 return reinterpret_cast<HANDLE>(::_get_osfhandle(FD));
1450}
1451
1452file_t getStdinHandle() { return ::GetStdHandle(STD_INPUT_HANDLE); }
1453file_t getStdoutHandle() { return ::GetStdHandle(STD_OUTPUT_HANDLE); }
1454file_t getStderrHandle() { return ::GetStdHandle(STD_ERROR_HANDLE); }
1455
1456static Expected<size_t> readNativeFileImpl(file_t FileHandle,
1458 OVERLAPPED *Overlap) {
1459 // ReadFile can only read 2GB at a time. The caller should check the number of
1460 // bytes and read in a loop until termination.
1461 DWORD BytesToRead =
1462 std::min(size_t(std::numeric_limits<DWORD>::max()), Buf.size());
1463 DWORD BytesRead = 0;
1464 if (::ReadFile(FileHandle, Buf.data(), BytesToRead, &BytesRead, Overlap))
1465 return BytesRead;
1466 DWORD Err = ::GetLastError();
1467 // EOF is not an error.
1468 if (Err == ERROR_BROKEN_PIPE || Err == ERROR_HANDLE_EOF)
1469 return BytesRead;
1470 return errorCodeToError(mapWindowsError(Err));
1471}
1472
1473Expected<size_t> readNativeFile(file_t FileHandle, MutableArrayRef<char> Buf) {
1475
1476 return readNativeFileImpl(FileHandle, Buf, /*Overlap=*/nullptr);
1477}
1478
1479Expected<size_t> readNativeFileSlice(file_t FileHandle,
1481 uint64_t Offset) {
1483
1484 OVERLAPPED Overlapped = {};
1485 Overlapped.Offset = uint32_t(Offset);
1486 Overlapped.OffsetHigh = uint32_t(Offset >> 32);
1487 return readNativeFileImpl(FileHandle, Buf, &Overlapped);
1488}
1489
1490std::error_code tryLockFile(int FD, std::chrono::milliseconds Timeout,
1491 LockKind Kind) {
1492 DWORD Flags = Kind == LockKind::Exclusive ? LOCKFILE_EXCLUSIVE_LOCK : 0;
1493 Flags |= LOCKFILE_FAIL_IMMEDIATELY;
1494 OVERLAPPED OV = {};
1496 auto Start = std::chrono::steady_clock::now();
1497 auto End = Start + Timeout;
1498 do {
1499 if (::LockFileEx(File, Flags, 0, MAXDWORD, MAXDWORD, &OV))
1500 return std::error_code();
1501 DWORD Error = ::GetLastError();
1502 if (Error == ERROR_LOCK_VIOLATION) {
1503 if (Timeout.count() == 0)
1504 break;
1505 ::Sleep(1);
1506 continue;
1507 }
1508 return mapWindowsError(Error);
1509 } while (std::chrono::steady_clock::now() < End);
1510 return mapWindowsError(ERROR_LOCK_VIOLATION);
1511}
1512
1513std::error_code lockFile(int FD, LockKind Kind) {
1514 DWORD Flags = Kind == LockKind::Exclusive ? LOCKFILE_EXCLUSIVE_LOCK : 0;
1515 OVERLAPPED OV = {};
1517 if (::LockFileEx(File, Flags, 0, MAXDWORD, MAXDWORD, &OV))
1518 return std::error_code();
1519 DWORD Error = ::GetLastError();
1520 return mapWindowsError(Error);
1521}
1522
1523std::error_code unlockFile(int FD) {
1524 OVERLAPPED OV = {};
1526 if (::UnlockFileEx(File, 0, MAXDWORD, MAXDWORD, &OV))
1527 return std::error_code();
1528 return mapWindowsError(::GetLastError());
1529}
1530
1531std::error_code closeFile(file_t &F) {
1532 file_t TmpF = F;
1533 F = kInvalidFile;
1534 if (!::CloseHandle(TmpF))
1535 return mapWindowsError(::GetLastError());
1536 return std::error_code();
1537}
1538
1539std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
1540 SmallString<128> NativePath;
1541 llvm::sys::path::native(path, NativePath, path::Style::windows_backslash);
1542 // Convert to utf-16.
1544 std::error_code EC = widenPath(NativePath, Path16);
1545 if (EC && !IgnoreErrors)
1546 return EC;
1547
1548 // SHFileOperation() accepts a list of paths, and so must be double null-
1549 // terminated to indicate the end of the list. The buffer is already null
1550 // terminated, but since that null character is not considered part of the
1551 // vector's size, pushing another one will just consume that byte. So we
1552 // need to push 2 null terminators.
1553 Path16.push_back(0);
1554 Path16.push_back(0);
1555
1556 HRESULT HR;
1557 do {
1558 HR =
1559 CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
1560 if (FAILED(HR))
1561 break;
1562 llvm::scope_exit Uninitialize([] { CoUninitialize(); });
1563 IFileOperation *FileOp = NULL;
1564 HR = CoCreateInstance(CLSID_FileOperation, NULL, CLSCTX_ALL,
1565 IID_PPV_ARGS(&FileOp));
1566 if (FAILED(HR))
1567 break;
1568 llvm::scope_exit FileOpRelease([&FileOp] { FileOp->Release(); });
1569 HR = FileOp->SetOperationFlags(FOF_NO_UI | FOFX_NOCOPYHOOKS);
1570 if (FAILED(HR))
1571 break;
1572 PIDLIST_ABSOLUTE PIDL = ILCreateFromPathW(Path16.data());
1573 llvm::scope_exit FreePIDL([&PIDL] { ILFree(PIDL); });
1574 IShellItem *ShItem = NULL;
1575 HR = SHCreateItemFromIDList(PIDL, IID_PPV_ARGS(&ShItem));
1576 if (FAILED(HR))
1577 break;
1578 llvm::scope_exit ShItemRelease([&ShItem] { ShItem->Release(); });
1579 HR = FileOp->DeleteItem(ShItem, NULL);
1580 if (FAILED(HR))
1581 break;
1582 HR = FileOp->PerformOperations();
1583 } while (false);
1584 if (FAILED(HR) && !IgnoreErrors)
1585 return mapWindowsError(HRESULT_CODE(HR));
1586 return std::error_code();
1587}
1588
1589static void expandTildeExpr(SmallVectorImpl<char> &Path) {
1590 // Path does not begin with a tilde expression.
1591 if (Path.empty() || Path[0] != '~')
1592 return;
1593
1594 StringRef PathStr(Path.begin(), Path.size());
1595 PathStr = PathStr.drop_front();
1596 StringRef Expr =
1597 PathStr.take_until([](char c) { return path::is_separator(c); });
1598
1599 if (!Expr.empty()) {
1600 // This is probably a ~username/ expression. Don't support this on Windows.
1601 return;
1602 }
1603
1604 SmallString<128> HomeDir;
1605 if (!path::home_directory(HomeDir)) {
1606 // For some reason we couldn't get the home directory. Just exit.
1607 return;
1608 }
1609
1610 // Overwrite the first character and insert the rest.
1611 Path[0] = HomeDir[0];
1612 Path.insert(Path.begin() + 1, HomeDir.begin() + 1, HomeDir.end());
1613}
1614
1615void expand_tilde(const Twine &path, SmallVectorImpl<char> &dest) {
1616 dest.clear();
1617 if (path.isTriviallyEmpty())
1618 return;
1619
1620 path.toVector(dest);
1621 expandTildeExpr(dest);
1622
1623 return;
1624}
1625
1626std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
1627 bool expand_tilde) {
1629
1630 dest.clear();
1631 if (path.isTriviallyEmpty())
1632 return std::error_code();
1633
1634 if (expand_tilde) {
1635 SmallString<128> Storage;
1636 path.toVector(Storage);
1637 expandTildeExpr(Storage);
1638 return real_path(Storage, dest, false);
1639 }
1640
1641 if (is_directory(path))
1642 return directoryRealPath(path, dest);
1643
1644 int fd;
1645 if (std::error_code EC =
1646 llvm::sys::fs::openFileForRead(path, fd, OF_None, &dest))
1647 return EC;
1648 ::close(fd);
1649 return std::error_code();
1650}
1651
1652} // end namespace fs
1653
1654namespace path {
1655static bool getKnownFolderPath(KNOWNFOLDERID folderId,
1656 SmallVectorImpl<char> &result) {
1657 wchar_t *path = nullptr;
1658 if (::SHGetKnownFolderPath(folderId, KF_FLAG_CREATE, nullptr, &path) != S_OK)
1659 return false;
1660
1661 bool ok = !UTF16ToUTF8(path, ::wcslen(path), result);
1662 ::CoTaskMemFree(path);
1663 if (ok)
1665 return ok;
1666}
1667
1668bool home_directory(SmallVectorImpl<char> &result) {
1669 return getKnownFolderPath(FOLDERID_Profile, result);
1670}
1671
1672bool user_config_directory(SmallVectorImpl<char> &result) {
1673 // Either local or roaming appdata may be suitable in some cases, depending
1674 // on the data. Local is more conservative, Roaming may not always be correct.
1675 return getKnownFolderPath(FOLDERID_LocalAppData, result);
1676}
1677
1678bool cache_directory(SmallVectorImpl<char> &result) {
1679 return getKnownFolderPath(FOLDERID_LocalAppData, result);
1680}
1681
1682static bool getTempDirEnvVar(const wchar_t *Var, SmallVectorImpl<char> &Res) {
1683 SmallVector<wchar_t, 1024> Buf;
1684 size_t Size = 1024;
1685 do {
1687 Size = GetEnvironmentVariableW(Var, Buf.data(), Buf.size());
1688 if (Size == 0)
1689 return false;
1690
1691 // Try again with larger buffer.
1692 } while (Size > Buf.size());
1693 Buf.truncate(Size);
1694
1695 return !windows::UTF16ToUTF8(Buf.data(), Size, Res);
1696}
1697
1698static bool getTempDirEnvVar(SmallVectorImpl<char> &Res) {
1699 const wchar_t *EnvironmentVariables[] = {L"TMP", L"TEMP", L"USERPROFILE"};
1700 for (auto *Env : EnvironmentVariables) {
1701 if (getTempDirEnvVar(Env, Res))
1702 return true;
1703 }
1704 return false;
1705}
1706
1707void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
1708 (void)ErasedOnReboot;
1709 Result.clear();
1710
1711 // Check whether the temporary directory is specified by an environment var.
1712 // This matches GetTempPath logic to some degree. GetTempPath is not used
1713 // directly as it cannot handle evn var longer than 130 chars on Windows 7
1714 // (fixed on Windows 8).
1715 if (getTempDirEnvVar(Result)) {
1716 assert(!Result.empty() && "Unexpected empty path");
1717 native(Result); // Some Unix-like shells use Unix path separator in $TMP.
1718 fs::make_absolute(Result); // Make it absolute if not already.
1719 return;
1720 }
1721
1722 // Fall back to a system default.
1723 const char *DefaultResult = "C:\\Temp";
1724 Result.append(DefaultResult, DefaultResult + strlen(DefaultResult));
1726}
1727} // end namespace path
1728
1729namespace windows {
1730std::error_code CodePageToUTF16(unsigned codepage, llvm::StringRef original,
1731 llvm::SmallVectorImpl<wchar_t> &utf16) {
1732 if (!original.empty()) {
1733 int len =
1734 ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.begin(),
1735 original.size(), utf16.begin(), 0);
1736
1737 if (len == 0) {
1738 return mapWindowsError(::GetLastError());
1739 }
1740
1741 utf16.reserve(len + 1);
1742 utf16.resize_for_overwrite(len);
1743
1744 len =
1745 ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.begin(),
1746 original.size(), utf16.begin(), utf16.size());
1747
1748 if (len == 0) {
1749 return mapWindowsError(::GetLastError());
1750 }
1751 }
1752
1753 // Make utf16 null terminated.
1754 utf16.push_back(0);
1755 utf16.pop_back();
1756
1757 return std::error_code();
1758}
1759
1760std::error_code UTF8ToUTF16(llvm::StringRef utf8,
1761 llvm::SmallVectorImpl<wchar_t> &utf16) {
1762 return CodePageToUTF16(CP_UTF8, utf8, utf16);
1763}
1764
1765std::error_code CurCPToUTF16(llvm::StringRef curcp,
1766 llvm::SmallVectorImpl<wchar_t> &utf16) {
1767 return CodePageToUTF16(CP_ACP, curcp, utf16);
1768}
1769
1770static std::error_code UTF16ToCodePage(unsigned codepage, const wchar_t *utf16,
1771 size_t utf16_len,
1772 llvm::SmallVectorImpl<char> &converted) {
1773 if (utf16_len) {
1774 // Get length.
1775 int len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len,
1776 converted.begin(), 0, NULL, NULL);
1777
1778 if (len == 0) {
1779 return mapWindowsError(::GetLastError());
1780 }
1781
1782 converted.reserve(len + 1);
1783 converted.resize_for_overwrite(len);
1784
1785 // Now do the actual conversion.
1786 len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, converted.data(),
1787 converted.size(), NULL, NULL);
1788
1789 if (len == 0) {
1790 return mapWindowsError(::GetLastError());
1791 }
1792 }
1793
1794 // Make the new string null terminated.
1795 converted.push_back(0);
1796 converted.pop_back();
1797
1798 return std::error_code();
1799}
1800
1801std::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
1802 llvm::SmallVectorImpl<char> &utf8) {
1803 return UTF16ToCodePage(CP_UTF8, utf16, utf16_len, utf8);
1804}
1805
1806std::error_code UTF16ToCurCP(const wchar_t *utf16, size_t utf16_len,
1807 llvm::SmallVectorImpl<char> &curcp) {
1808 return UTF16ToCodePage(CP_ACP, utf16, utf16_len, curcp);
1809}
1810
1811} // end namespace windows
1812} // end namespace sys
1813} // end namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU Kernel Attributes
static cl::opt< ITMode > IT(cl::desc("IT block support"), cl::Hidden, cl::init(DefaultIT), cl::values(clEnumValN(DefaultIT, "arm-default-it", "Generate any type of IT block"), clEnumValN(RestrictedIT, "arm-restrict-it", "Disallow complex IT blocks")))
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
DXIL Resource Access
amode Optimize addressing mode
std::unique_ptr< MemoryBuffer > openFile(const Twine &Path)
#define F(x, y, z)
Definition MD5.cpp:54
#define H(x, y, z)
Definition MD5.cpp:56
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
#define P(N)
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
This file contains some templates that are useful if you are working with the STL at all.
#define error(X)
LLVM_ABI const file_t kInvalidFile
int file_t
Definition FileSystem.h:56
size_t size() const
size - Get the array size.
Definition ArrayRef.h:142
Represents either an error or a value T.
Definition ErrorOr.h:56
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition ArrayRef.h:298
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
bool starts_with(StringRef Prefix) const
starts_with - Check if this string starts with the given Prefix.
void append(StringRef RHS)
Append from a StringRef.
Definition SmallString.h:68
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void resize_for_overwrite(size_type N)
Like resize, but T is POD, the new values won't be initialized.
void reserve(size_type N)
void truncate(size_type N)
Like resize, but requires that N is less than size().
void resize(size_type N)
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
A wrapper around a string literal that serves as a proxy for constructing global tables of StringRefs...
Definition StringRef.h:888
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:261
constexpr bool empty() const
empty - Check if the string is empty.
Definition StringRef.h:143
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition StringRef.h:635
iterator begin() const
Definition StringRef.h:112
constexpr size_t size() const
size - Get the string size.
Definition StringRef.h:146
StringRef take_until(function_ref< bool(char)> F) const
Return the longest prefix of 'this' such that no character in the prefix satisfies the given predicat...
Definition StringRef.h:629
bool equals_insensitive(StringRef RHS) const
Check for string equality, ignoring case.
Definition StringRef.h:172
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
StringRef toStringRef(SmallVectorImpl< char > &Out) const
This returns the twine as a single StringRef if it can be represented as such.
Definition Twine.h:461
LLVM_ABI void toVector(SmallVectorImpl< char > &Out) const
Append the concatenated string into the given SmallString or SmallVector.
Definition Twine.cpp:32
Represents a version number in the form major[.minor[.subminor[.build]]].
LLVM_ABI TimePoint getLastModificationTime() const
The file modification time as reported from the underlying file system.
LLVM_ABI TimePoint getLastAccessedTime() const
The file access time as reported from the underlying file system.
Represents the result of a call to sys::fs::status().
Definition FileSystem.h:222
LLVM_ABI uint32_t getLinkCount() const
LLVM_ABI UniqueID getUniqueID() const
@ priv
May modify via data, but changes are lost on destruction.
@ readonly
May only access map via const_data as read only.
@ readwrite
May access map via data and modify it. Written to path.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
initializer< Ty > init(const Ty &Val)
constexpr uint16_t Magic
Definition SFrame.h:32
uint32_t read32le(const void *P)
Definition Endian.h:432
LLVM_ABI std::error_code directory_iterator_increment(DirIterState &)
LLVM_ABI bool can_execute(const Twine &Path)
Can we execute this file?
LLVM_ABI std::error_code closeFile(file_t &F)
Close the file object.
LLVM_ABI std::error_code rename(const Twine &from, const Twine &to)
Rename from to to.
LLVM_ABI std::error_code create_hard_link(const Twine &to, const Twine &from)
Create a hard link from from to to, or return an error.
LLVM_ABI const file_t kInvalidFile
LLVM_ABI std::error_code access(const Twine &Path, AccessMode Mode)
Can the file be accessed?
LLVM_ABI ErrorOr< space_info > disk_space(const Twine &Path)
Get disk space usage information.
LLVM_ABI Expected< size_t > readNativeFile(file_t FileHandle, MutableArrayRef< char > Buf)
Reads Buf.size() bytes from FileHandle into Buf.
LLVM_ABI unsigned getUmask()
Get file creation mode mask of the process.
LLVM_ABI bool exists(const basic_file_status &status)
Does file exist?
Definition Path.cpp:1088
LLVM_ABI Expected< file_t > openNativeFile(const Twine &Name, CreationDisposition Disp, FileAccess Access, OpenFlags Flags, unsigned Mode=0666)
Opens a file with the specified creation disposition, access mode, and flags and returns a platform-s...
LLVM_ABI file_t getStdoutHandle()
Return an open handle to standard out.
file_type
An enumeration for the file system's view of the type.
Definition FileSystem.h:62
LLVM_ABI std::error_code create_link(const Twine &to, const Twine &from)
Create a link from from to to.
LLVM_ABI void expand_tilde(const Twine &path, SmallVectorImpl< char > &output)
Expands ~ expressions to the user's home directory.
LLVM_ABI std::error_code lockFile(int FD, LockKind Kind=LockKind::Exclusive)
Lock the file.
LLVM_ABI std::error_code set_current_path(const Twine &path)
Set the current path.
LLVM_ABI std::error_code real_path(const Twine &path, SmallVectorImpl< char > &output, bool expand_tilde=false)
Collapse all .
@ CD_OpenExisting
CD_OpenExisting - When opening a file:
Definition FileSystem.h:737
@ CD_OpenAlways
CD_OpenAlways - When opening a file:
Definition FileSystem.h:742
@ CD_CreateAlways
CD_CreateAlways - When opening a file:
Definition FileSystem.h:727
@ CD_CreateNew
CD_CreateNew - When opening a file:
Definition FileSystem.h:732
LLVM_ABI Expected< size_t > readNativeFileSlice(file_t FileHandle, MutableArrayRef< char > Buf, uint64_t Offset)
Reads Buf.size() bytes from FileHandle at offset Offset into Buf.
LLVM_ABI std::string getMainExecutable(const char *argv0, void *MainExecAddr)
Return the path to the main executable, given the value of argv[0] from program startup and the addre...
LLVM_ABI Expected< file_t > openNativeFileForRead(const Twine &Name, OpenFlags Flags=OF_None, SmallVectorImpl< char > *RealPath=nullptr)
Opens the file with the given name in a read-only mode, returning its open file descriptor.
LLVM_ABI bool status_known(const basic_file_status &s)
Is status available?
Definition Path.cpp:1092
LLVM_ABI std::error_code make_absolute(SmallVectorImpl< char > &path)
Make path an absolute path.
Definition Path.cpp:960
LLVM_ABI std::error_code resize_file_sparse(int FD, uint64_t Size)
Resize path to size with sparse files explicitly enabled.
LLVM_ABI std::error_code tryLockFile(int FD, std::chrono::milliseconds Timeout=std::chrono::milliseconds(0), LockKind Kind=LockKind::Exclusive)
Try to locks the file during the specified time.
LLVM_ABI std::error_code current_path(SmallVectorImpl< char > &result)
Get the current path.
LLVM_ABI std::error_code resize_file(int FD, uint64_t Size)
Resize path to size.
LLVM_ABI file_t convertFDToNativeFile(int FD)
Converts from a Posix file descriptor number to a native file handle.
Definition FileSystem.h:991
LLVM_ABI std::error_code status(const Twine &path, file_status &result, bool follow=true)
Get file status as if by POSIX stat().
LLVM_ABI std::error_code create_directory(const Twine &path, bool IgnoreExisting=true, perms Perms=owner_all|group_all)
Create the directory in path.
LLVM_ABI std::error_code is_local(const Twine &path, bool &result)
Is the file mounted on a local filesystem?
LLVM_ABI std::error_code openFileForRead(const Twine &Name, int &ResultFD, OpenFlags Flags=OF_None, SmallVectorImpl< char > *RealPath=nullptr)
Opens the file with the given name in a read-only mode, returning its open file descriptor.
LLVM_ABI std::error_code remove_directories(const Twine &path, bool IgnoreErrors=true)
Recursively delete a directory.
LLVM_ABI bool equivalent(file_status A, file_status B)
Do file_status's represent the same thing?
LLVM_ABI file_t getStderrHandle()
Return an open handle to standard error.
LLVM_ABI std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime, TimePoint<> ModificationTime)
Set the file modification and access time.
LLVM_ABI file_t getStdinHandle()
Return an open handle to standard in.
LLVM_ABI std::error_code unlockFile(int FD)
Unlock the file.
LLVM_ABI std::error_code setPermissions(const Twine &Path, perms Permissions)
Set file permissions.
LLVM_ABI bool is_directory(const basic_file_status &status)
Does status represent a directory?
Definition Path.cpp:1103
LLVM_ABI bool cache_directory(SmallVectorImpl< char > &result)
Get the directory where installed packages should put their machine-local cache, e....
LLVM_ABI bool user_config_directory(SmallVectorImpl< char > &result)
Get the directory where packages should read user-specific configurations.
LLVM_ABI bool remove_dots(SmallVectorImpl< char > &path, bool remove_dot_dot=false, Style style=Style::native)
Remove '.
Definition Path.cpp:763
LLVM_ABI bool has_root_path(const Twine &path, Style style=Style::native)
Has root path?
Definition Path.cpp:630
void make_preferred(SmallVectorImpl< char > &path, Style style=Style::native)
For Windows path styles, convert path to use the preferred path separators.
Definition Path.h:278
LLVM_ABI void system_temp_directory(bool erasedOnReboot, SmallVectorImpl< char > &result)
Get the typical temporary directory for the system, e.g., "/var/tmp" or "C:/TEMP".
LLVM_ABI void native(const Twine &path, SmallVectorImpl< char > &result, Style style=Style::native)
Convert path to the native form.
Definition Path.cpp:541
LLVM_ABI bool is_absolute(const Twine &path, Style style=Style::native)
Is path absolute?
Definition Path.cpp:672
LLVM_ABI StringRef root_name(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get root name.
Definition Path.cpp:374
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition Path.cpp:457
LLVM_ABI bool home_directory(SmallVectorImpl< char > &result)
Get the user's home directory.
LLVM_ABI bool is_separator(char value, Style style=Style::native)
Check whether the given char is a path separator on the host OS.
Definition Path.cpp:602
void violationIfEnabled()
Definition IOSandbox.h:37
ScopedSetting scopedDisable()
Definition IOSandbox.h:36
LLVM_ABI std::error_code makeLongFormPath(const Twine &Path8, llvm::SmallVectorImpl< char > &Result8)
Convert a UTF-8 path to a long form UTF-8 path expanding any short 8.3 form components.
LLVM_ABI std::error_code widenPath(const Twine &Path8, SmallVectorImpl< wchar_t > &Path16, size_t MaxPathLen=MAX_PATH)
Convert UTF-8 path to a suitable UTF-16 path for use with the Win32 Unicode File API.
LLVM_ABI HMODULE loadSystemModuleSecure(LPCWSTR lpModuleName)
Retrieves the handle to a in-memory system module such as ntdll.dll, while ensuring we're not retriev...
FILETIME toFILETIME(TimePoint<> TP)
std::chrono::time_point< std::chrono::system_clock, D > TimePoint
A time point on the system clock.
Definition Chrono.h:34
TimePoint< std::chrono::seconds > toTimePoint(std::time_t T)
Convert a std::time_t to a TimePoint.
Definition Chrono.h:65
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
@ Offset
Definition DWP.cpp:532
LLVM_ABI std::error_code mapLastWindowsError()
std::error_code make_error_code(BitcodeError E)
SmallVectorImpl< T >::const_pointer c_str(SmallVectorImpl< T > &str)
LLVM_ABI llvm::VersionTuple GetWindowsOSVersion()
Returns the Windows version as Major.Minor.0.BuildNumber.
std::string utostr(uint64_t X, bool isNeg=false)
ScopedHandle< FindHandleTraits > ScopedFindHandle
@ no_such_file_or_directory
Definition Errc.h:65
@ file_exists
Definition Errc.h:48
@ bad_file_descriptor
Definition Errc.h:39
@ not_supported
Definition Errc.h:69
@ permission_denied
Definition Errc.h:71
@ is_a_directory
Definition Errc.h:59
constexpr uint32_t Hi_32(uint64_t Value)
Return the high 32 bits of a 64 bit value.
Definition MathExtras.h:150
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
constexpr uint32_t Lo_32(uint64_t Value)
Return the low 32 bits of a 64 bit value.
Definition MathExtras.h:155
@ Success
The lock was released successfully.
@ Timeout
Reached timeout while waiting for the owner to release the lock.
FunctionAddr VTableAddr uintptr_t uintptr_t Data
Definition InstrProf.h:189
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition Error.cpp:107
LLVM_ABI std::error_code mapWindowsError(unsigned EV)
ScopedHandle< FileHandleTraits > ScopedFileHandle
LLVM_ABI std::error_code errorToErrorCode(Error Err)
Helper for converting an ECError to a std::error_code.
Definition Error.cpp:113
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition Hashing.h:466
space_info - Self explanatory.
Definition FileSystem.h:76