blob: ef7df3cddd5e86ff83276ad8f8fbc9bc88a0bc81 [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
Zachary Turnerc00cf4a2014-08-15 22:04:21 +000028#include "lldb/Host/FileSpec.h"
29#include "lldb/Host/FileSystem.h"
Zachary Turnerc00cf4a2014-08-15 22:04:21 +000030#include "lldb/Utility/CleanUp.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000031#include "lldb/Utility/RegularExpression.h"
32#include "lldb/Utility/Stream.h"
33#include "lldb/Utility/StreamString.h"
Zachary Turnerc00cf4a2014-08-15 22:04:21 +000034
Zachary Turnerfe83ad82016-09-27 20:48:37 +000035#include "llvm/ADT/StringExtras.h"
Caroline Tice391a9602010-09-12 00:10:52 +000036#include "llvm/ADT/StringRef.h"
Zachary Turner190fadc2016-03-22 17:58:09 +000037#include "llvm/Support/ConvertUTF.h"
Zachary Turner3f559742014-08-07 17:33:36 +000038#include "llvm/Support/FileSystem.h"
Greg Clayton38a61402010-12-02 23:20:03 +000039#include "llvm/Support/Path.h"
40#include "llvm/Support/Program.h"
Caroline Tice391a9602010-09-12 00:10:52 +000041
Chris Lattner30fdc8d2010-06-08 16:52:24 +000042using namespace lldb;
43using namespace lldb_private;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000044
Chaoren Lin1c614fe2015-05-28 17:02:45 +000045namespace {
46
Kate Stoneb9c1b512016-09-06 20:57:50 +000047bool PathSyntaxIsPosix(FileSpec::PathSyntax syntax) {
48 return (syntax == FileSpec::ePathSyntaxPosix ||
49 (syntax == FileSpec::ePathSyntaxHostNative &&
50 FileSystem::GetNativePathSyntax() == FileSpec::ePathSyntaxPosix));
Chaoren Lin1c614fe2015-05-28 17:02:45 +000051}
52
Kate Stoneb9c1b512016-09-06 20:57:50 +000053const char *GetPathSeparators(FileSpec::PathSyntax syntax) {
54 return PathSyntaxIsPosix(syntax) ? "/" : "\\/";
Pavel Labath144119b2016-04-04 14:39:12 +000055}
56
Zachary Turnerfe83ad82016-09-27 20:48:37 +000057char GetPreferredPathSeparator(FileSpec::PathSyntax syntax) {
Kate Stoneb9c1b512016-09-06 20:57:50 +000058 return GetPathSeparators(syntax)[0];
Pavel Labath144119b2016-04-04 14:39:12 +000059}
60
Kate Stoneb9c1b512016-09-06 20:57:50 +000061bool IsPathSeparator(char value, FileSpec::PathSyntax syntax) {
62 return value == '/' || (!PathSyntaxIsPosix(syntax) && value == '\\');
Chaoren Lin1c614fe2015-05-28 17:02:45 +000063}
64
Kate Stoneb9c1b512016-09-06 20:57:50 +000065void Normalize(llvm::SmallVectorImpl<char> &path, FileSpec::PathSyntax syntax) {
66 if (PathSyntaxIsPosix(syntax))
67 return;
Chaoren Lin1c614fe2015-05-28 17:02:45 +000068
Kate Stoneb9c1b512016-09-06 20:57:50 +000069 std::replace(path.begin(), path.end(), '\\', '/');
70 // Windows path can have \\ slashes which can be changed by replace
71 // call above to //. Here we remove the duplicate.
72 auto iter = std::unique(path.begin(), path.end(), [](char &c1, char &c2) {
73 return (c1 == '/' && c2 == '/');
74 });
75 path.erase(iter, path.end());
Chaoren Lin1c614fe2015-05-28 17:02:45 +000076}
77
Kate Stoneb9c1b512016-09-06 20:57:50 +000078void Denormalize(llvm::SmallVectorImpl<char> &path,
79 FileSpec::PathSyntax syntax) {
80 if (PathSyntaxIsPosix(syntax))
81 return;
Chaoren Lin1c614fe2015-05-28 17:02:45 +000082
Kate Stoneb9c1b512016-09-06 20:57:50 +000083 std::replace(path.begin(), path.end(), '/', '\\');
Chaoren Lin1c614fe2015-05-28 17:02:45 +000084}
85
Kate Stoneb9c1b512016-09-06 20:57:50 +000086bool GetFileStats(const FileSpec *file_spec, struct stat *stats_ptr) {
87 char resolved_path[PATH_MAX];
88 if (file_spec->GetPath(resolved_path, sizeof(resolved_path)))
89 return FileSystem::Stat(resolved_path, stats_ptr) == 0;
90 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000091}
92
Kate Stoneb9c1b512016-09-06 20:57:50 +000093size_t FilenamePos(llvm::StringRef str, FileSpec::PathSyntax syntax) {
94 if (str.size() == 2 && IsPathSeparator(str[0], syntax) && str[0] == str[1])
95 return 0;
Pavel Labath144119b2016-04-04 14:39:12 +000096
Kate Stoneb9c1b512016-09-06 20:57:50 +000097 if (str.size() > 0 && IsPathSeparator(str.back(), syntax))
98 return str.size() - 1;
Pavel Labath144119b2016-04-04 14:39:12 +000099
Kate Stoneb9c1b512016-09-06 20:57:50 +0000100 size_t pos = str.find_last_of(GetPathSeparators(syntax), str.size() - 1);
Pavel Labath144119b2016-04-04 14:39:12 +0000101
Kate Stoneb9c1b512016-09-06 20:57:50 +0000102 if (!PathSyntaxIsPosix(syntax) && pos == llvm::StringRef::npos)
103 pos = str.find_last_of(':', str.size() - 2);
Pavel Labath144119b2016-04-04 14:39:12 +0000104
Kate Stoneb9c1b512016-09-06 20:57:50 +0000105 if (pos == llvm::StringRef::npos ||
106 (pos == 1 && IsPathSeparator(str[0], syntax)))
107 return 0;
Pavel Labath144119b2016-04-04 14:39:12 +0000108
Kate Stoneb9c1b512016-09-06 20:57:50 +0000109 return pos + 1;
Chaoren Lin1c614fe2015-05-28 17:02:45 +0000110}
111
Kate Stoneb9c1b512016-09-06 20:57:50 +0000112size_t RootDirStart(llvm::StringRef str, FileSpec::PathSyntax syntax) {
113 // case "c:/"
114 if (!PathSyntaxIsPosix(syntax) &&
115 (str.size() > 2 && str[1] == ':' && IsPathSeparator(str[2], syntax)))
116 return 2;
Pavel Labath144119b2016-04-04 14:39:12 +0000117
Kate Stoneb9c1b512016-09-06 20:57:50 +0000118 // case "//"
119 if (str.size() == 2 && IsPathSeparator(str[0], syntax) && str[0] == str[1])
Pavel Labath144119b2016-04-04 14:39:12 +0000120 return llvm::StringRef::npos;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000121
122 // case "//net"
123 if (str.size() > 3 && IsPathSeparator(str[0], syntax) && str[0] == str[1] &&
124 !IsPathSeparator(str[2], syntax))
125 return str.find_first_of(GetPathSeparators(syntax), 2);
126
127 // case "/"
128 if (str.size() > 0 && IsPathSeparator(str[0], syntax))
129 return 0;
130
131 return llvm::StringRef::npos;
Pavel Labath144119b2016-04-04 14:39:12 +0000132}
133
Kate Stoneb9c1b512016-09-06 20:57:50 +0000134size_t ParentPathEnd(llvm::StringRef path, FileSpec::PathSyntax syntax) {
135 size_t end_pos = FilenamePos(path, syntax);
Pavel Labath144119b2016-04-04 14:39:12 +0000136
Kate Stoneb9c1b512016-09-06 20:57:50 +0000137 bool filename_was_sep =
138 path.size() > 0 && IsPathSeparator(path[end_pos], syntax);
Pavel Labath144119b2016-04-04 14:39:12 +0000139
Kate Stoneb9c1b512016-09-06 20:57:50 +0000140 // Skip separators except for root dir.
141 size_t root_dir_pos = RootDirStart(path.substr(0, end_pos), syntax);
Pavel Labath144119b2016-04-04 14:39:12 +0000142
Kate Stoneb9c1b512016-09-06 20:57:50 +0000143 while (end_pos > 0 && (end_pos - 1) != root_dir_pos &&
144 IsPathSeparator(path[end_pos - 1], syntax))
145 --end_pos;
Pavel Labath144119b2016-04-04 14:39:12 +0000146
Kate Stoneb9c1b512016-09-06 20:57:50 +0000147 if (end_pos == 1 && root_dir_pos == 0 && filename_was_sep)
148 return llvm::StringRef::npos;
Pavel Labath144119b2016-04-04 14:39:12 +0000149
Kate Stoneb9c1b512016-09-06 20:57:50 +0000150 return end_pos;
Pavel Labath144119b2016-04-04 14:39:12 +0000151}
152
153} // end anonymous namespace
154
Jim Inghamf818ca32010-07-01 01:48:53 +0000155// Resolves the username part of a path of the form ~user/other/directories, and
Kate Stoneb9c1b512016-09-06 20:57:50 +0000156// writes the result into dst_path. This will also resolve "~" to the current
157// user.
158// If you want to complete "~" to the list of users, pass it to
159// ResolvePartialUsername.
160void FileSpec::ResolveUsername(llvm::SmallVectorImpl<char> &path) {
Zachary Turner3f559742014-08-07 17:33:36 +0000161#if LLDB_CONFIG_TILDE_RESOLVES_TO_USER
Kate Stoneb9c1b512016-09-06 20:57:50 +0000162 if (path.empty() || path[0] != '~')
163 return;
Zachary Turner3f559742014-08-07 17:33:36 +0000164
Kate Stoneb9c1b512016-09-06 20:57:50 +0000165 llvm::StringRef path_str(path.data(), path.size());
166 size_t slash_pos = path_str.find('/', 1);
167 if (slash_pos == 1 || path.size() == 1) {
168 // A path of ~/ resolves to the current user's home dir
169 llvm::SmallString<64> home_dir;
170 // llvm::sys::path::home_directory() only checks if "HOME" is set in the
171 // environment and does nothing else to locate the user home directory
172 if (!llvm::sys::path::home_directory(home_dir)) {
173 struct passwd *pw = getpwuid(getuid());
174 if (pw && pw->pw_dir && pw->pw_dir[0]) {
175 // Update our environemnt so llvm::sys::path::home_directory() works
176 // next time
177 setenv("HOME", pw->pw_dir, 0);
178 home_dir.assign(llvm::StringRef(pw->pw_dir));
179 } else {
180 return;
181 }
Jim Inghamf818ca32010-07-01 01:48:53 +0000182 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000183
184 // Overwrite the ~ with the first character of the homedir, and insert
185 // the rest. This way we only trigger one move, whereas an insert
186 // followed by a delete (or vice versa) would trigger two.
187 path[0] = home_dir[0];
188 path.insert(path.begin() + 1, home_dir.begin() + 1, home_dir.end());
189 return;
190 }
191
192 auto username_begin = path.begin() + 1;
193 auto username_end = (slash_pos == llvm::StringRef::npos)
194 ? path.end()
195 : (path.begin() + slash_pos);
196 size_t replacement_length = std::distance(path.begin(), username_end);
197
198 llvm::SmallString<20> username(username_begin, username_end);
199 struct passwd *user_entry = ::getpwnam(username.c_str());
200 if (user_entry != nullptr) {
201 // Copy over the first n characters of the path, where n is the smaller of
202 // the length
203 // of the home directory and the slash pos.
204 llvm::StringRef homedir(user_entry->pw_dir);
205 size_t initial_copy_length = std::min(homedir.size(), replacement_length);
206 auto src_begin = homedir.begin();
207 auto src_end = src_begin + initial_copy_length;
208 std::copy(src_begin, src_end, path.begin());
209 if (replacement_length > homedir.size()) {
210 // We copied the entire home directory, but the ~username portion of the
211 // path was
212 // longer, so there's characters that need to be removed.
213 path.erase(path.begin() + initial_copy_length, username_end);
214 } else if (replacement_length < homedir.size()) {
215 // We copied all the way up to the slash in the destination, but there's
216 // still more
217 // characters that need to be inserted.
218 path.insert(username_end, src_end, homedir.end());
Jim Inghamf818ca32010-07-01 01:48:53 +0000219 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000220 } else {
221 // Unable to resolve username (user doesn't exist?)
222 path.clear();
223 }
Zachary Turner3f559742014-08-07 17:33:36 +0000224#endif
Jim Inghamf818ca32010-07-01 01:48:53 +0000225}
226
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000227size_t FileSpec::ResolvePartialUsername(llvm::StringRef partial_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000228 StringList &matches) {
Jim Ingham84363072011-02-08 23:24:09 +0000229#ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
Kate Stoneb9c1b512016-09-06 20:57:50 +0000230 size_t extant_entries = matches.GetSize();
231
232 setpwent();
233 struct passwd *user_entry;
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000234 partial_name = partial_name.drop_front();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000235 std::set<std::string> name_list;
236
237 while ((user_entry = getpwent()) != NULL) {
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000238 if (llvm::StringRef(user_entry->pw_name).startswith(partial_name)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000239 std::string tmp_buf("~");
240 tmp_buf.append(user_entry->pw_name);
241 tmp_buf.push_back('/');
242 name_list.insert(tmp_buf);
Jim Ingham84363072011-02-08 23:24:09 +0000243 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000244 }
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000245
246 for (auto &name : name_list) {
247 matches.AppendString(name);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000248 }
249 return matches.GetSize() - extant_entries;
Jim Ingham84363072011-02-08 23:24:09 +0000250#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000251 // Resolving home directories is not supported, just copy the path...
252 return 0;
253#endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
Jim Ingham84363072011-02-08 23:24:09 +0000254}
255
Kate Stoneb9c1b512016-09-06 20:57:50 +0000256void FileSpec::Resolve(llvm::SmallVectorImpl<char> &path) {
257 if (path.empty())
258 return;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000259
Greg Clayton45319462011-02-08 00:35:34 +0000260#ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
Kate Stoneb9c1b512016-09-06 20:57:50 +0000261 if (path[0] == '~')
262 ResolveUsername(path);
Greg Clayton45319462011-02-08 00:35:34 +0000263#endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000264
Kate Stoneb9c1b512016-09-06 20:57:50 +0000265 // Save a copy of the original path that's passed in
266 llvm::SmallString<128> original_path(path.begin(), path.end());
Jason Molenda671a29d2015-02-25 02:35:25 +0000267
Kate Stoneb9c1b512016-09-06 20:57:50 +0000268 llvm::sys::fs::make_absolute(path);
269 if (!llvm::sys::fs::exists(path)) {
270 path.clear();
271 path.append(original_path.begin(), original_path.end());
272 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000273}
274
Sam McCall6f43d9d2016-11-15 10:58:16 +0000275FileSpec::FileSpec() : m_syntax(FileSystem::GetNativePathSyntax()) {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000276
277//------------------------------------------------------------------
278// Default constructor that can take an optional full path to a
279// file on disk.
280//------------------------------------------------------------------
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000281FileSpec::FileSpec(llvm::StringRef path, bool resolve_path, PathSyntax syntax)
Sam McCall6f43d9d2016-11-15 10:58:16 +0000282 : m_syntax(syntax) {
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000283 SetFile(path, resolve_path, syntax);
Jim Ingham0909e5f2010-09-16 00:57:33 +0000284}
285
Zachary Turner8c6b5462017-03-06 23:42:44 +0000286FileSpec::FileSpec(llvm::StringRef path, bool resolve_path,
287 const llvm::Triple &Triple)
288 : FileSpec{path, resolve_path,
289 Triple.isOSWindows() ? ePathSyntaxWindows : ePathSyntaxPosix} {}
Chaoren Linf34f4102015-05-09 01:21:32 +0000290
Jim Ingham0909e5f2010-09-16 00:57:33 +0000291//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000292// Copy constructor
293//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000294FileSpec::FileSpec(const FileSpec &rhs)
295 : m_directory(rhs.m_directory), m_filename(rhs.m_filename),
296 m_is_resolved(rhs.m_is_resolved), m_syntax(rhs.m_syntax) {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000297
298//------------------------------------------------------------------
299// Copy constructor
300//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000301FileSpec::FileSpec(const FileSpec *rhs) : m_directory(), m_filename() {
302 if (rhs)
303 *this = *rhs;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000304}
305
306//------------------------------------------------------------------
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +0000307// Virtual destructor in case anyone inherits from this class.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000308//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000309FileSpec::~FileSpec() {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000310
311//------------------------------------------------------------------
312// Assignment operator.
313//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000314const FileSpec &FileSpec::operator=(const FileSpec &rhs) {
315 if (this != &rhs) {
316 m_directory = rhs.m_directory;
317 m_filename = rhs.m_filename;
318 m_is_resolved = rhs.m_is_resolved;
319 m_syntax = rhs.m_syntax;
320 }
321 return *this;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000322}
323
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000324//------------------------------------------------------------------
325// Update the contents of this object with a new path. The path will
326// be split up into a directory and filename and stored as uniqued
327// string values for quick comparison and efficient memory usage.
328//------------------------------------------------------------------
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000329void FileSpec::SetFile(llvm::StringRef pathname, bool resolve,
330 PathSyntax syntax) {
331 // CLEANUP: Use StringRef for string handling. This function is kind of a
332 // mess and the unclear semantics of RootDirStart and ParentPathEnd make
333 // it very difficult to understand this function. There's no reason this
334 // function should be particularly complicated or difficult to understand.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000335 m_filename.Clear();
336 m_directory.Clear();
337 m_is_resolved = false;
338 m_syntax = (syntax == ePathSyntaxHostNative)
339 ? FileSystem::GetNativePathSyntax()
340 : syntax;
Zachary Turnerdf62f202014-08-07 17:33:07 +0000341
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000342 if (pathname.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000343 return;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000344
Kate Stoneb9c1b512016-09-06 20:57:50 +0000345 llvm::SmallString<64> resolved(pathname);
Zachary Turnerdf62f202014-08-07 17:33:07 +0000346
Kate Stoneb9c1b512016-09-06 20:57:50 +0000347 if (resolve) {
348 FileSpec::Resolve(resolved);
349 m_is_resolved = true;
350 }
Zachary Turnerc7a17ed2014-12-01 23:13:32 +0000351
Zachary Turner827d5d72016-12-16 04:27:00 +0000352 Normalize(resolved, m_syntax);
Pavel Labatha212c582016-04-14 09:38:06 +0000353
Kate Stoneb9c1b512016-09-06 20:57:50 +0000354 llvm::StringRef resolve_path_ref(resolved.c_str());
Zachary Turner827d5d72016-12-16 04:27:00 +0000355 size_t dir_end = ParentPathEnd(resolve_path_ref, m_syntax);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000356 if (dir_end == 0) {
357 m_filename.SetString(resolve_path_ref);
358 return;
359 }
Pavel Labath144119b2016-04-04 14:39:12 +0000360
Kate Stoneb9c1b512016-09-06 20:57:50 +0000361 m_directory.SetString(resolve_path_ref.substr(0, dir_end));
Pavel Labath144119b2016-04-04 14:39:12 +0000362
Kate Stoneb9c1b512016-09-06 20:57:50 +0000363 size_t filename_begin = dir_end;
Zachary Turner827d5d72016-12-16 04:27:00 +0000364 size_t root_dir_start = RootDirStart(resolve_path_ref, m_syntax);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000365 while (filename_begin != llvm::StringRef::npos &&
366 filename_begin < resolve_path_ref.size() &&
367 filename_begin != root_dir_start &&
Zachary Turner827d5d72016-12-16 04:27:00 +0000368 IsPathSeparator(resolve_path_ref[filename_begin], m_syntax))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000369 ++filename_begin;
370 m_filename.SetString((filename_begin == llvm::StringRef::npos ||
371 filename_begin >= resolve_path_ref.size())
372 ? "."
373 : resolve_path_ref.substr(filename_begin));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000374}
375
Zachary Turner8c6b5462017-03-06 23:42:44 +0000376void FileSpec::SetFile(llvm::StringRef path, bool resolve,
377 const llvm::Triple &Triple) {
378 return SetFile(path, resolve,
379 Triple.isOSWindows() ? ePathSyntaxWindows : ePathSyntaxPosix);
Chaoren Lin44145d72015-05-29 19:52:37 +0000380}
381
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000382//----------------------------------------------------------------------
383// Convert to pointer operator. This allows code to check any FileSpec
384// objects to see if they contain anything valid using code such as:
385//
386// if (file_spec)
387// {}
388//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000389FileSpec::operator bool() const { return m_filename || m_directory; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000390
391//----------------------------------------------------------------------
392// Logical NOT operator. This allows code to check any FileSpec
393// objects to see if they are invalid using code such as:
394//
395// if (!file_spec)
396// {}
397//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000398bool FileSpec::operator!() const { return !m_directory && !m_filename; }
399
400bool FileSpec::DirectoryEquals(const FileSpec &rhs) const {
401 const bool case_sensitive = IsCaseSensitive() || rhs.IsCaseSensitive();
402 return ConstString::Equals(m_directory, rhs.m_directory, case_sensitive);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000403}
404
Kate Stoneb9c1b512016-09-06 20:57:50 +0000405bool FileSpec::FileEquals(const FileSpec &rhs) const {
406 const bool case_sensitive = IsCaseSensitive() || rhs.IsCaseSensitive();
407 return ConstString::Equals(m_filename, rhs.m_filename, case_sensitive);
Zachary Turner74e08ca2016-03-02 22:05:52 +0000408}
409
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000410//------------------------------------------------------------------
411// Equal to operator
412//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000413bool FileSpec::operator==(const FileSpec &rhs) const {
414 if (!FileEquals(rhs))
415 return false;
416 if (DirectoryEquals(rhs))
417 return true;
Zachary Turner47c03462016-02-24 21:26:47 +0000418
Kate Stoneb9c1b512016-09-06 20:57:50 +0000419 // TODO: determine if we want to keep this code in here.
420 // The code below was added to handle a case where we were
421 // trying to set a file and line breakpoint and one path
422 // was resolved, and the other not and the directory was
423 // in a mount point that resolved to a more complete path:
424 // "/tmp/a.c" == "/private/tmp/a.c". I might end up pulling
425 // this out...
426 if (IsResolved() && rhs.IsResolved()) {
427 // Both paths are resolved, no need to look further...
428 return false;
429 }
Zachary Turner47c03462016-02-24 21:26:47 +0000430
Kate Stoneb9c1b512016-09-06 20:57:50 +0000431 FileSpec resolved_lhs(*this);
Zachary Turner47c03462016-02-24 21:26:47 +0000432
Kate Stoneb9c1b512016-09-06 20:57:50 +0000433 // If "this" isn't resolved, resolve it
434 if (!IsResolved()) {
435 if (resolved_lhs.ResolvePath()) {
436 // This path wasn't resolved but now it is. Check if the resolved
437 // directory is the same as our unresolved directory, and if so,
438 // we can mark this object as resolved to avoid more future resolves
439 m_is_resolved = (m_directory == resolved_lhs.m_directory);
440 } else
441 return false;
442 }
Zachary Turner47c03462016-02-24 21:26:47 +0000443
Kate Stoneb9c1b512016-09-06 20:57:50 +0000444 FileSpec resolved_rhs(rhs);
445 if (!rhs.IsResolved()) {
446 if (resolved_rhs.ResolvePath()) {
447 // rhs's path wasn't resolved but now it is. Check if the resolved
448 // directory is the same as rhs's unresolved directory, and if so,
449 // we can mark this object as resolved to avoid more future resolves
450 rhs.m_is_resolved = (rhs.m_directory == resolved_rhs.m_directory);
451 } else
452 return false;
453 }
Zachary Turner47c03462016-02-24 21:26:47 +0000454
Kate Stoneb9c1b512016-09-06 20:57:50 +0000455 // If we reach this point in the code we were able to resolve both paths
456 // and since we only resolve the paths if the basenames are equal, then
457 // we can just check if both directories are equal...
458 return DirectoryEquals(rhs);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000459}
460
461//------------------------------------------------------------------
462// Not equal to operator
463//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000464bool FileSpec::operator!=(const FileSpec &rhs) const { return !(*this == rhs); }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000465
466//------------------------------------------------------------------
467// Less than operator
468//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000469bool FileSpec::operator<(const FileSpec &rhs) const {
470 return FileSpec::Compare(*this, rhs, true) < 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000471}
472
473//------------------------------------------------------------------
474// Dump a FileSpec object to a stream
475//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000476Stream &lldb_private::operator<<(Stream &s, const FileSpec &f) {
477 f.Dump(&s);
478 return s;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000479}
480
481//------------------------------------------------------------------
482// Clear this object by releasing both the directory and filename
483// string values and making them both the empty string.
484//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000485void FileSpec::Clear() {
486 m_directory.Clear();
487 m_filename.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000488}
489
490//------------------------------------------------------------------
491// Compare two FileSpec objects. If "full" is true, then both
492// the directory and the filename must match. If "full" is false,
493// then the directory names for "a" and "b" are only compared if
494// they are both non-empty. This allows a FileSpec object to only
495// contain a filename and it can match FileSpec objects that have
496// matching filenames with different paths.
497//
498// Return -1 if the "a" is less than "b", 0 if "a" is equal to "b"
499// and "1" if "a" is greater than "b".
500//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000501int FileSpec::Compare(const FileSpec &a, const FileSpec &b, bool full) {
502 int result = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000503
Kate Stoneb9c1b512016-09-06 20:57:50 +0000504 // case sensitivity of compare
505 const bool case_sensitive = a.IsCaseSensitive() || b.IsCaseSensitive();
Zachary Turner47c03462016-02-24 21:26:47 +0000506
Kate Stoneb9c1b512016-09-06 20:57:50 +0000507 // If full is true, then we must compare both the directory and filename.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000508
Kate Stoneb9c1b512016-09-06 20:57:50 +0000509 // If full is false, then if either directory is empty, then we match on
510 // the basename only, and if both directories have valid values, we still
511 // do a full compare. This allows for matching when we just have a filename
512 // in one of the FileSpec objects.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000513
Kate Stoneb9c1b512016-09-06 20:57:50 +0000514 if (full || (a.m_directory && b.m_directory)) {
515 result = ConstString::Compare(a.m_directory, b.m_directory, case_sensitive);
516 if (result)
517 return result;
518 }
519 return ConstString::Compare(a.m_filename, b.m_filename, case_sensitive);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000520}
521
Kate Stoneb9c1b512016-09-06 20:57:50 +0000522bool FileSpec::Equal(const FileSpec &a, const FileSpec &b, bool full,
523 bool remove_backups) {
524 // case sensitivity of equality test
525 const bool case_sensitive = a.IsCaseSensitive() || b.IsCaseSensitive();
Zachary Turner47c03462016-02-24 21:26:47 +0000526
Kate Stoneb9c1b512016-09-06 20:57:50 +0000527 if (!full && (a.GetDirectory().IsEmpty() || b.GetDirectory().IsEmpty()))
528 return ConstString::Equals(a.m_filename, b.m_filename, case_sensitive);
Pavel Labath218770b2016-10-31 16:22:07 +0000529
530 if (remove_backups == false)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000531 return a == b;
Jim Ingham96a15962014-11-15 01:54:26 +0000532
Pavel Labath218770b2016-10-31 16:22:07 +0000533 if (a == b)
534 return true;
535
536 return Equal(a.GetNormalizedPath(), b.GetNormalizedPath(), full, false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000537}
538
Pavel Labath218770b2016-10-31 16:22:07 +0000539FileSpec FileSpec::GetNormalizedPath() const {
540 // Fast path. Do nothing if the path is not interesting.
541 if (!m_directory.GetStringRef().contains(".") &&
Pavel Labathe6e7e6c2016-11-30 16:08:45 +0000542 !m_directory.GetStringRef().contains("//") &&
543 m_filename.GetStringRef() != ".." && m_filename.GetStringRef() != ".")
Pavel Labath218770b2016-10-31 16:22:07 +0000544 return *this;
Greg Clayton5a271952015-06-02 22:43:29 +0000545
Pavel Labath218770b2016-10-31 16:22:07 +0000546 llvm::SmallString<64> path, result;
547 const bool normalize = false;
548 GetPath(path, normalize);
549 llvm::StringRef rest(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000550
Pavel Labath218770b2016-10-31 16:22:07 +0000551 // We will not go below root dir.
552 size_t root_dir_start = RootDirStart(path, m_syntax);
553 const bool absolute = root_dir_start != llvm::StringRef::npos;
554 if (absolute) {
555 result += rest.take_front(root_dir_start + 1);
556 rest = rest.drop_front(root_dir_start + 1);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000557 } else {
Pavel Labath218770b2016-10-31 16:22:07 +0000558 if (m_syntax == ePathSyntaxWindows && path.size() > 2 && path[1] == ':') {
559 result += rest.take_front(2);
560 rest = rest.drop_front(2);
561 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000562 }
563
Pavel Labath218770b2016-10-31 16:22:07 +0000564 bool anything_added = false;
565 llvm::SmallVector<llvm::StringRef, 0> components, processed;
566 rest.split(components, '/', -1, false);
567 processed.reserve(components.size());
568 for (auto component : components) {
569 if (component == ".")
570 continue; // Skip these.
571 if (component != "..") {
572 processed.push_back(component);
573 continue; // Regular file name.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000574 }
Pavel Labath218770b2016-10-31 16:22:07 +0000575 if (!processed.empty()) {
576 processed.pop_back();
577 continue; // Dots. Go one level up if we can.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000578 }
Pavel Labath218770b2016-10-31 16:22:07 +0000579 if (absolute)
580 continue; // We're at the top level. Cannot go higher than that. Skip.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000581
Pavel Labath218770b2016-10-31 16:22:07 +0000582 result += component; // We're a relative path. We need to keep these.
583 result += '/';
584 anything_added = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000585 }
Pavel Labath218770b2016-10-31 16:22:07 +0000586 for (auto component : processed) {
587 result += component;
588 result += '/';
589 anything_added = true;
590 }
591 if (anything_added)
592 result.pop_back(); // Pop last '/'.
593 else if (result.empty())
594 result = ".";
Kate Stoneb9c1b512016-09-06 20:57:50 +0000595
Pavel Labath218770b2016-10-31 16:22:07 +0000596 return FileSpec(result, false, m_syntax);
Jim Ingham96a15962014-11-15 01:54:26 +0000597}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000598
599//------------------------------------------------------------------
600// Dump the object to the supplied stream. If the object contains
601// a valid directory name, it will be displayed followed by a
602// directory delimiter, and the filename.
603//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000604void FileSpec::Dump(Stream *s) const {
605 if (s) {
606 std::string path{GetPath(true)};
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000607 s->PutCString(path);
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000608 char path_separator = GetPreferredPathSeparator(m_syntax);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000609 if (!m_filename && !path.empty() && path.back() != path_separator)
610 s->PutChar(path_separator);
611 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000612}
613
614//------------------------------------------------------------------
615// Returns true if the file exists.
616//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000617bool FileSpec::Exists() const {
618 struct stat file_stats;
619 return GetFileStats(this, &file_stats);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000620}
621
Kate Stoneb9c1b512016-09-06 20:57:50 +0000622bool FileSpec::Readable() const {
623 const uint32_t permissions = GetPermissions();
624 if (permissions & eFilePermissionsEveryoneR)
625 return true;
626 return false;
Greg Clayton5acc1252014-08-15 18:00:45 +0000627}
628
Kate Stoneb9c1b512016-09-06 20:57:50 +0000629bool FileSpec::ResolveExecutableLocation() {
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000630 // CLEANUP: Use StringRef for string handling.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000631 if (!m_directory) {
632 const char *file_cstr = m_filename.GetCString();
633 if (file_cstr) {
634 const std::string file_str(file_cstr);
635 llvm::ErrorOr<std::string> error_or_path =
636 llvm::sys::findProgramByName(file_str);
637 if (!error_or_path)
Jim Ingham0909e5f2010-09-16 00:57:33 +0000638 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000639 std::string path = error_or_path.get();
640 llvm::StringRef dir_ref = llvm::sys::path::parent_path(path);
641 if (!dir_ref.empty()) {
642 // FindProgramByName returns "." if it can't find the file.
643 if (strcmp(".", dir_ref.data()) == 0)
644 return false;
645
646 m_directory.SetCString(dir_ref.data());
647 if (Exists())
648 return true;
649 else {
650 // If FindProgramByName found the file, it returns the directory +
651 // filename in its return results.
652 // We need to separate them.
653 FileSpec tmp_file(dir_ref.data(), false);
654 if (tmp_file.Exists()) {
655 m_directory = tmp_file.m_directory;
656 return true;
657 }
658 }
659 }
660 }
661 }
662
663 return false;
Jim Ingham0909e5f2010-09-16 00:57:33 +0000664}
665
Kate Stoneb9c1b512016-09-06 20:57:50 +0000666bool FileSpec::ResolvePath() {
667 if (m_is_resolved)
668 return true; // We have already resolved this path
669
670 char path_buf[PATH_MAX];
671 if (!GetPath(path_buf, PATH_MAX, false))
672 return false;
673 // SetFile(...) will set m_is_resolved correctly if it can resolve the path
674 SetFile(path_buf, true);
675 return m_is_resolved;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000676}
677
Kate Stoneb9c1b512016-09-06 20:57:50 +0000678uint64_t FileSpec::GetByteSize() const {
679 struct stat file_stats;
680 if (GetFileStats(this, &file_stats))
681 return file_stats.st_size;
682 return 0;
Zachary Turnerdf62f202014-08-07 17:33:07 +0000683}
684
Kate Stoneb9c1b512016-09-06 20:57:50 +0000685FileSpec::PathSyntax FileSpec::GetPathSyntax() const { return m_syntax; }
686
687FileSpec::FileType FileSpec::GetFileType() const {
688 struct stat file_stats;
689 if (GetFileStats(this, &file_stats)) {
690 mode_t file_type = file_stats.st_mode & S_IFMT;
691 switch (file_type) {
692 case S_IFDIR:
693 return eFileTypeDirectory;
694 case S_IFREG:
695 return eFileTypeRegular;
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000696#ifndef _WIN32
Kate Stoneb9c1b512016-09-06 20:57:50 +0000697 case S_IFIFO:
698 return eFileTypePipe;
699 case S_IFSOCK:
700 return eFileTypeSocket;
701 case S_IFLNK:
702 return eFileTypeSymbolicLink;
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000703#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000704 default:
705 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000706 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000707 return eFileTypeUnknown;
708 }
709 return eFileTypeInvalid;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000710}
711
Kate Stoneb9c1b512016-09-06 20:57:50 +0000712bool FileSpec::IsSymbolicLink() const {
713 char resolved_path[PATH_MAX];
714 if (!GetPath(resolved_path, sizeof(resolved_path)))
715 return false;
Oleksiy Vyalov8a578bf2015-07-21 01:28:22 +0000716
717#ifdef _WIN32
Kate Stoneb9c1b512016-09-06 20:57:50 +0000718 std::wstring wpath;
719 if (!llvm::ConvertUTF8toWide(resolved_path, wpath))
720 return false;
721 auto attrs = ::GetFileAttributesW(wpath.c_str());
722 if (attrs == INVALID_FILE_ATTRIBUTES)
723 return false;
Oleksiy Vyalov8a578bf2015-07-21 01:28:22 +0000724
Kate Stoneb9c1b512016-09-06 20:57:50 +0000725 return (attrs & FILE_ATTRIBUTE_REPARSE_POINT);
Oleksiy Vyalov8a578bf2015-07-21 01:28:22 +0000726#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000727 struct stat file_stats;
728 if (::lstat(resolved_path, &file_stats) != 0)
729 return false;
Oleksiy Vyalov8a578bf2015-07-21 01:28:22 +0000730
Kate Stoneb9c1b512016-09-06 20:57:50 +0000731 return (file_stats.st_mode & S_IFMT) == S_IFLNK;
Oleksiy Vyalov8a578bf2015-07-21 01:28:22 +0000732#endif
733}
734
Kate Stoneb9c1b512016-09-06 20:57:50 +0000735uint32_t FileSpec::GetPermissions() const {
736 uint32_t file_permissions = 0;
737 if (*this)
738 FileSystem::GetFilePermissions(*this, file_permissions);
739 return file_permissions;
Greg Claytonfbb76342013-11-20 21:07:01 +0000740}
741
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000742//------------------------------------------------------------------
743// Directory string get accessor.
744//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000745ConstString &FileSpec::GetDirectory() { return m_directory; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000746
747//------------------------------------------------------------------
748// Directory string const get accessor.
749//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000750const ConstString &FileSpec::GetDirectory() const { return m_directory; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000751
752//------------------------------------------------------------------
753// Filename string get accessor.
754//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000755ConstString &FileSpec::GetFilename() { return m_filename; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000756
757//------------------------------------------------------------------
758// Filename string const get accessor.
759//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000760const ConstString &FileSpec::GetFilename() const { return m_filename; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000761
762//------------------------------------------------------------------
763// Extract the directory and path into a fixed buffer. This is
764// needed as the directory and path are stored in separate string
765// values.
766//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000767size_t FileSpec::GetPath(char *path, size_t path_max_len,
768 bool denormalize) const {
769 if (!path)
770 return 0;
Zachary Turnerb6d99242014-08-08 23:54:35 +0000771
Kate Stoneb9c1b512016-09-06 20:57:50 +0000772 std::string result = GetPath(denormalize);
773 ::snprintf(path, path_max_len, "%s", result.c_str());
774 return std::min(path_max_len - 1, result.length());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000775}
776
Kate Stoneb9c1b512016-09-06 20:57:50 +0000777std::string FileSpec::GetPath(bool denormalize) const {
778 llvm::SmallString<64> result;
779 GetPath(result, denormalize);
780 return std::string(result.begin(), result.end());
Jason Molendaa7ae4672013-04-29 09:46:43 +0000781}
782
Kate Stoneb9c1b512016-09-06 20:57:50 +0000783const char *FileSpec::GetCString(bool denormalize) const {
784 return ConstString{GetPath(denormalize)}.AsCString(NULL);
Chaoren Lind3173f32015-05-29 19:52:29 +0000785}
786
Kate Stoneb9c1b512016-09-06 20:57:50 +0000787void FileSpec::GetPath(llvm::SmallVectorImpl<char> &path,
788 bool denormalize) const {
789 path.append(m_directory.GetStringRef().begin(),
790 m_directory.GetStringRef().end());
791 if (m_directory && m_filename &&
792 !IsPathSeparator(m_directory.GetStringRef().back(), m_syntax))
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000793 path.insert(path.end(), GetPreferredPathSeparator(m_syntax));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000794 path.append(m_filename.GetStringRef().begin(),
795 m_filename.GetStringRef().end());
796 Normalize(path, m_syntax);
797 if (denormalize && !path.empty())
798 Denormalize(path, m_syntax);
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000799}
800
Kate Stoneb9c1b512016-09-06 20:57:50 +0000801ConstString FileSpec::GetFileNameExtension() const {
802 if (m_filename) {
Enrico Granataa9dbf432011-10-17 21:45:27 +0000803 const char *filename = m_filename.GetCString();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000804 const char *dot_pos = strrchr(filename, '.');
805 if (dot_pos && dot_pos[1] != '\0')
806 return ConstString(dot_pos + 1);
807 }
808 return ConstString();
809}
810
811ConstString FileSpec::GetFileNameStrippingExtension() const {
812 const char *filename = m_filename.GetCString();
813 if (filename == NULL)
814 return ConstString();
815
816 const char *dot_pos = strrchr(filename, '.');
817 if (dot_pos == NULL)
818 return m_filename;
819
820 return ConstString(filename, dot_pos - filename);
Enrico Granataa9dbf432011-10-17 21:45:27 +0000821}
822
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000823//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000824// Return the size in bytes that this object takes in memory. This
825// returns the size in bytes of this object, not any shared string
826// values it may refer to.
827//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000828size_t FileSpec::MemorySize() const {
829 return m_filename.MemorySize() + m_directory.MemorySize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000830}
831
Greg Clayton4272cc72011-02-02 02:24:04 +0000832FileSpec::EnumerateDirectoryResult
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000833FileSpec::ForEachItemInDirectory(llvm::StringRef dir_path,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000834 DirectoryCallback const &callback) {
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000835 if (dir_path.empty())
836 return eEnumerateDirectoryResultNext;
837
Zachary Turner190fadc2016-03-22 17:58:09 +0000838#ifdef _WIN32
Kate Stoneb9c1b512016-09-06 20:57:50 +0000839 std::string szDir(dir_path);
840 szDir += "\\*";
Greg Clayton58c65f02015-06-29 18:29:00 +0000841
Kate Stoneb9c1b512016-09-06 20:57:50 +0000842 std::wstring wszDir;
843 if (!llvm::ConvertUTF8toWide(szDir, wszDir)) {
844 return eEnumerateDirectoryResultNext;
Greg Clayton58c65f02015-06-29 18:29:00 +0000845 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000846
847 WIN32_FIND_DATAW ffd;
848 HANDLE hFind = FindFirstFileW(wszDir.c_str(), &ffd);
849
850 if (hFind == INVALID_HANDLE_VALUE) {
851 return eEnumerateDirectoryResultNext;
852 }
853
854 do {
855 FileSpec::FileType file_type = eFileTypeUnknown;
856 if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
857 size_t len = wcslen(ffd.cFileName);
858
859 if (len == 1 && ffd.cFileName[0] == L'.')
860 continue;
861
862 if (len == 2 && ffd.cFileName[0] == L'.' && ffd.cFileName[1] == L'.')
863 continue;
864
865 file_type = eFileTypeDirectory;
866 } else if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DEVICE) {
867 file_type = eFileTypeOther;
868 } else {
869 file_type = eFileTypeRegular;
870 }
871
872 std::string fileName;
873 if (!llvm::convertWideToUTF8(ffd.cFileName, fileName)) {
874 continue;
875 }
876
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000877 std::string child_path = llvm::join_items("\\", dir_path, fileName);
878 // Don't resolve the file type or path
879 FileSpec child_path_spec(child_path.data(), false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000880
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000881 EnumerateDirectoryResult result = callback(file_type, child_path_spec);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000882
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000883 switch (result) {
884 case eEnumerateDirectoryResultNext:
885 // Enumerate next entry in the current directory. We just
886 // exit this switch and will continue enumerating the
887 // current directory as we currently are...
888 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000889
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000890 case eEnumerateDirectoryResultEnter: // Recurse into the current entry
891 // if it is a directory or symlink,
892 // or next if not
893 if (FileSpec::ForEachItemInDirectory(child_path.data(), callback) ==
894 eEnumerateDirectoryResultQuit) {
895 // The subdirectory returned Quit, which means to
896 // stop all directory enumerations at all levels.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000897 return eEnumerateDirectoryResultQuit;
898 }
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000899 break;
900
901 case eEnumerateDirectoryResultExit: // Exit from the current directory
902 // at the current level.
903 // Exit from this directory level and tell parent to
904 // keep enumerating.
905 return eEnumerateDirectoryResultNext;
906
907 case eEnumerateDirectoryResultQuit: // Stop directory enumerations at
908 // any level
909 return eEnumerateDirectoryResultQuit;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000910 }
911 } while (FindNextFileW(hFind, &ffd) != 0);
912
913 FindClose(hFind);
914#else
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000915 std::string dir_string(dir_path);
916 lldb_utility::CleanUp<DIR *, int> dir_path_dir(opendir(dir_string.c_str()),
917 NULL, closedir);
918 if (dir_path_dir.is_valid()) {
919 char dir_path_last_char = dir_path.back();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000920
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000921 long path_max = fpathconf(dirfd(dir_path_dir.get()), _PC_NAME_MAX);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000922#if defined(__APPLE_) && defined(__DARWIN_MAXPATHLEN)
923 if (path_max < __DARWIN_MAXPATHLEN)
924 path_max = __DARWIN_MAXPATHLEN;
925#endif
926 struct dirent *buf, *dp;
927 buf = (struct dirent *)malloc(offsetof(struct dirent, d_name) + path_max +
928 1);
929
930 while (buf && readdir_r(dir_path_dir.get(), buf, &dp) == 0 && dp) {
931 // Only search directories
932 if (dp->d_type == DT_DIR || dp->d_type == DT_UNKNOWN) {
933 size_t len = strlen(dp->d_name);
934
935 if (len == 1 && dp->d_name[0] == '.')
936 continue;
937
938 if (len == 2 && dp->d_name[0] == '.' && dp->d_name[1] == '.')
939 continue;
940 }
941
942 FileSpec::FileType file_type = eFileTypeUnknown;
943
944 switch (dp->d_type) {
945 default:
946 case DT_UNKNOWN:
947 file_type = eFileTypeUnknown;
948 break;
949 case DT_FIFO:
950 file_type = eFileTypePipe;
951 break;
952 case DT_CHR:
953 file_type = eFileTypeOther;
954 break;
955 case DT_DIR:
956 file_type = eFileTypeDirectory;
957 break;
958 case DT_BLK:
959 file_type = eFileTypeOther;
960 break;
961 case DT_REG:
962 file_type = eFileTypeRegular;
963 break;
964 case DT_LNK:
965 file_type = eFileTypeSymbolicLink;
966 break;
967 case DT_SOCK:
968 file_type = eFileTypeSocket;
969 break;
970#if !defined(__OpenBSD__)
971 case DT_WHT:
972 file_type = eFileTypeOther;
973 break;
974#endif
975 }
976
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000977 std::string child_path;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000978 // Don't make paths with "/foo//bar", that just confuses everybody.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000979 if (dir_path_last_char == '/')
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000980 child_path = llvm::join_items("", dir_path, dp->d_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000981 else
Zachary Turnerfe83ad82016-09-27 20:48:37 +0000982 child_path = llvm::join_items('/', dir_path, dp->d_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000983
Sylvestre Ledrub9b41a22017-02-16 18:45:27 +0000984 // Don't resolve the file type or path
985 FileSpec child_path_spec(child_path, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000986
Sylvestre Ledrub9b41a22017-02-16 18:45:27 +0000987 EnumerateDirectoryResult result =
988 callback(file_type, child_path_spec);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000989
Sylvestre Ledrub9b41a22017-02-16 18:45:27 +0000990 switch (result) {
991 case eEnumerateDirectoryResultNext:
992 // Enumerate next entry in the current directory. We just
993 // exit this switch and will continue enumerating the
994 // current directory as we currently are...
995 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000996
Sylvestre Ledrub9b41a22017-02-16 18:45:27 +0000997 case eEnumerateDirectoryResultEnter: // Recurse into the current entry
998 // if it is a directory or
999 // symlink, or next if not
1000 if (FileSpec::ForEachItemInDirectory(child_path, callback) ==
1001 eEnumerateDirectoryResultQuit) {
1002 // The subdirectory returned Quit, which means to
1003 // stop all directory enumerations at all levels.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001004 if (buf)
1005 free(buf);
1006 return eEnumerateDirectoryResultQuit;
1007 }
Sylvestre Ledrub9b41a22017-02-16 18:45:27 +00001008 break;
1009
1010 case eEnumerateDirectoryResultExit: // Exit from the current directory
1011 // at the current level.
1012 // Exit from this directory level and tell parent to
1013 // keep enumerating.
1014 if (buf)
1015 free(buf);
1016 return eEnumerateDirectoryResultNext;
1017
1018 case eEnumerateDirectoryResultQuit: // Stop directory enumerations at
1019 // any level
1020 if (buf)
1021 free(buf);
1022 return eEnumerateDirectoryResultQuit;
1023 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001024 }
1025 if (buf) {
1026 free(buf);
1027 }
1028 }
1029#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00001030 // By default when exiting a directory, we tell the parent enumeration
1031 // to continue enumerating.
1032 return eEnumerateDirectoryResultNext;
Greg Clayton58c65f02015-06-29 18:29:00 +00001033}
1034
1035FileSpec::EnumerateDirectoryResult
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001036FileSpec::EnumerateDirectory(llvm::StringRef dir_path, bool find_directories,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001037 bool find_files, bool find_other,
1038 EnumerateDirectoryCallbackType callback,
1039 void *callback_baton) {
1040 return ForEachItemInDirectory(
1041 dir_path,
1042 [&find_directories, &find_files, &find_other, &callback,
1043 &callback_baton](FileType file_type, const FileSpec &file_spec) {
1044 switch (file_type) {
1045 case FileType::eFileTypeDirectory:
1046 if (find_directories)
1047 return callback(callback_baton, file_type, file_spec);
1048 break;
1049 case FileType::eFileTypeRegular:
1050 if (find_files)
1051 return callback(callback_baton, file_type, file_spec);
1052 break;
1053 default:
1054 if (find_other)
1055 return callback(callback_baton, file_type, file_spec);
1056 break;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001057 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001058 return eEnumerateDirectoryResultNext;
1059 });
Daniel Maleae0f8f572013-08-26 23:57:52 +00001060}
1061
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001062FileSpec
1063FileSpec::CopyByAppendingPathComponent(llvm::StringRef component) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001064 FileSpec ret = *this;
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001065 ret.AppendPathComponent(component);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001066 return ret;
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001067}
1068
Kate Stoneb9c1b512016-09-06 20:57:50 +00001069FileSpec FileSpec::CopyByRemovingLastPathComponent() const {
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001070 // CLEANUP: Use StringRef for string handling.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001071 const bool resolve = false;
1072 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1073 return FileSpec("", resolve);
1074 if (m_directory.IsEmpty())
1075 return FileSpec("", resolve);
1076 if (m_filename.IsEmpty()) {
1077 const char *dir_cstr = m_directory.GetCString();
1078 const char *last_slash_ptr = ::strrchr(dir_cstr, '/');
1079
1080 // check for obvious cases before doing the full thing
1081 if (!last_slash_ptr)
1082 return FileSpec("", resolve);
1083 if (last_slash_ptr == dir_cstr)
1084 return FileSpec("/", resolve);
1085
1086 size_t last_slash_pos = last_slash_ptr - dir_cstr + 1;
1087 ConstString new_path(dir_cstr, last_slash_pos);
1088 return FileSpec(new_path.GetCString(), resolve);
1089 } else
1090 return FileSpec(m_directory.GetCString(), resolve);
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001091}
1092
Kate Stoneb9c1b512016-09-06 20:57:50 +00001093ConstString FileSpec::GetLastPathComponent() const {
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001094 // CLEANUP: Use StringRef for string handling.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001095 if (m_filename)
1096 return m_filename;
1097 if (m_directory) {
1098 const char *dir_cstr = m_directory.GetCString();
1099 const char *last_slash_ptr = ::strrchr(dir_cstr, '/');
1100 if (last_slash_ptr == NULL)
1101 return m_directory;
1102 if (last_slash_ptr == dir_cstr) {
1103 if (last_slash_ptr[1] == 0)
1104 return ConstString(last_slash_ptr);
1105 else
1106 return ConstString(last_slash_ptr + 1);
1107 }
1108 if (last_slash_ptr[1] != 0)
1109 return ConstString(last_slash_ptr + 1);
1110 const char *penultimate_slash_ptr = last_slash_ptr;
1111 while (*penultimate_slash_ptr) {
1112 --penultimate_slash_ptr;
1113 if (penultimate_slash_ptr == dir_cstr)
1114 break;
1115 if (*penultimate_slash_ptr == '/')
1116 break;
1117 }
1118 ConstString result(penultimate_slash_ptr + 1,
1119 last_slash_ptr - penultimate_slash_ptr);
1120 return result;
1121 }
1122 return ConstString();
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001123}
1124
Pavel Labath59d725c2017-01-16 10:07:02 +00001125static std::string
1126join_path_components(FileSpec::PathSyntax syntax,
1127 const std::vector<llvm::StringRef> components) {
1128 std::string result;
1129 for (size_t i = 0; i < components.size(); ++i) {
1130 if (components[i].empty())
1131 continue;
1132 result += components[i];
1133 if (i != components.size() - 1 &&
1134 !IsPathSeparator(components[i].back(), syntax))
1135 result += GetPreferredPathSeparator(syntax);
1136 }
1137
1138 return result;
1139}
1140
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001141void FileSpec::PrependPathComponent(llvm::StringRef component) {
1142 if (component.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001143 return;
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001144
Kate Stoneb9c1b512016-09-06 20:57:50 +00001145 const bool resolve = false;
1146 if (m_filename.IsEmpty() && m_directory.IsEmpty()) {
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001147 SetFile(component, resolve);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001148 return;
1149 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00001150
Pavel Labath59d725c2017-01-16 10:07:02 +00001151 std::string result =
1152 join_path_components(m_syntax, {component, m_directory.GetStringRef(),
1153 m_filename.GetStringRef()});
Pavel Labath238169d2017-01-16 12:15:42 +00001154 SetFile(result, resolve, m_syntax);
Chaoren Lind3173f32015-05-29 19:52:29 +00001155}
1156
Kate Stoneb9c1b512016-09-06 20:57:50 +00001157void FileSpec::PrependPathComponent(const FileSpec &new_path) {
1158 return PrependPathComponent(new_path.GetPath(false));
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001159}
1160
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001161void FileSpec::AppendPathComponent(llvm::StringRef component) {
1162 if (component.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001163 return;
1164
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001165 component = component.drop_while(
1166 [this](char c) { return IsPathSeparator(c, m_syntax); });
Kate Stoneb9c1b512016-09-06 20:57:50 +00001167
Pavel Labath59d725c2017-01-16 10:07:02 +00001168 std::string result =
1169 join_path_components(m_syntax, {m_directory.GetStringRef(),
1170 m_filename.GetStringRef(), component});
Kate Stoneb9c1b512016-09-06 20:57:50 +00001171
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001172 SetFile(result, false, m_syntax);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001173}
1174
1175void FileSpec::AppendPathComponent(const FileSpec &new_path) {
1176 return AppendPathComponent(new_path.GetPath(false));
1177}
1178
1179void FileSpec::RemoveLastPathComponent() {
Zachary Turnerfe83ad82016-09-27 20:48:37 +00001180 // CLEANUP: Use StringRef for string handling.
1181
Kate Stoneb9c1b512016-09-06 20:57:50 +00001182 const bool resolve = false;
1183 if (m_filename.IsEmpty() && m_directory.IsEmpty()) {
1184 SetFile("", resolve);
1185 return;
1186 }
1187 if (m_directory.IsEmpty()) {
1188 SetFile("", resolve);
1189 return;
1190 }
1191 if (m_filename.IsEmpty()) {
1192 const char *dir_cstr = m_directory.GetCString();
1193 const char *last_slash_ptr = ::strrchr(dir_cstr, '/');
1194
1195 // check for obvious cases before doing the full thing
1196 if (!last_slash_ptr) {
1197 SetFile("", resolve);
1198 return;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001199 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001200 if (last_slash_ptr == dir_cstr) {
1201 SetFile("/", resolve);
1202 return;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001203 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001204 size_t last_slash_pos = last_slash_ptr - dir_cstr + 1;
1205 ConstString new_path(dir_cstr, last_slash_pos);
1206 SetFile(new_path.GetCString(), resolve);
1207 } else
1208 SetFile(m_directory.GetCString(), resolve);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001209}
Greg Clayton1f746072012-08-29 21:13:06 +00001210//------------------------------------------------------------------
1211/// Returns true if the filespec represents an implementation source
1212/// file (files with a ".c", ".cpp", ".m", ".mm" (many more)
1213/// extension).
1214///
1215/// @return
1216/// \b true if the filespec represents an implementation source
1217/// file, \b false otherwise.
1218//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00001219bool FileSpec::IsSourceImplementationFile() const {
1220 ConstString extension(GetFileNameExtension());
Zachary Turner95eae422016-09-21 16:01:28 +00001221 if (!extension)
1222 return false;
1223
1224 static RegularExpression g_source_file_regex(llvm::StringRef(
1225 "^([cC]|[mM]|[mM][mM]|[cC][pP][pP]|[cC]\\+\\+|[cC][xX][xX]|[cC][cC]|["
1226 "cC][pP]|[sS]|[aA][sS][mM]|[fF]|[fF]77|[fF]90|[fF]95|[fF]03|[fF][oO]["
1227 "rR]|[fF][tT][nN]|[fF][pP][pP]|[aA][dD][aA]|[aA][dD][bB]|[aA][dD][sS])"
1228 "$"));
1229 return g_source_file_regex.Execute(extension.GetStringRef());
Greg Clayton1f746072012-08-29 21:13:06 +00001230}
1231
Kate Stoneb9c1b512016-09-06 20:57:50 +00001232bool FileSpec::IsRelative() const {
1233 const char *dir = m_directory.GetCString();
1234 llvm::StringRef directory(dir ? dir : "");
Zachary Turner270e99a2014-12-08 21:36:42 +00001235
Kate Stoneb9c1b512016-09-06 20:57:50 +00001236 if (directory.size() > 0) {
1237 if (PathSyntaxIsPosix(m_syntax)) {
1238 // If the path doesn't start with '/' or '~', return true
1239 switch (directory[0]) {
1240 case '/':
1241 case '~':
1242 return false;
1243 default:
Greg Claytona0ca6602012-10-18 16:33:33 +00001244 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001245 }
1246 } else {
1247 if (directory.size() >= 2 && directory[1] == ':')
1248 return false;
1249 if (directory[0] == '/')
1250 return false;
1251 return true;
Greg Claytona0ca6602012-10-18 16:33:33 +00001252 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001253 } else if (m_filename) {
1254 // No directory, just a basename, return true
1255 return true;
1256 }
1257 return false;
Greg Claytona0ca6602012-10-18 16:33:33 +00001258}
Chaoren Lin372e9062015-06-09 17:54:27 +00001259
Kate Stoneb9c1b512016-09-06 20:57:50 +00001260bool FileSpec::IsAbsolute() const { return !FileSpec::IsRelative(); }
Zachary Turner827d5d72016-12-16 04:27:00 +00001261
1262void llvm::format_provider<FileSpec>::format(const FileSpec &F,
1263 raw_ostream &Stream,
1264 StringRef Style) {
1265 assert(
1266 (Style.empty() || Style.equals_lower("F") || Style.equals_lower("D")) &&
1267 "Invalid FileSpec style!");
1268
1269 StringRef dir = F.GetDirectory().GetStringRef();
1270 StringRef file = F.GetFilename().GetStringRef();
1271
1272 if (dir.empty() && file.empty()) {
1273 Stream << "(empty)";
1274 return;
1275 }
1276
1277 if (Style.equals_lower("F")) {
1278 Stream << (file.empty() ? "(empty)" : file);
1279 return;
1280 }
1281
1282 // Style is either D or empty, either way we need to print the directory.
1283 if (!dir.empty()) {
1284 // Directory is stored in normalized form, which might be different
1285 // than preferred form. In order to handle this, we need to cut off
1286 // the filename, then denormalize, then write the entire denorm'ed
1287 // directory.
1288 llvm::SmallString<64> denormalized_dir = dir;
1289 Denormalize(denormalized_dir, F.GetPathSyntax());
1290 Stream << denormalized_dir;
1291 Stream << GetPreferredPathSeparator(F.GetPathSyntax());
1292 }
1293
1294 if (Style.equals_lower("D")) {
1295 // We only want to print the directory, so now just exit.
1296 if (dir.empty())
1297 Stream << "(empty)";
1298 return;
1299 }
1300
1301 if (!file.empty())
1302 Stream << file;
1303}