blob: b6952f7e3eb04e8d659586a3cbce37b9af4679cc [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
Jonas Devliegheread8d48f2018-06-13 16:23:21 +000015#include "llvm/ADT/SmallString.h"
16#include "llvm/ADT/SmallVector.h"
Caroline Tice391a9602010-09-12 00:10:52 +000017#include "llvm/ADT/StringRef.h"
Jonas Devliegheread8d48f2018-06-13 16:23:21 +000018#include "llvm/ADT/Triple.h"
19#include "llvm/ADT/Twine.h"
20#include "llvm/Support/ErrorOr.h"
Zachary Turner3f559742014-08-07 17:33:36 +000021#include "llvm/Support/FileSystem.h"
Greg Clayton38a61402010-12-02 23:20:03 +000022#include "llvm/Support/Program.h"
Jonas Devliegheread8d48f2018-06-13 16:23:21 +000023#include "llvm/Support/raw_ostream.h"
Zachary Turner4479ac12017-04-06 18:12:24 +000024
25#include <algorithm> // for replace, min, unique
26#include <system_error> // for error_code
27#include <vector> // for vector
28
29#include <assert.h> // for assert
30#include <stdio.h> // for size_t, NULL, snpr...
31#include <string.h> // for strcmp
Caroline Tice391a9602010-09-12 00:10:52 +000032
Chris Lattner30fdc8d2010-06-08 16:52:24 +000033using namespace lldb;
34using namespace lldb_private;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000035
Chaoren Lin1c614fe2015-05-28 17:02:45 +000036namespace {
37
Pavel Labath2cb7cf82018-05-14 14:52:47 +000038static constexpr FileSpec::Style GetNativeStyle() {
Nico Weberb1cb0b792018-04-10 13:33:45 +000039#if defined(_WIN32)
Pavel Labath2cb7cf82018-05-14 14:52:47 +000040 return FileSpec::Style::windows;
Zachary Turner7d86ee52017-03-08 17:56:08 +000041#else
Pavel Labath2cb7cf82018-05-14 14:52:47 +000042 return FileSpec::Style::posix;
Zachary Turner7d86ee52017-03-08 17:56:08 +000043#endif
44}
45
Pavel Labath2cb7cf82018-05-14 14:52:47 +000046bool PathStyleIsPosix(FileSpec::Style style) {
47 return (style == FileSpec::Style::posix ||
48 (style == FileSpec::Style::native &&
49 GetNativeStyle() == FileSpec::Style::posix));
Chaoren Lin1c614fe2015-05-28 17:02:45 +000050}
51
Pavel Labath2cb7cf82018-05-14 14:52:47 +000052const char *GetPathSeparators(FileSpec::Style style) {
Jonas Devliegheread8d48f2018-06-13 16:23:21 +000053 return llvm::sys::path::get_separator(style).data();
Pavel Labath144119b2016-04-04 14:39:12 +000054}
55
Pavel Labath2cb7cf82018-05-14 14:52:47 +000056char GetPreferredPathSeparator(FileSpec::Style style) {
57 return GetPathSeparators(style)[0];
Pavel Labath144119b2016-04-04 14:39:12 +000058}
59
Pavel Labath2cb7cf82018-05-14 14:52:47 +000060void Denormalize(llvm::SmallVectorImpl<char> &path, FileSpec::Style style) {
61 if (PathStyleIsPosix(style))
Kate Stoneb9c1b512016-09-06 20:57:50 +000062 return;
Chaoren Lin1c614fe2015-05-28 17:02:45 +000063
Kate Stoneb9c1b512016-09-06 20:57:50 +000064 std::replace(path.begin(), path.end(), '/', '\\');
Chaoren Lin1c614fe2015-05-28 17:02:45 +000065}
Greg Clayton86188d82018-05-21 14:14:36 +000066
Pavel Labath144119b2016-04-04 14:39:12 +000067} // end anonymous namespace
68
Kate Stoneb9c1b512016-09-06 20:57:50 +000069void FileSpec::Resolve(llvm::SmallVectorImpl<char> &path) {
70 if (path.empty())
71 return;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000072
Zachary Turner8d48cd62017-03-22 17:33:23 +000073 llvm::SmallString<32> Source(path.begin(), path.end());
74 StandardTildeExpressionResolver Resolver;
75 Resolver.ResolveFullPath(Source, path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +000076
Kate Stoneb9c1b512016-09-06 20:57:50 +000077 // Save a copy of the original path that's passed in
78 llvm::SmallString<128> original_path(path.begin(), path.end());
Jason Molenda671a29d2015-02-25 02:35:25 +000079
Kate Stoneb9c1b512016-09-06 20:57:50 +000080 llvm::sys::fs::make_absolute(path);
81 if (!llvm::sys::fs::exists(path)) {
82 path.clear();
83 path.append(original_path.begin(), original_path.end());
84 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +000085}
86
Pavel Labath2cb7cf82018-05-14 14:52:47 +000087FileSpec::FileSpec() : m_style(GetNativeStyle()) {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +000088
89//------------------------------------------------------------------
Adrian Prantl05097242018-04-30 16:49:04 +000090// Default constructor that can take an optional full path to a file on disk.
Chris Lattner30fdc8d2010-06-08 16:52:24 +000091//------------------------------------------------------------------
Pavel Labath2cb7cf82018-05-14 14:52:47 +000092FileSpec::FileSpec(llvm::StringRef path, bool resolve_path, Style style)
93 : m_style(style) {
94 SetFile(path, resolve_path, style);
Jim Ingham0909e5f2010-09-16 00:57:33 +000095}
96
Zachary Turner8c6b5462017-03-06 23:42:44 +000097FileSpec::FileSpec(llvm::StringRef path, bool resolve_path,
98 const llvm::Triple &Triple)
99 : FileSpec{path, resolve_path,
Pavel Labath2cb7cf82018-05-14 14:52:47 +0000100 Triple.isOSWindows() ? Style::windows : Style::posix} {}
Chaoren Linf34f4102015-05-09 01:21:32 +0000101
Jim Ingham0909e5f2010-09-16 00:57:33 +0000102//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000103// Copy constructor
104//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000105FileSpec::FileSpec(const FileSpec &rhs)
106 : m_directory(rhs.m_directory), m_filename(rhs.m_filename),
Pavel Labath2cb7cf82018-05-14 14:52:47 +0000107 m_is_resolved(rhs.m_is_resolved), m_style(rhs.m_style) {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000108
109//------------------------------------------------------------------
110// Copy constructor
111//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000112FileSpec::FileSpec(const FileSpec *rhs) : m_directory(), m_filename() {
113 if (rhs)
114 *this = *rhs;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000115}
116
117//------------------------------------------------------------------
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +0000118// Virtual destructor in case anyone inherits from this class.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000119//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000120FileSpec::~FileSpec() {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000121
Jonas Devliegherec1cc3172018-06-25 10:11:53 +0000122namespace {
123//------------------------------------------------------------------
124/// Safely get a character at the specified index.
125///
126/// @param[in] path
127/// A full, partial, or relative path to a file.
128///
129/// @param[in] i
130/// An index into path which may or may not be valid.
131///
132/// @return
133/// The character at index \a i if the index is valid, or 0 if
134/// the index is not valid.
135//------------------------------------------------------------------
136inline char safeCharAtIndex(const llvm::StringRef &path, size_t i) {
137 if (i < path.size())
138 return path[i];
139 return 0;
140}
141
142//------------------------------------------------------------------
143/// Check if a path needs to be normalized.
144///
145/// Check if a path needs to be normalized. We currently consider a
146/// path to need normalization if any of the following are true
147/// - path contains "/./"
148/// - path contains "/../"
149/// - path contains "//"
150/// - path ends with "/"
151/// Paths that start with "./" or with "../" are not considered to
152/// need normalization since we aren't trying to resolve the path,
153/// we are just trying to remove redundant things from the path.
154///
155/// @param[in] path
156/// A full, partial, or relative path to a file.
157///
158/// @return
159/// Returns \b true if the path needs to be normalized.
160//------------------------------------------------------------------
161bool needsNormalization(const llvm::StringRef &path) {
162 if (path.empty())
163 return false;
164 // We strip off leading "." values so these paths need to be normalized
165 if (path[0] == '.')
166 return true;
167 for (auto i = path.find_first_of("\\/"); i != llvm::StringRef::npos;
168 i = path.find_first_of("\\/", i + 1)) {
169 const auto next = safeCharAtIndex(path, i+1);
170 switch (next) {
171 case 0:
172 // path separator char at the end of the string which should be
173 // stripped unless it is the one and only character
174 return i > 0;
175 case '/':
176 case '\\':
177 // two path separator chars in the middle of a path needs to be
178 // normalized
179 if (i > 0)
180 return true;
181 ++i;
182 break;
183
184 case '.': {
185 const auto next_next = safeCharAtIndex(path, i+2);
186 switch (next_next) {
187 default: break;
188 case 0: return true; // ends with "/."
189 case '/':
190 case '\\':
191 return true; // contains "/./"
192 case '.': {
193 const auto next_next_next = safeCharAtIndex(path, i+3);
194 switch (next_next_next) {
195 default: break;
196 case 0: return true; // ends with "/.."
197 case '/':
198 case '\\':
199 return true; // contains "/../"
200 }
201 break;
202 }
203 }
204 }
205 break;
206
207 default:
208 break;
209 }
210 }
211 return false;
212}
213
214
215}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000216//------------------------------------------------------------------
217// Assignment operator.
218//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000219const FileSpec &FileSpec::operator=(const FileSpec &rhs) {
220 if (this != &rhs) {
221 m_directory = rhs.m_directory;
222 m_filename = rhs.m_filename;
223 m_is_resolved = rhs.m_is_resolved;
Pavel Labath2cb7cf82018-05-14 14:52:47 +0000224 m_style = rhs.m_style;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000225 }
226 return *this;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000227}
228
Jonas Devlieghere937348c2018-06-13 22:08:14 +0000229void FileSpec::SetFile(llvm::StringRef pathname, bool resolve) {
230 SetFile(pathname, resolve, m_style);
231}
232
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000233//------------------------------------------------------------------
Adrian Prantl05097242018-04-30 16:49:04 +0000234// Update the contents of this object with a new path. The path will be split
235// up into a directory and filename and stored as uniqued string values for
236// quick comparison and efficient memory usage.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000237//------------------------------------------------------------------
Pavel Labath2cb7cf82018-05-14 14:52:47 +0000238void FileSpec::SetFile(llvm::StringRef pathname, bool resolve, Style style) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000239 m_filename.Clear();
240 m_directory.Clear();
241 m_is_resolved = false;
Pavel Labath2cb7cf82018-05-14 14:52:47 +0000242 m_style = (style == Style::native) ? GetNativeStyle() : style;
Zachary Turnerdf62f202014-08-07 17:33:07 +0000243
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000244 if (pathname.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000245 return;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000246
Kate Stoneb9c1b512016-09-06 20:57:50 +0000247 llvm::SmallString<64> resolved(pathname);
Zachary Turnerdf62f202014-08-07 17:33:07 +0000248
Kate Stoneb9c1b512016-09-06 20:57:50 +0000249 if (resolve) {
250 FileSpec::Resolve(resolved);
251 m_is_resolved = true;
252 }
Zachary Turnerc7a17ed2014-12-01 23:13:32 +0000253
Greg Clayton776cd7a2018-04-27 15:45:58 +0000254 // Normalize the path by removing ".", ".." and other redundant components.
Jonas Devliegherec1cc3172018-06-25 10:11:53 +0000255 if (needsNormalization(resolved))
256 llvm::sys::path::remove_dots(resolved, true, m_style);
Greg Clayton776cd7a2018-04-27 15:45:58 +0000257
258 // Normalize back slashes to forward slashes
Pavel Labath2cb7cf82018-05-14 14:52:47 +0000259 if (m_style == Style::windows)
Greg Clayton776cd7a2018-04-27 15:45:58 +0000260 std::replace(resolved.begin(), resolved.end(), '\\', '/');
Pavel Labatha212c582016-04-14 09:38:06 +0000261
Greg Clayton39d50b72018-05-17 16:12:38 +0000262 if (resolved.empty()) {
263 // If we have no path after normalization set the path to the current
264 // directory. This matches what python does and also a few other path
Jonas Devliegheread8d48f2018-06-13 16:23:21 +0000265 // utilities.
Greg Clayton39d50b72018-05-17 16:12:38 +0000266 m_filename.SetString(".");
267 return;
268 }
269
Jonas Devliegheread8d48f2018-06-13 16:23:21 +0000270 // Split path into filename and directory. We rely on the underlying char
271 // pointer to be nullptr when the components are empty.
272 llvm::StringRef filename = llvm::sys::path::filename(resolved, m_style);
Jonas Devliegherec1cc3172018-06-25 10:11:53 +0000273 if(!filename.empty())
Jonas Devliegheread8d48f2018-06-13 16:23:21 +0000274 m_filename.SetString(filename);
275 llvm::StringRef directory = llvm::sys::path::parent_path(resolved, m_style);
Jonas Devliegherec1cc3172018-06-25 10:11:53 +0000276 if(!directory.empty())
Jonas Devliegheread8d48f2018-06-13 16:23:21 +0000277 m_directory.SetString(directory);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000278}
279
Zachary Turner8c6b5462017-03-06 23:42:44 +0000280void FileSpec::SetFile(llvm::StringRef path, bool resolve,
281 const llvm::Triple &Triple) {
282 return SetFile(path, resolve,
Pavel Labath2cb7cf82018-05-14 14:52:47 +0000283 Triple.isOSWindows() ? Style::windows : Style::posix);
Chaoren Lin44145d72015-05-29 19:52:37 +0000284}
285
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000286//----------------------------------------------------------------------
Adrian Prantl05097242018-04-30 16:49:04 +0000287// Convert to pointer operator. This allows code to check any FileSpec objects
288// to see if they contain anything valid using code such as:
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000289//
290// if (file_spec)
291// {}
292//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000293FileSpec::operator bool() const { return m_filename || m_directory; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000294
295//----------------------------------------------------------------------
Adrian Prantl05097242018-04-30 16:49:04 +0000296// Logical NOT operator. This allows code to check any FileSpec objects to see
297// if they are invalid using code such as:
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000298//
299// if (!file_spec)
300// {}
301//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000302bool FileSpec::operator!() const { return !m_directory && !m_filename; }
303
304bool FileSpec::DirectoryEquals(const FileSpec &rhs) const {
305 const bool case_sensitive = IsCaseSensitive() || rhs.IsCaseSensitive();
306 return ConstString::Equals(m_directory, rhs.m_directory, case_sensitive);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000307}
308
Kate Stoneb9c1b512016-09-06 20:57:50 +0000309bool FileSpec::FileEquals(const FileSpec &rhs) const {
310 const bool case_sensitive = IsCaseSensitive() || rhs.IsCaseSensitive();
311 return ConstString::Equals(m_filename, rhs.m_filename, case_sensitive);
Zachary Turner74e08ca2016-03-02 22:05:52 +0000312}
313
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000314//------------------------------------------------------------------
315// Equal to operator
316//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000317bool FileSpec::operator==(const FileSpec &rhs) const {
318 if (!FileEquals(rhs))
319 return false;
320 if (DirectoryEquals(rhs))
321 return true;
Zachary Turner47c03462016-02-24 21:26:47 +0000322
Kate Stoneb9c1b512016-09-06 20:57:50 +0000323 // TODO: determine if we want to keep this code in here.
Adrian Prantl05097242018-04-30 16:49:04 +0000324 // The code below was added to handle a case where we were trying to set a
325 // file and line breakpoint and one path was resolved, and the other not and
326 // the directory was in a mount point that resolved to a more complete path:
327 // "/tmp/a.c" == "/private/tmp/a.c". I might end up pulling this out...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000328 if (IsResolved() && rhs.IsResolved()) {
329 // Both paths are resolved, no need to look further...
330 return false;
331 }
Zachary Turner47c03462016-02-24 21:26:47 +0000332
Kate Stoneb9c1b512016-09-06 20:57:50 +0000333 FileSpec resolved_lhs(*this);
Zachary Turner47c03462016-02-24 21:26:47 +0000334
Kate Stoneb9c1b512016-09-06 20:57:50 +0000335 // If "this" isn't resolved, resolve it
336 if (!IsResolved()) {
337 if (resolved_lhs.ResolvePath()) {
338 // This path wasn't resolved but now it is. Check if the resolved
Adrian Prantl05097242018-04-30 16:49:04 +0000339 // directory is the same as our unresolved directory, and if so, we can
340 // mark this object as resolved to avoid more future resolves
Kate Stoneb9c1b512016-09-06 20:57:50 +0000341 m_is_resolved = (m_directory == resolved_lhs.m_directory);
342 } else
343 return false;
344 }
Zachary Turner47c03462016-02-24 21:26:47 +0000345
Kate Stoneb9c1b512016-09-06 20:57:50 +0000346 FileSpec resolved_rhs(rhs);
347 if (!rhs.IsResolved()) {
348 if (resolved_rhs.ResolvePath()) {
349 // rhs's path wasn't resolved but now it is. Check if the resolved
Adrian Prantl05097242018-04-30 16:49:04 +0000350 // directory is the same as rhs's unresolved directory, and if so, we can
351 // mark this object as resolved to avoid more future resolves
Kate Stoneb9c1b512016-09-06 20:57:50 +0000352 rhs.m_is_resolved = (rhs.m_directory == resolved_rhs.m_directory);
353 } else
354 return false;
355 }
Zachary Turner47c03462016-02-24 21:26:47 +0000356
Adrian Prantl05097242018-04-30 16:49:04 +0000357 // If we reach this point in the code we were able to resolve both paths and
358 // since we only resolve the paths if the basenames are equal, then we can
359 // just check if both directories are equal...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000360 return DirectoryEquals(rhs);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000361}
362
363//------------------------------------------------------------------
364// Not equal to operator
365//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000366bool FileSpec::operator!=(const FileSpec &rhs) const { return !(*this == rhs); }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000367
368//------------------------------------------------------------------
369// Less than operator
370//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000371bool FileSpec::operator<(const FileSpec &rhs) const {
372 return FileSpec::Compare(*this, rhs, true) < 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000373}
374
375//------------------------------------------------------------------
376// Dump a FileSpec object to a stream
377//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000378Stream &lldb_private::operator<<(Stream &s, const FileSpec &f) {
379 f.Dump(&s);
380 return s;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000381}
382
383//------------------------------------------------------------------
Adrian Prantl05097242018-04-30 16:49:04 +0000384// Clear this object by releasing both the directory and filename string values
385// and making them both the empty string.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000386//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000387void FileSpec::Clear() {
388 m_directory.Clear();
389 m_filename.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000390}
391
392//------------------------------------------------------------------
Adrian Prantl05097242018-04-30 16:49:04 +0000393// Compare two FileSpec objects. If "full" is true, then both the directory and
394// the filename must match. If "full" is false, then the directory names for
395// "a" and "b" are only compared if they are both non-empty. This allows a
396// FileSpec object to only contain a filename and it can match FileSpec objects
397// that have matching filenames with different paths.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000398//
Adrian Prantl05097242018-04-30 16:49:04 +0000399// Return -1 if the "a" is less than "b", 0 if "a" is equal to "b" and "1" if
400// "a" is greater than "b".
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000401//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000402int FileSpec::Compare(const FileSpec &a, const FileSpec &b, bool full) {
403 int result = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000404
Kate Stoneb9c1b512016-09-06 20:57:50 +0000405 // case sensitivity of compare
406 const bool case_sensitive = a.IsCaseSensitive() || b.IsCaseSensitive();
Zachary Turner47c03462016-02-24 21:26:47 +0000407
Kate Stoneb9c1b512016-09-06 20:57:50 +0000408 // If full is true, then we must compare both the directory and filename.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000409
Adrian Prantl05097242018-04-30 16:49:04 +0000410 // If full is false, then if either directory is empty, then we match on the
411 // basename only, and if both directories have valid values, we still do a
412 // full compare. This allows for matching when we just have a filename in one
413 // of the FileSpec objects.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000414
Kate Stoneb9c1b512016-09-06 20:57:50 +0000415 if (full || (a.m_directory && b.m_directory)) {
416 result = ConstString::Compare(a.m_directory, b.m_directory, case_sensitive);
417 if (result)
418 return result;
419 }
420 return ConstString::Compare(a.m_filename, b.m_filename, case_sensitive);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000421}
422
Greg Clayton776cd7a2018-04-27 15:45:58 +0000423bool FileSpec::Equal(const FileSpec &a, const FileSpec &b, bool full) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000424 // case sensitivity of equality test
425 const bool case_sensitive = a.IsCaseSensitive() || b.IsCaseSensitive();
Jonas Devliegheread8d48f2018-06-13 16:23:21 +0000426
Jonas Devliegherec1cc3172018-06-25 10:11:53 +0000427 const bool filenames_equal = ConstString::Equals(a.m_filename,
428 b.m_filename,
429 case_sensitive);
Jim Ingham97e4f472017-03-27 19:12:25 +0000430
Greg Clayton776cd7a2018-04-27 15:45:58 +0000431 if (!filenames_equal)
Jonas Devliegheread8d48f2018-06-13 16:23:21 +0000432 return false;
Jim Ingham97e4f472017-03-27 19:12:25 +0000433
Kate Stoneb9c1b512016-09-06 20:57:50 +0000434 if (!full && (a.GetDirectory().IsEmpty() || b.GetDirectory().IsEmpty()))
Jim Ingham97e4f472017-03-27 19:12:25 +0000435 return filenames_equal;
Pavel Labath218770b2016-10-31 16:22:07 +0000436
Greg Clayton776cd7a2018-04-27 15:45:58 +0000437 return a == b;
Jim Ingham96a15962014-11-15 01:54:26 +0000438}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000439
440//------------------------------------------------------------------
Adrian Prantl05097242018-04-30 16:49:04 +0000441// Dump the object to the supplied stream. If the object contains a valid
442// directory name, it will be displayed followed by a directory delimiter, and
443// the filename.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000444//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000445void FileSpec::Dump(Stream *s) const {
446 if (s) {
447 std::string path{GetPath(true)};
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000448 s->PutCString(path);
Pavel Labath2cb7cf82018-05-14 14:52:47 +0000449 char path_separator = GetPreferredPathSeparator(m_style);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000450 if (!m_filename && !path.empty() && path.back() != path_separator)
451 s->PutChar(path_separator);
452 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000453}
454
455//------------------------------------------------------------------
456// Returns true if the file exists.
457//------------------------------------------------------------------
Zachary Turner7d86ee52017-03-08 17:56:08 +0000458bool FileSpec::Exists() const { return llvm::sys::fs::exists(GetPath()); }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000459
Kate Stoneb9c1b512016-09-06 20:57:50 +0000460bool FileSpec::Readable() const {
Zachary Turner7d86ee52017-03-08 17:56:08 +0000461 return GetPermissions() & llvm::sys::fs::perms::all_read;
Greg Clayton5acc1252014-08-15 18:00:45 +0000462}
463
Kate Stoneb9c1b512016-09-06 20:57:50 +0000464bool FileSpec::ResolveExecutableLocation() {
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000465 // CLEANUP: Use StringRef for string handling.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000466 if (!m_directory) {
467 const char *file_cstr = m_filename.GetCString();
468 if (file_cstr) {
469 const std::string file_str(file_cstr);
470 llvm::ErrorOr<std::string> error_or_path =
471 llvm::sys::findProgramByName(file_str);
472 if (!error_or_path)
Jim Ingham0909e5f2010-09-16 00:57:33 +0000473 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000474 std::string path = error_or_path.get();
475 llvm::StringRef dir_ref = llvm::sys::path::parent_path(path);
476 if (!dir_ref.empty()) {
477 // FindProgramByName returns "." if it can't find the file.
478 if (strcmp(".", dir_ref.data()) == 0)
479 return false;
480
481 m_directory.SetCString(dir_ref.data());
482 if (Exists())
483 return true;
484 else {
485 // If FindProgramByName found the file, it returns the directory +
Adrian Prantl05097242018-04-30 16:49:04 +0000486 // filename in its return results. We need to separate them.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000487 FileSpec tmp_file(dir_ref.data(), false);
488 if (tmp_file.Exists()) {
489 m_directory = tmp_file.m_directory;
490 return true;
491 }
492 }
493 }
494 }
495 }
496
497 return false;
Jim Ingham0909e5f2010-09-16 00:57:33 +0000498}
499
Kate Stoneb9c1b512016-09-06 20:57:50 +0000500bool FileSpec::ResolvePath() {
501 if (m_is_resolved)
502 return true; // We have already resolved this path
503
Kate Stoneb9c1b512016-09-06 20:57:50 +0000504 // SetFile(...) will set m_is_resolved correctly if it can resolve the path
Jonas Devlieghere937348c2018-06-13 22:08:14 +0000505 SetFile(GetPath(false), true);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000506 return m_is_resolved;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000507}
508
Kate Stoneb9c1b512016-09-06 20:57:50 +0000509uint64_t FileSpec::GetByteSize() const {
Zachary Turner7d86ee52017-03-08 17:56:08 +0000510 uint64_t Size = 0;
511 if (llvm::sys::fs::file_size(GetPath(), Size))
512 return 0;
513 return Size;
Zachary Turnerdf62f202014-08-07 17:33:07 +0000514}
515
Pavel Labath2cb7cf82018-05-14 14:52:47 +0000516FileSpec::Style FileSpec::GetPathStyle() const { return m_style; }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000517
Pavel Labath30e6cbf2017-03-07 13:19:15 +0000518uint32_t FileSpec::GetPermissions() const {
Zachary Turner7d86ee52017-03-08 17:56:08 +0000519 namespace fs = llvm::sys::fs;
520 fs::file_status st;
521 if (fs::status(GetPath(), st, false))
522 return fs::perms::perms_not_known;
523
524 return st.permissions();
Greg Claytonfbb76342013-11-20 21:07:01 +0000525}
526
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000527//------------------------------------------------------------------
528// Directory string get accessor.
529//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000530ConstString &FileSpec::GetDirectory() { return m_directory; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000531
532//------------------------------------------------------------------
533// Directory string const get accessor.
534//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000535const ConstString &FileSpec::GetDirectory() const { return m_directory; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000536
537//------------------------------------------------------------------
538// Filename string get accessor.
539//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000540ConstString &FileSpec::GetFilename() { return m_filename; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000541
542//------------------------------------------------------------------
543// Filename string const get accessor.
544//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000545const ConstString &FileSpec::GetFilename() const { return m_filename; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000546
547//------------------------------------------------------------------
Adrian Prantl05097242018-04-30 16:49:04 +0000548// Extract the directory and path into a fixed buffer. This is needed as the
549// directory and path are stored in separate string values.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000550//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000551size_t FileSpec::GetPath(char *path, size_t path_max_len,
552 bool denormalize) const {
553 if (!path)
554 return 0;
Zachary Turnerb6d99242014-08-08 23:54:35 +0000555
Kate Stoneb9c1b512016-09-06 20:57:50 +0000556 std::string result = GetPath(denormalize);
557 ::snprintf(path, path_max_len, "%s", result.c_str());
558 return std::min(path_max_len - 1, result.length());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000559}
560
Kate Stoneb9c1b512016-09-06 20:57:50 +0000561std::string FileSpec::GetPath(bool denormalize) const {
562 llvm::SmallString<64> result;
563 GetPath(result, denormalize);
564 return std::string(result.begin(), result.end());
Jason Molendaa7ae4672013-04-29 09:46:43 +0000565}
566
Kate Stoneb9c1b512016-09-06 20:57:50 +0000567const char *FileSpec::GetCString(bool denormalize) const {
568 return ConstString{GetPath(denormalize)}.AsCString(NULL);
Chaoren Lind3173f32015-05-29 19:52:29 +0000569}
570
Kate Stoneb9c1b512016-09-06 20:57:50 +0000571void FileSpec::GetPath(llvm::SmallVectorImpl<char> &path,
572 bool denormalize) const {
573 path.append(m_directory.GetStringRef().begin(),
574 m_directory.GetStringRef().end());
Greg Clayton776cd7a2018-04-27 15:45:58 +0000575 // Since the path was normalized and all paths use '/' when stored in these
576 // objects, we don't need to look for the actual syntax specific path
577 // separator, we just look for and insert '/'.
578 if (m_directory && m_filename && m_directory.GetStringRef().back() != '/' &&
579 m_filename.GetStringRef().back() != '/')
580 path.insert(path.end(), '/');
Kate Stoneb9c1b512016-09-06 20:57:50 +0000581 path.append(m_filename.GetStringRef().begin(),
582 m_filename.GetStringRef().end());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000583 if (denormalize && !path.empty())
Pavel Labath2cb7cf82018-05-14 14:52:47 +0000584 Denormalize(path, m_style);
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000585}
586
Kate Stoneb9c1b512016-09-06 20:57:50 +0000587ConstString FileSpec::GetFileNameExtension() const {
Jonas Devlieghere9c1a6452018-06-13 16:36:07 +0000588 return ConstString(
589 llvm::sys::path::extension(m_filename.GetStringRef(), m_style));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000590}
591
592ConstString FileSpec::GetFileNameStrippingExtension() const {
Jonas Devlieghere9c1a6452018-06-13 16:36:07 +0000593 return ConstString(llvm::sys::path::stem(m_filename.GetStringRef(), m_style));
Enrico Granataa9dbf432011-10-17 21:45:27 +0000594}
595
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000596//------------------------------------------------------------------
Adrian Prantl05097242018-04-30 16:49:04 +0000597// Return the size in bytes that this object takes in memory. This returns the
598// size in bytes of this object, not any shared string values it may refer to.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000599//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000600size_t FileSpec::MemorySize() const {
601 return m_filename.MemorySize() + m_directory.MemorySize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000602}
603
Zachary Turner1f875342017-03-13 02:44:39 +0000604void FileSpec::EnumerateDirectory(llvm::StringRef dir_path,
605 bool find_directories, bool find_files,
606 bool find_other,
607 EnumerateDirectoryCallbackType callback,
608 void *callback_baton) {
609 namespace fs = llvm::sys::fs;
610 std::error_code EC;
611 fs::recursive_directory_iterator Iter(dir_path, EC);
612 fs::recursive_directory_iterator End;
613 for (; Iter != End && !EC; Iter.increment(EC)) {
614 const auto &Item = *Iter;
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000615 llvm::ErrorOr<fs::basic_file_status> Status = Item.status();
616 if (!Status)
Zachary Turner1f875342017-03-13 02:44:39 +0000617 break;
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000618 if (!find_files && fs::is_regular_file(*Status))
Zachary Turner1f875342017-03-13 02:44:39 +0000619 continue;
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000620 if (!find_directories && fs::is_directory(*Status))
Zachary Turner1f875342017-03-13 02:44:39 +0000621 continue;
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000622 if (!find_other && fs::is_other(*Status))
Zachary Turner1f875342017-03-13 02:44:39 +0000623 continue;
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000624
Zachary Turner1f875342017-03-13 02:44:39 +0000625 FileSpec Spec(Item.path(), false);
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000626 auto Result = callback(callback_baton, Status->type(), Spec);
Zachary Turner1f875342017-03-13 02:44:39 +0000627 if (Result == eEnumerateDirectoryResultQuit)
628 return;
629 if (Result == eEnumerateDirectoryResultNext) {
630 // Default behavior is to recurse. Opt out if the callback doesn't want
631 // this behavior.
632 Iter.no_push();
Greg Clayton58c65f02015-06-29 18:29:00 +0000633 }
Zachary Turner1f875342017-03-13 02:44:39 +0000634 }
Daniel Maleae0f8f572013-08-26 23:57:52 +0000635}
636
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000637FileSpec
638FileSpec::CopyByAppendingPathComponent(llvm::StringRef component) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000639 FileSpec ret = *this;
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000640 ret.AppendPathComponent(component);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000641 return ret;
Chaoren Lin0c5a9c12015-06-05 00:28:06 +0000642}
643
Kate Stoneb9c1b512016-09-06 20:57:50 +0000644FileSpec FileSpec::CopyByRemovingLastPathComponent() const {
Jonas Devlieghere24bd63c42018-06-24 10:18:01 +0000645 llvm::SmallString<64> current_path;
646 GetPath(current_path, false);
647 if (llvm::sys::path::has_parent_path(current_path, m_style))
648 return FileSpec(llvm::sys::path::parent_path(current_path, m_style), false,
649 m_style);
650 return *this;
Chaoren Lin0c5a9c12015-06-05 00:28:06 +0000651}
652
Kate Stoneb9c1b512016-09-06 20:57:50 +0000653ConstString FileSpec::GetLastPathComponent() const {
Jonas Devlieghere24bd63c42018-06-24 10:18:01 +0000654 llvm::SmallString<64> current_path;
655 GetPath(current_path, false);
656 return ConstString(llvm::sys::path::filename(current_path, m_style));
Pavel Labath59d725c2017-01-16 10:07:02 +0000657}
658
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000659void FileSpec::PrependPathComponent(llvm::StringRef component) {
Jonas Devlieghere24bd63c42018-06-24 10:18:01 +0000660 llvm::SmallString<64> new_path(component);
661 llvm::SmallString<64> current_path;
662 GetPath(current_path, false);
663 llvm::sys::path::append(new_path,
664 llvm::sys::path::begin(current_path, m_style),
665 llvm::sys::path::end(current_path), m_style);
666 SetFile(new_path, false, m_style);
Chaoren Lind3173f32015-05-29 19:52:29 +0000667}
668
Kate Stoneb9c1b512016-09-06 20:57:50 +0000669void FileSpec::PrependPathComponent(const FileSpec &new_path) {
670 return PrependPathComponent(new_path.GetPath(false));
Chaoren Lin0c5a9c12015-06-05 00:28:06 +0000671}
672
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000673void FileSpec::AppendPathComponent(llvm::StringRef component) {
Jonas Devlieghere24bd63c42018-06-24 10:18:01 +0000674 llvm::SmallString<64> current_path;
675 GetPath(current_path, false);
676 llvm::sys::path::append(current_path, m_style, component);
677 SetFile(current_path, false, m_style);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000678}
679
680void FileSpec::AppendPathComponent(const FileSpec &new_path) {
681 return AppendPathComponent(new_path.GetPath(false));
682}
683
Jonas Devliegheredf8e2912018-05-30 13:03:16 +0000684bool FileSpec::RemoveLastPathComponent() {
685 llvm::SmallString<64> current_path;
686 GetPath(current_path, false);
687 if (llvm::sys::path::has_parent_path(current_path, m_style)) {
Jonas Devlieghere937348c2018-06-13 22:08:14 +0000688 SetFile(llvm::sys::path::parent_path(current_path, m_style), false);
Jonas Devliegheredf8e2912018-05-30 13:03:16 +0000689 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000690 }
Jonas Devliegheredf8e2912018-05-30 13:03:16 +0000691 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +0000692}
Greg Clayton1f746072012-08-29 21:13:06 +0000693//------------------------------------------------------------------
694/// Returns true if the filespec represents an implementation source
695/// file (files with a ".c", ".cpp", ".m", ".mm" (many more)
696/// extension).
697///
698/// @return
699/// \b true if the filespec represents an implementation source
700/// file, \b false otherwise.
701//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000702bool FileSpec::IsSourceImplementationFile() const {
703 ConstString extension(GetFileNameExtension());
Zachary Turner95eae422016-09-21 16:01:28 +0000704 if (!extension)
705 return false;
706
707 static RegularExpression g_source_file_regex(llvm::StringRef(
Jonas Devliegheread8d48f2018-06-13 16:23:21 +0000708 "^.([cC]|[mM]|[mM][mM]|[cC][pP][pP]|[cC]\\+\\+|[cC][xX][xX]|[cC][cC]|["
Zachary Turner95eae422016-09-21 16:01:28 +0000709 "cC][pP]|[sS]|[aA][sS][mM]|[fF]|[fF]77|[fF]90|[fF]95|[fF]03|[fF][oO]["
710 "rR]|[fF][tT][nN]|[fF][pP][pP]|[aA][dD][aA]|[aA][dD][bB]|[aA][dD][sS])"
711 "$"));
712 return g_source_file_regex.Execute(extension.GetStringRef());
Greg Clayton1f746072012-08-29 21:13:06 +0000713}
714
Jonas Devliegherec1cc3172018-06-25 10:11:53 +0000715bool FileSpec::IsRelative() const {
716 return !IsAbsolute();
717}
Chaoren Lin372e9062015-06-09 17:54:27 +0000718
Jonas Devliegheread8d48f2018-06-13 16:23:21 +0000719bool FileSpec::IsAbsolute() const {
720 llvm::SmallString<64> current_path;
721 GetPath(current_path, false);
722
723 // Early return if the path is empty.
724 if (current_path.empty())
725 return false;
726
727 // We consider paths starting with ~ to be absolute.
728 if (current_path[0] == '~')
729 return true;
730
731 return llvm::sys::path::is_absolute(current_path, m_style);
732}
Zachary Turner827d5d72016-12-16 04:27:00 +0000733
734void llvm::format_provider<FileSpec>::format(const FileSpec &F,
735 raw_ostream &Stream,
736 StringRef Style) {
737 assert(
738 (Style.empty() || Style.equals_lower("F") || Style.equals_lower("D")) &&
739 "Invalid FileSpec style!");
740
741 StringRef dir = F.GetDirectory().GetStringRef();
742 StringRef file = F.GetFilename().GetStringRef();
743
744 if (dir.empty() && file.empty()) {
745 Stream << "(empty)";
746 return;
747 }
748
749 if (Style.equals_lower("F")) {
750 Stream << (file.empty() ? "(empty)" : file);
751 return;
752 }
753
754 // Style is either D or empty, either way we need to print the directory.
755 if (!dir.empty()) {
Adrian Prantl05097242018-04-30 16:49:04 +0000756 // Directory is stored in normalized form, which might be different than
757 // preferred form. In order to handle this, we need to cut off the
758 // filename, then denormalize, then write the entire denorm'ed directory.
Zachary Turner827d5d72016-12-16 04:27:00 +0000759 llvm::SmallString<64> denormalized_dir = dir;
Pavel Labath2cb7cf82018-05-14 14:52:47 +0000760 Denormalize(denormalized_dir, F.GetPathStyle());
Zachary Turner827d5d72016-12-16 04:27:00 +0000761 Stream << denormalized_dir;
Pavel Labath2cb7cf82018-05-14 14:52:47 +0000762 Stream << GetPreferredPathSeparator(F.GetPathStyle());
Zachary Turner827d5d72016-12-16 04:27:00 +0000763 }
764
765 if (Style.equals_lower("D")) {
766 // We only want to print the directory, so now just exit.
767 if (dir.empty())
768 Stream << "(empty)";
769 return;
770 }
771
772 if (!file.empty())
773 Stream << file;
774}