Path.inc revision 36782c514ae7c5f9270c317bdea660bdcd86d9d6
1//===- llvm/Support/Win32/Path.cpp - Win32 Path Implementation ---*- C++ -*-===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file provides the Win32 specific implementation of the Path class. 11// 12//===----------------------------------------------------------------------===// 13 14//===----------------------------------------------------------------------===// 15//=== WARNING: Implementation here must contain only generic Win32 code that 16//=== is guaranteed to work on *all* Win32 variants. 17//===----------------------------------------------------------------------===// 18 19#include "Windows.h" 20#include <cstdio> 21#include <malloc.h> 22 23// We need to undo a macro defined in Windows.h, otherwise we won't compile: 24#undef GetCurrentDirectory 25 26// Windows happily accepts either forward or backward slashes, though any path 27// returned by a Win32 API will have backward slashes. As LLVM code basically 28// assumes forward slashes are used, backward slashs are converted where they 29// can be introduced into a path. 30// 31// Another invariant is that a path ends with a slash if and only if the path 32// is a root directory. Any other use of a trailing slash is stripped. Unlike 33// in Unix, Windows has a rather complicated notion of a root path and this 34// invariant helps simply the code. 35 36static void FlipBackSlashes(std::string& s) { 37 for (size_t i = 0; i < s.size(); i++) 38 if (s[i] == '\\') 39 s[i] = '/'; 40} 41 42namespace llvm { 43namespace sys { 44 45const char PathSeparator = ';'; 46 47StringRef Path::GetEXESuffix() { 48 return "exe"; 49} 50 51Path::Path(llvm::StringRef p) 52 : path(p) { 53 FlipBackSlashes(path); 54} 55 56Path::Path(const char *StrStart, unsigned StrLen) 57 : path(StrStart, StrLen) { 58 FlipBackSlashes(path); 59} 60 61Path& 62Path::operator=(StringRef that) { 63 path.assign(that.data(), that.size()); 64 FlipBackSlashes(path); 65 return *this; 66} 67 68bool 69Path::isValid() const { 70 if (path.empty()) 71 return false; 72 73 size_t len = path.size(); 74 // If there is a null character, it and all its successors are ignored. 75 size_t pos = path.find_first_of('\0'); 76 if (pos != std::string::npos) 77 len = pos; 78 79 // If there is a colon, it must be the second character, preceded by a letter 80 // and followed by something. 81 pos = path.rfind(':',len); 82 size_t rootslash = 0; 83 if (pos != std::string::npos) { 84 if (pos != 1 || !isalpha(static_cast<unsigned char>(path[0])) || len < 3) 85 return false; 86 rootslash = 2; 87 } 88 89 // Look for a UNC path, and if found adjust our notion of the root slash. 90 if (len > 3 && path[0] == '/' && path[1] == '/') { 91 rootslash = path.find('/', 2); 92 if (rootslash == std::string::npos) 93 rootslash = 0; 94 } 95 96 // Check for illegal characters. 97 if (path.find_first_of("\\<>\"|\001\002\003\004\005\006\007\010\011\012" 98 "\013\014\015\016\017\020\021\022\023\024\025\026" 99 "\027\030\031\032\033\034\035\036\037") 100 != std::string::npos) 101 return false; 102 103 // Remove trailing slash, unless it's a root slash. 104 if (len > rootslash+1 && path[len-1] == '/') 105 path.erase(--len); 106 107 // Check each component for legality. 108 for (pos = 0; pos < len; ++pos) { 109 // A component may not end in a space. 110 if (path[pos] == ' ') { 111 if (pos+1 == len || path[pos+1] == '/' || path[pos+1] == '\0') 112 return false; 113 } 114 115 // A component may not end in a period. 116 if (path[pos] == '.') { 117 if (pos+1 == len || path[pos+1] == '/') { 118 // Unless it is the pseudo-directory "."... 119 if (pos == 0 || path[pos-1] == '/' || path[pos-1] == ':') 120 return true; 121 // or "..". 122 if (pos > 0 && path[pos-1] == '.') { 123 if (pos == 1 || path[pos-2] == '/' || path[pos-2] == ':') 124 return true; 125 } 126 return false; 127 } 128 } 129 } 130 131 return true; 132} 133 134void Path::makeAbsolute() { 135 TCHAR FullPath[MAX_PATH + 1] = {0}; 136 LPTSTR FilePart = NULL; 137 138 DWORD RetLength = ::GetFullPathNameA(path.c_str(), 139 sizeof(FullPath)/sizeof(FullPath[0]), 140 FullPath, &FilePart); 141 142 if (0 == RetLength) { 143 // FIXME: Report the error GetLastError() 144 assert(0 && "Unable to make absolute path!"); 145 } else if (RetLength > MAX_PATH) { 146 // FIXME: Report too small buffer (needed RetLength bytes). 147 assert(0 && "Unable to make absolute path!"); 148 } else { 149 path = FullPath; 150 } 151} 152 153bool 154Path::isAbsolute(const char *NameStart, unsigned NameLen) { 155 assert(NameStart); 156 // FIXME: This does not handle correctly an absolute path starting from 157 // a drive letter or in UNC format. 158 switch (NameLen) { 159 case 0: 160 return false; 161 case 1: 162 case 2: 163 return NameStart[0] == '/'; 164 default: 165 return 166 (NameStart[0] == '/' || (NameStart[1] == ':' && NameStart[2] == '/')) || 167 (NameStart[0] == '\\' || (NameStart[1] == ':' && NameStart[2] == '\\')); 168 } 169} 170 171bool 172Path::isAbsolute() const { 173 // FIXME: This does not handle correctly an absolute path starting from 174 // a drive letter or in UNC format. 175 switch (path.length()) { 176 case 0: 177 return false; 178 case 1: 179 case 2: 180 return path[0] == '/'; 181 default: 182 return path[0] == '/' || (path[1] == ':' && path[2] == '/'); 183 } 184} 185 186static Path *TempDirectory; 187 188Path 189Path::GetTemporaryDirectory(std::string* ErrMsg) { 190 if (TempDirectory) { 191#if defined(_MSC_VER) 192 // Visual Studio gets confused and emits a diagnostic about calling exists, 193 // even though this is the implementation for PathV1. Temporarily 194 // disable the deprecated warning message 195 #pragma warning(push) 196 #pragma warning(disable:4996) 197#endif 198 assert(TempDirectory->exists() && "Who has removed TempDirectory?"); 199#if defined(_MSC_VER) 200 #pragma warning(pop) 201#endif 202 return *TempDirectory; 203 } 204 205 char pathname[MAX_PATH]; 206 if (!GetTempPath(MAX_PATH, pathname)) { 207 if (ErrMsg) 208 *ErrMsg = "Can't determine temporary directory"; 209 return Path(); 210 } 211 212 Path result; 213 result.set(pathname); 214 215 // Append a subdirectory based on our process id so multiple LLVMs don't 216 // step on each other's toes. 217#ifdef __MINGW32__ 218 // Mingw's Win32 header files are broken. 219 sprintf(pathname, "LLVM_%u", unsigned(GetCurrentProcessId())); 220#else 221 sprintf(pathname, "LLVM_%u", GetCurrentProcessId()); 222#endif 223 result.appendComponent(pathname); 224 225 // If there's a directory left over from a previous LLVM execution that 226 // happened to have the same process id, get rid of it. 227 result.eraseFromDisk(true); 228 229 // And finally (re-)create the empty directory. 230 result.createDirectoryOnDisk(false); 231 TempDirectory = new Path(result); 232 return *TempDirectory; 233} 234 235Path 236Path::GetCurrentDirectory() { 237 char pathname[MAX_PATH]; 238 ::GetCurrentDirectoryA(MAX_PATH,pathname); 239 return Path(pathname); 240} 241 242/// GetMainExecutable - Return the path to the main executable, given the 243/// value of argv[0] from program startup. 244Path Path::GetMainExecutable(const char *argv0, void *MainAddr) { 245 char pathname[MAX_PATH]; 246 DWORD ret = ::GetModuleFileNameA(NULL, pathname, MAX_PATH); 247 return ret != MAX_PATH ? Path(pathname) : Path(); 248} 249 250 251// FIXME: the above set of functions don't map to Windows very well. 252 253StringRef 254Path::getSuffix() const { 255 // Find the last slash 256 size_t slash = path.rfind('/'); 257 if (slash == std::string::npos) 258 slash = 0; 259 else 260 slash++; 261 262 size_t dot = path.rfind('.'); 263 if (dot == std::string::npos || dot < slash) 264 return StringRef(""); 265 else 266 return StringRef(path).substr(dot + 1); 267} 268 269bool 270Path::exists() const { 271 DWORD attr = GetFileAttributes(path.c_str()); 272 return attr != INVALID_FILE_ATTRIBUTES; 273} 274 275bool 276Path::isDirectory() const { 277 DWORD attr = GetFileAttributes(path.c_str()); 278 return (attr != INVALID_FILE_ATTRIBUTES) && 279 (attr & FILE_ATTRIBUTE_DIRECTORY); 280} 281 282bool 283Path::isSymLink() const { 284 DWORD attributes = GetFileAttributes(path.c_str()); 285 286 if (attributes == INVALID_FILE_ATTRIBUTES) 287 // There's no sane way to report this :(. 288 assert(0 && "GetFileAttributes returned INVALID_FILE_ATTRIBUTES"); 289 290 // This isn't exactly what defines a NTFS symlink, but it is only true for 291 // paths that act like a symlink. 292 return attributes & FILE_ATTRIBUTE_REPARSE_POINT; 293} 294 295bool 296Path::canRead() const { 297 // FIXME: take security attributes into account. 298 DWORD attr = GetFileAttributes(path.c_str()); 299 return attr != INVALID_FILE_ATTRIBUTES; 300} 301 302bool 303Path::canWrite() const { 304 // FIXME: take security attributes into account. 305 DWORD attr = GetFileAttributes(path.c_str()); 306 return (attr != INVALID_FILE_ATTRIBUTES) && !(attr & FILE_ATTRIBUTE_READONLY); 307} 308 309bool 310Path::canExecute() const { 311 // FIXME: take security attributes into account. 312 DWORD attr = GetFileAttributes(path.c_str()); 313 return attr != INVALID_FILE_ATTRIBUTES; 314} 315 316bool 317Path::isRegularFile() const { 318 bool res; 319 if (fs::is_regular_file(path, res)) 320 return false; 321 return res; 322} 323 324const FileStatus * 325PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const { 326 if (!fsIsValid || update) { 327 WIN32_FILE_ATTRIBUTE_DATA fi; 328 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) { 329 MakeErrMsg(ErrStr, "getStatusInfo():" + std::string(path) + 330 ": Can't get status: "); 331 return 0; 332 } 333 334 status.fileSize = fi.nFileSizeHigh; 335 status.fileSize <<= sizeof(fi.nFileSizeHigh)*8; 336 status.fileSize += fi.nFileSizeLow; 337 338 status.mode = fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY ? 0555 : 0777; 339 status.user = 9999; // Not applicable to Windows, so... 340 status.group = 9999; // Not applicable to Windows, so... 341 342 // FIXME: this is only unique if the file is accessed by the same file path. 343 // How do we do this for C:\dir\file and ..\dir\file ? Unix has inode 344 // numbers, but the concept doesn't exist in Windows. 345 status.uniqueID = 0; 346 for (unsigned i = 0; i < path.length(); ++i) 347 status.uniqueID += path[i]; 348 349 ULARGE_INTEGER ui; 350 ui.LowPart = fi.ftLastWriteTime.dwLowDateTime; 351 ui.HighPart = fi.ftLastWriteTime.dwHighDateTime; 352 status.modTime.fromWin32Time(ui.QuadPart); 353 354 status.isDir = fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY; 355 fsIsValid = true; 356 } 357 return &status; 358} 359 360bool Path::makeReadableOnDisk(std::string* ErrMsg) { 361 // All files are readable on Windows (ignoring security attributes). 362 return false; 363} 364 365bool Path::makeWriteableOnDisk(std::string* ErrMsg) { 366 DWORD attr = GetFileAttributes(path.c_str()); 367 368 // If it doesn't exist, we're done. 369 if (attr == INVALID_FILE_ATTRIBUTES) 370 return false; 371 372 if (attr & FILE_ATTRIBUTE_READONLY) { 373 if (!SetFileAttributes(path.c_str(), attr & ~FILE_ATTRIBUTE_READONLY)) { 374 MakeErrMsg(ErrMsg, std::string(path) + ": Can't make file writable: "); 375 return true; 376 } 377 } 378 return false; 379} 380 381bool 382Path::getDirectoryContents(std::set& result, std::string* ErrMsg) const { 383 WIN32_FILE_ATTRIBUTE_DATA fi; 384 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) { 385 MakeErrMsg(ErrMsg, path + ": can't get status of file"); 386 return true; 387 } 388 389 if (!(fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { 390 if (ErrMsg) 391 *ErrMsg = path + ": not a directory"; 392 return true; 393 } 394 395 result.clear(); 396 WIN32_FIND_DATA fd; 397 std::string searchpath = path; 398 if (path.size() == 0 || searchpath[path.size()-1] == '/') 399 searchpath += "*"; 400 else 401 searchpath += "/*"; 402 403 HANDLE h = FindFirstFile(searchpath.c_str(), &fd); 404 if (h == INVALID_HANDLE_VALUE) { 405 if (GetLastError() == ERROR_FILE_NOT_FOUND) 406 return true; // not really an error, now is it? 407 MakeErrMsg(ErrMsg, path + ": Can't read directory: "); 408 return true; 409 } 410 411 do { 412 if (fd.cFileName[0] == '.') 413 continue; 414 Path aPath(path); 415 aPath.appendComponent(&fd.cFileName[0]); 416 result.insert(aPath); 417 } while (FindNextFile(h, &fd)); 418 419 DWORD err = GetLastError(); 420 FindClose(h); 421 if (err != ERROR_NO_MORE_FILES) { 422 SetLastError(err); 423 MakeErrMsg(ErrMsg, path + ": Can't read directory: "); 424 return true; 425 } 426 return false; 427} 428 429bool 430Path::set(StringRef a_path) { 431 if (a_path.empty()) 432 return false; 433 std::string save(path); 434 path = a_path; 435 FlipBackSlashes(path); 436 if (!isValid()) { 437 path = save; 438 return false; 439 } 440 return true; 441} 442 443bool 444Path::appendComponent(StringRef name) { 445 if (name.empty()) 446 return false; 447 std::string save(path); 448 if (!path.empty()) { 449 size_t last = path.size() - 1; 450 if (path[last] != '/') 451 path += '/'; 452 } 453 path += name; 454 if (!isValid()) { 455 path = save; 456 return false; 457 } 458 return true; 459} 460 461bool 462Path::eraseComponent() { 463 size_t slashpos = path.rfind('/',path.size()); 464 if (slashpos == path.size() - 1 || slashpos == std::string::npos) 465 return false; 466 std::string save(path); 467 path.erase(slashpos); 468 if (!isValid()) { 469 path = save; 470 return false; 471 } 472 return true; 473} 474 475bool 476Path::eraseSuffix() { 477 size_t dotpos = path.rfind('.',path.size()); 478 size_t slashpos = path.rfind('/',path.size()); 479 if (dotpos != std::string::npos) { 480 if (slashpos == std::string::npos || dotpos > slashpos+1) { 481 std::string save(path); 482 path.erase(dotpos, path.size()-dotpos); 483 if (!isValid()) { 484 path = save; 485 return false; 486 } 487 return true; 488 } 489 } 490 return false; 491} 492 493inline bool PathMsg(std::string* ErrMsg, const char* pathname, const char*msg) { 494 if (ErrMsg) 495 *ErrMsg = std::string(pathname) + ": " + std::string(msg); 496 return true; 497} 498 499bool 500Path::createDirectoryOnDisk(bool create_parents, std::string* ErrMsg) { 501 // Get a writeable copy of the path name 502 size_t len = path.length(); 503 char *pathname = reinterpret_cast<char *>(_alloca(len+2)); 504 path.copy(pathname, len); 505 pathname[len] = 0; 506 507 // Make sure it ends with a slash. 508 if (len == 0 || pathname[len - 1] != '/') { 509 pathname[len] = '/'; 510 pathname[++len] = 0; 511 } 512 513 // Determine starting point for initial / search. 514 char *next = pathname; 515 if (pathname[0] == '/' && pathname[1] == '/') { 516 // Skip host name. 517 next = strchr(pathname+2, '/'); 518 if (next == NULL) 519 return PathMsg(ErrMsg, pathname, "badly formed remote directory"); 520 521 // Skip share name. 522 next = strchr(next+1, '/'); 523 if (next == NULL) 524 return PathMsg(ErrMsg, pathname,"badly formed remote directory"); 525 526 next++; 527 if (*next == 0) 528 return PathMsg(ErrMsg, pathname, "badly formed remote directory"); 529 530 } else { 531 if (pathname[1] == ':') 532 next += 2; // skip drive letter 533 if (*next == '/') 534 next++; // skip root directory 535 } 536 537 // If we're supposed to create intermediate directories 538 if (create_parents) { 539 // Loop through the directory components until we're done 540 while (*next) { 541 next = strchr(next, '/'); 542 *next = 0; 543 if (!CreateDirectory(pathname, NULL) && 544 GetLastError() != ERROR_ALREADY_EXISTS) 545 return MakeErrMsg(ErrMsg, 546 std::string(pathname) + ": Can't create directory: "); 547 *next++ = '/'; 548 } 549 } else { 550 // Drop trailing slash. 551 pathname[len-1] = 0; 552 if (!CreateDirectory(pathname, NULL) && 553 GetLastError() != ERROR_ALREADY_EXISTS) { 554 return MakeErrMsg(ErrMsg, std::string(pathname) + 555 ": Can't create directory: "); 556 } 557 } 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 bool Exists; 570 if (fs::exists(path, Exists) || !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 = reinterpret_cast<char*>(alloca(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 Magic = std::string(buf, len); 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 false; 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 ULARGE_INTEGER ui; 701 ui.QuadPart = si.modTime.toWin32Time(); 702 FILETIME ft; 703 ft.dwLowDateTime = ui.LowPart; 704 ft.dwHighDateTime = ui.HighPart; 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 733Path::makeUnique(bool reuse_current, std::string* ErrMsg) { 734 bool Exists; 735 if (reuse_current && (fs::exists(path, Exists) || !Exists)) 736 return false; // File doesn't exist already, just use it! 737 738 // Reserve space for -XXXXXX at the end. 739 char *FNBuffer = (char*) alloca(path.size()+8); 740 unsigned offset = path.size(); 741 path.copy(FNBuffer, offset); 742 743 // Find a numeric suffix that isn't used by an existing file. Assume there 744 // won't be more than 1 million files with the same prefix. Probably a safe 745 // bet. 746 static int FCounter = -1; 747 if (FCounter < 0) { 748 // Give arbitrary initial seed. 749 // FIXME: We should use sys::fs::unique_file() in future. 750 LARGE_INTEGER cnt64; 751 DWORD x = GetCurrentProcessId(); 752 x = (x << 16) | (x >> 16); 753 if (QueryPerformanceCounter(&cnt64)) // RDTSC 754 x ^= cnt64.HighPart ^ cnt64.LowPart; 755 FCounter = x % 1000000; 756 } 757 do { 758 sprintf(FNBuffer+offset, "-%06u", FCounter); 759 if (++FCounter > 999999) 760 FCounter = 0; 761 path = FNBuffer; 762 } while (!fs::exists(path, Exists) && Exists); 763 return false; 764} 765 766bool 767Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) { 768 // Make this into a unique file name 769 makeUnique(reuse_current, ErrMsg); 770 771 // Now go and create it 772 HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW, 773 FILE_ATTRIBUTE_NORMAL, NULL); 774 if (h == INVALID_HANDLE_VALUE) 775 return MakeErrMsg(ErrMsg, path + ": can't create file"); 776 777 CloseHandle(h); 778 return false; 779} 780} 781} 782