blob: 074ec837ddad123ceb6a85264cdca5447b65636d [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;
188 if (!llvm::sys::path::home_directory(home_dir))
189 return;
190
191 // Overwrite the ~ with the first character of the homedir, and insert
192 // the rest. This way we only trigger one move, whereas an insert
193 // followed by a delete (or vice versa) would trigger two.
194 path[0] = home_dir[0];
195 path.insert(path.begin() + 1, home_dir.begin() + 1, home_dir.end());
196 return;
197 }
198
199 auto username_begin = path.begin()+1;
200 auto username_end = (slash_pos == llvm::StringRef::npos)
201 ? path.end()
202 : (path.begin() + slash_pos);
203 size_t replacement_length = std::distance(path.begin(), username_end);
204
205 llvm::SmallString<20> username(username_begin, username_end);
206 struct passwd *user_entry = ::getpwnam(username.c_str());
207 if (user_entry != nullptr)
208 {
209 // Copy over the first n characters of the path, where n is the smaller of the length
210 // of the home directory and the slash pos.
211 llvm::StringRef homedir(user_entry->pw_dir);
212 size_t initial_copy_length = std::min(homedir.size(), replacement_length);
213 auto src_begin = homedir.begin();
214 auto src_end = src_begin + initial_copy_length;
215 std::copy(src_begin, src_end, path.begin());
216 if (replacement_length > homedir.size())
Jim Inghamf818ca32010-07-01 01:48:53 +0000217 {
Zachary Turner3f559742014-08-07 17:33:36 +0000218 // We copied the entire home directory, but the ~username portion of the path was
219 // longer, so there's characters that need to be removed.
220 path.erase(path.begin() + initial_copy_length, username_end);
Jim Inghamf818ca32010-07-01 01:48:53 +0000221 }
Zachary Turner3f559742014-08-07 17:33:36 +0000222 else if (replacement_length < homedir.size())
223 {
224 // We copied all the way up to the slash in the destination, but there's still more
225 // characters that need to be inserted.
226 path.insert(username_end, src_end, homedir.end());
227 }
Jim Inghamf818ca32010-07-01 01:48:53 +0000228 }
229 else
230 {
Zachary Turner3f559742014-08-07 17:33:36 +0000231 // Unable to resolve username (user doesn't exist?)
232 path.clear();
Jim Inghamf818ca32010-07-01 01:48:53 +0000233 }
Zachary Turner3f559742014-08-07 17:33:36 +0000234#endif
Jim Inghamf818ca32010-07-01 01:48:53 +0000235}
236
Greg Claytonc982c762010-07-09 20:39:50 +0000237size_t
Jim Ingham84363072011-02-08 23:24:09 +0000238FileSpec::ResolvePartialUsername (const char *partial_name, StringList &matches)
239{
240#ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
241 size_t extant_entries = matches.GetSize();
242
243 setpwent();
244 struct passwd *user_entry;
245 const char *name_start = partial_name + 1;
246 std::set<std::string> name_list;
247
248 while ((user_entry = getpwent()) != NULL)
249 {
250 if (strstr(user_entry->pw_name, name_start) == user_entry->pw_name)
251 {
252 std::string tmp_buf("~");
253 tmp_buf.append(user_entry->pw_name);
254 tmp_buf.push_back('/');
255 name_list.insert(tmp_buf);
256 }
257 }
258 std::set<std::string>::iterator pos, end = name_list.end();
259 for (pos = name_list.begin(); pos != end; pos++)
260 {
261 matches.AppendString((*pos).c_str());
262 }
263 return matches.GetSize() - extant_entries;
264#else
265 // Resolving home directories is not supported, just copy the path...
266 return 0;
267#endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
268}
269
Zachary Turner3f559742014-08-07 17:33:36 +0000270void
271FileSpec::Resolve (llvm::SmallVectorImpl<char> &path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000272{
Zachary Turner3f559742014-08-07 17:33:36 +0000273 if (path.empty())
274 return;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000275
Greg Clayton45319462011-02-08 00:35:34 +0000276#ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
Zachary Turner3f559742014-08-07 17:33:36 +0000277 if (path[0] == '~')
278 ResolveUsername(path);
Greg Clayton45319462011-02-08 00:35:34 +0000279#endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000280
Jason Molenda671a29d2015-02-25 02:35:25 +0000281 // Save a copy of the original path that's passed in
Zachary Turner190fadc2016-03-22 17:58:09 +0000282 llvm::SmallString<128> original_path(path.begin(), path.end());
Jason Molenda671a29d2015-02-25 02:35:25 +0000283
Zachary Turner3f559742014-08-07 17:33:36 +0000284 llvm::sys::fs::make_absolute(path);
Zachary Turner190fadc2016-03-22 17:58:09 +0000285 if (!llvm::sys::fs::exists(path))
Jason Molenda671a29d2015-02-25 02:35:25 +0000286 {
287 path.clear();
288 path.append(original_path.begin(), original_path.end());
289 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000290}
291
Jason Molenda68c85212014-10-15 03:04:33 +0000292FileSpec::FileSpec() :
293 m_directory(),
294 m_filename(),
295 m_syntax(FileSystem::GetNativePathSyntax())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000296{
297}
298
299//------------------------------------------------------------------
300// Default constructor that can take an optional full path to a
301// file on disk.
302//------------------------------------------------------------------
Zachary Turnerdf62f202014-08-07 17:33:07 +0000303FileSpec::FileSpec(const char *pathname, bool resolve_path, PathSyntax syntax) :
Jim Ingham0909e5f2010-09-16 00:57:33 +0000304 m_directory(),
Greg Clayton7481c202010-11-08 00:28:40 +0000305 m_filename(),
Jason Molenda68c85212014-10-15 03:04:33 +0000306 m_is_resolved(false),
307 m_syntax(syntax)
Jim Ingham0909e5f2010-09-16 00:57:33 +0000308{
309 if (pathname && pathname[0])
Zachary Turnerdf62f202014-08-07 17:33:07 +0000310 SetFile(pathname, resolve_path, syntax);
Jim Ingham0909e5f2010-09-16 00:57:33 +0000311}
312
Chaoren Linf34f4102015-05-09 01:21:32 +0000313FileSpec::FileSpec(const char *pathname, bool resolve_path, ArchSpec arch) :
Chaoren Lind3173f32015-05-29 19:52:29 +0000314 FileSpec{pathname, resolve_path, arch.GetTriple().isOSWindows() ? ePathSyntaxWindows : ePathSyntaxPosix}
315{
316}
317
318FileSpec::FileSpec(const std::string &path, bool resolve_path, PathSyntax syntax) :
319 FileSpec{path.c_str(), resolve_path, syntax}
320{
321}
322
323FileSpec::FileSpec(const std::string &path, bool resolve_path, ArchSpec arch) :
324 FileSpec{path.c_str(), resolve_path, arch}
Chaoren Linf34f4102015-05-09 01:21:32 +0000325{
326}
327
Jim Ingham0909e5f2010-09-16 00:57:33 +0000328//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000329// Copy constructor
330//------------------------------------------------------------------
331FileSpec::FileSpec(const FileSpec& rhs) :
332 m_directory (rhs.m_directory),
Greg Clayton7481c202010-11-08 00:28:40 +0000333 m_filename (rhs.m_filename),
Zachary Turnerdf62f202014-08-07 17:33:07 +0000334 m_is_resolved (rhs.m_is_resolved),
335 m_syntax (rhs.m_syntax)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000336{
337}
338
339//------------------------------------------------------------------
340// Copy constructor
341//------------------------------------------------------------------
342FileSpec::FileSpec(const FileSpec* rhs) :
343 m_directory(),
344 m_filename()
345{
346 if (rhs)
347 *this = *rhs;
348}
349
350//------------------------------------------------------------------
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +0000351// Virtual destructor in case anyone inherits from this class.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000352//------------------------------------------------------------------
353FileSpec::~FileSpec()
354{
355}
356
357//------------------------------------------------------------------
358// Assignment operator.
359//------------------------------------------------------------------
360const FileSpec&
361FileSpec::operator= (const FileSpec& rhs)
362{
363 if (this != &rhs)
364 {
365 m_directory = rhs.m_directory;
366 m_filename = rhs.m_filename;
Greg Clayton7481c202010-11-08 00:28:40 +0000367 m_is_resolved = rhs.m_is_resolved;
Zachary Turnerdf62f202014-08-07 17:33:07 +0000368 m_syntax = rhs.m_syntax;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000369 }
370 return *this;
371}
372
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000373//------------------------------------------------------------------
374// Update the contents of this object with a new path. The path will
375// be split up into a directory and filename and stored as uniqued
376// string values for quick comparison and efficient memory usage.
377//------------------------------------------------------------------
378void
Zachary Turnerdf62f202014-08-07 17:33:07 +0000379FileSpec::SetFile (const char *pathname, bool resolve, PathSyntax syntax)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000380{
381 m_filename.Clear();
382 m_directory.Clear();
Greg Clayton7481c202010-11-08 00:28:40 +0000383 m_is_resolved = false;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000384 m_syntax = (syntax == ePathSyntaxHostNative) ? FileSystem::GetNativePathSyntax() : syntax;
Zachary Turnerdf62f202014-08-07 17:33:07 +0000385
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000386 if (pathname == NULL || pathname[0] == '\0')
387 return;
388
Pavel Labath144119b2016-04-04 14:39:12 +0000389 llvm::SmallString<64> resolved(pathname);
Zachary Turnerdf62f202014-08-07 17:33:07 +0000390
Jim Ingham0909e5f2010-09-16 00:57:33 +0000391 if (resolve)
392 {
Pavel Labath144119b2016-04-04 14:39:12 +0000393 FileSpec::Resolve (resolved);
Zachary Turner3f559742014-08-07 17:33:36 +0000394 m_is_resolved = true;
Jim Ingham0909e5f2010-09-16 00:57:33 +0000395 }
Zachary Turnerc7a17ed2014-12-01 23:13:32 +0000396
Pavel Labatha212c582016-04-14 09:38:06 +0000397 Normalize(resolved, syntax);
398
Pavel Labath144119b2016-04-04 14:39:12 +0000399 llvm::StringRef resolve_path_ref(resolved.c_str());
400 size_t dir_end = ParentPathEnd(resolve_path_ref, syntax);
401 if (dir_end == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000402 {
Pavel Labath144119b2016-04-04 14:39:12 +0000403 m_filename.SetString(resolve_path_ref);
404 return;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000405 }
Pavel Labath144119b2016-04-04 14:39:12 +0000406
407 m_directory.SetString(resolve_path_ref.substr(0, dir_end));
408
409 size_t filename_begin = dir_end;
410 size_t root_dir_start = RootDirStart(resolve_path_ref, syntax);
411 while (filename_begin != llvm::StringRef::npos && filename_begin < resolve_path_ref.size() &&
412 filename_begin != root_dir_start && IsPathSeparator(resolve_path_ref[filename_begin], syntax))
413 ++filename_begin;
414 m_filename.SetString((filename_begin == llvm::StringRef::npos || filename_begin >= resolve_path_ref.size())
415 ? "."
416 : resolve_path_ref.substr(filename_begin));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000417}
418
Chaoren Lind3173f32015-05-29 19:52:29 +0000419void
Chaoren Lin44145d72015-05-29 19:52:37 +0000420FileSpec::SetFile(const char *pathname, bool resolve, ArchSpec arch)
421{
422 return SetFile(pathname, resolve,
423 arch.GetTriple().isOSWindows()
424 ? ePathSyntaxWindows
425 : ePathSyntaxPosix);
426}
427
428void
Chaoren Lind3173f32015-05-29 19:52:29 +0000429FileSpec::SetFile(const std::string &pathname, bool resolve, PathSyntax syntax)
430{
431 return SetFile(pathname.c_str(), resolve, syntax);
432}
433
Chaoren Lin44145d72015-05-29 19:52:37 +0000434void
435FileSpec::SetFile(const std::string &pathname, bool resolve, ArchSpec arch)
436{
437 return SetFile(pathname.c_str(), resolve, arch);
438}
439
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000440//----------------------------------------------------------------------
441// Convert to pointer operator. This allows code to check any FileSpec
442// objects to see if they contain anything valid using code such as:
443//
444// if (file_spec)
445// {}
446//----------------------------------------------------------------------
Greg Clayton6372d1c2011-09-12 04:00:42 +0000447FileSpec::operator bool() const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000448{
Greg Clayton6372d1c2011-09-12 04:00:42 +0000449 return m_filename || m_directory;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000450}
451
452//----------------------------------------------------------------------
453// Logical NOT operator. This allows code to check any FileSpec
454// objects to see if they are invalid using code such as:
455//
456// if (!file_spec)
457// {}
458//----------------------------------------------------------------------
459bool
460FileSpec::operator!() const
461{
462 return !m_directory && !m_filename;
463}
464
Zachary Turner74e08ca2016-03-02 22:05:52 +0000465bool
466FileSpec::DirectoryEquals(const FileSpec &rhs) const
467{
468 const bool case_sensitive = IsCaseSensitive() || rhs.IsCaseSensitive();
469 return ConstString::Equals(m_directory, rhs.m_directory, case_sensitive);
470}
471
472bool
473FileSpec::FileEquals(const FileSpec &rhs) const
474{
475 const bool case_sensitive = IsCaseSensitive() || rhs.IsCaseSensitive();
476 return ConstString::Equals(m_filename, rhs.m_filename, case_sensitive);
477}
478
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000479//------------------------------------------------------------------
480// Equal to operator
481//------------------------------------------------------------------
482bool
483FileSpec::operator== (const FileSpec& rhs) const
484{
Zachary Turner74e08ca2016-03-02 22:05:52 +0000485 if (!FileEquals(rhs))
Zachary Turner47c03462016-02-24 21:26:47 +0000486 return false;
Zachary Turner74e08ca2016-03-02 22:05:52 +0000487 if (DirectoryEquals(rhs))
Zachary Turner47c03462016-02-24 21:26:47 +0000488 return true;
489
490 // TODO: determine if we want to keep this code in here.
491 // The code below was added to handle a case where we were
492 // trying to set a file and line breakpoint and one path
493 // was resolved, and the other not and the directory was
494 // in a mount point that resolved to a more complete path:
495 // "/tmp/a.c" == "/private/tmp/a.c". I might end up pulling
496 // this out...
497 if (IsResolved() && rhs.IsResolved())
Greg Clayton7481c202010-11-08 00:28:40 +0000498 {
Zachary Turner47c03462016-02-24 21:26:47 +0000499 // Both paths are resolved, no need to look further...
500 return false;
Greg Clayton7481c202010-11-08 00:28:40 +0000501 }
Zachary Turner47c03462016-02-24 21:26:47 +0000502
503 FileSpec resolved_lhs(*this);
504
505 // If "this" isn't resolved, resolve it
506 if (!IsResolved())
507 {
508 if (resolved_lhs.ResolvePath())
509 {
510 // This path wasn't resolved but now it is. Check if the resolved
511 // directory is the same as our unresolved directory, and if so,
512 // we can mark this object as resolved to avoid more future resolves
513 m_is_resolved = (m_directory == resolved_lhs.m_directory);
514 }
515 else
516 return false;
517 }
518
519 FileSpec resolved_rhs(rhs);
520 if (!rhs.IsResolved())
521 {
522 if (resolved_rhs.ResolvePath())
523 {
524 // rhs's path wasn't resolved but now it is. Check if the resolved
525 // directory is the same as rhs's unresolved directory, and if so,
526 // we can mark this object as resolved to avoid more future resolves
527 rhs.m_is_resolved = (rhs.m_directory == resolved_rhs.m_directory);
528 }
529 else
530 return false;
531 }
532
533 // If we reach this point in the code we were able to resolve both paths
534 // and since we only resolve the paths if the basenames are equal, then
535 // we can just check if both directories are equal...
Zachary Turner74e08ca2016-03-02 22:05:52 +0000536 return DirectoryEquals(rhs);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000537}
538
539//------------------------------------------------------------------
540// Not equal to operator
541//------------------------------------------------------------------
542bool
543FileSpec::operator!= (const FileSpec& rhs) const
544{
Greg Clayton7481c202010-11-08 00:28:40 +0000545 return !(*this == rhs);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000546}
547
548//------------------------------------------------------------------
549// Less than operator
550//------------------------------------------------------------------
551bool
552FileSpec::operator< (const FileSpec& rhs) const
553{
554 return FileSpec::Compare(*this, rhs, true) < 0;
555}
556
557//------------------------------------------------------------------
558// Dump a FileSpec object to a stream
559//------------------------------------------------------------------
560Stream&
561lldb_private::operator << (Stream &s, const FileSpec& f)
562{
563 f.Dump(&s);
564 return s;
565}
566
567//------------------------------------------------------------------
568// Clear this object by releasing both the directory and filename
569// string values and making them both the empty string.
570//------------------------------------------------------------------
571void
572FileSpec::Clear()
573{
574 m_directory.Clear();
575 m_filename.Clear();
576}
577
578//------------------------------------------------------------------
579// Compare two FileSpec objects. If "full" is true, then both
580// the directory and the filename must match. If "full" is false,
581// then the directory names for "a" and "b" are only compared if
582// they are both non-empty. This allows a FileSpec object to only
583// contain a filename and it can match FileSpec objects that have
584// matching filenames with different paths.
585//
586// Return -1 if the "a" is less than "b", 0 if "a" is equal to "b"
587// and "1" if "a" is greater than "b".
588//------------------------------------------------------------------
589int
590FileSpec::Compare(const FileSpec& a, const FileSpec& b, bool full)
591{
592 int result = 0;
593
Zachary Turner47c03462016-02-24 21:26:47 +0000594 // case sensitivity of compare
595 const bool case_sensitive = a.IsCaseSensitive() || b.IsCaseSensitive();
596
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000597 // If full is true, then we must compare both the directory and filename.
598
599 // If full is false, then if either directory is empty, then we match on
600 // the basename only, and if both directories have valid values, we still
601 // do a full compare. This allows for matching when we just have a filename
602 // in one of the FileSpec objects.
603
604 if (full || (a.m_directory && b.m_directory))
605 {
Zachary Turner47c03462016-02-24 21:26:47 +0000606 result = ConstString::Compare(a.m_directory, b.m_directory, case_sensitive);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000607 if (result)
608 return result;
609 }
Zachary Turner47c03462016-02-24 21:26:47 +0000610 return ConstString::Compare(a.m_filename, b.m_filename, case_sensitive);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000611}
612
613bool
Jim Ingham96a15962014-11-15 01:54:26 +0000614FileSpec::Equal (const FileSpec& a, const FileSpec& b, bool full, bool remove_backups)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000615{
Zachary Turner47c03462016-02-24 21:26:47 +0000616 // case sensitivity of equality test
617 const bool case_sensitive = a.IsCaseSensitive() || b.IsCaseSensitive();
618
Jim Ingham87df91b2011-09-23 00:54:11 +0000619 if (!full && (a.GetDirectory().IsEmpty() || b.GetDirectory().IsEmpty()))
Zachary Turner47c03462016-02-24 21:26:47 +0000620 return ConstString::Equals(a.m_filename, b.m_filename, case_sensitive);
Jim Ingham96a15962014-11-15 01:54:26 +0000621 else if (remove_backups == false)
Jim Ingham87df91b2011-09-23 00:54:11 +0000622 return a == b;
Jim Ingham96a15962014-11-15 01:54:26 +0000623 else
624 {
Zachary Turner47c03462016-02-24 21:26:47 +0000625 if (!ConstString::Equals(a.m_filename, b.m_filename, case_sensitive))
Jim Ingham96a15962014-11-15 01:54:26 +0000626 return false;
Zachary Turner47c03462016-02-24 21:26:47 +0000627 if (ConstString::Equals(a.m_directory, b.m_directory, case_sensitive))
Jim Ingham96a15962014-11-15 01:54:26 +0000628 return true;
629 ConstString a_without_dots;
630 ConstString b_without_dots;
631
632 RemoveBackupDots (a.m_directory, a_without_dots);
633 RemoveBackupDots (b.m_directory, b_without_dots);
Zachary Turner47c03462016-02-24 21:26:47 +0000634 return ConstString::Equals(a_without_dots, b_without_dots, case_sensitive);
Jim Ingham96a15962014-11-15 01:54:26 +0000635 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000636}
637
Jim Ingham96a15962014-11-15 01:54:26 +0000638void
Greg Clayton5a271952015-06-02 22:43:29 +0000639FileSpec::NormalizePath ()
640{
641 ConstString normalized_directory;
642 FileSpec::RemoveBackupDots(m_directory, normalized_directory);
643 m_directory = normalized_directory;
644}
645
646void
Jim Ingham96a15962014-11-15 01:54:26 +0000647FileSpec::RemoveBackupDots (const ConstString &input_const_str, ConstString &result_const_str)
648{
649 const char *input = input_const_str.GetCString();
650 result_const_str.Clear();
651 if (!input || input[0] == '\0')
652 return;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000653
Jim Ingham96a15962014-11-15 01:54:26 +0000654 const char win_sep = '\\';
655 const char unix_sep = '/';
656 char found_sep;
657 const char *win_backup = "\\..";
658 const char *unix_backup = "/..";
659
660 bool is_win = false;
661
662 // Determine the platform for the path (win or unix):
663
664 if (input[0] == win_sep)
665 is_win = true;
666 else if (input[0] == unix_sep)
667 is_win = false;
668 else if (input[1] == ':')
669 is_win = true;
670 else if (strchr(input, unix_sep) != nullptr)
671 is_win = false;
672 else if (strchr(input, win_sep) != nullptr)
673 is_win = true;
674 else
675 {
676 // No separators at all, no reason to do any work here.
677 result_const_str = input_const_str;
678 return;
679 }
680
681 llvm::StringRef backup_sep;
682 if (is_win)
683 {
684 found_sep = win_sep;
685 backup_sep = win_backup;
686 }
687 else
688 {
689 found_sep = unix_sep;
690 backup_sep = unix_backup;
691 }
692
693 llvm::StringRef input_ref(input);
694 llvm::StringRef curpos(input);
695
696 bool had_dots = false;
697 std::string result;
698
699 while (1)
700 {
701 // Start of loop
702 llvm::StringRef before_sep;
703 std::pair<llvm::StringRef, llvm::StringRef> around_sep = curpos.split(backup_sep);
704
705 before_sep = around_sep.first;
706 curpos = around_sep.second;
707
708 if (curpos.empty())
709 {
710 if (had_dots)
711 {
Greg Clayton9c284c42015-05-05 20:26:58 +0000712 while (before_sep.startswith("//"))
713 before_sep = before_sep.substr(1);
Jim Ingham96a15962014-11-15 01:54:26 +0000714 if (!before_sep.empty())
715 {
716 result.append(before_sep.data(), before_sep.size());
717 }
718 }
719 break;
720 }
721 had_dots = true;
722
723 unsigned num_backups = 1;
724 while (curpos.startswith(backup_sep))
725 {
726 num_backups++;
727 curpos = curpos.slice(backup_sep.size(), curpos.size());
728 }
729
730 size_t end_pos = before_sep.size();
731 while (num_backups-- > 0)
732 {
733 end_pos = before_sep.rfind(found_sep, end_pos);
734 if (end_pos == llvm::StringRef::npos)
735 {
736 result_const_str = input_const_str;
737 return;
738 }
739 }
740 result.append(before_sep.data(), end_pos);
741 }
742
743 if (had_dots)
744 result_const_str.SetCString(result.c_str());
745 else
746 result_const_str = input_const_str;
747
748 return;
749}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000750
751//------------------------------------------------------------------
752// Dump the object to the supplied stream. If the object contains
753// a valid directory name, it will be displayed followed by a
754// directory delimiter, and the filename.
755//------------------------------------------------------------------
756void
Chaoren Lin1c614fe2015-05-28 17:02:45 +0000757FileSpec::Dump(Stream *s) const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000758{
Enrico Granata80fcdd42012-11-03 00:09:46 +0000759 if (s)
760 {
Chaoren Lin1c614fe2015-05-28 17:02:45 +0000761 std::string path{GetPath(true)};
762 s->PutCString(path.c_str());
Pavel Labath144119b2016-04-04 14:39:12 +0000763 char path_separator = GetPrefferedPathSeparator(m_syntax);
Chaoren Lin1c614fe2015-05-28 17:02:45 +0000764 if (!m_filename && !path.empty() && path.back() != path_separator)
765 s->PutChar(path_separator);
Enrico Granata80fcdd42012-11-03 00:09:46 +0000766 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000767}
768
769//------------------------------------------------------------------
770// Returns true if the file exists.
771//------------------------------------------------------------------
772bool
773FileSpec::Exists () const
774{
775 struct stat file_stats;
776 return GetFileStats (this, &file_stats);
777}
778
Caroline Tice428a9a52010-09-10 04:48:55 +0000779bool
Greg Clayton5acc1252014-08-15 18:00:45 +0000780FileSpec::Readable () const
781{
782 const uint32_t permissions = GetPermissions();
783 if (permissions & eFilePermissionsEveryoneR)
784 return true;
785 return false;
786}
787
788bool
Caroline Tice428a9a52010-09-10 04:48:55 +0000789FileSpec::ResolveExecutableLocation ()
790{
Greg Clayton274060b2010-10-20 20:54:39 +0000791 if (!m_directory)
Caroline Tice391a9602010-09-12 00:10:52 +0000792 {
Greg Clayton58f41712011-01-25 21:32:01 +0000793 const char *file_cstr = m_filename.GetCString();
794 if (file_cstr)
Caroline Tice391a9602010-09-12 00:10:52 +0000795 {
Greg Clayton58f41712011-01-25 21:32:01 +0000796 const std::string file_str (file_cstr);
Enrico Granata404ab372014-11-04 19:33:45 +0000797 llvm::ErrorOr<std::string> error_or_path = llvm::sys::findProgramByName (file_str);
798 if (!error_or_path)
799 return false;
800 std::string path = error_or_path.get();
Rafael Espindolaff89ff22013-06-13 19:25:41 +0000801 llvm::StringRef dir_ref = llvm::sys::path::parent_path(path);
Greg Clayton6bc87392014-05-30 21:06:57 +0000802 if (!dir_ref.empty())
Caroline Tice391a9602010-09-12 00:10:52 +0000803 {
Greg Clayton58f41712011-01-25 21:32:01 +0000804 // FindProgramByName returns "." if it can't find the file.
805 if (strcmp (".", dir_ref.data()) == 0)
806 return false;
807
808 m_directory.SetCString (dir_ref.data());
809 if (Exists())
Caroline Tice391a9602010-09-12 00:10:52 +0000810 return true;
Greg Clayton58f41712011-01-25 21:32:01 +0000811 else
812 {
813 // If FindProgramByName found the file, it returns the directory + filename in its return results.
814 // We need to separate them.
815 FileSpec tmp_file (dir_ref.data(), false);
816 if (tmp_file.Exists())
817 {
818 m_directory = tmp_file.m_directory;
819 return true;
820 }
Caroline Tice391a9602010-09-12 00:10:52 +0000821 }
822 }
823 }
824 }
825
826 return false;
Caroline Tice428a9a52010-09-10 04:48:55 +0000827}
828
Jim Ingham0909e5f2010-09-16 00:57:33 +0000829bool
830FileSpec::ResolvePath ()
831{
Greg Clayton7481c202010-11-08 00:28:40 +0000832 if (m_is_resolved)
833 return true; // We have already resolved this path
834
835 char path_buf[PATH_MAX];
Zachary Turnerdf62f202014-08-07 17:33:07 +0000836 if (!GetPath (path_buf, PATH_MAX, false))
Jim Ingham0909e5f2010-09-16 00:57:33 +0000837 return false;
Greg Clayton7481c202010-11-08 00:28:40 +0000838 // SetFile(...) will set m_is_resolved correctly if it can resolve the path
Jim Ingham0909e5f2010-09-16 00:57:33 +0000839 SetFile (path_buf, true);
Greg Clayton7481c202010-11-08 00:28:40 +0000840 return m_is_resolved;
Jim Ingham0909e5f2010-09-16 00:57:33 +0000841}
842
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000843uint64_t
844FileSpec::GetByteSize() const
845{
846 struct stat file_stats;
847 if (GetFileStats (this, &file_stats))
848 return file_stats.st_size;
849 return 0;
850}
851
Zachary Turnerdf62f202014-08-07 17:33:07 +0000852FileSpec::PathSyntax
853FileSpec::GetPathSyntax() const
854{
855 return m_syntax;
856}
857
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000858FileSpec::FileType
859FileSpec::GetFileType () const
860{
861 struct stat file_stats;
862 if (GetFileStats (this, &file_stats))
863 {
864 mode_t file_type = file_stats.st_mode & S_IFMT;
865 switch (file_type)
866 {
867 case S_IFDIR: return eFileTypeDirectory;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000868 case S_IFREG: return eFileTypeRegular;
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000869#ifndef _WIN32
870 case S_IFIFO: return eFileTypePipe;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000871 case S_IFSOCK: return eFileTypeSocket;
872 case S_IFLNK: return eFileTypeSymbolicLink;
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000873#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000874 default:
875 break;
876 }
Greg Clayton4272cc72011-02-02 02:24:04 +0000877 return eFileTypeUnknown;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000878 }
879 return eFileTypeInvalid;
880}
881
Oleksiy Vyalov8a578bf2015-07-21 01:28:22 +0000882bool
883FileSpec::IsSymbolicLink () const
884{
885 char resolved_path[PATH_MAX];
886 if (!GetPath (resolved_path, sizeof (resolved_path)))
887 return false;
888
889#ifdef _WIN32
Zachary Turner190fadc2016-03-22 17:58:09 +0000890 std::wstring wpath;
891 if (!llvm::ConvertUTF8toWide(resolved_path, wpath))
892 return false;
893 auto attrs = ::GetFileAttributesW(wpath.c_str());
Oleksiy Vyalov8a578bf2015-07-21 01:28:22 +0000894 if (attrs == INVALID_FILE_ATTRIBUTES)
895 return false;
896
897 return (attrs & FILE_ATTRIBUTE_REPARSE_POINT);
898#else
899 struct stat file_stats;
900 if (::lstat (resolved_path, &file_stats) != 0)
901 return false;
902
903 return (file_stats.st_mode & S_IFMT) == S_IFLNK;
904#endif
905}
906
Greg Claytonfbb76342013-11-20 21:07:01 +0000907uint32_t
908FileSpec::GetPermissions () const
909{
910 uint32_t file_permissions = 0;
911 if (*this)
Chaoren Lind3173f32015-05-29 19:52:29 +0000912 FileSystem::GetFilePermissions(*this, file_permissions);
Greg Claytonfbb76342013-11-20 21:07:01 +0000913 return file_permissions;
914}
915
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000916TimeValue
917FileSpec::GetModificationTime () const
918{
919 TimeValue mod_time;
920 struct stat file_stats;
921 if (GetFileStats (this, &file_stats))
Eli Friedman6abb6342010-06-11 04:52:22 +0000922 mod_time.OffsetWithSeconds(file_stats.st_mtime);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000923 return mod_time;
924}
925
926//------------------------------------------------------------------
927// Directory string get accessor.
928//------------------------------------------------------------------
929ConstString &
930FileSpec::GetDirectory()
931{
932 return m_directory;
933}
934
935//------------------------------------------------------------------
936// Directory string const get accessor.
937//------------------------------------------------------------------
938const ConstString &
939FileSpec::GetDirectory() const
940{
941 return m_directory;
942}
943
944//------------------------------------------------------------------
945// Filename string get accessor.
946//------------------------------------------------------------------
947ConstString &
948FileSpec::GetFilename()
949{
950 return m_filename;
951}
952
953//------------------------------------------------------------------
954// Filename string const get accessor.
955//------------------------------------------------------------------
956const ConstString &
957FileSpec::GetFilename() const
958{
959 return m_filename;
960}
961
962//------------------------------------------------------------------
963// Extract the directory and path into a fixed buffer. This is
964// needed as the directory and path are stored in separate string
965// values.
966//------------------------------------------------------------------
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000967size_t
Zachary Turnerdf62f202014-08-07 17:33:07 +0000968FileSpec::GetPath(char *path, size_t path_max_len, bool denormalize) const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000969{
Zachary Turnerb6d99242014-08-08 23:54:35 +0000970 if (!path)
971 return 0;
972
Zachary Turnerdf62f202014-08-07 17:33:07 +0000973 std::string result = GetPath(denormalize);
Ilia K686b1fe2015-02-27 19:43:08 +0000974 ::snprintf(path, path_max_len, "%s", result.c_str());
975 return std::min(path_max_len-1, result.length());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000976}
977
Greg Claytona44c1e62013-04-29 16:36:27 +0000978std::string
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000979FileSpec::GetPath(bool denormalize) const
Jason Molendaa7ae4672013-04-29 09:46:43 +0000980{
Zachary Turnerdf62f202014-08-07 17:33:07 +0000981 llvm::SmallString<64> result;
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000982 GetPath(result, denormalize);
Zachary Turnerdf62f202014-08-07 17:33:07 +0000983 return std::string(result.begin(), result.end());
Jason Molendaa7ae4672013-04-29 09:46:43 +0000984}
985
Chaoren Lind3173f32015-05-29 19:52:29 +0000986const char *
987FileSpec::GetCString(bool denormalize) const
988{
989 return ConstString{GetPath(denormalize)}.AsCString(NULL);
990}
991
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000992void
993FileSpec::GetPath(llvm::SmallVectorImpl<char> &path, bool denormalize) const
994{
Chaoren Lin1c614fe2015-05-28 17:02:45 +0000995 path.append(m_directory.GetStringRef().begin(), m_directory.GetStringRef().end());
Pavel Labath144119b2016-04-04 14:39:12 +0000996 if (m_directory && m_filename && !IsPathSeparator(m_directory.GetStringRef().back(), m_syntax))
997 path.insert(path.end(), GetPrefferedPathSeparator(m_syntax));
Chaoren Lin1c614fe2015-05-28 17:02:45 +0000998 path.append(m_filename.GetStringRef().begin(), m_filename.GetStringRef().end());
Zachary Turner4e8ddf52015-04-09 18:08:50 +0000999 Normalize(path, m_syntax);
1000 if (denormalize && !path.empty())
Chaoren Lin1c614fe2015-05-28 17:02:45 +00001001 Denormalize(path, m_syntax);
Zachary Turner4e8ddf52015-04-09 18:08:50 +00001002}
1003
Enrico Granataa9dbf432011-10-17 21:45:27 +00001004ConstString
1005FileSpec::GetFileNameExtension () const
1006{
Greg Clayton1f746072012-08-29 21:13:06 +00001007 if (m_filename)
1008 {
1009 const char *filename = m_filename.GetCString();
1010 const char* dot_pos = strrchr(filename, '.');
1011 if (dot_pos && dot_pos[1] != '\0')
1012 return ConstString(dot_pos+1);
1013 }
1014 return ConstString();
Enrico Granataa9dbf432011-10-17 21:45:27 +00001015}
1016
1017ConstString
1018FileSpec::GetFileNameStrippingExtension () const
1019{
1020 const char *filename = m_filename.GetCString();
1021 if (filename == NULL)
1022 return ConstString();
1023
Johnny Chenf5df5372011-10-18 19:28:30 +00001024 const char* dot_pos = strrchr(filename, '.');
Enrico Granataa9dbf432011-10-17 21:45:27 +00001025 if (dot_pos == NULL)
1026 return m_filename;
1027
1028 return ConstString(filename, dot_pos-filename);
1029}
1030
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001031//------------------------------------------------------------------
1032// Returns a shared pointer to a data buffer that contains all or
1033// part of the contents of a file. The data is memory mapped and
1034// will lazily page in data from the file as memory is accessed.
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001035// The data that is mapped will start "file_offset" bytes into the
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001036// file, and "file_size" bytes will be mapped. If "file_size" is
1037// greater than the number of bytes available in the file starting
1038// at "file_offset", the number of bytes will be appropriately
1039// truncated. The final number of bytes that get mapped can be
1040// verified using the DataBuffer::GetByteSize() function.
1041//------------------------------------------------------------------
1042DataBufferSP
1043FileSpec::MemoryMapFileContents(off_t file_offset, size_t file_size) const
1044{
1045 DataBufferSP data_sp;
Greg Clayton7b0992d2013-04-18 22:45:39 +00001046 std::unique_ptr<DataBufferMemoryMap> mmap_data(new DataBufferMemoryMap());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001047 if (mmap_data.get())
1048 {
Greg Claytond398a1c2013-04-20 00:23:26 +00001049 const size_t mapped_length = mmap_data->MemoryMapFromFileSpec (this, file_offset, file_size);
1050 if (((file_size == SIZE_MAX) && (mapped_length > 0)) || (mapped_length >= file_size))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001051 data_sp.reset(mmap_data.release());
1052 }
1053 return data_sp;
1054}
1055
Greg Clayton736888c2015-02-23 23:47:09 +00001056DataBufferSP
1057FileSpec::MemoryMapFileContentsIfLocal(off_t file_offset, size_t file_size) const
1058{
1059 if (FileSystem::IsLocal(*this))
1060 return MemoryMapFileContents(file_offset, file_size);
1061 else
1062 return ReadFileContents(file_offset, file_size, NULL);
1063}
1064
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001065
1066//------------------------------------------------------------------
1067// Return the size in bytes that this object takes in memory. This
1068// returns the size in bytes of this object, not any shared string
1069// values it may refer to.
1070//------------------------------------------------------------------
1071size_t
1072FileSpec::MemorySize() const
1073{
1074 return m_filename.MemorySize() + m_directory.MemorySize();
1075}
1076
Greg Claytondda4f7b2010-06-30 23:03:03 +00001077
1078size_t
Greg Clayton4017fa32012-01-06 02:01:06 +00001079FileSpec::ReadFileContents (off_t file_offset, void *dst, size_t dst_len, Error *error_ptr) const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001080{
Greg Clayton4017fa32012-01-06 02:01:06 +00001081 Error error;
Greg Claytondda4f7b2010-06-30 23:03:03 +00001082 size_t bytes_read = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001083 char resolved_path[PATH_MAX];
1084 if (GetPath(resolved_path, sizeof(resolved_path)))
1085 {
Greg Clayton96c09682012-01-04 22:56:43 +00001086 File file;
1087 error = file.Open(resolved_path, File::eOpenOptionRead);
1088 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001089 {
Greg Clayton96c09682012-01-04 22:56:43 +00001090 off_t file_offset_after_seek = file_offset;
1091 bytes_read = dst_len;
1092 error = file.Read(dst, bytes_read, file_offset_after_seek);
Greg Claytondda4f7b2010-06-30 23:03:03 +00001093 }
Greg Claytondda4f7b2010-06-30 23:03:03 +00001094 }
Greg Clayton4017fa32012-01-06 02:01:06 +00001095 else
1096 {
1097 error.SetErrorString("invalid file specification");
1098 }
1099 if (error_ptr)
1100 *error_ptr = error;
Greg Claytondda4f7b2010-06-30 23:03:03 +00001101 return bytes_read;
1102}
1103
1104//------------------------------------------------------------------
1105// Returns a shared pointer to a data buffer that contains all or
1106// part of the contents of a file. The data copies into a heap based
1107// buffer that lives in the DataBuffer shared pointer object returned.
1108// The data that is cached will start "file_offset" bytes into the
1109// file, and "file_size" bytes will be mapped. If "file_size" is
1110// greater than the number of bytes available in the file starting
1111// at "file_offset", the number of bytes will be appropriately
1112// truncated. The final number of bytes that get mapped can be
1113// verified using the DataBuffer::GetByteSize() function.
1114//------------------------------------------------------------------
1115DataBufferSP
Greg Clayton4017fa32012-01-06 02:01:06 +00001116FileSpec::ReadFileContents (off_t file_offset, size_t file_size, Error *error_ptr) const
Greg Claytondda4f7b2010-06-30 23:03:03 +00001117{
Greg Clayton4017fa32012-01-06 02:01:06 +00001118 Error error;
Greg Claytondda4f7b2010-06-30 23:03:03 +00001119 DataBufferSP data_sp;
1120 char resolved_path[PATH_MAX];
1121 if (GetPath(resolved_path, sizeof(resolved_path)))
1122 {
Greg Clayton96c09682012-01-04 22:56:43 +00001123 File file;
1124 error = file.Open(resolved_path, File::eOpenOptionRead);
1125 if (error.Success())
Greg Clayton0b0b5122012-08-30 18:15:10 +00001126 {
1127 const bool null_terminate = false;
1128 error = file.Read (file_size, file_offset, null_terminate, data_sp);
1129 }
1130 }
1131 else
1132 {
1133 error.SetErrorString("invalid file specification");
1134 }
1135 if (error_ptr)
1136 *error_ptr = error;
1137 return data_sp;
1138}
1139
1140DataBufferSP
1141FileSpec::ReadFileContentsAsCString(Error *error_ptr)
1142{
1143 Error error;
1144 DataBufferSP data_sp;
1145 char resolved_path[PATH_MAX];
1146 if (GetPath(resolved_path, sizeof(resolved_path)))
1147 {
1148 File file;
1149 error = file.Open(resolved_path, File::eOpenOptionRead);
1150 if (error.Success())
1151 {
1152 off_t offset = 0;
1153 size_t length = SIZE_MAX;
1154 const bool null_terminate = true;
1155 error = file.Read (length, offset, null_terminate, data_sp);
1156 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001157 }
Greg Clayton4017fa32012-01-06 02:01:06 +00001158 else
1159 {
1160 error.SetErrorString("invalid file specification");
1161 }
1162 if (error_ptr)
1163 *error_ptr = error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001164 return data_sp;
1165}
1166
Greg Clayton58fc50e2010-10-20 22:52:05 +00001167size_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001168FileSpec::ReadFileLines (STLStringArray &lines)
1169{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001170 lines.clear();
Greg Clayton58fc50e2010-10-20 22:52:05 +00001171 char path[PATH_MAX];
1172 if (GetPath(path, sizeof(path)))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001173 {
Greg Claytone01e07b2013-04-18 18:10:51 +00001174 std::ifstream file_stream (path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001175
Greg Clayton58fc50e2010-10-20 22:52:05 +00001176 if (file_stream)
1177 {
1178 std::string line;
1179 while (getline (file_stream, line))
1180 lines.push_back (line);
1181 }
1182 }
1183 return lines.size();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001184}
Greg Clayton4272cc72011-02-02 02:24:04 +00001185
1186FileSpec::EnumerateDirectoryResult
Greg Clayton58c65f02015-06-29 18:29:00 +00001187FileSpec::ForEachItemInDirectory (const char *dir_path, DirectoryCallback const &callback)
1188{
1189 if (dir_path && dir_path[0])
1190 {
Zachary Turner190fadc2016-03-22 17:58:09 +00001191#ifdef _WIN32
Greg Clayton58c65f02015-06-29 18:29:00 +00001192 std::string szDir(dir_path);
1193 szDir += "\\*";
1194
Zachary Turner190fadc2016-03-22 17:58:09 +00001195 std::wstring wszDir;
1196 if (!llvm::ConvertUTF8toWide(szDir, wszDir))
1197 {
1198 return eEnumerateDirectoryResultNext;
1199 }
1200
1201 WIN32_FIND_DATAW ffd;
1202 HANDLE hFind = FindFirstFileW(wszDir.c_str(), &ffd);
Greg Clayton58c65f02015-06-29 18:29:00 +00001203
1204 if (hFind == INVALID_HANDLE_VALUE)
1205 {
1206 return eEnumerateDirectoryResultNext;
1207 }
1208
1209 do
1210 {
Greg Clayton58c65f02015-06-29 18:29:00 +00001211 FileSpec::FileType file_type = eFileTypeUnknown;
1212 if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
1213 {
Zachary Turner190fadc2016-03-22 17:58:09 +00001214 size_t len = wcslen(ffd.cFileName);
Greg Clayton58c65f02015-06-29 18:29:00 +00001215
Zachary Turner190fadc2016-03-22 17:58:09 +00001216 if (len == 1 && ffd.cFileName[0] == L'.')
Greg Clayton58c65f02015-06-29 18:29:00 +00001217 continue;
1218
Zachary Turner190fadc2016-03-22 17:58:09 +00001219 if (len == 2 && ffd.cFileName[0] == L'.' && ffd.cFileName[1] == L'.')
Greg Clayton58c65f02015-06-29 18:29:00 +00001220 continue;
1221
1222 file_type = eFileTypeDirectory;
Greg Clayton58c65f02015-06-29 18:29:00 +00001223 }
1224 else if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DEVICE)
1225 {
1226 file_type = eFileTypeOther;
Greg Clayton58c65f02015-06-29 18:29:00 +00001227 }
1228 else
1229 {
1230 file_type = eFileTypeRegular;
Greg Clayton58c65f02015-06-29 18:29:00 +00001231 }
Ewan Crawford184d4df2015-06-30 15:03:31 +00001232
Zachary Turner190fadc2016-03-22 17:58:09 +00001233 std::string fileName;
1234 if (!llvm::convertWideToUTF8(ffd.cFileName, fileName))
1235 {
1236 continue;
1237 }
1238
1239 std::vector<char> child_path(PATH_MAX);
1240 const int child_path_len =
1241 ::snprintf(child_path.data(), child_path.size(), "%s\\%s", dir_path, fileName.c_str());
1242 if (child_path_len < (int)(child_path.size() - 1))
Greg Clayton58c65f02015-06-29 18:29:00 +00001243 {
Ewan Crawford184d4df2015-06-30 15:03:31 +00001244 // Don't resolve the file type or path
Zachary Turner190fadc2016-03-22 17:58:09 +00001245 FileSpec child_path_spec(child_path.data(), false);
Ewan Crawford184d4df2015-06-30 15:03:31 +00001246
1247 EnumerateDirectoryResult result = callback (file_type, child_path_spec);
1248
1249 switch (result)
Greg Clayton58c65f02015-06-29 18:29:00 +00001250 {
Ewan Crawford184d4df2015-06-30 15:03:31 +00001251 case eEnumerateDirectoryResultNext:
1252 // Enumerate next entry in the current directory. We just
1253 // exit this switch and will continue enumerating the
1254 // current directory as we currently are...
1255 break;
Greg Clayton58c65f02015-06-29 18:29:00 +00001256
Ewan Crawford184d4df2015-06-30 15:03:31 +00001257 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 +00001258 if (FileSpec::ForEachItemInDirectory(child_path.data(), callback) ==
1259 eEnumerateDirectoryResultQuit)
Ewan Crawford184d4df2015-06-30 15:03:31 +00001260 {
1261 // The subdirectory returned Quit, which means to
1262 // stop all directory enumerations at all levels.
Greg Clayton58c65f02015-06-29 18:29:00 +00001263 return eEnumerateDirectoryResultQuit;
Ewan Crawford184d4df2015-06-30 15:03:31 +00001264 }
1265 break;
1266
1267 case eEnumerateDirectoryResultExit: // Exit from the current directory at the current level.
1268 // Exit from this directory level and tell parent to
1269 // keep enumerating.
1270 return eEnumerateDirectoryResultNext;
1271
1272 case eEnumerateDirectoryResultQuit: // Stop directory enumerations at any level
1273 return eEnumerateDirectoryResultQuit;
Greg Clayton58c65f02015-06-29 18:29:00 +00001274 }
1275 }
Zachary Turner190fadc2016-03-22 17:58:09 +00001276 } while (FindNextFileW(hFind, &ffd) != 0);
Greg Clayton58c65f02015-06-29 18:29:00 +00001277
1278 FindClose(hFind);
1279#else
1280 lldb_utility::CleanUp <DIR *, int> dir_path_dir(opendir(dir_path), NULL, closedir);
1281 if (dir_path_dir.is_valid())
1282 {
1283 char dir_path_last_char = dir_path[strlen(dir_path) - 1];
1284
1285 long path_max = fpathconf (dirfd (dir_path_dir.get()), _PC_NAME_MAX);
1286#if defined (__APPLE_) && defined (__DARWIN_MAXPATHLEN)
1287 if (path_max < __DARWIN_MAXPATHLEN)
1288 path_max = __DARWIN_MAXPATHLEN;
1289#endif
1290 struct dirent *buf, *dp;
1291 buf = (struct dirent *) malloc (offsetof (struct dirent, d_name) + path_max + 1);
1292
1293 while (buf && readdir_r(dir_path_dir.get(), buf, &dp) == 0 && dp)
1294 {
1295 // Only search directories
1296 if (dp->d_type == DT_DIR || dp->d_type == DT_UNKNOWN)
1297 {
1298 size_t len = strlen(dp->d_name);
1299
1300 if (len == 1 && dp->d_name[0] == '.')
1301 continue;
1302
1303 if (len == 2 && dp->d_name[0] == '.' && dp->d_name[1] == '.')
1304 continue;
1305 }
1306
1307 FileSpec::FileType file_type = eFileTypeUnknown;
1308
1309 switch (dp->d_type)
1310 {
1311 default:
1312 case DT_UNKNOWN: file_type = eFileTypeUnknown; break;
1313 case DT_FIFO: file_type = eFileTypePipe; break;
1314 case DT_CHR: file_type = eFileTypeOther; break;
1315 case DT_DIR: file_type = eFileTypeDirectory; break;
1316 case DT_BLK: file_type = eFileTypeOther; break;
1317 case DT_REG: file_type = eFileTypeRegular; break;
1318 case DT_LNK: file_type = eFileTypeSymbolicLink; break;
1319 case DT_SOCK: file_type = eFileTypeSocket; break;
1320#if !defined(__OpenBSD__)
1321 case DT_WHT: file_type = eFileTypeOther; break;
1322#endif
1323 }
1324
1325 char child_path[PATH_MAX];
1326
1327 // Don't make paths with "/foo//bar", that just confuses everybody.
1328 int child_path_len;
1329 if (dir_path_last_char == '/')
1330 child_path_len = ::snprintf (child_path, sizeof(child_path), "%s%s", dir_path, dp->d_name);
1331 else
1332 child_path_len = ::snprintf (child_path, sizeof(child_path), "%s/%s", dir_path, dp->d_name);
1333
1334 if (child_path_len < (int)(sizeof(child_path) - 1))
1335 {
1336 // Don't resolve the file type or path
1337 FileSpec child_path_spec (child_path, false);
1338
1339 EnumerateDirectoryResult result = callback (file_type, child_path_spec);
1340
1341 switch (result)
1342 {
1343 case eEnumerateDirectoryResultNext:
1344 // Enumerate next entry in the current directory. We just
1345 // exit this switch and will continue enumerating the
1346 // current directory as we currently are...
1347 break;
1348
1349 case eEnumerateDirectoryResultEnter: // Recurse into the current entry if it is a directory or symlink, or next if not
1350 if (FileSpec::ForEachItemInDirectory (child_path, callback) == eEnumerateDirectoryResultQuit)
1351 {
1352 // The subdirectory returned Quit, which means to
1353 // stop all directory enumerations at all levels.
1354 if (buf)
1355 free (buf);
1356 return eEnumerateDirectoryResultQuit;
1357 }
1358 break;
1359
1360 case eEnumerateDirectoryResultExit: // Exit from the current directory at the current level.
1361 // Exit from this directory level and tell parent to
1362 // keep enumerating.
1363 if (buf)
1364 free (buf);
1365 return eEnumerateDirectoryResultNext;
1366
1367 case eEnumerateDirectoryResultQuit: // Stop directory enumerations at any level
1368 if (buf)
1369 free (buf);
1370 return eEnumerateDirectoryResultQuit;
1371 }
1372 }
1373 }
1374 if (buf)
1375 {
1376 free (buf);
1377 }
1378 }
1379#endif
1380 }
1381 // By default when exiting a directory, we tell the parent enumeration
1382 // to continue enumerating.
1383 return eEnumerateDirectoryResultNext;
1384}
1385
1386FileSpec::EnumerateDirectoryResult
Greg Clayton4272cc72011-02-02 02:24:04 +00001387FileSpec::EnumerateDirectory
1388(
1389 const char *dir_path,
1390 bool find_directories,
1391 bool find_files,
1392 bool find_other,
1393 EnumerateDirectoryCallbackType callback,
1394 void *callback_baton
1395)
1396{
Chaoren Lin0246b6f2015-06-29 19:07:35 +00001397 return ForEachItemInDirectory(dir_path,
1398 [&find_directories, &find_files, &find_other, &callback, &callback_baton]
1399 (FileType file_type, const FileSpec &file_spec) {
1400 switch (file_type)
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001401 {
Chaoren Lin0246b6f2015-06-29 19:07:35 +00001402 case FileType::eFileTypeDirectory:
1403 if (find_directories)
1404 return callback(callback_baton, file_type, file_spec);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001405 break;
Chaoren Lin0246b6f2015-06-29 19:07:35 +00001406 case FileType::eFileTypeRegular:
1407 if (find_files)
1408 return callback(callback_baton, file_type, file_spec);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001409 break;
Chaoren Lin0246b6f2015-06-29 19:07:35 +00001410 default:
1411 if (find_other)
1412 return callback(callback_baton, file_type, file_spec);
1413 break;
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001414 }
Chaoren Lin0246b6f2015-06-29 19:07:35 +00001415 return eEnumerateDirectoryResultNext;
1416 });
Greg Clayton4272cc72011-02-02 02:24:04 +00001417}
1418
Daniel Maleae0f8f572013-08-26 23:57:52 +00001419FileSpec
1420FileSpec::CopyByAppendingPathComponent (const char *new_path) const
1421{
Pavel Labathcc0e87c2016-03-11 08:44:44 +00001422 FileSpec ret = *this;
1423 ret.AppendPathComponent(new_path);
1424 return ret;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001425}
1426
1427FileSpec
1428FileSpec::CopyByRemovingLastPathComponent () const
1429{
1430 const bool resolve = false;
1431 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1432 return FileSpec("",resolve);
1433 if (m_directory.IsEmpty())
1434 return FileSpec("",resolve);
1435 if (m_filename.IsEmpty())
1436 {
1437 const char* dir_cstr = m_directory.GetCString();
1438 const char* last_slash_ptr = ::strrchr(dir_cstr, '/');
1439
1440 // check for obvious cases before doing the full thing
1441 if (!last_slash_ptr)
1442 return FileSpec("",resolve);
1443 if (last_slash_ptr == dir_cstr)
1444 return FileSpec("/",resolve);
1445
1446 size_t last_slash_pos = last_slash_ptr - dir_cstr+1;
1447 ConstString new_path(dir_cstr,last_slash_pos);
1448 return FileSpec(new_path.GetCString(),resolve);
1449 }
1450 else
1451 return FileSpec(m_directory.GetCString(),resolve);
1452}
1453
Greg Claytonfbb76342013-11-20 21:07:01 +00001454ConstString
Daniel Maleae0f8f572013-08-26 23:57:52 +00001455FileSpec::GetLastPathComponent () const
1456{
Greg Claytonfbb76342013-11-20 21:07:01 +00001457 if (m_filename)
1458 return m_filename;
1459 if (m_directory)
Daniel Maleae0f8f572013-08-26 23:57:52 +00001460 {
1461 const char* dir_cstr = m_directory.GetCString();
1462 const char* last_slash_ptr = ::strrchr(dir_cstr, '/');
1463 if (last_slash_ptr == NULL)
Greg Claytonfbb76342013-11-20 21:07:01 +00001464 return m_directory;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001465 if (last_slash_ptr == dir_cstr)
1466 {
1467 if (last_slash_ptr[1] == 0)
Greg Claytonfbb76342013-11-20 21:07:01 +00001468 return ConstString(last_slash_ptr);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001469 else
Greg Claytonfbb76342013-11-20 21:07:01 +00001470 return ConstString(last_slash_ptr+1);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001471 }
1472 if (last_slash_ptr[1] != 0)
Greg Claytonfbb76342013-11-20 21:07:01 +00001473 return ConstString(last_slash_ptr+1);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001474 const char* penultimate_slash_ptr = last_slash_ptr;
1475 while (*penultimate_slash_ptr)
1476 {
1477 --penultimate_slash_ptr;
1478 if (penultimate_slash_ptr == dir_cstr)
1479 break;
1480 if (*penultimate_slash_ptr == '/')
1481 break;
1482 }
Greg Claytonfbb76342013-11-20 21:07:01 +00001483 ConstString result(penultimate_slash_ptr+1,last_slash_ptr-penultimate_slash_ptr);
1484 return result;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001485 }
Greg Claytonfbb76342013-11-20 21:07:01 +00001486 return ConstString();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001487}
1488
1489void
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001490FileSpec::PrependPathComponent(const char *new_path)
Daniel Maleae0f8f572013-08-26 23:57:52 +00001491{
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001492 if (!new_path) return;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001493 const bool resolve = false;
1494 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1495 {
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001496 SetFile(new_path, resolve);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001497 return;
1498 }
1499 StreamString stream;
1500 if (m_filename.IsEmpty())
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001501 stream.Printf("%s/%s", new_path, m_directory.GetCString());
Daniel Maleae0f8f572013-08-26 23:57:52 +00001502 else if (m_directory.IsEmpty())
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001503 stream.Printf("%s/%s", new_path, m_filename.GetCString());
Daniel Maleae0f8f572013-08-26 23:57:52 +00001504 else
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001505 stream.Printf("%s/%s/%s", new_path, m_directory.GetCString(), m_filename.GetCString());
1506 SetFile(stream.GetData(), resolve);
1507}
1508
1509void
1510FileSpec::PrependPathComponent(const std::string &new_path)
1511{
1512 return PrependPathComponent(new_path.c_str());
1513}
1514
1515void
1516FileSpec::PrependPathComponent(const FileSpec &new_path)
1517{
1518 return PrependPathComponent(new_path.GetPath(false));
1519}
1520
1521void
1522FileSpec::AppendPathComponent(const char *new_path)
1523{
1524 if (!new_path) return;
Pavel Labathcc0e87c2016-03-11 08:44:44 +00001525
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001526 StreamString stream;
Pavel Labathcc0e87c2016-03-11 08:44:44 +00001527 if (!m_directory.IsEmpty())
1528 {
1529 stream.PutCString(m_directory.GetCString());
Pavel Labath144119b2016-04-04 14:39:12 +00001530 if (!IsPathSeparator(m_directory.GetStringRef().back(), m_syntax))
1531 stream.PutChar(GetPrefferedPathSeparator(m_syntax));
Pavel Labathcc0e87c2016-03-11 08:44:44 +00001532 }
1533
1534 if (!m_filename.IsEmpty())
1535 {
1536 stream.PutCString(m_filename.GetCString());
Pavel Labath144119b2016-04-04 14:39:12 +00001537 if (!IsPathSeparator(m_filename.GetStringRef().back(), m_syntax))
1538 stream.PutChar(GetPrefferedPathSeparator(m_syntax));
Pavel Labathcc0e87c2016-03-11 08:44:44 +00001539 }
1540
1541 stream.PutCString(new_path);
1542
1543 const bool resolve = false;
1544 SetFile(stream.GetData(), resolve, m_syntax);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001545}
1546
1547void
Chaoren Lind3173f32015-05-29 19:52:29 +00001548FileSpec::AppendPathComponent(const std::string &new_path)
1549{
1550 return AppendPathComponent(new_path.c_str());
1551}
1552
1553void
Chaoren Lin0c5a9c12015-06-05 00:28:06 +00001554FileSpec::AppendPathComponent(const FileSpec &new_path)
1555{
1556 return AppendPathComponent(new_path.GetPath(false));
1557}
1558
1559void
Daniel Maleae0f8f572013-08-26 23:57:52 +00001560FileSpec::RemoveLastPathComponent ()
1561{
1562 const bool resolve = false;
1563 if (m_filename.IsEmpty() && m_directory.IsEmpty())
1564 {
1565 SetFile("",resolve);
1566 return;
1567 }
1568 if (m_directory.IsEmpty())
1569 {
1570 SetFile("",resolve);
1571 return;
1572 }
1573 if (m_filename.IsEmpty())
1574 {
1575 const char* dir_cstr = m_directory.GetCString();
1576 const char* last_slash_ptr = ::strrchr(dir_cstr, '/');
1577
1578 // check for obvious cases before doing the full thing
1579 if (!last_slash_ptr)
1580 {
1581 SetFile("",resolve);
1582 return;
1583 }
1584 if (last_slash_ptr == dir_cstr)
1585 {
1586 SetFile("/",resolve);
1587 return;
1588 }
1589 size_t last_slash_pos = last_slash_ptr - dir_cstr+1;
1590 ConstString new_path(dir_cstr,last_slash_pos);
1591 SetFile(new_path.GetCString(),resolve);
1592 }
1593 else
1594 SetFile(m_directory.GetCString(),resolve);
1595}
Greg Clayton1f746072012-08-29 21:13:06 +00001596//------------------------------------------------------------------
1597/// Returns true if the filespec represents an implementation source
1598/// file (files with a ".c", ".cpp", ".m", ".mm" (many more)
1599/// extension).
1600///
1601/// @return
1602/// \b true if the filespec represents an implementation source
1603/// file, \b false otherwise.
1604//------------------------------------------------------------------
1605bool
1606FileSpec::IsSourceImplementationFile () const
1607{
1608 ConstString extension (GetFileNameExtension());
1609 if (extension)
1610 {
Greg Clayton7bd4c602015-01-21 21:51:02 +00001611 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 +00001612 return g_source_file_regex.Execute (extension.GetCString());
1613 }
1614 return false;
1615}
1616
Greg Claytona0ca6602012-10-18 16:33:33 +00001617bool
Chaoren Lin372e9062015-06-09 17:54:27 +00001618FileSpec::IsRelative() const
Greg Claytona0ca6602012-10-18 16:33:33 +00001619{
Zachary Turner270e99a2014-12-08 21:36:42 +00001620 const char *dir = m_directory.GetCString();
1621 llvm::StringRef directory(dir ? dir : "");
1622
1623 if (directory.size() > 0)
Greg Claytona0ca6602012-10-18 16:33:33 +00001624 {
Chaoren Lin1c614fe2015-05-28 17:02:45 +00001625 if (PathSyntaxIsPosix(m_syntax))
Zachary Turner270e99a2014-12-08 21:36:42 +00001626 {
1627 // If the path doesn't start with '/' or '~', return true
1628 switch (directory[0])
1629 {
1630 case '/':
1631 case '~':
1632 return false;
1633 default:
1634 return true;
1635 }
1636 }
Chaoren Lin1c614fe2015-05-28 17:02:45 +00001637 else
1638 {
1639 if (directory.size() >= 2 && directory[1] == ':')
1640 return false;
1641 if (directory[0] == '/')
1642 return false;
1643 return true;
1644 }
Greg Claytona0ca6602012-10-18 16:33:33 +00001645 }
1646 else if (m_filename)
1647 {
1648 // No directory, just a basename, return true
1649 return true;
1650 }
1651 return false;
1652}
Chaoren Lin372e9062015-06-09 17:54:27 +00001653
1654bool
1655FileSpec::IsAbsolute() const
1656{
1657 return !FileSpec::IsRelative();
1658}