1 //===-- FileSpec.cpp --------------------------------------------*- 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 #include "lldb/Utility/FileSpec.h" 11 #include "lldb/Utility/CleanUp.h" 12 #include "lldb/Utility/RegularExpression.h" 13 #include "lldb/Utility/Stream.h" 14 #include "lldb/Utility/StreamString.h" 15 #include "lldb/Utility/StringList.h" 16 #include "lldb/Utility/TildeExpressionResolver.h" 17 18 #include "llvm/ADT/StringExtras.h" 19 #include "llvm/ADT/StringRef.h" 20 #include "llvm/Support/ConvertUTF.h" 21 #include "llvm/Support/FileSystem.h" 22 #include "llvm/Support/Path.h" 23 #include "llvm/Support/Program.h" 24 25 using namespace lldb; 26 using namespace lldb_private; 27 28 namespace { 29 30 static constexpr FileSpec::PathSyntax GetNativeSyntax() { 31 #if defined(LLVM_ON_WIN32) 32 return FileSpec::ePathSyntaxWindows; 33 #else 34 return FileSpec::ePathSyntaxPosix; 35 #endif 36 } 37 38 bool PathSyntaxIsPosix(FileSpec::PathSyntax syntax) { 39 return (syntax == FileSpec::ePathSyntaxPosix || 40 (syntax == FileSpec::ePathSyntaxHostNative && 41 GetNativeSyntax() == FileSpec::ePathSyntaxPosix)); 42 } 43 44 const char *GetPathSeparators(FileSpec::PathSyntax syntax) { 45 return PathSyntaxIsPosix(syntax) ? "/" : "\\/"; 46 } 47 48 char GetPreferredPathSeparator(FileSpec::PathSyntax syntax) { 49 return GetPathSeparators(syntax)[0]; 50 } 51 52 bool IsPathSeparator(char value, FileSpec::PathSyntax syntax) { 53 return value == '/' || (!PathSyntaxIsPosix(syntax) && value == '\\'); 54 } 55 56 void Normalize(llvm::SmallVectorImpl<char> &path, FileSpec::PathSyntax syntax) { 57 if (PathSyntaxIsPosix(syntax)) 58 return; 59 60 std::replace(path.begin(), path.end(), '\\', '/'); 61 // Windows path can have \\ slashes which can be changed by replace 62 // call above to //. Here we remove the duplicate. 63 auto iter = std::unique(path.begin(), path.end(), [](char &c1, char &c2) { 64 return (c1 == '/' && c2 == '/'); 65 }); 66 path.erase(iter, path.end()); 67 } 68 69 void Denormalize(llvm::SmallVectorImpl<char> &path, 70 FileSpec::PathSyntax syntax) { 71 if (PathSyntaxIsPosix(syntax)) 72 return; 73 74 std::replace(path.begin(), path.end(), '/', '\\'); 75 } 76 77 size_t FilenamePos(llvm::StringRef str, FileSpec::PathSyntax syntax) { 78 if (str.size() == 2 && IsPathSeparator(str[0], syntax) && str[0] == str[1]) 79 return 0; 80 81 if (str.size() > 0 && IsPathSeparator(str.back(), syntax)) 82 return str.size() - 1; 83 84 size_t pos = str.find_last_of(GetPathSeparators(syntax), str.size() - 1); 85 86 if (!PathSyntaxIsPosix(syntax) && pos == llvm::StringRef::npos) 87 pos = str.find_last_of(':', str.size() - 2); 88 89 if (pos == llvm::StringRef::npos || 90 (pos == 1 && IsPathSeparator(str[0], syntax))) 91 return 0; 92 93 return pos + 1; 94 } 95 96 size_t RootDirStart(llvm::StringRef str, FileSpec::PathSyntax syntax) { 97 // case "c:/" 98 if (!PathSyntaxIsPosix(syntax) && 99 (str.size() > 2 && str[1] == ':' && IsPathSeparator(str[2], syntax))) 100 return 2; 101 102 // case "//" 103 if (str.size() == 2 && IsPathSeparator(str[0], syntax) && str[0] == str[1]) 104 return llvm::StringRef::npos; 105 106 // case "//net" 107 if (str.size() > 3 && IsPathSeparator(str[0], syntax) && str[0] == str[1] && 108 !IsPathSeparator(str[2], syntax)) 109 return str.find_first_of(GetPathSeparators(syntax), 2); 110 111 // case "/" 112 if (str.size() > 0 && IsPathSeparator(str[0], syntax)) 113 return 0; 114 115 return llvm::StringRef::npos; 116 } 117 118 size_t ParentPathEnd(llvm::StringRef path, FileSpec::PathSyntax syntax) { 119 size_t end_pos = FilenamePos(path, syntax); 120 121 bool filename_was_sep = 122 path.size() > 0 && IsPathSeparator(path[end_pos], syntax); 123 124 // Skip separators except for root dir. 125 size_t root_dir_pos = RootDirStart(path.substr(0, end_pos), syntax); 126 127 while (end_pos > 0 && (end_pos - 1) != root_dir_pos && 128 IsPathSeparator(path[end_pos - 1], syntax)) 129 --end_pos; 130 131 if (end_pos == 1 && root_dir_pos == 0 && filename_was_sep) 132 return llvm::StringRef::npos; 133 134 return end_pos; 135 } 136 137 } // end anonymous namespace 138 139 void FileSpec::Resolve(llvm::SmallVectorImpl<char> &path) { 140 if (path.empty()) 141 return; 142 143 llvm::SmallString<32> Source(path.begin(), path.end()); 144 StandardTildeExpressionResolver Resolver; 145 Resolver.ResolveFullPath(Source, path); 146 147 // Save a copy of the original path that's passed in 148 llvm::SmallString<128> original_path(path.begin(), path.end()); 149 150 llvm::sys::fs::make_absolute(path); 151 if (!llvm::sys::fs::exists(path)) { 152 path.clear(); 153 path.append(original_path.begin(), original_path.end()); 154 } 155 } 156 157 FileSpec::FileSpec() : m_syntax(GetNativeSyntax()) {} 158 159 //------------------------------------------------------------------ 160 // Default constructor that can take an optional full path to a 161 // file on disk. 162 //------------------------------------------------------------------ 163 FileSpec::FileSpec(llvm::StringRef path, bool resolve_path, PathSyntax syntax) 164 : m_syntax(syntax) { 165 SetFile(path, resolve_path, syntax); 166 } 167 168 FileSpec::FileSpec(llvm::StringRef path, bool resolve_path, 169 const llvm::Triple &Triple) 170 : FileSpec{path, resolve_path, 171 Triple.isOSWindows() ? ePathSyntaxWindows : ePathSyntaxPosix} {} 172 173 //------------------------------------------------------------------ 174 // Copy constructor 175 //------------------------------------------------------------------ 176 FileSpec::FileSpec(const FileSpec &rhs) 177 : m_directory(rhs.m_directory), m_filename(rhs.m_filename), 178 m_is_resolved(rhs.m_is_resolved), m_syntax(rhs.m_syntax) {} 179 180 //------------------------------------------------------------------ 181 // Copy constructor 182 //------------------------------------------------------------------ 183 FileSpec::FileSpec(const FileSpec *rhs) : m_directory(), m_filename() { 184 if (rhs) 185 *this = *rhs; 186 } 187 188 //------------------------------------------------------------------ 189 // Virtual destructor in case anyone inherits from this class. 190 //------------------------------------------------------------------ 191 FileSpec::~FileSpec() {} 192 193 //------------------------------------------------------------------ 194 // Assignment operator. 195 //------------------------------------------------------------------ 196 const FileSpec &FileSpec::operator=(const FileSpec &rhs) { 197 if (this != &rhs) { 198 m_directory = rhs.m_directory; 199 m_filename = rhs.m_filename; 200 m_is_resolved = rhs.m_is_resolved; 201 m_syntax = rhs.m_syntax; 202 } 203 return *this; 204 } 205 206 //------------------------------------------------------------------ 207 // Update the contents of this object with a new path. The path will 208 // be split up into a directory and filename and stored as uniqued 209 // string values for quick comparison and efficient memory usage. 210 //------------------------------------------------------------------ 211 void FileSpec::SetFile(llvm::StringRef pathname, bool resolve, 212 PathSyntax syntax) { 213 // CLEANUP: Use StringRef for string handling. This function is kind of a 214 // mess and the unclear semantics of RootDirStart and ParentPathEnd make 215 // it very difficult to understand this function. There's no reason this 216 // function should be particularly complicated or difficult to understand. 217 m_filename.Clear(); 218 m_directory.Clear(); 219 m_is_resolved = false; 220 m_syntax = (syntax == ePathSyntaxHostNative) ? GetNativeSyntax() : syntax; 221 222 if (pathname.empty()) 223 return; 224 225 llvm::SmallString<64> resolved(pathname); 226 227 if (resolve) { 228 FileSpec::Resolve(resolved); 229 m_is_resolved = true; 230 } 231 232 Normalize(resolved, m_syntax); 233 234 llvm::StringRef resolve_path_ref(resolved.c_str()); 235 size_t dir_end = ParentPathEnd(resolve_path_ref, m_syntax); 236 if (dir_end == 0) { 237 m_filename.SetString(resolve_path_ref); 238 return; 239 } 240 241 m_directory.SetString(resolve_path_ref.substr(0, dir_end)); 242 243 size_t filename_begin = dir_end; 244 size_t root_dir_start = RootDirStart(resolve_path_ref, m_syntax); 245 while (filename_begin != llvm::StringRef::npos && 246 filename_begin < resolve_path_ref.size() && 247 filename_begin != root_dir_start && 248 IsPathSeparator(resolve_path_ref[filename_begin], m_syntax)) 249 ++filename_begin; 250 m_filename.SetString((filename_begin == llvm::StringRef::npos || 251 filename_begin >= resolve_path_ref.size()) 252 ? "." 253 : resolve_path_ref.substr(filename_begin)); 254 } 255 256 void FileSpec::SetFile(llvm::StringRef path, bool resolve, 257 const llvm::Triple &Triple) { 258 return SetFile(path, resolve, 259 Triple.isOSWindows() ? ePathSyntaxWindows : ePathSyntaxPosix); 260 } 261 262 //---------------------------------------------------------------------- 263 // Convert to pointer operator. This allows code to check any FileSpec 264 // objects to see if they contain anything valid using code such as: 265 // 266 // if (file_spec) 267 // {} 268 //---------------------------------------------------------------------- 269 FileSpec::operator bool() const { return m_filename || m_directory; } 270 271 //---------------------------------------------------------------------- 272 // Logical NOT operator. This allows code to check any FileSpec 273 // objects to see if they are invalid using code such as: 274 // 275 // if (!file_spec) 276 // {} 277 //---------------------------------------------------------------------- 278 bool FileSpec::operator!() const { return !m_directory && !m_filename; } 279 280 bool FileSpec::DirectoryEquals(const FileSpec &rhs) const { 281 const bool case_sensitive = IsCaseSensitive() || rhs.IsCaseSensitive(); 282 return ConstString::Equals(m_directory, rhs.m_directory, case_sensitive); 283 } 284 285 bool FileSpec::FileEquals(const FileSpec &rhs) const { 286 const bool case_sensitive = IsCaseSensitive() || rhs.IsCaseSensitive(); 287 return ConstString::Equals(m_filename, rhs.m_filename, case_sensitive); 288 } 289 290 //------------------------------------------------------------------ 291 // Equal to operator 292 //------------------------------------------------------------------ 293 bool FileSpec::operator==(const FileSpec &rhs) const { 294 if (!FileEquals(rhs)) 295 return false; 296 if (DirectoryEquals(rhs)) 297 return true; 298 299 // TODO: determine if we want to keep this code in here. 300 // The code below was added to handle a case where we were 301 // trying to set a file and line breakpoint and one path 302 // was resolved, and the other not and the directory was 303 // in a mount point that resolved to a more complete path: 304 // "/tmp/a.c" == "/private/tmp/a.c". I might end up pulling 305 // this out... 306 if (IsResolved() && rhs.IsResolved()) { 307 // Both paths are resolved, no need to look further... 308 return false; 309 } 310 311 FileSpec resolved_lhs(*this); 312 313 // If "this" isn't resolved, resolve it 314 if (!IsResolved()) { 315 if (resolved_lhs.ResolvePath()) { 316 // This path wasn't resolved but now it is. Check if the resolved 317 // directory is the same as our unresolved directory, and if so, 318 // we can mark this object as resolved to avoid more future resolves 319 m_is_resolved = (m_directory == resolved_lhs.m_directory); 320 } else 321 return false; 322 } 323 324 FileSpec resolved_rhs(rhs); 325 if (!rhs.IsResolved()) { 326 if (resolved_rhs.ResolvePath()) { 327 // rhs's path wasn't resolved but now it is. Check if the resolved 328 // directory is the same as rhs's unresolved directory, and if so, 329 // we can mark this object as resolved to avoid more future resolves 330 rhs.m_is_resolved = (rhs.m_directory == resolved_rhs.m_directory); 331 } else 332 return false; 333 } 334 335 // If we reach this point in the code we were able to resolve both paths 336 // and since we only resolve the paths if the basenames are equal, then 337 // we can just check if both directories are equal... 338 return DirectoryEquals(rhs); 339 } 340 341 //------------------------------------------------------------------ 342 // Not equal to operator 343 //------------------------------------------------------------------ 344 bool FileSpec::operator!=(const FileSpec &rhs) const { return !(*this == rhs); } 345 346 //------------------------------------------------------------------ 347 // Less than operator 348 //------------------------------------------------------------------ 349 bool FileSpec::operator<(const FileSpec &rhs) const { 350 return FileSpec::Compare(*this, rhs, true) < 0; 351 } 352 353 //------------------------------------------------------------------ 354 // Dump a FileSpec object to a stream 355 //------------------------------------------------------------------ 356 Stream &lldb_private::operator<<(Stream &s, const FileSpec &f) { 357 f.Dump(&s); 358 return s; 359 } 360 361 //------------------------------------------------------------------ 362 // Clear this object by releasing both the directory and filename 363 // string values and making them both the empty string. 364 //------------------------------------------------------------------ 365 void FileSpec::Clear() { 366 m_directory.Clear(); 367 m_filename.Clear(); 368 } 369 370 //------------------------------------------------------------------ 371 // Compare two FileSpec objects. If "full" is true, then both 372 // the directory and the filename must match. If "full" is false, 373 // then the directory names for "a" and "b" are only compared if 374 // they are both non-empty. This allows a FileSpec object to only 375 // contain a filename and it can match FileSpec objects that have 376 // matching filenames with different paths. 377 // 378 // Return -1 if the "a" is less than "b", 0 if "a" is equal to "b" 379 // and "1" if "a" is greater than "b". 380 //------------------------------------------------------------------ 381 int FileSpec::Compare(const FileSpec &a, const FileSpec &b, bool full) { 382 int result = 0; 383 384 // case sensitivity of compare 385 const bool case_sensitive = a.IsCaseSensitive() || b.IsCaseSensitive(); 386 387 // If full is true, then we must compare both the directory and filename. 388 389 // If full is false, then if either directory is empty, then we match on 390 // the basename only, and if both directories have valid values, we still 391 // do a full compare. This allows for matching when we just have a filename 392 // in one of the FileSpec objects. 393 394 if (full || (a.m_directory && b.m_directory)) { 395 result = ConstString::Compare(a.m_directory, b.m_directory, case_sensitive); 396 if (result) 397 return result; 398 } 399 return ConstString::Compare(a.m_filename, b.m_filename, case_sensitive); 400 } 401 402 bool FileSpec::Equal(const FileSpec &a, const FileSpec &b, bool full, 403 bool remove_backups) { 404 // case sensitivity of equality test 405 const bool case_sensitive = a.IsCaseSensitive() || b.IsCaseSensitive(); 406 407 if (!full && (a.GetDirectory().IsEmpty() || b.GetDirectory().IsEmpty())) 408 return ConstString::Equals(a.m_filename, b.m_filename, case_sensitive); 409 410 if (remove_backups == false) 411 return a == b; 412 413 if (a == b) 414 return true; 415 416 return Equal(a.GetNormalizedPath(), b.GetNormalizedPath(), full, false); 417 } 418 419 FileSpec FileSpec::GetNormalizedPath() const { 420 // Fast path. Do nothing if the path is not interesting. 421 if (!m_directory.GetStringRef().contains(".") && 422 !m_directory.GetStringRef().contains("//") && 423 m_filename.GetStringRef() != ".." && m_filename.GetStringRef() != ".") 424 return *this; 425 426 llvm::SmallString<64> path, result; 427 const bool normalize = false; 428 GetPath(path, normalize); 429 llvm::StringRef rest(path); 430 431 // We will not go below root dir. 432 size_t root_dir_start = RootDirStart(path, m_syntax); 433 const bool absolute = root_dir_start != llvm::StringRef::npos; 434 if (absolute) { 435 result += rest.take_front(root_dir_start + 1); 436 rest = rest.drop_front(root_dir_start + 1); 437 } else { 438 if (m_syntax == ePathSyntaxWindows && path.size() > 2 && path[1] == ':') { 439 result += rest.take_front(2); 440 rest = rest.drop_front(2); 441 } 442 } 443 444 bool anything_added = false; 445 llvm::SmallVector<llvm::StringRef, 0> components, processed; 446 rest.split(components, '/', -1, false); 447 processed.reserve(components.size()); 448 for (auto component : components) { 449 if (component == ".") 450 continue; // Skip these. 451 if (component != "..") { 452 processed.push_back(component); 453 continue; // Regular file name. 454 } 455 if (!processed.empty()) { 456 processed.pop_back(); 457 continue; // Dots. Go one level up if we can. 458 } 459 if (absolute) 460 continue; // We're at the top level. Cannot go higher than that. Skip. 461 462 result += component; // We're a relative path. We need to keep these. 463 result += '/'; 464 anything_added = true; 465 } 466 for (auto component : processed) { 467 result += component; 468 result += '/'; 469 anything_added = true; 470 } 471 if (anything_added) 472 result.pop_back(); // Pop last '/'. 473 else if (result.empty()) 474 result = "."; 475 476 return FileSpec(result, false, m_syntax); 477 } 478 479 //------------------------------------------------------------------ 480 // Dump the object to the supplied stream. If the object contains 481 // a valid directory name, it will be displayed followed by a 482 // directory delimiter, and the filename. 483 //------------------------------------------------------------------ 484 void FileSpec::Dump(Stream *s) const { 485 if (s) { 486 std::string path{GetPath(true)}; 487 s->PutCString(path); 488 char path_separator = GetPreferredPathSeparator(m_syntax); 489 if (!m_filename && !path.empty() && path.back() != path_separator) 490 s->PutChar(path_separator); 491 } 492 } 493 494 //------------------------------------------------------------------ 495 // Returns true if the file exists. 496 //------------------------------------------------------------------ 497 bool FileSpec::Exists() const { return llvm::sys::fs::exists(GetPath()); } 498 499 bool FileSpec::Readable() const { 500 return GetPermissions() & llvm::sys::fs::perms::all_read; 501 } 502 503 bool FileSpec::ResolveExecutableLocation() { 504 // CLEANUP: Use StringRef for string handling. 505 if (!m_directory) { 506 const char *file_cstr = m_filename.GetCString(); 507 if (file_cstr) { 508 const std::string file_str(file_cstr); 509 llvm::ErrorOr<std::string> error_or_path = 510 llvm::sys::findProgramByName(file_str); 511 if (!error_or_path) 512 return false; 513 std::string path = error_or_path.get(); 514 llvm::StringRef dir_ref = llvm::sys::path::parent_path(path); 515 if (!dir_ref.empty()) { 516 // FindProgramByName returns "." if it can't find the file. 517 if (strcmp(".", dir_ref.data()) == 0) 518 return false; 519 520 m_directory.SetCString(dir_ref.data()); 521 if (Exists()) 522 return true; 523 else { 524 // If FindProgramByName found the file, it returns the directory + 525 // filename in its return results. 526 // We need to separate them. 527 FileSpec tmp_file(dir_ref.data(), false); 528 if (tmp_file.Exists()) { 529 m_directory = tmp_file.m_directory; 530 return true; 531 } 532 } 533 } 534 } 535 } 536 537 return false; 538 } 539 540 bool FileSpec::ResolvePath() { 541 if (m_is_resolved) 542 return true; // We have already resolved this path 543 544 // SetFile(...) will set m_is_resolved correctly if it can resolve the path 545 SetFile(GetPath(false), true); 546 return m_is_resolved; 547 } 548 549 uint64_t FileSpec::GetByteSize() const { 550 uint64_t Size = 0; 551 if (llvm::sys::fs::file_size(GetPath(), Size)) 552 return 0; 553 return Size; 554 } 555 556 FileSpec::PathSyntax FileSpec::GetPathSyntax() const { return m_syntax; } 557 558 uint32_t FileSpec::GetPermissions() const { 559 namespace fs = llvm::sys::fs; 560 fs::file_status st; 561 if (fs::status(GetPath(), st, false)) 562 return fs::perms::perms_not_known; 563 564 return st.permissions(); 565 } 566 567 //------------------------------------------------------------------ 568 // Directory string get accessor. 569 //------------------------------------------------------------------ 570 ConstString &FileSpec::GetDirectory() { return m_directory; } 571 572 //------------------------------------------------------------------ 573 // Directory string const get accessor. 574 //------------------------------------------------------------------ 575 const ConstString &FileSpec::GetDirectory() const { return m_directory; } 576 577 //------------------------------------------------------------------ 578 // Filename string get accessor. 579 //------------------------------------------------------------------ 580 ConstString &FileSpec::GetFilename() { return m_filename; } 581 582 //------------------------------------------------------------------ 583 // Filename string const get accessor. 584 //------------------------------------------------------------------ 585 const ConstString &FileSpec::GetFilename() const { return m_filename; } 586 587 //------------------------------------------------------------------ 588 // Extract the directory and path into a fixed buffer. This is 589 // needed as the directory and path are stored in separate string 590 // values. 591 //------------------------------------------------------------------ 592 size_t FileSpec::GetPath(char *path, size_t path_max_len, 593 bool denormalize) const { 594 if (!path) 595 return 0; 596 597 std::string result = GetPath(denormalize); 598 ::snprintf(path, path_max_len, "%s", result.c_str()); 599 return std::min(path_max_len - 1, result.length()); 600 } 601 602 std::string FileSpec::GetPath(bool denormalize) const { 603 llvm::SmallString<64> result; 604 GetPath(result, denormalize); 605 return std::string(result.begin(), result.end()); 606 } 607 608 const char *FileSpec::GetCString(bool denormalize) const { 609 return ConstString{GetPath(denormalize)}.AsCString(NULL); 610 } 611 612 void FileSpec::GetPath(llvm::SmallVectorImpl<char> &path, 613 bool denormalize) const { 614 path.append(m_directory.GetStringRef().begin(), 615 m_directory.GetStringRef().end()); 616 if (m_directory && m_filename && 617 !IsPathSeparator(m_directory.GetStringRef().back(), m_syntax)) 618 path.insert(path.end(), GetPreferredPathSeparator(m_syntax)); 619 path.append(m_filename.GetStringRef().begin(), 620 m_filename.GetStringRef().end()); 621 Normalize(path, m_syntax); 622 if (denormalize && !path.empty()) 623 Denormalize(path, m_syntax); 624 } 625 626 ConstString FileSpec::GetFileNameExtension() const { 627 if (m_filename) { 628 const char *filename = m_filename.GetCString(); 629 const char *dot_pos = strrchr(filename, '.'); 630 if (dot_pos && dot_pos[1] != '\0') 631 return ConstString(dot_pos + 1); 632 } 633 return ConstString(); 634 } 635 636 ConstString FileSpec::GetFileNameStrippingExtension() const { 637 const char *filename = m_filename.GetCString(); 638 if (filename == NULL) 639 return ConstString(); 640 641 const char *dot_pos = strrchr(filename, '.'); 642 if (dot_pos == NULL) 643 return m_filename; 644 645 return ConstString(filename, dot_pos - filename); 646 } 647 648 //------------------------------------------------------------------ 649 // Return the size in bytes that this object takes in memory. This 650 // returns the size in bytes of this object, not any shared string 651 // values it may refer to. 652 //------------------------------------------------------------------ 653 size_t FileSpec::MemorySize() const { 654 return m_filename.MemorySize() + m_directory.MemorySize(); 655 } 656 657 void FileSpec::EnumerateDirectory(llvm::StringRef dir_path, 658 bool find_directories, bool find_files, 659 bool find_other, 660 EnumerateDirectoryCallbackType callback, 661 void *callback_baton) { 662 namespace fs = llvm::sys::fs; 663 std::error_code EC; 664 fs::recursive_directory_iterator Iter(dir_path, EC); 665 fs::recursive_directory_iterator End; 666 for (; Iter != End && !EC; Iter.increment(EC)) { 667 const auto &Item = *Iter; 668 fs::file_status Status; 669 if ((EC = Item.status(Status))) 670 break; 671 if (!find_files && fs::is_regular_file(Status)) 672 continue; 673 if (!find_directories && fs::is_directory(Status)) 674 continue; 675 if (!find_other && fs::is_other(Status)) 676 continue; 677 678 FileSpec Spec(Item.path(), false); 679 auto Result = callback(callback_baton, Status.type(), Spec); 680 if (Result == eEnumerateDirectoryResultQuit) 681 return; 682 if (Result == eEnumerateDirectoryResultNext) { 683 // Default behavior is to recurse. Opt out if the callback doesn't want 684 // this behavior. 685 Iter.no_push(); 686 } 687 } 688 } 689 690 FileSpec 691 FileSpec::CopyByAppendingPathComponent(llvm::StringRef component) const { 692 FileSpec ret = *this; 693 ret.AppendPathComponent(component); 694 return ret; 695 } 696 697 FileSpec FileSpec::CopyByRemovingLastPathComponent() const { 698 // CLEANUP: Use StringRef for string handling. 699 const bool resolve = false; 700 if (m_filename.IsEmpty() && m_directory.IsEmpty()) 701 return FileSpec("", resolve); 702 if (m_directory.IsEmpty()) 703 return FileSpec("", resolve); 704 if (m_filename.IsEmpty()) { 705 const char *dir_cstr = m_directory.GetCString(); 706 const char *last_slash_ptr = ::strrchr(dir_cstr, '/'); 707 708 // check for obvious cases before doing the full thing 709 if (!last_slash_ptr) 710 return FileSpec("", resolve); 711 if (last_slash_ptr == dir_cstr) 712 return FileSpec("/", resolve); 713 714 size_t last_slash_pos = last_slash_ptr - dir_cstr + 1; 715 ConstString new_path(dir_cstr, last_slash_pos); 716 return FileSpec(new_path.GetCString(), resolve); 717 } else 718 return FileSpec(m_directory.GetCString(), resolve); 719 } 720 721 ConstString FileSpec::GetLastPathComponent() const { 722 // CLEANUP: Use StringRef for string handling. 723 if (m_filename) 724 return m_filename; 725 if (m_directory) { 726 const char *dir_cstr = m_directory.GetCString(); 727 const char *last_slash_ptr = ::strrchr(dir_cstr, '/'); 728 if (last_slash_ptr == NULL) 729 return m_directory; 730 if (last_slash_ptr == dir_cstr) { 731 if (last_slash_ptr[1] == 0) 732 return ConstString(last_slash_ptr); 733 else 734 return ConstString(last_slash_ptr + 1); 735 } 736 if (last_slash_ptr[1] != 0) 737 return ConstString(last_slash_ptr + 1); 738 const char *penultimate_slash_ptr = last_slash_ptr; 739 while (*penultimate_slash_ptr) { 740 --penultimate_slash_ptr; 741 if (penultimate_slash_ptr == dir_cstr) 742 break; 743 if (*penultimate_slash_ptr == '/') 744 break; 745 } 746 ConstString result(penultimate_slash_ptr + 1, 747 last_slash_ptr - penultimate_slash_ptr); 748 return result; 749 } 750 return ConstString(); 751 } 752 753 static std::string 754 join_path_components(FileSpec::PathSyntax syntax, 755 const std::vector<llvm::StringRef> components) { 756 std::string result; 757 for (size_t i = 0; i < components.size(); ++i) { 758 if (components[i].empty()) 759 continue; 760 result += components[i]; 761 if (i != components.size() - 1 && 762 !IsPathSeparator(components[i].back(), syntax)) 763 result += GetPreferredPathSeparator(syntax); 764 } 765 766 return result; 767 } 768 769 void FileSpec::PrependPathComponent(llvm::StringRef component) { 770 if (component.empty()) 771 return; 772 773 const bool resolve = false; 774 if (m_filename.IsEmpty() && m_directory.IsEmpty()) { 775 SetFile(component, resolve); 776 return; 777 } 778 779 std::string result = 780 join_path_components(m_syntax, {component, m_directory.GetStringRef(), 781 m_filename.GetStringRef()}); 782 SetFile(result, resolve, m_syntax); 783 } 784 785 void FileSpec::PrependPathComponent(const FileSpec &new_path) { 786 return PrependPathComponent(new_path.GetPath(false)); 787 } 788 789 void FileSpec::AppendPathComponent(llvm::StringRef component) { 790 if (component.empty()) 791 return; 792 793 component = component.drop_while( 794 [this](char c) { return IsPathSeparator(c, m_syntax); }); 795 796 std::string result = 797 join_path_components(m_syntax, {m_directory.GetStringRef(), 798 m_filename.GetStringRef(), component}); 799 800 SetFile(result, false, m_syntax); 801 } 802 803 void FileSpec::AppendPathComponent(const FileSpec &new_path) { 804 return AppendPathComponent(new_path.GetPath(false)); 805 } 806 807 void FileSpec::RemoveLastPathComponent() { 808 // CLEANUP: Use StringRef for string handling. 809 810 const bool resolve = false; 811 if (m_filename.IsEmpty() && m_directory.IsEmpty()) { 812 SetFile("", resolve); 813 return; 814 } 815 if (m_directory.IsEmpty()) { 816 SetFile("", resolve); 817 return; 818 } 819 if (m_filename.IsEmpty()) { 820 const char *dir_cstr = m_directory.GetCString(); 821 const char *last_slash_ptr = ::strrchr(dir_cstr, '/'); 822 823 // check for obvious cases before doing the full thing 824 if (!last_slash_ptr) { 825 SetFile("", resolve); 826 return; 827 } 828 if (last_slash_ptr == dir_cstr) { 829 SetFile("/", resolve); 830 return; 831 } 832 size_t last_slash_pos = last_slash_ptr - dir_cstr + 1; 833 ConstString new_path(dir_cstr, last_slash_pos); 834 SetFile(new_path.GetCString(), resolve); 835 } else 836 SetFile(m_directory.GetCString(), resolve); 837 } 838 //------------------------------------------------------------------ 839 /// Returns true if the filespec represents an implementation source 840 /// file (files with a ".c", ".cpp", ".m", ".mm" (many more) 841 /// extension). 842 /// 843 /// @return 844 /// \b true if the filespec represents an implementation source 845 /// file, \b false otherwise. 846 //------------------------------------------------------------------ 847 bool FileSpec::IsSourceImplementationFile() const { 848 ConstString extension(GetFileNameExtension()); 849 if (!extension) 850 return false; 851 852 static RegularExpression g_source_file_regex(llvm::StringRef( 853 "^([cC]|[mM]|[mM][mM]|[cC][pP][pP]|[cC]\\+\\+|[cC][xX][xX]|[cC][cC]|[" 854 "cC][pP]|[sS]|[aA][sS][mM]|[fF]|[fF]77|[fF]90|[fF]95|[fF]03|[fF][oO][" 855 "rR]|[fF][tT][nN]|[fF][pP][pP]|[aA][dD][aA]|[aA][dD][bB]|[aA][dD][sS])" 856 "$")); 857 return g_source_file_regex.Execute(extension.GetStringRef()); 858 } 859 860 bool FileSpec::IsRelative() const { 861 const char *dir = m_directory.GetCString(); 862 llvm::StringRef directory(dir ? dir : ""); 863 864 if (directory.size() > 0) { 865 if (PathSyntaxIsPosix(m_syntax)) { 866 // If the path doesn't start with '/' or '~', return true 867 switch (directory[0]) { 868 case '/': 869 case '~': 870 return false; 871 default: 872 return true; 873 } 874 } else { 875 if (directory.size() >= 2 && directory[1] == ':') 876 return false; 877 if (directory[0] == '/') 878 return false; 879 return true; 880 } 881 } else if (m_filename) { 882 // No directory, just a basename, return true 883 return true; 884 } 885 return false; 886 } 887 888 bool FileSpec::IsAbsolute() const { return !FileSpec::IsRelative(); } 889 890 void llvm::format_provider<FileSpec>::format(const FileSpec &F, 891 raw_ostream &Stream, 892 StringRef Style) { 893 assert( 894 (Style.empty() || Style.equals_lower("F") || Style.equals_lower("D")) && 895 "Invalid FileSpec style!"); 896 897 StringRef dir = F.GetDirectory().GetStringRef(); 898 StringRef file = F.GetFilename().GetStringRef(); 899 900 if (dir.empty() && file.empty()) { 901 Stream << "(empty)"; 902 return; 903 } 904 905 if (Style.equals_lower("F")) { 906 Stream << (file.empty() ? "(empty)" : file); 907 return; 908 } 909 910 // Style is either D or empty, either way we need to print the directory. 911 if (!dir.empty()) { 912 // Directory is stored in normalized form, which might be different 913 // than preferred form. In order to handle this, we need to cut off 914 // the filename, then denormalize, then write the entire denorm'ed 915 // directory. 916 llvm::SmallString<64> denormalized_dir = dir; 917 Denormalize(denormalized_dir, F.GetPathSyntax()); 918 Stream << denormalized_dir; 919 Stream << GetPreferredPathSeparator(F.GetPathSyntax()); 920 } 921 922 if (Style.equals_lower("D")) { 923 // We only want to print the directory, so now just exit. 924 if (dir.empty()) 925 Stream << "(empty)"; 926 return; 927 } 928 929 if (!file.empty()) 930 Stream << file; 931 } 932