blob: 35bae337da7f5e0f1f5bed3595c3654ffdc9ddb3 [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 Kremenek4a4f5ed2008-04-07 21:53:57 +0000232std::string Path::getDirname() const { return getDirnameCharSep('\\'); }
233
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000234std::string
235Path::getBasename() const {
236 // Find the last slash
237 size_t slash = path.rfind('/');
238 if (slash == std::string::npos)
239 slash = 0;
240 else
241 slash++;
242
243 size_t dot = path.rfind('.');
244 if (dot == std::string::npos || dot < slash)
245 return path.substr(slash);
246 else
247 return path.substr(slash, dot - slash);
248}
249
250bool
251Path::exists() const {
252 DWORD attr = GetFileAttributes(path.c_str());
253 return attr != INVALID_FILE_ATTRIBUTES;
254}
255
256bool
Ted Kremenek65149be2007-12-18 19:46:22 +0000257Path::isDirectory() const {
258 DWORD attr = GetFileAttributes(path.c_str());
259 return (attr != INVALID_FILE_ATTRIBUTES) &&
260 (attr & FILE_ATTRIBUTE_DIRECTORY);
261}
262
263bool
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000264Path::canRead() const {
265 // FIXME: take security attributes into account.
266 DWORD attr = GetFileAttributes(path.c_str());
267 return attr != INVALID_FILE_ATTRIBUTES;
268}
269
270bool
271Path::canWrite() const {
272 // FIXME: take security attributes into account.
273 DWORD attr = GetFileAttributes(path.c_str());
274 return (attr != INVALID_FILE_ATTRIBUTES) && !(attr & FILE_ATTRIBUTE_READONLY);
275}
276
277bool
278Path::canExecute() const {
279 // FIXME: take security attributes into account.
280 DWORD attr = GetFileAttributes(path.c_str());
281 return attr != INVALID_FILE_ATTRIBUTES;
282}
283
284std::string
285Path::getLast() const {
286 // Find the last slash
287 size_t pos = path.rfind('/');
288
289 // Handle the corner cases
290 if (pos == std::string::npos)
291 return path;
292
293 // If the last character is a slash, we have a root directory
294 if (pos == path.length()-1)
295 return path;
296
297 // Return everything after the last slash
298 return path.substr(pos+1);
299}
300
301const FileStatus *
302PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
303 if (!fsIsValid || update) {
304 WIN32_FILE_ATTRIBUTE_DATA fi;
305 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
306 MakeErrMsg(ErrStr, "getStatusInfo():" + std::string(path) +
307 ": Can't get status: ");
308 return 0;
309 }
310
311 status.fileSize = fi.nFileSizeHigh;
312 status.fileSize <<= sizeof(fi.nFileSizeHigh)*8;
313 status.fileSize += fi.nFileSizeLow;
314
315 status.mode = fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY ? 0555 : 0777;
316 status.user = 9999; // Not applicable to Windows, so...
317 status.group = 9999; // Not applicable to Windows, so...
318
319 // FIXME: this is only unique if the file is accessed by the same file path.
320 // How do we do this for C:\dir\file and ..\dir\file ? Unix has inode
321 // numbers, but the concept doesn't exist in Windows.
322 status.uniqueID = 0;
323 for (unsigned i = 0; i < path.length(); ++i)
324 status.uniqueID += path[i];
325
326 __int64 ft = *reinterpret_cast<__int64*>(&fi.ftLastWriteTime);
327 status.modTime.fromWin32Time(ft);
328
329 status.isDir = fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
330 fsIsValid = true;
331 }
332 return &status;
333}
334
335bool Path::makeReadableOnDisk(std::string* ErrMsg) {
336 // All files are readable on Windows (ignoring security attributes).
337 return false;
338}
339
340bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
341 DWORD attr = GetFileAttributes(path.c_str());
342
343 // If it doesn't exist, we're done.
344 if (attr == INVALID_FILE_ATTRIBUTES)
345 return false;
346
347 if (attr & FILE_ATTRIBUTE_READONLY) {
348 if (!SetFileAttributes(path.c_str(), attr & ~FILE_ATTRIBUTE_READONLY)) {
349 MakeErrMsg(ErrMsg, std::string(path) + ": Can't make file writable: ");
350 return true;
351 }
352 }
353 return false;
354}
355
356bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
357 // All files are executable on Windows (ignoring security attributes).
358 return false;
359}
360
361bool
362Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
363 WIN32_FILE_ATTRIBUTE_DATA fi;
364 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
365 MakeErrMsg(ErrMsg, path + ": can't get status of file");
366 return true;
367 }
368
369 if (!(fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
370 if (ErrMsg)
371 *ErrMsg = path + ": not a directory";
372 return true;
373 }
374
375 result.clear();
376 WIN32_FIND_DATA fd;
377 std::string searchpath = path;
378 if (path.size() == 0 || searchpath[path.size()-1] == '/')
379 searchpath += "*";
380 else
381 searchpath += "/*";
382
383 HANDLE h = FindFirstFile(searchpath.c_str(), &fd);
384 if (h == INVALID_HANDLE_VALUE) {
385 if (GetLastError() == ERROR_FILE_NOT_FOUND)
386 return true; // not really an error, now is it?
387 MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
388 return true;
389 }
390
391 do {
392 if (fd.cFileName[0] == '.')
393 continue;
394 Path aPath(path);
395 aPath.appendComponent(&fd.cFileName[0]);
396 result.insert(aPath);
397 } while (FindNextFile(h, &fd));
398
399 DWORD err = GetLastError();
400 FindClose(h);
401 if (err != ERROR_NO_MORE_FILES) {
402 SetLastError(err);
403 MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
404 return true;
405 }
406 return false;
407}
408
409bool
410Path::set(const std::string& a_path) {
Dan Gohman301f4052008-01-29 13:02:09 +0000411 if (a_path.empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000412 return false;
413 std::string save(path);
414 path = a_path;
415 FlipBackSlashes(path);
416 if (!isValid()) {
417 path = save;
418 return false;
419 }
420 return true;
421}
422
423bool
424Path::appendComponent(const std::string& name) {
425 if (name.empty())
426 return false;
427 std::string save(path);
428 if (!path.empty()) {
429 size_t last = path.size() - 1;
430 if (path[last] != '/')
431 path += '/';
432 }
433 path += name;
434 if (!isValid()) {
435 path = save;
436 return false;
437 }
438 return true;
439}
440
441bool
442Path::eraseComponent() {
443 size_t slashpos = path.rfind('/',path.size());
444 if (slashpos == path.size() - 1 || slashpos == std::string::npos)
445 return false;
446 std::string save(path);
447 path.erase(slashpos);
448 if (!isValid()) {
449 path = save;
450 return false;
451 }
452 return true;
453}
454
455bool
456Path::appendSuffix(const std::string& suffix) {
457 std::string save(path);
458 path.append(".");
459 path.append(suffix);
460 if (!isValid()) {
461 path = save;
462 return false;
463 }
464 return true;
465}
466
467bool
468Path::eraseSuffix() {
469 size_t dotpos = path.rfind('.',path.size());
470 size_t slashpos = path.rfind('/',path.size());
471 if (dotpos != std::string::npos) {
472 if (slashpos == std::string::npos || dotpos > slashpos+1) {
473 std::string save(path);
474 path.erase(dotpos, path.size()-dotpos);
475 if (!isValid()) {
476 path = save;
477 return false;
478 }
479 return true;
480 }
481 }
482 return false;
483}
484
485inline bool PathMsg(std::string* ErrMsg, const char* pathname, const char*msg) {
486 if (ErrMsg)
487 *ErrMsg = std::string(pathname) + ": " + std::string(msg);
488 return true;
489}
490
491bool
492Path::createDirectoryOnDisk(bool create_parents, std::string* ErrMsg) {
493 // Get a writeable copy of the path name
494 size_t len = path.length();
495 char *pathname = reinterpret_cast<char *>(_alloca(len+2));
496 path.copy(pathname, len);
497 pathname[len] = 0;
498
499 // Make sure it ends with a slash.
500 if (len == 0 || pathname[len - 1] != '/') {
501 pathname[len] = '/';
502 pathname[++len] = 0;
503 }
504
505 // Determine starting point for initial / search.
506 char *next = pathname;
507 if (pathname[0] == '/' && pathname[1] == '/') {
508 // Skip host name.
509 next = strchr(pathname+2, '/');
510 if (next == NULL)
511 return PathMsg(ErrMsg, pathname, "badly formed remote directory");
512
513 // Skip share name.
514 next = strchr(next+1, '/');
515 if (next == NULL)
516 return PathMsg(ErrMsg, pathname,"badly formed remote directory");
517
518 next++;
519 if (*next == 0)
520 return PathMsg(ErrMsg, pathname, "badly formed remote directory");
521
522 } else {
523 if (pathname[1] == ':')
524 next += 2; // skip drive letter
525 if (*next == '/')
526 next++; // skip root directory
527 }
528
529 // If we're supposed to create intermediate directories
530 if (create_parents) {
531 // Loop through the directory components until we're done
532 while (*next) {
533 next = strchr(next, '/');
534 *next = 0;
535 if (!CreateDirectory(pathname, NULL))
536 return MakeErrMsg(ErrMsg,
537 std::string(pathname) + ": Can't create directory: ");
538 *next++ = '/';
539 }
540 } else {
541 // Drop trailing slash.
542 pathname[len-1] = 0;
543 if (!CreateDirectory(pathname, NULL)) {
544 return MakeErrMsg(ErrMsg, std::string(pathname) + ": Can't create directory: ");
545 }
546 }
547 return false;
548}
549
550bool
551Path::createFileOnDisk(std::string* ErrMsg) {
552 // Create the file
553 HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
554 FILE_ATTRIBUTE_NORMAL, NULL);
555 if (h == INVALID_HANDLE_VALUE)
556 return MakeErrMsg(ErrMsg, path + ": Can't create file: ");
557
558 CloseHandle(h);
559 return false;
560}
561
562bool
563Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
564 WIN32_FILE_ATTRIBUTE_DATA fi;
565 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi))
566 return true;
567
568 if (fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
569 // If it doesn't exist, we're done.
570 if (!exists())
571 return false;
572
573 char *pathname = reinterpret_cast<char *>(_alloca(path.length()+3));
574 int lastchar = path.length() - 1 ;
575 path.copy(pathname, lastchar+1);
576
577 // Make path end with '/*'.
578 if (pathname[lastchar] != '/')
579 pathname[++lastchar] = '/';
580 pathname[lastchar+1] = '*';
581 pathname[lastchar+2] = 0;
582
583 if (remove_contents) {
584 WIN32_FIND_DATA fd;
585 HANDLE h = FindFirstFile(pathname, &fd);
586
587 // It's a bad idea to alter the contents of a directory while enumerating
588 // its contents. So build a list of its contents first, then destroy them.
589
590 if (h != INVALID_HANDLE_VALUE) {
591 std::vector<Path> list;
592
593 do {
594 if (strcmp(fd.cFileName, ".") == 0)
595 continue;
596 if (strcmp(fd.cFileName, "..") == 0)
597 continue;
598
599 Path aPath(path);
600 aPath.appendComponent(&fd.cFileName[0]);
601 list.push_back(aPath);
602 } while (FindNextFile(h, &fd));
603
604 DWORD err = GetLastError();
605 FindClose(h);
606 if (err != ERROR_NO_MORE_FILES) {
607 SetLastError(err);
608 return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
609 }
610
611 for (std::vector<Path>::iterator I = list.begin(); I != list.end();
612 ++I) {
613 Path &aPath = *I;
614 aPath.eraseFromDisk(true);
615 }
616 } else {
617 if (GetLastError() != ERROR_FILE_NOT_FOUND)
618 return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
619 }
620 }
621
622 pathname[lastchar] = 0;
623 if (!RemoveDirectory(pathname))
624 return MakeErrMsg(ErrStr,
625 std::string(pathname) + ": Can't destroy directory: ");
626 return false;
627 } else {
628 // Read-only files cannot be deleted on Windows. Must remove the read-only
629 // attribute first.
630 if (fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
631 if (!SetFileAttributes(path.c_str(),
632 fi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
633 return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
634 }
635
636 if (!DeleteFile(path.c_str()))
637 return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
638 return false;
639 }
640}
641
642bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
643 assert(len < 1024 && "Request for magic string too long");
644 char* buf = (char*) alloca(1 + len);
645
646 HANDLE h = CreateFile(path.c_str(),
647 GENERIC_READ,
648 FILE_SHARE_READ,
649 NULL,
650 OPEN_EXISTING,
651 FILE_ATTRIBUTE_NORMAL,
652 NULL);
653 if (h == INVALID_HANDLE_VALUE)
654 return false;
655
656 DWORD nRead = 0;
657 BOOL ret = ReadFile(h, buf, len, &nRead, NULL);
658 CloseHandle(h);
659
660 if (!ret || nRead != len)
661 return false;
662
663 buf[len] = '\0';
664 Magic = buf;
665 return true;
666}
667
668bool
669Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
670 if (!MoveFileEx(path.c_str(), newName.c_str(), MOVEFILE_REPLACE_EXISTING))
671 return MakeErrMsg(ErrMsg, "Can't move '" + path + "' to '" + newName.path
672 + "': ");
673 return true;
674}
675
676bool
677Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrMsg) const {
678 // FIXME: should work on directories also.
679 if (!si.isFile) {
680 return true;
681 }
682
683 HANDLE h = CreateFile(path.c_str(),
684 FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES,
685 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
686 NULL,
687 OPEN_EXISTING,
688 FILE_ATTRIBUTE_NORMAL,
689 NULL);
690 if (h == INVALID_HANDLE_VALUE)
691 return true;
692
693 BY_HANDLE_FILE_INFORMATION bhfi;
694 if (!GetFileInformationByHandle(h, &bhfi)) {
695 DWORD err = GetLastError();
696 CloseHandle(h);
697 SetLastError(err);
698 return MakeErrMsg(ErrMsg, path + ": GetFileInformationByHandle: ");
699 }
700
701 FILETIME ft;
702 (uint64_t&)ft = si.modTime.toWin32Time();
703 BOOL ret = SetFileTime(h, NULL, &ft, &ft);
704 DWORD err = GetLastError();
705 CloseHandle(h);
706 if (!ret) {
707 SetLastError(err);
708 return MakeErrMsg(ErrMsg, path + ": SetFileTime: ");
709 }
710
711 // Best we can do with Unix permission bits is to interpret the owner
712 // writable bit.
713 if (si.mode & 0200) {
714 if (bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
715 if (!SetFileAttributes(path.c_str(),
716 bhfi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
717 return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
718 }
719 } else {
720 if (!(bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY)) {
721 if (!SetFileAttributes(path.c_str(),
722 bhfi.dwFileAttributes | FILE_ATTRIBUTE_READONLY))
723 return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
724 }
725 }
726
727 return false;
728}
729
730bool
731CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg) {
732 // Can't use CopyFile macro defined in Windows.h because it would mess up the
733 // above line. We use the expansion it would have in a non-UNICODE build.
734 if (!::CopyFileA(Src.c_str(), Dest.c_str(), false))
735 return MakeErrMsg(ErrMsg, "Can't copy '" + Src.toString() +
736 "' to '" + Dest.toString() + "': ");
737 return false;
738}
739
740bool
741Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
742 if (reuse_current && !exists())
743 return false; // File doesn't exist already, just use it!
744
745 // Reserve space for -XXXXXX at the end.
746 char *FNBuffer = (char*) alloca(path.size()+8);
747 unsigned offset = path.size();
748 path.copy(FNBuffer, offset);
749
750 // Find a numeric suffix that isn't used by an existing file. Assume there
751 // won't be more than 1 million files with the same prefix. Probably a safe
752 // bet.
753 static unsigned FCounter = 0;
754 do {
755 sprintf(FNBuffer+offset, "-%06u", FCounter);
756 if (++FCounter > 999999)
757 FCounter = 0;
758 path = FNBuffer;
759 } while (exists());
760 return false;
761}
762
763bool
764Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
765 // Make this into a unique file name
766 makeUnique(reuse_current, ErrMsg);
767
768 // Now go and create it
769 HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
770 FILE_ATTRIBUTE_NORMAL, NULL);
771 if (h == INVALID_HANDLE_VALUE)
772 return MakeErrMsg(ErrMsg, path + ": can't create file");
773
774 CloseHandle(h);
775 return false;
776}
777
Chris Lattner157d70a2008-04-01 06:00:12 +0000778/// MapInFilePages - Not yet implemented on win32.
779const char *Path::MapInFilePages(int FD, uint64_t FileSize) {
780 return 0;
781}
782
783/// MapInFilePages - Not yet implemented on win32.
784void Path::UnMapFilePages(const char *Base, uint64_t FileSize) {
785 assert(0 && "NOT IMPLEMENTED");
786}
787
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000788}
789}