LLDB mainline
FileSpec.cpp
Go to the documentation of this file.
1//===-- FileSpec.cpp ------------------------------------------------------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8
11#include "lldb/Utility/Stream.h"
12
13#include "llvm/ADT/SmallString.h"
14#include "llvm/ADT/SmallVector.h"
15#include "llvm/ADT/StringExtras.h"
16#include "llvm/ADT/StringRef.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"
22#include "llvm/TargetParser/Triple.h"
23
24#include <algorithm>
25#include <optional>
26#include <system_error>
27#include <vector>
28
29#include <cassert>
30#include <climits>
31#include <cstdio>
32#include <cstring>
33
34using namespace lldb;
35using namespace lldb_private;
36
37namespace {
38
39static constexpr FileSpec::Style GetNativeStyle() {
40#if defined(_WIN32)
41 return FileSpec::Style::windows;
42#else
43 return FileSpec::Style::posix;
44#endif
45}
46
47bool PathStyleIsPosix(FileSpec::Style style) {
48 return llvm::sys::path::is_style_posix(style);
49}
50
51const char *GetPathSeparators(FileSpec::Style style) {
52 return llvm::sys::path::get_separator(style).data();
53}
54
55char GetPreferredPathSeparator(FileSpec::Style style) {
56 return GetPathSeparators(style)[0];
57}
58
59void Denormalize(llvm::SmallVectorImpl<char> &path, FileSpec::Style style) {
60 if (PathStyleIsPosix(style))
61 return;
62
63 llvm::replace(path, '/', '\\');
64}
65
66} // end anonymous namespace
67
68FileSpec::FileSpec() : m_style(GetNativeStyle()) {}
69
70// Default constructor that can take an optional full path to a file on disk.
71FileSpec::FileSpec(llvm::StringRef path, Style style) : m_style(style) {
72 SetFile(path, style);
73}
74
75FileSpec::FileSpec(llvm::StringRef path, const llvm::Triple &triple)
76 : FileSpec{path, triple.isOSWindows() ? Style::windows : Style::posix} {}
77
78namespace {
79/// Safely get a character at the specified index.
80///
81/// \param[in] path
82/// A full, partial, or relative path to a file.
83///
84/// \param[in] i
85/// An index into path which may or may not be valid.
86///
87/// \return
88/// The character at index \a i if the index is valid, or 0 if
89/// the index is not valid.
90inline char safeCharAtIndex(const llvm::StringRef &path, size_t i) {
91 if (i < path.size())
92 return path[i];
93 return 0;
94}
95
96/// Check if a path needs to be normalized.
97///
98/// Check if a path needs to be normalized. We currently consider a
99/// path to need normalization if any of the following are true
100/// - path contains "/./"
101/// - path contains "/../"
102/// - path contains "//"
103/// - path ends with "/"
104/// Paths that start with "./" or with "../" are not considered to
105/// need normalization since we aren't trying to resolve the path,
106/// we are just trying to remove redundant things from the path.
107///
108/// \param[in] path
109/// A full, partial, or relative path to a file.
110///
111/// \return
112/// Returns \b true if the path needs to be normalized.
113bool needsNormalization(const llvm::StringRef &path) {
114 if (path.empty())
115 return false;
116 // We strip off leading "." values so these paths need to be normalized
117 if (path[0] == '.')
118 return true;
119 for (auto i = path.find_first_of("\\/"); i != llvm::StringRef::npos;
120 i = path.find_first_of("\\/", i + 1)) {
121 const auto next = safeCharAtIndex(path, i+1);
122 switch (next) {
123 case 0:
124 // path separator char at the end of the string which should be
125 // stripped unless it is the one and only character
126 return i > 0;
127 case '/':
128 case '\\':
129 // two path separator chars in the middle of a path needs to be
130 // normalized
131 if (i > 0)
132 return true;
133 ++i;
134 break;
135
136 case '.': {
137 const auto next_next = safeCharAtIndex(path, i+2);
138 switch (next_next) {
139 default: break;
140 case 0: return true; // ends with "/."
141 case '/':
142 case '\\':
143 return true; // contains "/./"
144 case '.': {
145 const auto next_next_next = safeCharAtIndex(path, i+3);
146 switch (next_next_next) {
147 default: break;
148 case 0: return true; // ends with "/.."
149 case '/':
150 case '\\':
151 return true; // contains "/../"
152 }
153 break;
154 }
155 }
156 }
157 break;
158
159 default:
160 break;
161 }
162 }
163 return false;
164}
165
166
167}
168
169void FileSpec::SetFile(llvm::StringRef pathname) { SetFile(pathname, m_style); }
170
171// Update the contents of this object with a new path. The path will be split
172// up into a directory and filename and stored as uniqued string values for
173// quick comparison and efficient memory usage.
174void FileSpec::SetFile(llvm::StringRef pathname, Style style) {
175 Clear();
176 m_style = (style == Style::native) ? GetNativeStyle() : style;
177
178 if (pathname.empty())
179 return;
180
181 llvm::SmallString<128> resolved(pathname);
182
183 // Normalize the path by removing ".", ".." and other redundant components.
184 if (needsNormalization(resolved))
185 llvm::sys::path::remove_dots(resolved, true, m_style);
186
187 // Normalize back slashes to forward slashes
188 if (m_style == Style::windows)
189 llvm::replace(resolved, '\\', '/');
190
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
194 // utilities.
195 m_filename.SetString(".");
196 return;
197 }
198
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);
204
205 llvm::StringRef directory = llvm::sys::path::parent_path(resolved, m_style);
206 if(!directory.empty())
207 m_directory.SetString(directory);
208}
209
210void FileSpec::SetFile(llvm::StringRef path, const llvm::Triple &triple) {
211 return SetFile(path, triple.isOSWindows() ? Style::windows : Style::posix);
212}
213
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:
216//
217// if (file_spec)
218// {}
219FileSpec::operator bool() const { return m_filename || m_directory; }
220
221// Logical NOT operator. This allows code to check any FileSpec objects to see
222// if they are invalid using code such as:
223//
224// if (!file_spec)
225// {}
226bool FileSpec::operator!() const { return !m_directory && !m_filename; }
227
228bool FileSpec::DirectoryEquals(const FileSpec &rhs) const {
229 if (IsCaseSensitive() || rhs.IsCaseSensitive())
230 return GetDirectory() == rhs.GetDirectory();
231 return GetDirectory().equals_insensitive(rhs.GetDirectory());
232}
233
234bool FileSpec::FileEquals(const FileSpec &rhs) const {
235 if (IsCaseSensitive() || rhs.IsCaseSensitive())
236 return GetFilename() == rhs.GetFilename();
237 return GetFilename().equals_insensitive(rhs.GetFilename());
238}
239
240// Equal to operator
241bool FileSpec::operator==(const FileSpec &rhs) const {
242 return FileEquals(rhs) && DirectoryEquals(rhs);
243}
244
245// Not equal to operator
246bool FileSpec::operator!=(const FileSpec &rhs) const { return !(*this == rhs); }
247
248// Less than operator
249bool FileSpec::operator<(const FileSpec &rhs) const {
250 return FileSpec::Compare(*this, rhs, true) < 0;
251}
252
253// Dump a FileSpec object to a stream
255 f.Dump(s.AsRawOstream());
256 return s;
257}
258
259// Clear this object by releasing both the directory and filename string values
260// and making them both the empty string.
262 m_directory.Clear();
263 m_filename.Clear();
265}
266
267// Compare two FileSpec objects. If "full" is true, then both the directory and
268// the filename must match. If "full" is false, then the directory names for
269// "a" and "b" are only compared if they are both non-empty. This allows a
270// FileSpec object to only contain a filename and it can match FileSpec objects
271// that have matching filenames with different paths.
272//
273// Return -1 if the "a" is less than "b", 0 if "a" is equal to "b" and "1" if
274// "a" is greater than "b".
275int FileSpec::Compare(const FileSpec &a, const FileSpec &b, bool full) {
276 int result = 0;
277
278 // case sensitivity of compare
279 const bool case_sensitive = a.IsCaseSensitive() || b.IsCaseSensitive();
280
281 // If full is true, then we must compare both the directory and filename.
282
283 // If full is false, then if either directory is empty, then we match on the
284 // basename only, and if both directories have valid values, we still do a
285 // full compare. This allows for matching when we just have a filename in one
286 // of the FileSpec objects.
287
288 if (full || (a.m_directory && b.m_directory)) {
289 if (case_sensitive)
290 result = a.GetDirectory().compare(b.GetDirectory());
291 else
292 result = a.GetDirectory().compare_insensitive(b.GetDirectory());
293
294 if (result)
295 return result;
296 }
297
298 if (case_sensitive)
299 result = a.GetFilename().compare(b.GetFilename());
300 else
301 result = a.GetFilename().compare_insensitive(b.GetFilename());
302
303 return result;
304}
305
306bool FileSpec::Equal(const FileSpec &a, const FileSpec &b, bool full) {
307 if (full || (!a.GetDirectory().empty() && !b.GetDirectory().empty()))
308 return a == b;
309
310 return a.FileEquals(b);
311}
312
313bool FileSpec::Match(const FileSpec &pattern, const FileSpec &file) {
314 if (!pattern.GetDirectory().empty())
315 return pattern == file;
316 if (!pattern.GetFilename().empty())
317 return pattern.FileEquals(file);
318 return true;
319}
320
321std::optional<FileSpec::Style>
322FileSpec::GuessPathStyle(llvm::StringRef absolute_path) {
323 if (absolute_path.starts_with("/"))
324 return Style::posix;
325 if (absolute_path.starts_with(R"(\\)"))
326 return Style::windows;
327 if (absolute_path.size() >= 3 && llvm::isAlpha(absolute_path[0]) &&
328 (absolute_path.substr(1, 2) == R"(:\)" ||
329 absolute_path.substr(1, 2) == R"(:/)"))
330 return Style::windows;
331 return std::nullopt;
332}
333
334// Dump the object to the supplied stream. If the object contains a valid
335// directory name, it will be displayed followed by a directory delimiter, and
336// the filename.
337void FileSpec::Dump(llvm::raw_ostream &s) const {
338 std::string path{GetPath(true)};
339 s << path;
340 char path_separator = GetPreferredPathSeparator(m_style);
341 if (!m_filename && !path.empty() && path.back() != path_separator)
342 s << path_separator;
343}
344
345llvm::json::Value FileSpec::ToJSON() const {
346 std::string str;
347 llvm::raw_string_ostream stream(str);
348 this->Dump(stream);
349 return llvm::json::Value(std::move(str));
350}
351
353
354void FileSpec::SetDirectory(llvm::StringRef directory) {
355 m_directory = ConstString(directory);
357}
358
359void FileSpec::SetFilename(llvm::StringRef filename) {
360 m_filename = ConstString(filename);
362}
363
365 m_filename.Clear();
367}
368
370 m_directory.Clear();
372}
373
374// Extract the directory and path into a fixed buffer. This is needed as the
375// directory and path are stored in separate string values.
376size_t FileSpec::GetPath(char *path, size_t path_max_len,
377 bool denormalize) const {
378 if (!path)
379 return 0;
380
381 std::string result = GetPath(denormalize);
382 ::snprintf(path, path_max_len, "%s", result.c_str());
383 return std::min(path_max_len - 1, result.length());
384}
385
386std::string FileSpec::GetPath(bool denormalize) const {
387 llvm::SmallString<64> result;
388 GetPath(result, denormalize);
389 return static_cast<std::string>(result);
390}
391
393 bool denormalize) const {
394 path.append(m_directory.GetStringRef().begin(),
395 m_directory.GetStringRef().end());
396 // Since the path was normalized and all paths use '/' when stored in these
397 // objects, we don't need to look for the actual syntax specific path
398 // separator, we just look for and insert '/'.
399 if (m_directory && m_filename && m_directory.GetStringRef().back() != '/' &&
400 m_filename.GetStringRef().back() != '/')
401 path.insert(path.end(), '/');
402 path.append(m_filename.GetStringRef().begin(),
403 m_filename.GetStringRef().end());
404 if (denormalize && !path.empty())
405 Denormalize(path, m_style);
406}
407
408llvm::StringRef FileSpec::GetFileNameExtension() const {
409 return llvm::sys::path::extension(m_filename.GetStringRef(), m_style);
410}
411
413 return llvm::sys::path::stem(m_filename.GetStringRef(), m_style);
414}
415
416// Return the size in bytes that this object takes in memory. This returns the
417// size in bytes of this object, not any shared string values it may refer to.
418size_t FileSpec::MemorySize() const {
419 return m_filename.MemorySize() + m_directory.MemorySize();
420}
421
423FileSpec::CopyByAppendingPathComponent(llvm::StringRef component) const {
424 FileSpec ret = *this;
425 ret.AppendPathComponent(component);
426 return ret;
427}
428
430 llvm::SmallString<64> current_path;
431 GetPath(current_path, false);
432 if (llvm::sys::path::has_parent_path(current_path, m_style))
433 return FileSpec(llvm::sys::path::parent_path(current_path, m_style),
434 m_style);
435 return *this;
436}
437
438void FileSpec::PrependPathComponent(llvm::StringRef component) {
439 llvm::SmallString<64> new_path(component);
440 llvm::SmallString<64> current_path;
441 GetPath(current_path, false);
442 llvm::sys::path::append(new_path,
443 llvm::sys::path::begin(current_path, m_style),
444 llvm::sys::path::end(current_path), m_style);
445 SetFile(new_path, m_style);
446}
447
449 return PrependPathComponent(new_path.GetPath(false));
450}
451
452void FileSpec::AppendPathComponent(llvm::StringRef component) {
453 llvm::SmallString<64> current_path;
454 GetPath(current_path, false);
455 llvm::sys::path::append(current_path, m_style, component);
456 SetFile(current_path, m_style);
457}
458
460 return AppendPathComponent(new_path.GetPath(false));
461}
462
464 llvm::SmallString<64> current_path;
465 GetPath(current_path, false);
466 if (llvm::sys::path::has_parent_path(current_path, m_style)) {
467 SetFile(llvm::sys::path::parent_path(current_path, m_style));
468 return true;
469 }
470 return false;
471}
472
473std::vector<llvm::StringRef> FileSpec::GetComponents() const {
474 std::vector<llvm::StringRef> components;
475
476 auto dir_begin = llvm::sys::path::begin(m_directory.GetStringRef(), m_style);
477 auto dir_end = llvm::sys::path::end(m_directory.GetStringRef());
478
479 for (auto iter = dir_begin; iter != dir_end; ++iter) {
480 if (*iter == "/" || *iter == ".")
481 continue;
482
483 components.push_back(*iter);
484 }
485
486 if (!m_filename.IsEmpty() && m_filename != "/" && m_filename != ".")
487 components.push_back(m_filename.GetStringRef());
488
489 return components;
490}
491
492/// Returns true if the filespec represents an implementation source
493/// file (files with a ".c", ".cpp", ".m", ".mm" (many more)
494/// extension).
495///
496/// \return
497/// \b true if the filespec represents an implementation source
498/// file, \b false otherwise.
500 llvm::StringRef extension = GetFileNameExtension();
501 if (extension.empty())
502 return false;
503
504 static RegularExpression g_source_file_regex(llvm::StringRef(
505 "^.([cC]|[mM]|[mM][mM]|[cC][pP][pP]|[cC]\\+\\+|[cC][xX][xX]|[cC][cC]|["
506 "cC][pP]|[sS]|[aA][sS][mM]|[fF]|[fF]77|[fF]90|[fF]95|[fF]03|[fF][oO]["
507 "rR]|[fF][tT][nN]|[fF][pP][pP]|[aA][dD][aA]|[aA][dD][bB]|[aA][dD][sS])"
508 "$"));
509 return g_source_file_regex.Execute(extension);
510}
511
513 return !IsAbsolute();
514}
515
517 // Check if we have cached if this path is absolute to avoid recalculating.
519 return m_absolute == Absolute::Yes;
520
522
523 llvm::SmallString<64> path;
524 GetPath(path, false);
525
526 if (!path.empty()) {
527 // We consider paths starting with ~ to be absolute.
528 if (path[0] == '~' || llvm::sys::path::is_absolute(path, m_style))
530 }
531
532 return m_absolute == Absolute::Yes;
533}
534
536 if (IsRelative())
538}
539
540void llvm::format_provider<FileSpec>::format(const FileSpec &F,
541 raw_ostream &Stream,
542 StringRef Style) {
543 assert((Style.empty() || Style.equals_insensitive("F") ||
544 Style.equals_insensitive("D")) &&
545 "Invalid FileSpec style!");
546
547 StringRef dir = F.GetDirectory();
548 StringRef file = F.GetFilename();
549
550 if (dir.empty() && file.empty()) {
551 Stream << "(empty)";
552 return;
553 }
554
555 if (Style.equals_insensitive("F")) {
556 Stream << (file.empty() ? "(empty)" : file);
557 return;
558 }
559
560 // Style is either D or empty, either way we need to print the directory.
561 if (!dir.empty()) {
562 // Directory is stored in normalized form, which might be different than
563 // preferred form. In order to handle this, we need to cut off the
564 // filename, then denormalize, then write the entire denorm'ed directory.
565 llvm::SmallString<64> denormalized_dir = dir;
566 Denormalize(denormalized_dir, F.GetPathStyle());
567 Stream << denormalized_dir;
568 Stream << GetPreferredPathSeparator(F.GetPathStyle());
569 }
570
571 if (Style.equals_insensitive("D")) {
572 // We only want to print the directory, so now just exit.
573 if (dir.empty())
574 Stream << "(empty)";
575 return;
576 }
577
578 if (!file.empty())
579 Stream << file;
580}
A uniqued constant string class.
Definition ConstString.h:40
A file utility class.
Definition FileSpec.h:57
void SetFile(llvm::StringRef path, Style style)
Change the file specified with a new path.
Definition FileSpec.cpp:174
FileSpec CopyByAppendingPathComponent(llvm::StringRef component) const
Definition FileSpec.cpp:423
void AppendPathComponent(llvm::StringRef component)
Definition FileSpec.cpp:452
static bool Equal(const FileSpec &a, const FileSpec &b, bool full)
Definition FileSpec.cpp:306
static std::optional< Style > GuessPathStyle(llvm::StringRef absolute_path)
Attempt to guess path style for a given path string.
Definition FileSpec.cpp:322
static bool Match(const FileSpec &pattern, const FileSpec &file)
Match FileSpec pattern against FileSpec file.
Definition FileSpec.cpp:313
bool IsRelative() const
Returns true if the filespec represents a relative path.
Definition FileSpec.cpp:512
bool FileEquals(const FileSpec &other) const
Definition FileSpec.cpp:234
bool operator<(const FileSpec &rhs) const
Less than to operator.
Definition FileSpec.cpp:249
bool RemoveLastPathComponent()
Removes the last path component by replacing the current path with its parent.
Definition FileSpec.cpp:463
llvm::StringRef GetFileNameStrippingExtension() const
Return the filename without the extension part.
Definition FileSpec.cpp:412
void SetFilename(llvm::StringRef filename)
Filename string set accessor.
Definition FileSpec.cpp:359
void MakeAbsolute(const FileSpec &dir)
Make the FileSpec absolute by treating it relative to dir.
Definition FileSpec.cpp:535
bool operator!() const
Logical NOT operator.
Definition FileSpec.cpp:226
ConstString m_filename
The unique'd filename path.
Definition FileSpec.h:422
std::vector< llvm::StringRef > GetComponents() const
Gets the components of the FileSpec's path.
Definition FileSpec.cpp:473
void ClearDirectory()
Clear the directory in this object.
Definition FileSpec.cpp:369
bool IsCaseSensitive() const
Case sensitivity of path.
Definition FileSpec.h:206
bool DirectoryEquals(const FileSpec &other) const
Definition FileSpec.cpp:228
llvm::StringRef GetFilename() const
Filename string const get accessor.
Definition FileSpec.h:249
bool IsAbsolute() const
Returns true if the filespec represents an absolute path.
Definition FileSpec.cpp:516
Style GetPathStyle() const
Definition FileSpec.cpp:352
void PathWasModified()
Called anytime m_directory or m_filename is changed to clear any cached state in this object.
Definition FileSpec.h:414
size_t MemorySize() const
Get the memory cost of this object.
Definition FileSpec.cpp:418
static int Compare(const FileSpec &lhs, const FileSpec &rhs, bool full)
Compare two FileSpec objects.
Definition FileSpec.cpp:275
llvm::json::Value ToJSON() const
Convert the filespec object to a json value.
Definition FileSpec.cpp:345
Style m_style
The syntax that this path uses. (e.g. Windows / Posix)
Definition FileSpec.h:428
void PrependPathComponent(llvm::StringRef component)
Definition FileSpec.cpp:438
llvm::StringRef GetDirectory() const
Directory string const get accessor.
Definition FileSpec.h:234
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:376
void Clear()
Clears the object state.
Definition FileSpec.cpp:261
Absolute m_absolute
Cache whether this path is absolute.
Definition FileSpec.h:425
bool operator!=(const FileSpec &rhs) const
Not equal to operator.
Definition FileSpec.cpp:246
void SetDirectory(llvm::StringRef directory)
Directory string set accessor.
Definition FileSpec.cpp:354
void Dump(llvm::raw_ostream &s) const
Dump this object to a Stream.
Definition FileSpec.cpp:337
bool IsSourceImplementationFile() const
Returns true if the filespec represents an implementation source file (files with a "....
Definition FileSpec.cpp:499
ConstString m_directory
The unique'd directory path.
Definition FileSpec.h:419
bool operator==(const FileSpec &rhs) const
Equal to operator.
Definition FileSpec.cpp:241
FileSpec CopyByRemovingLastPathComponent() const
Definition FileSpec.cpp:429
llvm::StringRef GetFileNameExtension() const
Extract the extension of the file.
Definition FileSpec.cpp:408
llvm::sys::path::Style Style
Definition FileSpec.h:59
void ClearFilename()
Clear the filename in this object.
Definition FileSpec.cpp:364
bool Execute(llvm::StringRef string, llvm::SmallVectorImpl< llvm::StringRef > *matches=nullptr) const
Execute a regular expression match using the compiled regular expression that is already in this obje...
A stream class that can stream formatted output to a file.
Definition Stream.h:28
llvm::raw_ostream & AsRawOstream()
Returns a raw_ostream that forwards the data to this Stream object.
Definition Stream.h:405
A class that represents a running process on the host machine.
Stream & operator<<(Stream &s, const Mangled &obj)