blob: ddb98401e24022fed14fd6c0d539055aae5893ec [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
Kate Stoneb9c1b512016-09-06 20:57:50 +000010#include <fstream>
Rafael Espindola09079162013-06-13 20:10:23 +000011#include <set>
Greg Claytone0f3c022011-02-07 17:41:11 +000012#include <string.h>
Greg Claytonfd184262011-02-05 02:27:52 +000013
Zachary Turner1f875342017-03-13 02:44:39 +000014#include "llvm/Config/llvm-config.h"
15#ifndef LLVM_ON_WIN32
Jim Inghamf818ca32010-07-01 01:48:53 +000016#include <pwd.h>
Greg Claytonfd184262011-02-05 02:27:52 +000017#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +000018
Zachary Turner4af068e2017-03-06 23:52:57 +000019#include "lldb/Core/StringList.h"
Zachary Turnerc00cf4a2014-08-15 22:04:21 +000020#include "lldb/Host/FileSpec.h"
Zachary Turnerc00cf4a2014-08-15 22:04:21 +000021#include "lldb/Utility/CleanUp.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000022#include "lldb/Utility/RegularExpression.h"
23#include "lldb/Utility/Stream.h"
24#include "lldb/Utility/StreamString.h"
Zachary Turnerc00cf4a2014-08-15 22:04:21 +000025
Zachary Turnerfe83ad82016-09-27 20:48:37 +000026#include "llvm/ADT/StringExtras.h"
Caroline Tice391a9602010-09-12 00:10:52 +000027#include "llvm/ADT/StringRef.h"
Zachary Turner190fadc2016-03-22 17:58:09 +000028#include "llvm/Support/ConvertUTF.h"
Zachary Turner3f559742014-08-07 17:33:36 +000029#include "llvm/Support/FileSystem.h"
Greg Clayton38a61402010-12-02 23:20:03 +000030#include "llvm/Support/Path.h"
31#include "llvm/Support/Program.h"
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
Zachary Turner7d86ee52017-03-08 17:56:08 +000038static constexpr FileSpec::PathSyntax GetNativeSyntax() {
39#if defined(LLVM_ON_WIN32)
40 return FileSpec::ePathSyntaxWindows;
41#else
42 return FileSpec::ePathSyntaxPosix;
43#endif
44}
45
Kate Stoneb9c1b512016-09-06 20:57:50 +000046bool PathSyntaxIsPosix(FileSpec::PathSyntax syntax) {
47 return (syntax == FileSpec::ePathSyntaxPosix ||
48 (syntax == FileSpec::ePathSyntaxHostNative &&
Zachary Turner7d86ee52017-03-08 17:56:08 +000049 GetNativeSyntax() == FileSpec::ePathSyntaxPosix));
Chaoren Lin1c614fe2015-05-28 17:02:45 +000050}
51
Kate Stoneb9c1b512016-09-06 20:57:50 +000052const char *GetPathSeparators(FileSpec::PathSyntax syntax) {
53 return PathSyntaxIsPosix(syntax) ? "/" : "\\/";
Pavel Labath144119b2016-04-04 14:39:12 +000054}
55
Zachary Turnerfe83ad82016-09-27 20:48:37 +000056char GetPreferredPathSeparator(FileSpec::PathSyntax syntax) {
Kate Stoneb9c1b512016-09-06 20:57:50 +000057 return GetPathSeparators(syntax)[0];
Pavel Labath144119b2016-04-04 14:39:12 +000058}
59
Kate Stoneb9c1b512016-09-06 20:57:50 +000060bool IsPathSeparator(char value, FileSpec::PathSyntax syntax) {
61 return value == '/' || (!PathSyntaxIsPosix(syntax) && value == '\\');
Chaoren Lin1c614fe2015-05-28 17:02:45 +000062}
63
Kate Stoneb9c1b512016-09-06 20:57:50 +000064void Normalize(llvm::SmallVectorImpl<char> &path, FileSpec::PathSyntax syntax) {
65 if (PathSyntaxIsPosix(syntax))
66 return;
Chaoren Lin1c614fe2015-05-28 17:02:45 +000067
Kate Stoneb9c1b512016-09-06 20:57:50 +000068 std::replace(path.begin(), path.end(), '\\', '/');
69 // Windows path can have \\ slashes which can be changed by replace
70 // call above to //. Here we remove the duplicate.
71 auto iter = std::unique(path.begin(), path.end(), [](char &c1, char &c2) {
72 return (c1 == '/' && c2 == '/');
73 });
74 path.erase(iter, path.end());
Chaoren Lin1c614fe2015-05-28 17:02:45 +000075}
76
Kate Stoneb9c1b512016-09-06 20:57:50 +000077void Denormalize(llvm::SmallVectorImpl<char> &path,
78 FileSpec::PathSyntax syntax) {
79 if (PathSyntaxIsPosix(syntax))
80 return;
Chaoren Lin1c614fe2015-05-28 17:02:45 +000081
Kate Stoneb9c1b512016-09-06 20:57:50 +000082 std::replace(path.begin(), path.end(), '/', '\\');
Chaoren Lin1c614fe2015-05-28 17:02:45 +000083}
84
Kate Stoneb9c1b512016-09-06 20:57:50 +000085size_t FilenamePos(llvm::StringRef str, FileSpec::PathSyntax syntax) {
86 if (str.size() == 2 && IsPathSeparator(str[0], syntax) && str[0] == str[1])
87 return 0;
Pavel Labath144119b2016-04-04 14:39:12 +000088
Kate Stoneb9c1b512016-09-06 20:57:50 +000089 if (str.size() > 0 && IsPathSeparator(str.back(), syntax))
90 return str.size() - 1;
Pavel Labath144119b2016-04-04 14:39:12 +000091
Kate Stoneb9c1b512016-09-06 20:57:50 +000092 size_t pos = str.find_last_of(GetPathSeparators(syntax), str.size() - 1);
Pavel Labath144119b2016-04-04 14:39:12 +000093
Kate Stoneb9c1b512016-09-06 20:57:50 +000094 if (!PathSyntaxIsPosix(syntax) && pos == llvm::StringRef::npos)
95 pos = str.find_last_of(':', str.size() - 2);
Pavel Labath144119b2016-04-04 14:39:12 +000096
Kate Stoneb9c1b512016-09-06 20:57:50 +000097 if (pos == llvm::StringRef::npos ||
98 (pos == 1 && IsPathSeparator(str[0], syntax)))
99 return 0;
Pavel Labath144119b2016-04-04 14:39:12 +0000100
Kate Stoneb9c1b512016-09-06 20:57:50 +0000101 return pos + 1;
Chaoren Lin1c614fe2015-05-28 17:02:45 +0000102}
103
Kate Stoneb9c1b512016-09-06 20:57:50 +0000104size_t RootDirStart(llvm::StringRef str, FileSpec::PathSyntax syntax) {
105 // case "c:/"
106 if (!PathSyntaxIsPosix(syntax) &&
107 (str.size() > 2 && str[1] == ':' && IsPathSeparator(str[2], syntax)))
108 return 2;
Pavel Labath144119b2016-04-04 14:39:12 +0000109
Kate Stoneb9c1b512016-09-06 20:57:50 +0000110 // case "//"
111 if (str.size() == 2 && IsPathSeparator(str[0], syntax) && str[0] == str[1])
Pavel Labath144119b2016-04-04 14:39:12 +0000112 return llvm::StringRef::npos;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000113
114 // case "//net"
115 if (str.size() > 3 && IsPathSeparator(str[0], syntax) && str[0] == str[1] &&
116 !IsPathSeparator(str[2], syntax))
117 return str.find_first_of(GetPathSeparators(syntax), 2);
118
119 // case "/"
120 if (str.size() > 0 && IsPathSeparator(str[0], syntax))
121 return 0;
122
123 return llvm::StringRef::npos;
Pavel Labath144119b2016-04-04 14:39:12 +0000124}
125
Kate Stoneb9c1b512016-09-06 20:57:50 +0000126size_t ParentPathEnd(llvm::StringRef path, FileSpec::PathSyntax syntax) {
127 size_t end_pos = FilenamePos(path, syntax);
Pavel Labath144119b2016-04-04 14:39:12 +0000128
Kate Stoneb9c1b512016-09-06 20:57:50 +0000129 bool filename_was_sep =
130 path.size() > 0 && IsPathSeparator(path[end_pos], syntax);
Pavel Labath144119b2016-04-04 14:39:12 +0000131
Kate Stoneb9c1b512016-09-06 20:57:50 +0000132 // Skip separators except for root dir.
133 size_t root_dir_pos = RootDirStart(path.substr(0, end_pos), syntax);
Pavel Labath144119b2016-04-04 14:39:12 +0000134
Kate Stoneb9c1b512016-09-06 20:57:50 +0000135 while (end_pos > 0 && (end_pos - 1) != root_dir_pos &&
136 IsPathSeparator(path[end_pos - 1], syntax))
137 --end_pos;
Pavel Labath144119b2016-04-04 14:39:12 +0000138
Kate Stoneb9c1b512016-09-06 20:57:50 +0000139 if (end_pos == 1 && root_dir_pos == 0 && filename_was_sep)
140 return llvm::StringRef::npos;
Pavel Labath144119b2016-04-04 14:39:12 +0000141
Kate Stoneb9c1b512016-09-06 20:57:50 +0000142 return end_pos;
Pavel Labath144119b2016-04-04 14:39:12 +0000143}
144
145} // end anonymous namespace
146
Jim Inghamf818ca32010-07-01 01:48:53 +0000147// Resolves the username part of a path of the form ~user/other/directories, and
Kate Stoneb9c1b512016-09-06 20:57:50 +0000148// writes the result into dst_path. This will also resolve "~" to the current
149// user.
150// If you want to complete "~" to the list of users, pass it to
151// ResolvePartialUsername.
152void FileSpec::ResolveUsername(llvm::SmallVectorImpl<char> &path) {
Zachary Turner1f875342017-03-13 02:44:39 +0000153#ifndef LLVM_ON_WIN32
Kate Stoneb9c1b512016-09-06 20:57:50 +0000154 if (path.empty() || path[0] != '~')
155 return;
Zachary Turner3f559742014-08-07 17:33:36 +0000156
Kate Stoneb9c1b512016-09-06 20:57:50 +0000157 llvm::StringRef path_str(path.data(), path.size());
158 size_t slash_pos = path_str.find('/', 1);
159 if (slash_pos == 1 || path.size() == 1) {
160 // A path of ~/ resolves to the current user's home dir
161 llvm::SmallString<64> home_dir;
162 // llvm::sys::path::home_directory() only checks if "HOME" is set in the
163 // environment and does nothing else to locate the user home directory
164 if (!llvm::sys::path::home_directory(home_dir)) {
165 struct passwd *pw = getpwuid(getuid());
166 if (pw && pw->pw_dir && pw->pw_dir[0]) {
167 // Update our environemnt so llvm::sys::path::home_directory() works
168 // next time
169 setenv("HOME", pw->pw_dir, 0);
170 home_dir.assign(llvm::StringRef(pw->pw_dir));
171 } else {
172 return;
173 }
Jim Inghamf818ca32010-07-01 01:48:53 +0000174 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000175
176 // Overwrite the ~ with the first character of the homedir, and insert
177 // the rest. This way we only trigger one move, whereas an insert
178 // followed by a delete (or vice versa) would trigger two.
179 path[0] = home_dir[0];
180 path.insert(path.begin() + 1, home_dir.begin() + 1, home_dir.end());
181 return;
182 }
183
184 auto username_begin = path.begin() + 1;
185 auto username_end = (slash_pos == llvm::StringRef::npos)
186 ? path.end()
187 : (path.begin() + slash_pos);
188 size_t replacement_length = std::distance(path.begin(), username_end);
189
190 llvm::SmallString<20> username(username_begin, username_end);
191 struct passwd *user_entry = ::getpwnam(username.c_str());
192 if (user_entry != nullptr) {
193 // Copy over the first n characters of the path, where n is the smaller of
194 // the length
195 // of the home directory and the slash pos.
196 llvm::StringRef homedir(user_entry->pw_dir);
197 size_t initial_copy_length = std::min(homedir.size(), replacement_length);
198 auto src_begin = homedir.begin();
199 auto src_end = src_begin + initial_copy_length;
200 std::copy(src_begin, src_end, path.begin());
201 if (replacement_length > homedir.size()) {
202 // We copied the entire home directory, but the ~username portion of the
203 // path was
204 // longer, so there's characters that need to be removed.
205 path.erase(path.begin() + initial_copy_length, username_end);
206 } else if (replacement_length < homedir.size()) {
207 // We copied all the way up to the slash in the destination, but there's
208 // still more
209 // characters that need to be inserted.
210 path.insert(username_end, src_end, homedir.end());
Jim Inghamf818ca32010-07-01 01:48:53 +0000211 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000212 } else {
213 // Unable to resolve username (user doesn't exist?)
214 path.clear();
215 }
Zachary Turner3f559742014-08-07 17:33:36 +0000216#endif
Jim Inghamf818ca32010-07-01 01:48:53 +0000217}
218
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000219size_t FileSpec::ResolvePartialUsername(llvm::StringRef partial_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000220 StringList &matches) {
Zachary Turner1f875342017-03-13 02:44:39 +0000221#ifndef LLVM_ON_WIN32
Kate Stoneb9c1b512016-09-06 20:57:50 +0000222 size_t extant_entries = matches.GetSize();
223
224 setpwent();
225 struct passwd *user_entry;
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000226 partial_name = partial_name.drop_front();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000227 std::set<std::string> name_list;
228
229 while ((user_entry = getpwent()) != NULL) {
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000230 if (llvm::StringRef(user_entry->pw_name).startswith(partial_name)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000231 std::string tmp_buf("~");
232 tmp_buf.append(user_entry->pw_name);
233 tmp_buf.push_back('/');
234 name_list.insert(tmp_buf);
Jim Ingham84363072011-02-08 23:24:09 +0000235 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000236 }
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000237
238 for (auto &name : name_list) {
239 matches.AppendString(name);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000240 }
241 return matches.GetSize() - extant_entries;
Jim Ingham84363072011-02-08 23:24:09 +0000242#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000243 // Resolving home directories is not supported, just copy the path...
244 return 0;
Zachary Turner1f875342017-03-13 02:44:39 +0000245#endif // #ifdef LLVM_ON_WIN32
Jim Ingham84363072011-02-08 23:24:09 +0000246}
247
Kate Stoneb9c1b512016-09-06 20:57:50 +0000248void FileSpec::Resolve(llvm::SmallVectorImpl<char> &path) {
249 if (path.empty())
250 return;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000251
Zachary Turner1f875342017-03-13 02:44:39 +0000252#ifndef LLVM_ON_WIN32
Kate Stoneb9c1b512016-09-06 20:57:50 +0000253 if (path[0] == '~')
254 ResolveUsername(path);
Zachary Turner1f875342017-03-13 02:44:39 +0000255#endif // #ifdef LLVM_ON_WIN32
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000256
Kate Stoneb9c1b512016-09-06 20:57:50 +0000257 // Save a copy of the original path that's passed in
258 llvm::SmallString<128> original_path(path.begin(), path.end());
Jason Molenda671a29d2015-02-25 02:35:25 +0000259
Kate Stoneb9c1b512016-09-06 20:57:50 +0000260 llvm::sys::fs::make_absolute(path);
261 if (!llvm::sys::fs::exists(path)) {
262 path.clear();
263 path.append(original_path.begin(), original_path.end());
264 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000265}
266
Zachary Turner7d86ee52017-03-08 17:56:08 +0000267FileSpec::FileSpec() : m_syntax(GetNativeSyntax()) {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000268
269//------------------------------------------------------------------
270// Default constructor that can take an optional full path to a
271// file on disk.
272//------------------------------------------------------------------
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000273FileSpec::FileSpec(llvm::StringRef path, bool resolve_path, PathSyntax syntax)
Sam McCall6f43d9d2016-11-15 10:58:16 +0000274 : m_syntax(syntax) {
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000275 SetFile(path, resolve_path, syntax);
Jim Ingham0909e5f2010-09-16 00:57:33 +0000276}
277
Zachary Turner8c6b5462017-03-06 23:42:44 +0000278FileSpec::FileSpec(llvm::StringRef path, bool resolve_path,
279 const llvm::Triple &Triple)
280 : FileSpec{path, resolve_path,
281 Triple.isOSWindows() ? ePathSyntaxWindows : ePathSyntaxPosix} {}
Chaoren Linf34f4102015-05-09 01:21:32 +0000282
Jim Ingham0909e5f2010-09-16 00:57:33 +0000283//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000284// Copy constructor
285//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000286FileSpec::FileSpec(const FileSpec &rhs)
287 : m_directory(rhs.m_directory), m_filename(rhs.m_filename),
288 m_is_resolved(rhs.m_is_resolved), m_syntax(rhs.m_syntax) {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000289
290//------------------------------------------------------------------
291// Copy constructor
292//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000293FileSpec::FileSpec(const FileSpec *rhs) : m_directory(), m_filename() {
294 if (rhs)
295 *this = *rhs;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000296}
297
298//------------------------------------------------------------------
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +0000299// Virtual destructor in case anyone inherits from this class.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000300//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000301FileSpec::~FileSpec() {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000302
303//------------------------------------------------------------------
304// Assignment operator.
305//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000306const FileSpec &FileSpec::operator=(const FileSpec &rhs) {
307 if (this != &rhs) {
308 m_directory = rhs.m_directory;
309 m_filename = rhs.m_filename;
310 m_is_resolved = rhs.m_is_resolved;
311 m_syntax = rhs.m_syntax;
312 }
313 return *this;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000314}
315
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000316//------------------------------------------------------------------
317// Update the contents of this object with a new path. The path will
318// be split up into a directory and filename and stored as uniqued
319// string values for quick comparison and efficient memory usage.
320//------------------------------------------------------------------
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000321void FileSpec::SetFile(llvm::StringRef pathname, bool resolve,
322 PathSyntax syntax) {
323 // CLEANUP: Use StringRef for string handling. This function is kind of a
324 // mess and the unclear semantics of RootDirStart and ParentPathEnd make
325 // it very difficult to understand this function. There's no reason this
326 // function should be particularly complicated or difficult to understand.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000327 m_filename.Clear();
328 m_directory.Clear();
329 m_is_resolved = false;
Zachary Turner7d86ee52017-03-08 17:56:08 +0000330 m_syntax = (syntax == ePathSyntaxHostNative) ? GetNativeSyntax() : syntax;
Zachary Turnerdf62f202014-08-07 17:33:07 +0000331
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000332 if (pathname.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000333 return;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000334
Kate Stoneb9c1b512016-09-06 20:57:50 +0000335 llvm::SmallString<64> resolved(pathname);
Zachary Turnerdf62f202014-08-07 17:33:07 +0000336
Kate Stoneb9c1b512016-09-06 20:57:50 +0000337 if (resolve) {
338 FileSpec::Resolve(resolved);
339 m_is_resolved = true;
340 }
Zachary Turnerc7a17ed2014-12-01 23:13:32 +0000341
Zachary Turner827d5d72016-12-16 04:27:00 +0000342 Normalize(resolved, m_syntax);
Pavel Labatha212c582016-04-14 09:38:06 +0000343
Kate Stoneb9c1b512016-09-06 20:57:50 +0000344 llvm::StringRef resolve_path_ref(resolved.c_str());
Zachary Turner827d5d72016-12-16 04:27:00 +0000345 size_t dir_end = ParentPathEnd(resolve_path_ref, m_syntax);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000346 if (dir_end == 0) {
347 m_filename.SetString(resolve_path_ref);
348 return;
349 }
Pavel Labath144119b2016-04-04 14:39:12 +0000350
Kate Stoneb9c1b512016-09-06 20:57:50 +0000351 m_directory.SetString(resolve_path_ref.substr(0, dir_end));
Pavel Labath144119b2016-04-04 14:39:12 +0000352
Kate Stoneb9c1b512016-09-06 20:57:50 +0000353 size_t filename_begin = dir_end;
Zachary Turner827d5d72016-12-16 04:27:00 +0000354 size_t root_dir_start = RootDirStart(resolve_path_ref, m_syntax);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000355 while (filename_begin != llvm::StringRef::npos &&
356 filename_begin < resolve_path_ref.size() &&
357 filename_begin != root_dir_start &&
Zachary Turner827d5d72016-12-16 04:27:00 +0000358 IsPathSeparator(resolve_path_ref[filename_begin], m_syntax))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000359 ++filename_begin;
360 m_filename.SetString((filename_begin == llvm::StringRef::npos ||
361 filename_begin >= resolve_path_ref.size())
362 ? "."
363 : resolve_path_ref.substr(filename_begin));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000364}
365
Zachary Turner8c6b5462017-03-06 23:42:44 +0000366void FileSpec::SetFile(llvm::StringRef path, bool resolve,
367 const llvm::Triple &Triple) {
368 return SetFile(path, resolve,
369 Triple.isOSWindows() ? ePathSyntaxWindows : ePathSyntaxPosix);
Chaoren Lin44145d72015-05-29 19:52:37 +0000370}
371
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000372//----------------------------------------------------------------------
373// Convert to pointer operator. This allows code to check any FileSpec
374// objects to see if they contain anything valid using code such as:
375//
376// if (file_spec)
377// {}
378//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000379FileSpec::operator bool() const { return m_filename || m_directory; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000380
381//----------------------------------------------------------------------
382// Logical NOT operator. This allows code to check any FileSpec
383// objects to see if they are invalid using code such as:
384//
385// if (!file_spec)
386// {}
387//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000388bool FileSpec::operator!() const { return !m_directory && !m_filename; }
389
390bool FileSpec::DirectoryEquals(const FileSpec &rhs) const {
391 const bool case_sensitive = IsCaseSensitive() || rhs.IsCaseSensitive();
392 return ConstString::Equals(m_directory, rhs.m_directory, case_sensitive);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000393}
394
Kate Stoneb9c1b512016-09-06 20:57:50 +0000395bool FileSpec::FileEquals(const FileSpec &rhs) const {
396 const bool case_sensitive = IsCaseSensitive() || rhs.IsCaseSensitive();
397 return ConstString::Equals(m_filename, rhs.m_filename, case_sensitive);
Zachary Turner74e08ca2016-03-02 22:05:52 +0000398}
399
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000400//------------------------------------------------------------------
401// Equal to operator
402//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000403bool FileSpec::operator==(const FileSpec &rhs) const {
404 if (!FileEquals(rhs))
405 return false;
406 if (DirectoryEquals(rhs))
407 return true;
Zachary Turner47c03462016-02-24 21:26:47 +0000408
Kate Stoneb9c1b512016-09-06 20:57:50 +0000409 // TODO: determine if we want to keep this code in here.
410 // The code below was added to handle a case where we were
411 // trying to set a file and line breakpoint and one path
412 // was resolved, and the other not and the directory was
413 // in a mount point that resolved to a more complete path:
414 // "/tmp/a.c" == "/private/tmp/a.c". I might end up pulling
415 // this out...
416 if (IsResolved() && rhs.IsResolved()) {
417 // Both paths are resolved, no need to look further...
418 return false;
419 }
Zachary Turner47c03462016-02-24 21:26:47 +0000420
Kate Stoneb9c1b512016-09-06 20:57:50 +0000421 FileSpec resolved_lhs(*this);
Zachary Turner47c03462016-02-24 21:26:47 +0000422
Kate Stoneb9c1b512016-09-06 20:57:50 +0000423 // If "this" isn't resolved, resolve it
424 if (!IsResolved()) {
425 if (resolved_lhs.ResolvePath()) {
426 // This path wasn't resolved but now it is. Check if the resolved
427 // directory is the same as our unresolved directory, and if so,
428 // we can mark this object as resolved to avoid more future resolves
429 m_is_resolved = (m_directory == resolved_lhs.m_directory);
430 } else
431 return false;
432 }
Zachary Turner47c03462016-02-24 21:26:47 +0000433
Kate Stoneb9c1b512016-09-06 20:57:50 +0000434 FileSpec resolved_rhs(rhs);
435 if (!rhs.IsResolved()) {
436 if (resolved_rhs.ResolvePath()) {
437 // rhs's path wasn't resolved but now it is. Check if the resolved
438 // directory is the same as rhs's unresolved directory, and if so,
439 // we can mark this object as resolved to avoid more future resolves
440 rhs.m_is_resolved = (rhs.m_directory == resolved_rhs.m_directory);
441 } else
442 return false;
443 }
Zachary Turner47c03462016-02-24 21:26:47 +0000444
Kate Stoneb9c1b512016-09-06 20:57:50 +0000445 // If we reach this point in the code we were able to resolve both paths
446 // and since we only resolve the paths if the basenames are equal, then
447 // we can just check if both directories are equal...
448 return DirectoryEquals(rhs);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000449}
450
451//------------------------------------------------------------------
452// Not equal to operator
453//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000454bool FileSpec::operator!=(const FileSpec &rhs) const { return !(*this == rhs); }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000455
456//------------------------------------------------------------------
457// Less than operator
458//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000459bool FileSpec::operator<(const FileSpec &rhs) const {
460 return FileSpec::Compare(*this, rhs, true) < 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000461}
462
463//------------------------------------------------------------------
464// Dump a FileSpec object to a stream
465//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000466Stream &lldb_private::operator<<(Stream &s, const FileSpec &f) {
467 f.Dump(&s);
468 return s;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000469}
470
471//------------------------------------------------------------------
472// Clear this object by releasing both the directory and filename
473// string values and making them both the empty string.
474//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000475void FileSpec::Clear() {
476 m_directory.Clear();
477 m_filename.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000478}
479
480//------------------------------------------------------------------
481// Compare two FileSpec objects. If "full" is true, then both
482// the directory and the filename must match. If "full" is false,
483// then the directory names for "a" and "b" are only compared if
484// they are both non-empty. This allows a FileSpec object to only
485// contain a filename and it can match FileSpec objects that have
486// matching filenames with different paths.
487//
488// Return -1 if the "a" is less than "b", 0 if "a" is equal to "b"
489// and "1" if "a" is greater than "b".
490//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000491int FileSpec::Compare(const FileSpec &a, const FileSpec &b, bool full) {
492 int result = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000493
Kate Stoneb9c1b512016-09-06 20:57:50 +0000494 // case sensitivity of compare
495 const bool case_sensitive = a.IsCaseSensitive() || b.IsCaseSensitive();
Zachary Turner47c03462016-02-24 21:26:47 +0000496
Kate Stoneb9c1b512016-09-06 20:57:50 +0000497 // If full is true, then we must compare both the directory and filename.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000498
Kate Stoneb9c1b512016-09-06 20:57:50 +0000499 // If full is false, then if either directory is empty, then we match on
500 // the basename only, and if both directories have valid values, we still
501 // do a full compare. This allows for matching when we just have a filename
502 // in one of the FileSpec objects.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000503
Kate Stoneb9c1b512016-09-06 20:57:50 +0000504 if (full || (a.m_directory && b.m_directory)) {
505 result = ConstString::Compare(a.m_directory, b.m_directory, case_sensitive);
506 if (result)
507 return result;
508 }
509 return ConstString::Compare(a.m_filename, b.m_filename, case_sensitive);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000510}
511
Kate Stoneb9c1b512016-09-06 20:57:50 +0000512bool FileSpec::Equal(const FileSpec &a, const FileSpec &b, bool full,
513 bool remove_backups) {
514 // case sensitivity of equality test
515 const bool case_sensitive = a.IsCaseSensitive() || b.IsCaseSensitive();
Zachary Turner47c03462016-02-24 21:26:47 +0000516
Kate Stoneb9c1b512016-09-06 20:57:50 +0000517 if (!full && (a.GetDirectory().IsEmpty() || b.GetDirectory().IsEmpty()))
518 return ConstString::Equals(a.m_filename, b.m_filename, case_sensitive);
Pavel Labath218770b2016-10-31 16:22:07 +0000519
520 if (remove_backups == false)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000521 return a == b;
Jim Ingham96a15962014-11-15 01:54:26 +0000522
Pavel Labath218770b2016-10-31 16:22:07 +0000523 if (a == b)
524 return true;
525
526 return Equal(a.GetNormalizedPath(), b.GetNormalizedPath(), full, false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000527}
528
Pavel Labath218770b2016-10-31 16:22:07 +0000529FileSpec FileSpec::GetNormalizedPath() const {
530 // Fast path. Do nothing if the path is not interesting.
531 if (!m_directory.GetStringRef().contains(".") &&
Pavel Labathe6e7e6c2016-11-30 16:08:45 +0000532 !m_directory.GetStringRef().contains("//") &&
533 m_filename.GetStringRef() != ".." && m_filename.GetStringRef() != ".")
Pavel Labath218770b2016-10-31 16:22:07 +0000534 return *this;
Greg Clayton5a271952015-06-02 22:43:29 +0000535
Pavel Labath218770b2016-10-31 16:22:07 +0000536 llvm::SmallString<64> path, result;
537 const bool normalize = false;
538 GetPath(path, normalize);
539 llvm::StringRef rest(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000540
Pavel Labath218770b2016-10-31 16:22:07 +0000541 // We will not go below root dir.
542 size_t root_dir_start = RootDirStart(path, m_syntax);
543 const bool absolute = root_dir_start != llvm::StringRef::npos;
544 if (absolute) {
545 result += rest.take_front(root_dir_start + 1);
546 rest = rest.drop_front(root_dir_start + 1);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000547 } else {
Pavel Labath218770b2016-10-31 16:22:07 +0000548 if (m_syntax == ePathSyntaxWindows && path.size() > 2 && path[1] == ':') {
549 result += rest.take_front(2);
550 rest = rest.drop_front(2);
551 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000552 }
553
Pavel Labath218770b2016-10-31 16:22:07 +0000554 bool anything_added = false;
555 llvm::SmallVector<llvm::StringRef, 0> components, processed;
556 rest.split(components, '/', -1, false);
557 processed.reserve(components.size());
558 for (auto component : components) {
559 if (component == ".")
560 continue; // Skip these.
561 if (component != "..") {
562 processed.push_back(component);
563 continue; // Regular file name.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000564 }
Pavel Labath218770b2016-10-31 16:22:07 +0000565 if (!processed.empty()) {
566 processed.pop_back();
567 continue; // Dots. Go one level up if we can.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000568 }
Pavel Labath218770b2016-10-31 16:22:07 +0000569 if (absolute)
570 continue; // We're at the top level. Cannot go higher than that. Skip.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000571
Pavel Labath218770b2016-10-31 16:22:07 +0000572 result += component; // We're a relative path. We need to keep these.
573 result += '/';
574 anything_added = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000575 }
Pavel Labath218770b2016-10-31 16:22:07 +0000576 for (auto component : processed) {
577 result += component;
578 result += '/';
579 anything_added = true;
580 }
581 if (anything_added)
582 result.pop_back(); // Pop last '/'.
583 else if (result.empty())
584 result = ".";
Kate Stoneb9c1b512016-09-06 20:57:50 +0000585
Pavel Labath218770b2016-10-31 16:22:07 +0000586 return FileSpec(result, false, m_syntax);
Jim Ingham96a15962014-11-15 01:54:26 +0000587}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000588
589//------------------------------------------------------------------
590// Dump the object to the supplied stream. If the object contains
591// a valid directory name, it will be displayed followed by a
592// directory delimiter, and the filename.
593//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000594void FileSpec::Dump(Stream *s) const {
595 if (s) {
596 std::string path{GetPath(true)};
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000597 s->PutCString(path);
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000598 char path_separator = GetPreferredPathSeparator(m_syntax);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000599 if (!m_filename && !path.empty() && path.back() != path_separator)
600 s->PutChar(path_separator);
601 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000602}
603
604//------------------------------------------------------------------
605// Returns true if the file exists.
606//------------------------------------------------------------------
Zachary Turner7d86ee52017-03-08 17:56:08 +0000607bool FileSpec::Exists() const { return llvm::sys::fs::exists(GetPath()); }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000608
Kate Stoneb9c1b512016-09-06 20:57:50 +0000609bool FileSpec::Readable() const {
Zachary Turner7d86ee52017-03-08 17:56:08 +0000610 return GetPermissions() & llvm::sys::fs::perms::all_read;
Greg Clayton5acc1252014-08-15 18:00:45 +0000611}
612
Kate Stoneb9c1b512016-09-06 20:57:50 +0000613bool FileSpec::ResolveExecutableLocation() {
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000614 // CLEANUP: Use StringRef for string handling.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000615 if (!m_directory) {
616 const char *file_cstr = m_filename.GetCString();
617 if (file_cstr) {
618 const std::string file_str(file_cstr);
619 llvm::ErrorOr<std::string> error_or_path =
620 llvm::sys::findProgramByName(file_str);
621 if (!error_or_path)
Jim Ingham0909e5f2010-09-16 00:57:33 +0000622 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000623 std::string path = error_or_path.get();
624 llvm::StringRef dir_ref = llvm::sys::path::parent_path(path);
625 if (!dir_ref.empty()) {
626 // FindProgramByName returns "." if it can't find the file.
627 if (strcmp(".", dir_ref.data()) == 0)
628 return false;
629
630 m_directory.SetCString(dir_ref.data());
631 if (Exists())
632 return true;
633 else {
634 // If FindProgramByName found the file, it returns the directory +
635 // filename in its return results.
636 // We need to separate them.
637 FileSpec tmp_file(dir_ref.data(), false);
638 if (tmp_file.Exists()) {
639 m_directory = tmp_file.m_directory;
640 return true;
641 }
642 }
643 }
644 }
645 }
646
647 return false;
Jim Ingham0909e5f2010-09-16 00:57:33 +0000648}
649
Kate Stoneb9c1b512016-09-06 20:57:50 +0000650bool FileSpec::ResolvePath() {
651 if (m_is_resolved)
652 return true; // We have already resolved this path
653
Kate Stoneb9c1b512016-09-06 20:57:50 +0000654 // SetFile(...) will set m_is_resolved correctly if it can resolve the path
Pavel Labath9bd69ad2017-03-13 09:46:15 +0000655 SetFile(GetPath(false), true);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000656 return m_is_resolved;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000657}
658
Kate Stoneb9c1b512016-09-06 20:57:50 +0000659uint64_t FileSpec::GetByteSize() const {
Zachary Turner7d86ee52017-03-08 17:56:08 +0000660 uint64_t Size = 0;
661 if (llvm::sys::fs::file_size(GetPath(), Size))
662 return 0;
663 return Size;
Zachary Turnerdf62f202014-08-07 17:33:07 +0000664}
665
Kate Stoneb9c1b512016-09-06 20:57:50 +0000666FileSpec::PathSyntax FileSpec::GetPathSyntax() const { return m_syntax; }
667
Pavel Labath30e6cbf2017-03-07 13:19:15 +0000668uint32_t FileSpec::GetPermissions() const {
Zachary Turner7d86ee52017-03-08 17:56:08 +0000669 namespace fs = llvm::sys::fs;
670 fs::file_status st;
671 if (fs::status(GetPath(), st, false))
672 return fs::perms::perms_not_known;
673
674 return st.permissions();
Greg Claytonfbb76342013-11-20 21:07:01 +0000675}
676
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000677//------------------------------------------------------------------
678// Directory string get accessor.
679//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000680ConstString &FileSpec::GetDirectory() { return m_directory; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000681
682//------------------------------------------------------------------
683// Directory string const get accessor.
684//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000685const ConstString &FileSpec::GetDirectory() const { return m_directory; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000686
687//------------------------------------------------------------------
688// Filename string get accessor.
689//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000690ConstString &FileSpec::GetFilename() { return m_filename; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000691
692//------------------------------------------------------------------
693// Filename string const get accessor.
694//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000695const ConstString &FileSpec::GetFilename() const { return m_filename; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000696
697//------------------------------------------------------------------
698// Extract the directory and path into a fixed buffer. This is
699// needed as the directory and path are stored in separate string
700// values.
701//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000702size_t FileSpec::GetPath(char *path, size_t path_max_len,
703 bool denormalize) const {
704 if (!path)
705 return 0;
Zachary Turnerb6d99242014-08-08 23:54:35 +0000706
Kate Stoneb9c1b512016-09-06 20:57:50 +0000707 std::string result = GetPath(denormalize);
708 ::snprintf(path, path_max_len, "%s", result.c_str());
709 return std::min(path_max_len - 1, result.length());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000710}
711
Kate Stoneb9c1b512016-09-06 20:57:50 +0000712std::string FileSpec::GetPath(bool denormalize) const {
713 llvm::SmallString<64> result;
714 GetPath(result, denormalize);
715 return std::string(result.begin(), result.end());
Jason Molendaa7ae4672013-04-29 09:46:43 +0000716}
717
Kate Stoneb9c1b512016-09-06 20:57:50 +0000718const char *FileSpec::GetCString(bool denormalize) const {
719 return ConstString{GetPath(denormalize)}.AsCString(NULL);
Chaoren Lind3173f32015-05-29 19:52:29 +0000720}
721
Kate Stoneb9c1b512016-09-06 20:57:50 +0000722void FileSpec::GetPath(llvm::SmallVectorImpl<char> &path,
723 bool denormalize) const {
724 path.append(m_directory.GetStringRef().begin(),
725 m_directory.GetStringRef().end());
726 if (m_directory && m_filename &&
727 !IsPathSeparator(m_directory.GetStringRef().back(), m_syntax))
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000728 path.insert(path.end(), GetPreferredPathSeparator(m_syntax));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000729 path.append(m_filename.GetStringRef().begin(),
730 m_filename.GetStringRef().end());
731 Normalize(path, m_syntax);
732 if (denormalize && !path.empty())
733 Denormalize(path, m_syntax);
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000734}
735
Kate Stoneb9c1b512016-09-06 20:57:50 +0000736ConstString FileSpec::GetFileNameExtension() const {
737 if (m_filename) {
Enrico Granataa9dbf432011-10-17 21:45:27 +0000738 const char *filename = m_filename.GetCString();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000739 const char *dot_pos = strrchr(filename, '.');
740 if (dot_pos && dot_pos[1] != '\0')
741 return ConstString(dot_pos + 1);
742 }
743 return ConstString();
744}
745
746ConstString FileSpec::GetFileNameStrippingExtension() const {
747 const char *filename = m_filename.GetCString();
748 if (filename == NULL)
749 return ConstString();
750
751 const char *dot_pos = strrchr(filename, '.');
752 if (dot_pos == NULL)
753 return m_filename;
754
755 return ConstString(filename, dot_pos - filename);
Enrico Granataa9dbf432011-10-17 21:45:27 +0000756}
757
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000758//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000759// Return the size in bytes that this object takes in memory. This
760// returns the size in bytes of this object, not any shared string
761// values it may refer to.
762//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000763size_t FileSpec::MemorySize() const {
764 return m_filename.MemorySize() + m_directory.MemorySize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000765}
766
Zachary Turner1f875342017-03-13 02:44:39 +0000767void FileSpec::EnumerateDirectory(llvm::StringRef dir_path,
768 bool find_directories, bool find_files,
769 bool find_other,
770 EnumerateDirectoryCallbackType callback,
771 void *callback_baton) {
772 namespace fs = llvm::sys::fs;
773 std::error_code EC;
774 fs::recursive_directory_iterator Iter(dir_path, EC);
775 fs::recursive_directory_iterator End;
776 for (; Iter != End && !EC; Iter.increment(EC)) {
777 const auto &Item = *Iter;
778 fs::file_status Status;
Pavel Labath9bd69ad2017-03-13 09:46:15 +0000779 if ((EC = Item.status(Status)))
Zachary Turner1f875342017-03-13 02:44:39 +0000780 break;
781 if (!find_files && fs::is_regular_file(Status))
782 continue;
783 if (!find_directories && fs::is_directory(Status))
784 continue;
785 if (!find_other && fs::is_other(Status))
786 continue;
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000787
Zachary Turner1f875342017-03-13 02:44:39 +0000788 FileSpec Spec(Item.path(), false);
789 auto Result = callback(callback_baton, Status.type(), Spec);
790 if (Result == eEnumerateDirectoryResultQuit)
791 return;
792 if (Result == eEnumerateDirectoryResultNext) {
793 // Default behavior is to recurse. Opt out if the callback doesn't want
794 // this behavior.
795 Iter.no_push();
Greg Clayton58c65f02015-06-29 18:29:00 +0000796 }
Zachary Turner1f875342017-03-13 02:44:39 +0000797 }
Daniel Maleae0f8f572013-08-26 23:57:52 +0000798}
799
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000800FileSpec
801FileSpec::CopyByAppendingPathComponent(llvm::StringRef component) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000802 FileSpec ret = *this;
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000803 ret.AppendPathComponent(component);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000804 return ret;
Chaoren Lin0c5a9c12015-06-05 00:28:06 +0000805}
806
Kate Stoneb9c1b512016-09-06 20:57:50 +0000807FileSpec FileSpec::CopyByRemovingLastPathComponent() const {
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000808 // CLEANUP: Use StringRef for string handling.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000809 const bool resolve = false;
810 if (m_filename.IsEmpty() && m_directory.IsEmpty())
811 return FileSpec("", resolve);
812 if (m_directory.IsEmpty())
813 return FileSpec("", resolve);
814 if (m_filename.IsEmpty()) {
815 const char *dir_cstr = m_directory.GetCString();
816 const char *last_slash_ptr = ::strrchr(dir_cstr, '/');
817
818 // check for obvious cases before doing the full thing
819 if (!last_slash_ptr)
820 return FileSpec("", resolve);
821 if (last_slash_ptr == dir_cstr)
822 return FileSpec("/", resolve);
823
824 size_t last_slash_pos = last_slash_ptr - dir_cstr + 1;
825 ConstString new_path(dir_cstr, last_slash_pos);
826 return FileSpec(new_path.GetCString(), resolve);
827 } else
828 return FileSpec(m_directory.GetCString(), resolve);
Chaoren Lin0c5a9c12015-06-05 00:28:06 +0000829}
830
Kate Stoneb9c1b512016-09-06 20:57:50 +0000831ConstString FileSpec::GetLastPathComponent() const {
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000832 // CLEANUP: Use StringRef for string handling.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000833 if (m_filename)
834 return m_filename;
835 if (m_directory) {
836 const char *dir_cstr = m_directory.GetCString();
837 const char *last_slash_ptr = ::strrchr(dir_cstr, '/');
838 if (last_slash_ptr == NULL)
839 return m_directory;
840 if (last_slash_ptr == dir_cstr) {
841 if (last_slash_ptr[1] == 0)
842 return ConstString(last_slash_ptr);
843 else
844 return ConstString(last_slash_ptr + 1);
845 }
846 if (last_slash_ptr[1] != 0)
847 return ConstString(last_slash_ptr + 1);
848 const char *penultimate_slash_ptr = last_slash_ptr;
849 while (*penultimate_slash_ptr) {
850 --penultimate_slash_ptr;
851 if (penultimate_slash_ptr == dir_cstr)
852 break;
853 if (*penultimate_slash_ptr == '/')
854 break;
855 }
856 ConstString result(penultimate_slash_ptr + 1,
857 last_slash_ptr - penultimate_slash_ptr);
858 return result;
859 }
860 return ConstString();
Chaoren Lin0c5a9c12015-06-05 00:28:06 +0000861}
862
Pavel Labath59d725c2017-01-16 10:07:02 +0000863static std::string
864join_path_components(FileSpec::PathSyntax syntax,
865 const std::vector<llvm::StringRef> components) {
866 std::string result;
867 for (size_t i = 0; i < components.size(); ++i) {
868 if (components[i].empty())
869 continue;
870 result += components[i];
871 if (i != components.size() - 1 &&
872 !IsPathSeparator(components[i].back(), syntax))
873 result += GetPreferredPathSeparator(syntax);
874 }
875
876 return result;
877}
878
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000879void FileSpec::PrependPathComponent(llvm::StringRef component) {
880 if (component.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000881 return;
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000882
Kate Stoneb9c1b512016-09-06 20:57:50 +0000883 const bool resolve = false;
884 if (m_filename.IsEmpty() && m_directory.IsEmpty()) {
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000885 SetFile(component, resolve);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000886 return;
887 }
Daniel Maleae0f8f572013-08-26 23:57:52 +0000888
Pavel Labath59d725c2017-01-16 10:07:02 +0000889 std::string result =
890 join_path_components(m_syntax, {component, m_directory.GetStringRef(),
891 m_filename.GetStringRef()});
Pavel Labath238169d2017-01-16 12:15:42 +0000892 SetFile(result, resolve, m_syntax);
Chaoren Lind3173f32015-05-29 19:52:29 +0000893}
894
Kate Stoneb9c1b512016-09-06 20:57:50 +0000895void FileSpec::PrependPathComponent(const FileSpec &new_path) {
896 return PrependPathComponent(new_path.GetPath(false));
Chaoren Lin0c5a9c12015-06-05 00:28:06 +0000897}
898
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000899void FileSpec::AppendPathComponent(llvm::StringRef component) {
900 if (component.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000901 return;
902
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000903 component = component.drop_while(
904 [this](char c) { return IsPathSeparator(c, m_syntax); });
Kate Stoneb9c1b512016-09-06 20:57:50 +0000905
Pavel Labath59d725c2017-01-16 10:07:02 +0000906 std::string result =
907 join_path_components(m_syntax, {m_directory.GetStringRef(),
908 m_filename.GetStringRef(), component});
Kate Stoneb9c1b512016-09-06 20:57:50 +0000909
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000910 SetFile(result, false, m_syntax);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000911}
912
913void FileSpec::AppendPathComponent(const FileSpec &new_path) {
914 return AppendPathComponent(new_path.GetPath(false));
915}
916
917void FileSpec::RemoveLastPathComponent() {
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000918 // CLEANUP: Use StringRef for string handling.
919
Kate Stoneb9c1b512016-09-06 20:57:50 +0000920 const bool resolve = false;
921 if (m_filename.IsEmpty() && m_directory.IsEmpty()) {
922 SetFile("", resolve);
923 return;
924 }
925 if (m_directory.IsEmpty()) {
926 SetFile("", resolve);
927 return;
928 }
929 if (m_filename.IsEmpty()) {
930 const char *dir_cstr = m_directory.GetCString();
931 const char *last_slash_ptr = ::strrchr(dir_cstr, '/');
932
933 // check for obvious cases before doing the full thing
934 if (!last_slash_ptr) {
935 SetFile("", resolve);
936 return;
Daniel Maleae0f8f572013-08-26 23:57:52 +0000937 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000938 if (last_slash_ptr == dir_cstr) {
939 SetFile("/", resolve);
940 return;
Daniel Maleae0f8f572013-08-26 23:57:52 +0000941 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000942 size_t last_slash_pos = last_slash_ptr - dir_cstr + 1;
943 ConstString new_path(dir_cstr, last_slash_pos);
944 SetFile(new_path.GetCString(), resolve);
945 } else
946 SetFile(m_directory.GetCString(), resolve);
Daniel Maleae0f8f572013-08-26 23:57:52 +0000947}
Greg Clayton1f746072012-08-29 21:13:06 +0000948//------------------------------------------------------------------
949/// Returns true if the filespec represents an implementation source
950/// file (files with a ".c", ".cpp", ".m", ".mm" (many more)
951/// extension).
952///
953/// @return
954/// \b true if the filespec represents an implementation source
955/// file, \b false otherwise.
956//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000957bool FileSpec::IsSourceImplementationFile() const {
958 ConstString extension(GetFileNameExtension());
Zachary Turner95eae422016-09-21 16:01:28 +0000959 if (!extension)
960 return false;
961
962 static RegularExpression g_source_file_regex(llvm::StringRef(
963 "^([cC]|[mM]|[mM][mM]|[cC][pP][pP]|[cC]\\+\\+|[cC][xX][xX]|[cC][cC]|["
964 "cC][pP]|[sS]|[aA][sS][mM]|[fF]|[fF]77|[fF]90|[fF]95|[fF]03|[fF][oO]["
965 "rR]|[fF][tT][nN]|[fF][pP][pP]|[aA][dD][aA]|[aA][dD][bB]|[aA][dD][sS])"
966 "$"));
967 return g_source_file_regex.Execute(extension.GetStringRef());
Greg Clayton1f746072012-08-29 21:13:06 +0000968}
969
Kate Stoneb9c1b512016-09-06 20:57:50 +0000970bool FileSpec::IsRelative() const {
971 const char *dir = m_directory.GetCString();
972 llvm::StringRef directory(dir ? dir : "");
Zachary Turner270e99a2014-12-08 21:36:42 +0000973
Kate Stoneb9c1b512016-09-06 20:57:50 +0000974 if (directory.size() > 0) {
975 if (PathSyntaxIsPosix(m_syntax)) {
976 // If the path doesn't start with '/' or '~', return true
977 switch (directory[0]) {
978 case '/':
979 case '~':
980 return false;
981 default:
Greg Claytona0ca6602012-10-18 16:33:33 +0000982 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000983 }
984 } else {
985 if (directory.size() >= 2 && directory[1] == ':')
986 return false;
987 if (directory[0] == '/')
988 return false;
989 return true;
Greg Claytona0ca6602012-10-18 16:33:33 +0000990 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000991 } else if (m_filename) {
992 // No directory, just a basename, return true
993 return true;
994 }
995 return false;
Greg Claytona0ca6602012-10-18 16:33:33 +0000996}
Chaoren Lin372e9062015-06-09 17:54:27 +0000997
Kate Stoneb9c1b512016-09-06 20:57:50 +0000998bool FileSpec::IsAbsolute() const { return !FileSpec::IsRelative(); }
Zachary Turner827d5d72016-12-16 04:27:00 +0000999
1000void llvm::format_provider<FileSpec>::format(const FileSpec &F,
1001 raw_ostream &Stream,
1002 StringRef Style) {
1003 assert(
1004 (Style.empty() || Style.equals_lower("F") || Style.equals_lower("D")) &&
1005 "Invalid FileSpec style!");
1006
1007 StringRef dir = F.GetDirectory().GetStringRef();
1008 StringRef file = F.GetFilename().GetStringRef();
1009
1010 if (dir.empty() && file.empty()) {
1011 Stream << "(empty)";
1012 return;
1013 }
1014
1015 if (Style.equals_lower("F")) {
1016 Stream << (file.empty() ? "(empty)" : file);
1017 return;
1018 }
1019
1020 // Style is either D or empty, either way we need to print the directory.
1021 if (!dir.empty()) {
1022 // Directory is stored in normalized form, which might be different
1023 // than preferred form. In order to handle this, we need to cut off
1024 // the filename, then denormalize, then write the entire denorm'ed
1025 // directory.
1026 llvm::SmallString<64> denormalized_dir = dir;
1027 Denormalize(denormalized_dir, F.GetPathSyntax());
1028 Stream << denormalized_dir;
1029 Stream << GetPreferredPathSeparator(F.GetPathSyntax());
1030 }
1031
1032 if (Style.equals_lower("D")) {
1033 // We only want to print the directory, so now just exit.
1034 if (dir.empty())
1035 Stream << "(empty)";
1036 return;
1037 }
1038
1039 if (!file.empty())
1040 Stream << file;
1041}