blob: 146d6b398519318d483526ab8ee0746d491ee20a [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"
Reid Spencer0e863362004-09-18 19:29:16 +000020#include <malloc.h>
Chris Lattner7e064432009-04-01 02:03:38 +000021#include <cstdio>
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) {
85 if (pos != 1 || !isalpha(path[0]) || len < 3)
86 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) {
192 assert(TempDirectory->exists() && "Who has removed TempDirectory?");
Reid Spencer0e863362004-09-18 19:29:16 +0000193 return *TempDirectory;
NAKAMURA Takumib030e8a2012-05-27 13:02:04 +0000194 }
Reid Spencer0e863362004-09-18 19:29:16 +0000195
196 char pathname[MAX_PATH];
Reid Spencer7e73c5132006-08-22 22:46:39 +0000197 if (!GetTempPath(MAX_PATH, pathname)) {
198 if (ErrMsg)
199 *ErrMsg = "Can't determine temporary directory";
200 return Path();
201 }
Reid Spencer0e863362004-09-18 19:29:16 +0000202
Reid Spencerb88212e2004-09-15 05:49:50 +0000203 Path result;
Reid Spencer17c1bd32005-07-07 23:35:23 +0000204 result.set(pathname);
Reid Spencer0e863362004-09-18 19:29:16 +0000205
Aaron Ballman503bbff32012-06-09 13:46:36 +0000206 // Append a subdirectory based on our process id so multiple LLVMs don't
Reid Spencer0e863362004-09-18 19:29:16 +0000207 // step on each other's toes.
Jeff Cohen7d6f3db2006-11-05 19:31:28 +0000208#ifdef __MINGW32__
209 // Mingw's Win32 header files are broken.
Reid Spencer36bc2b02006-06-08 18:08:43 +0000210 sprintf(pathname, "LLVM_%u", unsigned(GetCurrentProcessId()));
Jeff Cohen7d6f3db2006-11-05 19:31:28 +0000211#else
212 sprintf(pathname, "LLVM_%u", GetCurrentProcessId());
213#endif
Jeff Cohen215db902005-07-08 02:48:42 +0000214 result.appendComponent(pathname);
Reid Spencer0e863362004-09-18 19:29:16 +0000215
216 // If there's a directory left over from a previous LLVM execution that
217 // happened to have the same process id, get rid of it.
Reid Spenceraf48d862005-07-08 03:08:58 +0000218 result.eraseFromDisk(true);
Reid Spencer0e863362004-09-18 19:29:16 +0000219
220 // And finally (re-)create the empty directory.
Reid Spenceraf48d862005-07-08 03:08:58 +0000221 result.createDirectoryOnDisk(false);
Reid Spencer0e863362004-09-18 19:29:16 +0000222 TempDirectory = new Path(result);
223 return *TempDirectory;
Reid Spencerb88212e2004-09-15 05:49:50 +0000224}
225
Reid Spencer0e863362004-09-18 19:29:16 +0000226// FIXME: the following set of functions don't map to Windows very well.
Reid Spencerb88212e2004-09-15 05:49:50 +0000227Path
228Path::GetRootDirectory() {
Michael J. Spencerdf929cf2010-11-09 15:10:45 +0000229 // This is the only notion that that Windows has of a root directory. Nothing
230 // is here except for drives.
231 return Path("file:///");
Reid Spencerb88212e2004-09-15 05:49:50 +0000232}
233
Jeff Cohenf5067762005-07-08 05:02:13 +0000234void
Reid Spencer0a0d5822004-12-13 03:03:42 +0000235Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
Michael J. Spencer181fd8c2010-11-09 15:11:19 +0000236 char buff[MAX_PATH];
237 // Generic form of C:\Windows\System32
238 HRESULT res = SHGetFolderPathA(NULL,
239 CSIDL_FLAG_CREATE | CSIDL_SYSTEM,
240 NULL,
241 SHGFP_TYPE_CURRENT,
242 buff);
243 if (res != S_OK) {
244 assert(0 && "Failed to get system directory");
245 return;
246 }
247 Paths.push_back(sys::Path(buff));
248
249 // Reset buff.
250 buff[0] = 0;
251 // Generic form of C:\Windows
252 res = SHGetFolderPathA(NULL,
253 CSIDL_FLAG_CREATE | CSIDL_WINDOWS,
254 NULL,
255 SHGFP_TYPE_CURRENT,
256 buff);
257 if (res != S_OK) {
258 assert(0 && "Failed to get windows directory");
259 return;
260 }
261 Paths.push_back(sys::Path(buff));
Reid Spencer0e863362004-09-18 19:29:16 +0000262}
263
Reid Spencer0a0d5822004-12-13 03:03:42 +0000264void
Gabor Greif24027b52007-07-06 20:28:40 +0000265Path::GetBitcodeLibraryPaths(std::vector<sys::Path>& Paths) {
Reid Spencer0a0d5822004-12-13 03:03:42 +0000266 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
267 if (env_var != 0) {
268 getPathList(env_var,Paths);
269 }
Reid Spencer0a0d5822004-12-13 03:03:42 +0000270#ifdef LLVM_LIBDIR
271 {
272 Path tmpPath;
Reid Spencer17c1bd32005-07-07 23:35:23 +0000273 if (tmpPath.set(LLVM_LIBDIR))
Reid Spencer5b891e92005-07-07 18:21:42 +0000274 if (tmpPath.canRead())
Reid Spencer0a0d5822004-12-13 03:03:42 +0000275 Paths.push_back(tmpPath);
276 }
277#endif
278 GetSystemLibraryPaths(Paths);
Reid Spencerb88212e2004-09-15 05:49:50 +0000279}
280
281Path
Reid Spencerb88212e2004-09-15 05:49:50 +0000282Path::GetUserHomeDirectory() {
Michael J. Spencer86cdb422010-11-09 15:11:31 +0000283 char buff[MAX_PATH];
Michael J. Spencerb39a8972010-11-10 15:06:00 +0000284 HRESULT res = SHGetFolderPathA(NULL,
285 CSIDL_FLAG_CREATE | CSIDL_APPDATA,
286 NULL,
287 SHGFP_TYPE_CURRENT,
288 buff);
Michael J. Spencer86cdb422010-11-09 15:11:31 +0000289 if (res != S_OK)
290 assert(0 && "Failed to get user home directory");
291 return Path(buff);
Reid Spencerb88212e2004-09-15 05:49:50 +0000292}
Ted Kremenek14020702007-12-18 22:07:33 +0000293
294Path
295Path::GetCurrentDirectory() {
296 char pathname[MAX_PATH];
Anton Korobeynikov2ffb2c92007-12-22 14:26:49 +0000297 ::GetCurrentDirectoryA(MAX_PATH,pathname);
Kovarththanan Rajaratnam61bea8f2010-03-12 14:17:24 +0000298 return Path(pathname);
Ted Kremenek14020702007-12-18 22:07:33 +0000299}
300
Chris Lattnere209be42008-03-03 02:55:43 +0000301/// GetMainExecutable - Return the path to the main executable, given the
302/// value of argv[0] from program startup.
303Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
Chris Lattner7038cd522009-06-15 05:38:04 +0000304 char pathname[MAX_PATH];
305 DWORD ret = ::GetModuleFileNameA(NULL, pathname, MAX_PATH);
306 return ret != MAX_PATH ? Path(pathname) : Path();
Chris Lattnere209be42008-03-03 02:55:43 +0000307}
308
Ted Kremenek14020702007-12-18 22:07:33 +0000309
Reid Spencer0e863362004-09-18 19:29:16 +0000310// FIXME: the above set of functions don't map to Windows very well.
311
Jeff Cohen0aad91a2005-07-09 18:42:49 +0000312
Jeffrey Yasskin5908f1e2009-12-17 21:02:39 +0000313StringRef Path::getDirname() const {
314 return getDirnameCharSep(path, "/");
Ted Kremeneka518bb72008-04-07 22:01:32 +0000315}
Ted Kremenekc042bf12008-04-07 21:53:57 +0000316
Jeffrey Yasskin5908f1e2009-12-17 21:02:39 +0000317StringRef
Reid Spencer0c6a2832004-11-05 22:15:36 +0000318Path::getBasename() const {
Reid Spencer0e863362004-09-18 19:29:16 +0000319 // Find the last slash
320 size_t slash = path.rfind('/');
321 if (slash == std::string::npos)
322 slash = 0;
323 else
324 slash++;
325
Jeff Cohen0aad91a2005-07-09 18:42:49 +0000326 size_t dot = path.rfind('.');
327 if (dot == std::string::npos || dot < slash)
Jeffrey Yasskin5908f1e2009-12-17 21:02:39 +0000328 return StringRef(path).substr(slash);
Jeff Cohen0aad91a2005-07-09 18:42:49 +0000329 else
Jeffrey Yasskin5908f1e2009-12-17 21:02:39 +0000330 return StringRef(path).substr(slash, dot - slash);
Reid Spencer0e863362004-09-18 19:29:16 +0000331}
332
Jeffrey Yasskin5908f1e2009-12-17 21:02:39 +0000333StringRef
Argyrios Kyrtzidis2cc0abf2008-06-15 15:15:19 +0000334Path::getSuffix() const {
335 // Find the last slash
336 size_t slash = path.rfind('/');
337 if (slash == std::string::npos)
338 slash = 0;
339 else
340 slash++;
341
342 size_t dot = path.rfind('.');
343 if (dot == std::string::npos || dot < slash)
Jeffrey Yasskin5908f1e2009-12-17 21:02:39 +0000344 return StringRef("");
Argyrios Kyrtzidis2cc0abf2008-06-15 15:15:19 +0000345 else
Jeffrey Yasskin5908f1e2009-12-17 21:02:39 +0000346 return StringRef(path).substr(dot + 1);
Argyrios Kyrtzidis2cc0abf2008-06-15 15:15:19 +0000347}
348
Reid Spencer0e863362004-09-18 19:29:16 +0000349bool
Reid Spencerb88212e2004-09-15 05:49:50 +0000350Path::exists() const {
Reid Spencer0e863362004-09-18 19:29:16 +0000351 DWORD attr = GetFileAttributes(path.c_str());
352 return attr != INVALID_FILE_ATTRIBUTES;
Reid Spencerb88212e2004-09-15 05:49:50 +0000353}
354
355bool
Ted Kremenek74db0422007-12-18 19:46:22 +0000356Path::isDirectory() const {
357 DWORD attr = GetFileAttributes(path.c_str());
358 return (attr != INVALID_FILE_ATTRIBUTES) &&
359 (attr & FILE_ATTRIBUTE_DIRECTORY);
360}
361
362bool
Rafael Espindola559b8fb2010-11-07 04:36:50 +0000363Path::isSymLink() const {
Michael J. Spencer909d238e2010-11-10 15:05:39 +0000364 DWORD attributes = GetFileAttributes(path.c_str());
365
366 if (attributes == INVALID_FILE_ATTRIBUTES)
367 // There's no sane way to report this :(.
368 assert(0 && "GetFileAttributes returned INVALID_FILE_ATTRIBUTES");
369
370 // This isn't exactly what defines a NTFS symlink, but it is only true for
371 // paths that act like a symlink.
372 return attributes & FILE_ATTRIBUTE_REPARSE_POINT;
Rafael Espindola559b8fb2010-11-07 04:36:50 +0000373}
374
375bool
Reid Spencer5b891e92005-07-07 18:21:42 +0000376Path::canRead() const {
Reid Spencer0e863362004-09-18 19:29:16 +0000377 // FIXME: take security attributes into account.
378 DWORD attr = GetFileAttributes(path.c_str());
379 return attr != INVALID_FILE_ATTRIBUTES;
Reid Spencerb88212e2004-09-15 05:49:50 +0000380}
381
382bool
Reid Spencer5b891e92005-07-07 18:21:42 +0000383Path::canWrite() const {
Reid Spencer0e863362004-09-18 19:29:16 +0000384 // FIXME: take security attributes into account.
385 DWORD attr = GetFileAttributes(path.c_str());
386 return (attr != INVALID_FILE_ATTRIBUTES) && !(attr & FILE_ATTRIBUTE_READONLY);
Reid Spencerb88212e2004-09-15 05:49:50 +0000387}
388
389bool
Reid Spencer5b891e92005-07-07 18:21:42 +0000390Path::canExecute() const {
Reid Spencer0e863362004-09-18 19:29:16 +0000391 // FIXME: take security attributes into account.
392 DWORD attr = GetFileAttributes(path.c_str());
393 return attr != INVALID_FILE_ATTRIBUTES;
Reid Spencerb88212e2004-09-15 05:49:50 +0000394}
395
Edward O'Callaghandddf1342009-11-24 15:19:10 +0000396bool
Edward O'Callaghan746782d2009-11-25 06:32:19 +0000397Path::isRegularFile() const {
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000398 bool res;
399 if (fs::is_regular_file(path, res))
Edward O'Callaghan746782d2009-11-25 06:32:19 +0000400 return false;
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000401 return res;
Edward O'Callaghandddf1342009-11-24 15:19:10 +0000402}
403
Jeffrey Yasskin5908f1e2009-12-17 21:02:39 +0000404StringRef
Reid Spencerb88212e2004-09-15 05:49:50 +0000405Path::getLast() const {
406 // Find the last slash
407 size_t pos = path.rfind('/');
408
409 // Handle the corner cases
410 if (pos == std::string::npos)
411 return path;
412
Jeff Cohen0e1d7352005-07-08 04:50:08 +0000413 // If the last character is a slash, we have a root directory
414 if (pos == path.length()-1)
415 return path;
416
Reid Spencerb88212e2004-09-15 05:49:50 +0000417 // Return everything after the last slash
Jeffrey Yasskin5908f1e2009-12-17 21:02:39 +0000418 return StringRef(path).substr(pos+1);
Reid Spencerb88212e2004-09-15 05:49:50 +0000419}
420
Reid Spencer200c6f92007-03-29 19:05:44 +0000421const FileStatus *
Reid Spencerceeb9182007-04-07 18:52:17 +0000422PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
423 if (!fsIsValid || update) {
Reid Spencer0f92f0e2007-03-29 16:43:20 +0000424 WIN32_FILE_ATTRIBUTE_DATA fi;
Reid Spencer200c6f92007-03-29 19:05:44 +0000425 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
426 MakeErrMsg(ErrStr, "getStatusInfo():" + std::string(path) +
Reid Spencer0f92f0e2007-03-29 16:43:20 +0000427 ": Can't get status: ");
Reid Spencer200c6f92007-03-29 19:05:44 +0000428 return 0;
429 }
Jeff Cohen2b60d392004-12-14 05:26:43 +0000430
Reid Spencerceeb9182007-04-07 18:52:17 +0000431 status.fileSize = fi.nFileSizeHigh;
432 status.fileSize <<= sizeof(fi.nFileSizeHigh)*8;
433 status.fileSize += fi.nFileSizeLow;
Jeff Cohen2b60d392004-12-14 05:26:43 +0000434
Reid Spencerceeb9182007-04-07 18:52:17 +0000435 status.mode = fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY ? 0555 : 0777;
436 status.user = 9999; // Not applicable to Windows, so...
437 status.group = 9999; // Not applicable to Windows, so...
Jeff Cohen2b60d392004-12-14 05:26:43 +0000438
Reid Spencerd3946172007-03-29 17:00:31 +0000439 // FIXME: this is only unique if the file is accessed by the same file path.
440 // How do we do this for C:\dir\file and ..\dir\file ? Unix has inode
441 // numbers, but the concept doesn't exist in Windows.
Reid Spencerceeb9182007-04-07 18:52:17 +0000442 status.uniqueID = 0;
Reid Spencerd3946172007-03-29 17:00:31 +0000443 for (unsigned i = 0; i < path.length(); ++i)
Reid Spencerceeb9182007-04-07 18:52:17 +0000444 status.uniqueID += path[i];
Reid Spencerd3946172007-03-29 17:00:31 +0000445
Michael J. Spencerd75cf222010-08-28 16:39:32 +0000446 ULARGE_INTEGER ui;
447 ui.LowPart = fi.ftLastWriteTime.dwLowDateTime;
448 ui.HighPart = fi.ftLastWriteTime.dwHighDateTime;
449 status.modTime.fromWin32Time(ui.QuadPart);
Reid Spencer0f92f0e2007-03-29 16:43:20 +0000450
Reid Spencerceeb9182007-04-07 18:52:17 +0000451 status.isDir = fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
452 fsIsValid = true;
Reid Spencer0f92f0e2007-03-29 16:43:20 +0000453 }
Reid Spencerceeb9182007-04-07 18:52:17 +0000454 return &status;
Jeff Cohen2b60d392004-12-14 05:26:43 +0000455}
456
Reid Spencera1a7a352006-08-22 23:54:35 +0000457bool Path::makeReadableOnDisk(std::string* ErrMsg) {
Jeff Cohen2b60d392004-12-14 05:26:43 +0000458 // All files are readable on Windows (ignoring security attributes).
Reid Spencera1a7a352006-08-22 23:54:35 +0000459 return false;
Reid Spencer94bf2262004-12-13 19:59:50 +0000460}
461
Anton Korobeynikov6c6a70f2006-09-01 20:35:17 +0000462bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
Jeff Cohen2b60d392004-12-14 05:26:43 +0000463 DWORD attr = GetFileAttributes(path.c_str());
464
465 // If it doesn't exist, we're done.
466 if (attr == INVALID_FILE_ATTRIBUTES)
Anton Korobeynikov6c6a70f2006-09-01 20:35:17 +0000467 return false;
Jeff Cohen2b60d392004-12-14 05:26:43 +0000468
469 if (attr & FILE_ATTRIBUTE_READONLY) {
Reid Spencera1a7a352006-08-22 23:54:35 +0000470 if (!SetFileAttributes(path.c_str(), attr & ~FILE_ATTRIBUTE_READONLY)) {
471 MakeErrMsg(ErrMsg, std::string(path) + ": Can't make file writable: ");
472 return true;
473 }
Jeff Cohen2b60d392004-12-14 05:26:43 +0000474 }
Reid Spencera1a7a352006-08-22 23:54:35 +0000475 return false;
Reid Spencer94bf2262004-12-13 19:59:50 +0000476}
477
Reid Spencera1a7a352006-08-22 23:54:35 +0000478bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
Jeff Cohen2b60d392004-12-14 05:26:43 +0000479 // All files are executable on Windows (ignoring security attributes).
Reid Spencera1a7a352006-08-22 23:54:35 +0000480 return false;
Reid Spencer94bf2262004-12-13 19:59:50 +0000481}
482
Reid Spencerb88212e2004-09-15 05:49:50 +0000483bool
Reid Spencer51edba12006-08-23 06:56:27 +0000484Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
Jeff Cohen79582362007-04-07 20:47:27 +0000485 WIN32_FILE_ATTRIBUTE_DATA fi;
486 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
487 MakeErrMsg(ErrMsg, path + ": can't get status of file");
Anton Korobeynikov6c6a70f2006-09-01 20:35:17 +0000488 return true;
Jeff Cohen79582362007-04-07 20:47:27 +0000489 }
Kovarththanan Rajaratnam61bea8f2010-03-12 14:17:24 +0000490
Jeff Cohen79582362007-04-07 20:47:27 +0000491 if (!(fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
492 if (ErrMsg)
493 *ErrMsg = path + ": not a directory";
Reid Spencer51edba12006-08-23 06:56:27 +0000494 return true;
495 }
Jeff Cohen98aff882004-12-31 04:39:07 +0000496
497 result.clear();
498 WIN32_FIND_DATA fd;
Jeff Cohen0e1d7352005-07-08 04:50:08 +0000499 std::string searchpath = path;
500 if (path.size() == 0 || searchpath[path.size()-1] == '/')
Jeff Cohenf5067762005-07-08 05:02:13 +0000501 searchpath += "*";
Jeff Cohen0e1d7352005-07-08 04:50:08 +0000502 else
503 searchpath += "/*";
Jeff Cohenf5067762005-07-08 05:02:13 +0000504
Jeff Cohen9671b212005-01-27 03:49:03 +0000505 HANDLE h = FindFirstFile(searchpath.c_str(), &fd);
Jeff Cohen98aff882004-12-31 04:39:07 +0000506 if (h == INVALID_HANDLE_VALUE) {
Jeff Cohen9671b212005-01-27 03:49:03 +0000507 if (GetLastError() == ERROR_FILE_NOT_FOUND)
Jeff Cohen98aff882004-12-31 04:39:07 +0000508 return true; // not really an error, now is it?
Reid Spencer51edba12006-08-23 06:56:27 +0000509 MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
510 return true;
Jeff Cohen98aff882004-12-31 04:39:07 +0000511 }
512
513 do {
Jeff Cohen63f13c42004-12-31 05:07:26 +0000514 if (fd.cFileName[0] == '.')
515 continue;
Jeff Cohen0e1d7352005-07-08 04:50:08 +0000516 Path aPath(path);
517 aPath.appendComponent(&fd.cFileName[0]);
Jeff Cohen98aff882004-12-31 04:39:07 +0000518 result.insert(aPath);
519 } while (FindNextFile(h, &fd));
520
Jeff Cohen25dcdcc2004-12-31 19:01:08 +0000521 DWORD err = GetLastError();
522 FindClose(h);
523 if (err != ERROR_NO_MORE_FILES) {
524 SetLastError(err);
Reid Spencer51edba12006-08-23 06:56:27 +0000525 MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
526 return true;
Jeff Cohen25dcdcc2004-12-31 19:01:08 +0000527 }
Reid Spencer51edba12006-08-23 06:56:27 +0000528 return false;
Jeff Cohen98aff882004-12-31 04:39:07 +0000529}
530
531bool
Jeffrey Yasskin5908f1e2009-12-17 21:02:39 +0000532Path::set(StringRef a_path) {
Dan Gohman70de4cb2008-01-29 13:02:09 +0000533 if (a_path.empty())
Reid Spencerb88212e2004-09-15 05:49:50 +0000534 return false;
Reid Spencer17c1bd32005-07-07 23:35:23 +0000535 std::string save(path);
Reid Spencerb88212e2004-09-15 05:49:50 +0000536 path = a_path;
Reid Spencer7aed4482004-09-29 00:01:17 +0000537 FlipBackSlashes(path);
Reid Spencer0c6a2832004-11-05 22:15:36 +0000538 if (!isValid()) {
Reid Spencer17c1bd32005-07-07 23:35:23 +0000539 path = save;
Reid Spencerb88212e2004-09-15 05:49:50 +0000540 return false;
541 }
542 return true;
543}
544
545bool
Jeffrey Yasskin5908f1e2009-12-17 21:02:39 +0000546Path::appendComponent(StringRef name) {
Reid Spencer17c1bd32005-07-07 23:35:23 +0000547 if (name.empty())
Reid Spencerb88212e2004-09-15 05:49:50 +0000548 return false;
Reid Spencer17c1bd32005-07-07 23:35:23 +0000549 std::string save(path);
550 if (!path.empty()) {
551 size_t last = path.size() - 1;
Jeff Cohenf5067762005-07-08 05:02:13 +0000552 if (path[last] != '/')
Reid Spencer17c1bd32005-07-07 23:35:23 +0000553 path += '/';
554 }
555 path += name;
Reid Spencer0c6a2832004-11-05 22:15:36 +0000556 if (!isValid()) {
Reid Spencer17c1bd32005-07-07 23:35:23 +0000557 path = save;
Reid Spencerb88212e2004-09-15 05:49:50 +0000558 return false;
559 }
560 return true;
561}
562
563bool
Reid Spencer17c1bd32005-07-07 23:35:23 +0000564Path::eraseComponent() {
Reid Spencerb88212e2004-09-15 05:49:50 +0000565 size_t slashpos = path.rfind('/',path.size());
Jeff Cohen0e1d7352005-07-08 04:50:08 +0000566 if (slashpos == path.size() - 1 || slashpos == std::string::npos)
Reid Spencerb88212e2004-09-15 05:49:50 +0000567 return false;
Jeff Cohen0aad91a2005-07-09 18:42:49 +0000568 std::string save(path);
Reid Spencerb88212e2004-09-15 05:49:50 +0000569 path.erase(slashpos);
Jeff Cohen0aad91a2005-07-09 18:42:49 +0000570 if (!isValid()) {
571 path = save;
572 return false;
573 }
Reid Spencerb88212e2004-09-15 05:49:50 +0000574 return true;
575}
576
577bool
Reid Spencer17c1bd32005-07-07 23:35:23 +0000578Path::eraseSuffix() {
Reid Spencerb88212e2004-09-15 05:49:50 +0000579 size_t dotpos = path.rfind('.',path.size());
580 size_t slashpos = path.rfind('/',path.size());
Jeff Cohen0e1d7352005-07-08 04:50:08 +0000581 if (dotpos != std::string::npos) {
Jeff Cohen0aad91a2005-07-09 18:42:49 +0000582 if (slashpos == std::string::npos || dotpos > slashpos+1) {
583 std::string save(path);
Jeff Cohen0e1d7352005-07-08 04:50:08 +0000584 path.erase(dotpos, path.size()-dotpos);
Jeff Cohen0aad91a2005-07-09 18:42:49 +0000585 if (!isValid()) {
586 path = save;
587 return false;
588 }
Jeff Cohenf5067762005-07-08 05:02:13 +0000589 return true;
Jeff Cohen0e1d7352005-07-08 04:50:08 +0000590 }
Reid Spencerb88212e2004-09-15 05:49:50 +0000591 }
592 return false;
593}
594
Reid Spencerb5d6b8f2006-08-24 18:58:37 +0000595inline bool PathMsg(std::string* ErrMsg, const char* pathname, const char*msg) {
596 if (ErrMsg)
597 *ErrMsg = std::string(pathname) + ": " + std::string(msg);
598 return true;
599}
600
Reid Spencerb88212e2004-09-15 05:49:50 +0000601bool
Reid Spencerb5d6b8f2006-08-24 18:58:37 +0000602Path::createDirectoryOnDisk(bool create_parents, std::string* ErrMsg) {
Reid Spencerb88212e2004-09-15 05:49:50 +0000603 // Get a writeable copy of the path name
Jeff Cohen0e1d7352005-07-08 04:50:08 +0000604 size_t len = path.length();
605 char *pathname = reinterpret_cast<char *>(_alloca(len+2));
606 path.copy(pathname, len);
607 pathname[len] = 0;
Jeff Cohenf5067762005-07-08 05:02:13 +0000608
Jeff Cohen0e1d7352005-07-08 04:50:08 +0000609 // Make sure it ends with a slash.
610 if (len == 0 || pathname[len - 1] != '/') {
611 pathname[len] = '/';
612 pathname[++len] = 0;
613 }
Reid Spencerb88212e2004-09-15 05:49:50 +0000614
Reid Spencer7aed4482004-09-29 00:01:17 +0000615 // Determine starting point for initial / search.
616 char *next = pathname;
617 if (pathname[0] == '/' && pathname[1] == '/') {
618 // Skip host name.
619 next = strchr(pathname+2, '/');
620 if (next == NULL)
Reid Spencerb5d6b8f2006-08-24 18:58:37 +0000621 return PathMsg(ErrMsg, pathname, "badly formed remote directory");
622
Reid Spencer7aed4482004-09-29 00:01:17 +0000623 // Skip share name.
624 next = strchr(next+1, '/');
625 if (next == NULL)
Reid Spencerb5d6b8f2006-08-24 18:58:37 +0000626 return PathMsg(ErrMsg, pathname,"badly formed remote directory");
627
Reid Spencer7aed4482004-09-29 00:01:17 +0000628 next++;
629 if (*next == 0)
Reid Spencerb5d6b8f2006-08-24 18:58:37 +0000630 return PathMsg(ErrMsg, pathname, "badly formed remote directory");
631
Reid Spencer7aed4482004-09-29 00:01:17 +0000632 } else {
633 if (pathname[1] == ':')
634 next += 2; // skip drive letter
635 if (*next == '/')
636 next++; // skip root directory
637 }
Reid Spencerb88212e2004-09-15 05:49:50 +0000638
639 // If we're supposed to create intermediate directories
Reid Spencer7aed4482004-09-29 00:01:17 +0000640 if (create_parents) {
Reid Spencerb88212e2004-09-15 05:49:50 +0000641 // Loop through the directory components until we're done
Reid Spencer7aed4482004-09-29 00:01:17 +0000642 while (*next) {
643 next = strchr(next, '/');
Reid Spencerb88212e2004-09-15 05:49:50 +0000644 *next = 0;
Benjamin Kramer9470ecdb2009-11-05 14:32:40 +0000645 if (!CreateDirectory(pathname, NULL) &&
646 GetLastError() != ERROR_ALREADY_EXISTS)
Kovarththanan Rajaratnam61bea8f2010-03-12 14:17:24 +0000647 return MakeErrMsg(ErrMsg,
Reid Spencerb5d6b8f2006-08-24 18:58:37 +0000648 std::string(pathname) + ": Can't create directory: ");
Reid Spencer7aed4482004-09-29 00:01:17 +0000649 *next++ = '/';
Reid Spencerb88212e2004-09-15 05:49:50 +0000650 }
Reid Spencer7aed4482004-09-29 00:01:17 +0000651 } else {
652 // Drop trailing slash.
Jeff Cohen0e1d7352005-07-08 04:50:08 +0000653 pathname[len-1] = 0;
Benjamin Kramer9470ecdb2009-11-05 14:32:40 +0000654 if (!CreateDirectory(pathname, NULL) &&
655 GetLastError() != ERROR_ALREADY_EXISTS) {
Mikhail Glushenkovb4921a02010-11-02 20:32:31 +0000656 return MakeErrMsg(ErrMsg, std::string(pathname) +
657 ": Can't create directory: ");
Reid Spencer7aed4482004-09-29 00:01:17 +0000658 }
Reid Spencerb88212e2004-09-15 05:49:50 +0000659 }
Reid Spencerb5d6b8f2006-08-24 18:58:37 +0000660 return false;
Reid Spencerb88212e2004-09-15 05:49:50 +0000661}
662
663bool
Reid Spencerb5d6b8f2006-08-24 18:58:37 +0000664Path::createFileOnDisk(std::string* ErrMsg) {
Reid Spencerb88212e2004-09-15 05:49:50 +0000665 // Create the file
Reid Spencer7aed4482004-09-29 00:01:17 +0000666 HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
Reid Spencer0e863362004-09-18 19:29:16 +0000667 FILE_ATTRIBUTE_NORMAL, NULL);
668 if (h == INVALID_HANDLE_VALUE)
Reid Spencerb5d6b8f2006-08-24 18:58:37 +0000669 return MakeErrMsg(ErrMsg, path + ": Can't create file: ");
Reid Spencerb88212e2004-09-15 05:49:50 +0000670
Reid Spencer0e863362004-09-18 19:29:16 +0000671 CloseHandle(h);
Reid Spencerb5d6b8f2006-08-24 18:58:37 +0000672 return false;
Reid Spencerb88212e2004-09-15 05:49:50 +0000673}
674
675bool
Chris Lattner3cec1092006-07-28 22:29:50 +0000676Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
Jeff Cohen79582362007-04-07 20:47:27 +0000677 WIN32_FILE_ATTRIBUTE_DATA fi;
678 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi))
679 return true;
Kovarththanan Rajaratnam61bea8f2010-03-12 14:17:24 +0000680
Jeff Cohen79582362007-04-07 20:47:27 +0000681 if (fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
Reid Spencer17c1bd32005-07-07 23:35:23 +0000682 // If it doesn't exist, we're done.
Michael J. Spencer58df2e02011-01-10 02:34:23 +0000683 bool Exists;
684 if (fs::exists(path, Exists) || !Exists)
Chris Lattner3cec1092006-07-28 22:29:50 +0000685 return false;
Reid Spencer17c1bd32005-07-07 23:35:23 +0000686
Jeff Cohen0e1d7352005-07-08 04:50:08 +0000687 char *pathname = reinterpret_cast<char *>(_alloca(path.length()+3));
Reid Spencer17c1bd32005-07-07 23:35:23 +0000688 int lastchar = path.length() - 1 ;
Jeff Cohen0e1d7352005-07-08 04:50:08 +0000689 path.copy(pathname, lastchar+1);
Reid Spencer17c1bd32005-07-07 23:35:23 +0000690
691 // Make path end with '/*'.
Jeff Cohen0e1d7352005-07-08 04:50:08 +0000692 if (pathname[lastchar] != '/')
693 pathname[++lastchar] = '/';
Reid Spencer17c1bd32005-07-07 23:35:23 +0000694 pathname[lastchar+1] = '*';
695 pathname[lastchar+2] = 0;
696
697 if (remove_contents) {
698 WIN32_FIND_DATA fd;
699 HANDLE h = FindFirstFile(pathname, &fd);
700
701 // It's a bad idea to alter the contents of a directory while enumerating
702 // its contents. So build a list of its contents first, then destroy them.
703
704 if (h != INVALID_HANDLE_VALUE) {
705 std::vector<Path> list;
706
707 do {
708 if (strcmp(fd.cFileName, ".") == 0)
709 continue;
710 if (strcmp(fd.cFileName, "..") == 0)
711 continue;
712
Jeff Cohenf5067762005-07-08 05:02:13 +0000713 Path aPath(path);
714 aPath.appendComponent(&fd.cFileName[0]);
Reid Spencer17c1bd32005-07-07 23:35:23 +0000715 list.push_back(aPath);
716 } while (FindNextFile(h, &fd));
717
718 DWORD err = GetLastError();
719 FindClose(h);
720 if (err != ERROR_NO_MORE_FILES) {
721 SetLastError(err);
Reid Spencer50eac3b2006-08-25 21:37:17 +0000722 return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
Reid Spencer17c1bd32005-07-07 23:35:23 +0000723 }
724
Jeff Cohenf5067762005-07-08 05:02:13 +0000725 for (std::vector<Path>::iterator I = list.begin(); I != list.end();
Reid Spencer17c1bd32005-07-07 23:35:23 +0000726 ++I) {
727 Path &aPath = *I;
Reid Spenceraf48d862005-07-08 03:08:58 +0000728 aPath.eraseFromDisk(true);
Reid Spencer17c1bd32005-07-07 23:35:23 +0000729 }
730 } else {
731 if (GetLastError() != ERROR_FILE_NOT_FOUND)
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 }
735
736 pathname[lastchar] = 0;
737 if (!RemoveDirectory(pathname))
Kovarththanan Rajaratnam61bea8f2010-03-12 14:17:24 +0000738 return MakeErrMsg(ErrStr,
Reid Spencer50eac3b2006-08-25 21:37:17 +0000739 std::string(pathname) + ": Can't destroy directory: ");
Chris Lattner3cec1092006-07-28 22:29:50 +0000740 return false;
Jeff Cohen79582362007-04-07 20:47:27 +0000741 } else {
742 // Read-only files cannot be deleted on Windows. Must remove the read-only
743 // attribute first.
744 if (fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
745 if (!SetFileAttributes(path.c_str(),
746 fi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
747 return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
748 }
749
750 if (!DeleteFile(path.c_str()))
751 return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
752 return false;
753 }
Reid Spencerb88212e2004-09-15 05:49:50 +0000754}
755
Reid Spencerc936ad12004-12-14 18:42:13 +0000756bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
Reid Spencerc936ad12004-12-14 18:42:13 +0000757 assert(len < 1024 && "Request for magic string too long");
Michael J. Spencer18f50052010-08-31 06:36:33 +0000758 char* buf = reinterpret_cast<char*>(alloca(len));
Jeff Cohen25dcdcc2004-12-31 19:01:08 +0000759
760 HANDLE h = CreateFile(path.c_str(),
761 GENERIC_READ,
762 FILE_SHARE_READ,
763 NULL,
764 OPEN_EXISTING,
765 FILE_ATTRIBUTE_NORMAL,
766 NULL);
767 if (h == INVALID_HANDLE_VALUE)
Reid Spencerc936ad12004-12-14 18:42:13 +0000768 return false;
Jeff Cohen25dcdcc2004-12-31 19:01:08 +0000769
770 DWORD nRead = 0;
771 BOOL ret = ReadFile(h, buf, len, &nRead, NULL);
772 CloseHandle(h);
773
774 if (!ret || nRead != len)
Reid Spencerc936ad12004-12-14 18:42:13 +0000775 return false;
Jeff Cohen25dcdcc2004-12-31 19:01:08 +0000776
Michael J. Spencer18f50052010-08-31 06:36:33 +0000777 Magic = std::string(buf, len);
Reid Spencerc936ad12004-12-14 18:42:13 +0000778 return true;
779}
780
Jeff Cohen98aff882004-12-31 04:39:07 +0000781bool
Reid Spencer879ed5a2006-08-23 07:30:48 +0000782Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
Francois Pichet083f3682010-09-30 00:44:58 +0000783 if (!MoveFileEx(path.c_str(), newName.c_str(), MOVEFILE_REPLACE_EXISTING))
784 return MakeErrMsg(ErrMsg, "Can't move '" + path + "' to '" + newName.path
785 + "': ");
786 return false;
Jeff Cohen98aff882004-12-31 04:39:07 +0000787}
788
789bool
Anton Korobeynikov6c6a70f2006-09-01 20:35:17 +0000790Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrMsg) const {
Jeff Cohen0aad91a2005-07-09 18:42:49 +0000791 // FIXME: should work on directories also.
Anton Korobeynikov6c6a70f2006-09-01 20:35:17 +0000792 if (!si.isFile) {
793 return true;
794 }
Kovarththanan Rajaratnam61bea8f2010-03-12 14:17:24 +0000795
Jeff Cohen98aff882004-12-31 04:39:07 +0000796 HANDLE h = CreateFile(path.c_str(),
797 FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES,
798 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
Jeff Cohen63f13c42004-12-31 05:07:26 +0000799 NULL,
800 OPEN_EXISTING,
801 FILE_ATTRIBUTE_NORMAL,
802 NULL);
Jeff Cohen98aff882004-12-31 04:39:07 +0000803 if (h == INVALID_HANDLE_VALUE)
Chris Lattner60c50642006-07-28 22:36:17 +0000804 return true;
Jeff Cohen98aff882004-12-31 04:39:07 +0000805
806 BY_HANDLE_FILE_INFORMATION bhfi;
807 if (!GetFileInformationByHandle(h, &bhfi)) {
Jeff Cohen25dcdcc2004-12-31 19:01:08 +0000808 DWORD err = GetLastError();
Jeff Cohen98aff882004-12-31 04:39:07 +0000809 CloseHandle(h);
Jeff Cohen25dcdcc2004-12-31 19:01:08 +0000810 SetLastError(err);
Anton Korobeynikov6c6a70f2006-09-01 20:35:17 +0000811 return MakeErrMsg(ErrMsg, path + ": GetFileInformationByHandle: ");
Jeff Cohen98aff882004-12-31 04:39:07 +0000812 }
813
Michael J. Spencerd75cf222010-08-28 16:39:32 +0000814 ULARGE_INTEGER ui;
815 ui.QuadPart = si.modTime.toWin32Time();
Jeff Cohen98aff882004-12-31 04:39:07 +0000816 FILETIME ft;
Michael J. Spencerd75cf222010-08-28 16:39:32 +0000817 ft.dwLowDateTime = ui.LowPart;
818 ft.dwHighDateTime = ui.HighPart;
Jeff Cohen98aff882004-12-31 04:39:07 +0000819 BOOL ret = SetFileTime(h, NULL, &ft, &ft);
Jeff Cohen25dcdcc2004-12-31 19:01:08 +0000820 DWORD err = GetLastError();
Jeff Cohen98aff882004-12-31 04:39:07 +0000821 CloseHandle(h);
Jeff Cohen25dcdcc2004-12-31 19:01:08 +0000822 if (!ret) {
823 SetLastError(err);
Anton Korobeynikov6c6a70f2006-09-01 20:35:17 +0000824 return MakeErrMsg(ErrMsg, path + ": SetFileTime: ");
Jeff Cohen25dcdcc2004-12-31 19:01:08 +0000825 }
Jeff Cohen98aff882004-12-31 04:39:07 +0000826
827 // Best we can do with Unix permission bits is to interpret the owner
828 // writable bit.
829 if (si.mode & 0200) {
830 if (bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
831 if (!SetFileAttributes(path.c_str(),
Jeff Cohen63f13c42004-12-31 05:07:26 +0000832 bhfi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
Anton Korobeynikov6c6a70f2006-09-01 20:35:17 +0000833 return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
Jeff Cohen98aff882004-12-31 04:39:07 +0000834 }
835 } else {
836 if (!(bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY)) {
837 if (!SetFileAttributes(path.c_str(),
Jeff Cohen63f13c42004-12-31 05:07:26 +0000838 bhfi.dwFileAttributes | FILE_ATTRIBUTE_READONLY))
Anton Korobeynikov6c6a70f2006-09-01 20:35:17 +0000839 return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
Jeff Cohen98aff882004-12-31 04:39:07 +0000840 }
841 }
842
Chris Lattner60c50642006-07-28 22:36:17 +0000843 return false;
Jeff Cohen98aff882004-12-31 04:39:07 +0000844}
845
Reid Spencerb5d6b8f2006-08-24 18:58:37 +0000846bool
847CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg) {
Jeff Cohend567bb62004-12-24 02:38:34 +0000848 // Can't use CopyFile macro defined in Windows.h because it would mess up the
849 // above line. We use the expansion it would have in a non-UNICODE build.
850 if (!::CopyFileA(Src.c_str(), Dest.c_str(), false))
Chris Lattnerc521f542009-08-23 22:45:37 +0000851 return MakeErrMsg(ErrMsg, "Can't copy '" + Src.str() +
852 "' to '" + Dest.str() + "': ");
Reid Spencerb5d6b8f2006-08-24 18:58:37 +0000853 return false;
Reid Spencerf66d9322004-12-15 01:50:13 +0000854}
855
Reid Spencerb5d6b8f2006-08-24 18:58:37 +0000856bool
857Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
Michael J. Spencer58df2e02011-01-10 02:34:23 +0000858 bool Exists;
859 if (reuse_current && (fs::exists(path, Exists) || !Exists))
Reid Spencerb5d6b8f2006-08-24 18:58:37 +0000860 return false; // File doesn't exist already, just use it!
Reid Spencerf66d9322004-12-15 01:50:13 +0000861
Jeff Cohen9671b212005-01-27 03:49:03 +0000862 // Reserve space for -XXXXXX at the end.
863 char *FNBuffer = (char*) alloca(path.size()+8);
864 unsigned offset = path.size();
865 path.copy(FNBuffer, offset);
Reid Spencerf66d9322004-12-15 01:50:13 +0000866
Jeff Cohen0aad91a2005-07-09 18:42:49 +0000867 // Find a numeric suffix that isn't used by an existing file. Assume there
868 // won't be more than 1 million files with the same prefix. Probably a safe
869 // bet.
NAKAMURA Takumiaaa9b4f2011-03-16 02:53:24 +0000870 static int FCounter = -1;
871 if (FCounter < 0) {
872 // Give arbitrary initial seed.
873 // FIXME: We should use sys::fs::unique_file() in future.
874 LARGE_INTEGER cnt64;
875 DWORD x = GetCurrentProcessId();
876 x = (x << 16) | (x >> 16);
877 if (QueryPerformanceCounter(&cnt64)) // RDTSC
878 x ^= cnt64.HighPart ^ cnt64.LowPart;
879 FCounter = x % 1000000;
880 }
Jeff Cohen9671b212005-01-27 03:49:03 +0000881 do {
882 sprintf(FNBuffer+offset, "-%06u", FCounter);
883 if (++FCounter > 999999)
884 FCounter = 0;
885 path = FNBuffer;
Michael J. Spencer58df2e02011-01-10 02:34:23 +0000886 } while (!fs::exists(path, Exists) && Exists);
Reid Spencerb5d6b8f2006-08-24 18:58:37 +0000887 return false;
Reid Spencerf66d9322004-12-15 01:50:13 +0000888}
889
Reid Spencer98ce23f2004-12-15 08:32:45 +0000890bool
Reid Spencerb5d6b8f2006-08-24 18:58:37 +0000891Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
Reid Spencer98ce23f2004-12-15 08:32:45 +0000892 // Make this into a unique file name
Anton Korobeynikov6c6a70f2006-09-01 20:35:17 +0000893 makeUnique(reuse_current, ErrMsg);
Jeff Cohen9671b212005-01-27 03:49:03 +0000894
895 // Now go and create it
896 HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
897 FILE_ATTRIBUTE_NORMAL, NULL);
898 if (h == INVALID_HANDLE_VALUE)
Anton Korobeynikov6c6a70f2006-09-01 20:35:17 +0000899 return MakeErrMsg(ErrMsg, path + ": can't create file");
Jeff Cohen9671b212005-01-27 03:49:03 +0000900
901 CloseHandle(h);
Reid Spencerb5d6b8f2006-08-24 18:58:37 +0000902 return false;
Reid Spencer98ce23f2004-12-15 08:32:45 +0000903}
904
Chris Lattner3089e1d2008-04-01 06:00:12 +0000905/// MapInFilePages - Not yet implemented on win32.
Rafael Espindola510b00c2011-03-10 18:30:48 +0000906const char *Path::MapInFilePages(int FD, size_t FileSize, off_t Offset) {
Chris Lattner3089e1d2008-04-01 06:00:12 +0000907 return 0;
908}
909
910/// MapInFilePages - Not yet implemented on win32.
Rafael Espindola510b00c2011-03-10 18:30:48 +0000911void Path::UnMapFilePages(const char *Base, size_t FileSize) {
Chris Lattner3089e1d2008-04-01 06:00:12 +0000912 assert(0 && "NOT IMPLEMENTED");
913}
914
Reid Spencerb88212e2004-09-15 05:49:50 +0000915}
Reid Spencer566ac282004-09-11 04:59:30 +0000916}