]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lldb/source/Host/common/FileSpec.cpp
MFV r316693:
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lldb / source / Host / common / FileSpec.cpp
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 #ifndef _WIN32
11 #include <dirent.h>
12 #else
13 #include "lldb/Host/windows/windows.h"
14 #endif
15 #include <fcntl.h>
16 #ifndef _MSC_VER
17 #include <libgen.h>
18 #endif
19 #include <fstream>
20 #include <set>
21 #include <string.h>
22
23 #include "lldb/Host/Config.h" // Have to include this before we test the define...
24 #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
25 #include <pwd.h>
26 #endif
27
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"
39
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"
46
47 using namespace lldb;
48 using namespace lldb_private;
49
50 namespace {
51
52 bool PathSyntaxIsPosix(FileSpec::PathSyntax syntax) {
53   return (syntax == FileSpec::ePathSyntaxPosix ||
54           (syntax == FileSpec::ePathSyntaxHostNative &&
55            FileSystem::GetNativePathSyntax() == FileSpec::ePathSyntaxPosix));
56 }
57
58 const char *GetPathSeparators(FileSpec::PathSyntax syntax) {
59   return PathSyntaxIsPosix(syntax) ? "/" : "\\/";
60 }
61
62 char GetPreferredPathSeparator(FileSpec::PathSyntax syntax) {
63   return GetPathSeparators(syntax)[0];
64 }
65
66 bool IsPathSeparator(char value, FileSpec::PathSyntax syntax) {
67   return value == '/' || (!PathSyntaxIsPosix(syntax) && value == '\\');
68 }
69
70 void Normalize(llvm::SmallVectorImpl<char> &path, FileSpec::PathSyntax syntax) {
71   if (PathSyntaxIsPosix(syntax))
72     return;
73
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 == '/');
79   });
80   path.erase(iter, path.end());
81 }
82
83 void Denormalize(llvm::SmallVectorImpl<char> &path,
84                  FileSpec::PathSyntax syntax) {
85   if (PathSyntaxIsPosix(syntax))
86     return;
87
88   std::replace(path.begin(), path.end(), '/', '\\');
89 }
90
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;
95   return false;
96 }
97
98 size_t FilenamePos(llvm::StringRef str, FileSpec::PathSyntax syntax) {
99   if (str.size() == 2 && IsPathSeparator(str[0], syntax) && str[0] == str[1])
100     return 0;
101
102   if (str.size() > 0 && IsPathSeparator(str.back(), syntax))
103     return str.size() - 1;
104
105   size_t pos = str.find_last_of(GetPathSeparators(syntax), str.size() - 1);
106
107   if (!PathSyntaxIsPosix(syntax) && pos == llvm::StringRef::npos)
108     pos = str.find_last_of(':', str.size() - 2);
109
110   if (pos == llvm::StringRef::npos ||
111       (pos == 1 && IsPathSeparator(str[0], syntax)))
112     return 0;
113
114   return pos + 1;
115 }
116
117 size_t RootDirStart(llvm::StringRef str, FileSpec::PathSyntax syntax) {
118   // case "c:/"
119   if (!PathSyntaxIsPosix(syntax) &&
120       (str.size() > 2 && str[1] == ':' && IsPathSeparator(str[2], syntax)))
121     return 2;
122
123   // case "//"
124   if (str.size() == 2 && IsPathSeparator(str[0], syntax) && str[0] == str[1])
125     return llvm::StringRef::npos;
126
127   // case "//net"
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);
131
132   // case "/"
133   if (str.size() > 0 && IsPathSeparator(str[0], syntax))
134     return 0;
135
136   return llvm::StringRef::npos;
137 }
138
139 size_t ParentPathEnd(llvm::StringRef path, FileSpec::PathSyntax syntax) {
140   size_t end_pos = FilenamePos(path, syntax);
141
142   bool filename_was_sep =
143       path.size() > 0 && IsPathSeparator(path[end_pos], syntax);
144
145   // Skip separators except for root dir.
146   size_t root_dir_pos = RootDirStart(path.substr(0, end_pos), syntax);
147
148   while (end_pos > 0 && (end_pos - 1) != root_dir_pos &&
149          IsPathSeparator(path[end_pos - 1], syntax))
150     --end_pos;
151
152   if (end_pos == 1 && root_dir_pos == 0 && filename_was_sep)
153     return llvm::StringRef::npos;
154
155   return end_pos;
156 }
157
158 } // end anonymous namespace
159
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
162 // user.
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] != '~')
168     return;
169
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
181         // next time
182         setenv("HOME", pw->pw_dir, 0);
183         home_dir.assign(llvm::StringRef(pw->pw_dir));
184       } else {
185         return;
186       }
187     }
188
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());
194     return;
195   }
196
197   auto username_begin = path.begin() + 1;
198   auto username_end = (slash_pos == llvm::StringRef::npos)
199                           ? path.end()
200                           : (path.begin() + slash_pos);
201   size_t replacement_length = std::distance(path.begin(), username_end);
202
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
207     // the length
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
216       // path was
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
221       // still more
222       // characters that need to be inserted.
223       path.insert(username_end, src_end, homedir.end());
224     }
225   } else {
226     // Unable to resolve username (user doesn't exist?)
227     path.clear();
228   }
229 #endif
230 }
231
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();
236
237   setpwent();
238   struct passwd *user_entry;
239   partial_name = partial_name.drop_front();
240   std::set<std::string> name_list;
241
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);
248     }
249   }
250
251   for (auto &name : name_list) {
252     matches.AppendString(name);
253   }
254   return matches.GetSize() - extant_entries;
255 #else
256   // Resolving home directories is not supported, just copy the path...
257   return 0;
258 #endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
259 }
260
261 void FileSpec::Resolve(llvm::SmallVectorImpl<char> &path) {
262   if (path.empty())
263     return;
264
265 #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
266   if (path[0] == '~')
267     ResolveUsername(path);
268 #endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
269
270   // Save a copy of the original path that's passed in
271   llvm::SmallString<128> original_path(path.begin(), path.end());
272
273   llvm::sys::fs::make_absolute(path);
274   if (!llvm::sys::fs::exists(path)) {
275     path.clear();
276     path.append(original_path.begin(), original_path.end());
277   }
278 }
279
280 FileSpec::FileSpec() : m_syntax(FileSystem::GetNativePathSyntax()) {}
281
282 //------------------------------------------------------------------
283 // Default constructor that can take an optional full path to a
284 // file on disk.
285 //------------------------------------------------------------------
286 FileSpec::FileSpec(llvm::StringRef path, bool resolve_path, PathSyntax syntax)
287     : m_syntax(syntax) {
288   SetFile(path, resolve_path, syntax);
289 }
290
291 FileSpec::FileSpec(llvm::StringRef path, bool resolve_path, ArchSpec arch)
292     : FileSpec{path, resolve_path, arch.GetTriple().isOSWindows()
293                                        ? ePathSyntaxWindows
294                                        : ePathSyntaxPosix} {}
295
296 //------------------------------------------------------------------
297 // Copy constructor
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) {}
302
303 //------------------------------------------------------------------
304 // Copy constructor
305 //------------------------------------------------------------------
306 FileSpec::FileSpec(const FileSpec *rhs) : m_directory(), m_filename() {
307   if (rhs)
308     *this = *rhs;
309 }
310
311 //------------------------------------------------------------------
312 // Virtual destructor in case anyone inherits from this class.
313 //------------------------------------------------------------------
314 FileSpec::~FileSpec() {}
315
316 //------------------------------------------------------------------
317 // Assignment operator.
318 //------------------------------------------------------------------
319 const FileSpec &FileSpec::operator=(const FileSpec &rhs) {
320   if (this != &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;
325   }
326   return *this;
327 }
328
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,
335                        PathSyntax syntax) {
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.
340   m_filename.Clear();
341   m_directory.Clear();
342   m_is_resolved = false;
343   m_syntax = (syntax == ePathSyntaxHostNative)
344                  ? FileSystem::GetNativePathSyntax()
345                  : syntax;
346
347   if (pathname.empty())
348     return;
349
350   llvm::SmallString<64> resolved(pathname);
351
352   if (resolve) {
353     FileSpec::Resolve(resolved);
354     m_is_resolved = true;
355   }
356
357   Normalize(resolved, m_syntax);
358
359   llvm::StringRef resolve_path_ref(resolved.c_str());
360   size_t dir_end = ParentPathEnd(resolve_path_ref, m_syntax);
361   if (dir_end == 0) {
362     m_filename.SetString(resolve_path_ref);
363     return;
364   }
365
366   m_directory.SetString(resolve_path_ref.substr(0, dir_end));
367
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))
374     ++filename_begin;
375   m_filename.SetString((filename_begin == llvm::StringRef::npos ||
376                         filename_begin >= resolve_path_ref.size())
377                            ? "."
378                            : resolve_path_ref.substr(filename_begin));
379 }
380
381 void FileSpec::SetFile(llvm::StringRef path, bool resolve, ArchSpec arch) {
382   return SetFile(path, resolve, arch.GetTriple().isOSWindows()
383                                     ? ePathSyntaxWindows
384                                     : ePathSyntaxPosix);
385 }
386
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:
390 //
391 //  if (file_spec)
392 //  {}
393 //----------------------------------------------------------------------
394 FileSpec::operator bool() const { return m_filename || m_directory; }
395
396 //----------------------------------------------------------------------
397 // Logical NOT operator. This allows code to check any FileSpec
398 // objects to see if they are invalid using code such as:
399 //
400 //  if (!file_spec)
401 //  {}
402 //----------------------------------------------------------------------
403 bool FileSpec::operator!() const { return !m_directory && !m_filename; }
404
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);
408 }
409
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);
413 }
414
415 //------------------------------------------------------------------
416 // Equal to operator
417 //------------------------------------------------------------------
418 bool FileSpec::operator==(const FileSpec &rhs) const {
419   if (!FileEquals(rhs))
420     return false;
421   if (DirectoryEquals(rhs))
422     return true;
423
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
430   // this out...
431   if (IsResolved() && rhs.IsResolved()) {
432     // Both paths are resolved, no need to look further...
433     return false;
434   }
435
436   FileSpec resolved_lhs(*this);
437
438   // If "this" isn't resolved, resolve it
439   if (!IsResolved()) {
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);
445     } else
446       return false;
447   }
448
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);
456     } else
457       return false;
458   }
459
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);
464 }
465
466 //------------------------------------------------------------------
467 // Not equal to operator
468 //------------------------------------------------------------------
469 bool FileSpec::operator!=(const FileSpec &rhs) const { return !(*this == rhs); }
470
471 //------------------------------------------------------------------
472 // Less than operator
473 //------------------------------------------------------------------
474 bool FileSpec::operator<(const FileSpec &rhs) const {
475   return FileSpec::Compare(*this, rhs, true) < 0;
476 }
477
478 //------------------------------------------------------------------
479 // Dump a FileSpec object to a stream
480 //------------------------------------------------------------------
481 Stream &lldb_private::operator<<(Stream &s, const FileSpec &f) {
482   f.Dump(&s);
483   return s;
484 }
485
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() {
491   m_directory.Clear();
492   m_filename.Clear();
493 }
494
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.
502 //
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) {
507   int result = 0;
508
509   // case sensitivity of compare
510   const bool case_sensitive = a.IsCaseSensitive() || b.IsCaseSensitive();
511
512   // If full is true, then we must compare both the directory and filename.
513
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.
518
519   if (full || (a.m_directory && b.m_directory)) {
520     result = ConstString::Compare(a.m_directory, b.m_directory, case_sensitive);
521     if (result)
522       return result;
523   }
524   return ConstString::Compare(a.m_filename, b.m_filename, case_sensitive);
525 }
526
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();
531
532   if (!full && (a.GetDirectory().IsEmpty() || b.GetDirectory().IsEmpty()))
533     return ConstString::Equals(a.m_filename, b.m_filename, case_sensitive);
534
535   if (remove_backups == false)
536     return a == b;
537
538   if (a == b)
539     return true;
540
541   return Equal(a.GetNormalizedPath(), b.GetNormalizedPath(), full, false);
542 }
543
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() != ".")
549     return *this;
550
551   llvm::SmallString<64> path, result;
552   const bool normalize = false;
553   GetPath(path, normalize);
554   llvm::StringRef rest(path);
555
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;
559   if (absolute) {
560     result += rest.take_front(root_dir_start + 1);
561     rest = rest.drop_front(root_dir_start + 1);
562   } else {
563     if (m_syntax == ePathSyntaxWindows && path.size() > 2 && path[1] == ':') {
564       result += rest.take_front(2);
565       rest = rest.drop_front(2);
566     }
567   }
568
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.
579     }
580     if (!processed.empty()) {
581       processed.pop_back();
582       continue; // Dots. Go one level up if we can.
583     }
584     if (absolute)
585       continue; // We're at the top level. Cannot go higher than that. Skip.
586
587     result += component; // We're a relative path. We need to keep these.
588     result += '/';
589     anything_added = true;
590   }
591   for (auto component : processed) {
592     result += component;
593     result += '/';
594     anything_added = true;
595   }
596   if (anything_added)
597     result.pop_back(); // Pop last '/'.
598   else if (result.empty())
599     result = ".";
600
601   return FileSpec(result, false, m_syntax);
602 }
603
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 {
610   if (s) {
611     std::string path{GetPath(true)};
612     s->PutCString(path);
613     char path_separator = GetPreferredPathSeparator(m_syntax);
614     if (!m_filename && !path.empty() && path.back() != path_separator)
615       s->PutChar(path_separator);
616   }
617 }
618
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);
625 }
626
627 bool FileSpec::Readable() const {
628   const uint32_t permissions = GetPermissions();
629   if (permissions & eFilePermissionsEveryoneR)
630     return true;
631   return false;
632 }
633
634 bool FileSpec::ResolveExecutableLocation() {
635   // CLEANUP: Use StringRef for string handling.
636   if (!m_directory) {
637     const char *file_cstr = m_filename.GetCString();
638     if (file_cstr) {
639       const std::string file_str(file_cstr);
640       llvm::ErrorOr<std::string> error_or_path =
641           llvm::sys::findProgramByName(file_str);
642       if (!error_or_path)
643         return false;
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)
649           return false;
650
651         m_directory.SetCString(dir_ref.data());
652         if (Exists())
653           return true;
654         else {
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;
661             return true;
662           }
663         }
664       }
665     }
666   }
667
668   return false;
669 }
670
671 bool FileSpec::ResolvePath() {
672   if (m_is_resolved)
673     return true; // We have already resolved this path
674
675   char path_buf[PATH_MAX];
676   if (!GetPath(path_buf, PATH_MAX, false))
677     return 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;
681 }
682
683 uint64_t FileSpec::GetByteSize() const {
684   struct stat file_stats;
685   if (GetFileStats(this, &file_stats))
686     return file_stats.st_size;
687   return 0;
688 }
689
690 FileSpec::PathSyntax FileSpec::GetPathSyntax() const { return m_syntax; }
691
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;
696     switch (file_type) {
697     case S_IFDIR:
698       return eFileTypeDirectory;
699     case S_IFREG:
700       return eFileTypeRegular;
701 #ifndef _WIN32
702     case S_IFIFO:
703       return eFileTypePipe;
704     case S_IFSOCK:
705       return eFileTypeSocket;
706     case S_IFLNK:
707       return eFileTypeSymbolicLink;
708 #endif
709     default:
710       break;
711     }
712     return eFileTypeUnknown;
713   }
714   return eFileTypeInvalid;
715 }
716
717 bool FileSpec::IsSymbolicLink() const {
718   char resolved_path[PATH_MAX];
719   if (!GetPath(resolved_path, sizeof(resolved_path)))
720     return false;
721
722 #ifdef _WIN32
723   std::wstring wpath;
724   if (!llvm::ConvertUTF8toWide(resolved_path, wpath))
725     return false;
726   auto attrs = ::GetFileAttributesW(wpath.c_str());
727   if (attrs == INVALID_FILE_ATTRIBUTES)
728     return false;
729
730   return (attrs & FILE_ATTRIBUTE_REPARSE_POINT);
731 #else
732   struct stat file_stats;
733   if (::lstat(resolved_path, &file_stats) != 0)
734     return false;
735
736   return (file_stats.st_mode & S_IFMT) == S_IFLNK;
737 #endif
738 }
739
740 uint32_t FileSpec::GetPermissions() const {
741   uint32_t file_permissions = 0;
742   if (*this)
743     FileSystem::GetFilePermissions(*this, file_permissions);
744   return file_permissions;
745 }
746
747 //------------------------------------------------------------------
748 // Directory string get accessor.
749 //------------------------------------------------------------------
750 ConstString &FileSpec::GetDirectory() { return m_directory; }
751
752 //------------------------------------------------------------------
753 // Directory string const get accessor.
754 //------------------------------------------------------------------
755 const ConstString &FileSpec::GetDirectory() const { return m_directory; }
756
757 //------------------------------------------------------------------
758 // Filename string get accessor.
759 //------------------------------------------------------------------
760 ConstString &FileSpec::GetFilename() { return m_filename; }
761
762 //------------------------------------------------------------------
763 // Filename string const get accessor.
764 //------------------------------------------------------------------
765 const ConstString &FileSpec::GetFilename() const { return m_filename; }
766
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
770 // values.
771 //------------------------------------------------------------------
772 size_t FileSpec::GetPath(char *path, size_t path_max_len,
773                          bool denormalize) const {
774   if (!path)
775     return 0;
776
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());
780 }
781
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());
786 }
787
788 const char *FileSpec::GetCString(bool denormalize) const {
789   return ConstString{GetPath(denormalize)}.AsCString(NULL);
790 }
791
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);
804 }
805
806 ConstString FileSpec::GetFileNameExtension() const {
807   if (m_filename) {
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);
812   }
813   return ConstString();
814 }
815
816 ConstString FileSpec::GetFileNameStrippingExtension() const {
817   const char *filename = m_filename.GetCString();
818   if (filename == NULL)
819     return ConstString();
820
821   const char *dot_pos = strrchr(filename, '.');
822   if (dot_pos == NULL)
823     return m_filename;
824
825   return ConstString(filename, dot_pos - filename);
826 }
827
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());
849   }
850   return data_sp;
851 }
852
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);
857   else
858     return ReadFileContents(file_offset, file_size, NULL);
859 }
860
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();
868 }
869
870 size_t FileSpec::ReadFileContents(off_t file_offset, void *dst, size_t dst_len,
871                                   Error *error_ptr) const {
872   Error error;
873   size_t bytes_read = 0;
874   char resolved_path[PATH_MAX];
875   if (GetPath(resolved_path, sizeof(resolved_path))) {
876     File file;
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);
882     }
883   } else {
884     error.SetErrorString("invalid file specification");
885   }
886   if (error_ptr)
887     *error_ptr = error;
888   return bytes_read;
889 }
890
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 {
904   Error error;
905   DataBufferSP data_sp;
906   char resolved_path[PATH_MAX];
907   if (GetPath(resolved_path, sizeof(resolved_path))) {
908     File file;
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);
913     }
914   } else {
915     error.SetErrorString("invalid file specification");
916   }
917   if (error_ptr)
918     *error_ptr = error;
919   return data_sp;
920 }
921
922 DataBufferSP FileSpec::ReadFileContentsAsCString(Error *error_ptr) {
923   Error error;
924   DataBufferSP data_sp;
925   char resolved_path[PATH_MAX];
926   if (GetPath(resolved_path, sizeof(resolved_path))) {
927     File file;
928     error = file.Open(resolved_path, File::eOpenOptionRead);
929     if (error.Success()) {
930       off_t offset = 0;
931       size_t length = SIZE_MAX;
932       const bool null_terminate = true;
933       error = file.Read(length, offset, null_terminate, data_sp);
934     }
935   } else {
936     error.SetErrorString("invalid file specification");
937   }
938   if (error_ptr)
939     *error_ptr = error;
940   return data_sp;
941 }
942
943 size_t FileSpec::ReadFileLines(STLStringArray &lines) {
944   lines.clear();
945   char path[PATH_MAX];
946   if (GetPath(path, sizeof(path))) {
947     std::ifstream file_stream(path);
948
949     if (file_stream) {
950       std::string line;
951       while (getline(file_stream, line))
952         lines.push_back(line);
953     }
954   }
955   return lines.size();
956 }
957
958 FileSpec::EnumerateDirectoryResult
959 FileSpec::ForEachItemInDirectory(llvm::StringRef dir_path,
960                                  DirectoryCallback const &callback) {
961   if (dir_path.empty())
962     return eEnumerateDirectoryResultNext;
963
964 #ifdef _WIN32
965     std::string szDir(dir_path);
966     szDir += "\\*";
967
968     std::wstring wszDir;
969     if (!llvm::ConvertUTF8toWide(szDir, wszDir)) {
970       return eEnumerateDirectoryResultNext;
971     }
972
973     WIN32_FIND_DATAW ffd;
974     HANDLE hFind = FindFirstFileW(wszDir.c_str(), &ffd);
975
976     if (hFind == INVALID_HANDLE_VALUE) {
977       return eEnumerateDirectoryResultNext;
978     }
979
980     do {
981       FileSpec::FileType file_type = eFileTypeUnknown;
982       if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
983         size_t len = wcslen(ffd.cFileName);
984
985         if (len == 1 && ffd.cFileName[0] == L'.')
986           continue;
987
988         if (len == 2 && ffd.cFileName[0] == L'.' && ffd.cFileName[1] == L'.')
989           continue;
990
991         file_type = eFileTypeDirectory;
992       } else if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DEVICE) {
993         file_type = eFileTypeOther;
994       } else {
995         file_type = eFileTypeRegular;
996       }
997
998       std::string fileName;
999       if (!llvm::convertWideToUTF8(ffd.cFileName, fileName)) {
1000         continue;
1001       }
1002
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);
1006
1007       EnumerateDirectoryResult result = callback(file_type, child_path_spec);
1008
1009       switch (result) {
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...
1014         break;
1015
1016       case eEnumerateDirectoryResultEnter: // Recurse into the current entry
1017                                            // if it is a directory or symlink,
1018                                            // or next if not
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;
1024         }
1025         break;
1026
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;
1032
1033       case eEnumerateDirectoryResultQuit: // Stop directory enumerations at
1034                                           // any level
1035         return eEnumerateDirectoryResultQuit;
1036       }
1037     } while (FindNextFileW(hFind, &ffd) != 0);
1038
1039     FindClose(hFind);
1040 #else
1041   std::string dir_string(dir_path);
1042   lldb_utility::CleanUp<DIR *, int> dir_path_dir(opendir(dir_string.c_str()),
1043                                                  NULL, closedir);
1044   if (dir_path_dir.is_valid()) {
1045     char dir_path_last_char = dir_path.back();
1046
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;
1051 #endif
1052       struct dirent *buf, *dp;
1053       buf = (struct dirent *)malloc(offsetof(struct dirent, d_name) + path_max +
1054                                     1);
1055
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);
1060
1061           if (len == 1 && dp->d_name[0] == '.')
1062             continue;
1063
1064           if (len == 2 && dp->d_name[0] == '.' && dp->d_name[1] == '.')
1065             continue;
1066         }
1067
1068         FileSpec::FileType file_type = eFileTypeUnknown;
1069
1070         switch (dp->d_type) {
1071         default:
1072         case DT_UNKNOWN:
1073           file_type = eFileTypeUnknown;
1074           break;
1075         case DT_FIFO:
1076           file_type = eFileTypePipe;
1077           break;
1078         case DT_CHR:
1079           file_type = eFileTypeOther;
1080           break;
1081         case DT_DIR:
1082           file_type = eFileTypeDirectory;
1083           break;
1084         case DT_BLK:
1085           file_type = eFileTypeOther;
1086           break;
1087         case DT_REG:
1088           file_type = eFileTypeRegular;
1089           break;
1090         case DT_LNK:
1091           file_type = eFileTypeSymbolicLink;
1092           break;
1093         case DT_SOCK:
1094           file_type = eFileTypeSocket;
1095           break;
1096 #if !defined(__OpenBSD__)
1097         case DT_WHT:
1098           file_type = eFileTypeOther;
1099           break;
1100 #endif
1101         }
1102
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);
1107         else
1108           child_path = llvm::join_items('/', dir_path, dp->d_name);
1109
1110           // Don't resolve the file type or path
1111           FileSpec child_path_spec(child_path, false);
1112
1113           EnumerateDirectoryResult result =
1114               callback(file_type, child_path_spec);
1115
1116           switch (result) {
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...
1121             break;
1122
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.
1130               if (buf)
1131                 free(buf);
1132               return eEnumerateDirectoryResultQuit;
1133             }
1134             break;
1135
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.
1140             if (buf)
1141               free(buf);
1142             return eEnumerateDirectoryResultNext;
1143
1144           case eEnumerateDirectoryResultQuit: // Stop directory enumerations at
1145                                               // any level
1146             if (buf)
1147               free(buf);
1148             return eEnumerateDirectoryResultQuit;
1149           }
1150       }
1151       if (buf) {
1152         free(buf);
1153       }
1154     }
1155 #endif
1156   // By default when exiting a directory, we tell the parent enumeration
1157   // to continue enumerating.
1158   return eEnumerateDirectoryResultNext;
1159 }
1160
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(
1167       dir_path,
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);
1174           break;
1175         case FileType::eFileTypeRegular:
1176           if (find_files)
1177             return callback(callback_baton, file_type, file_spec);
1178           break;
1179         default:
1180           if (find_other)
1181             return callback(callback_baton, file_type, file_spec);
1182           break;
1183         }
1184         return eEnumerateDirectoryResultNext;
1185       });
1186 }
1187
1188 FileSpec
1189 FileSpec::CopyByAppendingPathComponent(llvm::StringRef component) const {
1190   FileSpec ret = *this;
1191   ret.AppendPathComponent(component);
1192   return ret;
1193 }
1194
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, '/');
1205
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);
1211
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);
1215   } else
1216     return FileSpec(m_directory.GetCString(), resolve);
1217 }
1218
1219 ConstString FileSpec::GetLastPathComponent() const {
1220   // CLEANUP: Use StringRef for string handling.
1221   if (m_filename)
1222     return m_filename;
1223   if (m_directory) {
1224     const char *dir_cstr = m_directory.GetCString();
1225     const char *last_slash_ptr = ::strrchr(dir_cstr, '/');
1226     if (last_slash_ptr == NULL)
1227       return m_directory;
1228     if (last_slash_ptr == dir_cstr) {
1229       if (last_slash_ptr[1] == 0)
1230         return ConstString(last_slash_ptr);
1231       else
1232         return ConstString(last_slash_ptr + 1);
1233     }
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)
1240         break;
1241       if (*penultimate_slash_ptr == '/')
1242         break;
1243     }
1244     ConstString result(penultimate_slash_ptr + 1,
1245                        last_slash_ptr - penultimate_slash_ptr);
1246     return result;
1247   }
1248   return ConstString();
1249 }
1250
1251 void FileSpec::PrependPathComponent(llvm::StringRef component) {
1252   if (component.empty())
1253     return;
1254
1255   const bool resolve = false;
1256   if (m_filename.IsEmpty() && m_directory.IsEmpty()) {
1257     SetFile(component, resolve);
1258     return;
1259   }
1260
1261   char sep = GetPreferredPathSeparator(m_syntax);
1262   std::string result;
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());
1267   else
1268     result = llvm::join_items(sep, component, m_directory.GetStringRef(),
1269                               m_filename.GetStringRef());
1270
1271   SetFile(result, resolve);
1272 }
1273
1274 void FileSpec::PrependPathComponent(const FileSpec &new_path) {
1275   return PrependPathComponent(new_path.GetPath(false));
1276 }
1277
1278 void FileSpec::AppendPathComponent(llvm::StringRef component) {
1279   if (component.empty())
1280     return;
1281
1282   std::string result;
1283   if (!m_directory.IsEmpty()) {
1284     result += m_directory.GetStringRef();
1285     if (!IsPathSeparator(m_directory.GetStringRef().back(), m_syntax))
1286       result += GetPreferredPathSeparator(m_syntax);
1287   }
1288
1289   if (!m_filename.IsEmpty()) {
1290     result += m_filename.GetStringRef();
1291     if (!IsPathSeparator(m_filename.GetStringRef().back(), m_syntax))
1292       result += GetPreferredPathSeparator(m_syntax);
1293   }
1294
1295   component = component.drop_while(
1296       [this](char c) { return IsPathSeparator(c, m_syntax); });
1297
1298   result += component;
1299
1300   SetFile(result, false, m_syntax);
1301 }
1302
1303 void FileSpec::AppendPathComponent(const FileSpec &new_path) {
1304   return AppendPathComponent(new_path.GetPath(false));
1305 }
1306
1307 void FileSpec::RemoveLastPathComponent() {
1308   // CLEANUP: Use StringRef for string handling.
1309
1310   const bool resolve = false;
1311   if (m_filename.IsEmpty() && m_directory.IsEmpty()) {
1312     SetFile("", resolve);
1313     return;
1314   }
1315   if (m_directory.IsEmpty()) {
1316     SetFile("", resolve);
1317     return;
1318   }
1319   if (m_filename.IsEmpty()) {
1320     const char *dir_cstr = m_directory.GetCString();
1321     const char *last_slash_ptr = ::strrchr(dir_cstr, '/');
1322
1323     // check for obvious cases before doing the full thing
1324     if (!last_slash_ptr) {
1325       SetFile("", resolve);
1326       return;
1327     }
1328     if (last_slash_ptr == dir_cstr) {
1329       SetFile("/", resolve);
1330       return;
1331     }
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);
1335   } else
1336     SetFile(m_directory.GetCString(), resolve);
1337 }
1338 //------------------------------------------------------------------
1339 /// Returns true if the filespec represents an implementation source
1340 /// file (files with a ".c", ".cpp", ".m", ".mm" (many more)
1341 /// extension).
1342 ///
1343 /// @return
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());
1349   if (!extension)
1350     return false;
1351
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])"
1356       "$"));
1357   return g_source_file_regex.Execute(extension.GetStringRef());
1358 }
1359
1360 bool FileSpec::IsRelative() const {
1361   const char *dir = m_directory.GetCString();
1362   llvm::StringRef directory(dir ? dir : "");
1363
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]) {
1368       case '/':
1369       case '~':
1370         return false;
1371       default:
1372         return true;
1373       }
1374     } else {
1375       if (directory.size() >= 2 && directory[1] == ':')
1376         return false;
1377       if (directory[0] == '/')
1378         return false;
1379       return true;
1380     }
1381   } else if (m_filename) {
1382     // No directory, just a basename, return true
1383     return true;
1384   }
1385   return false;
1386 }
1387
1388 bool FileSpec::IsAbsolute() const { return !FileSpec::IsRelative(); }
1389
1390 void llvm::format_provider<FileSpec>::format(const FileSpec &F,
1391                                              raw_ostream &Stream,
1392                                              StringRef Style) {
1393   assert(
1394       (Style.empty() || Style.equals_lower("F") || Style.equals_lower("D")) &&
1395       "Invalid FileSpec style!");
1396
1397   StringRef dir = F.GetDirectory().GetStringRef();
1398   StringRef file = F.GetFilename().GetStringRef();
1399
1400   if (dir.empty() && file.empty()) {
1401     Stream << "(empty)";
1402     return;
1403   }
1404
1405   if (Style.equals_lower("F")) {
1406     Stream << (file.empty() ? "(empty)" : file);
1407     return;
1408   }
1409
1410   // Style is either D or empty, either way we need to print the directory.
1411   if (!dir.empty()) {
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
1415     // directory.
1416     llvm::SmallString<64> denormalized_dir = dir;
1417     Denormalize(denormalized_dir, F.GetPathSyntax());
1418     Stream << denormalized_dir;
1419     Stream << GetPreferredPathSeparator(F.GetPathSyntax());
1420   }
1421
1422   if (Style.equals_lower("D")) {
1423     // We only want to print the directory, so now just exit.
1424     if (dir.empty())
1425       Stream << "(empty)";
1426     return;
1427   }
1428
1429   if (!file.empty())
1430     Stream << file;
1431 }