blob: 2168948fa81cea4e7990d01f5ea373ed13065132 [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;
Greg Clayton776cd7a2018-04-27 15:45:58 +000072 case FileSpec::ePathSyntaxHostNative:
73 return llvm::sys::path::Style::native;
74 };
75 return llvm::sys::path::Style::native;
Chaoren Lin1c614fe2015-05-28 17:02:45 +000076}
77
Kate Stoneb9c1b512016-09-06 20:57:50 +000078void Denormalize(llvm::SmallVectorImpl<char> &path,
79 FileSpec::PathSyntax syntax) {
80 if (PathSyntaxIsPosix(syntax))
81 return;
Chaoren Lin1c614fe2015-05-28 17:02:45 +000082
Kate Stoneb9c1b512016-09-06 20:57:50 +000083 std::replace(path.begin(), path.end(), '/', '\\');
Chaoren Lin1c614fe2015-05-28 17:02:45 +000084}
85
Kate Stoneb9c1b512016-09-06 20:57:50 +000086size_t FilenamePos(llvm::StringRef str, FileSpec::PathSyntax syntax) {
87 if (str.size() == 2 && IsPathSeparator(str[0], syntax) && str[0] == str[1])
88 return 0;
Pavel Labath144119b2016-04-04 14:39:12 +000089
Kate Stoneb9c1b512016-09-06 20:57:50 +000090 if (str.size() > 0 && IsPathSeparator(str.back(), syntax))
91 return str.size() - 1;
Pavel Labath144119b2016-04-04 14:39:12 +000092
Kate Stoneb9c1b512016-09-06 20:57:50 +000093 size_t pos = str.find_last_of(GetPathSeparators(syntax), str.size() - 1);
Pavel Labath144119b2016-04-04 14:39:12 +000094
Kate Stoneb9c1b512016-09-06 20:57:50 +000095 if (!PathSyntaxIsPosix(syntax) && pos == llvm::StringRef::npos)
96 pos = str.find_last_of(':', str.size() - 2);
Pavel Labath144119b2016-04-04 14:39:12 +000097
Kate Stoneb9c1b512016-09-06 20:57:50 +000098 if (pos == llvm::StringRef::npos ||
99 (pos == 1 && IsPathSeparator(str[0], syntax)))
100 return 0;
Pavel Labath144119b2016-04-04 14:39:12 +0000101
Kate Stoneb9c1b512016-09-06 20:57:50 +0000102 return pos + 1;
Chaoren Lin1c614fe2015-05-28 17:02:45 +0000103}
104
Kate Stoneb9c1b512016-09-06 20:57:50 +0000105size_t RootDirStart(llvm::StringRef str, FileSpec::PathSyntax syntax) {
106 // case "c:/"
107 if (!PathSyntaxIsPosix(syntax) &&
108 (str.size() > 2 && str[1] == ':' && IsPathSeparator(str[2], syntax)))
109 return 2;
Pavel Labath144119b2016-04-04 14:39:12 +0000110
Kate Stoneb9c1b512016-09-06 20:57:50 +0000111 // case "//"
112 if (str.size() == 2 && IsPathSeparator(str[0], syntax) && str[0] == str[1])
Pavel Labath144119b2016-04-04 14:39:12 +0000113 return llvm::StringRef::npos;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000114
115 // case "//net"
116 if (str.size() > 3 && IsPathSeparator(str[0], syntax) && str[0] == str[1] &&
117 !IsPathSeparator(str[2], syntax))
118 return str.find_first_of(GetPathSeparators(syntax), 2);
119
120 // case "/"
121 if (str.size() > 0 && IsPathSeparator(str[0], syntax))
122 return 0;
123
124 return llvm::StringRef::npos;
Pavel Labath144119b2016-04-04 14:39:12 +0000125}
126
Kate Stoneb9c1b512016-09-06 20:57:50 +0000127size_t ParentPathEnd(llvm::StringRef path, FileSpec::PathSyntax syntax) {
128 size_t end_pos = FilenamePos(path, syntax);
Pavel Labath144119b2016-04-04 14:39:12 +0000129
Kate Stoneb9c1b512016-09-06 20:57:50 +0000130 bool filename_was_sep =
131 path.size() > 0 && IsPathSeparator(path[end_pos], syntax);
Pavel Labath144119b2016-04-04 14:39:12 +0000132
Kate Stoneb9c1b512016-09-06 20:57:50 +0000133 // Skip separators except for root dir.
134 size_t root_dir_pos = RootDirStart(path.substr(0, end_pos), syntax);
Pavel Labath144119b2016-04-04 14:39:12 +0000135
Kate Stoneb9c1b512016-09-06 20:57:50 +0000136 while (end_pos > 0 && (end_pos - 1) != root_dir_pos &&
137 IsPathSeparator(path[end_pos - 1], syntax))
138 --end_pos;
Pavel Labath144119b2016-04-04 14:39:12 +0000139
Kate Stoneb9c1b512016-09-06 20:57:50 +0000140 if (end_pos == 1 && root_dir_pos == 0 && filename_was_sep)
141 return llvm::StringRef::npos;
Pavel Labath144119b2016-04-04 14:39:12 +0000142
Kate Stoneb9c1b512016-09-06 20:57:50 +0000143 return end_pos;
Pavel Labath144119b2016-04-04 14:39:12 +0000144}
145
146} // end anonymous namespace
147
Kate Stoneb9c1b512016-09-06 20:57:50 +0000148void FileSpec::Resolve(llvm::SmallVectorImpl<char> &path) {
149 if (path.empty())
150 return;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000151
Zachary Turner8d48cd62017-03-22 17:33:23 +0000152 llvm::SmallString<32> Source(path.begin(), path.end());
153 StandardTildeExpressionResolver Resolver;
154 Resolver.ResolveFullPath(Source, path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000155
Kate Stoneb9c1b512016-09-06 20:57:50 +0000156 // Save a copy of the original path that's passed in
157 llvm::SmallString<128> original_path(path.begin(), path.end());
Jason Molenda671a29d2015-02-25 02:35:25 +0000158
Kate Stoneb9c1b512016-09-06 20:57:50 +0000159 llvm::sys::fs::make_absolute(path);
160 if (!llvm::sys::fs::exists(path)) {
161 path.clear();
162 path.append(original_path.begin(), original_path.end());
163 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000164}
165
Zachary Turner7d86ee52017-03-08 17:56:08 +0000166FileSpec::FileSpec() : m_syntax(GetNativeSyntax()) {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000167
168//------------------------------------------------------------------
Adrian Prantl05097242018-04-30 16:49:04 +0000169// Default constructor that can take an optional full path to a file on disk.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000170//------------------------------------------------------------------
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000171FileSpec::FileSpec(llvm::StringRef path, bool resolve_path, PathSyntax syntax)
Sam McCall6f43d9d2016-11-15 10:58:16 +0000172 : m_syntax(syntax) {
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000173 SetFile(path, resolve_path, syntax);
Jim Ingham0909e5f2010-09-16 00:57:33 +0000174}
175
Zachary Turner8c6b5462017-03-06 23:42:44 +0000176FileSpec::FileSpec(llvm::StringRef path, bool resolve_path,
177 const llvm::Triple &Triple)
178 : FileSpec{path, resolve_path,
179 Triple.isOSWindows() ? ePathSyntaxWindows : ePathSyntaxPosix} {}
Chaoren Linf34f4102015-05-09 01:21:32 +0000180
Jim Ingham0909e5f2010-09-16 00:57:33 +0000181//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000182// Copy constructor
183//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000184FileSpec::FileSpec(const FileSpec &rhs)
185 : m_directory(rhs.m_directory), m_filename(rhs.m_filename),
186 m_is_resolved(rhs.m_is_resolved), m_syntax(rhs.m_syntax) {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000187
188//------------------------------------------------------------------
189// Copy constructor
190//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000191FileSpec::FileSpec(const FileSpec *rhs) : m_directory(), m_filename() {
192 if (rhs)
193 *this = *rhs;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000194}
195
196//------------------------------------------------------------------
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +0000197// Virtual destructor in case anyone inherits from this class.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000198//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000199FileSpec::~FileSpec() {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000200
Greg Clayton776cd7a2018-04-27 15:45:58 +0000201namespace {
202//------------------------------------------------------------------
203/// Safely get a character at the specified index.
204///
205/// @param[in] path
206/// A full, partial, or relative path to a file.
207///
208/// @param[in] i
209/// An index into path which may or may not be valid.
210///
211/// @return
212/// The character at index \a i if the index is valid, or 0 if
213/// the index is not valid.
214//------------------------------------------------------------------
215inline char safeCharAtIndex(const llvm::StringRef &path, size_t i) {
216 if (i < path.size())
217 return path[i];
218 return 0;
219}
220
221//------------------------------------------------------------------
222/// Check if a path needs to be normalized.
223///
224/// Check if a path needs to be normalized. We currently consider a
225/// path to need normalization if any of the following are true
226/// - path contains "/./"
227/// - path contains "/../"
228/// - path contains "//"
229/// - path ends with "/"
230/// Paths that start with "./" or with "../" are not considered to
231/// need normalization since we aren't trying to resolve the path,
232/// we are just trying to remove redundant things from the path.
233///
234/// @param[in] path
235/// A full, partial, or relative path to a file.
236///
Greg Clayton776cd7a2018-04-27 15:45:58 +0000237/// @return
238/// Returns \b true if the path needs to be normalized.
239//------------------------------------------------------------------
Pavel Labath410c5ac2018-04-30 12:59:14 +0000240bool needsNormalization(const llvm::StringRef &path) {
Greg Clayton27a0e102018-04-27 21:10:07 +0000241 if (path.empty())
242 return false;
243 // We strip off leading "." values so these paths need to be normalized
244 if (path[0] == '.')
245 return true;
246 for (auto i = path.find_first_of("\\/"); i != llvm::StringRef::npos;
247 i = path.find_first_of("\\/", i + 1)) {
Greg Clayton776cd7a2018-04-27 15:45:58 +0000248 const auto next = safeCharAtIndex(path, i+1);
249 switch (next) {
250 case 0:
251 // path separator char at the end of the string which should be
252 // stripped unless it is the one and only character
253 return i > 0;
254 case '/':
255 case '\\':
256 // two path separator chars in the middle of a path needs to be
257 // normalized
Greg Clayton27a0e102018-04-27 21:10:07 +0000258 if (i > 0)
Greg Clayton776cd7a2018-04-27 15:45:58 +0000259 return true;
260 ++i;
261 break;
262
263 case '.': {
264 const auto next_next = safeCharAtIndex(path, i+2);
265 switch (next_next) {
266 default: break;
267 case 0: return true; // ends with "/."
268 case '/':
269 case '\\':
Greg Clayton27a0e102018-04-27 21:10:07 +0000270 return true; // contains "/./"
Greg Clayton776cd7a2018-04-27 15:45:58 +0000271 case '.': {
272 const auto next_next_next = safeCharAtIndex(path, i+3);
273 switch (next_next_next) {
274 default: break;
275 case 0: return true; // ends with "/.."
276 case '/':
277 case '\\':
Greg Clayton27a0e102018-04-27 21:10:07 +0000278 return true; // contains "/../"
Greg Clayton776cd7a2018-04-27 15:45:58 +0000279 }
280 break;
281 }
282 }
283 }
284 break;
285
286 default:
287 break;
288 }
289 }
290 return false;
291}
292
293
294}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000295//------------------------------------------------------------------
296// Assignment operator.
297//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000298const FileSpec &FileSpec::operator=(const FileSpec &rhs) {
299 if (this != &rhs) {
300 m_directory = rhs.m_directory;
301 m_filename = rhs.m_filename;
302 m_is_resolved = rhs.m_is_resolved;
303 m_syntax = rhs.m_syntax;
304 }
305 return *this;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000306}
307
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000308//------------------------------------------------------------------
Adrian Prantl05097242018-04-30 16:49:04 +0000309// Update the contents of this object with a new path. The path will be split
310// up into a directory and filename and stored as uniqued string values for
311// quick comparison and efficient memory usage.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000312//------------------------------------------------------------------
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000313void FileSpec::SetFile(llvm::StringRef pathname, bool resolve,
314 PathSyntax syntax) {
315 // CLEANUP: Use StringRef for string handling. This function is kind of a
Adrian Prantl05097242018-04-30 16:49:04 +0000316 // mess and the unclear semantics of RootDirStart and ParentPathEnd make it
317 // very difficult to understand this function. There's no reason this
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000318 // function should be particularly complicated or difficult to understand.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000319 m_filename.Clear();
320 m_directory.Clear();
321 m_is_resolved = false;
Zachary Turner7d86ee52017-03-08 17:56:08 +0000322 m_syntax = (syntax == ePathSyntaxHostNative) ? GetNativeSyntax() : syntax;
Zachary Turnerdf62f202014-08-07 17:33:07 +0000323
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000324 if (pathname.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000325 return;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000326
Kate Stoneb9c1b512016-09-06 20:57:50 +0000327 llvm::SmallString<64> resolved(pathname);
Zachary Turnerdf62f202014-08-07 17:33:07 +0000328
Kate Stoneb9c1b512016-09-06 20:57:50 +0000329 if (resolve) {
330 FileSpec::Resolve(resolved);
331 m_is_resolved = true;
332 }
Zachary Turnerc7a17ed2014-12-01 23:13:32 +0000333
Greg Clayton776cd7a2018-04-27 15:45:58 +0000334 // Normalize the path by removing ".", ".." and other redundant components.
Pavel Labath410c5ac2018-04-30 12:59:14 +0000335 if (needsNormalization(resolved))
336 llvm::sys::path::remove_dots(resolved, true, LLVMPathSyntax(m_syntax));
Greg Clayton776cd7a2018-04-27 15:45:58 +0000337
338 // Normalize back slashes to forward slashes
Pavel Labath410c5ac2018-04-30 12:59:14 +0000339 if (m_syntax == FileSpec::ePathSyntaxWindows)
Greg Clayton776cd7a2018-04-27 15:45:58 +0000340 std::replace(resolved.begin(), resolved.end(), '\\', '/');
Pavel Labatha212c582016-04-14 09:38:06 +0000341
Kate Stoneb9c1b512016-09-06 20:57:50 +0000342 llvm::StringRef resolve_path_ref(resolved.c_str());
Zachary Turner827d5d72016-12-16 04:27:00 +0000343 size_t dir_end = ParentPathEnd(resolve_path_ref, m_syntax);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000344 if (dir_end == 0) {
345 m_filename.SetString(resolve_path_ref);
346 return;
347 }
Pavel Labath144119b2016-04-04 14:39:12 +0000348
Kate Stoneb9c1b512016-09-06 20:57:50 +0000349 m_directory.SetString(resolve_path_ref.substr(0, dir_end));
Pavel Labath144119b2016-04-04 14:39:12 +0000350
Kate Stoneb9c1b512016-09-06 20:57:50 +0000351 size_t filename_begin = dir_end;
Zachary Turner827d5d72016-12-16 04:27:00 +0000352 size_t root_dir_start = RootDirStart(resolve_path_ref, m_syntax);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000353 while (filename_begin != llvm::StringRef::npos &&
354 filename_begin < resolve_path_ref.size() &&
355 filename_begin != root_dir_start &&
Zachary Turner827d5d72016-12-16 04:27:00 +0000356 IsPathSeparator(resolve_path_ref[filename_begin], m_syntax))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000357 ++filename_begin;
358 m_filename.SetString((filename_begin == llvm::StringRef::npos ||
359 filename_begin >= resolve_path_ref.size())
360 ? "."
361 : resolve_path_ref.substr(filename_begin));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000362}
363
Zachary Turner8c6b5462017-03-06 23:42:44 +0000364void FileSpec::SetFile(llvm::StringRef path, bool resolve,
365 const llvm::Triple &Triple) {
366 return SetFile(path, resolve,
367 Triple.isOSWindows() ? ePathSyntaxWindows : ePathSyntaxPosix);
Chaoren Lin44145d72015-05-29 19:52:37 +0000368}
369
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000370//----------------------------------------------------------------------
Adrian Prantl05097242018-04-30 16:49:04 +0000371// Convert to pointer operator. This allows code to check any FileSpec objects
372// to see if they contain anything valid using code such as:
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000373//
374// if (file_spec)
375// {}
376//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000377FileSpec::operator bool() const { return m_filename || m_directory; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000378
379//----------------------------------------------------------------------
Adrian Prantl05097242018-04-30 16:49:04 +0000380// Logical NOT operator. This allows code to check any FileSpec objects to see
381// if they are invalid using code such as:
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000382//
383// if (!file_spec)
384// {}
385//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000386bool FileSpec::operator!() const { return !m_directory && !m_filename; }
387
388bool FileSpec::DirectoryEquals(const FileSpec &rhs) const {
389 const bool case_sensitive = IsCaseSensitive() || rhs.IsCaseSensitive();
390 return ConstString::Equals(m_directory, rhs.m_directory, case_sensitive);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000391}
392
Kate Stoneb9c1b512016-09-06 20:57:50 +0000393bool FileSpec::FileEquals(const FileSpec &rhs) const {
394 const bool case_sensitive = IsCaseSensitive() || rhs.IsCaseSensitive();
395 return ConstString::Equals(m_filename, rhs.m_filename, case_sensitive);
Zachary Turner74e08ca2016-03-02 22:05:52 +0000396}
397
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000398//------------------------------------------------------------------
399// Equal to operator
400//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000401bool FileSpec::operator==(const FileSpec &rhs) const {
402 if (!FileEquals(rhs))
403 return false;
404 if (DirectoryEquals(rhs))
405 return true;
Zachary Turner47c03462016-02-24 21:26:47 +0000406
Kate Stoneb9c1b512016-09-06 20:57:50 +0000407 // TODO: determine if we want to keep this code in here.
Adrian Prantl05097242018-04-30 16:49:04 +0000408 // The code below was added to handle a case where we were trying to set a
409 // file and line breakpoint and one path was resolved, and the other not and
410 // the directory was in a mount point that resolved to a more complete path:
411 // "/tmp/a.c" == "/private/tmp/a.c". I might end up pulling this out...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000412 if (IsResolved() && rhs.IsResolved()) {
413 // Both paths are resolved, no need to look further...
414 return false;
415 }
Zachary Turner47c03462016-02-24 21:26:47 +0000416
Kate Stoneb9c1b512016-09-06 20:57:50 +0000417 FileSpec resolved_lhs(*this);
Zachary Turner47c03462016-02-24 21:26:47 +0000418
Kate Stoneb9c1b512016-09-06 20:57:50 +0000419 // If "this" isn't resolved, resolve it
420 if (!IsResolved()) {
421 if (resolved_lhs.ResolvePath()) {
422 // This path wasn't resolved but now it is. Check if the resolved
Adrian Prantl05097242018-04-30 16:49:04 +0000423 // directory is the same as our unresolved directory, and if so, we can
424 // mark this object as resolved to avoid more future resolves
Kate Stoneb9c1b512016-09-06 20:57:50 +0000425 m_is_resolved = (m_directory == resolved_lhs.m_directory);
426 } else
427 return false;
428 }
Zachary Turner47c03462016-02-24 21:26:47 +0000429
Kate Stoneb9c1b512016-09-06 20:57:50 +0000430 FileSpec resolved_rhs(rhs);
431 if (!rhs.IsResolved()) {
432 if (resolved_rhs.ResolvePath()) {
433 // rhs's path wasn't resolved but now it is. Check if the resolved
Adrian Prantl05097242018-04-30 16:49:04 +0000434 // directory is the same as rhs's unresolved directory, and if so, we can
435 // mark this object as resolved to avoid more future resolves
Kate Stoneb9c1b512016-09-06 20:57:50 +0000436 rhs.m_is_resolved = (rhs.m_directory == resolved_rhs.m_directory);
437 } else
438 return false;
439 }
Zachary Turner47c03462016-02-24 21:26:47 +0000440
Adrian Prantl05097242018-04-30 16:49:04 +0000441 // If we reach this point in the code we were able to resolve both paths and
442 // since we only resolve the paths if the basenames are equal, then we can
443 // just check if both directories are equal...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000444 return DirectoryEquals(rhs);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000445}
446
447//------------------------------------------------------------------
448// Not equal to operator
449//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000450bool FileSpec::operator!=(const FileSpec &rhs) const { return !(*this == rhs); }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000451
452//------------------------------------------------------------------
453// Less than operator
454//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000455bool FileSpec::operator<(const FileSpec &rhs) const {
456 return FileSpec::Compare(*this, rhs, true) < 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000457}
458
459//------------------------------------------------------------------
460// Dump a FileSpec object to a stream
461//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000462Stream &lldb_private::operator<<(Stream &s, const FileSpec &f) {
463 f.Dump(&s);
464 return s;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000465}
466
467//------------------------------------------------------------------
Adrian Prantl05097242018-04-30 16:49:04 +0000468// Clear this object by releasing both the directory and filename string values
469// and making them both the empty string.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000470//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000471void FileSpec::Clear() {
472 m_directory.Clear();
473 m_filename.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000474}
475
476//------------------------------------------------------------------
Adrian Prantl05097242018-04-30 16:49:04 +0000477// Compare two FileSpec objects. If "full" is true, then both the directory and
478// the filename must match. If "full" is false, then the directory names for
479// "a" and "b" are only compared if they are both non-empty. This allows a
480// FileSpec object to only contain a filename and it can match FileSpec objects
481// that have matching filenames with different paths.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000482//
Adrian Prantl05097242018-04-30 16:49:04 +0000483// Return -1 if the "a" is less than "b", 0 if "a" is equal to "b" and "1" if
484// "a" is greater than "b".
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000485//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000486int FileSpec::Compare(const FileSpec &a, const FileSpec &b, bool full) {
487 int result = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000488
Kate Stoneb9c1b512016-09-06 20:57:50 +0000489 // case sensitivity of compare
490 const bool case_sensitive = a.IsCaseSensitive() || b.IsCaseSensitive();
Zachary Turner47c03462016-02-24 21:26:47 +0000491
Kate Stoneb9c1b512016-09-06 20:57:50 +0000492 // If full is true, then we must compare both the directory and filename.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000493
Adrian Prantl05097242018-04-30 16:49:04 +0000494 // If full is false, then if either directory is empty, then we match on the
495 // basename only, and if both directories have valid values, we still do a
496 // full compare. This allows for matching when we just have a filename in one
497 // of the FileSpec objects.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000498
Kate Stoneb9c1b512016-09-06 20:57:50 +0000499 if (full || (a.m_directory && b.m_directory)) {
500 result = ConstString::Compare(a.m_directory, b.m_directory, case_sensitive);
501 if (result)
502 return result;
503 }
504 return ConstString::Compare(a.m_filename, b.m_filename, case_sensitive);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000505}
506
Greg Clayton776cd7a2018-04-27 15:45:58 +0000507bool FileSpec::Equal(const FileSpec &a, const FileSpec &b, bool full) {
Jim Ingham97e4f472017-03-27 19:12:25 +0000508
Kate Stoneb9c1b512016-09-06 20:57:50 +0000509 // case sensitivity of equality test
510 const bool case_sensitive = a.IsCaseSensitive() || b.IsCaseSensitive();
Jim Ingham97e4f472017-03-27 19:12:25 +0000511
Greg Clayton776cd7a2018-04-27 15:45:58 +0000512 const bool filenames_equal = ConstString::Equals(a.m_filename,
513 b.m_filename,
514 case_sensitive);
Jim Ingham97e4f472017-03-27 19:12:25 +0000515
Greg Clayton776cd7a2018-04-27 15:45:58 +0000516 if (!filenames_equal)
Jim Ingham97e4f472017-03-27 19:12:25 +0000517 return false;
518
Kate Stoneb9c1b512016-09-06 20:57:50 +0000519 if (!full && (a.GetDirectory().IsEmpty() || b.GetDirectory().IsEmpty()))
Jim Ingham97e4f472017-03-27 19:12:25 +0000520 return filenames_equal;
Pavel Labath218770b2016-10-31 16:22:07 +0000521
Greg Clayton776cd7a2018-04-27 15:45:58 +0000522 return a == b;
Jim Ingham96a15962014-11-15 01:54:26 +0000523}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000524
525//------------------------------------------------------------------
Adrian Prantl05097242018-04-30 16:49:04 +0000526// Dump the object to the supplied stream. If the object contains a valid
527// directory name, it will be displayed followed by a directory delimiter, and
528// the filename.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000529//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000530void FileSpec::Dump(Stream *s) const {
531 if (s) {
532 std::string path{GetPath(true)};
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000533 s->PutCString(path);
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000534 char path_separator = GetPreferredPathSeparator(m_syntax);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000535 if (!m_filename && !path.empty() && path.back() != path_separator)
536 s->PutChar(path_separator);
537 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000538}
539
540//------------------------------------------------------------------
541// Returns true if the file exists.
542//------------------------------------------------------------------
Zachary Turner7d86ee52017-03-08 17:56:08 +0000543bool FileSpec::Exists() const { return llvm::sys::fs::exists(GetPath()); }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000544
Kate Stoneb9c1b512016-09-06 20:57:50 +0000545bool FileSpec::Readable() const {
Zachary Turner7d86ee52017-03-08 17:56:08 +0000546 return GetPermissions() & llvm::sys::fs::perms::all_read;
Greg Clayton5acc1252014-08-15 18:00:45 +0000547}
548
Kate Stoneb9c1b512016-09-06 20:57:50 +0000549bool FileSpec::ResolveExecutableLocation() {
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000550 // CLEANUP: Use StringRef for string handling.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000551 if (!m_directory) {
552 const char *file_cstr = m_filename.GetCString();
553 if (file_cstr) {
554 const std::string file_str(file_cstr);
555 llvm::ErrorOr<std::string> error_or_path =
556 llvm::sys::findProgramByName(file_str);
557 if (!error_or_path)
Jim Ingham0909e5f2010-09-16 00:57:33 +0000558 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000559 std::string path = error_or_path.get();
560 llvm::StringRef dir_ref = llvm::sys::path::parent_path(path);
561 if (!dir_ref.empty()) {
562 // FindProgramByName returns "." if it can't find the file.
563 if (strcmp(".", dir_ref.data()) == 0)
564 return false;
565
566 m_directory.SetCString(dir_ref.data());
567 if (Exists())
568 return true;
569 else {
570 // If FindProgramByName found the file, it returns the directory +
Adrian Prantl05097242018-04-30 16:49:04 +0000571 // filename in its return results. We need to separate them.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000572 FileSpec tmp_file(dir_ref.data(), false);
573 if (tmp_file.Exists()) {
574 m_directory = tmp_file.m_directory;
575 return true;
576 }
577 }
578 }
579 }
580 }
581
582 return false;
Jim Ingham0909e5f2010-09-16 00:57:33 +0000583}
584
Kate Stoneb9c1b512016-09-06 20:57:50 +0000585bool FileSpec::ResolvePath() {
586 if (m_is_resolved)
587 return true; // We have already resolved this path
588
Kate Stoneb9c1b512016-09-06 20:57:50 +0000589 // SetFile(...) will set m_is_resolved correctly if it can resolve the path
Pavel Labath9bd69ad2017-03-13 09:46:15 +0000590 SetFile(GetPath(false), true);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000591 return m_is_resolved;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000592}
593
Kate Stoneb9c1b512016-09-06 20:57:50 +0000594uint64_t FileSpec::GetByteSize() const {
Zachary Turner7d86ee52017-03-08 17:56:08 +0000595 uint64_t Size = 0;
596 if (llvm::sys::fs::file_size(GetPath(), Size))
597 return 0;
598 return Size;
Zachary Turnerdf62f202014-08-07 17:33:07 +0000599}
600
Kate Stoneb9c1b512016-09-06 20:57:50 +0000601FileSpec::PathSyntax FileSpec::GetPathSyntax() const { return m_syntax; }
602
Pavel Labath30e6cbf2017-03-07 13:19:15 +0000603uint32_t FileSpec::GetPermissions() const {
Zachary Turner7d86ee52017-03-08 17:56:08 +0000604 namespace fs = llvm::sys::fs;
605 fs::file_status st;
606 if (fs::status(GetPath(), st, false))
607 return fs::perms::perms_not_known;
608
609 return st.permissions();
Greg Claytonfbb76342013-11-20 21:07:01 +0000610}
611
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000612//------------------------------------------------------------------
613// Directory string get accessor.
614//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000615ConstString &FileSpec::GetDirectory() { return m_directory; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000616
617//------------------------------------------------------------------
618// Directory string const get accessor.
619//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000620const ConstString &FileSpec::GetDirectory() const { return m_directory; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000621
622//------------------------------------------------------------------
623// Filename string get accessor.
624//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000625ConstString &FileSpec::GetFilename() { return m_filename; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000626
627//------------------------------------------------------------------
628// Filename string const get accessor.
629//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000630const ConstString &FileSpec::GetFilename() const { return m_filename; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000631
632//------------------------------------------------------------------
Adrian Prantl05097242018-04-30 16:49:04 +0000633// Extract the directory and path into a fixed buffer. This is needed as the
634// directory and path are stored in separate string values.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000635//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000636size_t FileSpec::GetPath(char *path, size_t path_max_len,
637 bool denormalize) const {
638 if (!path)
639 return 0;
Zachary Turnerb6d99242014-08-08 23:54:35 +0000640
Kate Stoneb9c1b512016-09-06 20:57:50 +0000641 std::string result = GetPath(denormalize);
642 ::snprintf(path, path_max_len, "%s", result.c_str());
643 return std::min(path_max_len - 1, result.length());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000644}
645
Kate Stoneb9c1b512016-09-06 20:57:50 +0000646std::string FileSpec::GetPath(bool denormalize) const {
647 llvm::SmallString<64> result;
648 GetPath(result, denormalize);
649 return std::string(result.begin(), result.end());
Jason Molendaa7ae4672013-04-29 09:46:43 +0000650}
651
Kate Stoneb9c1b512016-09-06 20:57:50 +0000652const char *FileSpec::GetCString(bool denormalize) const {
653 return ConstString{GetPath(denormalize)}.AsCString(NULL);
Chaoren Lind3173f32015-05-29 19:52:29 +0000654}
655
Kate Stoneb9c1b512016-09-06 20:57:50 +0000656void FileSpec::GetPath(llvm::SmallVectorImpl<char> &path,
657 bool denormalize) const {
658 path.append(m_directory.GetStringRef().begin(),
659 m_directory.GetStringRef().end());
Greg Clayton776cd7a2018-04-27 15:45:58 +0000660 // Since the path was normalized and all paths use '/' when stored in these
661 // objects, we don't need to look for the actual syntax specific path
662 // separator, we just look for and insert '/'.
663 if (m_directory && m_filename && m_directory.GetStringRef().back() != '/' &&
664 m_filename.GetStringRef().back() != '/')
665 path.insert(path.end(), '/');
Kate Stoneb9c1b512016-09-06 20:57:50 +0000666 path.append(m_filename.GetStringRef().begin(),
667 m_filename.GetStringRef().end());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000668 if (denormalize && !path.empty())
669 Denormalize(path, m_syntax);
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000670}
671
Kate Stoneb9c1b512016-09-06 20:57:50 +0000672ConstString FileSpec::GetFileNameExtension() const {
673 if (m_filename) {
Enrico Granataa9dbf432011-10-17 21:45:27 +0000674 const char *filename = m_filename.GetCString();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000675 const char *dot_pos = strrchr(filename, '.');
676 if (dot_pos && dot_pos[1] != '\0')
677 return ConstString(dot_pos + 1);
678 }
679 return ConstString();
680}
681
682ConstString FileSpec::GetFileNameStrippingExtension() const {
683 const char *filename = m_filename.GetCString();
684 if (filename == NULL)
685 return ConstString();
686
687 const char *dot_pos = strrchr(filename, '.');
688 if (dot_pos == NULL)
689 return m_filename;
690
691 return ConstString(filename, dot_pos - filename);
Enrico Granataa9dbf432011-10-17 21:45:27 +0000692}
693
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000694//------------------------------------------------------------------
Adrian Prantl05097242018-04-30 16:49:04 +0000695// Return the size in bytes that this object takes in memory. This returns the
696// size in bytes of this object, not any shared string values it may refer to.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000697//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000698size_t FileSpec::MemorySize() const {
699 return m_filename.MemorySize() + m_directory.MemorySize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000700}
701
Zachary Turner1f875342017-03-13 02:44:39 +0000702void FileSpec::EnumerateDirectory(llvm::StringRef dir_path,
703 bool find_directories, bool find_files,
704 bool find_other,
705 EnumerateDirectoryCallbackType callback,
706 void *callback_baton) {
707 namespace fs = llvm::sys::fs;
708 std::error_code EC;
709 fs::recursive_directory_iterator Iter(dir_path, EC);
710 fs::recursive_directory_iterator End;
711 for (; Iter != End && !EC; Iter.increment(EC)) {
712 const auto &Item = *Iter;
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000713 llvm::ErrorOr<fs::basic_file_status> Status = Item.status();
714 if (!Status)
Zachary Turner1f875342017-03-13 02:44:39 +0000715 break;
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000716 if (!find_files && fs::is_regular_file(*Status))
Zachary Turner1f875342017-03-13 02:44:39 +0000717 continue;
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000718 if (!find_directories && fs::is_directory(*Status))
Zachary Turner1f875342017-03-13 02:44:39 +0000719 continue;
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000720 if (!find_other && fs::is_other(*Status))
Zachary Turner1f875342017-03-13 02:44:39 +0000721 continue;
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000722
Zachary Turner1f875342017-03-13 02:44:39 +0000723 FileSpec Spec(Item.path(), false);
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000724 auto Result = callback(callback_baton, Status->type(), Spec);
Zachary Turner1f875342017-03-13 02:44:39 +0000725 if (Result == eEnumerateDirectoryResultQuit)
726 return;
727 if (Result == eEnumerateDirectoryResultNext) {
728 // Default behavior is to recurse. Opt out if the callback doesn't want
729 // this behavior.
730 Iter.no_push();
Greg Clayton58c65f02015-06-29 18:29:00 +0000731 }
Zachary Turner1f875342017-03-13 02:44:39 +0000732 }
Daniel Maleae0f8f572013-08-26 23:57:52 +0000733}
734
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000735FileSpec
736FileSpec::CopyByAppendingPathComponent(llvm::StringRef component) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000737 FileSpec ret = *this;
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000738 ret.AppendPathComponent(component);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000739 return ret;
Chaoren Lin0c5a9c12015-06-05 00:28:06 +0000740}
741
Kate Stoneb9c1b512016-09-06 20:57:50 +0000742FileSpec FileSpec::CopyByRemovingLastPathComponent() const {
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000743 // CLEANUP: Use StringRef for string handling.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000744 const bool resolve = false;
745 if (m_filename.IsEmpty() && m_directory.IsEmpty())
746 return FileSpec("", resolve);
747 if (m_directory.IsEmpty())
748 return FileSpec("", resolve);
749 if (m_filename.IsEmpty()) {
750 const char *dir_cstr = m_directory.GetCString();
751 const char *last_slash_ptr = ::strrchr(dir_cstr, '/');
752
753 // check for obvious cases before doing the full thing
754 if (!last_slash_ptr)
755 return FileSpec("", resolve);
756 if (last_slash_ptr == dir_cstr)
757 return FileSpec("/", resolve);
758
759 size_t last_slash_pos = last_slash_ptr - dir_cstr + 1;
760 ConstString new_path(dir_cstr, last_slash_pos);
761 return FileSpec(new_path.GetCString(), resolve);
762 } else
763 return FileSpec(m_directory.GetCString(), resolve);
Chaoren Lin0c5a9c12015-06-05 00:28:06 +0000764}
765
Kate Stoneb9c1b512016-09-06 20:57:50 +0000766ConstString FileSpec::GetLastPathComponent() const {
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000767 // CLEANUP: Use StringRef for string handling.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000768 if (m_filename)
769 return m_filename;
770 if (m_directory) {
771 const char *dir_cstr = m_directory.GetCString();
772 const char *last_slash_ptr = ::strrchr(dir_cstr, '/');
773 if (last_slash_ptr == NULL)
774 return m_directory;
775 if (last_slash_ptr == dir_cstr) {
776 if (last_slash_ptr[1] == 0)
777 return ConstString(last_slash_ptr);
778 else
779 return ConstString(last_slash_ptr + 1);
780 }
781 if (last_slash_ptr[1] != 0)
782 return ConstString(last_slash_ptr + 1);
783 const char *penultimate_slash_ptr = last_slash_ptr;
784 while (*penultimate_slash_ptr) {
785 --penultimate_slash_ptr;
786 if (penultimate_slash_ptr == dir_cstr)
787 break;
788 if (*penultimate_slash_ptr == '/')
789 break;
790 }
791 ConstString result(penultimate_slash_ptr + 1,
792 last_slash_ptr - penultimate_slash_ptr);
793 return result;
794 }
795 return ConstString();
Chaoren Lin0c5a9c12015-06-05 00:28:06 +0000796}
797
Pavel Labath59d725c2017-01-16 10:07:02 +0000798static std::string
799join_path_components(FileSpec::PathSyntax syntax,
800 const std::vector<llvm::StringRef> components) {
801 std::string result;
802 for (size_t i = 0; i < components.size(); ++i) {
803 if (components[i].empty())
804 continue;
805 result += components[i];
806 if (i != components.size() - 1 &&
807 !IsPathSeparator(components[i].back(), syntax))
808 result += GetPreferredPathSeparator(syntax);
809 }
810
811 return result;
812}
813
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000814void FileSpec::PrependPathComponent(llvm::StringRef component) {
815 if (component.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000816 return;
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000817
Kate Stoneb9c1b512016-09-06 20:57:50 +0000818 const bool resolve = false;
819 if (m_filename.IsEmpty() && m_directory.IsEmpty()) {
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000820 SetFile(component, resolve);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000821 return;
822 }
Daniel Maleae0f8f572013-08-26 23:57:52 +0000823
Pavel Labath59d725c2017-01-16 10:07:02 +0000824 std::string result =
825 join_path_components(m_syntax, {component, m_directory.GetStringRef(),
826 m_filename.GetStringRef()});
Pavel Labath238169d2017-01-16 12:15:42 +0000827 SetFile(result, resolve, m_syntax);
Chaoren Lind3173f32015-05-29 19:52:29 +0000828}
829
Kate Stoneb9c1b512016-09-06 20:57:50 +0000830void FileSpec::PrependPathComponent(const FileSpec &new_path) {
831 return PrependPathComponent(new_path.GetPath(false));
Chaoren Lin0c5a9c12015-06-05 00:28:06 +0000832}
833
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000834void FileSpec::AppendPathComponent(llvm::StringRef component) {
835 if (component.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000836 return;
837
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000838 component = component.drop_while(
839 [this](char c) { return IsPathSeparator(c, m_syntax); });
Kate Stoneb9c1b512016-09-06 20:57:50 +0000840
Pavel Labath59d725c2017-01-16 10:07:02 +0000841 std::string result =
842 join_path_components(m_syntax, {m_directory.GetStringRef(),
843 m_filename.GetStringRef(), component});
Kate Stoneb9c1b512016-09-06 20:57:50 +0000844
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000845 SetFile(result, false, m_syntax);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000846}
847
848void FileSpec::AppendPathComponent(const FileSpec &new_path) {
849 return AppendPathComponent(new_path.GetPath(false));
850}
851
852void FileSpec::RemoveLastPathComponent() {
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000853 // CLEANUP: Use StringRef for string handling.
854
Kate Stoneb9c1b512016-09-06 20:57:50 +0000855 const bool resolve = false;
856 if (m_filename.IsEmpty() && m_directory.IsEmpty()) {
857 SetFile("", resolve);
858 return;
859 }
860 if (m_directory.IsEmpty()) {
861 SetFile("", resolve);
862 return;
863 }
864 if (m_filename.IsEmpty()) {
865 const char *dir_cstr = m_directory.GetCString();
866 const char *last_slash_ptr = ::strrchr(dir_cstr, '/');
867
868 // check for obvious cases before doing the full thing
869 if (!last_slash_ptr) {
870 SetFile("", resolve);
871 return;
Daniel Maleae0f8f572013-08-26 23:57:52 +0000872 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000873 if (last_slash_ptr == dir_cstr) {
874 SetFile("/", resolve);
875 return;
Daniel Maleae0f8f572013-08-26 23:57:52 +0000876 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000877 size_t last_slash_pos = last_slash_ptr - dir_cstr + 1;
878 ConstString new_path(dir_cstr, last_slash_pos);
879 SetFile(new_path.GetCString(), resolve);
880 } else
881 SetFile(m_directory.GetCString(), resolve);
Daniel Maleae0f8f572013-08-26 23:57:52 +0000882}
Greg Clayton1f746072012-08-29 21:13:06 +0000883//------------------------------------------------------------------
884/// Returns true if the filespec represents an implementation source
885/// file (files with a ".c", ".cpp", ".m", ".mm" (many more)
886/// extension).
887///
888/// @return
889/// \b true if the filespec represents an implementation source
890/// file, \b false otherwise.
891//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000892bool FileSpec::IsSourceImplementationFile() const {
893 ConstString extension(GetFileNameExtension());
Zachary Turner95eae422016-09-21 16:01:28 +0000894 if (!extension)
895 return false;
896
897 static RegularExpression g_source_file_regex(llvm::StringRef(
898 "^([cC]|[mM]|[mM][mM]|[cC][pP][pP]|[cC]\\+\\+|[cC][xX][xX]|[cC][cC]|["
899 "cC][pP]|[sS]|[aA][sS][mM]|[fF]|[fF]77|[fF]90|[fF]95|[fF]03|[fF][oO]["
900 "rR]|[fF][tT][nN]|[fF][pP][pP]|[aA][dD][aA]|[aA][dD][bB]|[aA][dD][sS])"
901 "$"));
902 return g_source_file_regex.Execute(extension.GetStringRef());
Greg Clayton1f746072012-08-29 21:13:06 +0000903}
904
Kate Stoneb9c1b512016-09-06 20:57:50 +0000905bool FileSpec::IsRelative() const {
906 const char *dir = m_directory.GetCString();
907 llvm::StringRef directory(dir ? dir : "");
Zachary Turner270e99a2014-12-08 21:36:42 +0000908
Kate Stoneb9c1b512016-09-06 20:57:50 +0000909 if (directory.size() > 0) {
910 if (PathSyntaxIsPosix(m_syntax)) {
911 // If the path doesn't start with '/' or '~', return true
912 switch (directory[0]) {
913 case '/':
914 case '~':
915 return false;
916 default:
Greg Claytona0ca6602012-10-18 16:33:33 +0000917 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000918 }
919 } else {
920 if (directory.size() >= 2 && directory[1] == ':')
921 return false;
922 if (directory[0] == '/')
923 return false;
924 return true;
Greg Claytona0ca6602012-10-18 16:33:33 +0000925 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000926 } else if (m_filename) {
927 // No directory, just a basename, return true
928 return true;
929 }
930 return false;
Greg Claytona0ca6602012-10-18 16:33:33 +0000931}
Chaoren Lin372e9062015-06-09 17:54:27 +0000932
Kate Stoneb9c1b512016-09-06 20:57:50 +0000933bool FileSpec::IsAbsolute() const { return !FileSpec::IsRelative(); }
Zachary Turner827d5d72016-12-16 04:27:00 +0000934
935void llvm::format_provider<FileSpec>::format(const FileSpec &F,
936 raw_ostream &Stream,
937 StringRef Style) {
938 assert(
939 (Style.empty() || Style.equals_lower("F") || Style.equals_lower("D")) &&
940 "Invalid FileSpec style!");
941
942 StringRef dir = F.GetDirectory().GetStringRef();
943 StringRef file = F.GetFilename().GetStringRef();
944
945 if (dir.empty() && file.empty()) {
946 Stream << "(empty)";
947 return;
948 }
949
950 if (Style.equals_lower("F")) {
951 Stream << (file.empty() ? "(empty)" : file);
952 return;
953 }
954
955 // Style is either D or empty, either way we need to print the directory.
956 if (!dir.empty()) {
Adrian Prantl05097242018-04-30 16:49:04 +0000957 // Directory is stored in normalized form, which might be different than
958 // preferred form. In order to handle this, we need to cut off the
959 // filename, then denormalize, then write the entire denorm'ed directory.
Zachary Turner827d5d72016-12-16 04:27:00 +0000960 llvm::SmallString<64> denormalized_dir = dir;
961 Denormalize(denormalized_dir, F.GetPathSyntax());
962 Stream << denormalized_dir;
963 Stream << GetPreferredPathSeparator(F.GetPathSyntax());
964 }
965
966 if (Style.equals_lower("D")) {
967 // We only want to print the directory, so now just exit.
968 if (dir.empty())
969 Stream << "(empty)";
970 return;
971 }
972
973 if (!file.empty())
974 Stream << file;
975}