blob: d90d408e6618ce15ffdb8e27a20d9eb219f74cd4 [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 Espindola281f23a2014-09-11 20:30:02 +0000254std::error_code access(const Twine &Path, AccessMode Mode) {
255 SmallString<128> PathStorage;
256 SmallVector<wchar_t, 128> PathUtf16;
Michael J. Spencer45710402010-12-03 01:21:28 +0000257
Rafael Espindola281f23a2014-09-11 20:30:02 +0000258 if (std::error_code EC =
259 UTF8ToUTF16(Path.toStringRef(PathStorage), PathUtf16))
260 return EC;
Michael J. Spencer45710402010-12-03 01:21:28 +0000261
Rafael Espindola281f23a2014-09-11 20:30:02 +0000262 DWORD Attributes = ::GetFileAttributesW(PathUtf16.begin());
Michael J. Spencer45710402010-12-03 01:21:28 +0000263
Rafael Espindola281f23a2014-09-11 20:30:02 +0000264 if (Attributes == INVALID_FILE_ATTRIBUTES) {
Michael J. Spencer45710402010-12-03 01:21:28 +0000265 // 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);
Rafael Espindola281f23a2014-09-11 20:30:02 +0000270 return errc::no_such_file_or_directory;
271 }
272
273 if (Mode == AccessMode::Write && (Attributes & FILE_ATTRIBUTE_READONLY))
274 return errc::permission_denied;
275
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000276 return std::error_code();
Michael J. Spencer45710402010-12-03 01:21:28 +0000277}
278
Michael J. Spencer203d7802011-12-12 06:04:28 +0000279bool equivalent(file_status A, file_status B) {
280 assert(status_known(A) && status_known(B));
281 return A.FileIndexHigh == B.FileIndexHigh &&
282 A.FileIndexLow == B.FileIndexLow &&
283 A.FileSizeHigh == B.FileSizeHigh &&
284 A.FileSizeLow == B.FileSizeLow &&
285 A.LastWriteTimeHigh == B.LastWriteTimeHigh &&
286 A.LastWriteTimeLow == B.LastWriteTimeLow &&
287 A.VolumeSerialNumber == B.VolumeSerialNumber;
288}
289
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000290std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
Michael J. Spencer203d7802011-12-12 06:04:28 +0000291 file_status fsA, fsB;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000292 if (std::error_code ec = status(A, fsA))
293 return ec;
294 if (std::error_code ec = status(B, fsB))
295 return ec;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000296 result = equivalent(fsA, fsB);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000297 return std::error_code();
Michael J. Spencer376d3872010-12-03 18:49:13 +0000298}
299
Benjamin Kramer58994ec2011-08-20 21:36:38 +0000300static bool isReservedName(StringRef path) {
301 // This list of reserved names comes from MSDN, at:
302 // http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
303 static const char *sReservedNames[] = { "nul", "con", "prn", "aux",
304 "com1", "com2", "com3", "com4", "com5", "com6",
305 "com7", "com8", "com9", "lpt1", "lpt2", "lpt3",
306 "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9" };
307
308 // First, check to see if this is a device namespace, which always
309 // starts with \\.\, since device namespaces are not legal file paths.
310 if (path.startswith("\\\\.\\"))
311 return true;
312
313 // Then compare against the list of ancient reserved names
Craig Topper58713212013-07-15 04:27:47 +0000314 for (size_t i = 0; i < array_lengthof(sReservedNames); ++i) {
Benjamin Kramer58994ec2011-08-20 21:36:38 +0000315 if (path.equals_lower(sReservedNames[i]))
316 return true;
317 }
318
319 // The path isn't what we consider reserved.
320 return false;
321}
322
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000323static std::error_code getStatus(HANDLE FileHandle, file_status &Result) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000324 if (FileHandle == INVALID_HANDLE_VALUE)
325 goto handle_status_error;
326
NAKAMURA Takumi8b01da42013-07-18 17:00:54 +0000327 switch (::GetFileType(FileHandle)) {
328 default:
Rafael Espindola81177c52013-07-18 18:42:52 +0000329 llvm_unreachable("Don't know anything about this file type");
330 case FILE_TYPE_UNKNOWN: {
331 DWORD Err = ::GetLastError();
332 if (Err != NO_ERROR)
333 return windows_error(Err);
334 Result = file_status(file_type::type_unknown);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000335 return std::error_code();
Rafael Espindola81177c52013-07-18 18:42:52 +0000336 }
NAKAMURA Takumi8b01da42013-07-18 17:00:54 +0000337 case FILE_TYPE_DISK:
338 break;
339 case FILE_TYPE_CHAR:
340 Result = file_status(file_type::character_file);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000341 return std::error_code();
NAKAMURA Takumi8b01da42013-07-18 17:00:54 +0000342 case FILE_TYPE_PIPE:
343 Result = file_status(file_type::fifo_file);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000344 return std::error_code();
NAKAMURA Takumi8b01da42013-07-18 17:00:54 +0000345 }
346
Rafael Espindola77021c92013-07-16 03:20:13 +0000347 BY_HANDLE_FILE_INFORMATION Info;
348 if (!::GetFileInformationByHandle(FileHandle, &Info))
349 goto handle_status_error;
350
Rafael Espindolaa5932af2013-07-30 20:25:53 +0000351 {
352 file_type Type = (Info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
353 ? file_type::directory_file
354 : file_type::regular_file;
355 Result =
356 file_status(Type, Info.ftLastWriteTime.dwHighDateTime,
357 Info.ftLastWriteTime.dwLowDateTime,
358 Info.dwVolumeSerialNumber, Info.nFileSizeHigh,
359 Info.nFileSizeLow, Info.nFileIndexHigh, Info.nFileIndexLow);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000360 return std::error_code();
Rafael Espindolaa5932af2013-07-30 20:25:53 +0000361 }
Rafael Espindola77021c92013-07-16 03:20:13 +0000362
363handle_status_error:
Rafael Espindolaa813d602014-06-11 03:58:34 +0000364 DWORD LastError = ::GetLastError();
365 if (LastError == ERROR_FILE_NOT_FOUND ||
366 LastError == ERROR_PATH_NOT_FOUND)
Rafael Espindola77021c92013-07-16 03:20:13 +0000367 Result = file_status(file_type::file_not_found);
Rafael Espindolaa813d602014-06-11 03:58:34 +0000368 else if (LastError == ERROR_SHARING_VIOLATION)
Rafael Espindola77021c92013-07-16 03:20:13 +0000369 Result = file_status(file_type::type_unknown);
Rafael Espindola107b74c2013-07-31 00:10:25 +0000370 else
Rafael Espindola77021c92013-07-16 03:20:13 +0000371 Result = file_status(file_type::status_error);
Rafael Espindolaa813d602014-06-11 03:58:34 +0000372 return windows_error(LastError);
Rafael Espindola77021c92013-07-16 03:20:13 +0000373}
374
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000375std::error_code status(const Twine &path, file_status &result) {
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000376 SmallString<128> path_storage;
377 SmallVector<wchar_t, 128> path_utf16;
378
NAKAMURA Takumia3d47492011-03-16 02:53:32 +0000379 StringRef path8 = path.toStringRef(path_storage);
Benjamin Kramer58994ec2011-08-20 21:36:38 +0000380 if (isReservedName(path8)) {
NAKAMURA Takumia3d47492011-03-16 02:53:32 +0000381 result = file_status(file_type::character_file);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000382 return std::error_code();
NAKAMURA Takumia3d47492011-03-16 02:53:32 +0000383 }
384
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000385 if (std::error_code ec = UTF8ToUTF16(path8, path_utf16))
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000386 return ec;
387
388 DWORD attr = ::GetFileAttributesW(path_utf16.begin());
389 if (attr == INVALID_FILE_ATTRIBUTES)
Rafael Espindola77021c92013-07-16 03:20:13 +0000390 return getStatus(INVALID_HANDLE_VALUE, result);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000391
392 // Handle reparse points.
393 if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
Michael J. Spencer513f1b62011-12-12 06:03:33 +0000394 ScopedFileHandle h(
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000395 ::CreateFileW(path_utf16.begin(),
396 0, // Attributes only.
397 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
398 NULL,
399 OPEN_EXISTING,
400 FILE_FLAG_BACKUP_SEMANTICS,
401 0));
Michael J. Spencer513f1b62011-12-12 06:03:33 +0000402 if (!h)
Rafael Espindola77021c92013-07-16 03:20:13 +0000403 return getStatus(INVALID_HANDLE_VALUE, result);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000404 }
405
Rafael Espindolaa5932af2013-07-30 20:25:53 +0000406 ScopedFileHandle h(
407 ::CreateFileW(path_utf16.begin(), 0, // Attributes only.
Michael J. Spencer203d7802011-12-12 06:04:28 +0000408 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
Rafael Espindolaa5932af2013-07-30 20:25:53 +0000409 NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0));
Michael J. Spencer203d7802011-12-12 06:04:28 +0000410 if (!h)
Rafael Espindola77021c92013-07-16 03:20:13 +0000411 return getStatus(INVALID_HANDLE_VALUE, result);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000412
Rafael Espindola77021c92013-07-16 03:20:13 +0000413 return getStatus(h, result);
Rafael Espindola77021c92013-07-16 03:20:13 +0000414}
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000415
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000416std::error_code status(int FD, file_status &Result) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000417 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
418 return getStatus(FileHandle, Result);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000419}
420
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000421std::error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000422 ULARGE_INTEGER UI;
423 UI.QuadPart = Time.toWin32Time();
424 FILETIME FT;
425 FT.dwLowDateTime = UI.LowPart;
426 FT.dwHighDateTime = UI.HighPart;
427 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
428 if (!SetFileTime(FileHandle, NULL, &FT, &FT))
429 return windows_error(::GetLastError());
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000430 return std::error_code();
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000431}
Nick Kledzik18497e92012-06-20 00:28:54 +0000432
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000433std::error_code mapped_file_region::init(int FD, bool CloseFD, uint64_t Offset) {
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000434 FileDescriptor = FD;
435 // Make sure that the requested size fits within SIZE_T.
436 if (Size > std::numeric_limits<SIZE_T>::max()) {
Michael J. Spencerd932d412013-03-15 19:25:47 +0000437 if (FileDescriptor) {
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000438 if (CloseFD)
439 _close(FileDescriptor);
Michael J. Spencerd932d412013-03-15 19:25:47 +0000440 } else
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000441 ::CloseHandle(FileHandle);
Rafael Espindola2a826e42014-06-13 17:20:48 +0000442 return make_error_code(errc::invalid_argument);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000443 }
444
445 DWORD flprotect;
446 switch (Mode) {
447 case readonly: flprotect = PAGE_READONLY; break;
448 case readwrite: flprotect = PAGE_READWRITE; break;
449 case priv: flprotect = PAGE_WRITECOPY; break;
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000450 }
451
David Majnemer17a44962013-10-07 09:52:36 +0000452 FileMappingHandle =
453 ::CreateFileMappingW(FileHandle, 0, flprotect,
454 (Offset + Size) >> 32,
455 (Offset + Size) & 0xffffffff,
456 0);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000457 if (FileMappingHandle == NULL) {
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000458 std::error_code ec = windows_error(GetLastError());
Michael J. Spencerd932d412013-03-15 19:25:47 +0000459 if (FileDescriptor) {
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000460 if (CloseFD)
461 _close(FileDescriptor);
Michael J. Spencerd932d412013-03-15 19:25:47 +0000462 } else
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000463 ::CloseHandle(FileHandle);
464 return ec;
465 }
466
467 DWORD dwDesiredAccess;
468 switch (Mode) {
469 case readonly: dwDesiredAccess = FILE_MAP_READ; break;
470 case readwrite: dwDesiredAccess = FILE_MAP_WRITE; break;
471 case priv: dwDesiredAccess = FILE_MAP_COPY; break;
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000472 }
473 Mapping = ::MapViewOfFile(FileMappingHandle,
474 dwDesiredAccess,
475 Offset >> 32,
476 Offset & 0xffffffff,
477 Size);
478 if (Mapping == NULL) {
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000479 std::error_code ec = windows_error(GetLastError());
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000480 ::CloseHandle(FileMappingHandle);
Michael J. Spencerd932d412013-03-15 19:25:47 +0000481 if (FileDescriptor) {
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000482 if (CloseFD)
483 _close(FileDescriptor);
Michael J. Spencerd932d412013-03-15 19:25:47 +0000484 } else
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000485 ::CloseHandle(FileHandle);
486 return ec;
487 }
488
489 if (Size == 0) {
490 MEMORY_BASIC_INFORMATION mbi;
491 SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));
492 if (Result == 0) {
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000493 std::error_code ec = windows_error(GetLastError());
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000494 ::UnmapViewOfFile(Mapping);
495 ::CloseHandle(FileMappingHandle);
Michael J. Spencerd932d412013-03-15 19:25:47 +0000496 if (FileDescriptor) {
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000497 if (CloseFD)
498 _close(FileDescriptor);
Michael J. Spencerd932d412013-03-15 19:25:47 +0000499 } else
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000500 ::CloseHandle(FileHandle);
501 return ec;
502 }
503 Size = mbi.RegionSize;
504 }
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000505
506 // Close all the handles except for the view. It will keep the other handles
507 // alive.
508 ::CloseHandle(FileMappingHandle);
Michael J. Spencerd932d412013-03-15 19:25:47 +0000509 if (FileDescriptor) {
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000510 if (CloseFD)
511 _close(FileDescriptor); // Also closes FileHandle.
Michael J. Spencerd932d412013-03-15 19:25:47 +0000512 } else
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000513 ::CloseHandle(FileHandle);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000514 return std::error_code();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000515}
516
517mapped_file_region::mapped_file_region(const Twine &path,
518 mapmode mode,
519 uint64_t length,
520 uint64_t offset,
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000521 std::error_code &ec)
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000522 : Mode(mode)
523 , Size(length)
524 , Mapping()
525 , FileDescriptor()
526 , FileHandle(INVALID_HANDLE_VALUE)
527 , FileMappingHandle() {
528 SmallString<128> path_storage;
529 SmallVector<wchar_t, 128> path_utf16;
530
531 // Convert path to UTF-16.
Nico Webereada11b2012-09-25 05:24:16 +0000532 if ((ec = UTF8ToUTF16(path.toStringRef(path_storage), path_utf16)))
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000533 return;
534
535 // Get file handle for creating a file mapping.
536 FileHandle = ::CreateFileW(c_str(path_utf16),
537 Mode == readonly ? GENERIC_READ
538 : GENERIC_READ | GENERIC_WRITE,
539 Mode == readonly ? FILE_SHARE_READ
540 : 0,
541 0,
542 Mode == readonly ? OPEN_EXISTING
543 : OPEN_ALWAYS,
544 Mode == readonly ? FILE_ATTRIBUTE_READONLY
545 : FILE_ATTRIBUTE_NORMAL,
546 0);
547 if (FileHandle == INVALID_HANDLE_VALUE) {
548 ec = windows_error(::GetLastError());
549 return;
550 }
551
552 FileDescriptor = 0;
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000553 ec = init(FileDescriptor, true, offset);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000554 if (ec) {
555 Mapping = FileMappingHandle = 0;
556 FileHandle = INVALID_HANDLE_VALUE;
557 FileDescriptor = 0;
558 }
559}
560
561mapped_file_region::mapped_file_region(int fd,
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000562 bool closefd,
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000563 mapmode mode,
564 uint64_t length,
565 uint64_t offset,
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000566 std::error_code &ec)
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000567 : Mode(mode)
568 , Size(length)
569 , Mapping()
570 , FileDescriptor(fd)
571 , FileHandle(INVALID_HANDLE_VALUE)
572 , FileMappingHandle() {
573 FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
574 if (FileHandle == INVALID_HANDLE_VALUE) {
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000575 if (closefd)
576 _close(FileDescriptor);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000577 FileDescriptor = 0;
Rafael Espindola2a826e42014-06-13 17:20:48 +0000578 ec = make_error_code(errc::bad_file_descriptor);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000579 return;
580 }
581
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000582 ec = init(FileDescriptor, closefd, offset);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000583 if (ec) {
584 Mapping = FileMappingHandle = 0;
585 FileHandle = INVALID_HANDLE_VALUE;
586 FileDescriptor = 0;
587 }
588}
589
590mapped_file_region::~mapped_file_region() {
591 if (Mapping)
592 ::UnmapViewOfFile(Mapping);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000593}
594
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000595mapped_file_region::mapped_file_region(mapped_file_region &&other)
596 : Mode(other.Mode)
597 , Size(other.Size)
598 , Mapping(other.Mapping)
599 , FileDescriptor(other.FileDescriptor)
600 , FileHandle(other.FileHandle)
601 , FileMappingHandle(other.FileMappingHandle) {
602 other.Mapping = other.FileMappingHandle = 0;
603 other.FileHandle = INVALID_HANDLE_VALUE;
604 other.FileDescriptor = 0;
605}
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000606
607mapped_file_region::mapmode mapped_file_region::flags() const {
608 assert(Mapping && "Mapping failed but used anyway!");
609 return Mode;
610}
611
612uint64_t mapped_file_region::size() const {
613 assert(Mapping && "Mapping failed but used anyway!");
614 return Size;
615}
616
617char *mapped_file_region::data() const {
Alp Tokerf907b892013-12-05 05:44:44 +0000618 assert(Mode != readonly && "Cannot get non-const data for readonly mapping!");
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000619 assert(Mapping && "Mapping failed but used anyway!");
620 return reinterpret_cast<char*>(Mapping);
621}
622
623const char *mapped_file_region::const_data() const {
624 assert(Mapping && "Mapping failed but used anyway!");
625 return reinterpret_cast<const char*>(Mapping);
626}
627
628int mapped_file_region::alignment() {
629 SYSTEM_INFO SysInfo;
630 ::GetSystemInfo(&SysInfo);
631 return SysInfo.dwAllocationGranularity;
632}
633
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000634std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000635 StringRef path){
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000636 SmallVector<wchar_t, 128> path_utf16;
637
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000638 if (std::error_code ec = UTF8ToUTF16(path, path_utf16))
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000639 return ec;
640
641 // Convert path to the format that Windows is happy with.
642 if (path_utf16.size() > 0 &&
643 !is_separator(path_utf16[path.size() - 1]) &&
644 path_utf16[path.size() - 1] != L':') {
645 path_utf16.push_back(L'\\');
646 path_utf16.push_back(L'*');
647 } else {
648 path_utf16.push_back(L'*');
649 }
650
651 // Get the first directory entry.
652 WIN32_FIND_DATAW FirstFind;
Michael J. Spencer751e9aa2010-12-09 17:37:18 +0000653 ScopedFindHandle FindHandle(::FindFirstFileW(c_str(path_utf16), &FirstFind));
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000654 if (!FindHandle)
655 return windows_error(::GetLastError());
656
Michael J. Spencer98879d72011-01-05 16:39:30 +0000657 size_t FilenameLen = ::wcslen(FirstFind.cFileName);
658 while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
659 (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
660 FirstFind.cFileName[1] == L'.'))
661 if (!::FindNextFileW(FindHandle, &FirstFind)) {
Rafael Espindolaa813d602014-06-11 03:58:34 +0000662 DWORD LastError = ::GetLastError();
Michael J. Spencer98879d72011-01-05 16:39:30 +0000663 // Check for end.
Rafael Espindolaa813d602014-06-11 03:58:34 +0000664 if (LastError == ERROR_NO_MORE_FILES)
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000665 return detail::directory_iterator_destruct(it);
Rafael Espindolaa813d602014-06-11 03:58:34 +0000666 return windows_error(LastError);
Michael J. Spencer98879d72011-01-05 16:39:30 +0000667 } else
668 FilenameLen = ::wcslen(FirstFind.cFileName);
669
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000670 // Construct the current directory entry.
Michael J. Spencer98879d72011-01-05 16:39:30 +0000671 SmallString<128> directory_entry_name_utf8;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000672 if (std::error_code ec =
673 UTF16ToUTF8(FirstFind.cFileName, ::wcslen(FirstFind.cFileName),
674 directory_entry_name_utf8))
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000675 return ec;
676
677 it.IterationHandle = intptr_t(FindHandle.take());
Michael J. Spencer98879d72011-01-05 16:39:30 +0000678 SmallString<128> directory_entry_path(path);
679 path::append(directory_entry_path, directory_entry_name_utf8.str());
680 it.CurrentEntry = directory_entry(directory_entry_path.str());
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000681
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000682 return std::error_code();
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000683}
684
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000685std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000686 if (it.IterationHandle != 0)
687 // Closes the handle if it's valid.
688 ScopedFindHandle close(HANDLE(it.IterationHandle));
689 it.IterationHandle = 0;
690 it.CurrentEntry = directory_entry();
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000691 return std::error_code();
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000692}
693
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000694std::error_code detail::directory_iterator_increment(detail::DirIterState &it) {
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000695 WIN32_FIND_DATAW FindData;
696 if (!::FindNextFileW(HANDLE(it.IterationHandle), &FindData)) {
Rafael Espindolaa813d602014-06-11 03:58:34 +0000697 DWORD LastError = ::GetLastError();
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000698 // Check for end.
Rafael Espindolaa813d602014-06-11 03:58:34 +0000699 if (LastError == ERROR_NO_MORE_FILES)
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000700 return detail::directory_iterator_destruct(it);
Rafael Espindolaa813d602014-06-11 03:58:34 +0000701 return windows_error(LastError);
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000702 }
703
Michael J. Spencer98879d72011-01-05 16:39:30 +0000704 size_t FilenameLen = ::wcslen(FindData.cFileName);
705 if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
706 (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
707 FindData.cFileName[1] == L'.'))
708 return directory_iterator_increment(it);
709
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000710 SmallString<128> directory_entry_path_utf8;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000711 if (std::error_code ec =
712 UTF16ToUTF8(FindData.cFileName, ::wcslen(FindData.cFileName),
713 directory_entry_path_utf8))
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000714 return ec;
715
716 it.CurrentEntry.replace_filename(Twine(directory_entry_path_utf8));
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000717 return std::error_code();
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000718}
719
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000720std::error_code openFileForRead(const Twine &Name, int &ResultFD) {
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000721 SmallString<128> PathStorage;
722 SmallVector<wchar_t, 128> PathUTF16;
Nick Kledzik18497e92012-06-20 00:28:54 +0000723
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000724 if (std::error_code EC =
725 UTF8ToUTF16(Name.toStringRef(PathStorage), PathUTF16))
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000726 return EC;
727
728 HANDLE H = ::CreateFileW(PathUTF16.begin(), GENERIC_READ,
Rafael Espindola16431fe2013-07-17 19:44:07 +0000729 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000730 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
731 if (H == INVALID_HANDLE_VALUE) {
Rafael Espindolaa813d602014-06-11 03:58:34 +0000732 DWORD LastError = ::GetLastError();
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000733 std::error_code EC = windows_error(LastError);
Rafael Espindola331aeba2013-07-17 19:58:28 +0000734 // Provide a better error message when trying to open directories.
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000735 // This only runs if we failed to open the file, so there is probably
736 // no performances issues.
Rafael Espindolaa813d602014-06-11 03:58:34 +0000737 if (LastError != ERROR_ACCESS_DENIED)
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000738 return EC;
739 if (is_directory(Name))
Rafael Espindola2a826e42014-06-13 17:20:48 +0000740 return make_error_code(errc::is_a_directory);
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000741 return EC;
742 }
743
744 int FD = ::_open_osfhandle(intptr_t(H), 0);
745 if (FD == -1) {
746 ::CloseHandle(H);
Rafael Espindolaa813d602014-06-11 03:58:34 +0000747 return windows_error(ERROR_INVALID_HANDLE);
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000748 }
749
750 ResultFD = FD;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000751 return std::error_code();
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000752}
Nick Kledzik18497e92012-06-20 00:28:54 +0000753
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000754std::error_code openFileForWrite(const Twine &Name, int &ResultFD,
Rafael Espindola67080ce2013-07-19 15:02:03 +0000755 sys::fs::OpenFlags Flags, unsigned Mode) {
756 // Verify that we don't have both "append" and "excl".
757 assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
758 "Cannot specify both 'excl' and 'append' file creation flags!");
759
760 SmallString<128> PathStorage;
761 SmallVector<wchar_t, 128> PathUTF16;
762
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000763 if (std::error_code EC =
764 UTF8ToUTF16(Name.toStringRef(PathStorage), PathUTF16))
Rafael Espindola67080ce2013-07-19 15:02:03 +0000765 return EC;
766
767 DWORD CreationDisposition;
768 if (Flags & F_Excl)
769 CreationDisposition = CREATE_NEW;
NAKAMURA Takumiedf76152013-08-22 15:14:45 +0000770 else if (Flags & F_Append)
Rafael Espindola67080ce2013-07-19 15:02:03 +0000771 CreationDisposition = OPEN_ALWAYS;
772 else
773 CreationDisposition = CREATE_ALWAYS;
774
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000775 DWORD Access = GENERIC_WRITE;
776 if (Flags & F_RW)
777 Access |= GENERIC_READ;
778
779 HANDLE H = ::CreateFileW(PathUTF16.begin(), Access,
Rafael Espindola67080ce2013-07-19 15:02:03 +0000780 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
781 CreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL);
782
783 if (H == INVALID_HANDLE_VALUE) {
Rafael Espindolaa813d602014-06-11 03:58:34 +0000784 DWORD LastError = ::GetLastError();
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000785 std::error_code EC = windows_error(LastError);
Rafael Espindola67080ce2013-07-19 15:02:03 +0000786 // Provide a better error message when trying to open directories.
787 // This only runs if we failed to open the file, so there is probably
788 // no performances issues.
Rafael Espindolaa813d602014-06-11 03:58:34 +0000789 if (LastError != ERROR_ACCESS_DENIED)
Rafael Espindola67080ce2013-07-19 15:02:03 +0000790 return EC;
791 if (is_directory(Name))
Rafael Espindola2a826e42014-06-13 17:20:48 +0000792 return make_error_code(errc::is_a_directory);
Rafael Espindola67080ce2013-07-19 15:02:03 +0000793 return EC;
794 }
795
796 int OpenFlags = 0;
797 if (Flags & F_Append)
798 OpenFlags |= _O_APPEND;
799
Rafael Espindola90c7f1c2014-02-24 18:20:12 +0000800 if (Flags & F_Text)
Rafael Espindola67080ce2013-07-19 15:02:03 +0000801 OpenFlags |= _O_TEXT;
802
803 int FD = ::_open_osfhandle(intptr_t(H), OpenFlags);
804 if (FD == -1) {
805 ::CloseHandle(H);
Rafael Espindolaa813d602014-06-11 03:58:34 +0000806 return windows_error(ERROR_INVALID_HANDLE);
Rafael Espindola67080ce2013-07-19 15:02:03 +0000807 }
808
809 ResultFD = FD;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000810 return std::error_code();
Rafael Espindola67080ce2013-07-19 15:02:03 +0000811}
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000812} // end namespace fs
Rui Ueyama471d0c52013-09-10 19:45:51 +0000813
Peter Collingbournef7d41012014-01-31 23:46:06 +0000814namespace path {
815
816bool home_directory(SmallVectorImpl<char> &result) {
817 wchar_t Path[MAX_PATH];
818 if (::SHGetFolderPathW(0, CSIDL_APPDATA | CSIDL_FLAG_CREATE, 0,
Peter Collingbournead141ab2014-02-01 02:42:20 +0000819 /*SHGFP_TYPE_CURRENT*/0, Path) != S_OK)
Peter Collingbournef7d41012014-01-31 23:46:06 +0000820 return false;
821
822 if (UTF16ToUTF8(Path, ::wcslen(Path), result))
823 return false;
824
825 return true;
826}
827
Rafael Espindola016a6d52014-08-26 14:47:52 +0000828static bool getTempDirEnvVar(const char *Var, SmallVectorImpl<char> &Res) {
829 SmallVector<wchar_t, 128> NameUTF16;
830 if (windows::UTF8ToUTF16(Var, NameUTF16))
831 return false;
832
833 SmallVector<wchar_t, 1024> Buf;
834 size_t Size = 1024;
835 do {
836 Buf.reserve(Size);
837 Size =
838 GetEnvironmentVariableW(NameUTF16.data(), Buf.data(), Buf.capacity());
839 if (Size == 0)
840 return false;
841
842 // Try again with larger buffer.
843 } while (Size > Buf.capacity());
844 Buf.set_size(Size);
845
846 if (windows::UTF16ToUTF8(Buf.data(), Size, Res))
847 return false;
848 return true;
849}
850
851static bool getTempDirEnvVar(SmallVectorImpl<char> &Res) {
852 const char *EnvironmentVariables[] = {"TMP", "TEMP", "USERPROFILE"};
853 for (const char *Env : EnvironmentVariables) {
854 if (getTempDirEnvVar(Env, Res))
855 return true;
856 }
857 return false;
858}
859
860void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
861 (void)ErasedOnReboot;
862 Result.clear();
863
864 // Check whether the temporary directory is specified by an environment
865 // variable.
866 if (getTempDirEnvVar(Result))
867 return;
868
869 // Fall back to a system default.
870 const char *DefaultResult = "C:\\TEMP";
871 Result.append(DefaultResult, DefaultResult + strlen(DefaultResult));
872}
Peter Collingbournef7d41012014-01-31 23:46:06 +0000873} // end namespace path
874
Rui Ueyama471d0c52013-09-10 19:45:51 +0000875namespace windows {
Rafael Espindola0a5f9cf2014-06-12 14:11:22 +0000876std::error_code UTF8ToUTF16(llvm::StringRef utf8,
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000877 llvm::SmallVectorImpl<wchar_t> &utf16) {
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000878 if (!utf8.empty()) {
879 int len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
880 utf8.size(), utf16.begin(), 0);
Rui Ueyama471d0c52013-09-10 19:45:51 +0000881
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000882 if (len == 0)
Rafael Espindolaa813d602014-06-11 03:58:34 +0000883 return windows_error(::GetLastError());
Rui Ueyama471d0c52013-09-10 19:45:51 +0000884
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000885 utf16.reserve(len + 1);
886 utf16.set_size(len);
Rui Ueyama471d0c52013-09-10 19:45:51 +0000887
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000888 len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
889 utf8.size(), utf16.begin(), utf16.size());
Rui Ueyama471d0c52013-09-10 19:45:51 +0000890
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000891 if (len == 0)
Rafael Espindolaa813d602014-06-11 03:58:34 +0000892 return windows_error(::GetLastError());
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000893 }
Rui Ueyama471d0c52013-09-10 19:45:51 +0000894
895 // Make utf16 null terminated.
896 utf16.push_back(0);
897 utf16.pop_back();
898
Rafael Espindola0a5f9cf2014-06-12 14:11:22 +0000899 return std::error_code();
Rui Ueyama471d0c52013-09-10 19:45:51 +0000900}
901
Rafael Espindola9c359662014-09-03 20:02:00 +0000902static
903std::error_code UTF16ToCodePage(unsigned codepage, const wchar_t *utf16,
904 size_t utf16_len,
905 llvm::SmallVectorImpl<char> &utf8) {
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000906 if (utf16_len) {
907 // Get length.
Rafael Espindola9c359662014-09-03 20:02:00 +0000908 int len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, utf8.begin(),
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000909 0, 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());
Rui Ueyama471d0c52013-09-10 19:45:51 +0000913
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000914 utf8.reserve(len);
915 utf8.set_size(len);
Rui Ueyama471d0c52013-09-10 19:45:51 +0000916
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000917 // Now do the actual conversion.
Rafael Espindola9c359662014-09-03 20:02:00 +0000918 len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, utf8.data(),
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000919 utf8.size(), NULL, NULL);
Rui Ueyama471d0c52013-09-10 19:45:51 +0000920
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000921 if (len == 0)
Rafael Espindolaa813d602014-06-11 03:58:34 +0000922 return windows_error(::GetLastError());
Michael J. Spencer7a3a5102014-02-20 20:46:23 +0000923 }
Rui Ueyama471d0c52013-09-10 19:45:51 +0000924
925 // Make utf8 null terminated.
926 utf8.push_back(0);
927 utf8.pop_back();
928
Rafael Espindola0a5f9cf2014-06-12 14:11:22 +0000929 return std::error_code();
Rui Ueyama471d0c52013-09-10 19:45:51 +0000930}
Rafael Espindola9c359662014-09-03 20:02:00 +0000931
932std::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
933 llvm::SmallVectorImpl<char> &utf8) {
934 return UTF16ToCodePage(CP_UTF8, utf16, utf16_len, utf8);
935}
936
937std::error_code UTF16ToCurCP(const wchar_t *utf16, size_t utf16_len,
938 llvm::SmallVectorImpl<char> &utf8) {
939 return UTF16ToCodePage(CP_ACP, utf16, utf16_len, utf8);
940}
Rui Ueyama471d0c52013-09-10 19:45:51 +0000941} // end namespace windows
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000942} // end namespace sys
943} // end namespace llvm