1 //===-- FileSpec.cpp --------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
13 #include "lldb/Host/windows/windows.h"
23 #include "lldb/Host/Config.h" // Have to include this before we test the define...
24 #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
28 #include "lldb/Core/ArchSpec.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/Core/StreamString.h"
34 #include "lldb/Host/File.h"
35 #include "lldb/Host/FileSpec.h"
36 #include "lldb/Host/FileSystem.h"
37 #include "lldb/Host/Host.h"
38 #include "lldb/Utility/CleanUp.h"
40 #include "llvm/ADT/StringExtras.h"
41 #include "llvm/ADT/StringRef.h"
42 #include "llvm/Support/ConvertUTF.h"
43 #include "llvm/Support/FileSystem.h"
44 #include "llvm/Support/Path.h"
45 #include "llvm/Support/Program.h"
48 using namespace lldb_private;
52 bool PathSyntaxIsPosix(FileSpec::PathSyntax syntax) {
53 return (syntax == FileSpec::ePathSyntaxPosix ||
54 (syntax == FileSpec::ePathSyntaxHostNative &&
55 FileSystem::GetNativePathSyntax() == FileSpec::ePathSyntaxPosix));
58 const char *GetPathSeparators(FileSpec::PathSyntax syntax) {
59 return PathSyntaxIsPosix(syntax) ? "/" : "\\/";
62 char GetPreferredPathSeparator(FileSpec::PathSyntax syntax) {
63 return GetPathSeparators(syntax)[0];
66 bool IsPathSeparator(char value, FileSpec::PathSyntax syntax) {
67 return value == '/' || (!PathSyntaxIsPosix(syntax) && value == '\\');
70 void Normalize(llvm::SmallVectorImpl<char> &path, FileSpec::PathSyntax syntax) {
71 if (PathSyntaxIsPosix(syntax))
74 std::replace(path.begin(), path.end(), '\\', '/');
75 // Windows path can have \\ slashes which can be changed by replace
76 // call above to //. Here we remove the duplicate.
77 auto iter = std::unique(path.begin(), path.end(), [](char &c1, char &c2) {
78 return (c1 == '/' && c2 == '/');
80 path.erase(iter, path.end());
83 void Denormalize(llvm::SmallVectorImpl<char> &path,
84 FileSpec::PathSyntax syntax) {
85 if (PathSyntaxIsPosix(syntax))
88 std::replace(path.begin(), path.end(), '/', '\\');
91 bool GetFileStats(const FileSpec *file_spec, struct stat *stats_ptr) {
92 char resolved_path[PATH_MAX];
93 if (file_spec->GetPath(resolved_path, sizeof(resolved_path)))
94 return FileSystem::Stat(resolved_path, stats_ptr) == 0;
98 size_t FilenamePos(llvm::StringRef str, FileSpec::PathSyntax syntax) {
99 if (str.size() == 2 && IsPathSeparator(str[0], syntax) && str[0] == str[1])
102 if (str.size() > 0 && IsPathSeparator(str.back(), syntax))
103 return str.size() - 1;
105 size_t pos = str.find_last_of(GetPathSeparators(syntax), str.size() - 1);
107 if (!PathSyntaxIsPosix(syntax) && pos == llvm::StringRef::npos)
108 pos = str.find_last_of(':', str.size() - 2);
110 if (pos == llvm::StringRef::npos ||
111 (pos == 1 && IsPathSeparator(str[0], syntax)))
117 size_t RootDirStart(llvm::StringRef str, FileSpec::PathSyntax syntax) {
119 if (!PathSyntaxIsPosix(syntax) &&
120 (str.size() > 2 && str[1] == ':' && IsPathSeparator(str[2], syntax)))
124 if (str.size() == 2 && IsPathSeparator(str[0], syntax) && str[0] == str[1])
125 return llvm::StringRef::npos;
128 if (str.size() > 3 && IsPathSeparator(str[0], syntax) && str[0] == str[1] &&
129 !IsPathSeparator(str[2], syntax))
130 return str.find_first_of(GetPathSeparators(syntax), 2);
133 if (str.size() > 0 && IsPathSeparator(str[0], syntax))
136 return llvm::StringRef::npos;
139 size_t ParentPathEnd(llvm::StringRef path, FileSpec::PathSyntax syntax) {
140 size_t end_pos = FilenamePos(path, syntax);
142 bool filename_was_sep =
143 path.size() > 0 && IsPathSeparator(path[end_pos], syntax);
145 // Skip separators except for root dir.
146 size_t root_dir_pos = RootDirStart(path.substr(0, end_pos), syntax);
148 while (end_pos > 0 && (end_pos - 1) != root_dir_pos &&
149 IsPathSeparator(path[end_pos - 1], syntax))
152 if (end_pos == 1 && root_dir_pos == 0 && filename_was_sep)
153 return llvm::StringRef::npos;
158 } // end anonymous namespace
160 // Resolves the username part of a path of the form ~user/other/directories, and
161 // writes the result into dst_path. This will also resolve "~" to the current
163 // If you want to complete "~" to the list of users, pass it to
164 // ResolvePartialUsername.
165 void FileSpec::ResolveUsername(llvm::SmallVectorImpl<char> &path) {
166 #if LLDB_CONFIG_TILDE_RESOLVES_TO_USER
167 if (path.empty() || path[0] != '~')
170 llvm::StringRef path_str(path.data(), path.size());
171 size_t slash_pos = path_str.find('/', 1);
172 if (slash_pos == 1 || path.size() == 1) {
173 // A path of ~/ resolves to the current user's home dir
174 llvm::SmallString<64> home_dir;
175 // llvm::sys::path::home_directory() only checks if "HOME" is set in the
176 // environment and does nothing else to locate the user home directory
177 if (!llvm::sys::path::home_directory(home_dir)) {
178 struct passwd *pw = getpwuid(getuid());
179 if (pw && pw->pw_dir && pw->pw_dir[0]) {
180 // Update our environemnt so llvm::sys::path::home_directory() works
182 setenv("HOME", pw->pw_dir, 0);
183 home_dir.assign(llvm::StringRef(pw->pw_dir));
189 // Overwrite the ~ with the first character of the homedir, and insert
190 // the rest. This way we only trigger one move, whereas an insert
191 // followed by a delete (or vice versa) would trigger two.
192 path[0] = home_dir[0];
193 path.insert(path.begin() + 1, home_dir.begin() + 1, home_dir.end());
197 auto username_begin = path.begin() + 1;
198 auto username_end = (slash_pos == llvm::StringRef::npos)
200 : (path.begin() + slash_pos);
201 size_t replacement_length = std::distance(path.begin(), username_end);
203 llvm::SmallString<20> username(username_begin, username_end);
204 struct passwd *user_entry = ::getpwnam(username.c_str());
205 if (user_entry != nullptr) {
206 // Copy over the first n characters of the path, where n is the smaller of
208 // of the home directory and the slash pos.
209 llvm::StringRef homedir(user_entry->pw_dir);
210 size_t initial_copy_length = std::min(homedir.size(), replacement_length);
211 auto src_begin = homedir.begin();
212 auto src_end = src_begin + initial_copy_length;
213 std::copy(src_begin, src_end, path.begin());
214 if (replacement_length > homedir.size()) {
215 // We copied the entire home directory, but the ~username portion of the
217 // longer, so there's characters that need to be removed.
218 path.erase(path.begin() + initial_copy_length, username_end);
219 } else if (replacement_length < homedir.size()) {
220 // We copied all the way up to the slash in the destination, but there's
222 // characters that need to be inserted.
223 path.insert(username_end, src_end, homedir.end());
226 // Unable to resolve username (user doesn't exist?)
232 size_t FileSpec::ResolvePartialUsername(llvm::StringRef partial_name,
233 StringList &matches) {
234 #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
235 size_t extant_entries = matches.GetSize();
238 struct passwd *user_entry;
239 partial_name = partial_name.drop_front();
240 std::set<std::string> name_list;
242 while ((user_entry = getpwent()) != NULL) {
243 if (llvm::StringRef(user_entry->pw_name).startswith(partial_name)) {
244 std::string tmp_buf("~");
245 tmp_buf.append(user_entry->pw_name);
246 tmp_buf.push_back('/');
247 name_list.insert(tmp_buf);
251 for (auto &name : name_list) {
252 matches.AppendString(name);
254 return matches.GetSize() - extant_entries;
256 // Resolving home directories is not supported, just copy the path...
258 #endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
261 void FileSpec::Resolve(llvm::SmallVectorImpl<char> &path) {
265 #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
267 ResolveUsername(path);
268 #endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
270 // Save a copy of the original path that's passed in
271 llvm::SmallString<128> original_path(path.begin(), path.end());
273 llvm::sys::fs::make_absolute(path);
274 if (!llvm::sys::fs::exists(path)) {
276 path.append(original_path.begin(), original_path.end());
280 FileSpec::FileSpec() : m_syntax(FileSystem::GetNativePathSyntax()) {}
282 //------------------------------------------------------------------
283 // Default constructor that can take an optional full path to a
285 //------------------------------------------------------------------
286 FileSpec::FileSpec(llvm::StringRef path, bool resolve_path, PathSyntax syntax)
288 SetFile(path, resolve_path, syntax);
291 FileSpec::FileSpec(llvm::StringRef path, bool resolve_path, ArchSpec arch)
292 : FileSpec{path, resolve_path, arch.GetTriple().isOSWindows()
294 : ePathSyntaxPosix} {}
296 //------------------------------------------------------------------
298 //------------------------------------------------------------------
299 FileSpec::FileSpec(const FileSpec &rhs)
300 : m_directory(rhs.m_directory), m_filename(rhs.m_filename),
301 m_is_resolved(rhs.m_is_resolved), m_syntax(rhs.m_syntax) {}
303 //------------------------------------------------------------------
305 //------------------------------------------------------------------
306 FileSpec::FileSpec(const FileSpec *rhs) : m_directory(), m_filename() {
311 //------------------------------------------------------------------
312 // Virtual destructor in case anyone inherits from this class.
313 //------------------------------------------------------------------
314 FileSpec::~FileSpec() {}
316 //------------------------------------------------------------------
317 // Assignment operator.
318 //------------------------------------------------------------------
319 const FileSpec &FileSpec::operator=(const FileSpec &rhs) {
321 m_directory = rhs.m_directory;
322 m_filename = rhs.m_filename;
323 m_is_resolved = rhs.m_is_resolved;
324 m_syntax = rhs.m_syntax;
329 //------------------------------------------------------------------
330 // Update the contents of this object with a new path. The path will
331 // be split up into a directory and filename and stored as uniqued
332 // string values for quick comparison and efficient memory usage.
333 //------------------------------------------------------------------
334 void FileSpec::SetFile(llvm::StringRef pathname, bool resolve,
336 // CLEANUP: Use StringRef for string handling. This function is kind of a
337 // mess and the unclear semantics of RootDirStart and ParentPathEnd make
338 // it very difficult to understand this function. There's no reason this
339 // function should be particularly complicated or difficult to understand.
342 m_is_resolved = false;
343 m_syntax = (syntax == ePathSyntaxHostNative)
344 ? FileSystem::GetNativePathSyntax()
347 if (pathname.empty())
350 llvm::SmallString<64> resolved(pathname);
353 FileSpec::Resolve(resolved);
354 m_is_resolved = true;
357 Normalize(resolved, m_syntax);
359 llvm::StringRef resolve_path_ref(resolved.c_str());
360 size_t dir_end = ParentPathEnd(resolve_path_ref, m_syntax);
362 m_filename.SetString(resolve_path_ref);
366 m_directory.SetString(resolve_path_ref.substr(0, dir_end));
368 size_t filename_begin = dir_end;
369 size_t root_dir_start = RootDirStart(resolve_path_ref, m_syntax);
370 while (filename_begin != llvm::StringRef::npos &&
371 filename_begin < resolve_path_ref.size() &&
372 filename_begin != root_dir_start &&
373 IsPathSeparator(resolve_path_ref[filename_begin], m_syntax))
375 m_filename.SetString((filename_begin == llvm::StringRef::npos ||
376 filename_begin >= resolve_path_ref.size())
378 : resolve_path_ref.substr(filename_begin));
381 void FileSpec::SetFile(llvm::StringRef path, bool resolve, ArchSpec arch) {
382 return SetFile(path, resolve, arch.GetTriple().isOSWindows()
387 //----------------------------------------------------------------------
388 // Convert to pointer operator. This allows code to check any FileSpec
389 // objects to see if they contain anything valid using code such as:
393 //----------------------------------------------------------------------
394 FileSpec::operator bool() const { return m_filename || m_directory; }
396 //----------------------------------------------------------------------
397 // Logical NOT operator. This allows code to check any FileSpec
398 // objects to see if they are invalid using code such as:
402 //----------------------------------------------------------------------
403 bool FileSpec::operator!() const { return !m_directory && !m_filename; }
405 bool FileSpec::DirectoryEquals(const FileSpec &rhs) const {
406 const bool case_sensitive = IsCaseSensitive() || rhs.IsCaseSensitive();
407 return ConstString::Equals(m_directory, rhs.m_directory, case_sensitive);
410 bool FileSpec::FileEquals(const FileSpec &rhs) const {
411 const bool case_sensitive = IsCaseSensitive() || rhs.IsCaseSensitive();
412 return ConstString::Equals(m_filename, rhs.m_filename, case_sensitive);
415 //------------------------------------------------------------------
417 //------------------------------------------------------------------
418 bool FileSpec::operator==(const FileSpec &rhs) const {
419 if (!FileEquals(rhs))
421 if (DirectoryEquals(rhs))
424 // TODO: determine if we want to keep this code in here.
425 // The code below was added to handle a case where we were
426 // trying to set a file and line breakpoint and one path
427 // was resolved, and the other not and the directory was
428 // in a mount point that resolved to a more complete path:
429 // "/tmp/a.c" == "/private/tmp/a.c". I might end up pulling
431 if (IsResolved() && rhs.IsResolved()) {
432 // Both paths are resolved, no need to look further...
436 FileSpec resolved_lhs(*this);
438 // If "this" isn't resolved, resolve it
440 if (resolved_lhs.ResolvePath()) {
441 // This path wasn't resolved but now it is. Check if the resolved
442 // directory is the same as our unresolved directory, and if so,
443 // we can mark this object as resolved to avoid more future resolves
444 m_is_resolved = (m_directory == resolved_lhs.m_directory);
449 FileSpec resolved_rhs(rhs);
450 if (!rhs.IsResolved()) {
451 if (resolved_rhs.ResolvePath()) {
452 // rhs's path wasn't resolved but now it is. Check if the resolved
453 // directory is the same as rhs's unresolved directory, and if so,
454 // we can mark this object as resolved to avoid more future resolves
455 rhs.m_is_resolved = (rhs.m_directory == resolved_rhs.m_directory);
460 // If we reach this point in the code we were able to resolve both paths
461 // and since we only resolve the paths if the basenames are equal, then
462 // we can just check if both directories are equal...
463 return DirectoryEquals(rhs);
466 //------------------------------------------------------------------
467 // Not equal to operator
468 //------------------------------------------------------------------
469 bool FileSpec::operator!=(const FileSpec &rhs) const { return !(*this == rhs); }
471 //------------------------------------------------------------------
472 // Less than operator
473 //------------------------------------------------------------------
474 bool FileSpec::operator<(const FileSpec &rhs) const {
475 return FileSpec::Compare(*this, rhs, true) < 0;
478 //------------------------------------------------------------------
479 // Dump a FileSpec object to a stream
480 //------------------------------------------------------------------
481 Stream &lldb_private::operator<<(Stream &s, const FileSpec &f) {
486 //------------------------------------------------------------------
487 // Clear this object by releasing both the directory and filename
488 // string values and making them both the empty string.
489 //------------------------------------------------------------------
490 void FileSpec::Clear() {
495 //------------------------------------------------------------------
496 // Compare two FileSpec objects. If "full" is true, then both
497 // the directory and the filename must match. If "full" is false,
498 // then the directory names for "a" and "b" are only compared if
499 // they are both non-empty. This allows a FileSpec object to only
500 // contain a filename and it can match FileSpec objects that have
501 // matching filenames with different paths.
503 // Return -1 if the "a" is less than "b", 0 if "a" is equal to "b"
504 // and "1" if "a" is greater than "b".
505 //------------------------------------------------------------------
506 int FileSpec::Compare(const FileSpec &a, const FileSpec &b, bool full) {
509 // case sensitivity of compare
510 const bool case_sensitive = a.IsCaseSensitive() || b.IsCaseSensitive();
512 // If full is true, then we must compare both the directory and filename.
514 // If full is false, then if either directory is empty, then we match on
515 // the basename only, and if both directories have valid values, we still
516 // do a full compare. This allows for matching when we just have a filename
517 // in one of the FileSpec objects.
519 if (full || (a.m_directory && b.m_directory)) {
520 result = ConstString::Compare(a.m_directory, b.m_directory, case_sensitive);
524 return ConstString::Compare(a.m_filename, b.m_filename, case_sensitive);
527 bool FileSpec::Equal(const FileSpec &a, const FileSpec &b, bool full,
528 bool remove_backups) {
529 // case sensitivity of equality test
530 const bool case_sensitive = a.IsCaseSensitive() || b.IsCaseSensitive();
532 if (!full && (a.GetDirectory().IsEmpty() || b.GetDirectory().IsEmpty()))
533 return ConstString::Equals(a.m_filename, b.m_filename, case_sensitive);
535 if (remove_backups == false)
541 return Equal(a.GetNormalizedPath(), b.GetNormalizedPath(), full, false);
544 FileSpec FileSpec::GetNormalizedPath() const {
545 // Fast path. Do nothing if the path is not interesting.
546 if (!m_directory.GetStringRef().contains(".") &&
547 !m_directory.GetStringRef().contains("//") &&
548 m_filename.GetStringRef() != ".." && m_filename.GetStringRef() != ".")
551 llvm::SmallString<64> path, result;
552 const bool normalize = false;
553 GetPath(path, normalize);
554 llvm::StringRef rest(path);
556 // We will not go below root dir.
557 size_t root_dir_start = RootDirStart(path, m_syntax);
558 const bool absolute = root_dir_start != llvm::StringRef::npos;
560 result += rest.take_front(root_dir_start + 1);
561 rest = rest.drop_front(root_dir_start + 1);
563 if (m_syntax == ePathSyntaxWindows && path.size() > 2 && path[1] == ':') {
564 result += rest.take_front(2);
565 rest = rest.drop_front(2);
569 bool anything_added = false;
570 llvm::SmallVector<llvm::StringRef, 0> components, processed;
571 rest.split(components, '/', -1, false);
572 processed.reserve(components.size());
573 for (auto component : components) {
574 if (component == ".")
575 continue; // Skip these.
576 if (component != "..") {
577 processed.push_back(component);
578 continue; // Regular file name.
580 if (!processed.empty()) {
581 processed.pop_back();
582 continue; // Dots. Go one level up if we can.
585 continue; // We're at the top level. Cannot go higher than that. Skip.
587 result += component; // We're a relative path. We need to keep these.
589 anything_added = true;
591 for (auto component : processed) {
594 anything_added = true;
597 result.pop_back(); // Pop last '/'.
598 else if (result.empty())
601 return FileSpec(result, false, m_syntax);
604 //------------------------------------------------------------------
605 // Dump the object to the supplied stream. If the object contains
606 // a valid directory name, it will be displayed followed by a
607 // directory delimiter, and the filename.
608 //------------------------------------------------------------------
609 void FileSpec::Dump(Stream *s) const {
611 std::string path{GetPath(true)};
613 char path_separator = GetPreferredPathSeparator(m_syntax);
614 if (!m_filename && !path.empty() && path.back() != path_separator)
615 s->PutChar(path_separator);
619 //------------------------------------------------------------------
620 // Returns true if the file exists.
621 //------------------------------------------------------------------
622 bool FileSpec::Exists() const {
623 struct stat file_stats;
624 return GetFileStats(this, &file_stats);
627 bool FileSpec::Readable() const {
628 const uint32_t permissions = GetPermissions();
629 if (permissions & eFilePermissionsEveryoneR)
634 bool FileSpec::ResolveExecutableLocation() {
635 // CLEANUP: Use StringRef for string handling.
637 const char *file_cstr = m_filename.GetCString();
639 const std::string file_str(file_cstr);
640 llvm::ErrorOr<std::string> error_or_path =
641 llvm::sys::findProgramByName(file_str);
644 std::string path = error_or_path.get();
645 llvm::StringRef dir_ref = llvm::sys::path::parent_path(path);
646 if (!dir_ref.empty()) {
647 // FindProgramByName returns "." if it can't find the file.
648 if (strcmp(".", dir_ref.data()) == 0)
651 m_directory.SetCString(dir_ref.data());
655 // If FindProgramByName found the file, it returns the directory +
656 // filename in its return results.
657 // We need to separate them.
658 FileSpec tmp_file(dir_ref.data(), false);
659 if (tmp_file.Exists()) {
660 m_directory = tmp_file.m_directory;
671 bool FileSpec::ResolvePath() {
673 return true; // We have already resolved this path
675 char path_buf[PATH_MAX];
676 if (!GetPath(path_buf, PATH_MAX, false))
678 // SetFile(...) will set m_is_resolved correctly if it can resolve the path
679 SetFile(path_buf, true);
680 return m_is_resolved;
683 uint64_t FileSpec::GetByteSize() const {
684 struct stat file_stats;
685 if (GetFileStats(this, &file_stats))
686 return file_stats.st_size;
690 FileSpec::PathSyntax FileSpec::GetPathSyntax() const { return m_syntax; }
692 FileSpec::FileType FileSpec::GetFileType() const {
693 struct stat file_stats;
694 if (GetFileStats(this, &file_stats)) {
695 mode_t file_type = file_stats.st_mode & S_IFMT;
698 return eFileTypeDirectory;
700 return eFileTypeRegular;
703 return eFileTypePipe;
705 return eFileTypeSocket;
707 return eFileTypeSymbolicLink;
712 return eFileTypeUnknown;
714 return eFileTypeInvalid;
717 bool FileSpec::IsSymbolicLink() const {
718 char resolved_path[PATH_MAX];
719 if (!GetPath(resolved_path, sizeof(resolved_path)))
724 if (!llvm::ConvertUTF8toWide(resolved_path, wpath))
726 auto attrs = ::GetFileAttributesW(wpath.c_str());
727 if (attrs == INVALID_FILE_ATTRIBUTES)
730 return (attrs & FILE_ATTRIBUTE_REPARSE_POINT);
732 struct stat file_stats;
733 if (::lstat(resolved_path, &file_stats) != 0)
736 return (file_stats.st_mode & S_IFMT) == S_IFLNK;
740 uint32_t FileSpec::GetPermissions() const {
741 uint32_t file_permissions = 0;
743 FileSystem::GetFilePermissions(*this, file_permissions);
744 return file_permissions;
747 //------------------------------------------------------------------
748 // Directory string get accessor.
749 //------------------------------------------------------------------
750 ConstString &FileSpec::GetDirectory() { return m_directory; }
752 //------------------------------------------------------------------
753 // Directory string const get accessor.
754 //------------------------------------------------------------------
755 const ConstString &FileSpec::GetDirectory() const { return m_directory; }
757 //------------------------------------------------------------------
758 // Filename string get accessor.
759 //------------------------------------------------------------------
760 ConstString &FileSpec::GetFilename() { return m_filename; }
762 //------------------------------------------------------------------
763 // Filename string const get accessor.
764 //------------------------------------------------------------------
765 const ConstString &FileSpec::GetFilename() const { return m_filename; }
767 //------------------------------------------------------------------
768 // Extract the directory and path into a fixed buffer. This is
769 // needed as the directory and path are stored in separate string
771 //------------------------------------------------------------------
772 size_t FileSpec::GetPath(char *path, size_t path_max_len,
773 bool denormalize) const {
777 std::string result = GetPath(denormalize);
778 ::snprintf(path, path_max_len, "%s", result.c_str());
779 return std::min(path_max_len - 1, result.length());
782 std::string FileSpec::GetPath(bool denormalize) const {
783 llvm::SmallString<64> result;
784 GetPath(result, denormalize);
785 return std::string(result.begin(), result.end());
788 const char *FileSpec::GetCString(bool denormalize) const {
789 return ConstString{GetPath(denormalize)}.AsCString(NULL);
792 void FileSpec::GetPath(llvm::SmallVectorImpl<char> &path,
793 bool denormalize) const {
794 path.append(m_directory.GetStringRef().begin(),
795 m_directory.GetStringRef().end());
796 if (m_directory && m_filename &&
797 !IsPathSeparator(m_directory.GetStringRef().back(), m_syntax))
798 path.insert(path.end(), GetPreferredPathSeparator(m_syntax));
799 path.append(m_filename.GetStringRef().begin(),
800 m_filename.GetStringRef().end());
801 Normalize(path, m_syntax);
802 if (denormalize && !path.empty())
803 Denormalize(path, m_syntax);
806 ConstString FileSpec::GetFileNameExtension() const {
808 const char *filename = m_filename.GetCString();
809 const char *dot_pos = strrchr(filename, '.');
810 if (dot_pos && dot_pos[1] != '\0')
811 return ConstString(dot_pos + 1);
813 return ConstString();
816 ConstString FileSpec::GetFileNameStrippingExtension() const {
817 const char *filename = m_filename.GetCString();
818 if (filename == NULL)
819 return ConstString();
821 const char *dot_pos = strrchr(filename, '.');
825 return ConstString(filename, dot_pos - filename);
828 //------------------------------------------------------------------
829 // Returns a shared pointer to a data buffer that contains all or
830 // part of the contents of a file. The data is memory mapped and
831 // will lazily page in data from the file as memory is accessed.
832 // The data that is mapped will start "file_offset" bytes into the
833 // file, and "file_size" bytes will be mapped. If "file_size" is
834 // greater than the number of bytes available in the file starting
835 // at "file_offset", the number of bytes will be appropriately
836 // truncated. The final number of bytes that get mapped can be
837 // verified using the DataBuffer::GetByteSize() function.
838 //------------------------------------------------------------------
839 DataBufferSP FileSpec::MemoryMapFileContents(off_t file_offset,
840 size_t file_size) const {
841 DataBufferSP data_sp;
842 std::unique_ptr<DataBufferMemoryMap> mmap_data(new DataBufferMemoryMap());
843 if (mmap_data.get()) {
844 const size_t mapped_length =
845 mmap_data->MemoryMapFromFileSpec(this, file_offset, file_size);
846 if (((file_size == SIZE_MAX) && (mapped_length > 0)) ||
847 (mapped_length >= file_size))
848 data_sp.reset(mmap_data.release());
853 DataBufferSP FileSpec::MemoryMapFileContentsIfLocal(off_t file_offset,
854 size_t file_size) const {
855 if (FileSystem::IsLocal(*this))
856 return MemoryMapFileContents(file_offset, file_size);
858 return ReadFileContents(file_offset, file_size, NULL);
861 //------------------------------------------------------------------
862 // Return the size in bytes that this object takes in memory. This
863 // returns the size in bytes of this object, not any shared string
864 // values it may refer to.
865 //------------------------------------------------------------------
866 size_t FileSpec::MemorySize() const {
867 return m_filename.MemorySize() + m_directory.MemorySize();
870 size_t FileSpec::ReadFileContents(off_t file_offset, void *dst, size_t dst_len,
871 Error *error_ptr) const {
873 size_t bytes_read = 0;
874 char resolved_path[PATH_MAX];
875 if (GetPath(resolved_path, sizeof(resolved_path))) {
877 error = file.Open(resolved_path, File::eOpenOptionRead);
878 if (error.Success()) {
879 off_t file_offset_after_seek = file_offset;
880 bytes_read = dst_len;
881 error = file.Read(dst, bytes_read, file_offset_after_seek);
884 error.SetErrorString("invalid file specification");
891 //------------------------------------------------------------------
892 // Returns a shared pointer to a data buffer that contains all or
893 // part of the contents of a file. The data copies into a heap based
894 // buffer that lives in the DataBuffer shared pointer object returned.
895 // The data that is cached will start "file_offset" bytes into the
896 // file, and "file_size" bytes will be mapped. If "file_size" is
897 // greater than the number of bytes available in the file starting
898 // at "file_offset", the number of bytes will be appropriately
899 // truncated. The final number of bytes that get mapped can be
900 // verified using the DataBuffer::GetByteSize() function.
901 //------------------------------------------------------------------
902 DataBufferSP FileSpec::ReadFileContents(off_t file_offset, size_t file_size,
903 Error *error_ptr) const {
905 DataBufferSP data_sp;
906 char resolved_path[PATH_MAX];
907 if (GetPath(resolved_path, sizeof(resolved_path))) {
909 error = file.Open(resolved_path, File::eOpenOptionRead);
910 if (error.Success()) {
911 const bool null_terminate = false;
912 error = file.Read(file_size, file_offset, null_terminate, data_sp);
915 error.SetErrorString("invalid file specification");
922 DataBufferSP FileSpec::ReadFileContentsAsCString(Error *error_ptr) {
924 DataBufferSP data_sp;
925 char resolved_path[PATH_MAX];
926 if (GetPath(resolved_path, sizeof(resolved_path))) {
928 error = file.Open(resolved_path, File::eOpenOptionRead);
929 if (error.Success()) {
931 size_t length = SIZE_MAX;
932 const bool null_terminate = true;
933 error = file.Read(length, offset, null_terminate, data_sp);
936 error.SetErrorString("invalid file specification");
943 size_t FileSpec::ReadFileLines(STLStringArray &lines) {
946 if (GetPath(path, sizeof(path))) {
947 std::ifstream file_stream(path);
951 while (getline(file_stream, line))
952 lines.push_back(line);
958 FileSpec::EnumerateDirectoryResult
959 FileSpec::ForEachItemInDirectory(llvm::StringRef dir_path,
960 DirectoryCallback const &callback) {
961 if (dir_path.empty())
962 return eEnumerateDirectoryResultNext;
965 std::string szDir(dir_path);
969 if (!llvm::ConvertUTF8toWide(szDir, wszDir)) {
970 return eEnumerateDirectoryResultNext;
973 WIN32_FIND_DATAW ffd;
974 HANDLE hFind = FindFirstFileW(wszDir.c_str(), &ffd);
976 if (hFind == INVALID_HANDLE_VALUE) {
977 return eEnumerateDirectoryResultNext;
981 FileSpec::FileType file_type = eFileTypeUnknown;
982 if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
983 size_t len = wcslen(ffd.cFileName);
985 if (len == 1 && ffd.cFileName[0] == L'.')
988 if (len == 2 && ffd.cFileName[0] == L'.' && ffd.cFileName[1] == L'.')
991 file_type = eFileTypeDirectory;
992 } else if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DEVICE) {
993 file_type = eFileTypeOther;
995 file_type = eFileTypeRegular;
998 std::string fileName;
999 if (!llvm::convertWideToUTF8(ffd.cFileName, fileName)) {
1003 std::string child_path = llvm::join_items("\\", dir_path, fileName);
1004 // Don't resolve the file type or path
1005 FileSpec child_path_spec(child_path.data(), false);
1007 EnumerateDirectoryResult result = callback(file_type, child_path_spec);
1010 case eEnumerateDirectoryResultNext:
1011 // Enumerate next entry in the current directory. We just
1012 // exit this switch and will continue enumerating the
1013 // current directory as we currently are...
1016 case eEnumerateDirectoryResultEnter: // Recurse into the current entry
1017 // if it is a directory or symlink,
1019 if (FileSpec::ForEachItemInDirectory(child_path.data(), callback) ==
1020 eEnumerateDirectoryResultQuit) {
1021 // The subdirectory returned Quit, which means to
1022 // stop all directory enumerations at all levels.
1023 return eEnumerateDirectoryResultQuit;
1027 case eEnumerateDirectoryResultExit: // Exit from the current directory
1028 // at the current level.
1029 // Exit from this directory level and tell parent to
1030 // keep enumerating.
1031 return eEnumerateDirectoryResultNext;
1033 case eEnumerateDirectoryResultQuit: // Stop directory enumerations at
1035 return eEnumerateDirectoryResultQuit;
1037 } while (FindNextFileW(hFind, &ffd) != 0);
1041 std::string dir_string(dir_path);
1042 lldb_utility::CleanUp<DIR *, int> dir_path_dir(opendir(dir_string.c_str()),
1044 if (dir_path_dir.is_valid()) {
1045 char dir_path_last_char = dir_path.back();
1047 long path_max = fpathconf(dirfd(dir_path_dir.get()), _PC_NAME_MAX);
1048 #if defined(__APPLE_) && defined(__DARWIN_MAXPATHLEN)
1049 if (path_max < __DARWIN_MAXPATHLEN)
1050 path_max = __DARWIN_MAXPATHLEN;
1052 struct dirent *buf, *dp;
1053 buf = (struct dirent *)malloc(offsetof(struct dirent, d_name) + path_max +
1056 while (buf && readdir_r(dir_path_dir.get(), buf, &dp) == 0 && dp) {
1057 // Only search directories
1058 if (dp->d_type == DT_DIR || dp->d_type == DT_UNKNOWN) {
1059 size_t len = strlen(dp->d_name);
1061 if (len == 1 && dp->d_name[0] == '.')
1064 if (len == 2 && dp->d_name[0] == '.' && dp->d_name[1] == '.')
1068 FileSpec::FileType file_type = eFileTypeUnknown;
1070 switch (dp->d_type) {
1073 file_type = eFileTypeUnknown;
1076 file_type = eFileTypePipe;
1079 file_type = eFileTypeOther;
1082 file_type = eFileTypeDirectory;
1085 file_type = eFileTypeOther;
1088 file_type = eFileTypeRegular;
1091 file_type = eFileTypeSymbolicLink;
1094 file_type = eFileTypeSocket;
1096 #if !defined(__OpenBSD__)
1098 file_type = eFileTypeOther;
1103 std::string child_path;
1104 // Don't make paths with "/foo//bar", that just confuses everybody.
1105 if (dir_path_last_char == '/')
1106 child_path = llvm::join_items("", dir_path, dp->d_name);
1108 child_path = llvm::join_items('/', dir_path, dp->d_name);
1110 // Don't resolve the file type or path
1111 FileSpec child_path_spec(child_path, false);
1113 EnumerateDirectoryResult result =
1114 callback(file_type, child_path_spec);
1117 case eEnumerateDirectoryResultNext:
1118 // Enumerate next entry in the current directory. We just
1119 // exit this switch and will continue enumerating the
1120 // current directory as we currently are...
1123 case eEnumerateDirectoryResultEnter: // Recurse into the current entry
1124 // if it is a directory or
1125 // symlink, or next if not
1126 if (FileSpec::ForEachItemInDirectory(child_path, callback) ==
1127 eEnumerateDirectoryResultQuit) {
1128 // The subdirectory returned Quit, which means to
1129 // stop all directory enumerations at all levels.
1132 return eEnumerateDirectoryResultQuit;
1136 case eEnumerateDirectoryResultExit: // Exit from the current directory
1137 // at the current level.
1138 // Exit from this directory level and tell parent to
1139 // keep enumerating.
1142 return eEnumerateDirectoryResultNext;
1144 case eEnumerateDirectoryResultQuit: // Stop directory enumerations at
1148 return eEnumerateDirectoryResultQuit;
1156 // By default when exiting a directory, we tell the parent enumeration
1157 // to continue enumerating.
1158 return eEnumerateDirectoryResultNext;
1161 FileSpec::EnumerateDirectoryResult
1162 FileSpec::EnumerateDirectory(llvm::StringRef dir_path, bool find_directories,
1163 bool find_files, bool find_other,
1164 EnumerateDirectoryCallbackType callback,
1165 void *callback_baton) {
1166 return ForEachItemInDirectory(
1168 [&find_directories, &find_files, &find_other, &callback,
1169 &callback_baton](FileType file_type, const FileSpec &file_spec) {
1170 switch (file_type) {
1171 case FileType::eFileTypeDirectory:
1172 if (find_directories)
1173 return callback(callback_baton, file_type, file_spec);
1175 case FileType::eFileTypeRegular:
1177 return callback(callback_baton, file_type, file_spec);
1181 return callback(callback_baton, file_type, file_spec);
1184 return eEnumerateDirectoryResultNext;
1189 FileSpec::CopyByAppendingPathComponent(llvm::StringRef component) const {
1190 FileSpec ret = *this;
1191 ret.AppendPathComponent(component);
1195 FileSpec FileSpec::CopyByRemovingLastPathComponent() const {
1196 // CLEANUP: Use StringRef for string handling.
1197 const bool resolve = false;
1198 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1199 return FileSpec("", resolve);
1200 if (m_directory.IsEmpty())
1201 return FileSpec("", resolve);
1202 if (m_filename.IsEmpty()) {
1203 const char *dir_cstr = m_directory.GetCString();
1204 const char *last_slash_ptr = ::strrchr(dir_cstr, '/');
1206 // check for obvious cases before doing the full thing
1207 if (!last_slash_ptr)
1208 return FileSpec("", resolve);
1209 if (last_slash_ptr == dir_cstr)
1210 return FileSpec("/", resolve);
1212 size_t last_slash_pos = last_slash_ptr - dir_cstr + 1;
1213 ConstString new_path(dir_cstr, last_slash_pos);
1214 return FileSpec(new_path.GetCString(), resolve);
1216 return FileSpec(m_directory.GetCString(), resolve);
1219 ConstString FileSpec::GetLastPathComponent() const {
1220 // CLEANUP: Use StringRef for string handling.
1224 const char *dir_cstr = m_directory.GetCString();
1225 const char *last_slash_ptr = ::strrchr(dir_cstr, '/');
1226 if (last_slash_ptr == NULL)
1228 if (last_slash_ptr == dir_cstr) {
1229 if (last_slash_ptr[1] == 0)
1230 return ConstString(last_slash_ptr);
1232 return ConstString(last_slash_ptr + 1);
1234 if (last_slash_ptr[1] != 0)
1235 return ConstString(last_slash_ptr + 1);
1236 const char *penultimate_slash_ptr = last_slash_ptr;
1237 while (*penultimate_slash_ptr) {
1238 --penultimate_slash_ptr;
1239 if (penultimate_slash_ptr == dir_cstr)
1241 if (*penultimate_slash_ptr == '/')
1244 ConstString result(penultimate_slash_ptr + 1,
1245 last_slash_ptr - penultimate_slash_ptr);
1248 return ConstString();
1251 void FileSpec::PrependPathComponent(llvm::StringRef component) {
1252 if (component.empty())
1255 const bool resolve = false;
1256 if (m_filename.IsEmpty() && m_directory.IsEmpty()) {
1257 SetFile(component, resolve);
1261 char sep = GetPreferredPathSeparator(m_syntax);
1263 if (m_filename.IsEmpty())
1264 result = llvm::join_items(sep, component, m_directory.GetStringRef());
1265 else if (m_directory.IsEmpty())
1266 result = llvm::join_items(sep, component, m_filename.GetStringRef());
1268 result = llvm::join_items(sep, component, m_directory.GetStringRef(),
1269 m_filename.GetStringRef());
1271 SetFile(result, resolve);
1274 void FileSpec::PrependPathComponent(const FileSpec &new_path) {
1275 return PrependPathComponent(new_path.GetPath(false));
1278 void FileSpec::AppendPathComponent(llvm::StringRef component) {
1279 if (component.empty())
1283 if (!m_directory.IsEmpty()) {
1284 result += m_directory.GetStringRef();
1285 if (!IsPathSeparator(m_directory.GetStringRef().back(), m_syntax))
1286 result += GetPreferredPathSeparator(m_syntax);
1289 if (!m_filename.IsEmpty()) {
1290 result += m_filename.GetStringRef();
1291 if (!IsPathSeparator(m_filename.GetStringRef().back(), m_syntax))
1292 result += GetPreferredPathSeparator(m_syntax);
1295 component = component.drop_while(
1296 [this](char c) { return IsPathSeparator(c, m_syntax); });
1298 result += component;
1300 SetFile(result, false, m_syntax);
1303 void FileSpec::AppendPathComponent(const FileSpec &new_path) {
1304 return AppendPathComponent(new_path.GetPath(false));
1307 void FileSpec::RemoveLastPathComponent() {
1308 // CLEANUP: Use StringRef for string handling.
1310 const bool resolve = false;
1311 if (m_filename.IsEmpty() && m_directory.IsEmpty()) {
1312 SetFile("", resolve);
1315 if (m_directory.IsEmpty()) {
1316 SetFile("", resolve);
1319 if (m_filename.IsEmpty()) {
1320 const char *dir_cstr = m_directory.GetCString();
1321 const char *last_slash_ptr = ::strrchr(dir_cstr, '/');
1323 // check for obvious cases before doing the full thing
1324 if (!last_slash_ptr) {
1325 SetFile("", resolve);
1328 if (last_slash_ptr == dir_cstr) {
1329 SetFile("/", resolve);
1332 size_t last_slash_pos = last_slash_ptr - dir_cstr + 1;
1333 ConstString new_path(dir_cstr, last_slash_pos);
1334 SetFile(new_path.GetCString(), resolve);
1336 SetFile(m_directory.GetCString(), resolve);
1338 //------------------------------------------------------------------
1339 /// Returns true if the filespec represents an implementation source
1340 /// file (files with a ".c", ".cpp", ".m", ".mm" (many more)
1344 /// \b true if the filespec represents an implementation source
1345 /// file, \b false otherwise.
1346 //------------------------------------------------------------------
1347 bool FileSpec::IsSourceImplementationFile() const {
1348 ConstString extension(GetFileNameExtension());
1352 static RegularExpression g_source_file_regex(llvm::StringRef(
1353 "^([cC]|[mM]|[mM][mM]|[cC][pP][pP]|[cC]\\+\\+|[cC][xX][xX]|[cC][cC]|["
1354 "cC][pP]|[sS]|[aA][sS][mM]|[fF]|[fF]77|[fF]90|[fF]95|[fF]03|[fF][oO]["
1355 "rR]|[fF][tT][nN]|[fF][pP][pP]|[aA][dD][aA]|[aA][dD][bB]|[aA][dD][sS])"
1357 return g_source_file_regex.Execute(extension.GetStringRef());
1360 bool FileSpec::IsRelative() const {
1361 const char *dir = m_directory.GetCString();
1362 llvm::StringRef directory(dir ? dir : "");
1364 if (directory.size() > 0) {
1365 if (PathSyntaxIsPosix(m_syntax)) {
1366 // If the path doesn't start with '/' or '~', return true
1367 switch (directory[0]) {
1375 if (directory.size() >= 2 && directory[1] == ':')
1377 if (directory[0] == '/')
1381 } else if (m_filename) {
1382 // No directory, just a basename, return true
1388 bool FileSpec::IsAbsolute() const { return !FileSpec::IsRelative(); }
1390 void llvm::format_provider<FileSpec>::format(const FileSpec &F,
1391 raw_ostream &Stream,
1394 (Style.empty() || Style.equals_lower("F") || Style.equals_lower("D")) &&
1395 "Invalid FileSpec style!");
1397 StringRef dir = F.GetDirectory().GetStringRef();
1398 StringRef file = F.GetFilename().GetStringRef();
1400 if (dir.empty() && file.empty()) {
1401 Stream << "(empty)";
1405 if (Style.equals_lower("F")) {
1406 Stream << (file.empty() ? "(empty)" : file);
1410 // Style is either D or empty, either way we need to print the directory.
1412 // Directory is stored in normalized form, which might be different
1413 // than preferred form. In order to handle this, we need to cut off
1414 // the filename, then denormalize, then write the entire denorm'ed
1416 llvm::SmallString<64> denormalized_dir = dir;
1417 Denormalize(denormalized_dir, F.GetPathSyntax());
1418 Stream << denormalized_dir;
1419 Stream << GetPreferredPathSeparator(F.GetPathSyntax());
1422 if (Style.equals_lower("D")) {
1423 // We only want to print the directory, so now just exit.
1425 Stream << "(empty)";