blob: 7ced3c3810c7b5793e07e9f756f6cdbc5f7f7b58 [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"
Zachary Turnerc00cf4a2014-08-15 22:04:21 +000031#include "lldb/Host/File.h"
32#include "lldb/Host/FileSpec.h"
33#include "lldb/Host/FileSystem.h"
34#include "lldb/Host/Host.h"
35#include "lldb/Utility/CleanUp.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000036#include "lldb/Utility/RegularExpression.h"
37#include "lldb/Utility/Stream.h"
38#include "lldb/Utility/StreamString.h"
Zachary Turnerc00cf4a2014-08-15 22:04:21 +000039
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
Zachary Turner827d5d72016-12-16 04:27:00 +0000357 Normalize(resolved, m_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());
Zachary Turner827d5d72016-12-16 04:27:00 +0000360 size_t dir_end = ParentPathEnd(resolve_path_ref, m_syntax);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000361 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;
Zachary Turner827d5d72016-12-16 04:27:00 +0000369 size_t root_dir_start = RootDirStart(resolve_path_ref, m_syntax);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000370 while (filename_begin != llvm::StringRef::npos &&
371 filename_begin < resolve_path_ref.size() &&
372 filename_begin != root_dir_start &&
Zachary Turner827d5d72016-12-16 04:27:00 +0000373 IsPathSeparator(resolve_path_ref[filename_begin], m_syntax))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000374 ++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(".") &&
Pavel Labathe6e7e6c2016-11-30 16:08:45 +0000547 !m_directory.GetStringRef().contains("//") &&
548 m_filename.GetStringRef() != ".." && m_filename.GetStringRef() != ".")
Pavel Labath218770b2016-10-31 16:22:07 +0000549 return *this;
Greg Clayton5a271952015-06-02 22:43:29 +0000550
Pavel Labath218770b2016-10-31 16:22:07 +0000551 llvm::SmallString<64> path, result;
552 const bool normalize = false;
553 GetPath(path, normalize);
554 llvm::StringRef rest(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000555
Pavel Labath218770b2016-10-31 16:22:07 +0000556 // We will not go below root dir.
557 size_t root_dir_start = RootDirStart(path, m_syntax);
558 const bool absolute = root_dir_start != llvm::StringRef::npos;
559 if (absolute) {
560 result += rest.take_front(root_dir_start + 1);
561 rest = rest.drop_front(root_dir_start + 1);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000562 } else {
Pavel Labath218770b2016-10-31 16:22:07 +0000563 if (m_syntax == ePathSyntaxWindows && path.size() > 2 && path[1] == ':') {
564 result += rest.take_front(2);
565 rest = rest.drop_front(2);
566 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000567 }
568
Pavel Labath218770b2016-10-31 16:22:07 +0000569 bool anything_added = false;
570 llvm::SmallVector<llvm::StringRef, 0> components, processed;
571 rest.split(components, '/', -1, false);
572 processed.reserve(components.size());
573 for (auto component : components) {
574 if (component == ".")
575 continue; // Skip these.
576 if (component != "..") {
577 processed.push_back(component);
578 continue; // Regular file name.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000579 }
Pavel Labath218770b2016-10-31 16:22:07 +0000580 if (!processed.empty()) {
581 processed.pop_back();
582 continue; // Dots. Go one level up if we can.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000583 }
Pavel Labath218770b2016-10-31 16:22:07 +0000584 if (absolute)
585 continue; // We're at the top level. Cannot go higher than that. Skip.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000586
Pavel Labath218770b2016-10-31 16:22:07 +0000587 result += component; // We're a relative path. We need to keep these.
588 result += '/';
589 anything_added = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000590 }
Pavel Labath218770b2016-10-31 16:22:07 +0000591 for (auto component : processed) {
592 result += component;
593 result += '/';
594 anything_added = true;
595 }
596 if (anything_added)
597 result.pop_back(); // Pop last '/'.
598 else if (result.empty())
599 result = ".";
Kate Stoneb9c1b512016-09-06 20:57:50 +0000600
Pavel Labath218770b2016-10-31 16:22:07 +0000601 return FileSpec(result, false, m_syntax);
Jim Ingham96a15962014-11-15 01:54:26 +0000602}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000603
604//------------------------------------------------------------------
605// Dump the object to the supplied stream. If the object contains
606// a valid directory name, it will be displayed followed by a
607// directory delimiter, and the filename.
608//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000609void FileSpec::Dump(Stream *s) const {
610 if (s) {
611 std::string path{GetPath(true)};
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000612 s->PutCString(path);
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000613 char path_separator = GetPreferredPathSeparator(m_syntax);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000614 if (!m_filename && !path.empty() && path.back() != path_separator)
615 s->PutChar(path_separator);
616 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000617}
618
619//------------------------------------------------------------------
620// Returns true if the file exists.
621//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000622bool FileSpec::Exists() const {
623 struct stat file_stats;
624 return GetFileStats(this, &file_stats);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000625}
626
Kate Stoneb9c1b512016-09-06 20:57:50 +0000627bool FileSpec::Readable() const {
628 const uint32_t permissions = GetPermissions();
629 if (permissions & eFilePermissionsEveryoneR)
630 return true;
631 return false;
Greg Clayton5acc1252014-08-15 18:00:45 +0000632}
633
Kate Stoneb9c1b512016-09-06 20:57:50 +0000634bool FileSpec::ResolveExecutableLocation() {
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000635 // CLEANUP: Use StringRef for string handling.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000636 if (!m_directory) {
637 const char *file_cstr = m_filename.GetCString();
638 if (file_cstr) {
639 const std::string file_str(file_cstr);
640 llvm::ErrorOr<std::string> error_or_path =
641 llvm::sys::findProgramByName(file_str);
642 if (!error_or_path)
Jim Ingham0909e5f2010-09-16 00:57:33 +0000643 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000644 std::string path = error_or_path.get();
645 llvm::StringRef dir_ref = llvm::sys::path::parent_path(path);
646 if (!dir_ref.empty()) {
647 // FindProgramByName returns "." if it can't find the file.
648 if (strcmp(".", dir_ref.data()) == 0)
649 return false;
650
651 m_directory.SetCString(dir_ref.data());
652 if (Exists())
653 return true;
654 else {
655 // If FindProgramByName found the file, it returns the directory +
656 // filename in its return results.
657 // We need to separate them.
658 FileSpec tmp_file(dir_ref.data(), false);
659 if (tmp_file.Exists()) {
660 m_directory = tmp_file.m_directory;
661 return true;
662 }
663 }
664 }
665 }
666 }
667
668 return false;
Jim Ingham0909e5f2010-09-16 00:57:33 +0000669}
670
Kate Stoneb9c1b512016-09-06 20:57:50 +0000671bool FileSpec::ResolvePath() {
672 if (m_is_resolved)
673 return true; // We have already resolved this path
674
675 char path_buf[PATH_MAX];
676 if (!GetPath(path_buf, PATH_MAX, false))
677 return false;
678 // SetFile(...) will set m_is_resolved correctly if it can resolve the path
679 SetFile(path_buf, true);
680 return m_is_resolved;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000681}
682
Kate Stoneb9c1b512016-09-06 20:57:50 +0000683uint64_t FileSpec::GetByteSize() const {
684 struct stat file_stats;
685 if (GetFileStats(this, &file_stats))
686 return file_stats.st_size;
687 return 0;
Zachary Turnerdf62f202014-08-07 17:33:07 +0000688}
689
Kate Stoneb9c1b512016-09-06 20:57:50 +0000690FileSpec::PathSyntax FileSpec::GetPathSyntax() const { return m_syntax; }
691
692FileSpec::FileType FileSpec::GetFileType() const {
693 struct stat file_stats;
694 if (GetFileStats(this, &file_stats)) {
695 mode_t file_type = file_stats.st_mode & S_IFMT;
696 switch (file_type) {
697 case S_IFDIR:
698 return eFileTypeDirectory;
699 case S_IFREG:
700 return eFileTypeRegular;
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000701#ifndef _WIN32
Kate Stoneb9c1b512016-09-06 20:57:50 +0000702 case S_IFIFO:
703 return eFileTypePipe;
704 case S_IFSOCK:
705 return eFileTypeSocket;
706 case S_IFLNK:
707 return eFileTypeSymbolicLink;
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000708#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000709 default:
710 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000711 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000712 return eFileTypeUnknown;
713 }
714 return eFileTypeInvalid;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000715}
716
Kate Stoneb9c1b512016-09-06 20:57:50 +0000717bool FileSpec::IsSymbolicLink() const {
718 char resolved_path[PATH_MAX];
719 if (!GetPath(resolved_path, sizeof(resolved_path)))
720 return false;
Oleksiy Vyalov8a578bf2015-07-21 01:28:22 +0000721
722#ifdef _WIN32
Kate Stoneb9c1b512016-09-06 20:57:50 +0000723 std::wstring wpath;
724 if (!llvm::ConvertUTF8toWide(resolved_path, wpath))
725 return false;
726 auto attrs = ::GetFileAttributesW(wpath.c_str());
727 if (attrs == INVALID_FILE_ATTRIBUTES)
728 return false;
Oleksiy Vyalov8a578bf2015-07-21 01:28:22 +0000729
Kate Stoneb9c1b512016-09-06 20:57:50 +0000730 return (attrs & FILE_ATTRIBUTE_REPARSE_POINT);
Oleksiy Vyalov8a578bf2015-07-21 01:28:22 +0000731#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000732 struct stat file_stats;
733 if (::lstat(resolved_path, &file_stats) != 0)
734 return false;
Oleksiy Vyalov8a578bf2015-07-21 01:28:22 +0000735
Kate Stoneb9c1b512016-09-06 20:57:50 +0000736 return (file_stats.st_mode & S_IFMT) == S_IFLNK;
Oleksiy Vyalov8a578bf2015-07-21 01:28:22 +0000737#endif
738}
739
Kate Stoneb9c1b512016-09-06 20:57:50 +0000740uint32_t FileSpec::GetPermissions() const {
741 uint32_t file_permissions = 0;
742 if (*this)
743 FileSystem::GetFilePermissions(*this, file_permissions);
744 return file_permissions;
Greg Claytonfbb76342013-11-20 21:07:01 +0000745}
746
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000747//------------------------------------------------------------------
748// Directory string get accessor.
749//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000750ConstString &FileSpec::GetDirectory() { return m_directory; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000751
752//------------------------------------------------------------------
753// Directory string const get accessor.
754//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000755const ConstString &FileSpec::GetDirectory() const { return m_directory; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000756
757//------------------------------------------------------------------
758// Filename string get accessor.
759//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000760ConstString &FileSpec::GetFilename() { return m_filename; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000761
762//------------------------------------------------------------------
763// Filename string const get accessor.
764//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000765const ConstString &FileSpec::GetFilename() const { return m_filename; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000766
767//------------------------------------------------------------------
768// Extract the directory and path into a fixed buffer. This is
769// needed as the directory and path are stored in separate string
770// values.
771//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000772size_t FileSpec::GetPath(char *path, size_t path_max_len,
773 bool denormalize) const {
774 if (!path)
775 return 0;
Zachary Turnerb6d99242014-08-08 23:54:35 +0000776
Kate Stoneb9c1b512016-09-06 20:57:50 +0000777 std::string result = GetPath(denormalize);
778 ::snprintf(path, path_max_len, "%s", result.c_str());
779 return std::min(path_max_len - 1, result.length());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000780}
781
Kate Stoneb9c1b512016-09-06 20:57:50 +0000782std::string FileSpec::GetPath(bool denormalize) const {
783 llvm::SmallString<64> result;
784 GetPath(result, denormalize);
785 return std::string(result.begin(), result.end());
Jason Molendaa7ae4672013-04-29 09:46:43 +0000786}
787
Kate Stoneb9c1b512016-09-06 20:57:50 +0000788const char *FileSpec::GetCString(bool denormalize) const {
789 return ConstString{GetPath(denormalize)}.AsCString(NULL);
Chaoren Lind3173f32015-05-29 19:52:29 +0000790}
791
Kate Stoneb9c1b512016-09-06 20:57:50 +0000792void FileSpec::GetPath(llvm::SmallVectorImpl<char> &path,
793 bool denormalize) const {
794 path.append(m_directory.GetStringRef().begin(),
795 m_directory.GetStringRef().end());
796 if (m_directory && m_filename &&
797 !IsPathSeparator(m_directory.GetStringRef().back(), m_syntax))
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000798 path.insert(path.end(), GetPreferredPathSeparator(m_syntax));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000799 path.append(m_filename.GetStringRef().begin(),
800 m_filename.GetStringRef().end());
801 Normalize(path, m_syntax);
802 if (denormalize && !path.empty())
803 Denormalize(path, m_syntax);
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000804}
805
Kate Stoneb9c1b512016-09-06 20:57:50 +0000806ConstString FileSpec::GetFileNameExtension() const {
807 if (m_filename) {
Enrico Granataa9dbf432011-10-17 21:45:27 +0000808 const char *filename = m_filename.GetCString();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000809 const char *dot_pos = strrchr(filename, '.');
810 if (dot_pos && dot_pos[1] != '\0')
811 return ConstString(dot_pos + 1);
812 }
813 return ConstString();
814}
815
816ConstString FileSpec::GetFileNameStrippingExtension() const {
817 const char *filename = m_filename.GetCString();
818 if (filename == NULL)
819 return ConstString();
820
821 const char *dot_pos = strrchr(filename, '.');
822 if (dot_pos == NULL)
823 return m_filename;
824
825 return ConstString(filename, dot_pos - filename);
Enrico Granataa9dbf432011-10-17 21:45:27 +0000826}
827
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000828//------------------------------------------------------------------
829// Returns a shared pointer to a data buffer that contains all or
830// part of the contents of a file. The data is memory mapped and
831// will lazily page in data from the file as memory is accessed.
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +0000832// The data that is mapped will start "file_offset" bytes into the
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000833// file, and "file_size" bytes will be mapped. If "file_size" is
834// greater than the number of bytes available in the file starting
835// at "file_offset", the number of bytes will be appropriately
836// truncated. The final number of bytes that get mapped can be
837// verified using the DataBuffer::GetByteSize() function.
838//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000839DataBufferSP FileSpec::MemoryMapFileContents(off_t file_offset,
840 size_t file_size) const {
841 DataBufferSP data_sp;
842 std::unique_ptr<DataBufferMemoryMap> mmap_data(new DataBufferMemoryMap());
843 if (mmap_data.get()) {
844 const size_t mapped_length =
845 mmap_data->MemoryMapFromFileSpec(this, file_offset, file_size);
846 if (((file_size == SIZE_MAX) && (mapped_length > 0)) ||
847 (mapped_length >= file_size))
848 data_sp.reset(mmap_data.release());
849 }
850 return data_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000851}
852
Kate Stoneb9c1b512016-09-06 20:57:50 +0000853DataBufferSP FileSpec::MemoryMapFileContentsIfLocal(off_t file_offset,
854 size_t file_size) const {
855 if (FileSystem::IsLocal(*this))
856 return MemoryMapFileContents(file_offset, file_size);
857 else
858 return ReadFileContents(file_offset, file_size, NULL);
Greg Clayton736888c2015-02-23 23:47:09 +0000859}
860
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000861//------------------------------------------------------------------
862// Return the size in bytes that this object takes in memory. This
863// returns the size in bytes of this object, not any shared string
864// values it may refer to.
865//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000866size_t FileSpec::MemorySize() const {
867 return m_filename.MemorySize() + m_directory.MemorySize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000868}
869
Kate Stoneb9c1b512016-09-06 20:57:50 +0000870size_t FileSpec::ReadFileContents(off_t file_offset, void *dst, size_t dst_len,
871 Error *error_ptr) const {
872 Error error;
873 size_t bytes_read = 0;
874 char resolved_path[PATH_MAX];
875 if (GetPath(resolved_path, sizeof(resolved_path))) {
876 File file;
877 error = file.Open(resolved_path, File::eOpenOptionRead);
878 if (error.Success()) {
879 off_t file_offset_after_seek = file_offset;
880 bytes_read = dst_len;
881 error = file.Read(dst, bytes_read, file_offset_after_seek);
Greg Claytondda4f7b2010-06-30 23:03:03 +0000882 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000883 } else {
884 error.SetErrorString("invalid file specification");
885 }
886 if (error_ptr)
887 *error_ptr = error;
888 return bytes_read;
Greg Claytondda4f7b2010-06-30 23:03:03 +0000889}
890
891//------------------------------------------------------------------
892// Returns a shared pointer to a data buffer that contains all or
893// part of the contents of a file. The data copies into a heap based
894// buffer that lives in the DataBuffer shared pointer object returned.
895// The data that is cached will start "file_offset" bytes into the
896// file, and "file_size" bytes will be mapped. If "file_size" is
897// greater than the number of bytes available in the file starting
898// at "file_offset", the number of bytes will be appropriately
899// truncated. The final number of bytes that get mapped can be
900// verified using the DataBuffer::GetByteSize() function.
901//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000902DataBufferSP FileSpec::ReadFileContents(off_t file_offset, size_t file_size,
903 Error *error_ptr) const {
904 Error error;
905 DataBufferSP data_sp;
906 char resolved_path[PATH_MAX];
907 if (GetPath(resolved_path, sizeof(resolved_path))) {
908 File file;
909 error = file.Open(resolved_path, File::eOpenOptionRead);
910 if (error.Success()) {
911 const bool null_terminate = false;
912 error = file.Read(file_size, file_offset, null_terminate, data_sp);
Greg Clayton0b0b5122012-08-30 18:15:10 +0000913 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000914 } else {
915 error.SetErrorString("invalid file specification");
916 }
917 if (error_ptr)
918 *error_ptr = error;
919 return data_sp;
Greg Clayton0b0b5122012-08-30 18:15:10 +0000920}
921
Kate Stoneb9c1b512016-09-06 20:57:50 +0000922DataBufferSP FileSpec::ReadFileContentsAsCString(Error *error_ptr) {
923 Error error;
924 DataBufferSP data_sp;
925 char resolved_path[PATH_MAX];
926 if (GetPath(resolved_path, sizeof(resolved_path))) {
927 File file;
928 error = file.Open(resolved_path, File::eOpenOptionRead);
929 if (error.Success()) {
930 off_t offset = 0;
931 size_t length = SIZE_MAX;
932 const bool null_terminate = true;
933 error = file.Read(length, offset, null_terminate, data_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000934 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000935 } else {
936 error.SetErrorString("invalid file specification");
937 }
938 if (error_ptr)
939 *error_ptr = error;
940 return data_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000941}
942
Kate Stoneb9c1b512016-09-06 20:57:50 +0000943size_t FileSpec::ReadFileLines(STLStringArray &lines) {
944 lines.clear();
945 char path[PATH_MAX];
946 if (GetPath(path, sizeof(path))) {
947 std::ifstream file_stream(path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000948
Kate Stoneb9c1b512016-09-06 20:57:50 +0000949 if (file_stream) {
950 std::string line;
951 while (getline(file_stream, line))
952 lines.push_back(line);
Greg Clayton58fc50e2010-10-20 22:52:05 +0000953 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000954 }
955 return lines.size();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000956}
Greg Clayton4272cc72011-02-02 02:24:04 +0000957
958FileSpec::EnumerateDirectoryResult
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000959FileSpec::ForEachItemInDirectory(llvm::StringRef dir_path,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000960 DirectoryCallback const &callback) {
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000961 if (dir_path.empty())
962 return eEnumerateDirectoryResultNext;
963
Zachary Turner190fadc2016-03-22 17:58:09 +0000964#ifdef _WIN32
Kate Stoneb9c1b512016-09-06 20:57:50 +0000965 std::string szDir(dir_path);
966 szDir += "\\*";
Greg Clayton58c65f02015-06-29 18:29:00 +0000967
Kate Stoneb9c1b512016-09-06 20:57:50 +0000968 std::wstring wszDir;
969 if (!llvm::ConvertUTF8toWide(szDir, wszDir)) {
970 return eEnumerateDirectoryResultNext;
Greg Clayton58c65f02015-06-29 18:29:00 +0000971 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000972
973 WIN32_FIND_DATAW ffd;
974 HANDLE hFind = FindFirstFileW(wszDir.c_str(), &ffd);
975
976 if (hFind == INVALID_HANDLE_VALUE) {
977 return eEnumerateDirectoryResultNext;
978 }
979
980 do {
981 FileSpec::FileType file_type = eFileTypeUnknown;
982 if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
983 size_t len = wcslen(ffd.cFileName);
984
985 if (len == 1 && ffd.cFileName[0] == L'.')
986 continue;
987
988 if (len == 2 && ffd.cFileName[0] == L'.' && ffd.cFileName[1] == L'.')
989 continue;
990
991 file_type = eFileTypeDirectory;
992 } else if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DEVICE) {
993 file_type = eFileTypeOther;
994 } else {
995 file_type = eFileTypeRegular;
996 }
997
998 std::string fileName;
999 if (!llvm::convertWideToUTF8(ffd.cFileName, fileName)) {
1000 continue;
1001 }
1002
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001003 std::string child_path = llvm::join_items("\\", dir_path, fileName);
1004 // Don't resolve the file type or path
1005 FileSpec child_path_spec(child_path.data(), false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001006
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001007 EnumerateDirectoryResult result = callback(file_type, child_path_spec);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001008
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001009 switch (result) {
1010 case eEnumerateDirectoryResultNext:
1011 // Enumerate next entry in the current directory. We just
1012 // exit this switch and will continue enumerating the
1013 // current directory as we currently are...
1014 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001015
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001016 case eEnumerateDirectoryResultEnter: // Recurse into the current entry
1017 // if it is a directory or symlink,
1018 // or next if not
1019 if (FileSpec::ForEachItemInDirectory(child_path.data(), callback) ==
1020 eEnumerateDirectoryResultQuit) {
1021 // The subdirectory returned Quit, which means to
1022 // stop all directory enumerations at all levels.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001023 return eEnumerateDirectoryResultQuit;
1024 }
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001025 break;
1026
1027 case eEnumerateDirectoryResultExit: // Exit from the current directory
1028 // at the current level.
1029 // Exit from this directory level and tell parent to
1030 // keep enumerating.
1031 return eEnumerateDirectoryResultNext;
1032
1033 case eEnumerateDirectoryResultQuit: // Stop directory enumerations at
1034 // any level
1035 return eEnumerateDirectoryResultQuit;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001036 }
1037 } while (FindNextFileW(hFind, &ffd) != 0);
1038
1039 FindClose(hFind);
1040#else
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001041 std::string dir_string(dir_path);
1042 lldb_utility::CleanUp<DIR *, int> dir_path_dir(opendir(dir_string.c_str()),
1043 NULL, closedir);
1044 if (dir_path_dir.is_valid()) {
1045 char dir_path_last_char = dir_path.back();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001046
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001047 long path_max = fpathconf(dirfd(dir_path_dir.get()), _PC_NAME_MAX);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001048#if defined(__APPLE_) && defined(__DARWIN_MAXPATHLEN)
1049 if (path_max < __DARWIN_MAXPATHLEN)
1050 path_max = __DARWIN_MAXPATHLEN;
1051#endif
1052 struct dirent *buf, *dp;
1053 buf = (struct dirent *)malloc(offsetof(struct dirent, d_name) + path_max +
1054 1);
1055
1056 while (buf && readdir_r(dir_path_dir.get(), buf, &dp) == 0 && dp) {
1057 // Only search directories
1058 if (dp->d_type == DT_DIR || dp->d_type == DT_UNKNOWN) {
1059 size_t len = strlen(dp->d_name);
1060
1061 if (len == 1 && dp->d_name[0] == '.')
1062 continue;
1063
1064 if (len == 2 && dp->d_name[0] == '.' && dp->d_name[1] == '.')
1065 continue;
1066 }
1067
1068 FileSpec::FileType file_type = eFileTypeUnknown;
1069
1070 switch (dp->d_type) {
1071 default:
1072 case DT_UNKNOWN:
1073 file_type = eFileTypeUnknown;
1074 break;
1075 case DT_FIFO:
1076 file_type = eFileTypePipe;
1077 break;
1078 case DT_CHR:
1079 file_type = eFileTypeOther;
1080 break;
1081 case DT_DIR:
1082 file_type = eFileTypeDirectory;
1083 break;
1084 case DT_BLK:
1085 file_type = eFileTypeOther;
1086 break;
1087 case DT_REG:
1088 file_type = eFileTypeRegular;
1089 break;
1090 case DT_LNK:
1091 file_type = eFileTypeSymbolicLink;
1092 break;
1093 case DT_SOCK:
1094 file_type = eFileTypeSocket;
1095 break;
1096#if !defined(__OpenBSD__)
1097 case DT_WHT:
1098 file_type = eFileTypeOther;
1099 break;
1100#endif
1101 }
1102
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001103 std::string child_path;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001104 // Don't make paths with "/foo//bar", that just confuses everybody.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001105 if (dir_path_last_char == '/')
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001106 child_path = llvm::join_items("", dir_path, dp->d_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001107 else
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001108 child_path = llvm::join_items('/', dir_path, dp->d_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001109
Kate Stoneb9c1b512016-09-06 20:57:50 +00001110 // Don't resolve the file type or path
1111 FileSpec child_path_spec(child_path, false);
1112
1113 EnumerateDirectoryResult result =
1114 callback(file_type, child_path_spec);
1115
1116 switch (result) {
1117 case eEnumerateDirectoryResultNext:
1118 // Enumerate next entry in the current directory. We just
1119 // exit this switch and will continue enumerating the
1120 // current directory as we currently are...
1121 break;
1122
1123 case eEnumerateDirectoryResultEnter: // Recurse into the current entry
1124 // if it is a directory or
1125 // symlink, or next if not
1126 if (FileSpec::ForEachItemInDirectory(child_path, callback) ==
1127 eEnumerateDirectoryResultQuit) {
1128 // The subdirectory returned Quit, which means to
1129 // stop all directory enumerations at all levels.
1130 if (buf)
1131 free(buf);
1132 return eEnumerateDirectoryResultQuit;
1133 }
1134 break;
1135
1136 case eEnumerateDirectoryResultExit: // Exit from the current directory
1137 // at the current level.
1138 // Exit from this directory level and tell parent to
1139 // keep enumerating.
1140 if (buf)
1141 free(buf);
1142 return eEnumerateDirectoryResultNext;
1143
1144 case eEnumerateDirectoryResultQuit: // Stop directory enumerations at
1145 // any level
1146 if (buf)
1147 free(buf);
1148 return eEnumerateDirectoryResultQuit;
1149 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001150 }
1151 if (buf) {
1152 free(buf);
1153 }
1154 }
1155#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00001156 // By default when exiting a directory, we tell the parent enumeration
1157 // to continue enumerating.
1158 return eEnumerateDirectoryResultNext;
Greg Clayton58c65f02015-06-29 18:29:00 +00001159}
1160
1161FileSpec::EnumerateDirectoryResult
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001162FileSpec::EnumerateDirectory(llvm::StringRef dir_path, bool find_directories,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001163 bool find_files, bool find_other,
1164 EnumerateDirectoryCallbackType callback,
1165 void *callback_baton) {
1166 return ForEachItemInDirectory(
1167 dir_path,
1168 [&find_directories, &find_files, &find_other, &callback,
1169 &callback_baton](FileType file_type, const FileSpec &file_spec) {
1170 switch (file_type) {
1171 case FileType::eFileTypeDirectory:
1172 if (find_directories)
1173 return callback(callback_baton, file_type, file_spec);
1174 break;
1175 case FileType::eFileTypeRegular:
1176 if (find_files)
1177 return callback(callback_baton, file_type, file_spec);
1178 break;
1179 default:
1180 if (find_other)
1181 return callback(callback_baton, file_type, file_spec);
1182 break;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001183 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001184 return eEnumerateDirectoryResultNext;
1185 });
Daniel Maleae0f8f572013-08-26 23:57:52 +00001186}
1187
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001188FileSpec
1189FileSpec::CopyByAppendingPathComponent(llvm::StringRef component) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001190 FileSpec ret = *this;
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001191 ret.AppendPathComponent(component);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001192 return ret;
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001193}
1194
Kate Stoneb9c1b512016-09-06 20:57:50 +00001195FileSpec FileSpec::CopyByRemovingLastPathComponent() const {
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001196 // CLEANUP: Use StringRef for string handling.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001197 const bool resolve = false;
1198 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1199 return FileSpec("", resolve);
1200 if (m_directory.IsEmpty())
1201 return FileSpec("", resolve);
1202 if (m_filename.IsEmpty()) {
1203 const char *dir_cstr = m_directory.GetCString();
1204 const char *last_slash_ptr = ::strrchr(dir_cstr, '/');
1205
1206 // check for obvious cases before doing the full thing
1207 if (!last_slash_ptr)
1208 return FileSpec("", resolve);
1209 if (last_slash_ptr == dir_cstr)
1210 return FileSpec("/", resolve);
1211
1212 size_t last_slash_pos = last_slash_ptr - dir_cstr + 1;
1213 ConstString new_path(dir_cstr, last_slash_pos);
1214 return FileSpec(new_path.GetCString(), resolve);
1215 } else
1216 return FileSpec(m_directory.GetCString(), resolve);
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001217}
1218
Kate Stoneb9c1b512016-09-06 20:57:50 +00001219ConstString FileSpec::GetLastPathComponent() const {
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001220 // CLEANUP: Use StringRef for string handling.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001221 if (m_filename)
1222 return m_filename;
1223 if (m_directory) {
1224 const char *dir_cstr = m_directory.GetCString();
1225 const char *last_slash_ptr = ::strrchr(dir_cstr, '/');
1226 if (last_slash_ptr == NULL)
1227 return m_directory;
1228 if (last_slash_ptr == dir_cstr) {
1229 if (last_slash_ptr[1] == 0)
1230 return ConstString(last_slash_ptr);
1231 else
1232 return ConstString(last_slash_ptr + 1);
1233 }
1234 if (last_slash_ptr[1] != 0)
1235 return ConstString(last_slash_ptr + 1);
1236 const char *penultimate_slash_ptr = last_slash_ptr;
1237 while (*penultimate_slash_ptr) {
1238 --penultimate_slash_ptr;
1239 if (penultimate_slash_ptr == dir_cstr)
1240 break;
1241 if (*penultimate_slash_ptr == '/')
1242 break;
1243 }
1244 ConstString result(penultimate_slash_ptr + 1,
1245 last_slash_ptr - penultimate_slash_ptr);
1246 return result;
1247 }
1248 return ConstString();
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001249}
1250
Pavel Labath59d725c2017-01-16 10:07:02 +00001251static std::string
1252join_path_components(FileSpec::PathSyntax syntax,
1253 const std::vector<llvm::StringRef> components) {
1254 std::string result;
1255 for (size_t i = 0; i < components.size(); ++i) {
1256 if (components[i].empty())
1257 continue;
1258 result += components[i];
1259 if (i != components.size() - 1 &&
1260 !IsPathSeparator(components[i].back(), syntax))
1261 result += GetPreferredPathSeparator(syntax);
1262 }
1263
1264 return result;
1265}
1266
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001267void FileSpec::PrependPathComponent(llvm::StringRef component) {
1268 if (component.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001269 return;
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001270
Kate Stoneb9c1b512016-09-06 20:57:50 +00001271 const bool resolve = false;
1272 if (m_filename.IsEmpty() && m_directory.IsEmpty()) {
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001273 SetFile(component, resolve);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001274 return;
1275 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00001276
Pavel Labath59d725c2017-01-16 10:07:02 +00001277 std::string result =
1278 join_path_components(m_syntax, {component, m_directory.GetStringRef(),
1279 m_filename.GetStringRef()});
Pavel Labath238169d2017-01-16 12:15:42 +00001280 SetFile(result, resolve, m_syntax);
Chaoren Lind3173f32015-05-29 19:52:29 +00001281}
1282
Kate Stoneb9c1b512016-09-06 20:57:50 +00001283void FileSpec::PrependPathComponent(const FileSpec &new_path) {
1284 return PrependPathComponent(new_path.GetPath(false));
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001285}
1286
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001287void FileSpec::AppendPathComponent(llvm::StringRef component) {
1288 if (component.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001289 return;
1290
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001291 component = component.drop_while(
1292 [this](char c) { return IsPathSeparator(c, m_syntax); });
Kate Stoneb9c1b512016-09-06 20:57:50 +00001293
Pavel Labath59d725c2017-01-16 10:07:02 +00001294 std::string result =
1295 join_path_components(m_syntax, {m_directory.GetStringRef(),
1296 m_filename.GetStringRef(), component});
Kate Stoneb9c1b512016-09-06 20:57:50 +00001297
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001298 SetFile(result, false, m_syntax);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001299}
1300
1301void FileSpec::AppendPathComponent(const FileSpec &new_path) {
1302 return AppendPathComponent(new_path.GetPath(false));
1303}
1304
1305void FileSpec::RemoveLastPathComponent() {
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001306 // CLEANUP: Use StringRef for string handling.
1307
Kate Stoneb9c1b512016-09-06 20:57:50 +00001308 const bool resolve = false;
1309 if (m_filename.IsEmpty() && m_directory.IsEmpty()) {
1310 SetFile("", resolve);
1311 return;
1312 }
1313 if (m_directory.IsEmpty()) {
1314 SetFile("", resolve);
1315 return;
1316 }
1317 if (m_filename.IsEmpty()) {
1318 const char *dir_cstr = m_directory.GetCString();
1319 const char *last_slash_ptr = ::strrchr(dir_cstr, '/');
1320
1321 // check for obvious cases before doing the full thing
1322 if (!last_slash_ptr) {
1323 SetFile("", resolve);
1324 return;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001325 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001326 if (last_slash_ptr == dir_cstr) {
1327 SetFile("/", resolve);
1328 return;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001329 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001330 size_t last_slash_pos = last_slash_ptr - dir_cstr + 1;
1331 ConstString new_path(dir_cstr, last_slash_pos);
1332 SetFile(new_path.GetCString(), resolve);
1333 } else
1334 SetFile(m_directory.GetCString(), resolve);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001335}
Greg Clayton1f746072012-08-29 21:13:06 +00001336//------------------------------------------------------------------
1337/// Returns true if the filespec represents an implementation source
1338/// file (files with a ".c", ".cpp", ".m", ".mm" (many more)
1339/// extension).
1340///
1341/// @return
1342/// \b true if the filespec represents an implementation source
1343/// file, \b false otherwise.
1344//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00001345bool FileSpec::IsSourceImplementationFile() const {
1346 ConstString extension(GetFileNameExtension());
Zachary Turner95eae422016-09-21 16:01:28 +00001347 if (!extension)
1348 return false;
1349
1350 static RegularExpression g_source_file_regex(llvm::StringRef(
1351 "^([cC]|[mM]|[mM][mM]|[cC][pP][pP]|[cC]\\+\\+|[cC][xX][xX]|[cC][cC]|["
1352 "cC][pP]|[sS]|[aA][sS][mM]|[fF]|[fF]77|[fF]90|[fF]95|[fF]03|[fF][oO]["
1353 "rR]|[fF][tT][nN]|[fF][pP][pP]|[aA][dD][aA]|[aA][dD][bB]|[aA][dD][sS])"
1354 "$"));
1355 return g_source_file_regex.Execute(extension.GetStringRef());
Greg Clayton1f746072012-08-29 21:13:06 +00001356}
1357
Kate Stoneb9c1b512016-09-06 20:57:50 +00001358bool FileSpec::IsRelative() const {
1359 const char *dir = m_directory.GetCString();
1360 llvm::StringRef directory(dir ? dir : "");
Zachary Turner270e99a2014-12-08 21:36:42 +00001361
Kate Stoneb9c1b512016-09-06 20:57:50 +00001362 if (directory.size() > 0) {
1363 if (PathSyntaxIsPosix(m_syntax)) {
1364 // If the path doesn't start with '/' or '~', return true
1365 switch (directory[0]) {
1366 case '/':
1367 case '~':
1368 return false;
1369 default:
Greg Claytona0ca6602012-10-18 16:33:33 +00001370 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001371 }
1372 } else {
1373 if (directory.size() >= 2 && directory[1] == ':')
1374 return false;
1375 if (directory[0] == '/')
1376 return false;
1377 return true;
Greg Claytona0ca6602012-10-18 16:33:33 +00001378 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001379 } else if (m_filename) {
1380 // No directory, just a basename, return true
1381 return true;
1382 }
1383 return false;
Greg Claytona0ca6602012-10-18 16:33:33 +00001384}
Chaoren Lin372e9062015-06-09 17:54:27 +00001385
Kate Stoneb9c1b512016-09-06 20:57:50 +00001386bool FileSpec::IsAbsolute() const { return !FileSpec::IsRelative(); }
Zachary Turner827d5d72016-12-16 04:27:00 +00001387
1388void llvm::format_provider<FileSpec>::format(const FileSpec &F,
1389 raw_ostream &Stream,
1390 StringRef Style) {
1391 assert(
1392 (Style.empty() || Style.equals_lower("F") || Style.equals_lower("D")) &&
1393 "Invalid FileSpec style!");
1394
1395 StringRef dir = F.GetDirectory().GetStringRef();
1396 StringRef file = F.GetFilename().GetStringRef();
1397
1398 if (dir.empty() && file.empty()) {
1399 Stream << "(empty)";
1400 return;
1401 }
1402
1403 if (Style.equals_lower("F")) {
1404 Stream << (file.empty() ? "(empty)" : file);
1405 return;
1406 }
1407
1408 // Style is either D or empty, either way we need to print the directory.
1409 if (!dir.empty()) {
1410 // Directory is stored in normalized form, which might be different
1411 // than preferred form. In order to handle this, we need to cut off
1412 // the filename, then denormalize, then write the entire denorm'ed
1413 // directory.
1414 llvm::SmallString<64> denormalized_dir = dir;
1415 Denormalize(denormalized_dir, F.GetPathSyntax());
1416 Stream << denormalized_dir;
1417 Stream << GetPreferredPathSeparator(F.GetPathSyntax());
1418 }
1419
1420 if (Style.equals_lower("D")) {
1421 // We only want to print the directory, so now just exit.
1422 if (dir.empty())
1423 Stream << "(empty)";
1424 return;
1425 }
1426
1427 if (!file.empty())
1428 Stream << file;
1429}