Path.cpp revision dce4a407a24b04eebc6a376f8e62b41aaa7b071f
1//===-- Path.cpp - Implement OS Path Concept ------------------------------===// 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 implements the operating system Path API. 11// 12//===----------------------------------------------------------------------===// 13 14#include "llvm/Support/Path.h" 15#include "llvm/Support/Endian.h" 16#include "llvm/Support/ErrorHandling.h" 17#include "llvm/Support/FileSystem.h" 18#include "llvm/Support/Process.h" 19#include <cctype> 20#include <cstdio> 21#include <cstring> 22#include <fcntl.h> 23 24#if !defined(_MSC_VER) && !defined(__MINGW32__) 25#include <unistd.h> 26#else 27#include <io.h> 28#endif 29 30using namespace llvm; 31 32namespace { 33 using llvm::StringRef; 34 using llvm::sys::path::is_separator; 35 36#ifdef LLVM_ON_WIN32 37 const char *separators = "\\/"; 38 const char preferred_separator = '\\'; 39#else 40 const char separators = '/'; 41 const char preferred_separator = '/'; 42#endif 43 44 StringRef find_first_component(StringRef path) { 45 // Look for this first component in the following order. 46 // * empty (in this case we return an empty string) 47 // * either C: or {//,\\}net. 48 // * {/,\} 49 // * {.,..} 50 // * {file,directory}name 51 52 if (path.empty()) 53 return path; 54 55#ifdef LLVM_ON_WIN32 56 // C: 57 if (path.size() >= 2 && std::isalpha(static_cast<unsigned char>(path[0])) && 58 path[1] == ':') 59 return path.substr(0, 2); 60#endif 61 62 // //net 63 if ((path.size() > 2) && 64 is_separator(path[0]) && 65 path[0] == path[1] && 66 !is_separator(path[2])) { 67 // Find the next directory separator. 68 size_t end = path.find_first_of(separators, 2); 69 return path.substr(0, end); 70 } 71 72 // {/,\} 73 if (is_separator(path[0])) 74 return path.substr(0, 1); 75 76 if (path.startswith("..")) 77 return path.substr(0, 2); 78 79 if (path[0] == '.') 80 return path.substr(0, 1); 81 82 // * {file,directory}name 83 size_t end = path.find_first_of(separators); 84 return path.substr(0, end); 85 } 86 87 size_t filename_pos(StringRef str) { 88 if (str.size() == 2 && 89 is_separator(str[0]) && 90 str[0] == str[1]) 91 return 0; 92 93 if (str.size() > 0 && is_separator(str[str.size() - 1])) 94 return str.size() - 1; 95 96 size_t pos = str.find_last_of(separators, str.size() - 1); 97 98#ifdef LLVM_ON_WIN32 99 if (pos == StringRef::npos) 100 pos = str.find_last_of(':', str.size() - 2); 101#endif 102 103 if (pos == StringRef::npos || 104 (pos == 1 && is_separator(str[0]))) 105 return 0; 106 107 return pos + 1; 108 } 109 110 size_t root_dir_start(StringRef str) { 111 // case "c:/" 112#ifdef LLVM_ON_WIN32 113 if (str.size() > 2 && 114 str[1] == ':' && 115 is_separator(str[2])) 116 return 2; 117#endif 118 119 // case "//" 120 if (str.size() == 2 && 121 is_separator(str[0]) && 122 str[0] == str[1]) 123 return StringRef::npos; 124 125 // case "//net" 126 if (str.size() > 3 && 127 is_separator(str[0]) && 128 str[0] == str[1] && 129 !is_separator(str[2])) { 130 return str.find_first_of(separators, 2); 131 } 132 133 // case "/" 134 if (str.size() > 0 && is_separator(str[0])) 135 return 0; 136 137 return StringRef::npos; 138 } 139 140 size_t parent_path_end(StringRef path) { 141 size_t end_pos = filename_pos(path); 142 143 bool filename_was_sep = path.size() > 0 && is_separator(path[end_pos]); 144 145 // Skip separators except for root dir. 146 size_t root_dir_pos = root_dir_start(path.substr(0, end_pos)); 147 148 while(end_pos > 0 && 149 (end_pos - 1) != root_dir_pos && 150 is_separator(path[end_pos - 1])) 151 --end_pos; 152 153 if (end_pos == 1 && root_dir_pos == 0 && filename_was_sep) 154 return StringRef::npos; 155 156 return end_pos; 157 } 158} // end unnamed namespace 159 160enum FSEntity { 161 FS_Dir, 162 FS_File, 163 FS_Name 164}; 165 166// Implemented in Unix/Path.inc and Windows/Path.inc. 167static error_code TempDir(SmallVectorImpl<char> &result); 168 169static error_code createUniqueEntity(const Twine &Model, int &ResultFD, 170 SmallVectorImpl<char> &ResultPath, 171 bool MakeAbsolute, unsigned Mode, 172 FSEntity Type) { 173 SmallString<128> ModelStorage; 174 Model.toVector(ModelStorage); 175 176 if (MakeAbsolute) { 177 // Make model absolute by prepending a temp directory if it's not already. 178 if (!sys::path::is_absolute(Twine(ModelStorage))) { 179 SmallString<128> TDir; 180 if (error_code EC = TempDir(TDir)) 181 return EC; 182 sys::path::append(TDir, Twine(ModelStorage)); 183 ModelStorage.swap(TDir); 184 } 185 } 186 187 // From here on, DO NOT modify model. It may be needed if the randomly chosen 188 // path already exists. 189 ResultPath = ModelStorage; 190 // Null terminate. 191 ResultPath.push_back(0); 192 ResultPath.pop_back(); 193 194retry_random_path: 195 // Replace '%' with random chars. 196 for (unsigned i = 0, e = ModelStorage.size(); i != e; ++i) { 197 if (ModelStorage[i] == '%') 198 ResultPath[i] = "0123456789abcdef"[sys::Process::GetRandomNumber() & 15]; 199 } 200 201 // Try to open + create the file. 202 switch (Type) { 203 case FS_File: { 204 if (error_code EC = 205 sys::fs::openFileForWrite(Twine(ResultPath.begin()), ResultFD, 206 sys::fs::F_RW | sys::fs::F_Excl, Mode)) { 207 if (EC == errc::file_exists) 208 goto retry_random_path; 209 return EC; 210 } 211 212 return error_code::success(); 213 } 214 215 case FS_Name: { 216 bool Exists; 217 error_code EC = sys::fs::exists(ResultPath.begin(), Exists); 218 if (EC) 219 return EC; 220 if (Exists) 221 goto retry_random_path; 222 return error_code::success(); 223 } 224 225 case FS_Dir: { 226 if (error_code EC = sys::fs::create_directory(ResultPath.begin(), false)) { 227 if (EC == errc::file_exists) 228 goto retry_random_path; 229 return EC; 230 } 231 return error_code::success(); 232 } 233 } 234 llvm_unreachable("Invalid Type"); 235} 236 237namespace llvm { 238namespace sys { 239namespace path { 240 241const_iterator begin(StringRef path) { 242 const_iterator i; 243 i.Path = path; 244 i.Component = find_first_component(path); 245 i.Position = 0; 246 return i; 247} 248 249const_iterator end(StringRef path) { 250 const_iterator i; 251 i.Path = path; 252 i.Position = path.size(); 253 return i; 254} 255 256const_iterator &const_iterator::operator++() { 257 assert(Position < Path.size() && "Tried to increment past end!"); 258 259 // Increment Position to past the current component 260 Position += Component.size(); 261 262 // Check for end. 263 if (Position == Path.size()) { 264 Component = StringRef(); 265 return *this; 266 } 267 268 // Both POSIX and Windows treat paths that begin with exactly two separators 269 // specially. 270 bool was_net = Component.size() > 2 && 271 is_separator(Component[0]) && 272 Component[1] == Component[0] && 273 !is_separator(Component[2]); 274 275 // Handle separators. 276 if (is_separator(Path[Position])) { 277 // Root dir. 278 if (was_net 279#ifdef LLVM_ON_WIN32 280 // c:/ 281 || Component.endswith(":") 282#endif 283 ) { 284 Component = Path.substr(Position, 1); 285 return *this; 286 } 287 288 // Skip extra separators. 289 while (Position != Path.size() && 290 is_separator(Path[Position])) { 291 ++Position; 292 } 293 294 // Treat trailing '/' as a '.'. 295 if (Position == Path.size()) { 296 --Position; 297 Component = "."; 298 return *this; 299 } 300 } 301 302 // Find next component. 303 size_t end_pos = Path.find_first_of(separators, Position); 304 Component = Path.slice(Position, end_pos); 305 306 return *this; 307} 308 309const_iterator &const_iterator::operator--() { 310 // If we're at the end and the previous char was a '/', return '.' unless 311 // we are the root path. 312 size_t root_dir_pos = root_dir_start(Path); 313 if (Position == Path.size() && 314 Path.size() > root_dir_pos + 1 && 315 is_separator(Path[Position - 1])) { 316 --Position; 317 Component = "."; 318 return *this; 319 } 320 321 // Skip separators unless it's the root directory. 322 size_t end_pos = Position; 323 324 while(end_pos > 0 && 325 (end_pos - 1) != root_dir_pos && 326 is_separator(Path[end_pos - 1])) 327 --end_pos; 328 329 // Find next separator. 330 size_t start_pos = filename_pos(Path.substr(0, end_pos)); 331 Component = Path.slice(start_pos, end_pos); 332 Position = start_pos; 333 return *this; 334} 335 336bool const_iterator::operator==(const const_iterator &RHS) const { 337 return Path.begin() == RHS.Path.begin() && 338 Position == RHS.Position; 339} 340 341bool const_iterator::operator!=(const const_iterator &RHS) const { 342 return !(*this == RHS); 343} 344 345ptrdiff_t const_iterator::operator-(const const_iterator &RHS) const { 346 return Position - RHS.Position; 347} 348 349const StringRef root_path(StringRef path) { 350 const_iterator b = begin(path), 351 pos = b, 352 e = end(path); 353 if (b != e) { 354 bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0]; 355 bool has_drive = 356#ifdef LLVM_ON_WIN32 357 b->endswith(":"); 358#else 359 false; 360#endif 361 362 if (has_net || has_drive) { 363 if ((++pos != e) && is_separator((*pos)[0])) { 364 // {C:/,//net/}, so get the first two components. 365 return path.substr(0, b->size() + pos->size()); 366 } else { 367 // just {C:,//net}, return the first component. 368 return *b; 369 } 370 } 371 372 // POSIX style root directory. 373 if (is_separator((*b)[0])) { 374 return *b; 375 } 376 } 377 378 return StringRef(); 379} 380 381const StringRef root_name(StringRef path) { 382 const_iterator b = begin(path), 383 e = end(path); 384 if (b != e) { 385 bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0]; 386 bool has_drive = 387#ifdef LLVM_ON_WIN32 388 b->endswith(":"); 389#else 390 false; 391#endif 392 393 if (has_net || has_drive) { 394 // just {C:,//net}, return the first component. 395 return *b; 396 } 397 } 398 399 // No path or no name. 400 return StringRef(); 401} 402 403const StringRef root_directory(StringRef path) { 404 const_iterator b = begin(path), 405 pos = b, 406 e = end(path); 407 if (b != e) { 408 bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0]; 409 bool has_drive = 410#ifdef LLVM_ON_WIN32 411 b->endswith(":"); 412#else 413 false; 414#endif 415 416 if ((has_net || has_drive) && 417 // {C:,//net}, skip to the next component. 418 (++pos != e) && is_separator((*pos)[0])) { 419 return *pos; 420 } 421 422 // POSIX style root directory. 423 if (!has_net && is_separator((*b)[0])) { 424 return *b; 425 } 426 } 427 428 // No path or no root. 429 return StringRef(); 430} 431 432const StringRef relative_path(StringRef path) { 433 StringRef root = root_path(path); 434 return path.substr(root.size()); 435} 436 437void append(SmallVectorImpl<char> &path, const Twine &a, 438 const Twine &b, 439 const Twine &c, 440 const Twine &d) { 441 SmallString<32> a_storage; 442 SmallString<32> b_storage; 443 SmallString<32> c_storage; 444 SmallString<32> d_storage; 445 446 SmallVector<StringRef, 4> components; 447 if (!a.isTriviallyEmpty()) components.push_back(a.toStringRef(a_storage)); 448 if (!b.isTriviallyEmpty()) components.push_back(b.toStringRef(b_storage)); 449 if (!c.isTriviallyEmpty()) components.push_back(c.toStringRef(c_storage)); 450 if (!d.isTriviallyEmpty()) components.push_back(d.toStringRef(d_storage)); 451 452 for (SmallVectorImpl<StringRef>::const_iterator i = components.begin(), 453 e = components.end(); 454 i != e; ++i) { 455 bool path_has_sep = !path.empty() && is_separator(path[path.size() - 1]); 456 bool component_has_sep = !i->empty() && is_separator((*i)[0]); 457 bool is_root_name = has_root_name(*i); 458 459 if (path_has_sep) { 460 // Strip separators from beginning of component. 461 size_t loc = i->find_first_not_of(separators); 462 StringRef c = i->substr(loc); 463 464 // Append it. 465 path.append(c.begin(), c.end()); 466 continue; 467 } 468 469 if (!component_has_sep && !(path.empty() || is_root_name)) { 470 // Add a separator. 471 path.push_back(preferred_separator); 472 } 473 474 path.append(i->begin(), i->end()); 475 } 476} 477 478void append(SmallVectorImpl<char> &path, 479 const_iterator begin, const_iterator end) { 480 for (; begin != end; ++begin) 481 path::append(path, *begin); 482} 483 484const StringRef parent_path(StringRef path) { 485 size_t end_pos = parent_path_end(path); 486 if (end_pos == StringRef::npos) 487 return StringRef(); 488 else 489 return path.substr(0, end_pos); 490} 491 492void remove_filename(SmallVectorImpl<char> &path) { 493 size_t end_pos = parent_path_end(StringRef(path.begin(), path.size())); 494 if (end_pos != StringRef::npos) 495 path.set_size(end_pos); 496} 497 498void replace_extension(SmallVectorImpl<char> &path, const Twine &extension) { 499 StringRef p(path.begin(), path.size()); 500 SmallString<32> ext_storage; 501 StringRef ext = extension.toStringRef(ext_storage); 502 503 // Erase existing extension. 504 size_t pos = p.find_last_of('.'); 505 if (pos != StringRef::npos && pos >= filename_pos(p)) 506 path.set_size(pos); 507 508 // Append '.' if needed. 509 if (ext.size() > 0 && ext[0] != '.') 510 path.push_back('.'); 511 512 // Append extension. 513 path.append(ext.begin(), ext.end()); 514} 515 516void native(const Twine &path, SmallVectorImpl<char> &result) { 517 assert((!path.isSingleStringRef() || 518 path.getSingleStringRef().data() != result.data()) && 519 "path and result are not allowed to overlap!"); 520 // Clear result. 521 result.clear(); 522 path.toVector(result); 523 native(result); 524} 525 526void native(SmallVectorImpl<char> &path) { 527#ifdef LLVM_ON_WIN32 528 std::replace(path.begin(), path.end(), '/', '\\'); 529#endif 530} 531 532const StringRef filename(StringRef path) { 533 return *(--end(path)); 534} 535 536const StringRef stem(StringRef path) { 537 StringRef fname = filename(path); 538 size_t pos = fname.find_last_of('.'); 539 if (pos == StringRef::npos) 540 return fname; 541 else 542 if ((fname.size() == 1 && fname == ".") || 543 (fname.size() == 2 && fname == "..")) 544 return fname; 545 else 546 return fname.substr(0, pos); 547} 548 549const StringRef extension(StringRef path) { 550 StringRef fname = filename(path); 551 size_t pos = fname.find_last_of('.'); 552 if (pos == StringRef::npos) 553 return StringRef(); 554 else 555 if ((fname.size() == 1 && fname == ".") || 556 (fname.size() == 2 && fname == "..")) 557 return StringRef(); 558 else 559 return fname.substr(pos); 560} 561 562bool is_separator(char value) { 563 switch(value) { 564#ifdef LLVM_ON_WIN32 565 case '\\': // fall through 566#endif 567 case '/': return true; 568 default: return false; 569 } 570} 571 572static const char preferred_separator_string[] = { preferred_separator, '\0' }; 573 574const StringRef get_separator() { 575 return preferred_separator_string; 576} 577 578void system_temp_directory(bool erasedOnReboot, SmallVectorImpl<char> &result) { 579 result.clear(); 580 581#if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR) 582 // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR. 583 // macros defined in <unistd.h> on darwin >= 9 584 int ConfName = erasedOnReboot? _CS_DARWIN_USER_TEMP_DIR 585 : _CS_DARWIN_USER_CACHE_DIR; 586 size_t ConfLen = confstr(ConfName, nullptr, 0); 587 if (ConfLen > 0) { 588 do { 589 result.resize(ConfLen); 590 ConfLen = confstr(ConfName, result.data(), result.size()); 591 } while (ConfLen > 0 && ConfLen != result.size()); 592 593 if (ConfLen > 0) { 594 assert(result.back() == 0); 595 result.pop_back(); 596 return; 597 } 598 599 result.clear(); 600 } 601#endif 602 603 // Check whether the temporary directory is specified by an environment 604 // variable. 605 const char *EnvironmentVariable; 606#ifdef LLVM_ON_WIN32 607 EnvironmentVariable = "TEMP"; 608#else 609 EnvironmentVariable = "TMPDIR"; 610#endif 611 if (char *RequestedDir = getenv(EnvironmentVariable)) { 612 result.append(RequestedDir, RequestedDir + strlen(RequestedDir)); 613 return; 614 } 615 616 // Fall back to a system default. 617 const char *DefaultResult; 618#ifdef LLVM_ON_WIN32 619 (void)erasedOnReboot; 620 DefaultResult = "C:\\TEMP"; 621#else 622 if (erasedOnReboot) 623 DefaultResult = "/tmp"; 624 else 625 DefaultResult = "/var/tmp"; 626#endif 627 result.append(DefaultResult, DefaultResult + strlen(DefaultResult)); 628} 629 630bool has_root_name(const Twine &path) { 631 SmallString<128> path_storage; 632 StringRef p = path.toStringRef(path_storage); 633 634 return !root_name(p).empty(); 635} 636 637bool has_root_directory(const Twine &path) { 638 SmallString<128> path_storage; 639 StringRef p = path.toStringRef(path_storage); 640 641 return !root_directory(p).empty(); 642} 643 644bool has_root_path(const Twine &path) { 645 SmallString<128> path_storage; 646 StringRef p = path.toStringRef(path_storage); 647 648 return !root_path(p).empty(); 649} 650 651bool has_relative_path(const Twine &path) { 652 SmallString<128> path_storage; 653 StringRef p = path.toStringRef(path_storage); 654 655 return !relative_path(p).empty(); 656} 657 658bool has_filename(const Twine &path) { 659 SmallString<128> path_storage; 660 StringRef p = path.toStringRef(path_storage); 661 662 return !filename(p).empty(); 663} 664 665bool has_parent_path(const Twine &path) { 666 SmallString<128> path_storage; 667 StringRef p = path.toStringRef(path_storage); 668 669 return !parent_path(p).empty(); 670} 671 672bool has_stem(const Twine &path) { 673 SmallString<128> path_storage; 674 StringRef p = path.toStringRef(path_storage); 675 676 return !stem(p).empty(); 677} 678 679bool has_extension(const Twine &path) { 680 SmallString<128> path_storage; 681 StringRef p = path.toStringRef(path_storage); 682 683 return !extension(p).empty(); 684} 685 686bool is_absolute(const Twine &path) { 687 SmallString<128> path_storage; 688 StringRef p = path.toStringRef(path_storage); 689 690 bool rootDir = has_root_directory(p), 691#ifdef LLVM_ON_WIN32 692 rootName = has_root_name(p); 693#else 694 rootName = true; 695#endif 696 697 return rootDir && rootName; 698} 699 700bool is_relative(const Twine &path) { 701 return !is_absolute(path); 702} 703 704} // end namespace path 705 706namespace fs { 707 708error_code getUniqueID(const Twine Path, UniqueID &Result) { 709 file_status Status; 710 error_code EC = status(Path, Status); 711 if (EC) 712 return EC; 713 Result = Status.getUniqueID(); 714 return error_code::success(); 715} 716 717error_code createUniqueFile(const Twine &Model, int &ResultFd, 718 SmallVectorImpl<char> &ResultPath, unsigned Mode) { 719 return createUniqueEntity(Model, ResultFd, ResultPath, false, Mode, FS_File); 720} 721 722error_code createUniqueFile(const Twine &Model, 723 SmallVectorImpl<char> &ResultPath) { 724 int Dummy; 725 return createUniqueEntity(Model, Dummy, ResultPath, false, 0, FS_Name); 726} 727 728static error_code createTemporaryFile(const Twine &Model, int &ResultFD, 729 llvm::SmallVectorImpl<char> &ResultPath, 730 FSEntity Type) { 731 SmallString<128> Storage; 732 StringRef P = Model.toNullTerminatedStringRef(Storage); 733 assert(P.find_first_of(separators) == StringRef::npos && 734 "Model must be a simple filename."); 735 // Use P.begin() so that createUniqueEntity doesn't need to recreate Storage. 736 return createUniqueEntity(P.begin(), ResultFD, ResultPath, 737 true, owner_read | owner_write, Type); 738} 739 740static error_code 741createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD, 742 llvm::SmallVectorImpl<char> &ResultPath, 743 FSEntity Type) { 744 const char *Middle = Suffix.empty() ? "-%%%%%%" : "-%%%%%%."; 745 return createTemporaryFile(Prefix + Middle + Suffix, ResultFD, ResultPath, 746 Type); 747} 748 749 750error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix, 751 int &ResultFD, 752 SmallVectorImpl<char> &ResultPath) { 753 return createTemporaryFile(Prefix, Suffix, ResultFD, ResultPath, FS_File); 754} 755 756error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix, 757 SmallVectorImpl<char> &ResultPath) { 758 int Dummy; 759 return createTemporaryFile(Prefix, Suffix, Dummy, ResultPath, FS_Name); 760} 761 762 763// This is a mkdtemp with a different pattern. We use createUniqueEntity mostly 764// for consistency. We should try using mkdtemp. 765error_code createUniqueDirectory(const Twine &Prefix, 766 SmallVectorImpl<char> &ResultPath) { 767 int Dummy; 768 return createUniqueEntity(Prefix + "-%%%%%%", Dummy, ResultPath, 769 true, 0, FS_Dir); 770} 771 772error_code make_absolute(SmallVectorImpl<char> &path) { 773 StringRef p(path.data(), path.size()); 774 775 bool rootDirectory = path::has_root_directory(p), 776#ifdef LLVM_ON_WIN32 777 rootName = path::has_root_name(p); 778#else 779 rootName = true; 780#endif 781 782 // Already absolute. 783 if (rootName && rootDirectory) 784 return error_code::success(); 785 786 // All of the following conditions will need the current directory. 787 SmallString<128> current_dir; 788 if (error_code ec = current_path(current_dir)) return ec; 789 790 // Relative path. Prepend the current directory. 791 if (!rootName && !rootDirectory) { 792 // Append path to the current directory. 793 path::append(current_dir, p); 794 // Set path to the result. 795 path.swap(current_dir); 796 return error_code::success(); 797 } 798 799 if (!rootName && rootDirectory) { 800 StringRef cdrn = path::root_name(current_dir); 801 SmallString<128> curDirRootName(cdrn.begin(), cdrn.end()); 802 path::append(curDirRootName, p); 803 // Set path to the result. 804 path.swap(curDirRootName); 805 return error_code::success(); 806 } 807 808 if (rootName && !rootDirectory) { 809 StringRef pRootName = path::root_name(p); 810 StringRef bRootDirectory = path::root_directory(current_dir); 811 StringRef bRelativePath = path::relative_path(current_dir); 812 StringRef pRelativePath = path::relative_path(p); 813 814 SmallString<128> res; 815 path::append(res, pRootName, bRootDirectory, bRelativePath, pRelativePath); 816 path.swap(res); 817 return error_code::success(); 818 } 819 820 llvm_unreachable("All rootName and rootDirectory combinations should have " 821 "occurred above!"); 822} 823 824error_code create_directories(const Twine &Path, bool IgnoreExisting) { 825 SmallString<128> PathStorage; 826 StringRef P = Path.toStringRef(PathStorage); 827 828 // Be optimistic and try to create the directory 829 error_code EC = create_directory(P, IgnoreExisting); 830 // If we succeeded, or had any error other than the parent not existing, just 831 // return it. 832 if (EC != errc::no_such_file_or_directory) 833 return EC; 834 835 // We failed because of a no_such_file_or_directory, try to create the 836 // parent. 837 StringRef Parent = path::parent_path(P); 838 if (Parent.empty()) 839 return EC; 840 841 if ((EC = create_directories(Parent))) 842 return EC; 843 844 return create_directory(P, IgnoreExisting); 845} 846 847bool exists(file_status status) { 848 return status_known(status) && status.type() != file_type::file_not_found; 849} 850 851bool status_known(file_status s) { 852 return s.type() != file_type::status_error; 853} 854 855bool is_directory(file_status status) { 856 return status.type() == file_type::directory_file; 857} 858 859error_code is_directory(const Twine &path, bool &result) { 860 file_status st; 861 if (error_code ec = status(path, st)) 862 return ec; 863 result = is_directory(st); 864 return error_code::success(); 865} 866 867bool is_regular_file(file_status status) { 868 return status.type() == file_type::regular_file; 869} 870 871error_code is_regular_file(const Twine &path, bool &result) { 872 file_status st; 873 if (error_code ec = status(path, st)) 874 return ec; 875 result = is_regular_file(st); 876 return error_code::success(); 877} 878 879bool is_other(file_status status) { 880 return exists(status) && 881 !is_regular_file(status) && 882 !is_directory(status); 883} 884 885void directory_entry::replace_filename(const Twine &filename, file_status st) { 886 SmallString<128> path(Path.begin(), Path.end()); 887 path::remove_filename(path); 888 path::append(path, filename); 889 Path = path.str(); 890 Status = st; 891} 892 893error_code has_magic(const Twine &path, const Twine &magic, bool &result) { 894 SmallString<32> MagicStorage; 895 StringRef Magic = magic.toStringRef(MagicStorage); 896 SmallString<32> Buffer; 897 898 if (error_code ec = get_magic(path, Magic.size(), Buffer)) { 899 if (ec == errc::value_too_large) { 900 // Magic.size() > file_size(Path). 901 result = false; 902 return error_code::success(); 903 } 904 return ec; 905 } 906 907 result = Magic == Buffer; 908 return error_code::success(); 909} 910 911/// @brief Identify the magic in magic. 912 file_magic identify_magic(StringRef Magic) { 913 if (Magic.size() < 4) 914 return file_magic::unknown; 915 switch ((unsigned char)Magic[0]) { 916 case 0x00: { 917 // COFF short import library file 918 if (Magic[1] == (char)0x00 && Magic[2] == (char)0xff && 919 Magic[3] == (char)0xff) 920 return file_magic::coff_import_library; 921 // Windows resource file 922 const char Expected[] = { 0, 0, 0, 0, '\x20', 0, 0, 0, '\xff' }; 923 if (Magic.size() >= sizeof(Expected) && 924 memcmp(Magic.data(), Expected, sizeof(Expected)) == 0) 925 return file_magic::windows_resource; 926 // 0x0000 = COFF unknown machine type 927 if (Magic[1] == 0) 928 return file_magic::coff_object; 929 break; 930 } 931 case 0xDE: // 0x0B17C0DE = BC wraper 932 if (Magic[1] == (char)0xC0 && Magic[2] == (char)0x17 && 933 Magic[3] == (char)0x0B) 934 return file_magic::bitcode; 935 break; 936 case 'B': 937 if (Magic[1] == 'C' && Magic[2] == (char)0xC0 && Magic[3] == (char)0xDE) 938 return file_magic::bitcode; 939 break; 940 case '!': 941 if (Magic.size() >= 8) 942 if (memcmp(Magic.data(),"!<arch>\n",8) == 0) 943 return file_magic::archive; 944 break; 945 946 case '\177': 947 if (Magic.size() >= 18 && Magic[1] == 'E' && Magic[2] == 'L' && 948 Magic[3] == 'F') { 949 bool Data2MSB = Magic[5] == 2; 950 unsigned high = Data2MSB ? 16 : 17; 951 unsigned low = Data2MSB ? 17 : 16; 952 if (Magic[high] == 0) 953 switch (Magic[low]) { 954 default: break; 955 case 1: return file_magic::elf_relocatable; 956 case 2: return file_magic::elf_executable; 957 case 3: return file_magic::elf_shared_object; 958 case 4: return file_magic::elf_core; 959 } 960 } 961 break; 962 963 case 0xCA: 964 if (Magic[1] == char(0xFE) && Magic[2] == char(0xBA) && 965 Magic[3] == char(0xBE)) { 966 // This is complicated by an overlap with Java class files. 967 // See the Mach-O section in /usr/share/file/magic for details. 968 if (Magic.size() >= 8 && Magic[7] < 43) 969 return file_magic::macho_universal_binary; 970 } 971 break; 972 973 // The two magic numbers for mach-o are: 974 // 0xfeedface - 32-bit mach-o 975 // 0xfeedfacf - 64-bit mach-o 976 case 0xFE: 977 case 0xCE: 978 case 0xCF: { 979 uint16_t type = 0; 980 if (Magic[0] == char(0xFE) && Magic[1] == char(0xED) && 981 Magic[2] == char(0xFA) && 982 (Magic[3] == char(0xCE) || Magic[3] == char(0xCF))) { 983 /* Native endian */ 984 if (Magic.size() >= 16) type = Magic[14] << 8 | Magic[15]; 985 } else if ((Magic[0] == char(0xCE) || Magic[0] == char(0xCF)) && 986 Magic[1] == char(0xFA) && Magic[2] == char(0xED) && 987 Magic[3] == char(0xFE)) { 988 /* Reverse endian */ 989 if (Magic.size() >= 14) type = Magic[13] << 8 | Magic[12]; 990 } 991 switch (type) { 992 default: break; 993 case 1: return file_magic::macho_object; 994 case 2: return file_magic::macho_executable; 995 case 3: return file_magic::macho_fixed_virtual_memory_shared_lib; 996 case 4: return file_magic::macho_core; 997 case 5: return file_magic::macho_preload_executable; 998 case 6: return file_magic::macho_dynamically_linked_shared_lib; 999 case 7: return file_magic::macho_dynamic_linker; 1000 case 8: return file_magic::macho_bundle; 1001 case 9: return file_magic::macho_dynamic_linker; 1002 case 10: return file_magic::macho_dsym_companion; 1003 } 1004 break; 1005 } 1006 case 0xF0: // PowerPC Windows 1007 case 0x83: // Alpha 32-bit 1008 case 0x84: // Alpha 64-bit 1009 case 0x66: // MPS R4000 Windows 1010 case 0x50: // mc68K 1011 case 0x4c: // 80386 Windows 1012 case 0xc4: // ARMNT Windows 1013 if (Magic[1] == 0x01) 1014 return file_magic::coff_object; 1015 1016 case 0x90: // PA-RISC Windows 1017 case 0x68: // mc68K Windows 1018 if (Magic[1] == 0x02) 1019 return file_magic::coff_object; 1020 break; 1021 1022 case 0x4d: // Possible MS-DOS stub on Windows PE file 1023 if (Magic[1] == 0x5a) { 1024 uint32_t off = 1025 *reinterpret_cast<const support::ulittle32_t*>(Magic.data() + 0x3c); 1026 // PE/COFF file, either EXE or DLL. 1027 if (off < Magic.size() && memcmp(Magic.data() + off, "PE\0\0",4) == 0) 1028 return file_magic::pecoff_executable; 1029 } 1030 break; 1031 1032 case 0x64: // x86-64 Windows. 1033 if (Magic[1] == char(0x86)) 1034 return file_magic::coff_object; 1035 break; 1036 1037 default: 1038 break; 1039 } 1040 return file_magic::unknown; 1041} 1042 1043error_code identify_magic(const Twine &path, file_magic &result) { 1044 SmallString<32> Magic; 1045 error_code ec = get_magic(path, Magic.capacity(), Magic); 1046 if (ec && ec != errc::value_too_large) 1047 return ec; 1048 1049 result = identify_magic(Magic); 1050 return error_code::success(); 1051} 1052 1053error_code directory_entry::status(file_status &result) const { 1054 return fs::status(Path, result); 1055} 1056 1057} // end namespace fs 1058} // end namespace sys 1059} // end namespace llvm 1060 1061// Include the truly platform-specific parts. 1062#if defined(LLVM_ON_UNIX) 1063#include "Unix/Path.inc" 1064#endif 1065#if defined(LLVM_ON_WIN32) 1066#include "Windows/Path.inc" 1067#endif 1068