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