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   static ConstString g_dot_string(".");
405   static ConstString g_dot_dot_string("..");
406 
407   // case sensitivity of equality test
408   const bool case_sensitive = a.IsCaseSensitive() || b.IsCaseSensitive();
409 
410   bool filenames_equal = ConstString::Equals(a.m_filename,
411                                              b.m_filename,
412                                              case_sensitive);
413 
414   // The only way two FileSpecs can be equal if their filenames are
415   // unequal is if we are removing backups and one or the other filename
416   // is a backup string:
417 
418   if (!filenames_equal && !remove_backups)
419       return false;
420 
421   bool last_component_is_dot = ConstString::Equals(a.m_filename, g_dot_string)
422                                || ConstString::Equals(a.m_filename,
423                                                       g_dot_dot_string)
424                                || ConstString::Equals(b.m_filename,
425                                                       g_dot_string)
426                                || ConstString::Equals(b.m_filename,
427                                                       g_dot_dot_string);
428 
429   if (!filenames_equal && !last_component_is_dot)
430     return false;
431 
432   if (!full && (a.GetDirectory().IsEmpty() || b.GetDirectory().IsEmpty()))
433     return filenames_equal;
434 
435   if (remove_backups == false)
436     return a == b;
437 
438   if (a == b)
439     return true;
440 
441   return Equal(a.GetNormalizedPath(), b.GetNormalizedPath(), full, false);
442 }
443 
444 FileSpec FileSpec::GetNormalizedPath() const {
445   // Fast path. Do nothing if the path is not interesting.
446   if (!m_directory.GetStringRef().contains(".") &&
447       !m_directory.GetStringRef().contains("//") &&
448       m_filename.GetStringRef() != ".." && m_filename.GetStringRef() != ".")
449     return *this;
450 
451   llvm::SmallString<64> path, result;
452   const bool normalize = false;
453   GetPath(path, normalize);
454   llvm::StringRef rest(path);
455 
456   // We will not go below root dir.
457   size_t root_dir_start = RootDirStart(path, m_syntax);
458   const bool absolute = root_dir_start != llvm::StringRef::npos;
459   if (absolute) {
460     result += rest.take_front(root_dir_start + 1);
461     rest = rest.drop_front(root_dir_start + 1);
462   } else {
463     if (m_syntax == ePathSyntaxWindows && path.size() > 2 && path[1] == ':') {
464       result += rest.take_front(2);
465       rest = rest.drop_front(2);
466     }
467   }
468 
469   bool anything_added = false;
470   llvm::SmallVector<llvm::StringRef, 0> components, processed;
471   rest.split(components, '/', -1, false);
472   processed.reserve(components.size());
473   for (auto component : components) {
474     if (component == ".")
475       continue; // Skip these.
476     if (component != "..") {
477       processed.push_back(component);
478       continue; // Regular file name.
479     }
480     if (!processed.empty()) {
481       processed.pop_back();
482       continue; // Dots. Go one level up if we can.
483     }
484     if (absolute)
485       continue; // We're at the top level. Cannot go higher than that. Skip.
486 
487     result += component; // We're a relative path. We need to keep these.
488     result += '/';
489     anything_added = true;
490   }
491   for (auto component : processed) {
492     result += component;
493     result += '/';
494     anything_added = true;
495   }
496   if (anything_added)
497     result.pop_back(); // Pop last '/'.
498   else if (result.empty())
499     result = ".";
500 
501   return FileSpec(result, false, m_syntax);
502 }
503 
504 //------------------------------------------------------------------
505 // Dump the object to the supplied stream. If the object contains
506 // a valid directory name, it will be displayed followed by a
507 // directory delimiter, and the filename.
508 //------------------------------------------------------------------
509 void FileSpec::Dump(Stream *s) const {
510   if (s) {
511     std::string path{GetPath(true)};
512     s->PutCString(path);
513     char path_separator = GetPreferredPathSeparator(m_syntax);
514     if (!m_filename && !path.empty() && path.back() != path_separator)
515       s->PutChar(path_separator);
516   }
517 }
518 
519 //------------------------------------------------------------------
520 // Returns true if the file exists.
521 //------------------------------------------------------------------
522 bool FileSpec::Exists() const { return llvm::sys::fs::exists(GetPath()); }
523 
524 bool FileSpec::Readable() const {
525   return GetPermissions() & llvm::sys::fs::perms::all_read;
526 }
527 
528 bool FileSpec::ResolveExecutableLocation() {
529   // CLEANUP: Use StringRef for string handling.
530   if (!m_directory) {
531     const char *file_cstr = m_filename.GetCString();
532     if (file_cstr) {
533       const std::string file_str(file_cstr);
534       llvm::ErrorOr<std::string> error_or_path =
535           llvm::sys::findProgramByName(file_str);
536       if (!error_or_path)
537         return false;
538       std::string path = error_or_path.get();
539       llvm::StringRef dir_ref = llvm::sys::path::parent_path(path);
540       if (!dir_ref.empty()) {
541         // FindProgramByName returns "." if it can't find the file.
542         if (strcmp(".", dir_ref.data()) == 0)
543           return false;
544 
545         m_directory.SetCString(dir_ref.data());
546         if (Exists())
547           return true;
548         else {
549           // If FindProgramByName found the file, it returns the directory +
550           // filename in its return results.
551           // We need to separate them.
552           FileSpec tmp_file(dir_ref.data(), false);
553           if (tmp_file.Exists()) {
554             m_directory = tmp_file.m_directory;
555             return true;
556           }
557         }
558       }
559     }
560   }
561 
562   return false;
563 }
564 
565 bool FileSpec::ResolvePath() {
566   if (m_is_resolved)
567     return true; // We have already resolved this path
568 
569   // SetFile(...) will set m_is_resolved correctly if it can resolve the path
570   SetFile(GetPath(false), true);
571   return m_is_resolved;
572 }
573 
574 uint64_t FileSpec::GetByteSize() const {
575   uint64_t Size = 0;
576   if (llvm::sys::fs::file_size(GetPath(), Size))
577     return 0;
578   return Size;
579 }
580 
581 FileSpec::PathSyntax FileSpec::GetPathSyntax() const { return m_syntax; }
582 
583 uint32_t FileSpec::GetPermissions() const {
584   namespace fs = llvm::sys::fs;
585   fs::file_status st;
586   if (fs::status(GetPath(), st, false))
587     return fs::perms::perms_not_known;
588 
589   return st.permissions();
590 }
591 
592 //------------------------------------------------------------------
593 // Directory string get accessor.
594 //------------------------------------------------------------------
595 ConstString &FileSpec::GetDirectory() { return m_directory; }
596 
597 //------------------------------------------------------------------
598 // Directory string const get accessor.
599 //------------------------------------------------------------------
600 const ConstString &FileSpec::GetDirectory() const { return m_directory; }
601 
602 //------------------------------------------------------------------
603 // Filename string get accessor.
604 //------------------------------------------------------------------
605 ConstString &FileSpec::GetFilename() { return m_filename; }
606 
607 //------------------------------------------------------------------
608 // Filename string const get accessor.
609 //------------------------------------------------------------------
610 const ConstString &FileSpec::GetFilename() const { return m_filename; }
611 
612 //------------------------------------------------------------------
613 // Extract the directory and path into a fixed buffer. This is
614 // needed as the directory and path are stored in separate string
615 // values.
616 //------------------------------------------------------------------
617 size_t FileSpec::GetPath(char *path, size_t path_max_len,
618                          bool denormalize) const {
619   if (!path)
620     return 0;
621 
622   std::string result = GetPath(denormalize);
623   ::snprintf(path, path_max_len, "%s", result.c_str());
624   return std::min(path_max_len - 1, result.length());
625 }
626 
627 std::string FileSpec::GetPath(bool denormalize) const {
628   llvm::SmallString<64> result;
629   GetPath(result, denormalize);
630   return std::string(result.begin(), result.end());
631 }
632 
633 const char *FileSpec::GetCString(bool denormalize) const {
634   return ConstString{GetPath(denormalize)}.AsCString(NULL);
635 }
636 
637 void FileSpec::GetPath(llvm::SmallVectorImpl<char> &path,
638                        bool denormalize) const {
639   path.append(m_directory.GetStringRef().begin(),
640               m_directory.GetStringRef().end());
641   if (m_directory && m_filename &&
642       !IsPathSeparator(m_directory.GetStringRef().back(), m_syntax))
643     path.insert(path.end(), GetPreferredPathSeparator(m_syntax));
644   path.append(m_filename.GetStringRef().begin(),
645               m_filename.GetStringRef().end());
646   Normalize(path, m_syntax);
647   if (denormalize && !path.empty())
648     Denormalize(path, m_syntax);
649 }
650 
651 ConstString FileSpec::GetFileNameExtension() const {
652   if (m_filename) {
653     const char *filename = m_filename.GetCString();
654     const char *dot_pos = strrchr(filename, '.');
655     if (dot_pos && dot_pos[1] != '\0')
656       return ConstString(dot_pos + 1);
657   }
658   return ConstString();
659 }
660 
661 ConstString FileSpec::GetFileNameStrippingExtension() const {
662   const char *filename = m_filename.GetCString();
663   if (filename == NULL)
664     return ConstString();
665 
666   const char *dot_pos = strrchr(filename, '.');
667   if (dot_pos == NULL)
668     return m_filename;
669 
670   return ConstString(filename, dot_pos - filename);
671 }
672 
673 //------------------------------------------------------------------
674 // Return the size in bytes that this object takes in memory. This
675 // returns the size in bytes of this object, not any shared string
676 // values it may refer to.
677 //------------------------------------------------------------------
678 size_t FileSpec::MemorySize() const {
679   return m_filename.MemorySize() + m_directory.MemorySize();
680 }
681 
682 void FileSpec::EnumerateDirectory(llvm::StringRef dir_path,
683                                   bool find_directories, bool find_files,
684                                   bool find_other,
685                                   EnumerateDirectoryCallbackType callback,
686                                   void *callback_baton) {
687   namespace fs = llvm::sys::fs;
688   std::error_code EC;
689   fs::recursive_directory_iterator Iter(dir_path, EC);
690   fs::recursive_directory_iterator End;
691   for (; Iter != End && !EC; Iter.increment(EC)) {
692     const auto &Item = *Iter;
693     fs::file_status Status;
694     if ((EC = Item.status(Status)))
695       break;
696     if (!find_files && fs::is_regular_file(Status))
697       continue;
698     if (!find_directories && fs::is_directory(Status))
699       continue;
700     if (!find_other && fs::is_other(Status))
701       continue;
702 
703     FileSpec Spec(Item.path(), false);
704     auto Result = callback(callback_baton, Status.type(), Spec);
705     if (Result == eEnumerateDirectoryResultQuit)
706       return;
707     if (Result == eEnumerateDirectoryResultNext) {
708       // Default behavior is to recurse.  Opt out if the callback doesn't want
709       // this behavior.
710       Iter.no_push();
711     }
712   }
713 }
714 
715 FileSpec
716 FileSpec::CopyByAppendingPathComponent(llvm::StringRef component) const {
717   FileSpec ret = *this;
718   ret.AppendPathComponent(component);
719   return ret;
720 }
721 
722 FileSpec FileSpec::CopyByRemovingLastPathComponent() const {
723   // CLEANUP: Use StringRef for string handling.
724   const bool resolve = false;
725   if (m_filename.IsEmpty() && m_directory.IsEmpty())
726     return FileSpec("", resolve);
727   if (m_directory.IsEmpty())
728     return FileSpec("", resolve);
729   if (m_filename.IsEmpty()) {
730     const char *dir_cstr = m_directory.GetCString();
731     const char *last_slash_ptr = ::strrchr(dir_cstr, '/');
732 
733     // check for obvious cases before doing the full thing
734     if (!last_slash_ptr)
735       return FileSpec("", resolve);
736     if (last_slash_ptr == dir_cstr)
737       return FileSpec("/", resolve);
738 
739     size_t last_slash_pos = last_slash_ptr - dir_cstr + 1;
740     ConstString new_path(dir_cstr, last_slash_pos);
741     return FileSpec(new_path.GetCString(), resolve);
742   } else
743     return FileSpec(m_directory.GetCString(), resolve);
744 }
745 
746 ConstString FileSpec::GetLastPathComponent() const {
747   // CLEANUP: Use StringRef for string handling.
748   if (m_filename)
749     return m_filename;
750   if (m_directory) {
751     const char *dir_cstr = m_directory.GetCString();
752     const char *last_slash_ptr = ::strrchr(dir_cstr, '/');
753     if (last_slash_ptr == NULL)
754       return m_directory;
755     if (last_slash_ptr == dir_cstr) {
756       if (last_slash_ptr[1] == 0)
757         return ConstString(last_slash_ptr);
758       else
759         return ConstString(last_slash_ptr + 1);
760     }
761     if (last_slash_ptr[1] != 0)
762       return ConstString(last_slash_ptr + 1);
763     const char *penultimate_slash_ptr = last_slash_ptr;
764     while (*penultimate_slash_ptr) {
765       --penultimate_slash_ptr;
766       if (penultimate_slash_ptr == dir_cstr)
767         break;
768       if (*penultimate_slash_ptr == '/')
769         break;
770     }
771     ConstString result(penultimate_slash_ptr + 1,
772                        last_slash_ptr - penultimate_slash_ptr);
773     return result;
774   }
775   return ConstString();
776 }
777 
778 static std::string
779 join_path_components(FileSpec::PathSyntax syntax,
780                      const std::vector<llvm::StringRef> components) {
781   std::string result;
782   for (size_t i = 0; i < components.size(); ++i) {
783     if (components[i].empty())
784       continue;
785     result += components[i];
786     if (i != components.size() - 1 &&
787         !IsPathSeparator(components[i].back(), syntax))
788       result += GetPreferredPathSeparator(syntax);
789   }
790 
791   return result;
792 }
793 
794 void FileSpec::PrependPathComponent(llvm::StringRef component) {
795   if (component.empty())
796     return;
797 
798   const bool resolve = false;
799   if (m_filename.IsEmpty() && m_directory.IsEmpty()) {
800     SetFile(component, resolve);
801     return;
802   }
803 
804   std::string result =
805       join_path_components(m_syntax, {component, m_directory.GetStringRef(),
806                                       m_filename.GetStringRef()});
807   SetFile(result, resolve, m_syntax);
808 }
809 
810 void FileSpec::PrependPathComponent(const FileSpec &new_path) {
811   return PrependPathComponent(new_path.GetPath(false));
812 }
813 
814 void FileSpec::AppendPathComponent(llvm::StringRef component) {
815   if (component.empty())
816     return;
817 
818   component = component.drop_while(
819       [this](char c) { return IsPathSeparator(c, m_syntax); });
820 
821   std::string result =
822       join_path_components(m_syntax, {m_directory.GetStringRef(),
823                                       m_filename.GetStringRef(), component});
824 
825   SetFile(result, false, m_syntax);
826 }
827 
828 void FileSpec::AppendPathComponent(const FileSpec &new_path) {
829   return AppendPathComponent(new_path.GetPath(false));
830 }
831 
832 void FileSpec::RemoveLastPathComponent() {
833   // CLEANUP: Use StringRef for string handling.
834 
835   const bool resolve = false;
836   if (m_filename.IsEmpty() && m_directory.IsEmpty()) {
837     SetFile("", resolve);
838     return;
839   }
840   if (m_directory.IsEmpty()) {
841     SetFile("", resolve);
842     return;
843   }
844   if (m_filename.IsEmpty()) {
845     const char *dir_cstr = m_directory.GetCString();
846     const char *last_slash_ptr = ::strrchr(dir_cstr, '/');
847 
848     // check for obvious cases before doing the full thing
849     if (!last_slash_ptr) {
850       SetFile("", resolve);
851       return;
852     }
853     if (last_slash_ptr == dir_cstr) {
854       SetFile("/", resolve);
855       return;
856     }
857     size_t last_slash_pos = last_slash_ptr - dir_cstr + 1;
858     ConstString new_path(dir_cstr, last_slash_pos);
859     SetFile(new_path.GetCString(), resolve);
860   } else
861     SetFile(m_directory.GetCString(), resolve);
862 }
863 //------------------------------------------------------------------
864 /// Returns true if the filespec represents an implementation source
865 /// file (files with a ".c", ".cpp", ".m", ".mm" (many more)
866 /// extension).
867 ///
868 /// @return
869 ///     \b true if the filespec represents an implementation source
870 ///     file, \b false otherwise.
871 //------------------------------------------------------------------
872 bool FileSpec::IsSourceImplementationFile() const {
873   ConstString extension(GetFileNameExtension());
874   if (!extension)
875     return false;
876 
877   static RegularExpression g_source_file_regex(llvm::StringRef(
878       "^([cC]|[mM]|[mM][mM]|[cC][pP][pP]|[cC]\\+\\+|[cC][xX][xX]|[cC][cC]|["
879       "cC][pP]|[sS]|[aA][sS][mM]|[fF]|[fF]77|[fF]90|[fF]95|[fF]03|[fF][oO]["
880       "rR]|[fF][tT][nN]|[fF][pP][pP]|[aA][dD][aA]|[aA][dD][bB]|[aA][dD][sS])"
881       "$"));
882   return g_source_file_regex.Execute(extension.GetStringRef());
883 }
884 
885 bool FileSpec::IsRelative() const {
886   const char *dir = m_directory.GetCString();
887   llvm::StringRef directory(dir ? dir : "");
888 
889   if (directory.size() > 0) {
890     if (PathSyntaxIsPosix(m_syntax)) {
891       // If the path doesn't start with '/' or '~', return true
892       switch (directory[0]) {
893       case '/':
894       case '~':
895         return false;
896       default:
897         return true;
898       }
899     } else {
900       if (directory.size() >= 2 && directory[1] == ':')
901         return false;
902       if (directory[0] == '/')
903         return false;
904       return true;
905     }
906   } else if (m_filename) {
907     // No directory, just a basename, return true
908     return true;
909   }
910   return false;
911 }
912 
913 bool FileSpec::IsAbsolute() const { return !FileSpec::IsRelative(); }
914 
915 void llvm::format_provider<FileSpec>::format(const FileSpec &F,
916                                              raw_ostream &Stream,
917                                              StringRef Style) {
918   assert(
919       (Style.empty() || Style.equals_lower("F") || Style.equals_lower("D")) &&
920       "Invalid FileSpec style!");
921 
922   StringRef dir = F.GetDirectory().GetStringRef();
923   StringRef file = F.GetFilename().GetStringRef();
924 
925   if (dir.empty() && file.empty()) {
926     Stream << "(empty)";
927     return;
928   }
929 
930   if (Style.equals_lower("F")) {
931     Stream << (file.empty() ? "(empty)" : file);
932     return;
933   }
934 
935   // Style is either D or empty, either way we need to print the directory.
936   if (!dir.empty()) {
937     // Directory is stored in normalized form, which might be different
938     // than preferred form.  In order to handle this, we need to cut off
939     // the filename, then denormalize, then write the entire denorm'ed
940     // directory.
941     llvm::SmallString<64> denormalized_dir = dir;
942     Denormalize(denormalized_dir, F.GetPathSyntax());
943     Stream << denormalized_dir;
944     Stream << GetPreferredPathSeparator(F.GetPathSyntax());
945   }
946 
947   if (Style.equals_lower("D")) {
948     // We only want to print the directory, so now just exit.
949     if (dir.empty())
950       Stream << "(empty)";
951     return;
952   }
953 
954   if (!file.empty())
955     Stream << file;
956 }
957