FileSpec.cpp revision 5581a7e69714aa6c08833e060de85237ec2a690a
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 11#include <dirent.h> 12#include <fcntl.h> 13#include <libgen.h> 14#include <sys/stat.h> 15#include <string.h> 16#include <fstream> 17 18#include "lldb/Host/Config.h" // Have to include this before we test the define... 19#ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER 20#include <pwd.h> 21#endif 22 23#include "llvm/ADT/StringRef.h" 24#include "llvm/Support/Path.h" 25#include "llvm/Support/Program.h" 26 27#include "lldb/Host/File.h" 28#include "lldb/Host/FileSpec.h" 29#include "lldb/Core/DataBufferHeap.h" 30#include "lldb/Core/DataBufferMemoryMap.h" 31#include "lldb/Core/RegularExpression.h" 32#include "lldb/Core/Stream.h" 33#include "lldb/Host/Host.h" 34#include "lldb/Utility/CleanUp.h" 35 36using namespace lldb; 37using namespace lldb_private; 38 39static bool 40GetFileStats (const FileSpec *file_spec, struct stat *stats_ptr) 41{ 42 char resolved_path[PATH_MAX]; 43 if (file_spec->GetPath (resolved_path, sizeof(resolved_path))) 44 return ::stat (resolved_path, stats_ptr) == 0; 45 return false; 46} 47 48#ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER 49 50static const char* 51GetCachedGlobTildeSlash() 52{ 53 static std::string g_tilde; 54 if (g_tilde.empty()) 55 { 56 struct passwd *user_entry; 57 user_entry = getpwuid(geteuid()); 58 if (user_entry != NULL) 59 g_tilde = user_entry->pw_dir; 60 61 if (g_tilde.empty()) 62 return NULL; 63 } 64 return g_tilde.c_str(); 65} 66 67#endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER 68 69// Resolves the username part of a path of the form ~user/other/directories, and 70// writes the result into dst_path. 71// Returns 0 if there WAS a ~ in the path but the username couldn't be resolved. 72// Otherwise returns the number of characters copied into dst_path. If the return 73// is >= dst_len, then the resolved path is too long... 74size_t 75FileSpec::ResolveUsername (const char *src_path, char *dst_path, size_t dst_len) 76{ 77 if (src_path == NULL || src_path[0] == '\0') 78 return 0; 79 80#ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER 81 82 char user_home[PATH_MAX]; 83 const char *user_name; 84 85 86 // If there's no ~, then just copy src_path straight to dst_path (they may be the same string...) 87 if (src_path[0] != '~') 88 { 89 size_t len = strlen (src_path); 90 if (len >= dst_len) 91 { 92 ::bcopy (src_path, dst_path, dst_len - 1); 93 dst_path[dst_len] = '\0'; 94 } 95 else 96 ::bcopy (src_path, dst_path, len + 1); 97 98 return len; 99 } 100 101 const char *first_slash = ::strchr (src_path, '/'); 102 char remainder[PATH_MAX]; 103 104 if (first_slash == NULL) 105 { 106 // The whole name is the username (minus the ~): 107 user_name = src_path + 1; 108 remainder[0] = '\0'; 109 } 110 else 111 { 112 size_t user_name_len = first_slash - src_path - 1; 113 ::memcpy (user_home, src_path + 1, user_name_len); 114 user_home[user_name_len] = '\0'; 115 user_name = user_home; 116 117 ::strcpy (remainder, first_slash); 118 } 119 120 if (user_name == NULL) 121 return 0; 122 // User name of "" means the current user... 123 124 struct passwd *user_entry; 125 const char *home_dir = NULL; 126 127 if (user_name[0] == '\0') 128 { 129 home_dir = GetCachedGlobTildeSlash(); 130 } 131 else 132 { 133 user_entry = ::getpwnam (user_name); 134 if (user_entry != NULL) 135 home_dir = user_entry->pw_dir; 136 } 137 138 if (home_dir == NULL) 139 return 0; 140 else 141 return ::snprintf (dst_path, dst_len, "%s%s", home_dir, remainder); 142#else 143 // Resolving home directories is not supported, just copy the path... 144 return ::snprintf (dst_path, dst_len, "%s", src_path); 145#endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER 146} 147 148size_t 149FileSpec::ResolvePartialUsername (const char *partial_name, StringList &matches) 150{ 151#ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER 152 size_t extant_entries = matches.GetSize(); 153 154 setpwent(); 155 struct passwd *user_entry; 156 const char *name_start = partial_name + 1; 157 std::set<std::string> name_list; 158 159 while ((user_entry = getpwent()) != NULL) 160 { 161 if (strstr(user_entry->pw_name, name_start) == user_entry->pw_name) 162 { 163 std::string tmp_buf("~"); 164 tmp_buf.append(user_entry->pw_name); 165 tmp_buf.push_back('/'); 166 name_list.insert(tmp_buf); 167 } 168 } 169 std::set<std::string>::iterator pos, end = name_list.end(); 170 for (pos = name_list.begin(); pos != end; pos++) 171 { 172 matches.AppendString((*pos).c_str()); 173 } 174 return matches.GetSize() - extant_entries; 175#else 176 // Resolving home directories is not supported, just copy the path... 177 return 0; 178#endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER 179} 180 181 182 183size_t 184FileSpec::Resolve (const char *src_path, char *dst_path, size_t dst_len) 185{ 186 if (src_path == NULL || src_path[0] == '\0') 187 return 0; 188 189 // Glob if needed for ~/, otherwise copy in case src_path is same as dst_path... 190 char unglobbed_path[PATH_MAX]; 191#ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER 192 if (src_path[0] == '~') 193 { 194 size_t return_count = ResolveUsername(src_path, unglobbed_path, sizeof(unglobbed_path)); 195 196 // If we couldn't find the user referred to, or the resultant path was too long, 197 // then just copy over the src_path. 198 if (return_count == 0 || return_count >= sizeof(unglobbed_path)) 199 ::snprintf (unglobbed_path, sizeof(unglobbed_path), "%s", src_path); 200 } 201 else 202#endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER 203 { 204 ::snprintf(unglobbed_path, sizeof(unglobbed_path), "%s", src_path); 205 } 206 207 // Now resolve the path if needed 208 char resolved_path[PATH_MAX]; 209 if (::realpath (unglobbed_path, resolved_path)) 210 { 211 // Success, copy the resolved path 212 return ::snprintf(dst_path, dst_len, "%s", resolved_path); 213 } 214 else 215 { 216 // Failed, just copy the unglobbed path 217 return ::snprintf(dst_path, dst_len, "%s", unglobbed_path); 218 } 219} 220 221FileSpec::FileSpec() : 222 m_directory(), 223 m_filename() 224{ 225} 226 227//------------------------------------------------------------------ 228// Default constructor that can take an optional full path to a 229// file on disk. 230//------------------------------------------------------------------ 231FileSpec::FileSpec(const char *pathname, bool resolve_path) : 232 m_directory(), 233 m_filename(), 234 m_is_resolved(false) 235{ 236 if (pathname && pathname[0]) 237 SetFile(pathname, resolve_path); 238} 239 240//------------------------------------------------------------------ 241// Copy constructor 242//------------------------------------------------------------------ 243FileSpec::FileSpec(const FileSpec& rhs) : 244 m_directory (rhs.m_directory), 245 m_filename (rhs.m_filename), 246 m_is_resolved (rhs.m_is_resolved) 247{ 248} 249 250//------------------------------------------------------------------ 251// Copy constructor 252//------------------------------------------------------------------ 253FileSpec::FileSpec(const FileSpec* rhs) : 254 m_directory(), 255 m_filename() 256{ 257 if (rhs) 258 *this = *rhs; 259} 260 261//------------------------------------------------------------------ 262// Virtual destrcuctor in case anyone inherits from this class. 263//------------------------------------------------------------------ 264FileSpec::~FileSpec() 265{ 266} 267 268//------------------------------------------------------------------ 269// Assignment operator. 270//------------------------------------------------------------------ 271const FileSpec& 272FileSpec::operator= (const FileSpec& rhs) 273{ 274 if (this != &rhs) 275 { 276 m_directory = rhs.m_directory; 277 m_filename = rhs.m_filename; 278 m_is_resolved = rhs.m_is_resolved; 279 } 280 return *this; 281} 282 283//------------------------------------------------------------------ 284// Update the contents of this object with a new path. The path will 285// be split up into a directory and filename and stored as uniqued 286// string values for quick comparison and efficient memory usage. 287//------------------------------------------------------------------ 288void 289FileSpec::SetFile (const char *pathname, bool resolve) 290{ 291 m_filename.Clear(); 292 m_directory.Clear(); 293 m_is_resolved = false; 294 if (pathname == NULL || pathname[0] == '\0') 295 return; 296 297 char resolved_path[PATH_MAX]; 298 bool path_fit = true; 299 300 if (resolve) 301 { 302 path_fit = (FileSpec::Resolve (pathname, resolved_path, sizeof(resolved_path)) < sizeof(resolved_path) - 1); 303 m_is_resolved = path_fit; 304 } 305 else 306 { 307 // Copy the path because "basename" and "dirname" want to muck with the 308 // path buffer 309 if (::strlen (pathname) > sizeof(resolved_path) - 1) 310 path_fit = false; 311 else 312 ::strcpy (resolved_path, pathname); 313 } 314 315 316 if (path_fit) 317 { 318 char *filename = ::basename (resolved_path); 319 if (filename) 320 { 321 m_filename.SetCString (filename); 322 // Truncate the basename off the end of the resolved path 323 324 // Only attempt to get the dirname if it looks like we have a path 325 if (strchr(resolved_path, '/')) 326 { 327 char *directory = ::dirname (resolved_path); 328 329 // Make sure we didn't get our directory resolved to "." without having 330 // specified 331 if (directory) 332 m_directory.SetCString(directory); 333 else 334 { 335 char *last_resolved_path_slash = strrchr(resolved_path, '/'); 336 if (last_resolved_path_slash) 337 { 338 *last_resolved_path_slash = '\0'; 339 m_directory.SetCString(resolved_path); 340 } 341 } 342 } 343 } 344 else 345 m_directory.SetCString(resolved_path); 346 } 347} 348 349//---------------------------------------------------------------------- 350// Convert to pointer operator. This allows code to check any FileSpec 351// objects to see if they contain anything valid using code such as: 352// 353// if (file_spec) 354// {} 355//---------------------------------------------------------------------- 356FileSpec::operator bool() const 357{ 358 return m_filename || m_directory; 359} 360 361//---------------------------------------------------------------------- 362// Logical NOT operator. This allows code to check any FileSpec 363// objects to see if they are invalid using code such as: 364// 365// if (!file_spec) 366// {} 367//---------------------------------------------------------------------- 368bool 369FileSpec::operator!() const 370{ 371 return !m_directory && !m_filename; 372} 373 374//------------------------------------------------------------------ 375// Equal to operator 376//------------------------------------------------------------------ 377bool 378FileSpec::operator== (const FileSpec& rhs) const 379{ 380 if (m_filename == rhs.m_filename) 381 { 382 if (m_directory == rhs.m_directory) 383 return true; 384 385 // TODO: determine if we want to keep this code in here. 386 // The code below was added to handle a case where we were 387 // trying to set a file and line breakpoint and one path 388 // was resolved, and the other not and the directory was 389 // in a mount point that resolved to a more complete path: 390 // "/tmp/a.c" == "/private/tmp/a.c". I might end up pulling 391 // this out... 392 if (IsResolved() && rhs.IsResolved()) 393 { 394 // Both paths are resolved, no need to look further... 395 return false; 396 } 397 398 FileSpec resolved_lhs(*this); 399 400 // If "this" isn't resolved, resolve it 401 if (!IsResolved()) 402 { 403 if (resolved_lhs.ResolvePath()) 404 { 405 // This path wasn't resolved but now it is. Check if the resolved 406 // directory is the same as our unresolved directory, and if so, 407 // we can mark this object as resolved to avoid more future resolves 408 m_is_resolved = (m_directory == resolved_lhs.m_directory); 409 } 410 else 411 return false; 412 } 413 414 FileSpec resolved_rhs(rhs); 415 if (!rhs.IsResolved()) 416 { 417 if (resolved_rhs.ResolvePath()) 418 { 419 // rhs's path wasn't resolved but now it is. Check if the resolved 420 // directory is the same as rhs's unresolved directory, and if so, 421 // we can mark this object as resolved to avoid more future resolves 422 rhs.m_is_resolved = (rhs.m_directory == resolved_rhs.m_directory); 423 } 424 else 425 return false; 426 } 427 428 // If we reach this point in the code we were able to resolve both paths 429 // and since we only resolve the paths if the basenames are equal, then 430 // we can just check if both directories are equal... 431 return resolved_lhs.GetDirectory() == resolved_rhs.GetDirectory(); 432 } 433 return false; 434} 435 436//------------------------------------------------------------------ 437// Not equal to operator 438//------------------------------------------------------------------ 439bool 440FileSpec::operator!= (const FileSpec& rhs) const 441{ 442 return !(*this == rhs); 443} 444 445//------------------------------------------------------------------ 446// Less than operator 447//------------------------------------------------------------------ 448bool 449FileSpec::operator< (const FileSpec& rhs) const 450{ 451 return FileSpec::Compare(*this, rhs, true) < 0; 452} 453 454//------------------------------------------------------------------ 455// Dump a FileSpec object to a stream 456//------------------------------------------------------------------ 457Stream& 458lldb_private::operator << (Stream &s, const FileSpec& f) 459{ 460 f.Dump(&s); 461 return s; 462} 463 464//------------------------------------------------------------------ 465// Clear this object by releasing both the directory and filename 466// string values and making them both the empty string. 467//------------------------------------------------------------------ 468void 469FileSpec::Clear() 470{ 471 m_directory.Clear(); 472 m_filename.Clear(); 473} 474 475//------------------------------------------------------------------ 476// Compare two FileSpec objects. If "full" is true, then both 477// the directory and the filename must match. If "full" is false, 478// then the directory names for "a" and "b" are only compared if 479// they are both non-empty. This allows a FileSpec object to only 480// contain a filename and it can match FileSpec objects that have 481// matching filenames with different paths. 482// 483// Return -1 if the "a" is less than "b", 0 if "a" is equal to "b" 484// and "1" if "a" is greater than "b". 485//------------------------------------------------------------------ 486int 487FileSpec::Compare(const FileSpec& a, const FileSpec& b, bool full) 488{ 489 int result = 0; 490 491 // If full is true, then we must compare both the directory and filename. 492 493 // If full is false, then if either directory is empty, then we match on 494 // the basename only, and if both directories have valid values, we still 495 // do a full compare. This allows for matching when we just have a filename 496 // in one of the FileSpec objects. 497 498 if (full || (a.m_directory && b.m_directory)) 499 { 500 result = ConstString::Compare(a.m_directory, b.m_directory); 501 if (result) 502 return result; 503 } 504 return ConstString::Compare (a.m_filename, b.m_filename); 505} 506 507bool 508FileSpec::Equal (const FileSpec& a, const FileSpec& b, bool full) 509{ 510 if (!full && (a.GetDirectory().IsEmpty() || b.GetDirectory().IsEmpty())) 511 return a.m_filename == b.m_filename; 512 else 513 return a == b; 514} 515 516 517 518//------------------------------------------------------------------ 519// Dump the object to the supplied stream. If the object contains 520// a valid directory name, it will be displayed followed by a 521// directory delimiter, and the filename. 522//------------------------------------------------------------------ 523void 524FileSpec::Dump(Stream *s) const 525{ 526 static ConstString g_slash_only ("/"); 527 if (s) 528 { 529 m_directory.Dump(s); 530 if (m_directory && m_directory != g_slash_only) 531 s->PutChar('/'); 532 m_filename.Dump(s); 533 } 534} 535 536//------------------------------------------------------------------ 537// Returns true if the file exists. 538//------------------------------------------------------------------ 539bool 540FileSpec::Exists () const 541{ 542 struct stat file_stats; 543 return GetFileStats (this, &file_stats); 544} 545 546bool 547FileSpec::ResolveExecutableLocation () 548{ 549 if (!m_directory) 550 { 551 const char *file_cstr = m_filename.GetCString(); 552 if (file_cstr) 553 { 554 const std::string file_str (file_cstr); 555 llvm::sys::Path path = llvm::sys::Program::FindProgramByName (file_str); 556 const std::string &path_str = path.str(); 557 llvm::StringRef dir_ref = llvm::sys::path::parent_path(path_str); 558 //llvm::StringRef dir_ref = path.getDirname(); 559 if (! dir_ref.empty()) 560 { 561 // FindProgramByName returns "." if it can't find the file. 562 if (strcmp (".", dir_ref.data()) == 0) 563 return false; 564 565 m_directory.SetCString (dir_ref.data()); 566 if (Exists()) 567 return true; 568 else 569 { 570 // If FindProgramByName found the file, it returns the directory + filename in its return results. 571 // We need to separate them. 572 FileSpec tmp_file (dir_ref.data(), false); 573 if (tmp_file.Exists()) 574 { 575 m_directory = tmp_file.m_directory; 576 return true; 577 } 578 } 579 } 580 } 581 } 582 583 return false; 584} 585 586bool 587FileSpec::ResolvePath () 588{ 589 if (m_is_resolved) 590 return true; // We have already resolved this path 591 592 char path_buf[PATH_MAX]; 593 if (!GetPath (path_buf, PATH_MAX)) 594 return false; 595 // SetFile(...) will set m_is_resolved correctly if it can resolve the path 596 SetFile (path_buf, true); 597 return m_is_resolved; 598} 599 600uint64_t 601FileSpec::GetByteSize() const 602{ 603 struct stat file_stats; 604 if (GetFileStats (this, &file_stats)) 605 return file_stats.st_size; 606 return 0; 607} 608 609FileSpec::FileType 610FileSpec::GetFileType () const 611{ 612 struct stat file_stats; 613 if (GetFileStats (this, &file_stats)) 614 { 615 mode_t file_type = file_stats.st_mode & S_IFMT; 616 switch (file_type) 617 { 618 case S_IFDIR: return eFileTypeDirectory; 619 case S_IFIFO: return eFileTypePipe; 620 case S_IFREG: return eFileTypeRegular; 621 case S_IFSOCK: return eFileTypeSocket; 622 case S_IFLNK: return eFileTypeSymbolicLink; 623 default: 624 break; 625 } 626 return eFileTypeUnknown; 627 } 628 return eFileTypeInvalid; 629} 630 631TimeValue 632FileSpec::GetModificationTime () const 633{ 634 TimeValue mod_time; 635 struct stat file_stats; 636 if (GetFileStats (this, &file_stats)) 637 mod_time.OffsetWithSeconds(file_stats.st_mtime); 638 return mod_time; 639} 640 641//------------------------------------------------------------------ 642// Directory string get accessor. 643//------------------------------------------------------------------ 644ConstString & 645FileSpec::GetDirectory() 646{ 647 return m_directory; 648} 649 650//------------------------------------------------------------------ 651// Directory string const get accessor. 652//------------------------------------------------------------------ 653const ConstString & 654FileSpec::GetDirectory() const 655{ 656 return m_directory; 657} 658 659//------------------------------------------------------------------ 660// Filename string get accessor. 661//------------------------------------------------------------------ 662ConstString & 663FileSpec::GetFilename() 664{ 665 return m_filename; 666} 667 668//------------------------------------------------------------------ 669// Filename string const get accessor. 670//------------------------------------------------------------------ 671const ConstString & 672FileSpec::GetFilename() const 673{ 674 return m_filename; 675} 676 677//------------------------------------------------------------------ 678// Extract the directory and path into a fixed buffer. This is 679// needed as the directory and path are stored in separate string 680// values. 681//------------------------------------------------------------------ 682size_t 683FileSpec::GetPath(char *path, size_t path_max_len) const 684{ 685 if (path_max_len) 686 { 687 const char *dirname = m_directory.GetCString(); 688 const char *filename = m_filename.GetCString(); 689 if (dirname) 690 { 691 if (filename) 692 return ::snprintf (path, path_max_len, "%s/%s", dirname, filename); 693 else 694 return ::snprintf (path, path_max_len, "%s", dirname); 695 } 696 else if (filename) 697 { 698 return ::snprintf (path, path_max_len, "%s", filename); 699 } 700 } 701 if (path) 702 path[0] = '\0'; 703 return 0; 704} 705 706std::string 707FileSpec::GetPath (void) const 708{ 709 static ConstString g_slash_only ("/"); 710 std::string path; 711 const char *dirname = m_directory.GetCString(); 712 const char *filename = m_filename.GetCString(); 713 if (dirname) 714 { 715 path.append (dirname); 716 if (filename && m_directory != g_slash_only) 717 path.append ("/"); 718 } 719 if (filename) 720 path.append (filename); 721 return path; 722} 723 724ConstString 725FileSpec::GetFileNameExtension () const 726{ 727 if (m_filename) 728 { 729 const char *filename = m_filename.GetCString(); 730 const char* dot_pos = strrchr(filename, '.'); 731 if (dot_pos && dot_pos[1] != '\0') 732 return ConstString(dot_pos+1); 733 } 734 return ConstString(); 735} 736 737ConstString 738FileSpec::GetFileNameStrippingExtension () const 739{ 740 const char *filename = m_filename.GetCString(); 741 if (filename == NULL) 742 return ConstString(); 743 744 const char* dot_pos = strrchr(filename, '.'); 745 if (dot_pos == NULL) 746 return m_filename; 747 748 return ConstString(filename, dot_pos-filename); 749} 750 751//------------------------------------------------------------------ 752// Returns a shared pointer to a data buffer that contains all or 753// part of the contents of a file. The data is memory mapped and 754// will lazily page in data from the file as memory is accessed. 755// The data that is mappped will start "file_offset" bytes into the 756// file, and "file_size" bytes will be mapped. If "file_size" is 757// greater than the number of bytes available in the file starting 758// at "file_offset", the number of bytes will be appropriately 759// truncated. The final number of bytes that get mapped can be 760// verified using the DataBuffer::GetByteSize() function. 761//------------------------------------------------------------------ 762DataBufferSP 763FileSpec::MemoryMapFileContents(off_t file_offset, size_t file_size) const 764{ 765 DataBufferSP data_sp; 766 std::unique_ptr<DataBufferMemoryMap> mmap_data(new DataBufferMemoryMap()); 767 if (mmap_data.get()) 768 { 769 const size_t mapped_length = mmap_data->MemoryMapFromFileSpec (this, file_offset, file_size); 770 if (((file_size == SIZE_MAX) && (mapped_length > 0)) || (mapped_length >= file_size)) 771 data_sp.reset(mmap_data.release()); 772 } 773 return data_sp; 774} 775 776 777//------------------------------------------------------------------ 778// Return the size in bytes that this object takes in memory. This 779// returns the size in bytes of this object, not any shared string 780// values it may refer to. 781//------------------------------------------------------------------ 782size_t 783FileSpec::MemorySize() const 784{ 785 return m_filename.MemorySize() + m_directory.MemorySize(); 786} 787 788 789size_t 790FileSpec::ReadFileContents (off_t file_offset, void *dst, size_t dst_len, Error *error_ptr) const 791{ 792 Error error; 793 size_t bytes_read = 0; 794 char resolved_path[PATH_MAX]; 795 if (GetPath(resolved_path, sizeof(resolved_path))) 796 { 797 File file; 798 error = file.Open(resolved_path, File::eOpenOptionRead); 799 if (error.Success()) 800 { 801 off_t file_offset_after_seek = file_offset; 802 bytes_read = dst_len; 803 error = file.Read(dst, bytes_read, file_offset_after_seek); 804 } 805 } 806 else 807 { 808 error.SetErrorString("invalid file specification"); 809 } 810 if (error_ptr) 811 *error_ptr = error; 812 return bytes_read; 813} 814 815//------------------------------------------------------------------ 816// Returns a shared pointer to a data buffer that contains all or 817// part of the contents of a file. The data copies into a heap based 818// buffer that lives in the DataBuffer shared pointer object returned. 819// The data that is cached will start "file_offset" bytes into the 820// file, and "file_size" bytes will be mapped. If "file_size" is 821// greater than the number of bytes available in the file starting 822// at "file_offset", the number of bytes will be appropriately 823// truncated. The final number of bytes that get mapped can be 824// verified using the DataBuffer::GetByteSize() function. 825//------------------------------------------------------------------ 826DataBufferSP 827FileSpec::ReadFileContents (off_t file_offset, size_t file_size, Error *error_ptr) const 828{ 829 Error error; 830 DataBufferSP data_sp; 831 char resolved_path[PATH_MAX]; 832 if (GetPath(resolved_path, sizeof(resolved_path))) 833 { 834 File file; 835 error = file.Open(resolved_path, File::eOpenOptionRead); 836 if (error.Success()) 837 { 838 const bool null_terminate = false; 839 error = file.Read (file_size, file_offset, null_terminate, data_sp); 840 } 841 } 842 else 843 { 844 error.SetErrorString("invalid file specification"); 845 } 846 if (error_ptr) 847 *error_ptr = error; 848 return data_sp; 849} 850 851DataBufferSP 852FileSpec::ReadFileContentsAsCString(Error *error_ptr) 853{ 854 Error error; 855 DataBufferSP data_sp; 856 char resolved_path[PATH_MAX]; 857 if (GetPath(resolved_path, sizeof(resolved_path))) 858 { 859 File file; 860 error = file.Open(resolved_path, File::eOpenOptionRead); 861 if (error.Success()) 862 { 863 off_t offset = 0; 864 size_t length = SIZE_MAX; 865 const bool null_terminate = true; 866 error = file.Read (length, offset, null_terminate, data_sp); 867 } 868 } 869 else 870 { 871 error.SetErrorString("invalid file specification"); 872 } 873 if (error_ptr) 874 *error_ptr = error; 875 return data_sp; 876} 877 878size_t 879FileSpec::ReadFileLines (STLStringArray &lines) 880{ 881 lines.clear(); 882 char path[PATH_MAX]; 883 if (GetPath(path, sizeof(path))) 884 { 885 std::ifstream file_stream (path); 886 887 if (file_stream) 888 { 889 std::string line; 890 while (getline (file_stream, line)) 891 lines.push_back (line); 892 } 893 } 894 return lines.size(); 895} 896 897FileSpec::EnumerateDirectoryResult 898FileSpec::EnumerateDirectory 899( 900 const char *dir_path, 901 bool find_directories, 902 bool find_files, 903 bool find_other, 904 EnumerateDirectoryCallbackType callback, 905 void *callback_baton 906) 907{ 908 if (dir_path && dir_path[0]) 909 { 910 lldb_utility::CleanUp <DIR *, int> dir_path_dir (opendir(dir_path), NULL, closedir); 911 if (dir_path_dir.is_valid()) 912 { 913 long path_max = fpathconf (dirfd (dir_path_dir.get()), _PC_NAME_MAX); 914#if defined (__APPLE_) && defined (__DARWIN_MAXPATHLEN) 915 if (path_max < __DARWIN_MAXPATHLEN) 916 path_max = __DARWIN_MAXPATHLEN; 917#endif 918 struct dirent *buf, *dp; 919 buf = (struct dirent *) malloc (offsetof (struct dirent, d_name) + path_max + 1); 920 921 while (buf && readdir_r(dir_path_dir.get(), buf, &dp) == 0 && dp) 922 { 923 // Only search directories 924 if (dp->d_type == DT_DIR || dp->d_type == DT_UNKNOWN) 925 { 926 size_t len = strlen(dp->d_name); 927 928 if (len == 1 && dp->d_name[0] == '.') 929 continue; 930 931 if (len == 2 && dp->d_name[0] == '.' && dp->d_name[1] == '.') 932 continue; 933 } 934 935 bool call_callback = false; 936 FileSpec::FileType file_type = eFileTypeUnknown; 937 938 switch (dp->d_type) 939 { 940 default: 941 case DT_UNKNOWN: file_type = eFileTypeUnknown; call_callback = true; break; 942 case DT_FIFO: file_type = eFileTypePipe; call_callback = find_other; break; 943 case DT_CHR: file_type = eFileTypeOther; call_callback = find_other; break; 944 case DT_DIR: file_type = eFileTypeDirectory; call_callback = find_directories; break; 945 case DT_BLK: file_type = eFileTypeOther; call_callback = find_other; break; 946 case DT_REG: file_type = eFileTypeRegular; call_callback = find_files; break; 947 case DT_LNK: file_type = eFileTypeSymbolicLink; call_callback = find_other; break; 948 case DT_SOCK: file_type = eFileTypeSocket; call_callback = find_other; break; 949#if !defined(__OpenBSD__) 950 case DT_WHT: file_type = eFileTypeOther; call_callback = find_other; break; 951#endif 952 } 953 954 if (call_callback) 955 { 956 char child_path[PATH_MAX]; 957 const int child_path_len = ::snprintf (child_path, sizeof(child_path), "%s/%s", dir_path, dp->d_name); 958 if (child_path_len < (int)(sizeof(child_path) - 1)) 959 { 960 // Don't resolve the file type or path 961 FileSpec child_path_spec (child_path, false); 962 963 EnumerateDirectoryResult result = callback (callback_baton, file_type, child_path_spec); 964 965 switch (result) 966 { 967 case eEnumerateDirectoryResultNext: 968 // Enumerate next entry in the current directory. We just 969 // exit this switch and will continue enumerating the 970 // current directory as we currently are... 971 break; 972 973 case eEnumerateDirectoryResultEnter: // Recurse into the current entry if it is a directory or symlink, or next if not 974 if (FileSpec::EnumerateDirectory (child_path, 975 find_directories, 976 find_files, 977 find_other, 978 callback, 979 callback_baton) == eEnumerateDirectoryResultQuit) 980 { 981 // The subdirectory returned Quit, which means to 982 // stop all directory enumerations at all levels. 983 return eEnumerateDirectoryResultQuit; 984 } 985 break; 986 987 case eEnumerateDirectoryResultExit: // Exit from the current directory at the current level. 988 // Exit from this directory level and tell parent to 989 // keep enumerating. 990 if (buf) 991 free (buf); 992 return eEnumerateDirectoryResultNext; 993 994 case eEnumerateDirectoryResultQuit: // Stop directory enumerations at any level 995 if (buf) 996 free (buf); 997 return eEnumerateDirectoryResultQuit; 998 } 999 } 1000 } 1001 } 1002 if (buf) 1003 { 1004 free (buf); 1005 } 1006 } 1007 } 1008 // By default when exiting a directory, we tell the parent enumeration 1009 // to continue enumerating. 1010 return eEnumerateDirectoryResultNext; 1011} 1012 1013//------------------------------------------------------------------ 1014/// Returns true if the filespec represents an implementation source 1015/// file (files with a ".c", ".cpp", ".m", ".mm" (many more) 1016/// extension). 1017/// 1018/// @return 1019/// \b true if the filespec represents an implementation source 1020/// file, \b false otherwise. 1021//------------------------------------------------------------------ 1022bool 1023FileSpec::IsSourceImplementationFile () const 1024{ 1025 ConstString extension (GetFileNameExtension()); 1026 if (extension) 1027 { 1028 static RegularExpression g_source_file_regex ("^(c|m|mm|cpp|c\\+\\+|cxx|cc|cp|s|asm|f|f77|f90|f95|f03|for|ftn|fpp|ada|adb|ads)$", 1029 REG_EXTENDED | REG_ICASE); 1030 return g_source_file_regex.Execute (extension.GetCString()); 1031 } 1032 return false; 1033} 1034 1035bool 1036FileSpec::IsRelativeToCurrentWorkingDirectory () const 1037{ 1038 const char *directory = m_directory.GetCString(); 1039 if (directory && directory[0]) 1040 { 1041 // If the path doesn't start with '/' or '~', return true 1042 switch (directory[0]) 1043 { 1044 case '/': 1045 case '~': 1046 return false; 1047 default: 1048 return true; 1049 } 1050 } 1051 else if (m_filename) 1052 { 1053 // No directory, just a basename, return true 1054 return true; 1055 } 1056 return false; 1057} 1058