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