blob: bff82141b343aecfa0b49b4a2dc51651522cc837 [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 Espindolab4ad29b2014-06-13 02:36:09 +000048static std::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 Espindola37b012d2014-02-23 15:16:03 +000052static bool is_separator(const wchar_t value) {
53 switch (value) {
54 case L'\\':
55 case L'/':
56 return true;
57 default:
58 return false;
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +000059 }
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +000060}
61
Michael J. Spencerebad2f92010-11-29 22:28:51 +000062namespace llvm {
63namespace sys {
Michael J. Spencer20daa282010-12-07 01:22:31 +000064namespace fs {
Michael J. Spencerebad2f92010-11-29 22:28:51 +000065
Rafael Espindolae03dfd92013-06-26 05:01:35 +000066std::string getMainExecutable(const char *argv0, void *MainExecAddr) {
David Majnemer17a44962013-10-07 09:52:36 +000067 SmallVector<wchar_t, MAX_PATH> PathName;
68 DWORD Size = ::GetModuleFileNameW(NULL, PathName.data(), PathName.capacity());
69
70 // A zero return value indicates a failure other than insufficient space.
71 if (Size == 0)
72 return "";
73
74 // Insufficient space is determined by a return value equal to the size of
75 // the buffer passed in.
76 if (Size == PathName.capacity())
77 return "";
78
79 // On success, GetModuleFileNameW returns the number of characters written to
80 // the buffer not including the NULL terminator.
81 PathName.set_size(Size);
82
83 // Convert the result from UTF-16 to UTF-8.
84 SmallVector<char, MAX_PATH> PathNameUTF8;
85 if (UTF16ToUTF8(PathName.data(), PathName.size(), PathNameUTF8))
86 return "";
87
88 return std::string(PathNameUTF8.data());
Rafael Espindolae03dfd92013-06-26 05:01:35 +000089}
90
Rafael Espindolad1230992013-07-29 21:55:38 +000091UniqueID file_status::getUniqueID() const {
Rafael Espindola7f822a92013-07-29 21:26:49 +000092 // The file is uniquely identified by the volume serial number along
93 // with the 64-bit file identifier.
94 uint64_t FileID = (static_cast<uint64_t>(FileIndexHigh) << 32ULL) |
95 static_cast<uint64_t>(FileIndexLow);
96
97 return UniqueID(VolumeSerialNumber, FileID);
98}
Rafael Espindolae03dfd92013-06-26 05:01:35 +000099
Rafael Espindolabe3ede72013-06-20 21:51:49 +0000100TimeValue file_status::getLastModificationTime() const {
Rafael Espindoladb5d8fe2013-06-20 18:42:04 +0000101 ULARGE_INTEGER UI;
102 UI.LowPart = LastWriteTimeLow;
103 UI.HighPart = LastWriteTimeHigh;
104
105 TimeValue Ret;
106 Ret.fromWin32Time(UI.QuadPart);
107 return Ret;
108}
109
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000110std::error_code current_path(SmallVectorImpl<char> &result) {
David Majnemer61eae2e2013-10-07 01:00:07 +0000111 SmallVector<wchar_t, MAX_PATH> cur_path;
112 DWORD len = MAX_PATH;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000113
David Majnemer61eae2e2013-10-07 01:00:07 +0000114 do {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000115 cur_path.reserve(len);
David Majnemer61eae2e2013-10-07 01:00:07 +0000116 len = ::GetCurrentDirectoryW(cur_path.capacity(), cur_path.data());
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000117
David Majnemer61eae2e2013-10-07 01:00:07 +0000118 // A zero return value indicates a failure other than insufficient space.
119 if (len == 0)
120 return windows_error(::GetLastError());
121
122 // If there's insufficient space, the len returned is larger than the len
123 // given.
124 } while (len > cur_path.capacity());
125
126 // On success, GetCurrentDirectoryW returns the number of characters not
127 // including the null-terminator.
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000128 cur_path.set_size(len);
Aaron Ballmanb16cf532013-08-16 17:53:28 +0000129 return UTF16ToUTF8(cur_path.begin(), cur_path.size(), result);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000130}
131
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000132std::error_code create_directory(const Twine &path, bool IgnoreExisting) {
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000133 SmallString<128> path_storage;
134 SmallVector<wchar_t, 128> path_utf16;
135
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000136 if (std::error_code ec =
137 UTF8ToUTF16(path.toStringRef(path_storage), path_utf16))
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000138 return ec;
139
140 if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {
Rafael Espindolaa813d602014-06-11 03:58:34 +0000141 DWORD LastError = ::GetLastError();
142 if (LastError != ERROR_ALREADY_EXISTS || !IgnoreExisting)
143 return windows_error(LastError);
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000144 }
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000145
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000146 return std::error_code();
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000147}
148
Rafael Espindola83f858e2014-03-11 18:40:24 +0000149// We can't use symbolic links for windows.
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000150std::error_code create_link(const Twine &to, const Twine &from) {
Michael J. Spencere0c45602010-12-03 05:58:41 +0000151 // Get arguments.
152 SmallString<128> from_storage;
153 SmallString<128> to_storage;
154 StringRef f = from.toStringRef(from_storage);
155 StringRef t = to.toStringRef(to_storage);
156
157 // Convert to utf-16.
158 SmallVector<wchar_t, 128> wide_from;
159 SmallVector<wchar_t, 128> wide_to;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000160 if (std::error_code ec = UTF8ToUTF16(f, wide_from))
161 return ec;
162 if (std::error_code ec = UTF8ToUTF16(t, wide_to))
163 return ec;
Michael J. Spencere0c45602010-12-03 05:58:41 +0000164
165 if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
Michael J. Spencer66a1f862010-12-04 18:45:32 +0000166 return windows_error(::GetLastError());
Michael J. Spencere0c45602010-12-03 05:58:41 +0000167
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000168 return std::error_code();
Michael J. Spencere0c45602010-12-03 05:58:41 +0000169}
170
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000171std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000172 SmallString<128> path_storage;
173 SmallVector<wchar_t, 128> path_utf16;
174
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000175 file_status ST;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000176 if (std::error_code EC = status(path, ST)) {
Rafael Espindola2a826e42014-06-13 17:20:48 +0000177 if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000178 return EC;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000179 return std::error_code();
Rafael Espindola107b74c2013-07-31 00:10:25 +0000180 }
Michael J. Spencer153749b2011-01-05 16:39:22 +0000181
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000182 if (std::error_code ec =
183 UTF8ToUTF16(path.toStringRef(path_storage), path_utf16))
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000184 return ec;
185
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000186 if (ST.type() == file_type::directory_file) {
Michael J. Spencer153749b2011-01-05 16:39:22 +0000187 if (!::RemoveDirectoryW(c_str(path_utf16))) {
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000188 std::error_code EC = windows_error(::GetLastError());
Rafael Espindola2a826e42014-06-13 17:20:48 +0000189 if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000190 return EC;
191 }
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000192 return std::error_code();
Michael J. Spencer153749b2011-01-05 16:39:22 +0000193 }
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000194 if (!::DeleteFileW(c_str(path_utf16))) {
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000195 std::error_code EC = windows_error(::GetLastError());
Rafael Espindola2a826e42014-06-13 17:20:48 +0000196 if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000197 return EC;
198 }
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000199 return std::error_code();
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000200}
201
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000202std::error_code rename(const Twine &from, const Twine &to) {
Michael J. Spencer409f5562010-12-03 17:53:55 +0000203 // Get arguments.
204 SmallString<128> from_storage;
205 SmallString<128> to_storage;
206 StringRef f = from.toStringRef(from_storage);
207 StringRef t = to.toStringRef(to_storage);
208
209 // Convert to utf-16.
210 SmallVector<wchar_t, 128> wide_from;
211 SmallVector<wchar_t, 128> wide_to;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000212 if (std::error_code ec = UTF8ToUTF16(f, wide_from))
213 return ec;
214 if (std::error_code ec = UTF8ToUTF16(t, wide_to))
215 return ec;
Michael J. Spencer409f5562010-12-03 17:53:55 +0000216
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000217 std::error_code ec = std::error_code();
NAKAMURA Takumi3b7f9952012-05-08 14:31:46 +0000218 for (int i = 0; i < 2000; i++) {
219 if (::MoveFileExW(wide_from.begin(), wide_to.begin(),
220 MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING))
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000221 return std::error_code();
Rafael Espindolaa813d602014-06-11 03:58:34 +0000222 DWORD LastError = ::GetLastError();
223 if (LastError != ERROR_ACCESS_DENIED)
NAKAMURA Takumi3b7f9952012-05-08 14:31:46 +0000224 break;
225 // Retry MoveFile() at ACCESS_DENIED.
226 // System scanners (eg. indexer) might open the source file when
227 // It is written and closed.
228 ::Sleep(1);
229 }
Michael J. Spencer409f5562010-12-03 17:53:55 +0000230
NAKAMURA Takumi3b7f9952012-05-08 14:31:46 +0000231 return ec;
Michael J. Spencer409f5562010-12-03 17:53:55 +0000232}
233
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000234std::error_code resize_file(const Twine &path, uint64_t size) {
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000235 SmallString<128> path_storage;
236 SmallVector<wchar_t, 128> path_utf16;
237
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000238 if (std::error_code ec =
239 UTF8ToUTF16(path.toStringRef(path_storage), path_utf16))
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000240 return ec;
241
Michael J. Spencer20abb202012-12-03 22:09:31 +0000242 int fd = ::_wopen(path_utf16.begin(), O_BINARY | _O_RDWR, S_IWRITE);
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000243 if (fd == -1)
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000244 return std::error_code(errno, std::generic_category());
Michael J. Spencerca242f22010-12-03 18:48:56 +0000245#ifdef HAVE__CHSIZE_S
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000246 errno_t error = ::_chsize_s(fd, size);
Michael J. Spencerca242f22010-12-03 18:48:56 +0000247#else
248 errno_t error = ::_chsize(fd, size);
249#endif
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000250 ::close(fd);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000251 return std::error_code(error, std::generic_category());
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000252}
253
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000254std::error_code exists(const Twine &path, bool &result) {
Michael J. Spencer45710402010-12-03 01:21:28 +0000255 SmallString<128> path_storage;
256 SmallVector<wchar_t, 128> path_utf16;
257
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000258 if (std::error_code ec =
259 UTF8ToUTF16(path.toStringRef(path_storage), path_utf16))
Michael J. Spencer45710402010-12-03 01:21:28 +0000260 return ec;
261
262 DWORD attributes = ::GetFileAttributesW(path_utf16.begin());
263
264 if (attributes == INVALID_FILE_ATTRIBUTES) {
265 // See if the file didn't actually exist.
Rafael Espindolaa813d602014-06-11 03:58:34 +0000266 DWORD LastError = ::GetLastError();
267 if (LastError != ERROR_FILE_NOT_FOUND &&
268 LastError != ERROR_PATH_NOT_FOUND)
269 return windows_error(LastError);
Michael J. Spencer45710402010-12-03 01:21:28 +0000270 result = false;
271 } else
272 result = true;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000273 return std::error_code();
Michael J. Spencer45710402010-12-03 01:21:28 +0000274}
275
Rafael Espindolaa1280c12013-06-18 20:56:38 +0000276bool can_write(const Twine &Path) {
277 // FIXME: take security attributes into account.
278 SmallString<128> PathStorage;
279 SmallVector<wchar_t, 128> PathUtf16;
280
281 if (UTF8ToUTF16(Path.toStringRef(PathStorage), PathUtf16))
282 return false;
283
284 DWORD Attr = ::GetFileAttributesW(PathUtf16.begin());
285 return (Attr != INVALID_FILE_ATTRIBUTES) && !(Attr & FILE_ATTRIBUTE_READONLY);
286}
287
Rafael Espindolab0a5c962013-06-14 19:38:45 +0000288bool can_execute(const Twine &Path) {
289 SmallString<128> PathStorage;
290 SmallVector<wchar_t, 128> PathUtf16;
291
292 if (UTF8ToUTF16(Path.toStringRef(PathStorage), PathUtf16))
293 return false;
294
295 DWORD Attr = ::GetFileAttributesW(PathUtf16.begin());
296 return Attr != INVALID_FILE_ATTRIBUTES;
297}
298
Michael J. Spencer203d7802011-12-12 06:04:28 +0000299bool equivalent(file_status A, file_status B) {
300 assert(status_known(A) && status_known(B));
301 return A.FileIndexHigh == B.FileIndexHigh &&
302 A.FileIndexLow == B.FileIndexLow &&
303 A.FileSizeHigh == B.FileSizeHigh &&
304 A.FileSizeLow == B.FileSizeLow &&
305 A.LastWriteTimeHigh == B.LastWriteTimeHigh &&
306 A.LastWriteTimeLow == B.LastWriteTimeLow &&
307 A.VolumeSerialNumber == B.VolumeSerialNumber;
308}
309
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000310std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
Michael J. Spencer203d7802011-12-12 06:04:28 +0000311 file_status fsA, fsB;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000312 if (std::error_code ec = status(A, fsA))
313 return ec;
314 if (std::error_code ec = status(B, fsB))
315 return ec;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000316 result = equivalent(fsA, fsB);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000317 return std::error_code();
Michael J. Spencer376d3872010-12-03 18:49:13 +0000318}
319
Benjamin Kramer58994ec2011-08-20 21:36:38 +0000320static bool isReservedName(StringRef path) {
321 // This list of reserved names comes from MSDN, at:
322 // http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
323 static const char *sReservedNames[] = { "nul", "con", "prn", "aux",
324 "com1", "com2", "com3", "com4", "com5", "com6",
325 "com7", "com8", "com9", "lpt1", "lpt2", "lpt3",
326 "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9" };
327
328 // First, check to see if this is a device namespace, which always
329 // starts with \\.\, since device namespaces are not legal file paths.
330 if (path.startswith("\\\\.\\"))
331 return true;
332
333 // Then compare against the list of ancient reserved names
Craig Topper58713212013-07-15 04:27:47 +0000334 for (size_t i = 0; i < array_lengthof(sReservedNames); ++i) {
Benjamin Kramer58994ec2011-08-20 21:36:38 +0000335 if (path.equals_lower(sReservedNames[i]))
336 return true;
337 }
338
339 // The path isn't what we consider reserved.
340 return false;
341}
342
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000343static std::error_code getStatus(HANDLE FileHandle, file_status &Result) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000344 if (FileHandle == INVALID_HANDLE_VALUE)
345 goto handle_status_error;
346
NAKAMURA Takumi8b01da42013-07-18 17:00:54 +0000347 switch (::GetFileType(FileHandle)) {
348 default:
Rafael Espindola81177c52013-07-18 18:42:52 +0000349 llvm_unreachable("Don't know anything about this file type");
350 case FILE_TYPE_UNKNOWN: {
351 DWORD Err = ::GetLastError();
352 if (Err != NO_ERROR)
353 return windows_error(Err);
354 Result = file_status(file_type::type_unknown);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000355 return std::error_code();
Rafael Espindola81177c52013-07-18 18:42:52 +0000356 }
NAKAMURA Takumi8b01da42013-07-18 17:00:54 +0000357 case FILE_TYPE_DISK:
358 break;
359 case FILE_TYPE_CHAR:
360 Result = file_status(file_type::character_file);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000361 return std::error_code();
NAKAMURA Takumi8b01da42013-07-18 17:00:54 +0000362 case FILE_TYPE_PIPE:
363 Result = file_status(file_type::fifo_file);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000364 return std::error_code();
NAKAMURA Takumi8b01da42013-07-18 17:00:54 +0000365 }
366
Rafael Espindola77021c92013-07-16 03:20:13 +0000367 BY_HANDLE_FILE_INFORMATION Info;
368 if (!::GetFileInformationByHandle(FileHandle, &Info))
369 goto handle_status_error;
370
Rafael Espindolaa5932af2013-07-30 20:25:53 +0000371 {
372 file_type Type = (Info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
373 ? file_type::directory_file
374 : file_type::regular_file;
375 Result =
376 file_status(Type, Info.ftLastWriteTime.dwHighDateTime,
377 Info.ftLastWriteTime.dwLowDateTime,
378 Info.dwVolumeSerialNumber, Info.nFileSizeHigh,
379 Info.nFileSizeLow, Info.nFileIndexHigh, Info.nFileIndexLow);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000380 return std::error_code();
Rafael Espindolaa5932af2013-07-30 20:25:53 +0000381 }
Rafael Espindola77021c92013-07-16 03:20:13 +0000382
383handle_status_error:
Rafael Espindolaa813d602014-06-11 03:58:34 +0000384 DWORD LastError = ::GetLastError();
385 if (LastError == ERROR_FILE_NOT_FOUND ||
386 LastError == ERROR_PATH_NOT_FOUND)
Rafael Espindola77021c92013-07-16 03:20:13 +0000387 Result = file_status(file_type::file_not_found);
Rafael Espindolaa813d602014-06-11 03:58:34 +0000388 else if (LastError == ERROR_SHARING_VIOLATION)
Rafael Espindola77021c92013-07-16 03:20:13 +0000389 Result = file_status(file_type::type_unknown);
Rafael Espindola107b74c2013-07-31 00:10:25 +0000390 else
Rafael Espindola77021c92013-07-16 03:20:13 +0000391 Result = file_status(file_type::status_error);
Rafael Espindolaa813d602014-06-11 03:58:34 +0000392 return windows_error(LastError);
Rafael Espindola77021c92013-07-16 03:20:13 +0000393}
394
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000395std::error_code status(const Twine &path, file_status &result) {
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000396 SmallString<128> path_storage;
397 SmallVector<wchar_t, 128> path_utf16;
398
NAKAMURA Takumia3d47492011-03-16 02:53:32 +0000399 StringRef path8 = path.toStringRef(path_storage);
Benjamin Kramer58994ec2011-08-20 21:36:38 +0000400 if (isReservedName(path8)) {
NAKAMURA Takumia3d47492011-03-16 02:53:32 +0000401 result = file_status(file_type::character_file);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000402 return std::error_code();
NAKAMURA Takumia3d47492011-03-16 02:53:32 +0000403 }
404
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000405 if (std::error_code ec = UTF8ToUTF16(path8, path_utf16))
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000406 return ec;
407
408 DWORD attr = ::GetFileAttributesW(path_utf16.begin());
409 if (attr == INVALID_FILE_ATTRIBUTES)
Rafael Espindola77021c92013-07-16 03:20:13 +0000410 return getStatus(INVALID_HANDLE_VALUE, result);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000411
412 // Handle reparse points.
413 if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
Michael J. Spencer513f1b62011-12-12 06:03:33 +0000414 ScopedFileHandle h(
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000415 ::CreateFileW(path_utf16.begin(),
416 0, // Attributes only.
417 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
418 NULL,
419 OPEN_EXISTING,
420 FILE_FLAG_BACKUP_SEMANTICS,
421 0));
Michael J. Spencer513f1b62011-12-12 06:03:33 +0000422 if (!h)
Rafael Espindola77021c92013-07-16 03:20:13 +0000423 return getStatus(INVALID_HANDLE_VALUE, result);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000424 }
425
Rafael Espindolaa5932af2013-07-30 20:25:53 +0000426 ScopedFileHandle h(
427 ::CreateFileW(path_utf16.begin(), 0, // Attributes only.
Michael J. Spencer203d7802011-12-12 06:04:28 +0000428 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
Rafael Espindolaa5932af2013-07-30 20:25:53 +0000429 NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0));
Michael J. Spencer203d7802011-12-12 06:04:28 +0000430 if (!h)
Rafael Espindola77021c92013-07-16 03:20:13 +0000431 return getStatus(INVALID_HANDLE_VALUE, result);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000432
Rafael Espindola77021c92013-07-16 03:20:13 +0000433 return getStatus(h, result);
Rafael Espindola77021c92013-07-16 03:20:13 +0000434}
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000435
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000436std::error_code status(int FD, file_status &Result) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000437 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
438 return getStatus(FileHandle, Result);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000439}
440
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000441std::error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000442 ULARGE_INTEGER UI;
443 UI.QuadPart = Time.toWin32Time();
444 FILETIME FT;
445 FT.dwLowDateTime = UI.LowPart;
446 FT.dwHighDateTime = UI.HighPart;
447 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
448 if (!SetFileTime(FileHandle, NULL, &FT, &FT))
449 return windows_error(::GetLastError());
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000450 return std::error_code();
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000451}
Nick Kledzik18497e92012-06-20 00:28:54 +0000452
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000453std::error_code mapped_file_region::init(int FD, bool CloseFD, uint64_t Offset) {
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000454 FileDescriptor = FD;
455 // Make sure that the requested size fits within SIZE_T.
456 if (Size > std::numeric_limits<SIZE_T>::max()) {
Michael J. Spencerd932d412013-03-15 19:25:47 +0000457 if (FileDescriptor) {
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000458 if (CloseFD)
459 _close(FileDescriptor);
Michael J. Spencerd932d412013-03-15 19:25:47 +0000460 } else
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000461 ::CloseHandle(FileHandle);
Rafael Espindola2a826e42014-06-13 17:20:48 +0000462 return make_error_code(errc::invalid_argument);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000463 }
464
465 DWORD flprotect;
466 switch (Mode) {
467 case readonly: flprotect = PAGE_READONLY; break;
468 case readwrite: flprotect = PAGE_READWRITE; break;
469 case priv: flprotect = PAGE_WRITECOPY; break;
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000470 }
471
David Majnemer17a44962013-10-07 09:52:36 +0000472 FileMappingHandle =
473 ::CreateFileMappingW(FileHandle, 0, flprotect,
474 (Offset + Size) >> 32,
475 (Offset + Size) & 0xffffffff,
476 0);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000477 if (FileMappingHandle == NULL) {
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000478 std::error_code ec = windows_error(GetLastError());
Michael J. Spencerd932d412013-03-15 19:25:47 +0000479 if (FileDescriptor) {
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000480 if (CloseFD)
481 _close(FileDescriptor);
Michael J. Spencerd932d412013-03-15 19:25:47 +0000482 } else
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000483 ::CloseHandle(FileHandle);
484 return ec;
485 }
486
487 DWORD dwDesiredAccess;
488 switch (Mode) {
489 case readonly: dwDesiredAccess = FILE_MAP_READ; break;
490 case readwrite: dwDesiredAccess = FILE_MAP_WRITE; break;
491 case priv: dwDesiredAccess = FILE_MAP_COPY; break;
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000492 }
493 Mapping = ::MapViewOfFile(FileMappingHandle,
494 dwDesiredAccess,
495 Offset >> 32,
496 Offset & 0xffffffff,
497 Size);
498 if (Mapping == NULL) {
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000499 std::error_code ec = windows_error(GetLastError());
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000500 ::CloseHandle(FileMappingHandle);
Michael J. Spencerd932d412013-03-15 19:25:47 +0000501 if (FileDescriptor) {
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000502 if (CloseFD)
503 _close(FileDescriptor);
Michael J. Spencerd932d412013-03-15 19:25:47 +0000504 } else
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000505 ::CloseHandle(FileHandle);
506 return ec;
507 }
508
509 if (Size == 0) {
510 MEMORY_BASIC_INFORMATION mbi;
511 SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));
512 if (Result == 0) {
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000513 std::error_code ec = windows_error(GetLastError());
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000514 ::UnmapViewOfFile(Mapping);
515 ::CloseHandle(FileMappingHandle);
Michael J. Spencerd932d412013-03-15 19:25:47 +0000516 if (FileDescriptor) {
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000517 if (CloseFD)
518 _close(FileDescriptor);
Michael J. Spencerd932d412013-03-15 19:25:47 +0000519 } else
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000520 ::CloseHandle(FileHandle);
521 return ec;
522 }
523 Size = mbi.RegionSize;
524 }
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000525
526 // Close all the handles except for the view. It will keep the other handles
527 // alive.
528 ::CloseHandle(FileMappingHandle);
Michael J. Spencerd932d412013-03-15 19:25:47 +0000529 if (FileDescriptor) {
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000530 if (CloseFD)
531 _close(FileDescriptor); // Also closes FileHandle.
Michael J. Spencerd932d412013-03-15 19:25:47 +0000532 } else
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000533 ::CloseHandle(FileHandle);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000534 return std::error_code();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000535}
536
537mapped_file_region::mapped_file_region(const Twine &path,
538 mapmode mode,
539 uint64_t length,
540 uint64_t offset,
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000541 std::error_code &ec)
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000542 : Mode(mode)
543 , Size(length)
544 , Mapping()
545 , FileDescriptor()
546 , FileHandle(INVALID_HANDLE_VALUE)
547 , FileMappingHandle() {
548 SmallString<128> path_storage;
549 SmallVector<wchar_t, 128> path_utf16;
550
551 // Convert path to UTF-16.
Nico Webereada11b2012-09-25 05:24:16 +0000552 if ((ec = UTF8ToUTF16(path.toStringRef(path_storage), path_utf16)))
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000553 return;
554
555 // Get file handle for creating a file mapping.
556 FileHandle = ::CreateFileW(c_str(path_utf16),
557 Mode == readonly ? GENERIC_READ
558 : GENERIC_READ | GENERIC_WRITE,
559 Mode == readonly ? FILE_SHARE_READ
560 : 0,
561 0,
562 Mode == readonly ? OPEN_EXISTING
563 : OPEN_ALWAYS,
564 Mode == readonly ? FILE_ATTRIBUTE_READONLY
565 : FILE_ATTRIBUTE_NORMAL,
566 0);
567 if (FileHandle == INVALID_HANDLE_VALUE) {
568 ec = windows_error(::GetLastError());
569 return;
570 }
571
572 FileDescriptor = 0;
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000573 ec = init(FileDescriptor, true, offset);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000574 if (ec) {
575 Mapping = FileMappingHandle = 0;
576 FileHandle = INVALID_HANDLE_VALUE;
577 FileDescriptor = 0;
578 }
579}
580
581mapped_file_region::mapped_file_region(int fd,
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000582 bool closefd,
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000583 mapmode mode,
584 uint64_t length,
585 uint64_t offset,
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000586 std::error_code &ec)
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000587 : Mode(mode)
588 , Size(length)
589 , Mapping()
590 , FileDescriptor(fd)
591 , FileHandle(INVALID_HANDLE_VALUE)
592 , FileMappingHandle() {
593 FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
594 if (FileHandle == INVALID_HANDLE_VALUE) {
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000595 if (closefd)
596 _close(FileDescriptor);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000597 FileDescriptor = 0;
Rafael Espindola2a826e42014-06-13 17:20:48 +0000598 ec = make_error_code(errc::bad_file_descriptor);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000599 return;
600 }
601
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000602 ec = init(FileDescriptor, closefd, offset);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000603 if (ec) {
604 Mapping = FileMappingHandle = 0;
605 FileHandle = INVALID_HANDLE_VALUE;
606 FileDescriptor = 0;
607 }
608}
609
610mapped_file_region::~mapped_file_region() {
611 if (Mapping)
612 ::UnmapViewOfFile(Mapping);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000613}
614
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000615mapped_file_region::mapped_file_region(mapped_file_region &&other)
616 : Mode(other.Mode)
617 , Size(other.Size)
618 , Mapping(other.Mapping)
619 , FileDescriptor(other.FileDescriptor)
620 , FileHandle(other.FileHandle)
621 , FileMappingHandle(other.FileMappingHandle) {
622 other.Mapping = other.FileMappingHandle = 0;
623 other.FileHandle = INVALID_HANDLE_VALUE;
624 other.FileDescriptor = 0;
625}
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000626
627mapped_file_region::mapmode mapped_file_region::flags() const {
628 assert(Mapping && "Mapping failed but used anyway!");
629 return Mode;
630}
631
632uint64_t mapped_file_region::size() const {
633 assert(Mapping && "Mapping failed but used anyway!");
634 return Size;
635}
636
637char *mapped_file_region::data() const {
Alp Tokerf907b892013-12-05 05:44:44 +0000638 assert(Mode != readonly && "Cannot get non-const data for readonly mapping!");
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000639 assert(Mapping && "Mapping failed but used anyway!");
640 return reinterpret_cast<char*>(Mapping);
641}
642
643const char *mapped_file_region::const_data() const {
644 assert(Mapping && "Mapping failed but used anyway!");
645 return reinterpret_cast<const char*>(Mapping);
646}
647
648int mapped_file_region::alignment() {
649 SYSTEM_INFO SysInfo;
650 ::GetSystemInfo(&SysInfo);
651 return SysInfo.dwAllocationGranularity;
652}
653
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000654std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000655 StringRef path){
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000656 SmallVector<wchar_t, 128> path_utf16;
657
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000658 if (std::error_code ec = UTF8ToUTF16(path, path_utf16))
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000659 return ec;
660
661 // Convert path to the format that Windows is happy with.
662 if (path_utf16.size() > 0 &&
663 !is_separator(path_utf16[path.size() - 1]) &&
664 path_utf16[path.size() - 1] != L':') {
665 path_utf16.push_back(L'\\');
666 path_utf16.push_back(L'*');
667 } else {
668 path_utf16.push_back(L'*');
669 }
670
671 // Get the first directory entry.
672 WIN32_FIND_DATAW FirstFind;
Michael J. Spencer751e9aa2010-12-09 17:37:18 +0000673 ScopedFindHandle FindHandle(::FindFirstFileW(c_str(path_utf16), &FirstFind));
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000674 if (!FindHandle)
675 return windows_error(::GetLastError());
676
Michael J. Spencer98879d72011-01-05 16:39:30 +0000677 size_t FilenameLen = ::wcslen(FirstFind.cFileName);
678 while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
679 (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
680 FirstFind.cFileName[1] == L'.'))
681 if (!::FindNextFileW(FindHandle, &FirstFind)) {
Rafael Espindolaa813d602014-06-11 03:58:34 +0000682 DWORD LastError = ::GetLastError();
Michael J. Spencer98879d72011-01-05 16:39:30 +0000683 // Check for end.
Rafael Espindolaa813d602014-06-11 03:58:34 +0000684 if (LastError == ERROR_NO_MORE_FILES)
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000685 return detail::directory_iterator_destruct(it);
Rafael Espindolaa813d602014-06-11 03:58:34 +0000686 return windows_error(LastError);
Michael J. Spencer98879d72011-01-05 16:39:30 +0000687 } else
688 FilenameLen = ::wcslen(FirstFind.cFileName);
689
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000690 // Construct the current directory entry.
Michael J. Spencer98879d72011-01-05 16:39:30 +0000691 SmallString<128> directory_entry_name_utf8;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000692 if (std::error_code ec =
693 UTF16ToUTF8(FirstFind.cFileName, ::wcslen(FirstFind.cFileName),
694 directory_entry_name_utf8))
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000695 return ec;
696
697 it.IterationHandle = intptr_t(FindHandle.take());
Michael J. Spencer98879d72011-01-05 16:39:30 +0000698 SmallString<128> directory_entry_path(path);
699 path::append(directory_entry_path, directory_entry_name_utf8.str());
700 it.CurrentEntry = directory_entry(directory_entry_path.str());
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000701
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000702 return std::error_code();
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000703}
704
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000705std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000706 if (it.IterationHandle != 0)
707 // Closes the handle if it's valid.
708 ScopedFindHandle close(HANDLE(it.IterationHandle));
709 it.IterationHandle = 0;
710 it.CurrentEntry = directory_entry();
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000711 return std::error_code();
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000712}
713
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000714std::error_code detail::directory_iterator_increment(detail::DirIterState &it) {
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000715 WIN32_FIND_DATAW FindData;
716 if (!::FindNextFileW(HANDLE(it.IterationHandle), &FindData)) {
Rafael Espindolaa813d602014-06-11 03:58:34 +0000717 DWORD LastError = ::GetLastError();
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000718 // Check for end.
Rafael Espindolaa813d602014-06-11 03:58:34 +0000719 if (LastError == ERROR_NO_MORE_FILES)
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000720 return detail::directory_iterator_destruct(it);
Rafael Espindolaa813d602014-06-11 03:58:34 +0000721 return windows_error(LastError);
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000722 }
723
Michael J. Spencer98879d72011-01-05 16:39:30 +0000724 size_t FilenameLen = ::wcslen(FindData.cFileName);
725 if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
726 (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
727 FindData.cFileName[1] == L'.'))
728 return directory_iterator_increment(it);
729
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000730 SmallString<128> directory_entry_path_utf8;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000731 if (std::error_code ec =
732 UTF16ToUTF8(FindData.cFileName, ::wcslen(FindData.cFileName),
733 directory_entry_path_utf8))
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000734 return ec;
735
736 it.CurrentEntry.replace_filename(Twine(directory_entry_path_utf8));
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000737 return std::error_code();
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000738}
739
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000740std::error_code openFileForRead(const Twine &Name, int &ResultFD) {
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000741 SmallString<128> PathStorage;
742 SmallVector<wchar_t, 128> PathUTF16;
Nick Kledzik18497e92012-06-20 00:28:54 +0000743
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000744 if (std::error_code EC =
745 UTF8ToUTF16(Name.toStringRef(PathStorage), PathUTF16))
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000746 return EC;
747
748 HANDLE H = ::CreateFileW(PathUTF16.begin(), GENERIC_READ,
Rafael Espindola16431fe2013-07-17 19:44:07 +0000749 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000750 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
751 if (H == INVALID_HANDLE_VALUE) {
Rafael Espindolaa813d602014-06-11 03:58:34 +0000752 DWORD LastError = ::GetLastError();
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000753 std::error_code EC = windows_error(LastError);
Rafael Espindola331aeba2013-07-17 19:58:28 +0000754 // Provide a better error message when trying to open directories.
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000755 // This only runs if we failed to open the file, so there is probably
756 // no performances issues.
Rafael Espindolaa813d602014-06-11 03:58:34 +0000757 if (LastError != ERROR_ACCESS_DENIED)
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000758 return EC;
759 if (is_directory(Name))
Rafael Espindola2a826e42014-06-13 17:20:48 +0000760 return make_error_code(errc::is_a_directory);
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000761 return EC;
762 }
763
764 int FD = ::_open_osfhandle(intptr_t(H), 0);
765 if (FD == -1) {
766 ::CloseHandle(H);
Rafael Espindolaa813d602014-06-11 03:58:34 +0000767 return windows_error(ERROR_INVALID_HANDLE);
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000768 }
769
770 ResultFD = FD;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000771 return std::error_code();
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000772}
Nick Kledzik18497e92012-06-20 00:28:54 +0000773
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000774std::error_code openFileForWrite(const Twine &Name, int &ResultFD,
Rafael Espindola67080ce2013-07-19 15:02:03 +0000775 sys::fs::OpenFlags Flags, unsigned Mode) {
776 // Verify that we don't have both "append" and "excl".
777 assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
778 "Cannot specify both 'excl' and 'append' file creation flags!");
779
780 SmallString<128> PathStorage;
781 SmallVector<wchar_t, 128> PathUTF16;
782
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000783 if (std::error_code EC =
784 UTF8ToUTF16(Name.toStringRef(PathStorage), PathUTF16))
Rafael Espindola67080ce2013-07-19 15:02:03 +0000785 return EC;
786
787 DWORD CreationDisposition;
788 if (Flags & F_Excl)
789 CreationDisposition = CREATE_NEW;
NAKAMURA Takumiedf76152013-08-22 15:14:45 +0000790 else if (Flags & F_Append)
Rafael Espindola67080ce2013-07-19 15:02:03 +0000791 CreationDisposition = OPEN_ALWAYS;
792 else
793 CreationDisposition = CREATE_ALWAYS;
794
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000795 DWORD Access = GENERIC_WRITE;
796 if (Flags & F_RW)
797 Access |= GENERIC_READ;
798
799 HANDLE H = ::CreateFileW(PathUTF16.begin(), Access,
Rafael Espindola67080ce2013-07-19 15:02:03 +0000800 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
801 CreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL);
802
803 if (H == INVALID_HANDLE_VALUE) {
Rafael Espindolaa813d602014-06-11 03:58:34 +0000804 DWORD LastError = ::GetLastError();
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000805 std::error_code EC = windows_error(LastError);
Rafael Espindola67080ce2013-07-19 15:02:03 +0000806 // Provide a better error message when trying to open directories.
807 // This only runs if we failed to open the file, so there is probably
808 // no performances issues.
Rafael Espindolaa813d602014-06-11 03:58:34 +0000809 if (LastError != ERROR_ACCESS_DENIED)
Rafael Espindola67080ce2013-07-19 15:02:03 +0000810 return EC;
811 if (is_directory(Name))
Rafael Espindola2a826e42014-06-13 17:20:48 +0000812 return make_error_code(errc::is_a_directory);
Rafael Espindola67080ce2013-07-19 15:02:03 +0000813 return EC;
814 }
815
816 int OpenFlags = 0;
817 if (Flags & F_Append)
818 OpenFlags |= _O_APPEND;
819
Rafael Espindola90c7f1c2014-02-24 18:20:12 +0000820 if (Flags & F_Text)
Rafael Espindola67080ce2013-07-19 15:02:03 +0000821 OpenFlags |= _O_TEXT;
822
823 int FD = ::_open_osfhandle(intptr_t(H), OpenFlags);
824 if (FD == -1) {
825 ::CloseHandle(H);
Rafael Espindolaa813d602014-06-11 03:58:34 +0000826 return windows_error(ERROR_INVALID_HANDLE);
Rafael Espindola67080ce2013-07-19 15:02:03 +0000827 }
828
829 ResultFD = FD;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000830 return std::error_code();
Rafael Espindola67080ce2013-07-19 15:02:03 +0000831}
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000832} // end namespace fs
Rui Ueyama471d0c52013-09-10 19:45:51 +0000833
Peter Collingbournef7d41012014-01-31 23:46:06 +0000834namespace path {
835
836bool home_directory(SmallVectorImpl<char> &result) {
837 wchar_t Path[MAX_PATH];
838 if (::SHGetFolderPathW(0, CSIDL_APPDATA | CSIDL_FLAG_CREATE, 0,
Peter Collingbournead141ab2014-02-01 02:42:20 +0000839 /*SHGFP_TYPE_CURRENT*/0, Path) != S_OK)
Peter Collingbournef7d41012014-01-31 23:46:06 +0000840 return false;
841
842 if (UTF16ToUTF8(Path, ::wcslen(Path), result))
843 return false;
844
845 return true;
846}
847
Rafael Espindola016a6d52014-08-26 14:47:52 +0000848static bool getTempDirEnvVar(const char *Var, SmallVectorImpl<char> &Res) {
849 SmallVector<wchar_t, 128> NameUTF16;
850 if (windows::UTF8ToUTF16(Var, NameUTF16))
851 return false;
852
853 SmallVector<wchar_t, 1024> Buf;
854 size_t Size = 1024;
855 do {
856 Buf.reserve(Size);
857 Size =
858 GetEnvironmentVariableW(NameUTF16.data(), Buf.data(), Buf.capacity());
859 if (Size == 0)
860 return false;
861
862 // Try again with larger buffer.
863 } while (Size > Buf.capacity());
864 Buf.set_size(Size);
865
866 if (windows::UTF16ToUTF8(Buf.data(), Size, Res))
867 return false;
868 return true;
869}
870
871static bool getTempDirEnvVar(SmallVectorImpl<char> &Res) {
872 const char *EnvironmentVariables[] = {"TMP", "TEMP", "USERPROFILE"};
873 for (const char *Env : EnvironmentVariables) {
874 if (getTempDirEnvVar(Env, Res))
875 return true;
876 }
877 return false;
878}
879
880void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
881 (void)ErasedOnReboot;
882 Result.clear();
883
884 // Check whether the temporary directory is specified by an environment
885 // variable.
886 if (getTempDirEnvVar(Result))
887 return;
888
889 // Fall back to a system default.
890 const char *DefaultResult = "C:\\TEMP";
891 Result.append(DefaultResult, DefaultResult + strlen(DefaultResult));
892}
Peter Collingbournef7d41012014-01-31 23:46:06 +0000893} // end namespace path
894
Rui Ueyama471d0c52013-09-10 19:45:51 +0000895namespace windows {
Rafael Espindola0a5f9cf2014-06-12 14:11:22 +0000896std::error_code UTF8ToUTF16(llvm::StringRef utf8,
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000897 llvm::SmallVectorImpl<wchar_t> &utf16) {
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000898 if (!utf8.empty()) {
899 int len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
900 utf8.size(), utf16.begin(), 0);
Rui Ueyama471d0c52013-09-10 19:45:51 +0000901
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000902 if (len == 0)
Rafael Espindolaa813d602014-06-11 03:58:34 +0000903 return windows_error(::GetLastError());
Rui Ueyama471d0c52013-09-10 19:45:51 +0000904
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000905 utf16.reserve(len + 1);
906 utf16.set_size(len);
Rui Ueyama471d0c52013-09-10 19:45:51 +0000907
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000908 len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
909 utf8.size(), utf16.begin(), utf16.size());
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 utf16 null terminated.
916 utf16.push_back(0);
917 utf16.pop_back();
918
Rafael Espindola0a5f9cf2014-06-12 14:11:22 +0000919 return std::error_code();
Rui Ueyama471d0c52013-09-10 19:45:51 +0000920}
921
Rafael Espindola9c359662014-09-03 20:02:00 +0000922static
923std::error_code UTF16ToCodePage(unsigned codepage, const wchar_t *utf16,
924 size_t utf16_len,
925 llvm::SmallVectorImpl<char> &utf8) {
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000926 if (utf16_len) {
927 // Get length.
Rafael Espindola9c359662014-09-03 20:02:00 +0000928 int len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, utf8.begin(),
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000929 0, NULL, NULL);
Rui Ueyama471d0c52013-09-10 19:45:51 +0000930
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000931 if (len == 0)
Rafael Espindolaa813d602014-06-11 03:58:34 +0000932 return windows_error(::GetLastError());
Rui Ueyama471d0c52013-09-10 19:45:51 +0000933
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000934 utf8.reserve(len);
935 utf8.set_size(len);
Rui Ueyama471d0c52013-09-10 19:45:51 +0000936
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000937 // Now do the actual conversion.
Rafael Espindola9c359662014-09-03 20:02:00 +0000938 len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, utf8.data(),
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000939 utf8.size(), NULL, NULL);
Rui Ueyama471d0c52013-09-10 19:45:51 +0000940
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000941 if (len == 0)
Rafael Espindolaa813d602014-06-11 03:58:34 +0000942 return windows_error(::GetLastError());
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000943 }
Rui Ueyama471d0c52013-09-10 19:45:51 +0000944
945 // Make utf8 null terminated.
946 utf8.push_back(0);
947 utf8.pop_back();
948
Rafael Espindola0a5f9cf2014-06-12 14:11:22 +0000949 return std::error_code();
Rui Ueyama471d0c52013-09-10 19:45:51 +0000950}
Rafael Espindola9c359662014-09-03 20:02:00 +0000951
952std::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
953 llvm::SmallVectorImpl<char> &utf8) {
954 return UTF16ToCodePage(CP_UTF8, utf16, utf16_len, utf8);
955}
956
957std::error_code UTF16ToCurCP(const wchar_t *utf16, size_t utf16_len,
958 llvm::SmallVectorImpl<char> &utf8) {
959 return UTF16ToCodePage(CP_ACP, utf16, utf16_len, utf8);
960}
Rui Ueyama471d0c52013-09-10 19:45:51 +0000961} // end namespace windows
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000962} // end namespace sys
963} // end namespace llvm