1 //===-- FileSpec.cpp ------------------------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "lldb/Utility/FileSpec.h"
10 #include "lldb/Utility/RegularExpression.h"
11 #include "lldb/Utility/Stream.h"
13 #include "llvm/ADT/SmallString.h"
14 #include "llvm/ADT/SmallVector.h"
15 #include "llvm/ADT/StringRef.h"
16 #include "llvm/ADT/Triple.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/Support/ErrorOr.h"
19 #include "llvm/Support/FileSystem.h"
20 #include "llvm/Support/Program.h"
21 #include "llvm/Support/raw_ostream.h"
24 #include <system_error>
33 using namespace lldb_private
;
37 static constexpr FileSpec::Style
GetNativeStyle() {
39 return FileSpec::Style::windows
;
41 return FileSpec::Style::posix
;
45 bool PathStyleIsPosix(FileSpec::Style style
) {
46 return llvm::sys::path::is_style_posix(style
);
49 const char *GetPathSeparators(FileSpec::Style style
) {
50 return llvm::sys::path::get_separator(style
).data();
53 char GetPreferredPathSeparator(FileSpec::Style style
) {
54 return GetPathSeparators(style
)[0];
57 void Denormalize(llvm::SmallVectorImpl
<char> &path
, FileSpec::Style style
) {
58 if (PathStyleIsPosix(style
))
61 std::replace(path
.begin(), path
.end(), '/', '\\');
64 } // end anonymous namespace
66 FileSpec::FileSpec() : m_style(GetNativeStyle()) {}
68 // Default constructor that can take an optional full path to a file on disk.
69 FileSpec::FileSpec(llvm::StringRef path
, Style style
) : m_style(style
) {
73 FileSpec::FileSpec(llvm::StringRef path
, const llvm::Triple
&triple
)
74 : FileSpec
{path
, triple
.isOSWindows() ? Style::windows
: Style::posix
} {}
77 /// Safely get a character at the specified index.
80 /// A full, partial, or relative path to a file.
83 /// An index into path which may or may not be valid.
86 /// The character at index \a i if the index is valid, or 0 if
87 /// the index is not valid.
88 inline char safeCharAtIndex(const llvm::StringRef
&path
, size_t i
) {
94 /// Check if a path needs to be normalized.
96 /// Check if a path needs to be normalized. We currently consider a
97 /// path to need normalization if any of the following are true
98 /// - path contains "/./"
99 /// - path contains "/../"
100 /// - path contains "//"
101 /// - path ends with "/"
102 /// Paths that start with "./" or with "../" are not considered to
103 /// need normalization since we aren't trying to resolve the path,
104 /// we are just trying to remove redundant things from the path.
107 /// A full, partial, or relative path to a file.
110 /// Returns \b true if the path needs to be normalized.
111 bool needsNormalization(const llvm::StringRef
&path
) {
114 // We strip off leading "." values so these paths need to be normalized
117 for (auto i
= path
.find_first_of("\\/"); i
!= llvm::StringRef::npos
;
118 i
= path
.find_first_of("\\/", i
+ 1)) {
119 const auto next
= safeCharAtIndex(path
, i
+1);
122 // path separator char at the end of the string which should be
123 // stripped unless it is the one and only character
127 // two path separator chars in the middle of a path needs to be
135 const auto next_next
= safeCharAtIndex(path
, i
+2);
138 case 0: return true; // ends with "/."
141 return true; // contains "/./"
143 const auto next_next_next
= safeCharAtIndex(path
, i
+3);
144 switch (next_next_next
) {
146 case 0: return true; // ends with "/.."
149 return true; // contains "/../"
167 void FileSpec::SetFile(llvm::StringRef pathname
) { SetFile(pathname
, m_style
); }
169 // Update the contents of this object with a new path. The path will be split
170 // up into a directory and filename and stored as uniqued string values for
171 // quick comparison and efficient memory usage.
172 void FileSpec::SetFile(llvm::StringRef pathname
, Style style
) {
175 m_is_resolved
= false;
176 m_style
= (style
== Style::native
) ? GetNativeStyle() : style
;
178 if (pathname
.empty())
181 llvm::SmallString
<128> resolved(pathname
);
183 // Normalize the path by removing ".", ".." and other redundant components.
184 if (needsNormalization(resolved
))
185 llvm::sys::path::remove_dots(resolved
, true, m_style
);
187 // Normalize back slashes to forward slashes
188 if (m_style
== Style::windows
)
189 std::replace(resolved
.begin(), resolved
.end(), '\\', '/');
191 if (resolved
.empty()) {
192 // If we have no path after normalization set the path to the current
193 // directory. This matches what python does and also a few other path
195 m_filename
.SetString(".");
199 // Split path into filename and directory. We rely on the underlying char
200 // pointer to be nullptr when the components are empty.
201 llvm::StringRef filename
= llvm::sys::path::filename(resolved
, m_style
);
202 if(!filename
.empty())
203 m_filename
.SetString(filename
);
205 llvm::StringRef directory
= llvm::sys::path::parent_path(resolved
, m_style
);
206 if(!directory
.empty())
207 m_directory
.SetString(directory
);
210 void FileSpec::SetFile(llvm::StringRef path
, const llvm::Triple
&triple
) {
211 return SetFile(path
, triple
.isOSWindows() ? Style::windows
: Style::posix
);
214 // Convert to pointer operator. This allows code to check any FileSpec objects
215 // to see if they contain anything valid using code such as:
219 FileSpec::operator bool() const { return m_filename
|| m_directory
; }
221 // Logical NOT operator. This allows code to check any FileSpec objects to see
222 // if they are invalid using code such as:
226 bool FileSpec::operator!() const { return !m_directory
&& !m_filename
; }
228 bool FileSpec::DirectoryEquals(const FileSpec
&rhs
) const {
229 const bool case_sensitive
= IsCaseSensitive() || rhs
.IsCaseSensitive();
230 return ConstString::Equals(m_directory
, rhs
.m_directory
, case_sensitive
);
233 bool FileSpec::FileEquals(const FileSpec
&rhs
) const {
234 const bool case_sensitive
= IsCaseSensitive() || rhs
.IsCaseSensitive();
235 return ConstString::Equals(m_filename
, rhs
.m_filename
, case_sensitive
);
239 bool FileSpec::operator==(const FileSpec
&rhs
) const {
240 return FileEquals(rhs
) && DirectoryEquals(rhs
);
243 // Not equal to operator
244 bool FileSpec::operator!=(const FileSpec
&rhs
) const { return !(*this == rhs
); }
246 // Less than operator
247 bool FileSpec::operator<(const FileSpec
&rhs
) const {
248 return FileSpec::Compare(*this, rhs
, true) < 0;
251 // Dump a FileSpec object to a stream
252 Stream
&lldb_private::operator<<(Stream
&s
, const FileSpec
&f
) {
253 f
.Dump(s
.AsRawOstream());
257 // Clear this object by releasing both the directory and filename string values
258 // and making them both the empty string.
259 void FileSpec::Clear() {
264 // Compare two FileSpec objects. If "full" is true, then both the directory and
265 // the filename must match. If "full" is false, then the directory names for
266 // "a" and "b" are only compared if they are both non-empty. This allows a
267 // FileSpec object to only contain a filename and it can match FileSpec objects
268 // that have matching filenames with different paths.
270 // Return -1 if the "a" is less than "b", 0 if "a" is equal to "b" and "1" if
271 // "a" is greater than "b".
272 int FileSpec::Compare(const FileSpec
&a
, const FileSpec
&b
, bool full
) {
275 // case sensitivity of compare
276 const bool case_sensitive
= a
.IsCaseSensitive() || b
.IsCaseSensitive();
278 // If full is true, then we must compare both the directory and filename.
280 // If full is false, then if either directory is empty, then we match on the
281 // basename only, and if both directories have valid values, we still do a
282 // full compare. This allows for matching when we just have a filename in one
283 // of the FileSpec objects.
285 if (full
|| (a
.m_directory
&& b
.m_directory
)) {
286 result
= ConstString::Compare(a
.m_directory
, b
.m_directory
, case_sensitive
);
290 return ConstString::Compare(a
.m_filename
, b
.m_filename
, case_sensitive
);
293 bool FileSpec::Equal(const FileSpec
&a
, const FileSpec
&b
, bool full
) {
294 if (full
|| (a
.GetDirectory() && b
.GetDirectory()))
297 return a
.FileEquals(b
);
300 bool FileSpec::Match(const FileSpec
&pattern
, const FileSpec
&file
) {
301 if (pattern
.GetDirectory())
302 return pattern
== file
;
303 if (pattern
.GetFilename())
304 return pattern
.FileEquals(file
);
308 llvm::Optional
<FileSpec::Style
> FileSpec::GuessPathStyle(llvm::StringRef absolute_path
) {
309 if (absolute_path
.startswith("/"))
311 if (absolute_path
.startswith(R
"(\\)"))
312 return Style::windows
;
313 if (absolute_path
.size() >= 3 && llvm::isAlpha(absolute_path
[0]) &&
314 absolute_path
.substr(1, 2) == R
"(:\)")
315 return Style::windows
;
319 // Dump the object to the supplied stream. If the object contains a valid
320 // directory name, it will be displayed followed by a directory delimiter, and
322 void FileSpec::Dump(llvm::raw_ostream
&s
) const {
323 std::string path
{GetPath(true)};
325 char path_separator
= GetPreferredPathSeparator(m_style
);
326 if (!m_filename
&& !path
.empty() && path
.back() != path_separator
)
330 FileSpec::Style
FileSpec::GetPathStyle() const { return m_style
; }
332 // Directory string get accessor.
333 ConstString
&FileSpec::GetDirectory() { return m_directory
; }
335 // Directory string const get accessor.
336 ConstString
FileSpec::GetDirectory() const { return m_directory
; }
338 // Filename string get accessor.
339 ConstString
&FileSpec::GetFilename() { return m_filename
; }
341 // Filename string const get accessor.
342 ConstString
FileSpec::GetFilename() const { return m_filename
; }
344 // Extract the directory and path into a fixed buffer. This is needed as the
345 // directory and path are stored in separate string values.
346 size_t FileSpec::GetPath(char *path
, size_t path_max_len
,
347 bool denormalize
) const {
351 std::string result
= GetPath(denormalize
);
352 ::snprintf(path
, path_max_len
, "%s", result
.c_str());
353 return std::min(path_max_len
- 1, result
.length());
356 std::string
FileSpec::GetPath(bool denormalize
) const {
357 llvm::SmallString
<64> result
;
358 GetPath(result
, denormalize
);
359 return std::string(result
.begin(), result
.end());
362 const char *FileSpec::GetCString(bool denormalize
) const {
363 return ConstString
{GetPath(denormalize
)}.AsCString(nullptr);
366 void FileSpec::GetPath(llvm::SmallVectorImpl
<char> &path
,
367 bool denormalize
) const {
368 path
.append(m_directory
.GetStringRef().begin(),
369 m_directory
.GetStringRef().end());
370 // Since the path was normalized and all paths use '/' when stored in these
371 // objects, we don't need to look for the actual syntax specific path
372 // separator, we just look for and insert '/'.
373 if (m_directory
&& m_filename
&& m_directory
.GetStringRef().back() != '/' &&
374 m_filename
.GetStringRef().back() != '/')
375 path
.insert(path
.end(), '/');
376 path
.append(m_filename
.GetStringRef().begin(),
377 m_filename
.GetStringRef().end());
378 if (denormalize
&& !path
.empty())
379 Denormalize(path
, m_style
);
382 ConstString
FileSpec::GetFileNameExtension() const {
384 llvm::sys::path::extension(m_filename
.GetStringRef(), m_style
));
387 ConstString
FileSpec::GetFileNameStrippingExtension() const {
388 return ConstString(llvm::sys::path::stem(m_filename
.GetStringRef(), m_style
));
391 // Return the size in bytes that this object takes in memory. This returns the
392 // size in bytes of this object, not any shared string values it may refer to.
393 size_t FileSpec::MemorySize() const {
394 return m_filename
.MemorySize() + m_directory
.MemorySize();
398 FileSpec::CopyByAppendingPathComponent(llvm::StringRef component
) const {
399 FileSpec ret
= *this;
400 ret
.AppendPathComponent(component
);
404 FileSpec
FileSpec::CopyByRemovingLastPathComponent() const {
405 llvm::SmallString
<64> current_path
;
406 GetPath(current_path
, false);
407 if (llvm::sys::path::has_parent_path(current_path
, m_style
))
408 return FileSpec(llvm::sys::path::parent_path(current_path
, m_style
),
413 ConstString
FileSpec::GetLastPathComponent() const {
414 llvm::SmallString
<64> current_path
;
415 GetPath(current_path
, false);
416 return ConstString(llvm::sys::path::filename(current_path
, m_style
));
419 void FileSpec::PrependPathComponent(llvm::StringRef component
) {
420 llvm::SmallString
<64> new_path(component
);
421 llvm::SmallString
<64> current_path
;
422 GetPath(current_path
, false);
423 llvm::sys::path::append(new_path
,
424 llvm::sys::path::begin(current_path
, m_style
),
425 llvm::sys::path::end(current_path
), m_style
);
426 SetFile(new_path
, m_style
);
429 void FileSpec::PrependPathComponent(const FileSpec
&new_path
) {
430 return PrependPathComponent(new_path
.GetPath(false));
433 void FileSpec::AppendPathComponent(llvm::StringRef component
) {
434 llvm::SmallString
<64> current_path
;
435 GetPath(current_path
, false);
436 llvm::sys::path::append(current_path
, m_style
, component
);
437 SetFile(current_path
, m_style
);
440 void FileSpec::AppendPathComponent(const FileSpec
&new_path
) {
441 return AppendPathComponent(new_path
.GetPath(false));
444 bool FileSpec::RemoveLastPathComponent() {
445 llvm::SmallString
<64> current_path
;
446 GetPath(current_path
, false);
447 if (llvm::sys::path::has_parent_path(current_path
, m_style
)) {
448 SetFile(llvm::sys::path::parent_path(current_path
, m_style
));
453 /// Returns true if the filespec represents an implementation source
454 /// file (files with a ".c", ".cpp", ".m", ".mm" (many more)
458 /// \b true if the filespec represents an implementation source
459 /// file, \b false otherwise.
460 bool FileSpec::IsSourceImplementationFile() const {
461 ConstString
extension(GetFileNameExtension());
465 static RegularExpression
g_source_file_regex(llvm::StringRef(
466 "^.([cC]|[mM]|[mM][mM]|[cC][pP][pP]|[cC]\\+\\+|[cC][xX][xX]|[cC][cC]|["
467 "cC][pP]|[sS]|[aA][sS][mM]|[fF]|[fF]77|[fF]90|[fF]95|[fF]03|[fF][oO]["
468 "rR]|[fF][tT][nN]|[fF][pP][pP]|[aA][dD][aA]|[aA][dD][bB]|[aA][dD][sS])"
470 return g_source_file_regex
.Execute(extension
.GetStringRef());
473 bool FileSpec::IsRelative() const {
474 return !IsAbsolute();
477 bool FileSpec::IsAbsolute() const {
478 llvm::SmallString
<64> current_path
;
479 GetPath(current_path
, false);
481 // Early return if the path is empty.
482 if (current_path
.empty())
485 // We consider paths starting with ~ to be absolute.
486 if (current_path
[0] == '~')
489 return llvm::sys::path::is_absolute(current_path
, m_style
);
492 void FileSpec::MakeAbsolute(const FileSpec
&dir
) {
494 PrependPathComponent(dir
);
497 void llvm::format_provider
<FileSpec
>::format(const FileSpec
&F
,
500 assert((Style
.empty() || Style
.equals_insensitive("F") ||
501 Style
.equals_insensitive("D")) &&
502 "Invalid FileSpec style!");
504 StringRef dir
= F
.GetDirectory().GetStringRef();
505 StringRef file
= F
.GetFilename().GetStringRef();
507 if (dir
.empty() && file
.empty()) {
512 if (Style
.equals_insensitive("F")) {
513 Stream
<< (file
.empty() ? "(empty)" : file
);
517 // Style is either D or empty, either way we need to print the directory.
519 // Directory is stored in normalized form, which might be different than
520 // preferred form. In order to handle this, we need to cut off the
521 // filename, then denormalize, then write the entire denorm'ed directory.
522 llvm::SmallString
<64> denormalized_dir
= dir
;
523 Denormalize(denormalized_dir
, F
.GetPathStyle());
524 Stream
<< denormalized_dir
;
525 Stream
<< GetPreferredPathSeparator(F
.GetPathStyle());
528 if (Style
.equals_insensitive("D")) {
529 // We only want to print the directory, so now just exit.
539 void llvm::yaml::ScalarEnumerationTraits
<FileSpecStyle
>::enumeration(
540 IO
&io
, FileSpecStyle
&value
) {
541 io
.enumCase(value
, "windows", FileSpecStyle(FileSpec::Style::windows
));
542 io
.enumCase(value
, "posix", FileSpecStyle(FileSpec::Style::posix
));
543 io
.enumCase(value
, "native", FileSpecStyle(FileSpec::Style::native
));
546 void llvm::yaml::MappingTraits
<FileSpec
>::mapping(IO
&io
, FileSpec
&f
) {
547 io
.mapRequired("directory", f
.m_directory
);
548 io
.mapRequired("file", f
.m_filename
);
549 io
.mapRequired("resolved", f
.m_is_resolved
);
550 FileSpecStyle style
= f
.m_style
;
551 io
.mapRequired("style", style
);