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