blob: 62117b78f06d165c8823ca0be76aaf2ebce95d3a [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
10
Virgile Bellob2f1fb22013-08-23 12:44:05 +000011#ifndef _WIN32
Greg Clayton4272cc72011-02-02 02:24:04 +000012#include <dirent.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000013#else
14#include "lldb/Host/windows/windows.h"
15#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +000016#include <fcntl.h>
Virgile Bello69571952013-09-20 22:35:22 +000017#ifndef _MSC_VER
Chris Lattner30fdc8d2010-06-08 16:52:24 +000018#include <libgen.h>
Virgile Bello69571952013-09-20 22:35:22 +000019#endif
Rafael Espindola09079162013-06-13 20:10:23 +000020#include <set>
Greg Claytone0f3c022011-02-07 17:41:11 +000021#include <string.h>
Jim Ingham9035e7c2011-02-07 19:42:39 +000022#include <fstream>
Greg Claytonfd184262011-02-05 02:27:52 +000023
Jim Ingham9035e7c2011-02-07 19:42:39 +000024#include "lldb/Host/Config.h" // Have to include this before we test the define...
Greg Clayton45319462011-02-08 00:35:34 +000025#ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
Jim Inghamf818ca32010-07-01 01:48:53 +000026#include <pwd.h>
Greg Claytonfd184262011-02-05 02:27:52 +000027#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +000028
Chaoren Linf34f4102015-05-09 01:21:32 +000029#include "lldb/Core/ArchSpec.h"
Zachary Turnerc00cf4a2014-08-15 22:04:21 +000030#include "lldb/Core/DataBufferHeap.h"
31#include "lldb/Core/DataBufferMemoryMap.h"
32#include "lldb/Core/RegularExpression.h"
33#include "lldb/Core/StreamString.h"
34#include "lldb/Core/Stream.h"
35#include "lldb/Host/File.h"
36#include "lldb/Host/FileSpec.h"
37#include "lldb/Host/FileSystem.h"
38#include "lldb/Host/Host.h"
39#include "lldb/Utility/CleanUp.h"
40
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
52bool
53PathSyntaxIsPosix(FileSpec::PathSyntax syntax)
54{
55 return (syntax == FileSpec::ePathSyntaxPosix ||
56 (syntax == FileSpec::ePathSyntaxHostNative &&
57 FileSystem::GetNativePathSyntax() == FileSpec::ePathSyntaxPosix));
58}
59
Pavel Labath144119b2016-04-04 14:39:12 +000060const char *
61GetPathSeparators(FileSpec::PathSyntax syntax)
Chaoren Lin1c614fe2015-05-28 17:02:45 +000062{
Pavel Labath144119b2016-04-04 14:39:12 +000063 return PathSyntaxIsPosix(syntax) ? "/" : "\\/";
64}
65
66char
67GetPrefferedPathSeparator(FileSpec::PathSyntax syntax)
68{
69 return GetPathSeparators(syntax)[0];
70}
71
72bool
73IsPathSeparator(char value, FileSpec::PathSyntax syntax)
74{
75 return value == '/' || (!PathSyntaxIsPosix(syntax) && value == '\\');
Chaoren Lin1c614fe2015-05-28 17:02:45 +000076}
77
78void
79Normalize(llvm::SmallVectorImpl<char> &path, FileSpec::PathSyntax syntax)
80{
81 if (PathSyntaxIsPosix(syntax)) return;
82
83 std::replace(path.begin(), path.end(), '\\', '/');
84 // Windows path can have \\ slashes which can be changed by replace
85 // call above to //. Here we remove the duplicate.
86 auto iter = std::unique ( path.begin(), path.end(),
87 []( char &c1, char &c2 ){
88 return (c1 == '/' && c2 == '/');});
89 path.erase(iter, path.end());
90}
91
92void
93Denormalize(llvm::SmallVectorImpl<char> &path, FileSpec::PathSyntax syntax)
94{
95 if (PathSyntaxIsPosix(syntax)) return;
96
97 std::replace(path.begin(), path.end(), '/', '\\');
98}
99
100bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000101GetFileStats (const FileSpec *file_spec, struct stat *stats_ptr)
102{
103 char resolved_path[PATH_MAX];
Greg Clayton7e14f912011-04-23 02:04:55 +0000104 if (file_spec->GetPath (resolved_path, sizeof(resolved_path)))
Zachary Turner190fadc2016-03-22 17:58:09 +0000105 return FileSystem::Stat(resolved_path, stats_ptr) == 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000106 return false;
107}
108
Pavel Labath144119b2016-04-04 14:39:12 +0000109size_t
110FilenamePos(llvm::StringRef str, FileSpec::PathSyntax syntax)
111{
112 if (str.size() == 2 && IsPathSeparator(str[0], syntax) && str[0] == str[1])
113 return 0;
114
115 if (str.size() > 0 && IsPathSeparator(str.back(), syntax))
116 return str.size() - 1;
117
118 size_t pos = str.find_last_of(GetPathSeparators(syntax), str.size() - 1);
119
120 if (!PathSyntaxIsPosix(syntax) && pos == llvm::StringRef::npos)
121 pos = str.find_last_of(':', str.size() - 2);
122
123 if (pos == llvm::StringRef::npos || (pos == 1 && IsPathSeparator(str[0], syntax)))
124 return 0;
125
126 return pos + 1;
Chaoren Lin1c614fe2015-05-28 17:02:45 +0000127}
128
Pavel Labath144119b2016-04-04 14:39:12 +0000129size_t
130RootDirStart(llvm::StringRef str, FileSpec::PathSyntax syntax)
131{
132 // case "c:/"
133 if (!PathSyntaxIsPosix(syntax) && (str.size() > 2 && str[1] == ':' && IsPathSeparator(str[2], syntax)))
134 return 2;
135
136 // case "//"
137 if (str.size() == 2 && IsPathSeparator(str[0], syntax) && str[0] == str[1])
138 return llvm::StringRef::npos;
139
140 // case "//net"
141 if (str.size() > 3 && IsPathSeparator(str[0], syntax) && str[0] == str[1] && !IsPathSeparator(str[2], syntax))
142 return str.find_first_of(GetPathSeparators(syntax), 2);
143
144 // case "/"
145 if (str.size() > 0 && IsPathSeparator(str[0], syntax))
146 return 0;
147
148 return llvm::StringRef::npos;
149}
150
151size_t
152ParentPathEnd(llvm::StringRef path, FileSpec::PathSyntax syntax)
153{
154 size_t end_pos = FilenamePos(path, syntax);
155
156 bool filename_was_sep = path.size() > 0 && IsPathSeparator(path[end_pos], syntax);
157
158 // Skip separators except for root dir.
159 size_t root_dir_pos = RootDirStart(path.substr(0, end_pos), syntax);
160
161 while (end_pos > 0 && (end_pos - 1) != root_dir_pos && IsPathSeparator(path[end_pos - 1], syntax))
162 --end_pos;
163
164 if (end_pos == 1 && root_dir_pos == 0 && filename_was_sep)
165 return llvm::StringRef::npos;
166
167 return end_pos;
168}
169
170} // end anonymous namespace
171
Jim Inghamf818ca32010-07-01 01:48:53 +0000172// Resolves the username part of a path of the form ~user/other/directories, and
Jim Inghamead45cc2014-09-12 23:50:36 +0000173// writes the result into dst_path. This will also resolve "~" to the current user.
174// If you want to complete "~" to the list of users, pass it to ResolvePartialUsername.
Zachary Turner3f559742014-08-07 17:33:36 +0000175void
176FileSpec::ResolveUsername (llvm::SmallVectorImpl<char> &path)
Jim Inghamf818ca32010-07-01 01:48:53 +0000177{
Zachary Turner3f559742014-08-07 17:33:36 +0000178#if LLDB_CONFIG_TILDE_RESOLVES_TO_USER
179 if (path.empty() || path[0] != '~')
180 return;
Jim Inghamf818ca32010-07-01 01:48:53 +0000181
Jason Molenda3bc66f12015-01-20 04:20:42 +0000182 llvm::StringRef path_str(path.data(), path.size());
Bruce Mitchenere8433cc2015-09-01 23:57:17 +0000183 size_t slash_pos = path_str.find('/', 1);
Jim Inghamead45cc2014-09-12 23:50:36 +0000184 if (slash_pos == 1 || path.size() == 1)
Jim Inghamf818ca32010-07-01 01:48:53 +0000185 {
Jim Ingham2f21bbc2014-09-12 23:04:40 +0000186 // A path of ~/ resolves to the current user's home dir
Zachary Turner3f559742014-08-07 17:33:36 +0000187 llvm::SmallString<64> home_dir;
Greg Claytonf258bf92016-04-19 23:04:35 +0000188 // llvm::sys::path::home_directory() only checks if "HOME" is set in the
189 // environment and does nothing else to locate the user home directory
Zachary Turner3f559742014-08-07 17:33:36 +0000190 if (!llvm::sys::path::home_directory(home_dir))
Greg Claytonf258bf92016-04-19 23:04:35 +0000191 {
192 struct passwd *pw = getpwuid(getuid());
193 if (pw && pw->pw_dir && pw->pw_dir[0])
194 {
195 // Update our environemnt so llvm::sys::path::home_directory() works next time
196 setenv("HOME", pw->pw_dir, 0);
197 home_dir.assign(llvm::StringRef(pw->pw_dir));
198 }
199 else
200 {
201 return;
202 }
203 }
Zachary Turner3f559742014-08-07 17:33:36 +0000204
205 // Overwrite the ~ with the first character of the homedir, and insert
206 // the rest. This way we only trigger one move, whereas an insert
207 // followed by a delete (or vice versa) would trigger two.
208 path[0] = home_dir[0];
209 path.insert(path.begin() + 1, home_dir.begin() + 1, home_dir.end());
210 return;
211 }
212
213 auto username_begin = path.begin()+1;
214 auto username_end = (slash_pos == llvm::StringRef::npos)
215 ? path.end()
216 : (path.begin() + slash_pos);
217 size_t replacement_length = std::distance(path.begin(), username_end);
218
219 llvm::SmallString<20> username(username_begin, username_end);
220 struct passwd *user_entry = ::getpwnam(username.c_str());
221 if (user_entry != nullptr)
222 {
223 // Copy over the first n characters of the path, where n is the smaller of the length
224 // of the home directory and the slash pos.
225 llvm::StringRef homedir(user_entry->pw_dir);
226 size_t initial_copy_length = std::min(homedir.size(), replacement_length);
227 auto src_begin = homedir.begin();
228 auto src_end = src_begin + initial_copy_length;
229 std::copy(src_begin, src_end, path.begin());
230 if (replacement_length > homedir.size())
Jim Inghamf818ca32010-07-01 01:48:53 +0000231 {
Zachary Turner3f559742014-08-07 17:33:36 +0000232 // We copied the entire home directory, but the ~username portion of the path was
233 // longer, so there's characters that need to be removed.
234 path.erase(path.begin() + initial_copy_length, username_end);
Jim Inghamf818ca32010-07-01 01:48:53 +0000235 }
Zachary Turner3f559742014-08-07 17:33:36 +0000236 else if (replacement_length < homedir.size())
237 {
238 // We copied all the way up to the slash in the destination, but there's still more
239 // characters that need to be inserted.
240 path.insert(username_end, src_end, homedir.end());
241 }
Jim Inghamf818ca32010-07-01 01:48:53 +0000242 }
243 else
244 {
Zachary Turner3f559742014-08-07 17:33:36 +0000245 // Unable to resolve username (user doesn't exist?)
246 path.clear();
Jim Inghamf818ca32010-07-01 01:48:53 +0000247 }
Zachary Turner3f559742014-08-07 17:33:36 +0000248#endif
Jim Inghamf818ca32010-07-01 01:48:53 +0000249}
250
Greg Claytonc982c762010-07-09 20:39:50 +0000251size_t
Jim Ingham84363072011-02-08 23:24:09 +0000252FileSpec::ResolvePartialUsername (const char *partial_name, StringList &matches)
253{
254#ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
255 size_t extant_entries = matches.GetSize();
256
257 setpwent();
258 struct passwd *user_entry;
259 const char *name_start = partial_name + 1;
260 std::set<std::string> name_list;
261
262 while ((user_entry = getpwent()) != NULL)
263 {
264 if (strstr(user_entry->pw_name, name_start) == user_entry->pw_name)
265 {
266 std::string tmp_buf("~");
267 tmp_buf.append(user_entry->pw_name);
268 tmp_buf.push_back('/');
269 name_list.insert(tmp_buf);
270 }
271 }
272 std::set<std::string>::iterator pos, end = name_list.end();
273 for (pos = name_list.begin(); pos != end; pos++)
274 {
275 matches.AppendString((*pos).c_str());
276 }
277 return matches.GetSize() - extant_entries;
278#else
279 // Resolving home directories is not supported, just copy the path...
280 return 0;
281#endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
282}
283
Zachary Turner3f559742014-08-07 17:33:36 +0000284void
285FileSpec::Resolve (llvm::SmallVectorImpl<char> &path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000286{
Zachary Turner3f559742014-08-07 17:33:36 +0000287 if (path.empty())
288 return;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000289
Greg Clayton45319462011-02-08 00:35:34 +0000290#ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
Zachary Turner3f559742014-08-07 17:33:36 +0000291 if (path[0] == '~')
292 ResolveUsername(path);
Greg Clayton45319462011-02-08 00:35:34 +0000293#endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000294
Jason Molenda671a29d2015-02-25 02:35:25 +0000295 // Save a copy of the original path that's passed in
Zachary Turner190fadc2016-03-22 17:58:09 +0000296 llvm::SmallString<128> original_path(path.begin(), path.end());
Jason Molenda671a29d2015-02-25 02:35:25 +0000297
Zachary Turner3f559742014-08-07 17:33:36 +0000298 llvm::sys::fs::make_absolute(path);
Zachary Turner190fadc2016-03-22 17:58:09 +0000299 if (!llvm::sys::fs::exists(path))
Jason Molenda671a29d2015-02-25 02:35:25 +0000300 {
301 path.clear();
302 path.append(original_path.begin(), original_path.end());
303 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000304}
305
Jason Molenda68c85212014-10-15 03:04:33 +0000306FileSpec::FileSpec() :
307 m_directory(),
308 m_filename(),
309 m_syntax(FileSystem::GetNativePathSyntax())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000310{
311}
312
313//------------------------------------------------------------------
314// Default constructor that can take an optional full path to a
315// file on disk.
316//------------------------------------------------------------------
Zachary Turnerdf62f202014-08-07 17:33:07 +0000317FileSpec::FileSpec(const char *pathname, bool resolve_path, PathSyntax syntax) :
Jim Ingham0909e5f2010-09-16 00:57:33 +0000318 m_directory(),
Greg Clayton7481c202010-11-08 00:28:40 +0000319 m_filename(),
Jason Molenda68c85212014-10-15 03:04:33 +0000320 m_is_resolved(false),
321 m_syntax(syntax)
Jim Ingham0909e5f2010-09-16 00:57:33 +0000322{
323 if (pathname && pathname[0])
Zachary Turnerdf62f202014-08-07 17:33:07 +0000324 SetFile(pathname, resolve_path, syntax);
Jim Ingham0909e5f2010-09-16 00:57:33 +0000325}
326
Chaoren Linf34f4102015-05-09 01:21:32 +0000327FileSpec::FileSpec(const char *pathname, bool resolve_path, ArchSpec arch) :
Chaoren Lind3173f32015-05-29 19:52:29 +0000328 FileSpec{pathname, resolve_path, arch.GetTriple().isOSWindows() ? ePathSyntaxWindows : ePathSyntaxPosix}
329{
330}
331
332FileSpec::FileSpec(const std::string &path, bool resolve_path, PathSyntax syntax) :
333 FileSpec{path.c_str(), resolve_path, syntax}
334{
335}
336
337FileSpec::FileSpec(const std::string &path, bool resolve_path, ArchSpec arch) :
338 FileSpec{path.c_str(), resolve_path, arch}
Chaoren Linf34f4102015-05-09 01:21:32 +0000339{
340}
341
Jim Ingham0909e5f2010-09-16 00:57:33 +0000342//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000343// Copy constructor
344//------------------------------------------------------------------
345FileSpec::FileSpec(const FileSpec& rhs) :
346 m_directory (rhs.m_directory),
Greg Clayton7481c202010-11-08 00:28:40 +0000347 m_filename (rhs.m_filename),
Zachary Turnerdf62f202014-08-07 17:33:07 +0000348 m_is_resolved (rhs.m_is_resolved),
349 m_syntax (rhs.m_syntax)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000350{
351}
352
353//------------------------------------------------------------------
354// Copy constructor
355//------------------------------------------------------------------
356FileSpec::FileSpec(const FileSpec* rhs) :
357 m_directory(),
358 m_filename()
359{
360 if (rhs)
361 *this = *rhs;
362}
363
364//------------------------------------------------------------------
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +0000365// Virtual destructor in case anyone inherits from this class.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000366//------------------------------------------------------------------
367FileSpec::~FileSpec()
368{
369}
370
371//------------------------------------------------------------------
372// Assignment operator.
373//------------------------------------------------------------------
374const FileSpec&
375FileSpec::operator= (const FileSpec& rhs)
376{
377 if (this != &rhs)
378 {
379 m_directory = rhs.m_directory;
380 m_filename = rhs.m_filename;
Greg Clayton7481c202010-11-08 00:28:40 +0000381 m_is_resolved = rhs.m_is_resolved;
Zachary Turnerdf62f202014-08-07 17:33:07 +0000382 m_syntax = rhs.m_syntax;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000383 }
384 return *this;
385}
386
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000387//------------------------------------------------------------------
388// Update the contents of this object with a new path. The path will
389// be split up into a directory and filename and stored as uniqued
390// string values for quick comparison and efficient memory usage.
391//------------------------------------------------------------------
392void
Zachary Turnerdf62f202014-08-07 17:33:07 +0000393FileSpec::SetFile (const char *pathname, bool resolve, PathSyntax syntax)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000394{
395 m_filename.Clear();
396 m_directory.Clear();
Greg Clayton7481c202010-11-08 00:28:40 +0000397 m_is_resolved = false;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000398 m_syntax = (syntax == ePathSyntaxHostNative) ? FileSystem::GetNativePathSyntax() : syntax;
Zachary Turnerdf62f202014-08-07 17:33:07 +0000399
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000400 if (pathname == NULL || pathname[0] == '\0')
401 return;
402
Pavel Labath144119b2016-04-04 14:39:12 +0000403 llvm::SmallString<64> resolved(pathname);
Zachary Turnerdf62f202014-08-07 17:33:07 +0000404
Jim Ingham0909e5f2010-09-16 00:57:33 +0000405 if (resolve)
406 {
Pavel Labath144119b2016-04-04 14:39:12 +0000407 FileSpec::Resolve (resolved);
Zachary Turner3f559742014-08-07 17:33:36 +0000408 m_is_resolved = true;
Jim Ingham0909e5f2010-09-16 00:57:33 +0000409 }
Zachary Turnerc7a17ed2014-12-01 23:13:32 +0000410
Pavel Labatha212c582016-04-14 09:38:06 +0000411 Normalize(resolved, syntax);
412
Pavel Labath144119b2016-04-04 14:39:12 +0000413 llvm::StringRef resolve_path_ref(resolved.c_str());
414 size_t dir_end = ParentPathEnd(resolve_path_ref, syntax);
415 if (dir_end == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000416 {
Pavel Labath144119b2016-04-04 14:39:12 +0000417 m_filename.SetString(resolve_path_ref);
418 return;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000419 }
Pavel Labath144119b2016-04-04 14:39:12 +0000420
421 m_directory.SetString(resolve_path_ref.substr(0, dir_end));
422
423 size_t filename_begin = dir_end;
424 size_t root_dir_start = RootDirStart(resolve_path_ref, syntax);
425 while (filename_begin != llvm::StringRef::npos && filename_begin < resolve_path_ref.size() &&
426 filename_begin != root_dir_start && IsPathSeparator(resolve_path_ref[filename_begin], syntax))
427 ++filename_begin;
428 m_filename.SetString((filename_begin == llvm::StringRef::npos || filename_begin >= resolve_path_ref.size())
429 ? "."
430 : resolve_path_ref.substr(filename_begin));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000431}
432
Chaoren Lind3173f32015-05-29 19:52:29 +0000433void
Chaoren Lin44145d72015-05-29 19:52:37 +0000434FileSpec::SetFile(const char *pathname, bool resolve, ArchSpec arch)
435{
436 return SetFile(pathname, resolve,
437 arch.GetTriple().isOSWindows()
438 ? ePathSyntaxWindows
439 : ePathSyntaxPosix);
440}
441
442void
Chaoren Lind3173f32015-05-29 19:52:29 +0000443FileSpec::SetFile(const std::string &pathname, bool resolve, PathSyntax syntax)
444{
445 return SetFile(pathname.c_str(), resolve, syntax);
446}
447
Chaoren Lin44145d72015-05-29 19:52:37 +0000448void
449FileSpec::SetFile(const std::string &pathname, bool resolve, ArchSpec arch)
450{
451 return SetFile(pathname.c_str(), resolve, arch);
452}
453
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000454//----------------------------------------------------------------------
455// Convert to pointer operator. This allows code to check any FileSpec
456// objects to see if they contain anything valid using code such as:
457//
458// if (file_spec)
459// {}
460//----------------------------------------------------------------------
Greg Clayton6372d1c2011-09-12 04:00:42 +0000461FileSpec::operator bool() const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000462{
Greg Clayton6372d1c2011-09-12 04:00:42 +0000463 return m_filename || m_directory;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000464}
465
466//----------------------------------------------------------------------
467// Logical NOT operator. This allows code to check any FileSpec
468// objects to see if they are invalid using code such as:
469//
470// if (!file_spec)
471// {}
472//----------------------------------------------------------------------
473bool
474FileSpec::operator!() const
475{
476 return !m_directory && !m_filename;
477}
478
Zachary Turner74e08ca2016-03-02 22:05:52 +0000479bool
480FileSpec::DirectoryEquals(const FileSpec &rhs) const
481{
482 const bool case_sensitive = IsCaseSensitive() || rhs.IsCaseSensitive();
483 return ConstString::Equals(m_directory, rhs.m_directory, case_sensitive);
484}
485
486bool
487FileSpec::FileEquals(const FileSpec &rhs) const
488{
489 const bool case_sensitive = IsCaseSensitive() || rhs.IsCaseSensitive();
490 return ConstString::Equals(m_filename, rhs.m_filename, case_sensitive);
491}
492
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000493//------------------------------------------------------------------
494// Equal to operator
495//------------------------------------------------------------------
496bool
497FileSpec::operator== (const FileSpec& rhs) const
498{
Zachary Turner74e08ca2016-03-02 22:05:52 +0000499 if (!FileEquals(rhs))
Zachary Turner47c03462016-02-24 21:26:47 +0000500 return false;
Zachary Turner74e08ca2016-03-02 22:05:52 +0000501 if (DirectoryEquals(rhs))
Zachary Turner47c03462016-02-24 21:26:47 +0000502 return true;
503
504 // TODO: determine if we want to keep this code in here.
505 // The code below was added to handle a case where we were
506 // trying to set a file and line breakpoint and one path
507 // was resolved, and the other not and the directory was
508 // in a mount point that resolved to a more complete path:
509 // "/tmp/a.c" == "/private/tmp/a.c". I might end up pulling
510 // this out...
511 if (IsResolved() && rhs.IsResolved())
Greg Clayton7481c202010-11-08 00:28:40 +0000512 {
Zachary Turner47c03462016-02-24 21:26:47 +0000513 // Both paths are resolved, no need to look further...
514 return false;
Greg Clayton7481c202010-11-08 00:28:40 +0000515 }
Zachary Turner47c03462016-02-24 21:26:47 +0000516
517 FileSpec resolved_lhs(*this);
518
519 // If "this" isn't resolved, resolve it
520 if (!IsResolved())
521 {
522 if (resolved_lhs.ResolvePath())
523 {
524 // This path wasn't resolved but now it is. Check if the resolved
525 // directory is the same as our unresolved directory, and if so,
526 // we can mark this object as resolved to avoid more future resolves
527 m_is_resolved = (m_directory == resolved_lhs.m_directory);
528 }
529 else
530 return false;
531 }
532
533 FileSpec resolved_rhs(rhs);
534 if (!rhs.IsResolved())
535 {
536 if (resolved_rhs.ResolvePath())
537 {
538 // rhs's path wasn't resolved but now it is. Check if the resolved
539 // directory is the same as rhs's unresolved directory, and if so,
540 // we can mark this object as resolved to avoid more future resolves
541 rhs.m_is_resolved = (rhs.m_directory == resolved_rhs.m_directory);
542 }
543 else
544 return false;
545 }
546
547 // If we reach this point in the code we were able to resolve both paths
548 // and since we only resolve the paths if the basenames are equal, then
549 // we can just check if both directories are equal...
Zachary Turner74e08ca2016-03-02 22:05:52 +0000550 return DirectoryEquals(rhs);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000551}
552
553//------------------------------------------------------------------
554// Not equal to operator
555//------------------------------------------------------------------
556bool
557FileSpec::operator!= (const FileSpec& rhs) const
558{
Greg Clayton7481c202010-11-08 00:28:40 +0000559 return !(*this == rhs);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000560}
561
562//------------------------------------------------------------------
563// Less than operator
564//------------------------------------------------------------------
565bool
566FileSpec::operator< (const FileSpec& rhs) const
567{
568 return FileSpec::Compare(*this, rhs, true) < 0;
569}
570
571//------------------------------------------------------------------
572// Dump a FileSpec object to a stream
573//------------------------------------------------------------------
574Stream&
575lldb_private::operator << (Stream &s, const FileSpec& f)
576{
577 f.Dump(&s);
578 return s;
579}
580
581//------------------------------------------------------------------
582// Clear this object by releasing both the directory and filename
583// string values and making them both the empty string.
584//------------------------------------------------------------------
585void
586FileSpec::Clear()
587{
588 m_directory.Clear();
589 m_filename.Clear();
590}
591
592//------------------------------------------------------------------
593// Compare two FileSpec objects. If "full" is true, then both
594// the directory and the filename must match. If "full" is false,
595// then the directory names for "a" and "b" are only compared if
596// they are both non-empty. This allows a FileSpec object to only
597// contain a filename and it can match FileSpec objects that have
598// matching filenames with different paths.
599//
600// Return -1 if the "a" is less than "b", 0 if "a" is equal to "b"
601// and "1" if "a" is greater than "b".
602//------------------------------------------------------------------
603int
604FileSpec::Compare(const FileSpec& a, const FileSpec& b, bool full)
605{
606 int result = 0;
607
Zachary Turner47c03462016-02-24 21:26:47 +0000608 // case sensitivity of compare
609 const bool case_sensitive = a.IsCaseSensitive() || b.IsCaseSensitive();
610
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000611 // If full is true, then we must compare both the directory and filename.
612
613 // If full is false, then if either directory is empty, then we match on
614 // the basename only, and if both directories have valid values, we still
615 // do a full compare. This allows for matching when we just have a filename
616 // in one of the FileSpec objects.
617
618 if (full || (a.m_directory && b.m_directory))
619 {
Zachary Turner47c03462016-02-24 21:26:47 +0000620 result = ConstString::Compare(a.m_directory, b.m_directory, case_sensitive);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000621 if (result)
622 return result;
623 }
Zachary Turner47c03462016-02-24 21:26:47 +0000624 return ConstString::Compare(a.m_filename, b.m_filename, case_sensitive);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000625}
626
627bool
Jim Ingham96a15962014-11-15 01:54:26 +0000628FileSpec::Equal (const FileSpec& a, const FileSpec& b, bool full, bool remove_backups)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000629{
Zachary Turner47c03462016-02-24 21:26:47 +0000630 // case sensitivity of equality test
631 const bool case_sensitive = a.IsCaseSensitive() || b.IsCaseSensitive();
632
Jim Ingham87df91b2011-09-23 00:54:11 +0000633 if (!full && (a.GetDirectory().IsEmpty() || b.GetDirectory().IsEmpty()))
Zachary Turner47c03462016-02-24 21:26:47 +0000634 return ConstString::Equals(a.m_filename, b.m_filename, case_sensitive);
Jim Ingham96a15962014-11-15 01:54:26 +0000635 else if (remove_backups == false)
Jim Ingham87df91b2011-09-23 00:54:11 +0000636 return a == b;
Jim Ingham96a15962014-11-15 01:54:26 +0000637 else
638 {
Zachary Turner47c03462016-02-24 21:26:47 +0000639 if (!ConstString::Equals(a.m_filename, b.m_filename, case_sensitive))
Jim Ingham96a15962014-11-15 01:54:26 +0000640 return false;
Zachary Turner47c03462016-02-24 21:26:47 +0000641 if (ConstString::Equals(a.m_directory, b.m_directory, case_sensitive))
Jim Ingham96a15962014-11-15 01:54:26 +0000642 return true;
643 ConstString a_without_dots;
644 ConstString b_without_dots;
645
646 RemoveBackupDots (a.m_directory, a_without_dots);
647 RemoveBackupDots (b.m_directory, b_without_dots);
Zachary Turner47c03462016-02-24 21:26:47 +0000648 return ConstString::Equals(a_without_dots, b_without_dots, case_sensitive);
Jim Ingham96a15962014-11-15 01:54:26 +0000649 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000650}
651
Jim Ingham96a15962014-11-15 01:54:26 +0000652void
Greg Clayton5a271952015-06-02 22:43:29 +0000653FileSpec::NormalizePath ()
654{
655 ConstString normalized_directory;
656 FileSpec::RemoveBackupDots(m_directory, normalized_directory);
657 m_directory = normalized_directory;
658}
659
660void
Jim Ingham96a15962014-11-15 01:54:26 +0000661FileSpec::RemoveBackupDots (const ConstString &input_const_str, ConstString &result_const_str)
662{
663 const char *input = input_const_str.GetCString();
664 result_const_str.Clear();
665 if (!input || input[0] == '\0')
666 return;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000667
Jim Ingham96a15962014-11-15 01:54:26 +0000668 const char win_sep = '\\';
669 const char unix_sep = '/';
670 char found_sep;
671 const char *win_backup = "\\..";
672 const char *unix_backup = "/..";
673
674 bool is_win = false;
675
676 // Determine the platform for the path (win or unix):
677
678 if (input[0] == win_sep)
679 is_win = true;
680 else if (input[0] == unix_sep)
681 is_win = false;
682 else if (input[1] == ':')
683 is_win = true;
684 else if (strchr(input, unix_sep) != nullptr)
685 is_win = false;
686 else if (strchr(input, win_sep) != nullptr)
687 is_win = true;
688 else
689 {
690 // No separators at all, no reason to do any work here.
691 result_const_str = input_const_str;
692 return;
693 }
694
695 llvm::StringRef backup_sep;
696 if (is_win)
697 {
698 found_sep = win_sep;
699 backup_sep = win_backup;
700 }
701 else
702 {
703 found_sep = unix_sep;
704 backup_sep = unix_backup;
705 }
706
707 llvm::StringRef input_ref(input);
708 llvm::StringRef curpos(input);
709
710 bool had_dots = false;
711 std::string result;
712
713 while (1)
714 {
715 // Start of loop
716 llvm::StringRef before_sep;
717 std::pair<llvm::StringRef, llvm::StringRef> around_sep = curpos.split(backup_sep);
718
719 before_sep = around_sep.first;
720 curpos = around_sep.second;
721
722 if (curpos.empty())
723 {
724 if (had_dots)
725 {
Greg Clayton9c284c42015-05-05 20:26:58 +0000726 while (before_sep.startswith("//"))
727 before_sep = before_sep.substr(1);
Jim Ingham96a15962014-11-15 01:54:26 +0000728 if (!before_sep.empty())
729 {
730 result.append(before_sep.data(), before_sep.size());
731 }
732 }
733 break;
734 }
735 had_dots = true;
736
737 unsigned num_backups = 1;
738 while (curpos.startswith(backup_sep))
739 {
740 num_backups++;
741 curpos = curpos.slice(backup_sep.size(), curpos.size());
742 }
743
744 size_t end_pos = before_sep.size();
745 while (num_backups-- > 0)
746 {
747 end_pos = before_sep.rfind(found_sep, end_pos);
748 if (end_pos == llvm::StringRef::npos)
749 {
750 result_const_str = input_const_str;
751 return;
752 }
753 }
754 result.append(before_sep.data(), end_pos);
755 }
756
757 if (had_dots)
758 result_const_str.SetCString(result.c_str());
759 else
760 result_const_str = input_const_str;
761
762 return;
763}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000764
765//------------------------------------------------------------------
766// Dump the object to the supplied stream. If the object contains
767// a valid directory name, it will be displayed followed by a
768// directory delimiter, and the filename.
769//------------------------------------------------------------------
770void
Chaoren Lin1c614fe2015-05-28 17:02:45 +0000771FileSpec::Dump(Stream *s) const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000772{
Enrico Granata80fcdd42012-11-03 00:09:46 +0000773 if (s)
774 {
Chaoren Lin1c614fe2015-05-28 17:02:45 +0000775 std::string path{GetPath(true)};
776 s->PutCString(path.c_str());
Pavel Labath144119b2016-04-04 14:39:12 +0000777 char path_separator = GetPrefferedPathSeparator(m_syntax);
Chaoren Lin1c614fe2015-05-28 17:02:45 +0000778 if (!m_filename && !path.empty() && path.back() != path_separator)
779 s->PutChar(path_separator);
Enrico Granata80fcdd42012-11-03 00:09:46 +0000780 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000781}
782
783//------------------------------------------------------------------
784// Returns true if the file exists.
785//------------------------------------------------------------------
786bool
787FileSpec::Exists () const
788{
789 struct stat file_stats;
790 return GetFileStats (this, &file_stats);
791}
792
Caroline Tice428a9a52010-09-10 04:48:55 +0000793bool
Greg Clayton5acc1252014-08-15 18:00:45 +0000794FileSpec::Readable () const
795{
796 const uint32_t permissions = GetPermissions();
797 if (permissions & eFilePermissionsEveryoneR)
798 return true;
799 return false;
800}
801
802bool
Caroline Tice428a9a52010-09-10 04:48:55 +0000803FileSpec::ResolveExecutableLocation ()
804{
Greg Clayton274060b2010-10-20 20:54:39 +0000805 if (!m_directory)
Caroline Tice391a9602010-09-12 00:10:52 +0000806 {
Greg Clayton58f41712011-01-25 21:32:01 +0000807 const char *file_cstr = m_filename.GetCString();
808 if (file_cstr)
Caroline Tice391a9602010-09-12 00:10:52 +0000809 {
Greg Clayton58f41712011-01-25 21:32:01 +0000810 const std::string file_str (file_cstr);
Enrico Granata404ab372014-11-04 19:33:45 +0000811 llvm::ErrorOr<std::string> error_or_path = llvm::sys::findProgramByName (file_str);
812 if (!error_or_path)
813 return false;
814 std::string path = error_or_path.get();
Rafael Espindolaff89ff22013-06-13 19:25:41 +0000815 llvm::StringRef dir_ref = llvm::sys::path::parent_path(path);
Greg Clayton6bc87392014-05-30 21:06:57 +0000816 if (!dir_ref.empty())
Caroline Tice391a9602010-09-12 00:10:52 +0000817 {
Greg Clayton58f41712011-01-25 21:32:01 +0000818 // FindProgramByName returns "." if it can't find the file.
819 if (strcmp (".", dir_ref.data()) == 0)
820 return false;
821
822 m_directory.SetCString (dir_ref.data());
823 if (Exists())
Caroline Tice391a9602010-09-12 00:10:52 +0000824 return true;
Greg Clayton58f41712011-01-25 21:32:01 +0000825 else
826 {
827 // If FindProgramByName found the file, it returns the directory + filename in its return results.
828 // We need to separate them.
829 FileSpec tmp_file (dir_ref.data(), false);
830 if (tmp_file.Exists())
831 {
832 m_directory = tmp_file.m_directory;
833 return true;
834 }
Caroline Tice391a9602010-09-12 00:10:52 +0000835 }
836 }
837 }
838 }
839
840 return false;
Caroline Tice428a9a52010-09-10 04:48:55 +0000841}
842
Jim Ingham0909e5f2010-09-16 00:57:33 +0000843bool
844FileSpec::ResolvePath ()
845{
Greg Clayton7481c202010-11-08 00:28:40 +0000846 if (m_is_resolved)
847 return true; // We have already resolved this path
848
849 char path_buf[PATH_MAX];
Zachary Turnerdf62f202014-08-07 17:33:07 +0000850 if (!GetPath (path_buf, PATH_MAX, false))
Jim Ingham0909e5f2010-09-16 00:57:33 +0000851 return false;
Greg Clayton7481c202010-11-08 00:28:40 +0000852 // SetFile(...) will set m_is_resolved correctly if it can resolve the path
Jim Ingham0909e5f2010-09-16 00:57:33 +0000853 SetFile (path_buf, true);
Greg Clayton7481c202010-11-08 00:28:40 +0000854 return m_is_resolved;
Jim Ingham0909e5f2010-09-16 00:57:33 +0000855}
856
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000857uint64_t
858FileSpec::GetByteSize() const
859{
860 struct stat file_stats;
861 if (GetFileStats (this, &file_stats))
862 return file_stats.st_size;
863 return 0;
864}
865
Zachary Turnerdf62f202014-08-07 17:33:07 +0000866FileSpec::PathSyntax
867FileSpec::GetPathSyntax() const
868{
869 return m_syntax;
870}
871
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000872FileSpec::FileType
873FileSpec::GetFileType () const
874{
875 struct stat file_stats;
876 if (GetFileStats (this, &file_stats))
877 {
878 mode_t file_type = file_stats.st_mode & S_IFMT;
879 switch (file_type)
880 {
881 case S_IFDIR: return eFileTypeDirectory;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000882 case S_IFREG: return eFileTypeRegular;
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000883#ifndef _WIN32
884 case S_IFIFO: return eFileTypePipe;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000885 case S_IFSOCK: return eFileTypeSocket;
886 case S_IFLNK: return eFileTypeSymbolicLink;
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000887#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000888 default:
889 break;
890 }
Greg Clayton4272cc72011-02-02 02:24:04 +0000891 return eFileTypeUnknown;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000892 }
893 return eFileTypeInvalid;
894}
895
Oleksiy Vyalov8a578bf2015-07-21 01:28:22 +0000896bool
897FileSpec::IsSymbolicLink () const
898{
899 char resolved_path[PATH_MAX];
900 if (!GetPath (resolved_path, sizeof (resolved_path)))
901 return false;
902
903#ifdef _WIN32
Zachary Turner190fadc2016-03-22 17:58:09 +0000904 std::wstring wpath;
905 if (!llvm::ConvertUTF8toWide(resolved_path, wpath))
906 return false;
907 auto attrs = ::GetFileAttributesW(wpath.c_str());
Oleksiy Vyalov8a578bf2015-07-21 01:28:22 +0000908 if (attrs == INVALID_FILE_ATTRIBUTES)
909 return false;
910
911 return (attrs & FILE_ATTRIBUTE_REPARSE_POINT);
912#else
913 struct stat file_stats;
914 if (::lstat (resolved_path, &file_stats) != 0)
915 return false;
916
917 return (file_stats.st_mode & S_IFMT) == S_IFLNK;
918#endif
919}
920
Greg Claytonfbb76342013-11-20 21:07:01 +0000921uint32_t
922FileSpec::GetPermissions () const
923{
924 uint32_t file_permissions = 0;
925 if (*this)
Chaoren Lind3173f32015-05-29 19:52:29 +0000926 FileSystem::GetFilePermissions(*this, file_permissions);
Greg Claytonfbb76342013-11-20 21:07:01 +0000927 return file_permissions;
928}
929
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000930TimeValue
931FileSpec::GetModificationTime () const
932{
933 TimeValue mod_time;
934 struct stat file_stats;
935 if (GetFileStats (this, &file_stats))
Eli Friedman6abb6342010-06-11 04:52:22 +0000936 mod_time.OffsetWithSeconds(file_stats.st_mtime);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000937 return mod_time;
938}
939
940//------------------------------------------------------------------
941// Directory string get accessor.
942//------------------------------------------------------------------
943ConstString &
944FileSpec::GetDirectory()
945{
946 return m_directory;
947}
948
949//------------------------------------------------------------------
950// Directory string const get accessor.
951//------------------------------------------------------------------
952const ConstString &
953FileSpec::GetDirectory() const
954{
955 return m_directory;
956}
957
958//------------------------------------------------------------------
959// Filename string get accessor.
960//------------------------------------------------------------------
961ConstString &
962FileSpec::GetFilename()
963{
964 return m_filename;
965}
966
967//------------------------------------------------------------------
968// Filename string const get accessor.
969//------------------------------------------------------------------
970const ConstString &
971FileSpec::GetFilename() const
972{
973 return m_filename;
974}
975
976//------------------------------------------------------------------
977// Extract the directory and path into a fixed buffer. This is
978// needed as the directory and path are stored in separate string
979// values.
980//------------------------------------------------------------------
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000981size_t
Zachary Turnerdf62f202014-08-07 17:33:07 +0000982FileSpec::GetPath(char *path, size_t path_max_len, bool denormalize) const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000983{
Zachary Turnerb6d99242014-08-08 23:54:35 +0000984 if (!path)
985 return 0;
986
Zachary Turnerdf62f202014-08-07 17:33:07 +0000987 std::string result = GetPath(denormalize);
Ilia K686b1fe2015-02-27 19:43:08 +0000988 ::snprintf(path, path_max_len, "%s", result.c_str());
989 return std::min(path_max_len-1, result.length());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000990}
991
Greg Claytona44c1e62013-04-29 16:36:27 +0000992std::string
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000993FileSpec::GetPath(bool denormalize) const
Jason Molendaa7ae4672013-04-29 09:46:43 +0000994{
Zachary Turnerdf62f202014-08-07 17:33:07 +0000995 llvm::SmallString<64> result;
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000996 GetPath(result, denormalize);
Zachary Turnerdf62f202014-08-07 17:33:07 +0000997 return std::string(result.begin(), result.end());
Jason Molendaa7ae4672013-04-29 09:46:43 +0000998}
999
Chaoren Lind3173f32015-05-29 19:52:29 +00001000const char *
1001FileSpec::GetCString(bool denormalize) const
1002{
1003 return ConstString{GetPath(denormalize)}.AsCString(NULL);
1004}
1005
Zachary Turner4e8ddf52015-04-09 18:08:50 +00001006void
1007FileSpec::GetPath(llvm::SmallVectorImpl<char> &path, bool denormalize) const
1008{
Chaoren Lin1c614fe2015-05-28 17:02:45 +00001009 path.append(m_directory.GetStringRef().begin(), m_directory.GetStringRef().end());
Pavel Labath144119b2016-04-04 14:39:12 +00001010 if (m_directory && m_filename && !IsPathSeparator(m_directory.GetStringRef().back(), m_syntax))
1011 path.insert(path.end(), GetPrefferedPathSeparator(m_syntax));
Chaoren Lin1c614fe2015-05-28 17:02:45 +00001012 path.append(m_filename.GetStringRef().begin(), m_filename.GetStringRef().end());
Zachary Turner4e8ddf52015-04-09 18:08:50 +00001013 Normalize(path, m_syntax);
1014 if (denormalize && !path.empty())
Chaoren Lin1c614fe2015-05-28 17:02:45 +00001015 Denormalize(path, m_syntax);
Zachary Turner4e8ddf52015-04-09 18:08:50 +00001016}
1017
Enrico Granataa9dbf432011-10-17 21:45:27 +00001018ConstString
1019FileSpec::GetFileNameExtension () const
1020{
Greg Clayton1f746072012-08-29 21:13:06 +00001021 if (m_filename)
1022 {
1023 const char *filename = m_filename.GetCString();
1024 const char* dot_pos = strrchr(filename, '.');
1025 if (dot_pos && dot_pos[1] != '\0')
1026 return ConstString(dot_pos+1);
1027 }
1028 return ConstString();
Enrico Granataa9dbf432011-10-17 21:45:27 +00001029}
1030
1031ConstString
1032FileSpec::GetFileNameStrippingExtension () const
1033{
1034 const char *filename = m_filename.GetCString();
1035 if (filename == NULL)
1036 return ConstString();
1037
Johnny Chenf5df5372011-10-18 19:28:30 +00001038 const char* dot_pos = strrchr(filename, '.');
Enrico Granataa9dbf432011-10-17 21:45:27 +00001039 if (dot_pos == NULL)
1040 return m_filename;
1041
1042 return ConstString(filename, dot_pos-filename);
1043}
1044
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001045//------------------------------------------------------------------
1046// Returns a shared pointer to a data buffer that contains all or
1047// part of the contents of a file. The data is memory mapped and
1048// will lazily page in data from the file as memory is accessed.
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001049// The data that is mapped will start "file_offset" bytes into the
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001050// file, and "file_size" bytes will be mapped. If "file_size" is
1051// greater than the number of bytes available in the file starting
1052// at "file_offset", the number of bytes will be appropriately
1053// truncated. The final number of bytes that get mapped can be
1054// verified using the DataBuffer::GetByteSize() function.
1055//------------------------------------------------------------------
1056DataBufferSP
1057FileSpec::MemoryMapFileContents(off_t file_offset, size_t file_size) const
1058{
1059 DataBufferSP data_sp;
Greg Clayton7b0992d2013-04-18 22:45:39 +00001060 std::unique_ptr<DataBufferMemoryMap> mmap_data(new DataBufferMemoryMap());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001061 if (mmap_data.get())
1062 {
Greg Claytond398a1c2013-04-20 00:23:26 +00001063 const size_t mapped_length = mmap_data->MemoryMapFromFileSpec (this, file_offset, file_size);
1064 if (((file_size == SIZE_MAX) && (mapped_length > 0)) || (mapped_length >= file_size))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001065 data_sp.reset(mmap_data.release());
1066 }
1067 return data_sp;
1068}
1069
Greg Clayton736888c2015-02-23 23:47:09 +00001070DataBufferSP
1071FileSpec::MemoryMapFileContentsIfLocal(off_t file_offset, size_t file_size) const
1072{
1073 if (FileSystem::IsLocal(*this))
1074 return MemoryMapFileContents(file_offset, file_size);
1075 else
1076 return ReadFileContents(file_offset, file_size, NULL);
1077}
1078
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001079
1080//------------------------------------------------------------------
1081// Return the size in bytes that this object takes in memory. This
1082// returns the size in bytes of this object, not any shared string
1083// values it may refer to.
1084//------------------------------------------------------------------
1085size_t
1086FileSpec::MemorySize() const
1087{
1088 return m_filename.MemorySize() + m_directory.MemorySize();
1089}
1090
Greg Claytondda4f7b2010-06-30 23:03:03 +00001091
1092size_t
Greg Clayton4017fa32012-01-06 02:01:06 +00001093FileSpec::ReadFileContents (off_t file_offset, void *dst, size_t dst_len, Error *error_ptr) const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001094{
Greg Clayton4017fa32012-01-06 02:01:06 +00001095 Error error;
Greg Claytondda4f7b2010-06-30 23:03:03 +00001096 size_t bytes_read = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001097 char resolved_path[PATH_MAX];
1098 if (GetPath(resolved_path, sizeof(resolved_path)))
1099 {
Greg Clayton96c09682012-01-04 22:56:43 +00001100 File file;
1101 error = file.Open(resolved_path, File::eOpenOptionRead);
1102 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001103 {
Greg Clayton96c09682012-01-04 22:56:43 +00001104 off_t file_offset_after_seek = file_offset;
1105 bytes_read = dst_len;
1106 error = file.Read(dst, bytes_read, file_offset_after_seek);
Greg Claytondda4f7b2010-06-30 23:03:03 +00001107 }
Greg Claytondda4f7b2010-06-30 23:03:03 +00001108 }
Greg Clayton4017fa32012-01-06 02:01:06 +00001109 else
1110 {
1111 error.SetErrorString("invalid file specification");
1112 }
1113 if (error_ptr)
1114 *error_ptr = error;
Greg Claytondda4f7b2010-06-30 23:03:03 +00001115 return bytes_read;
1116}
1117
1118//------------------------------------------------------------------
1119// Returns a shared pointer to a data buffer that contains all or
1120// part of the contents of a file. The data copies into a heap based
1121// buffer that lives in the DataBuffer shared pointer object returned.
1122// The data that is cached will start "file_offset" bytes into the
1123// file, and "file_size" bytes will be mapped. If "file_size" is
1124// greater than the number of bytes available in the file starting
1125// at "file_offset", the number of bytes will be appropriately
1126// truncated. The final number of bytes that get mapped can be
1127// verified using the DataBuffer::GetByteSize() function.
1128//------------------------------------------------------------------
1129DataBufferSP
Greg Clayton4017fa32012-01-06 02:01:06 +00001130FileSpec::ReadFileContents (off_t file_offset, size_t file_size, Error *error_ptr) const
Greg Claytondda4f7b2010-06-30 23:03:03 +00001131{
Greg Clayton4017fa32012-01-06 02:01:06 +00001132 Error error;
Greg Claytondda4f7b2010-06-30 23:03:03 +00001133 DataBufferSP data_sp;
1134 char resolved_path[PATH_MAX];
1135 if (GetPath(resolved_path, sizeof(resolved_path)))
1136 {
Greg Clayton96c09682012-01-04 22:56:43 +00001137 File file;
1138 error = file.Open(resolved_path, File::eOpenOptionRead);
1139 if (error.Success())
Greg Clayton0b0b5122012-08-30 18:15:10 +00001140 {
1141 const bool null_terminate = false;
1142 error = file.Read (file_size, file_offset, null_terminate, data_sp);
1143 }
1144 }
1145 else
1146 {
1147 error.SetErrorString("invalid file specification");
1148 }
1149 if (error_ptr)
1150 *error_ptr = error;
1151 return data_sp;
1152}
1153
1154DataBufferSP
1155FileSpec::ReadFileContentsAsCString(Error *error_ptr)
1156{
1157 Error error;
1158 DataBufferSP data_sp;
1159 char resolved_path[PATH_MAX];
1160 if (GetPath(resolved_path, sizeof(resolved_path)))
1161 {
1162 File file;
1163 error = file.Open(resolved_path, File::eOpenOptionRead);
1164 if (error.Success())
1165 {
1166 off_t offset = 0;
1167 size_t length = SIZE_MAX;
1168 const bool null_terminate = true;
1169 error = file.Read (length, offset, null_terminate, data_sp);
1170 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001171 }
Greg Clayton4017fa32012-01-06 02:01:06 +00001172 else
1173 {
1174 error.SetErrorString("invalid file specification");
1175 }
1176 if (error_ptr)
1177 *error_ptr = error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001178 return data_sp;
1179}
1180
Greg Clayton58fc50e2010-10-20 22:52:05 +00001181size_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001182FileSpec::ReadFileLines (STLStringArray &lines)
1183{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001184 lines.clear();
Greg Clayton58fc50e2010-10-20 22:52:05 +00001185 char path[PATH_MAX];
1186 if (GetPath(path, sizeof(path)))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001187 {
Greg Claytone01e07b2013-04-18 18:10:51 +00001188 std::ifstream file_stream (path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001189
Greg Clayton58fc50e2010-10-20 22:52:05 +00001190 if (file_stream)
1191 {
1192 std::string line;
1193 while (getline (file_stream, line))
1194 lines.push_back (line);
1195 }
1196 }
1197 return lines.size();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001198}
Greg Clayton4272cc72011-02-02 02:24:04 +00001199
1200FileSpec::EnumerateDirectoryResult
Greg Clayton58c65f02015-06-29 18:29:00 +00001201FileSpec::ForEachItemInDirectory (const char *dir_path, DirectoryCallback const &callback)
1202{
1203 if (dir_path && dir_path[0])
1204 {
Zachary Turner190fadc2016-03-22 17:58:09 +00001205#ifdef _WIN32
Greg Clayton58c65f02015-06-29 18:29:00 +00001206 std::string szDir(dir_path);
1207 szDir += "\\*";
1208
Zachary Turner190fadc2016-03-22 17:58:09 +00001209 std::wstring wszDir;
1210 if (!llvm::ConvertUTF8toWide(szDir, wszDir))
1211 {
1212 return eEnumerateDirectoryResultNext;
1213 }
1214
1215 WIN32_FIND_DATAW ffd;
1216 HANDLE hFind = FindFirstFileW(wszDir.c_str(), &ffd);
Greg Clayton58c65f02015-06-29 18:29:00 +00001217
1218 if (hFind == INVALID_HANDLE_VALUE)
1219 {
1220 return eEnumerateDirectoryResultNext;
1221 }
1222
1223 do
1224 {
Greg Clayton58c65f02015-06-29 18:29:00 +00001225 FileSpec::FileType file_type = eFileTypeUnknown;
1226 if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
1227 {
Zachary Turner190fadc2016-03-22 17:58:09 +00001228 size_t len = wcslen(ffd.cFileName);
Greg Clayton58c65f02015-06-29 18:29:00 +00001229
Zachary Turner190fadc2016-03-22 17:58:09 +00001230 if (len == 1 && ffd.cFileName[0] == L'.')
Greg Clayton58c65f02015-06-29 18:29:00 +00001231 continue;
1232
Zachary Turner190fadc2016-03-22 17:58:09 +00001233 if (len == 2 && ffd.cFileName[0] == L'.' && ffd.cFileName[1] == L'.')
Greg Clayton58c65f02015-06-29 18:29:00 +00001234 continue;
1235
1236 file_type = eFileTypeDirectory;
Greg Clayton58c65f02015-06-29 18:29:00 +00001237 }
1238 else if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DEVICE)
1239 {
1240 file_type = eFileTypeOther;
Greg Clayton58c65f02015-06-29 18:29:00 +00001241 }
1242 else
1243 {
1244 file_type = eFileTypeRegular;
Greg Clayton58c65f02015-06-29 18:29:00 +00001245 }
Ewan Crawford184d4df2015-06-30 15:03:31 +00001246
Zachary Turner190fadc2016-03-22 17:58:09 +00001247 std::string fileName;
1248 if (!llvm::convertWideToUTF8(ffd.cFileName, fileName))
1249 {
1250 continue;
1251 }
1252
1253 std::vector<char> child_path(PATH_MAX);
1254 const int child_path_len =
1255 ::snprintf(child_path.data(), child_path.size(), "%s\\%s", dir_path, fileName.c_str());
1256 if (child_path_len < (int)(child_path.size() - 1))
Greg Clayton58c65f02015-06-29 18:29:00 +00001257 {
Ewan Crawford184d4df2015-06-30 15:03:31 +00001258 // Don't resolve the file type or path
Zachary Turner190fadc2016-03-22 17:58:09 +00001259 FileSpec child_path_spec(child_path.data(), false);
Ewan Crawford184d4df2015-06-30 15:03:31 +00001260
1261 EnumerateDirectoryResult result = callback (file_type, child_path_spec);
1262
1263 switch (result)
Greg Clayton58c65f02015-06-29 18:29:00 +00001264 {
Ewan Crawford184d4df2015-06-30 15:03:31 +00001265 case eEnumerateDirectoryResultNext:
1266 // Enumerate next entry in the current directory. We just
1267 // exit this switch and will continue enumerating the
1268 // current directory as we currently are...
1269 break;
Greg Clayton58c65f02015-06-29 18:29:00 +00001270
Ewan Crawford184d4df2015-06-30 15:03:31 +00001271 case eEnumerateDirectoryResultEnter: // Recurse into the current entry if it is a directory or symlink, or next if not
Zachary Turner190fadc2016-03-22 17:58:09 +00001272 if (FileSpec::ForEachItemInDirectory(child_path.data(), callback) ==
1273 eEnumerateDirectoryResultQuit)
Ewan Crawford184d4df2015-06-30 15:03:31 +00001274 {
1275 // The subdirectory returned Quit, which means to
1276 // stop all directory enumerations at all levels.
Greg Clayton58c65f02015-06-29 18:29:00 +00001277 return eEnumerateDirectoryResultQuit;
Ewan Crawford184d4df2015-06-30 15:03:31 +00001278 }
1279 break;
1280
1281 case eEnumerateDirectoryResultExit: // Exit from the current directory at the current level.
1282 // Exit from this directory level and tell parent to
1283 // keep enumerating.
1284 return eEnumerateDirectoryResultNext;
1285
1286 case eEnumerateDirectoryResultQuit: // Stop directory enumerations at any level
1287 return eEnumerateDirectoryResultQuit;
Greg Clayton58c65f02015-06-29 18:29:00 +00001288 }
1289 }
Zachary Turner190fadc2016-03-22 17:58:09 +00001290 } while (FindNextFileW(hFind, &ffd) != 0);
Greg Clayton58c65f02015-06-29 18:29:00 +00001291
1292 FindClose(hFind);
1293#else
1294 lldb_utility::CleanUp <DIR *, int> dir_path_dir(opendir(dir_path), NULL, closedir);
1295 if (dir_path_dir.is_valid())
1296 {
1297 char dir_path_last_char = dir_path[strlen(dir_path) - 1];
1298
1299 long path_max = fpathconf (dirfd (dir_path_dir.get()), _PC_NAME_MAX);
1300#if defined (__APPLE_) && defined (__DARWIN_MAXPATHLEN)
1301 if (path_max < __DARWIN_MAXPATHLEN)
1302 path_max = __DARWIN_MAXPATHLEN;
1303#endif
1304 struct dirent *buf, *dp;
1305 buf = (struct dirent *) malloc (offsetof (struct dirent, d_name) + path_max + 1);
1306
1307 while (buf && readdir_r(dir_path_dir.get(), buf, &dp) == 0 && dp)
1308 {
1309 // Only search directories
1310 if (dp->d_type == DT_DIR || dp->d_type == DT_UNKNOWN)
1311 {
1312 size_t len = strlen(dp->d_name);
1313
1314 if (len == 1 && dp->d_name[0] == '.')
1315 continue;
1316
1317 if (len == 2 && dp->d_name[0] == '.' && dp->d_name[1] == '.')
1318 continue;
1319 }
1320
1321 FileSpec::FileType file_type = eFileTypeUnknown;
1322
1323 switch (dp->d_type)
1324 {
1325 default:
1326 case DT_UNKNOWN: file_type = eFileTypeUnknown; break;
1327 case DT_FIFO: file_type = eFileTypePipe; break;
1328 case DT_CHR: file_type = eFileTypeOther; break;
1329 case DT_DIR: file_type = eFileTypeDirectory; break;
1330 case DT_BLK: file_type = eFileTypeOther; break;
1331 case DT_REG: file_type = eFileTypeRegular; break;
1332 case DT_LNK: file_type = eFileTypeSymbolicLink; break;
1333 case DT_SOCK: file_type = eFileTypeSocket; break;
1334#if !defined(__OpenBSD__)
1335 case DT_WHT: file_type = eFileTypeOther; break;
1336#endif
1337 }
1338
1339 char child_path[PATH_MAX];
1340
1341 // Don't make paths with "/foo//bar", that just confuses everybody.
1342 int child_path_len;
1343 if (dir_path_last_char == '/')
1344 child_path_len = ::snprintf (child_path, sizeof(child_path), "%s%s", dir_path, dp->d_name);
1345 else
1346 child_path_len = ::snprintf (child_path, sizeof(child_path), "%s/%s", dir_path, dp->d_name);
1347
1348 if (child_path_len < (int)(sizeof(child_path) - 1))
1349 {
1350 // Don't resolve the file type or path
1351 FileSpec child_path_spec (child_path, false);
1352
1353 EnumerateDirectoryResult result = callback (file_type, child_path_spec);
1354
1355 switch (result)
1356 {
1357 case eEnumerateDirectoryResultNext:
1358 // Enumerate next entry in the current directory. We just
1359 // exit this switch and will continue enumerating the
1360 // current directory as we currently are...
1361 break;
1362
1363 case eEnumerateDirectoryResultEnter: // Recurse into the current entry if it is a directory or symlink, or next if not
1364 if (FileSpec::ForEachItemInDirectory (child_path, callback) == eEnumerateDirectoryResultQuit)
1365 {
1366 // The subdirectory returned Quit, which means to
1367 // stop all directory enumerations at all levels.
1368 if (buf)
1369 free (buf);
1370 return eEnumerateDirectoryResultQuit;
1371 }
1372 break;
1373
1374 case eEnumerateDirectoryResultExit: // Exit from the current directory at the current level.
1375 // Exit from this directory level and tell parent to
1376 // keep enumerating.
1377 if (buf)
1378 free (buf);
1379 return eEnumerateDirectoryResultNext;
1380
1381 case eEnumerateDirectoryResultQuit: // Stop directory enumerations at any level
1382 if (buf)
1383 free (buf);
1384 return eEnumerateDirectoryResultQuit;
1385 }
1386 }
1387 }
1388 if (buf)
1389 {
1390 free (buf);
1391 }
1392 }
1393#endif
1394 }
1395 // By default when exiting a directory, we tell the parent enumeration
1396 // to continue enumerating.
1397 return eEnumerateDirectoryResultNext;
1398}
1399
1400FileSpec::EnumerateDirectoryResult
Greg Clayton4272cc72011-02-02 02:24:04 +00001401FileSpec::EnumerateDirectory
1402(
1403 const char *dir_path,
1404 bool find_directories,
1405 bool find_files,
1406 bool find_other,
1407 EnumerateDirectoryCallbackType callback,
1408 void *callback_baton
1409)
1410{
Chaoren Lin0246b6f2015-06-29 19:07:35 +00001411 return ForEachItemInDirectory(dir_path,
1412 [&find_directories, &find_files, &find_other, &callback, &callback_baton]
1413 (FileType file_type, const FileSpec &file_spec) {
1414 switch (file_type)
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001415 {
Chaoren Lin0246b6f2015-06-29 19:07:35 +00001416 case FileType::eFileTypeDirectory:
1417 if (find_directories)
1418 return callback(callback_baton, file_type, file_spec);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001419 break;
Chaoren Lin0246b6f2015-06-29 19:07:35 +00001420 case FileType::eFileTypeRegular:
1421 if (find_files)
1422 return callback(callback_baton, file_type, file_spec);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001423 break;
Chaoren Lin0246b6f2015-06-29 19:07:35 +00001424 default:
1425 if (find_other)
1426 return callback(callback_baton, file_type, file_spec);
1427 break;
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001428 }
Chaoren Lin0246b6f2015-06-29 19:07:35 +00001429 return eEnumerateDirectoryResultNext;
1430 });
Greg Clayton4272cc72011-02-02 02:24:04 +00001431}
1432
Daniel Maleae0f8f572013-08-26 23:57:52 +00001433FileSpec
1434FileSpec::CopyByAppendingPathComponent (const char *new_path) const
1435{
Pavel Labathcc0e87c2016-03-11 08:44:44 +00001436 FileSpec ret = *this;
1437 ret.AppendPathComponent(new_path);
1438 return ret;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001439}
1440
1441FileSpec
1442FileSpec::CopyByRemovingLastPathComponent () const
1443{
1444 const bool resolve = false;
1445 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1446 return FileSpec("",resolve);
1447 if (m_directory.IsEmpty())
1448 return FileSpec("",resolve);
1449 if (m_filename.IsEmpty())
1450 {
1451 const char* dir_cstr = m_directory.GetCString();
1452 const char* last_slash_ptr = ::strrchr(dir_cstr, '/');
1453
1454 // check for obvious cases before doing the full thing
1455 if (!last_slash_ptr)
1456 return FileSpec("",resolve);
1457 if (last_slash_ptr == dir_cstr)
1458 return FileSpec("/",resolve);
1459
1460 size_t last_slash_pos = last_slash_ptr - dir_cstr+1;
1461 ConstString new_path(dir_cstr,last_slash_pos);
1462 return FileSpec(new_path.GetCString(),resolve);
1463 }
1464 else
1465 return FileSpec(m_directory.GetCString(),resolve);
1466}
1467
Greg Claytonfbb76342013-11-20 21:07:01 +00001468ConstString
Daniel Maleae0f8f572013-08-26 23:57:52 +00001469FileSpec::GetLastPathComponent () const
1470{
Greg Claytonfbb76342013-11-20 21:07:01 +00001471 if (m_filename)
1472 return m_filename;
1473 if (m_directory)
Daniel Maleae0f8f572013-08-26 23:57:52 +00001474 {
1475 const char* dir_cstr = m_directory.GetCString();
1476 const char* last_slash_ptr = ::strrchr(dir_cstr, '/');
1477 if (last_slash_ptr == NULL)
Greg Claytonfbb76342013-11-20 21:07:01 +00001478 return m_directory;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001479 if (last_slash_ptr == dir_cstr)
1480 {
1481 if (last_slash_ptr[1] == 0)
Greg Claytonfbb76342013-11-20 21:07:01 +00001482 return ConstString(last_slash_ptr);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001483 else
Greg Claytonfbb76342013-11-20 21:07:01 +00001484 return ConstString(last_slash_ptr+1);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001485 }
1486 if (last_slash_ptr[1] != 0)
Greg Claytonfbb76342013-11-20 21:07:01 +00001487 return ConstString(last_slash_ptr+1);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001488 const char* penultimate_slash_ptr = last_slash_ptr;
1489 while (*penultimate_slash_ptr)
1490 {
1491 --penultimate_slash_ptr;
1492 if (penultimate_slash_ptr == dir_cstr)
1493 break;
1494 if (*penultimate_slash_ptr == '/')
1495 break;
1496 }
Greg Claytonfbb76342013-11-20 21:07:01 +00001497 ConstString result(penultimate_slash_ptr+1,last_slash_ptr-penultimate_slash_ptr);
1498 return result;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001499 }
Greg Claytonfbb76342013-11-20 21:07:01 +00001500 return ConstString();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001501}
1502
1503void
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001504FileSpec::PrependPathComponent(const char *new_path)
Daniel Maleae0f8f572013-08-26 23:57:52 +00001505{
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001506 if (!new_path) return;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001507 const bool resolve = false;
1508 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1509 {
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001510 SetFile(new_path, resolve);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001511 return;
1512 }
1513 StreamString stream;
1514 if (m_filename.IsEmpty())
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001515 stream.Printf("%s/%s", new_path, m_directory.GetCString());
Daniel Maleae0f8f572013-08-26 23:57:52 +00001516 else if (m_directory.IsEmpty())
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001517 stream.Printf("%s/%s", new_path, m_filename.GetCString());
Daniel Maleae0f8f572013-08-26 23:57:52 +00001518 else
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001519 stream.Printf("%s/%s/%s", new_path, m_directory.GetCString(), m_filename.GetCString());
1520 SetFile(stream.GetData(), resolve);
1521}
1522
1523void
1524FileSpec::PrependPathComponent(const std::string &new_path)
1525{
1526 return PrependPathComponent(new_path.c_str());
1527}
1528
1529void
1530FileSpec::PrependPathComponent(const FileSpec &new_path)
1531{
1532 return PrependPathComponent(new_path.GetPath(false));
1533}
1534
1535void
1536FileSpec::AppendPathComponent(const char *new_path)
1537{
1538 if (!new_path) return;
Pavel Labathcc0e87c2016-03-11 08:44:44 +00001539
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001540 StreamString stream;
Pavel Labathcc0e87c2016-03-11 08:44:44 +00001541 if (!m_directory.IsEmpty())
1542 {
1543 stream.PutCString(m_directory.GetCString());
Pavel Labath144119b2016-04-04 14:39:12 +00001544 if (!IsPathSeparator(m_directory.GetStringRef().back(), m_syntax))
1545 stream.PutChar(GetPrefferedPathSeparator(m_syntax));
Pavel Labathcc0e87c2016-03-11 08:44:44 +00001546 }
1547
1548 if (!m_filename.IsEmpty())
1549 {
1550 stream.PutCString(m_filename.GetCString());
Pavel Labath144119b2016-04-04 14:39:12 +00001551 if (!IsPathSeparator(m_filename.GetStringRef().back(), m_syntax))
1552 stream.PutChar(GetPrefferedPathSeparator(m_syntax));
Pavel Labathcc0e87c2016-03-11 08:44:44 +00001553 }
1554
Jim Ingham291fd352016-08-23 17:13:33 +00001555 while (IsPathSeparator(new_path[0], m_syntax))
1556 new_path++;
1557
Pavel Labathcc0e87c2016-03-11 08:44:44 +00001558 stream.PutCString(new_path);
1559
1560 const bool resolve = false;
1561 SetFile(stream.GetData(), resolve, m_syntax);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001562}
1563
1564void
Chaoren Lind3173f32015-05-29 19:52:29 +00001565FileSpec::AppendPathComponent(const std::string &new_path)
1566{
1567 return AppendPathComponent(new_path.c_str());
1568}
1569
1570void
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001571FileSpec::AppendPathComponent(const FileSpec &new_path)
1572{
1573 return AppendPathComponent(new_path.GetPath(false));
1574}
1575
1576void
Daniel Maleae0f8f572013-08-26 23:57:52 +00001577FileSpec::RemoveLastPathComponent ()
1578{
1579 const bool resolve = false;
1580 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1581 {
1582 SetFile("",resolve);
1583 return;
1584 }
1585 if (m_directory.IsEmpty())
1586 {
1587 SetFile("",resolve);
1588 return;
1589 }
1590 if (m_filename.IsEmpty())
1591 {
1592 const char* dir_cstr = m_directory.GetCString();
1593 const char* last_slash_ptr = ::strrchr(dir_cstr, '/');
1594
1595 // check for obvious cases before doing the full thing
1596 if (!last_slash_ptr)
1597 {
1598 SetFile("",resolve);
1599 return;
1600 }
1601 if (last_slash_ptr == dir_cstr)
1602 {
1603 SetFile("/",resolve);
1604 return;
1605 }
1606 size_t last_slash_pos = last_slash_ptr - dir_cstr+1;
1607 ConstString new_path(dir_cstr,last_slash_pos);
1608 SetFile(new_path.GetCString(),resolve);
1609 }
1610 else
1611 SetFile(m_directory.GetCString(),resolve);
1612}
Greg Clayton1f746072012-08-29 21:13:06 +00001613//------------------------------------------------------------------
1614/// Returns true if the filespec represents an implementation source
1615/// file (files with a ".c", ".cpp", ".m", ".mm" (many more)
1616/// extension).
1617///
1618/// @return
1619/// \b true if the filespec represents an implementation source
1620/// file, \b false otherwise.
1621//------------------------------------------------------------------
1622bool
1623FileSpec::IsSourceImplementationFile () const
1624{
1625 ConstString extension (GetFileNameExtension());
1626 if (extension)
1627 {
Greg Clayton7bd4c602015-01-21 21:51:02 +00001628 static RegularExpression g_source_file_regex ("^([cC]|[mM]|[mM][mM]|[cC][pP][pP]|[cC]\\+\\+|[cC][xX][xX]|[cC][cC]|[cC][pP]|[sS]|[aA][sS][mM]|[fF]|[fF]77|[fF]90|[fF]95|[fF]03|[fF][oO][rR]|[fF][tT][nN]|[fF][pP][pP]|[aA][dD][aA]|[aA][dD][bB]|[aA][dD][sS])$");
Greg Clayton1f746072012-08-29 21:13:06 +00001629 return g_source_file_regex.Execute (extension.GetCString());
1630 }
1631 return false;
1632}
1633
Greg Claytona0ca6602012-10-18 16:33:33 +00001634bool
Chaoren Lin372e9062015-06-09 17:54:27 +00001635FileSpec::IsRelative() const
Greg Claytona0ca6602012-10-18 16:33:33 +00001636{
Zachary Turner270e99a2014-12-08 21:36:42 +00001637 const char *dir = m_directory.GetCString();
1638 llvm::StringRef directory(dir ? dir : "");
1639
1640 if (directory.size() > 0)
Greg Claytona0ca6602012-10-18 16:33:33 +00001641 {
Chaoren Lin1c614fe2015-05-28 17:02:45 +00001642 if (PathSyntaxIsPosix(m_syntax))
Zachary Turner270e99a2014-12-08 21:36:42 +00001643 {
1644 // If the path doesn't start with '/' or '~', return true
1645 switch (directory[0])
1646 {
1647 case '/':
1648 case '~':
1649 return false;
1650 default:
1651 return true;
1652 }
1653 }
Chaoren Lin1c614fe2015-05-28 17:02:45 +00001654 else
1655 {
1656 if (directory.size() >= 2 && directory[1] == ':')
1657 return false;
1658 if (directory[0] == '/')
1659 return false;
1660 return true;
1661 }
Greg Claytona0ca6602012-10-18 16:33:33 +00001662 }
1663 else if (m_filename)
1664 {
1665 // No directory, just a basename, return true
1666 return true;
1667 }
1668 return false;
1669}
Chaoren Lin372e9062015-06-09 17:54:27 +00001670
1671bool
1672FileSpec::IsAbsolute() const
1673{
1674 return !FileSpec::IsRelative();
1675}