blob: 72da7c5fec32dfa3d715ec90187970b097201f43 [file] [log] [blame]
Rafael Espindolaf1fc3822013-06-26 19:33:03 +00001//===- llvm/Support/Windows/Path.inc - Windows Path Impl --------*- C++ -*-===//
Michael J. Spencerebad2f92010-11-29 22:28:51 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Rafael Espindolaf1fc3822013-06-26 19:33:03 +000010// This file implements the Windows specific implementation of the Path API.
Michael J. Spencerebad2f92010-11-29 22:28:51 +000011//
12//===----------------------------------------------------------------------===//
13
14//===----------------------------------------------------------------------===//
15//=== WARNING: Implementation here must contain only generic Windows code that
16//=== is guaranteed to work on *all* Windows variants.
17//===----------------------------------------------------------------------===//
18
Craig Topperf18edae2013-07-15 07:15:05 +000019#include "llvm/ADT/STLExtras.h"
Rafael Espindola5c4f8292014-06-11 19:05:50 +000020#include "llvm/Support/WindowsError.h"
Michael J. Spencerc20a0322010-12-03 17:54:07 +000021#include <fcntl.h>
Michael J. Spencer45710402010-12-03 01:21:28 +000022#include <io.h>
Michael J. Spencerc20a0322010-12-03 17:54:07 +000023#include <sys/stat.h>
24#include <sys/types.h>
Michael J. Spencerebad2f92010-11-29 22:28:51 +000025
NAKAMURA Takumi04d39d72014-02-12 11:50:22 +000026// 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
Reid Klecknerd59e2fa2014-02-12 21:26:20 +000028#include "WindowsSupport.h"
NAKAMURA Takumi04d39d72014-02-12 11:50:22 +000029#include <shlobj.h>
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000030
Michael J. Spenceref2284f2012-08-15 19:05:47 +000031#undef max
32
Michael J. Spencer60252472010-12-03 18:03:28 +000033// MinGW doesn't define this.
Michael J. Spencer521c3212010-12-03 18:04:11 +000034#ifndef _ERRNO_T_DEFINED
35#define _ERRNO_T_DEFINED
36typedef int errno_t;
Michael J. Spencer60252472010-12-03 18:03:28 +000037#endif
38
Reid Kleckner11da0042013-08-07 20:19:31 +000039#ifdef _MSC_VER
40# pragma comment(lib, "advapi32.lib") // This provides CryptAcquireContextW.
41#endif
42
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +000043using namespace llvm;
44
Rui Ueyama471d0c52013-09-10 19:45:51 +000045using llvm::sys::windows::UTF8ToUTF16;
46using llvm::sys::windows::UTF16ToUTF8;
Paul Robinsonc38deee2014-11-24 18:05:29 +000047using llvm::sys::path::widenPath;
Rui Ueyama471d0c52013-09-10 19:45:51 +000048
Rafael Espindola37b012d2014-02-23 15:16:03 +000049static bool is_separator(const wchar_t value) {
50 switch (value) {
51 case L'\\':
52 case L'/':
53 return true;
54 default:
55 return false;
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +000056 }
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +000057}
58
Paul Robinsonc38deee2014-11-24 18:05:29 +000059namespace llvm {
60namespace sys {
61namespace path {
62
Paul Robinsond9c4a9a2014-11-13 00:12:14 +000063// Convert a UTF-8 path to UTF-16. Also, if the absolute equivalent of the
64// path is longer than CreateDirectory can tolerate, make it absolute and
65// prefixed by '\\?\'.
Paul Robinsonc38deee2014-11-24 18:05:29 +000066std::error_code widenPath(const Twine &Path8,
67 SmallVectorImpl<wchar_t> &Path16) {
Paul Robinsond9c4a9a2014-11-13 00:12:14 +000068 const size_t MaxDirLen = MAX_PATH - 12; // Must leave room for 8.3 filename.
69
70 // Several operations would convert Path8 to SmallString; more efficient to
71 // do it once up front.
72 SmallString<128> Path8Str;
73 Path8.toVector(Path8Str);
74
75 // If we made this path absolute, how much longer would it get?
76 size_t CurPathLen;
77 if (llvm::sys::path::is_absolute(Twine(Path8Str)))
78 CurPathLen = 0; // No contribution from current_path needed.
79 else {
80 CurPathLen = ::GetCurrentDirectoryW(0, NULL);
81 if (CurPathLen == 0)
Yaron Kerenf8e65172015-05-04 04:48:10 +000082 return mapWindowsError(::GetLastError());
Paul Robinsond9c4a9a2014-11-13 00:12:14 +000083 }
84
85 // Would the absolute path be longer than our limit?
86 if ((Path8Str.size() + CurPathLen) >= MaxDirLen &&
87 !Path8Str.startswith("\\\\?\\")) {
88 SmallString<2*MAX_PATH> FullPath("\\\\?\\");
89 if (CurPathLen) {
90 SmallString<80> CurPath;
91 if (std::error_code EC = llvm::sys::fs::current_path(CurPath))
92 return EC;
93 FullPath.append(CurPath);
94 }
95 // Traverse the requested path, canonicalizing . and .. as we go (because
96 // the \\?\ prefix is documented to treat them as real components).
97 // The iterators don't report separators and append() always attaches
98 // preferred_separator so we don't need to call native() on the result.
99 for (llvm::sys::path::const_iterator I = llvm::sys::path::begin(Path8Str),
100 E = llvm::sys::path::end(Path8Str);
101 I != E; ++I) {
102 if (I->size() == 1 && *I == ".")
103 continue;
104 if (I->size() == 2 && *I == "..")
105 llvm::sys::path::remove_filename(FullPath);
106 else
107 llvm::sys::path::append(FullPath, *I);
108 }
109 return UTF8ToUTF16(FullPath, Path16);
110 }
111
112 // Just use the caller's original path.
113 return UTF8ToUTF16(Path8Str, Path16);
114}
Paul Robinsonc38deee2014-11-24 18:05:29 +0000115} // end namespace path
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000116
Michael J. Spencer20daa282010-12-07 01:22:31 +0000117namespace fs {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000118
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000119std::string getMainExecutable(const char *argv0, void *MainExecAddr) {
David Majnemer17a44962013-10-07 09:52:36 +0000120 SmallVector<wchar_t, MAX_PATH> PathName;
121 DWORD Size = ::GetModuleFileNameW(NULL, PathName.data(), PathName.capacity());
122
123 // A zero return value indicates a failure other than insufficient space.
124 if (Size == 0)
125 return "";
126
127 // Insufficient space is determined by a return value equal to the size of
128 // the buffer passed in.
129 if (Size == PathName.capacity())
130 return "";
131
132 // On success, GetModuleFileNameW returns the number of characters written to
133 // the buffer not including the NULL terminator.
134 PathName.set_size(Size);
135
136 // Convert the result from UTF-16 to UTF-8.
137 SmallVector<char, MAX_PATH> PathNameUTF8;
138 if (UTF16ToUTF8(PathName.data(), PathName.size(), PathNameUTF8))
139 return "";
140
141 return std::string(PathNameUTF8.data());
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000142}
143
Rafael Espindolad1230992013-07-29 21:55:38 +0000144UniqueID file_status::getUniqueID() const {
Rafael Espindola7f822a92013-07-29 21:26:49 +0000145 // The file is uniquely identified by the volume serial number along
146 // with the 64-bit file identifier.
147 uint64_t FileID = (static_cast<uint64_t>(FileIndexHigh) << 32ULL) |
148 static_cast<uint64_t>(FileIndexLow);
149
150 return UniqueID(VolumeSerialNumber, FileID);
151}
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000152
Rafael Espindolabe3ede72013-06-20 21:51:49 +0000153TimeValue file_status::getLastModificationTime() const {
Rafael Espindoladb5d8fe2013-06-20 18:42:04 +0000154 ULARGE_INTEGER UI;
155 UI.LowPart = LastWriteTimeLow;
156 UI.HighPart = LastWriteTimeHigh;
157
158 TimeValue Ret;
159 Ret.fromWin32Time(UI.QuadPart);
160 return Ret;
161}
162
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000163std::error_code current_path(SmallVectorImpl<char> &result) {
David Majnemer61eae2e2013-10-07 01:00:07 +0000164 SmallVector<wchar_t, MAX_PATH> cur_path;
165 DWORD len = MAX_PATH;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000166
David Majnemer61eae2e2013-10-07 01:00:07 +0000167 do {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000168 cur_path.reserve(len);
David Majnemer61eae2e2013-10-07 01:00:07 +0000169 len = ::GetCurrentDirectoryW(cur_path.capacity(), cur_path.data());
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000170
David Majnemer61eae2e2013-10-07 01:00:07 +0000171 // A zero return value indicates a failure other than insufficient space.
172 if (len == 0)
Yaron Kerenf8e65172015-05-04 04:48:10 +0000173 return mapWindowsError(::GetLastError());
David Majnemer61eae2e2013-10-07 01:00:07 +0000174
175 // If there's insufficient space, the len returned is larger than the len
176 // given.
177 } while (len > cur_path.capacity());
178
179 // On success, GetCurrentDirectoryW returns the number of characters not
180 // including the null-terminator.
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000181 cur_path.set_size(len);
Aaron Ballmanb16cf532013-08-16 17:53:28 +0000182 return UTF16ToUTF8(cur_path.begin(), cur_path.size(), result);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000183}
184
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000185std::error_code create_directory(const Twine &path, bool IgnoreExisting) {
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000186 SmallVector<wchar_t, 128> path_utf16;
187
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000188 if (std::error_code ec = widenPath(path, path_utf16))
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000189 return ec;
190
191 if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {
Rafael Espindolaa813d602014-06-11 03:58:34 +0000192 DWORD LastError = ::GetLastError();
193 if (LastError != ERROR_ALREADY_EXISTS || !IgnoreExisting)
Yaron Kerenf8e65172015-05-04 04:48:10 +0000194 return mapWindowsError(LastError);
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000195 }
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000196
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000197 return std::error_code();
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000198}
199
Rafael Espindola83f858e2014-03-11 18:40:24 +0000200// We can't use symbolic links for windows.
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000201std::error_code create_link(const Twine &to, const Twine &from) {
Michael J. Spencere0c45602010-12-03 05:58:41 +0000202 // Convert to utf-16.
203 SmallVector<wchar_t, 128> wide_from;
204 SmallVector<wchar_t, 128> wide_to;
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000205 if (std::error_code ec = widenPath(from, wide_from))
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000206 return ec;
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000207 if (std::error_code ec = widenPath(to, wide_to))
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000208 return ec;
Michael J. Spencere0c45602010-12-03 05:58:41 +0000209
210 if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
Yaron Kerenf8e65172015-05-04 04:48:10 +0000211 return mapWindowsError(::GetLastError());
Michael J. Spencere0c45602010-12-03 05:58:41 +0000212
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000213 return std::error_code();
Michael J. Spencere0c45602010-12-03 05:58:41 +0000214}
215
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000216std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000217 SmallVector<wchar_t, 128> path_utf16;
218
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000219 file_status ST;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000220 if (std::error_code EC = status(path, ST)) {
Rafael Espindola2a826e42014-06-13 17:20:48 +0000221 if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000222 return EC;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000223 return std::error_code();
Rafael Espindola107b74c2013-07-31 00:10:25 +0000224 }
Michael J. Spencer153749b2011-01-05 16:39:22 +0000225
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000226 if (std::error_code ec = widenPath(path, path_utf16))
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000227 return ec;
228
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000229 if (ST.type() == file_type::directory_file) {
Michael J. Spencer153749b2011-01-05 16:39:22 +0000230 if (!::RemoveDirectoryW(c_str(path_utf16))) {
Yaron Kerenf8e65172015-05-04 04:48:10 +0000231 std::error_code EC = mapWindowsError(::GetLastError());
Rafael Espindola2a826e42014-06-13 17:20:48 +0000232 if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000233 return EC;
234 }
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000235 return std::error_code();
Michael J. Spencer153749b2011-01-05 16:39:22 +0000236 }
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000237 if (!::DeleteFileW(c_str(path_utf16))) {
Yaron Kerenf8e65172015-05-04 04:48:10 +0000238 std::error_code EC = mapWindowsError(::GetLastError());
Rafael Espindola2a826e42014-06-13 17:20:48 +0000239 if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000240 return EC;
241 }
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000242 return std::error_code();
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000243}
244
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000245std::error_code rename(const Twine &from, const Twine &to) {
Michael J. Spencer409f5562010-12-03 17:53:55 +0000246 // Convert to utf-16.
247 SmallVector<wchar_t, 128> wide_from;
248 SmallVector<wchar_t, 128> wide_to;
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000249 if (std::error_code ec = widenPath(from, wide_from))
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000250 return ec;
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000251 if (std::error_code ec = widenPath(to, wide_to))
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000252 return ec;
Michael J. Spencer409f5562010-12-03 17:53:55 +0000253
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000254 std::error_code ec = std::error_code();
NAKAMURA Takumi3b7f9952012-05-08 14:31:46 +0000255 for (int i = 0; i < 2000; i++) {
256 if (::MoveFileExW(wide_from.begin(), wide_to.begin(),
257 MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING))
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000258 return std::error_code();
Rafael Espindolaa813d602014-06-11 03:58:34 +0000259 DWORD LastError = ::GetLastError();
Yaron Kerenf8e65172015-05-04 04:48:10 +0000260 ec = mapWindowsError(LastError);
Rafael Espindolaa813d602014-06-11 03:58:34 +0000261 if (LastError != ERROR_ACCESS_DENIED)
NAKAMURA Takumi3b7f9952012-05-08 14:31:46 +0000262 break;
263 // Retry MoveFile() at ACCESS_DENIED.
264 // System scanners (eg. indexer) might open the source file when
265 // It is written and closed.
266 ::Sleep(1);
267 }
Michael J. Spencer409f5562010-12-03 17:53:55 +0000268
NAKAMURA Takumi3b7f9952012-05-08 14:31:46 +0000269 return ec;
Michael J. Spencer409f5562010-12-03 17:53:55 +0000270}
271
Rafael Espindola59aaa6c2014-12-12 17:55:12 +0000272std::error_code resize_file(int FD, uint64_t Size) {
Michael J. Spencerca242f22010-12-03 18:48:56 +0000273#ifdef HAVE__CHSIZE_S
Rafael Espindola59aaa6c2014-12-12 17:55:12 +0000274 errno_t error = ::_chsize_s(FD, Size);
Michael J. Spencerca242f22010-12-03 18:48:56 +0000275#else
Rafael Espindola59aaa6c2014-12-12 17:55:12 +0000276 errno_t error = ::_chsize(FD, Size);
Michael J. Spencerca242f22010-12-03 18:48:56 +0000277#endif
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000278 return std::error_code(error, std::generic_category());
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000279}
280
Rafael Espindola281f23a2014-09-11 20:30:02 +0000281std::error_code access(const Twine &Path, AccessMode Mode) {
Rafael Espindola281f23a2014-09-11 20:30:02 +0000282 SmallVector<wchar_t, 128> PathUtf16;
Michael J. Spencer45710402010-12-03 01:21:28 +0000283
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000284 if (std::error_code EC = widenPath(Path, PathUtf16))
Rafael Espindola281f23a2014-09-11 20:30:02 +0000285 return EC;
Michael J. Spencer45710402010-12-03 01:21:28 +0000286
Rafael Espindola281f23a2014-09-11 20:30:02 +0000287 DWORD Attributes = ::GetFileAttributesW(PathUtf16.begin());
Michael J. Spencer45710402010-12-03 01:21:28 +0000288
Rafael Espindola281f23a2014-09-11 20:30:02 +0000289 if (Attributes == INVALID_FILE_ATTRIBUTES) {
Michael J. Spencer45710402010-12-03 01:21:28 +0000290 // See if the file didn't actually exist.
Rafael Espindolaa813d602014-06-11 03:58:34 +0000291 DWORD LastError = ::GetLastError();
292 if (LastError != ERROR_FILE_NOT_FOUND &&
293 LastError != ERROR_PATH_NOT_FOUND)
Yaron Kerenf8e65172015-05-04 04:48:10 +0000294 return mapWindowsError(LastError);
Rafael Espindola281f23a2014-09-11 20:30:02 +0000295 return errc::no_such_file_or_directory;
296 }
297
298 if (Mode == AccessMode::Write && (Attributes & FILE_ATTRIBUTE_READONLY))
299 return errc::permission_denied;
300
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000301 return std::error_code();
Michael J. Spencer45710402010-12-03 01:21:28 +0000302}
303
Michael J. Spencer203d7802011-12-12 06:04:28 +0000304bool equivalent(file_status A, file_status B) {
305 assert(status_known(A) && status_known(B));
306 return A.FileIndexHigh == B.FileIndexHigh &&
307 A.FileIndexLow == B.FileIndexLow &&
308 A.FileSizeHigh == B.FileSizeHigh &&
309 A.FileSizeLow == B.FileSizeLow &&
310 A.LastWriteTimeHigh == B.LastWriteTimeHigh &&
311 A.LastWriteTimeLow == B.LastWriteTimeLow &&
312 A.VolumeSerialNumber == B.VolumeSerialNumber;
313}
314
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000315std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
Michael J. Spencer203d7802011-12-12 06:04:28 +0000316 file_status fsA, fsB;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000317 if (std::error_code ec = status(A, fsA))
318 return ec;
319 if (std::error_code ec = status(B, fsB))
320 return ec;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000321 result = equivalent(fsA, fsB);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000322 return std::error_code();
Michael J. Spencer376d3872010-12-03 18:49:13 +0000323}
324
Benjamin Kramer58994ec2011-08-20 21:36:38 +0000325static bool isReservedName(StringRef path) {
326 // This list of reserved names comes from MSDN, at:
327 // http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
328 static const char *sReservedNames[] = { "nul", "con", "prn", "aux",
329 "com1", "com2", "com3", "com4", "com5", "com6",
330 "com7", "com8", "com9", "lpt1", "lpt2", "lpt3",
331 "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9" };
332
333 // First, check to see if this is a device namespace, which always
334 // starts with \\.\, since device namespaces are not legal file paths.
335 if (path.startswith("\\\\.\\"))
336 return true;
337
338 // Then compare against the list of ancient reserved names
Craig Topper58713212013-07-15 04:27:47 +0000339 for (size_t i = 0; i < array_lengthof(sReservedNames); ++i) {
Benjamin Kramer58994ec2011-08-20 21:36:38 +0000340 if (path.equals_lower(sReservedNames[i]))
341 return true;
342 }
343
344 // The path isn't what we consider reserved.
345 return false;
346}
347
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000348static std::error_code getStatus(HANDLE FileHandle, file_status &Result) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000349 if (FileHandle == INVALID_HANDLE_VALUE)
350 goto handle_status_error;
351
NAKAMURA Takumi8b01da42013-07-18 17:00:54 +0000352 switch (::GetFileType(FileHandle)) {
353 default:
Rafael Espindola81177c52013-07-18 18:42:52 +0000354 llvm_unreachable("Don't know anything about this file type");
355 case FILE_TYPE_UNKNOWN: {
356 DWORD Err = ::GetLastError();
357 if (Err != NO_ERROR)
Yaron Kerenf8e65172015-05-04 04:48:10 +0000358 return mapWindowsError(Err);
Rafael Espindola81177c52013-07-18 18:42:52 +0000359 Result = file_status(file_type::type_unknown);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000360 return std::error_code();
Rafael Espindola81177c52013-07-18 18:42:52 +0000361 }
NAKAMURA Takumi8b01da42013-07-18 17:00:54 +0000362 case FILE_TYPE_DISK:
363 break;
364 case FILE_TYPE_CHAR:
365 Result = file_status(file_type::character_file);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000366 return std::error_code();
NAKAMURA Takumi8b01da42013-07-18 17:00:54 +0000367 case FILE_TYPE_PIPE:
368 Result = file_status(file_type::fifo_file);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000369 return std::error_code();
NAKAMURA Takumi8b01da42013-07-18 17:00:54 +0000370 }
371
Rafael Espindola77021c92013-07-16 03:20:13 +0000372 BY_HANDLE_FILE_INFORMATION Info;
373 if (!::GetFileInformationByHandle(FileHandle, &Info))
374 goto handle_status_error;
375
Rafael Espindolaa5932af2013-07-30 20:25:53 +0000376 {
377 file_type Type = (Info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
378 ? file_type::directory_file
379 : file_type::regular_file;
380 Result =
381 file_status(Type, Info.ftLastWriteTime.dwHighDateTime,
382 Info.ftLastWriteTime.dwLowDateTime,
383 Info.dwVolumeSerialNumber, Info.nFileSizeHigh,
384 Info.nFileSizeLow, Info.nFileIndexHigh, Info.nFileIndexLow);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000385 return std::error_code();
Rafael Espindolaa5932af2013-07-30 20:25:53 +0000386 }
Rafael Espindola77021c92013-07-16 03:20:13 +0000387
388handle_status_error:
Rafael Espindolaa813d602014-06-11 03:58:34 +0000389 DWORD LastError = ::GetLastError();
390 if (LastError == ERROR_FILE_NOT_FOUND ||
391 LastError == ERROR_PATH_NOT_FOUND)
Rafael Espindola77021c92013-07-16 03:20:13 +0000392 Result = file_status(file_type::file_not_found);
Rafael Espindolaa813d602014-06-11 03:58:34 +0000393 else if (LastError == ERROR_SHARING_VIOLATION)
Rafael Espindola77021c92013-07-16 03:20:13 +0000394 Result = file_status(file_type::type_unknown);
Rafael Espindola107b74c2013-07-31 00:10:25 +0000395 else
Rafael Espindola77021c92013-07-16 03:20:13 +0000396 Result = file_status(file_type::status_error);
Yaron Kerenf8e65172015-05-04 04:48:10 +0000397 return mapWindowsError(LastError);
Rafael Espindola77021c92013-07-16 03:20:13 +0000398}
399
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000400std::error_code status(const Twine &path, file_status &result) {
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000401 SmallString<128> path_storage;
402 SmallVector<wchar_t, 128> path_utf16;
403
NAKAMURA Takumia3d47492011-03-16 02:53:32 +0000404 StringRef path8 = path.toStringRef(path_storage);
Benjamin Kramer58994ec2011-08-20 21:36:38 +0000405 if (isReservedName(path8)) {
NAKAMURA Takumia3d47492011-03-16 02:53:32 +0000406 result = file_status(file_type::character_file);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000407 return std::error_code();
NAKAMURA Takumia3d47492011-03-16 02:53:32 +0000408 }
409
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000410 if (std::error_code ec = widenPath(path8, path_utf16))
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000411 return ec;
412
413 DWORD attr = ::GetFileAttributesW(path_utf16.begin());
414 if (attr == INVALID_FILE_ATTRIBUTES)
Rafael Espindola77021c92013-07-16 03:20:13 +0000415 return getStatus(INVALID_HANDLE_VALUE, result);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000416
417 // Handle reparse points.
418 if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
Michael J. Spencer513f1b62011-12-12 06:03:33 +0000419 ScopedFileHandle h(
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000420 ::CreateFileW(path_utf16.begin(),
421 0, // Attributes only.
422 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
423 NULL,
424 OPEN_EXISTING,
425 FILE_FLAG_BACKUP_SEMANTICS,
426 0));
Michael J. Spencer513f1b62011-12-12 06:03:33 +0000427 if (!h)
Rafael Espindola77021c92013-07-16 03:20:13 +0000428 return getStatus(INVALID_HANDLE_VALUE, result);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000429 }
430
Rafael Espindolaa5932af2013-07-30 20:25:53 +0000431 ScopedFileHandle h(
432 ::CreateFileW(path_utf16.begin(), 0, // Attributes only.
Michael J. Spencer203d7802011-12-12 06:04:28 +0000433 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
Rafael Espindolaa5932af2013-07-30 20:25:53 +0000434 NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0));
Michael J. Spencer203d7802011-12-12 06:04:28 +0000435 if (!h)
Rafael Espindola77021c92013-07-16 03:20:13 +0000436 return getStatus(INVALID_HANDLE_VALUE, result);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000437
Rafael Espindola77021c92013-07-16 03:20:13 +0000438 return getStatus(h, result);
Rafael Espindola77021c92013-07-16 03:20:13 +0000439}
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000440
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000441std::error_code status(int FD, file_status &Result) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000442 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
443 return getStatus(FileHandle, Result);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000444}
445
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000446std::error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000447 ULARGE_INTEGER UI;
448 UI.QuadPart = Time.toWin32Time();
449 FILETIME FT;
450 FT.dwLowDateTime = UI.LowPart;
451 FT.dwHighDateTime = UI.HighPart;
452 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
453 if (!SetFileTime(FileHandle, NULL, &FT, &FT))
Yaron Kerenf8e65172015-05-04 04:48:10 +0000454 return mapWindowsError(::GetLastError());
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000455 return std::error_code();
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000456}
Nick Kledzik18497e92012-06-20 00:28:54 +0000457
Rafael Espindola7eb1f182014-12-11 20:12:55 +0000458std::error_code mapped_file_region::init(int FD, uint64_t Offset,
459 mapmode Mode) {
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000460 // Make sure that the requested size fits within SIZE_T.
Rafael Espindola986f5ad2014-12-16 02:19:26 +0000461 if (Size > std::numeric_limits<SIZE_T>::max())
Rafael Espindola2a826e42014-06-13 17:20:48 +0000462 return make_error_code(errc::invalid_argument);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000463
Rafael Espindolaa23008a2014-12-16 03:10:29 +0000464 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
465 if (FileHandle == INVALID_HANDLE_VALUE)
466 return make_error_code(errc::bad_file_descriptor);
467
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000468 DWORD flprotect;
469 switch (Mode) {
470 case readonly: flprotect = PAGE_READONLY; break;
471 case readwrite: flprotect = PAGE_READWRITE; break;
472 case priv: flprotect = PAGE_WRITECOPY; break;
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000473 }
474
Rafael Espindola369d5142014-12-16 02:53:35 +0000475 HANDLE FileMappingHandle =
David Majnemer17a44962013-10-07 09:52:36 +0000476 ::CreateFileMappingW(FileHandle, 0, flprotect,
477 (Offset + Size) >> 32,
478 (Offset + Size) & 0xffffffff,
479 0);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000480 if (FileMappingHandle == NULL) {
Yaron Kerenf8e65172015-05-04 04:48:10 +0000481 std::error_code ec = mapWindowsError(GetLastError());
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000482 return ec;
483 }
484
485 DWORD dwDesiredAccess;
486 switch (Mode) {
487 case readonly: dwDesiredAccess = FILE_MAP_READ; break;
488 case readwrite: dwDesiredAccess = FILE_MAP_WRITE; break;
489 case priv: dwDesiredAccess = FILE_MAP_COPY; break;
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000490 }
491 Mapping = ::MapViewOfFile(FileMappingHandle,
492 dwDesiredAccess,
493 Offset >> 32,
494 Offset & 0xffffffff,
495 Size);
496 if (Mapping == NULL) {
Yaron Kerenf8e65172015-05-04 04:48:10 +0000497 std::error_code ec = mapWindowsError(GetLastError());
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000498 ::CloseHandle(FileMappingHandle);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000499 return ec;
500 }
501
502 if (Size == 0) {
503 MEMORY_BASIC_INFORMATION mbi;
504 SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));
505 if (Result == 0) {
Yaron Kerenf8e65172015-05-04 04:48:10 +0000506 std::error_code ec = mapWindowsError(GetLastError());
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000507 ::UnmapViewOfFile(Mapping);
508 ::CloseHandle(FileMappingHandle);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000509 return ec;
510 }
511 Size = mbi.RegionSize;
512 }
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000513
514 // Close all the handles except for the view. It will keep the other handles
515 // alive.
516 ::CloseHandle(FileMappingHandle);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000517 return std::error_code();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000518}
519
Rafael Espindola7eb1f182014-12-11 20:12:55 +0000520mapped_file_region::mapped_file_region(int fd, mapmode mode, uint64_t length,
521 uint64_t offset, std::error_code &ec)
Rafael Espindolaa23008a2014-12-16 03:10:29 +0000522 : Size(length), Mapping() {
Rafael Espindola986f5ad2014-12-16 02:19:26 +0000523 ec = init(fd, offset, mode);
Rafael Espindolaa23008a2014-12-16 03:10:29 +0000524 if (ec)
Rafael Espindola369d5142014-12-16 02:53:35 +0000525 Mapping = 0;
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000526}
527
528mapped_file_region::~mapped_file_region() {
529 if (Mapping)
530 ::UnmapViewOfFile(Mapping);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000531}
532
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000533uint64_t mapped_file_region::size() const {
534 assert(Mapping && "Mapping failed but used anyway!");
535 return Size;
536}
537
538char *mapped_file_region::data() const {
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000539 assert(Mapping && "Mapping failed but used anyway!");
540 return reinterpret_cast<char*>(Mapping);
541}
542
543const char *mapped_file_region::const_data() const {
544 assert(Mapping && "Mapping failed but used anyway!");
545 return reinterpret_cast<const char*>(Mapping);
546}
547
548int mapped_file_region::alignment() {
549 SYSTEM_INFO SysInfo;
550 ::GetSystemInfo(&SysInfo);
551 return SysInfo.dwAllocationGranularity;
552}
553
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000554std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000555 StringRef path){
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000556 SmallVector<wchar_t, 128> path_utf16;
557
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000558 if (std::error_code ec = widenPath(path, path_utf16))
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000559 return ec;
560
561 // Convert path to the format that Windows is happy with.
562 if (path_utf16.size() > 0 &&
563 !is_separator(path_utf16[path.size() - 1]) &&
564 path_utf16[path.size() - 1] != L':') {
565 path_utf16.push_back(L'\\');
566 path_utf16.push_back(L'*');
567 } else {
568 path_utf16.push_back(L'*');
569 }
570
571 // Get the first directory entry.
572 WIN32_FIND_DATAW FirstFind;
Michael J. Spencer751e9aa2010-12-09 17:37:18 +0000573 ScopedFindHandle FindHandle(::FindFirstFileW(c_str(path_utf16), &FirstFind));
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000574 if (!FindHandle)
Yaron Kerenf8e65172015-05-04 04:48:10 +0000575 return mapWindowsError(::GetLastError());
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000576
Michael J. Spencer98879d72011-01-05 16:39:30 +0000577 size_t FilenameLen = ::wcslen(FirstFind.cFileName);
578 while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
579 (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
580 FirstFind.cFileName[1] == L'.'))
581 if (!::FindNextFileW(FindHandle, &FirstFind)) {
Rafael Espindolaa813d602014-06-11 03:58:34 +0000582 DWORD LastError = ::GetLastError();
Michael J. Spencer98879d72011-01-05 16:39:30 +0000583 // Check for end.
Rafael Espindolaa813d602014-06-11 03:58:34 +0000584 if (LastError == ERROR_NO_MORE_FILES)
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000585 return detail::directory_iterator_destruct(it);
Yaron Kerenf8e65172015-05-04 04:48:10 +0000586 return mapWindowsError(LastError);
Michael J. Spencer98879d72011-01-05 16:39:30 +0000587 } else
588 FilenameLen = ::wcslen(FirstFind.cFileName);
589
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000590 // Construct the current directory entry.
Michael J. Spencer98879d72011-01-05 16:39:30 +0000591 SmallString<128> directory_entry_name_utf8;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000592 if (std::error_code ec =
593 UTF16ToUTF8(FirstFind.cFileName, ::wcslen(FirstFind.cFileName),
594 directory_entry_name_utf8))
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000595 return ec;
596
597 it.IterationHandle = intptr_t(FindHandle.take());
Michael J. Spencer98879d72011-01-05 16:39:30 +0000598 SmallString<128> directory_entry_path(path);
Yaron Keren92e1b622015-03-18 10:17:07 +0000599 path::append(directory_entry_path, directory_entry_name_utf8);
600 it.CurrentEntry = directory_entry(directory_entry_path);
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000601
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000602 return std::error_code();
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000603}
604
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000605std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000606 if (it.IterationHandle != 0)
607 // Closes the handle if it's valid.
608 ScopedFindHandle close(HANDLE(it.IterationHandle));
609 it.IterationHandle = 0;
610 it.CurrentEntry = directory_entry();
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000611 return std::error_code();
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000612}
613
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000614std::error_code detail::directory_iterator_increment(detail::DirIterState &it) {
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000615 WIN32_FIND_DATAW FindData;
616 if (!::FindNextFileW(HANDLE(it.IterationHandle), &FindData)) {
Rafael Espindolaa813d602014-06-11 03:58:34 +0000617 DWORD LastError = ::GetLastError();
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000618 // Check for end.
Rafael Espindolaa813d602014-06-11 03:58:34 +0000619 if (LastError == ERROR_NO_MORE_FILES)
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000620 return detail::directory_iterator_destruct(it);
Yaron Kerenf8e65172015-05-04 04:48:10 +0000621 return mapWindowsError(LastError);
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000622 }
623
Michael J. Spencer98879d72011-01-05 16:39:30 +0000624 size_t FilenameLen = ::wcslen(FindData.cFileName);
625 if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
626 (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
627 FindData.cFileName[1] == L'.'))
628 return directory_iterator_increment(it);
629
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000630 SmallString<128> directory_entry_path_utf8;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000631 if (std::error_code ec =
632 UTF16ToUTF8(FindData.cFileName, ::wcslen(FindData.cFileName),
633 directory_entry_path_utf8))
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000634 return ec;
635
636 it.CurrentEntry.replace_filename(Twine(directory_entry_path_utf8));
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000637 return std::error_code();
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000638}
639
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000640std::error_code openFileForRead(const Twine &Name, int &ResultFD) {
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000641 SmallVector<wchar_t, 128> PathUTF16;
Nick Kledzik18497e92012-06-20 00:28:54 +0000642
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000643 if (std::error_code EC = widenPath(Name, PathUTF16))
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000644 return EC;
645
646 HANDLE H = ::CreateFileW(PathUTF16.begin(), GENERIC_READ,
Rafael Espindola16431fe2013-07-17 19:44:07 +0000647 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000648 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
649 if (H == INVALID_HANDLE_VALUE) {
Rafael Espindolaa813d602014-06-11 03:58:34 +0000650 DWORD LastError = ::GetLastError();
Yaron Kerenf8e65172015-05-04 04:48:10 +0000651 std::error_code EC = mapWindowsError(LastError);
Rafael Espindola331aeba2013-07-17 19:58:28 +0000652 // Provide a better error message when trying to open directories.
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000653 // This only runs if we failed to open the file, so there is probably
654 // no performances issues.
Rafael Espindolaa813d602014-06-11 03:58:34 +0000655 if (LastError != ERROR_ACCESS_DENIED)
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000656 return EC;
657 if (is_directory(Name))
Rafael Espindola2a826e42014-06-13 17:20:48 +0000658 return make_error_code(errc::is_a_directory);
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000659 return EC;
660 }
661
662 int FD = ::_open_osfhandle(intptr_t(H), 0);
663 if (FD == -1) {
664 ::CloseHandle(H);
Yaron Kerenf8e65172015-05-04 04:48:10 +0000665 return mapWindowsError(ERROR_INVALID_HANDLE);
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000666 }
667
668 ResultFD = FD;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000669 return std::error_code();
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000670}
Nick Kledzik18497e92012-06-20 00:28:54 +0000671
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000672std::error_code openFileForWrite(const Twine &Name, int &ResultFD,
Rafael Espindola67080ce2013-07-19 15:02:03 +0000673 sys::fs::OpenFlags Flags, unsigned Mode) {
674 // Verify that we don't have both "append" and "excl".
675 assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
676 "Cannot specify both 'excl' and 'append' file creation flags!");
677
Rafael Espindola67080ce2013-07-19 15:02:03 +0000678 SmallVector<wchar_t, 128> PathUTF16;
679
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000680 if (std::error_code EC = widenPath(Name, PathUTF16))
Rafael Espindola67080ce2013-07-19 15:02:03 +0000681 return EC;
682
683 DWORD CreationDisposition;
684 if (Flags & F_Excl)
685 CreationDisposition = CREATE_NEW;
NAKAMURA Takumiedf76152013-08-22 15:14:45 +0000686 else if (Flags & F_Append)
Rafael Espindola67080ce2013-07-19 15:02:03 +0000687 CreationDisposition = OPEN_ALWAYS;
688 else
689 CreationDisposition = CREATE_ALWAYS;
690
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000691 DWORD Access = GENERIC_WRITE;
692 if (Flags & F_RW)
693 Access |= GENERIC_READ;
694
695 HANDLE H = ::CreateFileW(PathUTF16.begin(), Access,
Rafael Espindola67080ce2013-07-19 15:02:03 +0000696 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
697 CreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL);
698
699 if (H == INVALID_HANDLE_VALUE) {
Rafael Espindolaa813d602014-06-11 03:58:34 +0000700 DWORD LastError = ::GetLastError();
Yaron Kerenf8e65172015-05-04 04:48:10 +0000701 std::error_code EC = mapWindowsError(LastError);
Rafael Espindola67080ce2013-07-19 15:02:03 +0000702 // Provide a better error message when trying to open directories.
703 // This only runs if we failed to open the file, so there is probably
704 // no performances issues.
Rafael Espindolaa813d602014-06-11 03:58:34 +0000705 if (LastError != ERROR_ACCESS_DENIED)
Rafael Espindola67080ce2013-07-19 15:02:03 +0000706 return EC;
707 if (is_directory(Name))
Rafael Espindola2a826e42014-06-13 17:20:48 +0000708 return make_error_code(errc::is_a_directory);
Rafael Espindola67080ce2013-07-19 15:02:03 +0000709 return EC;
710 }
711
712 int OpenFlags = 0;
713 if (Flags & F_Append)
714 OpenFlags |= _O_APPEND;
715
Rafael Espindola90c7f1c2014-02-24 18:20:12 +0000716 if (Flags & F_Text)
Rafael Espindola67080ce2013-07-19 15:02:03 +0000717 OpenFlags |= _O_TEXT;
718
719 int FD = ::_open_osfhandle(intptr_t(H), OpenFlags);
720 if (FD == -1) {
721 ::CloseHandle(H);
Yaron Kerenf8e65172015-05-04 04:48:10 +0000722 return mapWindowsError(ERROR_INVALID_HANDLE);
Rafael Espindola67080ce2013-07-19 15:02:03 +0000723 }
724
725 ResultFD = FD;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000726 return std::error_code();
Rafael Espindola67080ce2013-07-19 15:02:03 +0000727}
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000728} // end namespace fs
Rui Ueyama471d0c52013-09-10 19:45:51 +0000729
Peter Collingbournef7d41012014-01-31 23:46:06 +0000730namespace path {
731
732bool home_directory(SmallVectorImpl<char> &result) {
733 wchar_t Path[MAX_PATH];
734 if (::SHGetFolderPathW(0, CSIDL_APPDATA | CSIDL_FLAG_CREATE, 0,
Peter Collingbournead141ab2014-02-01 02:42:20 +0000735 /*SHGFP_TYPE_CURRENT*/0, Path) != S_OK)
Peter Collingbournef7d41012014-01-31 23:46:06 +0000736 return false;
737
738 if (UTF16ToUTF8(Path, ::wcslen(Path), result))
739 return false;
740
741 return true;
742}
743
Rafael Espindola016a6d52014-08-26 14:47:52 +0000744static bool getTempDirEnvVar(const char *Var, SmallVectorImpl<char> &Res) {
745 SmallVector<wchar_t, 128> NameUTF16;
746 if (windows::UTF8ToUTF16(Var, NameUTF16))
747 return false;
748
749 SmallVector<wchar_t, 1024> Buf;
750 size_t Size = 1024;
751 do {
752 Buf.reserve(Size);
753 Size =
754 GetEnvironmentVariableW(NameUTF16.data(), Buf.data(), Buf.capacity());
755 if (Size == 0)
756 return false;
757
758 // Try again with larger buffer.
759 } while (Size > Buf.capacity());
760 Buf.set_size(Size);
761
762 if (windows::UTF16ToUTF8(Buf.data(), Size, Res))
763 return false;
764 return true;
765}
766
767static bool getTempDirEnvVar(SmallVectorImpl<char> &Res) {
768 const char *EnvironmentVariables[] = {"TMP", "TEMP", "USERPROFILE"};
769 for (const char *Env : EnvironmentVariables) {
770 if (getTempDirEnvVar(Env, Res))
771 return true;
772 }
773 return false;
774}
775
776void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
777 (void)ErasedOnReboot;
778 Result.clear();
779
780 // Check whether the temporary directory is specified by an environment
781 // variable.
782 if (getTempDirEnvVar(Result))
783 return;
784
785 // Fall back to a system default.
786 const char *DefaultResult = "C:\\TEMP";
787 Result.append(DefaultResult, DefaultResult + strlen(DefaultResult));
788}
Peter Collingbournef7d41012014-01-31 23:46:06 +0000789} // end namespace path
790
Rui Ueyama471d0c52013-09-10 19:45:51 +0000791namespace windows {
Rafael Espindola0a5f9cf2014-06-12 14:11:22 +0000792std::error_code UTF8ToUTF16(llvm::StringRef utf8,
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000793 llvm::SmallVectorImpl<wchar_t> &utf16) {
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000794 if (!utf8.empty()) {
795 int len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
796 utf8.size(), utf16.begin(), 0);
Rui Ueyama471d0c52013-09-10 19:45:51 +0000797
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000798 if (len == 0)
Yaron Kerenf8e65172015-05-04 04:48:10 +0000799 return mapWindowsError(::GetLastError());
Rui Ueyama471d0c52013-09-10 19:45:51 +0000800
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000801 utf16.reserve(len + 1);
802 utf16.set_size(len);
Rui Ueyama471d0c52013-09-10 19:45:51 +0000803
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000804 len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
805 utf8.size(), utf16.begin(), utf16.size());
Rui Ueyama471d0c52013-09-10 19:45:51 +0000806
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000807 if (len == 0)
Yaron Kerenf8e65172015-05-04 04:48:10 +0000808 return mapWindowsError(::GetLastError());
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000809 }
Rui Ueyama471d0c52013-09-10 19:45:51 +0000810
811 // Make utf16 null terminated.
812 utf16.push_back(0);
813 utf16.pop_back();
814
Rafael Espindola0a5f9cf2014-06-12 14:11:22 +0000815 return std::error_code();
Rui Ueyama471d0c52013-09-10 19:45:51 +0000816}
817
Rafael Espindola9c359662014-09-03 20:02:00 +0000818static
819std::error_code UTF16ToCodePage(unsigned codepage, const wchar_t *utf16,
820 size_t utf16_len,
821 llvm::SmallVectorImpl<char> &utf8) {
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000822 if (utf16_len) {
823 // Get length.
Rafael Espindola9c359662014-09-03 20:02:00 +0000824 int len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, utf8.begin(),
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000825 0, NULL, NULL);
Rui Ueyama471d0c52013-09-10 19:45:51 +0000826
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000827 if (len == 0)
Yaron Kerenf8e65172015-05-04 04:48:10 +0000828 return mapWindowsError(::GetLastError());
Rui Ueyama471d0c52013-09-10 19:45:51 +0000829
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000830 utf8.reserve(len);
831 utf8.set_size(len);
Rui Ueyama471d0c52013-09-10 19:45:51 +0000832
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000833 // Now do the actual conversion.
Rafael Espindola9c359662014-09-03 20:02:00 +0000834 len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, utf8.data(),
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000835 utf8.size(), NULL, NULL);
Rui Ueyama471d0c52013-09-10 19:45:51 +0000836
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000837 if (len == 0)
Yaron Kerenf8e65172015-05-04 04:48:10 +0000838 return mapWindowsError(::GetLastError());
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000839 }
Rui Ueyama471d0c52013-09-10 19:45:51 +0000840
841 // Make utf8 null terminated.
842 utf8.push_back(0);
843 utf8.pop_back();
844
Rafael Espindola0a5f9cf2014-06-12 14:11:22 +0000845 return std::error_code();
Rui Ueyama471d0c52013-09-10 19:45:51 +0000846}
Rafael Espindola9c359662014-09-03 20:02:00 +0000847
848std::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
849 llvm::SmallVectorImpl<char> &utf8) {
850 return UTF16ToCodePage(CP_UTF8, utf16, utf16_len, utf8);
851}
852
853std::error_code UTF16ToCurCP(const wchar_t *utf16, size_t utf16_len,
854 llvm::SmallVectorImpl<char> &utf8) {
855 return UTF16ToCodePage(CP_ACP, utf16, utf16_len, utf8);
856}
Rui Ueyama471d0c52013-09-10 19:45:51 +0000857} // end namespace windows
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000858} // end namespace sys
859} // end namespace llvm