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