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