blob: d958d8c20982b208c66e562a5ad7cf8ea844ccd6 [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
Virgile Bellob2f1fb22013-08-23 12:44:05 +000010#ifndef _WIN32
Greg Clayton4272cc72011-02-02 02:24:04 +000011#include <dirent.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000012#else
13#include "lldb/Host/windows/windows.h"
14#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +000015#include <fcntl.h>
Virgile Bello69571952013-09-20 22:35:22 +000016#ifndef _MSC_VER
Chris Lattner30fdc8d2010-06-08 16:52:24 +000017#include <libgen.h>
Virgile Bello69571952013-09-20 22:35:22 +000018#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +000019#include <fstream>
Rafael Espindola09079162013-06-13 20:10:23 +000020#include <set>
Greg Claytone0f3c022011-02-07 17:41:11 +000021#include <string.h>
Greg Claytonfd184262011-02-05 02:27:52 +000022
Jim Ingham9035e7c2011-02-07 19:42:39 +000023#include "lldb/Host/Config.h" // Have to include this before we test the define...
Greg Clayton45319462011-02-08 00:35:34 +000024#ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
Jim Inghamf818ca32010-07-01 01:48:53 +000025#include <pwd.h>
Greg Claytonfd184262011-02-05 02:27:52 +000026#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +000027
Chaoren Linf34f4102015-05-09 01:21:32 +000028#include "lldb/Core/ArchSpec.h"
Zachary Turnerc00cf4a2014-08-15 22:04:21 +000029#include "lldb/Core/DataBufferHeap.h"
30#include "lldb/Core/DataBufferMemoryMap.h"
31#include "lldb/Core/RegularExpression.h"
Zachary Turnerc00cf4a2014-08-15 22:04:21 +000032#include "lldb/Core/Stream.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000033#include "lldb/Core/StreamString.h"
Zachary Turnerc00cf4a2014-08-15 22:04:21 +000034#include "lldb/Host/File.h"
35#include "lldb/Host/FileSpec.h"
36#include "lldb/Host/FileSystem.h"
37#include "lldb/Host/Host.h"
38#include "lldb/Utility/CleanUp.h"
39
Zachary Turnerfe83ad82016-09-27 20:48:37 +000040#include "llvm/ADT/StringExtras.h"
Caroline Tice391a9602010-09-12 00:10:52 +000041#include "llvm/ADT/StringRef.h"
Zachary Turner190fadc2016-03-22 17:58:09 +000042#include "llvm/Support/ConvertUTF.h"
Zachary Turner3f559742014-08-07 17:33:36 +000043#include "llvm/Support/FileSystem.h"
Greg Clayton38a61402010-12-02 23:20:03 +000044#include "llvm/Support/Path.h"
45#include "llvm/Support/Program.h"
Caroline Tice391a9602010-09-12 00:10:52 +000046
Chris Lattner30fdc8d2010-06-08 16:52:24 +000047using namespace lldb;
48using namespace lldb_private;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000049
Chaoren Lin1c614fe2015-05-28 17:02:45 +000050namespace {
51
Kate Stoneb9c1b512016-09-06 20:57:50 +000052bool PathSyntaxIsPosix(FileSpec::PathSyntax syntax) {
53 return (syntax == FileSpec::ePathSyntaxPosix ||
54 (syntax == FileSpec::ePathSyntaxHostNative &&
55 FileSystem::GetNativePathSyntax() == FileSpec::ePathSyntaxPosix));
Chaoren Lin1c614fe2015-05-28 17:02:45 +000056}
57
Kate Stoneb9c1b512016-09-06 20:57:50 +000058const char *GetPathSeparators(FileSpec::PathSyntax syntax) {
59 return PathSyntaxIsPosix(syntax) ? "/" : "\\/";
Pavel Labath144119b2016-04-04 14:39:12 +000060}
61
Zachary Turnerfe83ad82016-09-27 20:48:37 +000062char GetPreferredPathSeparator(FileSpec::PathSyntax syntax) {
Kate Stoneb9c1b512016-09-06 20:57:50 +000063 return GetPathSeparators(syntax)[0];
Pavel Labath144119b2016-04-04 14:39:12 +000064}
65
Kate Stoneb9c1b512016-09-06 20:57:50 +000066bool IsPathSeparator(char value, FileSpec::PathSyntax syntax) {
67 return value == '/' || (!PathSyntaxIsPosix(syntax) && value == '\\');
Chaoren Lin1c614fe2015-05-28 17:02:45 +000068}
69
Kate Stoneb9c1b512016-09-06 20:57:50 +000070void Normalize(llvm::SmallVectorImpl<char> &path, FileSpec::PathSyntax syntax) {
71 if (PathSyntaxIsPosix(syntax))
72 return;
Chaoren Lin1c614fe2015-05-28 17:02:45 +000073
Kate Stoneb9c1b512016-09-06 20:57:50 +000074 std::replace(path.begin(), path.end(), '\\', '/');
75 // Windows path can have \\ slashes which can be changed by replace
76 // call above to //. Here we remove the duplicate.
77 auto iter = std::unique(path.begin(), path.end(), [](char &c1, char &c2) {
78 return (c1 == '/' && c2 == '/');
79 });
80 path.erase(iter, path.end());
Chaoren Lin1c614fe2015-05-28 17:02:45 +000081}
82
Kate Stoneb9c1b512016-09-06 20:57:50 +000083void Denormalize(llvm::SmallVectorImpl<char> &path,
84 FileSpec::PathSyntax syntax) {
85 if (PathSyntaxIsPosix(syntax))
86 return;
Chaoren Lin1c614fe2015-05-28 17:02:45 +000087
Kate Stoneb9c1b512016-09-06 20:57:50 +000088 std::replace(path.begin(), path.end(), '/', '\\');
Chaoren Lin1c614fe2015-05-28 17:02:45 +000089}
90
Kate Stoneb9c1b512016-09-06 20:57:50 +000091bool GetFileStats(const FileSpec *file_spec, struct stat *stats_ptr) {
92 char resolved_path[PATH_MAX];
93 if (file_spec->GetPath(resolved_path, sizeof(resolved_path)))
94 return FileSystem::Stat(resolved_path, stats_ptr) == 0;
95 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000096}
97
Kate Stoneb9c1b512016-09-06 20:57:50 +000098size_t FilenamePos(llvm::StringRef str, FileSpec::PathSyntax syntax) {
99 if (str.size() == 2 && IsPathSeparator(str[0], syntax) && str[0] == str[1])
100 return 0;
Pavel Labath144119b2016-04-04 14:39:12 +0000101
Kate Stoneb9c1b512016-09-06 20:57:50 +0000102 if (str.size() > 0 && IsPathSeparator(str.back(), syntax))
103 return str.size() - 1;
Pavel Labath144119b2016-04-04 14:39:12 +0000104
Kate Stoneb9c1b512016-09-06 20:57:50 +0000105 size_t pos = str.find_last_of(GetPathSeparators(syntax), str.size() - 1);
Pavel Labath144119b2016-04-04 14:39:12 +0000106
Kate Stoneb9c1b512016-09-06 20:57:50 +0000107 if (!PathSyntaxIsPosix(syntax) && pos == llvm::StringRef::npos)
108 pos = str.find_last_of(':', str.size() - 2);
Pavel Labath144119b2016-04-04 14:39:12 +0000109
Kate Stoneb9c1b512016-09-06 20:57:50 +0000110 if (pos == llvm::StringRef::npos ||
111 (pos == 1 && IsPathSeparator(str[0], syntax)))
112 return 0;
Pavel Labath144119b2016-04-04 14:39:12 +0000113
Kate Stoneb9c1b512016-09-06 20:57:50 +0000114 return pos + 1;
Chaoren Lin1c614fe2015-05-28 17:02:45 +0000115}
116
Kate Stoneb9c1b512016-09-06 20:57:50 +0000117size_t RootDirStart(llvm::StringRef str, FileSpec::PathSyntax syntax) {
118 // case "c:/"
119 if (!PathSyntaxIsPosix(syntax) &&
120 (str.size() > 2 && str[1] == ':' && IsPathSeparator(str[2], syntax)))
121 return 2;
Pavel Labath144119b2016-04-04 14:39:12 +0000122
Kate Stoneb9c1b512016-09-06 20:57:50 +0000123 // case "//"
124 if (str.size() == 2 && IsPathSeparator(str[0], syntax) && str[0] == str[1])
Pavel Labath144119b2016-04-04 14:39:12 +0000125 return llvm::StringRef::npos;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000126
127 // case "//net"
128 if (str.size() > 3 && IsPathSeparator(str[0], syntax) && str[0] == str[1] &&
129 !IsPathSeparator(str[2], syntax))
130 return str.find_first_of(GetPathSeparators(syntax), 2);
131
132 // case "/"
133 if (str.size() > 0 && IsPathSeparator(str[0], syntax))
134 return 0;
135
136 return llvm::StringRef::npos;
Pavel Labath144119b2016-04-04 14:39:12 +0000137}
138
Kate Stoneb9c1b512016-09-06 20:57:50 +0000139size_t ParentPathEnd(llvm::StringRef path, FileSpec::PathSyntax syntax) {
140 size_t end_pos = FilenamePos(path, syntax);
Pavel Labath144119b2016-04-04 14:39:12 +0000141
Kate Stoneb9c1b512016-09-06 20:57:50 +0000142 bool filename_was_sep =
143 path.size() > 0 && IsPathSeparator(path[end_pos], syntax);
Pavel Labath144119b2016-04-04 14:39:12 +0000144
Kate Stoneb9c1b512016-09-06 20:57:50 +0000145 // Skip separators except for root dir.
146 size_t root_dir_pos = RootDirStart(path.substr(0, end_pos), syntax);
Pavel Labath144119b2016-04-04 14:39:12 +0000147
Kate Stoneb9c1b512016-09-06 20:57:50 +0000148 while (end_pos > 0 && (end_pos - 1) != root_dir_pos &&
149 IsPathSeparator(path[end_pos - 1], syntax))
150 --end_pos;
Pavel Labath144119b2016-04-04 14:39:12 +0000151
Kate Stoneb9c1b512016-09-06 20:57:50 +0000152 if (end_pos == 1 && root_dir_pos == 0 && filename_was_sep)
153 return llvm::StringRef::npos;
Pavel Labath144119b2016-04-04 14:39:12 +0000154
Kate Stoneb9c1b512016-09-06 20:57:50 +0000155 return end_pos;
Pavel Labath144119b2016-04-04 14:39:12 +0000156}
157
158} // end anonymous namespace
159
Jim Inghamf818ca32010-07-01 01:48:53 +0000160// Resolves the username part of a path of the form ~user/other/directories, and
Kate Stoneb9c1b512016-09-06 20:57:50 +0000161// writes the result into dst_path. This will also resolve "~" to the current
162// user.
163// If you want to complete "~" to the list of users, pass it to
164// ResolvePartialUsername.
165void FileSpec::ResolveUsername(llvm::SmallVectorImpl<char> &path) {
Zachary Turner3f559742014-08-07 17:33:36 +0000166#if LLDB_CONFIG_TILDE_RESOLVES_TO_USER
Kate Stoneb9c1b512016-09-06 20:57:50 +0000167 if (path.empty() || path[0] != '~')
168 return;
Zachary Turner3f559742014-08-07 17:33:36 +0000169
Kate Stoneb9c1b512016-09-06 20:57:50 +0000170 llvm::StringRef path_str(path.data(), path.size());
171 size_t slash_pos = path_str.find('/', 1);
172 if (slash_pos == 1 || path.size() == 1) {
173 // A path of ~/ resolves to the current user's home dir
174 llvm::SmallString<64> home_dir;
175 // llvm::sys::path::home_directory() only checks if "HOME" is set in the
176 // environment and does nothing else to locate the user home directory
177 if (!llvm::sys::path::home_directory(home_dir)) {
178 struct passwd *pw = getpwuid(getuid());
179 if (pw && pw->pw_dir && pw->pw_dir[0]) {
180 // Update our environemnt so llvm::sys::path::home_directory() works
181 // next time
182 setenv("HOME", pw->pw_dir, 0);
183 home_dir.assign(llvm::StringRef(pw->pw_dir));
184 } else {
185 return;
186 }
Jim Inghamf818ca32010-07-01 01:48:53 +0000187 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000188
189 // Overwrite the ~ with the first character of the homedir, and insert
190 // the rest. This way we only trigger one move, whereas an insert
191 // followed by a delete (or vice versa) would trigger two.
192 path[0] = home_dir[0];
193 path.insert(path.begin() + 1, home_dir.begin() + 1, home_dir.end());
194 return;
195 }
196
197 auto username_begin = path.begin() + 1;
198 auto username_end = (slash_pos == llvm::StringRef::npos)
199 ? path.end()
200 : (path.begin() + slash_pos);
201 size_t replacement_length = std::distance(path.begin(), username_end);
202
203 llvm::SmallString<20> username(username_begin, username_end);
204 struct passwd *user_entry = ::getpwnam(username.c_str());
205 if (user_entry != nullptr) {
206 // Copy over the first n characters of the path, where n is the smaller of
207 // the length
208 // of the home directory and the slash pos.
209 llvm::StringRef homedir(user_entry->pw_dir);
210 size_t initial_copy_length = std::min(homedir.size(), replacement_length);
211 auto src_begin = homedir.begin();
212 auto src_end = src_begin + initial_copy_length;
213 std::copy(src_begin, src_end, path.begin());
214 if (replacement_length > homedir.size()) {
215 // We copied the entire home directory, but the ~username portion of the
216 // path was
217 // longer, so there's characters that need to be removed.
218 path.erase(path.begin() + initial_copy_length, username_end);
219 } else if (replacement_length < homedir.size()) {
220 // We copied all the way up to the slash in the destination, but there's
221 // still more
222 // characters that need to be inserted.
223 path.insert(username_end, src_end, homedir.end());
Jim Inghamf818ca32010-07-01 01:48:53 +0000224 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000225 } else {
226 // Unable to resolve username (user doesn't exist?)
227 path.clear();
228 }
Zachary Turner3f559742014-08-07 17:33:36 +0000229#endif
Jim Inghamf818ca32010-07-01 01:48:53 +0000230}
231
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000232size_t FileSpec::ResolvePartialUsername(llvm::StringRef partial_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000233 StringList &matches) {
Jim Ingham84363072011-02-08 23:24:09 +0000234#ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
Kate Stoneb9c1b512016-09-06 20:57:50 +0000235 size_t extant_entries = matches.GetSize();
236
237 setpwent();
238 struct passwd *user_entry;
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000239 partial_name = partial_name.drop_front();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000240 std::set<std::string> name_list;
241
242 while ((user_entry = getpwent()) != NULL) {
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000243 if (llvm::StringRef(user_entry->pw_name).startswith(partial_name)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000244 std::string tmp_buf("~");
245 tmp_buf.append(user_entry->pw_name);
246 tmp_buf.push_back('/');
247 name_list.insert(tmp_buf);
Jim Ingham84363072011-02-08 23:24:09 +0000248 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000249 }
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000250
251 for (auto &name : name_list) {
252 matches.AppendString(name);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000253 }
254 return matches.GetSize() - extant_entries;
Jim Ingham84363072011-02-08 23:24:09 +0000255#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000256 // Resolving home directories is not supported, just copy the path...
257 return 0;
258#endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
Jim Ingham84363072011-02-08 23:24:09 +0000259}
260
Kate Stoneb9c1b512016-09-06 20:57:50 +0000261void FileSpec::Resolve(llvm::SmallVectorImpl<char> &path) {
262 if (path.empty())
263 return;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000264
Greg Clayton45319462011-02-08 00:35:34 +0000265#ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
Kate Stoneb9c1b512016-09-06 20:57:50 +0000266 if (path[0] == '~')
267 ResolveUsername(path);
Greg Clayton45319462011-02-08 00:35:34 +0000268#endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000269
Kate Stoneb9c1b512016-09-06 20:57:50 +0000270 // Save a copy of the original path that's passed in
271 llvm::SmallString<128> original_path(path.begin(), path.end());
Jason Molenda671a29d2015-02-25 02:35:25 +0000272
Kate Stoneb9c1b512016-09-06 20:57:50 +0000273 llvm::sys::fs::make_absolute(path);
274 if (!llvm::sys::fs::exists(path)) {
275 path.clear();
276 path.append(original_path.begin(), original_path.end());
277 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000278}
279
Sam McCall6f43d9d2016-11-15 10:58:16 +0000280FileSpec::FileSpec() : m_syntax(FileSystem::GetNativePathSyntax()) {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000281
282//------------------------------------------------------------------
283// Default constructor that can take an optional full path to a
284// file on disk.
285//------------------------------------------------------------------
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000286FileSpec::FileSpec(llvm::StringRef path, bool resolve_path, PathSyntax syntax)
Sam McCall6f43d9d2016-11-15 10:58:16 +0000287 : m_syntax(syntax) {
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000288 SetFile(path, resolve_path, syntax);
Jim Ingham0909e5f2010-09-16 00:57:33 +0000289}
290
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000291FileSpec::FileSpec(llvm::StringRef path, bool resolve_path, ArchSpec arch)
292 : FileSpec{path, resolve_path, arch.GetTriple().isOSWindows()
293 ? ePathSyntaxWindows
294 : ePathSyntaxPosix} {}
Chaoren Linf34f4102015-05-09 01:21:32 +0000295
Jim Ingham0909e5f2010-09-16 00:57:33 +0000296//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000297// Copy constructor
298//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000299FileSpec::FileSpec(const FileSpec &rhs)
300 : m_directory(rhs.m_directory), m_filename(rhs.m_filename),
301 m_is_resolved(rhs.m_is_resolved), m_syntax(rhs.m_syntax) {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000302
303//------------------------------------------------------------------
304// Copy constructor
305//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000306FileSpec::FileSpec(const FileSpec *rhs) : m_directory(), m_filename() {
307 if (rhs)
308 *this = *rhs;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000309}
310
311//------------------------------------------------------------------
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +0000312// Virtual destructor in case anyone inherits from this class.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000313//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000314FileSpec::~FileSpec() {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000315
316//------------------------------------------------------------------
317// Assignment operator.
318//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000319const FileSpec &FileSpec::operator=(const FileSpec &rhs) {
320 if (this != &rhs) {
321 m_directory = rhs.m_directory;
322 m_filename = rhs.m_filename;
323 m_is_resolved = rhs.m_is_resolved;
324 m_syntax = rhs.m_syntax;
325 }
326 return *this;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000327}
328
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000329//------------------------------------------------------------------
330// Update the contents of this object with a new path. The path will
331// be split up into a directory and filename and stored as uniqued
332// string values for quick comparison and efficient memory usage.
333//------------------------------------------------------------------
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000334void FileSpec::SetFile(llvm::StringRef pathname, bool resolve,
335 PathSyntax syntax) {
336 // CLEANUP: Use StringRef for string handling. This function is kind of a
337 // mess and the unclear semantics of RootDirStart and ParentPathEnd make
338 // it very difficult to understand this function. There's no reason this
339 // function should be particularly complicated or difficult to understand.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000340 m_filename.Clear();
341 m_directory.Clear();
342 m_is_resolved = false;
343 m_syntax = (syntax == ePathSyntaxHostNative)
344 ? FileSystem::GetNativePathSyntax()
345 : syntax;
Zachary Turnerdf62f202014-08-07 17:33:07 +0000346
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000347 if (pathname.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000348 return;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000349
Kate Stoneb9c1b512016-09-06 20:57:50 +0000350 llvm::SmallString<64> resolved(pathname);
Zachary Turnerdf62f202014-08-07 17:33:07 +0000351
Kate Stoneb9c1b512016-09-06 20:57:50 +0000352 if (resolve) {
353 FileSpec::Resolve(resolved);
354 m_is_resolved = true;
355 }
Zachary Turnerc7a17ed2014-12-01 23:13:32 +0000356
Kate Stoneb9c1b512016-09-06 20:57:50 +0000357 Normalize(resolved, syntax);
Pavel Labatha212c582016-04-14 09:38:06 +0000358
Kate Stoneb9c1b512016-09-06 20:57:50 +0000359 llvm::StringRef resolve_path_ref(resolved.c_str());
360 size_t dir_end = ParentPathEnd(resolve_path_ref, syntax);
361 if (dir_end == 0) {
362 m_filename.SetString(resolve_path_ref);
363 return;
364 }
Pavel Labath144119b2016-04-04 14:39:12 +0000365
Kate Stoneb9c1b512016-09-06 20:57:50 +0000366 m_directory.SetString(resolve_path_ref.substr(0, dir_end));
Pavel Labath144119b2016-04-04 14:39:12 +0000367
Kate Stoneb9c1b512016-09-06 20:57:50 +0000368 size_t filename_begin = dir_end;
369 size_t root_dir_start = RootDirStart(resolve_path_ref, syntax);
370 while (filename_begin != llvm::StringRef::npos &&
371 filename_begin < resolve_path_ref.size() &&
372 filename_begin != root_dir_start &&
373 IsPathSeparator(resolve_path_ref[filename_begin], syntax))
374 ++filename_begin;
375 m_filename.SetString((filename_begin == llvm::StringRef::npos ||
376 filename_begin >= resolve_path_ref.size())
377 ? "."
378 : resolve_path_ref.substr(filename_begin));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000379}
380
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000381void FileSpec::SetFile(llvm::StringRef path, bool resolve, ArchSpec arch) {
382 return SetFile(path, resolve, arch.GetTriple().isOSWindows()
383 ? ePathSyntaxWindows
384 : ePathSyntaxPosix);
Chaoren Lin44145d72015-05-29 19:52:37 +0000385}
386
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000387//----------------------------------------------------------------------
388// Convert to pointer operator. This allows code to check any FileSpec
389// objects to see if they contain anything valid using code such as:
390//
391// if (file_spec)
392// {}
393//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000394FileSpec::operator bool() const { return m_filename || m_directory; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000395
396//----------------------------------------------------------------------
397// Logical NOT operator. This allows code to check any FileSpec
398// objects to see if they are invalid using code such as:
399//
400// if (!file_spec)
401// {}
402//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000403bool FileSpec::operator!() const { return !m_directory && !m_filename; }
404
405bool FileSpec::DirectoryEquals(const FileSpec &rhs) const {
406 const bool case_sensitive = IsCaseSensitive() || rhs.IsCaseSensitive();
407 return ConstString::Equals(m_directory, rhs.m_directory, case_sensitive);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000408}
409
Kate Stoneb9c1b512016-09-06 20:57:50 +0000410bool FileSpec::FileEquals(const FileSpec &rhs) const {
411 const bool case_sensitive = IsCaseSensitive() || rhs.IsCaseSensitive();
412 return ConstString::Equals(m_filename, rhs.m_filename, case_sensitive);
Zachary Turner74e08ca2016-03-02 22:05:52 +0000413}
414
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000415//------------------------------------------------------------------
416// Equal to operator
417//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000418bool FileSpec::operator==(const FileSpec &rhs) const {
419 if (!FileEquals(rhs))
420 return false;
421 if (DirectoryEquals(rhs))
422 return true;
Zachary Turner47c03462016-02-24 21:26:47 +0000423
Kate Stoneb9c1b512016-09-06 20:57:50 +0000424 // TODO: determine if we want to keep this code in here.
425 // The code below was added to handle a case where we were
426 // trying to set a file and line breakpoint and one path
427 // was resolved, and the other not and the directory was
428 // in a mount point that resolved to a more complete path:
429 // "/tmp/a.c" == "/private/tmp/a.c". I might end up pulling
430 // this out...
431 if (IsResolved() && rhs.IsResolved()) {
432 // Both paths are resolved, no need to look further...
433 return false;
434 }
Zachary Turner47c03462016-02-24 21:26:47 +0000435
Kate Stoneb9c1b512016-09-06 20:57:50 +0000436 FileSpec resolved_lhs(*this);
Zachary Turner47c03462016-02-24 21:26:47 +0000437
Kate Stoneb9c1b512016-09-06 20:57:50 +0000438 // If "this" isn't resolved, resolve it
439 if (!IsResolved()) {
440 if (resolved_lhs.ResolvePath()) {
441 // This path wasn't resolved but now it is. Check if the resolved
442 // directory is the same as our unresolved directory, and if so,
443 // we can mark this object as resolved to avoid more future resolves
444 m_is_resolved = (m_directory == resolved_lhs.m_directory);
445 } else
446 return false;
447 }
Zachary Turner47c03462016-02-24 21:26:47 +0000448
Kate Stoneb9c1b512016-09-06 20:57:50 +0000449 FileSpec resolved_rhs(rhs);
450 if (!rhs.IsResolved()) {
451 if (resolved_rhs.ResolvePath()) {
452 // rhs's path wasn't resolved but now it is. Check if the resolved
453 // directory is the same as rhs's unresolved directory, and if so,
454 // we can mark this object as resolved to avoid more future resolves
455 rhs.m_is_resolved = (rhs.m_directory == resolved_rhs.m_directory);
456 } else
457 return false;
458 }
Zachary Turner47c03462016-02-24 21:26:47 +0000459
Kate Stoneb9c1b512016-09-06 20:57:50 +0000460 // If we reach this point in the code we were able to resolve both paths
461 // and since we only resolve the paths if the basenames are equal, then
462 // we can just check if both directories are equal...
463 return DirectoryEquals(rhs);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000464}
465
466//------------------------------------------------------------------
467// Not equal to operator
468//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000469bool FileSpec::operator!=(const FileSpec &rhs) const { return !(*this == rhs); }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000470
471//------------------------------------------------------------------
472// Less than operator
473//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000474bool FileSpec::operator<(const FileSpec &rhs) const {
475 return FileSpec::Compare(*this, rhs, true) < 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000476}
477
478//------------------------------------------------------------------
479// Dump a FileSpec object to a stream
480//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000481Stream &lldb_private::operator<<(Stream &s, const FileSpec &f) {
482 f.Dump(&s);
483 return s;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000484}
485
486//------------------------------------------------------------------
487// Clear this object by releasing both the directory and filename
488// string values and making them both the empty string.
489//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000490void FileSpec::Clear() {
491 m_directory.Clear();
492 m_filename.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000493}
494
495//------------------------------------------------------------------
496// Compare two FileSpec objects. If "full" is true, then both
497// the directory and the filename must match. If "full" is false,
498// then the directory names for "a" and "b" are only compared if
499// they are both non-empty. This allows a FileSpec object to only
500// contain a filename and it can match FileSpec objects that have
501// matching filenames with different paths.
502//
503// Return -1 if the "a" is less than "b", 0 if "a" is equal to "b"
504// and "1" if "a" is greater than "b".
505//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000506int FileSpec::Compare(const FileSpec &a, const FileSpec &b, bool full) {
507 int result = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000508
Kate Stoneb9c1b512016-09-06 20:57:50 +0000509 // case sensitivity of compare
510 const bool case_sensitive = a.IsCaseSensitive() || b.IsCaseSensitive();
Zachary Turner47c03462016-02-24 21:26:47 +0000511
Kate Stoneb9c1b512016-09-06 20:57:50 +0000512 // If full is true, then we must compare both the directory and filename.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000513
Kate Stoneb9c1b512016-09-06 20:57:50 +0000514 // If full is false, then if either directory is empty, then we match on
515 // the basename only, and if both directories have valid values, we still
516 // do a full compare. This allows for matching when we just have a filename
517 // in one of the FileSpec objects.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000518
Kate Stoneb9c1b512016-09-06 20:57:50 +0000519 if (full || (a.m_directory && b.m_directory)) {
520 result = ConstString::Compare(a.m_directory, b.m_directory, case_sensitive);
521 if (result)
522 return result;
523 }
524 return ConstString::Compare(a.m_filename, b.m_filename, case_sensitive);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000525}
526
Kate Stoneb9c1b512016-09-06 20:57:50 +0000527bool FileSpec::Equal(const FileSpec &a, const FileSpec &b, bool full,
528 bool remove_backups) {
529 // case sensitivity of equality test
530 const bool case_sensitive = a.IsCaseSensitive() || b.IsCaseSensitive();
Zachary Turner47c03462016-02-24 21:26:47 +0000531
Kate Stoneb9c1b512016-09-06 20:57:50 +0000532 if (!full && (a.GetDirectory().IsEmpty() || b.GetDirectory().IsEmpty()))
533 return ConstString::Equals(a.m_filename, b.m_filename, case_sensitive);
Pavel Labath218770b2016-10-31 16:22:07 +0000534
535 if (remove_backups == false)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000536 return a == b;
Jim Ingham96a15962014-11-15 01:54:26 +0000537
Pavel Labath218770b2016-10-31 16:22:07 +0000538 if (a == b)
539 return true;
540
541 return Equal(a.GetNormalizedPath(), b.GetNormalizedPath(), full, false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000542}
543
Pavel Labath218770b2016-10-31 16:22:07 +0000544FileSpec FileSpec::GetNormalizedPath() const {
545 // Fast path. Do nothing if the path is not interesting.
546 if (!m_directory.GetStringRef().contains(".") &&
547 (m_filename.GetStringRef() != ".." && m_filename.GetStringRef() != "."))
548 return *this;
Greg Clayton5a271952015-06-02 22:43:29 +0000549
Pavel Labath218770b2016-10-31 16:22:07 +0000550 llvm::SmallString<64> path, result;
551 const bool normalize = false;
552 GetPath(path, normalize);
553 llvm::StringRef rest(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000554
Pavel Labath218770b2016-10-31 16:22:07 +0000555 // We will not go below root dir.
556 size_t root_dir_start = RootDirStart(path, m_syntax);
557 const bool absolute = root_dir_start != llvm::StringRef::npos;
558 if (absolute) {
559 result += rest.take_front(root_dir_start + 1);
560 rest = rest.drop_front(root_dir_start + 1);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000561 } else {
Pavel Labath218770b2016-10-31 16:22:07 +0000562 if (m_syntax == ePathSyntaxWindows && path.size() > 2 && path[1] == ':') {
563 result += rest.take_front(2);
564 rest = rest.drop_front(2);
565 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000566 }
567
Pavel Labath218770b2016-10-31 16:22:07 +0000568 bool anything_added = false;
569 llvm::SmallVector<llvm::StringRef, 0> components, processed;
570 rest.split(components, '/', -1, false);
571 processed.reserve(components.size());
572 for (auto component : components) {
573 if (component == ".")
574 continue; // Skip these.
575 if (component != "..") {
576 processed.push_back(component);
577 continue; // Regular file name.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000578 }
Pavel Labath218770b2016-10-31 16:22:07 +0000579 if (!processed.empty()) {
580 processed.pop_back();
581 continue; // Dots. Go one level up if we can.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000582 }
Pavel Labath218770b2016-10-31 16:22:07 +0000583 if (absolute)
584 continue; // We're at the top level. Cannot go higher than that. Skip.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000585
Pavel Labath218770b2016-10-31 16:22:07 +0000586 result += component; // We're a relative path. We need to keep these.
587 result += '/';
588 anything_added = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000589 }
Pavel Labath218770b2016-10-31 16:22:07 +0000590 for (auto component : processed) {
591 result += component;
592 result += '/';
593 anything_added = true;
594 }
595 if (anything_added)
596 result.pop_back(); // Pop last '/'.
597 else if (result.empty())
598 result = ".";
Kate Stoneb9c1b512016-09-06 20:57:50 +0000599
Pavel Labath218770b2016-10-31 16:22:07 +0000600 return FileSpec(result, false, m_syntax);
Jim Ingham96a15962014-11-15 01:54:26 +0000601}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000602
603//------------------------------------------------------------------
604// Dump the object to the supplied stream. If the object contains
605// a valid directory name, it will be displayed followed by a
606// directory delimiter, and the filename.
607//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000608void FileSpec::Dump(Stream *s) const {
609 if (s) {
610 std::string path{GetPath(true)};
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000611 s->PutCString(path);
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000612 char path_separator = GetPreferredPathSeparator(m_syntax);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000613 if (!m_filename && !path.empty() && path.back() != path_separator)
614 s->PutChar(path_separator);
615 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000616}
617
618//------------------------------------------------------------------
619// Returns true if the file exists.
620//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000621bool FileSpec::Exists() const {
622 struct stat file_stats;
623 return GetFileStats(this, &file_stats);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000624}
625
Kate Stoneb9c1b512016-09-06 20:57:50 +0000626bool FileSpec::Readable() const {
627 const uint32_t permissions = GetPermissions();
628 if (permissions & eFilePermissionsEveryoneR)
629 return true;
630 return false;
Greg Clayton5acc1252014-08-15 18:00:45 +0000631}
632
Kate Stoneb9c1b512016-09-06 20:57:50 +0000633bool FileSpec::ResolveExecutableLocation() {
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000634 // CLEANUP: Use StringRef for string handling.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000635 if (!m_directory) {
636 const char *file_cstr = m_filename.GetCString();
637 if (file_cstr) {
638 const std::string file_str(file_cstr);
639 llvm::ErrorOr<std::string> error_or_path =
640 llvm::sys::findProgramByName(file_str);
641 if (!error_or_path)
Jim Ingham0909e5f2010-09-16 00:57:33 +0000642 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000643 std::string path = error_or_path.get();
644 llvm::StringRef dir_ref = llvm::sys::path::parent_path(path);
645 if (!dir_ref.empty()) {
646 // FindProgramByName returns "." if it can't find the file.
647 if (strcmp(".", dir_ref.data()) == 0)
648 return false;
649
650 m_directory.SetCString(dir_ref.data());
651 if (Exists())
652 return true;
653 else {
654 // If FindProgramByName found the file, it returns the directory +
655 // filename in its return results.
656 // We need to separate them.
657 FileSpec tmp_file(dir_ref.data(), false);
658 if (tmp_file.Exists()) {
659 m_directory = tmp_file.m_directory;
660 return true;
661 }
662 }
663 }
664 }
665 }
666
667 return false;
Jim Ingham0909e5f2010-09-16 00:57:33 +0000668}
669
Kate Stoneb9c1b512016-09-06 20:57:50 +0000670bool FileSpec::ResolvePath() {
671 if (m_is_resolved)
672 return true; // We have already resolved this path
673
674 char path_buf[PATH_MAX];
675 if (!GetPath(path_buf, PATH_MAX, false))
676 return false;
677 // SetFile(...) will set m_is_resolved correctly if it can resolve the path
678 SetFile(path_buf, true);
679 return m_is_resolved;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000680}
681
Kate Stoneb9c1b512016-09-06 20:57:50 +0000682uint64_t FileSpec::GetByteSize() const {
683 struct stat file_stats;
684 if (GetFileStats(this, &file_stats))
685 return file_stats.st_size;
686 return 0;
Zachary Turnerdf62f202014-08-07 17:33:07 +0000687}
688
Kate Stoneb9c1b512016-09-06 20:57:50 +0000689FileSpec::PathSyntax FileSpec::GetPathSyntax() const { return m_syntax; }
690
691FileSpec::FileType FileSpec::GetFileType() const {
692 struct stat file_stats;
693 if (GetFileStats(this, &file_stats)) {
694 mode_t file_type = file_stats.st_mode & S_IFMT;
695 switch (file_type) {
696 case S_IFDIR:
697 return eFileTypeDirectory;
698 case S_IFREG:
699 return eFileTypeRegular;
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000700#ifndef _WIN32
Kate Stoneb9c1b512016-09-06 20:57:50 +0000701 case S_IFIFO:
702 return eFileTypePipe;
703 case S_IFSOCK:
704 return eFileTypeSocket;
705 case S_IFLNK:
706 return eFileTypeSymbolicLink;
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000707#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000708 default:
709 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000710 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000711 return eFileTypeUnknown;
712 }
713 return eFileTypeInvalid;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000714}
715
Kate Stoneb9c1b512016-09-06 20:57:50 +0000716bool FileSpec::IsSymbolicLink() const {
717 char resolved_path[PATH_MAX];
718 if (!GetPath(resolved_path, sizeof(resolved_path)))
719 return false;
Oleksiy Vyalov8a578bf2015-07-21 01:28:22 +0000720
721#ifdef _WIN32
Kate Stoneb9c1b512016-09-06 20:57:50 +0000722 std::wstring wpath;
723 if (!llvm::ConvertUTF8toWide(resolved_path, wpath))
724 return false;
725 auto attrs = ::GetFileAttributesW(wpath.c_str());
726 if (attrs == INVALID_FILE_ATTRIBUTES)
727 return false;
Oleksiy Vyalov8a578bf2015-07-21 01:28:22 +0000728
Kate Stoneb9c1b512016-09-06 20:57:50 +0000729 return (attrs & FILE_ATTRIBUTE_REPARSE_POINT);
Oleksiy Vyalov8a578bf2015-07-21 01:28:22 +0000730#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000731 struct stat file_stats;
732 if (::lstat(resolved_path, &file_stats) != 0)
733 return false;
Oleksiy Vyalov8a578bf2015-07-21 01:28:22 +0000734
Kate Stoneb9c1b512016-09-06 20:57:50 +0000735 return (file_stats.st_mode & S_IFMT) == S_IFLNK;
Oleksiy Vyalov8a578bf2015-07-21 01:28:22 +0000736#endif
737}
738
Kate Stoneb9c1b512016-09-06 20:57:50 +0000739uint32_t FileSpec::GetPermissions() const {
740 uint32_t file_permissions = 0;
741 if (*this)
742 FileSystem::GetFilePermissions(*this, file_permissions);
743 return file_permissions;
Greg Claytonfbb76342013-11-20 21:07:01 +0000744}
745
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000746//------------------------------------------------------------------
747// Directory string get accessor.
748//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000749ConstString &FileSpec::GetDirectory() { return m_directory; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000750
751//------------------------------------------------------------------
752// Directory string const get accessor.
753//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000754const ConstString &FileSpec::GetDirectory() const { return m_directory; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000755
756//------------------------------------------------------------------
757// Filename string get accessor.
758//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000759ConstString &FileSpec::GetFilename() { return m_filename; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000760
761//------------------------------------------------------------------
762// Filename string const get accessor.
763//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000764const ConstString &FileSpec::GetFilename() const { return m_filename; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000765
766//------------------------------------------------------------------
767// Extract the directory and path into a fixed buffer. This is
768// needed as the directory and path are stored in separate string
769// values.
770//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000771size_t FileSpec::GetPath(char *path, size_t path_max_len,
772 bool denormalize) const {
773 if (!path)
774 return 0;
Zachary Turnerb6d99242014-08-08 23:54:35 +0000775
Kate Stoneb9c1b512016-09-06 20:57:50 +0000776 std::string result = GetPath(denormalize);
777 ::snprintf(path, path_max_len, "%s", result.c_str());
778 return std::min(path_max_len - 1, result.length());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000779}
780
Kate Stoneb9c1b512016-09-06 20:57:50 +0000781std::string FileSpec::GetPath(bool denormalize) const {
782 llvm::SmallString<64> result;
783 GetPath(result, denormalize);
784 return std::string(result.begin(), result.end());
Jason Molendaa7ae4672013-04-29 09:46:43 +0000785}
786
Kate Stoneb9c1b512016-09-06 20:57:50 +0000787const char *FileSpec::GetCString(bool denormalize) const {
788 return ConstString{GetPath(denormalize)}.AsCString(NULL);
Chaoren Lind3173f32015-05-29 19:52:29 +0000789}
790
Kate Stoneb9c1b512016-09-06 20:57:50 +0000791void FileSpec::GetPath(llvm::SmallVectorImpl<char> &path,
792 bool denormalize) const {
793 path.append(m_directory.GetStringRef().begin(),
794 m_directory.GetStringRef().end());
795 if (m_directory && m_filename &&
796 !IsPathSeparator(m_directory.GetStringRef().back(), m_syntax))
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000797 path.insert(path.end(), GetPreferredPathSeparator(m_syntax));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000798 path.append(m_filename.GetStringRef().begin(),
799 m_filename.GetStringRef().end());
800 Normalize(path, m_syntax);
801 if (denormalize && !path.empty())
802 Denormalize(path, m_syntax);
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000803}
804
Kate Stoneb9c1b512016-09-06 20:57:50 +0000805ConstString FileSpec::GetFileNameExtension() const {
806 if (m_filename) {
Enrico Granataa9dbf432011-10-17 21:45:27 +0000807 const char *filename = m_filename.GetCString();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000808 const char *dot_pos = strrchr(filename, '.');
809 if (dot_pos && dot_pos[1] != '\0')
810 return ConstString(dot_pos + 1);
811 }
812 return ConstString();
813}
814
815ConstString FileSpec::GetFileNameStrippingExtension() const {
816 const char *filename = m_filename.GetCString();
817 if (filename == NULL)
818 return ConstString();
819
820 const char *dot_pos = strrchr(filename, '.');
821 if (dot_pos == NULL)
822 return m_filename;
823
824 return ConstString(filename, dot_pos - filename);
Enrico Granataa9dbf432011-10-17 21:45:27 +0000825}
826
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000827//------------------------------------------------------------------
828// Returns a shared pointer to a data buffer that contains all or
829// part of the contents of a file. The data is memory mapped and
830// will lazily page in data from the file as memory is accessed.
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +0000831// The data that is mapped will start "file_offset" bytes into the
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000832// file, and "file_size" bytes will be mapped. If "file_size" is
833// greater than the number of bytes available in the file starting
834// at "file_offset", the number of bytes will be appropriately
835// truncated. The final number of bytes that get mapped can be
836// verified using the DataBuffer::GetByteSize() function.
837//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000838DataBufferSP FileSpec::MemoryMapFileContents(off_t file_offset,
839 size_t file_size) const {
840 DataBufferSP data_sp;
841 std::unique_ptr<DataBufferMemoryMap> mmap_data(new DataBufferMemoryMap());
842 if (mmap_data.get()) {
843 const size_t mapped_length =
844 mmap_data->MemoryMapFromFileSpec(this, file_offset, file_size);
845 if (((file_size == SIZE_MAX) && (mapped_length > 0)) ||
846 (mapped_length >= file_size))
847 data_sp.reset(mmap_data.release());
848 }
849 return data_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000850}
851
Kate Stoneb9c1b512016-09-06 20:57:50 +0000852DataBufferSP FileSpec::MemoryMapFileContentsIfLocal(off_t file_offset,
853 size_t file_size) const {
854 if (FileSystem::IsLocal(*this))
855 return MemoryMapFileContents(file_offset, file_size);
856 else
857 return ReadFileContents(file_offset, file_size, NULL);
Greg Clayton736888c2015-02-23 23:47:09 +0000858}
859
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000860//------------------------------------------------------------------
861// Return the size in bytes that this object takes in memory. This
862// returns the size in bytes of this object, not any shared string
863// values it may refer to.
864//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000865size_t FileSpec::MemorySize() const {
866 return m_filename.MemorySize() + m_directory.MemorySize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000867}
868
Kate Stoneb9c1b512016-09-06 20:57:50 +0000869size_t FileSpec::ReadFileContents(off_t file_offset, void *dst, size_t dst_len,
870 Error *error_ptr) const {
871 Error error;
872 size_t bytes_read = 0;
873 char resolved_path[PATH_MAX];
874 if (GetPath(resolved_path, sizeof(resolved_path))) {
875 File file;
876 error = file.Open(resolved_path, File::eOpenOptionRead);
877 if (error.Success()) {
878 off_t file_offset_after_seek = file_offset;
879 bytes_read = dst_len;
880 error = file.Read(dst, bytes_read, file_offset_after_seek);
Greg Claytondda4f7b2010-06-30 23:03:03 +0000881 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000882 } else {
883 error.SetErrorString("invalid file specification");
884 }
885 if (error_ptr)
886 *error_ptr = error;
887 return bytes_read;
Greg Claytondda4f7b2010-06-30 23:03:03 +0000888}
889
890//------------------------------------------------------------------
891// Returns a shared pointer to a data buffer that contains all or
892// part of the contents of a file. The data copies into a heap based
893// buffer that lives in the DataBuffer shared pointer object returned.
894// The data that is cached will start "file_offset" bytes into the
895// file, and "file_size" bytes will be mapped. If "file_size" is
896// greater than the number of bytes available in the file starting
897// at "file_offset", the number of bytes will be appropriately
898// truncated. The final number of bytes that get mapped can be
899// verified using the DataBuffer::GetByteSize() function.
900//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000901DataBufferSP FileSpec::ReadFileContents(off_t file_offset, size_t file_size,
902 Error *error_ptr) const {
903 Error error;
904 DataBufferSP data_sp;
905 char resolved_path[PATH_MAX];
906 if (GetPath(resolved_path, sizeof(resolved_path))) {
907 File file;
908 error = file.Open(resolved_path, File::eOpenOptionRead);
909 if (error.Success()) {
910 const bool null_terminate = false;
911 error = file.Read(file_size, file_offset, null_terminate, data_sp);
Greg Clayton0b0b5122012-08-30 18:15:10 +0000912 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000913 } else {
914 error.SetErrorString("invalid file specification");
915 }
916 if (error_ptr)
917 *error_ptr = error;
918 return data_sp;
Greg Clayton0b0b5122012-08-30 18:15:10 +0000919}
920
Kate Stoneb9c1b512016-09-06 20:57:50 +0000921DataBufferSP FileSpec::ReadFileContentsAsCString(Error *error_ptr) {
922 Error error;
923 DataBufferSP data_sp;
924 char resolved_path[PATH_MAX];
925 if (GetPath(resolved_path, sizeof(resolved_path))) {
926 File file;
927 error = file.Open(resolved_path, File::eOpenOptionRead);
928 if (error.Success()) {
929 off_t offset = 0;
930 size_t length = SIZE_MAX;
931 const bool null_terminate = true;
932 error = file.Read(length, offset, null_terminate, data_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000933 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000934 } else {
935 error.SetErrorString("invalid file specification");
936 }
937 if (error_ptr)
938 *error_ptr = error;
939 return data_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000940}
941
Kate Stoneb9c1b512016-09-06 20:57:50 +0000942size_t FileSpec::ReadFileLines(STLStringArray &lines) {
943 lines.clear();
944 char path[PATH_MAX];
945 if (GetPath(path, sizeof(path))) {
946 std::ifstream file_stream(path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000947
Kate Stoneb9c1b512016-09-06 20:57:50 +0000948 if (file_stream) {
949 std::string line;
950 while (getline(file_stream, line))
951 lines.push_back(line);
Greg Clayton58fc50e2010-10-20 22:52:05 +0000952 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000953 }
954 return lines.size();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000955}
Greg Clayton4272cc72011-02-02 02:24:04 +0000956
957FileSpec::EnumerateDirectoryResult
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000958FileSpec::ForEachItemInDirectory(llvm::StringRef dir_path,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000959 DirectoryCallback const &callback) {
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000960 if (dir_path.empty())
961 return eEnumerateDirectoryResultNext;
962
Zachary Turner190fadc2016-03-22 17:58:09 +0000963#ifdef _WIN32
Kate Stoneb9c1b512016-09-06 20:57:50 +0000964 std::string szDir(dir_path);
965 szDir += "\\*";
Greg Clayton58c65f02015-06-29 18:29:00 +0000966
Kate Stoneb9c1b512016-09-06 20:57:50 +0000967 std::wstring wszDir;
968 if (!llvm::ConvertUTF8toWide(szDir, wszDir)) {
969 return eEnumerateDirectoryResultNext;
Greg Clayton58c65f02015-06-29 18:29:00 +0000970 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000971
972 WIN32_FIND_DATAW ffd;
973 HANDLE hFind = FindFirstFileW(wszDir.c_str(), &ffd);
974
975 if (hFind == INVALID_HANDLE_VALUE) {
976 return eEnumerateDirectoryResultNext;
977 }
978
979 do {
980 FileSpec::FileType file_type = eFileTypeUnknown;
981 if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
982 size_t len = wcslen(ffd.cFileName);
983
984 if (len == 1 && ffd.cFileName[0] == L'.')
985 continue;
986
987 if (len == 2 && ffd.cFileName[0] == L'.' && ffd.cFileName[1] == L'.')
988 continue;
989
990 file_type = eFileTypeDirectory;
991 } else if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DEVICE) {
992 file_type = eFileTypeOther;
993 } else {
994 file_type = eFileTypeRegular;
995 }
996
997 std::string fileName;
998 if (!llvm::convertWideToUTF8(ffd.cFileName, fileName)) {
999 continue;
1000 }
1001
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001002 std::string child_path = llvm::join_items("\\", dir_path, fileName);
1003 // Don't resolve the file type or path
1004 FileSpec child_path_spec(child_path.data(), false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001005
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001006 EnumerateDirectoryResult result = callback(file_type, child_path_spec);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001007
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001008 switch (result) {
1009 case eEnumerateDirectoryResultNext:
1010 // Enumerate next entry in the current directory. We just
1011 // exit this switch and will continue enumerating the
1012 // current directory as we currently are...
1013 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001014
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001015 case eEnumerateDirectoryResultEnter: // Recurse into the current entry
1016 // if it is a directory or symlink,
1017 // or next if not
1018 if (FileSpec::ForEachItemInDirectory(child_path.data(), callback) ==
1019 eEnumerateDirectoryResultQuit) {
1020 // The subdirectory returned Quit, which means to
1021 // stop all directory enumerations at all levels.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001022 return eEnumerateDirectoryResultQuit;
1023 }
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001024 break;
1025
1026 case eEnumerateDirectoryResultExit: // Exit from the current directory
1027 // at the current level.
1028 // Exit from this directory level and tell parent to
1029 // keep enumerating.
1030 return eEnumerateDirectoryResultNext;
1031
1032 case eEnumerateDirectoryResultQuit: // Stop directory enumerations at
1033 // any level
1034 return eEnumerateDirectoryResultQuit;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001035 }
1036 } while (FindNextFileW(hFind, &ffd) != 0);
1037
1038 FindClose(hFind);
1039#else
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001040 std::string dir_string(dir_path);
1041 lldb_utility::CleanUp<DIR *, int> dir_path_dir(opendir(dir_string.c_str()),
1042 NULL, closedir);
1043 if (dir_path_dir.is_valid()) {
1044 char dir_path_last_char = dir_path.back();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001045
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001046 long path_max = fpathconf(dirfd(dir_path_dir.get()), _PC_NAME_MAX);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001047#if defined(__APPLE_) && defined(__DARWIN_MAXPATHLEN)
1048 if (path_max < __DARWIN_MAXPATHLEN)
1049 path_max = __DARWIN_MAXPATHLEN;
1050#endif
1051 struct dirent *buf, *dp;
1052 buf = (struct dirent *)malloc(offsetof(struct dirent, d_name) + path_max +
1053 1);
1054
1055 while (buf && readdir_r(dir_path_dir.get(), buf, &dp) == 0 && dp) {
1056 // Only search directories
1057 if (dp->d_type == DT_DIR || dp->d_type == DT_UNKNOWN) {
1058 size_t len = strlen(dp->d_name);
1059
1060 if (len == 1 && dp->d_name[0] == '.')
1061 continue;
1062
1063 if (len == 2 && dp->d_name[0] == '.' && dp->d_name[1] == '.')
1064 continue;
1065 }
1066
1067 FileSpec::FileType file_type = eFileTypeUnknown;
1068
1069 switch (dp->d_type) {
1070 default:
1071 case DT_UNKNOWN:
1072 file_type = eFileTypeUnknown;
1073 break;
1074 case DT_FIFO:
1075 file_type = eFileTypePipe;
1076 break;
1077 case DT_CHR:
1078 file_type = eFileTypeOther;
1079 break;
1080 case DT_DIR:
1081 file_type = eFileTypeDirectory;
1082 break;
1083 case DT_BLK:
1084 file_type = eFileTypeOther;
1085 break;
1086 case DT_REG:
1087 file_type = eFileTypeRegular;
1088 break;
1089 case DT_LNK:
1090 file_type = eFileTypeSymbolicLink;
1091 break;
1092 case DT_SOCK:
1093 file_type = eFileTypeSocket;
1094 break;
1095#if !defined(__OpenBSD__)
1096 case DT_WHT:
1097 file_type = eFileTypeOther;
1098 break;
1099#endif
1100 }
1101
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001102 std::string child_path;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001103 // Don't make paths with "/foo//bar", that just confuses everybody.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001104 if (dir_path_last_char == '/')
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001105 child_path = llvm::join_items("", dir_path, dp->d_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001106 else
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001107 child_path = llvm::join_items('/', dir_path, dp->d_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001108
Kate Stoneb9c1b512016-09-06 20:57:50 +00001109 // Don't resolve the file type or path
1110 FileSpec child_path_spec(child_path, false);
1111
1112 EnumerateDirectoryResult result =
1113 callback(file_type, child_path_spec);
1114
1115 switch (result) {
1116 case eEnumerateDirectoryResultNext:
1117 // Enumerate next entry in the current directory. We just
1118 // exit this switch and will continue enumerating the
1119 // current directory as we currently are...
1120 break;
1121
1122 case eEnumerateDirectoryResultEnter: // Recurse into the current entry
1123 // if it is a directory or
1124 // symlink, or next if not
1125 if (FileSpec::ForEachItemInDirectory(child_path, callback) ==
1126 eEnumerateDirectoryResultQuit) {
1127 // The subdirectory returned Quit, which means to
1128 // stop all directory enumerations at all levels.
1129 if (buf)
1130 free(buf);
1131 return eEnumerateDirectoryResultQuit;
1132 }
1133 break;
1134
1135 case eEnumerateDirectoryResultExit: // Exit from the current directory
1136 // at the current level.
1137 // Exit from this directory level and tell parent to
1138 // keep enumerating.
1139 if (buf)
1140 free(buf);
1141 return eEnumerateDirectoryResultNext;
1142
1143 case eEnumerateDirectoryResultQuit: // Stop directory enumerations at
1144 // any level
1145 if (buf)
1146 free(buf);
1147 return eEnumerateDirectoryResultQuit;
1148 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001149 }
1150 if (buf) {
1151 free(buf);
1152 }
1153 }
1154#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00001155 // By default when exiting a directory, we tell the parent enumeration
1156 // to continue enumerating.
1157 return eEnumerateDirectoryResultNext;
Greg Clayton58c65f02015-06-29 18:29:00 +00001158}
1159
1160FileSpec::EnumerateDirectoryResult
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001161FileSpec::EnumerateDirectory(llvm::StringRef dir_path, bool find_directories,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001162 bool find_files, bool find_other,
1163 EnumerateDirectoryCallbackType callback,
1164 void *callback_baton) {
1165 return ForEachItemInDirectory(
1166 dir_path,
1167 [&find_directories, &find_files, &find_other, &callback,
1168 &callback_baton](FileType file_type, const FileSpec &file_spec) {
1169 switch (file_type) {
1170 case FileType::eFileTypeDirectory:
1171 if (find_directories)
1172 return callback(callback_baton, file_type, file_spec);
1173 break;
1174 case FileType::eFileTypeRegular:
1175 if (find_files)
1176 return callback(callback_baton, file_type, file_spec);
1177 break;
1178 default:
1179 if (find_other)
1180 return callback(callback_baton, file_type, file_spec);
1181 break;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001182 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001183 return eEnumerateDirectoryResultNext;
1184 });
Daniel Maleae0f8f572013-08-26 23:57:52 +00001185}
1186
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001187FileSpec
1188FileSpec::CopyByAppendingPathComponent(llvm::StringRef component) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001189 FileSpec ret = *this;
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001190 ret.AppendPathComponent(component);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001191 return ret;
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001192}
1193
Kate Stoneb9c1b512016-09-06 20:57:50 +00001194FileSpec FileSpec::CopyByRemovingLastPathComponent() const {
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001195 // CLEANUP: Use StringRef for string handling.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001196 const bool resolve = false;
1197 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1198 return FileSpec("", resolve);
1199 if (m_directory.IsEmpty())
1200 return FileSpec("", resolve);
1201 if (m_filename.IsEmpty()) {
1202 const char *dir_cstr = m_directory.GetCString();
1203 const char *last_slash_ptr = ::strrchr(dir_cstr, '/');
1204
1205 // check for obvious cases before doing the full thing
1206 if (!last_slash_ptr)
1207 return FileSpec("", resolve);
1208 if (last_slash_ptr == dir_cstr)
1209 return FileSpec("/", resolve);
1210
1211 size_t last_slash_pos = last_slash_ptr - dir_cstr + 1;
1212 ConstString new_path(dir_cstr, last_slash_pos);
1213 return FileSpec(new_path.GetCString(), resolve);
1214 } else
1215 return FileSpec(m_directory.GetCString(), resolve);
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001216}
1217
Kate Stoneb9c1b512016-09-06 20:57:50 +00001218ConstString FileSpec::GetLastPathComponent() const {
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001219 // CLEANUP: Use StringRef for string handling.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001220 if (m_filename)
1221 return m_filename;
1222 if (m_directory) {
1223 const char *dir_cstr = m_directory.GetCString();
1224 const char *last_slash_ptr = ::strrchr(dir_cstr, '/');
1225 if (last_slash_ptr == NULL)
1226 return m_directory;
1227 if (last_slash_ptr == dir_cstr) {
1228 if (last_slash_ptr[1] == 0)
1229 return ConstString(last_slash_ptr);
1230 else
1231 return ConstString(last_slash_ptr + 1);
1232 }
1233 if (last_slash_ptr[1] != 0)
1234 return ConstString(last_slash_ptr + 1);
1235 const char *penultimate_slash_ptr = last_slash_ptr;
1236 while (*penultimate_slash_ptr) {
1237 --penultimate_slash_ptr;
1238 if (penultimate_slash_ptr == dir_cstr)
1239 break;
1240 if (*penultimate_slash_ptr == '/')
1241 break;
1242 }
1243 ConstString result(penultimate_slash_ptr + 1,
1244 last_slash_ptr - penultimate_slash_ptr);
1245 return result;
1246 }
1247 return ConstString();
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001248}
1249
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001250void FileSpec::PrependPathComponent(llvm::StringRef component) {
1251 if (component.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001252 return;
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001253
Kate Stoneb9c1b512016-09-06 20:57:50 +00001254 const bool resolve = false;
1255 if (m_filename.IsEmpty() && m_directory.IsEmpty()) {
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001256 SetFile(component, resolve);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001257 return;
1258 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00001259
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001260 char sep = GetPreferredPathSeparator(m_syntax);
1261 std::string result;
1262 if (m_filename.IsEmpty())
1263 result = llvm::join_items(sep, component, m_directory.GetStringRef());
1264 else if (m_directory.IsEmpty())
1265 result = llvm::join_items(sep, component, m_filename.GetStringRef());
1266 else
1267 result = llvm::join_items(sep, component, m_directory.GetStringRef(),
1268 m_filename.GetStringRef());
1269
1270 SetFile(result, resolve);
Chaoren Lind3173f32015-05-29 19:52:29 +00001271}
1272
Kate Stoneb9c1b512016-09-06 20:57:50 +00001273void FileSpec::PrependPathComponent(const FileSpec &new_path) {
1274 return PrependPathComponent(new_path.GetPath(false));
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001275}
1276
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001277void FileSpec::AppendPathComponent(llvm::StringRef component) {
1278 if (component.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001279 return;
1280
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001281 std::string result;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001282 if (!m_directory.IsEmpty()) {
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001283 result += m_directory.GetStringRef();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001284 if (!IsPathSeparator(m_directory.GetStringRef().back(), m_syntax))
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001285 result += GetPreferredPathSeparator(m_syntax);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001286 }
1287
1288 if (!m_filename.IsEmpty()) {
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001289 result += m_filename.GetStringRef();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001290 if (!IsPathSeparator(m_filename.GetStringRef().back(), m_syntax))
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001291 result += GetPreferredPathSeparator(m_syntax);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001292 }
1293
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001294 component = component.drop_while(
1295 [this](char c) { return IsPathSeparator(c, m_syntax); });
Kate Stoneb9c1b512016-09-06 20:57:50 +00001296
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001297 result += component;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001298
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001299 SetFile(result, false, m_syntax);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001300}
1301
1302void FileSpec::AppendPathComponent(const FileSpec &new_path) {
1303 return AppendPathComponent(new_path.GetPath(false));
1304}
1305
1306void FileSpec::RemoveLastPathComponent() {
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001307 // CLEANUP: Use StringRef for string handling.
1308
Kate Stoneb9c1b512016-09-06 20:57:50 +00001309 const bool resolve = false;
1310 if (m_filename.IsEmpty() && m_directory.IsEmpty()) {
1311 SetFile("", resolve);
1312 return;
1313 }
1314 if (m_directory.IsEmpty()) {
1315 SetFile("", resolve);
1316 return;
1317 }
1318 if (m_filename.IsEmpty()) {
1319 const char *dir_cstr = m_directory.GetCString();
1320 const char *last_slash_ptr = ::strrchr(dir_cstr, '/');
1321
1322 // check for obvious cases before doing the full thing
1323 if (!last_slash_ptr) {
1324 SetFile("", resolve);
1325 return;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001326 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001327 if (last_slash_ptr == dir_cstr) {
1328 SetFile("/", resolve);
1329 return;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001330 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001331 size_t last_slash_pos = last_slash_ptr - dir_cstr + 1;
1332 ConstString new_path(dir_cstr, last_slash_pos);
1333 SetFile(new_path.GetCString(), resolve);
1334 } else
1335 SetFile(m_directory.GetCString(), resolve);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001336}
Greg Clayton1f746072012-08-29 21:13:06 +00001337//------------------------------------------------------------------
1338/// Returns true if the filespec represents an implementation source
1339/// file (files with a ".c", ".cpp", ".m", ".mm" (many more)
1340/// extension).
1341///
1342/// @return
1343/// \b true if the filespec represents an implementation source
1344/// file, \b false otherwise.
1345//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00001346bool FileSpec::IsSourceImplementationFile() const {
1347 ConstString extension(GetFileNameExtension());
Zachary Turner95eae422016-09-21 16:01:28 +00001348 if (!extension)
1349 return false;
1350
1351 static RegularExpression g_source_file_regex(llvm::StringRef(
1352 "^([cC]|[mM]|[mM][mM]|[cC][pP][pP]|[cC]\\+\\+|[cC][xX][xX]|[cC][cC]|["
1353 "cC][pP]|[sS]|[aA][sS][mM]|[fF]|[fF]77|[fF]90|[fF]95|[fF]03|[fF][oO]["
1354 "rR]|[fF][tT][nN]|[fF][pP][pP]|[aA][dD][aA]|[aA][dD][bB]|[aA][dD][sS])"
1355 "$"));
1356 return g_source_file_regex.Execute(extension.GetStringRef());
Greg Clayton1f746072012-08-29 21:13:06 +00001357}
1358
Kate Stoneb9c1b512016-09-06 20:57:50 +00001359bool FileSpec::IsRelative() const {
1360 const char *dir = m_directory.GetCString();
1361 llvm::StringRef directory(dir ? dir : "");
Zachary Turner270e99a2014-12-08 21:36:42 +00001362
Kate Stoneb9c1b512016-09-06 20:57:50 +00001363 if (directory.size() > 0) {
1364 if (PathSyntaxIsPosix(m_syntax)) {
1365 // If the path doesn't start with '/' or '~', return true
1366 switch (directory[0]) {
1367 case '/':
1368 case '~':
1369 return false;
1370 default:
Greg Claytona0ca6602012-10-18 16:33:33 +00001371 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001372 }
1373 } else {
1374 if (directory.size() >= 2 && directory[1] == ':')
1375 return false;
1376 if (directory[0] == '/')
1377 return false;
1378 return true;
Greg Claytona0ca6602012-10-18 16:33:33 +00001379 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001380 } else if (m_filename) {
1381 // No directory, just a basename, return true
1382 return true;
1383 }
1384 return false;
Greg Claytona0ca6602012-10-18 16:33:33 +00001385}
Chaoren Lin372e9062015-06-09 17:54:27 +00001386
Kate Stoneb9c1b512016-09-06 20:57:50 +00001387bool FileSpec::IsAbsolute() const { return !FileSpec::IsRelative(); }