blob: 0e695c2e7207a04eee47b4225e0a163af8cd71d7 [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;
47
Rafael Espindolaa813d602014-06-11 03:58:34 +000048static error_code windows_error(DWORD E) {
Rafael Espindola5c4f8292014-06-11 19:05:50 +000049 return mapWindowsError(E);
Rafael Espindolaa813d602014-06-11 03:58:34 +000050}
51
Rafael Espindola7a0b6402014-02-24 03:07:41 +000052static error_code TempDir(SmallVectorImpl<char> &Result) {
53 SmallVector<wchar_t, 64> Res;
Rafael Espindola37b012d2014-02-23 15:16:03 +000054retry_temp_dir:
Rafael Espindola7a0b6402014-02-24 03:07:41 +000055 DWORD Len = ::GetTempPathW(Res.capacity(), Res.begin());
Michael J. Spencer45710402010-12-03 01:21:28 +000056
Rafael Espindola7a0b6402014-02-24 03:07:41 +000057 if (Len == 0)
Rafael Espindola37b012d2014-02-23 15:16:03 +000058 return windows_error(::GetLastError());
Michael J. Spencer45710402010-12-03 01:21:28 +000059
Rafael Espindola7a0b6402014-02-24 03:07:41 +000060 if (Len > Res.capacity()) {
61 Res.reserve(Len);
Rafael Espindola37b012d2014-02-23 15:16:03 +000062 goto retry_temp_dir;
Michael J. Spencer45710402010-12-03 01:21:28 +000063 }
64
Rafael Espindola7a0b6402014-02-24 03:07:41 +000065 Res.set_size(Len);
66 return UTF16ToUTF8(Res.begin(), Res.size(), Result);
Rafael Espindola37b012d2014-02-23 15:16:03 +000067}
68
69static bool is_separator(const wchar_t value) {
70 switch (value) {
71 case L'\\':
72 case L'/':
73 return true;
74 default:
75 return false;
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +000076 }
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +000077}
78
Michael J. Spencerebad2f92010-11-29 22:28:51 +000079namespace llvm {
80namespace sys {
Michael J. Spencer20daa282010-12-07 01:22:31 +000081namespace fs {
Michael J. Spencerebad2f92010-11-29 22:28:51 +000082
Rafael Espindolae03dfd92013-06-26 05:01:35 +000083std::string getMainExecutable(const char *argv0, void *MainExecAddr) {
David Majnemer17a44962013-10-07 09:52:36 +000084 SmallVector<wchar_t, MAX_PATH> PathName;
85 DWORD Size = ::GetModuleFileNameW(NULL, PathName.data(), PathName.capacity());
86
87 // A zero return value indicates a failure other than insufficient space.
88 if (Size == 0)
89 return "";
90
91 // Insufficient space is determined by a return value equal to the size of
92 // the buffer passed in.
93 if (Size == PathName.capacity())
94 return "";
95
96 // On success, GetModuleFileNameW returns the number of characters written to
97 // the buffer not including the NULL terminator.
98 PathName.set_size(Size);
99
100 // Convert the result from UTF-16 to UTF-8.
101 SmallVector<char, MAX_PATH> PathNameUTF8;
102 if (UTF16ToUTF8(PathName.data(), PathName.size(), PathNameUTF8))
103 return "";
104
105 return std::string(PathNameUTF8.data());
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000106}
107
Rafael Espindolad1230992013-07-29 21:55:38 +0000108UniqueID file_status::getUniqueID() const {
Rafael Espindola7f822a92013-07-29 21:26:49 +0000109 // The file is uniquely identified by the volume serial number along
110 // with the 64-bit file identifier.
111 uint64_t FileID = (static_cast<uint64_t>(FileIndexHigh) << 32ULL) |
112 static_cast<uint64_t>(FileIndexLow);
113
114 return UniqueID(VolumeSerialNumber, FileID);
115}
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000116
Rafael Espindolabe3ede72013-06-20 21:51:49 +0000117TimeValue file_status::getLastModificationTime() const {
Rafael Espindoladb5d8fe2013-06-20 18:42:04 +0000118 ULARGE_INTEGER UI;
119 UI.LowPart = LastWriteTimeLow;
120 UI.HighPart = LastWriteTimeHigh;
121
122 TimeValue Ret;
123 Ret.fromWin32Time(UI.QuadPart);
124 return Ret;
125}
126
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000127error_code current_path(SmallVectorImpl<char> &result) {
David Majnemer61eae2e2013-10-07 01:00:07 +0000128 SmallVector<wchar_t, MAX_PATH> cur_path;
129 DWORD len = MAX_PATH;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000130
David Majnemer61eae2e2013-10-07 01:00:07 +0000131 do {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000132 cur_path.reserve(len);
David Majnemer61eae2e2013-10-07 01:00:07 +0000133 len = ::GetCurrentDirectoryW(cur_path.capacity(), cur_path.data());
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000134
David Majnemer61eae2e2013-10-07 01:00:07 +0000135 // A zero return value indicates a failure other than insufficient space.
136 if (len == 0)
137 return windows_error(::GetLastError());
138
139 // If there's insufficient space, the len returned is larger than the len
140 // given.
141 } while (len > cur_path.capacity());
142
143 // On success, GetCurrentDirectoryW returns the number of characters not
144 // including the null-terminator.
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000145 cur_path.set_size(len);
Aaron Ballmanb16cf532013-08-16 17:53:28 +0000146 return UTF16ToUTF8(cur_path.begin(), cur_path.size(), result);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000147}
148
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000149error_code create_directory(const Twine &path, bool IgnoreExisting) {
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000150 SmallString<128> path_storage;
151 SmallVector<wchar_t, 128> path_utf16;
152
153 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
154 path_utf16))
155 return ec;
156
157 if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {
Rafael Espindolaa813d602014-06-11 03:58:34 +0000158 DWORD LastError = ::GetLastError();
159 if (LastError != ERROR_ALREADY_EXISTS || !IgnoreExisting)
160 return windows_error(LastError);
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000161 }
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000162
Rafael Espindola03bddfe2014-05-31 01:37:45 +0000163 return error_code();
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000164}
165
Saleem Abdulrasoolafc50b3ed2014-03-11 22:05:42 +0000166error_code normalize_separators(SmallVectorImpl<char> &Path) {
167 (void) Path;
Rafael Espindola03bddfe2014-05-31 01:37:45 +0000168 return error_code();
Saleem Abdulrasoolafc50b3ed2014-03-11 22:05:42 +0000169}
170
Rafael Espindola83f858e2014-03-11 18:40:24 +0000171// We can't use symbolic links for windows.
172error_code create_link(const Twine &to, const Twine &from) {
Michael J. Spencere0c45602010-12-03 05:58:41 +0000173 // Get arguments.
174 SmallString<128> from_storage;
175 SmallString<128> to_storage;
176 StringRef f = from.toStringRef(from_storage);
177 StringRef t = to.toStringRef(to_storage);
178
179 // Convert to utf-16.
180 SmallVector<wchar_t, 128> wide_from;
181 SmallVector<wchar_t, 128> wide_to;
182 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
183 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
184
185 if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
Michael J. Spencer66a1f862010-12-04 18:45:32 +0000186 return windows_error(::GetLastError());
Michael J. Spencere0c45602010-12-03 05:58:41 +0000187
Rafael Espindola03bddfe2014-05-31 01:37:45 +0000188 return error_code();
Michael J. Spencere0c45602010-12-03 05:58:41 +0000189}
190
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000191error_code remove(const Twine &path, bool IgnoreNonExisting) {
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000192 SmallString<128> path_storage;
193 SmallVector<wchar_t, 128> path_utf16;
194
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000195 file_status ST;
196 if (error_code EC = status(path, ST)) {
Rafael Espindola5c4f8292014-06-11 19:05:50 +0000197 if (EC != std::errc::no_such_file_or_directory || !IgnoreNonExisting)
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000198 return EC;
Rafael Espindola03bddfe2014-05-31 01:37:45 +0000199 return error_code();
Rafael Espindola107b74c2013-07-31 00:10:25 +0000200 }
Michael J. Spencer153749b2011-01-05 16:39:22 +0000201
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000202 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
203 path_utf16))
204 return ec;
205
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000206 if (ST.type() == file_type::directory_file) {
Michael J. Spencer153749b2011-01-05 16:39:22 +0000207 if (!::RemoveDirectoryW(c_str(path_utf16))) {
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000208 error_code EC = windows_error(::GetLastError());
Rafael Espindola5c4f8292014-06-11 19:05:50 +0000209 if (EC != std::errc::no_such_file_or_directory || !IgnoreNonExisting)
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000210 return EC;
211 }
Rafael Espindola03bddfe2014-05-31 01:37:45 +0000212 return error_code();
Michael J. Spencer153749b2011-01-05 16:39:22 +0000213 }
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000214 if (!::DeleteFileW(c_str(path_utf16))) {
215 error_code EC = windows_error(::GetLastError());
Rafael Espindola5c4f8292014-06-11 19:05:50 +0000216 if (EC != std::errc::no_such_file_or_directory || !IgnoreNonExisting)
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000217 return EC;
218 }
Rafael Espindola03bddfe2014-05-31 01:37:45 +0000219 return error_code();
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000220}
221
Michael J. Spencer409f5562010-12-03 17:53:55 +0000222error_code rename(const Twine &from, const Twine &to) {
223 // Get arguments.
224 SmallString<128> from_storage;
225 SmallString<128> to_storage;
226 StringRef f = from.toStringRef(from_storage);
227 StringRef t = to.toStringRef(to_storage);
228
229 // Convert to utf-16.
230 SmallVector<wchar_t, 128> wide_from;
231 SmallVector<wchar_t, 128> wide_to;
232 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
233 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
234
Rafael Espindola03bddfe2014-05-31 01:37:45 +0000235 error_code ec = error_code();
NAKAMURA Takumi3b7f9952012-05-08 14:31:46 +0000236 for (int i = 0; i < 2000; i++) {
237 if (::MoveFileExW(wide_from.begin(), wide_to.begin(),
238 MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING))
Rafael Espindola03bddfe2014-05-31 01:37:45 +0000239 return error_code();
Rafael Espindolaa813d602014-06-11 03:58:34 +0000240 DWORD LastError = ::GetLastError();
241 if (LastError != ERROR_ACCESS_DENIED)
NAKAMURA Takumi3b7f9952012-05-08 14:31:46 +0000242 break;
243 // Retry MoveFile() at ACCESS_DENIED.
244 // System scanners (eg. indexer) might open the source file when
245 // It is written and closed.
246 ::Sleep(1);
247 }
Michael J. Spencer409f5562010-12-03 17:53:55 +0000248
NAKAMURA Takumi3b7f9952012-05-08 14:31:46 +0000249 return ec;
Michael J. Spencer409f5562010-12-03 17:53:55 +0000250}
251
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000252error_code resize_file(const Twine &path, uint64_t size) {
253 SmallString<128> path_storage;
254 SmallVector<wchar_t, 128> path_utf16;
255
256 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
257 path_utf16))
258 return ec;
259
Michael J. Spencer20abb202012-12-03 22:09:31 +0000260 int fd = ::_wopen(path_utf16.begin(), O_BINARY | _O_RDWR, S_IWRITE);
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000261 if (fd == -1)
Rafael Espindola7e577f72014-06-12 02:00:39 +0000262 return error_code(errno, std::generic_category());
Michael J. Spencerca242f22010-12-03 18:48:56 +0000263#ifdef HAVE__CHSIZE_S
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000264 errno_t error = ::_chsize_s(fd, size);
Michael J. Spencerca242f22010-12-03 18:48:56 +0000265#else
266 errno_t error = ::_chsize(fd, size);
267#endif
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000268 ::close(fd);
Rafael Espindola7e577f72014-06-12 02:00:39 +0000269 return error_code(error, std::generic_category());
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000270}
271
Michael J. Spencer45710402010-12-03 01:21:28 +0000272error_code exists(const Twine &path, bool &result) {
273 SmallString<128> path_storage;
274 SmallVector<wchar_t, 128> path_utf16;
275
276 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
277 path_utf16))
278 return ec;
279
280 DWORD attributes = ::GetFileAttributesW(path_utf16.begin());
281
282 if (attributes == INVALID_FILE_ATTRIBUTES) {
283 // See if the file didn't actually exist.
Rafael Espindolaa813d602014-06-11 03:58:34 +0000284 DWORD LastError = ::GetLastError();
285 if (LastError != ERROR_FILE_NOT_FOUND &&
286 LastError != ERROR_PATH_NOT_FOUND)
287 return windows_error(LastError);
Michael J. Spencer45710402010-12-03 01:21:28 +0000288 result = false;
289 } else
290 result = true;
Rafael Espindola03bddfe2014-05-31 01:37:45 +0000291 return error_code();
Michael J. Spencer45710402010-12-03 01:21:28 +0000292}
293
Rafael Espindolaa1280c12013-06-18 20:56:38 +0000294bool can_write(const Twine &Path) {
295 // FIXME: take security attributes into account.
296 SmallString<128> PathStorage;
297 SmallVector<wchar_t, 128> PathUtf16;
298
299 if (UTF8ToUTF16(Path.toStringRef(PathStorage), PathUtf16))
300 return false;
301
302 DWORD Attr = ::GetFileAttributesW(PathUtf16.begin());
303 return (Attr != INVALID_FILE_ATTRIBUTES) && !(Attr & FILE_ATTRIBUTE_READONLY);
304}
305
Rafael Espindolab0a5c962013-06-14 19:38:45 +0000306bool can_execute(const Twine &Path) {
307 SmallString<128> PathStorage;
308 SmallVector<wchar_t, 128> PathUtf16;
309
310 if (UTF8ToUTF16(Path.toStringRef(PathStorage), PathUtf16))
311 return false;
312
313 DWORD Attr = ::GetFileAttributesW(PathUtf16.begin());
314 return Attr != INVALID_FILE_ATTRIBUTES;
315}
316
Michael J. Spencer203d7802011-12-12 06:04:28 +0000317bool equivalent(file_status A, file_status B) {
318 assert(status_known(A) && status_known(B));
319 return A.FileIndexHigh == B.FileIndexHigh &&
320 A.FileIndexLow == B.FileIndexLow &&
321 A.FileSizeHigh == B.FileSizeHigh &&
322 A.FileSizeLow == B.FileSizeLow &&
323 A.LastWriteTimeHigh == B.LastWriteTimeHigh &&
324 A.LastWriteTimeLow == B.LastWriteTimeLow &&
325 A.VolumeSerialNumber == B.VolumeSerialNumber;
326}
327
Michael J. Spencer376d3872010-12-03 18:49:13 +0000328error_code equivalent(const Twine &A, const Twine &B, bool &result) {
Michael J. Spencer203d7802011-12-12 06:04:28 +0000329 file_status fsA, fsB;
330 if (error_code ec = status(A, fsA)) return ec;
331 if (error_code ec = status(B, fsB)) return ec;
332 result = equivalent(fsA, fsB);
Rafael Espindola03bddfe2014-05-31 01:37:45 +0000333 return error_code();
Michael J. Spencer376d3872010-12-03 18:49:13 +0000334}
335
Benjamin Kramer58994ec2011-08-20 21:36:38 +0000336static bool isReservedName(StringRef path) {
337 // This list of reserved names comes from MSDN, at:
338 // http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
339 static const char *sReservedNames[] = { "nul", "con", "prn", "aux",
340 "com1", "com2", "com3", "com4", "com5", "com6",
341 "com7", "com8", "com9", "lpt1", "lpt2", "lpt3",
342 "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9" };
343
344 // First, check to see if this is a device namespace, which always
345 // starts with \\.\, since device namespaces are not legal file paths.
346 if (path.startswith("\\\\.\\"))
347 return true;
348
349 // Then compare against the list of ancient reserved names
Craig Topper58713212013-07-15 04:27:47 +0000350 for (size_t i = 0; i < array_lengthof(sReservedNames); ++i) {
Benjamin Kramer58994ec2011-08-20 21:36:38 +0000351 if (path.equals_lower(sReservedNames[i]))
352 return true;
353 }
354
355 // The path isn't what we consider reserved.
356 return false;
357}
358
Rafael Espindola77021c92013-07-16 03:20:13 +0000359static error_code getStatus(HANDLE FileHandle, file_status &Result) {
360 if (FileHandle == INVALID_HANDLE_VALUE)
361 goto handle_status_error;
362
NAKAMURA Takumi8b01da42013-07-18 17:00:54 +0000363 switch (::GetFileType(FileHandle)) {
364 default:
Rafael Espindola81177c52013-07-18 18:42:52 +0000365 llvm_unreachable("Don't know anything about this file type");
366 case FILE_TYPE_UNKNOWN: {
367 DWORD Err = ::GetLastError();
368 if (Err != NO_ERROR)
369 return windows_error(Err);
370 Result = file_status(file_type::type_unknown);
Rafael Espindola03bddfe2014-05-31 01:37:45 +0000371 return error_code();
Rafael Espindola81177c52013-07-18 18:42:52 +0000372 }
NAKAMURA Takumi8b01da42013-07-18 17:00:54 +0000373 case FILE_TYPE_DISK:
374 break;
375 case FILE_TYPE_CHAR:
376 Result = file_status(file_type::character_file);
Rafael Espindola03bddfe2014-05-31 01:37:45 +0000377 return error_code();
NAKAMURA Takumi8b01da42013-07-18 17:00:54 +0000378 case FILE_TYPE_PIPE:
379 Result = file_status(file_type::fifo_file);
Rafael Espindola03bddfe2014-05-31 01:37:45 +0000380 return error_code();
NAKAMURA Takumi8b01da42013-07-18 17:00:54 +0000381 }
382
Rafael Espindola77021c92013-07-16 03:20:13 +0000383 BY_HANDLE_FILE_INFORMATION Info;
384 if (!::GetFileInformationByHandle(FileHandle, &Info))
385 goto handle_status_error;
386
Rafael Espindolaa5932af2013-07-30 20:25:53 +0000387 {
388 file_type Type = (Info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
389 ? file_type::directory_file
390 : file_type::regular_file;
391 Result =
392 file_status(Type, Info.ftLastWriteTime.dwHighDateTime,
393 Info.ftLastWriteTime.dwLowDateTime,
394 Info.dwVolumeSerialNumber, Info.nFileSizeHigh,
395 Info.nFileSizeLow, Info.nFileIndexHigh, Info.nFileIndexLow);
Rafael Espindola03bddfe2014-05-31 01:37:45 +0000396 return error_code();
Rafael Espindolaa5932af2013-07-30 20:25:53 +0000397 }
Rafael Espindola77021c92013-07-16 03:20:13 +0000398
399handle_status_error:
Rafael Espindolaa813d602014-06-11 03:58:34 +0000400 DWORD LastError = ::GetLastError();
401 if (LastError == ERROR_FILE_NOT_FOUND ||
402 LastError == ERROR_PATH_NOT_FOUND)
Rafael Espindola77021c92013-07-16 03:20:13 +0000403 Result = file_status(file_type::file_not_found);
Rafael Espindolaa813d602014-06-11 03:58:34 +0000404 else if (LastError == ERROR_SHARING_VIOLATION)
Rafael Espindola77021c92013-07-16 03:20:13 +0000405 Result = file_status(file_type::type_unknown);
Rafael Espindola107b74c2013-07-31 00:10:25 +0000406 else
Rafael Espindola77021c92013-07-16 03:20:13 +0000407 Result = file_status(file_type::status_error);
Rafael Espindolaa813d602014-06-11 03:58:34 +0000408 return windows_error(LastError);
Rafael Espindola77021c92013-07-16 03:20:13 +0000409}
410
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000411error_code status(const Twine &path, file_status &result) {
412 SmallString<128> path_storage;
413 SmallVector<wchar_t, 128> path_utf16;
414
NAKAMURA Takumia3d47492011-03-16 02:53:32 +0000415 StringRef path8 = path.toStringRef(path_storage);
Benjamin Kramer58994ec2011-08-20 21:36:38 +0000416 if (isReservedName(path8)) {
NAKAMURA Takumia3d47492011-03-16 02:53:32 +0000417 result = file_status(file_type::character_file);
Rafael Espindola03bddfe2014-05-31 01:37:45 +0000418 return error_code();
NAKAMURA Takumia3d47492011-03-16 02:53:32 +0000419 }
420
Michael J. Spencer203d7802011-12-12 06:04:28 +0000421 if (error_code ec = UTF8ToUTF16(path8, path_utf16))
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000422 return ec;
423
424 DWORD attr = ::GetFileAttributesW(path_utf16.begin());
425 if (attr == INVALID_FILE_ATTRIBUTES)
Rafael Espindola77021c92013-07-16 03:20:13 +0000426 return getStatus(INVALID_HANDLE_VALUE, result);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000427
428 // Handle reparse points.
429 if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
Michael J. Spencer513f1b62011-12-12 06:03:33 +0000430 ScopedFileHandle h(
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000431 ::CreateFileW(path_utf16.begin(),
432 0, // Attributes only.
433 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
434 NULL,
435 OPEN_EXISTING,
436 FILE_FLAG_BACKUP_SEMANTICS,
437 0));
Michael J. Spencer513f1b62011-12-12 06:03:33 +0000438 if (!h)
Rafael Espindola77021c92013-07-16 03:20:13 +0000439 return getStatus(INVALID_HANDLE_VALUE, result);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000440 }
441
Rafael Espindolaa5932af2013-07-30 20:25:53 +0000442 ScopedFileHandle h(
443 ::CreateFileW(path_utf16.begin(), 0, // Attributes only.
Michael J. Spencer203d7802011-12-12 06:04:28 +0000444 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
Rafael Espindolaa5932af2013-07-30 20:25:53 +0000445 NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0));
Michael J. Spencer203d7802011-12-12 06:04:28 +0000446 if (!h)
Rafael Espindola77021c92013-07-16 03:20:13 +0000447 return getStatus(INVALID_HANDLE_VALUE, result);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000448
Rafael Espindola77021c92013-07-16 03:20:13 +0000449 return getStatus(h, result);
Rafael Espindola77021c92013-07-16 03:20:13 +0000450}
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000451
Rafael Espindola77021c92013-07-16 03:20:13 +0000452error_code status(int FD, file_status &Result) {
453 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
454 return getStatus(FileHandle, Result);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000455}
456
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000457error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
458 ULARGE_INTEGER UI;
459 UI.QuadPart = Time.toWin32Time();
460 FILETIME FT;
461 FT.dwLowDateTime = UI.LowPart;
462 FT.dwHighDateTime = UI.HighPart;
463 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
464 if (!SetFileTime(FileHandle, NULL, &FT, &FT))
465 return windows_error(::GetLastError());
Rafael Espindola03bddfe2014-05-31 01:37:45 +0000466 return error_code();
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000467}
Nick Kledzik18497e92012-06-20 00:28:54 +0000468
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000469error_code mapped_file_region::init(int FD, bool CloseFD, uint64_t Offset) {
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000470 FileDescriptor = FD;
471 // Make sure that the requested size fits within SIZE_T.
472 if (Size > std::numeric_limits<SIZE_T>::max()) {
Michael J. Spencerd932d412013-03-15 19:25:47 +0000473 if (FileDescriptor) {
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000474 if (CloseFD)
475 _close(FileDescriptor);
Michael J. Spencerd932d412013-03-15 19:25:47 +0000476 } else
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000477 ::CloseHandle(FileHandle);
Rafael Espindolaed6882b2014-06-12 11:58:49 +0000478 return std::make_error_code(std::errc::invalid_argument);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000479 }
480
481 DWORD flprotect;
482 switch (Mode) {
483 case readonly: flprotect = PAGE_READONLY; break;
484 case readwrite: flprotect = PAGE_READWRITE; break;
485 case priv: flprotect = PAGE_WRITECOPY; break;
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000486 }
487
David Majnemer17a44962013-10-07 09:52:36 +0000488 FileMappingHandle =
489 ::CreateFileMappingW(FileHandle, 0, flprotect,
490 (Offset + Size) >> 32,
491 (Offset + Size) & 0xffffffff,
492 0);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000493 if (FileMappingHandle == NULL) {
494 error_code ec = windows_error(GetLastError());
Michael J. Spencerd932d412013-03-15 19:25:47 +0000495 if (FileDescriptor) {
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000496 if (CloseFD)
497 _close(FileDescriptor);
Michael J. Spencerd932d412013-03-15 19:25:47 +0000498 } else
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000499 ::CloseHandle(FileHandle);
500 return ec;
501 }
502
503 DWORD dwDesiredAccess;
504 switch (Mode) {
505 case readonly: dwDesiredAccess = FILE_MAP_READ; break;
506 case readwrite: dwDesiredAccess = FILE_MAP_WRITE; break;
507 case priv: dwDesiredAccess = FILE_MAP_COPY; break;
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000508 }
509 Mapping = ::MapViewOfFile(FileMappingHandle,
510 dwDesiredAccess,
511 Offset >> 32,
512 Offset & 0xffffffff,
513 Size);
514 if (Mapping == NULL) {
515 error_code ec = windows_error(GetLastError());
516 ::CloseHandle(FileMappingHandle);
Michael J. Spencerd932d412013-03-15 19:25:47 +0000517 if (FileDescriptor) {
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000518 if (CloseFD)
519 _close(FileDescriptor);
Michael J. Spencerd932d412013-03-15 19:25:47 +0000520 } else
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000521 ::CloseHandle(FileHandle);
522 return ec;
523 }
524
525 if (Size == 0) {
526 MEMORY_BASIC_INFORMATION mbi;
527 SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));
528 if (Result == 0) {
529 error_code ec = windows_error(GetLastError());
530 ::UnmapViewOfFile(Mapping);
531 ::CloseHandle(FileMappingHandle);
Michael J. Spencerd932d412013-03-15 19:25:47 +0000532 if (FileDescriptor) {
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000533 if (CloseFD)
534 _close(FileDescriptor);
Michael J. Spencerd932d412013-03-15 19:25:47 +0000535 } else
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000536 ::CloseHandle(FileHandle);
537 return ec;
538 }
539 Size = mbi.RegionSize;
540 }
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000541
542 // Close all the handles except for the view. It will keep the other handles
543 // alive.
544 ::CloseHandle(FileMappingHandle);
Michael J. Spencerd932d412013-03-15 19:25:47 +0000545 if (FileDescriptor) {
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000546 if (CloseFD)
547 _close(FileDescriptor); // Also closes FileHandle.
Michael J. Spencerd932d412013-03-15 19:25:47 +0000548 } else
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000549 ::CloseHandle(FileHandle);
Rafael Espindola03bddfe2014-05-31 01:37:45 +0000550 return error_code();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000551}
552
553mapped_file_region::mapped_file_region(const Twine &path,
554 mapmode mode,
555 uint64_t length,
556 uint64_t offset,
NAKAMURA Takumiedf76152013-08-22 15:14:45 +0000557 error_code &ec)
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000558 : Mode(mode)
559 , Size(length)
560 , Mapping()
561 , FileDescriptor()
562 , FileHandle(INVALID_HANDLE_VALUE)
563 , FileMappingHandle() {
564 SmallString<128> path_storage;
565 SmallVector<wchar_t, 128> path_utf16;
566
567 // Convert path to UTF-16.
Nico Webereada11b2012-09-25 05:24:16 +0000568 if ((ec = UTF8ToUTF16(path.toStringRef(path_storage), path_utf16)))
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000569 return;
570
571 // Get file handle for creating a file mapping.
572 FileHandle = ::CreateFileW(c_str(path_utf16),
573 Mode == readonly ? GENERIC_READ
574 : GENERIC_READ | GENERIC_WRITE,
575 Mode == readonly ? FILE_SHARE_READ
576 : 0,
577 0,
578 Mode == readonly ? OPEN_EXISTING
579 : OPEN_ALWAYS,
580 Mode == readonly ? FILE_ATTRIBUTE_READONLY
581 : FILE_ATTRIBUTE_NORMAL,
582 0);
583 if (FileHandle == INVALID_HANDLE_VALUE) {
584 ec = windows_error(::GetLastError());
585 return;
586 }
587
588 FileDescriptor = 0;
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000589 ec = init(FileDescriptor, true, offset);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000590 if (ec) {
591 Mapping = FileMappingHandle = 0;
592 FileHandle = INVALID_HANDLE_VALUE;
593 FileDescriptor = 0;
594 }
595}
596
597mapped_file_region::mapped_file_region(int fd,
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000598 bool closefd,
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000599 mapmode mode,
600 uint64_t length,
601 uint64_t offset,
602 error_code &ec)
603 : Mode(mode)
604 , Size(length)
605 , Mapping()
606 , FileDescriptor(fd)
607 , FileHandle(INVALID_HANDLE_VALUE)
608 , FileMappingHandle() {
609 FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
610 if (FileHandle == INVALID_HANDLE_VALUE) {
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000611 if (closefd)
612 _close(FileDescriptor);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000613 FileDescriptor = 0;
Rafael Espindolaed6882b2014-06-12 11:58:49 +0000614 ec = std::make_error_code(std::errc::bad_file_descriptor);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000615 return;
616 }
617
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000618 ec = init(FileDescriptor, closefd, offset);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000619 if (ec) {
620 Mapping = FileMappingHandle = 0;
621 FileHandle = INVALID_HANDLE_VALUE;
622 FileDescriptor = 0;
623 }
624}
625
626mapped_file_region::~mapped_file_region() {
627 if (Mapping)
628 ::UnmapViewOfFile(Mapping);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000629}
630
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000631mapped_file_region::mapped_file_region(mapped_file_region &&other)
632 : Mode(other.Mode)
633 , Size(other.Size)
634 , Mapping(other.Mapping)
635 , FileDescriptor(other.FileDescriptor)
636 , FileHandle(other.FileHandle)
637 , FileMappingHandle(other.FileMappingHandle) {
638 other.Mapping = other.FileMappingHandle = 0;
639 other.FileHandle = INVALID_HANDLE_VALUE;
640 other.FileDescriptor = 0;
641}
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000642
643mapped_file_region::mapmode mapped_file_region::flags() const {
644 assert(Mapping && "Mapping failed but used anyway!");
645 return Mode;
646}
647
648uint64_t mapped_file_region::size() const {
649 assert(Mapping && "Mapping failed but used anyway!");
650 return Size;
651}
652
653char *mapped_file_region::data() const {
Alp Tokerf907b892013-12-05 05:44:44 +0000654 assert(Mode != readonly && "Cannot get non-const data for readonly mapping!");
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000655 assert(Mapping && "Mapping failed but used anyway!");
656 return reinterpret_cast<char*>(Mapping);
657}
658
659const char *mapped_file_region::const_data() const {
660 assert(Mapping && "Mapping failed but used anyway!");
661 return reinterpret_cast<const char*>(Mapping);
662}
663
664int mapped_file_region::alignment() {
665 SYSTEM_INFO SysInfo;
666 ::GetSystemInfo(&SysInfo);
667 return SysInfo.dwAllocationGranularity;
668}
669
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000670error_code detail::directory_iterator_construct(detail::DirIterState &it,
671 StringRef path){
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000672 SmallVector<wchar_t, 128> path_utf16;
673
674 if (error_code ec = UTF8ToUTF16(path,
675 path_utf16))
676 return ec;
677
678 // Convert path to the format that Windows is happy with.
679 if (path_utf16.size() > 0 &&
680 !is_separator(path_utf16[path.size() - 1]) &&
681 path_utf16[path.size() - 1] != L':') {
682 path_utf16.push_back(L'\\');
683 path_utf16.push_back(L'*');
684 } else {
685 path_utf16.push_back(L'*');
686 }
687
688 // Get the first directory entry.
689 WIN32_FIND_DATAW FirstFind;
Michael J. Spencer751e9aa2010-12-09 17:37:18 +0000690 ScopedFindHandle FindHandle(::FindFirstFileW(c_str(path_utf16), &FirstFind));
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000691 if (!FindHandle)
692 return windows_error(::GetLastError());
693
Michael J. Spencer98879d72011-01-05 16:39:30 +0000694 size_t FilenameLen = ::wcslen(FirstFind.cFileName);
695 while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
696 (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
697 FirstFind.cFileName[1] == L'.'))
698 if (!::FindNextFileW(FindHandle, &FirstFind)) {
Rafael Espindolaa813d602014-06-11 03:58:34 +0000699 DWORD LastError = ::GetLastError();
Michael J. Spencer98879d72011-01-05 16:39:30 +0000700 // Check for end.
Rafael Espindolaa813d602014-06-11 03:58:34 +0000701 if (LastError == ERROR_NO_MORE_FILES)
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000702 return detail::directory_iterator_destruct(it);
Rafael Espindolaa813d602014-06-11 03:58:34 +0000703 return windows_error(LastError);
Michael J. Spencer98879d72011-01-05 16:39:30 +0000704 } else
705 FilenameLen = ::wcslen(FirstFind.cFileName);
706
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000707 // Construct the current directory entry.
Michael J. Spencer98879d72011-01-05 16:39:30 +0000708 SmallString<128> directory_entry_name_utf8;
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000709 if (error_code ec = UTF16ToUTF8(FirstFind.cFileName,
710 ::wcslen(FirstFind.cFileName),
Michael J. Spencer98879d72011-01-05 16:39:30 +0000711 directory_entry_name_utf8))
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000712 return ec;
713
714 it.IterationHandle = intptr_t(FindHandle.take());
Michael J. Spencer98879d72011-01-05 16:39:30 +0000715 SmallString<128> directory_entry_path(path);
716 path::append(directory_entry_path, directory_entry_name_utf8.str());
717 it.CurrentEntry = directory_entry(directory_entry_path.str());
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000718
Rafael Espindola03bddfe2014-05-31 01:37:45 +0000719 return error_code();
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000720}
721
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000722error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000723 if (it.IterationHandle != 0)
724 // Closes the handle if it's valid.
725 ScopedFindHandle close(HANDLE(it.IterationHandle));
726 it.IterationHandle = 0;
727 it.CurrentEntry = directory_entry();
Rafael Espindola03bddfe2014-05-31 01:37:45 +0000728 return error_code();
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000729}
730
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000731error_code detail::directory_iterator_increment(detail::DirIterState &it) {
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000732 WIN32_FIND_DATAW FindData;
733 if (!::FindNextFileW(HANDLE(it.IterationHandle), &FindData)) {
Rafael Espindolaa813d602014-06-11 03:58:34 +0000734 DWORD LastError = ::GetLastError();
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000735 // Check for end.
Rafael Espindolaa813d602014-06-11 03:58:34 +0000736 if (LastError == ERROR_NO_MORE_FILES)
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000737 return detail::directory_iterator_destruct(it);
Rafael Espindolaa813d602014-06-11 03:58:34 +0000738 return windows_error(LastError);
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000739 }
740
Michael J. Spencer98879d72011-01-05 16:39:30 +0000741 size_t FilenameLen = ::wcslen(FindData.cFileName);
742 if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
743 (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
744 FindData.cFileName[1] == L'.'))
745 return directory_iterator_increment(it);
746
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000747 SmallString<128> directory_entry_path_utf8;
748 if (error_code ec = UTF16ToUTF8(FindData.cFileName,
749 ::wcslen(FindData.cFileName),
750 directory_entry_path_utf8))
751 return ec;
752
753 it.CurrentEntry.replace_filename(Twine(directory_entry_path_utf8));
Rafael Espindola03bddfe2014-05-31 01:37:45 +0000754 return error_code();
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000755}
756
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000757error_code openFileForRead(const Twine &Name, int &ResultFD) {
758 SmallString<128> PathStorage;
759 SmallVector<wchar_t, 128> PathUTF16;
Nick Kledzik18497e92012-06-20 00:28:54 +0000760
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000761 if (error_code EC = UTF8ToUTF16(Name.toStringRef(PathStorage),
762 PathUTF16))
763 return EC;
764
765 HANDLE H = ::CreateFileW(PathUTF16.begin(), GENERIC_READ,
Rafael Espindola16431fe2013-07-17 19:44:07 +0000766 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000767 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
768 if (H == INVALID_HANDLE_VALUE) {
Rafael Espindolaa813d602014-06-11 03:58:34 +0000769 DWORD LastError = ::GetLastError();
770 error_code EC = windows_error(LastError);
Rafael Espindola331aeba2013-07-17 19:58:28 +0000771 // Provide a better error message when trying to open directories.
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000772 // This only runs if we failed to open the file, so there is probably
773 // no performances issues.
Rafael Espindolaa813d602014-06-11 03:58:34 +0000774 if (LastError != ERROR_ACCESS_DENIED)
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000775 return EC;
776 if (is_directory(Name))
Rafael Espindolaed6882b2014-06-12 11:58:49 +0000777 return std::make_error_code(std::errc::is_a_directory);
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000778 return EC;
779 }
780
781 int FD = ::_open_osfhandle(intptr_t(H), 0);
782 if (FD == -1) {
783 ::CloseHandle(H);
Rafael Espindolaa813d602014-06-11 03:58:34 +0000784 return windows_error(ERROR_INVALID_HANDLE);
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000785 }
786
787 ResultFD = FD;
Rafael Espindola03bddfe2014-05-31 01:37:45 +0000788 return error_code();
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000789}
Nick Kledzik18497e92012-06-20 00:28:54 +0000790
Rafael Espindola67080ce2013-07-19 15:02:03 +0000791error_code openFileForWrite(const Twine &Name, int &ResultFD,
792 sys::fs::OpenFlags Flags, unsigned Mode) {
793 // Verify that we don't have both "append" and "excl".
794 assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
795 "Cannot specify both 'excl' and 'append' file creation flags!");
796
797 SmallString<128> PathStorage;
798 SmallVector<wchar_t, 128> PathUTF16;
799
800 if (error_code EC = UTF8ToUTF16(Name.toStringRef(PathStorage),
801 PathUTF16))
802 return EC;
803
804 DWORD CreationDisposition;
805 if (Flags & F_Excl)
806 CreationDisposition = CREATE_NEW;
NAKAMURA Takumiedf76152013-08-22 15:14:45 +0000807 else if (Flags & F_Append)
Rafael Espindola67080ce2013-07-19 15:02:03 +0000808 CreationDisposition = OPEN_ALWAYS;
809 else
810 CreationDisposition = CREATE_ALWAYS;
811
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000812 DWORD Access = GENERIC_WRITE;
813 if (Flags & F_RW)
814 Access |= GENERIC_READ;
815
816 HANDLE H = ::CreateFileW(PathUTF16.begin(), Access,
Rafael Espindola67080ce2013-07-19 15:02:03 +0000817 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
818 CreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL);
819
820 if (H == INVALID_HANDLE_VALUE) {
Rafael Espindolaa813d602014-06-11 03:58:34 +0000821 DWORD LastError = ::GetLastError();
822 error_code EC = windows_error(LastError);
Rafael Espindola67080ce2013-07-19 15:02:03 +0000823 // Provide a better error message when trying to open directories.
824 // This only runs if we failed to open the file, so there is probably
825 // no performances issues.
Rafael Espindolaa813d602014-06-11 03:58:34 +0000826 if (LastError != ERROR_ACCESS_DENIED)
Rafael Espindola67080ce2013-07-19 15:02:03 +0000827 return EC;
828 if (is_directory(Name))
Rafael Espindolaed6882b2014-06-12 11:58:49 +0000829 return std::make_error_code(std::errc::is_a_directory);
Rafael Espindola67080ce2013-07-19 15:02:03 +0000830 return EC;
831 }
832
833 int OpenFlags = 0;
834 if (Flags & F_Append)
835 OpenFlags |= _O_APPEND;
836
Rafael Espindola90c7f1c2014-02-24 18:20:12 +0000837 if (Flags & F_Text)
Rafael Espindola67080ce2013-07-19 15:02:03 +0000838 OpenFlags |= _O_TEXT;
839
840 int FD = ::_open_osfhandle(intptr_t(H), OpenFlags);
841 if (FD == -1) {
842 ::CloseHandle(H);
Rafael Espindolaa813d602014-06-11 03:58:34 +0000843 return windows_error(ERROR_INVALID_HANDLE);
Rafael Espindola67080ce2013-07-19 15:02:03 +0000844 }
845
846 ResultFD = FD;
Rafael Espindola03bddfe2014-05-31 01:37:45 +0000847 return error_code();
Rafael Espindola67080ce2013-07-19 15:02:03 +0000848}
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000849} // end namespace fs
Rui Ueyama471d0c52013-09-10 19:45:51 +0000850
Peter Collingbournef7d41012014-01-31 23:46:06 +0000851namespace path {
852
853bool home_directory(SmallVectorImpl<char> &result) {
854 wchar_t Path[MAX_PATH];
855 if (::SHGetFolderPathW(0, CSIDL_APPDATA | CSIDL_FLAG_CREATE, 0,
Peter Collingbournead141ab2014-02-01 02:42:20 +0000856 /*SHGFP_TYPE_CURRENT*/0, Path) != S_OK)
Peter Collingbournef7d41012014-01-31 23:46:06 +0000857 return false;
858
859 if (UTF16ToUTF8(Path, ::wcslen(Path), result))
860 return false;
861
862 return true;
863}
864
865} // end namespace path
866
Rui Ueyama471d0c52013-09-10 19:45:51 +0000867namespace windows {
Rafael Espindola0a5f9cf2014-06-12 14:11:22 +0000868std::error_code UTF8ToUTF16(llvm::StringRef utf8,
Rui Ueyama471d0c52013-09-10 19:45:51 +0000869 llvm::SmallVectorImpl<wchar_t> &utf16) {
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000870 if (!utf8.empty()) {
871 int len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
872 utf8.size(), utf16.begin(), 0);
Rui Ueyama471d0c52013-09-10 19:45:51 +0000873
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000874 if (len == 0)
Rafael Espindolaa813d602014-06-11 03:58:34 +0000875 return windows_error(::GetLastError());
Rui Ueyama471d0c52013-09-10 19:45:51 +0000876
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000877 utf16.reserve(len + 1);
878 utf16.set_size(len);
Rui Ueyama471d0c52013-09-10 19:45:51 +0000879
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000880 len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
881 utf8.size(), utf16.begin(), utf16.size());
Rui Ueyama471d0c52013-09-10 19:45:51 +0000882
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000883 if (len == 0)
Rafael Espindolaa813d602014-06-11 03:58:34 +0000884 return windows_error(::GetLastError());
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000885 }
Rui Ueyama471d0c52013-09-10 19:45:51 +0000886
887 // Make utf16 null terminated.
888 utf16.push_back(0);
889 utf16.pop_back();
890
Rafael Espindola0a5f9cf2014-06-12 14:11:22 +0000891 return std::error_code();
Rui Ueyama471d0c52013-09-10 19:45:51 +0000892}
893
Rafael Espindola0a5f9cf2014-06-12 14:11:22 +0000894std::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
Rui Ueyama471d0c52013-09-10 19:45:51 +0000895 llvm::SmallVectorImpl<char> &utf8) {
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000896 if (utf16_len) {
897 // Get length.
898 int len = ::WideCharToMultiByte(CP_UTF8, 0, utf16, utf16_len, utf8.begin(),
899 0, NULL, NULL);
Rui Ueyama471d0c52013-09-10 19:45:51 +0000900
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000901 if (len == 0)
Rafael Espindolaa813d602014-06-11 03:58:34 +0000902 return windows_error(::GetLastError());
Rui Ueyama471d0c52013-09-10 19:45:51 +0000903
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000904 utf8.reserve(len);
905 utf8.set_size(len);
Rui Ueyama471d0c52013-09-10 19:45:51 +0000906
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000907 // Now do the actual conversion.
908 len = ::WideCharToMultiByte(CP_UTF8, 0, utf16, utf16_len, utf8.data(),
909 utf8.size(), NULL, NULL);
Rui Ueyama471d0c52013-09-10 19:45:51 +0000910
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000911 if (len == 0)
Rafael Espindolaa813d602014-06-11 03:58:34 +0000912 return windows_error(::GetLastError());
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000913 }
Rui Ueyama471d0c52013-09-10 19:45:51 +0000914
915 // Make utf8 null terminated.
916 utf8.push_back(0);
917 utf8.pop_back();
918
Rafael Espindola0a5f9cf2014-06-12 14:11:22 +0000919 return std::error_code();
Rui Ueyama471d0c52013-09-10 19:45:51 +0000920}
921} // end namespace windows
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000922} // end namespace sys
923} // end namespace llvm