blob: f4898e619abfa6499f2ba17c1e26ed94c6cdd86e [file] [log] [blame]
Charles Davis54c9eb62010-11-29 19:44:50 +00001//===- llvm/Support/Win32/Path.cpp - Win32 Path Implementation ---*- C++ -*-===//
Reid Spencerb88212e2004-09-15 05:49:50 +00002//
Reid Spencer566ac282004-09-11 04:59:30 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencerb88212e2004-09-15 05:49:50 +00007//
Reid Spencer566ac282004-09-11 04:59:30 +00008//===----------------------------------------------------------------------===//
9//
10// This file provides the Win32 specific implementation of the Path class.
11//
12//===----------------------------------------------------------------------===//
13
14//===----------------------------------------------------------------------===//
Reid Spencerb88212e2004-09-15 05:49:50 +000015//=== WARNING: Implementation here must contain only generic Win32 code that
16//=== is guaranteed to work on *all* Win32 variants.
Reid Spencer566ac282004-09-11 04:59:30 +000017//===----------------------------------------------------------------------===//
18
Michael J. Spencer447762d2010-11-29 18:16:10 +000019#include "Windows.h"
Chris Lattner7e064432009-04-01 02:03:38 +000020#include <cstdio>
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include <malloc.h>
Reid Spencer566ac282004-09-11 04:59:30 +000022
Jeff Cohend567bb62004-12-24 02:38:34 +000023// We need to undo a macro defined in Windows.h, otherwise we won't compile:
24#undef CopyFile
Anton Korobeynikov2ffb2c92007-12-22 14:26:49 +000025#undef GetCurrentDirectory
Jeff Cohend567bb62004-12-24 02:38:34 +000026
Jeff Cohen0aad91a2005-07-09 18:42:49 +000027// Windows happily accepts either forward or backward slashes, though any path
28// returned by a Win32 API will have backward slashes. As LLVM code basically
29// assumes forward slashes are used, backward slashs are converted where they
30// can be introduced into a path.
31//
32// Another invariant is that a path ends with a slash if and only if the path
33// is a root directory. Any other use of a trailing slash is stripped. Unlike
34// in Unix, Windows has a rather complicated notion of a root path and this
35// invariant helps simply the code.
36
Reid Spencer7aed4482004-09-29 00:01:17 +000037static void FlipBackSlashes(std::string& s) {
38 for (size_t i = 0; i < s.size(); i++)
39 if (s[i] == '\\')
40 s[i] = '/';
41}
42
Reid Spencer566ac282004-09-11 04:59:30 +000043namespace llvm {
Reid Spencerb88212e2004-09-15 05:49:50 +000044namespace sys {
Mikhail Glushenkovfcfaf512010-11-02 20:32:26 +000045
Chris Lattner4dec9122008-03-13 05:17:59 +000046const char PathSeparator = ';';
Chris Lattner6fca9382008-02-27 06:17:10 +000047
Mikhail Glushenkovfcfaf512010-11-02 20:32:26 +000048StringRef Path::GetEXESuffix() {
49 return "exe";
50}
51
Daniel Dunbarcf7744e2009-12-18 19:59:48 +000052Path::Path(llvm::StringRef p)
Nick Lewyckyc38c1712008-05-11 17:37:40 +000053 : path(p) {
54 FlipBackSlashes(path);
55}
56
57Path::Path(const char *StrStart, unsigned StrLen)
58 : path(StrStart, StrLen) {
59 FlipBackSlashes(path);
60}
61
Chris Lattnerb56e07e2008-08-11 23:39:47 +000062Path&
Jeffrey Yasskin5908f1e2009-12-17 21:02:39 +000063Path::operator=(StringRef that) {
64 path.assign(that.data(), that.size());
Chris Lattnerb56e07e2008-08-11 23:39:47 +000065 FlipBackSlashes(path);
66 return *this;
67}
68
Reid Spencerb88212e2004-09-15 05:49:50 +000069bool
Reid Spencer0c6a2832004-11-05 22:15:36 +000070Path::isValid() const {
Reid Spencerb88212e2004-09-15 05:49:50 +000071 if (path.empty())
72 return false;
Reid Spencer0e863362004-09-18 19:29:16 +000073
NAKAMURA Takumi66c9e4f2011-10-24 03:27:19 +000074 size_t len = path.size();
75 // If there is a null character, it and all its successors are ignored.
76 size_t pos = path.find_first_of('\0');
77 if (pos != std::string::npos)
78 len = pos;
79
Reid Spencer7aed4482004-09-29 00:01:17 +000080 // If there is a colon, it must be the second character, preceded by a letter
81 // and followed by something.
NAKAMURA Takumi66c9e4f2011-10-24 03:27:19 +000082 pos = path.rfind(':',len);
Jeff Cohen0e1d7352005-07-08 04:50:08 +000083 size_t rootslash = 0;
Reid Spencer7aed4482004-09-29 00:01:17 +000084 if (pos != std::string::npos) {
Guy Benyei83c74e92013-02-12 21:21:59 +000085 if (pos != 1 || !isalpha(static_cast<unsigned char>(path[0])) || len < 3)
Reid Spencer7aed4482004-09-29 00:01:17 +000086 return false;
Jeff Cohen0e1d7352005-07-08 04:50:08 +000087 rootslash = 2;
88 }
Jeff Cohenf5067762005-07-08 05:02:13 +000089
Jeff Cohen0e1d7352005-07-08 04:50:08 +000090 // Look for a UNC path, and if found adjust our notion of the root slash.
91 if (len > 3 && path[0] == '/' && path[1] == '/') {
92 rootslash = path.find('/', 2);
93 if (rootslash == std::string::npos)
94 rootslash = 0;
Reid Spencer7aed4482004-09-29 00:01:17 +000095 }
Reid Spencer0e863362004-09-18 19:29:16 +000096
Reid Spencer7aed4482004-09-29 00:01:17 +000097 // Check for illegal characters.
98 if (path.find_first_of("\\<>\"|\001\002\003\004\005\006\007\010\011\012"
99 "\013\014\015\016\017\020\021\022\023\024\025\026"
100 "\027\030\031\032\033\034\035\036\037")
101 != std::string::npos)
102 return false;
Jeff Cohenf5067762005-07-08 05:02:13 +0000103
Jeff Cohen0e1d7352005-07-08 04:50:08 +0000104 // Remove trailing slash, unless it's a root slash.
105 if (len > rootslash+1 && path[len-1] == '/')
106 path.erase(--len);
Reid Spencer7aed4482004-09-29 00:01:17 +0000107
Jeff Cohene246cdc2005-01-14 04:09:39 +0000108 // Check each component for legality.
109 for (pos = 0; pos < len; ++pos) {
110 // A component may not end in a space.
111 if (path[pos] == ' ') {
NAKAMURA Takumi66c9e4f2011-10-24 03:27:19 +0000112 if (pos+1 == len || path[pos+1] == '/' || path[pos+1] == '\0')
Jeff Cohene246cdc2005-01-14 04:09:39 +0000113 return false;
114 }
Reid Spencer7aed4482004-09-29 00:01:17 +0000115
Jeff Cohene246cdc2005-01-14 04:09:39 +0000116 // A component may not end in a period.
117 if (path[pos] == '.') {
NAKAMURA Takumi66c9e4f2011-10-24 03:27:19 +0000118 if (pos+1 == len || path[pos+1] == '/') {
Jeff Cohene246cdc2005-01-14 04:09:39 +0000119 // Unless it is the pseudo-directory "."...
120 if (pos == 0 || path[pos-1] == '/' || path[pos-1] == ':')
121 return true;
122 // or "..".
123 if (pos > 0 && path[pos-1] == '.') {
124 if (pos == 1 || path[pos-2] == '/' || path[pos-2] == ':')
125 return true;
126 }
127 return false;
128 }
129 }
130 }
Reid Spencer7aed4482004-09-29 00:01:17 +0000131
132 return true;
Reid Spencer566ac282004-09-11 04:59:30 +0000133}
134
Daniel Dunbardf555fd2009-07-12 20:23:56 +0000135void Path::makeAbsolute() {
Kovarththanan Rajaratnam61bea8f2010-03-12 14:17:24 +0000136 TCHAR FullPath[MAX_PATH + 1] = {0};
Daniel Dunbardf555fd2009-07-12 20:23:56 +0000137 LPTSTR FilePart = NULL;
138
139 DWORD RetLength = ::GetFullPathNameA(path.c_str(),
140 sizeof(FullPath)/sizeof(FullPath[0]),
141 FullPath, &FilePart);
142
143 if (0 == RetLength) {
144 // FIXME: Report the error GetLastError()
Daniel Dunbarbcd92f12009-07-26 21:16:42 +0000145 assert(0 && "Unable to make absolute path!");
Daniel Dunbardf555fd2009-07-12 20:23:56 +0000146 } else if (RetLength > MAX_PATH) {
147 // FIXME: Report too small buffer (needed RetLength bytes).
Daniel Dunbarbcd92f12009-07-26 21:16:42 +0000148 assert(0 && "Unable to make absolute path!");
Daniel Dunbardf555fd2009-07-12 20:23:56 +0000149 } else {
150 path = FullPath;
151 }
152}
153
Chris Lattner3f556da2009-06-15 04:17:07 +0000154bool
155Path::isAbsolute(const char *NameStart, unsigned NameLen) {
156 assert(NameStart);
Daniel Dunbardf555fd2009-07-12 20:23:56 +0000157 // FIXME: This does not handle correctly an absolute path starting from
158 // a drive letter or in UNC format.
Chris Lattner3f556da2009-06-15 04:17:07 +0000159 switch (NameLen) {
160 case 0:
161 return false;
162 case 1:
163 case 2:
164 return NameStart[0] == '/';
165 default:
Mikhail Glushenkovb4921a02010-11-02 20:32:31 +0000166 return
167 (NameStart[0] == '/' || (NameStart[1] == ':' && NameStart[2] == '/')) ||
168 (NameStart[0] == '\\' || (NameStart[1] == ':' && NameStart[2] == '\\'));
Chris Lattner3f556da2009-06-15 04:17:07 +0000169 }
170}
171
Kovarththanan Rajaratnam61bea8f2010-03-12 14:17:24 +0000172bool
Reid Spencer0f92f0e2007-03-29 16:43:20 +0000173Path::isAbsolute() const {
Daniel Dunbardf555fd2009-07-12 20:23:56 +0000174 // FIXME: This does not handle correctly an absolute path starting from
175 // a drive letter or in UNC format.
Jeff Cohen60c55222007-03-29 17:27:38 +0000176 switch (path.length()) {
177 case 0:
178 return false;
179 case 1:
180 case 2:
181 return path[0] == '/';
182 default:
183 return path[0] == '/' || (path[1] == ':' && path[2] == '/');
184 }
Kovarththanan Rajaratnam61bea8f2010-03-12 14:17:24 +0000185}
Reid Spencer0f92f0e2007-03-29 16:43:20 +0000186
Kovarththanan Rajaratnam61bea8f2010-03-12 14:17:24 +0000187static Path *TempDirectory;
Reid Spencer0e863362004-09-18 19:29:16 +0000188
Reid Spencerb88212e2004-09-15 05:49:50 +0000189Path
Reid Spencer7e73c5132006-08-22 22:46:39 +0000190Path::GetTemporaryDirectory(std::string* ErrMsg) {
NAKAMURA Takumib030e8a2012-05-27 13:02:04 +0000191 if (TempDirectory) {
Aaron Ballman36a978c2012-06-09 13:59:29 +0000192#if defined(_MSC_VER)
193 // Visual Studio gets confused and emits a diagnostic about calling exists,
194 // even though this is the implementation for PathV1. Temporarily
195 // disable the deprecated warning message
196 #pragma warning(push)
197 #pragma warning(disable:4996)
198#endif
NAKAMURA Takumib030e8a2012-05-27 13:02:04 +0000199 assert(TempDirectory->exists() && "Who has removed TempDirectory?");
Aaron Ballman36a978c2012-06-09 13:59:29 +0000200#if defined(_MSC_VER)
201 #pragma warning(pop)
202#endif
Reid Spencer0e863362004-09-18 19:29:16 +0000203 return *TempDirectory;
NAKAMURA Takumib030e8a2012-05-27 13:02:04 +0000204 }
Reid Spencer0e863362004-09-18 19:29:16 +0000205
206 char pathname[MAX_PATH];
Reid Spencer7e73c5132006-08-22 22:46:39 +0000207 if (!GetTempPath(MAX_PATH, pathname)) {
208 if (ErrMsg)
209 *ErrMsg = "Can't determine temporary directory";
210 return Path();
211 }
Reid Spencer0e863362004-09-18 19:29:16 +0000212
Reid Spencerb88212e2004-09-15 05:49:50 +0000213 Path result;
Reid Spencer17c1bd32005-07-07 23:35:23 +0000214 result.set(pathname);
Reid Spencer0e863362004-09-18 19:29:16 +0000215
Aaron Ballman503bbff32012-06-09 13:46:36 +0000216 // Append a subdirectory based on our process id so multiple LLVMs don't
Reid Spencer0e863362004-09-18 19:29:16 +0000217 // step on each other's toes.
Jeff Cohen7d6f3db2006-11-05 19:31:28 +0000218#ifdef __MINGW32__
219 // Mingw's Win32 header files are broken.
Reid Spencer36bc2b02006-06-08 18:08:43 +0000220 sprintf(pathname, "LLVM_%u", unsigned(GetCurrentProcessId()));
Jeff Cohen7d6f3db2006-11-05 19:31:28 +0000221#else
222 sprintf(pathname, "LLVM_%u", GetCurrentProcessId());
223#endif
Jeff Cohen215db902005-07-08 02:48:42 +0000224 result.appendComponent(pathname);
Reid Spencer0e863362004-09-18 19:29:16 +0000225
226 // If there's a directory left over from a previous LLVM execution that
227 // happened to have the same process id, get rid of it.
Reid Spenceraf48d862005-07-08 03:08:58 +0000228 result.eraseFromDisk(true);
Reid Spencer0e863362004-09-18 19:29:16 +0000229
230 // And finally (re-)create the empty directory.
Reid Spenceraf48d862005-07-08 03:08:58 +0000231 result.createDirectoryOnDisk(false);
Reid Spencer0e863362004-09-18 19:29:16 +0000232 TempDirectory = new Path(result);
233 return *TempDirectory;
Reid Spencerb88212e2004-09-15 05:49:50 +0000234}
235
Reid Spencer0e863362004-09-18 19:29:16 +0000236// FIXME: the following set of functions don't map to Windows very well.
Reid Spencerb88212e2004-09-15 05:49:50 +0000237Path
238Path::GetRootDirectory() {
Michael J. Spencerdf929cf2010-11-09 15:10:45 +0000239 // This is the only notion that that Windows has of a root directory. Nothing
240 // is here except for drives.
241 return Path("file:///");
Reid Spencerb88212e2004-09-15 05:49:50 +0000242}
243
Jeff Cohenf5067762005-07-08 05:02:13 +0000244void
Reid Spencer0a0d5822004-12-13 03:03:42 +0000245Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
Michael J. Spencer181fd8c2010-11-09 15:11:19 +0000246 char buff[MAX_PATH];
247 // Generic form of C:\Windows\System32
248 HRESULT res = SHGetFolderPathA(NULL,
249 CSIDL_FLAG_CREATE | CSIDL_SYSTEM,
250 NULL,
251 SHGFP_TYPE_CURRENT,
252 buff);
253 if (res != S_OK) {
254 assert(0 && "Failed to get system directory");
255 return;
256 }
257 Paths.push_back(sys::Path(buff));
258
259 // Reset buff.
260 buff[0] = 0;
261 // Generic form of C:\Windows
262 res = SHGetFolderPathA(NULL,
263 CSIDL_FLAG_CREATE | CSIDL_WINDOWS,
264 NULL,
265 SHGFP_TYPE_CURRENT,
266 buff);
267 if (res != S_OK) {
268 assert(0 && "Failed to get windows directory");
269 return;
270 }
271 Paths.push_back(sys::Path(buff));
Reid Spencer0e863362004-09-18 19:29:16 +0000272}
273
Reid Spencer0a0d5822004-12-13 03:03:42 +0000274void
Gabor Greif24027b52007-07-06 20:28:40 +0000275Path::GetBitcodeLibraryPaths(std::vector<sys::Path>& Paths) {
Reid Spencer0a0d5822004-12-13 03:03:42 +0000276 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
277 if (env_var != 0) {
278 getPathList(env_var,Paths);
279 }
Reid Spencer0a0d5822004-12-13 03:03:42 +0000280#ifdef LLVM_LIBDIR
281 {
282 Path tmpPath;
Reid Spencer17c1bd32005-07-07 23:35:23 +0000283 if (tmpPath.set(LLVM_LIBDIR))
Reid Spencer5b891e92005-07-07 18:21:42 +0000284 if (tmpPath.canRead())
Reid Spencer0a0d5822004-12-13 03:03:42 +0000285 Paths.push_back(tmpPath);
286 }
287#endif
288 GetSystemLibraryPaths(Paths);
Reid Spencerb88212e2004-09-15 05:49:50 +0000289}
290
291Path
Reid Spencerb88212e2004-09-15 05:49:50 +0000292Path::GetUserHomeDirectory() {
Michael J. Spencer86cdb422010-11-09 15:11:31 +0000293 char buff[MAX_PATH];
Michael J. Spencerb39a8972010-11-10 15:06:00 +0000294 HRESULT res = SHGetFolderPathA(NULL,
295 CSIDL_FLAG_CREATE | CSIDL_APPDATA,
296 NULL,
297 SHGFP_TYPE_CURRENT,
298 buff);
Michael J. Spencer86cdb422010-11-09 15:11:31 +0000299 if (res != S_OK)
300 assert(0 && "Failed to get user home directory");
301 return Path(buff);
Reid Spencerb88212e2004-09-15 05:49:50 +0000302}
Ted Kremenek14020702007-12-18 22:07:33 +0000303
304Path
305Path::GetCurrentDirectory() {
306 char pathname[MAX_PATH];
Anton Korobeynikov2ffb2c92007-12-22 14:26:49 +0000307 ::GetCurrentDirectoryA(MAX_PATH,pathname);
Kovarththanan Rajaratnam61bea8f2010-03-12 14:17:24 +0000308 return Path(pathname);
Ted Kremenek14020702007-12-18 22:07:33 +0000309}
310
Chris Lattnere209be42008-03-03 02:55:43 +0000311/// GetMainExecutable - Return the path to the main executable, given the
312/// value of argv[0] from program startup.
313Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
Chris Lattner7038cd522009-06-15 05:38:04 +0000314 char pathname[MAX_PATH];
315 DWORD ret = ::GetModuleFileNameA(NULL, pathname, MAX_PATH);
316 return ret != MAX_PATH ? Path(pathname) : Path();
Chris Lattnere209be42008-03-03 02:55:43 +0000317}
318
Ted Kremenek14020702007-12-18 22:07:33 +0000319
Reid Spencer0e863362004-09-18 19:29:16 +0000320// FIXME: the above set of functions don't map to Windows very well.
321
Jeff Cohen0aad91a2005-07-09 18:42:49 +0000322
Jeffrey Yasskin5908f1e2009-12-17 21:02:39 +0000323StringRef Path::getDirname() const {
324 return getDirnameCharSep(path, "/");
Ted Kremeneka518bb72008-04-07 22:01:32 +0000325}
Ted Kremenekc042bf12008-04-07 21:53:57 +0000326
Jeffrey Yasskin5908f1e2009-12-17 21:02:39 +0000327StringRef
Reid Spencer0c6a2832004-11-05 22:15:36 +0000328Path::getBasename() const {
Reid Spencer0e863362004-09-18 19:29:16 +0000329 // Find the last slash
330 size_t slash = path.rfind('/');
331 if (slash == std::string::npos)
332 slash = 0;
333 else
334 slash++;
335
Jeff Cohen0aad91a2005-07-09 18:42:49 +0000336 size_t dot = path.rfind('.');
337 if (dot == std::string::npos || dot < slash)
Jeffrey Yasskin5908f1e2009-12-17 21:02:39 +0000338 return StringRef(path).substr(slash);
Jeff Cohen0aad91a2005-07-09 18:42:49 +0000339 else
Jeffrey Yasskin5908f1e2009-12-17 21:02:39 +0000340 return StringRef(path).substr(slash, dot - slash);
Reid Spencer0e863362004-09-18 19:29:16 +0000341}
342
Jeffrey Yasskin5908f1e2009-12-17 21:02:39 +0000343StringRef
Argyrios Kyrtzidis2cc0abf2008-06-15 15:15:19 +0000344Path::getSuffix() const {
345 // Find the last slash
346 size_t slash = path.rfind('/');
347 if (slash == std::string::npos)
348 slash = 0;
349 else
350 slash++;
351
352 size_t dot = path.rfind('.');
353 if (dot == std::string::npos || dot < slash)
Jeffrey Yasskin5908f1e2009-12-17 21:02:39 +0000354 return StringRef("");
Argyrios Kyrtzidis2cc0abf2008-06-15 15:15:19 +0000355 else
Jeffrey Yasskin5908f1e2009-12-17 21:02:39 +0000356 return StringRef(path).substr(dot + 1);
Argyrios Kyrtzidis2cc0abf2008-06-15 15:15:19 +0000357}
358
Reid Spencer0e863362004-09-18 19:29:16 +0000359bool
Reid Spencerb88212e2004-09-15 05:49:50 +0000360Path::exists() const {
Reid Spencer0e863362004-09-18 19:29:16 +0000361 DWORD attr = GetFileAttributes(path.c_str());
362 return attr != INVALID_FILE_ATTRIBUTES;
Reid Spencerb88212e2004-09-15 05:49:50 +0000363}
364
365bool
Ted Kremenek74db0422007-12-18 19:46:22 +0000366Path::isDirectory() const {
367 DWORD attr = GetFileAttributes(path.c_str());
368 return (attr != INVALID_FILE_ATTRIBUTES) &&
369 (attr & FILE_ATTRIBUTE_DIRECTORY);
370}
371
372bool
Rafael Espindola559b8fb2010-11-07 04:36:50 +0000373Path::isSymLink() const {
Michael J. Spencer909d238e2010-11-10 15:05:39 +0000374 DWORD attributes = GetFileAttributes(path.c_str());
375
376 if (attributes == INVALID_FILE_ATTRIBUTES)
377 // There's no sane way to report this :(.
378 assert(0 && "GetFileAttributes returned INVALID_FILE_ATTRIBUTES");
379
380 // This isn't exactly what defines a NTFS symlink, but it is only true for
381 // paths that act like a symlink.
382 return attributes & FILE_ATTRIBUTE_REPARSE_POINT;
Rafael Espindola559b8fb2010-11-07 04:36:50 +0000383}
384
385bool
Reid Spencer5b891e92005-07-07 18:21:42 +0000386Path::canRead() const {
Reid Spencer0e863362004-09-18 19:29:16 +0000387 // FIXME: take security attributes into account.
388 DWORD attr = GetFileAttributes(path.c_str());
389 return attr != INVALID_FILE_ATTRIBUTES;
Reid Spencerb88212e2004-09-15 05:49:50 +0000390}
391
392bool
Reid Spencer5b891e92005-07-07 18:21:42 +0000393Path::canWrite() const {
Reid Spencer0e863362004-09-18 19:29:16 +0000394 // FIXME: take security attributes into account.
395 DWORD attr = GetFileAttributes(path.c_str());
396 return (attr != INVALID_FILE_ATTRIBUTES) && !(attr & FILE_ATTRIBUTE_READONLY);
Reid Spencerb88212e2004-09-15 05:49:50 +0000397}
398
399bool
Reid Spencer5b891e92005-07-07 18:21:42 +0000400Path::canExecute() const {
Reid Spencer0e863362004-09-18 19:29:16 +0000401 // FIXME: take security attributes into account.
402 DWORD attr = GetFileAttributes(path.c_str());
403 return attr != INVALID_FILE_ATTRIBUTES;
Reid Spencerb88212e2004-09-15 05:49:50 +0000404}
405
Edward O'Callaghandddf1342009-11-24 15:19:10 +0000406bool
Edward O'Callaghan746782d2009-11-25 06:32:19 +0000407Path::isRegularFile() const {
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000408 bool res;
409 if (fs::is_regular_file(path, res))
Edward O'Callaghan746782d2009-11-25 06:32:19 +0000410 return false;
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000411 return res;
Edward O'Callaghandddf1342009-11-24 15:19:10 +0000412}
413
Jeffrey Yasskin5908f1e2009-12-17 21:02:39 +0000414StringRef
Reid Spencerb88212e2004-09-15 05:49:50 +0000415Path::getLast() const {
416 // Find the last slash
417 size_t pos = path.rfind('/');
418
419 // Handle the corner cases
420 if (pos == std::string::npos)
421 return path;
422
Jeff Cohen0e1d7352005-07-08 04:50:08 +0000423 // If the last character is a slash, we have a root directory
424 if (pos == path.length()-1)
425 return path;
426
Reid Spencerb88212e2004-09-15 05:49:50 +0000427 // Return everything after the last slash
Jeffrey Yasskin5908f1e2009-12-17 21:02:39 +0000428 return StringRef(path).substr(pos+1);
Reid Spencerb88212e2004-09-15 05:49:50 +0000429}
430
Reid Spencer200c6f92007-03-29 19:05:44 +0000431const FileStatus *
Reid Spencerceeb9182007-04-07 18:52:17 +0000432PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
433 if (!fsIsValid || update) {
Reid Spencer0f92f0e2007-03-29 16:43:20 +0000434 WIN32_FILE_ATTRIBUTE_DATA fi;
Reid Spencer200c6f92007-03-29 19:05:44 +0000435 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
436 MakeErrMsg(ErrStr, "getStatusInfo():" + std::string(path) +
Reid Spencer0f92f0e2007-03-29 16:43:20 +0000437 ": Can't get status: ");
Reid Spencer200c6f92007-03-29 19:05:44 +0000438 return 0;
439 }
Jeff Cohen2b60d392004-12-14 05:26:43 +0000440
Reid Spencerceeb9182007-04-07 18:52:17 +0000441 status.fileSize = fi.nFileSizeHigh;
442 status.fileSize <<= sizeof(fi.nFileSizeHigh)*8;
443 status.fileSize += fi.nFileSizeLow;
Jeff Cohen2b60d392004-12-14 05:26:43 +0000444
Reid Spencerceeb9182007-04-07 18:52:17 +0000445 status.mode = fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY ? 0555 : 0777;
446 status.user = 9999; // Not applicable to Windows, so...
447 status.group = 9999; // Not applicable to Windows, so...
Jeff Cohen2b60d392004-12-14 05:26:43 +0000448
Reid Spencerd3946172007-03-29 17:00:31 +0000449 // FIXME: this is only unique if the file is accessed by the same file path.
450 // How do we do this for C:\dir\file and ..\dir\file ? Unix has inode
451 // numbers, but the concept doesn't exist in Windows.
Reid Spencerceeb9182007-04-07 18:52:17 +0000452 status.uniqueID = 0;
Reid Spencerd3946172007-03-29 17:00:31 +0000453 for (unsigned i = 0; i < path.length(); ++i)
Reid Spencerceeb9182007-04-07 18:52:17 +0000454 status.uniqueID += path[i];
Reid Spencerd3946172007-03-29 17:00:31 +0000455
Michael J. Spencerd75cf222010-08-28 16:39:32 +0000456 ULARGE_INTEGER ui;
457 ui.LowPart = fi.ftLastWriteTime.dwLowDateTime;
458 ui.HighPart = fi.ftLastWriteTime.dwHighDateTime;
459 status.modTime.fromWin32Time(ui.QuadPart);
Reid Spencer0f92f0e2007-03-29 16:43:20 +0000460
Reid Spencerceeb9182007-04-07 18:52:17 +0000461 status.isDir = fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
462 fsIsValid = true;
Reid Spencer0f92f0e2007-03-29 16:43:20 +0000463 }
Reid Spencerceeb9182007-04-07 18:52:17 +0000464 return &status;
Jeff Cohen2b60d392004-12-14 05:26:43 +0000465}
466
Reid Spencera1a7a352006-08-22 23:54:35 +0000467bool Path::makeReadableOnDisk(std::string* ErrMsg) {
Jeff Cohen2b60d392004-12-14 05:26:43 +0000468 // All files are readable on Windows (ignoring security attributes).
Reid Spencera1a7a352006-08-22 23:54:35 +0000469 return false;
Reid Spencer94bf2262004-12-13 19:59:50 +0000470}
471
Anton Korobeynikov6c6a70f2006-09-01 20:35:17 +0000472bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
Jeff Cohen2b60d392004-12-14 05:26:43 +0000473 DWORD attr = GetFileAttributes(path.c_str());
474
475 // If it doesn't exist, we're done.
476 if (attr == INVALID_FILE_ATTRIBUTES)
Anton Korobeynikov6c6a70f2006-09-01 20:35:17 +0000477 return false;
Jeff Cohen2b60d392004-12-14 05:26:43 +0000478
479 if (attr & FILE_ATTRIBUTE_READONLY) {
Reid Spencera1a7a352006-08-22 23:54:35 +0000480 if (!SetFileAttributes(path.c_str(), attr & ~FILE_ATTRIBUTE_READONLY)) {
481 MakeErrMsg(ErrMsg, std::string(path) + ": Can't make file writable: ");
482 return true;
483 }
Jeff Cohen2b60d392004-12-14 05:26:43 +0000484 }
Reid Spencera1a7a352006-08-22 23:54:35 +0000485 return false;
Reid Spencer94bf2262004-12-13 19:59:50 +0000486}
487
Reid Spencera1a7a352006-08-22 23:54:35 +0000488bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
Jeff Cohen2b60d392004-12-14 05:26:43 +0000489 // All files are executable on Windows (ignoring security attributes).
Reid Spencera1a7a352006-08-22 23:54:35 +0000490 return false;
Reid Spencer94bf2262004-12-13 19:59:50 +0000491}
492
Reid Spencerb88212e2004-09-15 05:49:50 +0000493bool
Reid Spencer51edba12006-08-23 06:56:27 +0000494Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
Jeff Cohen79582362007-04-07 20:47:27 +0000495 WIN32_FILE_ATTRIBUTE_DATA fi;
496 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
497 MakeErrMsg(ErrMsg, path + ": can't get status of file");
Anton Korobeynikov6c6a70f2006-09-01 20:35:17 +0000498 return true;
Jeff Cohen79582362007-04-07 20:47:27 +0000499 }
Kovarththanan Rajaratnam61bea8f2010-03-12 14:17:24 +0000500
Jeff Cohen79582362007-04-07 20:47:27 +0000501 if (!(fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
502 if (ErrMsg)
503 *ErrMsg = path + ": not a directory";
Reid Spencer51edba12006-08-23 06:56:27 +0000504 return true;
505 }
Jeff Cohen98aff882004-12-31 04:39:07 +0000506
507 result.clear();
508 WIN32_FIND_DATA fd;
Jeff Cohen0e1d7352005-07-08 04:50:08 +0000509 std::string searchpath = path;
510 if (path.size() == 0 || searchpath[path.size()-1] == '/')
Jeff Cohenf5067762005-07-08 05:02:13 +0000511 searchpath += "*";
Jeff Cohen0e1d7352005-07-08 04:50:08 +0000512 else
513 searchpath += "/*";
Jeff Cohenf5067762005-07-08 05:02:13 +0000514
Jeff Cohen9671b212005-01-27 03:49:03 +0000515 HANDLE h = FindFirstFile(searchpath.c_str(), &fd);
Jeff Cohen98aff882004-12-31 04:39:07 +0000516 if (h == INVALID_HANDLE_VALUE) {
Jeff Cohen9671b212005-01-27 03:49:03 +0000517 if (GetLastError() == ERROR_FILE_NOT_FOUND)
Jeff Cohen98aff882004-12-31 04:39:07 +0000518 return true; // not really an error, now is it?
Reid Spencer51edba12006-08-23 06:56:27 +0000519 MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
520 return true;
Jeff Cohen98aff882004-12-31 04:39:07 +0000521 }
522
523 do {
Jeff Cohen63f13c42004-12-31 05:07:26 +0000524 if (fd.cFileName[0] == '.')
525 continue;
Jeff Cohen0e1d7352005-07-08 04:50:08 +0000526 Path aPath(path);
527 aPath.appendComponent(&fd.cFileName[0]);
Jeff Cohen98aff882004-12-31 04:39:07 +0000528 result.insert(aPath);
529 } while (FindNextFile(h, &fd));
530
Jeff Cohen25dcdcc2004-12-31 19:01:08 +0000531 DWORD err = GetLastError();
532 FindClose(h);
533 if (err != ERROR_NO_MORE_FILES) {
534 SetLastError(err);
Reid Spencer51edba12006-08-23 06:56:27 +0000535 MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
536 return true;
Jeff Cohen25dcdcc2004-12-31 19:01:08 +0000537 }
Reid Spencer51edba12006-08-23 06:56:27 +0000538 return false;
Jeff Cohen98aff882004-12-31 04:39:07 +0000539}
540
541bool
Jeffrey Yasskin5908f1e2009-12-17 21:02:39 +0000542Path::set(StringRef a_path) {
Dan Gohman70de4cb2008-01-29 13:02:09 +0000543 if (a_path.empty())
Reid Spencerb88212e2004-09-15 05:49:50 +0000544 return false;
Reid Spencer17c1bd32005-07-07 23:35:23 +0000545 std::string save(path);
Reid Spencerb88212e2004-09-15 05:49:50 +0000546 path = a_path;
Reid Spencer7aed4482004-09-29 00:01:17 +0000547 FlipBackSlashes(path);
Reid Spencer0c6a2832004-11-05 22:15:36 +0000548 if (!isValid()) {
Reid Spencer17c1bd32005-07-07 23:35:23 +0000549 path = save;
Reid Spencerb88212e2004-09-15 05:49:50 +0000550 return false;
551 }
552 return true;
553}
554
555bool
Jeffrey Yasskin5908f1e2009-12-17 21:02:39 +0000556Path::appendComponent(StringRef name) {
Reid Spencer17c1bd32005-07-07 23:35:23 +0000557 if (name.empty())
Reid Spencerb88212e2004-09-15 05:49:50 +0000558 return false;
Reid Spencer17c1bd32005-07-07 23:35:23 +0000559 std::string save(path);
560 if (!path.empty()) {
561 size_t last = path.size() - 1;
Jeff Cohenf5067762005-07-08 05:02:13 +0000562 if (path[last] != '/')
Reid Spencer17c1bd32005-07-07 23:35:23 +0000563 path += '/';
564 }
565 path += name;
Reid Spencer0c6a2832004-11-05 22:15:36 +0000566 if (!isValid()) {
Reid Spencer17c1bd32005-07-07 23:35:23 +0000567 path = save;
Reid Spencerb88212e2004-09-15 05:49:50 +0000568 return false;
569 }
570 return true;
571}
572
573bool
Reid Spencer17c1bd32005-07-07 23:35:23 +0000574Path::eraseComponent() {
Reid Spencerb88212e2004-09-15 05:49:50 +0000575 size_t slashpos = path.rfind('/',path.size());
Jeff Cohen0e1d7352005-07-08 04:50:08 +0000576 if (slashpos == path.size() - 1 || slashpos == std::string::npos)
Reid Spencerb88212e2004-09-15 05:49:50 +0000577 return false;
Jeff Cohen0aad91a2005-07-09 18:42:49 +0000578 std::string save(path);
Reid Spencerb88212e2004-09-15 05:49:50 +0000579 path.erase(slashpos);
Jeff Cohen0aad91a2005-07-09 18:42:49 +0000580 if (!isValid()) {
581 path = save;
582 return false;
583 }
Reid Spencerb88212e2004-09-15 05:49:50 +0000584 return true;
585}
586
587bool
Reid Spencer17c1bd32005-07-07 23:35:23 +0000588Path::eraseSuffix() {
Reid Spencerb88212e2004-09-15 05:49:50 +0000589 size_t dotpos = path.rfind('.',path.size());
590 size_t slashpos = path.rfind('/',path.size());
Jeff Cohen0e1d7352005-07-08 04:50:08 +0000591 if (dotpos != std::string::npos) {
Jeff Cohen0aad91a2005-07-09 18:42:49 +0000592 if (slashpos == std::string::npos || dotpos > slashpos+1) {
593 std::string save(path);
Jeff Cohen0e1d7352005-07-08 04:50:08 +0000594 path.erase(dotpos, path.size()-dotpos);
Jeff Cohen0aad91a2005-07-09 18:42:49 +0000595 if (!isValid()) {
596 path = save;
597 return false;
598 }
Jeff Cohenf5067762005-07-08 05:02:13 +0000599 return true;
Jeff Cohen0e1d7352005-07-08 04:50:08 +0000600 }
Reid Spencerb88212e2004-09-15 05:49:50 +0000601 }
602 return false;
603}
604
Reid Spencerb5d6b8f2006-08-24 18:58:37 +0000605inline bool PathMsg(std::string* ErrMsg, const char* pathname, const char*msg) {
606 if (ErrMsg)
607 *ErrMsg = std::string(pathname) + ": " + std::string(msg);
608 return true;
609}
610
Reid Spencerb88212e2004-09-15 05:49:50 +0000611bool
Reid Spencerb5d6b8f2006-08-24 18:58:37 +0000612Path::createDirectoryOnDisk(bool create_parents, std::string* ErrMsg) {
Reid Spencerb88212e2004-09-15 05:49:50 +0000613 // Get a writeable copy of the path name
Jeff Cohen0e1d7352005-07-08 04:50:08 +0000614 size_t len = path.length();
615 char *pathname = reinterpret_cast<char *>(_alloca(len+2));
616 path.copy(pathname, len);
617 pathname[len] = 0;
Jeff Cohenf5067762005-07-08 05:02:13 +0000618
Jeff Cohen0e1d7352005-07-08 04:50:08 +0000619 // Make sure it ends with a slash.
620 if (len == 0 || pathname[len - 1] != '/') {
621 pathname[len] = '/';
622 pathname[++len] = 0;
623 }
Reid Spencerb88212e2004-09-15 05:49:50 +0000624
Reid Spencer7aed4482004-09-29 00:01:17 +0000625 // Determine starting point for initial / search.
626 char *next = pathname;
627 if (pathname[0] == '/' && pathname[1] == '/') {
628 // Skip host name.
629 next = strchr(pathname+2, '/');
630 if (next == NULL)
Reid Spencerb5d6b8f2006-08-24 18:58:37 +0000631 return PathMsg(ErrMsg, pathname, "badly formed remote directory");
632
Reid Spencer7aed4482004-09-29 00:01:17 +0000633 // Skip share name.
634 next = strchr(next+1, '/');
635 if (next == NULL)
Reid Spencerb5d6b8f2006-08-24 18:58:37 +0000636 return PathMsg(ErrMsg, pathname,"badly formed remote directory");
637
Reid Spencer7aed4482004-09-29 00:01:17 +0000638 next++;
639 if (*next == 0)
Reid Spencerb5d6b8f2006-08-24 18:58:37 +0000640 return PathMsg(ErrMsg, pathname, "badly formed remote directory");
641
Reid Spencer7aed4482004-09-29 00:01:17 +0000642 } else {
643 if (pathname[1] == ':')
644 next += 2; // skip drive letter
645 if (*next == '/')
646 next++; // skip root directory
647 }
Reid Spencerb88212e2004-09-15 05:49:50 +0000648
649 // If we're supposed to create intermediate directories
Reid Spencer7aed4482004-09-29 00:01:17 +0000650 if (create_parents) {
Reid Spencerb88212e2004-09-15 05:49:50 +0000651 // Loop through the directory components until we're done
Reid Spencer7aed4482004-09-29 00:01:17 +0000652 while (*next) {
653 next = strchr(next, '/');
Reid Spencerb88212e2004-09-15 05:49:50 +0000654 *next = 0;
Benjamin Kramer9470ecdb2009-11-05 14:32:40 +0000655 if (!CreateDirectory(pathname, NULL) &&
656 GetLastError() != ERROR_ALREADY_EXISTS)
Kovarththanan Rajaratnam61bea8f2010-03-12 14:17:24 +0000657 return MakeErrMsg(ErrMsg,
Reid Spencerb5d6b8f2006-08-24 18:58:37 +0000658 std::string(pathname) + ": Can't create directory: ");
Reid Spencer7aed4482004-09-29 00:01:17 +0000659 *next++ = '/';
Reid Spencerb88212e2004-09-15 05:49:50 +0000660 }
Reid Spencer7aed4482004-09-29 00:01:17 +0000661 } else {
662 // Drop trailing slash.
Jeff Cohen0e1d7352005-07-08 04:50:08 +0000663 pathname[len-1] = 0;
Benjamin Kramer9470ecdb2009-11-05 14:32:40 +0000664 if (!CreateDirectory(pathname, NULL) &&
665 GetLastError() != ERROR_ALREADY_EXISTS) {
Mikhail Glushenkovb4921a02010-11-02 20:32:31 +0000666 return MakeErrMsg(ErrMsg, std::string(pathname) +
667 ": Can't create directory: ");
Reid Spencer7aed4482004-09-29 00:01:17 +0000668 }
Reid Spencerb88212e2004-09-15 05:49:50 +0000669 }
Reid Spencerb5d6b8f2006-08-24 18:58:37 +0000670 return false;
Reid Spencerb88212e2004-09-15 05:49:50 +0000671}
672
673bool
Reid Spencerb5d6b8f2006-08-24 18:58:37 +0000674Path::createFileOnDisk(std::string* ErrMsg) {
Reid Spencerb88212e2004-09-15 05:49:50 +0000675 // Create the file
Reid Spencer7aed4482004-09-29 00:01:17 +0000676 HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
Reid Spencer0e863362004-09-18 19:29:16 +0000677 FILE_ATTRIBUTE_NORMAL, NULL);
678 if (h == INVALID_HANDLE_VALUE)
Reid Spencerb5d6b8f2006-08-24 18:58:37 +0000679 return MakeErrMsg(ErrMsg, path + ": Can't create file: ");
Reid Spencerb88212e2004-09-15 05:49:50 +0000680
Reid Spencer0e863362004-09-18 19:29:16 +0000681 CloseHandle(h);
Reid Spencerb5d6b8f2006-08-24 18:58:37 +0000682 return false;
Reid Spencerb88212e2004-09-15 05:49:50 +0000683}
684
685bool
Chris Lattner3cec1092006-07-28 22:29:50 +0000686Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
Jeff Cohen79582362007-04-07 20:47:27 +0000687 WIN32_FILE_ATTRIBUTE_DATA fi;
688 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi))
689 return true;
Kovarththanan Rajaratnam61bea8f2010-03-12 14:17:24 +0000690
Jeff Cohen79582362007-04-07 20:47:27 +0000691 if (fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
Reid Spencer17c1bd32005-07-07 23:35:23 +0000692 // If it doesn't exist, we're done.
Michael J. Spencer58df2e02011-01-10 02:34:23 +0000693 bool Exists;
694 if (fs::exists(path, Exists) || !Exists)
Chris Lattner3cec1092006-07-28 22:29:50 +0000695 return false;
Reid Spencer17c1bd32005-07-07 23:35:23 +0000696
Jeff Cohen0e1d7352005-07-08 04:50:08 +0000697 char *pathname = reinterpret_cast<char *>(_alloca(path.length()+3));
Reid Spencer17c1bd32005-07-07 23:35:23 +0000698 int lastchar = path.length() - 1 ;
Jeff Cohen0e1d7352005-07-08 04:50:08 +0000699 path.copy(pathname, lastchar+1);
Reid Spencer17c1bd32005-07-07 23:35:23 +0000700
701 // Make path end with '/*'.
Jeff Cohen0e1d7352005-07-08 04:50:08 +0000702 if (pathname[lastchar] != '/')
703 pathname[++lastchar] = '/';
Reid Spencer17c1bd32005-07-07 23:35:23 +0000704 pathname[lastchar+1] = '*';
705 pathname[lastchar+2] = 0;
706
707 if (remove_contents) {
708 WIN32_FIND_DATA fd;
709 HANDLE h = FindFirstFile(pathname, &fd);
710
711 // It's a bad idea to alter the contents of a directory while enumerating
712 // its contents. So build a list of its contents first, then destroy them.
713
714 if (h != INVALID_HANDLE_VALUE) {
715 std::vector<Path> list;
716
717 do {
718 if (strcmp(fd.cFileName, ".") == 0)
719 continue;
720 if (strcmp(fd.cFileName, "..") == 0)
721 continue;
722
Jeff Cohenf5067762005-07-08 05:02:13 +0000723 Path aPath(path);
724 aPath.appendComponent(&fd.cFileName[0]);
Reid Spencer17c1bd32005-07-07 23:35:23 +0000725 list.push_back(aPath);
726 } while (FindNextFile(h, &fd));
727
728 DWORD err = GetLastError();
729 FindClose(h);
730 if (err != ERROR_NO_MORE_FILES) {
731 SetLastError(err);
Reid Spencer50eac3b2006-08-25 21:37:17 +0000732 return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
Reid Spencer17c1bd32005-07-07 23:35:23 +0000733 }
734
Jeff Cohenf5067762005-07-08 05:02:13 +0000735 for (std::vector<Path>::iterator I = list.begin(); I != list.end();
Reid Spencer17c1bd32005-07-07 23:35:23 +0000736 ++I) {
737 Path &aPath = *I;
Reid Spenceraf48d862005-07-08 03:08:58 +0000738 aPath.eraseFromDisk(true);
Reid Spencer17c1bd32005-07-07 23:35:23 +0000739 }
740 } else {
741 if (GetLastError() != ERROR_FILE_NOT_FOUND)
Reid Spencer50eac3b2006-08-25 21:37:17 +0000742 return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
Reid Spencer17c1bd32005-07-07 23:35:23 +0000743 }
744 }
745
746 pathname[lastchar] = 0;
747 if (!RemoveDirectory(pathname))
Kovarththanan Rajaratnam61bea8f2010-03-12 14:17:24 +0000748 return MakeErrMsg(ErrStr,
Reid Spencer50eac3b2006-08-25 21:37:17 +0000749 std::string(pathname) + ": Can't destroy directory: ");
Chris Lattner3cec1092006-07-28 22:29:50 +0000750 return false;
Jeff Cohen79582362007-04-07 20:47:27 +0000751 } else {
752 // Read-only files cannot be deleted on Windows. Must remove the read-only
753 // attribute first.
754 if (fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
755 if (!SetFileAttributes(path.c_str(),
756 fi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
757 return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
758 }
759
760 if (!DeleteFile(path.c_str()))
761 return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
762 return false;
763 }
Reid Spencerb88212e2004-09-15 05:49:50 +0000764}
765
Reid Spencerc936ad12004-12-14 18:42:13 +0000766bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
Reid Spencerc936ad12004-12-14 18:42:13 +0000767 assert(len < 1024 && "Request for magic string too long");
Michael J. Spencer18f50052010-08-31 06:36:33 +0000768 char* buf = reinterpret_cast<char*>(alloca(len));
Jeff Cohen25dcdcc2004-12-31 19:01:08 +0000769
770 HANDLE h = CreateFile(path.c_str(),
771 GENERIC_READ,
772 FILE_SHARE_READ,
773 NULL,
774 OPEN_EXISTING,
775 FILE_ATTRIBUTE_NORMAL,
776 NULL);
777 if (h == INVALID_HANDLE_VALUE)
Reid Spencerc936ad12004-12-14 18:42:13 +0000778 return false;
Jeff Cohen25dcdcc2004-12-31 19:01:08 +0000779
780 DWORD nRead = 0;
781 BOOL ret = ReadFile(h, buf, len, &nRead, NULL);
782 CloseHandle(h);
783
784 if (!ret || nRead != len)
Reid Spencerc936ad12004-12-14 18:42:13 +0000785 return false;
Jeff Cohen25dcdcc2004-12-31 19:01:08 +0000786
Michael J. Spencer18f50052010-08-31 06:36:33 +0000787 Magic = std::string(buf, len);
Reid Spencerc936ad12004-12-14 18:42:13 +0000788 return true;
789}
790
Jeff Cohen98aff882004-12-31 04:39:07 +0000791bool
Reid Spencer879ed5a2006-08-23 07:30:48 +0000792Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
Francois Pichet083f3682010-09-30 00:44:58 +0000793 if (!MoveFileEx(path.c_str(), newName.c_str(), MOVEFILE_REPLACE_EXISTING))
794 return MakeErrMsg(ErrMsg, "Can't move '" + path + "' to '" + newName.path
795 + "': ");
796 return false;
Jeff Cohen98aff882004-12-31 04:39:07 +0000797}
798
799bool
Anton Korobeynikov6c6a70f2006-09-01 20:35:17 +0000800Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrMsg) const {
Jeff Cohen0aad91a2005-07-09 18:42:49 +0000801 // FIXME: should work on directories also.
Anton Korobeynikov6c6a70f2006-09-01 20:35:17 +0000802 if (!si.isFile) {
803 return true;
804 }
Kovarththanan Rajaratnam61bea8f2010-03-12 14:17:24 +0000805
Jeff Cohen98aff882004-12-31 04:39:07 +0000806 HANDLE h = CreateFile(path.c_str(),
807 FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES,
808 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
Jeff Cohen63f13c42004-12-31 05:07:26 +0000809 NULL,
810 OPEN_EXISTING,
811 FILE_ATTRIBUTE_NORMAL,
812 NULL);
Jeff Cohen98aff882004-12-31 04:39:07 +0000813 if (h == INVALID_HANDLE_VALUE)
Chris Lattner60c50642006-07-28 22:36:17 +0000814 return true;
Jeff Cohen98aff882004-12-31 04:39:07 +0000815
816 BY_HANDLE_FILE_INFORMATION bhfi;
817 if (!GetFileInformationByHandle(h, &bhfi)) {
Jeff Cohen25dcdcc2004-12-31 19:01:08 +0000818 DWORD err = GetLastError();
Jeff Cohen98aff882004-12-31 04:39:07 +0000819 CloseHandle(h);
Jeff Cohen25dcdcc2004-12-31 19:01:08 +0000820 SetLastError(err);
Anton Korobeynikov6c6a70f2006-09-01 20:35:17 +0000821 return MakeErrMsg(ErrMsg, path + ": GetFileInformationByHandle: ");
Jeff Cohen98aff882004-12-31 04:39:07 +0000822 }
823
Michael J. Spencerd75cf222010-08-28 16:39:32 +0000824 ULARGE_INTEGER ui;
825 ui.QuadPart = si.modTime.toWin32Time();
Jeff Cohen98aff882004-12-31 04:39:07 +0000826 FILETIME ft;
Michael J. Spencerd75cf222010-08-28 16:39:32 +0000827 ft.dwLowDateTime = ui.LowPart;
828 ft.dwHighDateTime = ui.HighPart;
Jeff Cohen98aff882004-12-31 04:39:07 +0000829 BOOL ret = SetFileTime(h, NULL, &ft, &ft);
Jeff Cohen25dcdcc2004-12-31 19:01:08 +0000830 DWORD err = GetLastError();
Jeff Cohen98aff882004-12-31 04:39:07 +0000831 CloseHandle(h);
Jeff Cohen25dcdcc2004-12-31 19:01:08 +0000832 if (!ret) {
833 SetLastError(err);
Anton Korobeynikov6c6a70f2006-09-01 20:35:17 +0000834 return MakeErrMsg(ErrMsg, path + ": SetFileTime: ");
Jeff Cohen25dcdcc2004-12-31 19:01:08 +0000835 }
Jeff Cohen98aff882004-12-31 04:39:07 +0000836
837 // Best we can do with Unix permission bits is to interpret the owner
838 // writable bit.
839 if (si.mode & 0200) {
840 if (bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
841 if (!SetFileAttributes(path.c_str(),
Jeff Cohen63f13c42004-12-31 05:07:26 +0000842 bhfi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
Anton Korobeynikov6c6a70f2006-09-01 20:35:17 +0000843 return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
Jeff Cohen98aff882004-12-31 04:39:07 +0000844 }
845 } else {
846 if (!(bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY)) {
847 if (!SetFileAttributes(path.c_str(),
Jeff Cohen63f13c42004-12-31 05:07:26 +0000848 bhfi.dwFileAttributes | FILE_ATTRIBUTE_READONLY))
Anton Korobeynikov6c6a70f2006-09-01 20:35:17 +0000849 return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
Jeff Cohen98aff882004-12-31 04:39:07 +0000850 }
851 }
852
Chris Lattner60c50642006-07-28 22:36:17 +0000853 return false;
Jeff Cohen98aff882004-12-31 04:39:07 +0000854}
855
Reid Spencerb5d6b8f2006-08-24 18:58:37 +0000856bool
857CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg) {
Jeff Cohend567bb62004-12-24 02:38:34 +0000858 // Can't use CopyFile macro defined in Windows.h because it would mess up the
859 // above line. We use the expansion it would have in a non-UNICODE build.
860 if (!::CopyFileA(Src.c_str(), Dest.c_str(), false))
Chris Lattnerc521f542009-08-23 22:45:37 +0000861 return MakeErrMsg(ErrMsg, "Can't copy '" + Src.str() +
862 "' to '" + Dest.str() + "': ");
Reid Spencerb5d6b8f2006-08-24 18:58:37 +0000863 return false;
Reid Spencerf66d9322004-12-15 01:50:13 +0000864}
865
Reid Spencerb5d6b8f2006-08-24 18:58:37 +0000866bool
867Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
Michael J. Spencer58df2e02011-01-10 02:34:23 +0000868 bool Exists;
869 if (reuse_current && (fs::exists(path, Exists) || !Exists))
Reid Spencerb5d6b8f2006-08-24 18:58:37 +0000870 return false; // File doesn't exist already, just use it!
Reid Spencerf66d9322004-12-15 01:50:13 +0000871
Jeff Cohen9671b212005-01-27 03:49:03 +0000872 // Reserve space for -XXXXXX at the end.
873 char *FNBuffer = (char*) alloca(path.size()+8);
874 unsigned offset = path.size();
875 path.copy(FNBuffer, offset);
Reid Spencerf66d9322004-12-15 01:50:13 +0000876
Jeff Cohen0aad91a2005-07-09 18:42:49 +0000877 // Find a numeric suffix that isn't used by an existing file. Assume there
878 // won't be more than 1 million files with the same prefix. Probably a safe
879 // bet.
NAKAMURA Takumiaaa9b4f2011-03-16 02:53:24 +0000880 static int FCounter = -1;
881 if (FCounter < 0) {
882 // Give arbitrary initial seed.
883 // FIXME: We should use sys::fs::unique_file() in future.
884 LARGE_INTEGER cnt64;
885 DWORD x = GetCurrentProcessId();
886 x = (x << 16) | (x >> 16);
887 if (QueryPerformanceCounter(&cnt64)) // RDTSC
888 x ^= cnt64.HighPart ^ cnt64.LowPart;
889 FCounter = x % 1000000;
890 }
Jeff Cohen9671b212005-01-27 03:49:03 +0000891 do {
892 sprintf(FNBuffer+offset, "-%06u", FCounter);
893 if (++FCounter > 999999)
894 FCounter = 0;
895 path = FNBuffer;
Michael J. Spencer58df2e02011-01-10 02:34:23 +0000896 } while (!fs::exists(path, Exists) && Exists);
Reid Spencerb5d6b8f2006-08-24 18:58:37 +0000897 return false;
Reid Spencerf66d9322004-12-15 01:50:13 +0000898}
899
Reid Spencer98ce23f2004-12-15 08:32:45 +0000900bool
Reid Spencerb5d6b8f2006-08-24 18:58:37 +0000901Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
Reid Spencer98ce23f2004-12-15 08:32:45 +0000902 // Make this into a unique file name
Anton Korobeynikov6c6a70f2006-09-01 20:35:17 +0000903 makeUnique(reuse_current, ErrMsg);
Jeff Cohen9671b212005-01-27 03:49:03 +0000904
905 // Now go and create it
906 HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
907 FILE_ATTRIBUTE_NORMAL, NULL);
908 if (h == INVALID_HANDLE_VALUE)
Anton Korobeynikov6c6a70f2006-09-01 20:35:17 +0000909 return MakeErrMsg(ErrMsg, path + ": can't create file");
Jeff Cohen9671b212005-01-27 03:49:03 +0000910
911 CloseHandle(h);
Reid Spencerb5d6b8f2006-08-24 18:58:37 +0000912 return false;
Reid Spencer98ce23f2004-12-15 08:32:45 +0000913}
914
Chris Lattner3089e1d2008-04-01 06:00:12 +0000915/// MapInFilePages - Not yet implemented on win32.
Rafael Espindola510b00c2011-03-10 18:30:48 +0000916const char *Path::MapInFilePages(int FD, size_t FileSize, off_t Offset) {
Chris Lattner3089e1d2008-04-01 06:00:12 +0000917 return 0;
918}
919
920/// MapInFilePages - Not yet implemented on win32.
Rafael Espindola510b00c2011-03-10 18:30:48 +0000921void Path::UnMapFilePages(const char *Base, size_t FileSize) {
Chris Lattner3089e1d2008-04-01 06:00:12 +0000922 assert(0 && "NOT IMPLEMENTED");
923}
924
Reid Spencerb88212e2004-09-15 05:49:50 +0000925}
Reid Spencer566ac282004-09-11 04:59:30 +0000926}