blob: 62da3a34c4501aba9078f48123914d71798fcce1 [file] [log] [blame]
Argiris Kirtzidisfb155472008-06-16 10:14:09 +00001//===- llvm/System/Win32/Path.cpp - Win32 Path Implementation ---*- C++ -*-===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8// Modified by Henrik Bach to comply with at least MinGW.
9// Ported to Win32 by Jeff Cohen.
10//
11//===----------------------------------------------------------------------===//
12//
13// This file provides the Win32 specific implementation of the Path class.
14//
15//===----------------------------------------------------------------------===//
16
17//===----------------------------------------------------------------------===//
18//=== WARNING: Implementation here must contain only generic Win32 code that
19//=== is guaranteed to work on *all* Win32 variants.
20//===----------------------------------------------------------------------===//
21
22#include "Win32.h"
23#include <malloc.h>
Chris Lattner4b1f1e42009-04-01 02:03:38 +000024#include <cstdio>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000025
26// We need to undo a macro defined in Windows.h, otherwise we won't compile:
27#undef CopyFile
Anton Korobeynikove41a4bd2007-12-22 14:26:49 +000028#undef GetCurrentDirectory
Dan Gohmanf17a25c2007-07-18 16:29:46 +000029
30// Windows happily accepts either forward or backward slashes, though any path
31// returned by a Win32 API will have backward slashes. As LLVM code basically
32// assumes forward slashes are used, backward slashs are converted where they
33// can be introduced into a path.
34//
35// Another invariant is that a path ends with a slash if and only if the path
36// is a root directory. Any other use of a trailing slash is stripped. Unlike
37// in Unix, Windows has a rather complicated notion of a root path and this
38// invariant helps simply the code.
39
40static void FlipBackSlashes(std::string& s) {
41 for (size_t i = 0; i < s.size(); i++)
42 if (s[i] == '\\')
43 s[i] = '/';
44}
45
46namespace llvm {
47namespace sys {
Chris Lattner510190e2008-03-13 05:17:59 +000048const char PathSeparator = ';';
Chris Lattner4b8f1c62008-02-27 06:17:10 +000049
Nick Lewycky4fd4b462008-05-11 17:37:40 +000050Path::Path(const std::string& p)
51 : path(p) {
52 FlipBackSlashes(path);
53}
54
55Path::Path(const char *StrStart, unsigned StrLen)
56 : path(StrStart, StrLen) {
57 FlipBackSlashes(path);
58}
59
Chris Lattner43ac42b2008-08-11 23:39:47 +000060Path&
61Path::operator=(const std::string &that) {
62 path = that;
63 FlipBackSlashes(path);
64 return *this;
65}
66
Dan Gohmanf17a25c2007-07-18 16:29:46 +000067bool
68Path::isValid() const {
69 if (path.empty())
70 return false;
71
72 // If there is a colon, it must be the second character, preceded by a letter
73 // and followed by something.
74 size_t len = path.size();
75 size_t pos = path.rfind(':',len);
76 size_t rootslash = 0;
77 if (pos != std::string::npos) {
78 if (pos != 1 || !isalpha(path[0]) || len < 3)
79 return false;
80 rootslash = 2;
81 }
82
83 // Look for a UNC path, and if found adjust our notion of the root slash.
84 if (len > 3 && path[0] == '/' && path[1] == '/') {
85 rootslash = path.find('/', 2);
86 if (rootslash == std::string::npos)
87 rootslash = 0;
88 }
89
90 // Check for illegal characters.
91 if (path.find_first_of("\\<>\"|\001\002\003\004\005\006\007\010\011\012"
92 "\013\014\015\016\017\020\021\022\023\024\025\026"
93 "\027\030\031\032\033\034\035\036\037")
94 != std::string::npos)
95 return false;
96
97 // Remove trailing slash, unless it's a root slash.
98 if (len > rootslash+1 && path[len-1] == '/')
99 path.erase(--len);
100
101 // Check each component for legality.
102 for (pos = 0; pos < len; ++pos) {
103 // A component may not end in a space.
104 if (path[pos] == ' ') {
105 if (path[pos+1] == '/' || path[pos+1] == '\0')
106 return false;
107 }
108
109 // A component may not end in a period.
110 if (path[pos] == '.') {
111 if (path[pos+1] == '/' || path[pos+1] == '\0') {
112 // Unless it is the pseudo-directory "."...
113 if (pos == 0 || path[pos-1] == '/' || path[pos-1] == ':')
114 return true;
115 // or "..".
116 if (pos > 0 && path[pos-1] == '.') {
117 if (pos == 1 || path[pos-2] == '/' || path[pos-2] == ':')
118 return true;
119 }
120 return false;
121 }
122 }
123 }
124
125 return true;
126}
127
Chris Lattnerd024d8d2009-06-15 04:17:07 +0000128bool
129Path::isAbsolute(const char *NameStart, unsigned NameLen) {
130 assert(NameStart);
131 switch (NameLen) {
132 case 0:
133 return false;
134 case 1:
135 case 2:
136 return NameStart[0] == '/';
137 default:
138 return NameStart[0] == '/' || (NameStart[1] == ':' && NameStart[2] == '/');
139 }
140}
141
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000142bool
143Path::isAbsolute() const {
144 switch (path.length()) {
145 case 0:
146 return false;
147 case 1:
148 case 2:
149 return path[0] == '/';
150 default:
151 return path[0] == '/' || (path[1] == ':' && path[2] == '/');
152 }
153}
154
155static Path *TempDirectory = NULL;
156
157Path
158Path::GetTemporaryDirectory(std::string* ErrMsg) {
159 if (TempDirectory)
160 return *TempDirectory;
161
162 char pathname[MAX_PATH];
163 if (!GetTempPath(MAX_PATH, pathname)) {
164 if (ErrMsg)
165 *ErrMsg = "Can't determine temporary directory";
166 return Path();
167 }
168
169 Path result;
170 result.set(pathname);
171
172 // Append a subdirectory passed on our process id so multiple LLVMs don't
173 // step on each other's toes.
174#ifdef __MINGW32__
175 // Mingw's Win32 header files are broken.
176 sprintf(pathname, "LLVM_%u", unsigned(GetCurrentProcessId()));
177#else
178 sprintf(pathname, "LLVM_%u", GetCurrentProcessId());
179#endif
180 result.appendComponent(pathname);
181
182 // If there's a directory left over from a previous LLVM execution that
183 // happened to have the same process id, get rid of it.
184 result.eraseFromDisk(true);
185
186 // And finally (re-)create the empty directory.
187 result.createDirectoryOnDisk(false);
188 TempDirectory = new Path(result);
189 return *TempDirectory;
190}
191
192// FIXME: the following set of functions don't map to Windows very well.
193Path
194Path::GetRootDirectory() {
195 Path result;
196 result.set("C:/");
197 return result;
198}
199
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000200void
201Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
202 Paths.push_back(sys::Path("C:/WINDOWS/SYSTEM32"));
203 Paths.push_back(sys::Path("C:/WINDOWS"));
204}
205
206void
207Path::GetBitcodeLibraryPaths(std::vector<sys::Path>& Paths) {
208 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
209 if (env_var != 0) {
210 getPathList(env_var,Paths);
211 }
212#ifdef LLVM_LIBDIR
213 {
214 Path tmpPath;
215 if (tmpPath.set(LLVM_LIBDIR))
216 if (tmpPath.canRead())
217 Paths.push_back(tmpPath);
218 }
219#endif
220 GetSystemLibraryPaths(Paths);
221}
222
223Path
224Path::GetLLVMDefaultConfigDir() {
225 // TODO: this isn't going to fly on Windows
226 return Path("/etc/llvm");
227}
228
229Path
230Path::GetUserHomeDirectory() {
231 // TODO: Typical Windows setup doesn't define HOME.
232 const char* home = getenv("HOME");
233 if (home) {
234 Path result;
235 if (result.set(home))
236 return result;
237 }
238 return GetRootDirectory();
239}
Ted Kremenekb05c9352007-12-18 22:07:33 +0000240
241Path
242Path::GetCurrentDirectory() {
243 char pathname[MAX_PATH];
Anton Korobeynikove41a4bd2007-12-22 14:26:49 +0000244 ::GetCurrentDirectoryA(MAX_PATH,pathname);
Ted Kremenekb05c9352007-12-18 22:07:33 +0000245 return Path(pathname);
246}
247
Chris Lattner365f2202008-03-03 02:55:43 +0000248/// GetMainExecutable - Return the path to the main executable, given the
249/// value of argv[0] from program startup.
250Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
251 return Path();
252}
253
Ted Kremenekb05c9352007-12-18 22:07:33 +0000254
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000255// FIXME: the above set of functions don't map to Windows very well.
256
257
258bool
259Path::isRootDirectory() const {
260 size_t len = path.size();
261 return len > 0 && path[len-1] == '/';
262}
263
Ted Kremenekb169dfa2008-04-07 22:01:32 +0000264std::string Path::getDirname() const {
Nick Lewycky4fd4b462008-05-11 17:37:40 +0000265 return getDirnameCharSep(path, '/');
Ted Kremenekb169dfa2008-04-07 22:01:32 +0000266}
Ted Kremenek4a4f5ed2008-04-07 21:53:57 +0000267
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000268std::string
269Path::getBasename() const {
270 // Find the last slash
271 size_t slash = path.rfind('/');
272 if (slash == std::string::npos)
273 slash = 0;
274 else
275 slash++;
276
277 size_t dot = path.rfind('.');
278 if (dot == std::string::npos || dot < slash)
279 return path.substr(slash);
280 else
281 return path.substr(slash, dot - slash);
282}
283
Argiris Kirtzidisc8f4a3a2008-06-15 15:15:19 +0000284std::string
285Path::getSuffix() const {
286 // Find the last slash
287 size_t slash = path.rfind('/');
288 if (slash == std::string::npos)
289 slash = 0;
290 else
291 slash++;
292
293 size_t dot = path.rfind('.');
294 if (dot == std::string::npos || dot < slash)
295 return std::string();
296 else
297 return path.substr(dot + 1);
298}
299
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000300bool
301Path::exists() const {
302 DWORD attr = GetFileAttributes(path.c_str());
303 return attr != INVALID_FILE_ATTRIBUTES;
304}
305
306bool
Ted Kremenek65149be2007-12-18 19:46:22 +0000307Path::isDirectory() const {
308 DWORD attr = GetFileAttributes(path.c_str());
309 return (attr != INVALID_FILE_ATTRIBUTES) &&
310 (attr & FILE_ATTRIBUTE_DIRECTORY);
311}
312
313bool
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000314Path::canRead() const {
315 // FIXME: take security attributes into account.
316 DWORD attr = GetFileAttributes(path.c_str());
317 return attr != INVALID_FILE_ATTRIBUTES;
318}
319
320bool
321Path::canWrite() const {
322 // FIXME: take security attributes into account.
323 DWORD attr = GetFileAttributes(path.c_str());
324 return (attr != INVALID_FILE_ATTRIBUTES) && !(attr & FILE_ATTRIBUTE_READONLY);
325}
326
327bool
328Path::canExecute() const {
329 // FIXME: take security attributes into account.
330 DWORD attr = GetFileAttributes(path.c_str());
331 return attr != INVALID_FILE_ATTRIBUTES;
332}
333
334std::string
335Path::getLast() const {
336 // Find the last slash
337 size_t pos = path.rfind('/');
338
339 // Handle the corner cases
340 if (pos == std::string::npos)
341 return path;
342
343 // If the last character is a slash, we have a root directory
344 if (pos == path.length()-1)
345 return path;
346
347 // Return everything after the last slash
348 return path.substr(pos+1);
349}
350
351const FileStatus *
352PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
353 if (!fsIsValid || update) {
354 WIN32_FILE_ATTRIBUTE_DATA fi;
355 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
356 MakeErrMsg(ErrStr, "getStatusInfo():" + std::string(path) +
357 ": Can't get status: ");
358 return 0;
359 }
360
361 status.fileSize = fi.nFileSizeHigh;
362 status.fileSize <<= sizeof(fi.nFileSizeHigh)*8;
363 status.fileSize += fi.nFileSizeLow;
364
365 status.mode = fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY ? 0555 : 0777;
366 status.user = 9999; // Not applicable to Windows, so...
367 status.group = 9999; // Not applicable to Windows, so...
368
369 // FIXME: this is only unique if the file is accessed by the same file path.
370 // How do we do this for C:\dir\file and ..\dir\file ? Unix has inode
371 // numbers, but the concept doesn't exist in Windows.
372 status.uniqueID = 0;
373 for (unsigned i = 0; i < path.length(); ++i)
374 status.uniqueID += path[i];
375
376 __int64 ft = *reinterpret_cast<__int64*>(&fi.ftLastWriteTime);
377 status.modTime.fromWin32Time(ft);
378
379 status.isDir = fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
380 fsIsValid = true;
381 }
382 return &status;
383}
384
385bool Path::makeReadableOnDisk(std::string* ErrMsg) {
386 // All files are readable on Windows (ignoring security attributes).
387 return false;
388}
389
390bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
391 DWORD attr = GetFileAttributes(path.c_str());
392
393 // If it doesn't exist, we're done.
394 if (attr == INVALID_FILE_ATTRIBUTES)
395 return false;
396
397 if (attr & FILE_ATTRIBUTE_READONLY) {
398 if (!SetFileAttributes(path.c_str(), attr & ~FILE_ATTRIBUTE_READONLY)) {
399 MakeErrMsg(ErrMsg, std::string(path) + ": Can't make file writable: ");
400 return true;
401 }
402 }
403 return false;
404}
405
406bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
407 // All files are executable on Windows (ignoring security attributes).
408 return false;
409}
410
411bool
412Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
413 WIN32_FILE_ATTRIBUTE_DATA fi;
414 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
415 MakeErrMsg(ErrMsg, path + ": can't get status of file");
416 return true;
417 }
418
419 if (!(fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
420 if (ErrMsg)
421 *ErrMsg = path + ": not a directory";
422 return true;
423 }
424
425 result.clear();
426 WIN32_FIND_DATA fd;
427 std::string searchpath = path;
428 if (path.size() == 0 || searchpath[path.size()-1] == '/')
429 searchpath += "*";
430 else
431 searchpath += "/*";
432
433 HANDLE h = FindFirstFile(searchpath.c_str(), &fd);
434 if (h == INVALID_HANDLE_VALUE) {
435 if (GetLastError() == ERROR_FILE_NOT_FOUND)
436 return true; // not really an error, now is it?
437 MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
438 return true;
439 }
440
441 do {
442 if (fd.cFileName[0] == '.')
443 continue;
444 Path aPath(path);
445 aPath.appendComponent(&fd.cFileName[0]);
446 result.insert(aPath);
447 } while (FindNextFile(h, &fd));
448
449 DWORD err = GetLastError();
450 FindClose(h);
451 if (err != ERROR_NO_MORE_FILES) {
452 SetLastError(err);
453 MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
454 return true;
455 }
456 return false;
457}
458
459bool
460Path::set(const std::string& a_path) {
Dan Gohman301f4052008-01-29 13:02:09 +0000461 if (a_path.empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000462 return false;
463 std::string save(path);
464 path = a_path;
465 FlipBackSlashes(path);
466 if (!isValid()) {
467 path = save;
468 return false;
469 }
470 return true;
471}
472
473bool
474Path::appendComponent(const std::string& name) {
475 if (name.empty())
476 return false;
477 std::string save(path);
478 if (!path.empty()) {
479 size_t last = path.size() - 1;
480 if (path[last] != '/')
481 path += '/';
482 }
483 path += name;
484 if (!isValid()) {
485 path = save;
486 return false;
487 }
488 return true;
489}
490
491bool
492Path::eraseComponent() {
493 size_t slashpos = path.rfind('/',path.size());
494 if (slashpos == path.size() - 1 || slashpos == std::string::npos)
495 return false;
496 std::string save(path);
497 path.erase(slashpos);
498 if (!isValid()) {
499 path = save;
500 return false;
501 }
502 return true;
503}
504
505bool
506Path::appendSuffix(const std::string& suffix) {
507 std::string save(path);
508 path.append(".");
509 path.append(suffix);
510 if (!isValid()) {
511 path = save;
512 return false;
513 }
514 return true;
515}
516
517bool
518Path::eraseSuffix() {
519 size_t dotpos = path.rfind('.',path.size());
520 size_t slashpos = path.rfind('/',path.size());
521 if (dotpos != std::string::npos) {
522 if (slashpos == std::string::npos || dotpos > slashpos+1) {
523 std::string save(path);
524 path.erase(dotpos, path.size()-dotpos);
525 if (!isValid()) {
526 path = save;
527 return false;
528 }
529 return true;
530 }
531 }
532 return false;
533}
534
535inline bool PathMsg(std::string* ErrMsg, const char* pathname, const char*msg) {
536 if (ErrMsg)
537 *ErrMsg = std::string(pathname) + ": " + std::string(msg);
538 return true;
539}
540
541bool
542Path::createDirectoryOnDisk(bool create_parents, std::string* ErrMsg) {
543 // Get a writeable copy of the path name
544 size_t len = path.length();
545 char *pathname = reinterpret_cast<char *>(_alloca(len+2));
546 path.copy(pathname, len);
547 pathname[len] = 0;
548
549 // Make sure it ends with a slash.
550 if (len == 0 || pathname[len - 1] != '/') {
551 pathname[len] = '/';
552 pathname[++len] = 0;
553 }
554
555 // Determine starting point for initial / search.
556 char *next = pathname;
557 if (pathname[0] == '/' && pathname[1] == '/') {
558 // Skip host name.
559 next = strchr(pathname+2, '/');
560 if (next == NULL)
561 return PathMsg(ErrMsg, pathname, "badly formed remote directory");
562
563 // Skip share name.
564 next = strchr(next+1, '/');
565 if (next == NULL)
566 return PathMsg(ErrMsg, pathname,"badly formed remote directory");
567
568 next++;
569 if (*next == 0)
570 return PathMsg(ErrMsg, pathname, "badly formed remote directory");
571
572 } else {
573 if (pathname[1] == ':')
574 next += 2; // skip drive letter
575 if (*next == '/')
576 next++; // skip root directory
577 }
578
579 // If we're supposed to create intermediate directories
580 if (create_parents) {
581 // Loop through the directory components until we're done
582 while (*next) {
583 next = strchr(next, '/');
584 *next = 0;
585 if (!CreateDirectory(pathname, NULL))
586 return MakeErrMsg(ErrMsg,
587 std::string(pathname) + ": Can't create directory: ");
588 *next++ = '/';
589 }
590 } else {
591 // Drop trailing slash.
592 pathname[len-1] = 0;
593 if (!CreateDirectory(pathname, NULL)) {
594 return MakeErrMsg(ErrMsg, std::string(pathname) + ": Can't create directory: ");
595 }
596 }
597 return false;
598}
599
600bool
601Path::createFileOnDisk(std::string* ErrMsg) {
602 // Create the file
603 HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
604 FILE_ATTRIBUTE_NORMAL, NULL);
605 if (h == INVALID_HANDLE_VALUE)
606 return MakeErrMsg(ErrMsg, path + ": Can't create file: ");
607
608 CloseHandle(h);
609 return false;
610}
611
612bool
613Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
614 WIN32_FILE_ATTRIBUTE_DATA fi;
615 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi))
616 return true;
617
618 if (fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
619 // If it doesn't exist, we're done.
620 if (!exists())
621 return false;
622
623 char *pathname = reinterpret_cast<char *>(_alloca(path.length()+3));
624 int lastchar = path.length() - 1 ;
625 path.copy(pathname, lastchar+1);
626
627 // Make path end with '/*'.
628 if (pathname[lastchar] != '/')
629 pathname[++lastchar] = '/';
630 pathname[lastchar+1] = '*';
631 pathname[lastchar+2] = 0;
632
633 if (remove_contents) {
634 WIN32_FIND_DATA fd;
635 HANDLE h = FindFirstFile(pathname, &fd);
636
637 // It's a bad idea to alter the contents of a directory while enumerating
638 // its contents. So build a list of its contents first, then destroy them.
639
640 if (h != INVALID_HANDLE_VALUE) {
641 std::vector<Path> list;
642
643 do {
644 if (strcmp(fd.cFileName, ".") == 0)
645 continue;
646 if (strcmp(fd.cFileName, "..") == 0)
647 continue;
648
649 Path aPath(path);
650 aPath.appendComponent(&fd.cFileName[0]);
651 list.push_back(aPath);
652 } while (FindNextFile(h, &fd));
653
654 DWORD err = GetLastError();
655 FindClose(h);
656 if (err != ERROR_NO_MORE_FILES) {
657 SetLastError(err);
658 return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
659 }
660
661 for (std::vector<Path>::iterator I = list.begin(); I != list.end();
662 ++I) {
663 Path &aPath = *I;
664 aPath.eraseFromDisk(true);
665 }
666 } else {
667 if (GetLastError() != ERROR_FILE_NOT_FOUND)
668 return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
669 }
670 }
671
672 pathname[lastchar] = 0;
673 if (!RemoveDirectory(pathname))
674 return MakeErrMsg(ErrStr,
675 std::string(pathname) + ": Can't destroy directory: ");
676 return false;
677 } else {
678 // Read-only files cannot be deleted on Windows. Must remove the read-only
679 // attribute first.
680 if (fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
681 if (!SetFileAttributes(path.c_str(),
682 fi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
683 return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
684 }
685
686 if (!DeleteFile(path.c_str()))
687 return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
688 return false;
689 }
690}
691
692bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
693 assert(len < 1024 && "Request for magic string too long");
694 char* buf = (char*) alloca(1 + len);
695
696 HANDLE h = CreateFile(path.c_str(),
697 GENERIC_READ,
698 FILE_SHARE_READ,
699 NULL,
700 OPEN_EXISTING,
701 FILE_ATTRIBUTE_NORMAL,
702 NULL);
703 if (h == INVALID_HANDLE_VALUE)
704 return false;
705
706 DWORD nRead = 0;
707 BOOL ret = ReadFile(h, buf, len, &nRead, NULL);
708 CloseHandle(h);
709
710 if (!ret || nRead != len)
711 return false;
712
713 buf[len] = '\0';
714 Magic = buf;
715 return true;
716}
717
718bool
719Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
720 if (!MoveFileEx(path.c_str(), newName.c_str(), MOVEFILE_REPLACE_EXISTING))
721 return MakeErrMsg(ErrMsg, "Can't move '" + path + "' to '" + newName.path
722 + "': ");
Nick Lewyckyc74d8f92008-05-06 03:42:21 +0000723 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000724}
725
726bool
727Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrMsg) const {
728 // FIXME: should work on directories also.
729 if (!si.isFile) {
730 return true;
731 }
732
733 HANDLE h = CreateFile(path.c_str(),
734 FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES,
735 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
736 NULL,
737 OPEN_EXISTING,
738 FILE_ATTRIBUTE_NORMAL,
739 NULL);
740 if (h == INVALID_HANDLE_VALUE)
741 return true;
742
743 BY_HANDLE_FILE_INFORMATION bhfi;
744 if (!GetFileInformationByHandle(h, &bhfi)) {
745 DWORD err = GetLastError();
746 CloseHandle(h);
747 SetLastError(err);
748 return MakeErrMsg(ErrMsg, path + ": GetFileInformationByHandle: ");
749 }
750
751 FILETIME ft;
752 (uint64_t&)ft = si.modTime.toWin32Time();
753 BOOL ret = SetFileTime(h, NULL, &ft, &ft);
754 DWORD err = GetLastError();
755 CloseHandle(h);
756 if (!ret) {
757 SetLastError(err);
758 return MakeErrMsg(ErrMsg, path + ": SetFileTime: ");
759 }
760
761 // Best we can do with Unix permission bits is to interpret the owner
762 // writable bit.
763 if (si.mode & 0200) {
764 if (bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
765 if (!SetFileAttributes(path.c_str(),
766 bhfi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
767 return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
768 }
769 } else {
770 if (!(bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY)) {
771 if (!SetFileAttributes(path.c_str(),
772 bhfi.dwFileAttributes | FILE_ATTRIBUTE_READONLY))
773 return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
774 }
775 }
776
777 return false;
778}
779
780bool
781CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg) {
782 // Can't use CopyFile macro defined in Windows.h because it would mess up the
783 // above line. We use the expansion it would have in a non-UNICODE build.
784 if (!::CopyFileA(Src.c_str(), Dest.c_str(), false))
785 return MakeErrMsg(ErrMsg, "Can't copy '" + Src.toString() +
786 "' to '" + Dest.toString() + "': ");
787 return false;
788}
789
790bool
791Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
792 if (reuse_current && !exists())
793 return false; // File doesn't exist already, just use it!
794
795 // Reserve space for -XXXXXX at the end.
796 char *FNBuffer = (char*) alloca(path.size()+8);
797 unsigned offset = path.size();
798 path.copy(FNBuffer, offset);
799
800 // Find a numeric suffix that isn't used by an existing file. Assume there
801 // won't be more than 1 million files with the same prefix. Probably a safe
802 // bet.
803 static unsigned FCounter = 0;
804 do {
805 sprintf(FNBuffer+offset, "-%06u", FCounter);
806 if (++FCounter > 999999)
807 FCounter = 0;
808 path = FNBuffer;
809 } while (exists());
810 return false;
811}
812
813bool
814Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
815 // Make this into a unique file name
816 makeUnique(reuse_current, ErrMsg);
817
818 // Now go and create it
819 HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
820 FILE_ATTRIBUTE_NORMAL, NULL);
821 if (h == INVALID_HANDLE_VALUE)
822 return MakeErrMsg(ErrMsg, path + ": can't create file");
823
824 CloseHandle(h);
825 return false;
826}
827
Chris Lattner157d70a2008-04-01 06:00:12 +0000828/// MapInFilePages - Not yet implemented on win32.
829const char *Path::MapInFilePages(int FD, uint64_t FileSize) {
830 return 0;
831}
832
833/// MapInFilePages - Not yet implemented on win32.
834void Path::UnMapFilePages(const char *Base, uint64_t FileSize) {
835 assert(0 && "NOT IMPLEMENTED");
836}
837
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000838}
839}