blob: cf94e63efcfd9a94aeb6b92b918210f762d48f07 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- 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
Zachary Turner5713a052017-03-22 18:40:07 +000010#include "lldb/Utility/FileSpec.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000011#include "lldb/Utility/RegularExpression.h"
12#include "lldb/Utility/Stream.h"
Zachary Turner8d48cd62017-03-22 17:33:23 +000013#include "lldb/Utility/TildeExpressionResolver.h"
Zachary Turnerc00cf4a2014-08-15 22:04:21 +000014
Zachary Turner4479ac12017-04-06 18:12:24 +000015#include "llvm/ADT/SmallString.h" // for SmallString
16#include "llvm/ADT/SmallVector.h" // for SmallVectorTemplat...
Caroline Tice391a9602010-09-12 00:10:52 +000017#include "llvm/ADT/StringRef.h"
Zachary Turner4479ac12017-04-06 18:12:24 +000018#include "llvm/ADT/Triple.h" // for Triple
19#include "llvm/ADT/Twine.h" // for Twine
Zachary Turner4479ac12017-04-06 18:12:24 +000020#include "llvm/Support/ErrorOr.h" // for ErrorOr
Zachary Turner3f559742014-08-07 17:33:36 +000021#include "llvm/Support/FileSystem.h"
Greg Clayton38a61402010-12-02 23:20:03 +000022#include "llvm/Support/Path.h"
23#include "llvm/Support/Program.h"
Zachary Turner4479ac12017-04-06 18:12:24 +000024#include "llvm/Support/raw_ostream.h" // for raw_ostream, fs
25
26#include <algorithm> // for replace, min, unique
27#include <system_error> // for error_code
28#include <vector> // for vector
29
30#include <assert.h> // for assert
31#include <stdio.h> // for size_t, NULL, snpr...
32#include <string.h> // for strcmp
Caroline Tice391a9602010-09-12 00:10:52 +000033
Chris Lattner30fdc8d2010-06-08 16:52:24 +000034using namespace lldb;
35using namespace lldb_private;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000036
Chaoren Lin1c614fe2015-05-28 17:02:45 +000037namespace {
38
Zachary Turner7d86ee52017-03-08 17:56:08 +000039static constexpr FileSpec::PathSyntax GetNativeSyntax() {
Nico Weberb1cb0b792018-04-10 13:33:45 +000040#if defined(_WIN32)
Zachary Turner7d86ee52017-03-08 17:56:08 +000041 return FileSpec::ePathSyntaxWindows;
42#else
43 return FileSpec::ePathSyntaxPosix;
44#endif
45}
46
Kate Stoneb9c1b512016-09-06 20:57:50 +000047bool PathSyntaxIsPosix(FileSpec::PathSyntax syntax) {
48 return (syntax == FileSpec::ePathSyntaxPosix ||
49 (syntax == FileSpec::ePathSyntaxHostNative &&
Zachary Turner7d86ee52017-03-08 17:56:08 +000050 GetNativeSyntax() == FileSpec::ePathSyntaxPosix));
Chaoren Lin1c614fe2015-05-28 17:02:45 +000051}
52
Kate Stoneb9c1b512016-09-06 20:57:50 +000053const char *GetPathSeparators(FileSpec::PathSyntax syntax) {
54 return PathSyntaxIsPosix(syntax) ? "/" : "\\/";
Pavel Labath144119b2016-04-04 14:39:12 +000055}
56
Zachary Turnerfe83ad82016-09-27 20:48:37 +000057char GetPreferredPathSeparator(FileSpec::PathSyntax syntax) {
Kate Stoneb9c1b512016-09-06 20:57:50 +000058 return GetPathSeparators(syntax)[0];
Pavel Labath144119b2016-04-04 14:39:12 +000059}
60
Kate Stoneb9c1b512016-09-06 20:57:50 +000061bool IsPathSeparator(char value, FileSpec::PathSyntax syntax) {
62 return value == '/' || (!PathSyntaxIsPosix(syntax) && value == '\\');
Chaoren Lin1c614fe2015-05-28 17:02:45 +000063}
64
Greg Clayton776cd7a2018-04-27 15:45:58 +000065inline llvm::sys::path::Style
66LLVMPathSyntax(FileSpec::PathSyntax lldb_syntax) {
67 switch (lldb_syntax) {
68 case FileSpec::ePathSyntaxPosix:
69 return llvm::sys::path::Style::posix;
70 case FileSpec::ePathSyntaxWindows:
71 return llvm::sys::path::Style::windows;
72 default:
73 case FileSpec::ePathSyntaxHostNative:
74 return llvm::sys::path::Style::native;
75 };
76 return llvm::sys::path::Style::native;
Chaoren Lin1c614fe2015-05-28 17:02:45 +000077}
78
Kate Stoneb9c1b512016-09-06 20:57:50 +000079void Denormalize(llvm::SmallVectorImpl<char> &path,
80 FileSpec::PathSyntax syntax) {
81 if (PathSyntaxIsPosix(syntax))
82 return;
Chaoren Lin1c614fe2015-05-28 17:02:45 +000083
Kate Stoneb9c1b512016-09-06 20:57:50 +000084 std::replace(path.begin(), path.end(), '/', '\\');
Chaoren Lin1c614fe2015-05-28 17:02:45 +000085}
86
Kate Stoneb9c1b512016-09-06 20:57:50 +000087size_t FilenamePos(llvm::StringRef str, FileSpec::PathSyntax syntax) {
88 if (str.size() == 2 && IsPathSeparator(str[0], syntax) && str[0] == str[1])
89 return 0;
Pavel Labath144119b2016-04-04 14:39:12 +000090
Kate Stoneb9c1b512016-09-06 20:57:50 +000091 if (str.size() > 0 && IsPathSeparator(str.back(), syntax))
92 return str.size() - 1;
Pavel Labath144119b2016-04-04 14:39:12 +000093
Kate Stoneb9c1b512016-09-06 20:57:50 +000094 size_t pos = str.find_last_of(GetPathSeparators(syntax), str.size() - 1);
Pavel Labath144119b2016-04-04 14:39:12 +000095
Kate Stoneb9c1b512016-09-06 20:57:50 +000096 if (!PathSyntaxIsPosix(syntax) && pos == llvm::StringRef::npos)
97 pos = str.find_last_of(':', str.size() - 2);
Pavel Labath144119b2016-04-04 14:39:12 +000098
Kate Stoneb9c1b512016-09-06 20:57:50 +000099 if (pos == llvm::StringRef::npos ||
100 (pos == 1 && IsPathSeparator(str[0], syntax)))
101 return 0;
Pavel Labath144119b2016-04-04 14:39:12 +0000102
Kate Stoneb9c1b512016-09-06 20:57:50 +0000103 return pos + 1;
Chaoren Lin1c614fe2015-05-28 17:02:45 +0000104}
105
Kate Stoneb9c1b512016-09-06 20:57:50 +0000106size_t RootDirStart(llvm::StringRef str, FileSpec::PathSyntax syntax) {
107 // case "c:/"
108 if (!PathSyntaxIsPosix(syntax) &&
109 (str.size() > 2 && str[1] == ':' && IsPathSeparator(str[2], syntax)))
110 return 2;
Pavel Labath144119b2016-04-04 14:39:12 +0000111
Kate Stoneb9c1b512016-09-06 20:57:50 +0000112 // case "//"
113 if (str.size() == 2 && IsPathSeparator(str[0], syntax) && str[0] == str[1])
Pavel Labath144119b2016-04-04 14:39:12 +0000114 return llvm::StringRef::npos;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000115
116 // case "//net"
117 if (str.size() > 3 && IsPathSeparator(str[0], syntax) && str[0] == str[1] &&
118 !IsPathSeparator(str[2], syntax))
119 return str.find_first_of(GetPathSeparators(syntax), 2);
120
121 // case "/"
122 if (str.size() > 0 && IsPathSeparator(str[0], syntax))
123 return 0;
124
125 return llvm::StringRef::npos;
Pavel Labath144119b2016-04-04 14:39:12 +0000126}
127
Kate Stoneb9c1b512016-09-06 20:57:50 +0000128size_t ParentPathEnd(llvm::StringRef path, FileSpec::PathSyntax syntax) {
129 size_t end_pos = FilenamePos(path, syntax);
Pavel Labath144119b2016-04-04 14:39:12 +0000130
Kate Stoneb9c1b512016-09-06 20:57:50 +0000131 bool filename_was_sep =
132 path.size() > 0 && IsPathSeparator(path[end_pos], syntax);
Pavel Labath144119b2016-04-04 14:39:12 +0000133
Kate Stoneb9c1b512016-09-06 20:57:50 +0000134 // Skip separators except for root dir.
135 size_t root_dir_pos = RootDirStart(path.substr(0, end_pos), syntax);
Pavel Labath144119b2016-04-04 14:39:12 +0000136
Kate Stoneb9c1b512016-09-06 20:57:50 +0000137 while (end_pos > 0 && (end_pos - 1) != root_dir_pos &&
138 IsPathSeparator(path[end_pos - 1], syntax))
139 --end_pos;
Pavel Labath144119b2016-04-04 14:39:12 +0000140
Kate Stoneb9c1b512016-09-06 20:57:50 +0000141 if (end_pos == 1 && root_dir_pos == 0 && filename_was_sep)
142 return llvm::StringRef::npos;
Pavel Labath144119b2016-04-04 14:39:12 +0000143
Kate Stoneb9c1b512016-09-06 20:57:50 +0000144 return end_pos;
Pavel Labath144119b2016-04-04 14:39:12 +0000145}
146
147} // end anonymous namespace
148
Kate Stoneb9c1b512016-09-06 20:57:50 +0000149void FileSpec::Resolve(llvm::SmallVectorImpl<char> &path) {
150 if (path.empty())
151 return;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000152
Zachary Turner8d48cd62017-03-22 17:33:23 +0000153 llvm::SmallString<32> Source(path.begin(), path.end());
154 StandardTildeExpressionResolver Resolver;
155 Resolver.ResolveFullPath(Source, path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000156
Kate Stoneb9c1b512016-09-06 20:57:50 +0000157 // Save a copy of the original path that's passed in
158 llvm::SmallString<128> original_path(path.begin(), path.end());
Jason Molenda671a29d2015-02-25 02:35:25 +0000159
Kate Stoneb9c1b512016-09-06 20:57:50 +0000160 llvm::sys::fs::make_absolute(path);
161 if (!llvm::sys::fs::exists(path)) {
162 path.clear();
163 path.append(original_path.begin(), original_path.end());
164 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000165}
166
Zachary Turner7d86ee52017-03-08 17:56:08 +0000167FileSpec::FileSpec() : m_syntax(GetNativeSyntax()) {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000168
169//------------------------------------------------------------------
170// Default constructor that can take an optional full path to a
171// file on disk.
172//------------------------------------------------------------------
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000173FileSpec::FileSpec(llvm::StringRef path, bool resolve_path, PathSyntax syntax)
Sam McCall6f43d9d2016-11-15 10:58:16 +0000174 : m_syntax(syntax) {
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000175 SetFile(path, resolve_path, syntax);
Jim Ingham0909e5f2010-09-16 00:57:33 +0000176}
177
Zachary Turner8c6b5462017-03-06 23:42:44 +0000178FileSpec::FileSpec(llvm::StringRef path, bool resolve_path,
179 const llvm::Triple &Triple)
180 : FileSpec{path, resolve_path,
181 Triple.isOSWindows() ? ePathSyntaxWindows : ePathSyntaxPosix} {}
Chaoren Linf34f4102015-05-09 01:21:32 +0000182
Jim Ingham0909e5f2010-09-16 00:57:33 +0000183//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000184// Copy constructor
185//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000186FileSpec::FileSpec(const FileSpec &rhs)
187 : m_directory(rhs.m_directory), m_filename(rhs.m_filename),
188 m_is_resolved(rhs.m_is_resolved), m_syntax(rhs.m_syntax) {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000189
190//------------------------------------------------------------------
191// Copy constructor
192//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000193FileSpec::FileSpec(const FileSpec *rhs) : m_directory(), m_filename() {
194 if (rhs)
195 *this = *rhs;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000196}
197
198//------------------------------------------------------------------
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +0000199// Virtual destructor in case anyone inherits from this class.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000200//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000201FileSpec::~FileSpec() {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000202
Greg Clayton776cd7a2018-04-27 15:45:58 +0000203namespace {
204//------------------------------------------------------------------
205/// Safely get a character at the specified index.
206///
207/// @param[in] path
208/// A full, partial, or relative path to a file.
209///
210/// @param[in] i
211/// An index into path which may or may not be valid.
212///
213/// @return
214/// The character at index \a i if the index is valid, or 0 if
215/// the index is not valid.
216//------------------------------------------------------------------
217inline char safeCharAtIndex(const llvm::StringRef &path, size_t i) {
218 if (i < path.size())
219 return path[i];
220 return 0;
221}
222
223//------------------------------------------------------------------
224/// Check if a path needs to be normalized.
225///
226/// Check if a path needs to be normalized. We currently consider a
227/// path to need normalization if any of the following are true
228/// - path contains "/./"
229/// - path contains "/../"
230/// - path contains "//"
231/// - path ends with "/"
232/// Paths that start with "./" or with "../" are not considered to
233/// need normalization since we aren't trying to resolve the path,
234/// we are just trying to remove redundant things from the path.
235///
236/// @param[in] path
237/// A full, partial, or relative path to a file.
238///
239/// @param[in] syntax
240/// The syntax enumeration for the path in \a path.
241///
242/// @return
243/// Returns \b true if the path needs to be normalized.
244//------------------------------------------------------------------
245bool needsNormalization(const llvm::StringRef &path,
246 FileSpec::PathSyntax syntax) {
Greg Clayton27a0e102018-04-27 21:10:07 +0000247 if (path.empty())
248 return false;
249 // We strip off leading "." values so these paths need to be normalized
250 if (path[0] == '.')
251 return true;
252 for (auto i = path.find_first_of("\\/"); i != llvm::StringRef::npos;
253 i = path.find_first_of("\\/", i + 1)) {
Greg Clayton776cd7a2018-04-27 15:45:58 +0000254 const auto next = safeCharAtIndex(path, i+1);
255 switch (next) {
256 case 0:
257 // path separator char at the end of the string which should be
258 // stripped unless it is the one and only character
259 return i > 0;
260 case '/':
261 case '\\':
262 // two path separator chars in the middle of a path needs to be
263 // normalized
Greg Clayton27a0e102018-04-27 21:10:07 +0000264 if (i > 0)
Greg Clayton776cd7a2018-04-27 15:45:58 +0000265 return true;
266 ++i;
267 break;
268
269 case '.': {
270 const auto next_next = safeCharAtIndex(path, i+2);
271 switch (next_next) {
272 default: break;
273 case 0: return true; // ends with "/."
274 case '/':
275 case '\\':
Greg Clayton27a0e102018-04-27 21:10:07 +0000276 return true; // contains "/./"
Greg Clayton776cd7a2018-04-27 15:45:58 +0000277 case '.': {
278 const auto next_next_next = safeCharAtIndex(path, i+3);
279 switch (next_next_next) {
280 default: break;
281 case 0: return true; // ends with "/.."
282 case '/':
283 case '\\':
Greg Clayton27a0e102018-04-27 21:10:07 +0000284 return true; // contains "/../"
Greg Clayton776cd7a2018-04-27 15:45:58 +0000285 }
286 break;
287 }
288 }
289 }
290 break;
291
292 default:
293 break;
294 }
295 }
296 return false;
297}
298
299
300}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000301//------------------------------------------------------------------
302// Assignment operator.
303//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000304const FileSpec &FileSpec::operator=(const FileSpec &rhs) {
305 if (this != &rhs) {
306 m_directory = rhs.m_directory;
307 m_filename = rhs.m_filename;
308 m_is_resolved = rhs.m_is_resolved;
309 m_syntax = rhs.m_syntax;
310 }
311 return *this;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000312}
313
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000314//------------------------------------------------------------------
315// Update the contents of this object with a new path. The path will
316// be split up into a directory and filename and stored as uniqued
317// string values for quick comparison and efficient memory usage.
318//------------------------------------------------------------------
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000319void FileSpec::SetFile(llvm::StringRef pathname, bool resolve,
320 PathSyntax syntax) {
321 // CLEANUP: Use StringRef for string handling. This function is kind of a
322 // mess and the unclear semantics of RootDirStart and ParentPathEnd make
323 // it very difficult to understand this function. There's no reason this
324 // function should be particularly complicated or difficult to understand.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000325 m_filename.Clear();
326 m_directory.Clear();
327 m_is_resolved = false;
Zachary Turner7d86ee52017-03-08 17:56:08 +0000328 m_syntax = (syntax == ePathSyntaxHostNative) ? GetNativeSyntax() : syntax;
Zachary Turnerdf62f202014-08-07 17:33:07 +0000329
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000330 if (pathname.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000331 return;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000332
Kate Stoneb9c1b512016-09-06 20:57:50 +0000333 llvm::SmallString<64> resolved(pathname);
Zachary Turnerdf62f202014-08-07 17:33:07 +0000334
Kate Stoneb9c1b512016-09-06 20:57:50 +0000335 if (resolve) {
336 FileSpec::Resolve(resolved);
337 m_is_resolved = true;
338 }
Zachary Turnerc7a17ed2014-12-01 23:13:32 +0000339
Greg Clayton776cd7a2018-04-27 15:45:58 +0000340 // Normalize the path by removing ".", ".." and other redundant components.
341 if (needsNormalization(llvm::StringRef(resolved.data(), resolved.size()),
342 syntax))
343 llvm::sys::path::remove_dots(resolved, true, LLVMPathSyntax(syntax));
344
345 // Normalize back slashes to forward slashes
346 if (syntax == FileSpec::ePathSyntaxWindows)
347 std::replace(resolved.begin(), resolved.end(), '\\', '/');
Pavel Labatha212c582016-04-14 09:38:06 +0000348
Kate Stoneb9c1b512016-09-06 20:57:50 +0000349 llvm::StringRef resolve_path_ref(resolved.c_str());
Zachary Turner827d5d72016-12-16 04:27:00 +0000350 size_t dir_end = ParentPathEnd(resolve_path_ref, m_syntax);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000351 if (dir_end == 0) {
352 m_filename.SetString(resolve_path_ref);
353 return;
354 }
Pavel Labath144119b2016-04-04 14:39:12 +0000355
Kate Stoneb9c1b512016-09-06 20:57:50 +0000356 m_directory.SetString(resolve_path_ref.substr(0, dir_end));
Pavel Labath144119b2016-04-04 14:39:12 +0000357
Kate Stoneb9c1b512016-09-06 20:57:50 +0000358 size_t filename_begin = dir_end;
Zachary Turner827d5d72016-12-16 04:27:00 +0000359 size_t root_dir_start = RootDirStart(resolve_path_ref, m_syntax);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000360 while (filename_begin != llvm::StringRef::npos &&
361 filename_begin < resolve_path_ref.size() &&
362 filename_begin != root_dir_start &&
Zachary Turner827d5d72016-12-16 04:27:00 +0000363 IsPathSeparator(resolve_path_ref[filename_begin], m_syntax))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000364 ++filename_begin;
365 m_filename.SetString((filename_begin == llvm::StringRef::npos ||
366 filename_begin >= resolve_path_ref.size())
367 ? "."
368 : resolve_path_ref.substr(filename_begin));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000369}
370
Zachary Turner8c6b5462017-03-06 23:42:44 +0000371void FileSpec::SetFile(llvm::StringRef path, bool resolve,
372 const llvm::Triple &Triple) {
373 return SetFile(path, resolve,
374 Triple.isOSWindows() ? ePathSyntaxWindows : ePathSyntaxPosix);
Chaoren Lin44145d72015-05-29 19:52:37 +0000375}
376
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000377//----------------------------------------------------------------------
378// Convert to pointer operator. This allows code to check any FileSpec
379// objects to see if they contain anything valid using code such as:
380//
381// if (file_spec)
382// {}
383//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000384FileSpec::operator bool() const { return m_filename || m_directory; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000385
386//----------------------------------------------------------------------
387// Logical NOT operator. This allows code to check any FileSpec
388// objects to see if they are invalid using code such as:
389//
390// if (!file_spec)
391// {}
392//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000393bool FileSpec::operator!() const { return !m_directory && !m_filename; }
394
395bool FileSpec::DirectoryEquals(const FileSpec &rhs) const {
396 const bool case_sensitive = IsCaseSensitive() || rhs.IsCaseSensitive();
397 return ConstString::Equals(m_directory, rhs.m_directory, case_sensitive);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000398}
399
Kate Stoneb9c1b512016-09-06 20:57:50 +0000400bool FileSpec::FileEquals(const FileSpec &rhs) const {
401 const bool case_sensitive = IsCaseSensitive() || rhs.IsCaseSensitive();
402 return ConstString::Equals(m_filename, rhs.m_filename, case_sensitive);
Zachary Turner74e08ca2016-03-02 22:05:52 +0000403}
404
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000405//------------------------------------------------------------------
406// Equal to operator
407//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000408bool FileSpec::operator==(const FileSpec &rhs) const {
409 if (!FileEquals(rhs))
410 return false;
411 if (DirectoryEquals(rhs))
412 return true;
Zachary Turner47c03462016-02-24 21:26:47 +0000413
Kate Stoneb9c1b512016-09-06 20:57:50 +0000414 // TODO: determine if we want to keep this code in here.
415 // The code below was added to handle a case where we were
416 // trying to set a file and line breakpoint and one path
417 // was resolved, and the other not and the directory was
418 // in a mount point that resolved to a more complete path:
419 // "/tmp/a.c" == "/private/tmp/a.c". I might end up pulling
420 // this out...
421 if (IsResolved() && rhs.IsResolved()) {
422 // Both paths are resolved, no need to look further...
423 return false;
424 }
Zachary Turner47c03462016-02-24 21:26:47 +0000425
Kate Stoneb9c1b512016-09-06 20:57:50 +0000426 FileSpec resolved_lhs(*this);
Zachary Turner47c03462016-02-24 21:26:47 +0000427
Kate Stoneb9c1b512016-09-06 20:57:50 +0000428 // If "this" isn't resolved, resolve it
429 if (!IsResolved()) {
430 if (resolved_lhs.ResolvePath()) {
431 // This path wasn't resolved but now it is. Check if the resolved
432 // directory is the same as our unresolved directory, and if so,
433 // we can mark this object as resolved to avoid more future resolves
434 m_is_resolved = (m_directory == resolved_lhs.m_directory);
435 } else
436 return false;
437 }
Zachary Turner47c03462016-02-24 21:26:47 +0000438
Kate Stoneb9c1b512016-09-06 20:57:50 +0000439 FileSpec resolved_rhs(rhs);
440 if (!rhs.IsResolved()) {
441 if (resolved_rhs.ResolvePath()) {
442 // rhs's path wasn't resolved but now it is. Check if the resolved
443 // directory is the same as rhs's unresolved directory, and if so,
444 // we can mark this object as resolved to avoid more future resolves
445 rhs.m_is_resolved = (rhs.m_directory == resolved_rhs.m_directory);
446 } else
447 return false;
448 }
Zachary Turner47c03462016-02-24 21:26:47 +0000449
Kate Stoneb9c1b512016-09-06 20:57:50 +0000450 // If we reach this point in the code we were able to resolve both paths
451 // and since we only resolve the paths if the basenames are equal, then
452 // we can just check if both directories are equal...
453 return DirectoryEquals(rhs);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000454}
455
456//------------------------------------------------------------------
457// Not equal to operator
458//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000459bool FileSpec::operator!=(const FileSpec &rhs) const { return !(*this == rhs); }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000460
461//------------------------------------------------------------------
462// Less than operator
463//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000464bool FileSpec::operator<(const FileSpec &rhs) const {
465 return FileSpec::Compare(*this, rhs, true) < 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000466}
467
468//------------------------------------------------------------------
469// Dump a FileSpec object to a stream
470//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000471Stream &lldb_private::operator<<(Stream &s, const FileSpec &f) {
472 f.Dump(&s);
473 return s;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000474}
475
476//------------------------------------------------------------------
477// Clear this object by releasing both the directory and filename
478// string values and making them both the empty string.
479//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000480void FileSpec::Clear() {
481 m_directory.Clear();
482 m_filename.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000483}
484
485//------------------------------------------------------------------
486// Compare two FileSpec objects. If "full" is true, then both
487// the directory and the filename must match. If "full" is false,
488// then the directory names for "a" and "b" are only compared if
489// they are both non-empty. This allows a FileSpec object to only
490// contain a filename and it can match FileSpec objects that have
491// matching filenames with different paths.
492//
493// Return -1 if the "a" is less than "b", 0 if "a" is equal to "b"
494// and "1" if "a" is greater than "b".
495//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000496int FileSpec::Compare(const FileSpec &a, const FileSpec &b, bool full) {
497 int result = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000498
Kate Stoneb9c1b512016-09-06 20:57:50 +0000499 // case sensitivity of compare
500 const bool case_sensitive = a.IsCaseSensitive() || b.IsCaseSensitive();
Zachary Turner47c03462016-02-24 21:26:47 +0000501
Kate Stoneb9c1b512016-09-06 20:57:50 +0000502 // If full is true, then we must compare both the directory and filename.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000503
Kate Stoneb9c1b512016-09-06 20:57:50 +0000504 // If full is false, then if either directory is empty, then we match on
505 // the basename only, and if both directories have valid values, we still
506 // do a full compare. This allows for matching when we just have a filename
507 // in one of the FileSpec objects.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000508
Kate Stoneb9c1b512016-09-06 20:57:50 +0000509 if (full || (a.m_directory && b.m_directory)) {
510 result = ConstString::Compare(a.m_directory, b.m_directory, case_sensitive);
511 if (result)
512 return result;
513 }
514 return ConstString::Compare(a.m_filename, b.m_filename, case_sensitive);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000515}
516
Greg Clayton776cd7a2018-04-27 15:45:58 +0000517bool FileSpec::Equal(const FileSpec &a, const FileSpec &b, bool full) {
Jim Ingham97e4f472017-03-27 19:12:25 +0000518
Kate Stoneb9c1b512016-09-06 20:57:50 +0000519 // case sensitivity of equality test
520 const bool case_sensitive = a.IsCaseSensitive() || b.IsCaseSensitive();
Jim Ingham97e4f472017-03-27 19:12:25 +0000521
Greg Clayton776cd7a2018-04-27 15:45:58 +0000522 const bool filenames_equal = ConstString::Equals(a.m_filename,
523 b.m_filename,
524 case_sensitive);
Jim Ingham97e4f472017-03-27 19:12:25 +0000525
Greg Clayton776cd7a2018-04-27 15:45:58 +0000526 if (!filenames_equal)
Jim Ingham97e4f472017-03-27 19:12:25 +0000527 return false;
528
Kate Stoneb9c1b512016-09-06 20:57:50 +0000529 if (!full && (a.GetDirectory().IsEmpty() || b.GetDirectory().IsEmpty()))
Jim Ingham97e4f472017-03-27 19:12:25 +0000530 return filenames_equal;
Pavel Labath218770b2016-10-31 16:22:07 +0000531
Greg Clayton776cd7a2018-04-27 15:45:58 +0000532 return a == b;
Jim Ingham96a15962014-11-15 01:54:26 +0000533}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000534
535//------------------------------------------------------------------
536// Dump the object to the supplied stream. If the object contains
537// a valid directory name, it will be displayed followed by a
538// directory delimiter, and the filename.
539//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000540void FileSpec::Dump(Stream *s) const {
541 if (s) {
542 std::string path{GetPath(true)};
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000543 s->PutCString(path);
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000544 char path_separator = GetPreferredPathSeparator(m_syntax);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000545 if (!m_filename && !path.empty() && path.back() != path_separator)
546 s->PutChar(path_separator);
547 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000548}
549
550//------------------------------------------------------------------
551// Returns true if the file exists.
552//------------------------------------------------------------------
Zachary Turner7d86ee52017-03-08 17:56:08 +0000553bool FileSpec::Exists() const { return llvm::sys::fs::exists(GetPath()); }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000554
Kate Stoneb9c1b512016-09-06 20:57:50 +0000555bool FileSpec::Readable() const {
Zachary Turner7d86ee52017-03-08 17:56:08 +0000556 return GetPermissions() & llvm::sys::fs::perms::all_read;
Greg Clayton5acc1252014-08-15 18:00:45 +0000557}
558
Kate Stoneb9c1b512016-09-06 20:57:50 +0000559bool FileSpec::ResolveExecutableLocation() {
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000560 // CLEANUP: Use StringRef for string handling.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000561 if (!m_directory) {
562 const char *file_cstr = m_filename.GetCString();
563 if (file_cstr) {
564 const std::string file_str(file_cstr);
565 llvm::ErrorOr<std::string> error_or_path =
566 llvm::sys::findProgramByName(file_str);
567 if (!error_or_path)
Jim Ingham0909e5f2010-09-16 00:57:33 +0000568 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000569 std::string path = error_or_path.get();
570 llvm::StringRef dir_ref = llvm::sys::path::parent_path(path);
571 if (!dir_ref.empty()) {
572 // FindProgramByName returns "." if it can't find the file.
573 if (strcmp(".", dir_ref.data()) == 0)
574 return false;
575
576 m_directory.SetCString(dir_ref.data());
577 if (Exists())
578 return true;
579 else {
580 // If FindProgramByName found the file, it returns the directory +
581 // filename in its return results.
582 // We need to separate them.
583 FileSpec tmp_file(dir_ref.data(), false);
584 if (tmp_file.Exists()) {
585 m_directory = tmp_file.m_directory;
586 return true;
587 }
588 }
589 }
590 }
591 }
592
593 return false;
Jim Ingham0909e5f2010-09-16 00:57:33 +0000594}
595
Kate Stoneb9c1b512016-09-06 20:57:50 +0000596bool FileSpec::ResolvePath() {
597 if (m_is_resolved)
598 return true; // We have already resolved this path
599
Kate Stoneb9c1b512016-09-06 20:57:50 +0000600 // SetFile(...) will set m_is_resolved correctly if it can resolve the path
Pavel Labath9bd69ad2017-03-13 09:46:15 +0000601 SetFile(GetPath(false), true);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000602 return m_is_resolved;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000603}
604
Kate Stoneb9c1b512016-09-06 20:57:50 +0000605uint64_t FileSpec::GetByteSize() const {
Zachary Turner7d86ee52017-03-08 17:56:08 +0000606 uint64_t Size = 0;
607 if (llvm::sys::fs::file_size(GetPath(), Size))
608 return 0;
609 return Size;
Zachary Turnerdf62f202014-08-07 17:33:07 +0000610}
611
Kate Stoneb9c1b512016-09-06 20:57:50 +0000612FileSpec::PathSyntax FileSpec::GetPathSyntax() const { return m_syntax; }
613
Pavel Labath30e6cbf2017-03-07 13:19:15 +0000614uint32_t FileSpec::GetPermissions() const {
Zachary Turner7d86ee52017-03-08 17:56:08 +0000615 namespace fs = llvm::sys::fs;
616 fs::file_status st;
617 if (fs::status(GetPath(), st, false))
618 return fs::perms::perms_not_known;
619
620 return st.permissions();
Greg Claytonfbb76342013-11-20 21:07:01 +0000621}
622
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000623//------------------------------------------------------------------
624// Directory string get accessor.
625//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000626ConstString &FileSpec::GetDirectory() { return m_directory; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000627
628//------------------------------------------------------------------
629// Directory string const get accessor.
630//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000631const ConstString &FileSpec::GetDirectory() const { return m_directory; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000632
633//------------------------------------------------------------------
634// Filename string get accessor.
635//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000636ConstString &FileSpec::GetFilename() { return m_filename; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000637
638//------------------------------------------------------------------
639// Filename string const get accessor.
640//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000641const ConstString &FileSpec::GetFilename() const { return m_filename; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000642
643//------------------------------------------------------------------
644// Extract the directory and path into a fixed buffer. This is
645// needed as the directory and path are stored in separate string
646// values.
647//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000648size_t FileSpec::GetPath(char *path, size_t path_max_len,
649 bool denormalize) const {
650 if (!path)
651 return 0;
Zachary Turnerb6d99242014-08-08 23:54:35 +0000652
Kate Stoneb9c1b512016-09-06 20:57:50 +0000653 std::string result = GetPath(denormalize);
654 ::snprintf(path, path_max_len, "%s", result.c_str());
655 return std::min(path_max_len - 1, result.length());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000656}
657
Kate Stoneb9c1b512016-09-06 20:57:50 +0000658std::string FileSpec::GetPath(bool denormalize) const {
659 llvm::SmallString<64> result;
660 GetPath(result, denormalize);
661 return std::string(result.begin(), result.end());
Jason Molendaa7ae4672013-04-29 09:46:43 +0000662}
663
Kate Stoneb9c1b512016-09-06 20:57:50 +0000664const char *FileSpec::GetCString(bool denormalize) const {
665 return ConstString{GetPath(denormalize)}.AsCString(NULL);
Chaoren Lind3173f32015-05-29 19:52:29 +0000666}
667
Kate Stoneb9c1b512016-09-06 20:57:50 +0000668void FileSpec::GetPath(llvm::SmallVectorImpl<char> &path,
669 bool denormalize) const {
670 path.append(m_directory.GetStringRef().begin(),
671 m_directory.GetStringRef().end());
Greg Clayton776cd7a2018-04-27 15:45:58 +0000672 // Since the path was normalized and all paths use '/' when stored in these
673 // objects, we don't need to look for the actual syntax specific path
674 // separator, we just look for and insert '/'.
675 if (m_directory && m_filename && m_directory.GetStringRef().back() != '/' &&
676 m_filename.GetStringRef().back() != '/')
677 path.insert(path.end(), '/');
Kate Stoneb9c1b512016-09-06 20:57:50 +0000678 path.append(m_filename.GetStringRef().begin(),
679 m_filename.GetStringRef().end());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000680 if (denormalize && !path.empty())
681 Denormalize(path, m_syntax);
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000682}
683
Kate Stoneb9c1b512016-09-06 20:57:50 +0000684ConstString FileSpec::GetFileNameExtension() const {
685 if (m_filename) {
Enrico Granataa9dbf432011-10-17 21:45:27 +0000686 const char *filename = m_filename.GetCString();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000687 const char *dot_pos = strrchr(filename, '.');
688 if (dot_pos && dot_pos[1] != '\0')
689 return ConstString(dot_pos + 1);
690 }
691 return ConstString();
692}
693
694ConstString FileSpec::GetFileNameStrippingExtension() const {
695 const char *filename = m_filename.GetCString();
696 if (filename == NULL)
697 return ConstString();
698
699 const char *dot_pos = strrchr(filename, '.');
700 if (dot_pos == NULL)
701 return m_filename;
702
703 return ConstString(filename, dot_pos - filename);
Enrico Granataa9dbf432011-10-17 21:45:27 +0000704}
705
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000706//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000707// Return the size in bytes that this object takes in memory. This
708// returns the size in bytes of this object, not any shared string
709// values it may refer to.
710//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000711size_t FileSpec::MemorySize() const {
712 return m_filename.MemorySize() + m_directory.MemorySize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000713}
714
Zachary Turner1f875342017-03-13 02:44:39 +0000715void FileSpec::EnumerateDirectory(llvm::StringRef dir_path,
716 bool find_directories, bool find_files,
717 bool find_other,
718 EnumerateDirectoryCallbackType callback,
719 void *callback_baton) {
720 namespace fs = llvm::sys::fs;
721 std::error_code EC;
722 fs::recursive_directory_iterator Iter(dir_path, EC);
723 fs::recursive_directory_iterator End;
724 for (; Iter != End && !EC; Iter.increment(EC)) {
725 const auto &Item = *Iter;
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000726 llvm::ErrorOr<fs::basic_file_status> Status = Item.status();
727 if (!Status)
Zachary Turner1f875342017-03-13 02:44:39 +0000728 break;
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000729 if (!find_files && fs::is_regular_file(*Status))
Zachary Turner1f875342017-03-13 02:44:39 +0000730 continue;
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000731 if (!find_directories && fs::is_directory(*Status))
Zachary Turner1f875342017-03-13 02:44:39 +0000732 continue;
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000733 if (!find_other && fs::is_other(*Status))
Zachary Turner1f875342017-03-13 02:44:39 +0000734 continue;
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000735
Zachary Turner1f875342017-03-13 02:44:39 +0000736 FileSpec Spec(Item.path(), false);
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000737 auto Result = callback(callback_baton, Status->type(), Spec);
Zachary Turner1f875342017-03-13 02:44:39 +0000738 if (Result == eEnumerateDirectoryResultQuit)
739 return;
740 if (Result == eEnumerateDirectoryResultNext) {
741 // Default behavior is to recurse. Opt out if the callback doesn't want
742 // this behavior.
743 Iter.no_push();
Greg Clayton58c65f02015-06-29 18:29:00 +0000744 }
Zachary Turner1f875342017-03-13 02:44:39 +0000745 }
Daniel Maleae0f8f572013-08-26 23:57:52 +0000746}
747
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000748FileSpec
749FileSpec::CopyByAppendingPathComponent(llvm::StringRef component) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000750 FileSpec ret = *this;
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000751 ret.AppendPathComponent(component);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000752 return ret;
Chaoren Lin0c5a9c12015-06-05 00:28:06 +0000753}
754
Kate Stoneb9c1b512016-09-06 20:57:50 +0000755FileSpec FileSpec::CopyByRemovingLastPathComponent() const {
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000756 // CLEANUP: Use StringRef for string handling.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000757 const bool resolve = false;
758 if (m_filename.IsEmpty() && m_directory.IsEmpty())
759 return FileSpec("", resolve);
760 if (m_directory.IsEmpty())
761 return FileSpec("", resolve);
762 if (m_filename.IsEmpty()) {
763 const char *dir_cstr = m_directory.GetCString();
764 const char *last_slash_ptr = ::strrchr(dir_cstr, '/');
765
766 // check for obvious cases before doing the full thing
767 if (!last_slash_ptr)
768 return FileSpec("", resolve);
769 if (last_slash_ptr == dir_cstr)
770 return FileSpec("/", resolve);
771
772 size_t last_slash_pos = last_slash_ptr - dir_cstr + 1;
773 ConstString new_path(dir_cstr, last_slash_pos);
774 return FileSpec(new_path.GetCString(), resolve);
775 } else
776 return FileSpec(m_directory.GetCString(), resolve);
Chaoren Lin0c5a9c12015-06-05 00:28:06 +0000777}
778
Kate Stoneb9c1b512016-09-06 20:57:50 +0000779ConstString FileSpec::GetLastPathComponent() const {
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000780 // CLEANUP: Use StringRef for string handling.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000781 if (m_filename)
782 return m_filename;
783 if (m_directory) {
784 const char *dir_cstr = m_directory.GetCString();
785 const char *last_slash_ptr = ::strrchr(dir_cstr, '/');
786 if (last_slash_ptr == NULL)
787 return m_directory;
788 if (last_slash_ptr == dir_cstr) {
789 if (last_slash_ptr[1] == 0)
790 return ConstString(last_slash_ptr);
791 else
792 return ConstString(last_slash_ptr + 1);
793 }
794 if (last_slash_ptr[1] != 0)
795 return ConstString(last_slash_ptr + 1);
796 const char *penultimate_slash_ptr = last_slash_ptr;
797 while (*penultimate_slash_ptr) {
798 --penultimate_slash_ptr;
799 if (penultimate_slash_ptr == dir_cstr)
800 break;
801 if (*penultimate_slash_ptr == '/')
802 break;
803 }
804 ConstString result(penultimate_slash_ptr + 1,
805 last_slash_ptr - penultimate_slash_ptr);
806 return result;
807 }
808 return ConstString();
Chaoren Lin0c5a9c12015-06-05 00:28:06 +0000809}
810
Pavel Labath59d725c2017-01-16 10:07:02 +0000811static std::string
812join_path_components(FileSpec::PathSyntax syntax,
813 const std::vector<llvm::StringRef> components) {
814 std::string result;
815 for (size_t i = 0; i < components.size(); ++i) {
816 if (components[i].empty())
817 continue;
818 result += components[i];
819 if (i != components.size() - 1 &&
820 !IsPathSeparator(components[i].back(), syntax))
821 result += GetPreferredPathSeparator(syntax);
822 }
823
824 return result;
825}
826
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000827void FileSpec::PrependPathComponent(llvm::StringRef component) {
828 if (component.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000829 return;
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000830
Kate Stoneb9c1b512016-09-06 20:57:50 +0000831 const bool resolve = false;
832 if (m_filename.IsEmpty() && m_directory.IsEmpty()) {
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000833 SetFile(component, resolve);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000834 return;
835 }
Daniel Maleae0f8f572013-08-26 23:57:52 +0000836
Pavel Labath59d725c2017-01-16 10:07:02 +0000837 std::string result =
838 join_path_components(m_syntax, {component, m_directory.GetStringRef(),
839 m_filename.GetStringRef()});
Pavel Labath238169d2017-01-16 12:15:42 +0000840 SetFile(result, resolve, m_syntax);
Chaoren Lind3173f32015-05-29 19:52:29 +0000841}
842
Kate Stoneb9c1b512016-09-06 20:57:50 +0000843void FileSpec::PrependPathComponent(const FileSpec &new_path) {
844 return PrependPathComponent(new_path.GetPath(false));
Chaoren Lin0c5a9c12015-06-05 00:28:06 +0000845}
846
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000847void FileSpec::AppendPathComponent(llvm::StringRef component) {
848 if (component.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000849 return;
850
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000851 component = component.drop_while(
852 [this](char c) { return IsPathSeparator(c, m_syntax); });
Kate Stoneb9c1b512016-09-06 20:57:50 +0000853
Pavel Labath59d725c2017-01-16 10:07:02 +0000854 std::string result =
855 join_path_components(m_syntax, {m_directory.GetStringRef(),
856 m_filename.GetStringRef(), component});
Kate Stoneb9c1b512016-09-06 20:57:50 +0000857
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000858 SetFile(result, false, m_syntax);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000859}
860
861void FileSpec::AppendPathComponent(const FileSpec &new_path) {
862 return AppendPathComponent(new_path.GetPath(false));
863}
864
865void FileSpec::RemoveLastPathComponent() {
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000866 // CLEANUP: Use StringRef for string handling.
867
Kate Stoneb9c1b512016-09-06 20:57:50 +0000868 const bool resolve = false;
869 if (m_filename.IsEmpty() && m_directory.IsEmpty()) {
870 SetFile("", resolve);
871 return;
872 }
873 if (m_directory.IsEmpty()) {
874 SetFile("", resolve);
875 return;
876 }
877 if (m_filename.IsEmpty()) {
878 const char *dir_cstr = m_directory.GetCString();
879 const char *last_slash_ptr = ::strrchr(dir_cstr, '/');
880
881 // check for obvious cases before doing the full thing
882 if (!last_slash_ptr) {
883 SetFile("", resolve);
884 return;
Daniel Maleae0f8f572013-08-26 23:57:52 +0000885 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000886 if (last_slash_ptr == dir_cstr) {
887 SetFile("/", resolve);
888 return;
Daniel Maleae0f8f572013-08-26 23:57:52 +0000889 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000890 size_t last_slash_pos = last_slash_ptr - dir_cstr + 1;
891 ConstString new_path(dir_cstr, last_slash_pos);
892 SetFile(new_path.GetCString(), resolve);
893 } else
894 SetFile(m_directory.GetCString(), resolve);
Daniel Maleae0f8f572013-08-26 23:57:52 +0000895}
Greg Clayton1f746072012-08-29 21:13:06 +0000896//------------------------------------------------------------------
897/// Returns true if the filespec represents an implementation source
898/// file (files with a ".c", ".cpp", ".m", ".mm" (many more)
899/// extension).
900///
901/// @return
902/// \b true if the filespec represents an implementation source
903/// file, \b false otherwise.
904//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000905bool FileSpec::IsSourceImplementationFile() const {
906 ConstString extension(GetFileNameExtension());
Zachary Turner95eae422016-09-21 16:01:28 +0000907 if (!extension)
908 return false;
909
910 static RegularExpression g_source_file_regex(llvm::StringRef(
911 "^([cC]|[mM]|[mM][mM]|[cC][pP][pP]|[cC]\\+\\+|[cC][xX][xX]|[cC][cC]|["
912 "cC][pP]|[sS]|[aA][sS][mM]|[fF]|[fF]77|[fF]90|[fF]95|[fF]03|[fF][oO]["
913 "rR]|[fF][tT][nN]|[fF][pP][pP]|[aA][dD][aA]|[aA][dD][bB]|[aA][dD][sS])"
914 "$"));
915 return g_source_file_regex.Execute(extension.GetStringRef());
Greg Clayton1f746072012-08-29 21:13:06 +0000916}
917
Kate Stoneb9c1b512016-09-06 20:57:50 +0000918bool FileSpec::IsRelative() const {
919 const char *dir = m_directory.GetCString();
920 llvm::StringRef directory(dir ? dir : "");
Zachary Turner270e99a2014-12-08 21:36:42 +0000921
Kate Stoneb9c1b512016-09-06 20:57:50 +0000922 if (directory.size() > 0) {
923 if (PathSyntaxIsPosix(m_syntax)) {
924 // If the path doesn't start with '/' or '~', return true
925 switch (directory[0]) {
926 case '/':
927 case '~':
928 return false;
929 default:
Greg Claytona0ca6602012-10-18 16:33:33 +0000930 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000931 }
932 } else {
933 if (directory.size() >= 2 && directory[1] == ':')
934 return false;
935 if (directory[0] == '/')
936 return false;
937 return true;
Greg Claytona0ca6602012-10-18 16:33:33 +0000938 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000939 } else if (m_filename) {
940 // No directory, just a basename, return true
941 return true;
942 }
943 return false;
Greg Claytona0ca6602012-10-18 16:33:33 +0000944}
Chaoren Lin372e9062015-06-09 17:54:27 +0000945
Kate Stoneb9c1b512016-09-06 20:57:50 +0000946bool FileSpec::IsAbsolute() const { return !FileSpec::IsRelative(); }
Zachary Turner827d5d72016-12-16 04:27:00 +0000947
948void llvm::format_provider<FileSpec>::format(const FileSpec &F,
949 raw_ostream &Stream,
950 StringRef Style) {
951 assert(
952 (Style.empty() || Style.equals_lower("F") || Style.equals_lower("D")) &&
953 "Invalid FileSpec style!");
954
955 StringRef dir = F.GetDirectory().GetStringRef();
956 StringRef file = F.GetFilename().GetStringRef();
957
958 if (dir.empty() && file.empty()) {
959 Stream << "(empty)";
960 return;
961 }
962
963 if (Style.equals_lower("F")) {
964 Stream << (file.empty() ? "(empty)" : file);
965 return;
966 }
967
968 // Style is either D or empty, either way we need to print the directory.
969 if (!dir.empty()) {
970 // Directory is stored in normalized form, which might be different
971 // than preferred form. In order to handle this, we need to cut off
972 // the filename, then denormalize, then write the entire denorm'ed
973 // directory.
974 llvm::SmallString<64> denormalized_dir = dir;
975 Denormalize(denormalized_dir, F.GetPathSyntax());
976 Stream << denormalized_dir;
977 Stream << GetPreferredPathSeparator(F.GetPathSyntax());
978 }
979
980 if (Style.equals_lower("D")) {
981 // We only want to print the directory, so now just exit.
982 if (dir.empty())
983 Stream << "(empty)";
984 return;
985 }
986
987 if (!file.empty())
988 Stream << file;
989}